1 /*
2 * Copyright (c) 2024 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 #include "rdb_store.h"
16
17 #include "sqlite_sql_builder.h"
18 #include "sqlite_utils.h"
19 #include "traits.h"
20 namespace OHOS::NativeRdb {
ModifyTime(std::shared_ptr<ResultSet> result,std::map<std::vector<uint8_t>,PRIKey> hashKeys,bool isFromRowId)21 RdbStore::ModifyTime::ModifyTime(std::shared_ptr<ResultSet> result, std::map<std::vector<uint8_t>, PRIKey> hashKeys,
22 bool isFromRowId)
23 : result_(std::move(result)), hash_(std::move(hashKeys)), isFromRowId_(isFromRowId)
24 {
25 for (auto &[_, priKey] : hash_) {
26 if (priKey.index() != Traits::variant_index_of_v<std::string, PRIKey>) {
27 break;
28 }
29 auto *val = Traits::get_if<std::string>(&priKey);
30 if (val != nullptr && maxOriginKeySize_ <= val->length()) {
31 maxOriginKeySize_ = val->length() + 1;
32 }
33 }
34 }
35
36 RdbStore::ModifyTime::operator std::map<PRIKey, Date>()
37 {
38 if (result_ == nullptr) {
39 return {};
40 }
41 int count = 0;
42 if (result_->GetRowCount(count) != E_OK || count <= 0) {
43 return {};
44 }
45 std::map<PRIKey, Date> result;
46 for (int i = 0; i < count; i++) {
47 result_->GoToRow(i);
48 int64_t timeStamp = 0;
49 result_->GetLong(1, timeStamp);
50 PRIKey index = 0;
51 if (isFromRowId_) {
52 int64_t rowid = 0;
53 result_->GetLong(0, rowid);
54 index = rowid;
55 } else {
56 std::vector<uint8_t> hashKey;
57 result_->GetBlob(0, hashKey);
58 index = hash_[hashKey];
59 }
60 result[index] = Date(timeStamp);
61 }
62 return result;
63 }
64
65 RdbStore::ModifyTime::operator std::shared_ptr<ResultSet>()
66 {
67 return result_;
68 }
69
GetOriginKey(const std::vector<uint8_t> & hash)70 RdbStore::PRIKey RdbStore::ModifyTime::GetOriginKey(const std::vector<uint8_t> &hash)
71 {
72 auto it = hash_.find(hash);
73 return it != hash_.end() ? it->second : std::monostate();
74 }
75
GetMaxOriginKeySize()76 size_t RdbStore::ModifyTime::GetMaxOriginKeySize()
77 {
78 return maxOriginKeySize_;
79 }
80
NeedConvert() const81 bool RdbStore::ModifyTime::NeedConvert() const
82 {
83 return !hash_.empty();
84 }
85
ToValues(const std::vector<std::string> & args)86 static std::vector<ValueObject> ToValues(const std::vector<std::string> &args)
87 {
88 std::vector<ValueObject> newArgs;
89 std::for_each(args.begin(), args.end(), [&newArgs](const auto &it) {
90 newArgs.push_back(ValueObject(it));
91 });
92 return newArgs;
93 }
94
ColHasSpecificField(const std::vector<std::string> & columns)95 static bool ColHasSpecificField(const std::vector<std::string> &columns)
96 {
97 for (const std::string &column : columns) {
98 if (column.find(SqliteUtils::REP) != std::string::npos) {
99 return true;
100 }
101 }
102 return false;
103 }
104
Insert(const std::string & table,const Row & row,Resolution resolution)105 std::pair<int, int64_t> RdbStore::Insert(const std::string &table, const Row &row, Resolution resolution)
106 {
107 (void)table;
108 (void)row;
109 (void)resolution;
110 return { E_NOT_SUPPORT, -1 };
111 }
112
Insert(int64_t & outRowId,const std::string & table,const Row & row)113 int RdbStore::Insert(int64_t &outRowId, const std::string &table, const Row &row)
114 {
115 auto [errCode, rowid] = Insert(table, row, NO_ACTION);
116 if (errCode == E_OK) {
117 outRowId = rowid;
118 }
119 return errCode;
120 }
121
InsertWithConflictResolution(int64_t & outRowId,const std::string & table,const Row & row,Resolution resolution)122 int RdbStore::InsertWithConflictResolution(int64_t &outRowId, const std::string &table, const Row &row,
123 Resolution resolution)
124 {
125 auto [errCode, rowid] = Insert(table, row, resolution);
126 if (errCode == E_OK) {
127 outRowId = rowid;
128 }
129 return errCode;
130 }
131
Replace(int64_t & outRowId,const std::string & table,const Row & row)132 int RdbStore::Replace(int64_t &outRowId, const std::string &table, const Row &row)
133 {
134 auto [errCode, rowid] = Insert(table, row, Resolution::ON_CONFLICT_REPLACE);
135 if (errCode == E_OK) {
136 outRowId = rowid;
137 }
138 return errCode;
139 }
140
BatchInsert(int64_t & outInsertNum,const std::string & table,const Rows & rows)141 int RdbStore::BatchInsert(int64_t &outInsertNum, const std::string &table, const Rows &rows)
142 {
143 ValuesBuckets refRows;
144 for (auto &row : rows) {
145 refRows.Put(row);
146 }
147 auto [errCode, count] = BatchInsert(table, refRows);
148 if (errCode == E_OK) {
149 outInsertNum = count;
150 }
151 return errCode;
152 }
153
BatchInsert(const std::string & table,const RefRows & rows)154 std::pair<int, int64_t> RdbStore::BatchInsert(const std::string &table, const RefRows &rows)
155 {
156 return { E_NOT_SUPPORT, -1 };
157 }
158
Update(const std::string & table,const Row & row,const std::string & where,const Values & args,Resolution resolution)159 std::pair<int, int> RdbStore::Update(const std::string &table, const Row &row, const std::string &where,
160 const Values &args, Resolution resolution)
161 {
162 (void)table;
163 (void)row;
164 (void)where;
165 (void)args;
166 (void)resolution;
167 return { E_NOT_SUPPORT, 0 };
168 }
169
Update(int & changedRows,const std::string & table,const Row & row,const std::string & whereClause,const Values & args)170 int RdbStore::Update(int &changedRows, const std::string &table, const Row &row, const std::string &whereClause,
171 const Values &args)
172 {
173 auto [errCode, changes] = Update(table, row, whereClause, args, NO_ACTION);
174 if (errCode == E_OK) {
175 changedRows = changes;
176 }
177 return errCode;
178 }
179
Update(int & changedRows,const Row & row,const AbsRdbPredicates & predicates)180 int RdbStore::Update(int &changedRows, const Row &row, const AbsRdbPredicates &predicates)
181 {
182 return Update(changedRows, predicates.GetTableName(), row, predicates.GetWhereClause(), predicates.GetBindArgs());
183 }
184
Update(int & changedRows,const std::string & table,const Row & row,const std::string & whereClause,const Olds & args)185 int RdbStore::Update(int &changedRows, const std::string &table, const Row &row, const std::string &whereClause,
186 const Olds &args)
187 {
188 return Update(changedRows, table, row, whereClause, ToValues(args));
189 };
190
UpdateWithConflictResolution(int & changedRows,const std::string & table,const Row & row,const std::string & whereClause,const Olds & args,Resolution resolution)191 int RdbStore::UpdateWithConflictResolution(int &changedRows, const std::string &table, const Row &row,
192 const std::string &whereClause, const Olds &args, Resolution resolution)
193 {
194 auto [errCode, changes] = Update(table, row, whereClause, ToValues(args), resolution);
195 if (errCode == E_OK) {
196 changedRows = changes;
197 }
198 return errCode;
199 }
200
UpdateWithConflictResolution(int & changedRows,const std::string & table,const Row & row,const std::string & whereClause,const Values & args,Resolution resolution)201 int RdbStore::UpdateWithConflictResolution(int &changedRows, const std::string &table, const Row &row,
202 const std::string &whereClause, const Values &args, Resolution resolution)
203 {
204 auto [errCode, changes] = Update(table, row, whereClause, args, resolution);
205 if (errCode == E_OK) {
206 changedRows = changes;
207 }
208 return errCode;
209 }
210
Delete(int & deletedRows,const std::string & table,const std::string & whereClause,const Olds & args)211 int RdbStore::Delete(int &deletedRows, const std::string &table, const std::string &whereClause, const Olds &args)
212 {
213 return Delete(deletedRows, table, whereClause, ToValues(args));
214 }
215
Delete(int & deletedRows,const AbsRdbPredicates & predicates)216 int RdbStore::Delete(int &deletedRows, const AbsRdbPredicates &predicates)
217 {
218 return Delete(deletedRows, predicates.GetTableName(), predicates.GetWhereClause(), predicates.GetBindArgs());
219 }
220
Query(int & errCode,bool distinct,const std::string & table,const Fields & columns,const std::string & whereClause,const Values & args,const std::string & groupBy,const std::string & indexName,const std::string & orderBy,const int & limit,const int & offset)221 std::shared_ptr<AbsSharedResultSet> RdbStore::Query(int &errCode, bool distinct, const std::string &table,
222 const Fields &columns, const std::string &whereClause, const Values &args, const std::string &groupBy,
223 const std::string &indexName, const std::string &orderBy, const int &limit, const int &offset)
224 {
225 std::string sql;
226 errCode = SqliteSqlBuilder::BuildQueryString(distinct, table, "", columns, whereClause, groupBy, indexName,
227 orderBy, limit, offset, sql);
228 if (errCode != E_OK) {
229 return nullptr;
230 }
231 return QuerySql(sql, args);
232 }
233
Query(const AbsRdbPredicates & predicates,const Fields & columns)234 std::shared_ptr<AbsSharedResultSet> RdbStore::Query(const AbsRdbPredicates &predicates, const Fields &columns)
235 {
236 std::string sql;
237 std::pair<bool, bool> queryStatus = { ColHasSpecificField(columns), predicates.HasSpecificField() };
238 if (queryStatus.first || queryStatus.second) {
239 std::string table = predicates.GetTableName();
240 std::string logTable = GetLogTableName(table);
241 sql = SqliteSqlBuilder::BuildCursorQueryString(predicates, columns, logTable, queryStatus);
242 } else {
243 sql = SqliteSqlBuilder::BuildQueryString(predicates, columns);
244 }
245 return QuerySql(sql, predicates.GetBindArgs());
246 }
247
QuerySql(const std::string & sql,const Olds & args)248 std::shared_ptr<AbsSharedResultSet> RdbStore::QuerySql(const std::string &sql, const Olds &args)
249 {
250 return QuerySql(sql, ToValues(args));
251 }
252
QueryByStep(const std::string & sql,const Olds & args)253 std::shared_ptr<ResultSet> RdbStore::QueryByStep(const std::string &sql, const Olds &args)
254 {
255 return QueryByStep(sql, ToValues(args));
256 }
257
QueryByStep(const AbsRdbPredicates & predicates,const RdbStore::Fields & columns,bool preCount)258 std::shared_ptr<ResultSet> RdbStore::QueryByStep(const AbsRdbPredicates &predicates, const RdbStore::Fields &columns,
259 bool preCount)
260 {
261 std::string sql;
262 if (predicates.HasSpecificField()) {
263 std::string table = predicates.GetTableName();
264 std::string logTable = GetLogTableName(table);
265 sql = SqliteSqlBuilder::BuildLockRowQueryString(predicates, columns, logTable);
266 } else {
267 sql = SqliteSqlBuilder::BuildQueryString(predicates, columns);
268 }
269 return QueryByStep(sql, predicates.GetBindArgs(), preCount);
270 }
271
RemoteQuery(const std::string & device,const AbsRdbPredicates & predicates,const Fields & columns,int & errCode)272 std::shared_ptr<ResultSet> RdbStore::RemoteQuery(const std::string &device, const AbsRdbPredicates &predicates,
273 const Fields &columns, int &errCode)
274 {
275 (void)device;
276 (void)predicates;
277 (void)columns;
278 errCode = E_NOT_SUPPORT;
279 return nullptr;
280 }
281
QuerySharingResource(const AbsRdbPredicates & predicates,const Fields & columns)282 std::pair<int32_t, std::shared_ptr<ResultSet>> RdbStore::QuerySharingResource(const AbsRdbPredicates &predicates,
283 const Fields &columns)
284 {
285 (void)predicates;
286 (void)columns;
287 return { E_NOT_SUPPORT, nullptr };
288 }
289
ExecuteSql(const std::string & sql,const Values & args)290 int RdbStore::ExecuteSql(const std::string &sql, const Values &args)
291 {
292 auto [errCode, value] = Execute(sql, args, 0);
293 return errCode;
294 }
295
Execute(const std::string & sql,const Values & args,int64_t trxId)296 std::pair<int32_t, ValueObject> RdbStore::Execute(const std::string &sql, const Values &args, int64_t trxId)
297 {
298 return { E_NOT_SUPPORT, ValueObject() };
299 }
300
ExecuteAndGetLong(int64_t & outValue,const std::string & sql,const Values & args)301 int RdbStore::ExecuteAndGetLong(int64_t &outValue, const std::string &sql, const Values &args)
302 {
303 auto [errCode, value] = Execute(sql, args);
304 if (errCode == E_OK) {
305 outValue = static_cast<int64_t>(value);
306 }
307 return errCode;
308 }
309
ExecuteAndGetString(std::string & outValue,const std::string & sql,const Values & args)310 int RdbStore::ExecuteAndGetString(std::string &outValue, const std::string &sql, const Values &args)
311 {
312 auto [errCode, value] = Execute(sql, args);
313 if (errCode == E_OK) {
314 outValue = static_cast<std::string>(value);
315 }
316 return errCode;
317 }
318
ExecuteForLastInsertedRowId(int64_t & outValue,const std::string & sql,const Values & args)319 int RdbStore::ExecuteForLastInsertedRowId(int64_t &outValue, const std::string &sql, const Values &args)
320 {
321 auto [errCode, value] = Execute(sql, args);
322 if (errCode == E_OK) {
323 (void)value.GetLong(outValue);
324 }
325 return errCode;
326 }
327
ExecuteForChangedRowCount(int64_t & outValue,const std::string & sql,const Values & args)328 int RdbStore::ExecuteForChangedRowCount(int64_t &outValue, const std::string &sql, const Values &args)
329 {
330 auto [errCode, value] = Execute(sql, args);
331 if (errCode == E_OK) {
332 (void)value.GetLong(outValue);
333 }
334 return errCode;
335 }
336
Backup(const std::string & databasePath,const std::vector<uint8_t> & encryptKey)337 int RdbStore::Backup(const std::string &databasePath, const std::vector<uint8_t> &encryptKey)
338 {
339 (void)databasePath;
340 (void)encryptKey;
341 return E_NOT_SUPPORT;
342 }
343
Attach(const std::string & alias,const std::string & pathName,const std::vector<uint8_t> encryptKey)344 int RdbStore::Attach(const std::string &alias, const std::string &pathName, const std::vector<uint8_t> encryptKey)
345 {
346 (void)alias;
347 (void)pathName;
348 (void)encryptKey;
349 return E_OK;
350 }
351
Count(int64_t & outValue,const AbsRdbPredicates & predicates)352 int RdbStore::Count(int64_t &outValue, const AbsRdbPredicates &predicates)
353 {
354 (void)outValue;
355 (void)predicates;
356 return E_NOT_SUPPORT;
357 }
358
CreateTransaction(int32_t type)359 std::pair<int32_t, std::shared_ptr<Transaction>> RdbStore::CreateTransaction(int32_t type)
360 {
361 (void)type;
362 return { E_NOT_SUPPORT, nullptr };
363 }
364
BeginTransaction()365 int RdbStore::BeginTransaction()
366 {
367 return E_NOT_SUPPORT;
368 }
369
BeginTrans()370 std::pair<int, int64_t> RdbStore::BeginTrans()
371 {
372 return { E_NOT_SUPPORT, 0 };
373 }
374
RollBack()375 int RdbStore::RollBack()
376 {
377 return E_NOT_SUPPORT;
378 }
379
RollBack(int64_t trxId)380 int RdbStore::RollBack(int64_t trxId)
381 {
382 (void)trxId;
383 return E_NOT_SUPPORT;
384 }
385
Commit()386 int RdbStore::Commit()
387 {
388 return E_NOT_SUPPORT;
389 }
390
Commit(int64_t trxId)391 int RdbStore::Commit(int64_t trxId)
392 {
393 (void)trxId;
394 return E_NOT_SUPPORT;
395 }
396
IsInTransaction()397 bool RdbStore::IsInTransaction()
398 {
399 return true;
400 }
401
GetPath()402 std::string RdbStore::GetPath()
403 {
404 return "";
405 }
406
IsHoldingConnection()407 bool RdbStore::IsHoldingConnection()
408 {
409 return true;
410 }
411
IsOpen() const412 bool RdbStore::IsOpen() const
413 {
414 return true;
415 }
416
IsReadOnly() const417 bool RdbStore::IsReadOnly() const
418 {
419 return false;
420 }
421
IsMemoryRdb() const422 bool RdbStore::IsMemoryRdb() const
423 {
424 return false;
425 }
426
Restore(const std::string & backupPath,const std::vector<uint8_t> & newKey)427 int RdbStore::Restore(const std::string &backupPath, const std::vector<uint8_t> &newKey)
428 {
429 (void)backupPath;
430 (void)newKey;
431 return E_NOT_SUPPORT;
432 }
433
SetDistributedTables(const std::vector<std::string> & tables,int32_t type,const DistributedRdb::DistributedConfig & distributedConfig)434 int RdbStore::SetDistributedTables(const std::vector<std::string> &tables, int32_t type,
435 const DistributedRdb::DistributedConfig &distributedConfig)
436 {
437 (void)tables;
438 (void)type;
439 (void)distributedConfig;
440 return E_NOT_SUPPORT;
441 }
442
ObtainDistributedTableName(const std::string & device,const std::string & table,int & errCode)443 std::string RdbStore::ObtainDistributedTableName(const std::string &device, const std::string &table, int &errCode)
444 {
445 errCode = E_NOT_SUPPORT;
446 return table + "_" + device;
447 }
448
Sync(const SyncOption & option,const AbsRdbPredicates & predicate,const AsyncBrief & async)449 int RdbStore::Sync(const SyncOption &option, const AbsRdbPredicates &predicate, const AsyncBrief &async)
450 {
451 (void)option;
452 (void)predicate;
453 (void)async;
454 return E_NOT_SUPPORT;
455 }
456
Sync(const SyncOption & option,const std::vector<std::string> & tables,const AsyncDetail & async)457 int RdbStore::Sync(const SyncOption &option, const std::vector<std::string> &tables, const AsyncDetail &async)
458 {
459 (void)option;
460 (void)tables;
461 (void)async;
462 return E_NOT_SUPPORT;
463 }
464
Sync(const SyncOption & option,const AbsRdbPredicates & predicate,const AsyncDetail & async)465 int RdbStore::Sync(const SyncOption &option, const AbsRdbPredicates &predicate, const AsyncDetail &async)
466 {
467 (void)option;
468 (void)predicate;
469 (void)async;
470 return E_NOT_SUPPORT;
471 }
472
Subscribe(const SubscribeOption & option,RdbStoreObserver * observer)473 int RdbStore::Subscribe(const SubscribeOption& option, RdbStoreObserver *observer)
474 {
475 (void)option;
476 (void)observer;
477 return E_NOT_SUPPORT;
478 }
479
UnSubscribe(const SubscribeOption & option,RdbStoreObserver * observer)480 int RdbStore::UnSubscribe(const SubscribeOption& option, RdbStoreObserver *observer)
481 {
482 (void)option;
483 (void)observer;
484 return E_NOT_SUPPORT;
485 }
486
SubscribeObserver(const SubscribeOption & option,const std::shared_ptr<RdbStoreObserver> & observer)487 int RdbStore::SubscribeObserver(const SubscribeOption& option, const std::shared_ptr<RdbStoreObserver> &observer)
488 {
489 (void)option;
490 (void)observer;
491 return E_NOT_SUPPORT;
492 }
493
UnsubscribeObserver(const SubscribeOption & option,const std::shared_ptr<RdbStoreObserver> & observer)494 int RdbStore::UnsubscribeObserver(const SubscribeOption& option, const std::shared_ptr<RdbStoreObserver> &observer)
495 {
496 (void)option;
497 (void)observer;
498 return E_NOT_SUPPORT;
499 }
500
RegisterAutoSyncCallback(std::shared_ptr<DetailProgressObserver> observer)501 int RdbStore::RegisterAutoSyncCallback(std::shared_ptr<DetailProgressObserver> observer)
502 {
503 (void)observer;
504 return E_NOT_SUPPORT;
505 }
506
UnregisterAutoSyncCallback(std::shared_ptr<DetailProgressObserver> observer)507 int RdbStore::UnregisterAutoSyncCallback(std::shared_ptr<DetailProgressObserver> observer)
508 {
509 (void)observer;
510 return E_NOT_SUPPORT;
511 }
512
Notify(const std::string & event)513 int RdbStore::Notify(const std::string &event)
514 {
515 (void)event;
516 return E_NOT_SUPPORT;
517 }
518
IsSlaveDiffFromMaster() const519 bool RdbStore::IsSlaveDiffFromMaster() const
520 {
521 return false;
522 }
523
GetDbType() const524 int32_t RdbStore::GetDbType() const
525 {
526 return DB_SQLITE;
527 }
528
LockCloudContainer()529 std::pair<int32_t, uint32_t> RdbStore::LockCloudContainer()
530 {
531 return { E_OK, 0 };
532 }
533
UnlockCloudContainer()534 int32_t RdbStore::UnlockCloudContainer()
535 {
536 return E_OK;
537 }
538
InterruptBackup()539 int RdbStore::InterruptBackup()
540 {
541 return E_OK;
542 }
543
GetBackupStatus() const544 int32_t RdbStore::GetBackupStatus() const
545 {
546 return SlaveStatus::UNDEFINED;
547 }
548
GetModifyTime(const std::string & table,const std::string & column,std::vector<PRIKey> & keys)549 RdbStore::ModifyTime RdbStore::GetModifyTime(const std::string &table, const std::string &column,
550 std::vector<PRIKey> &keys)
551 {
552 (void)table;
553 (void)column;
554 (void)keys;
555 return {};
556 }
557
CleanDirtyData(const std::string & table,uint64_t cursor)558 int RdbStore::CleanDirtyData(const std::string &table, uint64_t cursor)
559 {
560 (void)table;
561 (void)cursor;
562 return E_NOT_SUPPORT;
563 }
564
GetRebuilt(RebuiltType & rebuilt)565 int RdbStore::GetRebuilt(RebuiltType &rebuilt)
566 {
567 (void)rebuilt;
568 return E_NOT_SUPPORT;
569 }
570
Attach(const RdbStoreConfig & config,const std::string & attachName,int32_t waitTime)571 std::pair<int32_t, int32_t> RdbStore::Attach(const RdbStoreConfig &config, const std::string &attachName,
572 int32_t waitTime)
573 {
574 (void)config;
575 (void)attachName;
576 (void)waitTime;
577 return { E_NOT_SUPPORT, 0 };
578 }
579
Detach(const std::string & attachName,int32_t waitTime)580 std::pair<int32_t, int32_t> RdbStore::Detach(const std::string &attachName, int32_t waitTime)
581 {
582 (void)attachName;
583 (void)waitTime;
584 return { E_NOT_SUPPORT, 0 };
585 }
586
ModifyLockStatus(const AbsRdbPredicates & predicates,bool isLock)587 int RdbStore::ModifyLockStatus(const AbsRdbPredicates &predicates, bool isLock)
588 {
589 (void)predicates;
590 (void)isLock;
591 return E_NOT_SUPPORT;
592 }
593
SetSearchable(bool isSearchable)594 int RdbStore::SetSearchable(bool isSearchable)
595 {
596 (void)isSearchable;
597 return E_NOT_SUPPORT;
598 }
599
GetLogTableName(const std::string & tableName)600 std::string RdbStore::GetLogTableName(const std::string &tableName)
601 {
602 return "naturalbase_rdb_aux_" + tableName + "_log";
603 }
604 }