ctp-rs 0.3.2+ctp.6.7.11.darwin.6.7.7

Safe & idiomatic Rust bindings for CTP; cross-platform (Windows/Linux/macOS) with built-in LocalCTP support
Documentation
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
#include "CSqliteHandler.h"
#include <iostream>

#define CHECK_DB_VALID \
    if(nullptr == m_pMemoryDB ){ return false; } \
    std::lock_guard<std::recursive_mutex> lck(m_mtx);

CSqliteHandler::CSqliteHandler(const std::string& dbPath,
    const std::vector<std::string>& tableNames)
    : m_filedbStr("filedb"), m_dbPath(dbPath)
    , m_pMemoryDB(nullptr)
    , m_tableNames(tableNames), m_running(true)
{
    OpenSqlDB();

    m_syncThread = std::thread([this]() {
        size_t count = 0;
        while (m_running)
        {
            if (++count >= 10)
            {
                count = 0;
                SyncMemoryAndFileDatabase();
            }
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
        std::cout << "Quit the CSqliteHandler, let's sync for the last time...!" << std::endl;
        SyncMemoryAndFileDatabase(); //sync once more before exit
    });
}

CSqliteHandler::~CSqliteHandler()
{
    m_running = false;
    if (m_syncThread.joinable())
    {
        m_syncThread.join();
    }
#ifdef _WIN32
    //sync once more before exit, because some code in the thread func is not run actually in Windows, so put it here
    std::cout << "Quit the CSqliteHandler in Windows, let's sync for the last time...!" << std::endl;
    SyncMemoryAndFileDatabase();
#endif
    Destory();
}

bool CSqliteHandler::SyncMemoryAndFileDatabase(bool fromMemoryToFile /*= true*/)
{
    CHECK_DB_VALID

    if (!AttachMemoryAndFileDatabase())
    {
        return false;
    }
    char* errMsg = nullptr;
    for (const auto& tableName : m_tableNames)
    {
        const std::string targetTable = fromMemoryToFile ? (m_filedbStr + "." + tableName) : tableName;
        const std::string srcTable = fromMemoryToFile ? tableName : (m_filedbStr + "." + tableName);

        const std::string syncSql = "INSERT OR REPLACE INTO " + targetTable
            + " SELECT * FROM " + srcTable + ";";
        int ret = sqlite3_exec(m_pMemoryDB, syncSql.c_str(), 0, 0, &errMsg);
        if (errMsg)
        {
            std::cerr << "Sync memory and file database failed! sql:" << syncSql
                << " errMsg:" << errMsg << std::endl;
            sqlite3_free(errMsg);
        }
        if (SQLITE_OK != ret)
        {
            DetachMemoryAndFileDatabase();
            return false;
        }
    }
    if (!DetachMemoryAndFileDatabase())
    {
        return false;
    }

    return true;
}

void CSqliteHandler::Destory()
{
    if (nullptr != m_pMemoryDB)
    {
        sqlite3_close(m_pMemoryDB);
        m_pMemoryDB = nullptr;
    }
}

bool CSqliteHandler::OpenSqlDB()
{
    sqlite3* pDB(nullptr);//file database
    int ret = sqlite3_open(m_dbPath.c_str(), &pDB);// open file database, will create if not exist
    if (SQLITE_OK != ret)
    {
        std::cerr << "Open file database failed! dbPath:" << m_dbPath << std::endl;
        return false;
    }
    if (nullptr != pDB)
    {
        sqlite3_close(pDB);
        pDB = nullptr;
    }

    ret = sqlite3_open(":memory:", &m_pMemoryDB);// open memory database
    if (SQLITE_OK != ret)
    {
        std::cerr << "Open memory database failed! It shoule be attached with "
            << m_dbPath << std::endl;
        return false;
    }

    //const std::string pragmaSql = "PRAGMA cache_size = 10000;";//10 MB cache
    //char* errMsg = nullptr;
    //ret = sqlite3_exec(m_pMemoryDB, pragmaSql.c_str(), 0, 0, &errMsg);
    //if (errMsg)
    //{
    //    std::cerr << "PRAGMA something for file database " << m_dbPath << " failed! "
    //        << errMsg << std::endl;
    //    sqlite3_free(errMsg);
    //}
    //if (SQLITE_OK != ret)
    //{
    //    return false;
    //}
    std::cout << "OpenSqlDB done!~" << std::endl;
    return true;
}

bool CSqliteHandler::AttachMemoryAndFileDatabase()
{
    // attach the file database into the memory database connection,
    // otherwise we can not handle file database in the memory database connection,
    // because the sqlite forbids the cross-database operation if they are not attached,
    // and, the sql operation will be sync in these two database if they are attached
    char* errMsg = nullptr;
    const std::string attachSql = "ATTACH '" + m_dbPath + "' AS '" + m_filedbStr + "';";
    int ret = sqlite3_exec(m_pMemoryDB, attachSql.c_str(), 0, 0, &errMsg);
    if (errMsg)
    {
        std::cerr << "Attach memory and file database " << m_dbPath << " failed! "
            << errMsg << std::endl;
        sqlite3_free(errMsg);
    }
    if (SQLITE_OK != ret)
    {
        return false;
    }
    return true;
}

bool CSqliteHandler::DetachMemoryAndFileDatabase()
{
    // the sql operation will be sync in these two database if they are attached,
    // so we need detach them when we do not want to write to file database.
    char* errMsg = nullptr;
    const std::string detachSql = "DETACH DATABASE '" + m_filedbStr + "';";
    int ret = sqlite3_exec(m_pMemoryDB, detachSql.c_str(), 0, 0, &errMsg);
    if (errMsg)
    {
        std::cerr << "Detach memory and file database failed! " << errMsg << std::endl;
        sqlite3_free(errMsg);
    }
    if (SQLITE_OK != ret)
    {
        return false;
    }
    return true;
}

bool CSqliteHandler::CreateTable(const std::string& sql, const std::string& tableName)
{
    CHECK_DB_VALID
    char* errMsg = nullptr;
    int ret = 0;

    // the first step: create table in the file database.
    // because if the table does not exist in file database,
    // it can not sync from file database to memory database.
    // of course, if the table does exist already, we do not need this step.
    sqlite3* pDB(nullptr);//file database
    ret = sqlite3_open(m_dbPath.c_str(), &pDB);
    if (SQLITE_OK != ret)
    {
        std::cerr << "Open file database failed! dbPath:" << m_dbPath << std::endl;
        return false;
    }
    ret = sqlite3_exec(pDB, sql.c_str(), nullptr, nullptr, &errMsg);
    if (errMsg)
    {
        char* ptr = ::strstr(errMsg, "already exists");
        if (ptr != NULL)
        {
            // table already exists, not deem it as an error
            ret = SQLITE_OK;
        }
        else
        {
            std::cerr << "Create table in file database failed! sql:" << sql
                << " errMsg:" << errMsg << std::endl;
        }
        sqlite3_free(errMsg);
    }
    if (nullptr != pDB)
    {
        sqlite3_close(pDB);
        pDB = nullptr;
    }
    if (SQLITE_OK != ret)
    {
        std::cerr << "CreateTable " << tableName << " but sqlite3_exec ret is not OK!" << std::endl;
        return false;
    }

    // the second step: create table in the memory database.
    ret = sqlite3_exec(m_pMemoryDB, sql.c_str(), nullptr, nullptr, &errMsg);
    if (errMsg)
    {
        std::cerr << "Create table in memory database failed! sql:" << sql
            << " errMsg:" << errMsg << std::endl;
        sqlite3_free(errMsg);
    }

    // the third step: attach the memory and file database,
    // and read table data from the existing table in file database
    // into memory database, finally we should detach them.
    if (!AttachMemoryAndFileDatabase())
    {
        std::cerr << "CreateTable " << tableName << " but AttachMemoryAndFileDatabase fail!" << std::endl;
        return false;
    }
    const std::string targetTable = tableName;
    const std::string srcTable = m_filedbStr + "." + tableName;
    const std::string syncSql = "INSERT OR REPLACE INTO " + targetTable
        + " SELECT * FROM " + srcTable + ";";

    ret = sqlite3_exec(m_pMemoryDB, syncSql.c_str(), 0, 0, &errMsg);
    if (errMsg)
    {
        std::cerr << "Sync memory and file database on table " << tableName << " failed!"
            << " sql:" << syncSql
            << " errMsg:" << errMsg << std::endl;
        sqlite3_free(errMsg);
    }
    if (!DetachMemoryAndFileDatabase())
    {
        std::cerr << "CreateTable " << tableName << " but DetachMemoryAndFileDatabase fail!" << std::endl;
        return false;
    }
    if (SQLITE_OK != ret)
    {
        std::cerr << "CreateTable " << tableName << " but sqlite3_exec ret is not OK!" << std::endl;
        return false;
    }
    return ret == SQLITE_OK;
}

// begin the transaction
bool CSqliteHandler::BeginTransaction()
{
    if (nullptr == m_pMemoryDB) { return false; }
    m_mtx.lock();
    char* errMsg = nullptr;
    int ret = sqlite3_exec(m_pMemoryDB, "begin", nullptr, nullptr, &errMsg);
    if (errMsg)
    {
        std::cerr << "Begin transaction in memory database failed!"
            << " errMsg:" << errMsg << std::endl;
        sqlite3_free(errMsg);
    }
    return ret == SQLITE_OK;
}

// commit the transaction
bool CSqliteHandler::Commit()
{
    char* errMsg = nullptr;
    int ret = sqlite3_exec(m_pMemoryDB, "commit", nullptr, nullptr, &errMsg);
    if (errMsg)
    {
        std::cerr << "Commit in memory database failed!"
            << " errMsg:" << errMsg << std::endl;
        sqlite3_free(errMsg);
    }
    m_mtx.unlock();
    return ret == SQLITE_OK;
}

bool CSqliteHandler::Insert(const std::string& sql)
{
    CHECK_DB_VALID
    if (sql.empty()) return false;

    char* errMsg = nullptr;
    int ret = sqlite3_exec(m_pMemoryDB, sql.c_str(), nullptr, nullptr, &errMsg);
    if (errMsg)
    {
        std::cerr << "Insert in memory database failed! sql:" << sql
            << " errMsg:" << errMsg << std::endl;
        sqlite3_free(errMsg);
    }
    return ret == SQLITE_OK;
}

bool CSqliteHandler::Delete(const std::string& sql)
{
    CHECK_DB_VALID
    // How to handle deletion operations ?
    // First method : Synchronous operation, perform deletion in both the file databaseand the memory database.
    // Second method : Similar to the insertion operation, delete only in the memory database first,
    // and then in the timed task(SyncMemoryAndFileDatabase), clear all the data from the tables in the file database,
    // and then insert the content of each table in the memory database into the tables in the file database.
    // It is also possible to add a marker to the table to indicate that the table in the file database needs
    // to perform a clearand then insert operation.If there is no marker, it is not necessary to clear it first.
    //
    // This system uses the first method.

    // delete from table in file database, then delete from table in the memory database.
    sqlite3* pFileDB(nullptr);//file database
    int ret = sqlite3_open(m_dbPath.c_str(), &pFileDB);// open file database, will create if not exist
    if (SQLITE_OK != ret)
    {
        std::cerr << "Open file database in Delete() failed! dbPath:" << m_dbPath << std::endl;
        return false;
    }
    if (nullptr != pFileDB)
    {
        DeleteImpl(sql, pFileDB);

        sqlite3_close(pFileDB);
        pFileDB = nullptr;
    }

    return DeleteImpl(sql, m_pMemoryDB);
}

bool CSqliteHandler::DeleteImpl(const std::string& sql, sqlite3* pDB)
{
    CHECK_DB_VALID
    char* errMsg = nullptr;
    int result = sqlite3_exec(pDB, sql.c_str(), nullptr, nullptr, &errMsg);
    if (errMsg)
    {
        std::cerr << "Delete in " << (pDB == m_pMemoryDB ? "memory" : "file" )
            << " database failed! sql:" << sql
            << " errMsg:" << errMsg << std::endl;
        sqlite3_free(errMsg);
    }
    if (result != SQLITE_OK)
    {
        return false;
    }
    return true;
}


bool CSqliteHandler::Update(const std::string& sql)
{
    CHECK_DB_VALID
    char* errMsg = nullptr;

    int ret = sqlite3_exec(m_pMemoryDB, sql.c_str(), nullptr, nullptr, &errMsg);
    if (errMsg)
    {
        std::cerr << "Update in memory database failed! sql:" << sql
            << " errMsg:" << errMsg << std::endl;
        sqlite3_free(errMsg);
    }
    return ret == SQLITE_OK;
}

bool CSqliteHandler::SelectData(const std::string& sql, SQL_VALUES& values)
{
    CHECK_DB_VALID
    if (sql.empty()) return false;

    int nCols = 0;
    int nRows = 0;
    char** azResult = nullptr;
    char* errMsg = nullptr;
    int index = 0;
    const int result = sqlite3_get_table(m_pMemoryDB, sql.c_str(), &azResult, &nRows, &nCols, &errMsg);

    index = nCols;

    values.clear();
    for (int i = 0; i < nRows; ++i)
    {
        SQL_ROW_VALUE temp;
        for (int j = 0; j < nCols; ++j)
        {
            // maybe the result is null, TODO: maybe set as other value to present null?
            if (azResult[index] == nullptr)
            {
                temp[azResult[j]] = "";
            }
            else
            {
                temp[azResult[j]] = azResult[index];
            }
            index++;
        }
        values.push_back(temp);
    }

    if (azResult)
    {
        sqlite3_free_table(azResult);
    }
    if (errMsg)
    {
        std::cerr << "Select in memory database failed! sql:" << sql
            << " errMsg:" << errMsg << std::endl;
        sqlite3_free(errMsg);
    }
    return result == SQLITE_OK;
}