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

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

(Adding new DB support) Adding quick implementation of exists().

File size: 9.3 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 sqlitefile = NULL;
57 sqlite3_open(filename_cstr, &sqlitefile);
58 delete[] filename_cstr;
59
60 if (sqlitefile == NULL)
61 {
62 outconvertclass text_t2ascii;
63 (*logout) << text_t2ascii << "database open failed on: " << filename << "\n";
64 return false;
65 }
66
67 if (mode == DB_WRITER_CREATE)
68 {
69 sqlexec("CREATE TABLE data (key TEXT, value TEXT, PRIMARY KEY(key))");
70 }
71
72 return true;
73}
74
75
76void sqliteclass::closedatabase()
77{
78 if (sqlitefile == NULL) return;
79
80 sqlite3_close(sqlitefile);
81 sqlitefile = NULL;
82 openfile.clear();
83}
84
85
86// returns true on success
87bool sqliteclass::getinfo(const text_t& key, infodbclass &info)
88{
89 text_t sql_cmd = "SELECT value FROM data WHERE key='" + key + "'";
90 vector<text_tmap> sql_results;
91 if (sqlitefile == NULL || !sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
92 {
93 return false;
94 }
95
96 text_tmap sql_result = sql_results[0];
97 text_t sql_result_value = sql_result["value"];
98 text_t::iterator sql_result_value_iterator = sql_result_value.begin();
99 text_t ikey, ivalue;
100 info.clear();
101 while (getinfoline(sql_result_value_iterator, sql_result_value.end(), ikey, ivalue))
102 {
103 info.addinfo(ikey, ivalue);
104 }
105
106 return true;
107}
108
109
110// returns true if exists
111bool sqliteclass::exists(const text_t& key)
112{
113 text_t sql_cmd = "SELECT value FROM data WHERE key='" + key + "'";
114 vector<text_tmap> sql_results;
115 if (sqlitefile == NULL || !sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
116 {
117 return false;
118 }
119
120 return true;
121}
122
123
124// returns true on success
125bool sqliteclass::setinfo(const text_t &key, const infodbclass &info)
126{
127 if (sqlitefile == NULL) return false;
128
129 text_t subkey;
130 text_t data;
131
132 // get all the keys and values
133 infodbclass::const_iterator info_here = info.begin();
134 infodbclass::const_iterator info_end = info.end();
135 while (info_here != info_end) {
136 // add the key
137 subkey.clear();
138 subkey.push_back('<');
139 text_t::const_iterator subkey_here = (*info_here).first.begin();
140 text_t::const_iterator subkey_end = (*info_here).first.end();
141 while (subkey_here != subkey_end) {
142 if (*subkey_here == '>') {
143 subkey.push_back('\\'); subkey.push_back('>');
144 } else if (*subkey_here == '\n') {
145 subkey.push_back('\\'); subkey.push_back('n');
146 } else if (*subkey_here == '\r') {
147 subkey.push_back('\\'); subkey.push_back('r');
148 } else if (*subkey_here == '\\') {
149 subkey.push_back('\\'); subkey.push_back('\\');
150 } else {
151 subkey.push_back (*subkey_here);
152 }
153 ++subkey_here;
154 }
155 subkey.push_back('>');
156
157 // add the values
158 text_tarray::const_iterator subvalue_here = (*info_here).second.begin();
159 text_tarray::const_iterator subvalue_end = (*info_here).second.end();
160 while (subvalue_here != subvalue_end) {
161 data += subkey;
162
163 text_t::const_iterator thissubvalue_here = (*subvalue_here).begin();
164 text_t::const_iterator thissubvalue_end = (*subvalue_here).end();
165 while (thissubvalue_here != thissubvalue_end) {
166 if (*thissubvalue_here == '>') {
167 data.push_back('\\'); data.push_back('>');
168 } else if (*thissubvalue_here == '\n') {
169 data.push_back('\\'); data.push_back('n');
170 } else if (*thissubvalue_here == '\r') {
171 data.push_back('\\'); data.push_back('r');
172 } else if (*thissubvalue_here == '\\') {
173 data.push_back('\\'); data.push_back('\\');
174 } else {
175 data.push_back (*thissubvalue_here);
176 }
177
178 ++thissubvalue_here;
179 }
180
181 data.push_back('\n');
182 ++subvalue_here;
183 }
184
185 ++info_here;
186 }
187
188 outconvertclass text_t2ascii;
189 (*logout) << text_t2ascii << "Inserting for " << key << ":\n" << data << "\n";
190
191 text_t sql_cmd = "INSERT INTO data (key, value) VALUES ('" + key + "', '" + data + "')";
192 return sqlexec(sql_cmd);
193}
194
195
196void sqliteclass::deletekey (const text_t &key)
197{
198 text_t sql_cmd = "DELETE FROM data WHERE key='" + key + "'";
199 sqlexec(sql_cmd);
200}
201
202
203text_tarray sqliteclass::getkeys ()
204{
205 text_tarray keys;
206
207 // Get all the entries in the "key" column of the table
208 text_t sql_cmd = "SELECT key FROM data";
209 vector<text_tmap> sql_results;
210 if (sqlitefile == NULL || !sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
211 {
212 return keys;
213 }
214
215 // Iterate through the keys and add them to the array to be returned
216 vector<text_tmap>::iterator sql_results_iterator = sql_results.begin();
217 while (sql_results_iterator != sql_results.end())
218 {
219 text_tmap sql_result = (*sql_results_iterator);
220 keys.push_back(sql_result["key"]);
221 sql_results_iterator++;
222 }
223
224 return keys;
225}
226
227
228// returns true on success
229bool sqliteclass::getinfoline (text_t::iterator &here, text_t::iterator end,
230 text_t &key, text_t &value)
231{
232 key.clear();
233 value.clear();
234
235 // ignore white space
236 while (here != end && is_unicode_space (*here)) ++here;
237
238 // get the '<'
239 if (here == end || *here != '<') return false;
240 ++here;
241
242 // get the key
243 while (here != end && *here != '>') {
244 key.push_back(*here);
245 ++here;
246 }
247
248 // get the '>'
249 if (here == end || *here != '>') return false;
250 ++here;
251
252 // get the value
253 while (here != end && *here != '\n') {
254 if (*here == '\\') {
255 // found escape character
256 ++here;
257 if (here != end) {
258 if (*here == 'n') value.push_back ('\n');
259 else if (*here == 'r') value.push_back ('\r');
260 else value.push_back(*here);
261 }
262
263 } else {
264 // a normal character
265 value.push_back(*here);
266 }
267
268 ++here;
269 }
270
271 return true;
272}
273
274
275// ----------------------------------------------------------------------------------------
276// CORE SQL FUNCTIONS
277// ----------------------------------------------------------------------------------------
278
279// sqlexec simply executes the given sql statement - it doesn't obtain a
280// result set - returns true if the sql statement was executed successfully
281bool sqliteclass::sqlexec(const text_t &sql_cmd)
282{
283 char *sql_cmd_cstr = sql_cmd.getcstr();
284
285 int rv = 0;
286 int tries = 0;
287 while ((rv = sqlite3_exec(sqlitefile, sql_cmd_cstr, NULL, NULL, NULL)) == SQLITE_BUSY)
288 {
289 sleep(1000);
290 tries++;
291 if (tries > SQLITE_MAX_RETRIES)
292 {
293 outconvertclass text_t2ascii;
294 (*logout) << text_t2ascii << "max_retries exceeded for sql query: " << sql_cmd << "\n";
295 break;
296 }
297 }
298
299 delete[] sql_cmd_cstr;
300
301 if (rv == SQLITE_OK) return true;
302
303 // sqlite3_exec failed - return false
304 outconvertclass text_t2ascii;
305 (*logout) << text_t2ascii << "Error executing sql statement: " << sql_cmd << "\n";
306 return false;
307}
308
309
310// callback functions for sqlgetarray
311static int sqlgetarray_callback(void *res, int numcols, char **vals, char **columnnames)
312{
313 vector<text_tmap> *result = (vector<text_tmap>*) res;
314 text_tmap row;
315
316 for (int i = 0; i < numcols; i++)
317 {
318 row[columnnames[i]] = "";
319 // vals[i] will be NULL if set to a NULL db value
320 if (vals[i])
321 {
322 row[columnnames[i]] = vals[i];
323 }
324 }
325
326 result->push_back(row);
327 return 0;
328}
329
330
331// sqlgetarray executes sql and returns the result set in sql_results
332bool sqliteclass::sqlgetarray(const text_t &sql_cmd, vector<text_tmap> &sql_results)
333{
334 char *sql_cmd_cstr = sql_cmd.getcstr();
335 sql_results.erase(sql_results.begin(), sql_results.end());
336
337 int rv = 0;
338 int tries = 0;
339 while ((rv = sqlite3_exec(sqlitefile, sql_cmd_cstr, sqlgetarray_callback, &sql_results, NULL)) == SQLITE_BUSY)
340 {
341 sleep(1000);
342 tries++;
343 if (tries > SQLITE_MAX_RETRIES)
344 {
345 outconvertclass text_t2ascii;
346 (*logout) << text_t2ascii << "max_retries exceeded for sql query: " << sql_cmd << "\n";
347 break;
348 }
349 }
350
351 delete[] sql_cmd_cstr;
352
353 if (rv == SQLITE_OK) return true;
354
355 // sqlite3_exec failed - return empty result set
356 outconvertclass text_t2ascii;
357 (*logout) << text_t2ascii << "Error executing sql statement: " << sql_cmd << "\n";
358 return false;
359}
360
361
362// sleep for the given number of milliseconds
363void sleep(int m)
364{
365#ifdef __WIN32__
366 Sleep(m);
367#else
368 usleep(m);
369#endif
370}
Note: See TracBrowser for help on using the repository browser.