File: Sqlite.cpp

package info (click to toggle)
railcontrol 24%2Bdfsg1-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,540 kB
  • sloc: cpp: 40,823; javascript: 2,509; makefile: 110; php: 97; sh: 60
file content (491 lines) | stat: -rw-r--r-- 13,541 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/*
RailControl - Model Railway Control Software

Copyright (c) 2017-2025 by Teddy / Dominik Mahrer - www.railcontrol.org

RailControl is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3, or (at your option) any
later version.

RailControl is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with RailControl; see the file LICENCE. If not see
<http://www.gnu.org/licenses/>.
*/

#include <ctime>
#include <map>
#include <string>

#include "Languages.h"
#include "Storage/Sqlite.h"
#include "Utils/Integer.h"

using DataModel::Accessory;
using DataModel::Track;
using DataModel::Feedback;
using DataModel::Loco;
using DataModel::Switch;
using Hardware::HardwareParams;
using std::map;
using std::string;
using std::vector;
using std::to_string;

namespace Storage
{
	SQLite::SQLite(const StorageParams* params)
	:	filename(params->filename),
	 	logger(Logger::Logger::GetLogger("SQLite")),
	 	keepBackups(params->keepBackups)
	{
		Utils::Utils::RemoveOldBackupFiles (logger, filename, keepBackups);
		logger->Info(Languages::TextOpeningSQLite, filename);
		int rc = sqlite3_open(filename.c_str(), &db);
		if (rc)
		{
			logger->Error(Languages::TextUnableToOpenSQLite, sqlite3_errmsg(db));
			sqlite3_close(db);
			db = nullptr;
			return;
		}

		// check if needed tables exist
		map<string, bool> tablenames;
		const char* query = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;";
		bool ret = Execute(query, CallbackListTables, &tablenames);
		if (ret == false)
		{
			return;
		}

		// create hardware table if needed
		if (tablenames["hardware"] == false)
		{
			bool ret = CreateTableHardware();
			if (ret == false)
			{
				return;
			}
		}

		// create objects table if needed
		if (tablenames["objects"] == false)
		{
			bool ret = CreateTableObjects();
			if (ret == false)
			{
				return;
			}
		}

		// create relations table if needed
		string tableNameRelations = "relations";
		if (tablenames[tableNameRelations] == true)
		{
			ret = CheckTableRelations();
		}
		else {
			ret = CreateTableRelations(tableNameRelations);
		}
		if (ret == false)
		{
			return;
		}

		// create settings table if needed
		if (tablenames["settings"] == false)
		{
			bool ret = CreateTableSettings();
			if (ret == false)
			{
				return;
			}
		}
	}


	SQLite::~SQLite()
	{
		if (db == nullptr)
		{
			return;
		}

		logger->Info(Languages::TextClosingSQLite);
		sqlite3_close(db);
		db = nullptr;

		if (keepBackups == 0)
		{
			return;
		}
		Utils::Utils::CopyFile(logger, filename, filename + "." + std::to_string(std::time(nullptr)));
	}

	int SQLite::CallbackListTables(void* v, int argc, char **argv, __attribute__((unused)) char **colName)
	{
		map<string, bool>* tablenames = static_cast<map<string, bool>*>(v);
		if (argc != 1)
		{
			return 0;
		}
		(*tablenames)[argv[0]] = true;
		return 0;
	}

	bool SQLite::DropTable(const string table)
	{
		logger->Info(Languages::TextDroppingTable, table);
		string query = "DROP TABLE " + table + ";";
		return Execute(query);
	}

	bool SQLite::CreateTableHardware()
	{
		logger->Info(Languages::TextCreatingTable, "hardware");
		const string query = "CREATE TABLE hardware ("
			"controlid UNSIGNED TINYINT,"
			" hardwaretype UNSIGNED TINYINT,"
			" name VARCHAR(50),"
			" arg1 VARCHAR(255),"
			" arg2 VARCHAR(255),"
			" arg3 VARCHAR(255),"
			" arg4 VARCHAR(255),"
			" arg5 VARCHAR(255),"
			"PRIMARY KEY (controlid));";
		return Execute(query);
	}

	bool SQLite::CreateTableObjects()
	{
		logger->Info(Languages::TextCreatingTable, "objects");
		const char* query = "CREATE TABLE objects ("
			"objecttype UNSIGNED TINYINT, "
			"objectid UNSIGNED SHORTINT, "
			"name VARCHAR(50), "
			"object SHORTTEXT,"
			"PRIMARY KEY (objecttype, objectid));";
		return Execute(query);
	}

	bool SQLite::CreateTableRelations(const string& name)
	{
		logger->Info(Languages::TextCreatingTable, name);
		const string query = "CREATE TABLE " + name + " ("
			"type UNSIGNED TINYINT, "
			"objectid1 UNSIGNED SHORTINT, "
			"objecttype2 UNSIGNED TINYINT, "
			"objectid2 UNSIGNED SHORTINT, "
			"priority UNSIGNED TINYINT, "
			"relation SHORTTEXT,"
			"PRIMARY KEY (type, objectid1, objecttype2, objectid2, priority));";
		return Execute(query);
	}

	bool SQLite::CreateTableSettings()
	{
		logger->Info(Languages::TextCreatingTable, "settings");
		const char* query =  "CREATE TABLE settings ("
			"key TINYTEXT, "
			"value SHORTTEXT,"
			"PRIMARY KEY (key));";
		return Execute(query);
	}

	struct TableInfo
	{
		public:
			int cid;
			string name;
			string type;
			bool notNull;
			bool defaultNull;
			string defaultValue;
			int primaryKey;
	};

	bool SQLite::CheckTableRelations()
	{
		vector<TableInfo> tableInfos;
		string query = "PRAGMA table_info('relations');";
		bool ret = Execute(query, CallbackTableInfo, &tableInfos);
		if (ret == false)
		{
			return false;
		}

		string name = "relations";
		if (tableInfos.size() != 6)
		{
			return DropTable(name) && CreateTableRelations(name);
		}

		if (tableInfos[0].name.compare("type") != 0)
		{
			return UpdateTableRelations1();
		}

		// FIXME: simple check, extend with check if each object really exists
		query = "DELETE FROM relations WHERE objectid1 like 0;";
		ret = Execute(query);
		if (ret == false)
		{
			return false;
		}

		logger->Info(Languages::TextIsUpToDate, name);
		return true;
	}

	bool SQLite::UpdateTableRelations1()
	{
		const string tableName = "relations";
		const string tempTableName = "relations_temp";
		bool ret = CreateTableRelations(tempTableName);
		if (ret == false)
		{
			return false;
		}
		logger->Info(Languages::TextCopyingFromTo, tableName, tempTableName);
		const string query = "INSERT INTO " + tempTableName + " SELECT objecttype1 * 8, objectid1, objecttype2, objectid2, priority, relation FROM " + tableName + ";";
		ret = Execute(query);
		if (ret == false)
		{
			return false;
		}
		ret = DropTable(tableName);
		if (ret == false)
		{
			return false;
		}
		logger->Info(Languages::TextRenamingFromTo, tempTableName, tableName);
		return RenameTable(tempTableName, tableName);
	}

	bool SQLite::RenameTable(const string& oldName, const string& newName)
	{
		const string query = "ALTER TABLE " + oldName + " RENAME TO " + newName + ";";
		return Execute(query);
	}

	int SQLite::CallbackTableInfo(void* v, int argc, char **argv, __attribute__((unused)) char **colName)
	{
		vector<TableInfo>* tableInfos = static_cast<vector<TableInfo>*>(v);
		if (argc != 6)
		{
			return 0;
		}
		TableInfo tableInfo;
		tableInfo.cid = Utils::Integer::StringToInteger(argv[0]);
		tableInfo.name = argv[1];
		tableInfo.type = argv[2];
		tableInfo.notNull = Utils::Integer::StringToInteger(argv[3]) > 0;
		tableInfo.defaultNull = argv[4] == nullptr;
		tableInfo.defaultValue = argv[4] != nullptr ? argv[4] : "";
		tableInfo.primaryKey = Utils::Integer::StringToInteger(argv[5]);
		tableInfos->push_back(tableInfo);
		return 0;
	}

	void SQLite::SaveHardwareParams(const Hardware::HardwareParams& hardwareParams)
	{
		string query = "INSERT OR REPLACE INTO hardware VALUES ("
			+ to_string(hardwareParams.GetControlID()) + ", "
			+ to_string(hardwareParams.GetHardwareType()) + ", '"
			+ EscapeString(hardwareParams.GetName()) + "', '"
			+ EscapeString(hardwareParams.GetArg1()) + "', '"
			+ EscapeString(hardwareParams.GetArg2()) + "', '"
			+ EscapeString(hardwareParams.GetArg3()) + "', '"
			+ EscapeString(hardwareParams.GetArg4()) + "', '"
			+ EscapeString(hardwareParams.GetArg5()) + "');";
		Execute(query);
	}

	void SQLite::AllHardwareParams(std::map<ControlID, Hardware::HardwareParams*>& hardwareParams)
	{
		const char* query = "SELECT controlid, hardwaretype, name, arg1, arg2, arg3, arg4, arg5 FROM hardware ORDER BY controlid;";
		Execute(query, CallbackAllHardwareParams, &hardwareParams);
	}

	// callback read hardwareparams
	int SQLite::CallbackAllHardwareParams(void* v, int argc, char **argv, __attribute__((unused)) char **colName)
	{
		map<ControlID,HardwareParams*>* hardwareParams = static_cast<map<ControlID,HardwareParams*>*>(v);
		if (argc != 8)
		{
			return 0;
		}
		ControlID controlID = Utils::Integer::StringToInteger(argv[0]);

		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]);
		(*hardwareParams)[controlID] = params;
		return 0;
	}

	// delete control
	void SQLite::DeleteHardwareParams(const ControlID controlID)
	{
		string query = "DELETE FROM hardware WHERE controlid = " + to_string(controlID) + ";";
		Execute(query);
	}

	// save DataModelobject
	void SQLite::SaveObject(const ObjectType objectType, const ObjectID objectID, const std::string& name, const std::string& object)
	{
		string query = "INSERT OR REPLACE INTO objects (objecttype, objectid, name, object) VALUES ("
			+ to_string(objectType) + ", "
			+ to_string(objectID) + ", '"
			+ EscapeString(name) + "', '"
			+ EscapeString(object) + "');";
		Execute(query);
	}

	// delete DataModelobject
	void SQLite::DeleteObject(const ObjectType objectType, const ObjectID objectID)
	{
		string query = "DELETE FROM objects WHERE objecttype = " + to_string(objectType)
			+ " AND objectid = " + to_string(objectID) + ";";
		Execute(query);
	}

	// read DataModelobjects
	void SQLite::ObjectsOfType(const ObjectType objectType, vector<string>& objects)
	{
		string query = "SELECT object FROM objects WHERE objecttype = " + to_string(objectType) + " ORDER BY objectid;";
		Execute(query, CallbackStringVector, &objects);
	}

	// save DataModelrelation
	void SQLite::SaveRelation(const DataModel::Relation::RelationType type, const ObjectID objectID1, const ObjectType objectType2, const ObjectID objectID2, const Priority priority, const std::string& relation)
	{
		string query = "INSERT OR REPLACE INTO relations (type, objectid1, objecttype2, objectid2, priority, relation) VALUES ("
			+ to_string(type) + ", "
			+ to_string(objectID1) + ", "
			+ to_string(objectType2) + ", "
			+ to_string(objectID2) + ", "
			+ to_string(priority) + ", '"
			+ EscapeString(relation) + "');";
		Execute(query);
	}

	// delete DataModelrelaton
	void SQLite::DeleteRelationsFrom(const DataModel::Relation::RelationType type, const ObjectID objectID)
	{
		string query = "DELETE FROM relations WHERE type = " + to_string(type)
			+ " AND objectid1 = " + to_string(objectID) + ";";
		Execute(query);
	}

	// delete DataModelrelaton
	void SQLite::DeleteRelationsTo(const ObjectType objectType, const ObjectID objectID)
	{
		string query = "DELETE FROM relations WHERE objecttype2 = " + to_string(objectType)
			+ " AND objectid2 = " + to_string(objectID) + ";";
		Execute(query);
	}

	// read DataModelrelations
	void SQLite::RelationsFrom(const DataModel::Relation::RelationType type, const ObjectID objectID, vector<string>& relations)
	{
		string query = "SELECT relation FROM relations WHERE type = " + to_string(type)
			+ " AND objectid1 = " + to_string(objectID) + " ORDER BY priority ASC;";
		Execute(query, CallbackStringVector, &relations);
	}

	// read DataModelrelations
	void SQLite::RelationsTo(const ObjectType objectType, const ObjectID objectID, vector<string>& relations)
	{
		string query = "SELECT relation FROM relations WHERE objecttype2 = " + to_string(objectType)
			+ " AND objectid2 = " + to_string(objectID) + ";";
		Execute(query, CallbackStringVector, &relations);
	}

	void SQLite::SaveSetting(const string& key, const string& value)
	{
		Execute("INSERT OR REPLACE INTO settings (key, value) values ('" + EscapeString(key) + "', '" + EscapeString(value) + "');");
	}

	string SQLite::GetSetting(const string& key)
	{
		vector<string> values;
		string query = "SELECT value FROM settings WHERE key = '" + EscapeString(key) + "';";
		bool ret = Execute(query, CallbackStringVector, &values);
		if (ret == false || values.size() == 0)
		{
			return "";
		}

		return values[0];
	}

	// callback read all DataModel objects/relations
	int SQLite::CallbackStringVector(void* v, int argc, char **argv, __attribute__((unused)) char **colName)
	{
		vector<string>* objects = static_cast<vector<string>*>(v);
		if (argc != 1)
		{
			return 0;
		}
		objects->push_back(argv[0]);
		return 0;
	}

	void SQLite::StartTransaction()
	{
		Execute("BEGIN TRANSACTION;");
	}

	void SQLite::CommitTransaction()
	{
		Execute("COMMIT;");
	}

	bool SQLite::Execute(const char* query, sqlite3_callback callback = nullptr, void* result = nullptr)
	{
		if (db == nullptr)
		{
			return false;
		}

		char* dbError = nullptr;
		int rc = sqlite3_exec(db, query, callback, result, &dbError);
		if (rc == SQLITE_OK)
		{
			int affected = sqlite3_changes(db);

			if (affected)
			{
				logger->Debug(Languages::TextQueryAffected, query, affected);
			}
			else
			{
				logger->Debug(Languages::TextQuery, query);
			}
			return true;
		}

		logger->Error(Languages::TextSQLiteErrorQuery, dbError, query);
		sqlite3_free(dbError);
		return false;
	}

	string SQLite::EscapeString(const string& input)
	{
		string output;
		for (size_t i = 0; i < input.size(); ++i)
		{
			if (input[i] == '\'')
			{
				output += "'";
			}
			output += input[i];
		}
		return output;
	}
} // namespace Storage