• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "rdb_store_impl.h"
17 #include <sstream>
18 #include <unistd.h>
19 #include "logger.h"
20 #include "rdb_perf_trace.h"
21 #include "rdb_errno.h"
22 #include "rdb_manager.h"
23 #include "sqlite_shared_result_set.h"
24 #include "sqlite_sql_builder.h"
25 #include "sqlite_utils.h"
26 #include "step_result_set.h"
27 #include "relational_store_manager.h"
28 
29 namespace OHOS::NativeRdb {
Open(const RdbStoreConfig & config,int & errCode)30 std::shared_ptr<RdbStore> RdbStoreImpl::Open(const RdbStoreConfig &config, int &errCode)
31 {
32     std::shared_ptr<RdbStoreImpl> rdbStore = std::make_shared<RdbStoreImpl>();
33     errCode = rdbStore->InnerOpen(config);
34     if (errCode != E_OK) {
35         return nullptr;
36     }
37 
38     return rdbStore;
39 }
40 
RemoveSuffix(const std::string & name)41 static std::string RemoveSuffix(const std::string& name)
42 {
43     std::string suffix(".db");
44     auto pos = name.rfind(suffix);
45     if (pos == std::string::npos || pos < name.length() - suffix.length()) {
46         return name;
47     }
48     return std::string(name, 0, pos);
49 }
50 
InnerOpen(const RdbStoreConfig & config)51 int RdbStoreImpl::InnerOpen(const RdbStoreConfig &config)
52 {
53     RDB_TRACE_BEGIN("rdb open");
54     int errCode = E_OK;
55     connectionPool = SqliteConnectionPool::Create(config, errCode);
56     if (connectionPool == nullptr) {
57         RDB_TRACE_END();
58         return errCode;
59     }
60     isOpen = true;
61     path = config.GetPath();
62     orgPath = path;
63     isReadOnly = config.IsReadOnly();
64     isMemoryRdb = config.IsMemoryRdb();
65     name = config.GetName();
66     fileSecurityLevel = config.GetDatabaseFileSecurityLevel();
67     fileType = config.GetDatabaseFileType();
68     syncerParam_ = { config.GetBundleName(), config.GetAppModuleName() + '/' + config.GetRelativePath(),
69                    RemoveSuffix(config.GetName()), config.GetEncryptLevel(), "", config.GetDistributedType() };
70     RDB_TRACE_END();
71     return E_OK;
72 }
73 
RdbStoreImpl()74 RdbStoreImpl::RdbStoreImpl()
75     : connectionPool(nullptr), isOpen(false), path(""), orgPath(""), isReadOnly(false), isMemoryRdb(false)
76 {
77 }
78 
~RdbStoreImpl()79 RdbStoreImpl::~RdbStoreImpl()
80 {
81     delete connectionPool;
82     threadMap.clear();
83     idleSessions.clear();
84 }
85 
GetThreadSession()86 std::shared_ptr<StoreSession> RdbStoreImpl::GetThreadSession()
87 {
88     std::thread::id tid = std::this_thread::get_id();
89     std::lock_guard<std::mutex> lock(sessionMutex);
90 
91     auto iter = threadMap.find(tid);
92     if (iter != threadMap.end()) {
93         iter->second.second++; // useCount++
94         return iter->second.first;
95     }
96 
97     // get from idle stack
98     std::shared_ptr<StoreSession> session;
99     if (idleSessions.empty()) {
100         session = std::make_shared<StoreSession>(*connectionPool);
101     } else {
102         session = idleSessions.back();
103         idleSessions.pop_back();
104     }
105 
106     threadMap.insert(std::make_pair(tid, std::make_pair(session, 1))); // useCount is 1
107     return session;
108 }
109 
ReleaseThreadSession()110 void RdbStoreImpl::ReleaseThreadSession()
111 {
112     std::thread::id tid = std::this_thread::get_id();
113     std::lock_guard<std::mutex> lock(sessionMutex);
114 
115     auto iter = threadMap.find(tid);
116     if (iter == threadMap.end()) {
117         LOG_ERROR("RdbStoreImpl ReleaseThreadSession: no session found for the current thread");
118         return;
119     }
120     int &useCount = iter->second.second;
121     useCount--;
122     if (useCount > 0) {
123         return;
124     }
125 
126     if (idleSessions.size() < MAX_IDLE_SESSION_SIZE) {
127         idleSessions.push_back(iter->second.first);
128     }
129     threadMap.erase(iter);
130 }
131 
Insert(int64_t & outRowId,const std::string & table,const ValuesBucket & initialValues)132 int RdbStoreImpl::Insert(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues)
133 {
134     return InsertWithConflictResolution(outRowId, table, initialValues, ConflictResolution::ON_CONFLICT_NONE);
135 }
136 
Replace(int64_t & outRowId,const std::string & table,const ValuesBucket & initialValues)137 int RdbStoreImpl::Replace(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues)
138 {
139     return InsertWithConflictResolution(outRowId, table, initialValues, ConflictResolution::ON_CONFLICT_REPLACE);
140 }
141 
InsertWithConflictResolution(int64_t & outRowId,const std::string & table,const ValuesBucket & initialValues,ConflictResolution conflictResolution)142 int RdbStoreImpl::InsertWithConflictResolution(int64_t &outRowId, const std::string &table,
143     const ValuesBucket &initialValues, ConflictResolution conflictResolution)
144 {
145     if (table.empty()) {
146         return E_EMPTY_TABLE_NAME;
147     }
148 
149     if (initialValues.IsEmpty()) {
150         return E_EMPTY_VALUES_BUCKET;
151     }
152 
153     RDB_TRACE_BEGIN("rdb insert");
154     std::string conflictClause;
155     int errCode = SqliteUtils::GetConflictClause(static_cast<int>(conflictResolution), conflictClause);
156     if (errCode != E_OK) {
157         RDB_TRACE_END();
158         return errCode;
159     }
160 
161     std::stringstream sql;
162     sql << "INSERT" << conflictClause << " INTO " << table << '(';
163 
164     std::map<std::string, ValueObject> valuesMap;
165     initialValues.GetAll(valuesMap);
166     std::vector<ValueObject> bindArgs;
167     for (auto iter = valuesMap.begin(); iter != valuesMap.end(); iter++) {
168         sql << ((iter == valuesMap.begin()) ? "" : ",");
169         sql << iter->first;               // columnName
170         bindArgs.push_back(iter->second); // columnValue
171     }
172 
173     sql << ") VALUES (";
174     for (size_t i = 0; i < valuesMap.size(); i++) {
175         sql << ((i == 0) ? "?" : ",?");
176     }
177     sql << ')';
178 
179     std::shared_ptr<StoreSession> session = GetThreadSession();
180     errCode = session->ExecuteForLastInsertedRowId(outRowId, sql.str(), bindArgs);
181     ReleaseThreadSession();
182     RDB_TRACE_END();
183     return errCode;
184 }
185 
Update(int & changedRows,const std::string & table,const ValuesBucket & values,const std::string & whereClause,const std::vector<std::string> & whereArgs)186 int RdbStoreImpl::Update(int &changedRows, const std::string &table, const ValuesBucket &values,
187     const std::string &whereClause, const std::vector<std::string> &whereArgs)
188 {
189     return UpdateWithConflictResolution(
190         changedRows, table, values, whereClause, whereArgs, ConflictResolution::ON_CONFLICT_NONE);
191 }
192 
Update(int & changedRows,const ValuesBucket & values,const AbsRdbPredicates & predicates)193 int RdbStoreImpl::Update(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates)
194 {
195     return Update(
196         changedRows, predicates.GetTableName(), values, predicates.GetWhereClause(), predicates.GetWhereArgs());
197 }
198 
UpdateWithConflictResolution(int & changedRows,const std::string & table,const ValuesBucket & values,const std::string & whereClause,const std::vector<std::string> & whereArgs,ConflictResolution conflictResolution)199 int RdbStoreImpl::UpdateWithConflictResolution(int &changedRows, const std::string &table, const ValuesBucket &values,
200     const std::string &whereClause, const std::vector<std::string> &whereArgs, ConflictResolution conflictResolution)
201 {
202     if (table.empty()) {
203         return E_EMPTY_TABLE_NAME;
204     }
205 
206     if (values.IsEmpty()) {
207         return E_EMPTY_VALUES_BUCKET;
208     }
209 
210     RDB_TRACE_BEGIN("rdb update");
211     std::string conflictClause;
212     int errCode = SqliteUtils::GetConflictClause(static_cast<int>(conflictResolution), conflictClause);
213     if (errCode != E_OK) {
214         RDB_TRACE_END();
215         return errCode;
216     }
217 
218     std::stringstream sql;
219     sql << "UPDATE" << conflictClause << " " << table << " SET ";
220 
221     std::map<std::string, ValueObject> valuesMap;
222     values.GetAll(valuesMap);
223     std::vector<ValueObject> bindArgs;
224     for (auto iter = valuesMap.begin(); iter != valuesMap.end(); iter++) {
225         sql << ((iter == valuesMap.begin()) ? "" : ",");
226         sql << iter->first << "=?";       // columnName
227         bindArgs.push_back(iter->second); // columnValue
228     }
229 
230     if (whereClause.empty() == false) {
231         sql << " WHERE " << whereClause;
232     }
233 
234     for (auto &iter : whereArgs) {
235         bindArgs.push_back(ValueObject(iter));
236     }
237 
238     std::shared_ptr<StoreSession> session = GetThreadSession();
239     errCode = session->ExecuteForChangedRowCount(changedRows, sql.str(), bindArgs);
240     ReleaseThreadSession();
241     RDB_TRACE_END();
242     return errCode;
243 }
244 
Delete(int & deletedRows,const AbsRdbPredicates & predicates)245 int RdbStoreImpl::Delete(int &deletedRows, const AbsRdbPredicates &predicates)
246 {
247     return Delete(deletedRows, predicates.GetTableName(), predicates.GetWhereClause(), predicates.GetWhereArgs());
248 }
249 
Delete(int & deletedRows,const std::string & table,const std::string & whereClause,const std::vector<std::string> & whereArgs)250 int RdbStoreImpl::Delete(int &deletedRows, const std::string &table, const std::string &whereClause,
251     const std::vector<std::string> &whereArgs)
252 {
253     if (table.empty()) {
254         return E_EMPTY_TABLE_NAME;
255     }
256 
257     RDB_TRACE_BEGIN("rdb delete");
258     std::stringstream sql;
259     sql << "DELETE FROM " << table;
260     if (whereClause.empty() == false) {
261         sql << " WHERE " << whereClause;
262     }
263 
264     std::vector<ValueObject> bindArgs;
265     for (auto &iter : whereArgs) {
266         bindArgs.push_back(ValueObject(iter));
267     }
268 
269     std::shared_ptr<StoreSession> session = GetThreadSession();
270     int errCode = session->ExecuteForChangedRowCount(deletedRows, sql.str(), bindArgs);
271     ReleaseThreadSession();
272     RDB_TRACE_END();
273     return errCode;
274 }
275 
Query(const AbsRdbPredicates & predicates,const std::vector<std::string> columns)276 std::unique_ptr<AbsSharedResultSet> RdbStoreImpl::Query(
277     const AbsRdbPredicates &predicates, const std::vector<std::string> columns)
278 {
279     LOG_DEBUG("RdbStoreImpl::Query on called.");
280     std::vector<std::string> selectionArgs = predicates.GetWhereArgs();
281     std::string sql = SqliteSqlBuilder::BuildQueryString(predicates, columns);
282     return QuerySql(sql, selectionArgs);
283 }
284 
Query(int & errCode,bool distinct,const std::string & table,const std::vector<std::string> & columns,const std::string & selection,const std::vector<std::string> & selectionArgs,const std::string & groupBy,const std::string & having,const std::string & orderBy,const std::string & limit)285 std::unique_ptr<AbsSharedResultSet> RdbStoreImpl::Query(int &errCode, bool distinct, const std::string &table,
286     const std::vector<std::string> &columns, const std::string &selection,
287     const std::vector<std::string> &selectionArgs, const std::string &groupBy, const std::string &having,
288     const std::string &orderBy, const std::string &limit)
289 {
290     RDB_TRACE_BEGIN("rdb query");
291     std::string sql;
292     errCode = SqliteSqlBuilder::BuildQueryString(distinct, table, columns, selection, groupBy, having, orderBy, limit,
293         "", sql);
294     if (errCode != E_OK) {
295         RDB_TRACE_END();
296         return nullptr;
297     }
298 
299     auto resultSet = QuerySql(sql, selectionArgs);
300     RDB_TRACE_END();
301     return resultSet;
302 }
303 
QuerySql(const std::string & sql,const std::vector<std::string> & selectionArgs)304 std::unique_ptr<AbsSharedResultSet> RdbStoreImpl::QuerySql(const std::string &sql,
305     const std::vector<std::string> &selectionArgs)
306 {
307     RDB_TRACE_BEGIN("rdb query sql");
308     auto resultSet = std::make_unique<SqliteSharedResultSet>(shared_from_this(), path, sql, selectionArgs);
309     RDB_TRACE_END();
310     return resultSet;
311 }
312 
Count(int64_t & outValue,const AbsRdbPredicates & predicates)313 int RdbStoreImpl::Count(int64_t &outValue, const AbsRdbPredicates &predicates)
314 {
315     LOG_DEBUG("RdbStoreImpl::Count on called.");
316     std::vector<std::string> selectionArgs = predicates.GetWhereArgs();
317     std::string sql = SqliteSqlBuilder::BuildCountString(predicates);
318 
319     std::vector<ValueObject> bindArgs;
320     std::vector<std::string> whereArgs = predicates.GetWhereArgs();
321     for (const auto& whereArg : whereArgs) {
322         bindArgs.emplace_back(whereArg);
323     }
324 
325     return ExecuteAndGetLong(outValue, sql, bindArgs);
326 }
327 
ExecuteSql(const std::string & sql,const std::vector<ValueObject> & bindArgs)328 int RdbStoreImpl::ExecuteSql(const std::string &sql, const std::vector<ValueObject> &bindArgs)
329 {
330     int errCode = CheckAttach(sql);
331     if (errCode != E_OK) {
332         return errCode;
333     }
334 
335     std::shared_ptr<StoreSession> session = GetThreadSession();
336     errCode = session->ExecuteSql(sql, bindArgs);
337     if (errCode != E_OK) {
338         LOG_ERROR("RDB_STORE Execute SQL ERROR.");
339         ReleaseThreadSession();
340         return errCode;
341     }
342     int sqlType = SqliteUtils::GetSqlStatementType(sql);
343     if (sqlType == SqliteUtils::STATEMENT_DDL) {
344         errCode = connectionPool->ReOpenAvailableReadConnections();
345     }
346     ReleaseThreadSession();
347     return errCode;
348 }
349 
ExecuteAndGetLong(int64_t & outValue,const std::string & sql,const std::vector<ValueObject> & bindArgs)350 int RdbStoreImpl::ExecuteAndGetLong(int64_t &outValue, const std::string &sql, const std::vector<ValueObject> &bindArgs)
351 {
352     std::shared_ptr<StoreSession> session = GetThreadSession();
353     int errCode = session->ExecuteGetLong(outValue, sql, bindArgs);
354     ReleaseThreadSession();
355     return errCode;
356 }
357 
ExecuteAndGetString(std::string & outValue,const std::string & sql,const std::vector<ValueObject> & bindArgs)358 int RdbStoreImpl::ExecuteAndGetString(
359     std::string &outValue, const std::string &sql, const std::vector<ValueObject> &bindArgs)
360 {
361     std::shared_ptr<StoreSession> session = GetThreadSession();
362     int errCode = session->ExecuteGetString(outValue, sql, bindArgs);
363     ReleaseThreadSession();
364     return errCode;
365 }
366 
ExecuteForLastInsertedRowId(int64_t & outValue,const std::string & sql,const std::vector<ValueObject> & bindArgs)367 int RdbStoreImpl::ExecuteForLastInsertedRowId(int64_t &outValue, const std::string &sql,
368     const std::vector<ValueObject> &bindArgs)
369 {
370     std::shared_ptr<StoreSession> session = GetThreadSession();
371     int errCode = session->ExecuteForLastInsertedRowId(outValue, sql, bindArgs);
372     ReleaseThreadSession();
373     return errCode;
374 }
375 
ExecuteForChangedRowCount(int64_t & outValue,const std::string & sql,const std::vector<ValueObject> & bindArgs)376 int RdbStoreImpl::ExecuteForChangedRowCount(int64_t &outValue, const std::string &sql,
377     const std::vector<ValueObject> &bindArgs)
378 {
379     std::shared_ptr<StoreSession> session = GetThreadSession();
380     int changeRow = 0;
381     int errCode = session->ExecuteForChangedRowCount(changeRow, sql, bindArgs);
382     outValue = changeRow;
383     ReleaseThreadSession();
384     return errCode;
385 }
386 
387 /**
388  * Restores a database from a specified encrypted or unencrypted database file.
389  */
Backup(const std::string databasePath,const std::vector<uint8_t> destEncryptKey)390 int RdbStoreImpl::Backup(const std::string databasePath, const std::vector<uint8_t> destEncryptKey)
391 {
392     std::shared_ptr<StoreSession> session = GetThreadSession();
393     int errCode = session->Backup(databasePath, destEncryptKey);
394     ReleaseThreadSession();
395     return errCode;
396 }
397 
IsHoldingConnection()398 bool RdbStoreImpl::IsHoldingConnection()
399 {
400     std::shared_ptr<StoreSession> session = GetThreadSession();
401     return session->IsHoldingConnection();
402 }
403 
GiveConnectionTemporarily(long milliseconds)404 int RdbStoreImpl::GiveConnectionTemporarily(long milliseconds)
405 {
406     std::shared_ptr<StoreSession> session = GetThreadSession();
407     return session->GiveConnectionTemporarily(milliseconds);
408 }
409 
410 /**
411  * Attaches a database.
412  */
Attach(const std::string & alias,const std::string & pathName,const std::vector<uint8_t> destEncryptKey)413 int RdbStoreImpl::Attach(const std::string &alias, const std::string &pathName,
414     const std::vector<uint8_t> destEncryptKey)
415 {
416     std::shared_ptr<StoreSession> session = GetThreadSession();
417     int errCode = session->Attach(alias, pathName, destEncryptKey);
418     ReleaseThreadSession();
419     return errCode;
420 }
421 
422 /**
423  * Obtains the database version.
424  */
GetVersion(int & version)425 int RdbStoreImpl::GetVersion(int &version)
426 {
427     int64_t value;
428     int errCode = ExecuteAndGetLong(value, "PRAGMA user_version;", std::vector<ValueObject>());
429     version = static_cast<int>(value);
430     return errCode;
431 }
432 
433 /**
434  * Sets the version of a new database.
435  */
SetVersion(int version)436 int RdbStoreImpl::SetVersion(int version)
437 {
438     std::string sql = "PRAGMA user_version = " + std::to_string(version);
439     return ExecuteSql(sql, std::vector<ValueObject>());
440 }
441 
442 /**
443  * Begins a transaction in EXCLUSIVE mode.
444  */
BeginTransaction()445 int RdbStoreImpl::BeginTransaction()
446 {
447     std::shared_ptr<StoreSession> session = GetThreadSession();
448     int errCode = session->BeginTransaction();
449     if (errCode != E_OK) {
450         ReleaseThreadSession();
451     }
452     return errCode;
453 }
454 
455 /**
456 * Begins a transaction in EXCLUSIVE mode.
457 */
RollBack()458 int RdbStoreImpl::RollBack()
459 {
460     std::shared_ptr<StoreSession> session = GetThreadSession();
461     int errCode = session->RollBack();
462     if (errCode != E_OK) {
463         ReleaseThreadSession();
464     }
465     return errCode;
466 }
467 
468 /**
469 * Begins a transaction in EXCLUSIVE mode.
470 */
Commit()471 int RdbStoreImpl::Commit()
472 {
473     LOG_DEBUG("Enter Commit");
474     std::shared_ptr<StoreSession> session = GetThreadSession();
475     int errCode = session->Commit();
476     if (errCode != E_OK) {
477         ReleaseThreadSession();
478     }
479     return errCode;
480 }
481 
BeginTransactionWithObserver(TransactionObserver * transactionObserver)482 int RdbStoreImpl::BeginTransactionWithObserver(TransactionObserver *transactionObserver)
483 {
484     transactionObserverStack.push(transactionObserver);
485     std::shared_ptr<StoreSession> session = GetThreadSession();
486     int errCode = session->BeginTransaction(transactionObserver);
487     if (errCode != E_OK) {
488         ReleaseThreadSession();
489     }
490     return errCode;
491 }
492 
MarkAsCommit()493 int RdbStoreImpl::MarkAsCommit()
494 {
495     std::shared_ptr<StoreSession> session = GetThreadSession();
496     int errCode = session->MarkAsCommit();
497     ReleaseThreadSession();
498     return errCode;
499 }
500 
EndTransaction()501 int RdbStoreImpl::EndTransaction()
502 {
503     TransactionObserver *transactionObserver = nullptr;
504     if (transactionObserverStack.size() > 0) {
505         transactionObserver = transactionObserverStack.top();
506         transactionObserverStack.pop();
507     }
508 
509     std::shared_ptr<StoreSession> session = GetThreadSession();
510     int errCode = session->EndTransactionWithObserver(transactionObserver);
511     // release the session got in EndTransaction()
512     ReleaseThreadSession();
513     // release the session got in BeginTransaction()
514     ReleaseThreadSession();
515 
516     if (!transactionObserver) {
517         delete transactionObserver;
518     }
519 
520     return errCode;
521 }
522 
IsInTransaction()523 bool RdbStoreImpl::IsInTransaction()
524 {
525     std::shared_ptr<StoreSession> session = GetThreadSession();
526     bool inTransaction = session->IsInTransaction();
527     ReleaseThreadSession();
528     return inTransaction;
529 }
530 
ChangeEncryptKey(const std::vector<uint8_t> & newKey)531 int RdbStoreImpl::ChangeEncryptKey(const std::vector<uint8_t> &newKey)
532 {
533     return connectionPool->ChangeEncryptKey(newKey);
534 }
535 
BeginStepQuery(int & errCode,const std::string sql,const std::vector<std::string> & bindArgs)536 std::shared_ptr<SqliteStatement> RdbStoreImpl::BeginStepQuery(
537     int &errCode, const std::string sql, const std::vector<std::string> &bindArgs)
538 {
539     std::shared_ptr<StoreSession> session = GetThreadSession();
540     return session->BeginStepQuery(errCode, sql, bindArgs);
541 }
542 
EndStepQuery()543 int RdbStoreImpl::EndStepQuery()
544 {
545     std::shared_ptr<StoreSession> session = GetThreadSession();
546     int err = session->EndStepQuery();
547     ReleaseThreadSession(); // release session got by EndStepQuery
548     ReleaseThreadSession(); // release session got by BeginStepQuery
549     return err;
550 }
551 
CheckAttach(const std::string & sql)552 int RdbStoreImpl::CheckAttach(const std::string &sql)
553 {
554     size_t index = sql.find_first_not_of(' ');
555     if (index == std::string::npos) {
556         return E_OK;
557     }
558 
559     /* The first 3 characters can determine the type */
560     std::string sqlType = sql.substr(index, 3);
561     sqlType = SqliteUtils::StrToUpper(sqlType);
562     if (sqlType != "ATT") {
563         return E_OK;
564     }
565 
566     std::string journalMode;
567     int errCode = ExecuteAndGetString(journalMode, "PRAGMA journal_mode", std::vector<ValueObject>());
568     if (errCode != E_OK) {
569         LOG_ERROR("RdbStoreImpl CheckAttach fail to get journal mode : %{public}d", errCode);
570         return errCode;
571     }
572 
573     journalMode = SqliteUtils::StrToUpper(journalMode);
574     if (journalMode == "WAL") {
575         LOG_ERROR("RdbStoreImpl attach is not supported in WAL mode");
576         return E_NOT_SUPPORTED_ATTACH_IN_WAL_MODE;
577     }
578 
579     return E_OK;
580 }
581 
IsOpen() const582 bool RdbStoreImpl::IsOpen() const
583 {
584     return isOpen;
585 }
586 
GetPath()587 std::string RdbStoreImpl::GetPath()
588 {
589     return path;
590 }
591 
GetOrgPath()592 std::string RdbStoreImpl::GetOrgPath()
593 {
594     return orgPath;
595 }
596 
IsReadOnly() const597 bool RdbStoreImpl::IsReadOnly() const
598 {
599     return isReadOnly;
600 }
601 
IsMemoryRdb() const602 bool RdbStoreImpl::IsMemoryRdb() const
603 {
604     return isMemoryRdb;
605 }
606 
GetName()607 std::string RdbStoreImpl::GetName()
608 {
609     return name;
610 }
GetFileType()611 std::string RdbStoreImpl::GetFileType()
612 {
613     return fileType;
614 }
615 
GetFileSecurityLevel()616 std::string RdbStoreImpl::GetFileSecurityLevel()
617 {
618     return fileSecurityLevel;
619 }
620 
PrepareAndGetInfo(const std::string & sql,bool & outIsReadOnly,int & numParameters,std::vector<std::string> & columnNames)621 int RdbStoreImpl::PrepareAndGetInfo(const std::string &sql, bool &outIsReadOnly, int &numParameters,
622     std::vector<std::string> &columnNames)
623 {
624     std::shared_ptr<StoreSession> session = GetThreadSession();
625 
626     int errCode = session->PrepareAndGetInfo(sql, outIsReadOnly, numParameters, columnNames);
627     ReleaseThreadSession();
628     return errCode;
629 }
630 
631 /**
632  * Sets the database locale.
633  */
ConfigLocale(const std::string localeStr)634 int RdbStoreImpl::ConfigLocale(const std::string localeStr)
635 {
636     if (isOpen == false) {
637         LOG_ERROR("The connection pool has been closed.");
638         return E_ERROR;
639     }
640 
641     if (connectionPool == nullptr) {
642         LOG_ERROR("connectionPool is null");
643         return E_ERROR;
644     }
645     return connectionPool->ConfigLocale(localeStr);
646 }
647 
648 /**
649  * Restores a database from a specified encrypted or unencrypted database file.
650  */
ChangeDbFileForRestore(const std::string newPath,const std::string backupPath,const std::vector<uint8_t> & newKey)651 int RdbStoreImpl::ChangeDbFileForRestore(const std::string newPath, const std::string backupPath,
652     const std::vector<uint8_t> &newKey)
653 {
654     if (isOpen == false) {
655         LOG_ERROR("The connection pool has been closed.");
656         return E_ERROR;
657     }
658 
659     if (connectionPool == nullptr) {
660         LOG_ERROR("connectionPool is null");
661         return E_ERROR;
662     }
663     path = newPath;
664     return connectionPool->ChangeDbFileForRestore(newPath, backupPath, newKey);
665 }
ExecuteForSharedBlock(int & rowNum,AppDataFwk::SharedBlock * sharedBlock,int startPos,int requiredPos,bool isCountAllRows,std::string sql,std::vector<ValueObject> & bindArgVec)666 int RdbStoreImpl::ExecuteForSharedBlock(int &rowNum, AppDataFwk::SharedBlock *sharedBlock, int startPos,
667     int requiredPos, bool isCountAllRows, std::string sql, std::vector<ValueObject> &bindArgVec)
668 {
669     std::shared_ptr<StoreSession> session = GetThreadSession();
670     int errCode =
671         session->ExecuteForSharedBlock(rowNum, sql, bindArgVec, sharedBlock, startPos, requiredPos, isCountAllRows);
672     ReleaseThreadSession();
673     return errCode;
674 }
675 
676 /**
677  * Queries data in the database based on specified conditions.
678  */
QueryByStep(const std::string & sql,const std::vector<std::string> & selectionArgs)679 std::unique_ptr<ResultSet> RdbStoreImpl::QueryByStep(const std::string &sql,
680     const std::vector<std::string> &selectionArgs)
681 {
682     std::unique_ptr<ResultSet> resultSet =
683         std::make_unique<StepResultSet>(shared_from_this(), sql, selectionArgs);
684     return resultSet;
685 }
686 
SetDistributedTables(const std::vector<std::string> & tables)687 bool RdbStoreImpl::SetDistributedTables(const std::vector<std::string> &tables)
688 {
689     auto service = DistributedRdb::RdbManager::GetRdbService(syncerParam_);
690     if (service == nullptr) {
691         return false;
692     }
693     if (service->SetDistributedTables(syncerParam_, tables) != 0) {
694         LOG_ERROR("failed");
695         return false;
696     }
697     LOG_ERROR("success");
698     return true;
699 }
700 
ObtainDistributedTableName(const std::string & device,const std::string & table)701 std::string RdbStoreImpl::ObtainDistributedTableName(const std::string &device, const std::string &table)
702 {
703     RDB_TRACE_BEGIN("rdb obtain dist table name");
704     auto service = DistributedRdb::RdbManager::GetRdbService(syncerParam_);
705     if (service == nullptr) {
706         RDB_TRACE_END();
707         return "";
708     }
709     auto distTable = service->ObtainDistributedTableName(device, table);
710     RDB_TRACE_END();
711     return distTable;
712 }
713 
Sync(const SyncOption & option,const AbsRdbPredicates & predicate,const SyncCallback & callback)714 bool RdbStoreImpl::Sync(const SyncOption &option, const AbsRdbPredicates &predicate, const SyncCallback &callback)
715 {
716     RDB_TRACE_BEGIN("rdb sync");
717     auto service = DistributedRdb::RdbManager::GetRdbService(syncerParam_);
718     if (service == nullptr) {
719         RDB_TRACE_END();
720         return false;
721     }
722     if (service->Sync(syncerParam_, option, predicate.GetDistributedPredicates(), callback) != 0) {
723         LOG_ERROR("failed");
724         RDB_TRACE_END();
725         return false;
726     }
727     LOG_INFO("success");
728     RDB_TRACE_END();
729     return true;
730 }
731 
Subscribe(const SubscribeOption & option,RdbStoreObserver * observer)732 bool RdbStoreImpl::Subscribe(const SubscribeOption &option, RdbStoreObserver *observer)
733 {
734     LOG_INFO("enter");
735     auto service = DistributedRdb::RdbManager::GetRdbService(syncerParam_);
736     if (service == nullptr) {
737         return false;
738     }
739     return service->Subscribe(syncerParam_, option, observer) == 0;
740 }
741 
UnSubscribe(const SubscribeOption & option,RdbStoreObserver * observer)742 bool RdbStoreImpl::UnSubscribe(const SubscribeOption &option, RdbStoreObserver *observer)
743 {
744     LOG_INFO("enter");
745     auto service = DistributedRdb::RdbManager::GetRdbService(syncerParam_);
746     if (service == nullptr) {
747         return false;
748     }
749     return service->UnSubscribe(syncerParam_, option, observer) == 0;
750 }
751 
DropDeviceData(const std::vector<std::string> & devices,const DropOption & option)752 bool RdbStoreImpl::DropDeviceData(const std::vector<std::string> &devices, const DropOption &option)
753 {
754     LOG_INFO("not implement");
755     return true;
756 }
757 }
758