]> err.no Git - mapper/blob - src/db.c
Use g_snprintf
[mapper] / src / db.c
1 /*
2  * This file is part of mapper
3  *
4  * Copyright (C) 2007 Kaj-Michael Lang
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20
21 #include "config.h"
22
23 #include <glib.h>
24 #include <sqlite3.h>
25
26 #include "db.h"
27
28 sqlite3 *_db=NULL;
29 gchar *_mapper_db=NULL;
30
31 /**
32  * A simple check to test if a table exists
33  *
34  */
35 gboolean 
36 db_check(sqlite3 *db, const gchar *table)
37 {
38 gchar **pszResult;
39 guint nRow, nColumn;
40 gchar sql[64];
41
42 g_snprintf(sql, sizeof(sql),"select count(*) from %s", table);
43
44 if (SQLITE_OK != sqlite3_get_table(db, sql, &pszResult, &nRow, &nColumn, NULL))
45         return FALSE;
46
47 sqlite3_free_table(pszResult);
48 return TRUE;
49 }
50
51 /**
52  * Helper that execs a given prepared sql statment and resets clears bindings.
53  * return TRUE or FALSE depending on success of the query. 
54  *
55  */
56 gboolean
57 db_exec(sqlite3_stmt *sql)
58 {
59 gint r;
60
61 r=sqlite3_step(sql);
62 sqlite3_reset(sql);
63 sqlite3_clear_bindings(sql);
64
65 return (r==SQLITE_OK) ? TRUE : FALSE;
66 }
67
68 /**
69  * Close the database connection
70  *
71  */
72 gboolean 
73 db_close(sqlite3 **db)
74 {
75 if (db && *db) {
76         g_print("Closing database.\n");
77         sqlite3_close(*db);
78         *db=NULL;
79 }
80 return TRUE;
81 }
82
83 /**
84  * Connect to given sqlite database
85  *
86  */
87 gboolean 
88 db_connect(sqlite3 **db, const gchar *mapper_db)
89 {
90 if (db && *db) {
91         sqlite3_close(*db);
92         *db=NULL;
93 }
94
95 if (!mapper_db)
96         return FALSE;
97
98 if (SQLITE_OK!=(sqlite3_open(mapper_db, db))) {
99         sqlite3_close(*db);
100         *db=NULL;
101         return FALSE;
102 }
103
104 /* Use smaller cache as the IT does not have much memory to spare */
105 #ifdef WITH_DEVICE_770
106 sqlite3_exec(*db, "PRAGMA cache_size = 1000;", NULL, NULL, NULL);
107 #else
108 sqlite3_exec(*db, "PRAGMA cache_size = 8000;", NULL, NULL, NULL);
109 #endif
110
111 return TRUE;
112 }