Debian Codegraph @

src/lib/object_store/DB.cpp

raw
1 /*
2 * Copyright (c) 2013 SURFnet bv
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
18 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
20 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
22 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
23 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
24 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27 /*****************************************************************************
28 DB.cpp
29
30 Specifies classes to access the Token Database
31 *****************************************************************************/
32 #define HAVE_SQL_TRACE 0
33
34 #include "config.h"
35 #include "OSPathSep.h"
36 #include "log.h"
37 #include <cstdlib>
38 #include <cstdio>
39 #include <iostream>
40 #include <vector>
41 #include <sqlite3.h>
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #include <fcntl.h>
45 #include <unistd.h>
46 #include <errno.h>
47
48 #include "DB.h"
49
50 #if HAVE_SQL_TRACE
51 static void xTrace(void*connectionLabel,const char*zSql)
52 {
53 const char *label = static_cast<const char *>(connectionLabel);
54 if (label)
55 std::cout << std::endl << label << ": " << zSql ;
56 else
57 std::cout << std::endl << zSql ;
58 }
59 #endif
60
61 static int static_log_err(const char *format, va_list ap)
62 {
63 std::vector<char> logMessage;
64 logMessage.resize(4096);
65 vsnprintf(&logMessage[0], 4096, format, ap);
66 ERROR_MSG(&logMessage[0]);
67 return 0;
68 }
69
70 static DB::LogErrorHandler static_LogErrorhandler = static_log_err;
71
72 void DB::logError(const std::string &format, ...)
73 {
74 if (!static_LogErrorhandler)
75 return;
76 va_list args;
77 va_start(args, format);
78 static_LogErrorhandler(format.c_str(),args);
79 va_end(args);
80 }
81
82 DB::LogErrorHandler DB::setLogErrorHandler(DB::LogErrorHandler handler)
83 {
84 LogErrorHandler temp = static_LogErrorhandler;
85 static_LogErrorhandler = handler;
86 return temp;
87 }
88
89 void DB::resetLogErrorHandler()
90 {
91 static_LogErrorhandler = static_log_err;
92 }
93
94 static void reportErrorDB(sqlite3 *db)
95 {
96 if (!db) {
97 DB::logError("sqlite3 pointer is NULL");
98 return;
99 }
100
101 int rv = sqlite3_errcode(db);
102 if (rv == SQLITE_OK || rv == SQLITE_ROW || rv == SQLITE_DONE)
103 return;
104
105 #ifdef HAVE_SILENT_BUSY_AND_LOCKED_ERRORS
106 // Either the database file is locked (SQLITE_BUSY)
107 // or a table in the database is locked (SQLITE_LOCKED)
108 if (rv == SQLITE_BUSY || rv == SQLITE_LOCKED)
109 return;
110 #endif
111
112 DB::logError("SQLITE3: %s (%d)", sqlite3_errmsg(db), rv);
113 }
114
115 static void reportError(sqlite3_stmt *stmt)
116 {
117 if (!stmt) {
118 DB::logError("sqlite3_stmt pointer is NULL");
119 return;
120 }
121 reportErrorDB(sqlite3_db_handle(stmt));
122 }
123
124 static time_t sqlite3_gmtime(struct tm *tm)
125 {
126 // We don't want to depend on timegm() so we use a workaround via the
127 // gmtime_r() function to determine this.
128 // As input we use a moment in time just 10 days after the POSIX epoch.
129 // The POSIX epoch is defined as the moment in time at midnight Coordinated
130 // Universal Time (UTC) of Thursday, January 1, 1970. A time_t value is
131 // the number of seconds elapsed since epoch.
132 struct tm ref_tm = {0,0,0,0,0,0,0,0,0,0,0};
133 ref_tm.tm_year = 70; // Years since 1900;
134 ref_tm.tm_mday = 10; // 10th
135
136 // We need the time difference between local time and UTC time.
137 // mktime will interpret the UTC time stored in tm as local time
138 // so let's assume we are in a time zone 1 hour ahead of UTC (UTC+1)
139 // then a time of 13:00 interpreted as local time needs 1 hour subtracted
140 // to arrive at UTC time. This UTC time is then converted to a POSIX
141 // time_t value.
142 time_t posix_time = mktime(&ref_tm);
143
144 // Use gmtime_r to convert the POSIX time back to a tm struct.
145 // No time adjustment is done this time because POSIX time is
146 // defined in terms of UTC.
147 gmtime_r(&posix_time, &ref_tm);
148 if (ref_tm.tm_isdst != 0) {
149 DB::logError("expected gmtime_r to return zero in tm_isdst member of tm struct");
150 return ((time_t)-1);
151 }
152
153 // Using mktime again to convert tm. This will again subtract 1 hour from
154 // the time (under the assumption that we are 1 hour ahead of UTC).
155 // We can now use this to determine how much local time differred
156 // from UTC time on january the 10th 1970
157 long diff_time = posix_time - mktime(&ref_tm);
158
159 // We explicitly set tm_isdst to zero to prevent errors
160 // when the time we are trying to convert is occuring at
161 // the moment when a dst change is in progress.
162 // We require mktime to respect our setting of tm_isdst
163 // indicating that no dst is in effect.
164 tm->tm_isdst = 0; // Tell (and force) mktime not to take dst into account.
165
166 // We now can calculate and return a correct POSIX time.
167 // So, although mktime() interprets gm_tm as local time adjusts for
168 // the time difference between local time and UTC time. We then undo
169 // that adjustment by adding diff_time.
170 return mktime(tm) + diff_time;
171 }
172
173 /**************************
174 * Handle
175 **************************/
176
177 class DB::Handle {
178 public:
179 int _refcount;
180 sqlite3_stmt *_stmt;
181 Handle(sqlite3_stmt *stmt)
182 : _refcount(1), _stmt(stmt)
183 {
184 }
185 ~Handle()
186 {
187 if (_stmt)
188 {
189 sqlite3_finalize(_stmt);
190 _stmt = NULL;
191 }
192 }
193
194 Handle *retain()
195 {
196 if (_refcount)
197 {
198 _refcount++;
199 return this;
200 }
201 return NULL;
202 }
203 void release()
204 {
205 if (_refcount)
206 {
207 _refcount--;
208 if (_refcount)
209 return;
210 delete this;
211 }
212 }
213 bool reset()
214 {
215 if (sqlite3_reset(_stmt) != SQLITE_OK)
216 {
217 reportError(_stmt);
218 return false;
219 }
220 return true;
221 }
222 Statement::ReturnCode step()
223 {
224 int rv = sqlite3_step(_stmt);
225 if (rv != SQLITE_ROW && rv != SQLITE_DONE)
226 {
227 reportError(_stmt);
228 return Statement::ReturnCodeError;
229 }
230
231 if (rv==SQLITE_ROW)
232 {
233 return Statement::ReturnCodeRow;
234 }
235
236 return Statement::ReturnCodeDone;
237 }
238 private:
239 // disable evil constructors
240 Handle(const Handle &);
241 Handle & operator=(const Handle &);
242 };
243
244 DB::Statement::Statement()
245 : _handle(NULL)
246 {
247 }
248
249 DB::Statement::Statement(sqlite3_stmt *statement)
250 : _handle(new Handle(statement))
251 {
252 }
253
254 DB::Statement::Statement(const DB::Statement &statement)
255 : _handle(statement._handle)
256 {
257 if (_handle)
258 _handle = _handle->retain();
259 }
260
261 DB::Statement &DB::Statement::operator=(const DB::Statement &statement)
262 {
263 if (this != &statement)
264 {
265 Handle *tmp = NULL;
266 if (statement._handle) {
267 tmp = statement._handle->retain();
268 }
269 if (_handle) {
270 _handle->release();
271 }
272 _handle = tmp;
273 }
274 return *this;
275 }
276
277 DB::Statement::~Statement()
278 {
279 if (_handle) {
280 _handle->release();
281 _handle = NULL;
282 }
283 }
284
285 bool DB::Statement::isValid()
286 {
287 return _handle != NULL && _handle->_stmt != NULL;
288 }
289
290 int DB::Statement::refcount()
291 {
292 return _handle ? _handle->_refcount : 0;
293 }
294
295
296 bool DB::Statement::reset()
297 {
298 if (!isValid()) {
299 DB::logError("Statement::reset: statement is not valid");
300 return false;
301 }
302 return _handle->reset();
303 }
304
305 DB::Statement::ReturnCode DB::Statement::step()
306 {
307 if (!isValid()) {
308 DB::logError("Statement::step: statement is not valid");
309 return ReturnCodeError;
310 }
311 return _handle->step();
312 }
313
314 DB::Handle *DB::Statement::handle() const
315 {
316 return _handle;
317 }
318
319 /**************************
320 * Bindings
321 **************************/
322
323 DB::Bindings::Bindings()
324 : Statement()
325 {
326 }
327
328 DB::Bindings::Bindings(const Statement &statement)
329 : Statement(statement)
330 {
331 }
332
333 bool DB::Bindings::clear()
334 {
335 if (!isValid()) {
336 DB::logError("Bindings::clear: statement is not valid");
337 return false;
338 }
339 if (sqlite3_clear_bindings(_handle->_stmt) != SQLITE_OK) {
340 reportError(_handle->_stmt);
341 return false;
342 }
343 return true;
344 }
345
346 bool DB::Bindings::bindBlob(int index, const void *value, int n, void(*destruct)(void*))
347 {
348 if (!isValid()) {
349 DB::logError("Bindings::bindBlob: statement is not valid");
350 return false;
351 }
352 if (sqlite3_bind_blob(_handle->_stmt, index, value, n, destruct) != SQLITE_OK) {
353 reportError(_handle->_stmt);
354 return false;
355 }
356 return true;
357 }
358
359 bool DB::Bindings::bindDouble(int index, double value)
360 {
361 if (!isValid()) {
362 DB::logError("Bindings::bindDouble: statement is not valid");
363 return false;
364 }
365 if (sqlite3_bind_double(_handle->_stmt, index, value) != SQLITE_OK) {
366 reportError(_handle->_stmt);
367 return false;
368 }
369 return true;
370 }
371
372 bool DB::Bindings::bindInt(int index, int value)
373 {
374 if (!isValid()) {
375 DB::logError("Bindings::bindInt: statement is not valid");
376 return false;
377 }
378 if (sqlite3_bind_int(_handle->_stmt, index, value) != SQLITE_OK) {
379 reportError(_handle->_stmt);
380 return false;
381 }
382 return true;
383 }
384
385 bool DB::Bindings::bindInt64(int index, long long value)
386 {
387 if (!isValid()) {
388 DB::logError("Bindings::bindInt64: statement is not valid");
389 return false;
390 }
391 if (sqlite3_bind_int64(_handle->_stmt, index, value) != SQLITE_OK) {
392 reportError(_handle->_stmt);
393 return false;
394 }
395 return true;
396 }
397
398 //bool DB::Bindings::bindNull(int index)
399 //{
400 //#if 0
401 // int sqlite3_bind_null(sqlite3_stmt*, int);
402 //#endif
403 // return false;
404 //}
405
406 bool DB::Bindings::bindText(int index, const char *value, int n, void (*destruct)(void *))
407 {
408 if (!isValid()) {
409 DB::logError("Bindings::bindText: statement is not valid");
410 return false;
411 }
412 if (sqlite3_bind_text(_handle->_stmt, index, value, n, destruct) != SQLITE_OK) {
413 reportError(_handle->_stmt);
414 return false;
415 }
416 return true;
417 }
418
419 //bool DB::Bindings::bindZeroBlob(int index, int n)
420 //{
421 //#if 0
422 // int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
423 //#endif
424 // return false;
425 //}
426
427 /**************************
428 * Result
429 **************************/
430
431 DB::Result::Result()
432 : Statement()
433 {
434 }
435
436 DB::Result::Result(const Statement &statement)
437 : Statement(statement)
438 {
439 }
440
441 #if 0
442 unsigned int DB::Result::getField(const std::string &fieldname)
443 {
444 unsigned int fieldidx = fields[fieldname];
445 if (fieldidx == 0)
446 DB::logError("Result: invalid field name \"%s\"",fieldname.c_str());
447 return fieldidx;
448 }
449 #endif
450
451 bool DB::Result::fieldIsNull(unsigned int fieldidx)
452 {
453 if (!isValid()) {
454 DB::logError("Result::fieldIsNull: statement is not valid");
455 return true;
456 }
457 if (fieldidx == 0) {
458 DB::logError("Result: zero is an invalid field index");
459 return true;
460 }
461 int column_type = sqlite3_column_type(_handle->_stmt, fieldidx-1);
462 return column_type == SQLITE_NULL;
463 }
464
465 time_t DB::Result::getDatetime(unsigned int fieldidx)
466 {
467 if (!isValid()) {
468 DB::logError("Result::getDatetime: statement is not valid");
469 return ((time_t)-1);
470 }
471 if (fieldidx == 0) {
472 DB::logError("Result: zero is an invalid field index");
473 return ((time_t)-1);
474 }
475
476 const unsigned char *value = sqlite3_column_text(_handle->_stmt, fieldidx-1);
477 int valuelen = sqlite3_column_bytes(_handle->_stmt, fieldidx-1);
478
479 unsigned long years,mons,days,hours,mins,secs;
480 struct tm gm_tm = {0,0,0,0,0,0,0,0,0,0,0};
481 gm_tm.tm_isdst = 0; // Tell mktime not to take dst into account.
482 gm_tm.tm_year = 70; // 1970
483 gm_tm.tm_mday = 1; // 1th day of the month
484 const char *p = (const char *)value;
485 char *pnext;
486 bool bdateonly = true;
487 switch (valuelen) {
488 case 19: // 2011-12-31 23:59:59
489 bdateonly = false;
490 // falls through
491 case 10: // 2011-12-31
492 years = strtoul(p,&pnext,10);
493 gm_tm.tm_year = ((int)years)-1900; /* years since 1900 */
494 p = pnext+1;
495 mons = strtoul(p,&pnext,10);
496 gm_tm.tm_mon = ((int)mons)-1; /* months since January [0-11] */
497 p = pnext+1;
498 days = strtoul(p,&pnext,10);
499 gm_tm.tm_mday = ((int)days); /* day of the month [1-31] */
500 p = pnext+1;
501 if (bdateonly)
502 break;
503 // falls through
504 case 8: // 23:59:59
505 hours = strtoul(p,&pnext,10);
506 gm_tm.tm_hour = (int)hours; /* hours since midnight [0-23] */
507 if ((pnext-p) != 2) {
508 DB::logError("Result: invalid hours in time: '%s'",value);
509 return 0;
510 }
511 p = pnext+1;
512 mins = strtoul(p,&pnext,10);
513 gm_tm.tm_min = (int)mins; /* minutes after the hour [0-59] */
514 if ((pnext-p) != 2) {
515 DB::logError("Result: invalid minutes in time: '%s'",value);
516 return 0;
517 }
518 p = pnext+1;
519 secs = strtoul(p,&pnext,10);
520 gm_tm.tm_sec = (int)secs; /* seconds after the minute [0-60] */
521 if ((pnext-p) != 2) {
522 DB::logError("Result: invalid seconds in time: '%s'",value);
523 return 0;
524 }
525 break;
526 default:
527 DB::logError("Result: invalid date/time value: '%s'",value);
528 return 0;
529 }
530
531 return sqlite3_gmtime(&gm_tm);
532 }
533
534 unsigned char DB::Result::getUChar(unsigned int fieldidx)
535 {
536 if (!isValid()) {
537 DB::logError("Result::getUChar: statement is not valid");
538 return 0;
539 }
540 if (fieldidx == 0) {
541 DB::logError("Result: zero is an invalid field index");
542 return 0;
543 }
544 int value = sqlite3_column_int(_handle->_stmt, fieldidx-1);
545 reportError(_handle->_stmt);
546 return (unsigned char)value;
547 }
548
549 float DB::Result::getFloat(unsigned int fieldidx)
550 {
551 if (!isValid()) {
552 DB::logError("Result::getFloat: statement is not valid");
553 return 0.0f;
554 }
555 if (fieldidx == 0) {
556 DB::logError("Result: zero is an invalid field index");
557 return 0.0f;
558 }
559 double value = sqlite3_column_double(_handle->_stmt, fieldidx-1);
560 reportError(_handle->_stmt);
561 return (float)value;
562 }
563
564 double DB::Result::getDouble(unsigned int fieldidx)
565 {
566 if (!isValid()) {
567 DB::logError("Result::getDouble: statement is not valid");
568 return 0.0;
569 }
570 if (fieldidx == 0) {
571 DB::logError("Result: zero is an invalid field index");
572 return 0.0;
573 }
574 double value = sqlite3_column_double(_handle->_stmt, fieldidx-1);
575 reportError(_handle->_stmt);
576 return value;
577 }
578
579 int DB::Result::getInt(unsigned int fieldidx)
580 {
581 if (!isValid()) {
582 DB::logError("Result::getInt: statement is not valid");
583 return 0;
584 }
585 if (fieldidx == 0) {
586 DB::logError("Result: zero is an invalid field index");
587 return 0;
588 }
589 int value = sqlite3_column_int(_handle->_stmt, fieldidx-1);
590 reportError(_handle->_stmt);
591 return value;
592 }
593
594 unsigned int DB::Result::getUInt(unsigned int fieldidx)
595 {
596 if (!isValid()) {
597 DB::logError("Result::getUInt: statement is not valid");
598 return 0;
599 }
600 if (fieldidx == 0) {
601 DB::logError("Result: zero is an invalid field index");
602 return 0;
603 }
604 int value = sqlite3_column_int(_handle->_stmt, fieldidx-1);
605 reportError(_handle->_stmt);
606 return (unsigned int)value;
607 }
608
609 long long DB::Result::getLongLong(unsigned int fieldidx)
610 {
611 if (!isValid()) {
612 DB::logError("Result::getLongLong: statement is not valid");
613 return 0;
614 }
615 if (fieldidx == 0) {
616 DB::logError("Result: zero is an invalid field index");
617 return 0;
618 }
619 sqlite3_int64 value = sqlite3_column_int64(_handle->_stmt, fieldidx-1);
620 reportError(_handle->_stmt);
621 return value;
622 }
623
624 unsigned long long DB::Result::getULongLong(unsigned int fieldidx)
625 {
626 if (!isValid()) {
627 DB::logError("Result::getULongLong: statement is not valid");
628 return 0;
629 }
630 if (fieldidx == 0) {
631 DB::logError("Result: zero is an invalid field index");
632 return 0;
633 }
634 sqlite3_int64 value = sqlite3_column_int64(_handle->_stmt, fieldidx-1);
635 reportError(_handle->_stmt);
636 return (unsigned long long)value;
637 }
638
639 const char *DB::Result::getString(unsigned int fieldidx)
640 {
641 if (!isValid()) {
642 DB::logError("Result::getString: statement is not valid");
643 return NULL;
644 }
645 if (fieldidx == 0) {
646 DB::logError("Result: zero is an invalid field index");
647 return NULL;
648 }
649 const unsigned char *value = sqlite3_column_text(_handle->_stmt,fieldidx-1);
650 reportError(_handle->_stmt);
651 return (const char *)value;
652 }
653
654 const unsigned char *DB::Result::getBinary(unsigned int fieldidx)
655 {
656 if (!isValid()) {
657 DB::logError("Result::getBinary: statement is not valid");
658 return NULL;
659 }
660 if (fieldidx == 0) {
661 DB::logError("Result: zero is an invalid field index");
662 return NULL;
663 }
664 const unsigned char *value =
665 (const unsigned char *)sqlite3_column_blob(_handle->_stmt,fieldidx-1);
666 reportError(_handle->_stmt);
667 return value;
668 }
669
670 size_t DB::Result::getFieldLength(unsigned int fieldidx)
671 {
672 if (!isValid()) {
673 DB::logError("Result::getFieldLength: statement is not valid");
674 return 0;
675 }
676 if (fieldidx == 0) {
677 DB::logError("Result: zero is an invalid field index");
678 return 0;
679 }
680 int value = sqlite3_column_bytes(_handle->_stmt,fieldidx-1);
681 reportError(_handle->_stmt);
682 return (size_t)value;
683 }
684
685 bool DB::Result::firstRow()
686 {
687 if (!isValid()) {
688 DB::logError("Result::firstRow: statement is not valid");
689 return false;
690 }
691 return _handle->reset() && _handle->step()==Statement::ReturnCodeRow;
692 }
693
694 bool DB::Result::nextRow()
695 {
696 if (!isValid()) {
697 DB::logError("Result::nextRow: statement is not valid");
698 return false;
699 }
700 return _handle->step()==Statement::ReturnCodeRow;
701 }
702
703 /**************************
704 * Connection
705 **************************/
706
707 DB::Connection *DB::Connection::Create(const std::string &dbdir, const std::string &dbname)
708 {
709 if (dbdir.length() == 0) {
710 DB::logError("Connection::Create: database directory parameter dbdir is empty");
711 return NULL;
712 }
713
714 if (dbname.length() == 0) {
715 DB::logError("Connection::Create: database name parameter dbname is empty");
716 return NULL;
717 }
718
719 return new Connection(dbdir,dbname);
720 }
721
722 DB::Connection::Connection(const std::string &dbdir, const std::string &dbname)
723 : _dbdir(dbdir)
724 , _dbpath(dbdir + OS_PATHSEP + dbname)
725 , _db(NULL)
726 {
727 }
728
729 DB::Connection::~Connection()
730 {
731 close();
732 }
733
734 const std::string &DB::Connection::dbdir()
735 {
736 return _dbdir;
737 }
738
739 const std::string &DB::Connection::dbpath()
740 {
741 return _dbpath;
742 }
743
744 DB::Statement DB::Connection::prepare(const std::string &format, ...){
745 // pstatement will hold a dynamically allocated string that needs to be deleted.
746 char *pstatement = NULL;
747
748 // short form
749 char statement[128];
750 va_list args;
751 va_start(args, format);
752 int cneeded = vsnprintf(statement,sizeof(statement),format.c_str(),args);
753 va_end(args);
754 if (cneeded<0) {
755 DB::logError("Connection::prepare: vsnprintf encoding error");
756 return Statement();
757 }
758 if (((size_t)cneeded)>=sizeof(statement)) {
759 // long form
760 pstatement = new char[cneeded+1];
761 if (!pstatement) {
762 DB::logError("Connection::prepare: out of memory");
763 return Statement();
764 }
765 va_start(args, format);
766 bool ok = vsnprintf(pstatement,cneeded+1,format.c_str(),args)==cneeded;
767 va_end(args);
768 if (!ok) {
769 DB::logError("Connection::prepare: vsnprintf error");
770 delete[] pstatement;
771 return Statement();
772 }
773 }
774
775 sqlite3_stmt *stmt = NULL;
776 int rv = sqlite3_prepare_v2(_db,
777 pstatement ? pstatement : statement,
778 cneeded+1,
779 &stmt,
780 NULL);
781
782 if (pstatement)
783 delete[] pstatement;
784
785 if (rv != SQLITE_OK) {
786 reportErrorDB(_db);
787 if (stmt)
788 sqlite3_finalize(stmt);
789 return Statement();
790 }
791
792 if (!stmt) {
793 DB::logError("Connection::prepare: expected sqlite3_prepare_v2 to return a compiled "
794 "statement, got NULL, out of memory ?");
795 return Statement();
796 }
797
798 return Statement(stmt);
799 }
800
801 DB::Result DB::Connection::perform(DB::Statement &statement)
802 {
803 return (statement.step()==Statement::ReturnCodeRow) ? Result(statement) : Result();
804 }
805
806 bool DB::Connection::execute(DB::Statement &statement)
807 {
808 return statement.step()==Statement::ReturnCodeDone;
809 }
810
811 bool DB::Connection::connect(const char *
812 #if HAVE_SQL_TRACE
813 connectionLabel
814 #endif
815 )
816 {
817 // Create and set file permissions if the DB does not exist.
818 int fd = open(_dbpath.c_str(), O_CREAT, S_IRUSR | S_IWUSR);
819 if (fd == -1)
820 {
821 DB::logError("Could not open database: %s (errno %i)",
822 _dbpath.c_str(), errno);
823 return false;
824 }
825 ::close(fd);
826
827 int rv = sqlite3_open_v2(_dbpath.c_str(),
828 &_db,
829 SQLITE_OPEN_READWRITE
830 | SQLITE_OPEN_CREATE
831 | SQLITE_OPEN_FULLMUTEX,
832 NULL);
833
834 if (rv != SQLITE_OK) {
835 reportErrorDB(_db);
836 return false;
837 }
838
839 int foreignKeyEnabled = 0;
840 rv = sqlite3_db_config(_db,SQLITE_DBCONFIG_ENABLE_FKEY,1,&foreignKeyEnabled);
841 if (rv != SQLITE_OK) {
842 reportErrorDB(_db);
843 return false;
844 }
845
846 if (foreignKeyEnabled != 1) {
847 DB::logError("Connection::connect: foreign key support not enabled");
848 return false;
849 }
850
851 rv = sqlite3_busy_timeout(_db, 180000); // 3 minutes
852 if (rv != SQLITE_OK) {
853 reportErrorDB(_db);
854 return false;
855 }
856 #if HAVE_SQL_TRACE
857 sqlite3_trace(_db, xTrace, const_cast<char *>(connectionLabel));
858 #endif
859 return true;
860 }
861
862 void DB::Connection::close()
863 {
864 if (_db) {
865 sqlite3_close(_db);
866 _db = NULL;
867 }
868 }
869
870 bool DB::Connection::setBusyTimeout(int ms)
871 {
872 int rv = sqlite3_busy_timeout(_db, ms);
873 if (rv != SQLITE_OK) {
874 reportErrorDB(_db);
875 return false;
876 }
877
878 return true;
879 }
880
881 bool DB::Connection::tableExists(const std::string &tablename)
882 {
883 Statement statement = prepare("select name from sqlite_master where type='table' and name='%s';",tablename.c_str());
884 return statement.step()==Statement::ReturnCodeRow && statement.step()==Statement::ReturnCodeDone;
885 }
886
887 long long DB::Connection::lastInsertRowId()
888 {
889 return sqlite3_last_insert_rowid(_db);
890 }
891
892 bool DB::Connection::inTransaction()
893 {
894 return sqlite3_get_autocommit(_db)==0;
895 }
896
897 bool DB::Connection::beginTransactionRO()
898 {
899 Statement statement = prepare("begin");
900 return statement.step()==Statement::ReturnCodeDone;
901 }
902
903 bool DB::Connection::endTransactionRO()
904 {
905 Statement statement = prepare("end");
906 return statement.step()==Statement::ReturnCodeDone;
907 }
908
909 bool DB::Connection::beginTransactionRW()
910 {
911 Statement statement = prepare("begin immediate");
912 return statement.step()==Statement::ReturnCodeDone;
913 }
914
915 bool DB::Connection::commitTransaction()
916 {
917 Statement statement = prepare("commit");
918 return statement.step()==Statement::ReturnCodeDone;
919 }
920
921 bool DB::Connection::rollbackTransaction()
922 {
923 Statement statement = prepare("rollback");
924 return statement.step()==Statement::ReturnCodeDone;
925 }
926