drasi-source-sqlite 0.1.0

SQLite source plugin for Drasi
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
// Copyright 2025 The Drasi Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![allow(clippy::unwrap_used)]

use std::collections::HashSet;
use std::sync::Arc;
use std::time::Duration;

use drasi_bootstrap_sqlite::{SqliteBootstrapProvider, TableKeyConfig as BootstrapTableKeyConfig};
use drasi_core::models::{Element, ElementValue, SourceChange};
use drasi_lib::channels::ResultDiff;
use drasi_lib::config::SourceSubscriptionSettings;
use drasi_lib::Source;
use drasi_lib::{DrasiLib, Query};
use drasi_reaction_application::subscription::{Subscription, SubscriptionOptions};
use drasi_reaction_application::ApplicationReactionBuilder;
use drasi_source_sqlite::{RestApiConfig, SqliteSource, TableKeyConfig};
use reqwest::Client;
use serde_json::json;
use tempfile::TempDir;
use tokio::time::sleep;

async fn find_available_port() -> u16 {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); // DevSkim: ignore DS137138
    let port = listener.local_addr().unwrap().port();
    drop(listener);
    sleep(Duration::from_millis(50)).await;
    port
}

fn id_matches(value: &serde_json::Value, expected: i64) -> bool {
    value
        .as_i64()
        .map(|id| id == expected)
        .or_else(|| value.as_str().map(|id| id == expected.to_string()))
        .unwrap_or(false)
}

fn count_from_rows(rows: &[serde_json::Map<String, serde_json::Value>]) -> i64 {
    rows.first()
        .and_then(|row| row.get("count"))
        .and_then(|value| {
            value
                .as_i64()
                .or_else(|| value.as_str().and_then(|count| count.parse::<i64>().ok()))
        })
        .unwrap_or_default()
}

async fn wait_for_diff<F>(subscription: &mut Subscription, description: &str, predicate: F)
where
    F: Fn(&ResultDiff) -> bool,
{
    for _ in 0..20 {
        if let Some(result) = subscription.recv().await {
            if result.results.iter().any(&predicate) {
                return;
            }
        }
    }

    panic!("timed out waiting for {description}");
}

async fn wait_for_query_results<F>(
    core: &Arc<DrasiLib>,
    query_id: &str,
    description: &str,
    predicate: F,
) where
    F: Fn(&[serde_json::Value]) -> bool,
{
    for _ in 0..20 {
        let rows = core.get_query_results(query_id).await.unwrap();
        if predicate(&rows) {
            return;
        }
        sleep(Duration::from_millis(200)).await;
    }

    panic!("timed out waiting for {description}");
}

#[tokio::test]
#[ignore]
async fn sqlite_handle_create_update_delete_flow() {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("handle.db");

    let source = SqliteSource::builder("sqlite-handle-source")
        .with_path(db_path.to_string_lossy().to_string())
        .with_table_keys(vec![TableKeyConfig {
            table: "sensors".to_string(),
            key_columns: vec!["id".to_string()],
        }])
        .build()
        .unwrap();
    let handle = source.handle();

    let query = Query::cypher("sqlite-handle-query")
        .query("MATCH (s:sensors) RETURN s.id AS id, s.name AS name, s.temp AS temp")
        .from_source("sqlite-handle-source")
        .auto_start(true)
        .build();

    let (reaction, reaction_handle) = ApplicationReactionBuilder::new("sqlite-handle-reaction")
        .with_query("sqlite-handle-query")
        .build();

    let core = Arc::new(
        DrasiLib::builder()
            .with_id("sqlite-handle-core")
            .with_source(source)
            .with_query(query)
            .with_reaction(reaction)
            .build()
            .await
            .unwrap(),
    );

    core.start().await.unwrap();
    sleep(Duration::from_millis(200)).await;

    let mut subscription = reaction_handle
        .subscribe_with_options(SubscriptionOptions::default().with_timeout(Duration::from_secs(1)))
        .await
        .unwrap();

    handle
        .execute("CREATE TABLE sensors(id INTEGER PRIMARY KEY, name TEXT, temp REAL)")
        .await
        .unwrap();

    handle
        .execute("INSERT INTO sensors(id, name, temp) VALUES (1, 'sensor-a', 31.5)")
        .await
        .unwrap();
    wait_for_diff(&mut subscription, "insert add diff", |diff| match diff {
        ResultDiff::Add { data, .. } => data.get("name") == Some(&json!("sensor-a")),
        _ => false,
    })
    .await;

    handle
        .execute("UPDATE sensors SET name = 'sensor-a-updated', temp = 33.1 WHERE id = 1")
        .await
        .unwrap();
    wait_for_diff(&mut subscription, "update diff", |diff| match diff {
        ResultDiff::Update { after, .. } => {
            after.get("name") == Some(&json!("sensor-a-updated"))
                && id_matches(after.get("id").unwrap_or(&serde_json::Value::Null), 1)
        }
        _ => false,
    })
    .await;

    handle
        .execute("DELETE FROM sensors WHERE id = 1")
        .await
        .unwrap();
    wait_for_diff(&mut subscription, "delete diff", |diff| match diff {
        ResultDiff::Delete { data, .. } => {
            data.get("name") == Some(&json!("sensor-a-updated"))
                && id_matches(data.get("id").unwrap_or(&serde_json::Value::Null), 1)
        }
        _ => false,
    })
    .await;

    core.stop().await.unwrap();
}

#[tokio::test]
#[ignore]
async fn sqlite_rest_crud_and_batch_flow() {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("rest.db");
    let rest_port = find_available_port().await;

    let source = SqliteSource::builder("sqlite-rest-source")
        .with_path(db_path.to_string_lossy().to_string())
        .with_table_keys(vec![TableKeyConfig {
            table: "sensors".to_string(),
            key_columns: vec!["id".to_string()],
        }])
        .with_rest_api(RestApiConfig {
            host: "127.0.0.1".to_string(), // DevSkim: ignore DS137138
            port: rest_port,
        })
        .build()
        .unwrap();
    let handle = source.handle();

    let query = Query::cypher("sqlite-rest-query")
        .query("MATCH (s:sensors) RETURN s.id AS id, s.name AS name, s.temp AS temp")
        .from_source("sqlite-rest-source")
        .auto_start(true)
        .build();

    let (reaction, reaction_handle) = ApplicationReactionBuilder::new("sqlite-rest-reaction")
        .with_query("sqlite-rest-query")
        .build();

    let core = Arc::new(
        DrasiLib::builder()
            .with_id("sqlite-rest-core")
            .with_source(source)
            .with_query(query)
            .with_reaction(reaction)
            .build()
            .await
            .unwrap(),
    );

    core.start().await.unwrap();
    sleep(Duration::from_millis(250)).await;

    handle
        .execute("CREATE TABLE sensors(id INTEGER PRIMARY KEY, name TEXT, temp REAL)")
        .await
        .unwrap();

    let mut subscription = reaction_handle
        .subscribe_with_options(SubscriptionOptions::default().with_timeout(Duration::from_secs(1)))
        .await
        .unwrap();
    let client = Client::new();
    let base = format!("http://127.0.0.1:{rest_port}"); // DevSkim: ignore DS137138

    let insert_response = client
        .post(format!("{base}/api/tables/sensors"))
        .json(&json!({"id": 10, "name": "rest-insert", "temp": 40.0}))
        .send()
        .await
        .unwrap();
    assert_eq!(insert_response.status(), 200);
    wait_for_diff(
        &mut subscription,
        "rest insert add diff",
        |diff| match diff {
            ResultDiff::Add { data, .. } => data.get("name") == Some(&json!("rest-insert")),
            _ => false,
        },
    )
    .await;

    let update_response = client
        .put(format!("{base}/api/tables/sensors/10"))
        .json(&json!({"name": "rest-updated", "temp": 41.5}))
        .send()
        .await
        .unwrap();
    assert_eq!(update_response.status(), 200);
    wait_for_diff(&mut subscription, "rest update diff", |diff| match diff {
        ResultDiff::Update { after, .. } => after.get("name") == Some(&json!("rest-updated")),
        _ => false,
    })
    .await;

    let delete_response = client
        .delete(format!("{base}/api/tables/sensors/10"))
        .send()
        .await
        .unwrap();
    assert_eq!(delete_response.status(), 200);
    wait_for_diff(&mut subscription, "rest delete diff", |diff| match diff {
        ResultDiff::Delete { data, .. } => data.get("name") == Some(&json!("rest-updated")),
        _ => false,
    })
    .await;

    let failed_batch = client
        .post(format!("{base}/api/batch"))
        .json(&json!({
            "operations": [
                {"op": "insert", "table": "sensors", "data": {"id": 20, "name": "rollback-me", "temp": 50.0}},
                {"op": "update", "table": "sensors", "id": "20", "data": {"missing_column": 1}}
            ]
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(failed_batch.status(), 500);

    let rolled_back_rows = handle
        .query("SELECT COUNT(*) AS count FROM sensors WHERE id = 20")
        .await
        .unwrap();
    assert_eq!(count_from_rows(&rolled_back_rows), 0);

    let successful_batch = client
        .post(format!("{base}/api/batch"))
        .json(&json!({
            "operations": [
                {"op": "insert", "table": "sensors", "data": {"id": 30, "name": "batch-a", "temp": 60.0}},
                {"op": "insert", "table": "sensors", "data": {"id": 31, "name": "batch-b", "temp": 61.0}}
            ]
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(successful_batch.status(), 200);

    wait_for_query_results(
        &core,
        "sqlite-rest-query",
        "batch rows in query results",
        |rows| {
            let has_30 = rows
                .iter()
                .any(|row| row.get("id").map(|id| id_matches(id, 30)).unwrap_or(false));
            let has_31 = rows
                .iter()
                .any(|row| row.get("id").map(|id| id_matches(id, 31)).unwrap_or(false));
            has_30 && has_31
        },
    )
    .await;

    core.stop().await.unwrap();
}

#[tokio::test]
#[ignore]
async fn sqlite_bootstrap_loads_existing_rows() {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("bootstrap.db");

    {
        let conn = rusqlite::Connection::open(&db_path).unwrap();
        conn.execute_batch(
            r#"
            CREATE TABLE sensors(id INTEGER PRIMARY KEY, name TEXT, temp REAL);
            INSERT INTO sensors(id, name, temp) VALUES (1, 'bootstrap-sensor', 29.0);
            "#,
        )
        .unwrap();
    }

    let bootstrap_provider = SqliteBootstrapProvider::builder()
        .with_path(db_path.to_string_lossy().to_string())
        .with_tables(vec!["sensors".to_string()])
        .with_table_keys(vec![BootstrapTableKeyConfig {
            table: "sensors".to_string(),
            key_columns: vec!["id".to_string()],
        }])
        .build();

    let source = SqliteSource::builder("sqlite-bootstrap-source")
        .with_path(db_path.to_string_lossy().to_string())
        .with_table_keys(vec![TableKeyConfig {
            table: "sensors".to_string(),
            key_columns: vec!["id".to_string()],
        }])
        .with_bootstrap_provider(bootstrap_provider)
        .build()
        .unwrap();

    let settings = SourceSubscriptionSettings {
        source_id: "sqlite-bootstrap-source".to_string(),
        enable_bootstrap: true,
        query_id: "sqlite-bootstrap-query".to_string(),
        nodes: HashSet::from(["sensors".to_string()]),
        relations: HashSet::new(),
        resume_from: None,
        request_position_handle: false,
        last_sequence: None,
    };

    let response = source.subscribe(settings).await.unwrap();
    let mut bootstrap_rx = response
        .bootstrap_receiver
        .expect("missing bootstrap receiver");
    let bootstrap_event = tokio::time::timeout(Duration::from_secs(2), bootstrap_rx.recv())
        .await
        .expect("timed out waiting for bootstrap event")
        .expect("bootstrap channel closed");

    assert_eq!(bootstrap_event.source_id, "sqlite-bootstrap-source");
    match bootstrap_event.change {
        SourceChange::Insert {
            element: Element::Node { properties, .. },
        } => match properties.get("name") {
            Some(ElementValue::String(value)) => assert_eq!(value.as_ref(), "bootstrap-sensor"),
            other => panic!("unexpected name value: {other:?}"),
        },
        other => panic!("unexpected bootstrap change: {other:?}"),
    }
}

#[tokio::test]
#[ignore]
async fn sqlite_multi_table_changes_flow_to_queries() {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("multi-table.db");

    let source = SqliteSource::builder("sqlite-multi-source")
        .with_path(db_path.to_string_lossy().to_string())
        .with_table_keys(vec![
            TableKeyConfig {
                table: "sensors".to_string(),
                key_columns: vec!["id".to_string()],
            },
            TableKeyConfig {
                table: "devices".to_string(),
                key_columns: vec!["id".to_string()],
            },
        ])
        .build()
        .unwrap();
    let handle = source.handle();

    let sensors_query = Query::cypher("sqlite-sensors-query")
        .query("MATCH (s:sensors) RETURN s.id AS id, s.name AS name")
        .from_source("sqlite-multi-source")
        .auto_start(true)
        .build();
    let devices_query = Query::cypher("sqlite-devices-query")
        .query("MATCH (d:devices) RETURN d.id AS id, d.name AS name")
        .from_source("sqlite-multi-source")
        .auto_start(true)
        .build();

    let (reaction, reaction_handle) = ApplicationReactionBuilder::new("sqlite-multi-reaction")
        .with_queries(vec![
            "sqlite-sensors-query".to_string(),
            "sqlite-devices-query".to_string(),
        ])
        .build();

    let core = Arc::new(
        DrasiLib::builder()
            .with_id("sqlite-multi-core")
            .with_source(source)
            .with_query(sensors_query)
            .with_query(devices_query)
            .with_reaction(reaction)
            .build()
            .await
            .unwrap(),
    );

    core.start().await.unwrap();
    sleep(Duration::from_millis(250)).await;

    let mut subscription = reaction_handle
        .subscribe_with_options(SubscriptionOptions::default().with_timeout(Duration::from_secs(1)))
        .await
        .unwrap();

    handle
        .execute_batch(
            r#"
            CREATE TABLE sensors(id INTEGER PRIMARY KEY, name TEXT);
            CREATE TABLE devices(id INTEGER PRIMARY KEY, name TEXT);
            "#,
        )
        .await
        .unwrap();
    handle
        .execute("INSERT INTO sensors(id, name) VALUES (1, 'sensor-one')")
        .await
        .unwrap();
    handle
        .execute("INSERT INTO devices(id, name) VALUES (9, 'device-nine')")
        .await
        .unwrap();

    let mut saw_sensor_query = false;
    let mut saw_device_query = false;
    for _ in 0..20 {
        if let Some(result) = subscription.recv().await {
            match result.query_id.as_str() {
                "sqlite-sensors-query" => {
                    saw_sensor_query = result.results.iter().any(|diff| match diff {
                        ResultDiff::Add { data, .. } => {
                            data.get("name") == Some(&json!("sensor-one"))
                        }
                        _ => false,
                    });
                }
                "sqlite-devices-query" => {
                    saw_device_query = result.results.iter().any(|diff| match diff {
                        ResultDiff::Add { data, .. } => {
                            data.get("name") == Some(&json!("device-nine"))
                        }
                        _ => false,
                    });
                }
                _ => {}
            }
        }

        if saw_sensor_query && saw_device_query {
            break;
        }
    }

    assert!(saw_sensor_query, "did not receive sensors query result");
    assert!(saw_device_query, "did not receive devices query result");

    core.stop().await.unwrap();
}