pg-client 0.3.0

PostgreSQL client configuration and connection management
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
use std::num::NonZeroU16;

use indoc::indoc;
use sqlx::Row as _;
use sqlx::SqlSafeStr as _;

const TEST_DATABASE: pg_client::Database =
    pg_client::Database::from_static_or_panic("some-database");

async fn setup_partitioned_events(config: &pg_client::Config, cross_schema: bool) {
    let schema_q2 = if cross_schema { "analytics" } else { "public" };

    setup_partitioned_events_with_partitions(
        config,
        ("public", "events_2024q1"),
        (schema_q2, "events_2024q2"),
    )
    .await;
}

async fn setup_partitioned_events_with_partitions(
    config: &pg_client::Config,
    partition_1: (&str, &str),
    partition_2: (&str, &str),
) {
    config
        .with_sqlx_connection(async |connection| {
            for schema in [partition_1.0, partition_2.0] {
                if schema != "public" {
                    let statement: String = sqlx::query_scalar(indoc! {"
                        SELECT
                          format('CREATE SCHEMA IF NOT EXISTS %I', $1)
                    "})
                    .bind(schema)
                    .fetch_one(&mut *connection)
                    .await?;
                    sqlx::raw_sql(sqlx::AssertSqlSafe(statement).into_sql_str())
                        .execute(&mut *connection)
                        .await?;
                }
            }

            sqlx::query(indoc! {"
                CREATE TABLE public.events
                  ( id int
                  , created_at date
                  , payload text
                  )
                PARTITION BY RANGE (created_at)
            "})
                .execute(&mut *connection)
                .await?;

            let statement: String = sqlx::query_scalar(indoc! {"
                SELECT
                  format(
                    'CREATE TABLE %I.%I PARTITION OF public.events FOR VALUES FROM (''2024-01-01'') TO (''2024-04-01'')',
                    $1,
                    $2
                  )
            "})
            .bind(partition_1.0)
            .bind(partition_1.1)
            .fetch_one(&mut *connection)
            .await?;
            sqlx::raw_sql(sqlx::AssertSqlSafe(statement).into_sql_str())
                .execute(&mut *connection)
                .await?;

            let statement: String = sqlx::query_scalar(indoc! {"
                SELECT
                  format(
                    'CREATE TABLE %I.%I PARTITION OF public.events FOR VALUES FROM (''2024-04-01'') TO (''2024-07-01'')',
                    $1,
                    $2
                  )
            "})
            .bind(partition_2.0)
            .bind(partition_2.1)
            .fetch_one(&mut *connection)
            .await?;
            sqlx::raw_sql(sqlx::AssertSqlSafe(statement).into_sql_str())
                .execute(&mut *connection)
                .await?;

            Ok::<(), sqlx::Error>(())
        })
        .await
        .unwrap()
        .unwrap();
}

async fn run_partitioned_index_addition(
    config: &pg_client::Config,
) -> Result<
    pg_client::sqlx::partitioned_index::create::Result,
    pg_client::sqlx::partitioned_index::Error,
> {
    let input = pg_client::sqlx::partitioned_index::create::Input {
        qualified_table: pg_client::identifier::QualifiedTable {
            schema: pg_client::identifier::Schema::PUBLIC,
            table: "events".parse().unwrap(),
        },
        index: "idx_events_created_at".parse().unwrap(),
        key_expression: "created_at".parse().unwrap(),
        unique: false,
        method: "btree".parse().unwrap(),
        include: None,
        where_clause: None,
        fillfactor: None,
        concurrently: pg_client::sqlx::partitioned_index::ConcurrentlyConfig::All,
    };

    pg_client::sqlx::partitioned_index::create::run(
        config,
        &input,
        NonZeroU16::new(2).unwrap(),
        false,
    )
    .await
}

async fn assert_parent_index_valid(config: &pg_client::Config) {
    let is_valid = get_parent_index_validity(config).await;
    assert_eq!(is_valid, Some(true), "Parent index should be valid");
}

async fn assert_parent_index_invalid(config: &pg_client::Config) {
    let is_valid = get_parent_index_validity(config).await;
    assert_eq!(is_valid, Some(false), "Parent index should be invalid");
}

async fn get_parent_index_validity(config: &pg_client::Config) -> Option<bool> {
    config
        .with_sqlx_connection(async |connection| {
            let row = sqlx::query(indoc! {"
                SELECT
                  indisvalid
                FROM
                  pg_index
                JOIN
                  pg_class
                ON
                  pg_class.oid = pg_index.indexrelid
                WHERE
                  pg_class.relname = $1
            "})
            .bind("idx_events_created_at")
            .fetch_optional(&mut *connection)
            .await?;

            Ok::<Option<bool>, sqlx::Error>(row.map(|r| r.get("indisvalid")))
        })
        .await
        .unwrap()
        .unwrap()
}

async fn assert_index_exists(
    config: &pg_client::Config,
    schema: &pg_client::identifier::Schema,
    index: &pg_client::identifier::Index,
) {
    let count = count_index(config, schema, index).await;
    assert_eq!(count, 1, "Expected {schema}.{index} to exist");
}

async fn assert_index_not_exists(
    config: &pg_client::Config,
    schema: &pg_client::identifier::Schema,
    index: &pg_client::identifier::Index,
) {
    let count = count_index(config, schema, index).await;
    assert_eq!(count, 0, "Expected {schema}.{index} to not exist");
}

async fn count_index(
    config: &pg_client::Config,
    schema: &pg_client::identifier::Schema,
    index: &pg_client::identifier::Index,
) -> i64 {
    config
        .with_sqlx_connection(async |connection| {
            let row = sqlx::query(indoc! {"
                SELECT
                  count(*) AS index_count
                FROM
                  pg_class
                JOIN
                  pg_namespace
                ON
                  pg_namespace.oid = pg_class.relnamespace
                WHERE
                  pg_class.relkind = 'i'
                AND
                  pg_class.relname = $1
                AND
                  pg_namespace.nspname = $2
            "})
            .bind(index.as_str())
            .bind(schema.as_str())
            .fetch_one(&mut *connection)
            .await?;
            let count: i64 = row.get("index_count");

            Ok::<i64, sqlx::Error>(count)
        })
        .await
        .unwrap()
        .unwrap()
}

fn find_partition_index_name(
    result: &pg_client::sqlx::partitioned_index::create::Result,
    qualified_table: &pg_client::identifier::QualifiedTable,
) -> pg_client::identifier::Index {
    result
        .partitions
        .iter()
        .find(|partition| &partition.qualified_table == qualified_table)
        .unwrap_or_else(|| panic!("missing partition for table {qualified_table}"))
        .index
        .clone()
}

fn definition(backend: ociman::Backend) -> pg_ephemeral::Definition {
    // CI environments may be slow, use 30s instead of default 10s
    pg_ephemeral::Definition::new(
        backend,
        pg_ephemeral::Image::default(),
        "test".parse().unwrap(),
    )
    .wait_available_timeout(std::time::Duration::from_secs(30))
}

const TEST_USER: pg_client::User = pg_client::User::from_static_or_panic("some-user");

#[tokio::test]
async fn test_with_sqlx_connection() {
    let backend = ociman::test_backend_setup!();
    let definition = definition(backend);

    definition
        .with_container(async |container| {
            let result = container
                .client_config()
                .with_sqlx_connection(async |connection| {
                    let row = sqlx::query("SELECT true AS ok")
                        .fetch_one(connection)
                        .await
                        .unwrap();

                    let ok: bool = row.get("ok");
                    ok
                })
                .await;

            assert!(result.is_ok(), "Connection should succeed: {result:?}");
            assert!(result.unwrap(), "Query should return true");
        })
        .await
        .unwrap()
}

#[tokio::test]
async fn test_with_sqlx_connection_error_on_unavailable_database() {
    let config = pg_client::Config {
        endpoint: pg_client::config::Endpoint::Network {
            host: "localhost".parse().unwrap(),
            channel_binding: None,
            host_addr: None,
            port: Some(pg_client::config::Port::new(0)), // Port 0 is reserved and never available
        },
        session: pg_client::config::Session {
            application_name: None,
            database: TEST_DATABASE,
            password: Some("test".parse().unwrap()),
            user: TEST_USER,
        },
        ssl_mode: pg_client::config::SslMode::Disable,
        ssl_root_cert: None,
        sqlx: Default::default(),
    };

    let result = config
        .with_sqlx_connection(async |connection| {
            let row = sqlx::query("SELECT true AS ok")
                .fetch_one(connection)
                .await
                .unwrap();

            let ok: bool = row.get("ok");
            ok
        })
        .await;

    assert!(result.is_err(), "Connection should fail");

    let error = result.unwrap_err();
    match error {
        pg_client::sqlx::ConnectionError::Connect(_) => {
            // Expected error variant
        }
        other => panic!("Expected Connect error, got: {other:?}"),
    }
}

#[tokio::test]
async fn test_analyze_all_tables() {
    let backend = ociman::test_backend_setup!();
    let definition = definition(backend);

    definition
        .with_container(async |container| {
            let config = container.client_config();

            // Create a test table to analyze
            config
                .with_sqlx_connection(async |connection| {
                    sqlx::query(indoc! {"
                        CREATE TABLE test_table
                          ( id int PRIMARY KEY
                          , name text
                          )
                    "})
                    .execute(connection)
                    .await
                    .unwrap();
                })
                .await
                .unwrap();

            // Run analyze on public schema
            let result = pg_client::sqlx::analyze::run_all(
                config,
                &pg_client::sqlx::analyze::Schemas::Specific(
                    [pg_client::identifier::Schema::PUBLIC].into(),
                ),
                NonZeroU16::new(1).unwrap(),
            )
            .await;

            assert!(result.is_ok(), "Analyze should succeed: {result:?}");

            let result = result.unwrap();
            assert_eq!(result.table_count, 1, "Should have 1 table to analyze");
            assert!(!result.elapsed.is_zero(), "Elapsed time should be non-zero");
        })
        .await
        .unwrap()
}

#[tokio::test]
async fn test_partitioned_index_addition() {
    let backend = ociman::test_backend_setup!();
    let definition = definition(backend);

    definition
        .with_container(async |container| {
            let config = container.client_config();

            // Setup: create partitioned table with 2 range partitions
            setup_partitioned_events(config, false).await;

            // Run index addition
            let result = run_partitioned_index_addition(config).await;
            assert!(result.is_ok(), "Index addition failed: {result:?}");
            let result = result.unwrap();
            assert_eq!(result.partitions.len(), 2);

            // Verify parent index is valid
            assert_parent_index_valid(config).await;
        })
        .await
        .unwrap()
}

#[tokio::test]
async fn test_partitioned_index_addition_cross_schema() {
    let backend = ociman::test_backend_setup!();
    let definition = definition(backend);

    definition
        .with_container(async |container| {
            let config = container.client_config();

            // Setup: create partitioned table with partitions across schemas.
            setup_partitioned_events(config, true).await;

            // Run index addition
            let result = run_partitioned_index_addition(config).await;
            assert!(result.is_ok(), "Index addition failed: {result:?}");
            let result = result.unwrap();
            assert_eq!(result.partitions.len(), 2);

            // Verify parent index is valid
            assert_parent_index_valid(config).await;
            let public_qualified = pg_client::identifier::QualifiedTable {
                schema: pg_client::identifier::Schema::PUBLIC,
                table: "events_2024q1".parse().unwrap(),
            };
            let analytics_qualified = pg_client::identifier::QualifiedTable {
                schema: "analytics".parse().unwrap(),
                table: "events_2024q2".parse().unwrap(),
            };
            let public_index = find_partition_index_name(&result, &public_qualified);
            let analytics_index = find_partition_index_name(&result, &analytics_qualified);
            assert_index_exists(
                config,
                &pg_client::identifier::Schema::PUBLIC,
                &public_index,
            )
            .await;
            assert_index_exists(config, &analytics_qualified.schema, &analytics_index).await;
        })
        .await
        .unwrap()
}

#[tokio::test]
async fn test_partitioned_index_addition_truncation() {
    let backend = ociman::test_backend_setup!();
    let definition = definition(backend);

    definition
        .with_container(async |container| {
            let config = container.client_config();

            let long_suffix_a = "a".repeat(49);
            let long_suffix_b = "b".repeat(49);
            let partition_1 = format!("events_2024q1_{long_suffix_a}");
            let partition_2 = format!("events_2024q1_{long_suffix_b}");

            setup_partitioned_events_with_partitions(
                config,
                ("public", partition_1.as_str()),
                ("public", partition_2.as_str()),
            )
            .await;

            let result = run_partitioned_index_addition(config).await;
            assert!(result.is_ok(), "Index addition failed: {result:?}");
            let result = result.unwrap();
            assert_eq!(result.partitions.len(), 2);

            assert_parent_index_valid(config).await;

            let qualified_1 = pg_client::identifier::QualifiedTable {
                schema: pg_client::identifier::Schema::PUBLIC,
                table: partition_1.parse().unwrap(),
            };
            let qualified_2 = pg_client::identifier::QualifiedTable {
                schema: pg_client::identifier::Schema::PUBLIC,
                table: partition_2.parse().unwrap(),
            };
            let index_1 = find_partition_index_name(&result, &qualified_1);
            let index_2 = find_partition_index_name(&result, &qualified_2);

            assert_ne!(index_1, index_2, "Index names should be distinct");
            assert_index_exists(config, &pg_client::identifier::Schema::PUBLIC, &index_1).await;
            assert_index_exists(config, &pg_client::identifier::Schema::PUBLIC, &index_2).await;
        })
        .await
        .unwrap()
}

#[tokio::test]
async fn test_partitioned_index_concurrently_except_unknown_partition_fails() {
    let backend = ociman::test_backend_setup!();
    let definition = definition(backend);

    definition
        .with_container(async |container| {
            let config = container.client_config();

            // Setup: create partitioned table with 2 range partitions
            setup_partitioned_events(config, false).await;

            let missing_partition: pg_client::identifier::Table = "events_2024q3".parse().unwrap();
            let mut excluded_tables = std::collections::BTreeSet::new();
            excluded_tables.insert(missing_partition.clone());

            let input = pg_client::sqlx::partitioned_index::create::Input {
                qualified_table: pg_client::identifier::QualifiedTable {
                    schema: pg_client::identifier::Schema::PUBLIC,
                    table: "events".parse().unwrap(),
                },
                index: "idx_events_created_at".parse().unwrap(),
                key_expression: "created_at".parse().unwrap(),
                unique: false,
                method: "btree".parse().unwrap(),
                include: None,
                where_clause: None,
                fillfactor: None,
                concurrently: pg_client::sqlx::partitioned_index::ConcurrentlyConfig::Except(
                    excluded_tables,
                ),
            };

            let result =
                pg_client::sqlx::partitioned_index::create::fetch_statements(config, &input).await;

            match result {
                Err(pg_client::sqlx::partitioned_index::Error::UnknownPartitionTables {
                    tables,
                }) => {
                    assert!(
                        tables.contains(&missing_partition),
                        "Missing partition should be reported"
                    );
                }
                Err(other_error) => {
                    panic!("Expected UnknownPartitionTables error, got {other_error}")
                }
                Ok(_) => panic!("Expected UnknownPartitionTables error, got Ok"),
            }
        })
        .await
        .unwrap()
}

#[tokio::test]
async fn test_partitioned_index_gc() {
    let backend = ociman::test_backend_setup!();
    let definition = definition(backend);

    definition
        .with_container(async |container| {
            let config = container.client_config();

            // Setup: create partitioned table with 2 range partitions
            setup_partitioned_events(config, false).await;

            // Fetch statements but only partially apply them
            let input = pg_client::sqlx::partitioned_index::create::Input {
                qualified_table: pg_client::identifier::QualifiedTable {
                    schema: pg_client::identifier::Schema::PUBLIC,
                    table: "events".parse().unwrap(),
                },
                index: "idx_events_created_at".parse().unwrap(),
                key_expression: "created_at".parse().unwrap(),
                unique: false,
                method: "btree".parse().unwrap(),
                include: None,
                where_clause: None,
                fillfactor: None,
                concurrently: pg_client::sqlx::partitioned_index::ConcurrentlyConfig::None, // Non-concurrent for simpler partial state
            };

            let statements =
                pg_client::sqlx::partitioned_index::create::fetch_statements(config, &input)
                    .await
                    .expect("fetch_statements should succeed");

            // Create partition indexes and parent stub, but don't attach
            config
                .with_sqlx_connection(async |connection| {
                    // Create partition indexes
                    for partition in &statements.partitions {
                        sqlx::raw_sql(partition.create_index_statement.clone())
                            .execute(&mut *connection)
                            .await?;
                    }

                    // Create parent index stub (will be invalid)
                    sqlx::raw_sql(statements.parent_create.clone())
                        .execute(&mut *connection)
                        .await?;

                    Ok::<(), sqlx::Error>(())
                })
                .await
                .unwrap()
                .unwrap();

            // Verify we have an invalid parent index
            assert_parent_index_invalid(config).await;

            // Verify partition indexes exist
            for partition in &statements.partitions {
                assert_index_exists(config, &partition.qualified_table.schema, &partition.index)
                    .await;
            }

            // Run GC
            let gc_input = pg_client::sqlx::partitioned_index::gc::Input {
                schema: pg_client::identifier::Schema::PUBLIC,
                index: "idx_events_created_at".parse().unwrap(),
            };

            let gc_result = pg_client::sqlx::partitioned_index::gc::run(
                config,
                &gc_input,
                NonZeroU16::new(2).unwrap(),
                false,
            )
            .await
            .expect("gc should succeed");

            assert!(
                gc_result.parent_dropped,
                "Parent index should have been dropped"
            );
            assert_eq!(
                gc_result.partition_indexes.len(),
                statements.partitions.len(),
                "Should have dropped all partition indexes"
            );

            // Verify all indexes are gone
            let parent_index: pg_client::identifier::Index =
                "idx_events_created_at".parse().unwrap();
            assert_index_not_exists(
                config,
                &pg_client::identifier::Schema::PUBLIC,
                &parent_index,
            )
            .await;

            for partition in &statements.partitions {
                assert_index_not_exists(
                    config,
                    &partition.qualified_table.schema,
                    &partition.index,
                )
                .await;
            }
        })
        .await
        .unwrap()
}

#[tokio::test]
async fn test_partitioned_index_gc_refuses_valid_index() {
    let backend = ociman::test_backend_setup!();
    let definition = definition(backend);

    definition
        .with_container(async |container| {
            let config = container.client_config();

            // Setup and create a valid index
            setup_partitioned_events(config, false).await;
            run_partitioned_index_addition(config)
                .await
                .expect("index creation should succeed");

            // Verify index is valid
            assert_parent_index_valid(config).await;

            // Try to GC - should fail
            let gc_input = pg_client::sqlx::partitioned_index::gc::Input {
                schema: pg_client::identifier::Schema::PUBLIC,
                index: "idx_events_created_at".parse().unwrap(),
            };

            let gc_result = pg_client::sqlx::partitioned_index::gc::run(
                config,
                &gc_input,
                NonZeroU16::new(1).unwrap(),
                false,
            )
            .await;

            assert!(gc_result.is_err(), "GC should fail on valid index");
            assert!(
                matches!(
                    gc_result.unwrap_err(),
                    pg_client::sqlx::partitioned_index::Error::IndexAlreadyValid { .. }
                ),
                "Should be IndexAlreadyValid error"
            );
        })
        .await
        .unwrap()
}