summaryrefslogtreecommitdiff
path: root/include/boost/sqlite/statement.hpp
blob: b77bbe8946fea346c0fd95ff59c9389604c96bf9 (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
// Copyright (c) 2022 Klemens D. Morgenstern
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_SQLITE_STATEMENT_HPP
#define BOOST_SQLITE_STATEMENT_HPP

#include <boost/sqlite/detail/config.hpp>
#include <boost/sqlite/detail/exception.hpp>
#include <boost/sqlite/blob.hpp>
#include <boost/sqlite/resultset.hpp>

#include <boost/mp11/algorithm.hpp>
#include <boost/core/ignore_unused.hpp>
#include <boost/variant2/variant.hpp>


#include <tuple>

BOOST_SQLITE_BEGIN_NAMESPACE
struct connection;
template<typename, bool>
struct static_resultset;

/// @brief A reference to a value to temporary bind for an execute statement. Most values are captures by reference.
/// @ingroup reference
struct param_ref
{
    /// Default construct a parameter, gives `null`.
    param_ref() = default;
    /// Bind null
    param_ref(variant2::monostate) : impl_{variant2::in_place_type_t<variant2::monostate>{}} {}
    /// Bind null
    param_ref(std::nullptr_t)      : impl_{variant2::in_place_type_t<variant2::monostate>{}} {}
    /// Bind an integer.
    template<typename I,
             typename = typename std::enable_if<std::is_integral<I>::value>::type>
    param_ref(I value)
    {
        BOOST_IF_CONSTEXPR ((sizeof(I) == sizeof(int) && std::is_unsigned<I>::value)
                          || (sizeof(I) > sizeof(int)))
        impl_.emplace<sqlite3_int64>(static_cast<sqlite3_int64>(value));
      else
        impl_.emplace<int>(static_cast<int>(value));
    }
    /// Bind a blob.
    param_ref(blob_view blob) : impl_(blob) { }
    /// Bind a string.
    param_ref(string_view text) : impl_(text) { }

    template<typename StringLike>
    param_ref(StringLike && text,
              typename std::enable_if<std::is_constructible<string_view, StringLike>::value>::type * = nullptr)
            : impl_(variant2::in_place_type_t<string_view>{}, text) {}

    template<typename BlobLike>
    param_ref(BlobLike && text,
              typename std::enable_if<
                  !std::is_constructible<string_view, BlobLike>::value
                && std::is_constructible<blob_view, BlobLike>::value>::type * = nullptr)
        : impl_(variant2::in_place_type_t<blob_view>{}, text) {}

    /// Bind a floating point value.
    param_ref(double value) : impl_(value) { }
    /// Bind a zero_blob value, i.e. a blob that initialized by zero.
    param_ref(zero_blob zb) : impl_(zb) { }

#if SQLITE_VERSION_NUMBER >= 3020000
    /// Bind pointer value to the parameter. @see https://www.sqlite.org/bindptr.html
    template<typename T>
    param_ref(std::unique_ptr<T> ptr)
                    : impl_(variant2::in_place_index_t<7>{},
                            std::unique_ptr<void, void(*)(void*)>(
                                static_cast<void*>(ptr.release()),
                                +[](void * ptr){delete static_cast<T*>(ptr);}),
                                typeid(T).name())
    {
    }

    /// Bind pointer value with a function as deleter to the parameter. @see https://www.sqlite.org/bindptr.html
    template<typename T>
    param_ref(std::unique_ptr<T, void(*)(T*)> ptr)
                    : impl_(variant2::in_place_index_t<7>{},
                            std::unique_ptr<void, void(*)(void*)>(
                                static_cast<void*>(ptr.release()),
                                +[](void * ptr){delete static_cast<T*>(ptr);}),
                             typeid(T).name())
    {
    }

    /// @brief Bind pointer value with a function  custom deleter to the parameter.
    /// The deleter needs to be default constructible. @see https://www.sqlite.org/bindptr.html
    template<typename T, typename Deleter>
    param_ref(std::unique_ptr<T, Deleter> ptr,
              typename std::enable_if<std::is_empty<Deleter>::value &&
                               std::is_default_constructible<Deleter>::value, int>::type * = nullptr)
                    : impl_(variant2::in_place_index_t<7>{},
                            std::unique_ptr<void, void(*)(void*)>(
                                static_cast<void*>(ptr.release()),
                                +[](void * ptr){delete static_cast<T*>(ptr);}),
                            typeid(T).name())
    {
    }
#endif

    /// Apply the param_ref to a statement.
    int apply(sqlite3_stmt * stmt, int c) const
    {
      return variant2::visit(visitor{stmt, c}, impl_);
    }

 private:
    struct make_visitor
    {
      template<typename T>
      auto operator()(T&& t) const -> typename std::enable_if<std::is_constructible<param_ref, T&&>::value, param_ref>::type
      {
        return param_ref(std::forward<T>(t));
      }
    };

 public:
    /// Construct param_ref from a variant
    template<typename T>
    param_ref(T && t,
            decltype(variant2::visit(make_visitor(), std::forward<T>(t))) * = nullptr)
      : param_ref(variant2::visit(make_visitor(), std::forward<T>(t)))
    {}
 private:

    struct visitor
    {
      sqlite3_stmt * stmt;
      int col;

      int operator()(variant2::monostate )
      {
        return sqlite3_bind_null(stmt, col);
      }
      int operator()(int i )
      {
        return sqlite3_bind_int(stmt, col, i);
      }
      int operator()(sqlite3_int64 i64 )
      {
        return sqlite3_bind_int64(stmt, col, i64);
      }

      int operator()(blob_view blob)
      {
        if (blob.size() > static_cast<std::size_t>(std::numeric_limits<int>::max()))
          return sqlite3_bind_blob64(stmt, col, blob.data(), blob.size(), SQLITE_STATIC);
        else
          return sqlite3_bind_blob(stmt, col, blob.data(), static_cast<int>(blob.size()), SQLITE_STATIC);
      }

      int operator()(string_view text)
      {
        if (text.size() > std::numeric_limits<int>::max())
          return sqlite3_bind_text64(stmt, col, text.data(), text.size(), SQLITE_STATIC, SQLITE_UTF8);
        else
          return sqlite3_bind_text(stmt, col, text.data(), static_cast<int>(text.size()), SQLITE_STATIC);
      }
      int operator()(double value)
      {
        return sqlite3_bind_double(stmt, col, value);
      }
      int operator()(zero_blob zb)
      {
        if (static_cast<std::size_t>(zb) > static_cast<std::size_t>(std::numeric_limits<int>::max()))
          return sqlite3_bind_zeroblob64(stmt, col, static_cast<sqlite3_uint64>(zb));
        else
          return sqlite3_bind_zeroblob(stmt, col, static_cast<int>(zb));
      }
#if SQLITE_VERSION_NUMBER >= 3020000
      int operator()(std::pair<std::unique_ptr<void, void(*)(void*)>, const char*> & p)
      {
        auto d =p.first.get_deleter();
        return sqlite3_bind_pointer(stmt, col, p.first.release(), p.second, d);
      }
#endif
    };

    mutable // so we can use it with
    variant2::variant<variant2::monostate, int, sqlite3_int64,
                      blob_view, string_view, double, zero_blob
#if SQLITE_VERSION_NUMBER >= 3020000
                      , std::pair<std::unique_ptr<void, void(*)(void*)>, const char*>
#endif
                      > impl_;
};


/** @brief A statement used for a prepared-statement.
    @ingroup reference

 */
struct statement
{
    ///@{
    /** @brief execute the prepared statement once.

      @param params The arguments to be passed to the prepared statement. This can be a map or a vector of param_ref.
      @param ec     The system::error_code used to deliver errors for the exception less overload.
      @param info   The error_info used to deliver errors for the exception less overload.
      @return The resultset of the query.

      @code{.cpp}
        extern sqlite::connection conn;
        statement st = conn.prepare("select id from users where name = $1;");
        resultset q = std::move(st).execute(std::make_tuple("peter"));
      @endcode

     */
    template <typename ArgRange = std::initializer_list<param_ref>>
    resultset execute(
            ArgRange && params,
            system::error_code& ec,
            error_info& info) &&
    {
        bind_impl(std::forward<ArgRange>(params), ec, info);
        resultset rs;
        rs.impl_.reset(impl_.release());
        if (!ec)
          rs.read_next(ec, info);
        return rs;
    }

    template <typename ArgRange = std::initializer_list<param_ref>>
    resultset execute(ArgRange && params) &&
    {
        system::error_code ec;
        error_info ei;
        auto tmp = std::move(*this).execute(std::forward<ArgRange>(params), ec, ei);
        if (ec)
            detail::throw_error_code(ec, ei);
        return tmp;
    }

    resultset execute(
        std::initializer_list<std::pair<string_view, param_ref>> params,
        system::error_code& ec,
        error_info& info) &&
    {
        bind_impl(std::move(params), ec, info);
        resultset rs;
        rs.impl_.reset(impl_.release());
        if (!ec)
          rs.read_next(ec, info);
        return rs;
    }

    resultset execute(std::initializer_list<std::pair<string_view, param_ref>> params) &&
    {
      system::error_code ec;
      error_info ei;
      auto tmp = std::move(*this).execute(std::move(params), ec, ei);
      if (ec)
        detail::throw_error_code(ec, ei);
      return tmp;
    }

    template<typename T, bool Strict = false, typename ArgRange = std::initializer_list<param_ref>>
    static_resultset<T, Strict> execute(
        ArgRange && params,
        system::error_code & ec,
        error_info & ei) &&
    {
      static_resultset<T, Strict> tmp = std::move(*this).execute(std::forward<ArgRange>(params), ec, ei);
      if (ec)
        return {};
      tmp.check_columns_(ec, ei);
      if (ec)
        return {};

      return tmp;
    }

    template<typename T, bool Strict = false, typename ArgRange = std::initializer_list<param_ref>>
    static_resultset<T, Strict> execute(ArgRange && params) &&
    {
      system::error_code ec;
      error_info ei;
      auto tmp = std::move(*this).execute<T>(std::forward<ArgRange>(params), ec, ei);
      if (ec)
        throw_exception(system::system_error(ec, ei.message()));
      return tmp;
    }

    template<typename T, bool Strict = false>
    static_resultset<T, Strict> execute(
        std::initializer_list<std::pair<string_view, param_ref>> params,
        system::error_code & ec,
        error_info & ei) &&
    {
      static_resultset<T, Strict> tmp = std::move(*this).execute(std::move(params), ec, ei);
      if (ec)
        return {};
      tmp.check_columns_(ec, ei);
      if (ec)
        return {};

      return tmp;
    }

    template<typename T, bool Strict = false>
    static_resultset<T, Strict> execute(std::initializer_list<std::pair<string_view, param_ref>> params) &&
    {
      system::error_code ec;
      error_info ei;
      auto tmp = std::move(*this).execute<T, Strict>(std::move(params), ec, ei);
      if (ec)
        throw_exception(system::system_error(ec, ei.message()));
      return tmp;
    }

    ///@}

    ///@{
    /** @brief execute the prepared statement and reset it afterwards.

      @warning The handle is shared between the statement & resultset. The statemens need to be kept alive.

      @param params The arguments to be passed to the prepared statement.  This can be a map, a vector or a stuple of param_ref.
      @param ec     The system::error_code used to deliver errors for the exception less overload.
      @param info   The error_info used to deliver errors for the exception less overload.
      @return The resultset of the query.

      @code{.cpp}
        extern sqlite::connection conn;
        statement st = conn.prepare("select id from users where name = $1;");
        resultset q = std::move(st).execute(std::make_tuple("peter"));
      @endcode



     */
    template <typename ArgRange = std::initializer_list<param_ref>>
    resultset execute(
            ArgRange && params,
            system::error_code& ec,
            error_info& info) &
    {
        bind_impl(std::forward<ArgRange>(params), ec, info);
        resultset rs;
        rs.impl_.get_deleter().delete_ = false;
        rs.impl_.reset(impl_.get());
        if (!ec)
            rs.read_next(ec, info);
        return rs;
    }


    template <typename ArgRange = std::initializer_list<param_ref>>
    resultset execute(ArgRange && params) &
    {
        system::error_code ec;
        error_info ei;
        auto tmp = execute(std::forward<ArgRange>(params), ec, ei);
        if (ec)
            detail::throw_error_code(ec, ei);
        return tmp;
    }


    resultset execute(
        std::initializer_list<std::pair<string_view, param_ref>> params,
        system::error_code& ec,
        error_info& info) &
    {
      bind_impl(std::move(params), ec, info);
      resultset rs;
      rs.impl_.get_deleter().delete_ = false;
      rs.impl_.reset(impl_.get());
      if (!ec)
        rs.read_next(ec, info);
      return rs;
    }

    resultset execute(std::initializer_list<std::pair<string_view, param_ref>> params) &
    {
      system::error_code ec;
      error_info ei;
      auto tmp = execute(std::move(params), ec, ei);
      if (ec)
        detail::throw_error_code(ec, ei);
      return tmp;
    }

    template<typename T, bool Strict = false, typename ArgRange = std::initializer_list<param_ref>>
    static_resultset<T, Strict> execute(
        ArgRange && params,
        system::error_code & ec,
        error_info & ei) &
    {
      static_resultset<T, Strict> tmp = execute(std::forward<ArgRange>(params), ec, ei);
      if (ec)
        return {};
      tmp.check_columns_(ec, ei);
      if (ec)
        return {};

      return tmp;
    }

    template<typename T, bool Strict = false, typename ArgRange = std::initializer_list<param_ref>>
    static_resultset<T, Strict> execute(ArgRange && params) &
    {
      system::error_code ec;
      error_info ei;
      auto tmp = execute<T, Strict>(std::forward<ArgRange>(params), ec, ei);
      if (ec)
        throw_exception(system::system_error(ec, ei.message()));
      return tmp;
    }

    template<typename T, bool Strict = false>
    static_resultset<T, Strict> execute(
        std::initializer_list<std::pair<string_view, param_ref>> params,
        system::error_code & ec,
        error_info & ei) &
    {
      static_resultset<T, Strict> tmp = execute(std::move(params), ec, ei);
      if (ec)
        return {};
      tmp.check_columns_(ec, ei);
      if (ec)
        return {};

      return tmp;
    }

    template<typename T, bool Strict = false>
    static_resultset<T, Strict> execute(std::initializer_list<std::pair<string_view, param_ref>> params) &
    {
      system::error_code ec;
      error_info ei;
      auto tmp = execute<T, Strict>(std::move(params), ec, ei);
      if (ec)
        throw_exception(system::system_error(ec, ei.message()));
      return tmp;
    }

    ///@}


    /// Returns the sql used to construct the prepared statement.
    core::string_view sql()
    {
        return sqlite3_sql(impl_.get());
    }

#if SQLITE_VERSION_NUMBER >= 3014000
    /// Returns the expanded sql used to construct the prepared statement.
    core::string_view expanded_sql()
    {
      return sqlite3_expanded_sql(impl_.get());
    }
#endif

    /// Returns the expanded sql used to construct the prepared statement.
#ifdef SQLITE_ENABLE_NORMALIZE
    core::string_view normalized_sql()
    {
      return sqlite3_normalized_sql(impl_.get());
    }
#endif

    /// Returns the declared type of the column
    core::string_view declared_type(int id) const
    {
        return sqlite3_column_decltype(impl_.get(), id);
    }

  private:

    template<typename ... Args>
    void bind_impl(std::tuple<Args...> && vec,
                   system::error_code & ec,
                   error_info & ei)
    {
        const auto sz =  sqlite3_bind_parameter_count(impl_.get());
        if (sizeof...(Args) < static_cast<std::size_t>(sz))
        {
            BOOST_SQLITE_ASSIGN_EC(ec, SQLITE_ERROR);
            ei.format("To few parameters provided. Needed %d got %ld",
                      sz, sizeof...(Args));
            return;
        }

        int i = 1, ar = SQLITE_OK;
        mp11::tuple_for_each(std::move(vec),
                             [&](param_ref pr)
                             {
                                if (ar == SQLITE_OK)
                                  ar = pr.apply(impl_.get(), i++);
                             });
        if (ar != SQLITE_OK)
        {
          BOOST_SQLITE_ASSIGN_EC(ec, ar);
          ei.set_message(sqlite3_errmsg(sqlite3_db_handle(impl_.get())));
          return;
        }
    }


    template<typename ... Args>
    void bind_impl(const std::tuple<Args...> & vec,
                   system::error_code & ec,
                   error_info & ei)
    {
        const auto sz =  sqlite3_bind_parameter_count(impl_.get());
        if (static_cast<int>(sizeof...(Args)) < sz)
        {
            BOOST_SQLITE_ASSIGN_EC(ec, SQLITE_ERROR);
            ei.format("To few parameters provided. Needed %d got %ld",
                      sz, sizeof...(Args));
            return;
        }

        int i = 1, ar = SQLITE_OK;
        mp11::tuple_for_each(std::move(vec),
                             [&](param_ref pr)
                             {
                               if (ar == SQLITE_OK)
                                 ar = pr.apply(impl_.get(), i++);
                             });
        if (ar != SQLITE_OK)
        {
          BOOST_SQLITE_ASSIGN_EC(ec, ar);
          ei.set_message(sqlite3_errmsg(sqlite3_db_handle(impl_.get())));
          return;
        }
    }

    template<typename ParamVector>
    void bind_impl(ParamVector && vec, system::error_code & ec, error_info & ei,
                   typename std::enable_if<std::is_convertible<
                       typename std::decay<ParamVector>::type::value_type, param_ref>::value>::type * = nullptr)
    {
        const auto sz =  sqlite3_bind_parameter_count(impl_.get());
        if (vec.size() < static_cast<std::size_t>(sz))
        {
            BOOST_SQLITE_ASSIGN_EC(ec, SQLITE_ERROR);
            ei.format("To few parameters provided. Needed %d got %ld",
                      sz, vec.size());
        }
        int i = 1;
        for (const param_ref & pr : std::forward<ParamVector>(vec))
        {
          int ar = pr.apply(impl_.get(), i++);
          if (ar != SQLITE_OK)
          {

            BOOST_SQLITE_ASSIGN_EC(ec, ar);
            ei.set_message(sqlite3_errmsg(sqlite3_db_handle(impl_.get())));
            return;
          }
        }
    }

    template<typename ParamMap>
    void bind_impl(ParamMap && vec, system::error_code & ec, error_info & ei,
                   typename std::enable_if<
                       std::is_convertible<typename std::decay<ParamMap>::type::key_type, string_view>::value &&
                       std::is_convertible<typename std::decay<ParamMap>::type::mapped_type, param_ref>::value
                         >::type * = nullptr)
    {
        for (auto i = 1; i <= sqlite3_bind_parameter_count(impl_.get()); i ++)
        {
          auto c = sqlite3_bind_parameter_name(impl_.get(), i);
          if (c == nullptr)
          {
              BOOST_SQLITE_ASSIGN_EC(ec, SQLITE_MISUSE);
              ei.set_message("Parameter maps require all parameters to be named.");
              return ;
          }
          auto itr = vec.find(c+1);
          if (itr == vec.end())
          {
            BOOST_SQLITE_ASSIGN_EC(ec, SQLITE_MISUSE);
            ei.format("Can't find value for key '%s'", c+1);
            return ;
          }
          int ar = SQLITE_OK;
          if (std::is_rvalue_reference<ParamMap&&>::value)
            ar = param_ref(std::move(itr->second)).apply(impl_.get(), i);
          else
            ar = param_ref(itr->second).apply(impl_.get(), i);

          if (ar != SQLITE_OK)
          {

            BOOST_SQLITE_ASSIGN_EC(ec, ar);
            ei.set_message(sqlite3_errmsg(sqlite3_db_handle(impl_.get())));
            return;
          }
        }
    }

    void bind_impl(std::initializer_list<std::pair<string_view, param_ref>> params,
                   system::error_code & ec, error_info & ei)
    {
        for (auto i = 1; i <= sqlite3_bind_parameter_count(impl_.get()); i ++)
        {
          auto c = sqlite3_bind_parameter_name(impl_.get(), i);
          if (c == nullptr)
          {
              BOOST_SQLITE_ASSIGN_EC(ec, SQLITE_MISUSE);
              ei.set_message("Parameter maps require all parameters to be named.");
              return ;
          }

          auto itr = std::find_if(params.begin(), params.end(),
                                  [&](const std::pair<string_view, param_ref> & p)
                                  {
                                      return p.first == (c+1);
                                  });
          if (itr == params.end())
          {
            BOOST_SQLITE_ASSIGN_EC(ec, SQLITE_MISUSE);
            ei.format("Can't find value for key '%s'", c+1);
            return ;
          }
          auto ar = itr->second.apply(impl_.get(), i);
          if (ar != SQLITE_OK)
          {

            BOOST_SQLITE_ASSIGN_EC(ec, ar);
            ei.set_message(sqlite3_errmsg(sqlite3_db_handle(impl_.get())));
            return;
          }
        }
    }


    friend
    struct connection;
    struct deleter_
    {
        void operator()(sqlite3_stmt * sm)
        {
            sqlite3_finalize(sm);
        }
    };
    std::unique_ptr<sqlite3_stmt, deleter_> impl_;
};

BOOST_SQLITE_END_NAMESPACE

#endif //BOOST_SQLITE_STATEMENT_HPP