aboutsummaryrefslogtreecommitdiff
path: root/odb/sqlite/statement.cxx
blob: 09188cb07c40638279ce61f2b08ddad2d5a9e265 (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
// file      : odb/sqlite/statement.cxx
// copyright : Copyright (c) 2005-2013 Code Synthesis Tools CC
// license   : GNU GPL v2; see accompanying LICENSE file

#include <odb/tracer.hxx>
#include <odb/exceptions.hxx> // object_not_persistent

#include <odb/sqlite/database.hxx>
#include <odb/sqlite/statement.hxx>
#include <odb/sqlite/connection.hxx>
#include <odb/sqlite/error.hxx>

#include <odb/sqlite/details/config.hxx> // LIBODB_SQLITE_HAVE_UNLOCK_NOTIFY

using namespace std;

namespace odb
{
  namespace sqlite
  {
    // statement
    //

    statement::
    ~statement ()
    {
      if (stmt_ != 0)
      {
        {
          odb::tracer* t;
          if ((t = conn_.transaction_tracer ()) ||
              (t = conn_.tracer ()) ||
              (t = conn_.database ().tracer ()))
            t->deallocate (conn_, *this);
        }

        if (next_ != this)
          list_remove ();

        stmt_.reset ();
      }
    }

    void statement::
    init (const char* text,
          std::size_t text_size,
          statement_kind sk,
          const binding* proc,
          bool optimize)
    {
      active_ = false;
      prev_ = 0;
      next_ = this;

      string tmp;
      if (proc != 0)
      {
        switch (sk)
        {
        case statement_select:
          process_select (text,
                          &proc->bind->buffer, proc->count, sizeof (bind),
                          '"', '"',
                          optimize,
                          tmp);
          break;
        case statement_insert:
          process_insert (text,
                          &proc->bind->buffer, proc->count, sizeof (bind),
                          '?',
                          tmp);
          break;
        case statement_update:
          process_update (text,
                          &proc->bind->buffer, proc->count, sizeof (bind),
                          '?',
                          tmp);
          break;
        case statement_delete:
        case statement_generic:
          assert (false);
        }

        text = tmp.c_str ();
        text_size = tmp.size ();
      }

#if SQLITE_VERSION_NUMBER < 3005003
      text_.assign (text, text_size);
#endif

      // Empty statement.
      //
      if (*text == '\0')
        return;

      {
        odb::tracer* t;
        if ((t = conn_.transaction_tracer ()) ||
            (t = conn_.tracer ()) ||
            (t = conn_.database ().tracer ()))
        {
          // Temporarily store the statement text in prev_ so that
          // text() which may be called by the tracer can access it.
          //
#if SQLITE_VERSION_NUMBER >= 3005003
          prev_ = reinterpret_cast<statement*> (const_cast<char*> (text));
#endif
          t->prepare (conn_, *this);
#if SQLITE_VERSION_NUMBER >= 3005003
          prev_ = 0;
#endif
        }
      }

      int e;
      sqlite3_stmt* stmt (0);

      // sqlite3_prepare_v2() is only available since SQLite 3.3.9
      // but is buggy until 3.3.11.
      //
#if SQLITE_VERSION_NUMBER >= 3003011
      while ((e = sqlite3_prepare_v2 (conn_.handle (),
                                      text,
                                      static_cast<int> (text_size),
                                      &stmt,
                                      0)) == SQLITE_LOCKED)
      {
        conn_.wait ();
      }
#else
      e = sqlite3_prepare (conn_.handle (),
                           text,
                           static_cast<int> (text_size),
                           &stmt,
                           0);
#endif

      if (e != SQLITE_OK)
        translate_error (e, conn_);

      stmt_.reset (stmt);
    }

    const char* statement::
    text () const
    {
      // sqlite3_sql() is only available since 3.5.3.
      //
#if SQLITE_VERSION_NUMBER >= 3005003
      if (stmt_ == 0)
        // See init() above for details on what's going on here.
        //
        return prev_ != 0 ? reinterpret_cast<const char*> (prev_) : "";
      else
        return sqlite3_sql (stmt_);
#else
      return text_.c_str ();
#endif
    }

    void statement::
    bind_param (const bind* p, size_t n)
    {
      int e (SQLITE_OK);

      // SQLite parameters are counted from 1.
      //
      for (size_t i (0), j (1); e == SQLITE_OK && i < n; ++i)
      {
        const bind& b (p[i]);

        if (b.buffer == 0) // Skip NULL entries.
          continue;

        int c (static_cast<int> (j++));

        if (b.is_null != 0 && *b.is_null)
        {
          e = sqlite3_bind_null (stmt_, c);
          continue;
        }

        switch (b.type)
        {
        case bind::integer:
          {
            long long v (*static_cast<long long*> (b.buffer));

            e = sqlite3_bind_int64 (stmt_,
                                    c,
            // Prior to 3.5.0, sqlite3_int64 was called sqlite_int64.
#if SQLITE_VERSION_NUMBER >= 3005000
                                    static_cast<sqlite3_int64> (v)
#else
                                    static_cast<sqlite_int64> (v)
#endif
            );
            break;
          }
        case bind::real:
          {
            double v (*static_cast<double*> (b.buffer));
            e = sqlite3_bind_double (stmt_, c, v);
            break;
          }
        case bind::text:
          {
            e = sqlite3_bind_text (stmt_,
                                   c,
                                   static_cast<const char*> (b.buffer),
                                   static_cast<int> (*b.size),
                                   SQLITE_STATIC);
            break;
          }
        case bind::text16:
          {
            e = sqlite3_bind_text16 (stmt_,
                                     c,
                                     b.buffer,
                                     static_cast<int> (*b.size),
                                     SQLITE_STATIC);
            break;
          }
        case bind::blob:
          {
            e = sqlite3_bind_blob (stmt_,
                                   c,
                                   b.buffer,
                                   static_cast<int> (*b.size),
                                   SQLITE_STATIC);
            break;
          }
        }
      }

      if (e != SQLITE_OK)
        translate_error (e, conn_);
    }

    bool statement::
    bind_result (const bind* p, size_t count, bool truncated)
    {
      bool r (true);
      int col_count (sqlite3_data_count (stmt_));

      int col (0);
      for (size_t i (0); i != count && col != col_count; ++i)
      {
        const bind& b (p[i]);

        if (b.buffer == 0) // Skip NULL entries.
          continue;

        int c (col++);

        if (truncated && (b.truncated == 0 || !*b.truncated))
          continue;

        if (b.truncated != 0)
          *b.truncated = false;

        // Check for NULL unless we are reloading a truncated result.
        //
        if (!truncated)
        {
          *b.is_null = sqlite3_column_type (stmt_, c) == SQLITE_NULL;

          if (*b.is_null)
            continue;
        }

        switch (b.type)
        {
        case bind::integer:
          {
            *static_cast<long long*> (b.buffer) =
              static_cast<long long> (sqlite3_column_int64 (stmt_, c));
            break;
          }
        case bind::real:
          {
            *static_cast<double*> (b.buffer) =
              sqlite3_column_double (stmt_, c);
            break;
          }
        case bind::text:
        case bind::text16:
        case bind::blob:
          {
            // SQLite documentation recommends that we first call *_text(),
            // *_text16(), or *_blob() function in order to force the type
            // conversion, if any.
            //
            const void* d;

            if (b.type != bind::text16)
            {
              d = b.type == bind::text
                ? sqlite3_column_text (stmt_, c)
                : sqlite3_column_blob (stmt_, c);
              *b.size = static_cast<size_t> (sqlite3_column_bytes (stmt_, c));
            }
            else
            {
              d = sqlite3_column_text16 (stmt_, c);
              *b.size = static_cast<size_t> (
                sqlite3_column_bytes16 (stmt_, c));
            }

            if (*b.size > b.capacity)
            {
              if (b.truncated != 0)
                *b.truncated = true;

              r = false;
              continue;
            }

            memcpy (b.buffer, d, *b.size);
            break;
          }
        }
      }

      // Make sure that the number of columns in the result returned by
      // the database matches the number that we expect. A common cause
      // of this assertion is a native view with a number of data members
      // not matching the number of columns in the SELECT-list.
      //
      assert (col == col_count);

      return r;
    }

    // generic_statement
    //

    generic_statement::
    generic_statement (connection_type& conn, const string& text)
        : statement (conn,
                     text, statement_generic,
                     0, false),
          result_set_ (stmt_ ? sqlite3_column_count (stmt_) != 0: false)
    {
    }

    generic_statement::
    generic_statement (connection_type& conn, const char* text)
        : statement (conn,
                     text, statement_generic,
                     0, false),
          result_set_ (stmt_ ? sqlite3_column_count (stmt_) != 0: false)
    {
    }

    generic_statement::
    generic_statement (connection_type& conn,
                       const char* text,
                       std::size_t text_size)
        : statement (conn,
                     text, text_size, statement_generic,
                     0, false),
          result_set_ (stmt_ ? sqlite3_column_count (stmt_) != 0: false)
    {
    }

    unsigned long long generic_statement::
    execute ()
    {
      if (stmt_ == 0) // Empty statement or comment.
        return 0;

      {
        odb::tracer* t;
        if ((t = conn_.transaction_tracer ()) ||
            (t = conn_.tracer ()) ||
            (t = conn_.database ().tracer ()))
          t->execute (conn_, *this);
      }

      unsigned long long r (0);

      int e;
      sqlite3* h (conn_.handle ());

#ifdef LIBODB_SQLITE_HAVE_UNLOCK_NOTIFY
      // Only the first call to sqlite3_step() can return SQLITE_LOCKED.
      //
      while ((e = sqlite3_step (stmt_)) == SQLITE_LOCKED)
      {
        if (sqlite3_extended_errcode (h) != SQLITE_LOCKED_SHAREDCACHE)
          break;

        sqlite3_reset (stmt_);
        conn_.wait ();
      }
#else
      e = sqlite3_step (stmt_);
#endif

      for (; e == SQLITE_ROW; e = sqlite3_step (stmt_))
        r++;

      // sqlite3_step() will return a detailed error code only if we used
      // sqlite3_prepare_v2(). Otherwise, sqlite3_reset() returns the
      // error.
      //
#if SQLITE_VERSION_NUMBER >= 3003011
      sqlite3_reset (stmt_);

      if (e != SQLITE_DONE)
        translate_error (e, conn_);
#else
      e = sqlite3_reset (stmt_);

      if (e != SQLITE_OK)
      {
        // If the schema has changed, try to re-prepare and re-execute the
        // statement. That's what newer versions of SQLite do automatically.
        //
        if (e == SQLITE_SCHEMA)
        {
          sqlite3_stmt* stmt (0);
          e = sqlite3_prepare (h,
                               text_.c_str (),
                               static_cast<int> (text_.size () + 1),
                               &stmt,
                               0);

          if (e != SQLITE_OK)
            translate_error (e, conn_);

          stmt_.reset (stmt);
          return execute (); // Try again by recursively calling ourselves.
        }
        else
          translate_error (e, conn_);
      }
#endif

      if (!result_set_)
        r = static_cast<unsigned long long> (sqlite3_changes (h));

      return r;
    }

    // select_statement
    //

    select_statement::
    select_statement (connection_type& conn,
                      const string& text,
                      bool process,
                      bool optimize,
                      binding& param,
                      binding& result)
        : statement (conn,
                     text, statement_select,
                     (process ? &result : 0), optimize),
          param_ (&param),
          result_ (result)
    {
    }

    select_statement::
    select_statement (connection_type& conn,
                      const char* text,
                      bool process,
                      bool optimize,
                      binding& param,
                      binding& result)
        : statement (conn,
                     text, statement_select,
                     (process ? &result : 0), optimize),
          param_ (&param),
          result_ (result)
    {
    }

    select_statement::
    select_statement (connection_type& conn,
                      const string& text,
                      bool process,
                      bool optimize,
                      binding& result)
        : statement (conn,
                     text, statement_select,
                     (process ? &result : 0), optimize),
          param_ (0),
          result_ (result)
    {
    }

    select_statement::
    select_statement (connection_type& conn,
                      const char* text,
                      bool process,
                      bool optimize,
                      binding& result)
        : statement (conn,
                     text, statement_select,
                     (process ? &result : 0), optimize),
          param_ (0),
          result_ (result)
    {
    }

    void select_statement::
    execute ()
    {
      if (active ())
        reset ();

      {
        odb::tracer* t;
        if ((t = conn_.transaction_tracer ()) ||
            (t = conn_.tracer ()) ||
            (t = conn_.database ().tracer ()))
          t->execute (conn_, *this);
      }

      done_ = false;

      if (param_ != 0)
        bind_param (param_->bind, param_->count);

      active (true);
    }

    void select_statement::
    free_result ()
    {
      reset ();
      done_ = true;
    }

    bool select_statement::
    next ()
    {
      if (!done_)
      {
        int e;

#ifdef LIBODB_SQLITE_HAVE_UNLOCK_NOTIFY
        sqlite3* h (conn_.handle ());
        while ((e = sqlite3_step (stmt_)) == SQLITE_LOCKED)
        {
          if (sqlite3_extended_errcode (h) != SQLITE_LOCKED_SHAREDCACHE)
            break;

          sqlite3_reset (stmt_);
          conn_.wait ();
        }
#else
        e = sqlite3_step (stmt_);
#endif

        if (e != SQLITE_ROW)
        {
          done_ = true;

          // sqlite3_step() will return a detailed error code only if we used
          // sqlite3_prepare_v2(). Otherwise, sqlite3_reset() returns the
          // error.
          //
#if SQLITE_VERSION_NUMBER >= 3003011
          reset ();

          if (e != SQLITE_DONE)
#else
          e = reset ();

          if (e != SQLITE_OK)
#endif
            translate_error (e, conn_);
        }
      }

      return !done_;
    }

    select_statement::result select_statement::
    load ()
    {
      if (done_)
        return no_data;

      return bind_result (result_.bind, result_.count) ? success : truncated;
    }

    void select_statement::
    reload ()
    {
      assert (!done_);

      if (!bind_result (result_.bind, result_.count, true))
        assert (false);
    }

    // insert_statement
    //

    insert_statement::
    insert_statement (connection_type& conn,
                      const string& text,
                      bool process,
                      binding& param,
                      binding* returning)
        : statement (conn,
                     text, statement_insert,
                     (process ? &param : 0), false),
          param_ (param),
          returning_ (returning)
    {
    }

    insert_statement::
    insert_statement (connection_type& conn,
                      const char* text,
                      bool process,
                      binding& param,
                      binding* returning)
        : statement (conn,
                     text, statement_insert,
                     (process ? &param : 0), false),
          param_ (param),
          returning_ (returning)
    {
    }

    bool insert_statement::
    execute ()
    {
      {
        odb::tracer* t;
        if ((t = conn_.transaction_tracer ()) ||
            (t = conn_.tracer ()) ||
            (t = conn_.database ().tracer ()))
          t->execute (conn_, *this);
      }

      bind_param (param_.bind, param_.count);

      int e;

#ifdef LIBODB_SQLITE_HAVE_UNLOCK_NOTIFY
      sqlite3* h (conn_.handle ());
      while ((e = sqlite3_step (stmt_)) == SQLITE_LOCKED)
      {
        if (sqlite3_extended_errcode (h) != SQLITE_LOCKED_SHAREDCACHE)
          break;

        sqlite3_reset (stmt_);
        conn_.wait ();
      }
#else
      e = sqlite3_step (stmt_);
#endif

      // sqlite3_step() will return a detailed error code only if we used
      // sqlite3_prepare_v2(). Otherwise, sqlite3_reset() returns the
      // error.
      //
#if SQLITE_VERSION_NUMBER >= 3003011
      sqlite3_reset (stmt_);

      if (e != SQLITE_DONE)
#else
      e = sqlite3_reset (stmt_);

      if (e != SQLITE_OK)
#endif
      {
        // SQLITE_CONSTRAINT error code covers more than just a duplicate
        // primary key. Unfortunately, there is nothing more precise that
        // we can use (even sqlite3_errmsg() returns generic "constraint
        // failed").
        //
        if (e == SQLITE_CONSTRAINT)
          return false;
        else
          translate_error (e, conn_);
      }

      if (returning_ != 0)
      {
        bind& b (returning_->bind[0]);

        *b.is_null = false;
        *static_cast<long long*> (b.buffer) =
          static_cast<long long> (
            sqlite3_last_insert_rowid (conn_.handle ()));
      }

      return true;
    }

    // update_statement
    //

    update_statement::
    update_statement (connection_type& conn,
                      const string& text,
                      bool process,
                      binding& param)
        : statement (conn,
                     text, statement_update,
                     (process ? &param : 0), false),
          param_ (param)
    {
    }

    update_statement::
    update_statement (connection_type& conn,
                      const char* text,
                      bool process,
                      binding& param)
        : statement (conn,
                     text, statement_update,
                     (process ? &param : 0), false),
          param_ (param)
    {
    }

    unsigned long long update_statement::
    execute ()
    {
      {
        odb::tracer* t;
        if ((t = conn_.transaction_tracer ()) ||
            (t = conn_.tracer ()) ||
            (t = conn_.database ().tracer ()))
          t->execute (conn_, *this);
      }

      bind_param (param_.bind, param_.count);

      int e;
      sqlite3* h (conn_.handle ());

#ifdef LIBODB_SQLITE_HAVE_UNLOCK_NOTIFY
      while ((e = sqlite3_step (stmt_)) == SQLITE_LOCKED)
      {
        if (sqlite3_extended_errcode (h) != SQLITE_LOCKED_SHAREDCACHE)
          break;

        sqlite3_reset (stmt_);
        conn_.wait ();
      }
#else
      e = sqlite3_step (stmt_);
#endif

      // sqlite3_step() will return a detailed error code only if we used
      // sqlite3_prepare_v2(). Otherwise, sqlite3_reset() returns the
      // error.
      //
#if SQLITE_VERSION_NUMBER >= 3003011
      sqlite3_reset (stmt_);

      if (e != SQLITE_DONE)
#else
      e = sqlite3_reset (stmt_);

      if (e != SQLITE_OK)
#endif
        translate_error (e, conn_);

      return static_cast<unsigned long long> (sqlite3_changes (h));
    }

    // delete_statement
    //

    delete_statement::
    delete_statement (connection_type& conn,
                      const string& text,
                      binding& param)
        : statement (conn,
                     text, statement_delete,
                     0, false),
          param_ (param)
    {
    }

    delete_statement::
    delete_statement (connection_type& conn,
                      const char* text,
                      binding& param)
        : statement (conn,
                     text, statement_delete,
                     0, false),
          param_ (param)
    {
    }

    unsigned long long delete_statement::
    execute ()
    {
      {
        odb::tracer* t;
        if ((t = conn_.transaction_tracer ()) ||
            (t = conn_.tracer ()) ||
            (t = conn_.database ().tracer ()))
          t->execute (conn_, *this);
      }

      bind_param (param_.bind, param_.count);

      int e;
      sqlite3* h (conn_.handle ());

#ifdef LIBODB_SQLITE_HAVE_UNLOCK_NOTIFY
      while ((e = sqlite3_step (stmt_)) == SQLITE_LOCKED)
      {
        if (sqlite3_extended_errcode (h) != SQLITE_LOCKED_SHAREDCACHE)
          break;

        sqlite3_reset (stmt_);
        conn_.wait ();
      }
#else
      e = sqlite3_step (stmt_);
#endif

      // sqlite3_step() will return a detailed error code only if we used
      // sqlite3_prepare_v2(). Otherwise, sqlite3_reset() returns the
      // error.
      //
#if SQLITE_VERSION_NUMBER >= 3003011
      sqlite3_reset (stmt_);

      if (e != SQLITE_DONE)
#else
      e = sqlite3_reset (stmt_);

      if (e != SQLITE_OK)
#endif
        translate_error (e, conn_);

      return static_cast<unsigned long long> (sqlite3_changes (h));
    }
  }
}