fsqlite 0.4.10

Public API facade
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
#![cfg(feature = "async-api")]

//! G0 integration regression for the async facade over the async storage stack.
//!
//! This target stays separate from the crate's legacy unit-test module so the
//! facade can retain executable evidence while that module is migrated to the
//! async `Connection` API.

use asupersync::runtime::RuntimeBuilder;
use fsqlite::{AsyncConnection, FrankenError, SqliteValue};
use fsqlite_types::cx::Cx;

fn assert_send<T: Send + ?Sized>(_: &T) {}

fn assert_send_sync<T: Send + Sync>() {}

/// Construct (never poll) every public async entry point's future and require
/// it to be `Send`, so callers can drive the actor facade from multi-threaded
/// runtimes. A future that captures a `!Send` engine handle fails to compile.
fn assert_connection_futures_are_send(connection: &mut AsyncConnection, cx: &Cx) {
    assert_send(&AsyncConnection::open(cx, ":memory:"));
    assert_send(&connection.prepare(cx, "SELECT 1"));
    assert_send(&connection.query(cx, "SELECT 1"));
    assert_send(&connection.query_with_params(cx, "SELECT ?1", &[SqliteValue::Integer(1)]));
    assert_send(&connection.query_row(cx, "SELECT 1"));
    assert_send(&connection.execute(cx, "SELECT 1"));
    assert_send(&connection.execute_with_params(cx, "SELECT ?1", &[SqliteValue::Integer(1)]));
    assert_send(&connection.execute_batch(cx, "SELECT 1"));
    assert_send(&connection.begin_transaction(cx));
    assert_send(&connection.commit_transaction(cx));
    assert_send(&connection.rollback_transaction(cx));
    assert_send(&connection.close(cx));
}

#[test]
fn async_connection_and_its_public_futures_are_send() {
    assert_send_sync::<AsyncConnection>();

    let runtime = RuntimeBuilder::current_thread()
        .blocking_threads(1, 1)
        .build()
        .expect("test runtime should build");
    runtime.block_on(async {
        let cx = Cx::new();
        let mut connection = AsyncConnection::open(&cx, ":memory:")
            .await
            .expect("in-memory async connection should open");
        assert_connection_futures_are_send(&mut connection, &cx);
        assert_eq!(
            connection
                .query_row(&cx, "SELECT 41 + 1")
                .await
                .expect("unpolled futures must leave the connection usable")
                .get(0),
            Some(&SqliteValue::Integer(42))
        );
        connection
            .close(&cx)
            .await
            .expect("connection should close");
    });
}

#[test]
fn async_facade_drives_file_backed_storage_futures_to_completion() {
    let runtime = RuntimeBuilder::current_thread()
        // The engine owns a separate large-stack thread. One runtime blocking
        // slot is therefore sufficient for the sequential response waiters.
        .blocking_threads(1, 1)
        .build()
        .expect("test runtime should build");

    runtime.block_on(async {
        let directory = tempfile::tempdir().expect("temporary database directory");
        let database_path = directory.path().join("async-facade.db");
        let database_path = database_path.to_string_lossy().into_owned();
        let cx = Cx::new();

        let mut connection = AsyncConnection::open(&cx, database_path.clone())
            .await
            .expect("file-backed async connection should open");

        connection
            .execute_batch(
                &cx,
                "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL);",
            )
            .await
            .expect("schema batch should complete");
        connection
            .execute_with_params(
                &cx,
                "INSERT INTO items (id, name) VALUES (?1, ?2)",
                &[SqliteValue::Integer(1), SqliteValue::Text("one".into())],
            )
            .await
            .expect("parameterized insert should complete");

        let rows = connection
            .query_with_params(
                &cx,
                "SELECT name FROM items WHERE id = ?1",
                &[SqliteValue::Integer(1)],
            )
            .await
            .expect("parameterized query should complete");
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].get(0), Some(&SqliteValue::Text("one".into())));

        let row = connection
            .query_row_with_params(
                &cx,
                "SELECT name FROM items WHERE id = ?1",
                &[SqliteValue::Integer(1)],
            )
            .await
            .expect("parameterized row query should complete");
        assert_eq!(row.get(0), Some(&SqliteValue::Text("one".into())));

        connection
            .begin_transaction(&cx)
            .await
            .expect("transaction should begin");
        assert!(connection.in_transaction());
        connection
            .execute(&cx, "INSERT INTO items (id, name) VALUES (2, 'two')")
            .await
            .expect("transactional insert should complete");
        connection
            .rollback_transaction(&cx)
            .await
            .expect("transaction should roll back");
        assert!(!connection.in_transaction());
        assert!(
            connection
                .query(&cx, "SELECT id FROM items WHERE id = 2")
                .await
                .expect("post-rollback query should complete")
                .is_empty()
        );

        connection
            .begin_transaction(&cx)
            .await
            .expect("second transaction should begin");
        connection
            .execute(&cx, "INSERT INTO items (id, name) VALUES (3, 'three')")
            .await
            .expect("committed insert should complete");
        connection
            .commit_transaction(&cx)
            .await
            .expect("transaction should commit");
        assert!(!connection.in_transaction());

        let cancelled = Cx::new();
        cancelled.cancel();
        assert!(matches!(
            connection.query(&cancelled, "SELECT 1").await,
            Err(FrankenError::Interrupt)
        ));

        connection
            .close(&cx)
            .await
            .expect("explicit close should complete");

        let mut reopened = AsyncConnection::open(&cx, database_path)
            .await
            .expect("committed database should reopen");
        let row = reopened
            .query_row(&cx, "SELECT name FROM items WHERE id = 3")
            .await
            .expect("committed row should survive reopen");
        assert_eq!(row.get(0), Some(&SqliteValue::Text("three".into())));
        reopened
            .close(&cx)
            .await
            .expect("reopened connection should close");
    });
}

#[test]
fn sync_facade_owns_storage_futures_on_its_worker() {
    let directory = tempfile::tempdir().expect("temporary database directory");
    let database_path = directory.path().join("sync-facade.db");
    let database_path = database_path.to_string_lossy().into_owned();
    let mut connection =
        AsyncConnection::open_sync(database_path).expect("file-backed sync connection should open");

    connection
        .execute_batch_sync(
            "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
             INSERT INTO items(name) VALUES ('before');",
        )
        .expect("schema and seed batch should complete");
    connection
        .prepare_sync("SELECT id, name FROM items WHERE id = ?1")
        .expect("statement validation should complete on the worker");

    assert_eq!(
        connection
            .execute_with_params_sync(
                "INSERT INTO items(name) VALUES (?1)",
                &[SqliteValue::Text("after".into())],
            )
            .expect("parameterized insert should complete"),
        1
    );
    assert_eq!(
        connection
            .last_insert_rowid_sync()
            .expect("last inserted row id should cross the worker boundary"),
        2
    );

    let row = connection
        .query_row_with_params_sync(
            "SELECT id, name FROM items WHERE id = ?1",
            &[SqliteValue::Integer(2)],
        )
        .expect("parameterized row query should complete");
    assert_eq!(row.get(0), Some(&SqliteValue::Integer(2)));
    assert_eq!(row.get(1), Some(&SqliteValue::Text("after".into())));

    let mut streamed_ids = Vec::new();
    connection
        .query_with_params_for_each_sync(
            "SELECT id FROM items WHERE id >= ?1 ORDER BY id",
            &[SqliteValue::Integer(1)],
            |row| {
                streamed_ids.push(row.get(0).cloned());
                Ok(())
            },
        )
        .expect("bounded row stream should complete");
    assert_eq!(
        streamed_ids,
        vec![Some(SqliteValue::Integer(1)), Some(SqliteValue::Integer(2))]
    );

    assert!(matches!(
        connection.execute_many_with_params_in_transaction_sync(
            "INSERT INTO items(name) VALUES (?1)",
            &[vec![SqliteValue::Text("outside".into())]],
        ),
        Err(FrankenError::Internal(detail)) if detail.contains("explicit transaction")
    ));

    connection
        .begin_transaction_sync()
        .expect("batch transaction should begin");
    assert_eq!(
        connection
            .execute_many_with_params_in_transaction_sync(
                "INSERT INTO items(name) VALUES (?1)",
                &[
                    vec![SqliteValue::Text("batch-a".into())],
                    vec![SqliteValue::Text("batch-b".into())],
                ],
            )
            .expect("batched parameter sets should complete"),
        2
    );
    connection
        .commit_transaction_sync()
        .expect("batch transaction should commit");
    let batch_names = connection
        .query_sync("SELECT name FROM items WHERE id >= 3 ORDER BY id")
        .expect("committed batch should be queryable");
    assert_eq!(
        batch_names
            .iter()
            .map(|row| row.get(0).cloned())
            .collect::<Vec<_>>(),
        vec![
            Some(SqliteValue::Text("batch-a".into())),
            Some(SqliteValue::Text("batch-b".into())),
        ]
    );

    connection
        .begin_transaction_sync()
        .expect("failing batch transaction should begin");
    assert!(
        connection
            .execute_many_with_params_in_transaction_sync(
                "INSERT INTO items(id, name) VALUES (?1, ?2)",
                &[
                    vec![
                        SqliteValue::Integer(10),
                        SqliteValue::Text("pending".into()),
                    ],
                    vec![
                        SqliteValue::Integer(1),
                        SqliteValue::Text("duplicate".into()),
                    ],
                ],
            )
            .is_err()
    );
    assert!(connection.in_transaction());
    connection
        .rollback_transaction_sync()
        .expect("caller should roll back a failed batch");
    assert!(
        connection
            .query_sync("SELECT id FROM items WHERE id = 10")
            .expect("rolled-back batch should be queryable")
            .is_empty()
    );

    connection
        .begin_transaction_sync()
        .expect("transaction should begin");
    assert!(connection.in_transaction());
    connection
        .execute_sync("DELETE FROM items")
        .expect("transactional delete should complete");
    connection
        .rollback_transaction_sync()
        .expect("transaction should roll back");
    assert!(!connection.in_transaction());
    assert_eq!(
        connection
            .query_sync("SELECT id FROM items")
            .expect("post-rollback query should complete")
            .len(),
        4
    );

    connection
        .close_sync()
        .expect("explicit sync close should complete");
    assert!(connection.query_sync("SELECT 1").is_err());
}

#[test]
fn async_explicit_close_rolls_back_uncommitted_file_transaction() {
    let runtime = RuntimeBuilder::current_thread()
        .blocking_threads(2, 2)
        .build()
        .expect("test runtime should build");

    runtime.block_on(async {
        let directory = tempfile::tempdir().expect("temporary database directory");
        let database_path = directory.path().join("async-close-rollback.db");
        let database_path = database_path.to_string_lossy().into_owned();
        let cx = Cx::new();

        let mut connection = AsyncConnection::open(&cx, database_path.clone())
            .await
            .expect("file-backed async connection should open");
        connection
            .execute(
                &cx,
                "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)",
            )
            .await
            .expect("schema should be created");
        connection
            .begin_transaction(&cx)
            .await
            .expect("transaction should begin");
        connection
            .execute(&cx, "INSERT INTO items VALUES (1, 'uncommitted')")
            .await
            .expect("uncommitted insert should succeed");
        assert!(connection.in_transaction());

        connection
            .close(&cx)
            .await
            .expect("explicit close should roll back and finish cleanup");

        let mut reopened = AsyncConnection::open(&cx, database_path)
            .await
            .expect("database should reopen after explicit close");
        assert!(
            reopened
                .query(&cx, "SELECT id FROM items")
                .await
                .expect("reopened table should be queryable")
                .is_empty(),
            "an uncommitted row must not survive explicit async close"
        );
        reopened
            .close(&cx)
            .await
            .expect("reopened connection should close");
    });
}

#[test]
fn sync_drop_rolls_back_uncommitted_file_transaction() {
    let directory = tempfile::tempdir().expect("temporary database directory");
    let database_path = directory.path().join("sync-drop-rollback.db");
    let database_path = database_path.to_string_lossy().into_owned();

    {
        let connection = AsyncConnection::open_sync(database_path.clone())
            .expect("file-backed sync connection should open");
        connection
            .execute_sync("CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")
            .expect("schema should be created");
        connection
            .begin_transaction_sync()
            .expect("transaction should begin");
        connection
            .execute_sync("INSERT INTO items VALUES (1, 'uncommitted')")
            .expect("uncommitted insert should succeed");
        assert!(connection.in_transaction());
    }

    let mut reopened = AsyncConnection::open_sync(database_path)
        .expect("database should reopen after synchronous drop");
    assert!(
        reopened
            .query_sync("SELECT id FROM items")
            .expect("reopened table should be queryable")
            .is_empty(),
        "an uncommitted row must not survive synchronous facade drop"
    );
    reopened
        .close_sync()
        .expect("reopened sync connection should close");
}