Repository navigation
Expand file tree
/
Copy pathprovider.cpp
More file actions
2069 lines (1890 loc) · 79.9 KB
/
Copy pathprovider.cpp
File metadata and controls
2069 lines (1890 loc) · 79.9 KB
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
#include <teaql/provider_sqlite/provider.hpp>
#include <teaql/provider_sqlite/id.hpp>
#include <teaql/provider_sqlite/business_id.hpp>
#include <teaql/runtime/id_space.hpp>
#include <teaql/provider_sqlite/dialect.hpp>
#include <teaql/provider_sqlite/schema.hpp>
#include <teaql/provider_sqlite/detail/schema.hpp>
#include <teaql/provider_sqlite/detail/bindings.hpp>
#include <teaql/provider_sqlite/detail/decoding.hpp>
#include <teaql/provider_sqlite/detail/dynamic_fields.hpp>
#include <teaql/core/detail/text.hpp>
#include <sqlite3.h>
#include <algorithm>
#include <charconv>
#include <thread>
namespace teaql::detail {
namespace {
template <class T>
void append_number(String& out, T value) {
char buffer[32];
auto end = std::to_chars(buffer, buffer + sizeof(buffer), value).ptr;
out.append(buffer, end);
}
MutationExecutorError native_error(Memory r, sqlite3* db, int code) {
// A null statement can report MISUSE without updating the connection's
// last error. Match rusqlite's error_from_handle instead of using stale state.
const auto* message =
(!db || sqlite3_errcode(db) != code) ? sqlite3_errstr(code) : sqlite3_errmsg(db);
return MutationExecutorError::sqlite(r, code, message);
}
MutationExecutorError prepare_error(Memory r, sqlite3* db, int code, std::string_view sql) {
#if SQLITE_VERSION_NUMBER >= 3038000
if ((code & 0xff) == SQLITE_ERROR) {
if (auto offset = sqlite3_error_offset(db); offset >= 0) {
return MutationExecutorError::sqlite(
r, SqliteDriverError::sql_input(r, code, sqlite3_errmsg(db), sql, offset));
}
}
#else
(void)sql;
#endif
return native_error(r, db, code);
}
struct StatementEntry {
using allocator_type = Allocator;
String key;
sqlite3_stmt* statement = nullptr;
bool loaned = false;
StatementEntry(std::allocator_arg_t, Allocator a) : key(a.resource()) {}
StatementEntry(std::allocator_arg_t, Allocator a, StatementEntry&& other)
: key(std::move(other.key), a.resource()),
statement(std::exchange(other.statement, nullptr)),
loaned(std::exchange(other.loaned, false)) {}
StatementEntry(const StatementEntry&) = delete;
};
struct LayoutEntry {
using allocator_type = Allocator;
String key;
const SqliteRowLayout* layout = nullptr;
LayoutEntry(std::allocator_arg_t, Allocator a) : key(a.resource()) {}
LayoutEntry(std::allocator_arg_t, Allocator a, LayoutEntry&& other)
: key(std::move(other.key), a.resource()), layout(other.layout) {}
LayoutEntry(const LayoutEntry&) = delete;
};
}
struct SqliteLease;
struct SqliteConnectionState {
using allocator_type = Allocator;
Memory resource;
sqlite3* db = nullptr;
std::thread::id owner = std::this_thread::get_id();
Vector<StatementEntry> statements;
// MRU at the front, idle statements only. Capacity is fixed after creation.
Vector<std::size_t> recency;
SqliteLease* active = nullptr;
SqliteLease* first = nullptr;
SqliteLease* last = nullptr;
bool poisoned = false;
// Identity only, never an owning pointer. Native autocommit invalidates the
// identity so an old consumed handle cannot roll back a later transaction.
const void* transaction_owner = nullptr;
// Present only inside an explicitly bound synchronous transaction scope.
const void* resource_transaction = nullptr;
Memory resource_context = nullptr;
const void* id_transaction(Memory r) const {
if (resource_transaction && resource_context == r) {
if (resource_transaction != transaction_owner || sqlite3_get_autocommit(db)) {
throw MutationExecutorError::lock(
r, "SQLite transaction resource scope is no longer active");
}
return resource_transaction;
}
return nullptr;
}
// Recovery for a synchronous allocation is not an asynchronous lease.
const void* recovery_owner = nullptr;
SqliteConnectionState(std::allocator_arg_t, Allocator a, std::string_view filename)
: resource(a.resource()), statements(resource), recency(resource) {
statements.reserve(DEFAULT_PREPARED_STATEMENT_CACHE_CAPACITY);
for (std::size_t i = 0; i < DEFAULT_PREPARED_STATEMENT_CACHE_CAPACITY; ++i) {
statements.emplace_back();
}
recency.reserve(DEFAULT_PREPARED_STATEMENT_CACHE_CAPACITY);
// Resource construction failures are native C++ exceptions, as opposed
// to Context-borrowed provider results. They must survive stack unwinding
// that destroys the Context which attempted to create the connection.
if (filename.find('\0') != filename.npos) {
throw std::invalid_argument("SQLite filename contains a NUL byte");
}
String path(filename, resource);
auto code = sqlite3_open_v2(path.c_str(),
&db,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI |
SQLITE_OPEN_NOMUTEX,
nullptr);
if (code != SQLITE_OK) {
try {
throw std::runtime_error(db ? sqlite3_errmsg(db)
: "SQLite connection allocation failed");
} catch (...) {
sqlite3_close(db);
db = nullptr;
throw;
}
}
sqlite3_extended_result_codes(db, 1);
// rusqlite's default connection busy timeout.
sqlite3_busy_timeout(db, 5000);
}
~SqliteConnectionState() {
if (active || first) {
std::terminate();
}
flush();
if (db && sqlite3_close(db) != SQLITE_OK) {
std::terminate();
}
}
void require_owner() const {
if (owner != std::this_thread::get_id()) {
throw std::logic_error("SQLite Context resources are owner-thread confined");
}
}
void require_borrow(Memory destination) const {
require_owner();
if (!async_arena(resource).can_lend_to(async_arena(destination))) {
throw std::invalid_argument(
"SQLite work cannot retain a connection from a shorter or unrelated Context");
}
}
void flush() noexcept {
for (auto& entry : statements) {
sqlite3_finalize(entry.statement);
entry.statement = nullptr;
}
recency.clear();
}
void prepare(Memory r,
std::string_view sql,
bool cached,
sqlite3_stmt*& statement,
StatementEntry*& entry) {
require_owner();
if (cached) {
trim(sql);
}
if (cached) {
for (auto p = recency.begin(); p != recency.end(); ++p) {
if (statements[*p].key == sql) {
entry = &statements[*p];
statement = std::exchange(entry->statement, nullptr);
recency.erase(p);
entry->loaned = true;
return;
}
}
}
if (sql.size() > INT32_MAX) {
throw MutationExecutorError::sqlite(r, SQLITE_TOOBIG, "string or blob too big");
}
const char* tail = nullptr;
auto code = sqlite3_prepare_v3(db,
sql.data(),
int(sql.size()),
cached ? SQLITE_PREPARE_PERSISTENT : 0,
&statement,
&tail);
if (code != SQLITE_OK) {
throw prepare_error(r, db, code, sql);
}
// rusqlite prepares trailing SQL before reporting MultipleStatement;
// trailing syntax/schema errors therefore take precedence.
try {
auto rest = sql;
bool extra = false;
while (tail && tail > rest.data() && tail < rest.data() + rest.size()) {
rest.remove_prefix(std::size_t(tail - rest.data()));
sqlite3_stmt* next = nullptr;
code = sqlite3_prepare_v3(db, rest.data(), int(rest.size()), 0, &next, &tail);
if (code != SQLITE_OK) {
throw prepare_error(r, db, code, rest);
}
extra |= next != nullptr;
sqlite3_finalize(next);
}
if (extra) {
throw MutationExecutorError::sqlite(r, SqliteDriverError::multiple_statement(r));
}
if (cached && statement) {
auto slot = std::find_if(statements.begin(), statements.end(), [](const auto& e) {
return !e.statement && !e.loaned;
});
if (slot == statements.end() && recency.empty()) {
return; // Every fixed cache slot is borrowed; retain a transient statement.
}
if (slot == statements.end()) {
auto index = recency.back();
recency.pop_back();
slot = statements.begin() + std::ptrdiff_t(index);
sqlite3_finalize(slot->statement);
slot->statement = nullptr;
}
slot->key = sql;
entry = &*slot;
entry->loaned = true;
}
} catch (...) {
sqlite3_finalize(statement);
statement = nullptr;
throw;
}
}
void release_statement(sqlite3_stmt*& statement, StatementEntry*& entry) noexcept {
if (!statement) {
return;
}
sqlite3_reset(statement);
sqlite3_clear_bindings(statement);
if (entry) {
// Concurrent checkouts of one key return a single idle cache entry,
// matching the source map's replacement behavior.
for (auto position = recency.begin(); position != recency.end(); ++position) {
auto& other = statements[*position];
if (other.key == entry->key) {
sqlite3_finalize(other.statement);
other.statement = nullptr;
recency.erase(position);
break;
}
}
entry->statement = statement;
entry->loaned = false;
recency.insert(recency.begin(), std::size_t(entry - statements.data()));
entry = nullptr;
} else {
sqlite3_finalize(statement);
}
statement = nullptr;
}
};
class SqliteCachedDynamicStatements final : public SqliteDynamicStatementCache {
public:
explicit SqliteCachedDynamicStatements(SqliteConnectionState& connection)
: connection_(connection) {}
SqliteDynamicStatement prepare(Memory r, std::string_view sql) override {
sqlite3_stmt* statement = nullptr;
StatementEntry* entry = nullptr;
try {
connection_.prepare(r, sql, true, statement, entry);
} catch (const MutationExecutorError&) {
throw DynamicFieldError(r, "DYNAMIC_FIELD_STORAGE_FAILED", "storage");
}
if (!statement) {
throw DynamicFieldError(r, "DYNAMIC_FIELD_STORAGE_FAILED", "storage");
}
return SqliteDynamicStatement(
statement,
{&connection_, entry, [](void* owner, sqlite3_stmt* value, void* slot) noexcept {
auto* entry = static_cast<StatementEntry*>(slot);
static_cast<SqliteConnectionState*>(owner)->release_statement(value, entry);
}});
}
private:
SqliteConnectionState& connection_;
};
// Intrusive, allocation-free wait queue. SQLite calls run on the owner thread;
// the lease remains held between stream polls just like Rust's guarded cursor.
struct SqliteLease {
Memory resource;
SqliteConnectionState& connection;
SqliteLease* previous = nullptr;
SqliteLease* next = nullptr;
WakeSignal* wake = nullptr;
bool queued = false, owned = false;
const void* transaction = nullptr;
SqliteLease(Memory r, SqliteConnectionState& connection, const void* transaction = nullptr)
: resource(r), connection(connection), transaction(transaction) {}
~SqliteLease() {
release();
}
void unlink() noexcept {
if (!queued) {
return;
}
if (previous) {
previous->next = next;
} else {
connection.first = next;
}
if (next) {
next->previous = previous;
} else {
connection.last = previous;
}
previous = next = nullptr;
queued = false;
}
void require_unpoisoned() {
if (connection.poisoned) {
release();
throw MutationExecutorError::lock(resource,
"poisoned lock: another task failed inside");
}
}
bool acquire(WakeSignal& signal, bool defer_connection_lock = false) {
connection.require_owner();
if (owned) {
return true;
}
wake = &signal;
if (!defer_connection_lock) {
require_unpoisoned();
}
const bool allowed =
!connection.transaction_owner || connection.transaction_owner == transaction;
if (allowed && !connection.active &&
(connection.transaction_owner == transaction && transaction || !connection.first ||
connection.first == this)) {
unlink();
connection.active = this;
owned = true;
return true;
}
if (!queued) {
previous = connection.last;
if (previous) {
previous->next = this;
} else {
connection.first = this;
}
connection.last = this;
queued = true;
}
return false;
}
void release() noexcept {
if (!owned && !queued) {
return;
}
unlink();
if (owned) {
connection.active = nullptr;
owned = false;
}
wake = nullptr;
if (!connection.active && connection.first) {
connection.first->wake->notify();
}
}
};
struct SqliteProviderState {
using allocator_type = Allocator;
Memory resource;
SqliteConnectionState& connection;
Vector<LayoutEntry> layouts;
std::size_t count = 0;
std::uint64_t storage_instance_id = 0;
SqliteProviderState(std::allocator_arg_t, Allocator a, SqliteConnectionState& connection)
: resource(a.resource()), connection(connection), layouts(resource) {
connection.require_borrow(resource);
layouts.reserve(DEFAULT_COLUMN_LAYOUT_CACHE_CAPACITY);
for (std::size_t i = 0; i < DEFAULT_COLUMN_LAYOUT_CACHE_CAPACITY; ++i) {
layouts.emplace_back();
}
}
void require_borrow(Memory destination) const {
connection.require_borrow(destination);
// Connection and provider have independent owners. Global connections
// can serve User-local providers; their layouts and operation state
// cannot escape into another User or into Global.
if (!async_arena(resource).can_lend_to(async_arena(destination))) {
throw std::invalid_argument(
"SQLite work cannot retain a provider from a shorter or unrelated Context");
}
}
const SqliteRowLayout&
layout(Memory destination, std::string_view sql, sqlite3_stmt* statement) {
const SqliteRowLayout* found = nullptr;
for (std::size_t i = 0; i < count; ++i) {
if (layouts[i].key == sql) {
found = layouts[i].layout;
break;
}
}
if (!found) {
auto& arena = async_arena(resource);
found = statement ? &arena.make<SqliteRowLayout>(*statement)
: &arena.make<SqliteRowLayout>();
if (count == DEFAULT_COLUMN_LAYOUT_CACHE_CAPACITY) {
count = 0;
}
auto& entry = layouts[count];
entry.key = sql;
entry.layout = found;
++count;
}
if (destination == resource) {
return *found;
}
return async_arena(destination).make<SqliteRowLayout>(*found);
}
};
struct SqliteSchemaCall {
using allocator_type = Allocator;
Memory resource;
const UserContext& context;
const SqliteDialect* dialect = nullptr;
SqliteProviderState* state = nullptr;
Vector<const EntityDescriptor*> entities;
std::optional<SqliteLease> lease;
SqliteSchemaCall(std::allocator_arg_t, Allocator a, const UserContext& context)
: resource(a.resource()), context(context), entities(resource) {}
std::optional<RuntimeSchemaResult> poll(WakeSignal& wake) {
try {
if (!lease) {
dialect = context.get_resource<SqliteDialect>();
if (!dialect) {
throw MutationExecutorError::bind(resource,
"missing typed resource: SqliteDialect");
}
auto* executor = context.get_resource<SqliteMutationExecutor>();
if (!executor) {
throw MutationExecutorError::bind(
resource, "missing typed resource: SqliteMutationExecutor");
}
entities = context.all_entities();
state = &executor->state_;
state->require_borrow(resource);
lease.emplace(resource, state->connection);
}
if (!lease->acquire(wake)) {
return {};
}
ensure_sqlite_physical_schema(
resource, *state->connection.db, *dialect, entities, context);
lease->release();
state->connection.flush();
state->count = 0;
if (!context.initial_graphs().empty() || !context.root_graphs().empty()) {
throw MutationExecutorError::bind(
resource,
"generated root/constant bootstrap must use the typed RuntimeModule callback");
}
return RuntimeSchemaResult::ok(resource, {});
} catch (MutationExecutorError& e) {
return RuntimeSchemaResult::err(resource,
RuntimeError::schema(resource, e.to_string(resource)));
} catch (...) {
if (lease && lease->owned) {
state->connection.poisoned = true;
}
throw;
}
}
void finish_and_wait() noexcept {
lease.reset();
}
void cancel_and_wait() noexcept {
lease.reset();
}
};
struct SqliteCursor {
Memory resource;
SqliteProviderState& provider;
SqliteLease lease;
sqlite3_stmt* statement = nullptr;
StatementEntry* entry = nullptr;
const SqliteRowLayout* layout = nullptr;
SqliteCursor(Memory r, SqliteProviderState& provider, const void* transaction = nullptr)
: resource(r), provider(provider), lease(r, provider.connection, transaction) {}
~SqliteCursor() {
close();
}
void close() noexcept {
provider.connection.release_statement(statement, entry);
lease.release();
}
void prepare(const CompiledQuery& query, bool cached) {
auto sql = query.sql_with_comment(resource);
provider.connection.prepare(resource, sql, cached, statement, entry);
if (cached) {
layout = &provider.layout(resource, query.sql, statement);
}
}
void bind(std::span<const SqliteBoundValue> values) {
if (!statement) {
if (!values.empty()) {
throw MutationExecutorError::sqlite(
resource, SqliteDriverError::invalid_parameter_count(resource, 1, 0));
}
return;
}
auto result = bind_statement(resource, *statement, values);
if (!result) {
throw std::move(result).error();
}
}
bool next() {
auto code = sqlite3_step(statement);
if (sqlite3_get_autocommit(provider.connection.db)) {
provider.connection.transaction_owner = nullptr;
provider.connection.recovery_owner = nullptr;
}
if (code == SQLITE_ROW) {
return true;
}
if (code == SQLITE_DONE) {
return false;
}
throw native_error(resource, provider.connection.db, code);
}
CompactRow row() {
auto result = decode_sqlite_row(resource, *statement, *layout);
if (!result) {
throw std::move(result).error();
}
return std::move(result).value();
}
void reset() {
auto code = sqlite3_reset(statement);
if (code != SQLITE_OK) {
throw native_error(resource, provider.connection.db, code);
}
sqlite3_clear_bindings(statement);
}
};
// ID allocation reads native INTEGERs strictly, without Value's declaration or
// text inference. Keep one connection lease across the read/CAS write pair.
struct SqliteIdAccess {
Memory resource;
SqliteCursor cursor;
WakeSignal wake;
SqliteIdAccess(Memory r, SqliteProviderState& state)
: resource(r), cursor(r, state, state.connection.id_transaction(r)) {
if (!cursor.lease.acquire(wake)) {
throw MutationExecutorError::lock(
r, "connection is borrowed by an open SQLite stream; use the pollable transport");
}
}
void prepare(std::string_view sql, std::span<const Value> values) {
cursor.provider.connection.release_statement(cursor.statement, cursor.entry);
CompiledQuery query(std::allocator_arg, Allocator(resource));
query.sql = sql;
for (const auto& value : values) {
query.params.emplace_back(value);
}
cursor.prepare(query, false);
auto bound = bind_values(resource, query.params);
if (!bound) {
throw std::move(bound).error();
}
cursor.bind(bound.value());
}
std::int64_t integer(int index) {
auto type = sqlite3_column_type(cursor.statement, index);
if (type != SQLITE_INTEGER) {
auto native_type = type == SQLITE_FLOAT ? SqliteValueType::Real
: type == SQLITE_TEXT ? SqliteValueType::Text
: type == SQLITE_BLOB ? SqliteValueType::Blob
: SqliteValueType::Null;
throw MutationExecutorError::sqlite(
resource,
SqliteDriverError::invalid_column_type(resource,
std::size_t(index),
sqlite3_column_name(cursor.statement, index),
native_type));
}
return sqlite3_column_int64(cursor.statement, index);
}
std::optional<std::int64_t> current(std::string_view sql, std::span<const Value> values) {
prepare(sql, values);
if (!cursor.next()) {
return {};
}
return integer(0);
}
std::optional<std::pair<std::int64_t, std::int64_t>>
current_business(std::string_view sql, std::span<const Value> values) {
prepare(sql, values);
if (!cursor.next()) {
return {};
}
auto level = integer(0);
auto version = integer(1);
return std::pair(level, version);
}
std::uint64_t execute(std::string_view sql, std::span<const Value> values) {
prepare(sql, values);
if (cursor.next()) {
throw MutationExecutorError::sqlite(
resource, SqliteDriverError::execute_returned_results(resource));
}
cursor.reset();
return std::uint64_t(sqlite3_changes64(cursor.provider.connection.db));
}
};
template <class T>
struct SqliteCall {
using allocator_type = Allocator;
using Output = Result<T, MutationExecutorError>;
Memory resource;
CompiledQuery query;
SqliteCursor cursor;
std::optional<SqliteBindings> bindings;
bool wait_before_binding;
SqliteCall(std::allocator_arg_t,
Allocator a,
SqliteProviderState& state,
const CompiledQuery& query,
const void* transaction = nullptr,
bool wait_before_binding = false)
: resource(a.resource()), query(std::allocator_arg, a, query),
cursor(resource, state, transaction), wait_before_binding(wait_before_binding) {}
std::optional<Output> poll(WakeSignal& wake) {
bool native_guard = false;
try {
// Root async calls await the source transaction lease before binding.
// Synchronous and transaction-bound calls retain bind-before-lock.
if (wait_before_binding && !cursor.lease.acquire(wake, true)) {
return {};
}
if (!bindings) {
auto result = bind_values(resource, query.params);
if (!result) {
return Output::err(resource, std::move(result).error());
}
bindings.emplace(std::move(result).value());
}
if (!cursor.lease.acquire(wake)) {
return {};
}
cursor.lease.require_unpoisoned();
native_guard = true;
cursor.prepare(query, !std::is_same_v<T, std::uint64_t>);
cursor.bind(*bindings);
if constexpr (std::is_same_v<T, std::uint64_t>) {
if (cursor.next()) {
return Output::err(
resource,
MutationExecutorError::sqlite(
resource, SqliteDriverError::execute_returned_results(resource)));
}
cursor.reset();
return Output::ok(resource,
std::uint64_t(sqlite3_changes64(cursor.provider.connection.db)));
} else {
T rows(resource);
while (cursor.next()) {
rows.push_back(cursor.row());
}
return Output::ok(resource, std::move(rows));
}
} catch (MutationExecutorError& error) {
return Output::err(resource, std::move(error));
} catch (...) {
if (native_guard && cursor.lease.owned) {
cursor.provider.connection.poisoned = true;
}
throw;
}
}
void finish_and_wait() noexcept {
cursor.close();
}
void cancel_and_wait() noexcept {
cursor.close();
}
};
struct SqliteRepeatedCall {
using allocator_type = Allocator;
using Rows = Vector<CompactRow>;
using Output = Result<Rows, MutationExecutorError>;
Memory resource;
CompiledQuery query;
SqliteCursor cursor;
std::size_t index;
Vector<Value> values;
SqliteRepeatedCall(std::allocator_arg_t,
Allocator a,
SqliteProviderState& state,
const CompiledQuery& query,
std::size_t index,
std::span<const Value> values,
const void* transaction = nullptr)
: resource(a.resource()), query(std::allocator_arg, a, query),
cursor(resource, state, transaction), index(index),
values(values.begin(), values.end(), resource) {}
std::optional<Output> poll(WakeSignal& wake) {
bool native_guard = false;
try {
if (!cursor.lease.acquire(wake, true)) {
return {};
}
cursor.lease.require_unpoisoned();
native_guard = true;
cursor.prepare(query, true);
Rows rows(resource);
for (const auto& value : values) {
query.params.at(index) = Value(resource, value);
auto bindings = bind_values(resource, query.params);
if (!bindings) {
return Output::err(resource, std::move(bindings).error());
}
cursor.bind(bindings.value());
while (cursor.next()) {
rows.push_back(cursor.row());
}
cursor.reset();
}
return Output::ok(resource, std::move(rows));
} catch (MutationExecutorError& error) {
return Output::err(resource, std::move(error));
} catch (...) {
if (native_guard && cursor.lease.owned) {
cursor.provider.connection.poisoned = true;
}
throw;
}
}
void finish_and_wait() noexcept {
cursor.close();
}
void cancel_and_wait() noexcept {
cursor.close();
}
};
CompiledQuery transaction_query(Memory r, std::string_view sql) {
CompiledQuery query(std::allocator_arg, Allocator(r));
query.sql = sql;
return query;
}
struct SqliteDynamicErrorCall {
using allocator_type = Allocator;
Memory resource;
SqliteDynamicErrorCall(std::allocator_arg_t, Allocator a) : resource(a.resource()) {}
std::optional<Result<std::monostate, DynamicFieldError>> poll(WakeSignal&) {
return Result<std::monostate, DynamicFieldError>::err(
resource,
DynamicFieldError(resource, "DYNAMIC_FIELD_TRANSACTION_BINDING_REQUIRED", "save"));
}
void finish_and_wait() noexcept {}
void cancel_and_wait() noexcept {}
};
template <class T>
struct SqliteDynamicCall {
using allocator_type = Allocator;
using Output = Result<T, DynamicFieldError>;
Memory resource;
SqliteProviderState& provider;
SqliteLease lease;
String namespace_name;
std::optional<ArenaBorrow<DynamicFieldDefinitions>> definitions;
std::optional<DynamicFieldSelection> selection;
Vector<std::uint64_t> ids;
Vector<DynamicFieldWrite> writes;
std::optional<QueryIntent> query_intent;
std::optional<MutationIntent> mutation_intent;
bool apply = false;
SqliteDynamicCall(std::allocator_arg_t,
Allocator a,
SqliteProviderState& provider,
const void* transaction = nullptr)
: resource(a.resource()), provider(provider),
lease(resource, provider.connection, transaction), namespace_name(resource),
ids(resource), writes(resource) {}
SqliteDynamicCall(std::allocator_arg_t,
Allocator a,
SqliteProviderState& provider,
std::string_view namespace_name,
const DynamicFieldDefinitions& schema,
std::span<const std::uint64_t> ids,
const DynamicFieldSelection& selection,
const QueryIntent& intent,
const void* transaction = nullptr)
: SqliteDynamicCall(std::allocator_arg, a, provider, transaction) {
intent.require_valid();
this->namespace_name = namespace_name;
auto& target = async_arena(resource);
auto& origin = async_arena(schema.memory_resource());
const auto& copied =
origin.can_lend_to(target) ? schema : target.make<DynamicFieldDefinitions>(schema);
definitions.emplace(std::allocator_arg, a, copied);
this->ids.assign(ids.begin(), ids.end());
this->selection.emplace(std::allocator_arg, a, selection);
query_intent.emplace(std::allocator_arg, a, intent);
}
SqliteDynamicCall(std::allocator_arg_t,
Allocator a,
SqliteProviderState& provider,
std::span<const DynamicFieldWrite> writes,
const MutationIntent& intent,
const void* transaction)
: SqliteDynamicCall(std::allocator_arg, a, provider, transaction) {
intent.require_valid();
apply = true;
for (const auto& write : writes) {
this->writes.emplace_back(write);
}
mutation_intent.emplace(std::allocator_arg, a, intent);
}
std::optional<Output> poll(WakeSignal& wake) {
try {
if (lease.transaction && (provider.connection.transaction_owner != lease.transaction ||
sqlite3_get_autocommit(provider.connection.db))) {
return Output::err(resource,
DynamicFieldError(resource,
"DYNAMIC_FIELD_TRANSACTION_BINDING_REQUIRED",
"save"));
}
if (!lease.acquire(wake)) {
return {};
}
SqliteCachedDynamicStatements cache(provider.connection);
if constexpr (std::same_as<T, DynamicStorageRows>) {
return sqlite_dynamic_load(
resource, cache, namespace_name, definitions->get(), ids, *selection);
} else {
return apply ? sqlite_dynamic_apply(resource, cache, writes)
: sqlite_dynamic_ensure_schema(resource, provider.connection.db);
}
} catch (MutationExecutorError&) {
return Output::err(
resource, DynamicFieldError(resource, "DYNAMIC_FIELD_STORAGE_FAILED", "storage"));
} catch (...) {
if (lease.owned) {
provider.connection.poisoned = true;
}
throw;
}
}
void finish_and_wait() noexcept {
lease.release();
}
void cancel_and_wait() noexcept {
lease.release();
}
};
// Rust's associated Tx is a provider clone. This scoped carrier keeps that
// connection/cache borrow while making the consuming terminal API explicit.
struct SqliteNativeTransaction final : SqlTransportTransaction<MutationExecutorError>,
StreamingSqlTransport<MutationExecutorError>,
DynamicFieldStore {
using allocator_type = Allocator;
SqliteProviderState& provider;
Arena::Quiescence quiescence;
SqliteNativeTransaction(std::allocator_arg_t, Allocator a, SqliteProviderState& provider)
: SqlTransportTransaction<MutationExecutorError>(a.resource()), provider(provider) {
quiescence.attach(async_arena(a.resource()), this, [](void* p) noexcept {
static_cast<SqliteNativeTransaction*>(p)->abandon();
});
}
~SqliteNativeTransaction() {
abandon();
}
const DynamicFieldStore* dynamic_field_store() const override {
return this;
}
bool is_transaction_bound() const override {
return !consumed() && provider.connection.transaction_owner == this &&
!sqlite3_get_autocommit(provider.connection.db);
}
std::uintptr_t binding_key() const override {
return reinterpret_cast<std::uintptr_t>(&provider);
}
std::optional<std::uint64_t> source_identity() const override {
return provider.storage_instance_id;
}
DynamicStorageFuture<std::monostate>& ensure_schema(Memory) const override;
DynamicStorageFuture<DynamicStorageRows>& load_values(Memory,
std::string_view,
const DynamicFieldDefinitions&,
std::span<const std::uint64_t>,
const DynamicFieldSelection&,
const QueryIntent&) const override;
Result<std::monostate, DynamicFieldError>
validate_writes(Memory, std::span<const DynamicFieldWrite>) const override;
DynamicStorageFuture<std::monostate>&
apply_writes(Memory, std::span<const DynamicFieldWrite>, const MutationIntent&) const override;
QueryStream<MutationExecutorError>& stream_sql(Memory, CompiledQuery, std::size_t) override;
TransactionResourceScope do_bind_transaction_resources(Memory r) override {
auto& connection = provider.connection;
connection.require_owner();
if (connection.transaction_owner != this || sqlite3_get_autocommit(connection.db) ||
(connection.resource_transaction && connection.resource_transaction != this)) {
throw std::logic_error("SQLite resource scope requires its active native transaction");
}
if (resource_scope_depth == std::numeric_limits<std::size_t>::max()) {
throw std::overflow_error("SQLite transaction resource scope nesting exhausted");
}
++resource_scope_depth;
connection.resource_transaction = this;