switchy_database 0.2.0

Switchy database package
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
#![cfg(feature = "schema")]

//! # Savepoint Integration Tests
//!
//! This file contains savepoint tests for database backends that support nested transactions
//! using savepoints (SAVEPOINT/RELEASE/ROLLBACK TO syntax).
//!
//! ## Turso Backend Exclusion
//!
//! **Turso is currently excluded from these tests** because it does not yet support savepoints.
//! This is a known limitation tracked in the upstream issue:
//! <https://github.com/tursodatabase/turso/issues/1829>
//!
//! Once Turso adds savepoint support, a `turso_savepoint_tests` module should be added here
//! following the same pattern as the rusqlite and sqlite-sqlx implementations.

mod common;

use common::savepoint_tests::SavepointTestSuite;
use std::sync::Arc;

// ===== RUSQLITE BACKEND TESTS =====
#[cfg(feature = "sqlite-rusqlite")]
mod rusqlite_savepoint_tests {
    use super::*;
    use rusqlite::Connection;
    use switchy_async::sync::Mutex;
    use switchy_database::rusqlite::RusqliteDatabase;

    struct RusqliteSavepointTests;

    const CONNECTION_POOL_SIZE: u8 = 5;

    impl SavepointTestSuite for RusqliteSavepointTests {
        type DatabaseType = RusqliteDatabase;

        async fn get_database(&self) -> Option<Arc<Self::DatabaseType>> {
            // Always available - in-memory database
            let test_id = std::thread::current().id();
            let timestamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos();
            let db_url =
                format!("file:testdb_{test_id:?}_{timestamp}:?mode=memory&cache=shared&uri=true");

            let mut connections = Vec::new();

            for i in 0..CONNECTION_POOL_SIZE {
                let conn =
                    Connection::open(&db_url).expect("Failed to create shared memory database");

                // Configure SQLite for better concurrency on all connections
                conn.pragma_update(None, "journal_mode", "WAL")
                    .expect("Failed to set WAL mode");
                conn.pragma_update(None, "busy_timeout", 5000)
                    .expect("Failed to set busy timeout");
                conn.pragma_update(None, "synchronous", "NORMAL")
                    .expect("Failed to set synchronous mode");
                conn.pragma_update(None, "cache_size", -64000)
                    .expect("Failed to set cache size");
                conn.pragma_update(None, "temp_store", "MEMORY")
                    .expect("Failed to set temp store");

                // Only create table in first connection since shared memory shares schema
                if i == 0 {
                    conn.execute(
                    "CREATE TABLE test_table (id INTEGER PRIMARY KEY, name TEXT, value INTEGER)",
                    [],
                )
                .expect("Failed to create test table");
                }

                connections.push(Arc::new(Mutex::new(conn)));
            }
            let db = RusqliteDatabase::new(connections);
            Some(Arc::new(db))
        }
    }

    #[test_log::test(switchy_async::test)]
    async fn test_rusqlite_nested_savepoints_three_levels() {
        let suite = RusqliteSavepointTests;
        suite.test_nested_savepoints_three_levels().await;
    }

    #[test_log::test(switchy_async::test)]
    async fn test_rusqlite_rollback_to_middle_savepoint() {
        let suite = RusqliteSavepointTests;
        suite.test_rollback_to_middle_savepoint().await;
    }

    #[test_log::test(switchy_async::test)]
    async fn test_rusqlite_release_savepoints_out_of_order() {
        let suite = RusqliteSavepointTests;
        suite.test_release_savepoints_out_of_order().await;
    }

    #[test_log::test(switchy_async::test)]
    async fn test_rusqlite_savepoint_with_data_operations() {
        let suite = RusqliteSavepointTests;
        suite.test_savepoint_with_data_operations().await;
    }

    #[test_log::test(switchy_async::test)]
    async fn test_rusqlite_commit_with_unreleased_savepoints() {
        let suite = RusqliteSavepointTests;
        suite.test_commit_with_unreleased_savepoints().await;
    }

    #[test_log::test(switchy_async::test)]
    async fn test_rusqlite_savepoint_name_validation() {
        let suite = RusqliteSavepointTests;
        suite.test_savepoint_name_validation().await;
    }

    #[test_log::test(switchy_async::test)]
    async fn test_rusqlite_sequential_savepoints_different_transactions() {
        let suite = RusqliteSavepointTests;
        suite
            .test_sequential_savepoints_different_transactions()
            .await;
    }

    #[test_log::test(switchy_async::test(real_time))]
    async fn test_rusqlite_concurrent_savepoints_with_isolation() {
        let suite = RusqliteSavepointTests;
        suite.test_concurrent_savepoints_with_isolation().await;
    }

    #[test_log::test(switchy_async::test)]
    async fn test_rusqlite_savepoint_after_failed_operation() {
        let suite = RusqliteSavepointTests;
        suite.test_savepoint_after_failed_operation().await;
    }
}

// ===== SQLITE SQLX BACKEND TESTS =====
#[cfg(feature = "sqlite-sqlx")]
mod sqlite_sqlx_savepoint_tests {
    use super::*;
    use std::sync::Arc;
    use switchy_async::sync::Mutex;
    use switchy_database::sqlx::sqlite::SqliteSqlxDatabase;

    struct SqliteSqlxSavepointTests;

    impl SavepointTestSuite for SqliteSqlxSavepointTests {
        type DatabaseType = SqliteSqlxDatabase;

        async fn get_database(&self) -> Option<Arc<Self::DatabaseType>> {
            use sqlx::sqlite::SqlitePoolOptions;

            // Always available - in-memory database with WAL mode and connection pool
            let database_url = "sqlite::memory:?cache=shared";
            let pool = SqlitePoolOptions::new()
                .max_connections(5) // Match Rusqlite pool size
                .min_connections(2)
                .connect(database_url)
                .await
                .ok()?;

            // Configure SQLite for better concurrency
            sqlx::query("PRAGMA journal_mode = WAL")
                .execute(&pool)
                .await
                .expect("Failed to set WAL mode");
            sqlx::query("PRAGMA busy_timeout = 5000")
                .execute(&pool)
                .await
                .expect("Failed to set busy timeout");
            sqlx::query("PRAGMA synchronous = NORMAL")
                .execute(&pool)
                .await
                .expect("Failed to set synchronous mode");
            sqlx::query("PRAGMA cache_size = -64000")
                .execute(&pool)
                .await
                .expect("Failed to set cache size");
            sqlx::query("PRAGMA temp_store = MEMORY")
                .execute(&pool)
                .await
                .expect("Failed to set temp store");

            let pool = Arc::new(Mutex::new(pool));
            Some(Arc::new(SqliteSqlxDatabase::new(pool)))
        }
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_sqlite_sqlx_nested_savepoints_three_levels() {
        let suite = SqliteSqlxSavepointTests;
        suite.test_nested_savepoints_three_levels().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_sqlite_sqlx_rollback_to_middle_savepoint() {
        let suite = SqliteSqlxSavepointTests;
        suite.test_rollback_to_middle_savepoint().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_sqlite_sqlx_release_savepoints_out_of_order() {
        let suite = SqliteSqlxSavepointTests;
        suite.test_release_savepoints_out_of_order().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_sqlite_sqlx_savepoint_with_data_operations() {
        let suite = SqliteSqlxSavepointTests;
        suite.test_savepoint_with_data_operations().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_sqlite_sqlx_commit_with_unreleased_savepoints() {
        let suite = SqliteSqlxSavepointTests;
        suite.test_commit_with_unreleased_savepoints().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_sqlite_sqlx_savepoint_name_validation() {
        let suite = SqliteSqlxSavepointTests;
        suite.test_savepoint_name_validation().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_sqlite_sqlx_sequential_savepoints_different_transactions() {
        let suite = SqliteSqlxSavepointTests;
        suite
            .test_sequential_savepoints_different_transactions()
            .await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_sqlite_sqlx_concurrent_savepoints_with_isolation() {
        let suite = SqliteSqlxSavepointTests;
        suite.test_concurrent_savepoints_with_isolation().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_sqlite_sqlx_savepoint_after_failed_operation() {
        let suite = SqliteSqlxSavepointTests;
        suite.test_savepoint_after_failed_operation().await;
    }
}

// ===== POSTGRES RAW BACKEND TESTS =====
#[cfg(all(feature = "postgres-raw", not(feature = "postgres-sqlx")))]
mod postgres_savepoint_tests {
    use super::*;
    use switchy_database::postgres::postgres::PostgresDatabase;

    struct PostgresSavepointTests;

    impl SavepointTestSuite for PostgresSavepointTests {
        type DatabaseType = PostgresDatabase;

        async fn get_database(&self) -> Option<Arc<Self::DatabaseType>> {
            let url = std::env::var("POSTGRES_TEST_URL").ok()?;

            let mut cfg = deadpool_postgres::Config::new();
            cfg.url = Some(url.clone());

            let pool = if url.contains("sslmode=require") {
                let connector = native_tls::TlsConnector::builder()
                    .danger_accept_invalid_certs(true)
                    .build()
                    .ok()?;
                let connector = postgres_native_tls::MakeTlsConnector::new(connector);
                cfg.create_pool(Some(deadpool_postgres::Runtime::Tokio1), connector)
                    .ok()?
            } else {
                cfg.create_pool(
                    Some(deadpool_postgres::Runtime::Tokio1),
                    tokio_postgres::NoTls,
                )
                .ok()?
            };

            Some(Arc::new(PostgresDatabase::new(pool)))
        }
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_postgres_nested_savepoints_three_levels() {
        let suite = PostgresSavepointTests;
        suite.test_nested_savepoints_three_levels().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_postgres_rollback_to_middle_savepoint() {
        let suite = PostgresSavepointTests;
        suite.test_rollback_to_middle_savepoint().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_postgres_release_savepoints_out_of_order() {
        let suite = PostgresSavepointTests;
        suite.test_release_savepoints_out_of_order().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_postgres_savepoint_with_data_operations() {
        let suite = PostgresSavepointTests;
        suite.test_savepoint_with_data_operations().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_postgres_commit_with_unreleased_savepoints() {
        let suite = PostgresSavepointTests;
        suite.test_commit_with_unreleased_savepoints().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_postgres_savepoint_name_validation() {
        let suite = PostgresSavepointTests;
        suite.test_savepoint_name_validation().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_postgres_sequential_savepoints_different_transactions() {
        let suite = PostgresSavepointTests;
        suite
            .test_sequential_savepoints_different_transactions()
            .await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_postgres_concurrent_savepoints_with_isolation() {
        let suite = PostgresSavepointTests;
        suite.test_concurrent_savepoints_with_isolation().await;
    }

    // NOTE: test_savepoint_after_failed_operation is intentionally excluded
    // from PostgreSQL test suites. PostgreSQL does not allow creating new
    // savepoints after an error occurs in a transaction - the transaction
    // enters an aborted state requiring ROLLBACK. See the test documentation
    // in common/savepoint_tests.rs for details and proper PostgreSQL patterns.
}

// ===== POSTGRES SQLX BACKEND TESTS =====
#[cfg(feature = "postgres-sqlx")]
mod postgres_sqlx_savepoint_tests {
    use super::*;
    use sqlx::PgPool;
    use std::sync::Arc;
    use switchy_async::sync::Mutex;
    use switchy_database::sqlx::postgres::PostgresSqlxDatabase;

    struct PostgresSqlxSavepointTests;

    impl SavepointTestSuite for PostgresSqlxSavepointTests {
        type DatabaseType = PostgresSqlxDatabase;

        async fn get_database(&self) -> Option<Arc<Self::DatabaseType>> {
            let url = std::env::var("POSTGRES_TEST_URL").ok()?;
            let pool = PgPool::connect(&url).await.ok()?;
            let pool = Arc::new(Mutex::new(pool));
            Some(Arc::new(PostgresSqlxDatabase::new(pool)))
        }
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_postgres_sqlx_nested_savepoints_three_levels() {
        let suite = PostgresSqlxSavepointTests;
        suite.test_nested_savepoints_three_levels().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_postgres_sqlx_rollback_to_middle_savepoint() {
        let suite = PostgresSqlxSavepointTests;
        suite.test_rollback_to_middle_savepoint().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_postgres_sqlx_release_savepoints_out_of_order() {
        let suite = PostgresSqlxSavepointTests;
        suite.test_release_savepoints_out_of_order().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_postgres_sqlx_savepoint_with_data_operations() {
        let suite = PostgresSqlxSavepointTests;
        suite.test_savepoint_with_data_operations().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_postgres_sqlx_commit_with_unreleased_savepoints() {
        let suite = PostgresSqlxSavepointTests;
        suite.test_commit_with_unreleased_savepoints().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_postgres_sqlx_savepoint_name_validation() {
        let suite = PostgresSqlxSavepointTests;
        suite.test_savepoint_name_validation().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_postgres_sqlx_sequential_savepoints_different_transactions() {
        let suite = PostgresSqlxSavepointTests;
        suite
            .test_sequential_savepoints_different_transactions()
            .await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_postgres_sqlx_concurrent_savepoints_with_isolation() {
        let suite = PostgresSqlxSavepointTests;
        suite.test_concurrent_savepoints_with_isolation().await;
    }

    // NOTE: test_savepoint_after_failed_operation is intentionally excluded
    // from PostgreSQL test suites. PostgreSQL does not allow creating new
    // savepoints after an error occurs in a transaction - the transaction
    // enters an aborted state requiring ROLLBACK. See the test documentation
    // in common/savepoint_tests.rs for details and proper PostgreSQL patterns.
}

// ===== MYSQL SQLX BACKEND TESTS =====
#[cfg(feature = "mysql-sqlx")]
mod mysql_sqlx_savepoint_tests {
    use super::*;
    use sqlx::MySqlPool;
    use std::sync::Arc;
    use switchy_async::sync::Mutex;
    use switchy_database::sqlx::mysql::MySqlSqlxDatabase;

    struct MysqlSqlxSavepointTests;

    impl SavepointTestSuite for MysqlSqlxSavepointTests {
        type DatabaseType = MySqlSqlxDatabase;

        async fn get_database(&self) -> Option<Arc<Self::DatabaseType>> {
            let url = std::env::var("MYSQL_TEST_URL").ok()?;
            let pool = MySqlPool::connect(&url).await.ok()?;
            let pool = Arc::new(Mutex::new(pool));
            Some(Arc::new(MySqlSqlxDatabase::new(pool)))
        }
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_mysql_sqlx_nested_savepoints_three_levels() {
        let suite = MysqlSqlxSavepointTests;
        suite.test_nested_savepoints_three_levels().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_mysql_sqlx_rollback_to_middle_savepoint() {
        let suite = MysqlSqlxSavepointTests;
        suite.test_rollback_to_middle_savepoint().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_mysql_sqlx_release_savepoints_out_of_order() {
        let suite = MysqlSqlxSavepointTests;
        suite.test_release_savepoints_out_of_order().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_mysql_sqlx_savepoint_with_data_operations() {
        let suite = MysqlSqlxSavepointTests;
        suite.test_savepoint_with_data_operations().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_mysql_sqlx_commit_with_unreleased_savepoints() {
        let suite = MysqlSqlxSavepointTests;
        suite.test_commit_with_unreleased_savepoints().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_mysql_sqlx_savepoint_name_validation() {
        let suite = MysqlSqlxSavepointTests;
        suite.test_savepoint_name_validation().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_mysql_sqlx_sequential_savepoints_different_transactions() {
        let suite = MysqlSqlxSavepointTests;
        suite
            .test_sequential_savepoints_different_transactions()
            .await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_mysql_sqlx_concurrent_savepoints_with_isolation() {
        let suite = MysqlSqlxSavepointTests;
        suite.test_concurrent_savepoints_with_isolation().await;
    }

    #[test_log::test(switchy_async::test(no_simulator))]
    async fn test_mysql_sqlx_savepoint_after_failed_operation() {
        let suite = MysqlSqlxSavepointTests;
        suite.test_savepoint_after_failed_operation().await;
    }
}