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

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

(Adding dynamic classifiers) Added new get_documents_with_metadata_value() function, for use by the dynamic classifiers.

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