root/main/trunk/greenstone2/common-src/src/lib/sqlitedbclass.cpp @ 21865

Revision 21865, 10.5 KB (checked in by mdewsnip, 10 years ago)

Now displays rv value in error message if sqlite3_exec() fails.

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  openfile = filename;
80
81  return true;
82}
83
84
85void sqlitedbclass::closedatabase ()
86{
87  if (sqlitefile == NULL) return;
88
89  sqlite3_close(sqlitefile);
90  sqlitefile = NULL;
91  openfile.clear();
92}
93
94
95void sqlitedbclass::deletekey (const text_t &key)
96{
97  text_t sql_cmd = "DELETE FROM data WHERE key='" + sqlite_safe(key) + "'";
98  sqlexec(sql_cmd);
99}
100
101
102// returns array of document OIDs
103text_tarray sqlitedbclass::get_documents_with_metadata_value (const text_tarray &metadata_element_names,
104                                  const text_t &metadata_value,
105                                  const text_t &sort_by_metadata_element_name)
106{
107  text_tarray document_OIDs;
108
109  // Check at least one metadata element and a metadata value has been specified
110  if (metadata_element_names.empty() || metadata_value == "")
111  {
112    return document_OIDs;
113  }
114
115  // Get the entries in the "document_metadata" table where the element and value matches those specified
116  text_t sql_cmd = "SELECT DISTINCT docOID FROM document_metadata WHERE element IN ('" + sqlite_safe(metadata_element_names[0]) + "'";
117  for (int i = 1; i < metadata_element_names.size(); i++)
118  {
119    sql_cmd += ",'" + sqlite_safe(metadata_element_names[i]) + "'";
120  }
121  sql_cmd += ") AND value='" + sqlite_safe(metadata_value) + "'";
122
123  // If we're sorting the documents by a certain metadata element, extend the SQL command to do this
124  if (sort_by_metadata_element_name != "")
125  {
126    sql_cmd = "SELECT docOID FROM (" + sql_cmd + ") LEFT JOIN (SELECT docOID,value from document_metadata WHERE element='" + sqlite_safe(sort_by_metadata_element_name) + "') USING (docOID) ORDER by value";
127  }
128
129  // Perform the SQL request
130  vector<text_tmap> sql_results;
131  if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
132  {
133    return document_OIDs;
134  }
135
136  // Iterate through the documents and add them to the array to be returned
137  vector<text_tmap>::iterator sql_results_iterator = sql_results.begin();
138  while (sql_results_iterator != sql_results.end())
139  {
140    text_tmap sql_result = (*sql_results_iterator);
141    document_OIDs.push_back(sql_result["docOID"]);
142    sql_results_iterator++;
143  }
144
145  return document_OIDs;
146}
147
148
149// returns file extension string
150text_t sqlitedbclass::getfileextension ()
151{
152  return ".db";
153}
154
155
156// returns true on success
157bool sqlitedbclass::getkeydata (const text_t& key, text_t &data)
158{
159  text_t sql_cmd = "SELECT value FROM data WHERE key='" + sqlite_safe(key) + "'";
160  vector<text_tmap> sql_results;
161  if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
162  {
163    return false;
164  }
165
166  text_tmap sql_result = sql_results[0];
167  data = sql_result["value"];
168  return true;
169}
170
171
172// returns array of keys
173text_tarray sqlitedbclass::getkeys ()
174{
175  text_tarray keys;
176
177  // Get all the entries in the "key" column of the table
178  text_t sql_cmd = "SELECT key FROM data";
179  vector<text_tmap> sql_results;
180  if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
181  {
182    return keys;
183  }
184
185  // Iterate through the keys and add them to the array to be returned
186  vector<text_tmap>::iterator sql_results_iterator = sql_results.begin();
187  while (sql_results_iterator != sql_results.end())
188  {
189    text_tmap sql_result = (*sql_results_iterator);
190    keys.push_back(sql_result["key"]);
191    sql_results_iterator++;
192  }
193
194  return keys;
195}
196
197
198// returns array of values
199text_tarray sqlitedbclass::get_metadata_values (const text_tarray &metadata_element_names,
200                        const text_t &metadata_value_filter,
201                        const text_t &metadata_value_grouping_expression)
202{
203  text_tarray metadata_values;
204
205  // Check at least one metadata element has been specified
206  if (metadata_element_names.empty())
207  {
208    return metadata_values;
209  }
210
211  // Get the raw "value" field unless a grouping expression was provided (in this case an edited value is returned)
212  text_t value_select_expression = "value";
213  if (metadata_value_grouping_expression != "")
214  {
215    value_select_expression = metadata_value_grouping_expression;
216  }
217
218  // Get the entries in the "document_metadata" table where the element matches that specified
219  text_t sql_cmd = "SELECT DISTINCT docOID," + value_select_expression + " FROM document_metadata WHERE element IN ('" + sqlite_safe(metadata_element_names[0]) + "'";
220  for (int i = 1; i < metadata_element_names.size(); i++)
221  {
222    sql_cmd += ",'" + sqlite_safe(metadata_element_names[i]) + "'";
223  }
224  sql_cmd += ")";
225
226  // Add value filter, if one has been defined
227  if (metadata_value_filter != "")
228  {
229    sql_cmd += " AND value GLOB '" + sqlite_safe(metadata_value_filter) + "'";
230  }
231
232  // Perform the SQL request
233  vector<text_tmap> sql_results;
234  if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
235  {
236    return metadata_values;
237  }
238
239  // Iterate through the values and add them to the array to be returned
240  vector<text_tmap>::iterator sql_results_iterator = sql_results.begin();
241  while (sql_results_iterator != sql_results.end())
242  {
243    text_tmap sql_result = (*sql_results_iterator);
244    metadata_values.push_back(sql_result[value_select_expression]);
245    sql_results_iterator++;
246  }
247
248  return metadata_values;
249}
250
251
252// returns true on success
253bool sqlitedbclass::setkeydata (const text_t &key, const text_t &data)
254{
255  // We need to do either an INSERT or UPDATE depending on whether the key already exists
256  if (!exists(key))
257  {
258    text_t sql_cmd = "INSERT INTO data (key, value) VALUES ('" + sqlite_safe(key) + "', '" + sqlite_safe(data) + "')";
259    return sqlexec(sql_cmd);
260  }
261  else
262  {
263    text_t sql_cmd = "UPDATE data SET value='" + sqlite_safe(data) + "' WHERE key='" + sqlite_safe(key) + "'";
264    return sqlexec(sql_cmd);
265  }
266}
267
268
269// ----------------------------------------------------------------------------------------
270//   SQLITE-ONLY FUNCTIONS
271// ----------------------------------------------------------------------------------------
272
273// sleep for the given number of milliseconds
274void sleep(int m)
275{
276#ifdef __WIN32__
277  Sleep(m);
278#else
279  usleep(m);
280#endif
281}
282
283
284text_t sqlitedbclass::sqlite_safe (const text_t &value_arg)
285{
286  text_t value = value_arg;
287  value.replace("'", "''");
288  return value;
289}
290
291
292// sqlexec simply executes the given sql statement - it doesn't obtain a
293// result set - returns true if the sql statement was executed successfully
294bool sqlitedbclass::sqlexec(const text_t &sql_cmd)
295{
296  if (sqlitefile == NULL) return false;
297
298  char *sql_cmd_cstr = sql_cmd.getcstr();
299
300  int rv = 0;
301  int tries = 0;
302  while ((rv = sqlite3_exec(sqlitefile, sql_cmd_cstr, NULL, NULL, NULL)) == SQLITE_BUSY)
303  {
304    sleep(1000);
305    tries++;
306    if (tries > SQLITE_MAX_RETRIES)
307    {
308      outconvertclass text_t2ascii;
309      (*logout) << text_t2ascii << "max_retries exceeded for sql query: " << sql_cmd << "\n";
310      break;
311    }
312  }
313
314  delete[] sql_cmd_cstr;
315
316  if (rv == SQLITE_OK) return true;
317
318  // sqlite3_exec failed - return false
319  outconvertclass text_t2ascii;
320  (*logout) << text_t2ascii << "Error executing sql statement: " << sql_cmd << ", rv: " << rv << "\n";
321  return false;
322}
323
324
325// callback functions for sqlgetarray
326static int sqlgetarray_callback(void *res, int numcols, char **vals, char **columnnames)
327{
328  vector<text_tmap> *result = (vector<text_tmap>*) res;
329  text_tmap row;
330
331  for (int i = 0; i < numcols; i++)
332  {
333    row[columnnames[i]] = "";
334    // vals[i] will be NULL if set to a NULL db value
335    if (vals[i])
336    {
337      row[columnnames[i]] = to_uni(vals[i]);
338    }
339  }
340
341  result->push_back(row);
342  return 0;
343}
344
345
346// sqlgetarray executes sql and returns the result set in sql_results
347bool sqlitedbclass::sqlgetarray(const text_t &sql_cmd, vector<text_tmap> &sql_results)
348{
349  if (sqlitefile == NULL) return false;
350
351  char *sql_cmd_cstr = sql_cmd.getcstr();
352  sql_results.erase(sql_results.begin(), sql_results.end());
353
354  int rv = 0;
355  int tries = 0;
356  while ((rv = sqlite3_exec(sqlitefile, sql_cmd_cstr, sqlgetarray_callback, &sql_results, NULL)) == SQLITE_BUSY)
357  {
358    sleep(1000);
359    tries++;
360    if (tries > SQLITE_MAX_RETRIES)
361    {
362      outconvertclass text_t2ascii;
363      (*logout) << text_t2ascii << "max_retries exceeded for sql query: " << sql_cmd << "\n";
364      break;
365    }
366  }
367
368  delete[] sql_cmd_cstr;
369
370  if (rv == SQLITE_OK) return true;
371
372  // sqlite3_exec failed - return empty result set
373  outconvertclass text_t2ascii;
374  (*logout) << text_t2ascii << "Error executing sql statement: " << sql_cmd << "\n";
375  return false;
376}
377
378
379// returns true if exists
380bool sqlitedbclass::sqltableexists(const text_t &table_name)
381{
382  text_t sql_cmd = "SELECT * FROM sqlite_master WHERE tbl_name='" + sqlite_safe(table_name) + "'";
383  vector<text_tmap> sql_results;
384  if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
385  {
386    return false;
387  }
388
389  return true;
390}
Note: See TracBrowser for help on using the browser.