Debian Codegraph @

Storage/Sqlite.cpp

raw symbols ◀ ▶ SCIP
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)
63 {
64 return;
65 }
66
67 // create hardware table if needed
68 if (tablenames["hardware"] == false)
69 {
70 bool ret = CreateTableHardware();
•71 if (!ret)
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)
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 {
95 ret = CreateTableRelations(tableNameRelations);
96 }
•97 if (!ret)
98 {
99 return;
100 }
101
102 // create settings table if needed
103 if (tablenames["settings"] == false)
104 {
105 bool ret = CreateTableSettings();
•106 if (!ret)
107 {
108 return;
109 }
110 }
111 }
112
113
114 SQLite::~SQLite()
115 {
•116 if (!db)
117 {
118 return;
119 }
120
121 logger->Info(Languages::TextClosingSQLite);
122 sqlite3_close(db);
123 db = nullptr;
124
125 if (keepBackups == 0)
126 {
127 return;
128 }
129 Utils::Utils::CopyFile(logger, filename, filename + "." + std::to_string(std::time(nullptr)));
130 }
131
132 int SQLite::CallbackListTables(void* v, int argc, char **argv, __attribute__((unused)) char **colName)
133 {
134 map<string, bool>* tablenames = static_cast<map<string, bool>*>(v);
135 if (argc != 1)
136 {
137 return 0;
138 }
139 (*tablenames)[argv[0]] = true;
140 return 0;
141 }
142
143 bool SQLite::DropTable(const string table)
144 {
145 logger->Info(Languages::TextDroppingTable, table);
146 string query = "DROP TABLE " + table + ";";
147 return Execute(query);
148 }
149
150 bool SQLite::CreateTableHardware()
151 {
152 logger->Info(Languages::TextCreatingTable, "hardware");
153 const string query = "CREATE TABLE hardware ("
154 "controlid UNSIGNED TINYINT,"
155 " hardwaretype UNSIGNED TINYINT,"
156 " name VARCHAR(50),"
157 " arg1 VARCHAR(255),"
158 " arg2 VARCHAR(255),"
159 " arg3 VARCHAR(255),"
160 " arg4 VARCHAR(255),"
161 " arg5 VARCHAR(255),"
162 "PRIMARY KEY (controlid));";
163 return Execute(query);
164 }
165
166 bool SQLite::CreateTableObjects()
167 {
168 logger->Info(Languages::TextCreatingTable, "objects");
169 const char* query = "CREATE TABLE objects ("
170 "objecttype UNSIGNED TINYINT, "
171 "objectid UNSIGNED SHORTINT, "
172 "name VARCHAR(50), "
173 "object SHORTTEXT,"
174 "PRIMARY KEY (objecttype, objectid));";
175 return Execute(query);
176 }
177
178 bool SQLite::CreateTableRelations(const string& name)
179 {
180 logger->Info(Languages::TextCreatingTable, name);
181 const string query = "CREATE TABLE " + name + " ("
182 "type UNSIGNED TINYINT, "
183 "objectid1 UNSIGNED SHORTINT, "
184 "objecttype2 UNSIGNED TINYINT, "
185 "objectid2 UNSIGNED SHORTINT, "
186 "priority UNSIGNED TINYINT, "
187 "relation SHORTTEXT,"
188 "PRIMARY KEY (type, objectid1, objecttype2, objectid2, priority));";
189 return Execute(query);
190 }
191
192 bool SQLite::CreateTableSettings()
193 {
194 logger->Info(Languages::TextCreatingTable, "settings");
195 const char* query = "CREATE TABLE settings ("
196 "key TINYTEXT, "
197 "value SHORTTEXT,"
198 "PRIMARY KEY (key));";
199 return Execute(query);
200 }
201
202 struct TableInfo
203 {
204 public:
205 int cid;
206 string name;
207 string type;
208 bool notNull;
209 bool defaultNull;
210 string defaultValue;
211 int primaryKey;
212 };
213
214 bool SQLite::CheckTableRelations()
215 {
216 vector<TableInfo> tableInfos;
217 string query = "PRAGMA table_info('relations');";
218 bool ret = Execute(query, CallbackTableInfo, &tableInfos);
•219 if (!ret)
220 {
221 return false;
222 }
223
224 string name = "relations";
225 if (tableInfos.size() != 6)
226 {
227 return DropTable(name) && CreateTableRelations(name);
228 }
229
230 if (tableInfos[0].name.compare("type") != 0)
231 {
232 return UpdateTableRelations1();
233 }
234
235 // FIXME: simple check, extend with check if each object really exists
236 query = "DELETE FROM relations WHERE objectid1 like 0;";
237 ret = Execute(query);
•238 if (!ret)
239 {
240 return false;
241 }
242
243 logger->Info(Languages::TextIsUpToDate, name);
244 return true;
245 }
246
247 bool SQLite::UpdateTableRelations1()
248 {
249 const string tableName = "relations";
250 const string tempTableName = "relations_temp";
251 bool ret = CreateTableRelations(tempTableName);
•252 if (!ret)
253 {
254 return false;
255 }
256 logger->Info(Languages::TextCopyingFromTo, tableName, tempTableName);
257 const string query = "INSERT INTO " + tempTableName + " SELECT objecttype1 * 8, objectid1, objecttype2, objectid2, priority, relation FROM " + tableName + ";";
258 ret = Execute(query);
•259 if (!ret)
260 {
261 return false;
262 }
263 ret = DropTable(tableName);
•264 if (!ret)
265 {
266 return false;
267 }
268 logger->Info(Languages::TextRenamingFromTo, tempTableName, tableName);
269 return RenameTable(tempTableName, tableName);
270 }
271
272 bool SQLite::RenameTable(const string& oldName, const string& newName)
273 {
274 const string query = "ALTER TABLE " + oldName + " RENAME TO " + newName + ";";
275 return Execute(query);
276 }
277
278 int SQLite::CallbackTableInfo(void* v, int argc, char **argv, __attribute__((unused)) char **colName)
279 {
280 vector<TableInfo>* tableInfos = static_cast<vector<TableInfo>*>(v);
281 if (argc != 6)
282 {
283 return 0;
284 }
285 TableInfo tableInfo;
286 tableInfo.cid = Utils::Integer::StringToInteger(argv[0]);
287 tableInfo.name = argv[1];
288 tableInfo.type = argv[2];
289 tableInfo.notNull = Utils::Integer::StringToInteger(argv[3]) > 0;
290 tableInfo.defaultNull = argv[4] == nullptr;
291 tableInfo.defaultValue = argv[4] != nullptr ? argv[4] : "";
292 tableInfo.primaryKey = Utils::Integer::StringToInteger(argv[5]);
293 tableInfos->push_back(tableInfo);
294 return 0;
295 }
296
297 void SQLite::SaveHardwareParams(const Hardware::HardwareParams& hardwareParams)
298 {
299 string query = "INSERT OR REPLACE INTO hardware VALUES ("
300 + to_string(hardwareParams.GetControlID()) + ", "
301 + to_string(hardwareParams.GetHardwareType()) + ", '"
302 + EscapeString(hardwareParams.GetName()) + "', '"
303 + EscapeString(hardwareParams.GetArg1()) + "', '"
304 + EscapeString(hardwareParams.GetArg2()) + "', '"
305 + EscapeString(hardwareParams.GetArg3()) + "', '"
306 + EscapeString(hardwareParams.GetArg4()) + "', '"
307 + EscapeString(hardwareParams.GetArg5()) + "');";
308 Execute(query);
309 }
310
311 void SQLite::AllHardwareParams(std::map<ControlID, Hardware::HardwareParams*>& hardwareParams)
312 {
313 const char* query = "SELECT controlid, hardwaretype, name, arg1, arg2, arg3, arg4, arg5 FROM hardware ORDER BY controlid;";
314 Execute(query, CallbackAllHardwareParams, &hardwareParams);
315 }
316
317 // callback read hardwareparams
318 int SQLite::CallbackAllHardwareParams(void* v, int argc, char **argv, __attribute__((unused)) char **colName)
319 {
320 map<ControlID,HardwareParams*>* hardwareParams = static_cast<map<ControlID,HardwareParams*>*>(v);
321 if (argc != 8)
322 {
323 return 0;
324 }
325 ControlID controlID = Utils::Integer::StringToInteger(argv[0]);
326
327 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]);
328 (*hardwareParams)[controlID] = params;
329 return 0;
330 }
331
332 // delete control
333 void SQLite::DeleteHardwareParams(const ControlID controlID)
334 {
335 string query = "DELETE FROM hardware WHERE controlid = " + to_string(controlID) + ";";
336 Execute(query);
337 }
338
339 // save DataModelobject
340 void SQLite::SaveObject(const ObjectType objectType, const ObjectID objectID, const std::string& name, const std::string& object)
341 {
342 string query = "INSERT OR REPLACE INTO objects (objecttype, objectid, name, object) VALUES ("
343 + to_string(objectType) + ", "
344 + to_string(objectID) + ", '"
345 + EscapeString(name) + "', '"
346 + EscapeString(object) + "');";
347 Execute(query);
348 }
349
350 // delete DataModelobject
351 void SQLite::DeleteObject(const ObjectType objectType, const ObjectID objectID)
352 {
353 string query = "DELETE FROM objects WHERE objecttype = " + to_string(objectType)
354 + " AND objectid = " + to_string(objectID) + ";";
355 Execute(query);
356 }
357
358 // read DataModelobjects
359 void SQLite::ObjectsOfType(const ObjectType objectType, vector<string>& objects)
360 {
361 string query = "SELECT object FROM objects WHERE objecttype = " + to_string(objectType) + " ORDER BY objectid;";
362 Execute(query, CallbackStringVector, &objects);
363 }
364
365 // save DataModelrelation
366 void SQLite::SaveRelation(const DataModel::Relation::RelationType type, const ObjectID objectID1, const ObjectType objectType2, const ObjectID objectID2, const Priority priority, const std::string& relation)
367 {
368 string query = "INSERT OR REPLACE INTO relations (type, objectid1, objecttype2, objectid2, priority, relation) VALUES ("
369 + to_string(type) + ", "
370 + to_string(objectID1) + ", "
371 + to_string(objectType2) + ", "
372 + to_string(objectID2) + ", "
373 + to_string(priority) + ", '"
374 + EscapeString(relation) + "');";
375 Execute(query);
376 }
377
378 // delete DataModelrelaton
379 void SQLite::DeleteRelationsFrom(const DataModel::Relation::RelationType type, const ObjectID objectID)
380 {
381 string query = "DELETE FROM relations WHERE type = " + to_string(type)
382 + " AND objectid1 = " + to_string(objectID) + ";";
383 Execute(query);
384 }
385
386 // delete DataModelrelaton
387 void SQLite::DeleteRelationsTo(const ObjectType objectType, const ObjectID objectID)
388 {
389 string query = "DELETE FROM relations WHERE objecttype2 = " + to_string(objectType)
390 + " AND objectid2 = " + to_string(objectID) + ";";
391 Execute(query);
392 }
393
394 // read DataModelrelations
395 void SQLite::RelationsFrom(const DataModel::Relation::RelationType type, const ObjectID objectID, vector<string>& relations)
396 {
397 string query = "SELECT relation FROM relations WHERE type = " + to_string(type)
398 + " AND objectid1 = " + to_string(objectID) + " ORDER BY priority ASC;";
399 Execute(query, CallbackStringVector, &relations);
400 }
401
402 // read DataModelrelations
403 void SQLite::RelationsTo(const ObjectType objectType, const ObjectID objectID, vector<string>& relations)
404 {
405 string query = "SELECT relation FROM relations WHERE objecttype2 = " + to_string(objectType)
406 + " AND objectid2 = " + to_string(objectID) + ";";
407 Execute(query, CallbackStringVector, &relations);
408 }
409
410 void SQLite::SaveSetting(const string& key, const string& value)
411 {
412 Execute("INSERT OR REPLACE INTO settings (key, value) values ('" + EscapeString(key) + "', '" + EscapeString(value) + "');");
413 }
414
415 string SQLite::GetSetting(const string& key)
416 {
417 vector<string> values;
418 string query = "SELECT value FROM settings WHERE key = '" + EscapeString(key) + "';";
419 bool ret = Execute(query, CallbackStringVector, &values);
420 if (ret == false || values.size() == 0)
421 {
422 return "";
423 }
424
425 return values[0];
426 }
427
428 // callback read all DataModel objects/relations
429 int SQLite::CallbackStringVector(void* v, int argc, char **argv, __attribute__((unused)) char **colName)
430 {
431 vector<string>* objects = static_cast<vector<string>*>(v);
432 if (argc != 1)
433 {
434 return 0;
435 }
436 objects->push_back(argv[0]);
437 return 0;
438 }
439
440 void SQLite::StartTransaction()
441 {
442 Execute("BEGIN TRANSACTION;");
443 }
444
445 void SQLite::CommitTransaction()
446 {
447 Execute("COMMIT;");
448 }
449
450 bool SQLite::Execute(const char* query, sqlite3_callback callback = nullptr, void* result = nullptr)
451 {
•452 if (!db)
453 {
454 return false;
455 }
456
457 char* dbError = nullptr;
458 int rc = sqlite3_exec(db, query, callback, result, &dbError);
459 if (rc == SQLITE_OK)
460 {
461 int affected = sqlite3_changes(db);
462
463 if (affected)
464 {
465 logger->Debug(Languages::TextQueryAffected, query, affected);
466 }
467 else
468 {
469 logger->Debug(Languages::TextQuery, query);
470 }
471 return true;
472 }
473
474 logger->Error(Languages::TextSQLiteErrorQuery, dbError, query);
475 sqlite3_free(dbError);
476 return false;
477 }
478
479 string SQLite::EscapeString(const string& input)
480 {
481 string output;
482 for (size_t i = 0; i < input.size(); ++i)
483 {
484 if (input[i] == '\'')
485 {
486 output += "'";
487 }
488 output += input[i];
489 }
490 return output;
491 }
492 } // namespace Storage