Fix sign-compare
[platform/core/multimedia/libmedia-service.git] / plugin / media-ebook-plugin-dbinserter.cpp
1 /*
2  * libmedia-service
3  *
4  * Copyright (c) 2022 Samsung Electronics Co., Ltd. All rights reserved.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  */
19
20 #include <dlog.h>
21 #include <regex>
22 #include <sqlite3.h>
23 #include "media-ebook-plugin-dbinserter.h"
24
25 #ifdef LOG_TAG
26 #undef LOG_TAG
27 #endif
28
29 #define LOG_TAG "MEDIA_SERVICE"
30
31 #define INSERT_QUERY "INSERT INTO words(file_id, word) SELECT id, ? FROM files WHERE path=? ON CONFLICT (file_id, word) DO UPDATE SET frequency=frequency+1;"
32 #define TOKEN_KEY "\\s+"
33 #define SPECIAL_CHAR "[\\{\\}\\[\\]\\/?.,;:|\\)*~`!^\\-_+<>@\\#$%&\\\\=\\(\\\'\\\"]"
34
35 bool DbInserter::run(const std::string& text)
36 {
37         if (!dbHandle || filePath.empty() || text.empty())
38                 return false;
39
40         auto sqlite_handle = static_cast<sqlite3 *>(const_cast<void *>(dbHandle));
41
42         const std::regex sp(SPECIAL_CHAR);
43         std::string _text = std::regex_replace(text, sp, "");
44         const std::regex re(TOKEN_KEY);
45         auto words_begin = std::sregex_token_iterator(_text.begin(), _text.end(), re, -1);
46         auto words_end = std::sregex_token_iterator();
47
48         bool isTransaction = (sqlite3_exec(sqlite_handle, "BEGIN;", NULL, NULL, NULL) == SQLITE_OK);
49
50         sqlite3_stmt *stmt = NULL;
51         sqlite3_prepare_v2(sqlite_handle, INSERT_QUERY, -1, &stmt, NULL);
52
53         for (auto i = words_begin; i != words_end; ++i) {
54                 sqlite3_bind_text(stmt, 1, (*i).str().c_str(), -1, SQLITE_TRANSIENT);
55                 sqlite3_bind_text(stmt, 2, filePath.c_str(), -1, SQLITE_TRANSIENT);
56                 sqlite3_step(stmt);
57                 sqlite3_reset(stmt);
58         }
59
60         sqlite3_finalize(stmt);
61
62         if (isTransaction)
63                 sqlite3_exec(sqlite_handle, "COMMIT;", NULL, NULL, NULL);
64
65         return true;
66 }