Refactor alarm-manager 98/286598/7
authorjh9216.park <jh9216.park@samsung.com>
Tue, 10 Jan 2023 10:03:57 +0000 (05:03 -0500)
committerjh9216.park <jh9216.park@samsung.com>
Wed, 18 Jan 2023 04:25:50 +0000 (23:25 -0500)
- Use tizen_base::Database

Change-Id: I9b66c9f328287c3123cd1888fcf662ebde2bdb04
Signed-off-by: jh9216.park <jh9216.park@samsung.com>
12 files changed:
mock/tzplatform_config_mock.cc [new file with mode: 0644]
mock/tzplatform_config_mock.h [new file with mode: 0644]
packaging/alarm-manager.spec
server/CMakeLists.txt
server/alarm-manager-db-migration.c [deleted file]
server/alarm-manager-db.c [deleted file]
server/alarm-manager-db.cc [new file with mode: 0644]
server/alarm-manager-db.h
server/alarm-manager.c
unittest/CMakeLists.txt
unittest/alarm_manager_unittest.cpp
unittest/unittest.cpp

diff --git a/mock/tzplatform_config_mock.cc b/mock/tzplatform_config_mock.cc
new file mode 100644 (file)
index 0000000..7decf73
--- /dev/null
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2023 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "tzplatform_config_mock.h"
+
+#include "mock_hook.h"
+#include "test_fixture.h"
+
+extern "C" const char* tzplatform_mkpath(enum tzplatform_variable arg1, const char* arg2) {
+  return MOCK_HOOK_P2(TzplatformConfigMock, tzplatform_mkpath, arg1, arg2);
+}
\ No newline at end of file
diff --git a/mock/tzplatform_config_mock.h b/mock/tzplatform_config_mock.h
new file mode 100644 (file)
index 0000000..e0bc14e
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2023 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef UNIT_TESTS_MOCK_TZPLATFORM_CONFIG_MOCK_H_
+#define UNIT_TESTS_MOCK_TZPLATFORM_CONFIG_MOCK_H_
+
+#include <tzplatform_config.h>
+#include <gmock/gmock.h>
+
+#include "module_mock.h"
+
+class TzplatformConfigMock : public virtual ModuleMock {
+ public:
+  TzplatformConfigMock() {
+    using ::testing::_;
+    using ::testing::Return;
+    using ::testing::Invoke;
+  }
+
+  MOCK_METHOD2(tzplatform_mkpath, const char* (enum tzplatform_variable,
+      const char*));
+};
+
+#endif  // UNIT_TESTS_MOCK_TZPLATFORM_CONFIG_MOCK_H_
\ No newline at end of file
index f2f71a99147f41ae1e1c714280a55b07accbba21..631127a9ed13709bdf0ddd98d3fe9148f63250b3 100644 (file)
@@ -39,6 +39,7 @@ BuildRequires: pkgconfig(cynara-client)
 BuildRequires: pkgconfig(cynara-session)
 BuildRequires: pkgconfig(cynara-creds-gdbus)
 BuildRequires: pkgconfig(gmock)
+BuildRequires: pkgconfig(tizen-database)
 
 %if 0%{?gcov:1}
 BuildRequires:  lcov
index e07675aa2162c7e2f0bc8c9b7ced06c39d3017f3..30a3af4553d6b5bcc6ae6662c7794f766ccf4489 100755 (executable)
@@ -9,7 +9,7 @@ ADD_DEFINITIONS("-DPLUGIN_LIB_DIR=\"${LIB_INSTALL_DIR}\"")
 PKG_CHECK_MODULES(svr_pkgs REQUIRED glib-2.0 dlog aul bundle appsvc pkgmgr-info pkgmgr vconf
                gio-2.0 gio-unix-2.0 capi-system-device libtzplatform-config libsystemd
                eventsystem notification sqlite3 cert-svc-vcore
-               cynara-session cynara-client cynara-creds-gdbus)
+               cynara-session cynara-client cynara-creds-gdbus tizen-database)
 
 FOREACH(flag ${svr_pkgs_CFLAGS_OTHER})
        IF(${flag} MATCHES "\\-D+")
@@ -20,7 +20,10 @@ ENDFOREACH(flag)
 INCLUDE_DIRECTORIES(${svr_pkgs_INCLUDE_DIRS})
 LINK_DIRECTORIES(${svr_pkgs_LIBRARY_DIRS})
 
-SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fpie")
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fpie -fPIC")
+SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CMAKE_C_FLAGS} -fPIC -std=c++17")
+SET(CMAKE_CXX_FLAGS_DEBUG "-O0 -g")
+SET(CMAKE_CXX_FLAGS_RELEASE "-O2")
 
 ADD_EXECUTABLE(${SERVER} ${SRCS})
 
diff --git a/server/alarm-manager-db-migration.c b/server/alarm-manager-db-migration.c
deleted file mode 100644 (file)
index 14bcc3f..0000000
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (c) 2019 Samsung Electronics Co., Ltd All Rights Reserved
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdio.h>
-#include <sqlite3.h>
-
-#include "alarm-manager-db.h"
-
-extern sqlite3 *alarmmgr_db;
-
-int migration_func_version_1(void)
-{
-       static const char *query = "CREATE TABLE IF NOT EXISTS alarmmgr_temp (\n" \
-               "       alarm_id INTEGER PRIMARY KEY, \n" \
-               "       start INTEGER, \n" \
-               "       end INTEGER, \n" \
-               "       uid INTEGER, \n" \
-               "       global INTEGER, \n" \
-               "       is_disabled INTEGER, \n" \
-               "       caller_pkgid TEXT, \n" \
-               "       callee_pkgid TEXT, \n" \
-               "       app_unique_name TEXT, \n" \
-               "       app_service_name TEXT, \n" \
-               "       app_service_name_mod TEXT, \n" \
-               "       bundle TEXT, \n" \
-               "       noti_len INTEGER, \n" \
-               "       noti TEXT, \n" \
-               "       year INTEGER, \n" \
-               "       month INTEGER, \n" \
-               "       day INTEGER, \n" \
-               "       hour INTEGER, \n" \
-               "       min INTEGER, \n" \
-               "       sec INTEGER, \n" \
-               "       msec INTEGER, \n" \
-               "       day_of_week INTEGER, \n" \
-               "       repeat INTEGER, \n" \
-               "       alarm_type INTEGER, \n" \
-               "       reserved_info INTEGER, \n" \
-               "       dst_service_name TEXT, \n" \
-               "       dst_service_name_mod TEXT \n" \
-               ")";
-
-       static const char *insert_query = "INSERT INTO alarmmgr_temp (alarm_id, start, \
-               end, uid, global, is_disabled, caller_pkgid, callee_pkgid, \
-               app_unique_name, app_service_name, app_service_name_mod, \
-               bundle, noti_len, noti, year, month, day, hour, min, sec, msec,\
-               day_of_week, repeat, alarm_type, reserved_info, \
-               dst_service_name, dst_service_name_mod) \
-               SELECT alarm_id, start, end, uid, global, is_disabled, \
-               caller_pkgid, callee_pkgid, app_unique_name, app_service_name, \
-               app_service_name_mod, bundle, noti_len, noti, year, month, \
-               day, hour, min, sec, msec, day_of_week, repeat, alarm_type, \
-               reserved_info, dst_service_name, dst_service_name_mod \
-               FROM alarmmgr";
-
-       char *error_message = NULL;
-       int ret;
-
-       LOGD("DB migration init version start");
-
-       ret = sqlite3_exec(alarmmgr_db, "DROP TABLE IF EXISTS alarmmgr_temp", NULL,
-                       NULL, &error_message);
-       if (ret != SQLITE_OK) {
-               LOGE("Don't execute drop, error message = %s", error_message);
-               sqlite3_free(error_message);
-               return ret;
-       }
-
-       ret = sqlite3_exec(alarmmgr_db, query, NULL, NULL, &error_message);
-       if (ret != SQLITE_OK) {
-               LOGE("Don't execute query = %s, error message = %s", query, error_message);
-               sqlite3_free(error_message);
-               return ret;
-       }
-
-       ret = sqlite3_exec(alarmmgr_db, insert_query, NULL, NULL, &error_message);
-       if (ret != SQLITE_OK) {
-               LOGE("Don't execute query = %s, error message = %s", insert_query, error_message);
-               sqlite3_free(error_message);
-               return ret;
-       }
-
-       ret = sqlite3_exec(alarmmgr_db, "DROP TABLE alarmmgr", NULL, NULL, &error_message);
-       if (ret != SQLITE_OK) {
-               LOGE("Don't execute drop alarmmgr, error message = %s", error_message);
-               sqlite3_free(error_message);
-               return ret;
-       }
-
-       ret = sqlite3_exec(alarmmgr_db, "ALTER TABLE alarmmgr_temp RENAME TO alarmmgr",
-                       NULL, NULL, &error_message);
-       if (ret != SQLITE_OK) {
-               LOGE("Don't execute alter, error message = %s", error_message);
-               sqlite3_free(error_message);
-               return ret;
-       }
-
-       return ALARMMGR_RESULT_SUCCESS;
-}
diff --git a/server/alarm-manager-db.c b/server/alarm-manager-db.c
deleted file mode 100644 (file)
index 8d4d344..0000000
+++ /dev/null
@@ -1,865 +0,0 @@
-/*
- * Copyright (c) 2000 - 2019 Samsung Electronics Co., Ltd All Rights Reserved
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include <stdio.h>
-#include <stdlib.h>
-#include <time.h>
-#include <signal.h>
-#include <string.h>
-#include <sys/types.h>
-
-#include <sqlite3.h>
-#include <glib.h>
-#include <tzplatform_config.h>
-
-#include "alarm-manager-db.h"
-
-#define ALARMMGR_DB_FILE tzplatform_mkpath(TZ_SYS_DB, ".alarmmgr.db")
-#define QUERY_CREATE_TABLE_ALARMMGR \
-       "       CREATE TABLE IF NOT EXISTS alarmmgr (\n" \
-       "       alarm_id INTEGER PRIMARY KEY, \n" \
-       "       start INTEGER, \n" \
-       "       end INTEGER, \n" \
-       "       uid INTEGER, \n" \
-       "       global INTEGER, \n" \
-       "       is_disabled INTEGER, \n" \
-       "       caller_pkgid TEXT, \n" \
-       "       callee_pkgid TEXT, \n" \
-       "       app_unique_name TEXT, \n" \
-       "       app_service_name TEXT, \n" \
-       "       app_service_name_mod TEXT, \n" \
-       "       bundle TEXT, \n" \
-       "       noti_len INTEGER, \n" \
-       "       noti TEXT, \n" \
-       "       year INTEGER, \n" \
-       "       month INTEGER, \n" \
-       "       day INTEGER, \n" \
-       "       hour INTEGER, \n" \
-       "       min INTEGER, \n" \
-       "       sec INTEGER, \n" \
-       "       msec INTEGER, \n" \
-       "       day_of_week INTEGER, \n" \
-       "       repeat INTEGER, \n" \
-       "       alarm_type INTEGER, \n" \
-       "       reserved_info INTEGER, \n" \
-       "       dst_service_name TEXT, \n" \
-       "       dst_service_name_mod TEXT \n" \
-       ")"
-
-enum schema_version
-{
-       SCHEMA_VERSION_0 = 0,
-       SCHEMA_VERSION_1 = 1,
-       SCHEMA_VERSION_LATEST = SCHEMA_VERSION_1
-} schema_version_e;
-
-typedef struct
-{
-       const char *change_log;
-       int (*func)(void);
-} migration_func;
-
-extern GSList *g_disabled_alarm_list;
-extern __alarm_server_context_t alarm_context;
-
-sqlite3 *alarmmgr_db;
-static bool is_db_corrupted = false;
-static const int latest_settime_id = -2;
-
-static const migration_func m_func[] =
-{
-       {"SCHEMA_VERSION_0", NULL},
-       {"SCHEMA_VERSION_1", migration_func_version_1}
-};
-
-static int __create_db_version(void)
-{
-       static const char *query = "CREATE TABLE IF NOT EXISTS schema_version (version INTEGER)";
-
-       if (sqlite3_exec(alarmmgr_db, query, NULL, NULL, NULL) != SQLITE_OK) {
-               LOGE("Failed to execute the query (%s)\n", sqlite3_errmsg(alarmmgr_db));
-               return -1;
-       }
-
-       return 0;
-}
-
-static int __update_db_version(int ver)
-{
-       char *query;
-
-       if (sqlite3_exec(alarmmgr_db, "DELETE FROM schema_version", NULL, NULL, NULL)
-                               != SQLITE_OK) {
-               LOGE("Failed to execute the query (%s)\n", sqlite3_errmsg(alarmmgr_db));
-               return -1;
-       }
-
-       query = sqlite3_mprintf("INSERT INTO schema_version (version) VALUES (%d)", ver);
-       if (query == NULL) {
-               LOGE("Failed to alloc query");
-               return -1;
-       }
-
-       if (sqlite3_exec(alarmmgr_db, query, NULL, NULL, NULL) != SQLITE_OK) {
-               LOGE("Failed to execute the query (%s)\n", sqlite3_errmsg(alarmmgr_db));
-               sqlite3_free(query);
-               return -1;
-       }
-
-       sqlite3_free(query);
-
-       return 0;
-}
-
-static int __get_db_version(void)
-{
-       static const char *dml = "SELECT version FROM schema_version";
-       sqlite3_stmt *stmt;
-       int ret;
-
-       ret = sqlite3_prepare_v2(alarmmgr_db, dml, -1, &stmt, NULL);
-       if (ret != SQLITE_OK) {
-               LOGE("sqlite3_prepare_v2 error : %d", ret);
-               return -1;
-       }
-
-       if (sqlite3_step(stmt) != SQLITE_ROW)
-               ret = -1;
-       else
-               ret = sqlite3_column_int(stmt, 0);
-
-       sqlite3_reset(stmt);
-       sqlite3_clear_bindings(stmt);
-       sqlite3_finalize(stmt);
-       return ret;
-}
-
-static int __db_upgrade(void)
-{
-       int ver, ret, i;
-
-       ver = __get_db_version();
-       if (ver >= SCHEMA_VERSION_LATEST)
-               return 0;
-
-       if (sqlite3_exec(alarmmgr_db, "BEGIN TRANSACTION", NULL, NULL, NULL)) {
-               LOGE("begin transaction error : %s", sqlite3_errmsg(alarmmgr_db));
-               return -1;
-       }
-
-       if (ver == -1) {
-               LOGD("Schema version not exists : %d", ver);
-               ret = __create_db_version();
-               if (ret != 0)
-                       goto out;
-
-               ver = SCHEMA_VERSION_0;
-       }
-
-       for (i = ver + 1 ; i <= SCHEMA_VERSION_LATEST; i++) {
-               if (m_func[i].func() != ALARMMGR_RESULT_SUCCESS) {
-                       ret = -1;
-                       goto out;
-               }
-
-       }
-       ret = __update_db_version(SCHEMA_VERSION_LATEST);
-
-out:
-       if (ret == 0) {
-               if (sqlite3_exec(alarmmgr_db, "END TRANSACTION", NULL, NULL, NULL))
-                       LOGE("end transaction error : %s", sqlite3_errmsg(alarmmgr_db));
-       } else {
-               if (sqlite3_exec(alarmmgr_db, "ROLLBACK TRANSACTION", NULL, NULL, NULL))
-                       LOGE("rollback transaction error : %s", sqlite3_errmsg(alarmmgr_db));
-       }
-       return ret;
-}
-
-static int __db_busyhandler(void *pData, int count)
-{
-       if (5 - count > 0) {
-               struct timespec time = {
-                       .tv_sec = 0,
-                       .tv_nsec = (count + 1) * 100 * 1000 * 1000
-               };
-               nanosleep(&time, NULL);
-               LOGD("alarmmgr_db: busy handler called. count: %d", count + 1);
-               return 1;
-       } else {
-               LOGD("alarmmgr_db: busy handler will return SQLITE_BUSY error");
-               return 0;
-       }
-}
-
-bool _save_alarms(__alarm_info_t *__alarm_info)
-{
-       char *error_message = NULL;
-       base_info_t *base_info =
-               (base_info_t *) &(__alarm_info->base_info);
-       alarm_date_t *start = &base_info->start;
-       alarm_mode_t *mode = &base_info->mode;
-
-       char *query = sqlite3_mprintf("insert into alarmmgr( alarm_id, start,\
-                       end, uid, global, is_disabled, caller_pkgid, callee_pkgid, app_unique_name,\
-                       app_service_name, app_service_name_mod, bundle, noti_len, noti, year,\
-                       month, day, hour, min, sec, msec, day_of_week, repeat,\
-                       alarm_type, reserved_info, dst_service_name, dst_service_name_mod)\
-                       values (%d,%lld,%lld,%d,%d,0,%Q,%Q,%Q,%Q,%Q,%Q,%d,%Q,%d,%d,%d,%d,%d,%d,%d,%d,%d,\
-                       %d,%lld,%Q,%Q)",\
-                       __alarm_info->alarm_id,
-                       (gint64)__alarm_info->start,
-                       (gint64)__alarm_info->end,
-                       __alarm_info->uid,
-                       __alarm_info->global,
-                       CHECK_NULL_STRING(__alarm_info->caller_pkgid),
-                       CHECK_NULL_STRING(__alarm_info->callee_pkgid),
-                       CHECK_NULL_STRING(__alarm_info->app_unique_name),
-                       CHECK_NULL_STRING(__alarm_info->app_service_name),
-                       CHECK_NULL_STRING(__alarm_info->app_service_name_mod),
-                       CHECK_NULL_STRING(__alarm_info->bundle),
-                       __alarm_info->noti ? strlen(__alarm_info->noti) : 0,
-                       CHECK_NULL_STRING(__alarm_info->noti),
-                       start->year,
-                       start->month,
-                       start->day,
-                       start->hour,
-                       start->min,
-                       start->sec,
-                       base_info->msec,
-                       mode->u_interval.day_of_week,
-                       mode->repeat,
-                       base_info->alarm_type,
-                       (gint64)base_info->reserved_info,
-                       CHECK_NULL_STRING(__alarm_info->dst_service_name),
-                       CHECK_NULL_STRING(__alarm_info->dst_service_name_mod));
-
-       if (!query) {
-               LOGE("Failed to alloc query");
-               return false;
-       }
-
-       if (SQLITE_OK != sqlite3_exec(alarmmgr_db, query, NULL, NULL, &error_message)) {
-               SECURE_LOGE("sqlite3_exec() is failed. query = %s, error message = %s", query, error_message);
-               sqlite3_free(error_message);
-               sqlite3_free(query);
-               return false;
-       }
-
-       sqlite3_free(query);
-       return true;
-}
-
-bool _update_alarms(__alarm_info_t *__alarm_info)
-{
-       char *error_message = NULL;
-       base_info_t *base_info =
-               (base_info_t *) &(__alarm_info->base_info);
-       alarm_date_t *start = &base_info->start;
-       alarm_mode_t *mode = &base_info->mode;
-
-       char *query = sqlite3_mprintf("update alarmmgr set start=%lld, end=%lld,\
-                       uid=%d, global=%d, is_disabled=0, caller_pkgid=%Q, callee_pkgid=%Q, app_unique_name=%Q, app_service_name=%Q, app_service_name_mod=%Q,\
-                       bundle=%Q, noti_len=%d, noti=%Q, year=%d, month=%d, day=%d, hour=%d, min=%d, sec=%d, msec=%d,\
-                       day_of_week=%d, repeat=%d, alarm_type=%d,\
-                       reserved_info=%lld, dst_service_name=%Q, dst_service_name_mod=%Q\
-                       where alarm_id=%d",\
-                       (gint64)__alarm_info->start,
-                       (gint64)__alarm_info->end,
-                       __alarm_info->uid,
-                       __alarm_info->global,
-                       CHECK_NULL_STRING(__alarm_info->caller_pkgid),
-                       CHECK_NULL_STRING(__alarm_info->callee_pkgid),
-                       CHECK_NULL_STRING(__alarm_info->app_unique_name),
-                       CHECK_NULL_STRING(__alarm_info->app_service_name),
-                       CHECK_NULL_STRING(__alarm_info->app_service_name_mod),
-                       CHECK_NULL_STRING(__alarm_info->bundle),
-                       __alarm_info->noti ? strlen(__alarm_info->noti) : 0,
-                       CHECK_NULL_STRING(__alarm_info->noti),
-                       start->year,
-                       start->month,
-                       start->day,
-                       start->hour,
-                       start->min,
-                       start->sec,
-                       base_info->msec,
-                       mode->u_interval.day_of_week,
-                       mode->repeat,
-                       base_info->alarm_type,
-                       (gint64)base_info->reserved_info,
-                       CHECK_NULL_STRING(__alarm_info->dst_service_name),
-                       CHECK_NULL_STRING(__alarm_info->dst_service_name_mod),
-                       __alarm_info->alarm_id);
-
-       if (!query) {
-               LOGE("Failed to alloc query");
-               return false;
-       }
-
-       if (SQLITE_OK != sqlite3_exec(alarmmgr_db, query, NULL, NULL, &error_message)) {
-               SECURE_LOGE("sqlite3_exec() is failed. query = %s, error message = %s", query, error_message);
-               sqlite3_free(error_message);
-               sqlite3_free(query);
-               return false;
-       }
-
-       sqlite3_free(query);
-       return true;
-}
-
-bool _delete_alarms(alarm_id_t alarm_id)
-{
-       char *error_message = NULL;
-       char *query = sqlite3_mprintf("delete from alarmmgr where alarm_id=%d", alarm_id);
-
-       if (!query) {
-               LOGE("Failed to alloc query");
-               return false;
-       }
-
-       if (SQLITE_OK != sqlite3_exec(alarmmgr_db, query, NULL, NULL, &error_message)) {
-               SECURE_LOGE("sqlite3_exec() is failed. query = %s, error message = %s", query, error_message);
-               sqlite3_free(error_message);
-               sqlite3_free(query);
-               return false;
-       }
-
-       sqlite3_free(query);
-       return true;
-}
-
-void _load_alarms_from_db()
-{
-       int i = 0;
-       int col_idx;
-       const char *query = "select * from alarmmgr";
-       const char *null_str = "null";
-       sqlite3_stmt *stmt = NULL;
-       const char *tail = NULL;
-       base_info_t *base_info = NULL;
-       __alarm_info_t *__alarm_info = NULL;
-       alarm_date_t *start = NULL;
-       alarm_mode_t *mode = NULL;
-       int is_disabled;
-       char caller_pkgid[MAX_PKG_ID_LEN] = {0,};
-       char callee_pkgid[MAX_PKG_ID_LEN] = {0,};
-       char app_unique_name[MAX_APP_ID_LEN] = {0,};
-       char app_service_name[MAX_SERVICE_NAME_LEN] = {0,};
-       char app_service_name_mod[MAX_SERVICE_NAME_LEN] = {0,};
-       char dst_service_name[MAX_SERVICE_NAME_LEN] = {0,};
-       char dst_service_name_mod[MAX_SERVICE_NAME_LEN] = {0,};
-       char bundle[MAX_BUNDLE_NAME_LEN] = {0,};
-       int noti_len;
-       char *noti;
-       gint64 start_64, end_64, reserved_info_64;
-
-       if (SQLITE_OK != sqlite3_prepare(alarmmgr_db, query, strlen(query), &stmt, &tail)) {
-               LOGE("sqlite3_prepare() is failed.");
-               return;
-       }
-
-       for (i = 0; SQLITE_ROW == sqlite3_step(stmt); i++) {
-               col_idx = 0;
-               __alarm_info = (__alarm_info_t *)calloc(1, sizeof(__alarm_info_t));
-
-               if (G_UNLIKELY(__alarm_info == NULL)) {
-                       LOGE("Memory allocation failed.");
-                       goto done;
-               }
-               base_info = (base_info_t *) &(__alarm_info->base_info);
-               start = &base_info->start;
-               mode = &base_info->mode;
-
-               __alarm_info->alarm_id = sqlite3_column_int(stmt, col_idx++);
-               start_64 = sqlite3_column_int64(stmt, col_idx++);
-               __alarm_info->start = (time_t)start_64;
-               end_64 = sqlite3_column_int64(stmt, col_idx++);
-               __alarm_info->end = (time_t)end_64;
-               __alarm_info->uid = sqlite3_column_int(stmt, col_idx++);
-               __alarm_info->global = sqlite3_column_int(stmt, col_idx++);
-               is_disabled = sqlite3_column_int(stmt, col_idx++);
-
-               strncpy(caller_pkgid, (const char *)sqlite3_column_text(stmt, col_idx++),
-                       MAX_PKG_ID_LEN - 1);
-               strncpy(callee_pkgid, (const char *)sqlite3_column_text(stmt, col_idx++),
-                       MAX_PKG_ID_LEN - 1);
-               strncpy(app_unique_name, (const char *)sqlite3_column_text(stmt, col_idx++),
-                       MAX_APP_ID_LEN - 1);
-               strncpy(app_service_name, (const char *)sqlite3_column_text(stmt, col_idx++),
-                       MAX_SERVICE_NAME_LEN - 1);
-               strncpy(app_service_name_mod, (const char *)sqlite3_column_text(stmt, col_idx++),
-                       MAX_SERVICE_NAME_LEN - 1);
-               strncpy(bundle, (const char *)sqlite3_column_text(stmt, col_idx++),
-                       MAX_BUNDLE_NAME_LEN - 1);
-               noti_len = sqlite3_column_int(stmt, col_idx++);
-               noti_len = noti_len ? noti_len : strlen(null_str);
-               noti = (char *)calloc(1, noti_len + 1);
-               if (noti)
-                       strncpy(noti, (const char *)sqlite3_column_text(stmt, col_idx++),
-                                       noti_len);
-               start->year = sqlite3_column_int(stmt, col_idx++);
-               start->month = sqlite3_column_int(stmt, col_idx++);
-               start->day = sqlite3_column_int(stmt, col_idx++);
-               start->hour = sqlite3_column_int(stmt, col_idx++);
-               start->min = sqlite3_column_int(stmt, col_idx++);
-               start->sec = sqlite3_column_int(stmt, col_idx++);
-               base_info->msec = sqlite3_column_int(stmt, col_idx++);
-               mode->u_interval.day_of_week = sqlite3_column_int(stmt, col_idx++);
-               mode->repeat = (alarm_repeat_mode_t)sqlite3_column_int(stmt, col_idx++);
-               base_info->alarm_type = sqlite3_column_int(stmt, col_idx++);
-               reserved_info_64 = sqlite3_column_int64(stmt, col_idx++);
-               base_info->reserved_info = (time_t)reserved_info_64;
-               strncpy(dst_service_name, (const char *)sqlite3_column_text(stmt, col_idx++),
-                       MAX_SERVICE_NAME_LEN - 1);
-               strncpy(dst_service_name_mod, (const char *)sqlite3_column_text(stmt, col_idx++),
-                       MAX_SERVICE_NAME_LEN - 1);
-
-               __alarm_info->caller_pkgid = STRDUP_WITH_NULLCMP(caller_pkgid);
-               __alarm_info->callee_pkgid = STRDUP_WITH_NULLCMP(callee_pkgid);
-               __alarm_info->app_unique_name = STRDUP_WITH_NULLCMP(app_unique_name);
-               __alarm_info->app_service_name = STRDUP_WITH_NULLCMP(app_service_name);
-               __alarm_info->app_service_name_mod =
-                       STRDUP_WITH_NULLCMP(app_service_name_mod);
-               __alarm_info->dst_service_name = STRDUP_WITH_NULLCMP(dst_service_name);
-               __alarm_info->dst_service_name_mod =
-                       STRDUP_WITH_NULLCMP(dst_service_name_mod);
-               __alarm_info->bundle = STRDUP_WITH_NULLCMP(bundle);
-               if (noti) {
-                       __alarm_info->noti = STRDUP_WITH_NULLCMP(noti);
-                       free(noti);
-               }
-
-               if (is_disabled) {
-                       _alarm_set_next_duetime(__alarm_info);
-                       g_disabled_alarm_list = g_slist_append(g_disabled_alarm_list, __alarm_info);
-                       LOGW("Save alarm_id[%d] caller[%s] callee[%s]", __alarm_info->alarm_id, caller_pkgid, callee_pkgid);
-               } else {
-                       _alarm_set_next_duetime(__alarm_info);
-                       alarm_context.alarms = g_slist_append(alarm_context.alarms, __alarm_info);
-               }
-       }
-done:
-       _alarm_schedule();
-       if (sqlite3_finalize(stmt) != SQLITE_OK)
-               LOGE("sqlite3_finalize() is failed.");
-
-       return;
-}
-
-int _get_db_path_for_all_info(uid_t uid, char** db_path)
-{
-       sqlite3 *alarmmgr_tool_db;
-       char db_path_tmp[50] = {0,};
-       const char *query_for_creating_table =  "create table alarmmgr_tool \
-                                       (alarm_id integer primary key,\
-                                                       duetime_epoch integer,\
-                                                       duetime text,\
-                                                       start_epoch integer,\
-                                                       end_epoch integer,\
-                                                       global integer,\
-                                                       caller_pkgid text,\
-                                                       callee_pkgid text,\
-                                                       app_unique_name text,\
-                                                       app_service_name text,\
-                                                       dst_service_name text,\
-                                                       day_of_week integer,\
-                                                       repeat integer,\
-                                                       alarm_type integer)";
-       const char *query_for_deleting_table = "drop table alarmmgr_tool";
-       time_t current_time = 0;
-       struct tm current_tm;
-       GSList *gs_iter = NULL;
-       __alarm_info_t *entry = NULL;
-       char *error_message = NULL;
-       int index = 0;
-
-       /* Open a DB */
-       time(&current_time);
-       tzset();
-       localtime_r(&current_time, &current_tm);
-       snprintf(db_path_tmp, sizeof(db_path_tmp), "/tmp/alarmmgr_%d%d%d_%02d%02d%02d.db",
-               current_tm.tm_year + 1900, current_tm.tm_mon + 1, current_tm.tm_mday, current_tm.tm_hour, current_tm.tm_min, current_tm.tm_sec);
-       *db_path = strdup(db_path_tmp);
-       if (*db_path == NULL) {
-               LOGE("Out of memory");
-               return ERR_ALARM_SYSTEM_FAIL;
-       }
-
-       if (sqlite3_open(db_path_tmp, &alarmmgr_tool_db) != SQLITE_OK) {
-               LOGE("Failed to open [%s]", db_path_tmp);
-               return ERR_ALARM_SYSTEM_FAIL;
-       }
-
-       /* Register busy handler */
-       if (sqlite3_busy_handler(alarmmgr_tool_db, __db_busyhandler, NULL) != SQLITE_OK) {
-               LOGE("Failed to register the busy handler");
-               sqlite3_close(alarmmgr_tool_db);
-               return ERR_ALARM_SYSTEM_FAIL;
-       }
-
-       /* Drop a table */
-       if (sqlite3_exec(alarmmgr_tool_db, query_for_deleting_table, NULL, NULL, &error_message) != SQLITE_OK) {
-               LOGE("Deleting the table is failed. error message = %s", error_message);
-               sqlite3_free(error_message);
-       }
-
-       /* Create a table if it does not exist */
-       if (sqlite3_exec(alarmmgr_tool_db, query_for_creating_table, NULL, NULL, &error_message) != SQLITE_OK) {
-               LOGE("Creating the table is failed. error message = %s", error_message);
-               sqlite3_free(error_message);
-               sqlite3_close(alarmmgr_tool_db);
-               return ERR_ALARM_SYSTEM_FAIL;
-       }
-
-       /* Get information of all alarms and save those into the DB. */
-       for (gs_iter = alarm_context.alarms; gs_iter != NULL; gs_iter = g_slist_next(gs_iter)) {
-               entry = (__alarm_info_t*)gs_iter->data;
-               if (uid >= REGULAR_UID_MIN && entry->uid != uid)
-                       continue;
-               ++index;
-               SECURE_LOGD("#%d alarm id[%d] app_name[%s] duetime[%ld]",
-                               index, entry->alarm_id, entry->app_unique_name, entry->start);
-
-               base_info_t *base_info = (base_info_t *) &(entry->base_info);
-               alarm_mode_t *mode = &base_info->mode;
-
-               char *query = sqlite3_mprintf("insert into alarmmgr_tool( alarm_id, duetime_epoch, duetime, start_epoch,\
-                               end_epoch, global, caller_pkgid, callee_pkgid, app_unique_name, app_service_name, dst_service_name, day_of_week, repeat, alarm_type)\
-                               values (%d,%d,%Q,%d,%d,%d,%Q,%Q,%Q,%Q,%Q,%d,%d,%d)",
-                               entry->alarm_id,
-                               (int)entry->due_time,
-                               ctime(&(entry->due_time)),
-                               (int)entry->start,
-                               (int)entry->end,
-                               (bool)entry->global,
-                               CHECK_NULL_STRING(entry->caller_pkgid),
-                               CHECK_NULL_STRING(entry->callee_pkgid),
-                               CHECK_NULL_STRING(entry->app_unique_name),
-                               CHECK_NULL_STRING(entry->app_service_name),
-                               CHECK_NULL_STRING(entry->dst_service_name),
-                               mode->u_interval.day_of_week,
-                               mode->repeat,
-                               entry->base_info.alarm_type);
-
-               if (!query) {
-                       LOGE("Failed to alloc query");
-                       sqlite3_close(alarmmgr_tool_db);
-                       return ERR_ALARM_SYSTEM_FAIL;
-               }
-
-               if (sqlite3_exec(alarmmgr_tool_db, query, NULL, NULL, &error_message) != SQLITE_OK) {
-                       SECURE_LOGE("sqlite3_exec() is failed. error message = %s", error_message);
-                       sqlite3_free(error_message);
-               }
-
-               sqlite3_free(query);
-       }
-
-       sqlite3_close(alarmmgr_tool_db);
-       return ALARMMGR_RESULT_SUCCESS;
-}
-
-gboolean _update_relative_alarms(gpointer user_data)
-{
-       GSList *iter = NULL;
-       __alarm_info_t *entry = NULL;
-       char *error_message = NULL;
-
-       if (sqlite3_exec(alarmmgr_db, "BEGIN EXCLUSIVE", NULL, NULL, &error_message) != SQLITE_OK) {
-               SECURE_LOGE("sqlite3_exec() is failed. error message = %s", error_message);
-               sqlite3_free(error_message);
-               return false;
-       }
-
-       for (iter = alarm_context.alarms; iter != NULL; iter = g_slist_next(iter)) {
-               entry = (__alarm_info_t *)iter->data;
-               base_info_t *base_info = &(entry->base_info);
-               if (base_info->alarm_type & ALARM_TYPE_RELATIVE)
-                       _update_alarms(entry);
-       }
-
-       if (sqlite3_exec(alarmmgr_db, "COMMIT", NULL, NULL, &error_message) != SQLITE_OK) {
-               SECURE_LOGE("sqlite3_exec() is failed. error message = %s", error_message);
-               sqlite3_free(error_message);
-               return false;
-       }
-
-       return false;
-}
-
-bool _alarm_set_global_to_db(__alarm_info_t *alarm_info, bool global)
-{
-
-       char *error_message = NULL;
-       char *query = sqlite3_mprintf("update alarmmgr set global=%d where alarm_id=%d",
-                       alarm_info->global, alarm_info->alarm_id);
-
-       if (!query) {
-               LOGE("Failed to alloc query");
-               return false;
-       }
-
-       if (SQLITE_OK != sqlite3_exec(alarmmgr_db, query, NULL, NULL, &error_message)) {
-               SECURE_LOGE("sqlite3_exec() is failed. query = %s, error message = %s", query, error_message);
-               sqlite3_free(query);
-               sqlite3_free(error_message);
-               return false;
-       }
-
-       sqlite3_free(query);
-       return true;
-}
-
-void _update_db_for_disabled_alarm(alarm_id_t alarm_id, bool disabled)
-{
-       char *error_message = NULL;
-
-       LOGW("Update (%d) is_disabled to (%d)", alarm_id, disabled);
-       char *query = sqlite3_mprintf("update alarmmgr set is_disabled=%d where alarm_id=%d", disabled, alarm_id);
-
-       if (!query) {
-               LOGE("Failed to alloc query");
-               return;
-       }
-
-       if (SQLITE_OK != sqlite3_exec(alarmmgr_db, query, NULL, NULL, &error_message)) {
-               SECURE_LOGE("Failed to update the DB table. error message = %s", error_message);
-               sqlite3_free(error_message);
-       }
-
-       sqlite3_free(query);
-       return;
-}
-
-int __check_callback(void *pid, int argc, char **argv, char **notUsed2)
-{
-       if (strcmp(argv[0], "ok") != 0) {
-               LOGE("check integrity result : %s" , argv[0]);
-               is_db_corrupted = true;
-               return -1;
-       } else {
-               LOGD("check integrity result : %s" , argv[0]);
-       }
-
-       return 0;
-}
-
-int __check_alarmmgr_table(sqlite3 *alarmmgr_db, bool *is_exist)
-{
-       sqlite3_stmt *stmt = NULL;
-       int count, sqlret;
-
-       sqlret = sqlite3_prepare_v2(alarmmgr_db,
-                       "SELECT COUNT(*) FROM sqlite_master WHERE name='alarmmgr'",
-                       -1, &stmt, NULL);
-       if (sqlret != SQLITE_OK) {
-               /* LCOV_EXCL_START */
-               LOGE("sqlite3_prepare_v2 failed [%d][%s]", sqlret,
-                               sqlite3_errmsg(alarmmgr_db));
-               return sqlret;
-               /* LCOV_EXCL_STOP */
-       }
-
-       sqlret = sqlite3_step(stmt);
-       if (sqlret == SQLITE_ROW)
-               count = sqlite3_column_int(stmt, 0);
-       else
-               count = 0;
-
-       LOGD("DB search result[%d]", count);
-
-       if (count > 0)
-               *is_exist = true;
-       else
-               *is_exist = false;
-
-       sqlite3_finalize(stmt);
-
-       return SQLITE_OK;
-
-}
-bool _initialize_db()
-{
-       char *error_message = NULL;
-       int ret;
-       bool is_exist;
-
-       /* Create or Open the DB file */
-       ret = sqlite3_open(ALARMMGR_DB_FILE, &alarmmgr_db);
-       if (ret != SQLITE_OK) {
-               LOGE("Failed to open [%s]. error: %s", ALARMMGR_DB_FILE, sqlite3_errmsg(alarmmgr_db));
-               if (ret == SQLITE_CORRUPT)
-                       goto recover;
-               else
-                       return false;
-       }
-       /* Register busy handler */
-       ret = sqlite3_busy_handler(alarmmgr_db, __db_busyhandler, NULL);
-       if (ret != SQLITE_OK) {
-               LOGE("Failed to register the busy handler");
-               if (ret == SQLITE_CORRUPT) {
-                       goto recover;
-               } else {
-                       sqlite3_close(alarmmgr_db);
-                       return false;
-               }
-       }
-
-       ret = __check_alarmmgr_table(alarmmgr_db, &is_exist);
-       if (ret != SQLITE_OK) {
-               if (ret == SQLITE_CORRUPT) {
-                       goto recover;
-               } else {
-                       sqlite3_close(alarmmgr_db);
-                       return false;
-               }
-       }
-
-       /* Create alarmmgr table */
-       ret = sqlite3_exec(alarmmgr_db, QUERY_CREATE_TABLE_ALARMMGR, NULL, NULL, &error_message);
-       if (ret != SQLITE_OK) {
-               LOGE("Don't execute query = %s, error message = %s", QUERY_CREATE_TABLE_ALARMMGR, error_message);
-               if (ret == SQLITE_CORRUPT || ret == SQLITE_NOTADB) {
-                       goto recover;
-               } else {
-                       sqlite3_close(alarmmgr_db);
-                       sqlite3_free(error_message);
-                       return false;
-               }
-       }
-
-       if (is_exist == false) {
-               if (__create_db_version() != 0) {
-                       sqlite3_close(alarmmgr_db);
-                       return false;
-               }
-
-               if (__update_db_version(SCHEMA_VERSION_LATEST) != 0) {
-                       sqlite3_close(alarmmgr_db);
-                       return false;
-               }
-       } else {
-               ret = __db_upgrade();
-               if (ret) {
-                       LOGE("Failed db's migration");
-                       sqlite3_close(alarmmgr_db);
-                       return false;
-               }
-       }
-
-       /* Check integrity of DB */
-       ret = sqlite3_exec(alarmmgr_db, "PRAGMA integrity_check", __check_callback, NULL, 0);
-       if (ret != SQLITE_OK || is_db_corrupted) {
-               LOGE("Loss alarm db's integrity");
-               goto recover;
-       }
-
-       return true;
-
-recover:
-       if (alarmmgr_db)
-               sqlite3_close(alarmmgr_db);
-       if (error_message)
-               sqlite3_free(error_message);
-       unlink(ALARMMGR_DB_FILE);
-
-       ret = sqlite3_open(ALARMMGR_DB_FILE, &alarmmgr_db);
-       if (ret != SQLITE_OK) {
-               LOGE("[recover] Failed to open [%s]. error: %s", ALARMMGR_DB_FILE, sqlite3_errmsg(alarmmgr_db));
-               return false;
-       }
-
-       ret = sqlite3_busy_handler(alarmmgr_db, __db_busyhandler, NULL);
-       if (ret != SQLITE_OK) {
-               LOGE("[recover] Failed to register the busy handler");
-               sqlite3_close(alarmmgr_db);
-               return false;
-       }
-
-       ret = sqlite3_exec(alarmmgr_db, QUERY_CREATE_TABLE_ALARMMGR, NULL, NULL, &error_message);
-       if (ret != SQLITE_OK) {
-               LOGE("[recover] Don't execute query = %s, error message = %s", QUERY_CREATE_TABLE_ALARMMGR, error_message);
-               sqlite3_close(alarmmgr_db);
-               sqlite3_free(error_message);
-               return false;
-       }
-
-       if (__create_db_version() != 0) {
-               sqlite3_close(alarmmgr_db);
-               return false;
-       }
-
-       if (__update_db_version(SCHEMA_VERSION_LATEST) != 0) {
-               sqlite3_close(alarmmgr_db);
-               return false;
-       }
-
-       return true;
-}
-
-bool _set_latest_settime(time_t settime)
-{
-       char *error_message = NULL;
-
-       char *query = sqlite3_mprintf("insert or replace into alarmmgr( alarm_id, start,\
-                       end, uid, global, is_disabled, caller_pkgid, callee_pkgid, app_unique_name,\
-                       app_service_name, app_service_name_mod, bundle, noti_len, noti, year,\
-                       month, day, hour, min, sec, msec, day_of_week, repeat,\
-                       alarm_type, reserved_info, dst_service_name, dst_service_name_mod)\
-                       values (%d,%d,0,0,0,1,'n','n','n','n','n','n',0,\
-                       'n',0,0,0,0,0,0,0,0,0,0,0,'n','n')", latest_settime_id, (gint64)settime);
-
-       if (SQLITE_OK != sqlite3_exec(alarmmgr_db, query, NULL, NULL, &error_message)) {
-               SECURE_LOGE("sqlite3_exec() is failed. query = %s, error message = %s", query, error_message);
-               sqlite3_free(error_message);
-               sqlite3_free(query);
-               return false;
-       }
-
-       LOGD("latest_settime : %ld", settime);
-       sqlite3_free(query);
-       return true;
-}
-
-bool _get_latest_settime(time_t *settime)
-{
-       sqlite3_stmt *stmt = NULL;
-       int ret;
-
-       char *query = sqlite3_mprintf("select start from alarmmgr where alarm_id=%d",
-                       latest_settime_id);
-
-       ret = sqlite3_prepare_v2(alarmmgr_db, query, strlen(query), &stmt, NULL);
-       if (SQLITE_OK != ret) {
-               LOGE("sqlite3_prepare() is failed. [%d]", ret);
-               sqlite3_free(query);
-               return false;
-       }
-
-       ret = sqlite3_step(stmt);
-       if (SQLITE_ROW == ret) {
-               *settime = (time_t)sqlite3_column_int(stmt, 0);
-               LOGD("latest_settime : %ld", *settime);
-       } else {
-               LOGE("latest_settime is not set");
-               sqlite3_finalize(stmt);
-               sqlite3_free(query);
-               return false;
-       }
-
-       sqlite3_finalize(stmt);
-       sqlite3_free(query);
-       return true;
-}
\ No newline at end of file
diff --git a/server/alarm-manager-db.cc b/server/alarm-manager-db.cc
new file mode 100644 (file)
index 0000000..b8e1c72
--- /dev/null
@@ -0,0 +1,865 @@
+/*
+* Copyright (c) 2000 - 2023 Samsung Electronics Co., Ltd All Rights Reserved
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+
+#include "alarm-manager-db.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+#include <signal.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sqlite3.h>
+#include <glib.h>
+#include <tzplatform_config.h>
+
+#include <database.hpp>
+
+extern GSList* g_disabled_alarm_list;
+extern __alarm_server_context_t alarm_context;
+
+namespace {
+
+constexpr const char QUERY_CREATE_TABLE_ALARMMGR[] = R"__alarm(
+CREATE TABLE IF NOT EXISTS alarmmgr (
+  alarm_id INTEGER PRIMARY KEY,
+  start INTEGER,
+  end INTEGER,
+  uid INTEGER,
+  global INTEGER,
+  is_disabled INTEGER,
+  caller_pkgid TEXT,
+  callee_pkgid TEXT,
+  app_unique_name TEXT,
+  app_service_name TEXT,
+  app_service_name_mod TEXT,
+  bundle TEXT,
+  noti_len INTEGER,
+  noti TEXT,
+  year INTEGER,
+  month INTEGER,
+  day INTEGER,
+  hour INTEGER,
+  min INTEGER,
+  sec INTEGER,
+  msec INTEGER,
+  day_of_week INTEGER,
+  repeat INTEGER,
+  alarm_type INTEGER,
+  reserved_info INTEGER,
+  dst_service_name TEXT,
+  dst_service_name_mod TEXT)
+)__alarm";
+
+constexpr const int LATEST_SETTIME_ID = -2;
+
+enum SchemaVersion {
+  SCHEMA_VERSION_0 = 0,
+  SCHEMA_VERSION_1 = 1,
+  SCHEMA_VERSION_LATEST = SCHEMA_VERSION_1
+};
+
+struct MigrationFunc {
+  const char *change_log;
+  int (*func)(void);
+};
+
+std::unique_ptr<tizen_base::Database> alarmmgr_db;
+bool is_db_corrupted = false;
+
+char* GetCString(int idx, const tizen_base::Database::Result::Record& rec,
+    int max_size = -1) {
+  std::optional<std::string> str = rec.GetString(idx);
+  if (!str)
+    return nullptr;
+  if (*str == "null")
+    return nullptr;
+
+  if (max_size > 0) {
+    strdup(str->substr(max_size).c_str());
+  }
+
+  return strdup(str->c_str());
+}
+
+int MigrationFuncVersion1() {
+  static const char query[] =
+    "CREATE TABLE IF NOT EXISTS alarmmgr_temp ("
+    " alarm_id INTEGER PRIMARY KEY, "
+    " start INTEGER, "
+    " end INTEGER, "
+    " uid INTEGER, "
+    " global INTEGER, "
+    " is_disabled INTEGER, "
+    " caller_pkgid TEXT, "
+    " callee_pkgid TEXT, "
+    " app_unique_name TEXT, "
+    " app_service_name TEXT, "
+    " app_service_name_mod TEXT, "
+    " bundle TEXT, "
+    " noti_len INTEGER, "
+    " noti TEXT, "
+    " year INTEGER, "
+    " month INTEGER, "
+    " day INTEGER, "
+    " hour INTEGER, "
+    " min INTEGER, "
+    " sec INTEGER, "
+    " msec INTEGER, "
+    " day_of_week INTEGER, "
+    " repeat INTEGER, "
+    " alarm_type INTEGER, "
+    " reserved_info INTEGER, "
+    " dst_service_name TEXT, "
+    " dst_service_name_mod TEXT "
+    ")";
+
+  static const char insert_query[] =
+    "INSERT INTO alarmmgr_temp (alarm_id, start, "
+    "end, uid, global, is_disabled, caller_pkgid, callee_pkgid, "
+    "app_unique_name, app_service_name, app_service_name_mod, "
+    "bundle, noti_len, noti, year, month, day, hour, min, sec, msec, "
+    "day_of_week, repeat, alarm_type, reserved_info, "
+    "dst_service_name, dst_service_name_mod) "
+    "SELECT alarm_id, start, end, uid, global, is_disabled, "
+    "caller_pkgid, callee_pkgid, app_unique_name, app_service_name, "
+    "app_service_name_mod, bundle, noti_len, noti, year, month, "
+    "day, hour, min, sec, msec, day_of_week, repeat, alarm_type, "
+    "reserved_info, dst_service_name, dst_service_name_mod "
+    "FROM alarmmgr";
+
+  LOGD("DB migration init version start");
+  alarmmgr_db->OneStepExec({ "DROP TABLE IF EXISTS alarmmgr_temp" });
+  alarmmgr_db->OneStepExec({ query });
+  alarmmgr_db->OneStepExec({ insert_query });
+  alarmmgr_db->OneStepExec({ "DROP TABLE alarmmgr" });
+  alarmmgr_db->OneStepExec({ "ALTER TABLE alarmmgr_temp RENAME TO alarmmgr" });
+
+  return ALARMMGR_RESULT_SUCCESS;
+}
+
+const MigrationFunc m_func[] = {
+  { "SCHEMA_VERSION_0", nullptr },
+  { "SCHEMA_VERSION_1", MigrationFuncVersion1 }
+};
+
+const char* GetAlarmDbFile() {
+  static std::string str;
+
+  if (!str.empty())
+    return str.c_str();
+
+  str = tzplatform_mkpath(TZ_SYS_DB, ".alarmmgr.db");
+  return str.c_str();
+}
+
+int CreateDbVersion() {
+  alarmmgr_db->OneStepExec(
+      { "CREATE TABLE IF NOT EXISTS schema_version (version INTEGER)" });
+  return 0;
+}
+
+int UpdateDbVersion(int ver) {
+  auto r = alarmmgr_db->Exec({ "DELETE FROM schema_version" });
+  if (!r) {
+    LOGE("db.Exec() failed: %s", static_cast<const char*>(r));
+    return -1;
+  }
+
+  auto q = tizen_base::Database::Sql(
+      "INSERT INTO schema_version (version) VALUES (?)")
+      .Bind(ver);
+  r = alarmmgr_db->Exec(q);
+  if (!r) {
+    LOGE("db.Exec() failed: %s", static_cast<const char*>(r));
+    return -1;
+  }
+
+  return 0;
+}
+
+int GetDbVersion() {
+  auto r = alarmmgr_db->Exec({ "SELECT version FROM schema_version" });
+  if (!r) {
+    LOGE("db.Exec() failed: %s", static_cast<const char*>(r));
+    return -1;
+  }
+
+  auto rec = r.GetFirstRecord();
+  if (!rec)
+    return -1;
+  return static_cast<int>(rec->Get(0));
+}
+
+int DbUpgrade() {
+  int ver = GetDbVersion();
+  if (ver >= SCHEMA_VERSION_LATEST)
+    return 0;
+
+  auto guard = alarmmgr_db->CreateTransactionGuard();
+  if (ver == -1) {
+    LOGD("Schema version not exists : %d", ver);
+    int ret = CreateDbVersion();
+    if (ret != 0)
+      return ret;
+
+    ver = SCHEMA_VERSION_0;
+  }
+
+  for (int i = ver + 1 ; i <= SCHEMA_VERSION_LATEST; i++) {
+    if (m_func[i].func() != ALARMMGR_RESULT_SUCCESS)
+      return -1;
+  }
+
+  int ret = UpdateDbVersion(SCHEMA_VERSION_LATEST);
+  guard.Commit();
+
+  return ret;
+}
+
+bool DbBusyHandler(int count) {
+  if (5 - count > 0) {
+    struct timespec time = {
+      .tv_sec = 0,
+      .tv_nsec = (count + 1) * 100 * 1000 * 1000
+    };
+    nanosleep(&time, nullptr);
+    LOGD("alarmmgr_db: busy handler called. count: %d", count + 1);
+    return true;
+  } else {
+    LOGD("alarmmgr_db: busy handler will return SQLITE_BUSY error");
+    return false;
+  }
+}
+
+bool ReopenDb() {
+  unlink(GetAlarmDbFile());
+  try {
+    alarmmgr_db.reset(
+        new tizen_base::Database(
+            GetAlarmDbFile(), SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
+            DbBusyHandler));
+    alarmmgr_db->OneStepExec({ QUERY_CREATE_TABLE_ALARMMGR });
+  } catch (const tizen_base::DbException& e) {
+    LOGE("[ReopenDb] Failed error: %s", e.msg());
+    alarmmgr_db.reset();
+    return false;
+  }
+
+  if (CreateDbVersion() != 0) {
+    alarmmgr_db.reset();
+    return false;
+  }
+
+  if (UpdateDbVersion(SCHEMA_VERSION_LATEST) != 0) {
+    alarmmgr_db.reset();
+    return false;
+  }
+
+  return true;
+}
+
+void RecoverDb() {
+}
+
+int CheckAlarmMgrTable(const tizen_base::Database& db, bool* is_exist) {
+  auto r = db.Exec(
+      { "SELECT COUNT(*) FROM sqlite_master WHERE name='alarmmgr'" });
+  if (!r) {
+    LOGE("db.Exec failed : %s", static_cast<const char*>(r));
+    return static_cast<int>(r);
+  }
+
+  auto rec = r.GetFirstRecord();
+  if (!rec) {
+    *is_exist = false;
+    return SQLITE_OK;
+  }
+
+  int count = static_cast<int>(rec->Get(0));
+  LOGD("DB search result[%d]", count);
+
+  if (count > 0)
+    *is_exist = true;
+  else
+    *is_exist = false;
+
+  return SQLITE_OK;
+}
+
+int CheckCallback(void* pid, int argc, char** argv, char** notUsed2) {
+  if (strcmp(argv[0], "ok") != 0) {
+    LOGE("check integrity result : %s" , argv[0]);
+    is_db_corrupted = true;
+    return -1;
+  } else {
+    LOGD("check integrity result : %s" , argv[0]);
+  }
+
+  return 0;
+}
+
+bool SaveAlarms(__alarm_info_t* __alarm_info) {
+  base_info_t* base_info = static_cast<base_info_t*>(
+      &(__alarm_info->base_info));
+  alarm_date_t* start = &base_info->start;
+  alarm_mode_t* mode = &base_info->mode;
+
+  auto q = tizen_base::Database::Sql(
+      "INSERT INTO alarmmgr (alarm_id, start, end, uid, global, is_disabled, "
+      "caller_pkgid, callee_pkgid, app_unique_name, app_service_name, "
+      "app_service_name_mod, bundle, noti_len, noti, year, month, day, "
+      "hour, min, sec, msec, day_of_week, repeat, alarm_type, reserved_info, "
+      "dst_service_name, dst_service_name_mod) "
+      "VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "
+      "?, ?, ?, ?, ?, ?)")
+      .Bind(__alarm_info->alarm_id)
+      .Bind(static_cast<int64_t>(__alarm_info->start))
+      .Bind(static_cast<int64_t>(__alarm_info->end))
+      .Bind(static_cast<int>(__alarm_info->uid))
+      .Bind(__alarm_info->global)
+      .Bind(__alarm_info->caller_pkgid)
+      .Bind(__alarm_info->callee_pkgid)
+      .Bind(__alarm_info->app_unique_name)
+      .Bind(__alarm_info->app_service_name)
+      .Bind(__alarm_info->app_service_name_mod)
+      .Bind(__alarm_info->bundle)
+      .Bind(__alarm_info->noti ?
+          static_cast<int>(strlen(__alarm_info->noti)) : 0)
+      .Bind(__alarm_info->noti)
+      .Bind(start->year)
+      .Bind(start->month)
+      .Bind(start->day)
+      .Bind(start->hour)
+      .Bind(start->min)
+      .Bind(start->sec)
+      .Bind(base_info->msec)
+      .Bind(mode->u_interval.day_of_week)
+      .Bind(mode->repeat)
+      .Bind(base_info->alarm_type)
+      .Bind(static_cast<int64_t>(base_info->reserved_info))
+      .Bind(__alarm_info->dst_service_name)
+      .Bind(__alarm_info->dst_service_name_mod);
+  auto r = alarmmgr_db->Exec(q);
+  if (!r) {
+    LOGE("db.Exec failed : %s", static_cast<const char*>(r));
+    return false;
+  }
+
+  return true;
+}
+
+bool UpdateAlarms(__alarm_info_t* __alarm_info) {
+  base_info_t* base_info =
+      static_cast<base_info_t*>(&(__alarm_info->base_info));
+  alarm_date_t* start = &base_info->start;
+  alarm_mode_t* mode = &base_info->mode;
+
+  auto q = tizen_base::Database::Sql(
+      "UPDATE alarmmgr SET start=?, end=?, uid=?, global=?, is_disabled=0, "
+      "caller_pkgid=?, callee_pkgid=?, app_unique_name=?, app_service_name=?, "
+      "app_service_name_mod=?, bundle=?, noti_len=?, noti=?, year=?, month=?, "
+      "day=?, hour=?, min=?, sec=?, msec=?, day_of_week=?, repeat=?, "
+      "alarm_type=?, reserved_info=?, dst_service_name=?, "
+      "dst_service_name_mod=? WHERE alarm_id=?")
+      .Bind(static_cast<int64_t>(__alarm_info->start))
+      .Bind(static_cast<int64_t>(__alarm_info->end))
+      .Bind(static_cast<int>(__alarm_info->uid))
+      .Bind(__alarm_info->global)
+      .Bind(__alarm_info->caller_pkgid)
+      .Bind(__alarm_info->callee_pkgid)
+      .Bind(__alarm_info->app_unique_name)
+      .Bind(__alarm_info->app_service_name)
+      .Bind(__alarm_info->app_service_name_mod)
+      .Bind(__alarm_info->bundle)
+      .Bind(__alarm_info->noti ?
+          static_cast<int>(strlen(__alarm_info->noti)) : 0)
+      .Bind(__alarm_info->noti)
+      .Bind(start->year)
+      .Bind(start->month)
+      .Bind(start->day)
+      .Bind(start->hour)
+      .Bind(start->min)
+      .Bind(start->sec)
+      .Bind(base_info->msec)
+      .Bind(mode->u_interval.day_of_week)
+      .Bind(mode->repeat)
+      .Bind(base_info->alarm_type)
+      .Bind(static_cast<int64_t>(base_info->reserved_info))
+      .Bind(__alarm_info->dst_service_name)
+      .Bind(__alarm_info->dst_service_name_mod)
+      .Bind(__alarm_info->alarm_id);
+
+  auto r = alarmmgr_db->Exec(q);
+  if (!r) {
+    LOGE("db.Exec() failed: %s", static_cast<const char*>(r));
+    return false;
+  }
+
+  return true;
+}
+
+bool DeleteAlarms(alarm_id_t alarm_id) {
+  auto q = tizen_base::Database::Sql(
+      "DELETE FROM alarmmgr WHERE alarm_id=?")
+      .Bind(alarm_id);
+
+  auto r = alarmmgr_db->Exec(q);
+  if (!r) {
+    LOGE("db.Exec failed : %s", static_cast<const char*>(r));
+    return false;
+  }
+
+  return true;
+}
+
+void LoadAlarmsFromDb() {
+  if (!alarmmgr_db)
+    return;
+
+  auto r = alarmmgr_db->Exec({ "SELECT * FROM alarmmgr" });
+  if (!r) {
+    LOGE("db.Exec() failed: %s", static_cast<const char*>(r));
+    return;
+  }
+
+  for (const auto& rec : r) {
+    int col_idx = 0;
+    __alarm_info_t* __alarm_info = reinterpret_cast<__alarm_info_t*>(
+        calloc(1, sizeof(__alarm_info_t)));
+
+    if (G_UNLIKELY(__alarm_info == nullptr)) {
+      LOGE("Memory allocation failed.");
+      break;
+    }
+
+    base_info_t* base_info = (base_info_t *) &(__alarm_info->base_info);
+    alarm_date_t* start = &base_info->start;
+    alarm_mode_t* mode = &base_info->mode;
+    __alarm_info->alarm_id = static_cast<int>(rec.Get(col_idx++));
+    int64_t start_64 = static_cast<int64_t>(rec.Get(col_idx++));
+    __alarm_info->start = static_cast<time_t>(start_64);
+    int64_t end_64 = static_cast<int64_t>(rec.Get(col_idx++));
+    __alarm_info->end = static_cast<time_t>(end_64);
+    __alarm_info->uid = static_cast<int>(rec.Get(col_idx++));
+    __alarm_info->global = static_cast<int>(rec.Get(col_idx++));
+    int is_disabled = static_cast<int>(rec.Get(col_idx++));
+    __alarm_info->caller_pkgid = GetCString(col_idx++, rec);
+    __alarm_info->callee_pkgid = GetCString(col_idx++, rec);
+    __alarm_info->app_unique_name = GetCString(col_idx++, rec);
+    __alarm_info->app_service_name = GetCString(col_idx++, rec);
+    __alarm_info->app_service_name_mod = GetCString(col_idx++, rec);
+    __alarm_info->bundle = GetCString(col_idx++, rec);
+    int noti_len = static_cast<int>(rec.Get(col_idx++));
+    noti_len = noti_len ? noti_len : strlen("null");
+    __alarm_info->noti = GetCString(col_idx++, rec, noti_len);
+    start->year = static_cast<int>(rec.Get(col_idx++));
+    start->month = static_cast<int>(rec.Get(col_idx++));
+    start->day = static_cast<int>(rec.Get(col_idx++));
+    start->hour = static_cast<int>(rec.Get(col_idx++));
+    start->min = static_cast<int>(rec.Get(col_idx++));
+    start->sec = static_cast<int>(rec.Get(col_idx++));
+    base_info->msec = static_cast<int>(rec.Get(col_idx++));
+    mode->u_interval.day_of_week = static_cast<int>(rec.Get(col_idx++));
+    mode->repeat = static_cast<alarm_repeat_mode_t>(static_cast<int>(rec.Get(col_idx++)));
+    base_info->alarm_type = static_cast<int>(rec.Get(col_idx++));
+    int64_t reserved_info_64 = static_cast<int64_t>(rec.Get(col_idx++));
+    base_info->reserved_info = static_cast<time_t>(reserved_info_64);
+    __alarm_info->dst_service_name = GetCString(col_idx++, rec);
+    __alarm_info->dst_service_name_mod = GetCString(col_idx++, rec);
+
+    if (is_disabled) {
+      _alarm_set_next_duetime(__alarm_info);
+      g_disabled_alarm_list = g_slist_append(g_disabled_alarm_list, __alarm_info);
+      LOGW("Save alarm_id[%d] caller[%s] callee[%s]", __alarm_info->alarm_id,
+          __alarm_info->caller_pkgid, __alarm_info->callee_pkgid);
+    } else {
+      _alarm_set_next_duetime(__alarm_info);
+      alarm_context.alarms = g_slist_append(alarm_context.alarms, __alarm_info);
+    }
+  }
+
+  _alarm_schedule();
+}
+
+int GetDbPathForAllInfo(uid_t uid, char** db_path) {
+  char db_path_tmp[50] = {0,};
+  constexpr const char query_for_creating_table[] =
+      "CREATE TABLE alarmmgr_tool (alarm_id integer primary key, "
+      "duetime_epoch integer, duetime text, start_epoch integer, "
+      "end_epoch integer, global integer, caller_pkgid text, "
+      "callee_pkgid text, app_unique_name text, app_service_name text, "
+      "dst_service_name text, day_of_week integer, repeat integer, "
+      "alarm_type integer)";
+  constexpr const char query_for_deleting_table[] =
+      "DROP TABLE alarmmgr_tool";
+  time_t current_time = 0;
+  struct tm current_tm;
+  int index = 0;
+
+  time(&current_time);
+  tzset();
+  localtime_r(&current_time, &current_tm);
+  snprintf(db_path_tmp, sizeof(db_path_tmp),
+      "/tmp/alarmmgr_%d%d%d_%02d%02d%02d.db",
+      current_tm.tm_year + 1900, current_tm.tm_mon + 1,
+      current_tm.tm_mday, current_tm.tm_hour, current_tm.tm_min,
+      current_tm.tm_sec);
+
+  *db_path = strdup(db_path_tmp);
+  if (*db_path == nullptr) {
+    LOGE("Out of memory");
+    return ERR_ALARM_SYSTEM_FAIL;
+  }
+
+  tizen_base::Database alarmmgr_tool_db(db_path_tmp,
+      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
+      DbBusyHandler);
+  auto r = alarmmgr_tool_db.Exec({ query_for_deleting_table });
+  if (!r)
+    LOGE("Deleting the table failed : %s", static_cast<const char*>(r));
+
+  alarmmgr_tool_db.OneStepExec({ query_for_creating_table });
+  for (GSList* gs_iter = alarm_context.alarms; gs_iter != nullptr;
+      gs_iter = g_slist_next(gs_iter)) {
+    __alarm_info_t* entry = reinterpret_cast<__alarm_info_t*>(
+        gs_iter->data);
+    if (uid >= REGULAR_UID_MIN && entry->uid != uid)
+      continue;
+    ++index;
+    SECURE_LOGD("#%d alarm id[%d] app_name[%s] duetime[%ld]",
+        index, entry->alarm_id, entry->app_unique_name, entry->start);
+
+    base_info_t *base_info = (base_info_t *) &(entry->base_info);
+    alarm_mode_t *mode = &base_info->mode;
+
+    auto q = tizen_base::Database::Sql(
+        "INSERT INTO alarmmgr_tool( alarm_id, duetime_epoch, duetime, "
+        "start_epoch, end_epoch, global, caller_pkgid, callee_pkgid, "
+        "app_unique_name, app_service_name, dst_service_name, day_of_week, "
+        "repeat, alarm_type) "
+        "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
+        .Bind(entry->alarm_id)
+        .Bind(static_cast<int>(entry->due_time))
+        .Bind(ctime(&(entry->due_time)))
+        .Bind(static_cast<int>(entry->start))
+        .Bind(static_cast<int>(entry->end))
+        .Bind((bool)entry->global)
+        .Bind(entry->caller_pkgid)
+        .Bind(entry->callee_pkgid)
+        .Bind(entry->app_unique_name)
+        .Bind(entry->app_service_name)
+        .Bind(entry->dst_service_name)
+        .Bind(mode->u_interval.day_of_week)
+        .Bind(mode->repeat)
+        .Bind(entry->base_info.alarm_type);
+    auto r = alarmmgr_tool_db.Exec(q);
+    if (!r)
+      LOGE("db.Exec failed : %s", static_cast<const char*>(r));
+  }
+
+  return ALARMMGR_RESULT_SUCCESS;
+}
+
+gboolean UpdateRelativeAlarms(gpointer user_data) {
+  auto guard = alarmmgr_db->CreateTransactionGuard();
+
+  for (GSList* iter = alarm_context.alarms; iter != nullptr;
+      iter = g_slist_next(iter)) {
+    __alarm_info_t* entry = reinterpret_cast<__alarm_info_t*>(iter->data);
+    base_info_t* base_info = &(entry->base_info);
+    if (base_info->alarm_type & ALARM_TYPE_RELATIVE)
+      _update_alarms(entry);
+  }
+
+  guard.Commit();
+  return true;
+}
+
+bool AlarmSetGlobalToDb(__alarm_info_t* alarm_info, bool global) {
+  auto q = tizen_base::Database::Sql(
+      "UPDATE alarmmgr SET global=? WHERE alarm_id=?")
+      .Bind(alarm_info->global)
+      .Bind(alarm_info->alarm_id);
+
+  auto r = alarmmgr_db->Exec(q);
+  if (!r) {
+    LOGE("db.Exec failed : %s", static_cast<const char*>(r));
+    return false;
+  }
+
+  return true;
+}
+
+void UpdateDbForDisabledAlarm(alarm_id_t alarm_id, bool disabled) {
+  LOGW("Update (%d) is_disabled to (%d)", alarm_id, disabled);
+  auto q = tizen_base::Database::Sql(
+      "UPDATE alarmmgr SET is_disabled=? WHERE alarm_id=?")
+      .Bind(disabled)
+      .Bind(alarm_id);
+
+  auto r = alarmmgr_db->Exec(q);
+  if (!r)
+    LOGE("db.Exec failed : %s", static_cast<const char*>(r));
+}
+
+bool InitializeDb() {
+  try {
+    alarmmgr_db.reset(new tizen_base::Database(GetAlarmDbFile(),
+        SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, DbBusyHandler));
+  } catch (const tizen_base::DbException& e) {
+    LOGE("Failed to open [%s]. error: %s", GetAlarmDbFile(), e.msg());
+    if (e.code() == SQLITE_CORRUPT)
+      RecoverDb();
+    else
+      return false;
+  }
+
+  bool is_exist = false;
+  int ret = CheckAlarmMgrTable(*alarmmgr_db, &is_exist);
+  if (ret != SQLITE_OK) {
+    if (ret == SQLITE_CORRUPT) {
+      RecoverDb();
+    } else {
+      alarmmgr_db.reset();
+      return false;
+    }
+  }
+
+  auto r = alarmmgr_db->Exec({QUERY_CREATE_TABLE_ALARMMGR});
+
+  if (!r) {
+    LOGE("Don't execute query = %s, error message = %s",
+        QUERY_CREATE_TABLE_ALARMMGR, static_cast<const char*>(r));
+    if (static_cast<int>(r) == SQLITE_CORRUPT ||
+        static_cast<int>(r) == SQLITE_NOTADB) {
+      RecoverDb();
+      alarmmgr_db.reset();
+    }
+
+    return false;
+  }
+
+  if (is_exist == false) {
+    if (CreateDbVersion() != 0) {
+      alarmmgr_db.reset();
+      return false;
+    }
+
+    if (UpdateDbVersion(SCHEMA_VERSION_LATEST) != 0) {
+      alarmmgr_db.reset();
+      return false;
+    }
+  } else {
+    ret = DbUpgrade();
+    if (ret) {
+      LOGE("Failed db's migration");
+      alarmmgr_db.reset();
+      return false;
+    }
+  }
+
+  ret = sqlite3_exec(alarmmgr_db->GetRaw(), "PRAGMA integrity_check",
+      CheckCallback, nullptr, 0);
+  if (ret != SQLITE_OK || is_db_corrupted) {
+    LOGE("Loss alarm db's integrity");
+    return ReopenDb();
+  }
+
+  return true;
+}
+
+bool SetLatestSettime(time_t settime) {
+  auto q = tizen_base::Database::Sql(
+      "INSERT OR REPLACE INTO alarmmgr( alarm_id, start, "
+      "end, uid, global, is_disabled, caller_pkgid, callee_pkgid, "
+      "app_unique_name, app_service_name, app_service_name_mod, bundle, "
+      "noti_len, noti, year, month, day, hour, min, sec, msec, day_of_week, "
+      "repeat, alarm_type, reserved_info, dst_service_name, "
+      "dst_service_name_mod) "
+      "VALUES (?, ?, 0, 0, 0, 1, 'n', 'n', 'n', 'n', 'n', 'n', 0, 'n', "
+      "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'n', 'n')")
+      .Bind(LATEST_SETTIME_ID)
+      .Bind(static_cast<int64_t>(settime));
+
+  if (!alarmmgr_db)
+    return false;
+
+  auto r = alarmmgr_db->Exec(q);
+  if (!r) {
+    LOGE("db.Exec failed : %s", static_cast<const char*>(r));
+    return false;
+  }
+
+  LOGD("latest_settime : %ld", settime);
+  return true;
+}
+
+bool GetLatestSettime(time_t* settime) {
+  auto q = tizen_base::Database::Sql(
+      "SELECT start FROM alarmmgr WHERE alarm_id=?")
+      .Bind(LATEST_SETTIME_ID);
+
+  if (!alarmmgr_db)
+    return false;
+
+  auto r = alarmmgr_db->Exec(q);
+  if (!r) {
+    LOGE("db.Exec failed : %s", static_cast<const char*>(r));
+    return false;
+  }
+
+  auto rec = r.GetFirstRecord();
+  if (!rec) {
+    LOGE("latest_settime is not set");
+    return false;
+  }
+
+  *settime = static_cast<int64_t>(rec->Get(0));
+  LOGD("latest_settime : %ld", *settime);
+  return true;
+}
+
+}  // namespace
+
+bool _save_alarms(__alarm_info_t* __alarm_info) {
+  try {
+    return SaveAlarms(__alarm_info);
+  } catch (const tizen_base::DbException& e) {
+    LOGE("Exception: %s", e.msg());
+    return false;
+  } catch (const std::exception& e) {
+    LOGE("Exception: %s", e.what());
+    return false;
+  }
+}
+
+bool _update_alarms(__alarm_info_t* __alarm_info) {
+  try {
+    return UpdateAlarms(__alarm_info);
+  } catch (const tizen_base::DbException& e) {
+    LOGE("Exception: %s", e.msg());
+    return false;
+  } catch (const std::exception& e) {
+    LOGE("Exception: %s", e.what());
+    return false;
+  }
+}
+
+bool _delete_alarms(alarm_id_t alarm_id) {
+  try {
+    return DeleteAlarms(alarm_id);
+  } catch (const tizen_base::DbException& e) {
+    LOGE("Exception: %s", e.msg());
+    return false;
+  } catch (const std::exception& e) {
+    LOGE("Exception: %s", e.what());
+    return false;
+  }
+}
+
+void _load_alarms_from_db() {
+  try {
+    LoadAlarmsFromDb();
+  } catch (const tizen_base::DbException& e) {
+    LOGE("Exception: %s", e.msg());
+  } catch (const std::exception& e) {
+    LOGE("Exception: %s", e.what());
+  }
+}
+
+int _get_db_path_for_all_info(uid_t uid, char** db_path) {
+  try {
+    return GetDbPathForAllInfo(uid, db_path);
+  } catch (const tizen_base::DbException& e) {
+    LOGE("Exception: %s", e.msg());
+    return ERR_ALARM_SYSTEM_FAIL;
+  } catch (const std::exception& e) {
+    LOGE("Exception: %s", e.what());
+    return ERR_ALARM_SYSTEM_FAIL;
+  }
+}
+
+gboolean _update_relative_alarms(gpointer user_data) {
+  try {
+    return UpdateRelativeAlarms(user_data);
+  } catch (const tizen_base::DbException& e) {
+    LOGE("Exception: %s", e.msg());
+    return false;
+  } catch (const std::exception& e) {
+    LOGE("Exception: %s", e.what());
+    return false;
+  }
+}
+
+bool _alarm_set_global_to_db(__alarm_info_t* alarm_info, bool global) {
+  try {
+    return AlarmSetGlobalToDb(alarm_info, global);
+  } catch (const tizen_base::DbException& e) {
+    LOGE("Exception: %s", e.msg());
+    return false;
+  } catch (const std::exception& e) {
+    LOGE("Exception: %s", e.what());
+    return false;
+  }
+}
+
+void _update_db_for_disabled_alarm(alarm_id_t alarm_id, bool disabled) {
+  try {
+    UpdateDbForDisabledAlarm(alarm_id, disabled);
+  } catch (const tizen_base::DbException& e) {
+    LOGE("Exception: %s", e.msg());
+  } catch (const std::exception& e) {
+    LOGE("Exception: %s", e.what());
+  }
+}
+
+bool _initialize_db() {
+  try {
+    return InitializeDb();
+  } catch (const tizen_base::DbException& e) {
+    LOGE("Exception: %s", e.msg());
+    return false;
+  } catch (const std::exception& e) {
+    LOGE("Exception: %s", e.what());
+    return false;
+  }
+}
+
+bool _set_latest_settime(time_t settime) {
+  try {
+    return SetLatestSettime(settime);
+  } catch (const tizen_base::DbException& e) {
+    LOGE("Exception: %s", e.msg());
+    return false;
+  } catch (const std::exception& e) {
+    LOGE("Exception: %s", e.what());
+    return false;
+  }
+}
+
+bool _get_latest_settime(time_t* settime) {
+  try {
+    return GetLatestSettime(settime);
+  } catch (const tizen_base::DbException& e) {
+    LOGE("Exception: %s", e.msg());
+    return false;
+  } catch (const std::exception& e) {
+    LOGE("Exception: %s", e.what());
+    return false;
+  }
+}
index 02c18ba71215428f41d24e186805a347d5a2bc3d..e8ab5b6e45c721b267c49a4c665f3924bad6be70 100644 (file)
  */
 #pragma once
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #include <glib.h>
 
 #include "alarm.h"
 #include "alarm-internal.h"
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 bool _alarm_set_global_to_db(__alarm_info_t *alarm_info, bool global);
 bool _delete_alarms(alarm_id_t alarm_id);
 int _get_db_path_for_all_info(uid_t uid, char** db_path);
@@ -36,8 +36,6 @@ void _update_db_for_disabled_alarm(alarm_id_t alarm_id, bool disabled_by_ups);
 bool _get_latest_settime(time_t *settime);
 bool _set_latest_settime(time_t settime);
 
-int migration_func_version_1(void);
-
 #ifdef __cplusplus
 }
 #endif
index cf9b70719a7beaf9b07579f281112c6adbbd4a20..7a1944024bf1a4f577bb2018f6c30165d6dc1cea 100644 (file)
@@ -3197,6 +3197,7 @@ void _alarm_initialize()
        if (_initialize_db() == false) {
                LOGE("_initialize_db failed, "
                                        "alarm cannot be stored to database.\n");
+               exit(1);
        }
 
        if (__load_module(PATH_LIB_ALARMMGR_PLUGIN) != 0) {
index 38f185e9afe35fa767fbb1d7da7e27c96ab4980f..84ce9aad6a67d20955d262de8d515e23eee02846 100755 (executable)
@@ -4,7 +4,7 @@ INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/server)
 INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/mock)
 
 SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fpie")
-SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fpie")
+SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fpie -std=c++17")
 
 ADD_DEFINITIONS("-DPLUGIN_LIB_DIR=\"${LIB_INSTALL_DIR}\"")
 
@@ -14,8 +14,7 @@ SET(GTEST_SERVER_SRCS ${CMAKE_SOURCE_DIR}/server/alarm-manager.c
        ${CMAKE_SOURCE_DIR}/server/alarm-manager-timer.c
        ${CMAKE_SOURCE_DIR}/server/alarm-manager-schedule.c
        ${CMAKE_SOURCE_DIR}/server/alarm-manager-dbus.c
-       ${CMAKE_SOURCE_DIR}/server/alarm-manager-db.c
-       ${CMAKE_SOURCE_DIR}/server/alarm-manager-db-migration.c)
+       ${CMAKE_SOURCE_DIR}/server/alarm-manager-db.cc)
 
 AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR}/ GTEST_TEST_SRCS)
 AUX_SOURCE_DIRECTORY(${CMAKE_SOURCE_DIR}/mock GTEST_TEST_SRCS)
index 4e23d48aa6c3901bd1b4532f2ca3a62f54ebcfc7..f12030bbe10b0d73826260e139ba9df44103c0cd 100644 (file)
@@ -27,6 +27,7 @@
 #include "dbus_mock.h"
 #include "pkgmgr_info_mock.h"
 #include "test_fixture.h"
+#include "tzplatform_config_mock.h"
 #include "unittest.h"
 
 using ::testing::_;
@@ -77,7 +78,8 @@ GDBusNodeInfo* __g_dbus_node_info_new_for_xml_fake(const gchar* xml,
 
 class Mocks : virtual public ::testing::NiceMock<AulMock>,
     virtual public ::testing::NiceMock<DbusMock>,
-    virtual public ::testing::NiceMock<PkgmgrInfoMock> {};
+    virtual public ::testing::NiceMock<PkgmgrInfoMock>,
+    virtual public ::testing::NiceMock<TzplatformConfigMock> {};
 }  // namespace
 
 class AlarmServerTest : public TestFixture {
@@ -89,6 +91,11 @@ class AlarmServerTest : public TestFixture {
 };
 
 TEST_F(AlarmServerTest, alarm_manager_alarm_create_p) {
+  EXPECT_CALL(GetMock<TzplatformConfigMock>(), tzplatform_mkpath(_, _))
+      .WillRepeatedly(Invoke([](enum tzplatform_variable id,
+          const char* path) {
+        return ".alarm_test.db";
+      }));
   EXPECT_CALL(GetMock<DbusMock>(), g_bus_get_sync(_, _, _))
       .WillRepeatedly(Invoke(__g_bus_get_sync_fake));
   EXPECT_CALL(GetMock<DbusMock>(), g_dbus_connection_signal_subscribe(_, _, _,
@@ -278,7 +285,7 @@ TEST_F(AlarmServerTest, alarm_manager_alarm_set_timezone_n) {
   EXPECT_EQ(ERR_ALARM_SYSTEM_FAIL, ret);
 }
 
-TEST_F(AlarmServerTest, alarm_manager_alarm_set_global_n) {
+TEST_F(AlarmServerTest, alarm_manager_alarm_set_global) {
   EXPECT_CALL(GetMock<PkgmgrInfoMock>(), pkgmgrinfo_pkginfo_is_global(_, _))
       .WillRepeatedly(
           Invoke([](pkgmgrinfo_pkginfo_h, bool *is_global) -> int {
@@ -295,7 +302,7 @@ TEST_F(AlarmServerTest, alarm_manager_alarm_set_global_n) {
   int ret = alarm_manager_alarm_create(param, 5001, getpid(), "sender", &alarm_id);
   GVariant* param2 = g_variant_new("(ib)", alarm_id, true);
   ret = alarm_manager_alarm_set_global(param2, 5001);
-  EXPECT_EQ(ERR_ALARM_SYSTEM_FAIL, ret);
+  EXPECT_EQ(ALARMMGR_RESULT_SUCCESS, ret);
 }
 
 TEST_F(AlarmServerTest, alarm_manager_alarm_get_global_n) {
index a66a56e5845f05c54c6d6163bef515a9066f50d9..8d1f3664fb6515237d0962f32748ed6a45f95608 100755 (executable)
@@ -19,8 +19,6 @@
 
 #include "unittest.h"
 
-#define LOG_INTERNAL
-
 #ifdef LOG_INTERNAL
 #include <dlog.h>