• 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 #ifdef RELATIONAL_STORE
16 #include "sqlite_relational_store_connection.h"
17 #include "db_errno.h"
18 #include "log_print.h"
19 
20 namespace DistributedDB {
SQLiteRelationalStoreConnection(SQLiteRelationalStore * store)21 SQLiteRelationalStoreConnection::SQLiteRelationalStoreConnection(SQLiteRelationalStore *store)
22     : RelationalStoreConnection(store)
23 {
24     OnKill([this]() {
25         auto *store = GetDB<SQLiteRelationalStore>();
26         if (store == nullptr) {
27             return;
28         }
29         UnlockObj();
30         store->StopSync(GetConnectionId());
31         LockObj();
32     });
33 }
34 // Close and release the connection.
Close()35 int SQLiteRelationalStoreConnection::Close()
36 {
37     if (store_ == nullptr) {
38         return -E_INVALID_CONNECTION;
39     }
40 
41     if (isExclusive_.load()) {
42         return -E_BUSY;
43     }
44 
45     // check if transaction closed
46     {
47         std::lock_guard<std::mutex> transactionLock(transactionMutex_);
48         if (writeHandle_ != nullptr) {
49             LOGW("Transaction started, need to rollback before close.");
50             int errCode = RollBack();
51             if (errCode != E_OK) {
52                 LOGE("Rollback transaction failed, %d.", errCode);
53             }
54             ReleaseExecutor(writeHandle_);
55         }
56     }
57 
58     static_cast<SQLiteRelationalStore *>(store_)->ReleaseDBConnection(GetConnectionId(), this);
59     return E_OK;
60 }
61 
GetIdentifier()62 std::string SQLiteRelationalStoreConnection::GetIdentifier()
63 {
64     if (store_ == nullptr) {
65         return {};
66     }
67     return store_->GetProperties().GetStringProp(RelationalDBProperties::IDENTIFIER_DATA, "");
68 }
69 
GetExecutor(bool isWrite,int & errCode) const70 SQLiteSingleVerRelationalStorageExecutor *SQLiteRelationalStoreConnection::GetExecutor(bool isWrite, int &errCode) const
71 {
72     auto *store = GetDB<SQLiteRelationalStore>();
73     if (store == nullptr) {
74         errCode = -E_NOT_INIT;
75         LOGE("[RelationalConnection] store is null, get executor failed! errCode = [%d]", errCode);
76         return nullptr;
77     }
78 
79     return store->GetHandle(isWrite, errCode);
80 }
81 
ReleaseExecutor(SQLiteSingleVerRelationalStorageExecutor * & executor) const82 void SQLiteRelationalStoreConnection::ReleaseExecutor(SQLiteSingleVerRelationalStorageExecutor *&executor) const
83 {
84     auto *store = GetDB<SQLiteRelationalStore>();
85     if (store != nullptr) {
86         store->ReleaseHandle(executor);
87     }
88 }
89 
StartTransaction()90 int SQLiteRelationalStoreConnection::StartTransaction()
91 {
92     std::lock_guard<std::mutex> lock(transactionMutex_);
93     if (writeHandle_ != nullptr) {
94         LOGD("Transaction started already.");
95         return -E_TRANSACT_STATE;
96     }
97 
98     int errCode = E_OK;
99     auto *handle = GetExecutor(true, errCode);
100     if (handle == nullptr) {
101         return errCode;
102     }
103 
104     errCode = handle->StartTransaction(TransactType::DEFERRED);
105     if (errCode != E_OK) {
106         ReleaseExecutor(handle);
107         return errCode;
108     }
109 
110     writeHandle_ = handle;
111     return E_OK;
112 }
113 
114 // Commit the transaction
Commit()115 int SQLiteRelationalStoreConnection::Commit()
116 {
117     std::lock_guard<std::mutex> lock(transactionMutex_);
118     if (writeHandle_ == nullptr) {
119         LOGE("single version database is null or the transaction has not been started");
120         return -E_INVALID_DB;
121     }
122 
123     int errCode = writeHandle_->Commit();
124     ReleaseExecutor(writeHandle_);
125     LOGD("connection commit transaction!");
126     return errCode;
127 }
128 
129 // Roll back the transaction
RollBack()130 int SQLiteRelationalStoreConnection::RollBack()
131 {
132     std::lock_guard<std::mutex> lock(transactionMutex_);
133     if (writeHandle_ == nullptr) {
134         LOGE("Invalid handle for rollback or the transaction has not been started.");
135         return -E_INVALID_DB;
136     }
137 
138     int errCode = writeHandle_->Rollback();
139     ReleaseExecutor(writeHandle_);
140     LOGI("connection rollback transaction!");
141     return errCode;
142 }
143 
CreateDistributedTable(const std::string & tableName,TableSyncType syncType)144 int SQLiteRelationalStoreConnection::CreateDistributedTable(const std::string &tableName, TableSyncType syncType)
145 {
146     auto *store = GetDB<SQLiteRelationalStore>();
147     if (store == nullptr) {
148         LOGE("[RelationalConnection] store is null, get DB failed!");
149         return -E_INVALID_CONNECTION;
150     }
151 
152     int errCode = store->CreateDistributedTable(tableName, syncType);
153     if (errCode != E_OK) {
154         LOGE("[RelationalConnection] create distributed table failed. %d", errCode);
155     }
156     return errCode;
157 }
158 
RemoveDeviceData()159 int SQLiteRelationalStoreConnection::RemoveDeviceData()
160 {
161     auto *store = GetDB<SQLiteRelationalStore>();
162     if (store == nullptr) {
163         LOGE("[RelationalConnection] store is null, get DB failed!");
164         return -E_INVALID_CONNECTION;
165     }
166 
167     int errCode = store->RemoveDeviceData();
168     if (errCode != E_OK) {
169         LOGE("[RelationalConnection] remove device data failed. %d", errCode);
170     }
171     return errCode;
172 }
173 
GetCloudSyncTaskCount()174 int32_t SQLiteRelationalStoreConnection::GetCloudSyncTaskCount()
175 {
176     auto *store = GetDB<SQLiteRelationalStore>();
177     if (store == nullptr) {
178         LOGE("[RelationalConnection] store is null, get DB failed!");
179         return -1;
180     }
181     int32_t count = store->GetCloudSyncTaskCount();
182     if (count == -1) {
183         LOGE("[RelationalConnection] failed to get cloud sync task count");
184     }
185     return count;
186 }
187 
DoClean(ClearMode mode)188 int SQLiteRelationalStoreConnection::DoClean(ClearMode mode)
189 {
190     auto *store = GetDB<SQLiteRelationalStore>();
191     if (store == nullptr) {
192         LOGE("[RelationalConnection] store is null, get DB failed!");
193         return -E_INVALID_CONNECTION;
194     }
195 
196     int errCode = store->CleanCloudData(mode);
197     if (errCode != E_OK) {
198         LOGE("[RelationalConnection] failed to clean cloud data, %d.", errCode);
199     }
200     return errCode;
201 }
202 
RemoveDeviceData(const std::string & device)203 int SQLiteRelationalStoreConnection::RemoveDeviceData(const std::string &device)
204 {
205     return RemoveDeviceData(device, {});
206 }
207 
RemoveDeviceData(const std::string & device,const std::string & tableName)208 int SQLiteRelationalStoreConnection::RemoveDeviceData(const std::string &device, const std::string &tableName)
209 {
210     auto *store = GetDB<SQLiteRelationalStore>();
211     if (store == nullptr) {
212         LOGE("[RelationalConnection] store is null, get DB failed!");
213         return -E_INVALID_CONNECTION;
214     }
215 
216     int errCode = store->RemoveDeviceData(device, tableName);
217     if (errCode != E_OK) {
218         LOGE("[RelationalConnection] remove device data failed. %d", errCode);
219     }
220     return errCode;
221 }
222 
Pragma(int cmd,void * parameter)223 int SQLiteRelationalStoreConnection::Pragma(int cmd, void *parameter) // reserve for interface function fix
224 {
225     (void)cmd;
226     (void)parameter;
227     return E_OK;
228 }
229 
SyncToDevice(SyncInfo & info)230 int SQLiteRelationalStoreConnection::SyncToDevice(SyncInfo &info)
231 {
232     auto *store = GetDB<SQLiteRelationalStore>();
233     if (store == nullptr) {
234         LOGE("[RelationalConnection] store is null, get executor failed!");
235         return -E_INVALID_CONNECTION;
236     }
237 
238     {
239         AutoLock lockGuard(this);
240         if (IsKilled()) {
241             // If this happens, users are using a closed connection.
242             LOGE("Sync on a closed connection.");
243             return -E_STALE;
244         }
245         IncObjRef(this);
246     }
247     ISyncer::SyncParma syncParam;
248     syncParam.devices = info.devices;
249     syncParam.mode = info.mode;
250     syncParam.wait = info.wait;
251     syncParam.isQuerySync = true;
252     syncParam.relationOnComplete = info.onComplete;
253     syncParam.syncQuery = QuerySyncObject(info.query);
254     syncParam.onFinalize =  [this]() { DecObjRef(this); };
255     if (syncParam.syncQuery.GetSortType() != SortType::NONE) {
256         LOGE("not support order by timestamp");
257         DecObjRef(this);
258         return -E_NOT_SUPPORT;
259     }
260     int errCode = store->Sync(syncParam, GetConnectionId());
261     if (errCode != E_OK) {
262         DecObjRef(this);
263         return errCode;
264     }
265     return E_OK;
266 }
267 
RegisterLifeCycleCallback(const DatabaseLifeCycleNotifier & notifier)268 int SQLiteRelationalStoreConnection::RegisterLifeCycleCallback(const DatabaseLifeCycleNotifier &notifier)
269 {
270     auto *store = GetDB<SQLiteRelationalStore>();
271     if (store == nullptr) {
272         LOGE("[RelationalConnection] store is null, get executor failed!");
273         return -E_INVALID_CONNECTION;
274     }
275 
276     return store->RegisterLifeCycleCallback(notifier);
277 }
278 
RegisterObserverAction(const RelationalObserverAction & action)279 void SQLiteRelationalStoreConnection::RegisterObserverAction(const RelationalObserverAction &action)
280 {
281     static_cast<SQLiteRelationalStore *>(store_)->RegisterObserverAction(GetConnectionId(), action);
282 }
283 
RemoteQuery(const std::string & device,const RemoteCondition & condition,uint64_t timeout,std::shared_ptr<ResultSet> & result)284 int SQLiteRelationalStoreConnection::RemoteQuery(const std::string &device, const RemoteCondition &condition,
285     uint64_t timeout, std::shared_ptr<ResultSet> &result)
286 {
287     auto *store = GetDB<SQLiteRelationalStore>();
288     if (store == nullptr) {
289         LOGE("[RelationalConnection] store is null, get executor failed!");
290         return -E_INVALID_CONNECTION;
291     }
292     return store->RemoteQuery(device, condition, timeout, GetConnectionId(), result);
293 }
294 
SetCloudDB(const std::shared_ptr<ICloudDb> & cloudDb)295 int SQLiteRelationalStoreConnection::SetCloudDB(const std::shared_ptr<ICloudDb> &cloudDb)
296 {
297     auto *store = GetDB<SQLiteRelationalStore>();
298     if (store == nullptr) {
299         LOGE("[RelationalConnection] store is null, get DB failed!");
300         return -E_INVALID_CONNECTION;
301     }
302 
303     return store->SetCloudDB(cloudDb);
304 }
305 
SetCloudDbSchema(const DataBaseSchema & schema)306 int SQLiteRelationalStoreConnection::SetCloudDbSchema(const DataBaseSchema &schema)
307 {
308     auto *store = GetDB<SQLiteRelationalStore>();
309     if (store == nullptr) {
310         LOGE("[RelationalConnection] store is null, get DB failed!");
311         return -E_INVALID_CONNECTION;
312     }
313 
314     int ret = store->SetCloudDbSchema(schema);
315     if (ret != E_OK) {
316         LOGE("[RelationalConnection] SetCloudDbSchema failed. %d", ret);
317     }
318     return ret;
319 }
320 
SetIAssetLoader(const std::shared_ptr<IAssetLoader> & loader)321 int SQLiteRelationalStoreConnection::SetIAssetLoader(const std::shared_ptr<IAssetLoader> &loader)
322 {
323     auto *store = GetDB<SQLiteRelationalStore>();
324     if (store == nullptr) {
325         LOGE("[RelationalConnection] store is null, get DB failed!");
326         return -E_INVALID_CONNECTION;
327     }
328 
329     int ret = store->SetIAssetLoader(loader);
330     if (ret != E_OK) {
331         LOGE("[RelationalConnection] Set asset loader failed. %d", ret);
332     }
333     return E_OK;
334 }
335 
Sync(const std::vector<std::string> & devices,SyncMode mode,const Query & query,const SyncProcessCallback & onProcess,int64_t waitTime)336 int SQLiteRelationalStoreConnection::Sync(const std::vector<std::string> &devices, SyncMode mode, const Query &query,
337     const SyncProcessCallback &onProcess, int64_t waitTime)
338 {
339     auto *store = GetDB<SQLiteRelationalStore>();
340     if (store == nullptr) {
341         LOGE("[RelationalConnection] store is null, get executor failed!");
342         return -E_INVALID_CONNECTION;
343     }
344     {
345         AutoLock lockGuard(this);
346         if (IsKilled()) {
347             // If this happens, users are using a closed connection.
348             LOGE("Sync on a closed connection.");
349             return -E_STALE;
350         }
351         IncObjRef(this);
352     }
353     int errCode = store->Sync(devices, mode, query, onProcess, waitTime);
354     DecObjRef(this);
355     return errCode;
356 }
357 
GetStoreInfo(std::string & userId,std::string & appId,std::string & storeId)358 int SQLiteRelationalStoreConnection::GetStoreInfo(std::string &userId, std::string &appId, std::string &storeId)
359 {
360     auto *store = GetDB<SQLiteRelationalStore>();
361     if (store == nullptr) {
362         LOGE("[RelationalConnection] store is null, get storeInfo failed!");
363         return -E_INVALID_CONNECTION;
364     }
365     auto properties = store->GetProperties();
366     userId = properties.GetStringProp(RelationalDBProperties::USER_ID, "");
367     appId = properties.GetStringProp(RelationalDBProperties::APP_ID, "");
368     storeId = properties.GetStringProp(RelationalDBProperties::STORE_ID, "");
369     return E_OK;
370 }
371 }
372 #endif