ents-sqlite 0.5.1

Ents database implementation using sqlite3
Documentation
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
use ents::{
    DraftError, EdgeDraft, EdgeQuery, Ent, EntExt as _, EntMutationError, Id,
    IncomingEdgeProvider, IncomingEdgeValue, NullEdgeProvider, QueryEdge,
    ReadEnt, Transactional,
};
use ents_sqlite::Txn;
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use serde::{Deserialize, Serialize};

#[derive(Clone, Serialize, Deserialize)]
struct TestEntity {
    name: String,
    value: i32,
    id: Id,
    last_updated: u64,
}

#[typetag::serde]
impl Ent for TestEntity {
    type EdgeProvider = NullEdgeProvider;

    fn id(&self) -> Id {
        self.id
    }
    fn set_id(&mut self, id: Id) {
        self.id = id;
    }
    fn last_updated(&self) -> u64 {
        self.last_updated
    }
    fn mark_updated(&mut self) -> Result<(), EntMutationError> {
        self.last_updated = 12345; // Test value
        Ok(())
    }
}

impl TestEntity {
    pub fn build() -> TestEntityBuilder {
        TestEntityBuilder::default()
    }
}

#[derive(Default)]
struct TestEntityBuilder {
    name: String,
    value: i32,
    id: Id,
    last_updated: u64,
}

impl TestEntityBuilder {
    pub fn name(mut self, name: String) -> Self {
        self.name = name;
        self
    }
    pub fn value(mut self, value: i32) -> Self {
        self.value = value;
        self
    }
    pub fn finish(self) -> anyhow::Result<TestEntity> {
        Ok(TestEntity {
            name: self.name,
            value: self.value,
            id: self.id,
            last_updated: self.last_updated,
        })
    }
}

#[derive(Clone, Serialize, Deserialize)]
struct TestPerson {
    name: String,
    age: i32,
    lives_in_link: Id,
    id: Id,
    last_updated: u64,
}

#[typetag::serde]
impl Ent for TestPerson {
    type EdgeProvider = TestPersonEdgeProvider;

    fn id(&self) -> Id {
        self.id
    }
    fn set_id(&mut self, id: Id) {
        self.id = id;
    }
    fn last_updated(&self) -> u64 {
        self.last_updated
    }
    fn mark_updated(&mut self) -> Result<(), EntMutationError> {
        self.last_updated = 12345;
        Ok(())
    }
}

impl TestPerson {
    pub fn lives_in_link(&self) -> &Id {
        &self.lives_in_link
    }
}

impl TestPerson {
    pub fn build() -> TestPersonBuilder {
        TestPersonBuilder::default()
    }
}

#[derive(Default)]
struct TestPersonBuilder {
    name: String,
    age: i32,
    lives_in_link: Id,
    id: Id,
    last_updated: u64,
}

impl TestPersonBuilder {
    pub fn name(mut self, name: String) -> Self {
        self.name = name;
        self
    }
    pub fn age(mut self, age: i32) -> Self {
        self.age = age;
        self
    }
    pub fn lives_in_link(mut self, lives_in_link: Id) -> Self {
        self.lives_in_link = lives_in_link;
        self
    }
    pub fn last_updated(mut self, last_updated: u64) -> Self {
        self.last_updated = last_updated;
        self
    }
    pub fn finish(self) -> anyhow::Result<TestPerson> {
        Ok(TestPerson {
            name: self.name,
            age: self.age,
            lives_in_link: self.lives_in_link,
            id: self.id,
            last_updated: self.last_updated,
        })
    }
}

#[derive(PartialEq)]
struct TestPersonEdgeDraft {
    person_id: Id,
    city_id: Id,
}

impl EdgeDraft for TestPersonEdgeDraft {
    fn check<T: ReadEnt>(
        self,
        _txn: &T,
    ) -> Result<Vec<IncomingEdgeValue>, DraftError> {
        Ok(vec![IncomingEdgeValue::new(
            self.city_id,
            b"lives_in".to_vec(),
        )])
    }
}

struct TestPersonEdgeProvider;
impl IncomingEdgeProvider<TestPerson> for TestPersonEdgeProvider {
    type Draft = TestPersonEdgeDraft;
    fn draft(ent: &TestPerson) -> Self::Draft {
        TestPersonEdgeDraft {
            person_id: ent.id(),
            city_id: *ent.lives_in_link(),
        }
    }
}

impl TestPerson {
    pub fn set_lives_in_link(&mut self, lives_in_link: Id) {
        self.lives_in_link = lives_in_link;
    }
}

#[derive(Clone, Serialize, Deserialize)]
struct TestCity {
    name: String,
    population: i64,
    id: Id,
    last_updated: u64,
}

#[typetag::serde]
impl Ent for TestCity {
    type EdgeProvider = NullEdgeProvider;

    fn id(&self) -> Id {
        self.id
    }
    fn set_id(&mut self, id: Id) {
        self.id = id;
    }
    fn last_updated(&self) -> u64 {
        self.last_updated
    }
    fn mark_updated(&mut self) -> Result<(), EntMutationError> {
        self.last_updated = 12345;
        Ok(())
    }
}

impl TestCity {
    pub fn build() -> TestCityBuilder {
        TestCityBuilder::default()
    }
}

#[derive(Default)]
struct TestCityBuilder {
    name: String,
    population: i64,
    id: Id,
    last_updated: u64,
}

impl TestCityBuilder {
    pub fn name(mut self, name: String) -> Self {
        self.name = name;
        self
    }
    pub fn population(mut self, population: i64) -> Self {
        self.population = population;
        self
    }
    pub fn finish(self) -> anyhow::Result<TestCity> {
        Ok(TestCity {
            name: self.name,
            population: self.population,
            id: self.id,
            last_updated: self.last_updated,
        })
    }
}

fn setup_test_db() -> Pool<SqliteConnectionManager> {
    let pool = Pool::new(SqliteConnectionManager::memory()).unwrap();
    let conn = pool.get().unwrap();
    conn.execute_batch(
        r#"
CREATE TABLE IF NOT EXISTS entities (
   id INTEGER PRIMARY KEY,
   type TEXT NOT NULL,
   data TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS edges (
   source INTEGER NOT NULL,
   type TEXT NOT NULL,
   dest INTEGER NOT NULL,
   PRIMARY KEY (source, type, dest)
);
"#,
    )
    .unwrap();
    pool
}

#[test]
fn test_insert_and_get() {
    let pool = setup_test_db();
    let mut conn = pool.get().unwrap();
    let tx = conn.transaction().unwrap();
    let txn = Txn::new(tx);

    // Create an entity
    let ent = TestEntity::build()
        .name("test".to_string())
        .value(42)
        .finish()
        .unwrap();
    let id = txn.create(ent).unwrap();

    // Get the entity back
    let retrieved = txn.get(id).unwrap();
    assert!(retrieved.is_some());

    let retrieved_ent = retrieved.unwrap();
    assert_eq!(retrieved_ent.id(), id);
    assert!(retrieved_ent.is::<TestEntity>());
    assert_eq!(retrieved_ent.typetag_name(), "TestEntity");
}

#[test]
fn test_get_nonexistent() {
    let pool = setup_test_db();
    let mut conn = pool.get().unwrap();
    let tx = conn.transaction().unwrap();
    let txn = Txn::new(tx);

    // Try to get a non-existent entity
    let result = txn.get(999).unwrap();
    assert!(result.is_none());
}

#[test]
fn test_transaction_commit() {
    let pool = setup_test_db();

    let id = {
        let mut conn = pool.get().unwrap();
        let tx = conn.transaction().unwrap();
        let txn = Txn::new(tx);

        // Create an entity
        let ent = TestEntity::build()
            .name("committed".to_string())
            .value(999)
            .finish()
            .unwrap();
        let id = txn.create(ent).unwrap();

        // Commit the transaction
        txn.commit().unwrap();
        id
    };

    // Verify the entity persists after transaction commit
    let mut conn = pool.get().unwrap();
    let tx = conn.transaction().unwrap();
    let txn = Txn::new(tx);
    let retrieved = txn.get(id).unwrap();
    assert!(retrieved.is_some());
}

#[test]
fn test_transaction_rollback() {
    let pool = setup_test_db();

    let id = {
        let mut conn = pool.get().unwrap();
        let tx = conn.transaction().unwrap();
        let txn = Txn::new(tx);

        // Create an entity
        let ent = TestEntity::build()
            .name("rolled_back".to_string())
            .value(888)
            .finish()
            .unwrap();
        let id = txn.create(ent).unwrap();

        // Transaction is dropped without commit, so it rolls back
        id
    };

    // Verify the entity does NOT persist after rollback
    let mut conn = pool.get().unwrap();
    let tx = conn.transaction().unwrap();
    let txn = Txn::new(tx);
    let retrieved = txn.get(id).unwrap();
    assert!(retrieved.is_none());
}

#[test]
fn test_update_without_cas() {
    let pool = setup_test_db();
    let mut conn = pool.get().unwrap();
    let tx = conn.transaction().unwrap();
    let txn = Txn::new(tx);

    // Create an entity
    let mut ent = TestEntity::build()
        .name("original".to_string())
        .value(100)
        .finish()
        .unwrap();
    let id = txn.create(ent.clone()).unwrap();
    ent.set_id(id);

    // Update using update4
    let success = txn
        .update(&mut ent, |e: &mut TestEntity| {
            e.name = "updated".to_string();
            e.value = 200;
        })
        .unwrap();
    assert!(success);

    // Verify the update
    let retrieved = txn.get(id).unwrap().unwrap();
    let retrieved_json = serde_json::to_value(&retrieved).unwrap();
    assert_eq!(retrieved_json["name"], "updated");
    assert_eq!(retrieved_json["value"], 200);
}

#[derive(Clone, Serialize, Deserialize)]
struct TestEntityWithTimestamp {
    name: String,
    value: i32,
    id: Id,
    last_updated: u64,
}

#[typetag::serde]
impl Ent for TestEntityWithTimestamp {
    type EdgeProvider = NullEdgeProvider;

    fn id(&self) -> Id {
        self.id
    }
    fn set_id(&mut self, id: Id) {
        self.id = id;
    }
    fn last_updated(&self) -> u64 {
        self.last_updated
    }
    fn mark_updated(&mut self) -> Result<(), EntMutationError> {
        self.last_updated = 12345;
        Ok(())
    }
}

impl TestEntityWithTimestamp {
    pub fn build() -> TestEntityWithTimestampBuilder {
        TestEntityWithTimestampBuilder::default()
    }
}

#[derive(Default)]
struct TestEntityWithTimestampBuilder {
    name: String,
    value: i32,
    id: Id,
    last_updated: u64,
}

impl TestEntityWithTimestampBuilder {
    pub fn name(mut self, name: String) -> Self {
        self.name = name;
        self
    }
    pub fn value(mut self, value: i32) -> Self {
        self.value = value;
        self
    }
    pub fn last_updated(mut self, last_updated: u64) -> Self {
        self.last_updated = last_updated;
        self
    }
    pub fn finish(self) -> anyhow::Result<TestEntityWithTimestamp> {
        Ok(TestEntityWithTimestamp {
            name: self.name,
            value: self.value,
            id: self.id,
            last_updated: self.last_updated,
        })
    }
}

#[test]
fn test_update_with_timestamp() {
    let pool = setup_test_db();
    let mut conn = pool.get().unwrap();
    let tx = conn.transaction().unwrap();
    let txn = Txn::new(tx);

    // Create an entity with timestamp
    let timestamp1 = 1000u64;
    let mut ent = TestEntityWithTimestamp::build()
        .name("original".to_string())
        .value(100)
        .last_updated(timestamp1)
        .finish()
        .unwrap();
    let id = txn.create(ent.clone()).unwrap();
    ent.set_id(id);

    // Update using update4
    // Note: update4 calls mark_updated which sets last_updated to 12345
    let success = txn
        .update(&mut ent, |e: &mut TestEntityWithTimestamp| {
            e.name = "updated".to_string();
            e.value = 200;
        })
        .unwrap();
    assert!(success);

    // Verify the update
    let retrieved = txn.get(id).unwrap().unwrap();
    let retrieved_json = serde_json::to_value(&retrieved).unwrap();
    assert_eq!(retrieved_json["name"], "updated");
    assert_eq!(retrieved_json["value"], 200);
    // mark_updated sets the timestamp to 12345
    assert_eq!(retrieved_json["last_updated"], 12345);
}

#[test]
fn test_update4_edge_change() {
    let pool = setup_test_db();
    let mut conn = pool.get().unwrap();
    let tx = conn.transaction().unwrap();
    let txn = Txn::new(tx);

    // Create cities
    let city1 = TestCity::build()
        .name("City1".to_string())
        .population(100)
        .finish()
        .unwrap();
    let city1_id = txn.create(city1).unwrap();

    let city2 = TestCity::build()
        .name("City2".to_string())
        .population(200)
        .finish()
        .unwrap();
    let city2_id = txn.create(city2).unwrap();

    // Create person living in city1
    let mut person = TestPerson::build()
        .name("Alice".to_string())
        .age(30)
        .lives_in_link(city1_id)
        .last_updated(0)
        .finish()
        .unwrap();
    let person_id = txn.create(person.clone()).unwrap();
    person.set_id(person_id);

    // Verify incoming edge from city1 to person
    let result = txn.find_edges(city1_id, EdgeQuery::asc(&[])).unwrap();
    assert_eq!(result.edges.len(), 1);
    assert_eq!(result.edges[0].dest, person_id);

    // Update person to live in city2 using update4
    let success = txn
        .update(&mut person, |p: &mut TestPerson| {
            p.set_lives_in_link(city2_id);
        })
        .unwrap();
    assert!(success);

    // Verify edge moved from city1 to city2
    let result_city1 = txn.find_edges(city1_id, EdgeQuery::asc(&[])).unwrap();
    assert_eq!(result_city1.edges.len(), 0);

    let result_city2 = txn.find_edges(city2_id, EdgeQuery::asc(&[])).unwrap();
    assert_eq!(result_city2.edges.len(), 1);
    assert_eq!(result_city2.edges[0].dest, person_id);

    person.set_lives_in_link(city2_id);

    // Update person to live in city2 (no change) using update4
    // This should trigger the optimization path
    let success_no_change = txn
        .update(&mut person, |p: &mut TestPerson| {
            p.set_lives_in_link(city2_id);
        })
        .unwrap();
    assert!(success_no_change);

    // Verify edge is still from city2 to person
    let result = txn.find_edges(city2_id, EdgeQuery::asc(&[])).unwrap();
    assert_eq!(result.edges.len(), 1);
    assert_eq!(result.edges[0].dest, person_id);
}