sqlx-turso-driver 0.0.1

An asynchronous SQLx driver for embedded Turso databases
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
use futures_util::TryStreamExt;
use sqlx::{ConnectOptions, Connection, Executor, pool::PoolOptions};
use sqlx_turso_driver::{Turso, TursoConnectOptions, TursoPool, connect_pool};
use std::time::{Duration, Instant};
use tokio::time::timeout;

type TestResult = Result<(), Box<dyn std::error::Error>>;
const BOUND: Duration = Duration::from_secs(2);

// Catches shared physical connections and file connections that cannot see committed writes.
#[tokio::test]
async fn file_pool_shares_committed_data() -> TestResult {
    let directory = tempfile::tempdir()?;
    let options = TursoConnectOptions::file(directory.path().join("pool 中文.db"))?;
    let pool: TursoPool = timeout(BOUND, connect_pool(options.clone(), 2)).await??;
    let mut first = timeout(BOUND, pool.acquire()).await??;
    first.execute("CREATE TABLE items(value INTEGER)").await?;
    first
        .execute("CREATE TEMP TABLE local_state(value INTEGER)")
        .await?;
    let mut second = timeout(BOUND, pool.acquire()).await??;
    assert!(
        second
            .execute("INSERT INTO local_state VALUES (1)")
            .await
            .is_err(),
        "distinct slots must not clone the same physical connection"
    );
    assert_eq!(pool.size(), 2);
    first.execute("INSERT INTO items VALUES (7)").await?; // autocommit, not D4
    assert_eq!(
        sqlx::query_scalar::<Turso, i64>("SELECT value FROM items")
            .fetch_one(&mut *second)
            .await?,
        7
    );
    let held = Instant::now();
    assert!(
        timeout(Duration::from_millis(30), pool.acquire())
            .await
            .is_err()
    );
    assert!(held.elapsed() < BOUND);
    assert_eq!(pool.size(), 2);
    drop(first);
    drop(second);
    timeout(BOUND, pool.close()).await?;
    assert!(matches!(pool.acquire().await, Err(sqlx::Error::PoolClosed)));
    let mut reopened = options.connect().await?;
    assert_eq!(
        sqlx::query_scalar::<Turso, i64>("SELECT value FROM items")
            .fetch_one(&mut reopened)
            .await?,
        7
    );
    reopened.close().await?;
    Ok(())
}

// Catches zero/oversized capacities and accidental independent-memory database sharing.
#[tokio::test]
async fn memory_pool_rejects_multiple_connections() -> TestResult {
    for capacity in [0, 2] {
        assert!(matches!(
            connect_pool(TursoConnectOptions::memory(), capacity).await,
            Err(sqlx::Error::Configuration(_))
        ));
    }
    let directory = tempfile::tempdir()?;
    assert!(matches!(
        connect_pool(
            TursoConnectOptions::file(directory.path().join("zero.db"))?,
            0
        )
        .await,
        Err(sqlx::Error::Configuration(_))
    ));
    let first = connect_pool(TursoConnectOptions::memory(), 1).await?;
    let second = connect_pool(TursoConnectOptions::memory(), 1).await?;
    first.execute("CREATE TABLE items(value INTEGER)").await?;
    first.execute("INSERT INTO items VALUES (7)").await?;
    assert_eq!(
        sqlx::query_scalar::<Turso, i64>("SELECT value FROM items")
            .fetch_one(&first)
            .await?,
        7
    );
    assert!(
        sqlx::query_scalar::<Turso, i64>("SELECT value FROM items")
            .fetch_one(&second)
            .await
            .is_err()
    );
    timeout(BOUND, first.close()).await?;
    timeout(BOUND, second.close()).await?;
    Ok(())
}

// Catches on-release ping discarding memory state or a cancelled reader retaining a slot/lock.
#[tokio::test]
async fn dropped_stream_releases_pool_slot() -> TestResult {
    for memory in [true, false] {
        let directory = tempfile::tempdir()?;
        let options = if memory {
            TursoConnectOptions::memory()
        } else {
            TursoConnectOptions::file(directory.path().join("stream.db"))?
        };
        let pool = connect_pool(options, 1).await?;
        pool.execute("CREATE TABLE items(value INTEGER)").await?;
        pool.execute("INSERT INTO items VALUES (7), (8), (9)")
            .await?;
        let mut stream =
            sqlx::query_scalar::<Turso, i64>("SELECT value FROM items ORDER BY value").fetch(&pool);
        assert_eq!(timeout(BOUND, stream.try_next()).await??, Some(7));
        assert!(
            timeout(Duration::from_millis(30), pool.acquire())
                .await
                .is_err()
        );
        drop(stream);
        let mut connection = timeout(BOUND, pool.acquire()).await??;
        connection.ping().await?;
        assert_eq!(
            connection
                .execute("INSERT INTO items VALUES (10)")
                .await?
                .rows_affected(),
            1
        );
        assert_eq!(
            sqlx::query_scalar::<Turso, i64>("SELECT count(*) FROM items")
                .fetch_one(&mut *connection)
                .await?,
            4
        );
        drop(connection);
        timeout(BOUND, pool.close()).await?;
        assert!(matches!(pool.acquire().await, Err(sqlx::Error::PoolClosed)));
    }
    Ok(())
}

// Catches leaked permits and unwanted replacement of a healthy connection after acquire deadlines.
#[tokio::test]
async fn acquire_timeout_does_not_leak() -> TestResult {
    let directory = tempfile::tempdir()?;
    let pool = PoolOptions::<Turso>::new()
        .max_connections(1)
        .acquire_timeout(Duration::from_millis(40))
        .connect_with(TursoConnectOptions::file(
            directory.path().join("timeout.db"),
        )?)
        .await?;
    let mut held = pool.acquire().await?;
    held.execute("CREATE TABLE items(value INTEGER)").await?;
    held.execute("CREATE TEMP TABLE local_state(value INTEGER)")
        .await?;
    held.execute("INSERT INTO local_state VALUES (11)").await?;
    assert!(matches!(
        timeout(BOUND, pool.acquire()).await?,
        Err(sqlx::Error::PoolTimedOut)
    ));
    assert!(
        timeout(Duration::from_millis(10), pool.acquire())
            .await
            .is_err()
    );
    drop(held);
    let mut next = timeout(BOUND, pool.acquire()).await??;
    assert_eq!(
        sqlx::query_scalar::<Turso, i64>("SELECT value FROM local_state")
            .fetch_one(&mut *next)
            .await?,
        11
    );
    next.execute("INSERT INTO items VALUES (7)").await?;
    drop(next);
    assert_eq!(
        timeout(
            BOUND,
            sqlx::query_scalar::<Turso, i64>("SELECT value FROM items").fetch_one(&pool)
        )
        .await??,
        7
    );
    timeout(BOUND, pool.close()).await?;
    assert!(matches!(pool.acquire().await, Err(sqlx::Error::PoolClosed)));
    Ok(())
}

// Catches silent replacement with a new empty database after the sole memory connection is lost.
#[tokio::test]
async fn memory_connection_loss_is_explicit() -> TestResult {
    let pool = connect_pool(TursoConnectOptions::memory(), 1).await?;
    pool.execute("CREATE TABLE items(value INTEGER)").await?;
    let connection = pool.acquire().await?;
    connection.close().await?;
    let error = timeout(BOUND, pool.acquire()).await?.unwrap_err();
    assert!(matches!(error, sqlx::Error::Configuration(_)), "{error}");
    assert!(error.to_string().contains("memory"), "{error}");
    timeout(BOUND, pool.close()).await?;
    Ok(())
}

// Catches rejecting pool liveness checks or a ping that cannot clean an abandoned reader.
#[tokio::test]
async fn ping_cleans_abandoned_reader() -> TestResult {
    let mut connection = TursoConnectOptions::memory().connect().await?;
    connection.ping().await?;
    connection
        .execute("CREATE TABLE items(value INTEGER)")
        .await?;
    connection
        .execute("INSERT INTO items VALUES (7), (8)")
        .await?;
    let mut stream =
        sqlx::query_scalar::<Turso, i64>("SELECT value FROM items").fetch(&mut connection);
    assert_eq!(stream.try_next().await?, Some(7));
    drop(stream);
    connection.ping().await?;
    connection.execute("INSERT INTO items VALUES (9)").await?;
    connection.close().await?;
    Ok(())
}

// Actual engine regression: successful lifecycle flush resets a dropped reader
// without quarantining/replacing a healthy physical connection or losing pool state.
#[tokio::test]
async fn successful_flush_preserves_clean_pool_connection() -> TestResult {
    for memory in [false, true] {
        let directory = tempfile::tempdir()?;
        let options = if memory {
            TursoConnectOptions::memory()
        } else {
            TursoConnectOptions::file(directory.path().join("flush.db"))?
        };
        let pool = connect_pool(options, 1).await?;
        let mut connection = timeout(BOUND, pool.acquire()).await??;
        connection
            .execute("CREATE TABLE items(value INTEGER)")
            .await?;
        connection
            .execute("INSERT INTO items VALUES (7), (8)")
            .await?;
        connection
            .execute("CREATE TEMP TABLE local_state(value INTEGER)")
            .await?;
        connection
            .execute("INSERT INTO local_state VALUES (11)")
            .await?;
        let mut stream = sqlx::query_scalar::<Turso, i64>("SELECT value FROM items ORDER BY value")
            .fetch(&mut *connection);
        assert_eq!(timeout(BOUND, stream.try_next()).await??, Some(7));
        drop(stream);
        assert!(connection.should_flush());
        connection.flush().await?;
        assert!(!connection.should_flush());
        connection.ping().await?;
        drop(connection);
        let mut next = timeout(BOUND, pool.acquire()).await??;
        assert_eq!(
            sqlx::query_scalar::<Turso, i64>("SELECT value FROM local_state")
                .fetch_one(&mut *next)
                .await?,
            11
        );
        assert_eq!(
            sqlx::query_scalar::<Turso, i64>("SELECT sum(value) FROM items")
                .fetch_one(&mut *next)
                .await?,
            15
        );
        next.flush().await?;
        drop(next);
        timeout(BOUND, pool.close()).await?;
    }
    Ok(())
}

// Catches omission of the configured busy handler and silently replacing zero by a default.
#[tokio::test]
async fn busy_timeout_reaches_engine() -> TestResult {
    for (duration, milliseconds) in [(Duration::from_millis(37), 37), (Duration::ZERO, 0)] {
        let mut connection = TursoConnectOptions::memory()
            .busy_timeout(duration)
            .connect()
            .await?;
        assert_eq!(
            sqlx::query_scalar::<Turso, i64>("PRAGMA busy_timeout")
                .fetch_one(&mut connection)
                .await?,
            milliseconds
        );
        connection.close().await?;
    }
    Ok(())
}

// A raw pinned Turso writer supplies contention only; this does not implement D4 transactions.
// Catches unbounded busy retries and a failed write leaving the pooled connection unusable.
#[tokio::test]
async fn busy_writer_fails_finitely_then_pool_recovers() -> TestResult {
    let directory = tempfile::tempdir()?;
    let path = directory.path().join("busy.db");
    let pool = connect_pool(
        TursoConnectOptions::file(&path)?.busy_timeout(Duration::from_millis(40)),
        1,
    )
    .await?;
    pool.execute("CREATE TABLE items(value INTEGER)").await?;
    let database = turso::Builder::new_local(path.to_str().unwrap())
        .build()
        .await?;
    let writer = database.connect()?;
    writer.execute("BEGIN IMMEDIATE", ()).await?;
    writer.execute("INSERT INTO items VALUES (1)", ()).await?;
    let started = Instant::now();
    let error = timeout(BOUND, pool.execute("INSERT INTO items VALUES (2)"))
        .await?
        .unwrap_err();
    assert!(matches!(error, sqlx::Error::Database(_)), "{error}");
    assert!(started.elapsed() < BOUND);
    writer.execute("ROLLBACK", ()).await?;
    assert_eq!(
        timeout(BOUND, pool.execute("INSERT INTO items VALUES (3)"))
            .await??
            .rows_affected(),
        1
    );
    assert_eq!(
        sqlx::query_scalar::<Turso, i64>("SELECT sum(value) FROM items")
            .fetch_one(&pool)
            .await?,
        3
    );
    timeout(BOUND, pool.close()).await?;
    Ok(())
}

// Catches a cancelled in-flight engine future retaining its statement/locks on a live connection.
#[tokio::test]
async fn cancelled_busy_query_releases_clean_connection() -> TestResult {
    let directory = tempfile::tempdir()?;
    let path = directory.path().join("cancel.db");
    let pool = connect_pool(
        TursoConnectOptions::file(&path)?.busy_timeout(Duration::from_millis(200)),
        1,
    )
    .await?;
    let mut connection = pool.acquire().await?;
    connection
        .execute("CREATE TABLE items(value INTEGER)")
        .await?;
    connection
        .execute("CREATE TEMP TABLE local_state(value INTEGER)")
        .await?;
    connection
        .execute("INSERT INTO local_state VALUES (11)")
        .await?;
    let database = turso::Builder::new_local(path.to_str().unwrap())
        .build()
        .await?;
    let writer = database.connect()?;
    writer.execute("BEGIN IMMEDIATE", ()).await?;
    writer.execute("INSERT INTO items VALUES (1)", ()).await?;
    assert!(
        timeout(
            Duration::from_millis(10),
            connection.execute("INSERT INTO items VALUES (2)")
        )
        .await
        .is_err()
    );
    drop(connection);
    let mut next = timeout(BOUND, pool.acquire()).await??;
    assert_eq!(
        sqlx::query_scalar::<Turso, i64>("SELECT value FROM local_state")
            .fetch_one(&mut *next)
            .await?,
        11
    );
    writer.execute("ROLLBACK", ()).await?;
    assert_eq!(
        next.execute("INSERT INTO items VALUES (3)")
            .await?
            .rows_affected(),
        1
    );
    assert_eq!(
        sqlx::query_scalar::<Turso, i64>("SELECT sum(value) FROM items")
            .fetch_one(&mut *next)
            .await?,
        3
    );
    drop(next);
    timeout(BOUND, pool.close()).await?;
    Ok(())
}

// Catches returning a raw-SQL transaction as clean; D3 discards it rather than doing D4 rollback.
#[tokio::test]
async fn open_raw_transaction_is_not_returned_as_clean() -> TestResult {
    let directory = tempfile::tempdir()?;
    let pool = connect_pool(
        TursoConnectOptions::file(directory.path().join("unclean.db"))?,
        1,
    )
    .await?;
    let mut connection = pool.acquire().await?;
    connection
        .execute("CREATE TABLE items(value INTEGER)")
        .await?;
    // D4 now enables the SQLx path; the untracked raw-SQL guard below remains.
    connection.begin().await?.rollback().await?;
    connection.execute("BEGIN IMMEDIATE").await?;
    connection.execute("INSERT INTO items VALUES (1)").await?;
    assert!(connection.ping().await.is_err());
    drop(connection);
    let mut next = timeout(BOUND, pool.acquire()).await??;
    assert_eq!(
        sqlx::query_scalar::<Turso, i64>("SELECT count(*) FROM items")
            .fetch_one(&mut *next)
            .await?,
        0
    );
    next.execute("INSERT INTO items VALUES (7)").await?;
    drop(next);
    timeout(BOUND, pool.close()).await?;
    Ok(())
}

// Catches close waiting forever or continuing to grant slots while checked-out handles return.
#[tokio::test]
async fn shutdown_rejects_waiting_acquire() -> TestResult {
    let pool = connect_pool(TursoConnectOptions::memory(), 1).await?;
    let held = pool.acquire().await?;
    let mut close = Box::pin(pool.close());
    assert!(
        timeout(Duration::from_millis(20), &mut close)
            .await
            .is_err()
    );
    assert!(pool.is_closed());
    assert!(matches!(
        timeout(BOUND, pool.acquire()).await?,
        Err(sqlx::Error::PoolClosed)
    ));
    drop(held);
    timeout(BOUND, close).await?;
    assert_eq!(pool.size(), 0);
    Ok(())
}