Imported Upstream version 0.8
[platform/upstream/syncevolution.git] / src / backends / sqlite / SQLiteUtil.h
1 /*
2  * Copyright (C) 2007-2008 Patrick Ohly
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
18
19 #ifndef INCL_SQLITESYNCSOURCE
20 #define INCL_SQLITESYNCSOURCE
21
22 #ifdef ENABLE_SQLITE
23
24 #include <sqlite3.h>
25 #include "EvolutionSmartPtr.h"
26
27 #include <string>
28 using namespace std;
29
30 namespace vocl {
31     class VObject;
32 }
33
34 class SQLiteUnref {
35  public:
36     static void unref(sqlite3 *db) { sqlite3_close(db); }
37     static void unref(sqlite3_stmt *stmt) { sqlite3_finalize(stmt); }
38 };
39
40 typedef eptr<sqlite3_stmt, sqlite3_stmt, SQLiteUnref> sqliteptr;
41
42 /**
43  * This class implements access to SQLite database files:
44  * - opening the database file
45  * - error reporting
46  * - creating a database file
47  * - converting to and from a VObject via a simple property<->column name mapping
48  */
49 class SQLiteUtil
50 {
51   public:
52     /** information about the database mapping */
53     struct Mapping {
54         const char *colname;        /**< column name in SQL table */
55         const char *tablename;      /**< name of the SQL table which has this column */
56         const char *propname;       /**< optional: vcard/vcalendar property which corresponds to this */
57         int colindex;               /**< determined dynamically in open(): index of the column, -1 if not present */
58     };
59
60     const Mapping &getMapping(int i) { return m_mapping[i]; }
61
62     /**
63      * @param name        a name for the data source, used for error messages
64      * @param fileid      a descriptor which identifies the file to be opened:
65      *                    currently valid syntax is file:// followed by path
66      * @param mapping     array with database mapping, terminated by NULL colname
67      * @param schema      database schema to use when creating new databases, may be NULL
68      */
69     void open(const string &name,
70               const string &fileid,
71               const Mapping *mapping,
72               const char *schema);
73
74     void close();
75
76     /**
77      * throw error for a specific sqlite3 operation on m_db
78      * @param operation   a description of the operation which failed
79      */
80     void throwError(const string &operation);
81
82     /**
83      * wrapper around sqlite3_prepare() which operates on the current
84      * database and throws an error if the call fails
85      *
86      * @param sqlfmt         printf-style format string for query, followed by parameters for sprintf
87      */
88     sqlite3_stmt *prepareSQL(const char *sqlfmt, ...);
89
90     /**
91      * wrapper around sqlite3_prepare() which operates on the current
92      * database and throws an error if the call fails
93      *
94      * @param sql       preformatted SQL statement(s)
95      * @param nextsql   pointer to next statement in sql
96      */
97     sqlite3_stmt *prepareSQLWrapper(const char *sql, const char **nextsql = NULL);
98
99
100     /** checks the result of an sqlite3 call, throws an error if faulty, otherwise returns the result */
101     int checkSQL(int res, const char *operation = "SQLite call") {
102         if (res != SQLITE_OK && res != SQLITE_ROW && res != SQLITE_DONE) {
103             throwError(operation);
104         }
105         return res;
106     }
107
108     /** type used for row keys */
109     typedef long long key_t;
110     string toString(key_t key) { char buffer[32]; sprintf(buffer, "%lld", key); return buffer; }
111 #define SQLITE3_COLUMN_KEY sqlite3_column_int64
112
113     /** return row ID for a certain row */
114     key_t findKey(const char *database, const char *keyname, const char *key);
115
116     /** return a specific column for a row identified by a certain key column as text, returns default text if not found */
117     string findColumn(const char *database, const char *keyname, const char *key, const char *column, const char *def);
118
119     /** a wrapper for sqlite3_column_test() which will check for NULL and returns default text instead */
120     string getTextColumn(sqlite3_stmt *stmt, int col, const char *def = "");
121
122     typedef unsigned long syncml_time_t;
123     /** transform column to same time base as used by SyncML libary (typically time()) */
124     syncml_time_t getTimeColumn(sqlite3_stmt *stmt, int col);
125
126     /** convert time to string */
127     static string time2str(syncml_time_t t);
128
129     /** copies all columns which directly map to a property into the vobj */
130     void rowToVObject(sqlite3_stmt *stmt, vocl::VObject &vobj);
131
132     /**
133      * Creates a SQL INSERT INTO <tablename> ( <cols> ) VALUES ( <values> )
134      * statement and binds all rows/values that map directly from the vobj.
135      *
136      * @param numparams      number of ? placeholders in values; the caller has
137      *                       to bind those before executing the statement
138      */
139     sqlite3_stmt *vObjectToRow(vocl::VObject &vobj,
140                                const string &tablename,
141                                int numparams,
142                                const string &cols,
143                                const string &values);
144
145  private:
146     /* copy of open() parameters */
147     arrayptr<Mapping> m_mapping;
148     string m_name;
149     string m_fileid;
150
151     /** current database */
152     eptr<sqlite3, sqlite3, SQLiteUnref> m_db;
153 };
154
155 #endif // ENABLE_SQLITE
156 #endif // INCL_SQLITESYNCSOURCE