• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "sqlite_utils.h"
17 
18 #include <climits>
19 #include <cstring>
20 #include <chrono>
21 #include <thread>
22 #include <mutex>
23 #include <map>
24 #include <algorithm>
25 
26 #include "sqlite_import.h"
27 #include "securec.h"
28 #include "db_constant.h"
29 #include "db_common.h"
30 #include "db_errno.h"
31 #include "log_print.h"
32 #include "value_object.h"
33 #include "schema_utils.h"
34 #include "schema_constant.h"
35 #include "time_helper.h"
36 #include "platform_specific.h"
37 
38 namespace DistributedDB {
39     std::mutex SQLiteUtils::logMutex_;
40     std::string SQLiteUtils::lastErrorMsg_;
41 namespace {
42     const int BUSY_TIMEOUT_MS = 3000; // 3000ms for sqlite busy timeout.
43     const int BUSY_SLEEP_TIME = 50; // sleep for 50us
44     const int NO_SIZE_LIMIT = -1;
45     const int MAX_STEP_TIMES = 8000;
46     const int BIND_KEY_INDEX = 1;
47     const int BIND_VAL_INDEX = 2;
48     const int USING_STR_LEN = -1;
49     const std::string WAL_MODE_SQL = "PRAGMA journal_mode=WAL;";
50     const std::string SYNC_MODE_FULL_SQL = "PRAGMA synchronous=FULL;";
51     const std::string SYNC_MODE_NORMAL_SQL = "PRAGMA synchronous=NORMAL;";
52     const std::string USER_VERSION_SQL = "PRAGMA user_version;";
53     const std::string BEGIN_SQL = "BEGIN TRANSACTION";
54     const std::string BEGIN_IMMEDIATE_SQL = "BEGIN IMMEDIATE TRANSACTION";
55     const std::string COMMIT_SQL = "COMMIT TRANSACTION";
56     const std::string ROLLBACK_SQL = "ROLLBACK TRANSACTION";
57     const std::string JSON_EXTRACT_BY_PATH_TEST_CREATED = "SELECT json_extract_by_path('{\"field\":0}', '$.field', 0);";
58     const std::string DEFAULT_ATTACH_CIPHER = "PRAGMA cipher_default_attach_cipher=";
59     const std::string DEFAULT_ATTACH_KDF_ITER = "PRAGMA cipher_default_attach_kdf_iter=5000";
60     const std::string SHA1_ALGO_SQL = "PRAGMA codec_hmac_algo=SHA1;";
61     const std::string SHA256_ALGO_SQL = "PRAGMA codec_hmac_algo=SHA256;";
62     const std::string SHA256_ALGO_REKEY_SQL = "PRAGMA codec_rekey_hmac_algo=SHA256;";
63     const std::string SHA1_ALGO_ATTACH_SQL = "PRAGMA cipher_default_attach_hmac_algo=SHA1;";
64     const std::string SHA256_ALGO_ATTACH_SQL = "PRAGMA cipher_default_attach_hmac_algo=SHA256;";
65     const std::string EXPORT_BACKUP_SQL = "SELECT export_database('backup');";
66     const std::string CIPHER_CONFIG_SQL = "PRAGMA codec_cipher=";
67     const std::string KDF_ITER_CONFIG_SQL = "PRAGMA codec_kdf_iter=";
68     const std::string BACK_CIPHER_CONFIG_SQL = "PRAGMA backup.codec_cipher=";
69     const std::string BACK_KDF_ITER_CONFIG_SQL = "PRAGMA backup.codec_kdf_iter=5000;";
70     const std::string META_CIPHER_CONFIG_SQL = "PRAGMA meta.codec_cipher=";
71     const std::string META_KDF_ITER_CONFIG_SQL = "PRAGMA meta.codec_kdf_iter=5000;";
72 
73     const std::string DETACH_BACKUP_SQL = "DETACH 'backup'";
74     const std::string UPDATE_META_SQL = "INSERT OR REPLACE INTO meta_data VALUES (?, ?);";
75 
76     bool g_configLog = false;
77 
78     // statement must not be null
GetColString(sqlite3_stmt * statement,int nCol)79     std::string GetColString(sqlite3_stmt *statement, int nCol)
80     {
81         std::string rowString;
82         for (int i = 0; i < nCol; i++) {
83             if (sqlite3_column_name(statement, i) != nullptr) {
84                 rowString += sqlite3_column_name(statement, i);
85             }
86             int blankFill = (i + 1) * 16 - rowString.size(); // each column width 16
87             rowString.append(static_cast<std::string::size_type>((blankFill > 0) ? blankFill : 0), ' ');
88         }
89         return rowString;
90     }
91 }
92 
93 namespace TriggerMode {
94 const std::map<TriggerModeEnum, std::string> TRIGGER_MODE_MAP = {
95     {TriggerModeEnum::NONE,   ""},
96     {TriggerModeEnum::INSERT, "INSERT"},
97     {TriggerModeEnum::UPDATE, "UPDATE"},
98     {TriggerModeEnum::DELETE, "DELETE"},
99 };
100 
GetTriggerModeString(TriggerModeEnum mode)101 std::string GetTriggerModeString(TriggerModeEnum mode)
102 {
103     auto it = TRIGGER_MODE_MAP.find(mode);
104     return (it == TRIGGER_MODE_MAP.end()) ? "" : it->second;
105 }
106 }
107 
SqliteLogCallback(void * data,int err,const char * msg)108 void SQLiteUtils::SqliteLogCallback(void *data, int err, const char *msg)
109 {
110     bool verboseLog = (data != nullptr);
111     auto errType = static_cast<unsigned int>(err);
112     errType &= 0xFF;
113     if (errType == 0 || errType == SQLITE_CONSTRAINT || errType == SQLITE_SCHEMA ||
114         errType == SQLITE_NOTICE || err == SQLITE_WARNING_AUTOINDEX) {
115         if (verboseLog) {
116             LOGD("[SQLite] Error[%d] sys[%d] %s ", err, errno, sqlite3_errstr(err));
117         }
118     } else if (errType == SQLITE_WARNING || errType == SQLITE_IOERR ||
119         errType == SQLITE_CORRUPT || errType == SQLITE_CANTOPEN) {
120         LOGI("[SQLite] Error[%d], sys[%d], %s", err, errno, sqlite3_errstr(err));
121     } else {
122         LOGE("[SQLite] Error[%d], sys[%d]", err, errno);
123         return;
124     }
125 
126     const char *errMsg = sqlite3_errstr(err);
127     std::lock_guard<std::mutex> autoLock(logMutex_);
128     if (errMsg != nullptr) {
129         lastErrorMsg_ = std::string(errMsg);
130     }
131 }
132 
CreateDataBase(const OpenDbProperties & properties,sqlite3 * & dbTemp,bool setWal)133 int SQLiteUtils::CreateDataBase(const OpenDbProperties &properties, sqlite3 *&dbTemp, bool setWal)
134 {
135     uint64_t flag = SQLITE_OPEN_URI | SQLITE_OPEN_READWRITE;
136     if (properties.createIfNecessary) {
137         flag |= SQLITE_OPEN_CREATE;
138     }
139     std::string cipherName = GetCipherName(properties.cipherType);
140     if (cipherName.empty()) {
141         LOGE("[SQLite] GetCipherName failed");
142         return -E_INVALID_ARGS;
143     }
144     std::string defaultAttachCipher = DEFAULT_ATTACH_CIPHER + cipherName + ";";
145     std::vector<std::string> sqls {defaultAttachCipher, DEFAULT_ATTACH_KDF_ITER};
146     if (setWal) {
147         sqls.push_back(WAL_MODE_SQL);
148     }
149     std::string fileUrl = DBConstant::SQLITE_URL_PRE + properties.uri;
150     int errCode = sqlite3_open_v2(fileUrl.c_str(), &dbTemp, flag, nullptr);
151     if (errCode != SQLITE_OK) {
152         LOGE("[SQLite] open database failed: %d - sys err(%d)", errCode, errno);
153         errCode = SQLiteUtils::MapSQLiteErrno(errCode);
154         goto END;
155     }
156 
157     errCode = SetDataBaseProperty(dbTemp, properties, setWal, sqls);
158     if (errCode != SQLITE_OK) {
159         LOGE("[SQLite] SetDataBaseProperty failed: %d", errCode);
160         goto END;
161     }
162 
163 END:
164     if (errCode != E_OK && dbTemp != nullptr) {
165         (void)sqlite3_close_v2(dbTemp);
166         dbTemp = nullptr;
167     }
168 
169     return errCode;
170 }
171 
OpenDatabase(const OpenDbProperties & properties,sqlite3 * & db,bool setWal)172 int SQLiteUtils::OpenDatabase(const OpenDbProperties &properties, sqlite3 *&db, bool setWal)
173 {
174     {
175         // Only for register the sqlite3 log callback
176         std::lock_guard<std::mutex> lock(logMutex_);
177         if (!g_configLog) {
178             sqlite3_config(SQLITE_CONFIG_LOG, &SqliteLogCallback, &properties.createIfNecessary);
179             g_configLog = true;
180         }
181     }
182     sqlite3 *dbTemp = nullptr;
183     int errCode = CreateDataBase(properties, dbTemp, setWal);
184     if (errCode != E_OK) {
185         goto END;
186     }
187     errCode = RegisterJsonFunctions(dbTemp);
188     if (errCode != E_OK) {
189         goto END;
190     }
191     // Set the synchroized mode, default for full mode.
192     errCode = ExecuteRawSQL(dbTemp, SYNC_MODE_FULL_SQL);
193     if (errCode != E_OK) {
194         LOGE("SQLite sync mode failed: %d", errCode);
195         goto END;
196     }
197 
198     if (!properties.isMemDb) {
199         errCode = SQLiteUtils::SetPersistWalMode(dbTemp);
200         if (errCode != E_OK) {
201             LOGE("SQLite set persist wall mode failed: %d", errCode);
202         }
203     }
204 
205 END:
206     if (errCode != E_OK && dbTemp != nullptr) {
207         (void)sqlite3_close_v2(dbTemp);
208         dbTemp = nullptr;
209     }
210     if (errCode != E_OK && errno == EKEYREVOKED) {
211         errCode = -E_EKEYREVOKED;
212     }
213     db = dbTemp;
214     return errCode;
215 }
216 
GetStatement(sqlite3 * db,const std::string & sql,sqlite3_stmt * & statement)217 int SQLiteUtils::GetStatement(sqlite3 *db, const std::string &sql, sqlite3_stmt *&statement)
218 {
219     if (db == nullptr) {
220         LOGE("Invalid db for statement");
221         return -E_INVALID_DB;
222     }
223 
224     // Prepare the new statement only when the input parameter is not null
225     if (statement != nullptr) {
226         return E_OK;
227     }
228     int errCode = sqlite3_prepare_v2(db, sql.c_str(), NO_SIZE_LIMIT, &statement, nullptr);
229     if (errCode != SQLITE_OK) {
230         LOGE("Prepare SQLite statement failed:%d", errCode);
231         errCode = SQLiteUtils::MapSQLiteErrno(errCode);
232         SQLiteUtils::ResetStatement(statement, true, errCode);
233         return errCode;
234     }
235 
236     if (statement == nullptr) {
237         return -E_INVALID_DB;
238     }
239 
240     return E_OK;
241 }
242 
BindTextToStatement(sqlite3_stmt * statement,int index,const std::string & str)243 int SQLiteUtils::BindTextToStatement(sqlite3_stmt *statement, int index, const std::string &str)
244 {
245     if (statement == nullptr) {
246         return -E_INVALID_ARGS;
247     }
248 
249     int errCode = sqlite3_bind_text(statement, index, str.c_str(), str.length(), SQLITE_TRANSIENT);
250     if (errCode != SQLITE_OK) {
251         LOGE("[SQLiteUtil][Bind text]Failed to bind the value:%d", errCode);
252         return SQLiteUtils::MapSQLiteErrno(errCode);
253     }
254 
255     return E_OK;
256 }
257 
BindInt64ToStatement(sqlite3_stmt * statement,int index,int64_t value)258 int SQLiteUtils::BindInt64ToStatement(sqlite3_stmt *statement, int index, int64_t value)
259 {
260     // statement check outSide
261     int errCode = sqlite3_bind_int64(statement, index, value);
262     if (errCode != SQLITE_OK) {
263         LOGE("[SQLiteUtil][Bind int64]Failed to bind the value:%d", errCode);
264         return SQLiteUtils::MapSQLiteErrno(errCode);
265     }
266 
267     return E_OK;
268 }
269 
BindBlobToStatement(sqlite3_stmt * statement,int index,const std::vector<uint8_t> & value,bool permEmpty)270 int SQLiteUtils::BindBlobToStatement(sqlite3_stmt *statement, int index, const std::vector<uint8_t> &value,
271     bool permEmpty)
272 {
273     if (statement == nullptr) {
274         return -E_INVALID_ARGS;
275     }
276 
277     // Check empty value.
278     if (value.empty() && !permEmpty) {
279         LOGI("[SQLiteUtil][Bind blob]Invalid value");
280         return -E_INVALID_ARGS;
281     }
282 
283     int errCode;
284     if (value.empty()) {
285         errCode = sqlite3_bind_zeroblob(statement, index, -1); // -1 for zero-length blob.
286     } else {
287         errCode = sqlite3_bind_blob(statement, index, static_cast<const void *>(value.data()),
288             value.size(), SQLITE_TRANSIENT);
289     }
290 
291     if (errCode != SQLITE_OK) {
292         LOGE("[SQLiteUtil][Bind blob]Failed to bind the value:%d", errCode);
293         return SQLiteUtils::MapSQLiteErrno(errCode);
294     }
295 
296     return E_OK;
297 }
298 
ResetStatement(sqlite3_stmt * & statement,bool isNeedFinalize,int & errCode)299 void SQLiteUtils::ResetStatement(sqlite3_stmt *&statement, bool isNeedFinalize, int &errCode)
300 {
301     if (statement == nullptr) {
302         return;
303     }
304 
305     int innerCode = SQLITE_OK;
306     // if need finalize the statement, just goto finalize.
307     if (!isNeedFinalize) {
308         // reset the statement firstly.
309         innerCode = sqlite3_reset(statement);
310         if (innerCode != SQLITE_OK) {
311             LOGE("[SQLiteUtils] reset statement error:%d, sys:%d", innerCode, errno);
312             isNeedFinalize = true;
313         } else {
314             sqlite3_clear_bindings(statement);
315         }
316     }
317 
318     if (isNeedFinalize) {
319         int finalizeResult = sqlite3_finalize(statement);
320         if (finalizeResult != SQLITE_OK) {
321             LOGD("[SQLiteUtils] finalize statement error:%d, sys:%d", finalizeResult, errno);
322             innerCode = finalizeResult;
323         }
324         statement = nullptr;
325     }
326 
327     if (innerCode != SQLITE_OK) { // the sqlite error code has higher priority.
328         errCode = SQLiteUtils::MapSQLiteErrno(innerCode);
329     }
330 }
331 
StepWithRetry(sqlite3_stmt * statement,bool isMemDb)332 int SQLiteUtils::StepWithRetry(sqlite3_stmt *statement, bool isMemDb)
333 {
334     if (statement == nullptr) {
335         return -E_INVALID_ARGS;
336     }
337 
338     int errCode = E_OK;
339     int retryCount = 0;
340     do {
341         errCode = sqlite3_step(statement);
342         if ((errCode == SQLITE_LOCKED) && isMemDb) {
343             std::this_thread::sleep_for(std::chrono::microseconds(BUSY_SLEEP_TIME));
344             retryCount++;
345         } else {
346             break;
347         }
348     } while (retryCount <= MAX_STEP_TIMES);
349 
350     if (errCode != SQLITE_DONE && errCode != SQLITE_ROW) {
351         LOGE("[SQLiteUtils] Step error:%d, sys:%d", errCode, errno);
352     }
353 
354     return SQLiteUtils::MapSQLiteErrno(errCode);
355 }
356 
BindPrefixKey(sqlite3_stmt * statement,int index,const Key & keyPrefix)357 int SQLiteUtils::BindPrefixKey(sqlite3_stmt *statement, int index, const Key &keyPrefix)
358 {
359     if (statement == nullptr) {
360         return -E_INVALID_ARGS;
361     }
362 
363     const size_t maxKeySize = DBConstant::MAX_KEY_SIZE;
364     // bind the first prefix key
365     int errCode = BindBlobToStatement(statement, index, keyPrefix, true);
366     if (errCode != SQLITE_OK) {
367         LOGE("Bind the prefix first error:%d", errCode);
368         return SQLiteUtils::MapSQLiteErrno(errCode);
369     }
370 
371     // bind the second prefix key
372     uint8_t end[maxKeySize];
373     errno_t status = memset_s(end, maxKeySize, UCHAR_MAX, maxKeySize); // max byte value is 0xFF.
374     if (status != EOK) {
375         LOGE("memset error:%d", status);
376         return -E_SECUREC_ERROR;
377     }
378 
379     if (!keyPrefix.empty()) {
380         status = memcpy_s(end, maxKeySize, keyPrefix.data(), keyPrefix.size());
381         if (status != EOK) {
382             LOGE("memcpy error:%d", status);
383             return -E_SECUREC_ERROR;
384         }
385     }
386 
387     // index wouldn't be too large, just add one to the first index.
388     errCode = sqlite3_bind_blob(statement, index + 1, end, maxKeySize, SQLITE_TRANSIENT);
389     if (errCode != SQLITE_OK) {
390         LOGE("Bind the prefix second error:%d", errCode);
391         return SQLiteUtils::MapSQLiteErrno(errCode);
392     }
393     return E_OK;
394 }
395 
BeginTransaction(sqlite3 * db,TransactType type)396 int SQLiteUtils::BeginTransaction(sqlite3 *db, TransactType type)
397 {
398     if (type == TransactType::IMMEDIATE) {
399         return ExecuteRawSQL(db, BEGIN_IMMEDIATE_SQL);
400     }
401 
402     return ExecuteRawSQL(db, BEGIN_SQL);
403 }
404 
CommitTransaction(sqlite3 * db)405 int SQLiteUtils::CommitTransaction(sqlite3 *db)
406 {
407     return ExecuteRawSQL(db, COMMIT_SQL);
408 }
409 
RollbackTransaction(sqlite3 * db)410 int SQLiteUtils::RollbackTransaction(sqlite3 *db)
411 {
412     return ExecuteRawSQL(db, ROLLBACK_SQL);
413 }
414 
ExecuteRawSQL(sqlite3 * db,const std::string & sql)415 int SQLiteUtils::ExecuteRawSQL(sqlite3 *db, const std::string &sql)
416 {
417     if (db == nullptr) {
418         return -E_INVALID_DB;
419     }
420 
421     sqlite3_stmt *stmt = nullptr;
422     int errCode = SQLiteUtils::GetStatement(db, sql, stmt);
423     if (errCode != SQLiteUtils::MapSQLiteErrno(SQLITE_OK)) {
424         LOGE("[SQLiteUtils][ExecuteSQL] prepare statement failed(%d), sys(%d)", errCode, errno);
425         return errCode;
426     }
427 
428     do {
429         errCode = SQLiteUtils::StepWithRetry(stmt);
430         if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)) {
431             errCode = E_OK;
432             break;
433         } else if (errCode != SQLiteUtils::MapSQLiteErrno(SQLITE_ROW)) {
434             LOGE("[SQLiteUtils][ExecuteSQL] execute statement failed(%d), sys(%d)", errCode, errno);
435             break;
436         }
437     } while (true);
438 
439     SQLiteUtils::ResetStatement(stmt, true, errCode);
440     return errCode;
441 }
442 
SetKey(sqlite3 * db,CipherType type,const CipherPassword & passwd,bool setWal,uint32_t iterTimes)443 int SQLiteUtils::SetKey(sqlite3 *db, CipherType type, const CipherPassword &passwd, bool setWal, uint32_t iterTimes)
444 {
445     if (db == nullptr) {
446         return -E_INVALID_DB;
447     }
448 
449     if (passwd.GetSize() != 0) {
450 #ifndef OMIT_ENCRYPT
451         int errCode = SetKeyInner(db, type, passwd, iterTimes);
452         if (errCode != E_OK) {
453             LOGE("[SQLiteUtils][Setkey] set keyInner failed:%d", errCode);
454             return errCode;
455         }
456         errCode = SQLiteUtils::ExecuteRawSQL(db, SHA256_ALGO_SQL);
457         if (errCode != E_OK) {
458             LOGE("[SQLiteUtils][Setkey] set sha algo failed:%d", errCode);
459             return errCode;
460         }
461         errCode = SQLiteUtils::ExecuteRawSQL(db, SHA256_ALGO_REKEY_SQL);
462         if (errCode != E_OK) {
463             LOGE("[SQLiteUtils][Setkey] set rekey sha algo failed:%d", errCode);
464             return errCode;
465         }
466 #else
467         return -E_NOT_SUPPORT;
468 #endif
469     }
470 
471     // verify key
472     int errCode = SQLiteUtils::ExecuteRawSQL(db, USER_VERSION_SQL);
473     if (errCode != E_OK) {
474         LOGE("[SQLiteUtils][Setkey] verify version failed:%d", errCode);
475         if (errno == EKEYREVOKED) {
476             return -E_EKEYREVOKED;
477         }
478         if (errCode == -E_BUSY) {
479             return errCode;
480         }
481 #ifndef OMIT_ENCRYPT
482         errCode = UpdateCipherShaAlgo(db, setWal, type, passwd, iterTimes);
483         if (errCode != E_OK) {
484             LOGE("[SQLiteUtils][Setkey] upgrade cipher sha algo failed:%d", errCode);
485         }
486 #endif
487     }
488     return errCode;
489 }
490 
GetColumnBlobValue(sqlite3_stmt * statement,int index,std::vector<uint8_t> & value)491 int SQLiteUtils::GetColumnBlobValue(sqlite3_stmt *statement, int index, std::vector<uint8_t> &value)
492 {
493     if (statement == nullptr) {
494         return -E_INVALID_ARGS;
495     }
496 
497     int keySize = sqlite3_column_bytes(statement, index);
498     auto keyRead = static_cast<const uint8_t *>(sqlite3_column_blob(statement, index));
499     if (keySize < 0) {
500         LOGE("[SQLiteUtils][Column blob] size:%d", keySize);
501         return -E_INVALID_DATA;
502     } else if (keySize == 0 || keyRead == nullptr) {
503         value.resize(0);
504     } else {
505         value.resize(keySize);
506         value.assign(keyRead, keyRead + keySize);
507     }
508 
509     return E_OK;
510 }
511 
GetColumnTextValue(sqlite3_stmt * statement,int index,std::string & value)512 int SQLiteUtils::GetColumnTextValue(sqlite3_stmt *statement, int index, std::string &value)
513 {
514     if (statement == nullptr) {
515         return -E_INVALID_ARGS;
516     }
517     const unsigned char *val = sqlite3_column_text(statement, index);
518     value = (val != nullptr) ? std::string(reinterpret_cast<const char *>(val)) : std::string();
519     return E_OK;
520 }
521 
AttachNewDatabase(sqlite3 * db,CipherType type,const CipherPassword & password,const std::string & attachDbAbsPath,const std::string & attachAsName)522 int SQLiteUtils::AttachNewDatabase(sqlite3 *db, CipherType type, const CipherPassword &password,
523     const std::string &attachDbAbsPath, const std::string &attachAsName)
524 {
525 #ifndef OMIT_ENCRYPT
526     int errCode = SQLiteUtils::ExecuteRawSQL(db, SHA256_ALGO_ATTACH_SQL);
527     if (errCode != E_OK) {
528         LOGE("[SQLiteUtils][AttachNewDatabase] set attach sha256 algo failed:%d", errCode);
529         return errCode;
530     }
531 #endif
532     errCode = AttachNewDatabaseInner(db, type, password, attachDbAbsPath, attachAsName);
533 #ifndef OMIT_ENCRYPT
534     if (errCode == -E_INVALID_PASSWD_OR_CORRUPTED_DB) {
535         errCode = SQLiteUtils::ExecuteRawSQL(db, SHA1_ALGO_ATTACH_SQL);
536         if (errCode != E_OK) {
537             LOGE("[SQLiteUtils][AttachNewDatabase] set attach sha1 algo failed:%d", errCode);
538             return errCode;
539         }
540         errCode = AttachNewDatabaseInner(db, type, password, attachDbAbsPath, attachAsName);
541         if (errCode != E_OK) {
542             LOGE("[SQLiteUtils][AttachNewDatabase] attach db failed:%d", errCode);
543             return errCode;
544         }
545         errCode = SQLiteUtils::ExecuteRawSQL(db, SHA256_ALGO_ATTACH_SQL);
546         if (errCode != E_OK) {
547             LOGE("[SQLiteUtils][AttachNewDatabase] set attach sha256 algo failed:%d", errCode);
548         }
549     }
550 #endif
551     return errCode;
552 }
553 
AttachNewDatabaseInner(sqlite3 * db,CipherType type,const CipherPassword & password,const std::string & attachDbAbsPath,const std::string & attachAsName)554 int SQLiteUtils::AttachNewDatabaseInner(sqlite3 *db, CipherType type, const CipherPassword &password,
555     const std::string &attachDbAbsPath, const std::string &attachAsName)
556 {
557     // example: "ATTACH '../new.db' AS backup KEY XXXX;"
558     std::string attachSql = "ATTACH ? AS " + attachAsName + " KEY ?;"; // Internal interface not need verify alias name
559 
560     sqlite3_stmt* statement = nullptr;
561     int errCode = SQLiteUtils::GetStatement(db, attachSql, statement);
562     if (errCode != E_OK) {
563         return errCode;
564     }
565     // 1st is name.
566     errCode = sqlite3_bind_text(statement, 1, attachDbAbsPath.c_str(), attachDbAbsPath.length(), SQLITE_TRANSIENT);
567     if (errCode != SQLITE_OK) {
568         LOGE("Bind the attached db name failed:%d", errCode);
569         errCode = SQLiteUtils::MapSQLiteErrno(errCode);
570         goto END;
571     }
572     // Passwords do not allow vector operations, so we can not use function BindBlobToStatement here.
573     errCode = sqlite3_bind_blob(statement, 2, static_cast<const void *>(password.GetData()),  // 2 means password index.
574         password.GetSize(), SQLITE_TRANSIENT);
575     if (errCode != SQLITE_OK) {
576         LOGE("Bind the attached key failed:%d", errCode);
577         errCode = SQLiteUtils::MapSQLiteErrno(errCode);
578         goto END;
579     }
580 
581     errCode = SQLiteUtils::StepWithRetry(statement);
582     if (errCode != SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)) {
583         LOGE("Execute the SQLite attach failed:%d", errCode);
584         goto END;
585     }
586     errCode = SQLiteUtils::ExecuteRawSQL(db, WAL_MODE_SQL);
587     if (errCode != E_OK) {
588         LOGE("Set journal mode failed: %d", errCode);
589     }
590 
591 END:
592     SQLiteUtils::ResetStatement(statement, true, errCode);
593     return errCode;
594 }
595 
CreateMetaDatabase(const std::string & metaDbPath)596 int SQLiteUtils::CreateMetaDatabase(const std::string &metaDbPath)
597 {
598     OpenDbProperties metaProperties {metaDbPath, true, false};
599     sqlite3 *db = nullptr;
600     int errCode = SQLiteUtils::OpenDatabase(metaProperties, db);
601     if (errCode != E_OK) {
602         LOGE("[CreateMetaDatabase] Failed to create the meta database[%d]", errCode);
603     }
604     if (db != nullptr) {
605         (void)sqlite3_close_v2(db);
606         db = nullptr;
607     }
608     return errCode;
609 }
610 
CheckIntegrity(sqlite3 * db,const std::string & sql)611 int SQLiteUtils::CheckIntegrity(sqlite3 *db, const std::string &sql)
612 {
613     sqlite3_stmt *statement = nullptr;
614     int errCode = SQLiteUtils::GetStatement(db, sql, statement);
615     if (errCode != E_OK) {
616         LOGE("Prepare the integrity check statement error:%d", errCode);
617         return errCode;
618     }
619     int resultCnt = 0;
620     bool checkResultOK = false;
621     do {
622         errCode = SQLiteUtils::StepWithRetry(statement);
623         if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)) {
624             break;
625         } else if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_ROW)) {
626             auto result = reinterpret_cast<const char *>(sqlite3_column_text(statement, 0));
627             if (result == nullptr) {
628                 continue;
629             }
630             resultCnt = (resultCnt > 1) ? resultCnt : (resultCnt + 1);
631             if (strcmp(result, "ok") == 0) {
632                 checkResultOK = true;
633             }
634         } else {
635             checkResultOK = false;
636             LOGW("Step for the integrity check failed:%d", errCode);
637             break;
638         }
639     } while (true);
640     if (resultCnt == 1 && checkResultOK) {
641         errCode = E_OK;
642     } else {
643         errCode = -E_INVALID_PASSWD_OR_CORRUPTED_DB;
644     }
645     SQLiteUtils::ResetStatement(statement, true, errCode);
646     return errCode;
647 }
648 #ifdef RELATIONAL_STORE
649 namespace { // anonymous namespace for schema analysis
AnalysisSchemaSqlAndTrigger(sqlite3 * db,const std::string & tableName,TableInfo & table)650 int AnalysisSchemaSqlAndTrigger(sqlite3 *db, const std::string &tableName, TableInfo &table)
651 {
652     std::string sql = "select type, sql from sqlite_master where tbl_name = ?";
653     sqlite3_stmt *statement = nullptr;
654     int errCode = SQLiteUtils::GetStatement(db, sql, statement);
655     if (errCode != E_OK) {
656         LOGE("[AnalysisSchema] Prepare the analysis schema sql and trigger statement error:%d", errCode);
657         return errCode;
658     }
659     errCode = SQLiteUtils::BindTextToStatement(statement, 1, tableName);
660     if (errCode != E_OK) {
661         LOGE("[AnalysisSchema] Bind table name failed:%d", errCode);
662         SQLiteUtils::ResetStatement(statement, true, errCode);
663         return errCode;
664     }
665 
666     errCode = -E_NOT_FOUND;
667     std::vector<std::string> triggerList;
668     do {
669         int err = SQLiteUtils::StepWithRetry(statement);
670         if (err == SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)) {
671             break;
672         } else if (err == SQLiteUtils::MapSQLiteErrno(SQLITE_ROW)) {
673             errCode = E_OK;
674             std::string type;
675             (void) SQLiteUtils::GetColumnTextValue(statement, 0, type);
676             if (type == "table") {
677                 std::string createTableSql;
678                 (void) SQLiteUtils::GetColumnTextValue(statement, 1, createTableSql); // 1 means create table sql
679                 table.SetCreateTableSql(createTableSql);
680             }
681         } else {
682             LOGE("[AnalysisSchema] Step for the analysis create table sql and trigger failed:%d", err);
683             errCode = SQLiteUtils::MapSQLiteErrno(err);
684             break;
685         }
686     } while (true);
687     SQLiteUtils::ResetStatement(statement, true, errCode);
688     return errCode;
689 }
690 
GetSchemaIndexList(sqlite3 * db,const std::string & tableName,std::vector<std::string> & indexList,std::vector<std::string> & uniqueList)691 int GetSchemaIndexList(sqlite3 *db, const std::string &tableName, std::vector<std::string> &indexList,
692     std::vector<std::string> &uniqueList)
693 {
694     std::string sql = "pragma index_list(" + tableName + ")";
695     sqlite3_stmt *statement = nullptr;
696     int errCode = SQLiteUtils::GetStatement(db, sql, statement);
697     if (errCode != E_OK) {
698         LOGE("[AnalysisSchema] Prepare the get schema index list statement error:%d", errCode);
699         return errCode;
700     }
701 
702     do {
703         errCode = SQLiteUtils::StepWithRetry(statement);
704         if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)) {
705             errCode = E_OK;
706             break;
707         } else if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_ROW)) {
708             std::string indexName;
709             (void) SQLiteUtils::GetColumnTextValue(statement, 1, indexName);  // 1 means index name
710             std::string origin;
711             (void) SQLiteUtils::GetColumnTextValue(statement, 3, origin);  // 3 means index type, whether unique
712             if (origin == "c") { // 'c' means index created by user declare
713                 indexList.push_back(indexName);
714             } else if (origin == "u") { // 'u' means an unique define
715                 uniqueList.push_back(indexName);
716             }
717         } else {
718             LOGW("[AnalysisSchema] Step for the get schema index list failed:%d", errCode);
719             break;
720         }
721     } while (true);
722     SQLiteUtils::ResetStatement(statement, true, errCode);
723     return errCode;
724 }
725 
AnalysisSchemaIndexDefine(sqlite3 * db,const std::string & indexName,CompositeFields & indexDefine)726 int AnalysisSchemaIndexDefine(sqlite3 *db, const std::string &indexName, CompositeFields &indexDefine)
727 {
728     auto sql = "pragma index_info(" + indexName + ")";
729     sqlite3_stmt *statement = nullptr;
730     int errCode = SQLiteUtils::GetStatement(db, sql, statement);
731     if (errCode != E_OK) {
732         LOGE("[AnalysisSchema] Prepare the analysis schema index statement error:%d", errCode);
733         return errCode;
734     }
735 
736     do {
737         errCode = SQLiteUtils::StepWithRetry(statement);
738         if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)) {
739             errCode = E_OK;
740             break;
741         } else if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_ROW)) {
742             std::string indexField;
743             (void) SQLiteUtils::GetColumnTextValue(statement, 2, indexField);  // 2 means index's column name.
744             indexDefine.push_back(indexField);
745         } else {
746             LOGW("[AnalysisSchema] Step for the analysis schema index failed:%d", errCode);
747             break;
748         }
749     } while (true);
750 
751     SQLiteUtils::ResetStatement(statement, true, errCode);
752     return errCode;
753 }
754 
AnalysisSchemaIndex(sqlite3 * db,const std::string & tableName,TableInfo & table)755 int AnalysisSchemaIndex(sqlite3 *db, const std::string &tableName, TableInfo &table)
756 {
757     std::vector<std::string> indexList;
758     std::vector<std::string> uniqueList;
759     int errCode = GetSchemaIndexList(db, tableName, indexList, uniqueList);
760     if (errCode != E_OK) {
761         LOGE("[AnalysisSchema] get schema index list failed.");
762         return errCode;
763     }
764 
765     for (const auto &indexName : indexList) {
766         CompositeFields indexDefine;
767         errCode = AnalysisSchemaIndexDefine(db, indexName, indexDefine);
768         if (errCode != E_OK) {
769             LOGE("[AnalysisSchema] analysis schema index columns failed.");
770             return errCode;
771         }
772         table.AddIndexDefine(indexName, indexDefine);
773     }
774 
775     std::vector<CompositeFields> uniques;
776     for (const auto &uniqueName : uniqueList) {
777         CompositeFields uniqueDefine;
778         errCode = AnalysisSchemaIndexDefine(db, uniqueName, uniqueDefine);
779         if (errCode != E_OK) {
780             LOGE("[AnalysisSchema] analysis schema unique columns failed.");
781             return errCode;
782         }
783         uniques.push_back(uniqueDefine);
784     }
785     table.SetUniqueDefine(uniques);
786     return E_OK;
787 }
788 
SetFieldInfo(sqlite3_stmt * statement,TableInfo & table)789 int SetFieldInfo(sqlite3_stmt *statement, TableInfo &table)
790 {
791     FieldInfo field;
792     field.SetColumnId(sqlite3_column_int(statement, 0));  // 0 means column id index
793 
794     std::string tmpString;
795     (void) SQLiteUtils::GetColumnTextValue(statement, 1, tmpString);  // 1 means column name index
796     if (!DBCommon::CheckIsAlnumAndUnderscore(tmpString)) {
797         LOGE("[AnalysisSchema] unsupported field name.");
798         return -E_NOT_SUPPORT;
799     }
800     field.SetFieldName(tmpString);
801 
802     (void) SQLiteUtils::GetColumnTextValue(statement, 2, tmpString);  // 2 means datatype index
803     field.SetDataType(tmpString);
804 
805     field.SetNotNull(static_cast<bool>(sqlite3_column_int64(statement, 3)));  // 3 means whether null index
806 
807     (void) SQLiteUtils::GetColumnTextValue(statement, 4, tmpString);  // 4 means default value index
808     if (!tmpString.empty()) {
809         field.SetDefaultValue(tmpString);
810     }
811 
812     int keyIndex = sqlite3_column_int64(statement, 5); // 5 means primary key index
813     if (keyIndex != 0) {  // not 0 means is a primary key
814         table.SetPrimaryKey(field.GetFieldName(), keyIndex);
815     }
816     table.AddField(field);
817     return E_OK;
818 }
819 
AnalysisSchemaFieldDefine(sqlite3 * db,const std::string & tableName,TableInfo & table)820 int AnalysisSchemaFieldDefine(sqlite3 *db, const std::string &tableName, TableInfo &table)
821 {
822     std::string sql = "pragma table_info(" + tableName + ")";
823     sqlite3_stmt *statement = nullptr;
824     int errCode = SQLiteUtils::GetStatement(db, sql, statement);
825     if (errCode != E_OK) {
826         LOGE("[AnalysisSchema] Prepare the analysis schema field statement error:%d", errCode);
827         return errCode;
828     }
829 
830     do {
831         errCode = SQLiteUtils::StepWithRetry(statement);
832         if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)) {
833             errCode = E_OK;
834             break;
835         } else if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_ROW)) {
836             errCode = SetFieldInfo(statement, table);
837             if (errCode != E_OK) {
838                 break;
839             }
840         } else {
841             LOGW("[AnalysisSchema] Step for the analysis schema field failed:%d", errCode);
842             break;
843         }
844     } while (true);
845 
846     if (table.GetPrimaryKey().empty()) {
847         table.SetPrimaryKey("rowid", 1);
848     }
849 
850     SQLiteUtils::ResetStatement(statement, true, errCode);
851     return errCode;
852 }
853 } // end of anonymous namespace for schema analysis
854 
AnalysisSchema(sqlite3 * db,const std::string & tableName,TableInfo & table)855 int SQLiteUtils::AnalysisSchema(sqlite3 *db, const std::string &tableName, TableInfo &table)
856 {
857     if (db == nullptr) {
858         return -E_INVALID_DB;
859     }
860 
861     if (!DBCommon::CheckIsAlnumAndUnderscore(tableName)) {
862         LOGE("[AnalysisSchema] unsupported table name.");
863         return -E_NOT_SUPPORT;
864     }
865 
866     int errCode = AnalysisSchemaSqlAndTrigger(db, tableName, table);
867     if (errCode != E_OK) {
868         LOGE("[AnalysisSchema] Analysis sql and trigger failed. errCode = [%d]", errCode);
869         return errCode;
870     }
871 
872     errCode = AnalysisSchemaIndex(db, tableName, table);
873     if (errCode != E_OK) {
874         LOGE("[AnalysisSchema] Analysis index failed.");
875         return errCode;
876     }
877 
878     errCode = AnalysisSchemaFieldDefine(db, tableName, table);
879     if (errCode != E_OK) {
880         LOGE("[AnalysisSchema] Analysis field failed.");
881         return errCode;
882     }
883 
884     table.SetTableName(tableName);
885     return E_OK;
886 }
887 #endif
888 #ifndef OMIT_ENCRYPT
ExportDatabase(sqlite3 * db,CipherType type,const CipherPassword & passwd,const std::string & newDbName)889 int SQLiteUtils::ExportDatabase(sqlite3 *db, CipherType type, const CipherPassword &passwd,
890     const std::string &newDbName)
891 {
892     if (db == nullptr) {
893         return -E_INVALID_DB;
894     }
895 
896     int errCode = AttachNewDatabase(db, type, passwd, newDbName);
897     if (errCode != E_OK) {
898         LOGE("Attach New Db fail!");
899         return errCode;
900     }
901     errCode = SQLiteUtils::ExecuteRawSQL(db, EXPORT_BACKUP_SQL);
902     if (errCode != E_OK) {
903         LOGE("Execute the SQLite export failed:%d", errCode);
904     }
905 
906     int detachError = SQLiteUtils::ExecuteRawSQL(db, DETACH_BACKUP_SQL);
907     if (errCode == E_OK) {
908         errCode = detachError;
909         if (detachError != E_OK) {
910             LOGE("Execute the SQLite detach failed:%d", errCode);
911         }
912     }
913     return errCode;
914 }
915 
Rekey(sqlite3 * db,const CipherPassword & passwd)916 int SQLiteUtils::Rekey(sqlite3 *db, const CipherPassword &passwd)
917 {
918     if (db == nullptr) {
919         return -E_INVALID_DB;
920     }
921 
922     int errCode = sqlite3_rekey(db, static_cast<const void *>(passwd.GetData()), static_cast<int>(passwd.GetSize()));
923     if (errCode != E_OK) {
924         LOGE("SQLite rekey failed:(%d)", errCode);
925         return SQLiteUtils::MapSQLiteErrno(errCode);
926     }
927 
928     return E_OK;
929 }
930 #else
ExportDatabase(sqlite3 * db,CipherType type,const CipherPassword & passwd,const std::string & newDbName)931 int SQLiteUtils::ExportDatabase(sqlite3 *db, CipherType type, const CipherPassword &passwd,
932     const std::string &newDbName)
933 {
934     (void)db;
935     (void)type;
936     (void)passwd;
937     (void)newDbName;
938     return -E_NOT_SUPPORT;
939 }
940 
Rekey(sqlite3 * db,const CipherPassword & passwd)941 int SQLiteUtils::Rekey(sqlite3 *db, const CipherPassword &passwd)
942 {
943     (void)db;
944     (void)passwd;
945     return -E_NOT_SUPPORT;
946 }
947 #endif
948 
GetVersion(const OpenDbProperties & properties,int & version)949 int SQLiteUtils::GetVersion(const OpenDbProperties &properties, int &version)
950 {
951     if (properties.uri.empty()) {
952         return -E_INVALID_ARGS;
953     }
954 
955     sqlite3 *dbTemp = nullptr;
956     // Please make sure the database file exists and is working properly
957     std::string fileUrl = DBConstant::SQLITE_URL_PRE + properties.uri;
958     int errCode = sqlite3_open_v2(fileUrl.c_str(), &dbTemp, SQLITE_OPEN_URI | SQLITE_OPEN_READONLY, nullptr);
959     if (errCode != SQLITE_OK) {
960         errCode = SQLiteUtils::MapSQLiteErrno(errCode);
961         LOGE("Open database failed: %d, sys:%d", errCode, errno);
962         goto END;
963     }
964     // in memory mode no need cipher
965     if (!properties.isMemDb) {
966         errCode = SQLiteUtils::SetKey(dbTemp, properties.cipherType, properties.passwd, false,
967             properties.iterTimes);
968         if (errCode != E_OK) {
969             LOGE("Set key failed: %d", errCode);
970             goto END;
971         }
972     }
973 
974     errCode = GetVersion(dbTemp, version);
975 
976 END:
977     if (dbTemp != nullptr) {
978         (void)sqlite3_close_v2(dbTemp);
979         dbTemp = nullptr;
980     }
981     return errCode;
982 }
983 
GetVersion(sqlite3 * db,int & version)984 int SQLiteUtils::GetVersion(sqlite3 *db, int &version)
985 {
986     if (db == nullptr) {
987         return -E_INVALID_DB;
988     }
989 
990     std::string strSql = "PRAGMA user_version;";
991     sqlite3_stmt *statement = nullptr;
992     int errCode = sqlite3_prepare(db, strSql.c_str(), -1, &statement, nullptr);
993     if (errCode != SQLITE_OK || statement == nullptr) {
994         LOGE("[SqlUtil][GetVer] sqlite3_prepare failed.");
995         errCode = SQLiteUtils::MapSQLiteErrno(errCode);
996         return errCode;
997     }
998 
999     if (sqlite3_step(statement) == SQLITE_ROW) {
1000         // Get pragma user_version at first column
1001         version = sqlite3_column_int(statement, 0);
1002     } else {
1003         LOGE("[SqlUtil][GetVer] Get db user_version failed.");
1004         errCode = SQLiteUtils::MapSQLiteErrno(SQLITE_ERROR);
1005     }
1006 
1007     SQLiteUtils::ResetStatement(statement, true, errCode);
1008     return errCode;
1009 }
1010 
GetJournalMode(sqlite3 * db,std::string & mode)1011 int SQLiteUtils::GetJournalMode(sqlite3 *db, std::string &mode)
1012 {
1013     if (db == nullptr) {
1014         return -E_INVALID_DB;
1015     }
1016 
1017     std::string sql = "PRAGMA journal_mode;";
1018     sqlite3_stmt *statement = nullptr;
1019     int errCode = SQLiteUtils::GetStatement(db, sql, statement);
1020     if (errCode != E_OK || statement == nullptr) {
1021         return errCode;
1022     }
1023 
1024     errCode = SQLiteUtils::StepWithRetry(statement);
1025     if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_ROW)) {
1026         errCode = SQLiteUtils::GetColumnTextValue(statement, 0, mode);
1027     } else {
1028         LOGE("[SqlUtil][GetJournal] Get db journal_mode failed.");
1029     }
1030 
1031     SQLiteUtils::ResetStatement(statement, true, errCode);
1032     return errCode;
1033 }
1034 
SetUserVer(const OpenDbProperties & properties,int version)1035 int SQLiteUtils::SetUserVer(const OpenDbProperties &properties, int version)
1036 {
1037     if (properties.uri.empty()) {
1038         return -E_INVALID_ARGS;
1039     }
1040 
1041     // Please make sure the database file exists and is working properly
1042     sqlite3 *db = nullptr;
1043     int errCode = SQLiteUtils::OpenDatabase(properties, db);
1044     if (errCode != E_OK) {
1045         return errCode;
1046     }
1047 
1048     // Set user version
1049     errCode = SQLiteUtils::SetUserVer(db, version);
1050     if (errCode != E_OK) {
1051         LOGE("Set user version fail: %d", errCode);
1052         goto END;
1053     }
1054 
1055 END:
1056     if (db != nullptr) {
1057         (void)sqlite3_close_v2(db);
1058         db = nullptr;
1059     }
1060 
1061     return errCode;
1062 }
1063 
SetUserVer(sqlite3 * db,int version)1064 int SQLiteUtils::SetUserVer(sqlite3 *db, int version)
1065 {
1066     if (db == nullptr) {
1067         return -E_INVALID_DB;
1068     }
1069     std::string userVersionSql = "PRAGMA user_version=" + std::to_string(version) + ";";
1070     return SQLiteUtils::ExecuteRawSQL(db, userVersionSql);
1071 }
1072 
MapSQLiteErrno(int errCode)1073 int SQLiteUtils::MapSQLiteErrno(int errCode)
1074 {
1075     if (errCode == SQLITE_OK) {
1076         return E_OK;
1077     } else if (errCode == SQLITE_IOERR) {
1078         if (errno == EKEYREVOKED) {
1079             return -E_EKEYREVOKED;
1080         }
1081     } else if (errCode == SQLITE_CORRUPT || errCode == SQLITE_NOTADB) {
1082         return -E_INVALID_PASSWD_OR_CORRUPTED_DB;
1083     } else if (errCode == SQLITE_LOCKED || errCode == SQLITE_BUSY) {
1084         return -E_BUSY;
1085     } else if (errCode == SQLITE_ERROR && errno == EKEYREVOKED) {
1086         return -E_EKEYREVOKED;
1087     } else if (errCode == SQLITE_AUTH) {
1088         return -E_DENIED_SQL;
1089     }
1090     return -errCode;
1091 }
1092 
SetBusyTimeout(sqlite3 * db,int timeout)1093 int SQLiteUtils::SetBusyTimeout(sqlite3 *db, int timeout)
1094 {
1095     if (db == nullptr) {
1096         return -E_INVALID_DB;
1097     }
1098 
1099     // Set the default busy handler to retry automatically before returning SQLITE_BUSY.
1100     int errCode = sqlite3_busy_timeout(db, timeout);
1101     if (errCode != SQLITE_OK) {
1102         LOGE("[SQLite] set busy timeout failed:%d", errCode);
1103     }
1104 
1105     return SQLiteUtils::MapSQLiteErrno(errCode);
1106 }
1107 
1108 #ifndef OMIT_ENCRYPT
ExportDatabase(const std::string & srcFile,CipherType type,const CipherPassword & srcPasswd,const std::string & targetFile,const CipherPassword & passwd)1109 int SQLiteUtils::ExportDatabase(const std::string &srcFile, CipherType type, const CipherPassword &srcPasswd,
1110     const std::string &targetFile, const CipherPassword &passwd)
1111 {
1112     std::vector<std::string> createTableSqls;
1113     OpenDbProperties option = {srcFile, true, false, createTableSqls, type, srcPasswd};
1114     sqlite3 *db = nullptr;
1115     int errCode = SQLiteUtils::OpenDatabase(option, db);
1116     if (errCode != E_OK) {
1117         LOGE("Open db error while exporting:%d", errCode);
1118         return errCode;
1119     }
1120 
1121     errCode = SQLiteUtils::ExportDatabase(db, type, passwd, targetFile);
1122     if (db != nullptr) {
1123         (void)sqlite3_close_v2(db);
1124         db = nullptr;
1125     }
1126     return errCode;
1127 }
1128 #else
ExportDatabase(const std::string & srcFile,CipherType type,const CipherPassword & srcPasswd,const std::string & targetFile,const CipherPassword & passwd)1129 int SQLiteUtils::ExportDatabase(const std::string &srcFile, CipherType type, const CipherPassword &srcPasswd,
1130     const std::string &targetFile, const CipherPassword &passwd)
1131 {
1132     (void)srcFile;
1133     (void)type;
1134     (void)srcPasswd;
1135     (void)targetFile;
1136     (void)passwd;
1137     return -E_NOT_SUPPORT;
1138 }
1139 #endif
1140 
SaveSchema(const OpenDbProperties & properties)1141 int SQLiteUtils::SaveSchema(const OpenDbProperties &properties)
1142 {
1143     if (properties.uri.empty()) {
1144         return -E_INVALID_ARGS;
1145     }
1146 
1147     sqlite3 *db = nullptr;
1148     int errCode = OpenDatabase(properties, db);
1149     if (errCode != E_OK) {
1150         return errCode;
1151     }
1152 
1153     errCode = SaveSchema(db, properties.schema);
1154     (void)sqlite3_close_v2(db);
1155     db = nullptr;
1156     return errCode;
1157 }
1158 
SaveSchema(sqlite3 * db,const std::string & strSchema)1159 int SQLiteUtils::SaveSchema(sqlite3 *db, const std::string &strSchema)
1160 {
1161     if (db == nullptr) {
1162         return -E_INVALID_DB;
1163     }
1164 
1165     sqlite3_stmt *statement = nullptr;
1166     std::string sql = "INSERT OR REPLACE INTO meta_data VALUES(?,?);";
1167     int errCode = GetStatement(db, sql, statement);
1168     if (errCode != E_OK) {
1169         return errCode;
1170     }
1171 
1172     Key schemaKey;
1173     DBCommon::StringToVector(DBConstant::SCHEMA_KEY, schemaKey);
1174     errCode = BindBlobToStatement(statement, BIND_KEY_INDEX, schemaKey, false);
1175     if (errCode != E_OK) {
1176         ResetStatement(statement, true, errCode);
1177         return errCode;
1178     }
1179 
1180     Value schemaValue;
1181     DBCommon::StringToVector(strSchema, schemaValue);
1182     errCode = BindBlobToStatement(statement, BIND_VAL_INDEX, schemaValue, false);
1183     if (errCode != E_OK) {
1184         ResetStatement(statement, true, errCode);
1185         return errCode;
1186     }
1187 
1188     errCode = StepWithRetry(statement); // memory db does not support schema
1189     if (errCode != MapSQLiteErrno(SQLITE_DONE)) {
1190         LOGE("[SqlUtil][SetSchema] StepWithRetry fail, errCode=%d.", errCode);
1191         ResetStatement(statement, true, errCode);
1192         return errCode;
1193     }
1194     errCode = E_OK;
1195     ResetStatement(statement, true, errCode);
1196     return errCode;
1197 }
1198 
GetSchema(const OpenDbProperties & properties,std::string & strSchema)1199 int SQLiteUtils::GetSchema(const OpenDbProperties &properties, std::string &strSchema)
1200 {
1201     sqlite3 *db = nullptr;
1202     int errCode = OpenDatabase(properties, db);
1203     if (errCode != E_OK) {
1204         return errCode;
1205     }
1206 
1207     int version = 0;
1208     errCode = GetVersion(db, version);
1209     if (version <= 0 || errCode != E_OK) {
1210         // if version does exist, it represents database is error
1211         (void)sqlite3_close_v2(db);
1212         db = nullptr;
1213         return -E_INVALID_VERSION;
1214     }
1215 
1216     errCode = GetSchema(db, strSchema);
1217     (void)sqlite3_close_v2(db);
1218     db = nullptr;
1219     return errCode;
1220 }
1221 
GetSchema(sqlite3 * db,std::string & strSchema)1222 int SQLiteUtils::GetSchema(sqlite3 *db, std::string &strSchema)
1223 {
1224     if (db == nullptr) {
1225         return -E_INVALID_DB;
1226     }
1227 
1228     sqlite3_stmt *statement = nullptr;
1229     std::string sql = "SELECT value FROM meta_data WHERE key=?;";
1230     int errCode = GetStatement(db, sql, statement);
1231     if (errCode != E_OK) {
1232         return errCode;
1233     }
1234 
1235     Key schemakey;
1236     DBCommon::StringToVector(DBConstant::SCHEMA_KEY, schemakey);
1237     errCode = BindBlobToStatement(statement, 1, schemakey, false);
1238     if (errCode != E_OK) {
1239         ResetStatement(statement, true, errCode);
1240         return errCode;
1241     }
1242 
1243     errCode = StepWithRetry(statement); // memory db does not support schema
1244     if (errCode == MapSQLiteErrno(SQLITE_DONE)) {
1245         ResetStatement(statement, true, errCode);
1246         return -E_NOT_FOUND;
1247     } else if (errCode != MapSQLiteErrno(SQLITE_ROW)) {
1248         ResetStatement(statement, true, errCode);
1249         return errCode;
1250     }
1251 
1252     Value schemaValue;
1253     errCode = GetColumnBlobValue(statement, 0, schemaValue);
1254     if (errCode != E_OK) {
1255         ResetStatement(statement, true, errCode);
1256         return errCode;
1257     }
1258     DBCommon::VectorToString(schemaValue, strSchema);
1259     ResetStatement(statement, true, errCode);
1260     return errCode;
1261 }
1262 
IncreaseIndex(sqlite3 * db,const IndexName & name,const IndexInfo & info,SchemaType type,uint32_t skipSize)1263 int SQLiteUtils::IncreaseIndex(sqlite3 *db, const IndexName &name, const IndexInfo &info, SchemaType type,
1264     uint32_t skipSize)
1265 {
1266     if (db == nullptr) {
1267         LOGE("[IncreaseIndex] Sqlite DB not exists.");
1268         return -E_INVALID_DB;
1269     }
1270     if (name.empty()) {
1271         LOGE("[IncreaseIndex] Name can not be empty.");
1272         return -E_NOT_PERMIT;
1273     }
1274     if (info.empty()) {
1275         LOGE("[IncreaseIndex] Info can not be empty.");
1276         return -E_NOT_PERMIT;
1277     }
1278     std::string indexName = SchemaUtils::FieldPathString(name);
1279     std::string sqlCommand = "CREATE INDEX IF NOT EXISTS '" + indexName + "' ON sync_data (";
1280     for (uint32_t i = 0; i < info.size(); i++) {
1281         if (i != 0) {
1282             sqlCommand += ", ";
1283         }
1284         std::string extractSql = SchemaObject::GenerateExtractSQL(type, info[i].first, info[i].second,
1285             skipSize);
1286         if (extractSql.empty()) { // Unlikely
1287             LOGE("[IncreaseIndex] GenerateExtractSQL fail at field=%u.", i);
1288             return -E_INTERNAL_ERROR;
1289         }
1290         sqlCommand += extractSql;
1291     }
1292     sqlCommand += ") WHERE (flag&0x01=0);";
1293     return SQLiteUtils::ExecuteRawSQL(db, sqlCommand);
1294 }
1295 
ChangeIndex(sqlite3 * db,const IndexName & name,const IndexInfo & info,SchemaType type,uint32_t skipSize)1296 int SQLiteUtils::ChangeIndex(sqlite3 *db, const IndexName &name, const IndexInfo &info, SchemaType type,
1297     uint32_t skipSize)
1298 {
1299     // Currently we change index by drop it then create it, SQLite "REINDEX" may be used in the future
1300     int errCode = DecreaseIndex(db, name);
1301     if (errCode != OK) {
1302         LOGE("[ChangeIndex] Decrease fail=%d.", errCode);
1303         return errCode;
1304     }
1305     errCode = IncreaseIndex(db, name, info, type, skipSize);
1306     if (errCode != OK) {
1307         LOGE("[ChangeIndex] Increase fail=%d.", errCode);
1308         return errCode;
1309     }
1310     return E_OK;
1311 }
1312 
DecreaseIndex(sqlite3 * db,const IndexName & name)1313 int SQLiteUtils::DecreaseIndex(sqlite3 *db, const IndexName &name)
1314 {
1315     if (db == nullptr) {
1316         LOGE("[DecreaseIndex] Sqlite DB not exists.");
1317         return -E_INVALID_DB;
1318     }
1319     if (name.empty()) {
1320         LOGE("[DecreaseIndex] Name can not be empty.");
1321         return -E_NOT_PERMIT;
1322     }
1323     std::string indexName = SchemaUtils::FieldPathString(name);
1324     std::string sqlCommand = "DROP INDEX IF EXISTS '" + indexName + "';";
1325     return ExecuteRawSQL(db, sqlCommand);
1326 }
1327 
RegisterJsonFunctions(sqlite3 * db)1328 int SQLiteUtils::RegisterJsonFunctions(sqlite3 *db)
1329 {
1330     if (db == nullptr) {
1331         LOGE("Sqlite DB not exists.");
1332         return -E_INVALID_DB;
1333     }
1334     int errCode = sqlite3_create_function_v2(db, "calc_hash_key", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC,
1335         nullptr, &CalcHashKey, nullptr, nullptr, nullptr);
1336     if (errCode != SQLITE_OK) {
1337         LOGE("sqlite3_create_function_v2 about calc_hash_key returned %d", errCode);
1338         return MapSQLiteErrno(errCode);
1339     }
1340 #ifdef USING_DB_JSON_EXTRACT_AUTOMATICALLY
1341     errCode = ExecuteRawSQL(db, JSON_EXTRACT_BY_PATH_TEST_CREATED);
1342     if (errCode == E_OK) {
1343         LOGI("json_extract_by_path already created.");
1344     } else {
1345         // Specify need 3 parameter in json_extract_by_path function
1346         errCode = sqlite3_create_function_v2(db, "json_extract_by_path", 3, SQLITE_UTF8 | SQLITE_DETERMINISTIC,
1347             nullptr, &JsonExtractByPath, nullptr, nullptr, nullptr);
1348         if (errCode != SQLITE_OK) {
1349             LOGE("sqlite3_create_function_v2 about json_extract_by_path returned %d", errCode);
1350             return MapSQLiteErrno(errCode);
1351         }
1352     }
1353 #endif
1354     return E_OK;
1355 }
1356 
1357 namespace {
SchemaObjectDestructor(SchemaObject * inObject)1358 void SchemaObjectDestructor(SchemaObject *inObject)
1359 {
1360     delete inObject;
1361     inObject = nullptr;
1362 }
1363 }
1364 #ifdef RELATIONAL_STORE
RegisterCalcHash(sqlite3 * db)1365 int SQLiteUtils::RegisterCalcHash(sqlite3 *db)
1366 {
1367     TransactFunc func;
1368     func.xFunc = &CalcHashKey;
1369     return SQLiteUtils::RegisterFunction(db, "calc_hash", 1, nullptr, func);
1370 }
1371 
GetSysTime(sqlite3_context * ctx,int argc,sqlite3_value ** argv)1372 void SQLiteUtils::GetSysTime(sqlite3_context *ctx, int argc, sqlite3_value **argv)
1373 {
1374     if (ctx == nullptr || argc != 1 || argv == nullptr) {
1375         LOGE("Parameter does not meet restrictions.");
1376         return;
1377     }
1378 
1379     sqlite3_result_int64(ctx, (sqlite3_int64)TimeHelper::GetSysCurrentTime());
1380 }
1381 
RegisterGetSysTime(sqlite3 * db)1382 int SQLiteUtils::RegisterGetSysTime(sqlite3 *db)
1383 {
1384     TransactFunc func;
1385     func.xFunc = &GetSysTime;
1386     return SQLiteUtils::RegisterFunction(db, "get_sys_time", 1, nullptr, func);
1387 }
1388 
CreateRelationalMetaTable(sqlite3 * db)1389 int SQLiteUtils::CreateRelationalMetaTable(sqlite3 *db)
1390 {
1391     std::string sql =
1392         "CREATE TABLE IF NOT EXISTS " + DBConstant::RELATIONAL_PREFIX + "metadata(" \
1393         "key    BLOB PRIMARY KEY NOT NULL," \
1394         "value  BLOB);";
1395     int errCode = SQLiteUtils::ExecuteRawSQL(db, sql);
1396     if (errCode != E_OK) {
1397         LOGE("[SQLite] execute create table sql failed, err=%d", errCode);
1398     }
1399     return errCode;
1400 }
1401 
CreateSameStuTable(sqlite3 * db,const TableInfo & baseTbl,const std::string & newTableName)1402 int SQLiteUtils::CreateSameStuTable(sqlite3 *db, const TableInfo &baseTbl, const std::string &newTableName)
1403 {
1404     std::string sql = "CREATE TABLE IF NOT EXISTS " + newTableName + "(";
1405     const std::map<FieldName, FieldInfo> &fields = baseTbl.GetFields();
1406     for (uint32_t cid = 0; cid < fields.size(); ++cid) {
1407         std::string fieldName = baseTbl.GetFieldName(cid);
1408         sql += fieldName + " " + fields.at(fieldName).GetDataType();
1409         if (fields.at(fieldName).IsNotNull()) {
1410             sql += " NOT NULL";
1411         }
1412         if (fields.at(fieldName).HasDefaultValue()) {
1413             sql += " DEFAULT " + fields.at(fieldName).GetDefaultValue();
1414         }
1415         sql += ",";
1416     }
1417     // base table has primary key
1418     if (!(baseTbl.GetPrimaryKey().size() == 1 && baseTbl.GetPrimaryKey().at(0) == "rowid")) {
1419         sql += " PRIMARY KEY (";
1420         for (const auto &it : baseTbl.GetPrimaryKey()) {
1421             sql += it.second + ",";
1422         }
1423         sql.pop_back();
1424         sql += "),";
1425     }
1426     sql.pop_back();
1427     sql += ");";
1428     int errCode = SQLiteUtils::ExecuteRawSQL(db, sql);
1429     if (errCode != E_OK) {
1430         LOGE("[SQLite] execute create table sql failed");
1431     }
1432     return errCode;
1433 }
1434 
CloneIndexes(sqlite3 * db,const std::string & oriTableName,const std::string & newTableName)1435 int SQLiteUtils::CloneIndexes(sqlite3 *db, const std::string &oriTableName, const std::string &newTableName)
1436 {
1437     std::string sql =
1438         "SELECT 'CREATE ' || CASE WHEN il.'unique' THEN 'UNIQUE ' ELSE '' END || 'INDEX IF NOT EXISTS ' || '" +
1439             newTableName + "_' || il.name || ' ON ' || '" + newTableName +
1440             "' || '(' || GROUP_CONCAT(ii.name) || ');' "
1441         "FROM sqlite_master AS m,"
1442             "pragma_index_list(m.name) AS il,"
1443             "pragma_index_info(il.name) AS ii "
1444         "WHERE m.type='table' AND m.name='" + oriTableName + "' AND il.origin='c' "
1445         "GROUP BY il.name;";
1446     sqlite3_stmt *stmt = nullptr;
1447     int errCode = SQLiteUtils::GetStatement(db, sql, stmt);
1448     if (errCode != E_OK) {
1449         LOGE("Prepare the clone sql failed:%d", errCode);
1450         return errCode;
1451     }
1452 
1453     std::vector<std::string> indexes;
1454     while (true) {
1455         errCode = SQLiteUtils::StepWithRetry(stmt, false);
1456         if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_ROW)) {
1457             std::string indexSql;
1458             (void)GetColumnTextValue(stmt, 0, indexSql);
1459             indexes.emplace_back(indexSql);
1460             continue;
1461         }
1462         if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)) {
1463             errCode = E_OK;
1464         }
1465         (void)ResetStatement(stmt, true, errCode);
1466         break;
1467     }
1468 
1469     if (errCode != E_OK) {
1470         return errCode;
1471     }
1472 
1473     for (const auto &it : indexes) {
1474         errCode = SQLiteUtils::ExecuteRawSQL(db, it);
1475         if (errCode != E_OK) {
1476             LOGE("[SQLite] execute clone index sql failed");
1477         }
1478     }
1479     return errCode;
1480 }
1481 
GetRelationalSchema(sqlite3 * db,std::string & schema)1482 int SQLiteUtils::GetRelationalSchema(sqlite3 *db, std::string &schema)
1483 {
1484     if (db == nullptr) {
1485         return -E_INVALID_DB;
1486     }
1487 
1488     sqlite3_stmt *statement = nullptr;
1489     std::string sql = "SELECT value FROM " + DBConstant::RELATIONAL_PREFIX + "metadata WHERE key=?;";
1490     int errCode = GetStatement(db, sql, statement);
1491     if (errCode != E_OK) {
1492         return errCode;
1493     }
1494 
1495     Key schemakey;
1496     DBCommon::StringToVector(DBConstant::RELATIONAL_SCHEMA_KEY, schemakey);
1497     errCode = BindBlobToStatement(statement, 1, schemakey, false);
1498     if (errCode != E_OK) {
1499         ResetStatement(statement, true, errCode);
1500         return errCode;
1501     }
1502 
1503     errCode = StepWithRetry(statement);
1504     if (errCode == MapSQLiteErrno(SQLITE_DONE)) {
1505         ResetStatement(statement, true, errCode);
1506         return -E_NOT_FOUND;
1507     } else if (errCode != MapSQLiteErrno(SQLITE_ROW)) {
1508         ResetStatement(statement, true, errCode);
1509         return errCode;
1510     }
1511 
1512     Value schemaValue;
1513     errCode = GetColumnBlobValue(statement, 0, schemaValue);
1514     if (errCode != E_OK) {
1515         ResetStatement(statement, true, errCode);
1516         return errCode;
1517     }
1518     DBCommon::VectorToString(schemaValue, schema);
1519     ResetStatement(statement, true, errCode);
1520     return errCode;
1521 }
1522 
GetLogTableVersion(sqlite3 * db,std::string & version)1523 int SQLiteUtils::GetLogTableVersion(sqlite3 *db, std::string &version)
1524 {
1525     if (db == nullptr) {
1526         return -E_INVALID_DB;
1527     }
1528 
1529     sqlite3_stmt *statement = nullptr;
1530     std::string sql = "SELECT value FROM " + DBConstant::RELATIONAL_PREFIX + "metadata WHERE key=?;";
1531     int errCode = GetStatement(db, sql, statement);
1532     if (errCode != E_OK) {
1533         return errCode;
1534     }
1535 
1536     Key logTableKey;
1537     DBCommon::StringToVector(DBConstant::LOG_TABLE_VERSION_KEY, logTableKey);
1538     errCode = BindBlobToStatement(statement, 1, logTableKey, false);
1539     if (errCode != E_OK) {
1540         ResetStatement(statement, true, errCode);
1541         return errCode;
1542     }
1543 
1544     errCode = StepWithRetry(statement);
1545     if (errCode == MapSQLiteErrno(SQLITE_DONE)) {
1546         ResetStatement(statement, true, errCode);
1547         return -E_NOT_FOUND;
1548     } else if (errCode != MapSQLiteErrno(SQLITE_ROW)) {
1549         ResetStatement(statement, true, errCode);
1550         return errCode;
1551     }
1552 
1553     Value value;
1554     errCode = GetColumnBlobValue(statement, 0, value);
1555     if (errCode != E_OK) {
1556         ResetStatement(statement, true, errCode);
1557         return errCode;
1558     }
1559     DBCommon::VectorToString(value, version);
1560     ResetStatement(statement, true, errCode);
1561     return errCode;
1562 }
1563 
RegisterFunction(sqlite3 * db,const std::string & funcName,int nArg,void * uData,TransactFunc & func)1564 int SQLiteUtils::RegisterFunction(sqlite3 *db, const std::string &funcName, int nArg, void *uData, TransactFunc &func)
1565 {
1566     if (db == nullptr) {
1567         LOGE("Sqlite DB not exists.");
1568         return -E_INVALID_DB;
1569     }
1570 
1571     int errCode = sqlite3_create_function_v2(db, funcName.c_str(), nArg, SQLITE_UTF8 | SQLITE_DETERMINISTIC, uData,
1572         func.xFunc, func.xStep, func.xFinal, func.xDestroy);
1573     if (errCode != SQLITE_OK) {
1574         LOGE("sqlite3_create_function_v2 about [%s] returned %d", funcName.c_str(), errCode);
1575         return MapSQLiteErrno(errCode);
1576     }
1577     return E_OK;
1578 }
1579 #endif
RegisterFlatBufferFunction(sqlite3 * db,const std::string & inSchema)1580 int SQLiteUtils::RegisterFlatBufferFunction(sqlite3 *db, const std::string &inSchema)
1581 {
1582     if (db == nullptr) {
1583         LOGE("Sqlite DB not exists.");
1584         return -E_INVALID_DB;
1585     }
1586     auto heapSchemaObj = new (std::nothrow) SchemaObject;
1587     if (heapSchemaObj == nullptr) {
1588         return -E_OUT_OF_MEMORY;
1589     }
1590     int errCode = heapSchemaObj->ParseFromSchemaString(inSchema);
1591     if (errCode != E_OK) { // Unlikely, it has been parsed before
1592         delete heapSchemaObj;
1593         heapSchemaObj = nullptr;
1594         return -E_INTERNAL_ERROR;
1595     }
1596     if (heapSchemaObj->GetSchemaType() != SchemaType::FLATBUFFER) { // Do not need to register FlatBufferExtract
1597         delete heapSchemaObj;
1598         heapSchemaObj = nullptr;
1599         return E_OK;
1600     }
1601     errCode = sqlite3_create_function_v2(db, SchemaObject::GetExtractFuncName(SchemaType::FLATBUFFER).c_str(),
1602         3, SQLITE_UTF8 | SQLITE_DETERMINISTIC, heapSchemaObj, &FlatBufferExtractByPath, nullptr, nullptr, // 3 args
1603         reinterpret_cast<void(*)(void*)>(SchemaObjectDestructor));
1604     // About the release of heapSchemaObj: SQLite guarantee that at following case, sqlite will invoke the destructor
1605     // (that is SchemaObjectDestructor) we passed to it. See sqlite.org for more information.
1606     // The destructor is invoked when the function is deleted, either by being overloaded or when the database
1607     // connection closes. The destructor is also invoked if the call to sqlite3_create_function_v2() fails
1608     if (errCode != SQLITE_OK) {
1609         LOGE("sqlite3_create_function_v2 about flatbuffer_extract_by_path return=%d.", errCode);
1610         // As mentioned above, SQLite had invoked the SchemaObjectDestructor to release the heapSchemaObj
1611         return MapSQLiteErrno(errCode);
1612     }
1613     return E_OK;
1614 }
1615 
UpdateMetaDataWithinTrigger(sqlite3_context * ctx,int argc,sqlite3_value ** argv)1616 void SQLiteUtils::UpdateMetaDataWithinTrigger(sqlite3_context *ctx, int argc, sqlite3_value **argv)
1617 {
1618     if (ctx == nullptr || argc != 2 || argv == nullptr) { // 2 : Number of parameters for sqlite register function
1619         LOGE("[UpdateMetaDataWithinTrigger] Invalid parameter, argc=%d.", argc);
1620         return;
1621     }
1622     auto *handle = static_cast<sqlite3 *>(sqlite3_user_data(ctx));
1623     if (handle == nullptr) {
1624         sqlite3_result_error(ctx, "Sqlite context is invalid.", USING_STR_LEN);
1625         LOGE("Sqlite context is invalid.");
1626         return;
1627     }
1628     auto *keyPtr = static_cast<const uint8_t *>(sqlite3_value_blob(argv[0])); // 0 : first argv for key
1629     int keyLen = sqlite3_value_bytes(argv[0]); // 0 : first argv for key
1630     if (keyPtr == nullptr || keyLen <= 0 || keyLen > static_cast<int>(DBConstant::MAX_KEY_SIZE)) {
1631         sqlite3_result_error(ctx, "key is invalid.", USING_STR_LEN);
1632         LOGE("key is invalid.");
1633         return;
1634     }
1635     auto val = sqlite3_value_int64(argv[1]); // 1 : second argv for value
1636 
1637     sqlite3_stmt *stmt = nullptr;
1638     int errCode = SQLiteUtils::GetStatement(handle, UPDATE_META_SQL, stmt);
1639     if (errCode != E_OK) {
1640         sqlite3_result_error(ctx, "Get update meta_data statement failed.", USING_STR_LEN);
1641         LOGE("Get update meta_data statement failed. %d", errCode);
1642         return;
1643     }
1644 
1645     Key key(keyPtr, keyPtr + keyLen);
1646     errCode = SQLiteUtils::BindBlobToStatement(stmt, BIND_KEY_INDEX, key, false);
1647     if (errCode != E_OK) {
1648         sqlite3_result_error(ctx, "Bind key to statement failed.", USING_STR_LEN);
1649         LOGE("Bind key to statement failed. %d", errCode);
1650         goto END;
1651     }
1652 
1653     errCode = SQLiteUtils::BindInt64ToStatement(stmt, BIND_VAL_INDEX, val);
1654     if (errCode != E_OK) {
1655         sqlite3_result_error(ctx, "Bind value to statement failed.", USING_STR_LEN);
1656         LOGE("Bind value to statement failed. %d", errCode);
1657         goto END;
1658     }
1659 
1660     errCode = SQLiteUtils::StepWithRetry(stmt, false);
1661     if (errCode != SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)) {
1662         sqlite3_result_error(ctx, "Execute the update meta_data attach failed.", USING_STR_LEN);
1663         LOGE("Execute the update meta_data attach failed. %d", errCode);
1664     }
1665 END:
1666     SQLiteUtils::ResetStatement(stmt, true, errCode);
1667 }
1668 
RegisterMetaDataUpdateFunction(sqlite3 * db)1669 int SQLiteUtils::RegisterMetaDataUpdateFunction(sqlite3 *db)
1670 {
1671     int errCode = sqlite3_create_function_v2(db, DBConstant::UPDATE_META_FUNC.c_str(),
1672         2, // 2: argc for register function
1673         SQLITE_UTF8 | SQLITE_DETERMINISTIC, db, &SQLiteUtils::UpdateMetaDataWithinTrigger, nullptr, nullptr, nullptr);
1674     if (errCode != SQLITE_OK) {
1675         LOGE("sqlite3_create_function_v2 about %s returned %d", DBConstant::UPDATE_META_FUNC.c_str(), errCode);
1676     }
1677     return SQLiteUtils::MapSQLiteErrno(errCode);
1678 }
1679 
1680 struct ValueParseCache {
1681     ValueObject valueParsed;
1682     std::vector<uint8_t> valueOriginal;
1683 };
1684 
1685 namespace {
IsDeleteRecord(const uint8_t * valueBlob,int valueBlobLen)1686 inline bool IsDeleteRecord(const uint8_t *valueBlob, int valueBlobLen)
1687 {
1688     return (valueBlob == nullptr) || (valueBlobLen <= 0); // In fact, sqlite guarantee valueBlobLen not negative
1689 }
1690 
1691 // Use the same cache id as sqlite use for json_extract which is substituted by our json_extract_by_path
1692 // A negative cache-id enables sharing of cache between different operation during the same statement
1693 constexpr int VALUE_CACHE_ID = -429938;
1694 
ValueParseCacheFree(ValueParseCache * inCache)1695 void ValueParseCacheFree(ValueParseCache *inCache)
1696 {
1697     delete inCache;
1698     inCache = nullptr;
1699 }
1700 
1701 // We don't use cache array since we only cache value column of sqlite table, see sqlite implementation for compare.
ParseValueThenCacheOrGetFromCache(sqlite3_context * ctx,const uint8_t * valueBlob,uint32_t valueBlobLen,uint32_t offset)1702 const ValueObject *ParseValueThenCacheOrGetFromCache(sqlite3_context *ctx, const uint8_t *valueBlob,
1703     uint32_t valueBlobLen, uint32_t offset)
1704 {
1705     // Note: All parameter had already been check inside JsonExtractByPath, only called by JsonExtractByPath
1706     auto cached = static_cast<ValueParseCache *>(sqlite3_get_auxdata(ctx, VALUE_CACHE_ID));
1707     if (cached != nullptr) { // A previous cache exist
1708         if (cached->valueOriginal.size() == valueBlobLen) {
1709             if (std::memcmp(cached->valueOriginal.data(), valueBlob, valueBlobLen) == 0) {
1710                 // Cache match
1711                 return &(cached->valueParsed);
1712             }
1713         }
1714     }
1715     // No cache or cache mismatch
1716     auto newCache = new (std::nothrow) ValueParseCache;
1717     if (newCache == nullptr) {
1718         sqlite3_result_error(ctx, "[ParseValueCache] OOM.", USING_STR_LEN);
1719         LOGE("[ParseValueCache] OOM.");
1720         return nullptr;
1721     }
1722     int errCode = newCache->valueParsed.Parse(valueBlob, valueBlob + valueBlobLen, offset);
1723     if (errCode != E_OK) {
1724         sqlite3_result_error(ctx, "[ParseValueCache] Parse fail.", USING_STR_LEN);
1725         LOGE("[ParseValueCache] Parse fail, errCode=%d.", errCode);
1726         delete newCache;
1727         newCache = nullptr;
1728         return nullptr;
1729     }
1730     newCache->valueOriginal.assign(valueBlob, valueBlob + valueBlobLen);
1731     sqlite3_set_auxdata(ctx, VALUE_CACHE_ID, newCache, reinterpret_cast<void(*)(void*)>(ValueParseCacheFree));
1732     // If sqlite3_set_auxdata fail, it will immediately call ValueParseCacheFree to delete newCache;
1733     // Next time sqlite3_set_auxdata will call ValueParseCacheFree to delete newCache of this time;
1734     // At the end, newCache will be eventually deleted when call sqlite3_reset or sqlite3_finalize;
1735     // Since sqlite3_set_auxdata may fail, we have to call sqlite3_get_auxdata other than return newCache directly.
1736     auto cacheInAuxdata = static_cast<ValueParseCache *>(sqlite3_get_auxdata(ctx, VALUE_CACHE_ID));
1737     if (cacheInAuxdata == nullptr) {
1738         return nullptr;
1739     }
1740     return &(cacheInAuxdata->valueParsed);
1741 }
1742 }
1743 
JsonExtractByPath(sqlite3_context * ctx,int argc,sqlite3_value ** argv)1744 void SQLiteUtils::JsonExtractByPath(sqlite3_context *ctx, int argc, sqlite3_value **argv)
1745 {
1746     if (ctx == nullptr || argc != 3 || argv == nullptr) { // 3 parameters, which are value, path and offset
1747         LOGE("[JsonExtract] Invalid parameter, argc=%d.", argc);
1748         return;
1749     }
1750     auto valueBlob = static_cast<const uint8_t *>(sqlite3_value_blob(argv[0]));
1751     int valueBlobLen = sqlite3_value_bytes(argv[0]);
1752     if (IsDeleteRecord(valueBlob, valueBlobLen)) {
1753         // Currently delete records are filtered out of query and create-index sql, so not allowed here.
1754         sqlite3_result_error(ctx, "[JsonExtract] Delete record not allowed.", USING_STR_LEN);
1755         LOGE("[JsonExtract] Delete record not allowed.");
1756         return;
1757     }
1758     auto path = reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
1759     int offset = sqlite3_value_int(argv[2]); // index 2 is the third parameter
1760     if ((path == nullptr) || (offset < 0)) {
1761         sqlite3_result_error(ctx, "[JsonExtract] Path nullptr or offset invalid.", USING_STR_LEN);
1762         LOGE("[JsonExtract] Path nullptr or offset=%d invalid.", offset);
1763         return;
1764     }
1765     FieldPath outPath;
1766     int errCode = SchemaUtils::ParseAndCheckFieldPath(path, outPath);
1767     if (errCode != E_OK) {
1768         sqlite3_result_error(ctx, "[JsonExtract] Path illegal.", USING_STR_LEN);
1769         LOGE("[JsonExtract] Path=%s illegal.", path);
1770         return;
1771     }
1772     // Parameter Check Done Here
1773     const ValueObject *valueObj = ParseValueThenCacheOrGetFromCache(ctx, valueBlob, static_cast<uint32_t>(valueBlobLen),
1774         static_cast<uint32_t>(offset));
1775     if (valueObj == nullptr) {
1776         return; // Necessary had been printed in ParseValueThenCacheOrGetFromCache
1777     }
1778     JsonExtractInnerFunc(ctx, *valueObj, outPath);
1779 }
1780 
1781 namespace {
IsExtractableType(FieldType inType)1782 inline bool IsExtractableType(FieldType inType)
1783 {
1784     return (inType != FieldType::LEAF_FIELD_NULL && inType != FieldType::LEAF_FIELD_ARRAY &&
1785         inType != FieldType::LEAF_FIELD_OBJECT && inType != FieldType::INTERNAL_FIELD_OBJECT);
1786 }
1787 }
1788 
JsonExtractInnerFunc(sqlite3_context * ctx,const ValueObject & inValue,const FieldPath & inPath)1789 void SQLiteUtils::JsonExtractInnerFunc(sqlite3_context *ctx, const ValueObject &inValue, const FieldPath &inPath)
1790 {
1791     FieldType outType = FieldType::LEAF_FIELD_NULL; // Default type null for invalid-path(path not exist)
1792     int errCode = inValue.GetFieldTypeByFieldPath(inPath, outType);
1793     if (errCode != E_OK && errCode != -E_INVALID_PATH) {
1794         sqlite3_result_error(ctx, "[JsonExtract] GetFieldType fail.", USING_STR_LEN);
1795         LOGE("[JsonExtract] GetFieldType fail, errCode=%d.", errCode);
1796         return;
1797     }
1798     FieldValue outValue;
1799     if (IsExtractableType(outType)) {
1800         errCode = inValue.GetFieldValueByFieldPath(inPath, outValue);
1801         if (errCode != E_OK) {
1802             sqlite3_result_error(ctx, "[JsonExtract] GetFieldValue fail.", USING_STR_LEN);
1803             LOGE("[JsonExtract] GetFieldValue fail, errCode=%d.", errCode);
1804             return;
1805         }
1806     }
1807     // FieldType null, array, object do not have value, all these FieldValue will be regarded as null in JsonReturn.
1808     ExtractReturn(ctx, outType, outValue);
1809 }
1810 
1811 // NOTE!!! This function is performance sensitive !!! Carefully not to allocate memory often!!!
FlatBufferExtractByPath(sqlite3_context * ctx,int argc,sqlite3_value ** argv)1812 void SQLiteUtils::FlatBufferExtractByPath(sqlite3_context *ctx, int argc, sqlite3_value **argv)
1813 {
1814     if (ctx == nullptr || argc != 3 || argv == nullptr) { // 3 parameters, which are value, path and offset
1815         LOGE("[FlatBufferExtract] Invalid parameter, argc=%d.", argc);
1816         return;
1817     }
1818     auto schema = static_cast<SchemaObject *>(sqlite3_user_data(ctx));
1819     if (schema == nullptr || !schema->IsSchemaValid() || (schema->GetSchemaType() != SchemaType::FLATBUFFER)) {
1820         sqlite3_result_error(ctx, "[FlatBufferExtract] No SchemaObject or invalid.", USING_STR_LEN);
1821         LOGE("[FlatBufferExtract] No SchemaObject or invalid.");
1822         return;
1823     }
1824     // Get information from argv
1825     auto valueBlob = static_cast<const uint8_t *>(sqlite3_value_blob(argv[0]));
1826     int valueBlobLen = sqlite3_value_bytes(argv[0]);
1827     if (IsDeleteRecord(valueBlob, valueBlobLen)) {
1828         // Currently delete records are filtered out of query and create-index sql, so not allowed here.
1829         sqlite3_result_error(ctx, "[FlatBufferExtract] Delete record not allowed.", USING_STR_LEN);
1830         LOGE("[FlatBufferExtract] Delete record not allowed.");
1831         return;
1832     }
1833     auto path = reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
1834     int offset = sqlite3_value_int(argv[2]); // index 2 is the third parameter
1835     if ((path == nullptr) || (offset < 0) || (static_cast<uint32_t>(offset) != schema->GetSkipSize())) {
1836         sqlite3_result_error(ctx, "[FlatBufferExtract] Path null or offset invalid.", USING_STR_LEN);
1837         LOGE("[FlatBufferExtract] Path null or offset=%d(skipsize=%u) invalid.", offset, schema->GetSkipSize());
1838         return;
1839     }
1840     FlatBufferExtractInnerFunc(ctx, *schema, RawValue { valueBlob, valueBlobLen }, path);
1841 }
1842 
1843 namespace {
1844 constexpr uint32_t FLATBUFFER_MAX_CACHE_SIZE = 102400; // 100 KBytes
1845 
FlatBufferCacheFree(std::vector<uint8_t> * inCache)1846 void FlatBufferCacheFree(std::vector<uint8_t> *inCache)
1847 {
1848     delete inCache;
1849     inCache = nullptr;
1850 }
1851 }
1852 
FlatBufferExtractInnerFunc(sqlite3_context * ctx,const SchemaObject & schema,const RawValue & inValue,RawString inPath)1853 void SQLiteUtils::FlatBufferExtractInnerFunc(sqlite3_context *ctx, const SchemaObject &schema, const RawValue &inValue,
1854     RawString inPath)
1855 {
1856     // All parameter had already been check inside FlatBufferExtractByPath, only called by FlatBufferExtractByPath
1857     if (schema.GetSkipSize() % SchemaConstant::SECURE_BYTE_ALIGN == 0) {
1858         TypeValue outExtract;
1859         int errCode = schema.ExtractValue(ValueSource::FROM_DBFILE, inPath, inValue, outExtract, nullptr);
1860         if (errCode != E_OK) {
1861             sqlite3_result_error(ctx, "[FlatBufferExtract] ExtractValue fail.", USING_STR_LEN);
1862             LOGE("[FlatBufferExtract] ExtractValue fail, errCode=%d.", errCode);
1863             return;
1864         }
1865         ExtractReturn(ctx, outExtract.first, outExtract.second);
1866         return;
1867     }
1868     // Not byte-align secure, we have to make a cache for copy. Check whether cache had already exist.
1869     auto cached = static_cast<std::vector<uint8_t> *>(sqlite3_get_auxdata(ctx, VALUE_CACHE_ID)); // Share the same id
1870     if (cached == nullptr) {
1871         // Make the cache
1872         auto newCache = new (std::nothrow) std::vector<uint8_t>;
1873         if (newCache == nullptr) {
1874             sqlite3_result_error(ctx, "[FlatBufferExtract] OOM.", USING_STR_LEN);
1875             LOGE("[FlatBufferExtract] OOM.");
1876             return;
1877         }
1878         newCache->resize(FLATBUFFER_MAX_CACHE_SIZE);
1879         sqlite3_set_auxdata(ctx, VALUE_CACHE_ID, newCache, reinterpret_cast<void(*)(void*)>(FlatBufferCacheFree));
1880         // If sqlite3_set_auxdata fail, it will immediately call FlatBufferCacheFree to delete newCache;
1881         // Next time sqlite3_set_auxdata will call FlatBufferCacheFree to delete newCache of this time;
1882         // At the end, newCache will be eventually deleted when call sqlite3_reset or sqlite3_finalize;
1883         // Since sqlite3_set_auxdata may fail, we have to call sqlite3_get_auxdata other than return newCache directly.
1884         // See sqlite.org for more information.
1885         cached = static_cast<std::vector<uint8_t> *>(sqlite3_get_auxdata(ctx, VALUE_CACHE_ID));
1886     }
1887     if (cached == nullptr) {
1888         LOGW("[FlatBufferExtract] Something wrong with Auxdata, but it is no matter without cache.");
1889     }
1890     TypeValue outExtract;
1891     int errCode = schema.ExtractValue(ValueSource::FROM_DBFILE, inPath, inValue, outExtract, cached);
1892     if (errCode != E_OK) {
1893         sqlite3_result_error(ctx, "[FlatBufferExtract] ExtractValue fail.", USING_STR_LEN);
1894         LOGE("[FlatBufferExtract] ExtractValue fail, errCode=%d.", errCode);
1895         return;
1896     }
1897     ExtractReturn(ctx, outExtract.first, outExtract.second);
1898 }
1899 
ExtractReturn(sqlite3_context * ctx,FieldType type,const FieldValue & value)1900 void SQLiteUtils::ExtractReturn(sqlite3_context *ctx, FieldType type, const FieldValue &value)
1901 {
1902     if (ctx == nullptr) {
1903         return;
1904     }
1905     switch (type) {
1906         case FieldType::LEAF_FIELD_BOOL:
1907             sqlite3_result_int(ctx, (value.boolValue ? 1 : 0));
1908             break;
1909         case FieldType::LEAF_FIELD_INTEGER:
1910             sqlite3_result_int(ctx, value.integerValue);
1911             break;
1912         case FieldType::LEAF_FIELD_LONG:
1913             sqlite3_result_int64(ctx, value.longValue);
1914             break;
1915         case FieldType::LEAF_FIELD_DOUBLE:
1916             sqlite3_result_double(ctx, value.doubleValue);
1917             break;
1918         case FieldType::LEAF_FIELD_STRING:
1919             // The SQLITE_TRANSIENT value means that the content will likely change in the near future and
1920             // that SQLite should make its own private copy of the content before returning.
1921             sqlite3_result_text(ctx, value.stringValue.c_str(), -1, SQLITE_TRANSIENT); // -1 mean use the string length
1922             break;
1923         default:
1924             // All other type regard as null
1925             sqlite3_result_null(ctx);
1926     }
1927     return;
1928 }
1929 
CalcHashKey(sqlite3_context * ctx,int argc,sqlite3_value ** argv)1930 void SQLiteUtils::CalcHashKey(sqlite3_context *ctx, int argc, sqlite3_value **argv)
1931 {
1932     // 1 means that the function only needs one parameter, namely key
1933     if (ctx == nullptr || argc != 1 || argv == nullptr) {
1934         LOGE("Parameter does not meet restrictions.");
1935         return;
1936     }
1937     auto keyBlob = static_cast<const uint8_t *>(sqlite3_value_blob(argv[0]));
1938     if (keyBlob == nullptr) {
1939         sqlite3_result_error(ctx, "Parameters is invalid.", USING_STR_LEN);
1940         LOGE("Parameters is invalid.");
1941         return;
1942     }
1943     int blobLen = sqlite3_value_bytes(argv[0]);
1944     std::vector<uint8_t> value(keyBlob, keyBlob + blobLen);
1945     std::vector<uint8_t> hashValue;
1946     int errCode = DBCommon::CalcValueHash(value, hashValue);
1947     if (errCode != E_OK) {
1948         sqlite3_result_error(ctx, "Get hash value error.", USING_STR_LEN);
1949         LOGE("Get hash value error.");
1950         return;
1951     }
1952     sqlite3_result_blob(ctx, hashValue.data(), hashValue.size(), SQLITE_TRANSIENT);
1953     return;
1954 }
1955 
GetDbSize(const std::string & dir,const std::string & dbName,uint64_t & size)1956 int SQLiteUtils::GetDbSize(const std::string &dir, const std::string &dbName, uint64_t &size)
1957 {
1958     std::string dataDir = dir + "/" + dbName + DBConstant::SQLITE_DB_EXTENSION;
1959     uint64_t localDbSize = 0;
1960     int errCode = OS::CalFileSize(dataDir, localDbSize);
1961     if (errCode != E_OK) {
1962         LOGD("Failed to get the db file size, errCode:%d", errCode);
1963         return errCode;
1964     }
1965 
1966     std::string shmFileName = dataDir + "-shm";
1967     uint64_t localshmFileSize = 0;
1968     errCode = OS::CalFileSize(shmFileName, localshmFileSize);
1969     if (errCode != E_OK) {
1970         localshmFileSize = 0;
1971     }
1972 
1973     std::string walFileName = dataDir + "-wal";
1974     uint64_t localWalFileSize = 0;
1975     errCode = OS::CalFileSize(walFileName, localWalFileSize);
1976     if (errCode != E_OK) {
1977         localWalFileSize = 0;
1978     }
1979 
1980     // 64-bit system is Suffice. Computer storage is less than uint64_t max
1981     size += (localDbSize + localshmFileSize + localWalFileSize);
1982     return E_OK;
1983 }
1984 
ExplainPlan(sqlite3 * db,const std::string & execSql,bool isQueryPlan)1985 int SQLiteUtils::ExplainPlan(sqlite3 *db, const std::string &execSql, bool isQueryPlan)
1986 {
1987     if (db == nullptr) {
1988         return -E_INVALID_DB;
1989     }
1990 
1991     sqlite3_stmt *statement = nullptr;
1992     std::string explainSql = (isQueryPlan ? "explain query plan " : "explain ") + execSql;
1993     int errCode = GetStatement(db, explainSql, statement);
1994     if (errCode != E_OK) {
1995         return errCode;
1996     }
1997 
1998     bool isFirst = true;
1999     errCode = StepWithRetry(statement); // memory db does not support schema
2000     while (errCode == MapSQLiteErrno(SQLITE_ROW)) {
2001         int nCol = sqlite3_column_count(statement);
2002         nCol = std::min(nCol, 8); // Read 8 column at most
2003 
2004         if (isFirst) {
2005             LOGD("#### %s", GetColString(statement, nCol).c_str());
2006             isFirst = false;
2007         }
2008 
2009         std::string rowString;
2010         for (int i = 0; i < nCol; i++) {
2011             if (sqlite3_column_text(statement, i) != nullptr) {
2012                 rowString += reinterpret_cast<const std::string::value_type *>(sqlite3_column_text(statement, i));
2013             }
2014             int blankFill = (i + 1) * 16 - rowString.size(); // each column width 16
2015             rowString.append(static_cast<std::string::size_type>((blankFill > 0) ? blankFill : 0), ' ');
2016         }
2017         LOGD("#### %s", rowString.c_str());
2018         errCode = StepWithRetry(statement);
2019     }
2020     if (errCode != MapSQLiteErrno(SQLITE_DONE)) {
2021         LOGE("[SqlUtil][Explain] StepWithRetry fail, errCode=%d.", errCode);
2022         ResetStatement(statement, true, errCode);
2023         return errCode;
2024     }
2025     errCode = E_OK;
2026     ResetStatement(statement, true, errCode);
2027     return errCode;
2028 }
2029 
SetDataBaseProperty(sqlite3 * db,const OpenDbProperties & properties,bool setWal,const std::vector<std::string> & sqls)2030 int SQLiteUtils::SetDataBaseProperty(sqlite3 *db, const OpenDbProperties &properties, bool setWal,
2031     const std::vector<std::string> &sqls)
2032 {
2033     // Set the default busy handler to retry automatically before returning SQLITE_BUSY.
2034     int errCode = SetBusyTimeout(db, BUSY_TIMEOUT_MS);
2035     if (errCode != E_OK) {
2036         return errCode;
2037     }
2038     if (!properties.isMemDb) {
2039         errCode = SQLiteUtils::SetKey(db, properties.cipherType, properties.passwd, setWal,
2040             properties.iterTimes);
2041         if (errCode != E_OK) {
2042             LOGD("SQLiteUtils::SetKey fail!!![%d]", errCode);
2043             return errCode;
2044         }
2045     }
2046 
2047     for (const auto &sql : sqls) {
2048         errCode = SQLiteUtils::ExecuteRawSQL(db, sql);
2049         if (errCode != E_OK) {
2050             LOGE("[SQLite] execute sql failed: %d", errCode);
2051             return errCode;
2052         }
2053     }
2054     // Create table if not exist according the sqls.
2055     if (properties.createIfNecessary) {
2056         for (const auto &sql : properties.sqls) {
2057             errCode = SQLiteUtils::ExecuteRawSQL(db, sql);
2058             if (errCode != E_OK) {
2059                 LOGE("[SQLite] execute preset sqls failed");
2060                 return errCode;
2061             }
2062         }
2063     }
2064     return E_OK;
2065 }
2066 
2067 #ifndef OMIT_ENCRYPT
SetCipherSettings(sqlite3 * db,CipherType type,uint32_t iterTimes)2068 int SQLiteUtils::SetCipherSettings(sqlite3 *db, CipherType type, uint32_t iterTimes)
2069 {
2070     if (db == nullptr) {
2071         return -E_INVALID_DB;
2072     }
2073     std::string cipherName = GetCipherName(type);
2074     if (cipherName.empty()) {
2075         return -E_INVALID_ARGS;
2076     }
2077     std::string cipherConfig = CIPHER_CONFIG_SQL + cipherName + ";";
2078     int errCode = SQLiteUtils::ExecuteRawSQL(db, cipherConfig);
2079     if (errCode != E_OK) {
2080         LOGE("[SQLiteUtils][SetCipherSettings] config cipher failed:%d", errCode);
2081         return errCode;
2082     }
2083     errCode = SQLiteUtils::ExecuteRawSQL(db, KDF_ITER_CONFIG_SQL + std::to_string(iterTimes));
2084     if (errCode != E_OK) {
2085         LOGE("[SQLiteUtils][SetCipherSettings] config iter failed:%d", errCode);
2086         return errCode;
2087     }
2088     return errCode;
2089 }
2090 
GetCipherName(CipherType type)2091 std::string SQLiteUtils::GetCipherName(CipherType type)
2092 {
2093     if (type == CipherType::AES_256_GCM || type == CipherType::DEFAULT) {
2094         return "'aes-256-gcm'";
2095     }
2096     return "";
2097 }
2098 #endif
2099 
DropTriggerByName(sqlite3 * db,const std::string & name)2100 int SQLiteUtils::DropTriggerByName(sqlite3 *db, const std::string &name)
2101 {
2102     const std::string dropTriggerSql = "DROP TRIGGER " + name + ";";
2103     int errCode = SQLiteUtils::ExecuteRawSQL(db, dropTriggerSql);
2104     if (errCode != E_OK) {
2105         LOGE("Remove trigger failed. %d", errCode);
2106     }
2107     return errCode;
2108 }
2109 
ExpandedSql(sqlite3_stmt * stmt,std::string & basicString)2110 int SQLiteUtils::ExpandedSql(sqlite3_stmt *stmt, std::string &basicString)
2111 {
2112     if (stmt == nullptr) {
2113         return -E_INVALID_ARGS;
2114     }
2115     char *eSql = sqlite3_expanded_sql(stmt);
2116     if (eSql == nullptr) {
2117         LOGE("expand statement to sql failed.");
2118         return -E_INVALID_DATA;
2119     }
2120     basicString = std::string(eSql);
2121     sqlite3_free(eSql);
2122     return E_OK;
2123 }
2124 
ExecuteCheckPoint(sqlite3 * db)2125 void SQLiteUtils::ExecuteCheckPoint(sqlite3 *db)
2126 {
2127     if (db == nullptr) {
2128         return;
2129     }
2130 
2131     int chkResult = sqlite3_wal_checkpoint_v2(db, nullptr, SQLITE_CHECKPOINT_TRUNCATE, nullptr, nullptr);
2132     LOGI("SQLite checkpoint result:%d", chkResult);
2133 }
2134 
CheckTableEmpty(sqlite3 * db,const std::string & tableName,bool & isEmpty)2135 int SQLiteUtils::CheckTableEmpty(sqlite3 *db, const std::string &tableName, bool &isEmpty)
2136 {
2137     if (db == nullptr) {
2138         return -E_INVALID_ARGS;
2139     }
2140 
2141     std::string cntSql = "SELECT min(rowid) FROM " + tableName + ";";
2142     sqlite3_stmt *stmt = nullptr;
2143     int errCode = SQLiteUtils::GetStatement(db, cntSql, stmt);
2144     if (errCode != E_OK) {
2145         return errCode;
2146     }
2147 
2148     errCode = SQLiteUtils::StepWithRetry(stmt, false);
2149     if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_ROW)) {
2150         if (sqlite3_column_type(stmt, 0) == SQLITE_NULL) {
2151             isEmpty = true;
2152         } else {
2153             isEmpty = false;
2154         }
2155         errCode = E_OK;
2156     }
2157 
2158     SQLiteUtils::ResetStatement(stmt, true, errCode);
2159     return SQLiteUtils::MapSQLiteErrno(errCode);
2160 }
2161 
SetPersistWalMode(sqlite3 * db)2162 int SQLiteUtils::SetPersistWalMode(sqlite3 *db)
2163 {
2164     if (db == nullptr) {
2165         return -E_INVALID_ARGS;
2166     }
2167     int opCode = 1;
2168     int errCode = sqlite3_file_control(db, "main", SQLITE_FCNTL_PERSIST_WAL, &opCode);
2169     if (errCode != SQLITE_OK) {
2170         LOGE("Set persist wal mode failed. %d", errCode);
2171     }
2172     return SQLiteUtils::MapSQLiteErrno(errCode);
2173 }
2174 
CheckSchemaChanged(sqlite3_stmt * stmt,const TableInfo & table,int offset)2175 int SQLiteUtils::CheckSchemaChanged(sqlite3_stmt *stmt, const TableInfo &table, int offset)
2176 {
2177     if (stmt == nullptr) {
2178         return  -E_INVALID_ARGS;
2179     }
2180 
2181     int columnNum = sqlite3_column_count(stmt);
2182     if (columnNum - offset != static_cast<int>(table.GetFields().size())) {
2183         LOGE("Schema field number does not match.");
2184         return -E_DISTRIBUTED_SCHEMA_CHANGED;
2185     }
2186 
2187     auto fields = table.GetFields();
2188     for (int i = offset; i < columnNum; i++) {
2189         const char *name = sqlite3_column_name(stmt, i);
2190         std::string colName = (name == nullptr) ? std::string() : name;
2191         const char *declType = sqlite3_column_decltype(stmt, i);
2192         std::string colType = (declType == nullptr) ? std::string() : declType;
2193         transform(colType.begin(), colType.end(), colType.begin(), ::tolower);
2194 
2195         auto it = fields.find(colName);
2196         if (it == fields.end() || it->second.GetDataType() != colType) {
2197             LOGE("Schema field define does not match.");
2198             return -E_DISTRIBUTED_SCHEMA_CHANGED;
2199         }
2200     }
2201     return E_OK;
2202 }
2203 
GetLastRowId(sqlite3 * db)2204 int64_t SQLiteUtils::GetLastRowId(sqlite3 *db)
2205 {
2206     if (db == nullptr) {
2207         return -1;
2208     }
2209     return sqlite3_last_insert_rowid(db);
2210 }
2211 
GetLastErrorMsg()2212 std::string SQLiteUtils::GetLastErrorMsg()
2213 {
2214     std::lock_guard<std::mutex> autoLock(logMutex_);
2215     return lastErrorMsg_;
2216 }
2217 
SetAuthorizer(sqlite3 * db,int (* xAuth)(void *,int,const char *,const char *,const char *,const char *))2218 int SQLiteUtils::SetAuthorizer(sqlite3 *db,
2219     int (*xAuth)(void*, int, const char*, const char*, const char*, const char*))
2220 {
2221     return SQLiteUtils::MapSQLiteErrno(sqlite3_set_authorizer(db, xAuth, nullptr));
2222 }
2223 
GetSelectCols(sqlite3_stmt * stmt,std::vector<std::string> & colNames)2224 void SQLiteUtils::GetSelectCols(sqlite3_stmt *stmt, std::vector<std::string> &colNames)
2225 {
2226     colNames.clear();
2227     for (int i = 0; i < sqlite3_column_count(stmt); ++i) {
2228         const char *name = sqlite3_column_name(stmt, i);
2229         colNames.emplace_back(name == nullptr ? std::string() : std::string(name));
2230     }
2231 }
2232 
SetKeyInner(sqlite3 * db,CipherType type,const CipherPassword & passwd,uint32_t iterTimes)2233 int SQLiteUtils::SetKeyInner(sqlite3 *db, CipherType type, const CipherPassword &passwd, uint32_t iterTimes)
2234 {
2235 #ifndef OMIT_ENCRYPT
2236     int errCode = sqlite3_key(db, static_cast<const void *>(passwd.GetData()), static_cast<int>(passwd.GetSize()));
2237     if (errCode != SQLITE_OK) {
2238         LOGE("[SQLiteUtils][SetKeyInner] config key failed:(%d)", errCode);
2239         return SQLiteUtils::MapSQLiteErrno(errCode);
2240     }
2241 
2242     errCode = SQLiteUtils::SetCipherSettings(db, type, iterTimes);
2243     if (errCode != E_OK) {
2244         LOGE("[SQLiteUtils][SetKeyInner] set cipher settings failed:%d", errCode);
2245     }
2246     return errCode;
2247 #else
2248     return -E_NOT_SUPPORT;
2249 #endif
2250 }
2251 
UpdateCipherShaAlgo(sqlite3 * db,bool setWal,CipherType type,const CipherPassword & passwd,uint32_t iterTimes)2252 int SQLiteUtils::UpdateCipherShaAlgo(sqlite3 *db, bool setWal, CipherType type, const CipherPassword &passwd,
2253     uint32_t iterTimes)
2254 {
2255     if (passwd.GetSize() != 0) {
2256         int errCode = SetKeyInner(db, type, passwd, iterTimes);
2257         if (errCode != E_OK) {
2258             return errCode;
2259         }
2260         // set sha1 algo for old version
2261         errCode = SQLiteUtils::ExecuteRawSQL(db, SHA1_ALGO_SQL);
2262         if (errCode != E_OK) {
2263             LOGE("[SQLiteUtils][UpdateCipherShaAlgo] set sha algo failed:%d", errCode);
2264             return errCode;
2265         }
2266         // try to get user version
2267         errCode = SQLiteUtils::ExecuteRawSQL(db, USER_VERSION_SQL);
2268         if (errCode != E_OK) {
2269             LOGE("[SQLiteUtils][UpdateCipherShaAlgo] verify version failed:%d", errCode);
2270             if (errno == EKEYREVOKED) {
2271                 return -E_EKEYREVOKED;
2272             }
2273             if (errCode == -E_BUSY) {
2274                 return errCode;
2275             }
2276             return -E_INVALID_PASSWD_OR_CORRUPTED_DB;
2277         }
2278         // try to update sha algo by rekey operation
2279         errCode = SQLiteUtils::ExecuteRawSQL(db, SHA256_ALGO_REKEY_SQL);
2280         if (errCode != E_OK) {
2281             LOGE("[SQLiteUtils][UpdateCipherShaAlgo] set rekey sha algo failed:%d", errCode);
2282             return errCode;
2283         }
2284         if (setWal) {
2285             errCode = SQLiteUtils::ExecuteRawSQL(db, WAL_MODE_SQL);
2286             if (errCode != E_OK) {
2287                 LOGE("[SQLite][UpdateCipherShaAlgo] execute wal sql failed: %d", errCode);
2288                 return errCode;
2289             }
2290         }
2291         return Rekey(db, passwd);
2292     }
2293     return -E_INVALID_PASSWD_OR_CORRUPTED_DB;
2294 }
2295 } // namespace DistributedDB