f2ddcbc988e65b5fda5ed40f0a79b1f35e06bec7
[platform/core/pim/calendar-service.git] / server / cal_server_schema.c
1 /*
2  * Calendar Service
3  *
4  * Copyright (c) 2012 - 2015 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 <unistd.h>
21 #include <fcntl.h>
22 #include <sys/stat.h>
23 #include <string.h>
24 #include <sqlite3.h>
25 #include <db-util.h>
26
27 #include "cal_internal.h"
28 #include "cal_typedef.h"
29 #include "cal_db.h"
30 #include "schema.h"
31
32 static inline int __remake_db_file(char* db_path)
33 {
34         int ret;
35         char *errmsg;
36         sqlite3 *db;
37         char db_file[CAL_STR_MIDDLE_LEN] = {0};
38
39         snprintf(db_file, sizeof(db_file), "%s/%s", db_path ? db_path : DB_PATH, CALS_DB_NAME);
40
41         ret = db_util_open(db_file, &db, 0);
42         if (SQLITE_OK != ret) {
43                 ERR("db_util_open() Fail(%d) ", ret);
44                 return -1;
45         }
46
47         ret = sqlite3_exec(db, schema_query, NULL, 0, &errmsg);
48         if (SQLITE_OK != ret) {
49                 ERR("sqlite3_exec() Fail[%s]", errmsg);
50                 sqlite3_free(errmsg);
51         }
52         db_util_close(db);
53         return 0;
54 }
55
56 static inline int __check_db_file(char* db_path)
57 {
58         int fd = -1;
59         char db_file[CAL_STR_MIDDLE_LEN] = {0,};
60         snprintf(db_file, sizeof(db_file), "%s/%s", db_path ? db_path : DB_PATH, CALS_DB_NAME);
61         DBG("[%s]", db_file);
62
63         fd = open(db_file, O_RDONLY);
64         if (fd < 0) {
65                 ERR("DB file(%s) is not exist(err:%d) ", db_file, fd);
66                 return -1;
67         }
68         close(fd);
69         return 0;
70 }
71
72 int cal_server_schema_check(void)
73 {
74         if (__check_db_file(NULL))
75                 __remake_db_file(NULL);
76         return 0;
77 }