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 #include "table_info.h"
16
17 #include <algorithm>
18
19 #include "db_common.h"
20 #include "db_errno.h"
21 #include "log_print.h"
22
23 namespace DistributedDB {
24 constexpr const char *ASSET_STR = "asset";
25 constexpr const char *ASSETS_STR = "assets";
26 constexpr const char *ROW_ID = "rowid";
27
GetFieldName() const28 const std::string &FieldInfo::GetFieldName() const
29 {
30 return fieldName_;
31 }
32
SetFieldName(const std::string & fileName)33 void FieldInfo::SetFieldName(const std::string &fileName)
34 {
35 fieldName_ = fileName;
36 }
37
GetDataType() const38 const std::string &FieldInfo::GetDataType() const
39 {
40 return dataType_;
41 }
42
43 namespace {
AffinityPatternHex(const std::string & ss)44 inline uint32_t AffinityPatternHex(const std::string &ss)
45 {
46 uint32_t res = 0;
47 for (const auto &c : ss) {
48 res = (res << 8) + c; // 8: shift length
49 }
50 return res;
51 }
52
53 static uint32_t affinityTable[] = {
54 AffinityPatternHex("char"), AffinityPatternHex("clob"), AffinityPatternHex("text"),
55 AffinityPatternHex("blob"), AffinityPatternHex("real"), AffinityPatternHex("floa"),
56 AffinityPatternHex("doub"), AffinityPatternHex("int"),
57 };
58
59 enum AffinityPattern : uint32_t {
60 AFFINITY_CHAR,
61 AFFINITY_CLOB,
62 AFFINITY_TEXT,
63 AFFINITY_BLOB,
64 AFFINITY_REAL,
65 AFFINITY_FLOA,
66 AFFINITY_DOUB,
67 AFFINITY_INT,
68 };
69 }
70
AffinityType(const std::string & dataType)71 static StorageType AffinityType(const std::string &dataType)
72 {
73 StorageType type = StorageType::STORAGE_TYPE_NULL;
74 uint32_t hex = 0;
75 for (uint32_t i = 0; i < dataType.length(); i++) {
76 hex = (hex << 8) + static_cast<uint32_t>((std::tolower(dataType[i]))); // 8: shift length
77 if (hex == affinityTable[AFFINITY_CHAR]) {
78 type = StorageType::STORAGE_TYPE_TEXT;
79 } else if (hex == affinityTable[AFFINITY_CLOB]) {
80 type = StorageType::STORAGE_TYPE_TEXT;
81 } else if (hex == affinityTable[AFFINITY_TEXT]) {
82 type = StorageType::STORAGE_TYPE_TEXT;
83 } else if (hex == affinityTable[AFFINITY_BLOB] && (type == StorageType::STORAGE_TYPE_NULL ||
84 type == StorageType::STORAGE_TYPE_REAL)) {
85 type = StorageType::STORAGE_TYPE_BLOB;
86 } else if (hex == affinityTable[AFFINITY_REAL] && type == StorageType::STORAGE_TYPE_NULL) {
87 type = StorageType::STORAGE_TYPE_REAL;
88 } else if (hex == affinityTable[AFFINITY_FLOA] && type == StorageType::STORAGE_TYPE_NULL) {
89 type = StorageType::STORAGE_TYPE_REAL;
90 } else if (hex == affinityTable[AFFINITY_DOUB] && type == StorageType::STORAGE_TYPE_NULL) {
91 type = StorageType::STORAGE_TYPE_REAL;
92 } else if ((hex & 0x00ffffff) == affinityTable[AFFINITY_INT]) { // 0x00ffffff: mask for 3 byte
93 type = StorageType::STORAGE_TYPE_INTEGER;
94 }
95 }
96 return type;
97 }
98
SetDataType(const std::string & dataType)99 void FieldInfo::SetDataType(const std::string &dataType)
100 {
101 dataType_ = dataType;
102 std::transform(dataType_.begin(), dataType_.end(), dataType_.begin(), ::tolower);
103 if (IsAssetType() || IsAssetsType()) {
104 storageType_ = StorageType::STORAGE_TYPE_BLOB; // use for cloud sync
105 } else if (dataType_ == DBConstant::STORAGE_TYPE_LONG) {
106 storageType_ = StorageType::STORAGE_TYPE_INTEGER;
107 } else {
108 storageType_ = AffinityType(dataType_);
109 }
110 }
111
IsNotNull() const112 bool FieldInfo::IsNotNull() const
113 {
114 return isNotNull_;
115 }
116
SetNotNull(bool isNotNull)117 void FieldInfo::SetNotNull(bool isNotNull)
118 {
119 isNotNull_ = isNotNull;
120 }
121
HasDefaultValue() const122 bool FieldInfo::HasDefaultValue() const
123 {
124 return hasDefaultValue_;
125 }
126
GetDefaultValue() const127 const std::string &FieldInfo::GetDefaultValue() const
128 {
129 return defaultValue_;
130 }
131
SetDefaultValue(const std::string & value)132 void FieldInfo::SetDefaultValue(const std::string &value)
133 {
134 hasDefaultValue_ = true;
135 defaultValue_ = value;
136 }
137
138 // convert to StorageType according "Determination Of Column Affinity"
GetStorageType() const139 StorageType FieldInfo::GetStorageType() const
140 {
141 return storageType_;
142 }
143
SetStorageType(StorageType storageType)144 void FieldInfo::SetStorageType(StorageType storageType)
145 {
146 storageType_ = storageType;
147 }
148
GetColumnId() const149 int FieldInfo::GetColumnId() const
150 {
151 return cid_;
152 }
153
SetColumnId(int cid)154 void FieldInfo::SetColumnId(int cid)
155 {
156 cid_ = cid;
157 }
158
ToAttributeString() const159 std::string FieldInfo::ToAttributeString() const
160 {
161 std::string attrStr = "\"" + fieldName_ + "\": {";
162 attrStr += "\"COLUMN_ID\":" + std::to_string(cid_) + ",";
163 attrStr += "\"TYPE\":\"" + dataType_ + "\",";
164 attrStr += "\"NOT_NULL\":" + std::string(isNotNull_ ? "true" : "false");
165 if (hasDefaultValue_) {
166 attrStr += ",";
167 attrStr += "\"DEFAULT\":\"" + defaultValue_ + "\"";
168 }
169 attrStr += "}";
170 return attrStr;
171 }
172
CompareWithField(const FieldInfo & inField,bool isLite) const173 int FieldInfo::CompareWithField(const FieldInfo &inField, bool isLite) const
174 {
175 if (!DBCommon::CaseInsensitiveCompare(fieldName_, inField.GetFieldName()) || isNotNull_ != inField.IsNotNull()) {
176 return false;
177 }
178 if (isLite) {
179 if (storageType_ != inField.GetStorageType()) {
180 return false;
181 }
182 } else {
183 if (dataType_ != inField.GetDataType()) {
184 return false;
185 }
186 }
187 if (hasDefaultValue_ && inField.HasDefaultValue()) {
188 // lite schema only uses NULL as default value
189 return (isLite && DBCommon::CaseInsensitiveCompare(defaultValue_, "NULL")) ||
190 (DBCommon::CaseInsensitiveCompare(defaultValue_, "NULL") &&
191 DBCommon::CaseInsensitiveCompare(inField.GetDefaultValue(), "NULL")) ||
192 (defaultValue_ == inField.GetDefaultValue());
193 }
194 return hasDefaultValue_ == inField.HasDefaultValue();
195 }
196
IsAssetType() const197 bool FieldInfo::IsAssetType() const
198 {
199 return strcasecmp(dataType_.c_str(), ASSET_STR) == 0;
200 }
201
IsAssetsType() const202 bool FieldInfo::IsAssetsType() const
203 {
204 return strcasecmp(dataType_.c_str(), ASSETS_STR) == 0;
205 }
206
GetCollateType() const207 CollateType FieldInfo::GetCollateType() const
208 {
209 return collateType_;
210 }
211
SetCollateType(CollateType collateType)212 void FieldInfo::SetCollateType(CollateType collateType)
213 {
214 collateType_ = collateType;
215 }
216
GetTableName() const217 const std::string &TableInfo::GetTableName() const
218 {
219 return tableName_;
220 }
221
SetTableName(const std::string & tableName)222 void TableInfo::SetTableName(const std::string &tableName)
223 {
224 tableName_ = tableName;
225 }
226
GetOriginTableName() const227 const std::string &TableInfo::GetOriginTableName() const
228 {
229 return originTableName_;
230 }
231
SetOriginTableName(const std::string & originTableName)232 void TableInfo::SetOriginTableName(const std::string &originTableName)
233 {
234 originTableName_ = originTableName;
235 }
236
SetSharedTableMark(bool sharedTableMark)237 void TableInfo::SetSharedTableMark(bool sharedTableMark)
238 {
239 sharedTableMark_ = sharedTableMark;
240 }
241
GetSharedTableMark() const242 bool TableInfo::GetSharedTableMark() const
243 {
244 return sharedTableMark_;
245 }
246
SetAutoIncrement(bool autoInc)247 void TableInfo::SetAutoIncrement(bool autoInc)
248 {
249 autoInc_ = autoInc;
250 }
251
GetAutoIncrement() const252 bool TableInfo::GetAutoIncrement() const
253 {
254 return autoInc_;
255 }
256
SetTableSyncType(TableSyncType tableSyncType)257 void TableInfo::SetTableSyncType(TableSyncType tableSyncType)
258 {
259 tableSyncType_ = tableSyncType;
260 }
261
GetTableSyncType() const262 TableSyncType TableInfo::GetTableSyncType() const
263 {
264 return tableSyncType_;
265 }
266
GetCreateTableSql() const267 const std::string &TableInfo::GetCreateTableSql() const
268 {
269 return sql_;
270 }
271
SetCreateTableSql(const std::string & sql)272 void TableInfo::SetCreateTableSql(const std::string &sql)
273 {
274 sql_ = sql;
275 for (auto &c : sql_) {
276 c = static_cast<char>(std::toupper(c));
277 }
278 if (DBCommon::HasConstraint(DBCommon::TrimSpace(sql_), "AUTOINCREMENT", " ", " ,)")) {
279 autoInc_ = true;
280 }
281 }
282
GetFields() const283 const FieldInfoMap &TableInfo::GetFields() const
284 {
285 return fields_;
286 }
287
GetFieldInfos() const288 const std::vector<FieldInfo> &TableInfo::GetFieldInfos() const
289 {
290 if (!fieldInfos_.empty() && fieldInfos_.size() == fields_.size()) {
291 return fieldInfos_;
292 }
293 fieldInfos_.resize(fields_.size());
294 if (fieldInfos_.size() != fields_.size()) {
295 LOGE("GetField error, alloc memory failed.");
296 return fieldInfos_;
297 }
298 for (const auto &entry : fields_) {
299 if (static_cast<size_t>(entry.second.GetColumnId()) >= fieldInfos_.size()) {
300 LOGE("Cid is over field size.");
301 fieldInfos_.clear();
302 return fieldInfos_;
303 }
304 fieldInfos_.at(entry.second.GetColumnId()) = entry.second;
305 }
306 return fieldInfos_;
307 }
308
GetFieldName(uint32_t cid) const309 std::string TableInfo::GetFieldName(uint32_t cid) const
310 {
311 if (cid >= fields_.size() || GetFieldInfos().empty()) {
312 return {};
313 }
314 return GetFieldInfos().at(cid).GetFieldName();
315 }
316
IsValid() const317 bool TableInfo::IsValid() const
318 {
319 return !tableName_.empty();
320 }
321
AddField(const FieldInfo & field)322 void TableInfo::AddField(const FieldInfo &field)
323 {
324 fields_[field.GetFieldName()] = field;
325 }
326
GetIndexDefine() const327 const IndexInfoMap &TableInfo::GetIndexDefine() const
328 {
329 return indexDefines_;
330 }
331
GetUniqueDefine() const332 const std::vector<CompositeFields> &TableInfo::GetUniqueDefine() const
333 {
334 return uniqueDefines_;
335 }
336
AddIndexDefine(const std::string & indexName,const CompositeFields & indexDefine)337 void TableInfo::AddIndexDefine(const std::string &indexName, const CompositeFields &indexDefine)
338 {
339 indexDefines_[indexName] = indexDefine;
340 }
341
SetUniqueDefine(const std::vector<CompositeFields> & uniqueDefine)342 void TableInfo::SetUniqueDefine(const std::vector<CompositeFields> &uniqueDefine)
343 {
344 uniqueDefines_ = uniqueDefine;
345 std::sort(uniqueDefines_.begin(), uniqueDefines_.end());
346 }
347
GetPrimaryKey() const348 const std::map<int, FieldName> &TableInfo::GetPrimaryKey() const
349 {
350 return primaryKey_;
351 }
352
GetIdentifyKey() const353 CompositeFields TableInfo::GetIdentifyKey() const
354 {
355 if (primaryKey_.size() == 1 && primaryKey_.at(0) == ROW_ID) {
356 if (!uniqueDefines_.empty()) { // LCOV_EXCL_BR_LINE
357 return uniqueDefines_.at(0);
358 }
359 }
360 CompositeFields key;
361 for (const auto &it : primaryKey_) {
362 key.emplace_back(it.second);
363 }
364 return key;
365 }
366
SetPrimaryKey(const std::map<int,FieldName> & key)367 void TableInfo::SetPrimaryKey(const std::map<int, FieldName> &key)
368 {
369 primaryKey_ = key;
370 }
371
SetPrimaryKey(const FieldName & fieldName,int keyIndex)372 void TableInfo::SetPrimaryKey(const FieldName &fieldName, int keyIndex)
373 {
374 if (keyIndex <= 0) {
375 LOGW("Set primary key index %d less than or equal to 0", keyIndex);
376 return;
377 }
378
379 primaryKey_[keyIndex - 1] = fieldName;
380 }
381
AddFieldDefineString(std::string & attrStr) const382 void TableInfo::AddFieldDefineString(std::string &attrStr) const
383 {
384 if (fields_.empty()) {
385 return;
386 }
387 attrStr += R"("DEFINE": {)";
388 for (auto itField = fields_.begin(); itField != fields_.end(); ++itField) {
389 attrStr += itField->second.ToAttributeString();
390 if (itField != std::prev(fields_.end(), 1)) {
391 attrStr += ",";
392 }
393 }
394 attrStr += "},";
395 }
396
AddIndexDefineString(std::string & attrStr) const397 void TableInfo::AddIndexDefineString(std::string &attrStr) const
398 {
399 if (indexDefines_.empty()) {
400 return;
401 }
402 attrStr += R"(,"INDEX": {)";
403 for (auto itIndexDefine = indexDefines_.begin(); itIndexDefine != indexDefines_.end(); ++itIndexDefine) {
404 attrStr += "\"" + (*itIndexDefine).first + "\": [\"";
405 for (auto itField = itIndexDefine->second.begin(); itField != itIndexDefine->second.end(); ++itField) {
406 attrStr += *itField;
407 if (itField != itIndexDefine->second.end() - 1) {
408 attrStr += "\",\"";
409 }
410 }
411 attrStr += "\"]";
412 if (itIndexDefine != std::prev(indexDefines_.end(), 1)) {
413 attrStr += ",";
414 }
415 }
416 attrStr += "}";
417 }
418
AddUniqueDefineString(std::string & attrStr) const419 void TableInfo::AddUniqueDefineString(std::string &attrStr) const
420 {
421 if (uniqueDefines_.empty()) {
422 return;
423 }
424
425 attrStr += R"("UNIQUE":[)";
426 for (const auto &unique : uniqueDefines_) {
427 attrStr += "[";
428 for (const auto &it : unique) {
429 attrStr += "\"" + it + "\",";
430 }
431 attrStr.pop_back();
432 attrStr += "],";
433 }
434 attrStr.pop_back();
435 attrStr += "],";
436 }
437
CompareWithTable(const TableInfo & inTableInfo,const std::string & schemaVersion) const438 int TableInfo::CompareWithTable(const TableInfo &inTableInfo, const std::string &schemaVersion) const
439 {
440 if (!DBCommon::CaseInsensitiveCompare(tableName_, inTableInfo.GetTableName())) {
441 LOGW("[Relational][Compare] Table name is not same");
442 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
443 }
444
445 int primaryKeyResult = CompareWithPrimaryKey(primaryKey_, inTableInfo.GetPrimaryKey());
446 if (primaryKeyResult == -E_RELATIONAL_TABLE_INCOMPATIBLE) {
447 LOGW("[Relational][Compare] Table primary key is not same");
448 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
449 }
450
451 int fieldCompareResult = CompareWithTableFields(inTableInfo.GetFields());
452 if (fieldCompareResult == -E_RELATIONAL_TABLE_INCOMPATIBLE) {
453 LOGW("[Relational][Compare] Compare table fields with in table, %d", fieldCompareResult);
454 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
455 }
456
457 if (schemaVersion == SchemaConstant::SCHEMA_SUPPORT_VERSION_V2_1) {
458 int uniqueCompareResult = CompareWithTableUnique(inTableInfo.GetUniqueDefine());
459 if (uniqueCompareResult == -E_RELATIONAL_TABLE_INCOMPATIBLE) {
460 LOGW("[Relational][Compare] Compare table unique with in table, %d", fieldCompareResult);
461 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
462 }
463
464 if (autoInc_ != inTableInfo.GetAutoIncrement()) {
465 LOGW("[Relational][Compare] Compare table auto increment with in table");
466 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
467 }
468 }
469
470 int indexCompareResult = CompareWithTableIndex(inTableInfo.GetIndexDefine());
471 return (fieldCompareResult == -E_RELATIONAL_TABLE_EQUAL) ? indexCompareResult : fieldCompareResult;
472 }
473
CompareWithPrimaryKey(const std::map<int,FieldName> & local,const std::map<int,FieldName> & remote) const474 int TableInfo::CompareWithPrimaryKey(const std::map<int, FieldName> &local,
475 const std::map<int, FieldName> &remote) const
476 {
477 if (local.size() != remote.size()) {
478 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
479 }
480
481 for (size_t i = 0; i < local.size(); i++) {
482 if (local.find(i) == local.end() || remote.find(i) == remote.end() ||
483 !DBCommon::CaseInsensitiveCompare(local.at(i), remote.at(i))) {
484 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
485 }
486 }
487
488 return -E_RELATIONAL_TABLE_EQUAL;
489 }
490
CompareWithTableFields(const FieldInfoMap & inTableFields,bool isLite) const491 int TableInfo::CompareWithTableFields(const FieldInfoMap &inTableFields, bool isLite) const
492 {
493 auto itLocal = fields_.begin();
494 auto itInTable = inTableFields.begin();
495 int errCode = -E_RELATIONAL_TABLE_EQUAL;
496 while (itLocal != fields_.end() && itInTable != inTableFields.end()) {
497 if (DBCommon::CaseInsensitiveCompare(itLocal->first, itInTable->first)) { // Same field
498 if (!itLocal->second.CompareWithField(itInTable->second, isLite)) { // Compare field
499 LOGW("[Relational][Compare] Table field is incompatible"); // not compatible
500 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
501 }
502 itLocal++; // Compare next field
503 } else { // Assume local table fields is a subset of in table
504 if (itInTable->second.IsNotNull() && !itInTable->second.HasDefaultValue()) { // Upgrade field not compatible
505 LOGW("[Relational][Compare] Table upgrade field should allowed to be empty or have default value.");
506 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
507 }
508 errCode = -E_RELATIONAL_TABLE_COMPATIBLE_UPGRADE;
509 }
510 itInTable++; // Next in table field
511 }
512
513 if (itLocal != fields_.end()) {
514 LOGW("[Relational][Compare] Table field is missing");
515 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
516 }
517
518 if (itInTable == inTableFields.end()) {
519 return errCode;
520 }
521
522 while (itInTable != inTableFields.end()) {
523 if (itInTable->second.IsNotNull() && !itInTable->second.HasDefaultValue()) {
524 LOGW("[Relational][Compare] Table upgrade field should allowed to be empty or have default value.");
525 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
526 }
527 itInTable++;
528 }
529 return -E_RELATIONAL_TABLE_COMPATIBLE_UPGRADE;
530 }
531
CompareCompositeFields(const CompositeFields & local,const CompositeFields & remote) const532 int TableInfo::CompareCompositeFields(const CompositeFields &local, const CompositeFields &remote) const
533 {
534 if (local.size() != remote.size()) {
535 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
536 }
537
538 for (size_t i = 0; i < local.size(); i++) {
539 if (!DBCommon::CaseInsensitiveCompare(local.at(i), remote.at(i))) {
540 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
541 }
542 }
543
544 return -E_RELATIONAL_TABLE_EQUAL;
545 }
546
CompareWithTableUnique(const std::vector<CompositeFields> & inTableUnique) const547 int TableInfo::CompareWithTableUnique(const std::vector<CompositeFields> &inTableUnique) const
548 {
549 if (uniqueDefines_.size() != inTableUnique.size()) {
550 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
551 }
552
553 auto itLocal = uniqueDefines_.begin();
554 auto itInTable = inTableUnique.begin();
555 while (itLocal != uniqueDefines_.end()) {
556 if (CompareCompositeFields(*itLocal, *itInTable) != -E_RELATIONAL_TABLE_EQUAL) {
557 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
558 }
559 itLocal++;
560 itInTable++;
561 }
562 return -E_RELATIONAL_TABLE_EQUAL;
563 }
564
CompareWithTableIndex(const IndexInfoMap & inTableIndex) const565 int TableInfo::CompareWithTableIndex(const IndexInfoMap &inTableIndex) const
566 {
567 // Index comparison results do not affect synchronization decisions
568 auto itLocal = indexDefines_.begin();
569 auto itInTable = inTableIndex.begin();
570 while (itLocal != indexDefines_.end() && itInTable != inTableIndex.end()) {
571 if (!DBCommon::CaseInsensitiveCompare(itLocal->first, itInTable->first) ||
572 !CompareCompositeFields(itLocal->second, itInTable->second)) {
573 return -E_RELATIONAL_TABLE_COMPATIBLE;
574 }
575 itLocal++;
576 itInTable++;
577 }
578 return (itLocal == indexDefines_.end() && itInTable == inTableIndex.end()) ? -E_RELATIONAL_TABLE_EQUAL :
579 -E_RELATIONAL_TABLE_COMPATIBLE;
580 }
581
582 namespace {
Difference(const FieldInfoMap & first,const FieldInfoMap & second,FieldInfoMap & orphanFst,FieldInfoMap & orphanSnd,FieldInfoMap & bothAppear)583 void Difference(const FieldInfoMap &first, const FieldInfoMap &second, FieldInfoMap &orphanFst, FieldInfoMap &orphanSnd,
584 FieldInfoMap &bothAppear)
585 {
586 auto itFirst = first.begin();
587 auto itSecond = second.begin();
588 while (itFirst != first.end()) { // LCOV_EXCL_BR_LINE
589 if (itSecond == second.end()) { // LCOV_EXCL_BR_LINE
590 break;
591 }
592 if (itFirst->first == itSecond->first) { // LCOV_EXCL_BR_LINE
593 bothAppear.insert(*itFirst);
594 itFirst++;
595 itSecond++;
596 continue;
597 } else if (itFirst->first < itSecond->first) {
598 orphanFst.insert(*itFirst++);
599 } else {
600 orphanSnd.insert(*itSecond++);
601 }
602 }
603
604 while (itFirst != first.end()) { // LCOV_EXCL_BR_LINE
605 orphanFst.insert(*itFirst++);
606 }
607
608 while (itSecond != second.end()) { // LCOV_EXCL_BR_LINE
609 orphanSnd.insert(*itSecond++);
610 }
611 }
612 }
613
CompareWithLiteTableFields(const FieldInfoMap & liteTableFields) const614 int TableInfo::CompareWithLiteTableFields(const FieldInfoMap &liteTableFields) const
615 {
616 FieldInfoMap orphanLocal;
617 FieldInfoMap orphanLite;
618 FieldInfoMap bothAppear;
619 Difference(fields_, liteTableFields, orphanLocal, orphanLite, bothAppear);
620
621 if (!orphanLocal.empty() && !orphanLite.empty()) { // LCOV_EXCL_BR_LINE
622 LOGE("[Relational][Compare] Only one side should have upgrade fields");
623 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
624 }
625
626 for (const auto &it : bothAppear) {
627 if (!it.second.CompareWithField(liteTableFields.at(it.first), true)) { // LCOV_EXCL_BR_LINE
628 LOGE("[Relational][Compare] field is incompatible");
629 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
630 }
631 }
632
633 for (const auto &it : orphanLocal) {
634 if (it.second.IsNotNull() && !it.second.HasDefaultValue()) { // LCOV_EXCL_BR_LINE
635 LOGE("[Relational][Compare] field is upgrade incompatible");
636 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
637 }
638 }
639
640 for (const auto &it : orphanLite) {
641 if (it.second.IsNotNull() && !it.second.HasDefaultValue()) { // LCOV_EXCL_BR_LINE
642 LOGE("[Relational][Compare] field is upgrade incompatible");
643 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
644 }
645 }
646
647 return E_OK;
648 }
649
CompareWithLiteSchemaTable(const TableInfo & liteTableInfo) const650 int TableInfo::CompareWithLiteSchemaTable(const TableInfo &liteTableInfo) const
651 {
652 if (!liteTableInfo.GetPrimaryKey().empty() && (primaryKey_.at(0) != ROW_ID) &&
653 !CompareWithPrimaryKey(primaryKey_, liteTableInfo.GetPrimaryKey())) { // LCOV_EXCL_BR_LINE
654 LOGE("[Relational][Compare] Table primary key is not same");
655 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
656 }
657 if (!liteTableInfo.GetPrimaryKey().empty() && (primaryKey_.at(0) == ROW_ID)) { // LCOV_EXCL_BR_LINE
658 LOGE("[Relational][Compare] Table primary key is not same");
659 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
660 }
661 if ((liteTableInfo.GetPrimaryKey().empty() && (primaryKey_.at(0) != ROW_ID) && !autoInc_)) { // LCOV_EXCL_BR_LINE
662 LOGE("[Relational][Compare] Table primary key is not same");
663 return -E_RELATIONAL_TABLE_INCOMPATIBLE;
664 }
665
666 return CompareWithLiteTableFields(liteTableInfo.GetFields());
667 }
668
ToTableInfoString(const std::string & schemaVersion) const669 std::string TableInfo::ToTableInfoString(const std::string &schemaVersion) const
670 {
671 std::string attrStr;
672 attrStr += "{";
673 attrStr += R"("NAME": ")" + tableName_ + "\",";
674 AddFieldDefineString(attrStr);
675 attrStr += R"("ORIGINTABLENAME": ")" + originTableName_ + "\",";
676 attrStr += R"("AUTOINCREMENT": )";
677 if (autoInc_) {
678 attrStr += "true,";
679 } else {
680 attrStr += "false,";
681 }
682 attrStr += R"("SHAREDTABLEMARK": )";
683 if (sharedTableMark_) {
684 attrStr += "true,";
685 } else {
686 attrStr += "false,";
687 }
688 AddUniqueDefineString(attrStr);
689 if (primaryKey_.size() == 1 && schemaVersion == SchemaConstant::SCHEMA_SUPPORT_VERSION_V2) {
690 attrStr += R"("PRIMARY_KEY": ")" + primaryKey_.at(0) + "\"";
691 } else {
692 if (!primaryKey_.empty()) {
693 std::string primaryKey;
694 for (const auto &item : primaryKey_) {
695 primaryKey += "\"" + item.second + "\",";
696 }
697 primaryKey.pop_back(); // remove the last comma
698 attrStr += R"("PRIMARY_KEY": [)" + primaryKey + "]";
699 }
700 }
701 attrStr += R"(,"TABLE_SYNC_TYPE": )" + std::to_string(static_cast<int>(tableSyncType_));
702 AddIndexDefineString(attrStr);
703 attrStr += "}";
704 return attrStr;
705 }
706
GetSchemaDefine() const707 std::map<FieldPath, SchemaAttribute> TableInfo::GetSchemaDefine() const
708 {
709 std::map<FieldPath, SchemaAttribute> schemaDefine;
710 for (const auto &[fieldName, fieldInfo] : GetFields()) {
711 FieldValue defaultValue;
712 defaultValue.stringValue = fieldInfo.GetDefaultValue();
713 schemaDefine[std::vector { DBCommon::ToLowerCase(fieldName) }] = SchemaAttribute {
714 .type = FieldType::LEAF_FIELD_NULL, // For relational schema, the json field type is unimportant.
715 .isIndexable = true, // For relational schema, all field is indexable.
716 .hasNotNullConstraint = fieldInfo.IsNotNull(),
717 .hasDefaultValue = fieldInfo.HasDefaultValue(),
718 .defaultValue = defaultValue,
719 .customFieldType = {}
720 };
721 }
722 return schemaDefine;
723 }
724
SetTableId(int id)725 void TableInfo::SetTableId(int id)
726 {
727 id_ = id;
728 }
729
GetTableId() const730 int TableInfo::GetTableId() const
731 {
732 return id_;
733 }
734
Empty() const735 bool TableInfo::Empty() const
736 {
737 return tableName_.empty() || fields_.empty();
738 }
739
SetTrackerTable(const TrackerTable & table)740 void TableInfo::SetTrackerTable(const TrackerTable &table)
741 {
742 trackerTable_ = table;
743 }
744
CheckTrackerTable()745 int TableInfo::CheckTrackerTable()
746 {
747 if (tableName_ != trackerTable_.GetTableName()) {
748 LOGE("the table name in schema is different from tracker table.");
749 return -E_NOT_FOUND;
750 }
751 if (trackerTable_.GetTrackerColNames().empty()) {
752 return E_OK;
753 }
754 for (const auto &colName: trackerTable_.GetTrackerColNames()) {
755 if (colName.empty()) {
756 LOGE("tracker col cannot be empty.");
757 return -E_INVALID_ARGS;
758 }
759 if (GetFields().find(colName) == GetFields().end()) {
760 LOGE("unable to match the tracker col from table schema.");
761 return -E_SCHEMA_MISMATCH;
762 }
763 }
764 if (trackerTable_.GetExtendName().empty()) {
765 return E_OK;
766 }
767 auto iter = GetFields().find(trackerTable_.GetExtendName());
768 if (iter == GetFields().end()) {
769 LOGE("unable to match the extend col from table schema.");
770 return -E_SCHEMA_MISMATCH;
771 } else {
772 if (iter->second.IsAssetType() || iter->second.IsAssetsType()) {
773 LOGE("extend col is not allowed to be set as an asset field.");
774 return -E_INVALID_ARGS;
775 }
776 }
777 return E_OK;
778 }
779
GetTrackerTable() const780 const TrackerTable &TableInfo::GetTrackerTable() const
781 {
782 return trackerTable_;
783 }
784
AddTableReferenceProperty(const TableReferenceProperty & tableRefProperty)785 void TableInfo::AddTableReferenceProperty(const TableReferenceProperty &tableRefProperty)
786 {
787 sourceTableReferenced_.push_back(tableRefProperty);
788 }
789
SetSourceTableReference(const std::vector<TableReferenceProperty> & tableReference)790 void TableInfo::SetSourceTableReference(const std::vector<TableReferenceProperty> &tableReference)
791 {
792 sourceTableReferenced_ = tableReference;
793 }
794
GetTableReference() const795 const std::vector<TableReferenceProperty> &TableInfo::GetTableReference() const
796 {
797 return sourceTableReferenced_;
798 }
799
IsNoPkTable() const800 bool TableInfo::IsNoPkTable() const
801 {
802 if (primaryKey_.size() == 1 && primaryKey_.at(0) == ROW_ID) {
803 return true;
804 }
805 return false;
806 }
807 } // namespace DistributeDB