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 "db_common.h"
17
18 #include <atomic>
19 #include <charconv>
20 #include <climits>
21 #include <cstdio>
22 #ifndef _WIN32
23 #include <dlfcn.h>
24 #endif
25 #include <mutex>
26 #include <queue>
27
28 #include "cloud/cloud_db_constant.h"
29 #include "cloud/cloud_db_types.h"
30 #include "db_errno.h"
31 #include "param_check_utils.h"
32 #include "platform_specific.h"
33 #include "query_sync_object.h"
34 #include "hash.h"
35 #include "runtime_context.h"
36 #include "value_hash_calc.h"
37
38 namespace DistributedDB {
39 namespace {
40 constexpr const int32_t HEAD_SIZE = 3;
41 constexpr const int32_t END_SIZE = 3;
42 constexpr const int32_t MIN_SIZE = HEAD_SIZE + END_SIZE + 3;
43 constexpr const char *REPLACE_CHAIN = "***";
44 constexpr const char *DEFAULT_ANONYMOUS = "******";
45
RemoveFiles(const std::list<OS::FileAttr> & fileList,OS::FileType type)46 void RemoveFiles(const std::list<OS::FileAttr> &fileList, OS::FileType type)
47 {
48 for (const auto &item : fileList) {
49 if (item.fileType != type) {
50 continue;
51 }
52 int errCode = OS::RemoveFile(item.fileName);
53 if (errCode != E_OK) {
54 LOGE("Remove file failed:%d", errno);
55 }
56 }
57 }
58
RemoveDirectories(const std::list<OS::FileAttr> & fileList,OS::FileType type)59 void RemoveDirectories(const std::list<OS::FileAttr> &fileList, OS::FileType type)
60 {
61 for (auto item = fileList.rbegin(); item != fileList.rend(); ++item) {
62 if (item->fileType != type) {
63 continue;
64 }
65 int errCode = OS::RemoveDBDirectory(item->fileName);
66 if (errCode != 0) {
67 LOGE("Remove directory failed:%d", errno);
68 }
69 }
70 }
71 const std::string HEX_CHAR_MAP = "0123456789abcdef";
72 const std::string CAP_HEX_CHAR_MAP = "0123456789ABCDEF";
73 }
74
75 static std::atomic_bool g_isGrdLoaded = false;
76 static std::mutex g_mutex;
77
CreateDirectory(const std::string & directory)78 int DBCommon::CreateDirectory(const std::string &directory)
79 {
80 bool isExisted = OS::CheckPathExistence(directory);
81 if (!isExisted) {
82 int errCode = OS::MakeDBDirectory(directory);
83 if (errCode != E_OK) {
84 return errCode;
85 }
86 }
87 return E_OK;
88 }
89
StringToVector(const std::string & src,std::vector<uint8_t> & dst)90 void DBCommon::StringToVector(const std::string &src, std::vector<uint8_t> &dst)
91 {
92 dst.resize(src.size());
93 dst.assign(src.begin(), src.end());
94 }
95
VectorToString(const std::vector<uint8_t> & src,std::string & dst)96 void DBCommon::VectorToString(const std::vector<uint8_t> &src, std::string &dst)
97 {
98 dst.clear();
99 dst.assign(src.begin(), src.end());
100 }
101
VectorToHexString(const std::vector<uint8_t> & inVec,const std::string & separator)102 std::string DBCommon::VectorToHexString(const std::vector<uint8_t> &inVec, const std::string &separator)
103 {
104 std::string outString;
105 for (auto &entry : inVec) {
106 outString.push_back(CAP_HEX_CHAR_MAP[entry >> 4]); // high 4 bits to one hex.
107 outString.push_back(CAP_HEX_CHAR_MAP[entry & 0x0F]); // low 4 bits to one hex.
108 outString += separator;
109 }
110 outString.erase(outString.size() - separator.size(), separator.size()); // remove needless separator at last
111 return outString;
112 }
113
PrintHexVector(const std::vector<uint8_t> & data,int line,const std::string & tag)114 void DBCommon::PrintHexVector(const std::vector<uint8_t> &data, int line, const std::string &tag)
115 {
116 const size_t maxDataLength = 1024;
117 const int byteHexNum = 2;
118 size_t dataLength = data.size();
119
120 if (data.size() > maxDataLength) {
121 dataLength = maxDataLength;
122 }
123
124 char *buff = new (std::nothrow) char[dataLength * byteHexNum + 1]; // dual and add one for the end;
125 if (buff == nullptr) {
126 return;
127 }
128
129 for (std::vector<uint8_t>::size_type i = 0; i < dataLength; ++i) {
130 buff[byteHexNum * i] = CAP_HEX_CHAR_MAP[data[i] >> 4]; // high 4 bits to one hex.
131 buff[byteHexNum * i + 1] = CAP_HEX_CHAR_MAP[data[i] & 0x0F]; // low 4 bits to one hex.
132 }
133 buff[dataLength * byteHexNum] = '\0';
134
135 if (line == 0) {
136 LOGD("[%s] size:%zu -- %s", tag.c_str(), data.size(), buff);
137 } else {
138 LOGD("[%s][%d] size:%zu -- %s", tag.c_str(), line, data.size(), buff);
139 }
140
141 delete []buff;
142 return;
143 }
144
TransferHashString(const std::string & devName)145 std::string DBCommon::TransferHashString(const std::string &devName)
146 {
147 if (devName.empty()) {
148 return "";
149 }
150 std::vector<uint8_t> devVect(devName.begin(), devName.end());
151 std::vector<uint8_t> hashVect;
152 int errCode = CalcValueHash(devVect, hashVect);
153 if (errCode != E_OK) {
154 return "";
155 }
156
157 return std::string(hashVect.begin(), hashVect.end());
158 }
159
TransferStringToHex(const std::string & origStr)160 std::string DBCommon::TransferStringToHex(const std::string &origStr)
161 {
162 if (origStr.empty()) {
163 return "";
164 }
165
166 std::string tmp;
167 for (auto item : origStr) {
168 unsigned char currentByte = static_cast<unsigned char>(item);
169 tmp.push_back(HEX_CHAR_MAP[currentByte >> 4]); // high 4 bits to one hex.
170 tmp.push_back(HEX_CHAR_MAP[currentByte & 0x0F]); // low 4 bits to one hex.
171 }
172 return tmp;
173 }
174
CalcValueHash(const std::vector<uint8_t> & value,std::vector<uint8_t> & hashValue)175 int DBCommon::CalcValueHash(const std::vector<uint8_t> &value, std::vector<uint8_t> &hashValue)
176 {
177 ValueHashCalc hashCalc;
178 int errCode = hashCalc.Initialize();
179 if (errCode != E_OK) {
180 return -E_INTERNAL_ERROR;
181 }
182
183 errCode = hashCalc.Update(value);
184 if (errCode != E_OK) {
185 return -E_INTERNAL_ERROR;
186 }
187
188 errCode = hashCalc.GetResult(hashValue);
189 if (errCode != E_OK) {
190 return -E_INTERNAL_ERROR;
191 }
192
193 return E_OK;
194 }
195
CreateStoreDirectory(const std::string & directory,const std::string & identifierName,const std::string & subDir,bool isCreate)196 int DBCommon::CreateStoreDirectory(const std::string &directory, const std::string &identifierName,
197 const std::string &subDir, bool isCreate)
198 {
199 std::string newDir = directory;
200 if (newDir.back() != '/') {
201 newDir += "/";
202 }
203
204 newDir += identifierName;
205 if (!isCreate) {
206 if (!OS::CheckPathExistence(newDir)) {
207 LOGE("Required path does not exist and won't create.");
208 return -E_INVALID_ARGS;
209 }
210 return E_OK;
211 }
212
213 if (directory.empty()) {
214 return -E_INVALID_ARGS;
215 }
216
217 int errCode = DBCommon::CreateDirectory(newDir);
218 if (errCode != E_OK) {
219 return errCode;
220 }
221
222 newDir += ("/" + subDir);
223 return DBCommon::CreateDirectory(newDir);
224 }
225
CopyFile(const std::string & srcFile,const std::string & dstFile)226 int DBCommon::CopyFile(const std::string &srcFile, const std::string &dstFile)
227 {
228 const int copyBlockSize = 4096;
229 std::vector<uint8_t> tmpBlock(copyBlockSize, 0);
230 int errCode;
231 FILE *fileIn = fopen(srcFile.c_str(), "rb");
232 if (fileIn == nullptr) {
233 LOGE("[Common:CpFile] open the source file error:%d", errno);
234 return -E_INVALID_FILE;
235 }
236 FILE *fileOut = fopen(dstFile.c_str(), "wb");
237 if (fileOut == nullptr) {
238 LOGE("[Common:CpFile] open the target file error:%d", errno);
239 errCode = -E_INVALID_FILE;
240 goto END;
241 }
242 for (;;) {
243 size_t readSize = fread(static_cast<void *>(tmpBlock.data()), 1, copyBlockSize, fileIn);
244 if (readSize < copyBlockSize) {
245 // not end and have error.
246 if (feof(fileIn) != 0 && ferror(fileIn) != 0) {
247 LOGE("Copy the file error:%d", errno);
248 errCode = -E_SYSTEM_API_FAIL;
249 break;
250 }
251 }
252
253 if (readSize != 0) {
254 size_t writeSize = fwrite(static_cast<void *>(tmpBlock.data()), 1, readSize, fileOut);
255 if (ferror(fileOut) != 0 || writeSize != readSize) {
256 LOGE("Write the data while copy:%d", errno);
257 errCode = -E_SYSTEM_API_FAIL;
258 break;
259 }
260 }
261
262 if (feof(fileIn) != 0) {
263 errCode = E_OK;
264 break;
265 }
266 }
267
268 END:
269 if (fileIn != nullptr) {
270 (void)fclose(fileIn);
271 }
272 if (fileOut != nullptr) {
273 (void)fclose(fileOut);
274 }
275 return errCode;
276 }
277
RemoveAllFilesOfDirectory(const std::string & dir,bool isNeedRemoveDir)278 int DBCommon::RemoveAllFilesOfDirectory(const std::string &dir, bool isNeedRemoveDir)
279 {
280 std::list<OS::FileAttr> fileList;
281 bool isExisted = OS::CheckPathExistence(dir);
282 if (!isExisted) {
283 return E_OK;
284 }
285 int errCode = OS::GetFileAttrFromPath(dir, fileList, true);
286 if (errCode != E_OK) {
287 return errCode;
288 }
289
290 RemoveFiles(fileList, OS::FileType::FILE);
291 RemoveDirectories(fileList, OS::FileType::PATH);
292 if (isNeedRemoveDir) {
293 // Pay attention to the order of deleting the directory
294 if (OS::CheckPathExistence(dir) && OS::RemoveDBDirectory(dir) != 0) {
295 LOGI("Remove the directory error:%d", errno);
296 errCode = -E_SYSTEM_API_FAIL;
297 }
298 }
299
300 return errCode;
301 }
302
GenerateIdentifierId(const std::string & storeId,const std::string & appId,const std::string & userId,const std::string & subUser,int32_t instanceId)303 std::string DBCommon::GenerateIdentifierId(const std::string &storeId,
304 const std::string &appId, const std::string &userId, const std::string &subUser, int32_t instanceId)
305 {
306 std::string id = userId + "-" + appId + "-" + storeId;
307 if (instanceId != 0) {
308 id += "-" + std::to_string(instanceId);
309 }
310 if (!subUser.empty()) {
311 id += "-" + subUser;
312 }
313 return id;
314 }
315
GenerateDualTupleIdentifierId(const std::string & storeId,const std::string & appId)316 std::string DBCommon::GenerateDualTupleIdentifierId(const std::string &storeId, const std::string &appId)
317 {
318 return appId + "-" + storeId;
319 }
320
SetDatabaseIds(KvDBProperties & properties,const DbIdParam & dbIdParam)321 void DBCommon::SetDatabaseIds(KvDBProperties &properties, const DbIdParam &dbIdParam)
322 {
323 properties.SetIdentifier(dbIdParam.userId, dbIdParam.appId, dbIdParam.storeId,
324 dbIdParam.subUser, dbIdParam.instanceId);
325 std::string oriStoreDir;
326 // IDENTIFIER_DIR no need cal with instanceId and subUser
327 std::string identifier = GenerateIdentifierId(dbIdParam.storeId, dbIdParam.appId, dbIdParam.userId);
328 if (properties.GetBoolProp(KvDBProperties::CREATE_DIR_BY_STORE_ID_ONLY, false)) {
329 oriStoreDir = dbIdParam.storeId;
330 } else {
331 oriStoreDir = identifier;
332 }
333 std::string hashIdentifier = TransferHashString(identifier);
334 std::string hashDir = TransferHashString(oriStoreDir);
335 std::string hexHashDir = TransferStringToHex(hashDir);
336 properties.SetStringProp(KvDBProperties::IDENTIFIER_DIR, hexHashDir);
337 }
338
StringMasking(const std::string & oriStr,size_t remain)339 std::string DBCommon::StringMasking(const std::string &oriStr, size_t remain)
340 {
341 #ifndef DB_DEBUG_ENV
342 if (oriStr.size() > remain) {
343 return oriStr.substr(0, remain);
344 }
345 #endif
346 return oriStr;
347 }
348
StringMiddleMasking(const std::string & name)349 std::string DBCommon::StringMiddleMasking(const std::string &name)
350 {
351 if (name.length() <= HEAD_SIZE) {
352 return DEFAULT_ANONYMOUS;
353 }
354
355 if (name.length() < MIN_SIZE) {
356 return (name.substr(0, HEAD_SIZE) + REPLACE_CHAIN);
357 }
358
359 return (name.substr(0, HEAD_SIZE) + REPLACE_CHAIN + name.substr(name.length() - END_SIZE, END_SIZE));
360 }
361
GetDistributedTableName(const std::string & device,const std::string & tableName)362 std::string DBCommon::GetDistributedTableName(const std::string &device, const std::string &tableName)
363 {
364 if (!RuntimeContext::GetInstance()->ExistTranslateDevIdCallback()) {
365 return GetDistributedTableNameWithHash(device, tableName);
366 }
367 return CalDistributedTableName(device, tableName);
368 }
369
GetDistributedTableName(const std::string & device,const std::string & tableName,const StoreInfo & info)370 std::string DBCommon::GetDistributedTableName(const std::string &device, const std::string &tableName,
371 const StoreInfo &info)
372 {
373 std::string newDeviceId;
374 if (RuntimeContext::GetInstance()->TranslateDeviceId(device, info, newDeviceId) != E_OK) {
375 return GetDistributedTableNameWithHash(device, tableName);
376 }
377 return CalDistributedTableName(newDeviceId, tableName);
378 }
379
GetDistributedTableNameWithHash(const std::string & device,const std::string & tableName)380 std::string DBCommon::GetDistributedTableNameWithHash(const std::string &device, const std::string &tableName)
381 {
382 std::string deviceHashHex = DBCommon::TransferStringToHex(DBCommon::TransferHashString(device));
383 return CalDistributedTableName(deviceHashHex, tableName);
384 }
385
CalDistributedTableName(const std::string & device,const std::string & tableName)386 std::string DBCommon::CalDistributedTableName(const std::string &device, const std::string &tableName)
387 {
388 return DBConstant::RELATIONAL_PREFIX + tableName + "_" + device;
389 }
390
GetDeviceFromName(const std::string & deviceTableName,std::string & deviceHash,std::string & tableName)391 void DBCommon::GetDeviceFromName(const std::string &deviceTableName, std::string &deviceHash, std::string &tableName)
392 {
393 std::size_t found = deviceTableName.rfind('_');
394 if (found != std::string::npos && found + 1 < deviceTableName.length() &&
395 found > DBConstant::RELATIONAL_PREFIX_SIZE) {
396 deviceHash = deviceTableName.substr(found + 1);
397 tableName = deviceTableName.substr(DBConstant::RELATIONAL_PREFIX_SIZE,
398 found - DBConstant::RELATIONAL_PREFIX_SIZE);
399 }
400 }
401
TrimSpace(const std::string & input)402 std::string DBCommon::TrimSpace(const std::string &input)
403 {
404 std::string res;
405 res.reserve(input.length());
406 bool isPreSpace = true;
407 for (char c : input) {
408 if (std::isspace(c)) {
409 isPreSpace = true;
410 } else {
411 if (!res.empty() && isPreSpace) {
412 res += ' ';
413 }
414 res += c;
415 isPreSpace = false;
416 }
417 }
418 res.shrink_to_fit();
419 return res;
420 }
421
RTrim(std::string & oriString)422 void DBCommon::RTrim(std::string &oriString)
423 {
424 if (oriString.empty()) {
425 return;
426 }
427 oriString.erase(oriString.find_last_not_of(" ") + 1);
428 }
429
430 namespace {
CharIn(char c,const std::string & pattern)431 bool CharIn(char c, const std::string &pattern)
432 {
433 return std::any_of(pattern.begin(), pattern.end(), [c] (char p) {
434 return c == p;
435 });
436 }
437 }
438
HasConstraint(const std::string & sql,const std::string & keyWord,const std::string & prePattern,const std::string & nextPattern)439 bool DBCommon::HasConstraint(const std::string &sql, const std::string &keyWord, const std::string &prePattern,
440 const std::string &nextPattern)
441 {
442 size_t pos = 0;
443 while ((pos = sql.find(keyWord, pos)) != std::string::npos) {
444 if (pos >= 1 && CharIn(sql[pos - 1], prePattern) && ((pos + keyWord.length() == sql.length()) ||
445 ((pos + keyWord.length() < sql.length()) && CharIn(sql[pos + keyWord.length()], nextPattern)))) {
446 return true;
447 }
448 pos++;
449 }
450 return false;
451 }
452
IsSameCipher(CipherType srcType,CipherType inputType)453 bool DBCommon::IsSameCipher(CipherType srcType, CipherType inputType)
454 {
455 // At present, the default type is AES-256-GCM.
456 // So when src is default and input is AES-256-GCM,
457 // or when src is AES-256-GCM and input is default,
458 // we think they are the same type.
459 if (srcType == inputType ||
460 ((srcType == CipherType::DEFAULT || srcType == CipherType::AES_256_GCM) &&
461 (inputType == CipherType::DEFAULT || inputType == CipherType::AES_256_GCM))) {
462 return true;
463 }
464 return false;
465 }
466
ToLowerCase(const std::string & str)467 std::string DBCommon::ToLowerCase(const std::string &str)
468 {
469 std::string res(str.length(), ' ');
470 std::transform(str.begin(), str.end(), res.begin(), ::tolower);
471 return res;
472 }
473
ToUpperCase(const std::string & str)474 std::string DBCommon::ToUpperCase(const std::string &str)
475 {
476 std::string res(str.length(), ' ');
477 std::transform(str.begin(), str.end(), res.begin(), ::toupper);
478 return res;
479 }
480
CaseInsensitiveCompare(const std::string & first,const std::string & second)481 bool DBCommon::CaseInsensitiveCompare(const std::string &first, const std::string &second)
482 {
483 return (strcasecmp(first.c_str(), second.c_str()) == 0);
484 }
485
CheckIsAlnumOrUnderscore(const std::string & text)486 bool DBCommon::CheckIsAlnumOrUnderscore(const std::string &text)
487 {
488 auto iter = std::find_if_not(text.begin(), text.end(), [](char c) {
489 return (std::isalnum(c) || c == '_');
490 });
491 return iter == text.end();
492 }
493
CheckQueryWithoutMultiTable(const Query & query)494 bool DBCommon::CheckQueryWithoutMultiTable(const Query &query)
495 {
496 if (!QuerySyncObject::GetQuerySyncObject(query).empty()) {
497 LOGE("check query object from table failed!");
498 return false;
499 }
500 return true;
501 }
502
503 /* this function us topology sorting algorithm to detect whether a ring exists in the dependency
504 * the algorithm main procedure as below:
505 * 1. select a point which in-degree is 0 in the graph and record it;
506 * 2. delete the point and all edges starting from this point;
507 * 3. repeat step 1 and 2, until the graph is empty or there is no point with a zero degree
508 * */
IsCircularDependency(int size,const std::vector<std::vector<int>> & dependency)509 bool DBCommon::IsCircularDependency(int size, const std::vector<std::vector<int>> &dependency)
510 {
511 std::vector<int> inDegree(size, 0); // save in-degree of every point
512 std::vector<std::vector<int>> adjacencyList(size);
513 for (size_t i = 0; i < dependency.size(); i++) {
514 adjacencyList[dependency[i][0]].push_back(dependency[i][1]); // update adjacencyList
515 inDegree[dependency[i][1]]++;
516 }
517 std::queue<int> que;
518 for (size_t i = 0; i < inDegree.size(); i++) {
519 if (inDegree[i] == 0) {
520 que.push(i); // push all point which in-degree = 0
521 }
522 }
523
524 int zeroDegreeCnt = static_cast<int>(que.size());
525 while (!que.empty()) {
526 int index = que.front();
527 que.pop();
528 for (size_t i = 0; i < adjacencyList[index].size(); ++i) {
529 int j = adjacencyList[index][i]; // adjacencyList[index] save the point which is connected to index
530 inDegree[j]--;
531 if (inDegree[j] == 0) {
532 zeroDegreeCnt++;
533 que.push(j);
534 }
535 }
536 }
537 return zeroDegreeCnt != size;
538 }
539
SerializeWaterMark(Timestamp localMark,const std::string & cloudMark,Value & blobMeta)540 int DBCommon::SerializeWaterMark(Timestamp localMark, const std::string &cloudMark, Value &blobMeta)
541 {
542 uint64_t length = Parcel::GetUInt64Len() + Parcel::GetStringLen(cloudMark);
543 blobMeta.resize(length);
544 Parcel parcel(blobMeta.data(), blobMeta.size());
545 parcel.WriteUInt64(localMark);
546 parcel.WriteString(cloudMark);
547 if (parcel.IsError()) {
548 LOGE("[DBCommon] Parcel error while serializing cloud meta data.");
549 return -E_PARSE_FAIL;
550 }
551 return E_OK;
552 }
553
GetPrefixTableName(const TableName & tableName)554 Key DBCommon::GetPrefixTableName(const TableName &tableName)
555 {
556 TableName newName = CloudDbConstant::CLOUD_META_TABLE_PREFIX + tableName;
557 Key prefixedTableName(newName.begin(), newName.end());
558 return prefixedTableName;
559 }
560
InsertNodesByScore(const std::map<std::string,std::map<std::string,bool>> & graph,const std::vector<std::string> & generateNodes,const std::map<std::string,int> & scoreGraph,std::list<std::string> & insertTarget)561 void DBCommon::InsertNodesByScore(const std::map<std::string, std::map<std::string, bool>> &graph,
562 const std::vector<std::string> &generateNodes, const std::map<std::string, int> &scoreGraph,
563 std::list<std::string> &insertTarget)
564 {
565 auto copyGraph = graph;
566 // insert all nodes into res
567 for (const auto &generateNode : generateNodes) {
568 auto iterator = insertTarget.begin();
569 for (; iterator != insertTarget.end(); iterator++) {
570 // don't compare two no reachable node
571 if (!copyGraph[*iterator][generateNode] && !copyGraph[generateNode][*iterator]) {
572 continue;
573 }
574 if (scoreGraph.find(*iterator) == scoreGraph.end() || scoreGraph.find(generateNode) == scoreGraph.end()) {
575 // should not happen
576 LOGW("[DBCommon] not find score in graph");
577 continue;
578 }
579 if (scoreGraph.at(*iterator) <= scoreGraph.at(generateNode)) {
580 break;
581 }
582 }
583 insertTarget.insert(iterator, generateNode);
584 }
585 }
586
GenerateNodesByNodeWeight(const std::vector<std::string> & nodes,const std::map<std::string,std::map<std::string,bool>> & graph,const std::map<std::string,int> & nodeWeight)587 std::list<std::string> DBCommon::GenerateNodesByNodeWeight(const std::vector<std::string> &nodes,
588 const std::map<std::string, std::map<std::string, bool>> &graph,
589 const std::map<std::string, int> &nodeWeight)
590 {
591 std::list<std::string> res;
592 std::set<std::string> paramNodes;
593 std::set<std::string> visitNodes;
594 for (const auto &node : nodes) {
595 res.push_back(node);
596 paramNodes.insert(node);
597 visitNodes.insert(node);
598 }
599 // find all node which can be reached by param nodes
600 for (const auto &source : paramNodes) {
601 if (graph.find(source) == graph.end()) {
602 continue;
603 }
604 for (const auto &[target, reach] : graph.at(source)) {
605 if (reach) {
606 visitNodes.insert(target);
607 }
608 }
609 }
610 std::vector<std::string> generateNodes;
611 for (const auto &node : visitNodes) {
612 // ignore the node which is param
613 if (paramNodes.find(node) == paramNodes.end()) {
614 generateNodes.push_back(node);
615 }
616 }
617 InsertNodesByScore(graph, generateNodes, nodeWeight, res);
618 return res;
619 }
620
HasPrimaryKey(const std::vector<Field> & fields)621 bool DBCommon::HasPrimaryKey(const std::vector<Field> &fields)
622 {
623 for (const auto &field : fields) {
624 if (field.primary) {
625 return true;
626 }
627 }
628 return false;
629 }
630
IsRecordError(const VBucket & record)631 bool DBCommon::IsRecordError(const VBucket &record)
632 {
633 // check record err should deal or skip, false is no error or error is considered, true is error not considered
634 if (record.find(CloudDbConstant::ERROR_FIELD) == record.end()) {
635 return false;
636 }
637 if (record.at(CloudDbConstant::ERROR_FIELD).index() != TYPE_INDEX<int64_t>) {
638 return false;
639 }
640 auto status = std::get<int64_t>(record.at(CloudDbConstant::ERROR_FIELD));
641 return status != static_cast<int64_t>(DBStatus::CLOUD_RECORD_EXIST_CONFLICT) &&
642 status != static_cast<int64_t>(DBStatus::CLOUD_RECORD_ALREADY_EXISTED) &&
643 status != static_cast<int64_t>(DBStatus::CLOUD_RECORD_NOT_FOUND) &&
644 status != static_cast<int64_t>(DBStatus::LOCAL_ASSET_NOT_FOUND);
645 }
646
IsIntTypeRecordError(const VBucket & record)647 bool DBCommon::IsIntTypeRecordError(const VBucket &record)
648 {
649 if (record.find(CloudDbConstant::ERROR_FIELD) == record.end()) {
650 return false;
651 }
652 return record.at(CloudDbConstant::ERROR_FIELD).index() == TYPE_INDEX<int64_t>;
653 }
654
IsRecordIgnored(const VBucket & record)655 bool DBCommon::IsRecordIgnored(const VBucket &record)
656 {
657 if (record.find(CloudDbConstant::ERROR_FIELD) == record.end()) {
658 return false;
659 }
660 if (record.at(CloudDbConstant::ERROR_FIELD).index() != TYPE_INDEX<int64_t>) {
661 return false;
662 }
663 auto status = std::get<int64_t>(record.at(CloudDbConstant::ERROR_FIELD));
664 return status == static_cast<int64_t>(DBStatus::CLOUD_RECORD_EXIST_CONFLICT) ||
665 status == static_cast<int64_t>(DBStatus::CLOUD_VERSION_CONFLICT);
666 }
667
IsRecordFailed(const VBucket & record,DBStatus status)668 bool DBCommon::IsRecordFailed(const VBucket &record, DBStatus status)
669 {
670 if (status == OK) {
671 return false;
672 }
673 return DBCommon::IsRecordError(record) || !DBCommon::IsRecordSuccess(record);
674 }
675
IsRecordVersionConflict(const VBucket & record)676 bool DBCommon::IsRecordVersionConflict(const VBucket &record)
677 {
678 if (record.find(CloudDbConstant::ERROR_FIELD) == record.end()) {
679 return false;
680 }
681 if (record.at(CloudDbConstant::ERROR_FIELD).index() != TYPE_INDEX<int64_t>) {
682 return false;
683 }
684 auto status = std::get<int64_t>(record.at(CloudDbConstant::ERROR_FIELD));
685 return status == static_cast<int64_t>(DBStatus::CLOUD_VERSION_CONFLICT);
686 }
687
IsRecordAssetsMissing(const VBucket & record)688 bool DBCommon::IsRecordAssetsMissing(const VBucket &record)
689 {
690 if (record.find(CloudDbConstant::ERROR_FIELD) == record.end()) {
691 return false;
692 }
693 if (record.at(CloudDbConstant::ERROR_FIELD).index() != TYPE_INDEX<int64_t>) {
694 return false;
695 }
696 auto status = std::get<int64_t>(record.at(CloudDbConstant::ERROR_FIELD));
697 return status == static_cast<int64_t>(DBStatus::LOCAL_ASSET_NOT_FOUND);
698 }
699
IsRecordDelete(const VBucket & record)700 bool DBCommon::IsRecordDelete(const VBucket &record)
701 {
702 if (record.find(CloudDbConstant::DELETE_FIELD) == record.end()) {
703 return false;
704 }
705 if (record.at(CloudDbConstant::DELETE_FIELD).index() != TYPE_INDEX<bool>) {
706 return false;
707 }
708 return std::get<bool>(record.at(CloudDbConstant::DELETE_FIELD));
709 }
710
IsCloudRecordNotFound(const VBucket & record)711 bool DBCommon::IsCloudRecordNotFound(const VBucket &record)
712 {
713 if (record.find(CloudDbConstant::ERROR_FIELD) == record.end()) {
714 return false;
715 }
716 if (record.at(CloudDbConstant::ERROR_FIELD).index() != TYPE_INDEX<int64_t>) {
717 return false;
718 }
719 auto status = std::get<int64_t>(record.at(CloudDbConstant::ERROR_FIELD));
720 return status == static_cast<int64_t>(DBStatus::CLOUD_RECORD_NOT_FOUND);
721 }
722
IsCloudRecordAlreadyExisted(const VBucket & record)723 bool DBCommon::IsCloudRecordAlreadyExisted(const VBucket &record)
724 {
725 if (record.find(CloudDbConstant::ERROR_FIELD) == record.end()) {
726 return false;
727 }
728 if (record.at(CloudDbConstant::ERROR_FIELD).index() != TYPE_INDEX<int64_t>) {
729 return false;
730 }
731 auto status = std::get<int64_t>(record.at(CloudDbConstant::ERROR_FIELD));
732 return status == static_cast<int64_t>(DBStatus::CLOUD_RECORD_ALREADY_EXISTED);
733 }
734
IsNeedCompensatedForUpload(const VBucket & uploadExtend,const CloudWaterType & type)735 bool DBCommon::IsNeedCompensatedForUpload(const VBucket &uploadExtend, const CloudWaterType &type)
736 {
737 return (DBCommon::IsCloudRecordAlreadyExisted(uploadExtend) && type == CloudWaterType::INSERT) ||
738 (DBCommon::IsCloudRecordNotFound(uploadExtend) && type == CloudWaterType::UPDATE);
739 }
740
IsRecordIgnoredForReliability(const VBucket & uploadExtend,const CloudWaterType & type)741 bool DBCommon::IsRecordIgnoredForReliability(const VBucket &uploadExtend, const CloudWaterType &type)
742 {
743 return (DBCommon::IsCloudRecordAlreadyExisted(uploadExtend) && type == CloudWaterType::INSERT) ||
744 (DBCommon::IsCloudRecordNotFound(uploadExtend) &&
745 (type == CloudWaterType::UPDATE || type == CloudWaterType::DELETE));
746 }
747
IsRecordSuccess(const VBucket & record)748 bool DBCommon::IsRecordSuccess(const VBucket &record)
749 {
750 return record.find(CloudDbConstant::ERROR_FIELD) == record.end();
751 }
752
GenerateHashLabel(const DBInfo & dbInfo)753 std::string DBCommon::GenerateHashLabel(const DBInfo &dbInfo)
754 {
755 if (dbInfo.syncDualTupleMode) {
756 return DBCommon::TransferHashString(dbInfo.appId + "-" + dbInfo.storeId);
757 }
758 return DBCommon::TransferHashString(dbInfo.userId + "-" + dbInfo.appId + "-" + dbInfo.storeId);
759 }
760
EraseBit(uint64_t origin,uint64_t eraseBit)761 uint64_t DBCommon::EraseBit(uint64_t origin, uint64_t eraseBit)
762 {
763 return origin & (~eraseBit);
764 }
765
LoadGrdLib(void)766 void DBCommon::LoadGrdLib(void)
767 {
768 std::lock_guard<std::mutex> lock(g_mutex);
769 static std::once_flag loadOnceFlag;
770 std::call_once(loadOnceFlag, []() {
771 #ifndef _WIN32
772 if (!g_isGrdLoaded) {
773 if (dlopen("libarkdata_db_core.z.so", RTLD_LAZY) != NULL) {
774 g_isGrdLoaded = true;
775 } else {
776 LOGW("[DBCommon] unable to load grd lib, errno: %d, %s", errno, dlerror());
777 }
778 }
779 #endif
780 });
781 }
782
IsGrdLibLoaded(void)783 bool DBCommon::IsGrdLibLoaded(void)
784 {
785 return g_isGrdLoaded;
786 }
787
CheckCloudSyncConfigValid(const CloudSyncConfig & config)788 bool DBCommon::CheckCloudSyncConfigValid(const CloudSyncConfig &config)
789 {
790 if (config.maxUploadCount < CloudDbConstant::MIN_UPLOAD_BATCH_COUNT ||
791 config.maxUploadCount > CloudDbConstant::MAX_UPLOAD_BATCH_COUNT) {
792 LOGE("[DBCommon] invalid upload count %" PRId32, config.maxUploadCount);
793 return false;
794 }
795 if (config.maxUploadSize < CloudDbConstant::MIN_UPLOAD_SIZE ||
796 config.maxUploadSize > CloudDbConstant::MAX_UPLOAD_SIZE) {
797 LOGE("[DBCommon] invalid upload size %" PRId32, config.maxUploadSize);
798 return false;
799 }
800 if (config.maxRetryConflictTimes < CloudDbConstant::MIN_RETRY_CONFLICT_COUNTS) {
801 LOGE("[DBCommon] invalid retry conflict count %" PRId32, config.maxRetryConflictTimes);
802 return false;
803 }
804 return true;
805 }
806
GetCursorKey(const std::string & tableName)807 std::string DBCommon::GetCursorKey(const std::string &tableName)
808 {
809 return std::string(DBConstant::RELATIONAL_PREFIX) + "cursor_" + ToLowerCase(tableName);
810 }
811
ConvertToUInt64(const std::string & str,uint64_t & value)812 bool DBCommon::ConvertToUInt64(const std::string &str, uint64_t &value)
813 {
814 auto [ptr, errCode] = std::from_chars(str.data(), str.data() + str.size(), value);
815 return errCode == std::errc{} && ptr == str.data() + str.size();
816 }
817
CmpModifyTime(const std::string & preModifyTimeStr,const std::string & curModifyTimeStr)818 bool CmpModifyTime(const std::string &preModifyTimeStr, const std::string &curModifyTimeStr)
819 {
820 uint64_t curModifyTime = 0;
821 uint64_t preModifyTime = 0;
822 if (preModifyTimeStr.empty() || !DBCommon::ConvertToUInt64(preModifyTimeStr, preModifyTime)) {
823 return true;
824 }
825 if (curModifyTimeStr.empty() || !DBCommon::ConvertToUInt64(curModifyTimeStr, curModifyTime)) {
826 return false;
827 }
828 return curModifyTime >= preModifyTime;
829 }
830
RemoveDuplicateAssetsData(std::vector<Asset> & assets)831 void DBCommon::RemoveDuplicateAssetsData(std::vector<Asset> &assets)
832 {
833 std::unordered_map<std::string, size_t> indexMap;
834 size_t vectorSize = assets.size();
835 std::vector<size_t> arr(vectorSize, 0);
836 for (std::vector<DistributedDB::Asset>::size_type i = 0; i < assets.size(); ++i) {
837 DistributedDB::Asset asset = assets.at(i);
838 auto it = indexMap.find(asset.name);
839 if (it == indexMap.end()) {
840 indexMap[asset.name] = i;
841 continue;
842 }
843 size_t prevIndex = it->second;
844 Asset &prevAsset = assets.at(prevIndex);
845 if (prevAsset.assetId.empty() && !asset.assetId.empty()) {
846 arr[prevIndex] = 1;
847 indexMap[asset.name] = i;
848 continue;
849 }
850 if (!prevAsset.assetId.empty() && asset.assetId.empty()) {
851 arr[i] = 1;
852 indexMap[asset.name] = prevIndex;
853 continue;
854 }
855 if (CmpModifyTime(prevAsset.modifyTime, asset.modifyTime)) {
856 arr[prevIndex] = 1;
857 indexMap[asset.name] = i;
858 continue;
859 }
860 arr[i] = 1;
861 indexMap[asset.name] = prevIndex;
862 }
863 indexMap.clear();
864 size_t arrIndex = 0;
865 for (auto it = assets.begin(); it != assets.end();) {
866 if (arr[arrIndex] == 1) {
867 it = assets.erase(it);
868 } else {
869 it++;
870 }
871 arrIndex++;
872 }
873 }
874
TransformToCaseInsensitive(const std::vector<std::string> & origin)875 std::set<std::string, CaseInsensitiveComparator> DBCommon::TransformToCaseInsensitive(
876 const std::vector<std::string> &origin)
877 {
878 std::set<std::string, CaseInsensitiveComparator> res;
879 for (const auto &item : origin) {
880 res.insert(item);
881 }
882 return res;
883 }
884
GetStoreIdentifier(const StoreInfo & info,const std::string & subUser,bool syncDualTupleMode,bool allowStoreIdWithDot)885 std::string DBCommon::GetStoreIdentifier(const StoreInfo &info, const std::string &subUser, bool syncDualTupleMode,
886 bool allowStoreIdWithDot)
887 {
888 if (!ParamCheckUtils::CheckStoreParameter(info, syncDualTupleMode, subUser, allowStoreIdWithDot)) {
889 return "";
890 }
891 if (syncDualTupleMode) {
892 return DBCommon::TransferHashString(info.appId + "-" + info.storeId);
893 }
894 if (subUser.empty()) {
895 return DBCommon::TransferHashString(info.userId + "-" + info.appId + "-" + info.storeId);
896 }
897 return DBCommon::TransferHashString(info.userId + "-" + info.appId + "-" + info.storeId + "-" + subUser);
898 }
899 } // namespace DistributedDB
900