1 /*
2 * Copyright (c) 2023 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 #define LOG_TAG "ResultSetJsonFormatter"
16 #include "resultset_json_formatter.h"
17
18 #include "log_print.h"
19 #include "rdb_errno.h"
20
21 namespace OHOS::DataShare {
Marshal(json & node) const22 bool ResultSetJsonFormatter::Marshal(json &node) const
23 {
24 node = json::array();
25 int columnCount = 0;
26 auto result = resultSet->GetColumnCount(columnCount);
27 if (result != NativeRdb::E_OK) {
28 ZLOGE("GetColumnCount err, %{public}d", result);
29 return false;
30 }
31 while (resultSet->GoToNextRow() == NativeRdb::E_OK) {
32 if (!MarshalRow(node, columnCount)) {
33 ZLOGE("MarshalRow err");
34 return false;
35 }
36 }
37 return true;
38 }
39
Unmarshal(const DistributedData::Serializable::json & node)40 bool ResultSetJsonFormatter::Unmarshal(const DistributedData::Serializable::json &node)
41 {
42 return false;
43 }
44
MarshalRow(DistributedData::Serializable::json & node,int columnCount) const45 bool ResultSetJsonFormatter::MarshalRow(DistributedData::Serializable::json &node, int columnCount) const
46 {
47 using namespace NativeRdb;
48 json result;
49 std::string columnName;
50 NativeRdb::ColumnType type;
51 for (int i = 0; i < columnCount; i++) {
52 if (resultSet->GetColumnType(i, type) != E_OK) {
53 ZLOGE("GetColumnType err %{public}d", i);
54 return false;
55 }
56 if (resultSet->GetColumnName(i, columnName) != E_OK) {
57 ZLOGE("GetColumnName err %{public}d", i);
58 return false;
59 }
60 switch (type) {
61 case ColumnType::TYPE_INTEGER:
62 int64_t value;
63 resultSet->GetLong(i, value);
64 SetValue(result[columnName], value);
65 break;
66 case ColumnType::TYPE_FLOAT:
67 double dValue;
68 resultSet->GetDouble(i, dValue);
69 SetValue(result[columnName], dValue);
70 break;
71 case ColumnType::TYPE_NULL:
72 result[columnName] = nullptr;
73 break;
74 case ColumnType::TYPE_STRING: {
75 std::string stringValue;
76 resultSet->GetString(i, stringValue);
77 SetValue(result[columnName], stringValue);
78 break;
79 }
80 case ColumnType::TYPE_BLOB: {
81 std::vector<uint8_t> blobValue;
82 resultSet->GetBlob(i, blobValue);
83 SetValue(result[columnName], blobValue);
84 break;
85 }
86 default:
87 ZLOGE("unknow type %{public}d", type);
88 return false;
89 }
90 }
91 node.push_back(result);
92 return true;
93 }
94 } // namespace OHOS::DataShare