database-sqlite3.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. /*
  17. SQLite format specification:
  18. blocks:
  19. (PK) INT id
  20. BLOB data
  21. */
  22. #include "database-sqlite3.h"
  23. #include "log.h"
  24. #include "filesys.h"
  25. #include "exceptions.h"
  26. #include "settings.h"
  27. #include "porting.h"
  28. #include "util/string.h"
  29. #include "content_sao.h"
  30. #include "remoteplayer.h"
  31. #include <cassert>
  32. // When to print messages when the database is being held locked by another process
  33. // Note: I've seen occasional delays of over 250ms while running minetestmapper.
  34. #define BUSY_INFO_TRESHOLD 100 // Print first informational message after 100ms.
  35. #define BUSY_WARNING_TRESHOLD 250 // Print warning message after 250ms. Lag is increased.
  36. #define BUSY_ERROR_TRESHOLD 1000 // Print error message after 1000ms. Significant lag.
  37. #define BUSY_FATAL_TRESHOLD 3000 // Allow SQLITE_BUSY to be returned, which will cause a minetest crash.
  38. #define BUSY_ERROR_INTERVAL 10000 // Safety net: report again every 10 seconds
  39. #define SQLRES(s, r, m) \
  40. if ((s) != (r)) { \
  41. throw DatabaseException(std::string(m) + ": " +\
  42. sqlite3_errmsg(m_database)); \
  43. }
  44. #define SQLOK(s, m) SQLRES(s, SQLITE_OK, m)
  45. #define PREPARE_STATEMENT(name, query) \
  46. SQLOK(sqlite3_prepare_v2(m_database, query, -1, &m_stmt_##name, NULL),\
  47. "Failed to prepare query '" query "'")
  48. #define SQLOK_ERRSTREAM(s, m) \
  49. if ((s) != SQLITE_OK) { \
  50. errorstream << (m) << ": " \
  51. << sqlite3_errmsg(m_database) << std::endl; \
  52. }
  53. #define FINALIZE_STATEMENT(statement) SQLOK_ERRSTREAM(sqlite3_finalize(statement), \
  54. "Failed to finalize " #statement)
  55. int Database_SQLite3::busyHandler(void *data, int count)
  56. {
  57. s64 &first_time = reinterpret_cast<s64 *>(data)[0];
  58. s64 &prev_time = reinterpret_cast<s64 *>(data)[1];
  59. s64 cur_time = porting::getTimeMs();
  60. if (count == 0) {
  61. first_time = cur_time;
  62. prev_time = first_time;
  63. } else {
  64. while (cur_time < prev_time)
  65. cur_time += s64(1)<<32;
  66. }
  67. if (cur_time - first_time < BUSY_INFO_TRESHOLD) {
  68. ; // do nothing
  69. } else if (cur_time - first_time >= BUSY_INFO_TRESHOLD &&
  70. prev_time - first_time < BUSY_INFO_TRESHOLD) {
  71. infostream << "SQLite3 database has been locked for "
  72. << cur_time - first_time << " ms." << std::endl;
  73. } else if (cur_time - first_time >= BUSY_WARNING_TRESHOLD &&
  74. prev_time - first_time < BUSY_WARNING_TRESHOLD) {
  75. warningstream << "SQLite3 database has been locked for "
  76. << cur_time - first_time << " ms." << std::endl;
  77. } else if (cur_time - first_time >= BUSY_ERROR_TRESHOLD &&
  78. prev_time - first_time < BUSY_ERROR_TRESHOLD) {
  79. errorstream << "SQLite3 database has been locked for "
  80. << cur_time - first_time << " ms; this causes lag." << std::endl;
  81. } else if (cur_time - first_time >= BUSY_FATAL_TRESHOLD &&
  82. prev_time - first_time < BUSY_FATAL_TRESHOLD) {
  83. errorstream << "SQLite3 database has been locked for "
  84. << cur_time - first_time << " ms - giving up!" << std::endl;
  85. } else if ((cur_time - first_time) / BUSY_ERROR_INTERVAL !=
  86. (prev_time - first_time) / BUSY_ERROR_INTERVAL) {
  87. // Safety net: keep reporting every BUSY_ERROR_INTERVAL
  88. errorstream << "SQLite3 database has been locked for "
  89. << (cur_time - first_time) / 1000 << " seconds!" << std::endl;
  90. }
  91. prev_time = cur_time;
  92. // Make sqlite transaction fail if delay exceeds BUSY_FATAL_TRESHOLD
  93. return cur_time - first_time < BUSY_FATAL_TRESHOLD;
  94. }
  95. Database_SQLite3::Database_SQLite3(const std::string &savedir, const std::string &dbname) :
  96. m_savedir(savedir),
  97. m_dbname(dbname)
  98. {
  99. }
  100. void Database_SQLite3::beginSave()
  101. {
  102. verifyDatabase();
  103. SQLRES(sqlite3_step(m_stmt_begin), SQLITE_DONE,
  104. "Failed to start SQLite3 transaction");
  105. sqlite3_reset(m_stmt_begin);
  106. }
  107. void Database_SQLite3::endSave()
  108. {
  109. verifyDatabase();
  110. SQLRES(sqlite3_step(m_stmt_end), SQLITE_DONE,
  111. "Failed to commit SQLite3 transaction");
  112. sqlite3_reset(m_stmt_end);
  113. }
  114. void Database_SQLite3::openDatabase()
  115. {
  116. if (m_database) return;
  117. std::string dbp = m_savedir + DIR_DELIM + m_dbname + ".sqlite";
  118. // Open the database connection
  119. if (!fs::CreateAllDirs(m_savedir)) {
  120. infostream << "Database_SQLite3: Failed to create directory \""
  121. << m_savedir << "\"" << std::endl;
  122. throw FileNotGoodException("Failed to create database "
  123. "save directory");
  124. }
  125. bool needs_create = !fs::PathExists(dbp);
  126. SQLOK(sqlite3_open_v2(dbp.c_str(), &m_database,
  127. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL),
  128. std::string("Failed to open SQLite3 database file ") + dbp);
  129. SQLOK(sqlite3_busy_handler(m_database, Database_SQLite3::busyHandler,
  130. m_busy_handler_data), "Failed to set SQLite3 busy handler");
  131. if (needs_create) {
  132. createDatabase();
  133. }
  134. std::string query_str = std::string("PRAGMA synchronous = ")
  135. + itos(g_settings->getU16("sqlite_synchronous"));
  136. SQLOK(sqlite3_exec(m_database, query_str.c_str(), NULL, NULL, NULL),
  137. "Failed to modify sqlite3 synchronous mode");
  138. SQLOK(sqlite3_exec(m_database, "PRAGMA foreign_keys = ON", NULL, NULL, NULL),
  139. "Failed to enable sqlite3 foreign key support");
  140. }
  141. void Database_SQLite3::verifyDatabase()
  142. {
  143. if (m_initialized) return;
  144. openDatabase();
  145. PREPARE_STATEMENT(begin, "BEGIN;");
  146. PREPARE_STATEMENT(end, "COMMIT;");
  147. initStatements();
  148. m_initialized = true;
  149. }
  150. Database_SQLite3::~Database_SQLite3()
  151. {
  152. FINALIZE_STATEMENT(m_stmt_begin)
  153. FINALIZE_STATEMENT(m_stmt_end)
  154. SQLOK_ERRSTREAM(sqlite3_close(m_database), "Failed to close database");
  155. }
  156. /*
  157. * Map database
  158. */
  159. MapDatabaseSQLite3::MapDatabaseSQLite3(const std::string &savedir):
  160. Database_SQLite3(savedir, "map"),
  161. MapDatabase()
  162. {
  163. }
  164. MapDatabaseSQLite3::~MapDatabaseSQLite3()
  165. {
  166. FINALIZE_STATEMENT(m_stmt_read)
  167. FINALIZE_STATEMENT(m_stmt_write)
  168. FINALIZE_STATEMENT(m_stmt_list)
  169. FINALIZE_STATEMENT(m_stmt_delete)
  170. }
  171. void MapDatabaseSQLite3::createDatabase()
  172. {
  173. assert(m_database); // Pre-condition
  174. SQLOK(sqlite3_exec(m_database,
  175. "CREATE TABLE IF NOT EXISTS `blocks` (\n"
  176. " `pos` INT PRIMARY KEY,\n"
  177. " `data` BLOB\n"
  178. ");\n",
  179. NULL, NULL, NULL),
  180. "Failed to create database table");
  181. }
  182. void MapDatabaseSQLite3::initStatements()
  183. {
  184. PREPARE_STATEMENT(read, "SELECT `data` FROM `blocks` WHERE `pos` = ? LIMIT 1");
  185. #ifdef __ANDROID__
  186. PREPARE_STATEMENT(write, "INSERT INTO `blocks` (`pos`, `data`) VALUES (?, ?)");
  187. #else
  188. PREPARE_STATEMENT(write, "REPLACE INTO `blocks` (`pos`, `data`) VALUES (?, ?)");
  189. #endif
  190. PREPARE_STATEMENT(delete, "DELETE FROM `blocks` WHERE `pos` = ?");
  191. PREPARE_STATEMENT(list, "SELECT `pos` FROM `blocks`");
  192. verbosestream << "ServerMap: SQLite3 database opened." << std::endl;
  193. }
  194. inline void MapDatabaseSQLite3::bindPos(sqlite3_stmt *stmt, const v3s16 &pos, int index)
  195. {
  196. SQLOK(sqlite3_bind_int64(stmt, index, getBlockAsInteger(pos)),
  197. "Internal error: failed to bind query at " __FILE__ ":" TOSTRING(__LINE__));
  198. }
  199. bool MapDatabaseSQLite3::deleteBlock(const v3s16 &pos)
  200. {
  201. verifyDatabase();
  202. bindPos(m_stmt_delete, pos);
  203. bool good = sqlite3_step(m_stmt_delete) == SQLITE_DONE;
  204. sqlite3_reset(m_stmt_delete);
  205. if (!good) {
  206. warningstream << "deleteBlock: Block failed to delete "
  207. << PP(pos) << ": " << sqlite3_errmsg(m_database) << std::endl;
  208. }
  209. return good;
  210. }
  211. bool MapDatabaseSQLite3::saveBlock(const v3s16 &pos, const std::string &data)
  212. {
  213. verifyDatabase();
  214. #ifdef __ANDROID__
  215. /**
  216. * Note: For some unknown reason SQLite3 fails to REPLACE blocks on Android,
  217. * deleting them and then inserting works.
  218. */
  219. bindPos(m_stmt_read, pos);
  220. if (sqlite3_step(m_stmt_read) == SQLITE_ROW) {
  221. deleteBlock(pos);
  222. }
  223. sqlite3_reset(m_stmt_read);
  224. #endif
  225. bindPos(m_stmt_write, pos);
  226. SQLOK(sqlite3_bind_blob(m_stmt_write, 2, data.data(), data.size(), NULL),
  227. "Internal error: failed to bind query at " __FILE__ ":" TOSTRING(__LINE__));
  228. SQLRES(sqlite3_step(m_stmt_write), SQLITE_DONE, "Failed to save block")
  229. sqlite3_reset(m_stmt_write);
  230. return true;
  231. }
  232. void MapDatabaseSQLite3::loadBlock(const v3s16 &pos, std::string *block)
  233. {
  234. verifyDatabase();
  235. bindPos(m_stmt_read, pos);
  236. if (sqlite3_step(m_stmt_read) != SQLITE_ROW) {
  237. sqlite3_reset(m_stmt_read);
  238. return;
  239. }
  240. const char *data = (const char *) sqlite3_column_blob(m_stmt_read, 0);
  241. size_t len = sqlite3_column_bytes(m_stmt_read, 0);
  242. *block = (data) ? std::string(data, len) : "";
  243. sqlite3_step(m_stmt_read);
  244. // We should never get more than 1 row, so ok to reset
  245. sqlite3_reset(m_stmt_read);
  246. }
  247. void MapDatabaseSQLite3::listAllLoadableBlocks(std::vector<v3s16> &dst)
  248. {
  249. verifyDatabase();
  250. while (sqlite3_step(m_stmt_list) == SQLITE_ROW)
  251. dst.push_back(getIntegerAsBlock(sqlite3_column_int64(m_stmt_list, 0)));
  252. sqlite3_reset(m_stmt_list);
  253. }
  254. /*
  255. * Player Database
  256. */
  257. PlayerDatabaseSQLite3::PlayerDatabaseSQLite3(const std::string &savedir):
  258. Database_SQLite3(savedir, "players"),
  259. PlayerDatabase()
  260. {
  261. }
  262. PlayerDatabaseSQLite3::~PlayerDatabaseSQLite3()
  263. {
  264. FINALIZE_STATEMENT(m_stmt_player_load)
  265. FINALIZE_STATEMENT(m_stmt_player_add)
  266. FINALIZE_STATEMENT(m_stmt_player_update)
  267. FINALIZE_STATEMENT(m_stmt_player_remove)
  268. FINALIZE_STATEMENT(m_stmt_player_list)
  269. FINALIZE_STATEMENT(m_stmt_player_add_inventory)
  270. FINALIZE_STATEMENT(m_stmt_player_add_inventory_items)
  271. FINALIZE_STATEMENT(m_stmt_player_remove_inventory)
  272. FINALIZE_STATEMENT(m_stmt_player_remove_inventory_items)
  273. FINALIZE_STATEMENT(m_stmt_player_load_inventory)
  274. FINALIZE_STATEMENT(m_stmt_player_load_inventory_items)
  275. FINALIZE_STATEMENT(m_stmt_player_metadata_load)
  276. FINALIZE_STATEMENT(m_stmt_player_metadata_add)
  277. FINALIZE_STATEMENT(m_stmt_player_metadata_remove)
  278. };
  279. void PlayerDatabaseSQLite3::createDatabase()
  280. {
  281. assert(m_database); // Pre-condition
  282. SQLOK(sqlite3_exec(m_database,
  283. "CREATE TABLE IF NOT EXISTS `player` ("
  284. "`name` VARCHAR(50) NOT NULL,"
  285. "`pitch` NUMERIC(11, 4) NOT NULL,"
  286. "`yaw` NUMERIC(11, 4) NOT NULL,"
  287. "`posX` NUMERIC(11, 4) NOT NULL,"
  288. "`posY` NUMERIC(11, 4) NOT NULL,"
  289. "`posZ` NUMERIC(11, 4) NOT NULL,"
  290. "`hp` INT NOT NULL,"
  291. "`breath` INT NOT NULL,"
  292. "`creation_date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,"
  293. "`modification_date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,"
  294. "PRIMARY KEY (`name`));",
  295. NULL, NULL, NULL),
  296. "Failed to create player table");
  297. SQLOK(sqlite3_exec(m_database,
  298. "CREATE TABLE IF NOT EXISTS `player_metadata` ("
  299. " `player` VARCHAR(50) NOT NULL,"
  300. " `metadata` VARCHAR(256) NOT NULL,"
  301. " `value` TEXT,"
  302. " PRIMARY KEY(`player`, `metadata`),"
  303. " FOREIGN KEY (`player`) REFERENCES player (`name`) ON DELETE CASCADE );",
  304. NULL, NULL, NULL),
  305. "Failed to create player metadata table");
  306. SQLOK(sqlite3_exec(m_database,
  307. "CREATE TABLE IF NOT EXISTS `player_inventories` ("
  308. " `player` VARCHAR(50) NOT NULL,"
  309. " `inv_id` INT NOT NULL,"
  310. " `inv_width` INT NOT NULL,"
  311. " `inv_name` TEXT NOT NULL DEFAULT '',"
  312. " `inv_size` INT NOT NULL,"
  313. " PRIMARY KEY(player, inv_id),"
  314. " FOREIGN KEY (`player`) REFERENCES player (`name`) ON DELETE CASCADE );",
  315. NULL, NULL, NULL),
  316. "Failed to create player inventory table");
  317. SQLOK(sqlite3_exec(m_database,
  318. "CREATE TABLE `player_inventory_items` ("
  319. " `player` VARCHAR(50) NOT NULL,"
  320. " `inv_id` INT NOT NULL,"
  321. " `slot_id` INT NOT NULL,"
  322. " `item` TEXT NOT NULL DEFAULT '',"
  323. " PRIMARY KEY(player, inv_id, slot_id),"
  324. " FOREIGN KEY (`player`) REFERENCES player (`name`) ON DELETE CASCADE );",
  325. NULL, NULL, NULL),
  326. "Failed to create player inventory items table");
  327. }
  328. void PlayerDatabaseSQLite3::initStatements()
  329. {
  330. PREPARE_STATEMENT(player_load, "SELECT `pitch`, `yaw`, `posX`, `posY`, `posZ`, `hp`, "
  331. "`breath`"
  332. "FROM `player` WHERE `name` = ?")
  333. PREPARE_STATEMENT(player_add, "INSERT INTO `player` (`name`, `pitch`, `yaw`, `posX`, "
  334. "`posY`, `posZ`, `hp`, `breath`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
  335. PREPARE_STATEMENT(player_update, "UPDATE `player` SET `pitch` = ?, `yaw` = ?, "
  336. "`posX` = ?, `posY` = ?, `posZ` = ?, `hp` = ?, `breath` = ?, "
  337. "`modification_date` = CURRENT_TIMESTAMP WHERE `name` = ?")
  338. PREPARE_STATEMENT(player_remove, "DELETE FROM `player` WHERE `name` = ?")
  339. PREPARE_STATEMENT(player_list, "SELECT `name` FROM `player`")
  340. PREPARE_STATEMENT(player_add_inventory, "INSERT INTO `player_inventories` "
  341. "(`player`, `inv_id`, `inv_width`, `inv_name`, `inv_size`) VALUES (?, ?, ?, ?, ?)")
  342. PREPARE_STATEMENT(player_add_inventory_items, "INSERT INTO `player_inventory_items` "
  343. "(`player`, `inv_id`, `slot_id`, `item`) VALUES (?, ?, ?, ?)")
  344. PREPARE_STATEMENT(player_remove_inventory, "DELETE FROM `player_inventories` "
  345. "WHERE `player` = ?")
  346. PREPARE_STATEMENT(player_remove_inventory_items, "DELETE FROM `player_inventory_items` "
  347. "WHERE `player` = ?")
  348. PREPARE_STATEMENT(player_load_inventory, "SELECT `inv_id`, `inv_width`, `inv_name`, "
  349. "`inv_size` FROM `player_inventories` WHERE `player` = ? ORDER BY inv_id")
  350. PREPARE_STATEMENT(player_load_inventory_items, "SELECT `slot_id`, `item` "
  351. "FROM `player_inventory_items` WHERE `player` = ? AND `inv_id` = ?")
  352. PREPARE_STATEMENT(player_metadata_load, "SELECT `metadata`, `value` FROM "
  353. "`player_metadata` WHERE `player` = ?")
  354. PREPARE_STATEMENT(player_metadata_add, "INSERT INTO `player_metadata` "
  355. "(`player`, `metadata`, `value`) VALUES (?, ?, ?)")
  356. PREPARE_STATEMENT(player_metadata_remove, "DELETE FROM `player_metadata` "
  357. "WHERE `player` = ?")
  358. verbosestream << "ServerEnvironment: SQLite3 database opened (players)." << std::endl;
  359. }
  360. bool PlayerDatabaseSQLite3::playerDataExists(const std::string &name)
  361. {
  362. verifyDatabase();
  363. str_to_sqlite(m_stmt_player_load, 1, name);
  364. bool res = (sqlite3_step(m_stmt_player_load) == SQLITE_ROW);
  365. sqlite3_reset(m_stmt_player_load);
  366. return res;
  367. }
  368. void PlayerDatabaseSQLite3::savePlayer(RemotePlayer *player)
  369. {
  370. PlayerSAO* sao = player->getPlayerSAO();
  371. sanity_check(sao);
  372. const v3f &pos = sao->getBasePosition();
  373. // Begin save in brace is mandatory
  374. if (!playerDataExists(player->getName())) {
  375. beginSave();
  376. str_to_sqlite(m_stmt_player_add, 1, player->getName());
  377. double_to_sqlite(m_stmt_player_add, 2, sao->getLookPitch());
  378. double_to_sqlite(m_stmt_player_add, 3, sao->getRotation().Y);
  379. double_to_sqlite(m_stmt_player_add, 4, pos.X);
  380. double_to_sqlite(m_stmt_player_add, 5, pos.Y);
  381. double_to_sqlite(m_stmt_player_add, 6, pos.Z);
  382. int64_to_sqlite(m_stmt_player_add, 7, sao->getHP());
  383. int64_to_sqlite(m_stmt_player_add, 8, sao->getBreath());
  384. sqlite3_vrfy(sqlite3_step(m_stmt_player_add), SQLITE_DONE);
  385. sqlite3_reset(m_stmt_player_add);
  386. } else {
  387. beginSave();
  388. double_to_sqlite(m_stmt_player_update, 1, sao->getLookPitch());
  389. double_to_sqlite(m_stmt_player_update, 2, sao->getRotation().Y);
  390. double_to_sqlite(m_stmt_player_update, 3, pos.X);
  391. double_to_sqlite(m_stmt_player_update, 4, pos.Y);
  392. double_to_sqlite(m_stmt_player_update, 5, pos.Z);
  393. int64_to_sqlite(m_stmt_player_update, 6, sao->getHP());
  394. int64_to_sqlite(m_stmt_player_update, 7, sao->getBreath());
  395. str_to_sqlite(m_stmt_player_update, 8, player->getName());
  396. sqlite3_vrfy(sqlite3_step(m_stmt_player_update), SQLITE_DONE);
  397. sqlite3_reset(m_stmt_player_update);
  398. }
  399. // Write player inventories
  400. str_to_sqlite(m_stmt_player_remove_inventory, 1, player->getName());
  401. sqlite3_vrfy(sqlite3_step(m_stmt_player_remove_inventory), SQLITE_DONE);
  402. sqlite3_reset(m_stmt_player_remove_inventory);
  403. str_to_sqlite(m_stmt_player_remove_inventory_items, 1, player->getName());
  404. sqlite3_vrfy(sqlite3_step(m_stmt_player_remove_inventory_items), SQLITE_DONE);
  405. sqlite3_reset(m_stmt_player_remove_inventory_items);
  406. std::vector<const InventoryList*> inventory_lists = sao->getInventory()->getLists();
  407. for (u16 i = 0; i < inventory_lists.size(); i++) {
  408. const InventoryList* list = inventory_lists[i];
  409. str_to_sqlite(m_stmt_player_add_inventory, 1, player->getName());
  410. int_to_sqlite(m_stmt_player_add_inventory, 2, i);
  411. int_to_sqlite(m_stmt_player_add_inventory, 3, list->getWidth());
  412. str_to_sqlite(m_stmt_player_add_inventory, 4, list->getName());
  413. int_to_sqlite(m_stmt_player_add_inventory, 5, list->getSize());
  414. sqlite3_vrfy(sqlite3_step(m_stmt_player_add_inventory), SQLITE_DONE);
  415. sqlite3_reset(m_stmt_player_add_inventory);
  416. for (u32 j = 0; j < list->getSize(); j++) {
  417. std::ostringstream os;
  418. list->getItem(j).serialize(os);
  419. std::string itemStr = os.str();
  420. str_to_sqlite(m_stmt_player_add_inventory_items, 1, player->getName());
  421. int_to_sqlite(m_stmt_player_add_inventory_items, 2, i);
  422. int_to_sqlite(m_stmt_player_add_inventory_items, 3, j);
  423. str_to_sqlite(m_stmt_player_add_inventory_items, 4, itemStr);
  424. sqlite3_vrfy(sqlite3_step(m_stmt_player_add_inventory_items), SQLITE_DONE);
  425. sqlite3_reset(m_stmt_player_add_inventory_items);
  426. }
  427. }
  428. str_to_sqlite(m_stmt_player_metadata_remove, 1, player->getName());
  429. sqlite3_vrfy(sqlite3_step(m_stmt_player_metadata_remove), SQLITE_DONE);
  430. sqlite3_reset(m_stmt_player_metadata_remove);
  431. const StringMap &attrs = sao->getMeta().getStrings();
  432. for (const auto &attr : attrs) {
  433. str_to_sqlite(m_stmt_player_metadata_add, 1, player->getName());
  434. str_to_sqlite(m_stmt_player_metadata_add, 2, attr.first);
  435. str_to_sqlite(m_stmt_player_metadata_add, 3, attr.second);
  436. sqlite3_vrfy(sqlite3_step(m_stmt_player_metadata_add), SQLITE_DONE);
  437. sqlite3_reset(m_stmt_player_metadata_add);
  438. }
  439. endSave();
  440. player->onSuccessfulSave();
  441. }
  442. bool PlayerDatabaseSQLite3::loadPlayer(RemotePlayer *player, PlayerSAO *sao)
  443. {
  444. verifyDatabase();
  445. str_to_sqlite(m_stmt_player_load, 1, player->getName());
  446. if (sqlite3_step(m_stmt_player_load) != SQLITE_ROW) {
  447. sqlite3_reset(m_stmt_player_load);
  448. return false;
  449. }
  450. sao->setLookPitch(sqlite_to_float(m_stmt_player_load, 0));
  451. sao->setPlayerYaw(sqlite_to_float(m_stmt_player_load, 1));
  452. sao->setBasePosition(sqlite_to_v3f(m_stmt_player_load, 2));
  453. sao->setHPRaw((u16) MYMIN(sqlite_to_int(m_stmt_player_load, 5), U16_MAX));
  454. sao->setBreath((u16) MYMIN(sqlite_to_int(m_stmt_player_load, 6), U16_MAX), false);
  455. sqlite3_reset(m_stmt_player_load);
  456. // Load inventory
  457. str_to_sqlite(m_stmt_player_load_inventory, 1, player->getName());
  458. while (sqlite3_step(m_stmt_player_load_inventory) == SQLITE_ROW) {
  459. InventoryList *invList = player->inventory.addList(
  460. sqlite_to_string(m_stmt_player_load_inventory, 2),
  461. sqlite_to_uint(m_stmt_player_load_inventory, 3));
  462. invList->setWidth(sqlite_to_uint(m_stmt_player_load_inventory, 1));
  463. u32 invId = sqlite_to_uint(m_stmt_player_load_inventory, 0);
  464. str_to_sqlite(m_stmt_player_load_inventory_items, 1, player->getName());
  465. int_to_sqlite(m_stmt_player_load_inventory_items, 2, invId);
  466. while (sqlite3_step(m_stmt_player_load_inventory_items) == SQLITE_ROW) {
  467. const std::string itemStr = sqlite_to_string(m_stmt_player_load_inventory_items, 1);
  468. if (itemStr.length() > 0) {
  469. ItemStack stack;
  470. stack.deSerialize(itemStr);
  471. invList->changeItem(sqlite_to_uint(m_stmt_player_load_inventory_items, 0), stack);
  472. }
  473. }
  474. sqlite3_reset(m_stmt_player_load_inventory_items);
  475. }
  476. sqlite3_reset(m_stmt_player_load_inventory);
  477. str_to_sqlite(m_stmt_player_metadata_load, 1, sao->getPlayer()->getName());
  478. while (sqlite3_step(m_stmt_player_metadata_load) == SQLITE_ROW) {
  479. std::string attr = sqlite_to_string(m_stmt_player_metadata_load, 0);
  480. std::string value = sqlite_to_string(m_stmt_player_metadata_load, 1);
  481. sao->getMeta().setString(attr, value);
  482. }
  483. sao->getMeta().setModified(false);
  484. sqlite3_reset(m_stmt_player_metadata_load);
  485. return true;
  486. }
  487. bool PlayerDatabaseSQLite3::removePlayer(const std::string &name)
  488. {
  489. if (!playerDataExists(name))
  490. return false;
  491. str_to_sqlite(m_stmt_player_remove, 1, name);
  492. sqlite3_vrfy(sqlite3_step(m_stmt_player_remove), SQLITE_DONE);
  493. sqlite3_reset(m_stmt_player_remove);
  494. return true;
  495. }
  496. void PlayerDatabaseSQLite3::listPlayers(std::vector<std::string> &res)
  497. {
  498. verifyDatabase();
  499. while (sqlite3_step(m_stmt_player_list) == SQLITE_ROW)
  500. res.push_back(sqlite_to_string(m_stmt_player_list, 0));
  501. sqlite3_reset(m_stmt_player_list);
  502. }
  503. /*
  504. * Auth database
  505. */
  506. AuthDatabaseSQLite3::AuthDatabaseSQLite3(const std::string &savedir) :
  507. Database_SQLite3(savedir, "auth"), AuthDatabase()
  508. {
  509. }
  510. AuthDatabaseSQLite3::~AuthDatabaseSQLite3()
  511. {
  512. FINALIZE_STATEMENT(m_stmt_read)
  513. FINALIZE_STATEMENT(m_stmt_write)
  514. FINALIZE_STATEMENT(m_stmt_create)
  515. FINALIZE_STATEMENT(m_stmt_delete)
  516. FINALIZE_STATEMENT(m_stmt_list_names)
  517. FINALIZE_STATEMENT(m_stmt_read_privs)
  518. FINALIZE_STATEMENT(m_stmt_write_privs)
  519. FINALIZE_STATEMENT(m_stmt_delete_privs)
  520. FINALIZE_STATEMENT(m_stmt_last_insert_rowid)
  521. }
  522. void AuthDatabaseSQLite3::createDatabase()
  523. {
  524. assert(m_database); // Pre-condition
  525. SQLOK(sqlite3_exec(m_database,
  526. "CREATE TABLE IF NOT EXISTS `auth` ("
  527. "`id` INTEGER PRIMARY KEY AUTOINCREMENT,"
  528. "`name` VARCHAR(32) UNIQUE,"
  529. "`password` VARCHAR(512),"
  530. "`last_login` INTEGER"
  531. ");",
  532. NULL, NULL, NULL),
  533. "Failed to create auth table");
  534. SQLOK(sqlite3_exec(m_database,
  535. "CREATE TABLE IF NOT EXISTS `user_privileges` ("
  536. "`id` INTEGER,"
  537. "`privilege` VARCHAR(32),"
  538. "PRIMARY KEY (id, privilege)"
  539. "CONSTRAINT fk_id FOREIGN KEY (id) REFERENCES auth (id) ON DELETE CASCADE"
  540. ");",
  541. NULL, NULL, NULL),
  542. "Failed to create auth privileges table");
  543. }
  544. void AuthDatabaseSQLite3::initStatements()
  545. {
  546. PREPARE_STATEMENT(read, "SELECT id, name, password, last_login FROM auth WHERE name = ?");
  547. PREPARE_STATEMENT(write, "UPDATE auth set name = ?, password = ?, last_login = ? WHERE id = ?");
  548. PREPARE_STATEMENT(create, "INSERT INTO auth (name, password, last_login) VALUES (?, ?, ?)");
  549. PREPARE_STATEMENT(delete, "DELETE FROM auth WHERE name = ?");
  550. PREPARE_STATEMENT(list_names, "SELECT name FROM auth ORDER BY name DESC");
  551. PREPARE_STATEMENT(read_privs, "SELECT privilege FROM user_privileges WHERE id = ?");
  552. PREPARE_STATEMENT(write_privs, "INSERT OR IGNORE INTO user_privileges (id, privilege) VALUES (?, ?)");
  553. PREPARE_STATEMENT(delete_privs, "DELETE FROM user_privileges WHERE id = ?");
  554. PREPARE_STATEMENT(last_insert_rowid, "SELECT last_insert_rowid()");
  555. }
  556. bool AuthDatabaseSQLite3::getAuth(const std::string &name, AuthEntry &res)
  557. {
  558. verifyDatabase();
  559. str_to_sqlite(m_stmt_read, 1, name);
  560. if (sqlite3_step(m_stmt_read) != SQLITE_ROW) {
  561. sqlite3_reset(m_stmt_read);
  562. return false;
  563. }
  564. res.id = sqlite_to_uint(m_stmt_read, 0);
  565. res.name = sqlite_to_string(m_stmt_read, 1);
  566. res.password = sqlite_to_string(m_stmt_read, 2);
  567. res.last_login = sqlite_to_int64(m_stmt_read, 3);
  568. sqlite3_reset(m_stmt_read);
  569. int64_to_sqlite(m_stmt_read_privs, 1, res.id);
  570. while (sqlite3_step(m_stmt_read_privs) == SQLITE_ROW) {
  571. res.privileges.emplace_back(sqlite_to_string(m_stmt_read_privs, 0));
  572. }
  573. sqlite3_reset(m_stmt_read_privs);
  574. return true;
  575. }
  576. bool AuthDatabaseSQLite3::saveAuth(const AuthEntry &authEntry)
  577. {
  578. beginSave();
  579. str_to_sqlite(m_stmt_write, 1, authEntry.name);
  580. str_to_sqlite(m_stmt_write, 2, authEntry.password);
  581. int64_to_sqlite(m_stmt_write, 3, authEntry.last_login);
  582. int64_to_sqlite(m_stmt_write, 4, authEntry.id);
  583. sqlite3_vrfy(sqlite3_step(m_stmt_write), SQLITE_DONE);
  584. sqlite3_reset(m_stmt_write);
  585. writePrivileges(authEntry);
  586. endSave();
  587. return true;
  588. }
  589. bool AuthDatabaseSQLite3::createAuth(AuthEntry &authEntry)
  590. {
  591. beginSave();
  592. // id autoincrements
  593. str_to_sqlite(m_stmt_create, 1, authEntry.name);
  594. str_to_sqlite(m_stmt_create, 2, authEntry.password);
  595. int64_to_sqlite(m_stmt_create, 3, authEntry.last_login);
  596. sqlite3_vrfy(sqlite3_step(m_stmt_create), SQLITE_DONE);
  597. sqlite3_reset(m_stmt_create);
  598. // obtain id and write back to original authEntry
  599. sqlite3_step(m_stmt_last_insert_rowid);
  600. authEntry.id = sqlite_to_uint(m_stmt_last_insert_rowid, 0);
  601. sqlite3_reset(m_stmt_last_insert_rowid);
  602. writePrivileges(authEntry);
  603. endSave();
  604. return true;
  605. }
  606. bool AuthDatabaseSQLite3::deleteAuth(const std::string &name)
  607. {
  608. verifyDatabase();
  609. str_to_sqlite(m_stmt_delete, 1, name);
  610. sqlite3_vrfy(sqlite3_step(m_stmt_delete), SQLITE_DONE);
  611. int changes = sqlite3_changes(m_database);
  612. sqlite3_reset(m_stmt_delete);
  613. // privileges deleted by foreign key on delete cascade
  614. return changes > 0;
  615. }
  616. void AuthDatabaseSQLite3::listNames(std::vector<std::string> &res)
  617. {
  618. verifyDatabase();
  619. while (sqlite3_step(m_stmt_list_names) == SQLITE_ROW) {
  620. res.push_back(sqlite_to_string(m_stmt_list_names, 0));
  621. }
  622. sqlite3_reset(m_stmt_list_names);
  623. }
  624. void AuthDatabaseSQLite3::reload()
  625. {
  626. // noop for SQLite
  627. }
  628. void AuthDatabaseSQLite3::writePrivileges(const AuthEntry &authEntry)
  629. {
  630. int64_to_sqlite(m_stmt_delete_privs, 1, authEntry.id);
  631. sqlite3_vrfy(sqlite3_step(m_stmt_delete_privs), SQLITE_DONE);
  632. sqlite3_reset(m_stmt_delete_privs);
  633. for (const std::string &privilege : authEntry.privileges) {
  634. int64_to_sqlite(m_stmt_write_privs, 1, authEntry.id);
  635. str_to_sqlite(m_stmt_write_privs, 2, privilege);
  636. sqlite3_vrfy(sqlite3_step(m_stmt_write_privs), SQLITE_DONE);
  637. sqlite3_reset(m_stmt_write_privs);
  638. }
  639. }