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 #define LOG_TAG "StepResultSet"
16 #include "step_result_set.h"
17
18 #include <unistd.h>
19
20 #include "connection_pool.h"
21 #include "logger.h"
22 #include "rdb_errno.h"
23 #include "sqlite3sym.h"
24 #include "sqlite_errno.h"
25 #include "sqlite_statement.h"
26 #include "sqlite_utils.h"
27 #include "value_object.h"
28
29 namespace OHOS {
30 namespace NativeRdb {
31 using namespace OHOS::Rdb;
32
33 constexpr int64_t TIME_OUT = 1500;
StepResultSet(Time start,Conn conn,const std::string & sql,const Values & args,bool preCount,bool safe)34 StepResultSet::StepResultSet(Time start, Conn conn, const std::string &sql, const Values &args,
35 bool preCount, bool safe) : AbsResultSet(safe), conn_(std::move(conn)), sql_(sql), args_(args)
36 {
37 if (conn_ == nullptr) {
38 isClosed_ = true;
39 return;
40 }
41
42 auto prepareStart = std::chrono::steady_clock::now();
43 auto errCode = PrepareStep();
44 if (errCode != E_OK) {
45 LOG_ERROR("step resultset ret %{public}d", errCode);
46 return;
47 }
48 auto prepareEnd = std::chrono::steady_clock::now();
49 auto statement = GetStatement();
50 if (statement == nullptr) {
51 return;
52 }
53 if (preCount) {
54 std::tie(lastErr_, rowCount_) = statement->Count();
55 } else {
56 isSupportCountRow_ = false;
57 }
58 if (lastErr_ == E_NOT_SUPPORT && rowCount_ == Statement::INVALID_COUNT) {
59 isSupportCountRow_ = false;
60 lastErr_ = E_OK;
61 }
62 auto queryEnd = std::chrono::steady_clock::now();
63 int64_t totalCost = std::chrono::duration_cast<std::chrono::milliseconds>(queryEnd - start).count();
64 if (totalCost >= TIME_OUT) {
65 int64_t acquireCost = std::chrono::duration_cast<std::chrono::milliseconds>(prepareStart - start).count();
66 int64_t prepareCost = std::chrono::duration_cast<std::chrono::milliseconds>(prepareEnd - prepareStart).count();
67 int64_t countCost = std::chrono::duration_cast<std::chrono::milliseconds>(queryEnd - prepareEnd).count();
68 LOG_WARN("total[%{public}" PRId64 "]<%{public}" PRId64 ",%{public}" PRId64 ",%{public}" PRId64
69 "> count[%{public}d] sql[%{public}s]",
70 totalCost, acquireCost, prepareCost, countCost, rowCount_, SqliteUtils::Anonymous(sql_).c_str());
71 }
72 }
73
~StepResultSet()74 StepResultSet::~StepResultSet()
75 {
76 Close();
77 }
78
79 /**
80 * Obtain session and prepare precompile statement for step query
81 */
PrepareStep()82 int StepResultSet::PrepareStep()
83 {
84 std::lock_guard<decltype(globalMtx_)> lockGuard(globalMtx_);
85 if (statement_ != nullptr) {
86 return E_OK;
87 }
88
89 if (isClosed_ || conn_ == nullptr) {
90 lastErr_ = E_ALREADY_CLOSED;
91 return lastErr_;
92 }
93
94 auto type = SqliteUtils::GetSqlStatementType(sql_);
95 if (type == SqliteUtils::STATEMENT_ERROR) {
96 LOG_ERROR("invalid sql_ %{public}s!", SqliteUtils::Anonymous(sql_).c_str());
97 lastErr_ = E_INVALID_ARGS;
98 return lastErr_;
99 }
100
101 auto [errCode, statement] = conn_->CreateStatement(sql_, conn_);
102 if (statement == nullptr || errCode != E_OK) {
103 lastErr_ = errCode;
104 return E_STATEMENT_NOT_PREPARED;
105 }
106
107 if (!statement->ReadOnly()) {
108 LOG_ERROR("failed, %{public}s is not query sql!", SqliteUtils::Anonymous(sql_).c_str());
109 lastErr_ = E_NOT_SELECT;
110 return lastErr_;
111 }
112
113 errCode = statement->Bind(args_);
114 if (errCode != E_OK) {
115 LOG_ERROR("Bind arg faild! Ret is %{public}d", errCode);
116 statement->Reset();
117 statement = nullptr;
118 lastErr_ = errCode;
119 return lastErr_;
120 }
121
122 statement_ = std::move(statement);
123 return E_OK;
124 }
125
GetColumnNames()126 std::pair<int, std::vector<std::string>> StepResultSet::GetColumnNames()
127 {
128 if (lastErr_ != E_OK) {
129 return { lastErr_, {} };
130 }
131 auto statement = GetStatement();
132 if (statement == nullptr) {
133 LOG_ERROR("Statement is nullptr.");
134 return { E_ALREADY_CLOSED, {} };
135 }
136 auto colCount = statement->GetColumnCount();
137 std::vector<std::string> names;
138 for (int i = 0; i < colCount; i++) {
139 auto [code, colName] = statement->GetColumnName(i);
140 if (code) {
141 LOG_ERROR("GetColumnName ret %{public}d", code);
142 return { code, {} };
143 }
144 names.push_back(colName);
145 }
146
147 return { E_OK, std::move(names) };
148 }
149
GetColumnType(int columnIndex,ColumnType & columnType)150 int StepResultSet::GetColumnType(int columnIndex, ColumnType &columnType)
151 {
152 if (isClosed_) {
153 return E_ALREADY_CLOSED;
154 }
155 if (rowPos_ == INIT_POS || ((isSupportCountRow_ || rowCount_ != Statement::INVALID_COUNT) && IsEnded().second)) {
156 LOG_ERROR("query not executed.");
157 return E_ROW_OUT_RANGE;
158 }
159 auto statement = GetStatement();
160 if (statement == nullptr) {
161 LOG_ERROR("Statement is nullptr.");
162 return E_ALREADY_CLOSED;
163 }
164
165 auto [errCode, outPutType] = statement->GetColumnType(columnIndex);
166 if (errCode != E_OK) {
167 LOG_ERROR("GetColumnType ret %{public}d", errCode);
168 return errCode;
169 }
170 columnType = static_cast<ColumnType>(outPutType);
171 return E_OK;
172 }
173
174 /**
175 * Moves the result set to a specified position
176 */
GoToRow(int position)177 int StepResultSet::GoToRow(int position)
178 {
179 if (isClosed_) {
180 return E_ALREADY_CLOSED;
181 }
182
183 if (lastErr_ != E_OK) {
184 return lastErr_;
185 }
186
187 if (isSupportCountRow_ && position >= rowCount_) {
188 rowPos_ = (position >= rowCount_ && rowCount_ != 0) ? rowCount_ : rowPos_;
189 LOG_ERROR("position[%{public}d] rowCount[%{public}d] rowPos_[%{public}d]!", position, rowCount_, rowPos_);
190 return E_ROW_OUT_RANGE;
191 }
192
193 if (position < 0) {
194 return E_ROW_OUT_RANGE;
195 }
196
197 if (position < rowPos_) {
198 Reset();
199 return GoToRow(position);
200 }
201 while (position != rowPos_) {
202 int errCode = GoToNextRow();
203 if (errCode != E_OK) {
204 LOG_WARN("GoToNextRow ret %{public}d", errCode);
205 return errCode;
206 }
207 }
208 return E_OK;
209 }
210
211 /**
212 * Move the result set to the next row
213 */
GoToNextRow()214 int StepResultSet::GoToNextRow()
215 {
216 if (isClosed_) {
217 LOG_ERROR("resultSet closed.");
218 return E_ALREADY_CLOSED;
219 }
220
221 auto statement = GetStatement();
222 if (statement == nullptr) {
223 LOG_ERROR("Statement is nullptr.");
224 return E_ALREADY_CLOSED;
225 }
226
227 int retryCount = 0;
228 auto errCode = statement->Step();
229
230 while (errCode == E_SQLITE_LOCKED || errCode == E_SQLITE_BUSY) {
231 // The table is locked, retry
232 if (retryCount > STEP_QUERY_RETRY_MAX_TIMES) {
233 LOG_ERROR("Step in busy ret is %{public}d", errCode);
234 return E_STEP_RESULT_QUERY_EXCEEDED;
235 } else {
236 // Sleep to give the thread holding the lock a chance to finish
237 usleep(STEP_QUERY_RETRY_INTERVAL);
238 errCode = statement->Step();
239 retryCount++;
240 }
241 }
242
243 if (errCode == E_OK) {
244 rowPos_++;
245 return E_OK;
246 } else if (errCode == E_NO_MORE_ROWS) {
247 if (isSupportCountRow_ || rowCount_ != Statement::INVALID_COUNT) {
248 rowPos_ = rowCount_ != 0 ? rowCount_ : rowPos_;
249 } else {
250 ++rowPos_;
251 rowCount_ = rowPos_;
252 }
253 return E_ROW_OUT_RANGE;
254 } else {
255 Reset();
256 rowPos_ = rowCount_;
257 return errCode;
258 }
259 }
260
Close()261 int StepResultSet::Close()
262 {
263 if (isClosed_) {
264 return E_OK;
265 }
266 isClosed_ = true;
267 {
268 std::lock_guard<decltype(globalMtx_)> lockGuard(globalMtx_);
269 conn_ = nullptr;
270 statement_ = nullptr;
271 auto args = std::move(args_);
272 auto sql = std::move(sql_);
273 }
274 Reset();
275 return E_OK;
276 }
277
GetRowCount(int & count)278 int StepResultSet::GetRowCount(int &count)
279 {
280 if (isSupportCountRow_ || rowCount_ != Statement::INVALID_COUNT) {
281 return AbsResultSet::GetRowCount(count);
282 }
283
284 int oldPosition = 0;
285 // Get the start position of the query result
286 GetRowIndex(oldPosition);
287 int ret = E_OK;
288 while (ret == E_OK) {
289 ret = GoToNextRow();
290 if (ret == E_ROW_OUT_RANGE) {
291 rowCount_ = rowPos_;
292 break;
293 }
294 if (ret != E_OK) {
295 LOG_ERROR("Get row cnt err %{public}d, rowCount_ %{public}d, rowPos_ %{public}d", ret, rowCount_, rowPos_);
296 return ret;
297 }
298 };
299 count = rowCount_;
300 // Reset the start position of the query result
301 if (oldPosition != INIT_POS) {
302 GoToRow(oldPosition);
303 } else {
304 Reset();
305 }
306 return E_OK;
307 }
308
309 /**
310 * Reset the statement
311 */
Reset()312 int StepResultSet::Reset()
313 {
314 rowPos_ = INIT_POS;
315 auto statement = GetStatement();
316 if (statement != nullptr) {
317 return statement->Reset();
318 }
319 return E_OK;
320 }
321
Get(int32_t col,ValueObject & value)322 int StepResultSet::Get(int32_t col, ValueObject &value)
323 {
324 if (isClosed_) {
325 return E_ALREADY_CLOSED;
326 }
327 return GetValue(col, value);
328 }
329
GetSize(int columnIndex,size_t & size)330 int StepResultSet::GetSize(int columnIndex, size_t &size)
331 {
332 if (isClosed_) {
333 return E_ALREADY_CLOSED;
334 }
335 if (rowPos_ == INIT_POS || ((isSupportCountRow_ || rowCount_ != Statement::INVALID_COUNT) && IsEnded().second)) {
336 size = 0;
337 return E_ROW_OUT_RANGE;
338 }
339
340 auto statement = GetStatement();
341 if (statement == nullptr) {
342 LOG_ERROR("Statement is nullptr.");
343 return E_ALREADY_CLOSED;
344 }
345 auto errCode = E_ERROR;
346 std::tie(errCode, size) = statement->GetSize(columnIndex);
347 return errCode;
348 }
349
350 template<typename T>
GetValue(int32_t col,T & value)351 int StepResultSet::GetValue(int32_t col, T &value)
352 {
353 auto [errCode, object] = GetValueObject(col, ValueObject::TYPE_INDEX<decltype(value)>);
354 if (errCode != E_OK) {
355 LOG_ERROR("ret is %{public}d", errCode);
356 return errCode;
357 }
358 value = static_cast<T>(object);
359 return E_OK;
360 }
361
GetValueObject(int32_t col,size_t index)362 std::pair<int, ValueObject> StepResultSet::GetValueObject(int32_t col, size_t index)
363 {
364 if (rowPos_ == INIT_POS || ((isSupportCountRow_ || rowCount_ != Statement::INVALID_COUNT) && IsEnded().second)) {
365 return { E_ROW_OUT_RANGE, ValueObject() };
366 }
367 auto statement = GetStatement();
368 if (statement == nullptr) {
369 return { E_ALREADY_CLOSED, ValueObject() };
370 }
371 auto [ret, value] = statement->GetColumn(col);
372 if (index < ValueObject::TYPE_MAX && value.value.index() != index) {
373 return { E_INVALID_COLUMN_TYPE, ValueObject() };
374 }
375 return { ret, std::move(value) };
376 }
377
GetStatement()378 std::shared_ptr<Statement> StepResultSet::GetStatement()
379 {
380 std::lock_guard<decltype(globalMtx_)> lockGuard(globalMtx_);
381 if (isClosed_ || conn_ == nullptr) {
382 return nullptr;
383 }
384
385 return statement_;
386 }
387 } // namespace NativeRdb
388 } // namespace OHOS