45de3cb605aa251997525faaeec25b2a80792226
[oweals/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 "util/string.h"
35
36 #include <cassert>
37
38
39 #define SQLRES(s, r) \
40         if ((s) != (r)) { \
41                 throw FileNotGoodException(std::string(\
42                                         "SQLite3 database error (" \
43                                         __FILE__ ":" TOSTRING(__LINE__) \
44                                         "): ") +\
45                                 sqlite3_errmsg(m_database)); \
46         }
47 #define SQLOK(s) SQLRES(s, SQLITE_OK)
48
49 #define PREPARE_STATEMENT(name, query) \
50         SQLOK(sqlite3_prepare_v2(m_database, query, -1, &m_stmt_##name, NULL))
51
52 #define FINALIZE_STATEMENT(statement) \
53         if (sqlite3_finalize(statement) != SQLITE_OK) { \
54                 throw FileNotGoodException(std::string( \
55                         "SQLite3: Failed to finalize " #statement ": ") + \
56                          sqlite3_errmsg(m_database)); \
57         }
58
59
60 Database_SQLite3::Database_SQLite3(const std::string &savedir) :
61         m_initialized(false),
62         m_savedir(savedir),
63         m_database(NULL),
64         m_stmt_read(NULL),
65         m_stmt_write(NULL),
66         m_stmt_list(NULL),
67         m_stmt_delete(NULL)
68 {
69 }
70
71 void Database_SQLite3::beginSave() {
72         verifyDatabase();
73         SQLRES(sqlite3_step(m_stmt_begin), SQLITE_DONE);
74         sqlite3_reset(m_stmt_begin);
75 }
76
77 void Database_SQLite3::endSave() {
78         verifyDatabase();
79         SQLRES(sqlite3_step(m_stmt_end), SQLITE_DONE);
80         sqlite3_reset(m_stmt_end);
81 }
82
83 void Database_SQLite3::openDatabase()
84 {
85         if (m_database) return;
86
87         std::string dbp = m_savedir + DIR_DELIM + "map.sqlite";
88
89         // Open the database connection
90
91         if (!fs::CreateAllDirs(m_savedir)) {
92                 infostream << "Database_SQLite3: Failed to create directory \""
93                         << m_savedir << "\"" << std::endl;
94                 throw FileNotGoodException("Failed to create database "
95                                 "save directory");
96         }
97
98         bool needs_create = !fs::PathExists(dbp);
99
100         if (sqlite3_open_v2(dbp.c_str(), &m_database,
101                         SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
102                         NULL) != SQLITE_OK) {
103                 errorstream << "SQLite3 database failed to open: "
104                         << sqlite3_errmsg(m_database) << std::endl;
105                 throw FileNotGoodException("Cannot open database file");
106         }
107
108         if (needs_create) {
109                 createDatabase();
110         }
111
112         std::string query_str = std::string("PRAGMA synchronous = ")
113                          + itos(g_settings->getU16("sqlite_synchronous"));
114         SQLOK(sqlite3_exec(m_database, query_str.c_str(), NULL, NULL, NULL));
115 }
116
117 void Database_SQLite3::verifyDatabase()
118 {
119         if (m_initialized) return;
120
121         openDatabase();
122
123         PREPARE_STATEMENT(begin, "BEGIN");
124         PREPARE_STATEMENT(end, "COMMIT");
125         PREPARE_STATEMENT(read, "SELECT `data` FROM `blocks` WHERE `pos` = ? LIMIT 1");
126 #ifdef __ANDROID__
127         PREPARE_STATEMENT(write,  "INSERT INTO `blocks` (`pos`, `data`) VALUES (?, ?)");
128 #else
129         PREPARE_STATEMENT(write, "REPLACE INTO `blocks` (`pos`, `data`) VALUES (?, ?)");
130 #endif
131         PREPARE_STATEMENT(delete, "DELETE FROM `blocks` WHERE `pos` = ?");
132         PREPARE_STATEMENT(list, "SELECT `pos` FROM `blocks`");
133
134         m_initialized = true;
135
136         verbosestream << "ServerMap: SQLite3 database opened." << std::endl;
137 }
138
139 inline void Database_SQLite3::bindPos(sqlite3_stmt *stmt, const v3s16 &pos, int index)
140 {
141         SQLOK(sqlite3_bind_int64(stmt, index, getBlockAsInteger(pos)));
142 }
143
144 bool Database_SQLite3::deleteBlock(const v3s16 &pos)
145 {
146         verifyDatabase();
147
148         bindPos(m_stmt_delete, pos);
149
150         bool good = sqlite3_step(m_stmt_delete) == SQLITE_DONE;
151         sqlite3_reset(m_stmt_delete);
152
153         if (!good) {
154                 errorstream << "WARNING: deleteBlock: Block failed to delete "
155                         << PP(pos) << ": " << sqlite3_errmsg(m_database) << std::endl;
156         }
157         return good;
158 }
159
160 bool Database_SQLite3::saveBlock(const v3s16 &pos, const std::string &data)
161 {
162         verifyDatabase();
163
164 #ifdef __ANDROID__
165         /**
166          * Note: For some unknown reason SQLite3 fails to REPLACE blocks on Android,
167          * deleting them and then inserting works.
168          */
169         bindPos(m_stmt_read, pos);
170
171         if (sqlite3_step(m_stmt_read) == SQLITE_ROW) {
172                 deleteBlock(pos);
173         }
174         sqlite3_reset(m_stmt_read);
175 #endif
176
177         bindPos(m_stmt_write, pos);
178         SQLOK(sqlite3_bind_blob(m_stmt_write, 2, data.data(), data.size(), NULL));
179
180         SQLRES(sqlite3_step(m_stmt_write), SQLITE_DONE)
181         sqlite3_reset(m_stmt_write);
182
183         return true;
184 }
185
186 std::string Database_SQLite3::loadBlock(const v3s16 &pos)
187 {
188         verifyDatabase();
189
190         bindPos(m_stmt_read, pos);
191
192         if (sqlite3_step(m_stmt_read) != SQLITE_ROW) {
193                 sqlite3_reset(m_stmt_read);
194                 return "";
195         }
196         const char *data = (const char *) sqlite3_column_blob(m_stmt_read, 0);
197         size_t len = sqlite3_column_bytes(m_stmt_read, 0);
198
199         std::string s;
200         if (data)
201                 s = std::string(data, len);
202
203         sqlite3_step(m_stmt_read);
204         // We should never get more than 1 row, so ok to reset
205         sqlite3_reset(m_stmt_read);
206
207         return s;
208 }
209
210 void Database_SQLite3::createDatabase()
211 {
212         assert(m_database); // Pre-condition
213         SQLOK(sqlite3_exec(m_database,
214                 "CREATE TABLE IF NOT EXISTS `blocks` (\n"
215                 "       `pos` INT PRIMARY KEY,\n"
216                 "       `data` BLOB\n"
217                 ");\n",
218                 NULL, NULL, NULL));
219 }
220
221 void Database_SQLite3::listAllLoadableBlocks(std::vector<v3s16> &dst)
222 {
223         verifyDatabase();
224
225         while (sqlite3_step(m_stmt_list) == SQLITE_ROW) {
226                 dst.push_back(getIntegerAsBlock(sqlite3_column_int64(m_stmt_list, 0)));
227         }
228         sqlite3_reset(m_stmt_list);
229 }
230
231 Database_SQLite3::~Database_SQLite3()
232 {
233         FINALIZE_STATEMENT(m_stmt_read)
234         FINALIZE_STATEMENT(m_stmt_write)
235         FINALIZE_STATEMENT(m_stmt_list)
236         FINALIZE_STATEMENT(m_stmt_begin)
237         FINALIZE_STATEMENT(m_stmt_end)
238         FINALIZE_STATEMENT(m_stmt_delete)
239
240         if (sqlite3_close(m_database) != SQLITE_OK) {
241                 errorstream << "Database_SQLite3::~Database_SQLite3(): "
242                                 << "Failed to close database: "
243                                 << sqlite3_errmsg(m_database) << std::endl;
244         }
245 }
246