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

#include <cstring> // std::strlen, std::memmove, std::memset
#include <cassert>

#include <odb/tracer.hxx>

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

using namespace std;

namespace odb
{
  namespace mysql
  {
    // statement
    //

    statement::
    statement (connection_type& conn,
               const string& text,
               statement_kind sk,
               const binding* process,
               bool optimize)
        : conn_ (conn)
    {
      if (process == 0)
      {
        text_copy_ = text;
        text_ = text_copy_.c_str ();
      }
      else
        text_ = text.c_str (); // Temporary, see init().

      init (text.size (), sk, process, optimize);
    }

    statement::
    statement (connection_type& conn,
               const char* text,
               statement_kind sk,
               const binding* process,
               bool optimize,
               bool copy)
        : conn_ (conn)
    {
      size_t n;

      if (process == 0 && copy)
      {
        text_copy_ = text;
        text_ = text_copy_.c_str ();
        n = text_copy_.size ();
      }
      else
      {
        text_ = text; // Potentially temporary, see init().
        n = strlen (text_);
      }

      init (n, sk, process, optimize);
    }

    void statement::
    init (size_t text_size,
          statement_kind sk,
          const binding* proc,
          bool optimize)
    {
      if (proc != 0)
      {
        switch (sk)
        {
        case statement_select:
          process_select (text_,
                          &proc->bind->buffer, proc->count, sizeof (MYSQL_BIND),
                          '`', '`',
                          optimize,
                          text_copy_);
          break;
        case statement_insert:
          process_insert (text_,
                          &proc->bind->buffer, proc->count, sizeof (MYSQL_BIND),
                          '?',
                          text_copy_);
          break;
        case statement_update:
          process_update (text_,
                          &proc->bind->buffer, proc->count, sizeof (MYSQL_BIND),
                          '?',
                          text_copy_);
          break;
        case statement_delete:
          assert (false);
        }

        text_ = text_copy_.c_str ();
        text_size = text_copy_.size ();
      }

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

      stmt_.reset (conn_.alloc_stmt_handle ());

      conn_.clear ();

      if (mysql_stmt_prepare (stmt_, text_, text_size) != 0)
        translate_error (conn_, stmt_);

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

    size_t statement::
    process_bind (MYSQL_BIND* b, size_t n)
    {
      size_t shifts (0);
      for (MYSQL_BIND* e (b + n); b != e;)
      {
        if (b->buffer == 0)
        {
          // It is possible that this array has already been processed
          // (shared among multiple statements).
          //
          if (b->length != 0)
          {
            n -= e - b;
            break;
          }

          e--;

          // Shift the rest of the entries to the left.
          //
          memmove (b, b + 1, (e - b) * sizeof (MYSQL_BIND));

          // Store the original position of the NULL entry at the end.
          //
          e->buffer = 0;
          e->length = reinterpret_cast<unsigned long*> (b + shifts);

          shifts++;
          continue;
        }

        b++;
      }

      return n - shifts;
    }

    void statement::
    restore_bind (MYSQL_BIND* b, size_t n)
    {
      for (MYSQL_BIND* e (b + n - 1); e->buffer == 0 && e->length != 0;)
      {
        MYSQL_BIND* p (reinterpret_cast<MYSQL_BIND*> (e->length));

        // Shift the entries from the specified position to the right.
        //
        memmove (p + 1, p, (e - p) * sizeof (MYSQL_BIND));

        // Restore the original NULL entry.
        //
        memset (p, 0, sizeof (MYSQL_BIND));
      }
    }

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

      // Let the connection handle the release of the statement (it
      // may delay the actual freeing if it will mess up the currently
      // active statement).
      //
      conn_.free_stmt_handle (stmt_);
    }

    const char* statement::
    text () const
    {
      return text_;
    }

    void statement::
    cancel ()
    {
    }

    // select_statement
    //

    select_statement::
    ~select_statement ()
    {
      assert (freed_);
    }

    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),
          end_ (false),
          cached_ (false),
          freed_ (true),
          rows_ (0),
          param_ (&param),
          param_version_ (0),
          result_ (result),
          result_version_ (0)
    {
    }

    select_statement::
    select_statement (connection_type& conn,
                      const char* text,
                      bool process,
                      bool optimize,
                      binding& param,
                      binding& result,
                      bool copy_text)
        : statement (conn,
                     text, statement_select,
                     (process ? &result : 0), optimize,
                     copy_text),
          end_ (false),
          cached_ (false),
          freed_ (true),
          rows_ (0),
          param_ (&param),
          param_version_ (0),
          result_ (result),
          result_version_ (0)
    {
    }

    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),
          end_ (false),
          cached_ (false),
          freed_ (true),
          rows_ (0),
          param_ (0),
          result_ (result),
          result_version_ (0)
    {
    }

    select_statement::
    select_statement (connection_type& conn,
                      const char* text,
                      bool process,
                      bool optimize,
                      binding& result,
                      bool copy_text)
        : statement (conn,
                     text, statement_select,
                     (process ? &result : 0), optimize,
                     copy_text),
          end_ (false),
          cached_ (false),
          freed_ (true),
          rows_ (0),
          param_ (0),
          result_ (result),
          result_version_ (0)
    {
    }

    void select_statement::
    execute ()
    {
      assert (freed_);

      conn_.clear ();

      end_ = false;
      rows_ = 0;

      if (mysql_stmt_reset (stmt_))
        translate_error (conn_, stmt_);

      if (param_ != 0 && param_version_ != param_->version)
      {
        // For now cannot have NULL entries.
        //
        if (mysql_stmt_bind_param (stmt_, param_->bind))
          translate_error (conn_, stmt_);

        param_version_ = param_->version;
      }

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

      if (mysql_stmt_execute (stmt_))
        translate_error (conn_, stmt_);

      // This flag appears to be cleared once we start processing the
      // result, so we have to cache it for free_result() below.
      //
#if MYSQL_VERSION_ID >= 50503
      out_params_ = (conn_.handle ()->server_status & SERVER_PS_OUT_PARAMS);
#endif

      freed_ = false;
      conn_.active (this);
    }

    void select_statement::
    cache ()
    {
      if (!cached_)
      {
        if (!end_)
        {
          if (mysql_stmt_store_result (stmt_))
            translate_error (conn_, stmt_);

          // mysql_stmt_num_rows() returns the number of rows that have been
          // fetched by store_result.
          //
          size_ = rows_ + static_cast<size_t> (mysql_stmt_num_rows (stmt_));
        }
        else
          size_ = rows_;

        cached_ = true;
      }
    }

    select_statement::result select_statement::
    fetch (bool next)
    {
      if (result_version_ != result_.version)
      {
        size_t count (process_bind (result_.bind, result_.count));

        // 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 (mysql_stmt_field_count (stmt_) == count);

        if (mysql_stmt_bind_result (stmt_, result_.bind))
          translate_error (conn_, stmt_);

        if (count != result_.count)
          restore_bind (result_.bind, result_.count);

        result_version_ = result_.version;
      }

      if (!next && rows_ != 0)
      {
        assert (cached_);
        mysql_stmt_data_seek (stmt_, static_cast<my_ulonglong> (rows_ - 1));
      }

      int r (mysql_stmt_fetch (stmt_));

      switch (r)
      {
      case 0:
        {
          if (next)
            rows_++;
          return success;
        }
      case MYSQL_NO_DATA:
        {
          end_ = true;
          return no_data;
        }
      case MYSQL_DATA_TRUNCATED:
        {
          if (next)
            rows_++;
          return truncated;
        }
      default:
        {
          translate_error (conn_, stmt_);
          return no_data; // Never reached.
        }
      }
    }

    void select_statement::
    refetch ()
    {
      // Re-fetch columns that were truncated.
      //
      unsigned int col (0);
      for (size_t i (0); i < result_.count; ++i)
      {
        MYSQL_BIND& b (result_.bind[i]);

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

        if (*b.error)
        {
          *b.error = 0;

          if (mysql_stmt_fetch_column (stmt_, &b, col, 0))
            translate_error (conn_, stmt_);
        }

        col++;
      }
    }

    void select_statement::
    free_result ()
    {
      if (!freed_)
      {
        // If this is a stored procedure call, then we have multiple
        // results. The first is the rowset that is the result of the
        // procedure (actually, it can be several rowsets if, for
        // example, the procedure executes multiple SELECT statements,
        // but we don't support this). This result we have just handled.
        // Next, there could be another rowset with just one row which
        // contains the output variable values (OUT and INOUT; actually,
        // if the procedure does not have any SELECT statements, then
        // this will be the first result and we have just handled it).
        // Finally, the last result is always the stored procedure status
        // (not clear how to get this value; all MySQL sample code simply
        // ignores it).
        //
        // So what we need to do here is read and ignore these other
        // results since otherwise MySQL won't let us execute any
        // subsequent statements. Calling mysql_stmt_next_result()
        // until it tells us there is no more results seems to do
        // the trick.
        //
        // mysql_stmt_next_result() is only available since 5.5.3.
        // Checking the source code reveals that it does call
        // mysql_next_result() (which is available prior to 5.5.3)
        // but also does some other house keeping. So it is not
        // clear if it is possible to emulate the below logic for
        // prior MySQL versions.
        //

        // Handling OUT parameters requires a special Voodoo dance:
        // we have to fetch the row itself and we have to call fetch
        // again and get MYSQL_NO_DATA. Without doing these exact
        // steps the server simply drops the connection. Go figure.
        //
#if MYSQL_VERSION_ID >= 50503
        if (out_params_)
        {
          if (mysql_stmt_fetch (stmt_) != MYSQL_NO_DATA)
            translate_error (conn_, stmt_);
        }
#endif

        if (mysql_stmt_free_result (stmt_))
          translate_error (conn_, stmt_);

#if MYSQL_VERSION_ID >= 50503
        {
          int s;
          while ((s = mysql_stmt_next_result (stmt_)) == 0)
          {
            if (mysql_stmt_field_count (stmt_) != 0)
            {
              // The same Voodoo dance as above.
              //
              if (conn_.handle ()->server_status & SERVER_PS_OUT_PARAMS)
              {
                if (mysql_stmt_fetch (stmt_))
                  translate_error (conn_, stmt_);

                if (mysql_stmt_fetch (stmt_) != MYSQL_NO_DATA)
                  translate_error (conn_, stmt_);
              }

              if (mysql_stmt_free_result (stmt_))
                translate_error (conn_, stmt_);
            }
          }

          if (s != -1)
            translate_error (conn_, stmt_);
        }
#endif

        if (conn_.active () == this)
          conn_.active (0);

        end_ = true;
        cached_ = false;
        freed_ = true;
        rows_ = 0;
      }
    }

    void select_statement::
    cancel ()
    {
      // If we cached the result, don't free it just yet.
      //
      if (!cached_ || end_)
        free_result ();
      else
        conn_.active (0);
    }

    // insert_statement
    //

    insert_statement::
    ~insert_statement ()
    {
    }

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

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

    bool insert_statement::
    execute ()
    {
      conn_.clear ();

      if (mysql_stmt_reset (stmt_))
        translate_error (conn_, stmt_);

      if (param_version_ != param_.version)
      {
        size_t count (process_bind (param_.bind, param_.count));

        if (mysql_stmt_bind_param (stmt_, param_.bind))
          translate_error (conn_, stmt_);

        if (count != param_.count)
          restore_bind (param_.bind, param_.count);

        param_version_ = param_.version;
      }

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

      if (mysql_stmt_execute (stmt_))
      {
        if (mysql_stmt_errno (stmt_) == ER_DUP_ENTRY)
          return false;
        else
          translate_error (conn_, stmt_);
      }

      return true;
    }

    unsigned long long insert_statement::
    id ()
    {
      return static_cast<unsigned long long> (mysql_stmt_insert_id (stmt_));
    }

    // update_statement
    //

    update_statement::
    ~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),
          param_version_ (0)
    {
    }

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

    unsigned long long update_statement::
    execute ()
    {
      conn_.clear ();

      if (mysql_stmt_reset (stmt_))
        translate_error (conn_, stmt_);

      if (param_version_ != param_.version)
      {
        size_t count (process_bind (param_.bind, param_.count));

        if (mysql_stmt_bind_param (stmt_, param_.bind))
          translate_error (conn_, stmt_);

        if (count != param_.count)
          restore_bind (param_.bind, param_.count);

        param_version_ = param_.version;
      }

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

      if (mysql_stmt_execute (stmt_))
        translate_error (conn_, stmt_);

      my_ulonglong r (mysql_stmt_affected_rows (stmt_));

      if (r == static_cast<my_ulonglong> (-1))
        translate_error (conn_, stmt_);

      return static_cast<unsigned long long> (r);
    }

    // delete_statement
    //

    delete_statement::
    ~delete_statement ()
    {
    }

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

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

    unsigned long long delete_statement::
    execute ()
    {
      conn_.clear ();

      if (mysql_stmt_reset (stmt_))
        translate_error (conn_, stmt_);

      if (param_version_ != param_.version)
      {
        // Cannot have NULL entries for now.
        //
        if (mysql_stmt_bind_param (stmt_, param_.bind))
          translate_error (conn_, stmt_);

        param_version_ = param_.version;
      }

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

      if (mysql_stmt_execute (stmt_))
        translate_error (conn_, stmt_);

      my_ulonglong r (mysql_stmt_affected_rows (stmt_));

      if (r == static_cast<my_ulonglong> (-1))
        translate_error (conn_, stmt_);

      return static_cast<unsigned long long> (r);
    }
  }
}