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

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

Added minor comment.

File size: 7.6 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 // Get all the entries in the "value" column of the "document_metadata" table
154 text_t sql_cmd = "SELECT value FROM document_metadata WHERE element='" + metadata_element_name + "'";
155 vector<text_tmap> sql_results;
156 if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
157 {
158 return metadata_values;
159 }
160
161 // Iterate through the values and add them to the array to be returned
162 vector<text_tmap>::iterator sql_results_iterator = sql_results.begin();
163 while (sql_results_iterator != sql_results.end())
164 {
165 text_tmap sql_result = (*sql_results_iterator);
166 metadata_values.push_back(sql_result["value"]);
167 sql_results_iterator++;
168 }
169
170 return metadata_values;
171}
172
173
174// returns true on success
175bool sqlitedbclass::setkeydata (const text_t &key, const text_t &data)
176{
177 // We need to do either an INSERT or UPDATE depending on whether the key already exists
178 if (!exists(key))
179 {
180 text_t sql_cmd = "INSERT INTO data (key, value) VALUES ('" + key + "', '" + data + "')";
181 return sqlexec(sql_cmd);
182 }
183 else
184 {
185 text_t sql_cmd = "UPDATE data SET value='" + data + "' WHERE key='" + key + "'";
186 return sqlexec(sql_cmd);
187 }
188}
189
190
191// ----------------------------------------------------------------------------------------
192// SQLITE-ONLY FUNCTIONS
193// ----------------------------------------------------------------------------------------
194
195// sleep for the given number of milliseconds
196void sleep(int m)
197{
198#ifdef __WIN32__
199 Sleep(m);
200#else
201 usleep(m);
202#endif
203}
204
205
206// sqlexec simply executes the given sql statement - it doesn't obtain a
207// result set - returns true if the sql statement was executed successfully
208bool sqlitedbclass::sqlexec(const text_t &sql_cmd)
209{
210 if (sqlitefile == NULL) return false;
211
212 char *sql_cmd_cstr = sql_cmd.getcstr();
213
214 int rv = 0;
215 int tries = 0;
216 while ((rv = sqlite3_exec(sqlitefile, sql_cmd_cstr, NULL, NULL, NULL)) == SQLITE_BUSY)
217 {
218 sleep(1000);
219 tries++;
220 if (tries > SQLITE_MAX_RETRIES)
221 {
222 outconvertclass text_t2ascii;
223 (*logout) << text_t2ascii << "max_retries exceeded for sql query: " << sql_cmd << "\n";
224 break;
225 }
226 }
227
228 delete[] sql_cmd_cstr;
229
230 if (rv == SQLITE_OK) return true;
231
232 // sqlite3_exec failed - return false
233 outconvertclass text_t2ascii;
234 (*logout) << text_t2ascii << "Error executing sql statement: " << sql_cmd << "\n";
235 return false;
236}
237
238
239// callback functions for sqlgetarray
240static int sqlgetarray_callback(void *res, int numcols, char **vals, char **columnnames)
241{
242 vector<text_tmap> *result = (vector<text_tmap>*) res;
243 text_tmap row;
244
245 for (int i = 0; i < numcols; i++)
246 {
247 row[columnnames[i]] = "";
248 // vals[i] will be NULL if set to a NULL db value
249 if (vals[i])
250 {
251 row[columnnames[i]] = vals[i];
252 }
253 }
254
255 result->push_back(row);
256 return 0;
257}
258
259
260// sqlgetarray executes sql and returns the result set in sql_results
261bool sqlitedbclass::sqlgetarray(const text_t &sql_cmd, vector<text_tmap> &sql_results)
262{
263 if (sqlitefile == NULL) return false;
264
265 char *sql_cmd_cstr = sql_cmd.getcstr();
266 sql_results.erase(sql_results.begin(), sql_results.end());
267
268 int rv = 0;
269 int tries = 0;
270 while ((rv = sqlite3_exec(sqlitefile, sql_cmd_cstr, sqlgetarray_callback, &sql_results, NULL)) == SQLITE_BUSY)
271 {
272 sleep(1000);
273 tries++;
274 if (tries > SQLITE_MAX_RETRIES)
275 {
276 outconvertclass text_t2ascii;
277 (*logout) << text_t2ascii << "max_retries exceeded for sql query: " << sql_cmd << "\n";
278 break;
279 }
280 }
281
282 delete[] sql_cmd_cstr;
283
284 if (rv == SQLITE_OK) return true;
285
286 // sqlite3_exec failed - return empty result set
287 outconvertclass text_t2ascii;
288 (*logout) << text_t2ascii << "Error executing sql statement: " << sql_cmd << "\n";
289 return false;
290}
291
292
293// returns true if exists
294bool sqlitedbclass::sqltableexists(const text_t &table_name)
295{
296 text_t sql_cmd = "SELECT * FROM sqlite_master WHERE tbl_name='" + table_name + "'";
297 vector<text_tmap> sql_results;
298 if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
299 {
300 return false;
301 }
302
303 return true;
304}
Note: See TracBrowser for help on using the repository browser.