]> git.lizzy.rs Git - minetest.git/blob - src/database-sqlite3.cpp
Only include keycode unittests in client build (fixes #4559)
[minetest.git] / src / database-sqlite3.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 /*
21 SQLite format specification:
22         blocks:
23                 (PK) INT id
24                 BLOB data
25 */
26
27
28 #include "database-sqlite3.h"
29
30 #include "log.h"
31 #include "filesys.h"
32 #include "exceptions.h"
33 #include "settings.h"
34 #include "porting.h"
35 #include "util/string.h"
36
37 #include <cassert>
38
39 // When to print messages when the database is being held locked by another process
40 // Note: I've seen occasional delays of over 250ms while running minetestmapper.
41 #define BUSY_INFO_TRESHOLD      100     // Print first informational message after 100ms.
42 #define BUSY_WARNING_TRESHOLD   250     // Print warning message after 250ms. Lag is increased.
43 #define BUSY_ERROR_TRESHOLD     1000    // Print error message after 1000ms. Significant lag.
44 #define BUSY_FATAL_TRESHOLD     3000    // Allow SQLITE_BUSY to be returned, which will cause a minetest crash.
45 #define BUSY_ERROR_INTERVAL     10000   // Safety net: report again every 10 seconds
46
47
48 #define SQLRES(s, r, m) \
49         if ((s) != (r)) { \
50                 throw DatabaseException(std::string(m) + ": " +\
51                                 sqlite3_errmsg(m_database)); \
52         }
53 #define SQLOK(s, m) SQLRES(s, SQLITE_OK, m)
54
55 #define PREPARE_STATEMENT(name, query) \
56         SQLOK(sqlite3_prepare_v2(m_database, query, -1, &m_stmt_##name, NULL),\
57                 "Failed to prepare query '" query "'")
58
59 #define SQLOK_ERRSTREAM(s, m)                           \
60         if ((s) != SQLITE_OK) {                             \
61                 errorstream << (m) << ": "                      \
62                         << sqlite3_errmsg(m_database) << std::endl; \
63         }
64
65 #define FINALIZE_STATEMENT(statement) SQLOK_ERRSTREAM(sqlite3_finalize(statement), \
66         "Failed to finalize " #statement)
67
68 int Database_SQLite3::busyHandler(void *data, int count)
69 {
70         s64 &first_time = reinterpret_cast<s64 *>(data)[0];
71         s64 &prev_time = reinterpret_cast<s64 *>(data)[1];
72         s64 cur_time = getTimeMs();
73
74         if (count == 0) {
75                 first_time = cur_time;
76                 prev_time = first_time;
77         } else {
78                 while (cur_time < prev_time)
79                         cur_time += s64(1)<<32;
80         }
81
82         if (cur_time - first_time < BUSY_INFO_TRESHOLD) {
83                 ; // do nothing
84         } else if (cur_time - first_time >= BUSY_INFO_TRESHOLD &&
85                         prev_time - first_time < BUSY_INFO_TRESHOLD) {
86                 infostream << "SQLite3 database has been locked for "
87                         << cur_time - first_time << " ms." << std::endl;
88         } else if (cur_time - first_time >= BUSY_WARNING_TRESHOLD &&
89                         prev_time - first_time < BUSY_WARNING_TRESHOLD) {
90                 warningstream << "SQLite3 database has been locked for "
91                         << cur_time - first_time << " ms." << std::endl;
92         } else if (cur_time - first_time >= BUSY_ERROR_TRESHOLD &&
93                         prev_time - first_time < BUSY_ERROR_TRESHOLD) {
94                 errorstream << "SQLite3 database has been locked for "
95                         << cur_time - first_time << " ms; this causes lag." << std::endl;
96         } else if (cur_time - first_time >= BUSY_FATAL_TRESHOLD &&
97                         prev_time - first_time < BUSY_FATAL_TRESHOLD) {
98                 errorstream << "SQLite3 database has been locked for "
99                         << cur_time - first_time << " ms - giving up!" << std::endl;
100         } else if ((cur_time - first_time) / BUSY_ERROR_INTERVAL !=
101                         (prev_time - first_time) / BUSY_ERROR_INTERVAL) {
102                 // Safety net: keep reporting every BUSY_ERROR_INTERVAL
103                 errorstream << "SQLite3 database has been locked for "
104                         << (cur_time - first_time) / 1000 << " seconds!" << std::endl;
105         }
106
107         prev_time = cur_time;
108
109         // Make sqlite transaction fail if delay exceeds BUSY_FATAL_TRESHOLD
110         return cur_time - first_time < BUSY_FATAL_TRESHOLD;
111 }
112
113
114 Database_SQLite3::Database_SQLite3(const std::string &savedir) :
115         m_initialized(false),
116         m_savedir(savedir),
117         m_database(NULL),
118         m_stmt_read(NULL),
119         m_stmt_write(NULL),
120         m_stmt_list(NULL),
121         m_stmt_delete(NULL),
122         m_stmt_begin(NULL),
123         m_stmt_end(NULL)
124 {
125 }
126
127 void Database_SQLite3::beginSave() {
128         verifyDatabase();
129         SQLRES(sqlite3_step(m_stmt_begin), SQLITE_DONE,
130                 "Failed to start SQLite3 transaction");
131         sqlite3_reset(m_stmt_begin);
132 }
133
134 void Database_SQLite3::endSave() {
135         verifyDatabase();
136         SQLRES(sqlite3_step(m_stmt_end), SQLITE_DONE,
137                 "Failed to commit SQLite3 transaction");
138         sqlite3_reset(m_stmt_end);
139 }
140
141 void Database_SQLite3::openDatabase()
142 {
143         if (m_database) return;
144
145         std::string dbp = m_savedir + DIR_DELIM + "map.sqlite";
146
147         // Open the database connection
148
149         if (!fs::CreateAllDirs(m_savedir)) {
150                 infostream << "Database_SQLite3: Failed to create directory \""
151                         << m_savedir << "\"" << std::endl;
152                 throw FileNotGoodException("Failed to create database "
153                                 "save directory");
154         }
155
156         bool needs_create = !fs::PathExists(dbp);
157
158         SQLOK(sqlite3_open_v2(dbp.c_str(), &m_database,
159                         SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL),
160                 std::string("Failed to open SQLite3 database file ") + dbp);
161
162         SQLOK(sqlite3_busy_handler(m_database, Database_SQLite3::busyHandler,
163                 m_busy_handler_data), "Failed to set SQLite3 busy handler");
164
165         if (needs_create) {
166                 createDatabase();
167         }
168
169         std::string query_str = std::string("PRAGMA synchronous = ")
170                          + itos(g_settings->getU16("sqlite_synchronous"));
171         SQLOK(sqlite3_exec(m_database, query_str.c_str(), NULL, NULL, NULL),
172                 "Failed to modify sqlite3 synchronous mode");
173 }
174
175 void Database_SQLite3::verifyDatabase()
176 {
177         if (m_initialized) return;
178
179         openDatabase();
180
181         PREPARE_STATEMENT(begin, "BEGIN");
182         PREPARE_STATEMENT(end, "COMMIT");
183         PREPARE_STATEMENT(read, "SELECT `data` FROM `blocks` WHERE `pos` = ? LIMIT 1");
184 #ifdef __ANDROID__
185         PREPARE_STATEMENT(write,  "INSERT INTO `blocks` (`pos`, `data`) VALUES (?, ?)");
186 #else
187         PREPARE_STATEMENT(write, "REPLACE INTO `blocks` (`pos`, `data`) VALUES (?, ?)");
188 #endif
189         PREPARE_STATEMENT(delete, "DELETE FROM `blocks` WHERE `pos` = ?");
190         PREPARE_STATEMENT(list, "SELECT `pos` FROM `blocks`");
191
192         m_initialized = true;
193
194         verbosestream << "ServerMap: SQLite3 database opened." << std::endl;
195 }
196
197 inline void Database_SQLite3::bindPos(sqlite3_stmt *stmt, const v3s16 &pos, int index)
198 {
199         SQLOK(sqlite3_bind_int64(stmt, index, getBlockAsInteger(pos)),
200                 "Internal error: failed to bind query at " __FILE__ ":" TOSTRING(__LINE__));
201 }
202
203 bool Database_SQLite3::deleteBlock(const v3s16 &pos)
204 {
205         verifyDatabase();
206
207         bindPos(m_stmt_delete, pos);
208
209         bool good = sqlite3_step(m_stmt_delete) == SQLITE_DONE;
210         sqlite3_reset(m_stmt_delete);
211
212         if (!good) {
213                 warningstream << "deleteBlock: Block failed to delete "
214                         << PP(pos) << ": " << sqlite3_errmsg(m_database) << std::endl;
215         }
216         return good;
217 }
218
219 bool Database_SQLite3::saveBlock(const v3s16 &pos, const std::string &data)
220 {
221         verifyDatabase();
222
223 #ifdef __ANDROID__
224         /**
225          * Note: For some unknown reason SQLite3 fails to REPLACE blocks on Android,
226          * deleting them and then inserting works.
227          */
228         bindPos(m_stmt_read, pos);
229
230         if (sqlite3_step(m_stmt_read) == SQLITE_ROW) {
231                 deleteBlock(pos);
232         }
233         sqlite3_reset(m_stmt_read);
234 #endif
235
236         bindPos(m_stmt_write, pos);
237         SQLOK(sqlite3_bind_blob(m_stmt_write, 2, data.data(), data.size(), NULL),
238                 "Internal error: failed to bind query at " __FILE__ ":" TOSTRING(__LINE__));
239
240         SQLRES(sqlite3_step(m_stmt_write), SQLITE_DONE, "Failed to save block")
241         sqlite3_reset(m_stmt_write);
242
243         return true;
244 }
245
246 void Database_SQLite3::loadBlock(const v3s16 &pos, std::string *block)
247 {
248         verifyDatabase();
249
250         bindPos(m_stmt_read, pos);
251
252         if (sqlite3_step(m_stmt_read) != SQLITE_ROW) {
253                 sqlite3_reset(m_stmt_read);
254                 return;
255         }
256
257         const char *data = (const char *) sqlite3_column_blob(m_stmt_read, 0);
258         size_t len = sqlite3_column_bytes(m_stmt_read, 0);
259
260         *block = (data) ? std::string(data, len) : "";
261
262         sqlite3_step(m_stmt_read);
263         // We should never get more than 1 row, so ok to reset
264         sqlite3_reset(m_stmt_read);
265 }
266
267 void Database_SQLite3::createDatabase()
268 {
269         assert(m_database); // Pre-condition
270         SQLOK(sqlite3_exec(m_database,
271                 "CREATE TABLE IF NOT EXISTS `blocks` (\n"
272                 "       `pos` INT PRIMARY KEY,\n"
273                 "       `data` BLOB\n"
274                 ");\n",
275                 NULL, NULL, NULL),
276                 "Failed to create database table");
277 }
278
279 void Database_SQLite3::listAllLoadableBlocks(std::vector<v3s16> &dst)
280 {
281         verifyDatabase();
282
283         while (sqlite3_step(m_stmt_list) == SQLITE_ROW) {
284                 dst.push_back(getIntegerAsBlock(sqlite3_column_int64(m_stmt_list, 0)));
285         }
286         sqlite3_reset(m_stmt_list);
287 }
288
289 Database_SQLite3::~Database_SQLite3()
290 {
291         FINALIZE_STATEMENT(m_stmt_read)
292         FINALIZE_STATEMENT(m_stmt_write)
293         FINALIZE_STATEMENT(m_stmt_list)
294         FINALIZE_STATEMENT(m_stmt_begin)
295         FINALIZE_STATEMENT(m_stmt_end)
296         FINALIZE_STATEMENT(m_stmt_delete)
297
298         SQLOK_ERRSTREAM(sqlite3_close(m_database), "Failed to close database");
299 }
300