source: gsdl/trunk/lib/sqliteclass.cpp@ 15637

Last change on this file since 15637 was 15637, checked in by mdewsnip, 16 years ago

(Adding new DB support) Added a sqltableexists() function to prevent errors re-creating the "data" table.

File size: 9.8 KB
Line 
1/**********************************************************************
2 *
3 * sqliteclass.cpp --
4 * Copyright (C) 2008 DL Consulting Ltd
5 *
6 * A component of the Greenstone digital library software
7 * from the New Zealand Digital Library Project at the
8 * University of Waikato, New Zealand.
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 *
24 *********************************************************************/
25
26#include "sqliteclass.h"
27#include "unitool.h"
28
29
30#define SQLITE_MAX_RETRIES 8
31
32
33sqliteclass::~sqliteclass()
34{
35 closedatabase();
36}
37
38
39// returns true if opened
40bool sqliteclass::opendatabase(const text_t &filename, int mode, int num_retrys,
41#ifdef __WIN32__
42 bool need_filelock
43#else
44 bool
45#endif
46 )
47{
48 // Check if we've already got the database open
49 if (sqlitefile != NULL)
50 {
51 if (openfile == filename) return true;
52 else closedatabase();
53 }
54
55 char *filename_cstr = filename.getcstr();
56 sqlite3_open(filename_cstr, &sqlitefile);
57 delete[] filename_cstr;
58
59 if (sqlitefile == NULL)
60 {
61 (*logout) << "ERROR: sqliteclass::opendatabase() failed on: " << filename << "\n";
62 return false;
63 }
64
65 if ((mode == DB_WRITER || mode == DB_WRITER_CREATE) && !sqltableexists("data"))
66 {
67 sqlexec("CREATE TABLE data (key TEXT, value TEXT, PRIMARY KEY(key))");
68 }
69
70 return true;
71}
72
73
74void sqliteclass::closedatabase()
75{
76 if (sqlitefile == NULL) return;
77
78 sqlite3_close(sqlitefile);
79 sqlitefile = NULL;
80 openfile.clear();
81}
82
83
84// returns true on success
85bool sqliteclass::getinfo(const text_t& key, infodbclass &info)
86{
87 text_t sql_cmd = "SELECT value FROM data WHERE key='" + key + "'";
88 vector<text_tmap> sql_results;
89 if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
90 {
91 return false;
92 }
93
94 text_tmap sql_result = sql_results[0];
95 text_t sql_result_value = sql_result["value"];
96 text_t::iterator sql_result_value_iterator = sql_result_value.begin();
97 text_t ikey, ivalue;
98 info.clear();
99 while (getinfoline(sql_result_value_iterator, sql_result_value.end(), ikey, ivalue))
100 {
101 info.addinfo(ikey, ivalue);
102 }
103
104 return true;
105}
106
107
108// returns true if exists
109bool sqliteclass::exists(const text_t& key)
110{
111 text_t sql_cmd = "SELECT value FROM data WHERE key='" + key + "'";
112 vector<text_tmap> sql_results;
113 if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
114 {
115 return false;
116 }
117
118 return true;
119}
120
121
122// returns true on success
123bool sqliteclass::setinfo(const text_t &key, const infodbclass &info)
124{
125 text_t subkey;
126 text_t data;
127
128 // get all the keys and values
129 infodbclass::const_iterator info_here = info.begin();
130 infodbclass::const_iterator info_end = info.end();
131 while (info_here != info_end) {
132 // add the key
133 subkey.clear();
134 subkey.push_back('<');
135 text_t::const_iterator subkey_here = (*info_here).first.begin();
136 text_t::const_iterator subkey_end = (*info_here).first.end();
137 while (subkey_here != subkey_end) {
138 if (*subkey_here == '>') {
139 subkey.push_back('\\'); subkey.push_back('>');
140 } else if (*subkey_here == '\n') {
141 subkey.push_back('\\'); subkey.push_back('n');
142 } else if (*subkey_here == '\r') {
143 subkey.push_back('\\'); subkey.push_back('r');
144 } else if (*subkey_here == '\\') {
145 subkey.push_back('\\'); subkey.push_back('\\');
146 } else {
147 subkey.push_back (*subkey_here);
148 }
149 ++subkey_here;
150 }
151 subkey.push_back('>');
152
153 // add the values
154 text_tarray::const_iterator subvalue_here = (*info_here).second.begin();
155 text_tarray::const_iterator subvalue_end = (*info_here).second.end();
156 while (subvalue_here != subvalue_end) {
157 data += subkey;
158
159 text_t::const_iterator thissubvalue_here = (*subvalue_here).begin();
160 text_t::const_iterator thissubvalue_end = (*subvalue_here).end();
161 while (thissubvalue_here != thissubvalue_end) {
162 if (*thissubvalue_here == '>') {
163 data.push_back('\\'); data.push_back('>');
164 } else if (*thissubvalue_here == '\n') {
165 data.push_back('\\'); data.push_back('n');
166 } else if (*thissubvalue_here == '\r') {
167 data.push_back('\\'); data.push_back('r');
168 } else if (*thissubvalue_here == '\\') {
169 data.push_back('\\'); data.push_back('\\');
170 } else {
171 data.push_back (*thissubvalue_here);
172 }
173
174 ++thissubvalue_here;
175 }
176
177 data.push_back('\n');
178 ++subvalue_here;
179 }
180
181 ++info_here;
182 }
183
184 // We need to do either an INSERT or UPDATE depending on whether the key already exists
185 if (!exists(key))
186 {
187 text_t sql_cmd = "INSERT INTO data (key, value) VALUES ('" + key + "', '" + data + "')";
188 return sqlexec(sql_cmd);
189 }
190 else
191 {
192 text_t sql_cmd = "UPDATE data SET value='" + data + "' WHERE key='" + key + "'";
193 return sqlexec(sql_cmd);
194 }
195}
196
197
198void sqliteclass::deletekey (const text_t &key)
199{
200 text_t sql_cmd = "DELETE FROM data WHERE key='" + key + "'";
201 sqlexec(sql_cmd);
202}
203
204
205text_tarray sqliteclass::getkeys ()
206{
207 text_tarray keys;
208
209 // Get all the entries in the "key" column of the table
210 text_t sql_cmd = "SELECT key FROM data";
211 vector<text_tmap> sql_results;
212 if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
213 {
214 return keys;
215 }
216
217 // Iterate through the keys and add them to the array to be returned
218 vector<text_tmap>::iterator sql_results_iterator = sql_results.begin();
219 while (sql_results_iterator != sql_results.end())
220 {
221 text_tmap sql_result = (*sql_results_iterator);
222 keys.push_back(sql_result["key"]);
223 sql_results_iterator++;
224 }
225
226 return keys;
227}
228
229
230// returns true on success
231bool sqliteclass::getinfoline (text_t::iterator &here, text_t::iterator end,
232 text_t &key, text_t &value)
233{
234 key.clear();
235 value.clear();
236
237 // ignore white space
238 while (here != end && is_unicode_space (*here)) ++here;
239
240 // get the '<'
241 if (here == end || *here != '<') return false;
242 ++here;
243
244 // get the key
245 while (here != end && *here != '>') {
246 key.push_back(*here);
247 ++here;
248 }
249
250 // get the '>'
251 if (here == end || *here != '>') return false;
252 ++here;
253
254 // get the value
255 while (here != end && *here != '\n') {
256 if (*here == '\\') {
257 // found escape character
258 ++here;
259 if (here != end) {
260 if (*here == 'n') value.push_back ('\n');
261 else if (*here == 'r') value.push_back ('\r');
262 else value.push_back(*here);
263 }
264
265 } else {
266 // a normal character
267 value.push_back(*here);
268 }
269
270 ++here;
271 }
272
273 return true;
274}
275
276
277// ----------------------------------------------------------------------------------------
278// CORE SQL FUNCTIONS
279// ----------------------------------------------------------------------------------------
280
281// sqlexec simply executes the given sql statement - it doesn't obtain a
282// result set - returns true if the sql statement was executed successfully
283bool sqliteclass::sqlexec(const text_t &sql_cmd)
284{
285 if (sqlitefile == NULL) return false;
286
287 char *sql_cmd_cstr = sql_cmd.getcstr();
288
289 int rv = 0;
290 int tries = 0;
291 while ((rv = sqlite3_exec(sqlitefile, sql_cmd_cstr, NULL, NULL, NULL)) == SQLITE_BUSY)
292 {
293 sleep(1000);
294 tries++;
295 if (tries > SQLITE_MAX_RETRIES)
296 {
297 outconvertclass text_t2ascii;
298 (*logout) << text_t2ascii << "max_retries exceeded for sql query: " << sql_cmd << "\n";
299 break;
300 }
301 }
302
303 delete[] sql_cmd_cstr;
304
305 if (rv == SQLITE_OK) return true;
306
307 // sqlite3_exec failed - return false
308 outconvertclass text_t2ascii;
309 (*logout) << text_t2ascii << "Error executing sql statement: " << sql_cmd << "\n";
310 return false;
311}
312
313
314// callback functions for sqlgetarray
315static int sqlgetarray_callback(void *res, int numcols, char **vals, char **columnnames)
316{
317 vector<text_tmap> *result = (vector<text_tmap>*) res;
318 text_tmap row;
319
320 for (int i = 0; i < numcols; i++)
321 {
322 row[columnnames[i]] = "";
323 // vals[i] will be NULL if set to a NULL db value
324 if (vals[i])
325 {
326 row[columnnames[i]] = vals[i];
327 }
328 }
329
330 result->push_back(row);
331 return 0;
332}
333
334
335// sqlgetarray executes sql and returns the result set in sql_results
336bool sqliteclass::sqlgetarray(const text_t &sql_cmd, vector<text_tmap> &sql_results)
337{
338 if (sqlitefile == NULL) return false;
339
340 char *sql_cmd_cstr = sql_cmd.getcstr();
341 sql_results.erase(sql_results.begin(), sql_results.end());
342
343 int rv = 0;
344 int tries = 0;
345 while ((rv = sqlite3_exec(sqlitefile, sql_cmd_cstr, sqlgetarray_callback, &sql_results, NULL)) == SQLITE_BUSY)
346 {
347 sleep(1000);
348 tries++;
349 if (tries > SQLITE_MAX_RETRIES)
350 {
351 outconvertclass text_t2ascii;
352 (*logout) << text_t2ascii << "max_retries exceeded for sql query: " << sql_cmd << "\n";
353 break;
354 }
355 }
356
357 delete[] sql_cmd_cstr;
358
359 if (rv == SQLITE_OK) return true;
360
361 // sqlite3_exec failed - return empty result set
362 outconvertclass text_t2ascii;
363 (*logout) << text_t2ascii << "Error executing sql statement: " << sql_cmd << "\n";
364 return false;
365}
366
367
368// returns true if exists
369bool sqliteclass::sqltableexists(const text_t &table_name)
370{
371 text_t sql_cmd = "SELECT * FROM sqlite_master WHERE tbl_name='" + table_name + "'";
372 vector<text_tmap> sql_results;
373 if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
374 {
375 return false;
376 }
377
378 return true;
379}
380
381
382// sleep for the given number of milliseconds
383void sleep(int m)
384{
385#ifdef __WIN32__
386 Sleep(m);
387#else
388 usleep(m);
389#endif
390}
Note: See TracBrowser for help on using the repository browser.