1 /*
2 * Copyright (c) 2022-2024 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 void 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 if (int ret = rdbStore.ExecuteSql(sql); ret != NativeRdb::E_OK) {
114 HILOG_ERROR(LOG_CORE, "failed to upgrade db version from 1 to 2, ret=%{public}d", ret);
115 }
116 }
117 }
118
OnCreate(NativeRdb::RdbStore & rdbStore)119 int AppEventStoreCallback::OnCreate(NativeRdb::RdbStore& rdbStore)
120 {
121 HILOG_DEBUG(LOG_CORE, "OnCreate start to create db");
122 return NativeRdb::E_OK;
123 }
124
OnUpgrade(NativeRdb::RdbStore & rdbStore,int oldVersion,int newVersion)125 int AppEventStoreCallback::OnUpgrade(NativeRdb::RdbStore& rdbStore, int oldVersion, int newVersion)
126 {
127 HILOG_DEBUG(LOG_CORE, "OnUpgrade, oldVersion=%{public}d, newVersion=%{public}d", oldVersion, newVersion);
128 for (int i = oldVersion; i < newVersion; ++i) {
129 if (i == 1) { // upgrade db version from 1 to 2
130 UpToDbVersion2(rdbStore);
131 }
132 }
133 return NativeRdb::E_OK;
134 }
135
AppEventStore()136 AppEventStore::AppEventStore()
137 {
138 (void)InitDbStore();
139 }
140
~AppEventStore()141 AppEventStore::~AppEventStore()
142 {
143 dbStore_ = nullptr;
144 }
145
GetInstance()146 AppEventStore& AppEventStore::GetInstance()
147 {
148 static AppEventStore instance;
149 return instance;
150 }
151
InitDbStore()152 int AppEventStore::InitDbStore()
153 {
154 if (!InitDbStoreDir()) {
155 return DB_FAILED;
156 }
157
158 int ret = NativeRdb::E_OK;
159 NativeRdb::RdbStoreConfig config(dirPath_ + DATABASE_NAME);
160 config.SetSecurityLevel(NativeRdb::SecurityLevel::S1);
161 const int dbVersion = 2; // 2 means new db version
162 AppEventStoreCallback callback;
163 auto dbStore = NativeRdb::RdbHelper::GetRdbStore(config, dbVersion, callback, ret);
164 if (ret != NativeRdb::E_OK || dbStore == nullptr) {
165 HILOG_ERROR(LOG_CORE, "failed to create db store, ret=%{public}d", ret);
166 return DB_FAILED;
167 }
168
169 dbStore_ = dbStore;
170 appEventDao_ = std::make_shared<AppEventDao>(dbStore_);
171 appEventObserverDao_ = std::make_shared<AppEventObserverDao>(dbStore_);
172 appEventMappingDao_ = std::make_shared<AppEventMappingDao>(dbStore_);
173 userIdDao_ = std::make_shared<UserIdDao>(dbStore_);
174 userPropertyDao_ = std::make_shared<UserPropertyDao>(dbStore_);
175 customEventParamDao_ = std::make_shared<CustomEventParamDao>(dbStore_);
176 HILOG_INFO(LOG_CORE, "create db store successfully");
177 return DB_SUCC;
178 }
179
InitDbStoreDir()180 bool AppEventStore::InitDbStoreDir()
181 {
182 std::string dir = HiAppEventConfig::GetInstance().GetStorageDir();
183 if (dir.empty()) {
184 HILOG_ERROR(LOG_CORE, "failed to init db dir, path is empty");
185 return false;
186 }
187 dirPath_ = FileUtil::GetFilePathByDir(dir, DATABASE_DIR);
188 if (!FileUtil::IsFileExists(dirPath_) && !FileUtil::ForceCreateDirectory(dirPath_)) {
189 HILOG_ERROR(LOG_CORE, "failed to create database dir, errno=%{public}d", errno);
190 return false;
191 }
192 return true;
193 }
194
DestroyDbStore()195 int AppEventStore::DestroyDbStore()
196 {
197 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
198 if (dbStore_ == nullptr) {
199 return DB_SUCC;
200 }
201 dbStore_ = nullptr;
202 if (int ret = NativeRdb::RdbHelper::DeleteRdbStore(dirPath_ + DATABASE_NAME); ret != NativeRdb::E_OK) {
203 HILOG_ERROR(LOG_CORE, "failed to destroy db store, ret=%{public}d", ret);
204 return DB_FAILED;
205 }
206 HILOG_INFO(LOG_CORE, "destroy db store successfully");
207 return DB_SUCC;
208 }
209
InsertEvent(std::shared_ptr<AppEventPack> event)210 int64_t AppEventStore::InsertEvent(std::shared_ptr<AppEventPack> event)
211 {
212 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
213 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
214 return DB_FAILED;
215 }
216 return appEventDao_->Insert(event);
217 }
218
InsertObserver(const std::string & observer,int64_t hashCode)219 int64_t AppEventStore::InsertObserver(const std::string& observer, int64_t hashCode)
220 {
221 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
222 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
223 return DB_FAILED;
224 }
225 return appEventObserverDao_->Insert(observer, hashCode);
226 }
227
InsertEventMapping(int64_t eventSeq,int64_t observerSeq)228 int64_t AppEventStore::InsertEventMapping(int64_t eventSeq, int64_t observerSeq)
229 {
230 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
231 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
232 return DB_FAILED;
233 }
234 return appEventMappingDao_->Insert(eventSeq, observerSeq);
235 }
236
InsertUserId(const std::string & name,const std::string & value)237 int64_t AppEventStore::InsertUserId(const std::string& name, const std::string& value)
238 {
239 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
240 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
241 return DB_FAILED;
242 }
243 return userIdDao_->Insert(name, value);
244 }
245
InsertUserProperty(const std::string & name,const std::string & value)246 int64_t AppEventStore::InsertUserProperty(const std::string& name, const std::string& value)
247 {
248 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
249 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
250 return DB_FAILED;
251 }
252 return userPropertyDao_->Insert(name, value);
253 }
254
InsertCustomEventParams(std::shared_ptr<AppEventPack> event)255 int64_t AppEventStore::InsertCustomEventParams(std::shared_ptr<AppEventPack> event)
256 {
257 std::vector<CustomEventParam> newParams;
258 event->GetCustomParams(newParams);
259 if (newParams.empty()) {
260 return DB_SUCC;
261 }
262 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
263 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
264 return DB_FAILED;
265 }
266
267 dbStore_->BeginTransaction();
268 std::unordered_set<std::string> oldParamkeys;
269 customEventParamDao_->QueryParamkeys(oldParamkeys, event->GetRunningId(), event->GetDomain(), event->GetName());
270 // check params num of same (runningid, domain, name)
271 size_t totalNum = oldParamkeys.size();
272 for (const auto& param : newParams) {
273 if (oldParamkeys.find(param.key) == oldParamkeys.end()) {
274 ++totalNum;
275 }
276 }
277 if (totalNum > MAX_NUM_OF_CUSTOM_PARAMS) {
278 dbStore_->RollBack();
279 return ErrorCode::ERROR_INVALID_CUSTOM_PARAM_NUM;
280 }
281 std::vector<NativeRdb::ValuesBucket> buckets;
282 for (const auto& param : newParams) {
283 if (oldParamkeys.find(param.key) == oldParamkeys.end()) {
284 if (customEventParamDao_->Insert(param, event->GetRunningId(), event->GetDomain(), event->GetName())
285 == DB_FAILED) {
286 dbStore_->RollBack();
287 return DB_FAILED;
288 }
289 } else {
290 if (customEventParamDao_->Update(param, event->GetRunningId(), event->GetDomain(), event->GetName())
291 == DB_FAILED) {
292 dbStore_->RollBack();
293 return DB_FAILED;
294 }
295 }
296 }
297 dbStore_->Commit();
298 return DB_SUCC;
299 }
300
UpdateUserId(const std::string & name,const std::string & value)301 int64_t AppEventStore::UpdateUserId(const std::string& name, const std::string& value)
302 {
303 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
304 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
305 return DB_FAILED;
306 }
307 return userIdDao_->Update(name, value);
308 }
309
UpdateUserProperty(const std::string & name,const std::string & value)310 int64_t AppEventStore::UpdateUserProperty(const std::string& name, const std::string& value)
311 {
312 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
313 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
314 return DB_FAILED;
315 }
316 return userPropertyDao_->Update(name, value);
317 }
318
DeleteUserId(const std::string & name)319 int AppEventStore::DeleteUserId(const std::string& name)
320 {
321 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
322 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
323 return DB_FAILED;
324 }
325 return userIdDao_->Delete(name);
326 }
327
DeleteUserProperty(const std::string & name)328 int AppEventStore::DeleteUserProperty(const std::string& name)
329 {
330 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
331 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
332 return DB_FAILED;
333 }
334 return userPropertyDao_->Delete(name);
335 }
336
QueryUserIds(std::unordered_map<std::string,std::string> & out)337 int AppEventStore::QueryUserIds(std::unordered_map<std::string, std::string>& out)
338 {
339 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
340 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
341 return DB_FAILED;
342 }
343 return userIdDao_->QueryAll(out);
344 }
345
QueryUserId(const std::string & name,std::string & out)346 int AppEventStore::QueryUserId(const std::string& name, std::string& out)
347 {
348 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
349 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
350 return DB_FAILED;
351 }
352 return userIdDao_->Query(name, out);
353 }
354
QueryUserProperties(std::unordered_map<std::string,std::string> & out)355 int AppEventStore::QueryUserProperties(std::unordered_map<std::string, std::string>& out)
356 {
357 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
358 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
359 return DB_FAILED;
360 }
361 return userPropertyDao_->QueryAll(out);
362 }
363
QueryUserProperty(const std::string & name,std::string & out)364 int AppEventStore::QueryUserProperty(const std::string& name, std::string& out)
365 {
366 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
367 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
368 return DB_FAILED;
369 }
370 return userPropertyDao_->Query(name, out);
371 }
372
TakeEvents(std::vector<std::shared_ptr<AppEventPack>> & events,int64_t observerSeq,uint32_t size)373 int AppEventStore::TakeEvents(std::vector<std::shared_ptr<AppEventPack>>& events, int64_t observerSeq, uint32_t size)
374 {
375 // query the events of the observer
376 if (int ret = QueryEvents(events, observerSeq, size); ret != DB_SUCC) {
377 return ret;
378 }
379 if (events.empty()) {
380 return DB_SUCC;
381 }
382 // delete the events mapping of the observer
383 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
384 std::vector<int64_t> eventSeqs;
385 for (const auto &event : events) {
386 eventSeqs.emplace_back(event->GetSeq());
387 }
388 if (appEventMappingDao_->Delete(observerSeq, eventSeqs) < 0) {
389 HILOG_WARN(LOG_CORE, "failed to delete the events mapping data, observer=%{public}" PRId64, observerSeq);
390 return DB_FAILED;
391 }
392 return DB_SUCC;
393 }
394
QueryEvents(std::vector<std::shared_ptr<AppEventPack>> & events,int64_t observerSeq,uint32_t size)395 int AppEventStore::QueryEvents(std::vector<std::shared_ptr<AppEventPack>>& events, int64_t observerSeq, uint32_t size)
396 {
397 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
398 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
399 return DB_FAILED;
400 }
401
402 std::shared_ptr<NativeRdb::AbsSharedResultSet> resultSet = nullptr;
403 std::string sql = "SELECT " + Events::TABLE + ".* FROM " + AppEventMapping::TABLE + " INNER JOIN "
404 + Events::TABLE + " ON " + AppEventMapping::TABLE + "." + AppEventMapping::FIELD_EVENT_SEQ + "="
405 + Events::TABLE + "." + Events::FIELD_SEQ + " WHERE " + AppEventMapping::FIELD_OBSERVER_SEQ + "=?"
406 + " ORDER BY " + AppEventMapping::TABLE + "." + AppEventMapping::FIELD_EVENT_SEQ + " DESC ";
407 if (size > 0) {
408 sql += " LIMIT " + std::to_string(size);
409 }
410 resultSet = dbStore_->QuerySql(sql, std::vector<std::string>{std::to_string(observerSeq)});
411 if (resultSet == nullptr) {
412 HILOG_WARN(LOG_CORE, "result set is null, observer=%{public}" PRId64, observerSeq);
413 return DB_FAILED;
414 }
415 while (resultSet->GoToNextRow() == NativeRdb::E_OK) {
416 auto event = GetEventFromResultSet(resultSet);
417 // query custom event params, and add to AppEventPack
418 std::unordered_map<std::string, std::string> params;
419 customEventParamDao_->Query(params, event->GetRunningId(), event->GetDomain());
420 customEventParamDao_->Query(params, event->GetRunningId(), event->GetDomain(), event->GetName());
421 event->AddCustomParams(params);
422 events.emplace_back(event);
423 }
424 resultSet->Close();
425 return DB_SUCC;
426 }
427
QueryCustomParamsAdd2EventPack(std::shared_ptr<AppEventPack> event)428 int AppEventStore::QueryCustomParamsAdd2EventPack(std::shared_ptr<AppEventPack> event)
429 {
430 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
431 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
432 return DB_FAILED;
433 }
434 std::unordered_map<std::string, std::string> params;
435 customEventParamDao_->Query(params, event->GetRunningId(), event->GetDomain());
436 customEventParamDao_->Query(params, event->GetRunningId(), event->GetDomain(), event->GetName());
437 event->AddCustomParams(params);
438 return DB_SUCC;
439 }
440
QueryObserverSeq(const std::string & observer,int64_t hashCode)441 int64_t AppEventStore::QueryObserverSeq(const std::string& observer, int64_t hashCode)
442 {
443 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
444 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
445 return DB_FAILED;
446 }
447 return appEventObserverDao_->QuerySeq(observer, hashCode);
448 }
449
QueryObserverSeqs(const std::string & observer,std::vector<int64_t> & observerSeqs)450 int AppEventStore::QueryObserverSeqs(const std::string& observer, std::vector<int64_t>& observerSeqs)
451 {
452 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
453 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
454 return DB_FAILED;
455 }
456 return appEventObserverDao_->QuerySeqs(observer, observerSeqs);
457 }
458
DeleteObserver(int64_t observerSeq)459 int AppEventStore::DeleteObserver(int64_t observerSeq)
460 {
461 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
462 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
463 return DB_FAILED;
464 }
465 if (int ret = appEventMappingDao_->Delete(observerSeq, {}); ret < 0) {
466 return ret;
467 }
468 return appEventObserverDao_->Delete(observerSeq);
469 }
470
DeleteEventMapping(int64_t observerSeq,const std::vector<int64_t> & eventSeqs)471 int AppEventStore::DeleteEventMapping(int64_t observerSeq, const std::vector<int64_t>& eventSeqs)
472 {
473 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
474 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
475 return DB_FAILED;
476 }
477 return appEventMappingDao_->Delete(observerSeq, eventSeqs);
478 }
479
DeleteEvent(int64_t eventSeq)480 int AppEventStore::DeleteEvent(int64_t eventSeq)
481 {
482 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
483 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
484 return DB_FAILED;
485 }
486 return appEventDao_->Delete(eventSeq);
487 }
488
DeleteCustomEventParams()489 int AppEventStore::DeleteCustomEventParams()
490 {
491 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
492 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
493 return DB_FAILED;
494 }
495 return customEventParamDao_->Delete();
496 }
497
DeleteEvent(const std::vector<int64_t> & eventSeqs)498 int AppEventStore::DeleteEvent(const std::vector<int64_t>& eventSeqs)
499 {
500 if (eventSeqs.empty()) {
501 return DB_SUCC;
502 }
503 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
504 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
505 return DB_FAILED;
506 }
507 std::unordered_set<int64_t> existEventSeqs;
508 // query seqs in event_observer_mapping
509 if (appEventMappingDao_->QueryExistEvent(eventSeqs, existEventSeqs) == DB_FAILED) {
510 return DB_FAILED;
511 }
512 // delete events if seqs not in event_observer_mapping
513 if (existEventSeqs.empty()) {
514 return appEventDao_->Delete(eventSeqs);
515 }
516 std::vector<int64_t> delEventSeqs;
517 for (const auto& seq : eventSeqs) {
518 if (existEventSeqs.find(seq) == existEventSeqs.end()) {
519 delEventSeqs.emplace_back(seq);
520 }
521 }
522 return appEventDao_->Delete(delEventSeqs);
523 }
524
DeleteUnusedParamsExceptCurId(const std::string & curRunningId)525 int AppEventStore::DeleteUnusedParamsExceptCurId(const std::string& curRunningId)
526 {
527 if (curRunningId.empty()) {
528 return DB_SUCC;
529 }
530 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
531 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
532 return DB_FAILED;
533 }
534 int deleteRows = 0;
535 // delete custom_event_params if running_id not in events, and running_id isn't current runningId
536 std::string whereClause = "(" + CustomEventParams::TABLE + "." + CustomEventParams::FIELD_RUNNING_ID
537 + " NOT IN (SELECT " + Events::FIELD_RUNNING_ID + " FROM " + Events::TABLE + ")) AND "
538 + CustomEventParams::FIELD_RUNNING_ID + " != ?";
539 if (dbStore_->Delete(deleteRows, CustomEventParams::TABLE, whereClause, std::vector<std::string>{curRunningId})
540 != NativeRdb::E_OK) {
541 return DB_FAILED;
542 }
543 HILOG_INFO(LOG_CORE, "delete %{public}d params unused", deleteRows);
544 return deleteRows;
545 }
546
DeleteUnusedEventMapping()547 int AppEventStore::DeleteUnusedEventMapping()
548 {
549 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
550 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
551 return DB_FAILED;
552 }
553 int deleteRows = 0;
554 // delete event_observer_mapping if event_seq not in events
555 std::string whereClause = AppEventMapping::TABLE + "." + AppEventMapping::FIELD_EVENT_SEQ + " NOT IN (SELECT "
556 + Events::FIELD_SEQ + " FROM " + Events::TABLE + ")";
557 if (dbStore_->Delete(deleteRows, AppEventMapping::TABLE, whereClause) != NativeRdb::E_OK) {
558 return DB_FAILED;
559 }
560 HILOG_INFO(LOG_CORE, "delete %{public}d event map unused", deleteRows);
561 return deleteRows;
562 }
563
DeleteHistoryEvent(int reservedNum,int reservedNumOs)564 int AppEventStore::DeleteHistoryEvent(int reservedNum, int reservedNumOs)
565 {
566 std::lock_guard<ffrt::mutex> lockGuard(dbMutex_);
567 if (dbStore_ == nullptr && InitDbStore() != DB_SUCC) {
568 return DB_FAILED;
569 }
570 int deleteRows = 0;
571 std::vector<std::string> whereArgs = {
572 DOMAIN_OS, std::to_string(reservedNum), DOMAIN_OS, std::to_string(reservedNumOs)
573 };
574 // delete history events, keep the latest reservedNum events, and keep the latest reservedNumOs events of OS domain
575 std::string whereClause
576 = Events::FIELD_SEQ + " NOT IN (SELECT " + Events::FIELD_SEQ + " FROM " + Events::TABLE
577 + " WHERE " + Events::FIELD_DOMAIN + " != ? ORDER BY "+ Events::FIELD_SEQ + " DESC LIMIT 0,?) AND "
578 + Events::FIELD_SEQ + " NOT IN (SELECT " + Events::FIELD_SEQ + " FROM " + Events::TABLE
579 + " WHERE " + Events::FIELD_DOMAIN + " = ? ORDER BY " + Events::FIELD_SEQ + " DESC LIMIT 0,?)";
580 if (dbStore_->Delete(deleteRows, Events::TABLE, whereClause, whereArgs) != NativeRdb::E_OK) {
581 return DB_FAILED;
582 }
583 HILOG_INFO(LOG_CORE, "delete %{public}d events over limit", deleteRows);
584 return deleteRows;
585 }
586
DeleteData(int64_t observerSeq,const std::vector<int64_t> & eventSeqs)587 bool AppEventStore::DeleteData(int64_t observerSeq, const std::vector<int64_t>& eventSeqs)
588 {
589 if (DeleteEventMapping(observerSeq, eventSeqs) < 0) {
590 return false;
591 }
592 if (DeleteEvent(eventSeqs) < 0) {
593 HILOG_WARN(LOG_CORE, "failed to delete unused event");
594 }
595 std::string runningId = HiAppEventConfig::GetInstance().GetRunningId();
596 if (!runningId.empty() && DeleteUnusedParamsExceptCurId(runningId) < 0) {
597 HILOG_WARN(LOG_CORE, "failed to delete unused params");
598 }
599 return true;
600 }
601 } // namespace HiviewDFX
602 } // namespace OHOS
603