Debian Codegraph @

Storage/Sqlite.cpp

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 /*
2 RailControl - Model Railway Control Software
3
4 Copyright (c) 2017-2025 by Teddy / Dominik Mahrer - www.railcontrol.org
5
6 RailControl is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
10
11 RailControl is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14 See the GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with RailControl; see the file LICENCE. If not see
18 <http://www.gnu.org/licenses/>.
19 */
20
21 #include <ctime>
22 #include <map>
23 #include <string>
24
25 #include "Languages.h"
26 #include "Storage/Sqlite.h"
27 #include "Utils/Integer.h"
28
29 using DataModel::Accessory;
30 using DataModel::Track;
31 using DataModel::Feedback;
32 using DataModel::Loco;
33 using DataModel::Switch;
34 using Hardware::HardwareParams;
35 using std::map;
36 using std::string;
37 using std::vector;
38 using std::to_string;
39
40 namespace Storage
41 {
42 SQLite::SQLite(const StorageParams* params)
43 : filename(params->filename),
44 logger(Logger::Logger::GetLogger("SQLite")),
45 keepBackups(params->keepBackups)
46 {
47 Utils::Utils::RemoveOldBackupFiles (logger, filename, keepBackups);
48 logger->Info(Languages::TextOpeningSQLite, filename);
49 int rc = sqlite3_open(filename.c_str(), &db);
50 if (rc)
51 {
52 logger->Error(Languages::TextUnableToOpenSQLite, sqlite3_errmsg(db));
53 sqlite3_close(db);
54 db = nullptr;
55 return;
56 }
57
58 // check if needed tables exist
59 map<string, bool> tablenames;
60 const char* query = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;";
61 bool ret = Execute(query, CallbackListTables, &tablenames);
62 if (ret == false)
63 {
64 return;
65 }
66
67 // create hardware table if needed
68 if (tablenames["hardware"] == false)
69 {
70 bool ret = CreateTableHardware();
71 if (ret == false)
72 {
73 return;
74 }
75 }
76
77 // create objects table if needed
78 if (tablenames["objects"] == false)
79 {
80 bool ret = CreateTableObjects();
81 if (ret == false)
82 {
83 return;
84 }
85 }
86
87 // create relations table if needed
88 string tableNameRelations = "relations";
89 if (tablenames[tableNameRelations] == true)
90 {
91 ret = CheckTableRelations();
92 }
93 else {
94 ret = CreateTableRelations(tableNameRelations);
95 }
96 if (ret == false)
97 {
98 return;
99 }
100
101 // create settings table if needed
102 if (tablenames["settings"] == false)
103 {
104 bool ret = CreateTableSettings();
105 if (ret == false)
106 {
107 return;
108 }
109 }
110 }
111
112
113 SQLite::~SQLite()
114 {
115 if (db == nullptr)
116 {
117 return;
118 }
119
120 logger->Info(Languages::TextClosingSQLite);
121 sqlite3_close(db);
122 db = nullptr;
123
124 if (keepBackups == 0)
125 {
126 return;
127 }
128 Utils::Utils::CopyFile(logger, filename, filename + "." + std::to_string(std::time(nullptr)));
129 }
130
131 int SQLite::CallbackListTables(void* v, int argc, char **argv, __attribute__((unused)) char **colName)
132 {
133 map<string, bool>* tablenames = static_cast<map<string, bool>*>(v);
134 if (argc != 1)
135 {
136 return 0;
137 }
138 (*tablenames)[argv[0]] = true;
139 return 0;
140 }
141
142 bool SQLite::DropTable(const string table)
143 {
144 logger->Info(Languages::TextDroppingTable, table);
145 string query = "DROP TABLE " + table + ";";
146 return Execute(query);
147 }
148
149 bool SQLite::CreateTableHardware()
150 {
151 logger->Info(Languages::TextCreatingTable, "hardware");
152 const string query = "CREATE TABLE hardware ("
153 "controlid UNSIGNED TINYINT,"
154 " hardwaretype UNSIGNED TINYINT,"
155 " name VARCHAR(50),"
156 " arg1 VARCHAR(255),"
157 " arg2 VARCHAR(255),"
158 " arg3 VARCHAR(255),"
159 " arg4 VARCHAR(255),"
160 " arg5 VARCHAR(255),"
161 "PRIMARY KEY (controlid));";
162 return Execute(query);
163 }
164
165 bool SQLite::CreateTableObjects()
166 {
167 logger->Info(Languages::TextCreatingTable, "objects");
168 const char* query = "CREATE TABLE objects ("
169 "objecttype UNSIGNED TINYINT, "
170 "objectid UNSIGNED SHORTINT, "
171 "name VARCHAR(50), "
172 "object SHORTTEXT,"
173 "PRIMARY KEY (objecttype, objectid));";
174 return Execute(query);
175 }
176
177 bool SQLite::CreateTableRelations(const string& name)
178 {
179 logger->Info(Languages::TextCreatingTable, name);
180 const string query = "CREATE TABLE " + name + " ("
181 "type UNSIGNED TINYINT, "
182 "objectid1 UNSIGNED SHORTINT, "
183 "objecttype2 UNSIGNED TINYINT, "
184 "objectid2 UNSIGNED SHORTINT, "
185 "priority UNSIGNED TINYINT, "
186 "relation SHORTTEXT,"
187 "PRIMARY KEY (type, objectid1, objecttype2, objectid2, priority));";
188 return Execute(query);
189 }
190
191 bool SQLite::CreateTableSettings()
192 {
193 logger->Info(Languages::TextCreatingTable, "settings");
194 const char* query = "CREATE TABLE settings ("
195 "key TINYTEXT, "
196 "value SHORTTEXT,"
197 "PRIMARY KEY (key));";
198 return Execute(query);
199 }
200
201 struct TableInfo
202 {
203 public:
204 int cid;
205 string name;
206 string type;
207 bool notNull;
208 bool defaultNull;
209 string defaultValue;
210 int primaryKey;
211 };
212
213 bool SQLite::CheckTableRelations()
214 {
215 vector<TableInfo> tableInfos;
216 string query = "PRAGMA table_info('relations');";
217 bool ret = Execute(query, CallbackTableInfo, &tableInfos);
218 if (ret == false)
219 {
220 return false;
221 }
222
223 string name = "relations";
224 if (tableInfos.size() != 6)
225 {
226 return DropTable(name) && CreateTableRelations(name);
227 }
228
229 if (tableInfos[0].name.compare("type") != 0)
230 {
231 return UpdateTableRelations1();
232 }
233
234 // FIXME: simple check, extend with check if each object really exists
235 query = "DELETE FROM relations WHERE objectid1 like 0;";
236 ret = Execute(query);
237 if (ret == false)
238 {
239 return false;
240 }
241
242 logger->Info(Languages::TextIsUpToDate, name);
243 return true;
244 }
245
246 bool SQLite::UpdateTableRelations1()
247 {
248 const string tableName = "relations";
249 const string tempTableName = "relations_temp";
250 bool ret = CreateTableRelations(tempTableName);
251 if (ret == false)
252 {
253 return false;
254 }
255 logger->Info(Languages::TextCopyingFromTo, tableName, tempTableName);
256 const string query = "INSERT INTO " + tempTableName + " SELECT objecttype1 * 8, objectid1, objecttype2, objectid2, priority, relation FROM " + tableName + ";";
257 ret = Execute(query);
258 if (ret == false)
259 {
260 return false;
261 }
262 ret = DropTable(tableName);
263 if (ret == false)
264 {
265 return false;
266 }
267 logger->Info(Languages::TextRenamingFromTo, tempTableName, tableName);
268 return RenameTable(tempTableName, tableName);
269 }
270
271 bool SQLite::RenameTable(const string& oldName, const string& newName)
272 {
273 const string query = "ALTER TABLE " + oldName + " RENAME TO " + newName + ";";
274 return Execute(query);
275 }
276
277 int SQLite::CallbackTableInfo(void* v, int argc, char **argv, __attribute__((unused)) char **colName)
278 {
279 vector<TableInfo>* tableInfos = static_cast<vector<TableInfo>*>(v);
280 if (argc != 6)
281 {
282 return 0;
283 }
284 TableInfo tableInfo;
285 tableInfo.cid = Utils::Integer::StringToInteger(argv[0]);
286 tableInfo.name = argv[1];
287 tableInfo.type = argv[2];
288 tableInfo.notNull = Utils::Integer::StringToInteger(argv[3]) > 0;
289 tableInfo.defaultNull = argv[4] == nullptr;
290 tableInfo.defaultValue = argv[4] != nullptr ? argv[4] : "";
291 tableInfo.primaryKey = Utils::Integer::StringToInteger(argv[5]);
292 tableInfos->push_back(tableInfo);
293 return 0;
294 }
295
296 void SQLite::SaveHardwareParams(const Hardware::HardwareParams& hardwareParams)
297 {
298 string query = "INSERT OR REPLACE INTO hardware VALUES ("
299 + to_string(hardwareParams.GetControlID()) + ", "
300 + to_string(hardwareParams.GetHardwareType()) + ", '"
301 + EscapeString(hardwareParams.GetName()) + "', '"
302 + EscapeString(hardwareParams.GetArg1()) + "', '"
303 + EscapeString(hardwareParams.GetArg2()) + "', '"
304 + EscapeString(hardwareParams.GetArg3()) + "', '"
305 + EscapeString(hardwareParams.GetArg4()) + "', '"
306 + EscapeString(hardwareParams.GetArg5()) + "');";
307 Execute(query);
308 }
309
310 void SQLite::AllHardwareParams(std::map<ControlID, Hardware::HardwareParams*>& hardwareParams)
311 {
312 const char* query = "SELECT controlid, hardwaretype, name, arg1, arg2, arg3, arg4, arg5 FROM hardware ORDER BY controlid;";
313 Execute(query, CallbackAllHardwareParams, &hardwareParams);
314 }
315
316 // callback read hardwareparams
317 int SQLite::CallbackAllHardwareParams(void* v, int argc, char **argv, __attribute__((unused)) char **colName)
318 {
319 map<ControlID,HardwareParams*>* hardwareParams = static_cast<map<ControlID,HardwareParams*>*>(v);
320 if (argc != 8)
321 {
322 return 0;
323 }
324 ControlID controlID = Utils::Integer::StringToInteger(argv[0]);
325
326 HardwareParams* params = new HardwareParams(controlID, static_cast<HardwareType>(Utils::Integer::StringToInteger(argv[1])), argv[2], argv[3], argv[4], argv[5], argv[6], argv[7]);
327 (*hardwareParams)[controlID] = params;
328 return 0;
329 }
330
331 // delete control
332 void SQLite::DeleteHardwareParams(const ControlID controlID)
333 {
334 string query = "DELETE FROM hardware WHERE controlid = " + to_string(controlID) + ";";
335 Execute(query);
336 }
337
338 // save DataModelobject
339 void SQLite::SaveObject(const ObjectType objectType, const ObjectID objectID, const std::string& name, const std::string& object)
340 {
341 string query = "INSERT OR REPLACE INTO objects (objecttype, objectid, name, object) VALUES ("
342 + to_string(objectType) + ", "
343 + to_string(objectID) + ", '"
344 + EscapeString(name) + "', '"
345 + EscapeString(object) + "');";
346 Execute(query);
347 }
348
349 // delete DataModelobject
350 void SQLite::DeleteObject(const ObjectType objectType, const ObjectID objectID)
351 {
352 string query = "DELETE FROM objects WHERE objecttype = " + to_string(objectType)
353 + " AND objectid = " + to_string(objectID) + ";";
354 Execute(query);
355 }
356
357 // read DataModelobjects
358 void SQLite::ObjectsOfType(const ObjectType objectType, vector<string>& objects)
359 {
360 string query = "SELECT object FROM objects WHERE objecttype = " + to_string(objectType) + " ORDER BY objectid;";
361 Execute(query, CallbackStringVector, &objects);
362 }
363
364 // save DataModelrelation
365 void SQLite::SaveRelation(const DataModel::Relation::RelationType type, const ObjectID objectID1, const ObjectType objectType2, const ObjectID objectID2, const Priority priority, const std::string& relation)
366 {
367 string query = "INSERT OR REPLACE INTO relations (type, objectid1, objecttype2, objectid2, priority, relation) VALUES ("
368 + to_string(type) + ", "
369 + to_string(objectID1) + ", "
370 + to_string(objectType2) + ", "
371 + to_string(objectID2) + ", "
372 + to_string(priority) + ", '"
373 + EscapeString(relation) + "');";
374 Execute(query);
375 }
376
377 // delete DataModelrelaton
378 void SQLite::DeleteRelationsFrom(const DataModel::Relation::RelationType type, const ObjectID objectID)
379 {
380 string query = "DELETE FROM relations WHERE type = " + to_string(type)
381 + " AND objectid1 = " + to_string(objectID) + ";";
382 Execute(query);
383 }
384
385 // delete DataModelrelaton
386 void SQLite::DeleteRelationsTo(const ObjectType objectType, const ObjectID objectID)
387 {
388 string query = "DELETE FROM relations WHERE objecttype2 = " + to_string(objectType)
389 + " AND objectid2 = " + to_string(objectID) + ";";
390 Execute(query);
391 }
392
393 // read DataModelrelations
394 void SQLite::RelationsFrom(const DataModel::Relation::RelationType type, const ObjectID objectID, vector<string>& relations)
395 {
396 string query = "SELECT relation FROM relations WHERE type = " + to_string(type)
397 + " AND objectid1 = " + to_string(objectID) + " ORDER BY priority ASC;";
398 Execute(query, CallbackStringVector, &relations);
399 }
400
401 // read DataModelrelations
402 void SQLite::RelationsTo(const ObjectType objectType, const ObjectID objectID, vector<string>& relations)
403 {
404 string query = "SELECT relation FROM relations WHERE objecttype2 = " + to_string(objectType)
405 + " AND objectid2 = " + to_string(objectID) + ";";
406 Execute(query, CallbackStringVector, &relations);
407 }
408
409 void SQLite::SaveSetting(const string& key, const string& value)
410 {
411 Execute("INSERT OR REPLACE INTO settings (key, value) values ('" + EscapeString(key) + "', '" + EscapeString(value) + "');");
412 }
413
414 string SQLite::GetSetting(const string& key)
415 {
416 vector<string> values;
417 string query = "SELECT value FROM settings WHERE key = '" + EscapeString(key) + "';";
418 bool ret = Execute(query, CallbackStringVector, &values);
419 if (ret == false || values.size() == 0)
420 {
421 return "";
422 }
423
424 return values[0];
425 }
426
427 // callback read all DataModel objects/relations
428 int SQLite::CallbackStringVector(void* v, int argc, char **argv, __attribute__((unused)) char **colName)
429 {
430 vector<string>* objects = static_cast<vector<string>*>(v);
431 if (argc != 1)
432 {
433 return 0;
434 }
435 objects->push_back(argv[0]);
436 return 0;
437 }
438
439 void SQLite::StartTransaction()
440 {
441 Execute("BEGIN TRANSACTION;");
442 }
443
444 void SQLite::CommitTransaction()
445 {
446 Execute("COMMIT;");
447 }
448
449 bool SQLite::Execute(const char* query, sqlite3_callback callback = nullptr, void* result = nullptr)
450 {
451 if (db == nullptr)
452 {
453 return false;
454 }
455
456 char* dbError = nullptr;
457 int rc = sqlite3_exec(db, query, callback, result, &dbError);
458 if (rc == SQLITE_OK)
459 {
460 int affected = sqlite3_changes(db);
461
462 if (affected)
463 {
464 logger->Debug(Languages::TextQueryAffected, query, affected);
465 }
466 else
467 {
468 logger->Debug(Languages::TextQuery, query);
469 }
470 return true;
471 }
472
473 logger->Error(Languages::TextSQLiteErrorQuery, dbError, query);
474 sqlite3_free(dbError);
475 return false;
476 }
477
478 string SQLite::EscapeString(const string& input)
479 {
480 string output;
481 for (size_t i = 0; i < input.size(); ++i)
482 {
483 if (input[i] == '\'')
484 {
485 output += "'";
486 }
487 output += input[i];
488 }
489 return output;
490 }
491 } // namespace Storage