Repository navigation
Expand file tree
/
Copy pathrelation_hydration_tests.cpp
More file actions
673 lines (637 loc) · 29.7 KB
/
Copy pathrelation_hydration_tests.cpp
File metadata and controls
673 lines (637 loc) · 29.7 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
#include "../../tests/support/relation_hydration_fixture.hpp"
#include <teaql/provider_sqlite/provider.hpp>
#include <teaql/provider_sqlite/dialect.hpp>
#include <teaql/sql/executor.hpp>
#include <teaql/runtime/data_service.hpp>
#include <atomic>
#include <iostream>
#include <semaphore>
#include <thread>
using namespace hydration_fixture;
using Access = detail::ContextEntityAccess;
using ServiceAccess = detail::EntityDataServiceAccess;
static void check(bool value, const char* message) {
if (!value) {
throw std::runtime_error(message);
}
}
template <class F>
static void rejected(F&& f, const char* message) {
bool failed = false;
try {
f();
} catch (const std::logic_error&) {
failed = true;
}
check(failed, message);
}
static CompactRow row(Memory r,
std::initializer_list<std::pair<std::string_view, std::uint64_t>> fields) {
Record values(r);
for (auto [key, value] : fields) {
values.emplace(String(key, r), Value(r, value));
}
return CompactRow(std::allocator_arg, Allocator(r), values);
}
static InMemoryMetadataStore& metadata(UserContext& c) {
auto r = c.memory_resource();
auto& store = c.make<InMemoryMetadataStore>();
EntityDescriptor parent(std::allocator_arg, Allocator(r), "Parent");
parent.table("parents");
parent.property("id", DataType::U64).is_id = true;
auto& children = parent.relation("children", "Child");
children.local_key = "id";
children.foreign_key = "parent_id";
children.many = true;
EntityDescriptor child(std::allocator_arg, Allocator(r), "Child");
child.table("children");
child.property("id", DataType::U64).is_id = true;
child.property("parent_id", DataType::U64);
child.property("leaf_ref", DataType::U64);
auto& back = child.relation("parent", "Parent");
back.local_key = "parent_id";
back.foreign_key = "id";
auto& product = child.relation("product", "Leaf");
product.local_key = "leaf_ref";
product.foreign_key = "id";
EntityDescriptor leaf(std::allocator_arg, Allocator(r), "Leaf");
leaf.table("leaves");
leaf.property("id", DataType::U64).is_id = true;
store.register_entity(std::move(parent));
store.register_entity(std::move(child));
store.register_entity(std::move(leaf));
c.set_metadata(c, store);
auto& decoders = c.make<InMemoryEntityGraphDecoderRegistry>();
decoders.register_entity<Model<0>>();
decoders.register_entity<Model<1>>();
decoders.register_entity<Model<2>>();
c.set_entity_graph_decoder_registry(decoders);
return store;
}
static Vector<RelationLoadPlan>& plans(UserContext& c) {
auto r = c.memory_resource();
auto& result = c.make<Vector<RelationLoadPlan>>();
RelationDescriptor children(std::allocator_arg, Allocator(r), "children", "Child");
children.local_key = "id";
children.foreign_key = "parent_id";
children.many = true;
result.emplace_back("Parent", children);
result.back().query.emplace(std::allocator_arg, Allocator(r), "Child");
result.back().query->order_asc("id");
RelationDescriptor product(std::allocator_arg, Allocator(r), "product", "Leaf");
product.local_key = "leaf_ref";
product.foreign_key = "id";
result.back().children.emplace_back("Child", product);
return result;
}
static void check_graph(const EntityRuntimeState& root, Memory r, bool compact) {
auto children = root.relation_list<Model<1>>("Parent", 1, "children");
auto empty = root.relation_list<Model<1>>("Parent", 2, "children");
check(children.state() == LoadedRelation::Loaded && children.value()->data.size() == 3,
"SQLite children installed through list decoder");
check(empty.state() == LoadedRelation::Empty && empty.value()->is_loaded &&
!root.has_relation_view("Parent", 3, "children"),
"loaded empty and not loaded remain distinct");
auto* leaf = root.resolve_entity<Model<2>>(20);
check(leaf && leaf->memory_resource() == r, "forward target installed in its identity table");
const auto& a = children.value()->data[0];
const auto& b = children.value()->data[1];
const auto& missing = children.value()->data[2];
check(a.state && b.state && a.state->resolve_entity<Model<2>>(20) == leaf &&
b.state->resolve_entity<Model<2>>(20) == leaf,
"relation model states resolve one shared target identity");
check(!root.has_relation_view("Child", 10, "product") &&
!root.has_relation_view("Child", 11, "product"),
"owners sharing a fetched target do not manufacture unfetched identity edges");
check(a.row.memory_resource() == r && a.row.get("leaf_ref")->memory_resource() == r,
"nested model data uses owning arena");
check(!missing.row.contains_key("product"),
"unfetched forward detail stays in its graph edge rather than the scalar row");
auto inverse = root.relation_option<Model<0>>("Child", 10, "parent");
check(inverse.state() == (compact ? LoadedRelation::NotLoaded : LoadedRelation::Loaded),
"ordinary and compact inverse rules remain separate");
if (!compact) {
check(inverse.value()->state->relation_list<Model<1>>("Parent", 1, "children").value() ==
children.value(),
"inverse model follows frozen graph back to same relation view");
}
}
static void sqlite_hydration(detail::RelationHydrationMode mode) {
GlobalContext g;
EntityRuntimeState* retained_graph = nullptr;
Vector<CompactRow>* retained_rows = nullptr;
{
auto c = g.make_user_context();
auto r = c->memory_resource();
c->disable_sql_log();
auto& store = metadata(*c);
auto& connection = c->make_resource<SqliteConnection>();
auto& provider = c->make<SqliteMutationExecutor>(connection);
auto& sql = c->make<CompiledQuery>();
for (auto text :
{"CREATE TABLE parents(id INTEGER PRIMARY KEY)",
"CREATE TABLE children(id INTEGER PRIMARY KEY,parent_id INTEGER,leaf_ref INTEGER)",
"CREATE TABLE leaves(id INTEGER PRIMARY KEY)",
"INSERT INTO parents VALUES(1),(2)",
"INSERT INTO children VALUES(10,1,20),(11,1,20),(12,1,99)",
"INSERT INTO leaves VALUES(20)"}) {
sql.sql = text;
check(bool(provider.execute(r, sql)), "create SQLite hydration fixture");
}
auto& dialect = c->make_resource<SqliteDialect>();
auto& state = c->make<SqlExecutorState>();
auto& executor =
c->make<SqlDataServiceExecutor<MutationExecutorError>>(dialect, provider, store, state);
using E = std::remove_reference_t<decltype(executor)>;
auto& repo = EntityDataService<E>::for_executor(*c, "Parent", *c, executor);
auto& children = plans(*c);
auto root_intent =
std::move(QueryIntent::create(
r, "load hydration fixture", "verify nested relation hydration"))
.value();
detail::EntityDataServiceAccess::bind_query_intent(repo, root_intent);
auto query = repo.select();
query.comment_text.emplace(root_intent.comment(), r);
query.purpose_text.emplace(root_intent.purpose(), r);
query.order_asc("id");
auto& fetched = ServiceAccess::context_service(repo).fetch_all(query);
check(bool(fetched.wait()), "fetch parent rows from SQLite");
auto& parents = c->make<Vector<CompactRow>>(fetched.wait().value());
auto& traces = c->make<Vector<TraceChain>>();
// This fixture supplies the entity-fetch boundary. Public EntityDataService
// fetch orchestration, pagination and aggregates have separate contracts.
detail::EntityRelationFetch<E> fetch(
std::allocator_arg,
Allocator(r),
[&](const EntityDataService<E>& child, SelectQuery q) -> auto& {
auto prepared = ServiceAccess::prepare_select(child, q);
check(bool(prepared), "prepare relation query through entity hooks");
traces.emplace_back(prepared.value().trace_chain);
return ServiceAccess::context_service(child).fetch_all(prepared.value());
});
auto& root = c->make<EntityRuntimeState>();
auto& graph = c->make<EntityGraphBuilder>();
auto& work =
mode == detail::RelationHydrationMode::Embedded
? detail::enhance_relation_plans(repo, parents, children, fetch)
: mode == detail::RelationHydrationMode::Flat
? detail::hydrate_flat_plans(repo, parents, children, root, graph, fetch)
: detail::hydrate_compact_flat_plans(repo, parents, children, root, graph, fetch);
auto& result = work.wait();
check(bool(result), "recursive hydration from actual SQLite rows");
check(traces.size() == 2 && traces.back().size() == 2 &&
traces.back()[0].comment == "Parent.children" &&
traces.back()[1].comment == "Child.product",
"nested fetch carries relation lineage");
if (mode == detail::RelationHydrationMode::Embedded) {
auto* values = std::get_if<Value::List>(&parents[0].get("children")->data);
check(values && values->size() == 3, "embedded children attached");
auto& first = std::get<Value::Object>((*values)[0].data);
auto& inverse = std::get<Value::Object>(first.find("parent")->second.data);
auto& leaf = std::get<Value::Object>(first.find("product")->second.data);
check(!inverse.contains("children") && inverse.at(String("id", r)).try_u64() == 1 &&
leaf.at(String("id", r)).try_u64() == 20,
"embedded inverse removes current relation before recursive enhancement");
check(std::get<Value::List>(parents[1].get("children")->data).empty(),
"embedded empty relation retained");
retained_rows = &g.make<Vector<CompactRow>>(parents);
} else {
check(bool(Access::decode_entity_graph_compact_batch(
*c, "Parent", detail::clone_in(r, parents), root, graph)),
"root model decode remains separate from hydration");
check(bool(root.freeze_graph(std::move(graph))), "freeze hydrated graph");
check_graph(root, r, mode == detail::RelationHydrationMode::CompactFlat);
retained_graph = &g.make<EntityRuntimeState>(root);
}
}
if (retained_graph) {
check_graph(*retained_graph,
g.memory_resource(),
mode == detail::RelationHydrationMode::CompactFlat);
}
if (retained_rows) {
auto& first = std::get<Value::List>(retained_rows->front().get("children")->data).front();
check(first.memory_resource() == g.memory_resource() &&
std::get<Value::Object>(first.data).find("product")->second.memory_resource() ==
g.memory_resource(),
"explicit embedded result copy outlives native database and User arena");
}
}
using Rows = detail::RelationRowsResult<UnusedExecutor>;
struct ReadyRows {
using allocator_type = Allocator;
Memory r;
Vector<CompactRow> rows;
ReadyRows(std::allocator_arg_t, Allocator a, Vector<CompactRow> rows)
: r(a.resource()), rows(std::move(rows), r) {}
std::optional<Rows> poll(WakeSignal&) {
return Rows::ok(r, std::move(rows));
}
void finish_and_wait() noexcept {}
void cancel_and_wait() noexcept {}
};
struct NativeCounts {
bool read = false;
unsigned stopped = 0, scopes = 0, successes = 0, failures = 0, drops = 0;
bool dropped_before_stop = false;
};
struct NativeScope : RuntimeTelemetryScope {
NativeCounts& counts;
explicit NativeScope(NativeCounts& counts) : counts(counts) {
++counts.scopes;
}
~NativeScope() {
++counts.drops;
if (!counts.stopped) {
counts.dropped_before_stop = true;
}
}
void with_context(FunctionRef<void()> cb) const override {
cb();
}
void success(const RuntimeAttributes&) override {
++counts.successes;
}
void failure(std::string_view) override {
++counts.failures;
}
};
struct NativeTelemetry : RuntimeTelemetry {
using allocator_type = Allocator;
Memory r;
NativeCounts& counts;
NativeTelemetry(std::allocator_arg_t, Allocator a, NativeCounts& counts)
: r(a.resource()), counts(counts) {}
Memory memory_resource() const noexcept override {
return r;
}
ContextBox<RuntimeTelemetryScope>& start(Memory r, const RuntimeOperation&) const override {
return detail::resource_arena(r).make<ContextBox<RuntimeTelemetryScope>>(
std::in_place_type<NativeScope>, counts);
}
};
struct NativeWork {
using allocator_type = Allocator;
Memory r;
const EntityDataService<UnusedExecutor>& service;
SelectQuery query;
NativeCounts& counts;
String payload;
std::thread worker;
std::binary_semaphore go{0};
std::atomic<bool> done = false;
bool released = false;
NativeWork(std::allocator_arg_t,
Allocator a,
const EntityDataService<UnusedExecutor>& service,
SelectQuery q,
NativeCounts& counts)
: r(a.resource()), service(service), query(std::allocator_arg, a, std::move(q)),
counts(counts), payload(32768, 'h', r) {}
~NativeWork() {
if (worker.joinable()) {
std::terminate();
}
}
std::optional<Rows> poll(WakeSignal& wake) {
if (!worker.joinable() && !done.load()) {
worker = std::thread([this, &wake] {
go.acquire();
auto trace = ServiceAccess::trace(service);
counts.read = service.entity() == "Leaf" && query.entity == "Leaf" &&
trace.size() == 2 && trace.back().comment == "Child.product" &&
payload.back() == 'h';
done.store(true);
wake.notify();
});
return {};
}
if (!done.load()) {
return {};
}
Vector<CompactRow> rows(r);
rows.emplace_back(row(r, {{"id", 20}}));
return Rows::ok(r, std::move(rows));
}
void release() {
if (!released) {
released = true;
go.release();
}
}
void stop() noexcept {
release();
if (worker.joinable()) {
worker.join();
}
++counts.stopped;
}
void finish_and_wait() noexcept {
stop();
}
void cancel_and_wait() noexcept {
stop();
}
};
static void native_lifetime(detail::RelationHydrationMode mode, unsigned action) {
NativeCounts counts;
GlobalContext g;
auto& telemetry = g.make_resource<NativeTelemetry>(counts);
auto c = g.make_user_context();
auto r = c->memory_resource();
metadata(*c);
c->set_runtime_telemetry(g, telemetry);
auto& executor = c->make<UnusedExecutor>();
auto& repo = EntityDataService<UnusedExecutor>::for_executor(*c, "Parent", *c, executor);
auto& plan = plans(*c);
auto& parents = c->make<Vector<CompactRow>>();
parents.emplace_back(row(r, {{"id", 1}}));
auto& root = c->make<EntityRuntimeState>();
auto& graph = c->make<EntityGraphBuilder>();
NativeWork* native = nullptr;
detail::EntityRelationFetch<UnusedExecutor> fetch(
std::allocator_arg,
Allocator(r),
[&](const auto& child, SelectQuery q) -> AsyncOperation<Rows>& {
if (q.entity == "Child") {
Vector<CompactRow> rows(r);
rows.emplace_back(row(r, {{"id", 10}, {"parent_id", 1}, {"leaf_ref", 20}}));
return make_operation<Rows, ReadyRows>(r, std::move(rows));
}
native = &c->make_resource<NativeWork>(child, std::move(q), counts);
return c->make<AsyncOperation<Rows>>(*native);
});
auto& work = mode == detail::RelationHydrationMode::Embedded
? detail::enhance_relation_plans(repo, parents, plan, fetch)
: mode == detail::RelationHydrationMode::Flat
? detail::hydrate_flat_plans(repo, parents, plan, root, graph, fetch)
: detail::hydrate_compact_flat_plans(repo, parents, plan, root, graph, fetch);
plan.front().children.clear();
plan.front().relation_name = "changed";
check(!work.poll() && native, "hydration owns original plan tree and suspends in a descendant");
if (action == 0) {
native->release();
check(bool(work.wait()), "native completion wakes recursive operation tree");
} else if (action == 1) {
work.cancel();
if (mode == detail::RelationHydrationMode::Embedded) {
check(!parents.front().contains_key("children"),
"5.0.6 cancellation leaves parent untouched until the child batch completes");
}
}
c->close();
check(counts.read && counts.stopped == 1 && c->allocation_stats().live_blocks == 0,
"all descendant host accesses join before arena reclamation");
check(!counts.dropped_before_stop && counts.drops == counts.scopes && counts.failures == 0,
"native child stops before relation telemetry destruction");
check(counts.scopes == (mode == detail::RelationHydrationMode::Embedded ? 2 : 0) &&
counts.successes ==
(mode == detail::RelationHydrationMode::Embedded && action == 0 ? 2 : 0),
"only completed embedded relation scopes report success");
}
static void domain_contracts() {
GlobalContext g;
auto c = g.make_user_context();
auto sibling = g.make_user_context();
auto r = c->memory_resource();
metadata(*c);
auto& executor = c->make<UnusedExecutor>();
auto& repo = EntityDataService<UnusedExecutor>::for_executor(*c, "Parent", *c, executor);
auto& plan = plans(*c);
auto& rows = c->make<Vector<CompactRow>>();
rows.emplace_back(row(r, {{"id", 1}}));
auto& foreign = sibling->make<Vector<CompactRow>>();
foreign.emplace_back(row(sibling->memory_resource(), {{"id", 1}}));
auto& root = c->make<EntityRuntimeState>();
auto& graph = c->make<EntityGraphBuilder>();
auto& foreign_root = sibling->make<EntityRuntimeState>();
auto& foreign_graph = sibling->make<EntityGraphBuilder>();
unsigned calls = 0;
detail::EntityRelationFetch<UnusedExecutor> fetch(
std::allocator_arg, Allocator(r), [&](const auto&, SelectQuery) -> AsyncOperation<Rows>& {
++calls;
return make_operation<Rows, ReadyRows>(r, Vector<CompactRow>(r));
});
rejected(
[&] {
detail::enhance_relation_plans(repo, foreign, plan, fetch);
},
"embedded parent rows require explicit copy into query domain");
rejected(
[&] {
detail::hydrate_flat_plans(repo, rows, plan, foreign_root, graph, fetch);
},
"flat graph refuses foreign root");
rejected(
[&] {
detail::hydrate_compact_flat_plans(repo, rows, plan, root, foreign_graph, fetch);
},
"compact graph refuses foreign builder");
rejected(
[&] {
detail::hydrate_compact_flat_plans(repo, foreign, plan, root, graph, fetch);
},
"readonly compact parent borrow cannot hide foreign lifetime");
check(calls == 0 && graph.entity_count() == 0,
"domain validation precedes all fetches and graph mutation");
auto& unrelated =
make_operation<Rows, ReadyRows>(*sibling, Vector<CompactRow>(sibling->memory_resource()));
detail::EntityRelationFetch<UnusedExecutor> bad(
std::allocator_arg, Allocator(r), [&](const auto&, SelectQuery) -> auto& {
return unrelated;
});
auto& invalid = detail::hydrate_flat_plans(repo, rows, plan, root, graph, bad);
rejected(
[&] {
invalid.poll();
},
"recursive fetch refuses a child operation from another Context");
check(unrelated.status() == AsyncStatus::Cancelled,
"recursive fetch cancels its rejected callback result");
unrelated.cancel();
}
static void sqlite_owner_facets(detail::RelationHydrationMode mode) {
GlobalContext global;
Vector<CompactRow>* retained = nullptr;
EntityRuntimeState* retained_graph = nullptr;
{
auto user_context = global.make_user_context();
auto r = user_context->memory_resource();
user_context->disable_sql_log();
auto& connection = user_context->make_resource<SqliteConnection>();
auto& provider = user_context->make<SqliteMutationExecutor>(connection);
CompiledQuery sql(std::allocator_arg, Allocator(r));
for (auto text : {"CREATE TABLE children(id INTEGER PRIMARY KEY, owner INTEGER)",
"CREATE TABLE tags(id INTEGER PRIMARY KEY, owner INTEGER)",
"INSERT INTO children VALUES(10,1),(11,1),(20,2)",
"INSERT INTO tags VALUES(100,10),(101,11),(200,20)"}) {
sql.sql = text;
check(bool(provider.execute(r, sql)), "create owner facet SQLite fixture");
}
auto& metadata = user_context->make<InMemoryMetadataStore>();
EntityDescriptor parent(std::allocator_arg, Allocator(r), "Parent");
parent.property("id", DataType::U64).is_id = true;
parent.property("link", DataType::U64);
auto& relation = parent.relation("children", "Child");
relation.local_key = "link";
relation.foreign_key = "owner";
relation.many = true;
EntityDescriptor child(std::allocator_arg, Allocator(r), "Child");
child.table("children");
child.property("id", DataType::U64).is_id = true;
child.property("owner", DataType::U64);
auto& tags = child.relation("tags", "Tag");
tags.local_key = "id";
tags.foreign_key = "owner";
tags.many = true;
EntityDescriptor tag(std::allocator_arg, Allocator(r), "Tag");
tag.table("tags");
tag.property("id", DataType::U64).is_id = true;
tag.property("owner", DataType::U64);
metadata.register_entity(std::move(parent));
metadata.register_entity(std::move(child));
metadata.register_entity(std::move(tag));
user_context->set_metadata(*user_context, metadata);
auto& decoders = user_context->make<InMemoryEntityGraphDecoderRegistry>();
decoders.register_entity<Model<1>>();
user_context->set_entity_graph_decoder_registry(decoders);
auto& dialect = user_context->make_resource<SqliteDialect>();
auto& state = user_context->make<SqlExecutorState>();
auto& executor = user_context->make<SqlDataServiceExecutor<MutationExecutorError>>(
dialect, provider, metadata, state);
using E = std::remove_reference_t<decltype(executor)>;
auto& service =
EntityDataService<E>::for_executor(*user_context, "Parent", *user_context, executor);
SelectQuery target(std::allocator_arg, Allocator(r), "Child");
target.comment("Read a limited child page")
.purpose("Verify owner facet membership")
.order_desc("id")
.limit(1);
SelectQuery facet(std::allocator_arg, Allocator(r), "Tag");
facet.comment("Read owner tag values");
target.facets.emplace_back("tagsFacet", "tags", facet, false);
RelationLoad load(std::allocator_arg, Allocator(r), "children", target);
auto plans = detail::build_relation_plans_from_loads(
*user_context, "Parent", std::span<const RelationLoad>(&load, 1));
check(bool(plans), "owner facet relation plan");
Vector<CompactRow> parents(r);
parents.emplace_back(row(r, {{"id", 1}, {"link", 1}}));
parents.emplace_back(row(r, {{"id", 2}, {"link", 2}}));
parents.emplace_back(row(r, {{"id", 3}}));
detail::EntityRelationFetch<E> fetch(
std::allocator_arg,
Allocator(r),
[&](const auto& child_service, SelectQuery query) -> auto& {
return detail::EntityDataServiceAccess::fetch_all(child_service, query);
});
auto& root = user_context->make<EntityRuntimeState>();
auto& graph = user_context->make<EntityGraphBuilder>();
auto& operation =
mode == detail::RelationHydrationMode::Embedded
? detail::enhance_relation_plans(service, parents, plans.value(), fetch)
: mode == detail::RelationHydrationMode::Flat
? detail::hydrate_flat_plans(service, parents, plans.value(), root, graph, fetch)
: detail::hydrate_compact_flat_plans(
service, parents, plans.value(), root, graph, fetch);
auto& result = operation.wait();
if (!result) {
throw std::runtime_error(std::string(result.error().to_string(r)));
}
if (mode != detail::RelationHydrationMode::Embedded) {
check(bool(root.freeze_graph(std::move(graph))), "freeze SQLite owner facet graph");
}
for (std::size_t index = 0; index < parents.size(); ++index) {
auto* loaded = parents[index].loaded_relation("children");
auto* graph_list =
mode == detail::RelationHydrationMode::Embedded
? nullptr
: root.resolve_relation_list<Model<1>>("Parent", index + 1, "children");
auto* facet_values =
mode == detail::RelationHydrationMode::Embedded
? (loaded && loaded->facets.contains("tagsFacet")
? &loaded->facets.find("tagsFacet")->second
: nullptr)
: root.relation_facet("Parent", index + 1, "children", "tagsFacet");
check(facet_values, "facets exist for every owner including missing keys");
if (graph_list) {
check(graph_list->is_loaded && graph_list->facets.contains("tagsFacet") &&
graph_list->facets.at(String("tagsFacet", r)).data == facet_values->data,
"typed relation list preserves query-only facet metadata");
}
const auto& values = facet_values->data;
check(values.size() == (index == 0 ? 2
: index == 1 ? 1
: 0),
"facet membership uses complete owner relation rather than materialized page");
check((graph_list ? graph_list->data.size() : loaded->data.size()) ==
(index == 2 ? 0 : 1),
"child page limit remains independent of facet membership");
for (const auto& value : values) {
auto id = *value.get("id")->try_u64();
check(index == 0 ? id == 100 || id == 101 : id == 200,
"owner facet values never cross owners");
}
}
if (mode == detail::RelationHydrationMode::Embedded) {
retained = &global.make<Vector<CompactRow>>(parents);
Vector<CompactRow> reconstructed_rows(parents, r);
auto reconstructed =
detail::attach_flat_relation_graph(*user_context, "Parent", reconstructed_rows);
check(bool(reconstructed),
"reconstruct SQLite embedded owner facets into the typed graph");
for (std::uint64_t id : {1, 2, 3}) {
auto* values =
reconstructed.value().relation_facet("Parent", id, "children", "tagsFacet");
auto* list =
reconstructed.value().resolve_relation_list<Model<1>>("Parent", id, "children");
check(values && list && list->facets.contains("tagsFacet") &&
values->data.size() == (id == 1 ? 2
: id == 2 ? 1
: 0),
"loaded-row reconstruction preserves complete SQLite owner facets");
}
retained_graph = &global.make<EntityRuntimeState>(reconstructed.value());
} else {
retained_graph = &global.make<EntityRuntimeState>(root);
}
}
if (retained_graph) {
auto* facet = retained_graph->relation_facet("Parent", 1, "children", "tagsFacet");
check(
facet && facet->memory_resource() == global.memory_resource() &&
facet->data.size() == 2,
"Global graph copy retains owner facets after actual database and UserContext destruction");
check(retained_graph->resolve_relation_list<Model<1>>("Parent", 1, "children")
->facets.size() == 1,
"Global graph copy also retains typed SmartList facets");
}
if (retained) {
check(
retained->front()
.loaded_relation("children")
->facets.begin()
->second.memory_resource() == global.memory_resource(),
"explicit Global copies retain nested owner facets after database and UserContext destruction");
}
}
int main() {
try {
setenv("TEAQL_LOG_ENDPOINT", "off", 1);
auto* old = std::pmr::set_default_resource(std::pmr::null_memory_resource());
for (auto mode : {detail::RelationHydrationMode::Embedded,
detail::RelationHydrationMode::Flat,
detail::RelationHydrationMode::CompactFlat}) {
sqlite_hydration(mode);
sqlite_owner_facets(mode);
for (unsigned action = 0; action < 3; ++action) {
native_lifetime(mode, action);
}
}
domain_contracts();
std::pmr::set_default_resource(old);
std::cout << "Recursive relation, SQLite and lifetime contracts passed\n";
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
return 1;
}
}