1 /*
2 * Copyright (c) 2022-2025 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 "app_event_store.h"
16
17 #include <cinttypes>
18 #include <utility>
19 #include <vector>
20
21 #include "app_event_cache_common.h"
22 #include "app_event_store_callback.h"
23 #include "file_util.h"
24 #include "hiappevent_base.h"
25 #include "hiappevent_common.h"
26 #include "hiappevent_config.h"
27 #include "hilog/log.h"
28 #include "rdb_errno.h"
29 #include "rdb_helper.h"
30 #include "sql_util.h"
31
32 #undef LOG_DOMAIN
33 #define LOG_DOMAIN 0xD002D07
34
35 #undef LOG_TAG
36 #define LOG_TAG "Store"
37
38 using namespace OHOS::HiviewDFX::AppEventCacheCommon;
39 using namespace OHOS::HiviewDFX::HiAppEvent;
40 namespace OHOS {
41 namespace HiviewDFX {
42 namespace {
43 const char* DATABASE_NAME = "appevent.db";
44 const char* DATABASE_DIR = "databases/";
45 static constexpr size_t MAX_NUM_OF_CUSTOM_PARAMS = 64;
46
GetIntFromResultSet(std::shared_ptr<NativeRdb::AbsSharedResultSet> resultSet,const std::string & colName)47 int GetIntFromResultSet(std::shared_ptr<NativeRdb::AbsSharedResultSet> resultSet, const std::string& colName)
48 {
49 int value = 0;
50 int colIndex = 0;
51 if (resultSet->GetColumnIndex(colName, colIndex) != NativeRdb::E_OK) {
52 HILOG_WARN(LOG_CORE, "failed to get column index, colName=%{public}s", colName.c_str());
53 return value;
54 }
55 if (resultSet->GetInt(colIndex, value) != NativeRdb::E_OK) {
56 HILOG_WARN(LOG_CORE, "failed to get int value, colName=%{public}s", colName.c_str());
57 }
58 return value;
59 }
60
GetLongFromResultSet(std::shared_ptr<NativeRdb::AbsSharedResultSet> resultSet,const std::string & colName)61 int64_t GetLongFromResultSet(std::shared_ptr<NativeRdb::AbsSharedResultSet> resultSet, const std::string& colName)
62 {
63 int64_t value = 0;
64 int colIndex = 0;
65 if (resultSet->GetColumnIndex(colName, colIndex) != NativeRdb::E_OK) {
66 HILOG_WARN(LOG_CORE, "failed to get column index, colName=%{public}s", colName.c_str());
67 return value;
68 }
69 if (resultSet->GetLong(colIndex, value) != NativeRdb::E_OK) {
70 HILOG_WARN(LOG_CORE, "failed to get long value, colName=%{public}s", colName.c_str());
71 }
72 return value;
73 }
74
GetStringFromResultSet(std::shared_ptr<NativeRdb::AbsSharedResultSet> resultSet,const std::string & colName)75 std::string GetStringFromResultSet(std::shared_ptr<NativeRdb::AbsSharedResultSet> resultSet, const std::string& colName)
76 {
77 std::string value;
78 int colIndex = 0;
79 if (resultSet->GetColumnIndex(colName, colIndex) != NativeRdb::E_OK) {
80 HILOG_WARN(LOG_CORE, "failed to get column index, colName=%{public}s", colName.c_str());
81 return value;
82 }
83 if (resultSet->GetString(colIndex, value) != NativeRdb::E_OK) {
84 HILOG_WARN(LOG_CORE, "failed to get string value, colName=%{public}s", colName.c_str());
85 }
86 return value;
87 }
88
GetEventFromResultSet(std::shared_ptr<NativeRdb::AbsSharedResultSet> resultSet)89 std::shared_ptr<AppEventPack> GetEventFromResultSet(std::shared_ptr<NativeRdb::AbsSharedResultSet> resultSet)
90 {
91 auto event = std::make_shared<AppEventPack>();
92 event->SetSeq(GetLongFromResultSet(resultSet, Events::FIELD_SEQ));
93 event->SetDomain(GetStringFromResultSet(resultSet, Events::FIELD_DOMAIN));
94 event->SetName(GetStringFromResultSet(resultSet, Events::FIELD_NAME));
95 event->SetType(GetIntFromResultSet(resultSet, Events::FIELD_TYPE));
96 event->SetTime(GetLongFromResultSet(resultSet, Events::FIELD_TIME));
97 event->SetTimeZone(GetStringFromResultSet(resultSet, Events::FIELD_TZ));
98 event->SetPid(GetIntFromResultSet(resultSet, Events::FIELD_PID));
99 event->SetTid(GetIntFromResultSet(resultSet, Events::FIELD_TID));
100 event->SetTraceId(GetLongFromResultSet(resultSet, Events::FIELD_TRACE_ID));
101 event->SetSpanId(GetLongFromResultSet(resultSet, Events::FIELD_SPAN_ID));
102 event->SetPspanId(GetLongFromResultSet(resultSet, Events::FIELD_PSPAN_ID));
103 event->SetTraceFlag(GetIntFromResultSet(resultSet, Events::FIELD_TRACE_FLAG));
104 event->SetParamStr(GetStringFromResultSet(resultSet, Events::FIELD_PARAMS));
105 event->SetRunningId(GetStringFromResultSet(resultSet, Events::FIELD_RUNNING_ID));
106 return event;
107 }
108
UpToDbVersion2(NativeRdb::RdbStore & rdbStore)109 int UpToDbVersion2(NativeRdb::RdbStore& rdbStore)
110 {
111 std::string sql = "ALTER TABLE " + Events::TABLE + " ADD COLUMN "
112 + Events::FIELD_RUNNING_ID + " " + SqlUtil::SQL_TEXT_TYPE + " DEFAULT " + "'';";
113 return rdbStore.ExecuteSql(sql);
114 }
115
UpToDbVersion3(NativeRdb::RdbStore & rdbStore)116 int UpToDbVersion3(NativeRdb::RdbStore& rdbStore)
117 {
118 std::string sql = "ALTER TABLE " + Observers::TABLE + " ADD COLUMN "
119 + Observers::FIELD_FILTERS + " " + SqlUtil::SQL_TEXT_TYPE + " DEFAULT " + "'';";
120 return rdbStore.ExecuteSql(sql);
121 }
122 }
123
OnCreate(NativeRdb::RdbStore & rdbStore)124 int AppEventStoreCallback::OnCreate(NativeRdb::RdbStore& rdbStore)
125 {
126 HILOG_DEBUG(LOG_CORE, "OnCreate start to create db");
127 if (int ret = AppEventDao::Create(rdbStore); ret != NativeRdb::E_OK) {
128 HILOG_ERROR(LOG_CORE, "failed to create table events, ret=%{public}d", ret);
129 return ret;
130 }
131 if (int ret = AppEventObserverDao::Create(rdbStore); ret != NativeRdb::E_OK) {
132 HILOG_ERROR(LOG_CORE, "failed to create table observers, ret=%{public}d", ret);
133 return ret;
134 }
135 if (int ret = AppEventMappingDao::Create(rdbStore); ret != NativeRdb::E_OK) {
136 HILOG_ERROR(LOG_CORE, "failed to create table event_observer_mapping, ret=%{public}d", ret);
137 return ret;
138 }
139 if (int ret = UserIdDao::Create(rdbStore); ret != NativeRdb::E_OK) {
140 HILOG_ERROR(LOG_CORE, "failed to create table user_ids, ret=%{public}d", ret);
141 return ret;
142 }
143 if (int ret = UserPropertyDao::Create(rdbStore); ret != NativeRdb::E_OK) {
144 HILOG_ERROR(LOG_CORE, "failed to create table user_properties, ret=%{public}d", ret);
145 return ret;
146 }
147 if (int ret = CustomEventParamDao::Create(rdbStore); ret != NativeRdb::E_OK) {
148 HILOG_ERROR(LOG_CORE, "failed to create table custom_event_params, ret=%{public}d", ret);
149 return ret;
150 }
151 return NativeRdb::E_OK;
152 }
153
OnUpgrade(NativeRdb::RdbStore & rdbStore,int oldVersion,int newVersion)154 int AppEventStoreCallback::OnUpgrade(NativeRdb::RdbStore& rdbStore, int oldVersion, int newVersion)
155 {
156 HILOG_DEBUG(LOG_CORE, "OnUpgrade, oldVersion=%{public}d, newVersion=%{public}d", oldVersion, newVersion);
157 for (int i = oldVersion; i < newVersion; ++i) {
158 switch (i) {
159 case 1: // upgrade db version from 1 to 2
160 if (int ret = UpToDbVersion2(rdbStore); ret != NativeRdb::E_OK) {
161 HILOG_ERROR(LOG_CORE, "failed to upgrade db version from 1 to 2, ret=%{public}d", ret);
162 return ret;
163 }
164 break;
165 case 2: // upgrade db version from 2 to 3
166 if (int ret = UpToDbVersion3(rdbStore); ret != NativeRdb::E_OK) {
167 HILOG_ERROR(LOG_CORE, "failed to upgrade db version from 2 to 3, ret=%{public}d", ret);
168 return ret;
169 }
170 break;
171 default:
172 break;
173 }
174 }
175 return NativeRdb::E_OK;
176 }
177
AppEventStore()178 AppEventStore::AppEventStore()
179 {
180 (void)InitDbStore();
181 }
182
~AppEventStore()183 AppEventStore::~AppEventStore()
184 {
185 dbStore_ = nullptr;
186 }
187
GetInstance()188 AppEventStore& AppEventStore::GetInstance()
189 {
190 static AppEventStore instance;
191 return instance;
192 }
193
InitDbStore()194 int AppEventStore::InitDbStore()
195 {
196 if (!InitDbStoreDir()) {
197 return DB_FAILED;
198 }
199
200 int ret = NativeRdb::E_OK;
201 NativeRdb::RdbStoreConfig config(dirPath_ + DATABASE_NAME);
202 config.SetSecurityLevel(NativeRdb::SecurityLevel::S1);
203 const int dbVersion = 3; // 3 means new db version
204 AppEventStoreCallback callback;
205 auto dbStore = NativeRdb::RdbHelper::GetRdbStore(config, dbVersion, callback, ret);
206 if (ret != NativeRdb::E_OK || dbStore == nullptr) {
207 HILOG_ERROR(LOG_CORE, "failed to create db store, ret=%{public}d", ret);
208 CheckAndRepairDbStore(ret);
209 return DB_FAILED;
210 }
211
212 dbStore_ = dbStore;
213 HILOG_INFO(LOG_CORE, "create db store successfully");
214 return DB_SUCC;
215 }
216
InitDbStoreDir()217 bool AppEventStore::InitDbStoreDir()
218 {
219 std::string dir = HiAppEventConfig::GetInstance().GetStorageDir();
220 if (dir.empty()) {
221 HILOG_ERROR(LOG_CORE, "failed to init db dir, path is empty");
222 return false;
223 }
224 dirPath_ = FileUtil::GetFilePathByDir(dir, DATABASE_DIR);
225 if (!FileUtil::IsFileExists(dirPath_) && !FileUtil::ForceCreateDirectory(dirPath_)) {
226 HILOG_ERROR(LOG_CORE, "failed to create database dir, errno=%{public}d", errno);
227 return false;
228 }
229 return true;
230 }
231
CheckAndRepairDbStore(int errCode)232 void AppEventStore::CheckAndRepairDbStore(int errCode)
233 {
234 if (errCode != NativeRdb::E_SQLITE_CORRUPT) {
235 return;
236 }
237 dbStore_ = nullptr;
238 if (int ret = NativeRdb::RdbHelper::DeleteRdbStore(dirPath_ + DATABASE_NAME); ret != NativeRdb::E_OK) {
239 HILOG_ERROR(LOG_CORE, "errCode=%{public}d failed to delete db file, ret=%{public}d", errCode, ret);
240 return;
241 }
242 HILOG_INFO(LOG_CORE, "errCode=%{public}d delete db file successfully", errCode);
243 return;
244 }
245
DestroyDbStore()246 int AppEventStore::DestroyDbStore()
247 {
248 std::lock_guard<std::mutex> lockGuard(dbMutex_);
249 if (dbStore_ == nullptr) {
250 return DB_SUCC;
251 }
252 dbStore_ = nullptr;
253 if (int ret = NativeRdb::RdbHelper::DeleteRdbStore(dirPath_ + DATABASE_NAME); ret != NativeRdb::E_OK) {
254 HILOG_ERROR(LOG_CORE, "failed to destroy db store, ret=%{public}d", ret);
255 return DB_FAILED;
256 }
257 HILOG_INFO(LOG_CORE, "destroy db store successfully");
258 return DB_SUCC;
259 }
260
InsertEvent(std::shared_ptr<AppEventPack> event)261 int64_t AppEventStore::InsertEvent(std::shared_ptr<AppEventPack> event)
262 {
263 std::lock_guard<std::mutex> lockGuard(dbMutex_);
264 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
265 return DB_FAILED;
266 }
267 int64_t seq = 0;
268 if (int ret = AppEventDao::Insert(dbStore_, event, seq); ret != NativeRdb::E_OK) {
269 CheckAndRepairDbStore(ret);
270 return DB_FAILED;
271 }
272 return seq;
273 }
274
InsertObserver(const Observer & observer)275 int64_t AppEventStore::InsertObserver(const Observer& observer)
276 {
277 std::lock_guard<std::mutex> lockGuard(dbMutex_);
278 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
279 return DB_FAILED;
280 }
281 int64_t seq = 0;
282 if (int ret = AppEventObserverDao::Insert(dbStore_, observer, seq); ret != NativeRdb::E_OK) {
283 CheckAndRepairDbStore(ret);
284 return DB_FAILED;
285 }
286 return seq;
287 }
288
InsertEventMapping(const std::vector<EventObserverInfo> & eventObservers)289 int AppEventStore::InsertEventMapping(const std::vector<EventObserverInfo>& eventObservers)
290 {
291 std::lock_guard<std::mutex> lockGuard(dbMutex_);
292 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
293 return DB_FAILED;
294 }
295 if (int ret = AppEventMappingDao::Insert(dbStore_, eventObservers); ret != NativeRdb::E_OK) {
296 CheckAndRepairDbStore(ret);
297 return DB_FAILED;
298 }
299 return DB_SUCC;
300 }
301
InsertUserId(const std::string & name,const std::string & value)302 int AppEventStore::InsertUserId(const std::string& name, const std::string& value)
303 {
304 std::lock_guard<std::mutex> lockGuard(dbMutex_);
305 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
306 return DB_FAILED;
307 }
308 if (int ret = UserIdDao::Insert(dbStore_, name, value); ret != NativeRdb::E_OK) {
309 CheckAndRepairDbStore(ret);
310 return DB_FAILED;
311 }
312 return DB_SUCC;
313 }
314
InsertUserProperty(const std::string & name,const std::string & value)315 int AppEventStore::InsertUserProperty(const std::string& name, const std::string& value)
316 {
317 std::lock_guard<std::mutex> lockGuard(dbMutex_);
318 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
319 return DB_FAILED;
320 }
321 if (int ret = UserPropertyDao::Insert(dbStore_, name, value); ret != NativeRdb::E_OK) {
322 CheckAndRepairDbStore(ret);
323 return DB_FAILED;
324 }
325 return DB_SUCC;
326 }
327
InsertCustomEventParams(std::shared_ptr<AppEventPack> event)328 int AppEventStore::InsertCustomEventParams(std::shared_ptr<AppEventPack> event)
329 {
330 std::vector<CustomEventParam> newParams;
331 event->GetCustomParams(newParams);
332 if (newParams.empty()) {
333 return DB_SUCC;
334 }
335 std::lock_guard<std::mutex> lockGuard(dbMutex_);
336 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
337 return DB_FAILED;
338 }
339
340 dbStore_->BeginTransaction();
341 std::unordered_set<std::string> oldParamkeys;
342 CustomEvent customEvent(event->GetRunningId(), event->GetDomain(), event->GetName());
343 CustomEventParamDao::QueryParamkeys(dbStore_, oldParamkeys, customEvent);
344 // check params num of same (runningid, domain, name)
345 size_t totalNum = oldParamkeys.size();
346 for (const auto& param : newParams) {
347 if (oldParamkeys.find(param.key) == oldParamkeys.end()) {
348 ++totalNum;
349 }
350 }
351 if (totalNum > MAX_NUM_OF_CUSTOM_PARAMS) {
352 dbStore_->RollBack();
353 return ErrorCode::ERROR_INVALID_CUSTOM_PARAM_NUM;
354 }
355 std::vector<CustomEventParam> insertParams;
356 std::vector<CustomEventParam> updateParams;
357 for (const auto& param : newParams) {
358 if (oldParamkeys.find(param.key) == oldParamkeys.end()) {
359 insertParams.emplace_back(param);
360 } else {
361 updateParams.emplace_back(param);
362 }
363 }
364 customEvent.params = insertParams;
365 if (int ret = CustomEventParamDao::BatchInsert(dbStore_, customEvent); ret != NativeRdb::E_OK) {
366 dbStore_->RollBack();
367 CheckAndRepairDbStore(ret);
368 return DB_FAILED;
369 }
370 customEvent.params = updateParams;
371 if (int ret = CustomEventParamDao::Updates(dbStore_, customEvent); ret != NativeRdb::E_OK) {
372 dbStore_->RollBack();
373 CheckAndRepairDbStore(ret);
374 return DB_FAILED;
375 }
376 dbStore_->Commit();
377 return DB_SUCC;
378 }
379
UpdateUserId(const std::string & name,const std::string & value)380 int AppEventStore::UpdateUserId(const std::string& name, const std::string& value)
381 {
382 std::lock_guard<std::mutex> lockGuard(dbMutex_);
383 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
384 return DB_FAILED;
385 }
386 if (int ret = UserIdDao::Update(dbStore_, name, value); ret != NativeRdb::E_OK) {
387 CheckAndRepairDbStore(ret);
388 return DB_FAILED;
389 }
390 return DB_SUCC;
391 }
392
UpdateUserProperty(const std::string & name,const std::string & value)393 int AppEventStore::UpdateUserProperty(const std::string& name, const std::string& value)
394 {
395 std::lock_guard<std::mutex> lockGuard(dbMutex_);
396 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
397 return DB_FAILED;
398 }
399 if (int ret = UserPropertyDao::Update(dbStore_, name, value); ret != NativeRdb::E_OK) {
400 CheckAndRepairDbStore(ret);
401 return DB_FAILED;
402 }
403 return DB_SUCC;
404 }
405
UpdateObserver(int64_t seq,const std::string & filters)406 int AppEventStore::UpdateObserver(int64_t seq, const std::string& filters)
407 {
408 std::lock_guard<std::mutex> lockGuard(dbMutex_);
409 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
410 return DB_FAILED;
411 }
412 if (int ret = AppEventObserverDao::Update(dbStore_, seq, filters); ret != NativeRdb::E_OK) {
413 CheckAndRepairDbStore(ret);
414 return DB_FAILED;
415 }
416 return DB_SUCC;
417 }
418
DeleteUserId(const std::string & name)419 int AppEventStore::DeleteUserId(const std::string& name)
420 {
421 std::lock_guard<std::mutex> lockGuard(dbMutex_);
422 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
423 return DB_FAILED;
424 }
425 if (int ret = UserIdDao::Delete(dbStore_, name); ret != NativeRdb::E_OK) {
426 CheckAndRepairDbStore(ret);
427 return DB_FAILED;
428 }
429 return DB_SUCC;
430 }
431
DeleteUserProperty(const std::string & name)432 int AppEventStore::DeleteUserProperty(const std::string& name)
433 {
434 std::lock_guard<std::mutex> lockGuard(dbMutex_);
435 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
436 return DB_FAILED;
437 }
438 if (int ret = UserPropertyDao::Delete(dbStore_, name); ret != NativeRdb::E_OK) {
439 CheckAndRepairDbStore(ret);
440 return DB_FAILED;
441 }
442 return DB_SUCC;
443 }
444
QueryUserIds(std::unordered_map<std::string,std::string> & out)445 int AppEventStore::QueryUserIds(std::unordered_map<std::string, std::string>& out)
446 {
447 std::lock_guard<std::mutex> lockGuard(dbMutex_);
448 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
449 return DB_FAILED;
450 }
451 if (int ret = UserIdDao::QueryAll(dbStore_, out); ret != NativeRdb::E_OK) {
452 CheckAndRepairDbStore(ret);
453 return DB_FAILED;
454 }
455 return DB_SUCC;
456 }
457
QueryUserId(const std::string & name,std::string & out)458 int AppEventStore::QueryUserId(const std::string& name, std::string& out)
459 {
460 std::lock_guard<std::mutex> lockGuard(dbMutex_);
461 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
462 return DB_FAILED;
463 }
464 if (int ret = UserIdDao::Query(dbStore_, name, out); ret != NativeRdb::E_OK) {
465 CheckAndRepairDbStore(ret);
466 return DB_FAILED;
467 }
468 return DB_SUCC;
469 }
470
QueryUserProperties(std::unordered_map<std::string,std::string> & out)471 int AppEventStore::QueryUserProperties(std::unordered_map<std::string, std::string>& out)
472 {
473 std::lock_guard<std::mutex> lockGuard(dbMutex_);
474 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
475 return DB_FAILED;
476 }
477 if (int ret = UserPropertyDao::QueryAll(dbStore_, out); ret != NativeRdb::E_OK) {
478 CheckAndRepairDbStore(ret);
479 return DB_FAILED;
480 }
481 return DB_SUCC;
482 }
483
QueryUserProperty(const std::string & name,std::string & out)484 int AppEventStore::QueryUserProperty(const std::string& name, std::string& out)
485 {
486 std::lock_guard<std::mutex> lockGuard(dbMutex_);
487 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
488 return DB_FAILED;
489 }
490 if (int ret = UserPropertyDao::Query(dbStore_, name, out); ret != NativeRdb::E_OK) {
491 CheckAndRepairDbStore(ret);
492 return DB_FAILED;
493 }
494 return DB_SUCC;
495 }
496
TakeEvents(std::vector<std::shared_ptr<AppEventPack>> & events,int64_t observerSeq,uint32_t size)497 int AppEventStore::TakeEvents(std::vector<std::shared_ptr<AppEventPack>>& events, int64_t observerSeq, uint32_t size)
498 {
499 // query the events of the observer
500 if (int ret = QueryEvents(events, observerSeq, size); ret != DB_SUCC) {
501 return ret;
502 }
503 if (events.empty()) {
504 return DB_SUCC;
505 }
506 // delete the events mapping of the observer
507 std::vector<int64_t> eventSeqs;
508 for (const auto &event : events) {
509 eventSeqs.emplace_back(event->GetSeq());
510 }
511 std::lock_guard<std::mutex> lockGuard(dbMutex_);
512 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
513 return DB_FAILED;
514 }
515 if (int ret = AppEventMappingDao::Delete(dbStore_, observerSeq, eventSeqs); ret != NativeRdb::E_OK) {
516 HILOG_WARN(LOG_CORE, "failed to delete the events mapping data ret=%{public}d, observer=%{public}" PRId64,
517 ret, observerSeq);
518 CheckAndRepairDbStore(ret);
519 return DB_FAILED;
520 }
521 return DB_SUCC;
522 }
523
QueryEvents(std::vector<std::shared_ptr<AppEventPack>> & events,int64_t observerSeq,uint32_t size)524 int AppEventStore::QueryEvents(std::vector<std::shared_ptr<AppEventPack>>& events, int64_t observerSeq, uint32_t size)
525 {
526 std::lock_guard<std::mutex> lockGuard(dbMutex_);
527 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
528 return DB_FAILED;
529 }
530
531 std::shared_ptr<NativeRdb::AbsSharedResultSet> resultSet = nullptr;
532 std::string sql = "SELECT " + Events::TABLE + ".* FROM " + AppEventMapping::TABLE + " INNER JOIN "
533 + Events::TABLE + " ON " + AppEventMapping::TABLE + "." + AppEventMapping::FIELD_EVENT_SEQ + "="
534 + Events::TABLE + "." + Events::FIELD_SEQ + " WHERE " + AppEventMapping::FIELD_OBSERVER_SEQ + "=?"
535 + " ORDER BY " + AppEventMapping::TABLE + "." + AppEventMapping::FIELD_EVENT_SEQ + " DESC ";
536 if (size > 0) {
537 sql += " LIMIT " + std::to_string(size);
538 }
539 resultSet = dbStore_->QuerySql(sql, std::vector<std::string>{std::to_string(observerSeq)});
540 if (resultSet == nullptr) {
541 HILOG_WARN(LOG_CORE, "result set is null, observer=%{public}" PRId64, observerSeq);
542 return DB_FAILED;
543 }
544 int ret = resultSet->GoToNextRow();
545 while (ret == NativeRdb::E_OK) {
546 auto event = GetEventFromResultSet(resultSet);
547 // query custom event params, and add to AppEventPack
548 std::unordered_map<std::string, std::string> params;
549 CustomEventParamDao::Query(dbStore_, params, CustomEvent(event->GetRunningId(), event->GetDomain(), ""));
550 CustomEventParamDao::Query(dbStore_, params,
551 CustomEvent(event->GetRunningId(), event->GetDomain(), event->GetName()));
552 event->AddCustomParams(params);
553 events.emplace_back(event);
554 ret = resultSet->GoToNextRow();
555 }
556 resultSet->Close();
557 if (ret == NativeRdb::E_SQLITE_CORRUPT) {
558 CheckAndRepairDbStore(ret);
559 return DB_FAILED;
560 }
561 return DB_SUCC;
562 }
563
QueryCustomParamsAdd2EventPack(std::shared_ptr<AppEventPack> event)564 int AppEventStore::QueryCustomParamsAdd2EventPack(std::shared_ptr<AppEventPack> event)
565 {
566 std::lock_guard<std::mutex> lockGuard(dbMutex_);
567 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
568 return DB_FAILED;
569 }
570 std::unordered_map<std::string, std::string> params;
571 CustomEventParamDao::Query(dbStore_, params, CustomEvent(event->GetRunningId(), event->GetDomain(), ""));
572 CustomEventParamDao::Query(dbStore_, params,
573 CustomEvent(event->GetRunningId(), event->GetDomain(), event->GetName()));
574 event->AddCustomParams(params);
575 return DB_SUCC;
576 }
577
QueryObserverSeq(const std::string & name,int64_t hashCode)578 int64_t AppEventStore::QueryObserverSeq(const std::string& name, int64_t hashCode)
579 {
580 std::string filters;
581 return QueryObserverSeqAndFilters(name, hashCode, filters);
582 }
583
QueryObserverSeqAndFilters(const std::string & name,int64_t hashCode,std::string & filters)584 int64_t AppEventStore::QueryObserverSeqAndFilters(const std::string& name, int64_t hashCode, std::string& filters)
585 {
586 std::lock_guard<std::mutex> lockGuard(dbMutex_);
587 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
588 return DB_FAILED;
589 }
590 int64_t seq = 0;
591 if (int ret = AppEventObserverDao::QuerySeqAndFilters(dbStore_, Observer(name, hashCode),
592 seq, filters); ret != NativeRdb::E_OK) {
593 CheckAndRepairDbStore(ret);
594 return DB_FAILED;
595 }
596 return seq;
597 }
598
QueryObserverSeqs(const std::string & name,std::vector<int64_t> & observerSeqs)599 int AppEventStore::QueryObserverSeqs(const std::string& name, std::vector<int64_t>& observerSeqs)
600 {
601 std::lock_guard<std::mutex> lockGuard(dbMutex_);
602 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
603 return DB_FAILED;
604 }
605 if (int ret = AppEventObserverDao::QuerySeqs(dbStore_, name, observerSeqs); ret != NativeRdb::E_OK) {
606 CheckAndRepairDbStore(ret);
607 return DB_FAILED;
608 }
609 return DB_SUCC;
610 }
611
QueryWatchers(std::vector<Observer> & observers)612 int AppEventStore::QueryWatchers(std::vector<Observer>& observers)
613 {
614 std::lock_guard<std::mutex> lockGuard(dbMutex_);
615 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
616 return DB_FAILED;
617 }
618 if (int ret = AppEventObserverDao::QueryWatchers(dbStore_, observers); ret != NativeRdb::E_OK) {
619 CheckAndRepairDbStore(ret);
620 return DB_FAILED;
621 }
622 return DB_SUCC;
623 }
624
DeleteObserver(int64_t observerSeq)625 int AppEventStore::DeleteObserver(int64_t observerSeq)
626 {
627 std::lock_guard<std::mutex> lockGuard(dbMutex_);
628 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
629 return DB_FAILED;
630 }
631 if (int ret = AppEventMappingDao::Delete(dbStore_, observerSeq, {}); ret != NativeRdb::E_OK) {
632 CheckAndRepairDbStore(ret);
633 return DB_FAILED;
634 }
635 if (int ret = AppEventObserverDao::Delete(dbStore_, observerSeq); ret != NativeRdb::E_OK) {
636 CheckAndRepairDbStore(ret);
637 return DB_FAILED;
638 }
639 return DB_SUCC;
640 }
641
DeleteEventMapping(int64_t observerSeq,const std::vector<int64_t> & eventSeqs)642 int AppEventStore::DeleteEventMapping(int64_t observerSeq, const std::vector<int64_t>& eventSeqs)
643 {
644 std::lock_guard<std::mutex> lockGuard(dbMutex_);
645 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
646 return DB_FAILED;
647 }
648 if (int ret = AppEventMappingDao::Delete(dbStore_, observerSeq, eventSeqs); ret != NativeRdb::E_OK) {
649 CheckAndRepairDbStore(ret);
650 return DB_FAILED;
651 }
652 return DB_SUCC;
653 }
654
DeleteEvent(int64_t eventSeq)655 int AppEventStore::DeleteEvent(int64_t eventSeq)
656 {
657 std::lock_guard<std::mutex> lockGuard(dbMutex_);
658 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
659 return DB_FAILED;
660 }
661 if (int ret = AppEventDao::Delete(dbStore_, eventSeq); ret != NativeRdb::E_OK) {
662 CheckAndRepairDbStore(ret);
663 return DB_FAILED;
664 }
665 return DB_SUCC;
666 }
667
DeleteCustomEventParams()668 int AppEventStore::DeleteCustomEventParams()
669 {
670 std::lock_guard<std::mutex> lockGuard(dbMutex_);
671 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
672 return DB_FAILED;
673 }
674 if (int ret = CustomEventParamDao::Delete(dbStore_); ret != NativeRdb::E_OK) {
675 CheckAndRepairDbStore(ret);
676 return DB_FAILED;
677 }
678 return DB_SUCC;
679 }
680
DeleteEvent(const std::vector<int64_t> & eventSeqs)681 int AppEventStore::DeleteEvent(const std::vector<int64_t>& eventSeqs)
682 {
683 if (eventSeqs.empty()) {
684 return DB_SUCC;
685 }
686 std::lock_guard<std::mutex> lockGuard(dbMutex_);
687 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
688 return DB_FAILED;
689 }
690 std::unordered_set<int64_t> existEventSeqs;
691 // query seqs in event_observer_mapping
692 if (int ret = AppEventMappingDao::QueryExistEvent(dbStore_, eventSeqs, existEventSeqs); ret != NativeRdb::E_OK) {
693 CheckAndRepairDbStore(ret);
694 return DB_FAILED;
695 }
696 // delete events if seqs not in event_observer_mapping
697 std::vector<int64_t> delEventSeqs;
698 for (const auto& seq : eventSeqs) {
699 if (existEventSeqs.find(seq) == existEventSeqs.end()) {
700 delEventSeqs.emplace_back(seq);
701 }
702 }
703 if (int ret = AppEventDao::Delete(dbStore_, delEventSeqs); ret != NativeRdb::E_OK) {
704 CheckAndRepairDbStore(ret);
705 return DB_FAILED;
706 }
707 return DB_SUCC;
708 }
709
DeleteUnusedParamsExceptCurId(const std::string & curRunningId)710 int AppEventStore::DeleteUnusedParamsExceptCurId(const std::string& curRunningId)
711 {
712 if (curRunningId.empty()) {
713 return DB_SUCC;
714 }
715 std::lock_guard<std::mutex> lockGuard(dbMutex_);
716 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
717 return DB_FAILED;
718 }
719 int deleteRows = 0;
720 // delete custom_event_params if running_id not in events, and running_id isn't current runningId
721 std::string whereClause = "(" + CustomEventParams::TABLE + "." + CustomEventParams::FIELD_RUNNING_ID
722 + " NOT IN (SELECT " + Events::FIELD_RUNNING_ID + " FROM " + Events::TABLE + ")) AND "
723 + CustomEventParams::FIELD_RUNNING_ID + " != ?";
724 if (int ret = dbStore_->Delete(deleteRows, CustomEventParams::TABLE, whereClause,
725 std::vector<std::string>{curRunningId}); ret != NativeRdb::E_OK) {
726 CheckAndRepairDbStore(ret);
727 return DB_FAILED;
728 }
729 HILOG_INFO(LOG_CORE, "delete %{public}d params unused", deleteRows);
730 return DB_SUCC;
731 }
732
DeleteUnusedEventMapping()733 int AppEventStore::DeleteUnusedEventMapping()
734 {
735 std::lock_guard<std::mutex> lockGuard(dbMutex_);
736 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
737 return DB_FAILED;
738 }
739 int deleteRows = 0;
740 // delete event_observer_mapping if event_seq not in events
741 std::string whereClause = AppEventMapping::TABLE + "." + AppEventMapping::FIELD_EVENT_SEQ + " NOT IN (SELECT "
742 + Events::FIELD_SEQ + " FROM " + Events::TABLE + ")";
743 if (int ret = dbStore_->Delete(deleteRows, AppEventMapping::TABLE, whereClause); ret != NativeRdb::E_OK) {
744 CheckAndRepairDbStore(ret);
745 return DB_FAILED;
746 }
747 HILOG_INFO(LOG_CORE, "delete %{public}d event map unused", deleteRows);
748 return DB_SUCC;
749 }
750
DeleteHistoryEvent(int reservedNum,int reservedNumOs)751 int AppEventStore::DeleteHistoryEvent(int reservedNum, int reservedNumOs)
752 {
753 std::lock_guard<std::mutex> lockGuard(dbMutex_);
754 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
755 return DB_FAILED;
756 }
757 int deleteRows = 0;
758 std::vector<std::string> whereArgs = {
759 DOMAIN_OS, std::to_string(reservedNum), DOMAIN_OS, std::to_string(reservedNumOs)
760 };
761 // delete history events, keep the latest reservedNum events, and keep the latest reservedNumOs events of OS domain
762 std::string whereClause
763 = Events::FIELD_SEQ + " NOT IN (SELECT " + Events::FIELD_SEQ + " FROM " + Events::TABLE
764 + " WHERE " + Events::FIELD_DOMAIN + " != ? ORDER BY "+ Events::FIELD_SEQ + " DESC LIMIT 0,?) AND "
765 + Events::FIELD_SEQ + " NOT IN (SELECT " + Events::FIELD_SEQ + " FROM " + Events::TABLE
766 + " WHERE " + Events::FIELD_DOMAIN + " = ? ORDER BY " + Events::FIELD_SEQ + " DESC LIMIT 0,?)";
767 if (int ret = dbStore_->Delete(deleteRows, Events::TABLE, whereClause, whereArgs); ret != NativeRdb::E_OK) {
768 CheckAndRepairDbStore(ret);
769 return DB_FAILED;
770 }
771 HILOG_INFO(LOG_CORE, "delete %{public}d events over limit", deleteRows);
772 return DB_SUCC;
773 }
774
DeleteData(int64_t observerSeq,const std::vector<int64_t> & eventSeqs)775 bool AppEventStore::DeleteData(int64_t observerSeq, const std::vector<int64_t>& eventSeqs)
776 {
777 if (DeleteEventMapping(observerSeq, eventSeqs) < 0) {
778 return false;
779 }
780 if (DeleteEvent(eventSeqs) < 0) {
781 HILOG_WARN(LOG_CORE, "failed to delete unused event");
782 }
783 std::string runningId = HiAppEventConfig::GetInstance().GetRunningId();
784 if (!runningId.empty() && DeleteUnusedParamsExceptCurId(runningId) < 0) {
785 HILOG_WARN(LOG_CORE, "failed to delete unused params");
786 }
787 return true;
788 }
789 } // namespace HiviewDFX
790 } // namespace OHOS
791