-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathGAStore.cpp
More file actions
416 lines (356 loc) · 15.1 KB
/
GAStore.cpp
File metadata and controls
416 lines (356 loc) · 15.1 KB
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
//
// GA-SDK-CPP
// Copyright 2018 GameAnalytics C++ SDK. All rights reserved.
//
#include "GAStore.h"
#include "GADevice.h"
#include "GAThreading.h"
#include "GALogger.h"
#include "GAUtilities.h"
#include <fstream>
#include <string.h>
#include "GAState.h"
namespace gameanalytics
{
namespace store
{
constexpr int MaxDbSizeBytes = 6291456;
constexpr int MaxDbSizeBytesBeforeTrim = 5242880;
GAStore::GAStore()
{
}
GAStore::~GAStore()
{
}
GAStore& GAStore::getInstance()
{
return state::GAState::getInstance()._gaStore;
}
bool GAStore::executeQuerySync(std::string const& sql)
{
json d;
executeQuerySync(sql, d);
return !d.is_null();
}
void GAStore::executeQuerySync(std::string const& sql, json& out)
{
executeQuerySync(sql, {}, 0, out);
}
void GAStore::executeQuerySync(std::string const& sql, StringVector const& parameters)
{
json d;
executeQuerySync(sql, parameters, false, d);
}
void GAStore::executeQuerySync(std::string const& sql, StringVector const& parameters, json& out)
{
executeQuerySync(sql, parameters, false, out);
}
void GAStore::executeQuerySync(std::string const& sql, StringVector const& parameters, bool useTransaction)
{
json d;
executeQuerySync(sql, parameters, useTransaction, d);
}
void GAStore::executeQuerySync(std::string const& sql, StringVector const& parameters, bool useTransaction, json& out)
{
try
{
// Force transaction if it is an update, insert or delete.
if (utilities::GAUtilities::stringMatch(utilities::toUpperCase(sql), "^(UPDATE|INSERT|DELETE)"))
{
useTransaction = true;
}
// Get database connection from singelton getInstance
sqlite3 *sqlDatabasePtr = getInstance().getDatabase();
if (useTransaction)
{
if (sqlite3_exec(sqlDatabasePtr, "BEGIN;", 0, 0, 0) != SQLITE_OK)
{
logging::GALogger::e("SQLITE3 BEGIN ERROR: %s", sqlite3_errmsg(sqlDatabasePtr));
return;
}
}
out = json::array();
// Create statement
sqlite3_stmt *statement = nullptr;
// Prepare statement
if (sqlite3_prepare_v2(sqlDatabasePtr, sql.c_str(), -1, &statement, nullptr) == SQLITE_OK)
{
// Bind parameters
if (!parameters.empty())
{
for (size_t index = 0; index < parameters.size(); index++)
{
sqlite3_bind_text(statement, static_cast<int>(index + 1), parameters[index].c_str(), -1, 0);
}
}
// get columns count
int columnCount = sqlite3_column_count(statement);
// Loop through results
while (sqlite3_step(statement) == SQLITE_ROW)
{
json row;
for (int i = 0; i < columnCount; i++)
{
const char *column = sqlite3_column_name(statement, i);
const char *value = reinterpret_cast<const char*>(sqlite3_column_text(statement, i));
if (!column || !value)
{
continue;
}
switch (sqlite3_column_type(statement, i))
{
case SQLITE_INTEGER:
{
try
{
int64_t valInt = std::stoll(value);
row[column] = valInt;
}
catch(std::exception& e)
{
logging::GALogger::w("Failed to parse int: %s", e.what());
}
break;
}
case SQLITE_FLOAT:
{
try
{
double valFloat = std::stod(value);
row[column] = valFloat;
}
catch(std::exception& e)
{
logging::GALogger::w("Failed to parse float: %s", e.what());
}
break;
}
default:
{
row[column] = value;
}
}
}
out.push_back(std::move(row));
}
}
else
{
// TODO(nikolaj): Should we do a db validation to see if the db is corrupt here?
logging::GALogger::e("SQLITE3 PREPARE ERROR: %s", sqlite3_errmsg(sqlDatabasePtr));
out = {};
return;
}
// Destroy statement
if (sqlite3_finalize(statement) == SQLITE_OK)
{
if (useTransaction)
{
if (sqlite3_exec(sqlDatabasePtr, "COMMIT", 0, 0, 0) != SQLITE_OK)
{
logging::GALogger::e("SQLITE3 COMMIT ERROR: %s", sqlite3_errmsg(sqlDatabasePtr));
out = {};
return;
}
}
}
else
{
logging::GALogger::d("SQLITE3 FINALIZE ERROR: %s", sqlite3_errmsg(sqlDatabasePtr));
if (useTransaction)
{
if (sqlite3_exec(sqlDatabasePtr, "ROLLBACK", 0, 0, 0) != SQLITE_OK)
{
logging::GALogger::e("SQLITE3 ROLLBACK ERROR: %s", sqlite3_errmsg(sqlDatabasePtr));
}
out = {};
}
return;
}
}
catch(std::exception& e)
{
logging::GALogger::e("Exception thrown: %s", e.what());
out = {};
}
}
sqlite3* GAStore::getDatabase()
{
return sqlDatabase;
}
bool GAStore::initDatabaseLocation()
{
constexpr const char* DATABASE_NAME = "ga.sqlite3";
std::filesystem::path p = device::GADevice::getWritablePath();
p /= state::GAState::getGameKey();
dbPath = (p / DATABASE_NAME).string();
if(!std::filesystem::exists(p))
{
if(!std::filesystem::create_directory(p))
return false;
}
return true;
}
bool GAStore::ensureDatabase(bool dropDatabase, std::string const& key)
{
getInstance().initDatabaseLocation();
// Open database
if (sqlite3_open(getInstance().dbPath.c_str(), &getInstance().sqlDatabase) != SQLITE_OK)
{
getInstance().dbReady = false;
logging::GALogger::w("Could not open database: %s", getInstance().dbPath.c_str());
return false;
}
else
{
getInstance().dbReady = true;
logging::GALogger::i("Database opened: %s", getInstance().dbPath.c_str());
}
if (dropDatabase)
{
logging::GALogger::d("Drop tables");
GAStore::executeQuerySync("DROP TABLE ga_events");
GAStore::executeQuerySync("DROP TABLE ga_state");
GAStore::executeQuerySync("DROP TABLE ga_session");
GAStore::executeQuerySync("DROP TABLE ga_progression");
GAStore::executeQuerySync("VACUUM");
}
// Create statements
constexpr const char* sql_ga_events = "CREATE TABLE IF NOT EXISTS ga_events(status CHAR(50) NOT NULL, category CHAR(50) NOT NULL, session_id CHAR(50) NOT NULL, client_ts CHAR(50) NOT NULL, event TEXT NOT NULL);";
constexpr const char* sql_ga_session = "CREATE TABLE IF NOT EXISTS ga_session(session_id CHAR(50) PRIMARY KEY NOT NULL, timestamp CHAR(50) NOT NULL, event TEXT NOT NULL);";
constexpr const char* sql_ga_state = "CREATE TABLE IF NOT EXISTS ga_state(key CHAR(255) PRIMARY KEY NOT NULL, value TEXT);";
constexpr const char* sql_ga_progression = "CREATE TABLE IF NOT EXISTS ga_progression(progression CHAR(255) PRIMARY KEY NOT NULL, tries CHAR(255));";
if (!GAStore::executeQuerySync(sql_ga_events))
{
logging::GALogger::d("ensureDatabase failed: %s", sql_ga_events);
return false;
}
if (!GAStore::executeQuerySync("SELECT status FROM ga_events LIMIT 0,1"))
{
logging::GALogger::d("ga_events corrupt, recreating.");
GAStore::executeQuerySync("DROP TABLE ga_events");
if (!GAStore::executeQuerySync(sql_ga_events))
{
logging::GALogger::w("ga_events corrupt, could not recreate it.");
return false;
}
}
if (!GAStore::executeQuerySync(sql_ga_session))
{
return false;
}
if (!GAStore::executeQuerySync("SELECT session_id FROM ga_session LIMIT 0,1"))
{
logging::GALogger::d("ga_session corrupt, recreating.");
GAStore::executeQuerySync("DROP TABLE ga_session");
if (!GAStore::executeQuerySync(sql_ga_session))
{
logging::GALogger::w("ga_session corrupt, could not recreate it.");
return false;
}
}
if (!GAStore::executeQuerySync(sql_ga_state))
{
return false;
}
if (!GAStore::executeQuerySync("SELECT key FROM ga_state LIMIT 0,1"))
{
logging::GALogger::d("ga_state corrupt, recreating.");
GAStore::executeQuerySync("DROP TABLE ga_state");
if (!GAStore::executeQuerySync(sql_ga_state))
{
logging::GALogger::w("ga_state corrupt, could not recreate it.");
return false;
}
}
if (!GAStore::executeQuerySync(sql_ga_progression))
{
return false;
}
if (!GAStore::executeQuerySync("SELECT progression FROM ga_progression LIMIT 0,1"))
{
logging::GALogger::d("ga_progression corrupt, recreating.");
GAStore::executeQuerySync("DROP TABLE ga_progression");
if (!GAStore::executeQuerySync(sql_ga_progression))
{
logging::GALogger::w("ga_progression corrupt, could not recreate it.");
return false;
}
}
getInstance().trimEventTable();
getInstance().tableReady = true;
logging::GALogger::d("Database tables ensured present");
return true;
}
void GAStore::setState(std::string const& key, std::string const& value)
{
if (value.empty())
{
StringVector parameterArray = {key};
executeQuerySync("DELETE FROM ga_state WHERE key = ?;", parameterArray);
}
else
{
StringVector parameterArray = {key, value};
executeQuerySync("INSERT OR REPLACE INTO ga_state (key, value) VALUES(?, ?);", parameterArray, true);
}
}
int64_t GAStore::getDbSizeBytes()
{
std::ifstream in(getInstance().dbPath, std::ifstream::ate | std::ifstream::binary);
return in.tellg();
}
bool GAStore::getTableReady()
{
return getInstance().tableReady;
}
bool GAStore::isDbTooLargeForEvents()
{
return getDbSizeBytes() > MaxDbSizeBytes;
}
bool GAStore::trimEventTable()
{
if(getDbSizeBytes() > MaxDbSizeBytesBeforeTrim)
{
try
{
json resultSessionArray;
executeQuerySync("SELECT session_id, Max(client_ts) FROM ga_events GROUP BY session_id ORDER BY client_ts LIMIT 3", resultSessionArray);
if(!resultSessionArray.is_null() && resultSessionArray.size() > 0)
{
std::string sessionDeleteString;
unsigned int i = 0;
for (auto itr = resultSessionArray.begin(); itr != resultSessionArray.end(); ++itr)
{
std::string const session_id = itr->get<std::string>();
if(i < resultSessionArray.size() - 1)
{
sessionDeleteString += session_id + ",";
}
else
{
sessionDeleteString += session_id;
}
++i;
}
const std::string deleteOldSessionsSql = utilities::printString("DELETE FROM ga_events WHERE session_id IN (\"%s\");", sessionDeleteString.c_str());
logging::GALogger::w("Database too large when initializing. Deleting the oldest 3 sessions.");
executeQuerySync(deleteOldSessionsSql);
executeQuerySync("VACUUM");
return true;
}
else
{
return false;
}
}
catch(std::exception& e)
{
logging::GALogger::e("Exception thrown: %s", e.what());
return false;
}
}
return true;
}
}
}