axa-postgres-sqlx 0.2.1

PostgreSQL pooling, migrations, and test resets over sqlx for Axum services.
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
//! Behaviour against a real Postgres. Ignored by default, because these drop
//! every table in the database they are given. Run them with:
//!
//! ```sh
//! AXA_TEST_DB_URL=postgres://... cargo test -p axa-postgres-sqlx -- --ignored --test-threads=1
//! ```

use std::path::Path;

use axa_postgres_sqlx::{
    BACKGROUND_LOCK, Background, Db, PoolConfig, begin_with, connect, dangerously_recreate,
    is_unique_violation, migrate, pending, pending_background, ping, revert, run_background,
    sqlx::{self, PgPool, Row, migrate::Migrator},
    status, truncate,
};

async fn pool() -> PgPool {
    let uri = std::env::var("AXA_TEST_DB_URL").expect("AXA_TEST_DB_URL");
    connect(&PoolConfig::new(uri)).await.expect("connect")
}

async fn migrator() -> Migrator {
    let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/migrations");
    Migrator::new(path).await.expect("load migrations")
}

async fn table_exists(pool: &PgPool, name: &str) -> bool {
    sqlx::query("SELECT to_regclass($1) IS NOT NULL AS found")
        .bind(name)
        .fetch_one(pool)
        .await
        .unwrap()
        .get("found")
}

async fn count_items(pool: &PgPool) -> i64 {
    sqlx::query("SELECT count(*) AS n FROM items")
        .fetch_one(pool)
        .await
        .unwrap()
        .get("n")
}

async fn insert_item(pool: &PgPool, name: &str) -> Result<i64, sqlx::Error> {
    Ok(
        sqlx::query("INSERT INTO items (name) VALUES ($1) RETURNING id")
            .bind(name)
            .fetch_one(pool)
            .await?
            .get("id"),
    )
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL and drops every table in it"]
async fn pooling_and_migrations_against_postgres() {
    let pool = pool().await;
    let migrator = migrator().await;
    ping(&pool).await.unwrap();

    // Recreating from anything leaves exactly the migrated schema.
    dangerously_recreate(&pool, &migrator).await.unwrap();
    assert!(table_exists(&pool, "items").await);
    assert!(table_exists(&pool, "notes").await);

    // Status lists both, oldest first, applied.
    let rows = status(&pool, &migrator).await.unwrap();
    assert_eq!(rows.len(), 2);
    assert_eq!(rows[0].description, "create items");
    assert!(rows.iter().all(|row| row.applied));

    // Migrating again changes nothing.
    migrate(&pool, &migrator).await.unwrap();

    // A violated unique constraint is recognised, and other errors are not.
    insert_item(&pool, "one").await.unwrap();
    let error = insert_item(&pool, "one").await.unwrap_err();
    assert!(is_unique_violation(&error));
    let error = sqlx::query("SELECT * FROM missing_table")
        .execute(&pool)
        .await
        .unwrap_err();
    assert!(!is_unique_violation(&error));

    // Truncating empties the table and restarts its sequence, including when
    // another table references it.
    truncate(&pool, &["items"]).await.unwrap();
    assert_eq!(count_items(&pool).await, 0);
    assert_eq!(insert_item(&pool, "two").await.unwrap(), 1);

    // A bad name is refused before any SQL runs, and leaves the data alone.
    assert!(truncate(&pool, &["items; DROP TABLE items"]).await.is_err());
    assert_eq!(count_items(&pool).await, 1);

    // No tables is not an error.
    truncate::<&str>(&pool, &[]).await.unwrap();

    // Reverting one step removes only the newest migration.
    revert(&pool, &migrator, 1).await.unwrap();
    assert!(table_exists(&pool, "items").await);
    assert!(!table_exists(&pool, "notes").await);
    let rows = status(&pool, &migrator).await.unwrap();
    assert!(rows[0].applied);
    assert!(!rows[1].applied);

    // Reverting past the start reverts everything, and migrating restores it.
    revert(&pool, &migrator, 5).await.unwrap();
    assert!(!table_exists(&pool, "items").await);
    migrate(&pool, &migrator).await.unwrap();
    assert!(table_exists(&pool, "notes").await);

    // Recreating clears data and enum types, then works a second time.
    insert_item(&pool, "three").await.unwrap();
    dangerously_recreate(&pool, &migrator).await.unwrap();
    assert_eq!(count_items(&pool).await, 0);
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL and drops every table in it"]
async fn recreating_keeps_extensions() {
    let pool = pool().await;
    let migrator = migrator().await;
    sqlx::query("CREATE EXTENSION IF NOT EXISTS citext")
        .execute(&pool)
        .await
        .unwrap();
    dangerously_recreate(&pool, &migrator).await.unwrap();
    let found: i64 = sqlx::query("SELECT count(*) AS n FROM pg_extension WHERE extname = 'citext'")
        .fetch_one(&pool)
        .await
        .unwrap()
        .get("n");
    assert_eq!(found, 1);
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL and drops every table in it"]
async fn services_booting_together_all_migrate() {
    let pool = pool().await;
    let migrator = migrator().await;
    dangerously_recreate(&pool, &migrator).await.unwrap();
    revert(&pool, &migrator, 5).await.unwrap();
    let boots: Vec<_> = (0..6)
        .map(|_| {
            tokio::spawn(async {
                let pool = self::pool().await;
                let migrator = self::migrator().await;
                migrate(&pool, &migrator).await
            })
        })
        .collect();
    for boot in boots {
        boot.await.unwrap().unwrap();
    }
    assert!(table_exists(&pool, "notes").await);
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL and drops every table in it"]
async fn status_on_a_fresh_database_shows_nothing_applied() {
    let pool = pool().await;
    let migrator = migrator().await;
    dangerously_recreate(&pool, &migrator).await.unwrap();
    sqlx::query("DROP TABLE _sqlx_migrations")
        .execute(&pool)
        .await
        .unwrap();
    let rows = status(&pool, &migrator).await.unwrap();
    assert!(rows.iter().all(|row| !row.applied));
    assert_eq!(
        pending(&pool, &migrator).await.unwrap(),
        ["1_create items", "2_create notes"]
    );
    dangerously_recreate(&pool, &migrator).await.unwrap();
    assert_eq!(
        pending(&pool, &migrator).await.unwrap(),
        Vec::<String>::new()
    );
}

/// One function, reached from the pool and from inside a transaction, in a
/// future that can be spawned.
async fn item_count(db: impl Into<Db<'_>>) -> Result<i64, sqlx::Error> {
    let mut conn = db.into().acquire().await?;
    sqlx::query_scalar("SELECT count(*) FROM items")
        .fetch_one(&mut *conn)
        .await
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL and drops every table in it"]
async fn one_function_serves_the_pool_and_a_transaction() {
    let pool = pool().await;
    let migrator = migrator().await;
    dangerously_recreate(&pool, &migrator).await.unwrap();

    let mut tx = pool.begin().await.unwrap();
    sqlx::query("INSERT INTO items (name) VALUES ('held')")
        .execute(&mut *tx)
        .await
        .unwrap();
    assert_eq!(item_count(&mut *tx).await.unwrap(), 1);
    // The pool cannot see what the transaction has not committed.
    assert_eq!(item_count(&pool).await.unwrap(), 0);
    tx.rollback().await.unwrap();

    let spawned = tokio::spawn({
        let pool = pool.clone();
        async move { item_count(&pool).await }
    });
    assert_eq!(spawned.await.unwrap().unwrap(), 0);
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL and drops every table in it"]
async fn a_setting_lasts_for_its_transaction_and_never_reaches_the_next() {
    let uri = std::env::var("AXA_TEST_DB_URL").expect("AXA_TEST_DB_URL");
    // One connection, so the next transaction is on the same one.
    let mut config = PoolConfig::new(uri);
    config.min_connections = 0;
    config.max_connections = 1;
    let pool = connect(&config).await.unwrap();
    let read = "SELECT coalesce(current_setting('app.tenant', true), '') AS tenant";

    let mut tx = begin_with(&pool, &[("app.tenant", "acme"), ("app.user_id", "42")])
        .await
        .unwrap();
    let tenant: String = sqlx::query(read)
        .fetch_one(&mut *tx)
        .await
        .unwrap()
        .get("tenant");
    assert_eq!(tenant, "acme");
    let user: String = sqlx::query("SELECT current_setting('app.user_id') AS user_id")
        .fetch_one(&mut *tx)
        .await
        .unwrap()
        .get("user_id");
    assert_eq!(user, "42");
    tx.commit().await.unwrap();
    let after: String = sqlx::query(read)
        .fetch_one(&pool)
        .await
        .unwrap()
        .get("tenant");
    assert_eq!(after, "", "a committed setting leaked into the pool");

    let mut tx = begin_with(&pool, &[("app.tenant", "globex")])
        .await
        .unwrap();
    let _: String = sqlx::query(read)
        .fetch_one(&mut *tx)
        .await
        .unwrap()
        .get("tenant");
    tx.rollback().await.unwrap();
    let after: String = sqlx::query(read)
        .fetch_one(&pool)
        .await
        .unwrap()
        .get("tenant");
    assert_eq!(after, "", "a rolled-back setting leaked into the pool");

    // A value is bound, so SQL in it is only text.
    let mut tx = begin_with(&pool, &[("app.tenant", "x'); RESET ALL; --")])
        .await
        .unwrap();
    let tenant: String = sqlx::query(read)
        .fetch_one(&mut *tx)
        .await
        .unwrap()
        .get("tenant");
    assert_eq!(tenant, "x'); RESET ALL; --");
    tx.rollback().await.unwrap();
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL as a superuser, and drops every table in it"]
async fn row_security_holds_only_for_a_role_without_bypass_on_a_forced_table() {
    use axa_postgres_sqlx::row_security;
    let uri = std::env::var("AXA_TEST_DB_URL").expect("AXA_TEST_DB_URL");
    // One connection, so SET ROLE below is the role every later query runs as.
    let mut config = PoolConfig::new(uri);
    config.min_connections = 0;
    config.max_connections = 1;
    let pool = connect(&config).await.unwrap();
    for statement in [
        "DROP TABLE IF EXISTS rls_plain, rls_enabled, rls_forced",
        "CREATE TABLE rls_plain (tenant_id TEXT)",
        "CREATE TABLE rls_enabled (tenant_id TEXT)",
        "ALTER TABLE rls_enabled ENABLE ROW LEVEL SECURITY",
        "CREATE TABLE rls_forced (tenant_id TEXT)",
        "ALTER TABLE rls_forced ENABLE ROW LEVEL SECURITY",
        "ALTER TABLE rls_forced FORCE ROW LEVEL SECURITY",
        "DROP ROLE IF EXISTS axa_rls_app",
        "CREATE ROLE axa_rls_app NOLOGIN",
    ] {
        sqlx::query(statement).execute(&pool).await.unwrap();
    }
    let tables = ["rls_plain", "rls_enabled", "rls_forced", "rls_missing"];

    let as_superuser = row_security(&pool, &tables).await.unwrap();
    assert!(as_superuser.bypasses);
    assert_eq!(
        as_superuser.unprotected,
        ["rls_plain", "rls_enabled", "rls_missing"]
    );
    assert!(!as_superuser.holds());

    sqlx::query("SET ROLE axa_rls_app")
        .execute(&pool)
        .await
        .unwrap();
    let as_app = row_security(&pool, &["rls_forced"]).await.unwrap();
    assert_eq!(as_app.role, "axa_rls_app");
    assert!(!as_app.bypasses);
    assert!(as_app.holds(), "{as_app:?}");
    sqlx::query("RESET ROLE").execute(&pool).await.unwrap();

    sqlx::query("ALTER ROLE axa_rls_app BYPASSRLS")
        .execute(&pool)
        .await
        .unwrap();
    sqlx::query("SET ROLE axa_rls_app")
        .execute(&pool)
        .await
        .unwrap();
    assert!(row_security(&pool, &["rls_forced"]).await.unwrap().bypasses);
    sqlx::query("RESET ROLE").execute(&pool).await.unwrap();
    sqlx::query("DROP TABLE rls_plain, rls_enabled, rls_forced")
        .execute(&pool)
        .await
        .unwrap();
    sqlx::query("DROP ROLE axa_rls_app")
        .execute(&pool)
        .await
        .unwrap();
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL and drops every table in it"]
async fn a_stale_plan_retires_the_connection_and_the_next_attempt_works() {
    use axa_postgres_sqlx::{is_stale_plan, note_stale_plan};
    let uri = std::env::var("AXA_TEST_DB_URL").expect("AXA_TEST_DB_URL");
    // One connection, so the statement cached on it is the one that goes stale.
    let mut config = PoolConfig::new(uri);
    config.min_connections = 0;
    config.max_connections = 1;
    let pool = connect(&config).await.unwrap();
    for statement in [
        "DROP TABLE IF EXISTS stale_plan",
        "CREATE TABLE stale_plan (x INT)",
        "INSERT INTO stale_plan VALUES (1)",
    ] {
        sqlx::raw_sql(statement).execute(&pool).await.unwrap();
    }
    let select = "SELECT * FROM stale_plan";
    sqlx::query(select).fetch_all(&pool).await.unwrap();
    sqlx::raw_sql("ALTER TABLE stale_plan ALTER COLUMN x TYPE TEXT")
        .execute(&pool)
        .await
        .unwrap();

    let error = sqlx::query(select).fetch_all(&pool).await.unwrap_err();
    assert!(is_stale_plan(&error), "{error:?}");
    assert!(note_stale_plan(&error));

    // The pool hands out a fresh connection, where the statement is prepared again.
    let rows = sqlx::query(select).fetch_all(&pool).await.unwrap();
    let x: String = rows[0].get("x");
    assert_eq!(x, "1");
    sqlx::raw_sql("DROP TABLE stale_plan")
        .execute(&pool)
        .await
        .unwrap();
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn every_connection_starts_with_the_session_settings() {
    let uri = std::env::var("AXA_TEST_DB_URL").expect("AXA_TEST_DB_URL");
    let mut config = PoolConfig::new(uri);
    config.statement_timeout_ms = 1234;
    config.application_name = "axa-session-test".to_string();
    config.read_only = true;
    let pool = connect(&config).await.unwrap();
    let show = |sql: &'static str| {
        let pool = pool.clone();
        async move {
            let row = sqlx::query(sql).fetch_one(&pool).await.unwrap();
            row.get::<String, _>(0)
        }
    };
    assert_eq!(show("SHOW statement_timeout").await, "1234ms");
    assert_eq!(show("SHOW application_name").await, "axa-session-test");
    assert_eq!(show("SHOW default_transaction_read_only").await, "on");
    let refused = sqlx::raw_sql("CREATE TABLE axa_read_only_refused (x INT)")
        .execute(&pool)
        .await
        .unwrap_err();
    let code = refused
        .as_database_error()
        .and_then(axa_postgres_sqlx::sqlx::error::DatabaseError::code);
    assert_eq!(code.as_deref(), Some("25006"), "{refused:?}");
}

const NOTES_BY_ITEM: Background = Background {
    name: "notes_by_item",
    statements: &[
        "DROP INDEX CONCURRENTLY IF EXISTS notes_by_item",
        "CREATE INDEX CONCURRENTLY notes_by_item ON notes (item_id)",
    ],
};

const ITEMS_BY_STATE: Background = Background {
    name: "items_by_state",
    statements: &["CREATE INDEX CONCURRENTLY items_by_state ON items (state)"],
};

const BROKEN: Background = Background {
    name: "broken",
    statements: &["CREATE INDEX CONCURRENTLY broken ON no_such_table (x)"],
};

const FIXED: Background = Background {
    name: "broken",
    statements: &["CREATE INDEX CONCURRENTLY broken ON items (name)"],
};

const BLANK: Background = Background {
    name: "",
    statements: &[],
};

async fn fresh_for_background() -> PgPool {
    let pool = pool().await;
    dangerously_recreate(&pool, &migrator().await)
        .await
        .unwrap();
    sqlx::query("DROP TABLE IF EXISTS axa_background_migrations")
        .execute(&pool)
        .await
        .unwrap();
    pool
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn background_migrations_run_outside_a_transaction_once_each() {
    let pool = fresh_for_background().await;
    let all = [NOTES_BY_ITEM, ITEMS_BY_STATE];
    assert_eq!(
        pending_background(&pool, &all).await.unwrap(),
        ["notes_by_item", "items_by_state"]
    );
    let ran = run_background(&pool, &all).await.unwrap();
    assert_eq!(ran.unwrap(), ["notes_by_item", "items_by_state"]);
    assert!(table_exists(&pool, "notes_by_item").await);
    assert!(table_exists(&pool, "items_by_state").await);
    assert_eq!(
        pending_background(&pool, &all).await.unwrap(),
        Vec::<String>::new()
    );
    assert_eq!(
        run_background(&pool, &all).await.unwrap().unwrap(),
        Vec::<String>::new()
    );
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_process_finding_the_lock_held_runs_nothing() {
    let pool = fresh_for_background().await;
    let mut holder = pool.acquire().await.unwrap();
    sqlx::query("SELECT pg_advisory_lock($1)")
        .bind(BACKGROUND_LOCK)
        .execute(&mut *holder)
        .await
        .unwrap();
    assert_eq!(run_background(&pool, &[NOTES_BY_ITEM]).await.unwrap(), None);
    assert!(!table_exists(&pool, "notes_by_item").await);
    sqlx::query("SELECT pg_advisory_unlock($1)")
        .bind(BACKGROUND_LOCK)
        .execute(&mut *holder)
        .await
        .unwrap();
    drop(holder);
    assert!(
        run_background(&pool, &[NOTES_BY_ITEM])
            .await
            .unwrap()
            .is_some()
    );
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_failed_background_migration_is_left_to_run_again_and_frees_the_lock() {
    let pool = fresh_for_background().await;
    assert!(
        run_background(&pool, &[NOTES_BY_ITEM, BROKEN])
            .await
            .is_err()
    );
    assert_eq!(
        pending_background(&pool, &[NOTES_BY_ITEM, BROKEN])
            .await
            .unwrap(),
        ["broken"]
    );
    let ran = run_background(&pool, &[NOTES_BY_ITEM, FIXED])
        .await
        .unwrap();
    assert_eq!(
        ran.unwrap(),
        ["broken"],
        "the lock was freed, and only it ran"
    );
}

#[tokio::test]
async fn a_background_migration_named_twice_or_badly_is_refused() {
    let pool = sqlx::postgres::PgPoolOptions::new()
        .connect_lazy("postgres://axa:axa@127.0.0.1:1/axa")
        .unwrap();
    let twice = run_background(&pool, &[NOTES_BY_ITEM, NOTES_BY_ITEM]).await;
    assert!(
        matches!(twice, Err(sqlx::Error::Configuration(_))),
        "{twice:?}"
    );
    let blank = run_background(&pool, &[BLANK]).await;
    assert!(
        matches!(blank, Err(sqlx::Error::Configuration(_))),
        "{blank:?}"
    );
}