1 /* 2 * Copyright (c) 2022 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 #ifndef NATIVE_RDB_SQLITE_CONNECTION_H 17 #define NATIVE_RDB_SQLITE_CONNECTION_H 18 19 #include <atomic> 20 #include <cstdint> 21 #include <list> 22 #include <memory> 23 #include <mutex> 24 #include <vector> 25 26 #include "connection.h" 27 #include "rdb_local_db_observer.h" 28 #include "rdb_store_config.h" 29 #include "sqlite3sym.h" 30 #include "sqlite_statement.h" 31 #include "value_object.h" 32 33 typedef struct ClientChangedData ClientChangedData; 34 namespace OHOS { 35 namespace NativeRdb { 36 /** 37 * @brief Use DataChangeCallback replace std::function<void(ClientChangedData &clientChangedData)>. 38 */ 39 using DataChangeCallback = std::function<void(ClientChangedData &clientChangedData)>; 40 41 class SqliteConnection : public Connection { 42 public: 43 static std::pair<int32_t, std::shared_ptr<Connection>> Create(const RdbStoreConfig &config, bool isWrite); 44 static int32_t Delete(const RdbStoreConfig &config); 45 static int32_t Delete(const std::string &path); 46 static int32_t Repair(const RdbStoreConfig &config); 47 static std::map<std::string, Info> Collect(const RdbStoreConfig &config); 48 SqliteConnection(const RdbStoreConfig &config, bool isWriteConnection); 49 ~SqliteConnection(); 50 int32_t OnInitialize() override; 51 int TryCheckPoint(bool timeout) override; 52 int LimitWalSize() override; 53 int ConfigLocale(const std::string &localeStr) override; 54 int CleanDirtyData(const std::string &table, uint64_t cursor) override; 55 int ReSetKey(const RdbStoreConfig &config) override; 56 int32_t GetJournalMode() override; 57 std::pair<int32_t, Stmt> CreateStatement(const std::string &sql, SConn conn) override; 58 bool IsWriter() const override; 59 int SubscribeTableChanges(const Notifier ¬ifier) override; 60 int GetMaxVariable() const override; 61 int32_t GetDBType() const override; 62 int32_t ClearCache() override; 63 int32_t Subscribe(const std::string &event, 64 const std::shared_ptr<DistributedRdb::RdbStoreObserver> &observer) override; 65 int32_t Unsubscribe(const std::string &event, 66 const std::shared_ptr<DistributedRdb::RdbStoreObserver> &observer) override; 67 int32_t Backup(const std::string &databasePath, const std::vector<uint8_t> &destEncryptKey, 68 bool isAsync, SlaveStatus &slaveStatus) override; 69 int32_t Restore(const std::string &databasePath, const std::vector<uint8_t> &destEncryptKey, 70 SlaveStatus &slaveStatus) override; 71 ExchangeStrategy GenerateExchangeStrategy(const SlaveStatus &status) override; 72 73 protected: 74 std::pair<int32_t, ValueObject> ExecuteForValue(const std::string &sql, 75 const std::vector<ValueObject> &bindArgs = std::vector<ValueObject>()); 76 int ExecuteSql(const std::string &sql, const std::vector<ValueObject> &bindArgs = std::vector<ValueObject>()); 77 78 private: 79 struct Suffix { 80 const char *suffix_ = nullptr; 81 const char *debug_ = nullptr; 82 }; 83 84 int InnerOpen(const RdbStoreConfig &config); 85 int Configure(const RdbStoreConfig &config, std::string &dbPath); 86 int SetPageSize(const RdbStoreConfig &config); 87 std::string GetSecManagerName(const RdbStoreConfig &config); 88 int SetEncrypt(const RdbStoreConfig &config); 89 int SetEncryptKey(const std::vector<uint8_t> &key, const RdbStoreConfig &config); 90 int SetServiceKey(const RdbStoreConfig &config, int32_t errCode); 91 int SetEncryptAgo(const RdbStoreConfig &config); 92 int SetJournalMode(const RdbStoreConfig &config); 93 int SetJournalSizeLimit(const RdbStoreConfig &config); 94 int SetAutoCheckpoint(const RdbStoreConfig &config); 95 int SetWalFile(const RdbStoreConfig &config); 96 int SetWalSyncMode(const std::string &syncMode); 97 void LimitPermission(const std::string &dbPath) const; 98 99 int SetPersistWal(); 100 int SetBusyTimeout(int timeout); 101 102 int RegDefaultFunctions(sqlite3 *dbHandle); 103 static void MergeAssets(sqlite3_context *ctx, int argc, sqlite3_value **argv); 104 static void MergeAsset(sqlite3_context *ctx, int argc, sqlite3_value **argv); 105 static void CompAssets(std::map<std::string, ValueObject::Asset> &oldAssets, 106 std::map<std::string, ValueObject::Asset> &newAssets); 107 static void MergeAsset(ValueObject::Asset &oldAsset, ValueObject::Asset &newAsset); 108 109 int SetCustomFunctions(const RdbStoreConfig &config); 110 int SetCustomScalarFunction(const std::string &functionName, int argc, ScalarFunction *function); 111 int32_t UnsubscribeLocalDetail(const std::string &event, 112 const std::shared_ptr<DistributedRdb::RdbStoreObserver> &observer); 113 int32_t UnsubscribeLocalDetailAll(const std::string &event); 114 int32_t OpenDatabase(const std::string &dbPath, int openFileFlags); 115 int LoadExtension(const RdbStoreConfig &config, sqlite3 *dbHandle); 116 RdbStoreConfig GetSlaveRdbStoreConfig(const RdbStoreConfig &rdbConfig); 117 int CreateSlaveConnection(const RdbStoreConfig &config, bool checkSlaveExist = true); 118 int ExchangeSlaverToMaster(bool isRestore, SlaveStatus &status); 119 int IsRepairable(); 120 int ExchangeVerify(bool isRestore); 121 static std::pair<int32_t, std::shared_ptr<SqliteConnection>> InnerCreate(const RdbStoreConfig &config, 122 bool isWrite); 123 static constexpr SqliteConnection::Suffix FILE_SUFFIXES[] = { 124 {"", "DB"}, 125 {"-shm", "SHM"}, 126 {"-wal", "WAL"}, 127 {"-journal", "JOURNAL"}, 128 {"-slaveFailure", nullptr}, 129 {"-syncInterrupt", nullptr}, 130 {".corruptedflg", nullptr} 131 }; 132 static constexpr const char *MERGE_ASSETS_FUNC = "merge_assets"; 133 static constexpr const char *MERGE_ASSET_FUNC = "merge_asset"; 134 static constexpr int CHECKPOINT_TIME = 1000; 135 static constexpr int DEFAULT_BUSY_TIMEOUT_MS = 2000; 136 static constexpr int BACKUP_PAGES_PRE_STEP = 12800; // 1024 * 4 * 12800 == 50m 137 static constexpr int BACKUP_PRE_WAIT_TIME = 10; 138 static constexpr ssize_t SLAVE_WAL_SIZE_LIMIT = 2147483647; // 2147483647 = 2g - 1 139 static constexpr uint32_t NO_ITER = 0; 140 static constexpr uint32_t WAL_INDEX = 2; 141 static const int32_t regCreator_; 142 static const int32_t regRepairer_; 143 static const int32_t regDeleter_; 144 static const int32_t regCollector_; 145 146 std::atomic<uint64_t> backupId_; 147 sqlite3 *dbHandle_; 148 bool isWriter_; 149 bool isReadOnly_; 150 bool isConfigured_ = false; 151 bool hasClientObserver_ = false; 152 JournalMode mode_ = JournalMode::MODE_WAL; 153 int maxVariableNumber_; 154 std::mutex mutex_; 155 std::string filePath; 156 std::shared_ptr<SqliteConnection> slaveConnection_; 157 std::map<std::string, ScalarFunctionInfo> customScalarFunctions_; 158 std::map<std::string, std::list<std::shared_ptr<RdbStoreLocalDbObserver>>> observers_; 159 const RdbStoreConfig config_; 160 std::atomic<SlaveStatus> slaveStatus_ = SlaveStatus::UNDEFINED; 161 }; 162 } // namespace NativeRdb 163 } // namespace OHOS 164 #endif