-
-
Notifications
You must be signed in to change notification settings - Fork 327
/
Copy pathstorage.h
1771 lines (1588 loc) · 83.3 KB
/
storage.h
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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma once
#include <sqlite3.h>
#ifndef SQLITE_ORM_IMPORT_STD_MODULE
#include <memory> // std::unique_ptr/shared_ptr, std::make_unique
#include <system_error> // std::system_error
#include <string> // std::string
#include <type_traits> // std::remove_reference, std::remove_cvref, std::decay
#include <functional> // std::identity
#include <sstream> // std::stringstream
#include <iomanip> // std::flush
#include <map> // std::map
#include <vector> // std::vector
#include <tuple> // std::tuple_size, std::tuple, std::make_tuple, std::tie
#include <utility> // std::forward, std::pair
#include <algorithm> // std::for_each, std::ranges::for_each
#endif
#include "functional/cxx_optional.h"
#include "functional/cxx_type_traits_polyfill.h"
#include "functional/cxx_functional_polyfill.h"
#include "functional/static_magic.h"
#include "functional/mpl.h"
#include "tuple_helper/tuple_traits.h"
#include "tuple_helper/tuple_filter.h"
#include "tuple_helper/tuple_transformer.h"
#include "tuple_helper/tuple_iteration.h"
#include "type_traits.h"
#include "alias.h"
#include "error_code.h"
#include "type_printer.h"
#include "constraints.h"
#include "field_printer.h"
#include "rowid.h"
#include "operators.h"
#include "select_constraints.h"
#include "core_functions.h"
#include "conditions.h"
#include "statement_binder.h"
#include "column_result.h"
#include "mapped_type_proxy.h"
#include "sync_schema_result.h"
#include "table_info.h"
#include "storage_impl.h"
#include "journal_mode.h"
#include "mapped_view.h"
#include "result_set_view.h"
#include "ast_iterator.h"
#include "storage_base.h"
#include "prepared_statement.h"
#include "expression_object_type.h"
#include "statement_serializer.h"
#include "serializer_context.h"
#include "schema/triggers.h"
#include "object_from_column_builder.h"
#include "row_extractor.h"
#include "schema/table.h"
#include "schema/column.h"
#include "schema/index.h"
#include "cte_storage.h"
#include "util.h"
#include "serializing_util.h"
namespace sqlite_orm {
namespace internal {
/*
* Implementation note: the technique of indirect expression testing is because
* of older compilers having problems with the detection of dependent templates [SQLITE_ORM_BROKEN_ALIAS_TEMPLATE_DEPENDENT_EXPR_SFINAE].
* It must also be a type that differs from those for `is_printable_v`, `is_bindable_v`.
*/
template<class Binder>
struct indirectly_test_preparable;
template<class S, class E, class SFINAE = void>
SQLITE_ORM_INLINE_VAR constexpr bool is_preparable_v = false;
template<class S, class E>
SQLITE_ORM_INLINE_VAR constexpr bool is_preparable_v<
S,
E,
polyfill::void_t<indirectly_test_preparable<decltype(std::declval<S>().prepare(std::declval<E>()))>>> =
true;
template<class Opt, class OptionsTpl>
decltype(auto) storage_opt_or_default(OptionsTpl& options) {
#ifdef SQLITE_ORM_CTAD_SUPPORTED
if constexpr (tuple_has_type<OptionsTpl, Opt>::value) {
return std::move(std::get<Opt>(options));
} else {
return Opt{};
}
#else
return Opt{};
#endif
}
/**
* Storage class itself. Create an instanse to use it as an interfacto to sqlite db by calling `make_storage`
* function.
*/
template<class... DBO>
struct storage_t : storage_base {
using self_type = storage_t;
using db_objects_type = db_objects_tuple<DBO...>;
/**
* @param filename database filename.
* @param dbObjects db_objects_tuple
*/
template<class OptionsTpl>
storage_t(std::string filename, db_objects_type dbObjects, OptionsTpl options) :
storage_base{std::move(filename),
storage_opt_or_default<connection_control>(options),
storage_opt_or_default<on_open_spec>(options),
foreign_keys_count(dbObjects)},
db_objects{std::move(dbObjects)} {}
storage_t(const storage_t&) = default;
private:
db_objects_type db_objects;
/**
* Obtain a storage_t's const db_objects_tuple.
*
* @note Historically, `serializer_context_builder` was declared friend, along with
* a few other library stock objects, in order to limit access to the db_objects_tuple.
* However, one could gain access to a storage_t's db_objects_tuple through
* `serializer_context_builder`, hence leading the whole friend declaration mambo-jumbo
* ad absurdum.
* Providing a free function is way better and cleaner.
*
* Hence, friend was replaced by `obtain_db_objects()` and `pick_const_impl()`.
*/
friend const db_objects_type& obtain_db_objects(const self_type& storage) noexcept {
return storage.db_objects;
}
template<class Table>
void create_table(sqlite3* db, const std::string& tableName, const Table& table) {
using context_t = serializer_context<db_objects_type>;
context_t context{this->db_objects};
statement_serializer<Table, void> serializer;
std::string sql = serializer.serialize(table, context, tableName);
perform_void_exec(db, std::move(sql));
}
/**
* Copies sourceTableName to another table with name: destinationTableName
* Performs INSERT INTO %destinationTableName% () SELECT %table.column_names% FROM %sourceTableName%
*/
template<class Table>
void copy_table(sqlite3* db,
const std::string& sourceTableName,
const std::string& destinationTableName,
const Table& table,
const std::vector<const table_xinfo*>& columnsToIgnore) const;
#if SQLITE_VERSION_NUMBER >= 3035000 // DROP COLUMN feature exists (v3.35.0)
void drop_column(sqlite3* db, const std::string& tableName, const std::string& columnName) {
std::stringstream ss;
ss << "ALTER TABLE " << streaming_identifier(tableName) << " DROP COLUMN "
<< streaming_identifier(columnName) << std::flush;
perform_void_exec(db, ss.str());
}
#endif
template<class Table>
void drop_create_with_loss(sqlite3* db, const Table& table) {
// eliminated all transaction handling
this->drop_table_internal(db, table.name, false);
this->create_table(db, table.name, table);
}
template<class Table>
void backup_table(sqlite3* db, const Table& table, const std::vector<const table_xinfo*>& columnsToIgnore) {
// here we copy source table to another with a name with '_backup' suffix, but in case table with such
// a name already exists we append suffix 1, then 2, etc until we find a free name..
auto backupTableName = table.name + "_backup";
if (this->table_exists(db, backupTableName)) {
int suffix = 1;
do {
std::stringstream ss;
ss << suffix << std::flush;
auto anotherBackupTableName = backupTableName + ss.str();
if (!this->table_exists(db, anotherBackupTableName)) {
backupTableName = std::move(anotherBackupTableName);
break;
}
++suffix;
} while (true);
}
this->create_table(db, backupTableName, table);
this->copy_table(db, table.name, backupTableName, table, columnsToIgnore);
this->drop_table_internal(db, table.name, false);
this->rename_table(db, backupTableName, table.name);
}
template<class O>
void assert_mapped_type() const {
static_assert(tuple_has_type<db_objects_type, O, object_type_t>::value,
"type is not mapped to storage");
}
template<class O>
void assert_updatable_type() const {
#if defined(SQLITE_ORM_FOLD_EXPRESSIONS_SUPPORTED)
using Table = storage_pick_table_t<O, db_objects_type>;
using elements_type = elements_type_t<Table>;
using col_index_sequence = filter_tuple_sequence_t<elements_type, is_column>;
using pk_index_sequence = filter_tuple_sequence_t<elements_type, is_primary_key>;
using pkcol_index_sequence = col_index_sequence_with<elements_type, is_primary_key>;
constexpr size_t dedicatedPrimaryKeyColumnsCount =
nested_tuple_size_for_t<columns_tuple_t, elements_type, pk_index_sequence>::value;
constexpr size_t primaryKeyColumnsCount =
dedicatedPrimaryKeyColumnsCount + pkcol_index_sequence::size();
constexpr ptrdiff_t nonPrimaryKeysColumnsCount = col_index_sequence::size() - primaryKeyColumnsCount;
static_assert(primaryKeyColumnsCount > 0, "A table without primary keys cannot be updated");
static_assert(
nonPrimaryKeysColumnsCount > 0,
"A table with only primary keys cannot be updated. You need at least 1 non-primary key column");
#endif
}
template<class O,
class Table = storage_pick_table_t<O, db_objects_type>,
std::enable_if_t<Table::is_without_rowid::value, bool> = true>
void assert_insertable_type() const {}
template<class O,
class Table = storage_pick_table_t<O, db_objects_type>,
std::enable_if_t<!Table::is_without_rowid::value, bool> = true>
void assert_insertable_type() const {
using elements_type = elements_type_t<Table>;
using pkcol_index_sequence = col_index_sequence_with<elements_type, is_primary_key>;
static_assert(
count_filtered_tuple<elements_type, is_primary_key_insertable, pkcol_index_sequence>::value <= 1,
"Attempting to execute 'insert' request into an noninsertable table was detected. "
"Insertable table cannot contain > 1 primary keys. Please use 'replace' instead of "
"'insert', or you can use 'insert' with explicit column listing.");
static_assert(count_filtered_tuple<elements_type,
check_if_not<is_primary_key_insertable>::template fn,
pkcol_index_sequence>::value == 0,
"Attempting to execute 'insert' request into an noninsertable table was detected. "
"Insertable table cannot contain non-standard primary keys. Please use 'replace' instead "
"of 'insert', or you can use 'insert' with explicit column listing.");
}
template<class O>
auto& get_table() const {
return pick_table<O>(this->db_objects);
}
template<class O>
auto& get_table() {
return pick_table<O>(this->db_objects);
}
public:
template<class T, class O = mapped_type_proxy_t<T>, class... Args>
mapped_view<O, self_type, Args...> iterate(Args&&... args) {
this->assert_mapped_type<O>();
auto con = this->get_connection();
return {*this, std::move(con), std::forward<Args>(args)...};
}
#ifdef SQLITE_ORM_WITH_CPP20_ALIASES
template<orm_refers_to_table auto mapped, class... Args>
auto iterate(Args&&... args) {
return this->iterate<decltype(mapped)>(std::forward<Args>(args)...);
}
#endif
#if defined(SQLITE_ORM_SENTINEL_BASED_FOR_SUPPORTED) && defined(SQLITE_ORM_DEFAULT_COMPARISONS_SUPPORTED)
template<class Select>
#ifdef SQLITE_ORM_CONCEPTS_SUPPORTED
requires (is_select_v<Select>)
#endif
result_set_view<Select, db_objects_type> iterate(Select expression) {
expression.highest_level = true;
auto con = this->get_connection();
return {this->db_objects, std::move(con), std::move(expression)};
}
#if (SQLITE_VERSION_NUMBER >= 3008003) && defined(SQLITE_ORM_WITH_CTE)
template<class... CTEs, class E>
#ifdef SQLITE_ORM_CONCEPTS_SUPPORTED
requires (is_select_v<E>)
#endif
result_set_view<with_t<E, CTEs...>, db_objects_type> iterate(with_t<E, CTEs...> expression) {
auto con = this->get_connection();
return {this->db_objects, std::move(con), std::move(expression)};
}
#endif
#endif
/**
* Delete from routine.
* O is an object's type. Must be specified explicitly.
* @param args optional conditions: `where`, `join` etc
* @example: storage.remove_all<User>(); - DELETE FROM users
* @example: storage.remove_all<User>(where(in(&User::id, {5, 6, 7}))); - DELETE FROM users WHERE id IN (5, 6, 7)
*/
template<class O, class... Args>
void remove_all(Args&&... args) {
this->assert_mapped_type<O>();
auto statement = this->prepare(sqlite_orm::remove_all<O>(std::forward<Args>(args)...));
this->execute(statement);
}
#ifdef SQLITE_ORM_WITH_CPP20_ALIASES
template<orm_table_reference auto table, class... Args>
void remove_all(Args&&... args) {
return this->remove_all<auto_decay_table_ref_t<table>>(std::forward<Args>(args)...);
}
#endif
/**
* Delete routine.
* O is an object's type. Must be specified explicitly.
* @param ids ids of object to be removed.
*/
template<class O, class... Ids>
void remove(Ids... ids) {
this->assert_mapped_type<O>();
auto statement = this->prepare(sqlite_orm::remove<O>(std::forward<Ids>(ids)...));
this->execute(statement);
}
#ifdef SQLITE_ORM_WITH_CPP20_ALIASES
template<orm_table_reference auto table, class... Ids>
void remove(Ids... ids) {
return this->remove<auto_decay_table_ref_t<table>>(std::forward<Ids>(ids)...);
}
#endif
/**
* Update routine. Sets all non primary key fields where primary key is equal.
* O is an object type. May be not specified explicitly cause it can be deduced by
* compiler from first parameter.
* @param o object to be updated.
*/
template<class O>
void update(const O& o) {
this->assert_mapped_type<O>();
auto statement = this->prepare(sqlite_orm::update(std::ref(o)));
this->execute(statement);
}
template<class S, class... Wargs>
void update_all(S set, Wargs... wh) {
static_assert(internal::is_set<S>::value,
"first argument in update_all can be either set or dynamic_set");
auto statement = this->prepare(sqlite_orm::update_all(std::move(set), std::forward<Wargs>(wh)...));
this->execute(statement);
}
protected:
template<class F, class O, class... Args>
std::string group_concat_internal(F O::* m, std::unique_ptr<std::string> y, Args&&... args) {
this->assert_mapped_type<O>();
std::vector<std::string> rows;
if (y) {
rows = this->select(sqlite_orm::group_concat(m, std::move(*y)), std::forward<Args>(args)...);
} else {
rows = this->select(sqlite_orm::group_concat(m), std::forward<Args>(args)...);
}
if (!rows.empty()) {
return std::move(rows.front());
} else {
return {};
}
}
public:
/**
* SELECT * routine.
* T is an explicitly specified object mapped to a storage or a table alias.
* R is an explicit return type. This type must have `push_back(O &&)` function. Defaults to `std::vector<O>`
* @return All objects of type O stored in database at the moment in `R`.
* @example: storage.get_all<User, std::list<User>>(); - SELECT * FROM users
* @example: storage.get_all<User, std::list<User>>(where(like(&User::name, "N%")), order_by(&User::id)); - SELECT * FROM users WHERE name LIKE 'N%' ORDER BY id
*/
template<class T, class R = std::vector<mapped_type_proxy_t<T>>, class... Args>
R get_all(Args&&... args) {
this->assert_mapped_type<mapped_type_proxy_t<T>>();
auto statement = this->prepare(sqlite_orm::get_all<T, R>(std::forward<Args>(args)...));
return this->execute(statement);
}
#ifdef SQLITE_ORM_WITH_CPP20_ALIASES
/**
* SELECT * routine.
* `mapped` is an explicitly specified table reference or table alias of an object to be extracted.
* `R` is the container return type, which must have a `R::push_back(O&&)` method, and defaults to `std::vector<O>`
* @return All objects stored in database.
* @example: storage.get_all<sqlite_schema, std::list<sqlite_master>>(); - SELECT sqlite_schema.* FROM sqlite_master AS sqlite_schema
*/
template<orm_refers_to_table auto mapped,
class R = std::vector<mapped_type_proxy_t<decltype(mapped)>>,
class... Args>
R get_all(Args&&... args) {
this->assert_mapped_type<mapped_type_proxy_t<decltype(mapped)>>();
auto statement = this->prepare(sqlite_orm::get_all<mapped, R>(std::forward<Args>(args)...));
return this->execute(statement);
}
#endif
/**
* SELECT * routine.
* O is an object type to be extracted. Must be specified explicitly.
* R is a container type. std::vector<std::unique_ptr<O>> is default
* @return All objects of type O as std::unique_ptr<O> stored in database at the moment.
* @example: storage.get_all_pointer<User, std::list<std::unique_ptr<User>>>(); - SELECT * FROM users
* @example: storage.get_all_pointer<User, std::list<std::unique_ptr<User>>>(where(length(&User::name) > 6)); - SELECT * FROM users WHERE LENGTH(name) > 6
*/
template<class O, class R = std::vector<std::unique_ptr<O>>, class... Args>
auto get_all_pointer(Args&&... args) {
this->assert_mapped_type<O>();
auto statement = this->prepare(sqlite_orm::get_all_pointer<O, R>(std::forward<Args>(args)...));
return this->execute(statement);
}
#ifdef SQLITE_ORM_WITH_CPP20_ALIASES
template<orm_table_reference auto table,
class R = std::vector<std::unique_ptr<auto_decay_table_ref_t<table>>>,
class... Args>
auto get_all_pointer(Args&&... args) {
return this->get_all_pointer<auto_decay_table_ref_t<table>>(std::forward<Args>(args)...);
}
#endif
#ifdef SQLITE_ORM_OPTIONAL_SUPPORTED
/**
* SELECT * routine.
* O is an object type to be extracted. Must be specified explicitly.
* R is a container type. std::vector<std::optional<O>> is default
* @return All objects of type O as std::optional<O> stored in database at the moment.
* @example: storage.get_all_optional<User, std::list<std::optional<O>>>(); - SELECT * FROM users
* @example: storage.get_all_optional<User, std::list<std::optional<O>>>(where(length(&User::name) > 6)); - SELECT * FROM users WHERE LENGTH(name) > 6
*/
template<class O, class R = std::vector<std::optional<O>>, class... Args>
auto get_all_optional(Args&&... conditions) {
this->assert_mapped_type<O>();
auto statement = this->prepare(sqlite_orm::get_all_optional<O, R>(std::forward<Args>(conditions)...));
return this->execute(statement);
}
#endif
#ifdef SQLITE_ORM_WITH_CPP20_ALIASES
template<orm_table_reference auto table,
class R = std::vector<std::optional<auto_decay_table_ref_t<table>>>,
class... Args>
auto get_all_optional(Args&&... conditions) {
return this->get_all_optional<auto_decay_table_ref_t<table>>(std::forward<Args>(conditions)...);
}
#endif
/**
* Select * by id routine.
* throws std::system_error{orm_error_code::not_found} if object not found with given
* id. throws std::system_error with orm_error_category in case of db error. O is an object type to be
* extracted. Must be specified explicitly.
* @return Object of type O where id is equal parameter passed or throws
* `std::system_error{orm_error_code::not_found}` if there is no object with such id.
*/
template<class O, class... Ids>
O get(Ids... ids) {
this->assert_mapped_type<O>();
auto statement = this->prepare(sqlite_orm::get<O>(std::forward<Ids>(ids)...));
return this->execute(statement);
}
#ifdef SQLITE_ORM_WITH_CPP20_ALIASES
template<orm_table_reference auto table, class... Ids>
auto get(Ids... ids) {
return this->get<auto_decay_table_ref_t<table>>(std::forward<Ids>(ids)...);
}
#endif
/**
* The same as `get` function but doesn't throw an exception if noting found but returns std::unique_ptr
* with null value. throws std::system_error in case of db error.
*/
template<class O, class... Ids>
std::unique_ptr<O> get_pointer(Ids... ids) {
this->assert_mapped_type<O>();
auto statement = this->prepare(sqlite_orm::get_pointer<O>(std::forward<Ids>(ids)...));
return this->execute(statement);
}
#ifdef SQLITE_ORM_WITH_CPP20_ALIASES
template<orm_table_reference auto table, class... Ids>
auto get_pointer(Ids... ids) {
return this->get_pointer<auto_decay_table_ref_t<table>>(std::forward<Ids>(ids)...);
}
#endif
/**
* A previous version of get_pointer() that returns a shared_ptr
* instead of a unique_ptr. New code should prefer get_pointer()
* unless the data needs to be shared.
*
* @note
* Most scenarios don't need shared ownership of data, so we should prefer
* unique_ptr when possible. It's more efficient, doesn't require atomic
* ops for a reference count (which can cause major slowdowns on
* weakly-ordered platforms like ARM), and can be easily promoted to a
* shared_ptr, exactly like we're doing here.
* (Conversely, you _can't_ go from shared back to unique.)
*/
template<class O, class... Ids>
std::shared_ptr<O> get_no_throw(Ids... ids) {
return std::shared_ptr<O>(this->get_pointer<O>(std::forward<Ids>(ids)...));
}
#ifdef SQLITE_ORM_OPTIONAL_SUPPORTED
/**
* The same as `get` function but doesn't throw an exception if noting found but
* returns an empty std::optional. throws std::system_error in case of db error.
*/
template<class O, class... Ids>
std::optional<O> get_optional(Ids... ids) {
this->assert_mapped_type<O>();
auto statement = this->prepare(sqlite_orm::get_optional<O>(std::forward<Ids>(ids)...));
return this->execute(statement);
}
#endif // SQLITE_ORM_OPTIONAL_SUPPORTED
#ifdef SQLITE_ORM_WITH_CPP20_ALIASES
template<orm_table_reference auto table, class... Ids>
auto get_optional(Ids... ids) {
return this->get_optional<auto_decay_table_ref_t<table>>(std::forward<Ids>(ids)...);
}
#endif
/**
* SELECT COUNT(*) https://www.sqlite.org/lang_aggfunc.html#count
* @return Number of O object in table.
*/
template<class O, class... Args>
int count(Args&&... args) {
using R = mapped_type_proxy_t<O>;
this->assert_mapped_type<R>();
auto rows = this->select(sqlite_orm::count<R>(), std::forward<Args>(args)...);
if (!rows.empty()) {
return rows.front();
} else {
return 0;
}
}
#ifdef SQLITE_ORM_WITH_CPP20_ALIASES
template<orm_refers_to_table auto mapped, class... Args>
int count(Args&&... args) {
return this->count<auto_decay_table_ref_t<mapped>>(std::forward<Args>(args)...);
}
#endif
/**
* SELECT COUNT(X) https://www.sqlite.org/lang_aggfunc.html#count
* @param m member pointer to class mapped to the storage.
* @return count of `m` values from database.
*/
template<class F,
class... Args,
std::enable_if_t<polyfill::disjunction<std::is_member_pointer<F>, is_column_pointer<F>>::value,
bool> = true>
int count(F field, Args&&... args) {
this->assert_mapped_type<table_type_of_t<F>>();
auto rows = this->select(sqlite_orm::count(std::move(field)), std::forward<Args>(args)...);
if (!rows.empty()) {
return rows.front();
} else {
return 0;
}
}
/**
* AVG(X) query. https://www.sqlite.org/lang_aggfunc.html#avg
* @param m is a class member pointer (the same you passed into make_column).
* @return average value from database.
*/
template<class F,
class... Args,
std::enable_if_t<polyfill::disjunction<std::is_member_pointer<F>, is_column_pointer<F>>::value,
bool> = true>
double avg(F field, Args&&... args) {
this->assert_mapped_type<table_type_of_t<F>>();
auto rows = this->select(sqlite_orm::avg(std::move(field)), std::forward<Args>(args)...);
if (!rows.empty()) {
return rows.front();
} else {
return 0;
}
}
template<class F,
std::enable_if_t<polyfill::disjunction<std::is_member_pointer<F>, is_column_pointer<F>>::value,
bool> = true>
std::string group_concat(F field) {
return this->group_concat_internal(std::move(field), {});
}
/**
* GROUP_CONCAT(X) query. https://www.sqlite.org/lang_aggfunc.html#groupconcat
* @param m is a class member pointer (the same you passed into make_column).
* @return group_concat query result.
*/
template<class F,
class... Args,
class Tuple = std::tuple<Args...>,
std::enable_if_t<std::tuple_size<Tuple>::value >= 1, bool> = true,
std::enable_if_t<polyfill::disjunction<std::is_member_pointer<F>, is_column_pointer<F>>::value,
bool> = true>
std::string group_concat(F field, Args&&... args) {
return this->group_concat_internal(std::move(field), {}, std::forward<Args>(args)...);
}
/**
* GROUP_CONCAT(X, Y) query. https://www.sqlite.org/lang_aggfunc.html#groupconcat
* @param m is a class member pointer (the same you passed into make_column).
* @return group_concat query result.
*/
template<class F,
class... Args,
std::enable_if_t<polyfill::disjunction<std::is_member_pointer<F>, is_column_pointer<F>>::value,
bool> = true>
std::string group_concat(F field, std::string y, Args&&... args) {
return this->group_concat_internal(std::move(field),
std::make_unique<std::string>(std::move(y)),
std::forward<Args>(args)...);
}
template<class F,
class... Args,
std::enable_if_t<polyfill::disjunction<std::is_member_pointer<F>, is_column_pointer<F>>::value,
bool> = true>
std::string group_concat(F field, const char* y, Args&&... args) {
std::unique_ptr<std::string> str;
if (y) {
str = std::make_unique<std::string>(y);
} else {
str = std::make_unique<std::string>();
}
return this->group_concat_internal(std::move(field), std::move(str), std::forward<Args>(args)...);
}
/**
* MAX(x) query.
* @param m is a class member pointer (the same you passed into make_column).
* @return std::unique_ptr with max value or null if sqlite engine returned null.
*/
template<class F,
class... Args,
class R = column_result_of_t<db_objects_type, F>,
std::enable_if_t<polyfill::disjunction<std::is_member_pointer<F>, is_column_pointer<F>>::value,
bool> = true>
std::unique_ptr<R> max(F field, Args&&... args) {
this->assert_mapped_type<table_type_of_t<F>>();
auto rows = this->select(sqlite_orm::max(std::move(field)), std::forward<Args>(args)...);
if (!rows.empty()) {
return std::move(rows.front());
} else {
return {};
}
}
/**
* MIN(x) query.
* @param m is a class member pointer (the same you passed into make_column).
* @return std::unique_ptr with min value or null if sqlite engine returned null.
*/
template<class F,
class... Args,
class R = column_result_of_t<db_objects_type, F>,
std::enable_if_t<polyfill::disjunction<std::is_member_pointer<F>, is_column_pointer<F>>::value,
bool> = true>
std::unique_ptr<R> min(F field, Args&&... args) {
this->assert_mapped_type<table_type_of_t<F>>();
auto rows = this->select(sqlite_orm::min(std::move(field)), std::forward<Args>(args)...);
if (!rows.empty()) {
return std::move(rows.front());
} else {
return {};
}
}
/**
* SUM(x) query.
* @param m is a class member pointer (the same you passed into make_column).
* @return std::unique_ptr with sum value or null if sqlite engine returned null.
*/
template<class F,
class... Args,
class R = column_result_of_t<db_objects_type, F>,
std::enable_if_t<polyfill::disjunction<std::is_member_pointer<F>, is_column_pointer<F>>::value,
bool> = true>
std::unique_ptr<R> sum(F field, Args&&... args) {
this->assert_mapped_type<table_type_of_t<F>>();
std::vector<std::unique_ptr<double>> rows =
this->select(sqlite_orm::sum(std::move(field)), std::forward<Args>(args)...);
if (!rows.empty()) {
if (rows.front()) {
return std::make_unique<R>(std::move(*rows.front()));
} else {
return {};
}
} else {
return {};
}
}
/**
* TOTAL(x) query.
* @param m is a class member pointer (the same you passed into make_column).
* @return total value (the same as SUM but not nullable. More details here
* https://www.sqlite.org/lang_aggfunc.html)
*/
template<class F,
class... Args,
std::enable_if_t<polyfill::disjunction<std::is_member_pointer<F>, is_column_pointer<F>>::value,
bool> = true>
double total(F field, Args&&... args) {
this->assert_mapped_type<table_type_of_t<F>>();
auto rows = this->select(sqlite_orm::total(std::move(field)), std::forward<Args>(args)...);
if (!rows.empty()) {
return std::move(rows.front());
} else {
return {};
}
}
/**
* Select a single column into std::vector<T> or multiple columns into std::vector<std::tuple<...>>.
* For a single column use `auto rows = storage.select(&User::id, where(...));
* For multicolumns use `auto rows = storage.select(columns(&User::id, &User::name), where(...));
*/
template<class T, class... Args>
auto select(T m, Args... args) {
static_assert(!is_compound_operator_v<T> || sizeof...(Args) == 0,
"Cannot use args with a compound operator");
auto statement = this->prepare(sqlite_orm::select(std::move(m), std::forward<Args>(args)...));
return this->execute(statement);
}
#if (SQLITE_VERSION_NUMBER >= 3008003) && defined(SQLITE_ORM_WITH_CTE)
/**
* Using a CTE, select a single column into std::vector<T> or multiple columns into std::vector<std::tuple<...>>.
*/
template<class CTE, class E>
auto with(CTE cte, E expression) {
auto statement = this->prepare(sqlite_orm::with(std::move(cte), std::move(expression)));
return this->execute(statement);
}
/**
* Using a CTE, select a single column into std::vector<T> or multiple columns into std::vector<std::tuple<...>>.
*/
template<class... CTEs, class E>
auto with(common_table_expressions<CTEs...> cte, E expression) {
auto statement = this->prepare(sqlite_orm::with(std::move(cte), std::move(expression)));
return this->execute(statement);
}
/**
* Using a CTE, select a single column into std::vector<T> or multiple columns into std::vector<std::tuple<...>>.
*/
template<class CTE, class E>
auto with_recursive(CTE cte, E expression) {
auto statement = this->prepare(sqlite_orm::with_recursive(std::move(cte), std::move(expression)));
return this->execute(statement);
}
/**
* Using a CTE, select a single column into std::vector<T> or multiple columns into std::vector<std::tuple<...>>.
*/
template<class... CTEs, class E>
auto with_recursive(common_table_expressions<CTEs...> cte, E expression) {
auto statement = this->prepare(sqlite_orm::with_recursive(std::move(cte), std::move(expression)));
return this->execute(statement);
}
#endif
template<class T, satisfies<is_prepared_statement, T> = true>
std::string dump(const T& preparedStatement, bool parametrized = true) const {
return this->dump_highest_level(preparedStatement.expression, parametrized);
}
template<class E,
class Ex = polyfill::remove_cvref_t<E>,
std::enable_if_t<!is_prepared_statement<Ex>::value && !is_mapped<db_objects_type, Ex>::value,
bool> = true>
std::string dump(E&& expression, bool parametrized = false) const {
static_assert(is_preparable_v<self_type, Ex>, "Expression must be a high-level statement");
decltype(auto) e2 = static_if<is_select<Ex>::value>(
[](auto expression) -> auto {
expression.highest_level = true;
return expression;
},
[](const auto& expression) -> decltype(auto) {
return (expression);
})(std::forward<E>(expression));
return this->dump_highest_level(e2, parametrized);
}
/**
* Returns a string representation of object of a class mapped to the storage.
* Type of string has json-like style.
*/
template<class O, satisfies<is_mapped, db_objects_type, O> = true>
std::string dump(const O& object) const {
auto& table = this->get_table<O>();
std::stringstream ss;
ss << "{ ";
table.for_each_column([&ss, &object, first = true](auto& column) mutable {
using field_type = field_type_t<std::remove_reference_t<decltype(column)>>;
static constexpr std::array<const char*, 2> sep = {", ", ""};
ss << sep[std::exchange(first, false)] << column.name << " : '"
<< field_printer<field_type>{}(polyfill::invoke(column.member_pointer, object)) << "'";
});
ss << " }";
return ss.str();
}
/**
* This is REPLACE (INSERT OR REPLACE) function.
* Also if you need to insert value with knows id you should
* also you this function instead of insert cause inserts ignores
* id and creates own one.
*/
template<class O>
void replace(const O& o) {
this->assert_mapped_type<O>();
auto statement = this->prepare(sqlite_orm::replace(std::ref(o)));
this->execute(statement);
}
template<class It, class Projection = polyfill::identity>
void replace_range(It from, It to, Projection project = {}) {
using O = std::decay_t<decltype(polyfill::invoke(project, *from))>;
this->assert_mapped_type<O>();
if (from == to) {
return;
}
auto statement =
this->prepare(sqlite_orm::replace_range(std::move(from), std::move(to), std::move(project)));
this->execute(statement);
}
template<class O, class It, class Projection = polyfill::identity>
void replace_range(It from, It to, Projection project = {}) {
this->assert_mapped_type<O>();
if (from == to) {
return;
}
auto statement =
this->prepare(sqlite_orm::replace_range<O>(std::move(from), std::move(to), std::move(project)));
this->execute(statement);
}
template<class O, class... Cols>
int insert(const O& o, columns_t<Cols...> cols) {
static_assert(cols.count > 0, "Use insert or replace with 1 argument instead");
this->assert_mapped_type<O>();
auto statement = this->prepare(sqlite_orm::insert(std::ref(o), std::move(cols)));
return int(this->execute(statement));
}
/**
* Insert routine. Inserts object with all non primary key fields in passed object. Id of passed
* object doesn't matter.
* @return id of just created object.
*/
template<class O>
int insert(const O& o) {
this->assert_mapped_type<O>();
this->assert_insertable_type<O>();
auto statement = this->prepare(sqlite_orm::insert(std::ref(o)));
return int(this->execute(statement));
}
/**
* Raw insert routine. Use this if `insert` with object does not fit you. This insert is designed to be able
* to call any type of `INSERT` query with no limitations.
* @example
* ```sql
* INSERT INTO users (id, name) VALUES(5, 'Little Mix')
* ```
* will be
* ```c++
* storage.insert(into<User>, columns(&User::id, &User::name), values(std::make_tuple(5, "Little Mix")));
* ```
* One more example:
* ```sql
* INSERT INTO singers (name) VALUES ('Sofia Reyes')('Kungs')
* ```
* will be
* ```c++
* storage.insert(into<Singer>(), columns(&Singer::name), values(std::make_tuple("Sofia Reyes"), std::make_tuple("Kungs")));
* ```
* One can use `default_values` to add `DEFAULT VALUES` modifier:
* ```sql
* INSERT INTO users DEFAULT VALUES
* ```
* will be
* ```c++
* storage.insert(into<Singer>(), default_values());
* ```
* Also one can use `INSERT OR ABORT`/`INSERT OR FAIL`/`INSERT OR IGNORE`/`INSERT OR REPLACE`/`INSERT ROLLBACK`:
* ```c++
* storage.insert(or_ignore(), into<Singer>(), columns(&Singer::name), values(std::make_tuple("Sofia Reyes"), std::make_tuple("Kungs")));
* storage.insert(or_rollback(), into<Singer>(), default_values());
* storage.insert(or_abort(), into<User>, columns(&User::id, &User::name), values(std::make_tuple(5, "Little Mix")));
* ```
*/
template<class... Args>
void insert(Args... args) {
auto statement = this->prepare(sqlite_orm::insert(std::forward<Args>(args)...));
this->execute(statement);
}
/**
* Raw replace statement creation routine. Use this if `replace` with object does not fit you. This replace is designed to be able
* to call any type of `REPLACE` query with no limitations. Actually this is the same query as raw insert except `OR...` option existance.
* @example
* ```sql
* REPLACE INTO users (id, name) VALUES(5, 'Little Mix')
* ```
* will be
* ```c++
* storage.prepare(replace(into<User>, columns(&User::id, &User::name), values(std::make_tuple(5, "Little Mix"))));
* ```
* One more example:
* ```sql
* REPLACE INTO singers (name) VALUES ('Sofia Reyes')('Kungs')
* ```
* will be
* ```c++
* storage.prepare(replace(into<Singer>(), columns(&Singer::name), values(std::make_tuple("Sofia Reyes"), std::make_tuple("Kungs"))));
* ```
* One can use `default_values` to add `DEFAULT VALUES` modifier:
* ```sql
* REPLACE INTO users DEFAULT VALUES
* ```
* will be
* ```c++
* storage.prepare(replace(into<Singer>(), default_values()));
* ```
*/
template<class... Args>
void replace(Args... args) {
auto statement = this->prepare(sqlite_orm::replace(std::forward<Args>(args)...));
this->execute(statement);
}
template<class It, class Projection = polyfill::identity>
void insert_range(It from, It to, Projection project = {}) {
using O = std::decay_t<decltype(polyfill::invoke(std::declval<Projection>(), *std::declval<It>()))>;
this->assert_mapped_type<O>();
this->assert_insertable_type<O>();
if (from == to) {
return;
}
auto statement =
this->prepare(sqlite_orm::insert_range(std::move(from), std::move(to), std::move(project)));
this->execute(statement);
}
template<class O, class It, class Projection = polyfill::identity>
void insert_range(It from, It to, Projection project = {}) {
this->assert_mapped_type<O>();
this->assert_insertable_type<O>();
if (from == to) {
return;
}
auto statement =
this->prepare(sqlite_orm::insert_range<O>(std::move(from), std::move(to), std::move(project)));
this->execute(statement);
}
/**
* Change table name inside storage's schema info. This function does not
* affect database
*/
template<class O>
void rename_table(std::string name) {
this->assert_mapped_type<O>();
auto& table = this->get_table<O>();