source: gsdl/trunk/src/lib/sqlitedbclass.cpp@ 15907

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

(Adding new DB support) Adding a "sqlite_safe()" function for escaping any single quotes in values going into SQL statements, and applied this everywhere it might be required.

File size: 9.7 KB
Line 
1/**********************************************************************
2 *
3 * sqlitedbclass.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 "sqlitedbclass.h"
27#include "gsdlunicode.h"
28#include "unitool.h"
29
30#ifdef __WIN32__
31// for Sleep
32# include <windows.h>
33#else
34// for usleep
35# include <unistd.h>
36#endif
37
38
39#define SQLITE_MAX_RETRIES 8
40
41
42sqlitedbclass::~sqlitedbclass()
43{
44 closedatabase();
45}
46
47
48// returns true if opened
49bool sqlitedbclass::opendatabase (const text_t &filename, int mode, int num_retrys,
50#ifdef __WIN32__
51 bool need_filelock
52#else
53 bool
54#endif
55 )
56{
57 // Check if we've already got the database open
58 if (sqlitefile != NULL)
59 {
60 if (openfile == filename) return true;
61 else closedatabase();
62 }
63
64 char *filename_cstr = filename.getcstr();
65 sqlite3_open(filename_cstr, &sqlitefile);
66 delete[] filename_cstr;
67
68 if (sqlitefile == NULL)
69 {
70 (*logout) << "ERROR: sqlitedbclass::opendatabase() failed on: " << filename << "\n";
71 return false;
72 }
73
74 if ((mode == DB_WRITER || mode == DB_WRITER_CREATE) && !sqltableexists("data"))
75 {
76 sqlexec("CREATE TABLE data (key TEXT, value TEXT, PRIMARY KEY(key))");
77 }
78
79 return true;
80}
81
82
83void sqlitedbclass::closedatabase ()
84{
85 if (sqlitefile == NULL) return;
86
87 sqlite3_close(sqlitefile);
88 sqlitefile = NULL;
89 openfile.clear();
90}
91
92
93void sqlitedbclass::deletekey (const text_t &key)
94{
95 text_t sql_cmd = "DELETE FROM data WHERE key='" + sqlite_safe(key) + "'";
96 sqlexec(sql_cmd);
97}
98
99
100// returns array of document OIDs
101text_tarray sqlitedbclass::get_documents_with_metadata_value (const text_t &metadata_element_name,
102 const text_t &metadata_value,
103 const text_t &sort_by_metadata_element_name)
104{
105 text_tarray document_OIDs;
106
107 // Check a metadata element and value has been specified
108 if (metadata_element_name == "" || metadata_value == "")
109 {
110 return document_OIDs;
111 }
112
113 // Get the entries in the "document_metadata" table where the element and value matches those specified
114 text_t sql_cmd;
115 if (sort_by_metadata_element_name == "")
116 {
117 // No sorting required
118 sql_cmd = "SELECT docOID FROM document_metadata WHERE element='" + sqlite_safe(metadata_element_name) + "' AND value='" + sqlite_safe(metadata_value) + "'";
119 }
120 else
121 {
122 // Sort the documents by a certain metadata element
123 // John Thompson thinks this may not be the most efficient solution, and recommends using ON instead of WHERE
124 sql_cmd = "SELECT b.docOID FROM document_metadata AS a LEFT JOIN document_metadata AS b USING (docOID) WHERE a.element='" + sqlite_safe(metadata_element_name) + "' AND a.value='" + sqlite_safe(metadata_value) + "' AND b.element='" + sqlite_safe(sort_by_metadata_element_name) + "' ORDER BY b.value";
125 }
126 vector<text_tmap> sql_results;
127 if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
128 {
129 return document_OIDs;
130 }
131
132 // Iterate through the documents and add them to the array to be returned
133 vector<text_tmap>::iterator sql_results_iterator = sql_results.begin();
134 while (sql_results_iterator != sql_results.end())
135 {
136 text_tmap sql_result = (*sql_results_iterator);
137 document_OIDs.push_back(sql_result["docOID"]);
138 sql_results_iterator++;
139 }
140
141 return document_OIDs;
142}
143
144
145// returns file extension string
146text_t sqlitedbclass::getfileextension ()
147{
148 return ".db";
149}
150
151
152// returns true on success
153bool sqlitedbclass::getkeydata (const text_t& key, text_t &data)
154{
155 text_t sql_cmd = "SELECT value FROM data WHERE key='" + sqlite_safe(key) + "'";
156 vector<text_tmap> sql_results;
157 if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
158 {
159 return false;
160 }
161
162 text_tmap sql_result = sql_results[0];
163 data = sql_result["value"];
164 return true;
165}
166
167
168// returns array of keys
169text_tarray sqlitedbclass::getkeys ()
170{
171 text_tarray keys;
172
173 // Get all the entries in the "key" column of the table
174 text_t sql_cmd = "SELECT key FROM data";
175 vector<text_tmap> sql_results;
176 if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
177 {
178 return keys;
179 }
180
181 // Iterate through the keys and add them to the array to be returned
182 vector<text_tmap>::iterator sql_results_iterator = sql_results.begin();
183 while (sql_results_iterator != sql_results.end())
184 {
185 text_tmap sql_result = (*sql_results_iterator);
186 keys.push_back(sql_result["key"]);
187 sql_results_iterator++;
188 }
189
190 return keys;
191}
192
193
194// returns array of values
195text_tarray sqlitedbclass::get_metadata_values (const text_t &metadata_element_name)
196{
197 text_tarray metadata_values;
198
199 // Check a metadata element has been specified
200 if (metadata_element_name == "")
201 {
202 return metadata_values;
203 }
204
205 // Get the entries in the "document_metadata" table where the element matches that specified
206 text_t sql_cmd = "SELECT value FROM document_metadata WHERE element='" + sqlite_safe(metadata_element_name) + "'";
207 vector<text_tmap> sql_results;
208 if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
209 {
210 return metadata_values;
211 }
212
213 // Iterate through the values and add them to the array to be returned
214 vector<text_tmap>::iterator sql_results_iterator = sql_results.begin();
215 while (sql_results_iterator != sql_results.end())
216 {
217 text_tmap sql_result = (*sql_results_iterator);
218 metadata_values.push_back(sql_result["value"]);
219 sql_results_iterator++;
220 }
221
222 return metadata_values;
223}
224
225
226// returns true on success
227bool sqlitedbclass::setkeydata (const text_t &key, const text_t &data)
228{
229 // We need to do either an INSERT or UPDATE depending on whether the key already exists
230 if (!exists(key))
231 {
232 text_t sql_cmd = "INSERT INTO data (key, value) VALUES ('" + key + "', '" + data + "')";
233 return sqlexec(sql_cmd);
234 }
235 else
236 {
237 text_t sql_cmd = "UPDATE data SET value='" + sqlite_safe(data) + "' WHERE key='" + sqlite_safe(key) + "'";
238 return sqlexec(sql_cmd);
239 }
240}
241
242
243// ----------------------------------------------------------------------------------------
244// SQLITE-ONLY FUNCTIONS
245// ----------------------------------------------------------------------------------------
246
247// sleep for the given number of milliseconds
248void sleep(int m)
249{
250#ifdef __WIN32__
251 Sleep(m);
252#else
253 usleep(m);
254#endif
255}
256
257
258text_t sqlitedbclass::sqlite_safe (const text_t &value_arg)
259{
260 text_t value = value_arg;
261 value.replace("'", "''");
262 return value;
263}
264
265
266// sqlexec simply executes the given sql statement - it doesn't obtain a
267// result set - returns true if the sql statement was executed successfully
268bool sqlitedbclass::sqlexec(const text_t &sql_cmd)
269{
270 if (sqlitefile == NULL) return false;
271
272 char *sql_cmd_cstr = sql_cmd.getcstr();
273
274 int rv = 0;
275 int tries = 0;
276 while ((rv = sqlite3_exec(sqlitefile, sql_cmd_cstr, NULL, NULL, NULL)) == SQLITE_BUSY)
277 {
278 sleep(1000);
279 tries++;
280 if (tries > SQLITE_MAX_RETRIES)
281 {
282 outconvertclass text_t2ascii;
283 (*logout) << text_t2ascii << "max_retries exceeded for sql query: " << sql_cmd << "\n";
284 break;
285 }
286 }
287
288 delete[] sql_cmd_cstr;
289
290 if (rv == SQLITE_OK) return true;
291
292 // sqlite3_exec failed - return false
293 outconvertclass text_t2ascii;
294 (*logout) << text_t2ascii << "Error executing sql statement: " << sql_cmd << "\n";
295 return false;
296}
297
298
299// callback functions for sqlgetarray
300static int sqlgetarray_callback(void *res, int numcols, char **vals, char **columnnames)
301{
302 vector<text_tmap> *result = (vector<text_tmap>*) res;
303 text_tmap row;
304
305 for (int i = 0; i < numcols; i++)
306 {
307 row[columnnames[i]] = "";
308 // vals[i] will be NULL if set to a NULL db value
309 if (vals[i])
310 {
311 row[columnnames[i]] = to_uni(vals[i]);
312 }
313 }
314
315 result->push_back(row);
316 return 0;
317}
318
319
320// sqlgetarray executes sql and returns the result set in sql_results
321bool sqlitedbclass::sqlgetarray(const text_t &sql_cmd, vector<text_tmap> &sql_results)
322{
323 if (sqlitefile == NULL) return false;
324
325 char *sql_cmd_cstr = sql_cmd.getcstr();
326 sql_results.erase(sql_results.begin(), sql_results.end());
327
328 int rv = 0;
329 int tries = 0;
330 while ((rv = sqlite3_exec(sqlitefile, sql_cmd_cstr, sqlgetarray_callback, &sql_results, NULL)) == SQLITE_BUSY)
331 {
332 sleep(1000);
333 tries++;
334 if (tries > SQLITE_MAX_RETRIES)
335 {
336 outconvertclass text_t2ascii;
337 (*logout) << text_t2ascii << "max_retries exceeded for sql query: " << sql_cmd << "\n";
338 break;
339 }
340 }
341
342 delete[] sql_cmd_cstr;
343
344 if (rv == SQLITE_OK) return true;
345
346 // sqlite3_exec failed - return empty result set
347 outconvertclass text_t2ascii;
348 (*logout) << text_t2ascii << "Error executing sql statement: " << sql_cmd << "\n";
349 return false;
350}
351
352
353// returns true if exists
354bool sqlitedbclass::sqltableexists(const text_t &table_name)
355{
356 text_t sql_cmd = "SELECT * FROM sqlite_master WHERE tbl_name='" + sqlite_safe(table_name) + "'";
357 vector<text_tmap> sql_results;
358 if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
359 {
360 return false;
361 }
362
363 return true;
364}
Note: See TracBrowser for help on using the repository browser.