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

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

(Adding dynamic classifiers) Added check for empty metadata_element_name in get_metadata_values().

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