3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
28 #include "util/serialize.h"
29 #include "util/string.h"
30 #include "util/numeric.h"
31 #include "inventorymanager.h" // deserializing InventoryLocations
35 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
37 #define POINTS_PER_NODE (16.0)
41 sqlite3_stmt* dbs_insert;
42 sqlite3_stmt* dbs_replace;
43 sqlite3_stmt* dbs_select;
44 sqlite3_stmt* dbs_select_range;
45 sqlite3_stmt* dbs_select_withActor;
46 sqlite3_stmt* dbs_knownActor_select;
47 sqlite3_stmt* dbs_knownActor_insert;
48 sqlite3_stmt* dbs_knownNode_select;
49 sqlite3_stmt* dbs_knownNode_insert;
62 std::string location, list;
68 int oldParam1, oldParam2;
71 int newParam1, newParam2;
80 typedef std::vector<Entity> Entities;
85 void registerNewActor (int id, std::string name)
92 KnownActors.push_back(newActor);
94 //std::cout << "New actor registered: " << id << " | " << name << std::endl;
96 void registerNewNode (int id, std::string name)
103 KnownNodes.push_back(newNode);
105 //std::cout << "New node registered: " << id << " | " << name << std::endl;
107 int getActorId (std::string name)
109 Entities::const_iterator iter;
111 for (iter = KnownActors.begin(); iter != KnownActors.end(); ++iter)
112 if (iter->name == name)
115 sqlite3_reset (dbs_knownActor_insert);
116 sqlite3_bind_text (dbs_knownActor_insert, 1, name.c_str(), -1, NULL);
117 sqlite3_step (dbs_knownActor_insert);
119 int id = sqlite3_last_insert_rowid(dbh);
121 //std::cout << "Actor ID insert returns " << insert << std::endl;
123 registerNewActor(id, name);
127 int getNodeId (std::string name)
129 Entities::const_iterator iter;
131 for (iter = KnownNodes.begin(); iter != KnownNodes.end(); ++iter)
132 if (iter->name == name)
135 sqlite3_reset (dbs_knownNode_insert);
136 sqlite3_bind_text (dbs_knownNode_insert, 1, name.c_str(), -1, NULL);
137 sqlite3_step (dbs_knownNode_insert);
139 int id = sqlite3_last_insert_rowid(dbh);
141 registerNewNode(id, name);
145 const char * getActorName (int id)
147 Entities::const_iterator iter;
149 //std::cout << "getActorName of id " << id << std::endl;
151 for (iter = KnownActors.begin(); iter != KnownActors.end(); ++iter)
153 return iter->name.c_str();
157 const char * getNodeName (int id)
159 Entities::const_iterator iter;
161 //std::cout << "getNodeName of id " << id << std::endl;
163 for (iter = KnownNodes.begin(); iter != KnownNodes.end(); ++iter)
165 return iter->name.c_str();
169 Stack getStackFromString (std::string text)
173 size_t off = text.find_last_of(" ");
175 stack.node = getNodeId(text.substr(0, off));
176 stack.quantity = atoi(text.substr(off + 1).c_str());
180 std::string getStringFromStack (Stack stack)
184 text.append(getNodeName(stack.node));
186 text.append(itos(stack.quantity));
190 bool SQL_createDatabase (void)
192 infostream << "CreateDB:" << dbp << std::endl;
194 int dbs = sqlite3_exec(
196 , "CREATE TABLE IF NOT EXISTS `actor` ("
197 "`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
198 "`name` TEXT NOT NULL);"
199 "CREATE TABLE IF NOT EXISTS `node` ("
200 "`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
201 "`name` TEXT NOT NULL);"
202 "CREATE TABLE IF NOT EXISTS `action` ("
203 "`id` INTEGER PRIMARY KEY AUTOINCREMENT,"
204 "`actor` INTEGER NOT NULL,"
205 "`timestamp` INTEGER NOT NULL,"
206 "`type` INTEGER NOT NULL,"
210 "`stackNode` INTEGER,"
211 "`stackQuantity` INTEGER,"
212 "`nodeMeta` INTEGER,"
217 "`oldParam1` INTEGER,"
218 "`oldParam2` INTEGER,"
221 "`newParam1` INTEGER,"
222 "`newParam2` INTEGER,"
224 "`guessedActor` INTEGER,"
225 "FOREIGN KEY (`actor`) REFERENCES `actor`(`id`),"
226 "FOREIGN KEY (`oldNode`) REFERENCES `node`(`id`),"
227 "FOREIGN KEY (`newNode`) REFERENCES `node`(`id`));"
228 "CREATE INDEX IF NOT EXISTS `actionActor` ON `action`(`actor`);"
229 "CREATE INDEX IF NOT EXISTS `actionTimestamp` ON `action`(`timestamp`);"
232 if (dbs == SQLITE_ABORT)
233 throw FileNotGoodException("Could not create sqlite3 database structure");
236 throw FileNotGoodException("SQL Rollback: Exec statement to create table structure returned a non-zero value");
238 infostream << "SQL Rollback: SQLite3 database structure was created" << std::endl;
242 void SQL_databaseCheck (void)
246 infostream << "Database connection setup" << std::endl;
248 bool needsCreate = !fs::PathExists(dbp);
249 int dbo = sqlite3_open_v2(dbp.c_str(), &dbh, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
251 if (dbo != SQLITE_OK)
254 << "SQLROLLBACK: SQLite3 database failed to open: "
255 << sqlite3_errmsg(dbh)
257 throw FileNotGoodException("Cannot open database file");
260 if (needsCreate) SQL_createDatabase();
264 dbr = sqlite3_prepare_v2(
266 , "INSERT INTO `action`"
267 " ( `actor`, `timestamp`, `type`,"
268 " `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodeMeta`,"
270 " `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,"
271 " `newNode`, `newParam1`, `newParam2`, `newMeta`,"
282 , -1, &dbs_insert, NULL
285 if (dbr != SQLITE_OK)
286 throw FileNotGoodException(sqlite3_errmsg(dbh));
288 dbr = sqlite3_prepare_v2(
290 , "REPLACE INTO `action`"
291 " ( `actor`, `timestamp`, `type`,"
292 " `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodeMeta`,"
294 " `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,"
295 " `newNode`, `newParam1`, `newParam2`, `newMeta`,"
296 " `guessedActor`, `id`"
306 , -1, &dbs_replace, NULL
309 if (dbr != SQLITE_OK)
310 throw FileNotGoodException(sqlite3_errmsg(dbh));
312 dbr = sqlite3_prepare_v2(dbh
314 " `actor`, `timestamp`, `type`"
315 " , `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`"
317 " , `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`"
318 " , `newNode`, `newParam1`, `newParam2`, `newMeta`"
321 " WHERE `timestamp` >= ?"
322 " ORDER BY `timestamp` DESC, `id` DESC"
323 , -1, &dbs_select, NULL
325 if (dbr != SQLITE_OK)
326 throw FileNotGoodException(itos(dbr).c_str());
328 dbr = sqlite3_prepare_v2(dbh
330 " `actor`, `timestamp`, `type`"
331 " , `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`"
333 " , `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`"
334 " , `newNode`, `newParam1`, `newParam2`, `newMeta`"
337 " WHERE `timestamp` >= ?"
338 " AND `x` IS NOT NULL"
339 " AND `y` IS NOT NULL"
340 " AND `z` IS NOT NULL"
341 " AND (ABS(`x`) - ABS(?)) <= ?"
342 " AND (ABS(`y`) - ABS(?)) <= ?"
343 " AND (ABS(`z`) - ABS(?)) <= ?"
344 " ORDER BY `timestamp` DESC, `id` DESC"
346 , -1, &dbs_select_range, NULL
348 if (dbr != SQLITE_OK)
349 throw FileNotGoodException(itos(dbr).c_str());
351 dbr = sqlite3_prepare_v2(dbh
353 " `actor`, `timestamp`, `type`"
354 " , `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`"
356 " , `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`"
357 " , `newNode`, `newParam1`, `newParam2`, `newMeta`"
360 " WHERE `timestamp` >= ?"
362 " ORDER BY `timestamp` DESC, `id` DESC"
363 , -1, &dbs_select_withActor, NULL
365 if (dbr != SQLITE_OK)
366 throw FileNotGoodException(itos(dbr).c_str());
368 dbr = sqlite3_prepare_v2(dbh, "SELECT `id`, `name` FROM `actor`", -1, &dbs_knownActor_select, NULL);
369 if (dbr != SQLITE_OK)
370 throw FileNotGoodException(itos(dbr).c_str());
372 dbr = sqlite3_prepare_v2(dbh, "INSERT INTO `actor` (`name`) VALUES (?)", -1, &dbs_knownActor_insert, NULL);
373 if (dbr != SQLITE_OK)
374 throw FileNotGoodException(itos(dbr).c_str());
376 dbr = sqlite3_prepare_v2(dbh, "SELECT `id`, `name` FROM `node`", -1, &dbs_knownNode_select, NULL);
377 if (dbr != SQLITE_OK)
378 throw FileNotGoodException(itos(dbr).c_str());
380 dbr = sqlite3_prepare_v2(dbh, "INSERT INTO `node` (`name`) VALUES (?)", -1, &dbs_knownNode_insert, NULL);
381 if (dbr != SQLITE_OK)
382 throw FileNotGoodException(itos(dbr).c_str());
384 infostream << "SQL prepared statements setup correctly" << std::endl;
388 sqlite3_reset(dbs_knownActor_select);
389 while (SQLITE_ROW == (select = sqlite3_step(dbs_knownActor_select)))
391 sqlite3_column_int (dbs_knownActor_select, 0),
392 reinterpret_cast<const char *>(sqlite3_column_text (dbs_knownActor_select, 1))
395 sqlite3_reset(dbs_knownNode_select);
396 while (SQLITE_ROW == (select = sqlite3_step(dbs_knownNode_select)))
398 sqlite3_column_int (dbs_knownNode_select, 0),
399 reinterpret_cast<const char *>(sqlite3_column_text (dbs_knownNode_select, 1))
404 bool SQL_registerRow (ActionRow row)
408 sqlite3_stmt * dbs_do = (row.id)? dbs_replace: dbs_insert;
412 << (row.id? "Replacing": "Inserting")
413 << " ActionRow" << std::endl;
415 sqlite3_reset(dbs_do);
417 int bind [20 + (((bool) row.id)? 1: 0)], ii = 0;
418 bool nodeMeta = false;
420 bind[ii++] = sqlite3_bind_int (dbs_do, 1, row.actor);
421 bind[ii++] = sqlite3_bind_int (dbs_do, 2, row.timestamp);
422 bind[ii++] = sqlite3_bind_int (dbs_do, 3, row.type);
424 if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK)
426 std::string loc = row.location;
427 std::string locType = loc.substr(0, loc.find(":"));
428 nodeMeta = (locType == "nodemeta");
430 bind[ii++] = sqlite3_bind_text (dbs_do, 4, row.list.c_str(), row.list.size(), NULL);
431 bind[ii++] = sqlite3_bind_int (dbs_do, 5, row.index);
432 bind[ii++] = sqlite3_bind_int (dbs_do, 6, row.add);
433 bind[ii++] = sqlite3_bind_int (dbs_do, 7, row.stack.node);
434 bind[ii++] = sqlite3_bind_int (dbs_do, 8, row.stack.quantity);
435 bind[ii++] = sqlite3_bind_int (dbs_do, 9, (int) nodeMeta);
441 l = loc.find(':') + 1;
443 x = loc.substr(l, r - l);
445 r = loc.find(',', l);
446 y = loc.substr(l, r - l);
447 z = loc.substr(r +1);
448 bind[ii++] = sqlite3_bind_int (dbs_do, 10, atoi(x.c_str()));
449 bind[ii++] = sqlite3_bind_int (dbs_do, 11, atoi(y.c_str()));
450 bind[ii++] = sqlite3_bind_int (dbs_do, 12, atoi(z.c_str()));
455 bind[ii++] = sqlite3_bind_null (dbs_do, 4);
456 bind[ii++] = sqlite3_bind_null (dbs_do, 5);
457 bind[ii++] = sqlite3_bind_null (dbs_do, 6);
458 bind[ii++] = sqlite3_bind_null (dbs_do, 7);
459 bind[ii++] = sqlite3_bind_null (dbs_do, 8);
460 bind[ii++] = sqlite3_bind_null (dbs_do, 9);
463 if (row.type == RollbackAction::TYPE_SET_NODE)
465 bind[ii++] = sqlite3_bind_int (dbs_do, 10, row.x);
466 bind[ii++] = sqlite3_bind_int (dbs_do, 11, row.y);
467 bind[ii++] = sqlite3_bind_int (dbs_do, 12, row.z);
468 bind[ii++] = sqlite3_bind_int (dbs_do, 13, row.oldNode);
469 bind[ii++] = sqlite3_bind_int (dbs_do, 14, row.oldParam1);
470 bind[ii++] = sqlite3_bind_int (dbs_do, 15, row.oldParam2);
471 bind[ii++] = sqlite3_bind_text (dbs_do, 16, row.oldMeta.c_str(), row.oldMeta.size(), NULL);
472 bind[ii++] = sqlite3_bind_int (dbs_do, 17, row.newNode);
473 bind[ii++] = sqlite3_bind_int (dbs_do, 18, row.newParam1);
474 bind[ii++] = sqlite3_bind_int (dbs_do, 19, row.newParam2);
475 bind[ii++] = sqlite3_bind_text (dbs_do, 20, row.newMeta.c_str(), row.newMeta.size(), NULL);
476 bind[ii++] = sqlite3_bind_int (dbs_do, 21, row.guessed? 1: 0);
482 bind[ii++] = sqlite3_bind_null (dbs_do, 10);
483 bind[ii++] = sqlite3_bind_null (dbs_do, 11);
484 bind[ii++] = sqlite3_bind_null (dbs_do, 12);
486 bind[ii++] = sqlite3_bind_null (dbs_do, 13);
487 bind[ii++] = sqlite3_bind_null (dbs_do, 14);
488 bind[ii++] = sqlite3_bind_null (dbs_do, 15);
489 bind[ii++] = sqlite3_bind_null (dbs_do, 16);
490 bind[ii++] = sqlite3_bind_null (dbs_do, 17);
491 bind[ii++] = sqlite3_bind_null (dbs_do, 18);
492 bind[ii++] = sqlite3_bind_null (dbs_do, 19);
493 bind[ii++] = sqlite3_bind_null (dbs_do, 20);
494 bind[ii++] = sqlite3_bind_null (dbs_do, 21);
498 bind[ii++] = sqlite3_bind_int (dbs_do, 22, row.id);
500 for (ii = 0; ii < 20; ++ii)
501 if (bind[ii] != SQLITE_OK)
503 << "WARNING: failed to bind param " << ii + 1
504 << " when inserting an entry in table setnode" << std::endl;
507 std::cout << "========DB-WRITTEN==========" << std::endl;
508 std::cout << "id: " << row.id << std::endl;
509 std::cout << "actor: " << row.actor << std::endl;
510 std::cout << "time: " << row.timestamp << std::endl;
511 std::cout << "type: " << row.type << std::endl;
512 if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK)
514 std::cout << "Location: " << row.location << std::endl;
515 std::cout << "List: " << row.list << std::endl;
516 std::cout << "Index: " << row.index << std::endl;
517 std::cout << "Add: " << row.add << std::endl;
518 std::cout << "Stack: " << row.stack << std::endl;
520 if (row.type == RollbackAction::TYPE_SET_NODE)
522 std::cout << "x: " << row.x << std::endl;
523 std::cout << "y: " << row.y << std::endl;
524 std::cout << "z: " << row.z << std::endl;
525 std::cout << "oldNode: " << row.oldNode << std::endl;
526 std::cout << "oldParam1: " << row.oldParam1 << std::endl;
527 std::cout << "oldParam2: " << row.oldParam2 << std::endl;
528 std::cout << "oldMeta: " << row.oldMeta << std::endl;
529 std::cout << "newNode: " << row.newNode << std::endl;
530 std::cout << "newParam1: " << row.newParam1 << std::endl;
531 std::cout << "newParam2: " << row.newParam2 << std::endl;
532 std::cout << "newMeta: " << row.newMeta << std::endl;
533 std::cout << "DESERIALIZE" << row.newMeta.c_str() << std::endl;
534 std::cout << "guessed: " << row.guessed << std::endl;
538 int written = sqlite3_step(dbs_do);
540 return written == SQLITE_DONE;
542 //if (written != SQLITE_DONE)
543 // std::cout << "WARNING: rollback action not written: " << sqlite3_errmsg(dbh) << std::endl;
544 //else std::cout << "Action correctly inserted via SQL" << std::endl;
546 std::list<ActionRow> actionRowsFromSelect (sqlite3_stmt* stmt)
548 std::list<ActionRow> rows;
549 const unsigned char * text;
552 while (SQLITE_ROW == sqlite3_step(stmt))
556 row.actor = sqlite3_column_int (stmt, 0);
557 row.timestamp = sqlite3_column_int (stmt, 1);
558 row.type = sqlite3_column_int (stmt, 2);
560 if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK)
562 text = sqlite3_column_text (stmt, 3);
563 size = sqlite3_column_bytes(stmt, 3);
564 row.list = std::string(reinterpret_cast<const char*>(text), size);
565 row.index = sqlite3_column_int (stmt, 4);
566 row.add = sqlite3_column_int (stmt, 5);
567 row.stack.node = sqlite3_column_int (stmt, 6);
568 row.stack.quantity = sqlite3_column_int (stmt, 7);
569 row.nodeMeta = sqlite3_column_int (stmt, 8);
572 if (row.type == RollbackAction::TYPE_SET_NODE || row.nodeMeta)
574 row.x = sqlite3_column_int (stmt, 9);
575 row.y = sqlite3_column_int (stmt, 10);
576 row.z = sqlite3_column_int (stmt, 11);
579 if (row.type == RollbackAction::TYPE_SET_NODE)
581 row.oldNode = sqlite3_column_int (stmt, 12);
582 row.oldParam1 = sqlite3_column_int (stmt, 13);
583 row.oldParam2 = sqlite3_column_int (stmt, 14);
584 text = sqlite3_column_text (stmt, 15);
585 size = sqlite3_column_bytes(stmt, 15);
586 row.oldMeta = std::string(reinterpret_cast<const char*>(text), size);
587 row.newNode = sqlite3_column_int (stmt, 16);
588 row.newParam1 = sqlite3_column_int (stmt, 17);
589 row.newParam2 = sqlite3_column_int (stmt, 18);
590 text = sqlite3_column_text (stmt, 19);
591 size = sqlite3_column_bytes(stmt, 19);
592 row.newMeta = std::string(reinterpret_cast<const char*>(text), size);
593 row.guessed = sqlite3_column_int (stmt, 20);
596 row.location = row.nodeMeta? "nodemeta:": getActorName(row.actor);
600 row.location.append(itos(row.x));
601 row.location.append(",");
602 row.location.append(itos(row.y));
603 row.location.append(",");
604 row.location.append(itos(row.z));
608 std::cout << "=======SELECTED==========" << "\n";
609 std::cout << "Actor: " << row.actor << "\n";
610 std::cout << "Timestamp: " << row.timestamp << "\n";
612 if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK)
614 std::cout << "list: " << row.list << "\n";
615 std::cout << "index: " << row.index << "\n";
616 std::cout << "add: " << row.add << "\n";
617 std::cout << "stackNode: " << row.stack.node << "\n";
618 std::cout << "stackQuantity: " << row.stack.quantity << "\n";
621 std::cout << "X: " << row.x << "\n";
622 std::cout << "Y: " << row.y << "\n";
623 std::cout << "Z: " << row.z << "\n";
625 std::cout << "Location: " << row.location << "\n";
629 std::cout << "X: " << row.x << "\n";
630 std::cout << "Y: " << row.y << "\n";
631 std::cout << "Z: " << row.z << "\n";
632 std::cout << "oldNode: " << row.oldNode << "\n";
633 std::cout << "oldParam1: " << row.oldParam1 << "\n";
634 std::cout << "oldParam2: " << row.oldParam2 << "\n";
635 std::cout << "oldMeta: " << row.oldMeta << "\n";
636 std::cout << "newNode: " << row.newNode << "\n";
637 std::cout << "newParam1: " << row.newParam1 << "\n";
638 std::cout << "newParam2: " << row.newParam2 << "\n";
639 std::cout << "newMeta: " << row.newMeta << "\n";
640 std::cout << "guessed: " << row.guessed << "\n";
649 ActionRow actionRowFromRollbackAction (RollbackAction action)
654 row.actor = getActorId(action.actor);
655 row.timestamp = action.unix_time;
656 row.type = action.type;
658 if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK)
660 row.location = action.inventory_location;
661 row.list = action.inventory_list;
662 row.index = action.inventory_index;
663 row.add = action.inventory_add;
664 row.stack = getStackFromString(action.inventory_stack);
671 row.oldNode = getNodeId(action.n_old.name);
672 row.oldParam1 = action.n_old.param1;
673 row.oldParam2 = action.n_old.param2;
674 row.oldMeta = action.n_old.meta;
675 row.newNode = getNodeId(action.n_new.name);
676 row.newParam1 = action.n_new.param1;
677 row.newParam2 = action.n_new.param2;
678 row.newMeta = action.n_new.meta;
679 row.guessed = action.actor_is_guess;
684 std::list<RollbackAction> rollbackActionsFromActionRows (std::list<ActionRow> rows)
686 std::list<RollbackAction> actions;
687 std::list<ActionRow>::const_iterator it;
689 for (it = rows.begin(); it != rows.end(); ++it)
691 RollbackAction action;
692 action.actor = (it->actor)? getActorName(it->actor): "";
693 action.unix_time = it->timestamp;
694 action.type = static_cast<RollbackAction::Type>(it->type);
698 case RollbackAction::TYPE_MODIFY_INVENTORY_STACK:
700 action.inventory_location = it->location.c_str();
701 action.inventory_list = it->list;
702 action.inventory_index = it->index;
703 action.inventory_add = it->add;
704 action.inventory_stack = getStringFromStack(it->stack);
707 case RollbackAction::TYPE_SET_NODE:
709 action.p = v3s16(it->x, it->y, it->z);
710 action.n_old.name = getNodeName(it->oldNode);
711 action.n_old.param1 = it->oldParam1;
712 action.n_old.param2 = it->oldParam2;
713 action.n_old.meta = it->oldMeta;
714 action.n_new.name = getNodeName(it->newNode);
715 action.n_new.param1 = it->newParam1;
716 action.n_new.param2 = it->newParam2;
717 action.n_new.meta = it->newMeta;
726 actions.push_back(action);
731 std::list<ActionRow> SQL_getRowsSince (int firstTime, std::string actor = "")
733 sqlite3_stmt * dbs_stmt = (!actor.length())? dbs_select: dbs_select_withActor;
734 sqlite3_reset (dbs_stmt);
735 sqlite3_bind_int (dbs_stmt, 1, firstTime);
738 sqlite3_bind_int (dbs_stmt, 2, getActorId(actor));
740 return actionRowsFromSelect(dbs_stmt);
742 std::list<ActionRow> SQL_getRowsSince_range (int firstTime, v3s16 p, int range)
744 sqlite3_stmt * stmt = dbs_select_range;
747 sqlite3_bind_int(stmt, 1, firstTime);
748 sqlite3_bind_int(stmt, 2, (int) p.X);
749 sqlite3_bind_int(stmt, 3, range);
750 sqlite3_bind_int(stmt, 4, (int) p.Y);
751 sqlite3_bind_int(stmt, 5, range);
752 sqlite3_bind_int(stmt, 6, (int) p.Z);
753 sqlite3_bind_int(stmt, 7, range);
755 return actionRowsFromSelect(stmt);
757 std::list<RollbackAction> SQL_getActionsSince_range (int firstTime, v3s16 p, int range)
759 std::list<ActionRow> rows = SQL_getRowsSince_range(firstTime, p, range);
761 return rollbackActionsFromActionRows(rows);
763 std::list<RollbackAction> SQL_getActionsSince (int firstTime, std::string actor = "")
765 std::list<ActionRow> rows = SQL_getRowsSince(firstTime, actor);
766 return rollbackActionsFromActionRows(rows);
768 void TXT_migrate (std::string filepath)
770 std::cout << "Migrating from rollback.txt to rollback.sqlite" << std::endl;
773 std::ifstream fh (filepath.c_str(), std::ios::in | std::ios::ate);
774 if (!fh.good()) throw("DIE");
776 int filesize = fh.tellg();
793 std::getline(fh, bit, ' '); bit = trim(bit); if (!atoi(trim(bit).c_str())) { std::getline(fh, bit); continue; }
794 row.timestamp = atoi(bit.c_str());
797 row.actor = getActorId(trim(deSerializeJsonString(fh)));
799 // Get the action type
800 std::getline(fh, bit, '[');
801 std::getline(fh, bit, ' ');
803 if (bit == "modify_inventory_stack")
804 row.type = RollbackAction::TYPE_MODIFY_INVENTORY_STACK;
806 if (bit == "set_node")
807 row.type = RollbackAction::TYPE_SET_NODE;
809 if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK)
811 row.location = trim(deSerializeJsonString(fh));
812 std::getline(fh, bit, ' '); row.list = trim(deSerializeJsonString(fh));
813 std::getline(fh, bit, ' ');
814 std::getline(fh, bit, ' ');
815 row.index = atoi(trim(bit).c_str());
816 std::getline(fh, bit, ' '); row.add = (int) ( trim(bit) == "add" );
817 row.stack = getStackFromString(trim(deSerializeJsonString(fh)));
818 std::getline(fh, bit);
822 if (row.type == RollbackAction::TYPE_SET_NODE)
824 std::getline(fh, bit, '(');
825 std::getline(fh, bit, ','); row.x = atoi(trim(bit).c_str());
826 std::getline(fh, bit, ','); row.y = atoi(trim(bit).c_str());
827 std::getline(fh, bit, ')'); row.z = atoi(trim(bit).c_str());
828 std::getline(fh, bit, ' '); row.oldNode = getNodeId(trim(deSerializeJsonString(fh)));
829 std::getline(fh, bit, ' ');
830 std::getline(fh, bit, ' '); row.oldParam1 = atoi(trim(bit).c_str());
831 std::getline(fh, bit, ' '); row.oldParam2 = atoi(trim(bit).c_str());
832 row.oldMeta = trim(deSerializeJsonString(fh));
833 std::getline(fh, bit, ' '); row.newNode = getNodeId(trim(deSerializeJsonString(fh)));
834 std::getline(fh, bit, ' ');
835 std::getline(fh, bit, ' '); row.newParam1 = atoi(trim(bit).c_str());
836 std::getline(fh, bit, ' '); row.newParam2 = atoi(trim(bit).c_str());
837 row.newMeta = trim(deSerializeJsonString(fh));
838 std::getline(fh, bit, ' ');
839 std::getline(fh, bit, ' ');
840 std::getline(fh, bit); row.guessed = (int) ( trim(bit) == "actor_is_guess" );
844 std::cout << "==========READ===========" << std::endl;
845 std::cout << "time: " << row.timestamp << std::endl;
846 std::cout << "actor: " << row.actor << std::endl;
847 std::cout << "type: " << row.type << std::endl;
848 if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK)
850 std::cout << "Location: " << row.location << std::endl;
851 std::cout << "List: " << row.list << std::endl;
852 std::cout << "Index: " << row.index << std::endl;
853 std::cout << "Add: " << row.add << std::endl;
854 std::cout << "Stack: " << row.stack << std::endl;
856 if (row.type == RollbackAction::TYPE_SET_NODE)
858 std::cout << "x: " << row.x << std::endl;
859 std::cout << "y: " << row.y << std::endl;
860 std::cout << "z: " << row.z << std::endl;
861 std::cout << "oldNode: " << row.oldNode << std::endl;
862 std::cout << "oldParam1: " << row.oldParam1 << std::endl;
863 std::cout << "oldParam2: " << row.oldParam2 << std::endl;
864 std::cout << "oldMeta: " << row.oldMeta << std::endl;
865 std::cout << "newNode: " << row.newNode << std::endl;
866 std::cout << "newParam1: " << row.newParam1 << std::endl;
867 std::cout << "newParam2: " << row.newParam2 << std::endl;
868 std::cout << "newMeta: " << row.newMeta << std::endl;
869 std::cout << "guessed: " << row.guessed << std::endl;
876 sqlite3_exec(dbh, "BEGIN", NULL, NULL, NULL);
879 SQL_registerRow(row); ++i;
883 sqlite3_exec(dbh, "COMMIT", NULL, NULL, NULL);
886 << " Done: " << (int)(((float) fh.tellg() / (float) filesize) * 100) << "%"
887 << "\tSpeed: " << i / t << " actions inserted per second "
895 while (!fh.eof() && fh.good());
899 << " Done: 100%" << std::endl
900 << " Now you can delete the old rollback.txt file." << std::endl;
902 // Get nearness factor for subject's action for this action
903 // Return value: 0 = impossible, >0 = factor
904 static float getSuspectNearness(bool is_guess, v3s16 suspect_p, int suspect_t,
905 v3s16 action_p, int action_t)
907 // Suspect cannot cause things in the past
908 if(action_t < suspect_t)
909 return 0; // 0 = cannot be
912 // Distance (1 node = -x points)
913 f -= POINTS_PER_NODE * intToFloat(suspect_p, 1).getDistanceFrom(intToFloat(action_p, 1));
914 // Time (1 second = -x points)
915 f -= 1 * (action_t - suspect_t);
916 // If is a guess, halve the points
924 class RollbackManager: public IRollbackManager
927 // IRollbackManager interface
928 void reportAction(const RollbackAction &action_)
930 // Ignore if not important
931 if (!action_.isImportant(m_gamedef))
934 RollbackAction action = action_;
935 action.unix_time = time(0);
938 action.actor = m_current_actor;
939 action.actor_is_guess = m_current_actor_is_guess;
941 if (action.actor.empty()) // If actor is not known, find out suspect or cancel
944 if (!action.getPosition(&p))
947 action.actor = getSuspect(p, 83, 1);
948 if (action.actor.empty())
951 action.actor_is_guess = true;
955 << "RollbackManager::reportAction():"
956 << " time=" << action.unix_time
957 << " actor=\"" << action.actor << "\""
958 << (action.actor_is_guess? " (guess)": "")
959 << " action=" << action.toString()
963 std::string getActor()
965 return m_current_actor;
969 return m_current_actor_is_guess;
971 void setActor(const std::string &actor, bool is_guess)
973 m_current_actor = actor;
974 m_current_actor_is_guess = is_guess;
976 std::string getSuspect(v3s16 p, float nearness_shortcut, float min_nearness)
978 if(m_current_actor != "")
979 return m_current_actor;
980 int cur_time = time(0);
981 int first_time = cur_time - (100-min_nearness);
982 RollbackAction likely_suspect;
983 float likely_suspect_nearness = 0;
984 for(std::list<RollbackAction>::const_reverse_iterator
985 i = m_action_latest_buffer.rbegin();
986 i != m_action_latest_buffer.rend(); i++)
988 if(i->unix_time < first_time)
992 // Find position of suspect or continue
994 if(!i->getPosition(&suspect_p))
996 float f = getSuspectNearness(i->actor_is_guess, suspect_p,
997 i->unix_time, p, cur_time);
998 if(f >= min_nearness && f > likely_suspect_nearness){
999 likely_suspect_nearness = f;
1000 likely_suspect = *i;
1001 if(likely_suspect_nearness >= nearness_shortcut)
1005 // No likely suspect was found
1006 if(likely_suspect_nearness == 0)
1008 // Likely suspect was found
1009 return likely_suspect.actor;
1013 infostream << "RollbackManager::flush()" << std::endl;
1015 sqlite3_exec(dbh, "BEGIN", NULL, NULL, NULL);
1017 std::list<RollbackAction>::const_iterator iter;
1019 for (iter = m_action_todisk_buffer.begin();
1020 iter != m_action_todisk_buffer.end();
1023 if (iter->actor == "")
1026 SQL_registerRow(actionRowFromRollbackAction(*iter));
1029 sqlite3_exec(dbh, "COMMIT", NULL, NULL, NULL);
1030 m_action_todisk_buffer.clear();
1032 RollbackManager(const std::string &filepath, IGameDef *gamedef):
1033 m_filepath(filepath),
1035 m_current_actor_is_guess(false)
1038 << "RollbackManager::RollbackManager(" << filepath << ")"
1041 // Operate correctly in case of still being given rollback.txt as filepath
1042 std::string directory = filepath.substr(0, filepath.rfind(DIR_DELIM) + 1);
1043 std::string filenameOld = filepath.substr(1+ filepath.rfind(DIR_DELIM));
1044 std::string filenameNew = (filenameOld == "rollback.txt")? "rollback.sqlite": filenameOld;
1045 std::string filenameTXT = directory + "rollback.txt";
1046 std::string migratingFlag = filepath;
1047 migratingFlag.append(".migrating");
1049 infostream << "Directory: " << directory << std::endl;
1050 infostream << "CheckFor: " << filenameTXT << std::endl;
1051 infostream << "FileOld: " << filenameOld << std::endl;
1052 infostream << "FileNew: " << filenameNew << std::endl;
1054 dbp = directory + filenameNew;
1056 if ((fs::PathExists(filenameTXT) && fs::PathExists(migratingFlag))
1057 || (fs::PathExists(filenameTXT) && !fs::PathExists(dbp)))
1059 std::ofstream of(migratingFlag.c_str());
1060 TXT_migrate(filenameTXT);
1061 fs::DeleteSingleFileOrEmptyDirectory(migratingFlag);
1064 SQL_databaseCheck();
1068 infostream << "RollbackManager::~RollbackManager()" << std::endl;
1071 void addAction(const RollbackAction &action)
1073 m_action_todisk_buffer.push_back(action);
1074 m_action_latest_buffer.push_back(action);
1076 // Flush to disk sometimes
1077 if(m_action_todisk_buffer.size() >= 500)
1080 std::list<RollbackAction> getEntriesSince(int first_time)
1083 << "RollbackManager::getEntriesSince(" << first_time << ")"
1088 std::list<RollbackAction> result = SQL_getActionsSince(first_time);
1092 std::string getLastNodeActor(v3s16 p, int range, int seconds, v3s16 *act_p, int *act_seconds)
1094 int cur_time = time(0);
1095 int first_time = cur_time - seconds;
1097 std::list<RollbackAction> action_buffer = SQL_getActionsSince_range(first_time, p, range);
1098 std::list<RollbackAction>::const_reverse_iterator iter;
1100 for (iter = action_buffer.rbegin();
1101 iter != action_buffer.rend();
1106 action_p.X = iter->p.X;
1107 action_p.Y = iter->p.Y;
1108 action_p.Z = iter->p.Z;
1114 *act_seconds = cur_time - iter->unix_time;
1121 std::list<RollbackAction> getRevertActions(const std::string &actor_filter, int seconds)
1124 << "RollbackManager::getRevertActions(" << actor_filter
1125 << ", " << seconds << ")"
1129 int cur_time = time(0);
1130 int first_time = cur_time - seconds;
1134 std::list<RollbackAction> result = SQL_getActionsSince(first_time, actor_filter);
1139 std::string m_filepath;
1140 IGameDef *m_gamedef;
1141 std::string m_current_actor;
1142 bool m_current_actor_is_guess;
1143 std::list<RollbackAction> m_action_todisk_buffer;
1144 std::list<RollbackAction> m_action_latest_buffer;
1147 IRollbackManager *createRollbackManager(const std::string &filepath, IGameDef *gamedef)
1149 return new RollbackManager(filepath, gamedef);