source: gsdl/trunk/lib/sqlitedbclass.cpp@ 15811

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

(Adding new DB support) Now calls to_uni() on the values from the database so they are encoded correctly.

File size: 8.8 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='" + 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{
104 text_tarray document_OIDs;
105
106 // Check a metadata element and value has been specified
107 if (metadata_element_name == "" || metadata_value == "")
108 {
109 return document_OIDs;
110 }
111
112 // Get the entries in the "document_metadata" table where the element and value matches those specified
113 text_t sql_cmd = "SELECT docOID FROM document_metadata WHERE element='" + metadata_element_name + "' AND value='" + metadata_value + "'";
114 vector<text_tmap> sql_results;
115 if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
116 {
117 return document_OIDs;
118 }
119
120 // Iterate through the documents and add them to the array to be returned
121 vector<text_tmap>::iterator sql_results_iterator = sql_results.begin();
122 while (sql_results_iterator != sql_results.end())
123 {
124 text_tmap sql_result = (*sql_results_iterator);
125 document_OIDs.push_back(sql_result["docOID"]);
126 sql_results_iterator++;
127 }
128
129 return document_OIDs;
130}
131
132
133// returns file extension string
134text_t sqlitedbclass::getfileextension ()
135{
136 return ".db";
137}
138
139
140// returns true on success
141bool sqlitedbclass::getkeydata (const text_t& key, text_t &data)
142{
143 text_t sql_cmd = "SELECT value FROM data WHERE key='" + key + "'";
144 vector<text_tmap> sql_results;
145 if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
146 {
147 return false;
148 }
149
150 text_tmap sql_result = sql_results[0];
151 data = sql_result["value"];
152 return true;
153}
154
155
156// returns array of keys
157text_tarray sqlitedbclass::getkeys ()
158{
159 text_tarray keys;
160
161 // Get all the entries in the "key" column of the table
162 text_t sql_cmd = "SELECT key FROM data";
163 vector<text_tmap> sql_results;
164 if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
165 {
166 return keys;
167 }
168
169 // Iterate through the keys and add them to the array to be returned
170 vector<text_tmap>::iterator sql_results_iterator = sql_results.begin();
171 while (sql_results_iterator != sql_results.end())
172 {
173 text_tmap sql_result = (*sql_results_iterator);
174 keys.push_back(sql_result["key"]);
175 sql_results_iterator++;
176 }
177
178 return keys;
179}
180
181
182// returns array of values
183text_tarray sqlitedbclass::get_metadata_values (const text_t &metadata_element_name)
184{
185 text_tarray metadata_values;
186
187 // Check a metadata element has been specified
188 if (metadata_element_name == "")
189 {
190 return metadata_values;
191 }
192
193 // Get the entries in the "document_metadata" table where the element matches that specified
194 text_t sql_cmd = "SELECT value FROM document_metadata WHERE element='" + metadata_element_name + "'";
195 vector<text_tmap> sql_results;
196 if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
197 {
198 return metadata_values;
199 }
200
201 // Iterate through the values and add them to the array to be returned
202 vector<text_tmap>::iterator sql_results_iterator = sql_results.begin();
203 while (sql_results_iterator != sql_results.end())
204 {
205 text_tmap sql_result = (*sql_results_iterator);
206 metadata_values.push_back(sql_result["value"]);
207 sql_results_iterator++;
208 }
209
210 return metadata_values;
211}
212
213
214// returns true on success
215bool sqlitedbclass::setkeydata (const text_t &key, const text_t &data)
216{
217 // We need to do either an INSERT or UPDATE depending on whether the key already exists
218 if (!exists(key))
219 {
220 text_t sql_cmd = "INSERT INTO data (key, value) VALUES ('" + key + "', '" + data + "')";
221 return sqlexec(sql_cmd);
222 }
223 else
224 {
225 text_t sql_cmd = "UPDATE data SET value='" + data + "' WHERE key='" + key + "'";
226 return sqlexec(sql_cmd);
227 }
228}
229
230
231// ----------------------------------------------------------------------------------------
232// SQLITE-ONLY FUNCTIONS
233// ----------------------------------------------------------------------------------------
234
235// sleep for the given number of milliseconds
236void sleep(int m)
237{
238#ifdef __WIN32__
239 Sleep(m);
240#else
241 usleep(m);
242#endif
243}
244
245
246// sqlexec simply executes the given sql statement - it doesn't obtain a
247// result set - returns true if the sql statement was executed successfully
248bool sqlitedbclass::sqlexec(const text_t &sql_cmd)
249{
250 if (sqlitefile == NULL) return false;
251
252 char *sql_cmd_cstr = sql_cmd.getcstr();
253
254 int rv = 0;
255 int tries = 0;
256 while ((rv = sqlite3_exec(sqlitefile, sql_cmd_cstr, NULL, NULL, NULL)) == SQLITE_BUSY)
257 {
258 sleep(1000);
259 tries++;
260 if (tries > SQLITE_MAX_RETRIES)
261 {
262 outconvertclass text_t2ascii;
263 (*logout) << text_t2ascii << "max_retries exceeded for sql query: " << sql_cmd << "\n";
264 break;
265 }
266 }
267
268 delete[] sql_cmd_cstr;
269
270 if (rv == SQLITE_OK) return true;
271
272 // sqlite3_exec failed - return false
273 outconvertclass text_t2ascii;
274 (*logout) << text_t2ascii << "Error executing sql statement: " << sql_cmd << "\n";
275 return false;
276}
277
278
279// callback functions for sqlgetarray
280static int sqlgetarray_callback(void *res, int numcols, char **vals, char **columnnames)
281{
282 vector<text_tmap> *result = (vector<text_tmap>*) res;
283 text_tmap row;
284
285 for (int i = 0; i < numcols; i++)
286 {
287 row[columnnames[i]] = "";
288 // vals[i] will be NULL if set to a NULL db value
289 if (vals[i])
290 {
291 row[columnnames[i]] = to_uni(vals[i]);
292 }
293 }
294
295 result->push_back(row);
296 return 0;
297}
298
299
300// sqlgetarray executes sql and returns the result set in sql_results
301bool sqlitedbclass::sqlgetarray(const text_t &sql_cmd, vector<text_tmap> &sql_results)
302{
303 if (sqlitefile == NULL) return false;
304
305 char *sql_cmd_cstr = sql_cmd.getcstr();
306 sql_results.erase(sql_results.begin(), sql_results.end());
307
308 int rv = 0;
309 int tries = 0;
310 while ((rv = sqlite3_exec(sqlitefile, sql_cmd_cstr, sqlgetarray_callback, &sql_results, NULL)) == SQLITE_BUSY)
311 {
312 sleep(1000);
313 tries++;
314 if (tries > SQLITE_MAX_RETRIES)
315 {
316 outconvertclass text_t2ascii;
317 (*logout) << text_t2ascii << "max_retries exceeded for sql query: " << sql_cmd << "\n";
318 break;
319 }
320 }
321
322 delete[] sql_cmd_cstr;
323
324 if (rv == SQLITE_OK) return true;
325
326 // sqlite3_exec failed - return empty result set
327 outconvertclass text_t2ascii;
328 (*logout) << text_t2ascii << "Error executing sql statement: " << sql_cmd << "\n";
329 return false;
330}
331
332
333// returns true if exists
334bool sqlitedbclass::sqltableexists(const text_t &table_name)
335{
336 text_t sql_cmd = "SELECT * FROM sqlite_master WHERE tbl_name='" + table_name + "'";
337 vector<text_tmap> sql_results;
338 if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
339 {
340 return false;
341 }
342
343 return true;
344}
Note: See TracBrowser for help on using the repository browser.