summaryrefslogtreecommitdiff
path: root/src/dpl/db/src/sql_connection.cpp
blob: 4bee5ded3a28a695b41dbcd0b21a4b7bbc0abcb0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
/*
 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
/*
 * @file        sql_connection.cpp
 * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
 * @version     1.0
 * @brief       This file is the implementation file of SQL connection
 */
#include <stddef.h>
#include <db-util.h>
#include <unistd.h>
#include <cstdio>
#include <cstdarg>

#include <cchecker/dpl/scoped_free.h>
#include <cchecker/dpl/noncopyable.h>
#include <cchecker/dpl/assert.h>
#include <cchecker/dpl/db/sql_connection.h>
#include <cchecker/dpl/db/naive_synchronization_object.h>

#include "common/log.h"

namespace CCHECKER {
namespace DB {
namespace // anonymous
{
class ScopedNotifyAll :
    public Noncopyable
{
  private:
    SqlConnection::SynchronizationObject *m_synchronizationObject;

  public:
    explicit ScopedNotifyAll(
        SqlConnection::SynchronizationObject *synchronizationObject) :
        m_synchronizationObject(synchronizationObject)
    {}

    ~ScopedNotifyAll()
    {
        if (!m_synchronizationObject) {
            return;
        }

        LogDebug("Notifying after successful synchronize");
        m_synchronizationObject->NotifyAll();
    }
};
} // namespace anonymous

SqlConnection::DataCommand::DataCommand(SqlConnection *connection,
                                        const char *buffer) :
    m_masterConnection(connection),
    m_stmt(NULL)
{
    Assert(connection != NULL);

    // Notify all after potentially synchronized database connection access
    ScopedNotifyAll notifyAll(connection->m_synchronizationObject.get());

    for (;;) {
        int ret = sqlite3_prepare_v2(connection->m_connection,
                                     buffer, strlen(buffer),
                                     &m_stmt, NULL);

        if (ret == SQLITE_OK) {
            LogDebug("Data command prepared successfuly");
            break;
        } else if (ret == SQLITE_BUSY) {
            LogDebug("Collision occurred while preparing SQL command");

            // Synchronize if synchronization object is available
            if (connection->m_synchronizationObject) {
                LogDebug("Performing synchronization");
                connection->m_synchronizationObject->Synchronize();
                continue;
            }

            // No synchronization object defined. Fail.
        }

        // Fatal error
        const char *error = sqlite3_errmsg(m_masterConnection->m_connection);

        LogDebug("SQL prepare data command failed");
        LogDebug("    Statement: " << buffer);
        LogDebug("    Error: " << error);

        ThrowMsg(Exception::SyntaxError, error);
    }

    LogDebug("Prepared data command: " << buffer);

    // Increment stored data command count
    ++m_masterConnection->m_dataCommandsCount;
}

SqlConnection::DataCommand::~DataCommand()
{
    LogDebug("SQL data command finalizing");

    if (sqlite3_finalize(m_stmt) != SQLITE_OK) {
        LogDebug("Failed to finalize data command");
    }

    // Decrement stored data command count
    --m_masterConnection->m_dataCommandsCount;
}

void SqlConnection::DataCommand::CheckBindResult(int result)
{
    if (result != SQLITE_OK) {
        const char *error = sqlite3_errmsg(
                m_masterConnection->m_connection);

        LogDebug("Failed to bind SQL statement parameter");
        LogDebug("    Error: " << error);

        ThrowMsg(Exception::SyntaxError, error);
    }
}

void SqlConnection::DataCommand::BindNull(
    SqlConnection::ArgumentIndex position)
{
    CheckBindResult(sqlite3_bind_null(m_stmt, position));
    LogDebug("SQL data command bind null: ["
                << position << "]");
}

void SqlConnection::DataCommand::BindInteger(
    SqlConnection::ArgumentIndex position,
    int value)
{
    CheckBindResult(sqlite3_bind_int(m_stmt, position, value));
    LogDebug("SQL data command bind integer: ["
                << position << "] -> " << value);
}

void SqlConnection::DataCommand::BindInt8(
    SqlConnection::ArgumentIndex position,
    int8_t value)
{
    CheckBindResult(sqlite3_bind_int(m_stmt, position,
                                     static_cast<int>(value)));
    LogDebug("SQL data command bind int8: ["
                << position << "] -> " << value);
}

void SqlConnection::DataCommand::BindInt16(
    SqlConnection::ArgumentIndex position,
    int16_t value)
{
    CheckBindResult(sqlite3_bind_int(m_stmt, position,
                                     static_cast<int>(value)));
    LogDebug("SQL data command bind int16: ["
                << position << "] -> " << value);
}

void SqlConnection::DataCommand::BindInt32(
    SqlConnection::ArgumentIndex position,
    int32_t value)
{
    CheckBindResult(sqlite3_bind_int(m_stmt, position,
                                     static_cast<int>(value)));
    LogDebug("SQL data command bind int32: ["
                << position << "] -> " << value);
}

void SqlConnection::DataCommand::BindInt64(
    SqlConnection::ArgumentIndex position,
    int64_t value)
{
    CheckBindResult(sqlite3_bind_int64(m_stmt, position,
                                       static_cast<sqlite3_int64>(value)));
    LogDebug("SQL data command bind int64: ["
                << position << "] -> " << value);
}

void SqlConnection::DataCommand::BindFloat(
    SqlConnection::ArgumentIndex position,
    float value)
{
    CheckBindResult(sqlite3_bind_double(m_stmt, position,
                                        static_cast<double>(value)));
    LogDebug("SQL data command bind float: ["
                << position << "] -> " << value);
}

void SqlConnection::DataCommand::BindDouble(
    SqlConnection::ArgumentIndex position,
    double value)
{
    CheckBindResult(sqlite3_bind_double(m_stmt, position, value));
    LogDebug("SQL data command bind double: ["
                << position << "] -> " << value);
}

void SqlConnection::DataCommand::BindString(
    SqlConnection::ArgumentIndex position,
    const char *value)
{
    if (!value) {
        BindNull(position);
        return;
    }

    // Assume that text may disappear
    CheckBindResult(sqlite3_bind_text(m_stmt, position,
                                      value, strlen(value),
                                      SQLITE_TRANSIENT));

    LogDebug("SQL data command bind string: ["
                << position << "] -> " << value);
}

void SqlConnection::DataCommand::BindString(
    SqlConnection::ArgumentIndex position,
    const String &value)
{
    BindString(position, ToUTF8String(value).c_str());
}

void SqlConnection::DataCommand::BindInteger(
    SqlConnection::ArgumentIndex position,
    const Optional<int> &value)
{
    if (value.IsNull()) {
        BindNull(position);
    } else {
        BindInteger(position, *value);
    }
}

void SqlConnection::DataCommand::BindInt8(
    SqlConnection::ArgumentIndex position,
    const Optional<int8_t> &value)
{
    if (value.IsNull()) {
        BindNull(position);
    } else {
        BindInt8(position, *value);
    }
}

void SqlConnection::DataCommand::BindInt16(
    SqlConnection::ArgumentIndex position,
    const Optional<int16_t> &value)
{
    if (value.IsNull()) {
        BindNull(position);
    } else {
        BindInt16(position, *value);
    }
}

void SqlConnection::DataCommand::BindInt32(
    SqlConnection::ArgumentIndex position,
    const Optional<int32_t> &value)
{
    if (value.IsNull()) {
        BindNull(position);
    } else {
        BindInt32(position, *value);
    }
}

void SqlConnection::DataCommand::BindInt64(
    SqlConnection::ArgumentIndex position,
    const Optional<int64_t> &value)
{
    if (value.IsNull()) {
        BindNull(position);
    } else {
        BindInt64(position, *value);
    }
}

void SqlConnection::DataCommand::BindFloat(
    SqlConnection::ArgumentIndex position,
    const Optional<float> &value)
{
    if (value.IsNull()) {
        BindNull(position);
    } else {
        BindFloat(position, *value);
    }
}

void SqlConnection::DataCommand::BindDouble(
    SqlConnection::ArgumentIndex position,
    const Optional<double> &value)
{
    if (value.IsNull()) {
        BindNull(position);
    } else {
        BindDouble(position, *value);
    }
}

void SqlConnection::DataCommand::BindString(
    SqlConnection::ArgumentIndex position,
    const Optional<String> &value)
{
    if (!!value) {
        BindString(position, ToUTF8String(*value).c_str());
    } else {
        BindNull(position);
    }
}

bool SqlConnection::DataCommand::Step()
{
    // Notify all after potentially synchronized database connection access
    ScopedNotifyAll notifyAll(
        m_masterConnection->m_synchronizationObject.get());

    for (;;) {
        int ret = sqlite3_step(m_stmt);

        if (ret == SQLITE_ROW) {
            LogDebug("SQL data command step ROW");
            return true;
        } else if (ret == SQLITE_DONE) {
            LogDebug("SQL data command step DONE");
            return false;
        } else if (ret == SQLITE_BUSY) {
            LogDebug("Collision occurred while executing SQL command");

            // Synchronize if synchronization object is available
            if (m_masterConnection->m_synchronizationObject) {
                LogDebug("Performing synchronization");

                m_masterConnection->
                    m_synchronizationObject->Synchronize();

                continue;
            }

            // No synchronization object defined. Fail.
        }

        // Fatal error
        const char *error = sqlite3_errmsg(m_masterConnection->m_connection);

        LogDebug("SQL step data command failed");
        LogDebug("    Error: " << error);

        ThrowMsg(Exception::InternalError, error);
    }
}

void SqlConnection::DataCommand::Reset()
{
    /*
     * According to:
     * http://www.sqlite.org/c3ref/stmt.html
     *
     * if last sqlite3_step command on this stmt returned an error,
     * then sqlite3_reset will return that error, althought it is not an error.
     * So sqlite3_reset allways succedes.
     */
    sqlite3_reset(m_stmt);

    LogDebug("SQL data command reset");
}

void SqlConnection::DataCommand::CheckColumnIndex(
    SqlConnection::ColumnIndex column)
{
    if (column < 0 || column >= sqlite3_column_count(m_stmt)) {
        ThrowMsg(Exception::InvalidColumn, "Column index is out of bounds");
    }
}

bool SqlConnection::DataCommand::IsColumnNull(
    SqlConnection::ColumnIndex column)
{
    LogDebug("SQL data command get column type: [" << column << "]");
    CheckColumnIndex(column);
    return sqlite3_column_type(m_stmt, column) == SQLITE_NULL;
}

int SqlConnection::DataCommand::GetColumnInteger(
    SqlConnection::ColumnIndex column)
{
    LogDebug("SQL data command get column integer: [" << column << "]");
    CheckColumnIndex(column);
    int value = sqlite3_column_int(m_stmt, column);
    LogDebug("    Value: " << value);
    return value;
}

int8_t SqlConnection::DataCommand::GetColumnInt8(
    SqlConnection::ColumnIndex column)
{
    LogDebug("SQL data command get column int8: [" << column << "]");
    CheckColumnIndex(column);
    int8_t value = static_cast<int8_t>(sqlite3_column_int(m_stmt, column));
    LogDebug("    Value: " << value);
    return value;
}

int16_t SqlConnection::DataCommand::GetColumnInt16(
    SqlConnection::ColumnIndex column)
{
    LogDebug("SQL data command get column int16: [" << column << "]");
    CheckColumnIndex(column);
    int16_t value = static_cast<int16_t>(sqlite3_column_int(m_stmt, column));
    LogDebug("    Value: " << value);
    return value;
}

int32_t SqlConnection::DataCommand::GetColumnInt32(
    SqlConnection::ColumnIndex column)
{
    LogDebug("SQL data command get column int32: [" << column << "]");
    CheckColumnIndex(column);
    int32_t value = static_cast<int32_t>(sqlite3_column_int(m_stmt, column));
    LogDebug("    Value: " << value);
    return value;
}

int64_t SqlConnection::DataCommand::GetColumnInt64(
    SqlConnection::ColumnIndex column)
{
    LogDebug("SQL data command get column int64: [" << column << "]");
    CheckColumnIndex(column);
    int64_t value = static_cast<int64_t>(sqlite3_column_int64(m_stmt, column));
    LogDebug("    Value: " << value);
    return value;
}

float SqlConnection::DataCommand::GetColumnFloat(
    SqlConnection::ColumnIndex column)
{
    LogDebug("SQL data command get column float: [" << column << "]");
    CheckColumnIndex(column);
    float value = static_cast<float>(sqlite3_column_double(m_stmt, column));
    LogDebug("    Value: " << value);
    return value;
}

double SqlConnection::DataCommand::GetColumnDouble(
    SqlConnection::ColumnIndex column)
{
    LogDebug("SQL data command get column double: [" << column << "]");
    CheckColumnIndex(column);
    double value = sqlite3_column_double(m_stmt, column);
    LogDebug("    Value: " << value);
    return value;
}

std::string SqlConnection::DataCommand::GetColumnString(
    SqlConnection::ColumnIndex column)
{
    LogDebug("SQL data command get column string: [" << column << "]");
    CheckColumnIndex(column);

    const char *value = reinterpret_cast<const char *>(
            sqlite3_column_text(m_stmt, column));

    LogDebug("Value: " << (value ? value : "NULL"));

    if (value == NULL) {
        return std::string();
    }

    return std::string(value);
}

Optional<int> SqlConnection::DataCommand::GetColumnOptionalInteger(
    SqlConnection::ColumnIndex column)
{
    LogDebug("SQL data command get column optional integer: ["
                << column << "]");
    CheckColumnIndex(column);
    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
        return Optional<int>::Null;
    }
    int value = sqlite3_column_int(m_stmt, column);
    LogDebug("    Value: " << value);
    return Optional<int>(value);
}

Optional<int8_t> SqlConnection::DataCommand::GetColumnOptionalInt8(
    SqlConnection::ColumnIndex column)
{
    LogDebug("SQL data command get column optional int8: ["
                << column << "]");
    CheckColumnIndex(column);
    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
        return Optional<int8_t>::Null;
    }
    int8_t value = static_cast<int8_t>(sqlite3_column_int(m_stmt, column));
    LogDebug("    Value: " << value);
    return Optional<int8_t>(value);
}

Optional<int16_t> SqlConnection::DataCommand::GetColumnOptionalInt16(
    SqlConnection::ColumnIndex column)
{
    LogDebug("SQL data command get column optional int16: ["
                << column << "]");
    CheckColumnIndex(column);
    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
        return Optional<int16_t>::Null;
    }
    int16_t value = static_cast<int16_t>(sqlite3_column_int(m_stmt, column));
    LogDebug("    Value: " << value);
    return Optional<int16_t>(value);
}

Optional<int32_t> SqlConnection::DataCommand::GetColumnOptionalInt32(
    SqlConnection::ColumnIndex column)
{
    LogDebug("SQL data command get column optional int32: ["
                << column << "]");
    CheckColumnIndex(column);
    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
        return Optional<int32_t>::Null;
    }
    int32_t value = static_cast<int32_t>(sqlite3_column_int(m_stmt, column));
    LogDebug("    Value: " << value);
    return Optional<int32_t>(value);
}

Optional<int64_t> SqlConnection::DataCommand::GetColumnOptionalInt64(
    SqlConnection::ColumnIndex column)
{
    LogDebug("SQL data command get column optional int64: ["
                << column << "]");
    CheckColumnIndex(column);
    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
        return Optional<int64_t>::Null;
    }
    int64_t value = static_cast<int64_t>(sqlite3_column_int64(m_stmt, column));
    LogDebug("    Value: " << value);
    return Optional<int64_t>(value);
}

Optional<float> SqlConnection::DataCommand::GetColumnOptionalFloat(
    SqlConnection::ColumnIndex column)
{
    LogDebug("SQL data command get column optional float: ["
                << column << "]");
    CheckColumnIndex(column);
    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
        return Optional<float>::Null;
    }
    float value = static_cast<float>(sqlite3_column_double(m_stmt, column));
    LogDebug("    Value: " << value);
    return Optional<float>(value);
}

Optional<double> SqlConnection::DataCommand::GetColumnOptionalDouble(
    SqlConnection::ColumnIndex column)
{
    LogDebug("SQL data command get column optional double: ["
                << column << "]");
    CheckColumnIndex(column);
    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
        return Optional<double>::Null;
    }
    double value = sqlite3_column_double(m_stmt, column);
    LogDebug("    Value: " << value);
    return Optional<double>(value);
}

Optional<String> SqlConnection::DataCommand::GetColumnOptionalString(
    SqlConnection::ColumnIndex column)
{
    LogDebug("SQL data command get column optional string: ["
                << column << "]");
    CheckColumnIndex(column);
    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
        return Optional<String>::Null;
    }
    const char *value = reinterpret_cast<const char *>(
            sqlite3_column_text(m_stmt, column));
    LogDebug("Value: " << value);
    String s = FromUTF8String(value);
    return Optional<String>(s);
}

void SqlConnection::Connect(const std::string &address,
                            Flag::Type type,
                            Flag::Option flag)
{
    if (m_connection != NULL) {
        LogDebug("Already connected.");
        return;
    }
    LogDebug("Connecting to DB: " << address << "...");

    // Connect to database
    int result;
    if (type & Flag::UseLucene) {
        result = db_util_open_with_options(
                address.c_str(),
                &m_connection,
                flag,
                NULL);

        m_usingLucene = true;
        LogDebug("Lucene index enabled");
    } else {
        result = sqlite3_open_v2(
                address.c_str(),
                &m_connection,
                flag,
                NULL);

        m_usingLucene = false;
        LogDebug("Lucene index disabled");
    }

    if (result == SQLITE_OK) {
        LogDebug("Connected to DB");
    } else {
        LogDebug("Failed to connect to DB!");
        ThrowMsg(Exception::ConnectionBroken, address);
    }

    // Enable foreign keys
    TurnOnForeignKeys();
}

void SqlConnection::Disconnect()
{
    if (m_connection == NULL) {
        LogDebug("Already disconnected.");
        return;
    }

    LogDebug("Disconnecting from DB...");

    // All stored data commands must be deleted before disconnect
    Assert(m_dataCommandsCount == 0 &&
           "All stored procedures must be deleted"
           " before disconnecting SqlConnection");

    int result;

    if (m_usingLucene) {
        result = db_util_close(m_connection);
    } else {
        result = sqlite3_close(m_connection);
    }

    if (result != SQLITE_OK) {
        const char *error = sqlite3_errmsg(m_connection);
        LogDebug("SQL close failed");
        LogDebug("    Error: " << error);
        Throw(Exception::InternalError);
    }

    m_connection = NULL;

    LogDebug("Disconnected from DB");
}

bool SqlConnection::CheckTableExist(const char *tableName)
{
    if (m_connection == NULL) {
        LogDebug("Cannot execute command. Not connected to DB!");
        return false;
    }

    DataCommandAutoPtr command =
        PrepareDataCommand("select tbl_name from sqlite_master where name=?;");

    command->BindString(1, tableName);

    if (!command->Step()) {
        LogDebug("No matching records in table");
        return false;
    }

    return command->GetColumnString(0) == tableName;
}

SqlConnection::SqlConnection(const std::string &address,
                             Flag::Type flag,
                             Flag::Option option,
                             SynchronizationObject *synchronizationObject) :
    m_connection(NULL),
    m_usingLucene(false),
    m_dataCommandsCount(0),
    m_synchronizationObject(synchronizationObject)
{
    LogDebug("Opening database connection to: " << address);

    // Connect to DB
    SqlConnection::Connect(address, flag, option);

    if (!m_synchronizationObject) {
        LogDebug("No synchronization object defined");
    }
}

SqlConnection::~SqlConnection()
{
    LogDebug("Closing database connection");

    // Disconnect from DB
    Try
    {
        SqlConnection::Disconnect();
    }
    Catch(Exception::Base)
    {
        LogDebug("Failed to disconnect from database");
    }
}

void SqlConnection::ExecCommand(const char *format, ...)
{
    if (m_connection == NULL) {
        LogDebug("Cannot execute command. Not connected to DB!");
        return;
    }

    if (format == NULL) {
        LogDebug("Null query!");
        ThrowMsg(Exception::SyntaxError, "Null statement");
    }

    char *rawBuffer;

    va_list args;
    va_start(args, format);

    if (vasprintf(&rawBuffer, format, args) == -1) {
        rawBuffer = NULL;
    }

    va_end(args);

    ScopedFree<char> buffer(rawBuffer);

    if (!buffer) {
        LogDebug("Failed to allocate statement string");
        return;
    }

    LogDebug("Executing SQL command: " << buffer.Get());

    // Notify all after potentially synchronized database connection access
    ScopedNotifyAll notifyAll(m_synchronizationObject.get());

    for (;;) {
        char *errorBuffer;

        int ret = sqlite3_exec(m_connection,
                               buffer.Get(),
                               NULL,
                               NULL,
                               &errorBuffer);

        std::string errorMsg;

        // Take allocated error buffer
        if (errorBuffer != NULL) {
            errorMsg = errorBuffer;
            sqlite3_free(errorBuffer);
        }

        if (ret == SQLITE_OK) {
            return;
        }

        if (ret == SQLITE_BUSY) {
            LogDebug("Collision occurred while executing SQL command");

            // Synchronize if synchronization object is available
            if (m_synchronizationObject) {
                LogDebug("Performing synchronization");
                m_synchronizationObject->Synchronize();
                continue;
            }

            // No synchronization object defined. Fail.
        }

        // Fatal error
        LogDebug("Failed to execute SQL command. Error: " << errorMsg);
        ThrowMsg(Exception::SyntaxError, errorMsg);
    }
}

SqlConnection::DataCommandAutoPtr SqlConnection::PrepareDataCommand(
    const char *format,
    ...)
{
    if (m_connection == NULL) {
        LogDebug("Cannot execute data command. Not connected to DB!");
        return DataCommandAutoPtr();
    }

    char *rawBuffer;

    va_list args;
    va_start(args, format);

    if (vasprintf(&rawBuffer, format, args) == -1) {
        rawBuffer = NULL;
    }

    va_end(args);

    ScopedFree<char> buffer(rawBuffer);

    if (!buffer) {
        LogDebug("Failed to allocate statement string");
        return DataCommandAutoPtr();
    }

    LogDebug("Executing SQL data command: " << buffer.Get());

    return DataCommandAutoPtr(new DataCommand(this, buffer.Get()));
}

SqlConnection::RowID SqlConnection::GetLastInsertRowID() const
{
    return static_cast<RowID>(sqlite3_last_insert_rowid(m_connection));
}

void SqlConnection::TurnOnForeignKeys()
{
    ExecCommand("PRAGMA foreign_keys = ON;");
}

SqlConnection::SynchronizationObject *
SqlConnection::AllocDefaultSynchronizationObject()
{
    return new NaiveSynchronizationObject();
}

void SqlConnection::BeginTransaction()
{
    ExecCommand("BEGIN;");
}

void SqlConnection::RollbackTransaction()
{
    ExecCommand("ROLLBACK;");
}

void SqlConnection::CommitTransaction()
{
    ExecCommand("COMMIT;");
}

} // namespace DB
} // namespace CCHECKER