mockgres 0.0.26

An in-memory database that replicates a reasonable subset of Postgres functionality to make unit tests that rely on a database to run.
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
use crate::engine::{Plan, fe};
use pg_query::{NodeEnum, parse, protobuf::Token, scan};
use pgwire::error::PgWireResult;

use super::{ddl, delete, dml, insert, update};

pub struct Planner;

impl Planner {
    #[allow(dead_code)]
    pub fn plan_sql(sql: &str) -> PgWireResult<Plan> {
        let plans = Self::plan_sql_batch(sql)?;
        let mut non_empty = plans.into_iter().filter(|p| !matches!(p, Plan::Empty));
        let Some(first) = non_empty.next() else {
            return Ok(Plan::Empty);
        };
        if non_empty.next().is_some() {
            return Err(fe(
                "cannot insert multiple commands into a prepared statement",
            ));
        }
        Ok(first)
    }

    pub fn plan_sql_batch(sql: &str) -> PgWireResult<Vec<Plan>> {
        let mut plans = Vec::new();
        for segment in split_sql_segments(sql)? {
            if segment.trim().is_empty() {
                plans.push(Plan::Empty);
                continue;
            }
            let parsed =
                parse(segment).map_err(|e| pgwire::error::PgWireError::ApiError(Box::new(e)))?;
            let mut nodes = parsed
                .protobuf
                .stmts
                .into_iter()
                .filter_map(|stmt| stmt.stmt.and_then(|node| node.node));
            match (nodes.next(), nodes.next()) {
                (None, _) => plans.push(Plan::Empty),
                (Some(node), None) => plans.push(plan_stmt_node(node)?),
                (Some(_), Some(_)) => return Err(fe("multiple statements not supported")),
            }
        }
        if plans.is_empty() {
            plans.push(Plan::Empty);
        }
        Ok(plans)
    }
}

fn split_sql_segments(sql: &str) -> PgWireResult<Vec<&str>> {
    let scanned = scan(sql).map_err(|e| pgwire::error::PgWireError::ApiError(Box::new(e)))?;
    let mut out = Vec::new();
    let mut start = 0usize;
    for token in scanned.tokens {
        if token.token == Token::Ascii59 as i32 {
            let end = token.start as usize;
            out.push(&sql[start..end]);
            start = token.end as usize;
        }
    }
    out.push(&sql[start..]);
    Ok(out)
}

fn plan_stmt_node(node: NodeEnum) -> PgWireResult<Plan> {
    match node {
        NodeEnum::TransactionStmt(tx) => ddl::plan_transaction_stmt(&tx),
        NodeEnum::SelectStmt(sel) => dml::plan_select(*sel),
        NodeEnum::CreateStmt(cs) => ddl::plan_create_table(cs),
        NodeEnum::CreateSchemaStmt(cs) => ddl::plan_create_schema(cs),
        NodeEnum::CreatedbStmt(db) => ddl::plan_create_database(db),
        NodeEnum::AlterTableStmt(at) => ddl::plan_alter_table(at),
        NodeEnum::IndexStmt(idx) => ddl::plan_create_index(*idx),
        NodeEnum::DropStmt(drop) => ddl::plan_drop_stmt(drop),
        NodeEnum::DropdbStmt(db) => ddl::plan_drop_database(db),
        NodeEnum::RenameStmt(rename) => ddl::plan_rename(*rename),
        NodeEnum::VariableShowStmt(show) => ddl::plan_show(show),
        NodeEnum::VariableSetStmt(set) => ddl::plan_set(set),
        NodeEnum::AlterDatabaseStmt(db) => ddl::plan_alter_database(db),
        NodeEnum::AlterDatabaseSetStmt(db) => ddl::plan_alter_database_set(db),
        NodeEnum::InsertStmt(ins) => insert::plan_insert(*ins),
        NodeEnum::UpdateStmt(upd) => update::plan_update(*upd),
        NodeEnum::DeleteStmt(del) => delete::plan_delete(*del),
        NodeEnum::TruncateStmt(trunc) => ddl::plan_truncate(trunc),
        _ => Err(fe("unsupported statement type")),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::{
        InsertSource, OnConflictAction, OnConflictTarget, Plan, ScalarExpr, Value,
    };

    #[test]
    fn parses_alter_table_add_column_default() {
        let plan = Planner::plan_sql("alter table items add column note text default 'pending'")
            .expect("plan sql");
        match plan {
            Plan::AlterTableAddColumn { column, .. } => {
                let (name, _ty, _nullable, default, identity) = column;
                assert_eq!(name, "note");
                assert!(identity.is_none());
                match default {
                    Some(ScalarExpr::Literal(Value::Text(s))) => assert_eq!(s, "pending"),
                    other => panic!("expected text default, got {other:?}"),
                }
            }
            other => panic!("unexpected plan: {other:?}"),
        }
    }

    #[test]
    fn insert_values_preserves_default_cells() {
        let plan =
            Planner::plan_sql("insert into things values (DEFAULT, 1)").expect("plan insert");
        match plan {
            Plan::InsertValues {
                columns,
                rows,
                on_conflict: _,
                ..
            } => {
                assert!(columns.is_none());
                assert_eq!(rows.len(), 1);
                assert!(matches!(rows[0][0], InsertSource::Default));
            }
            other => panic!("unexpected plan: {other:?}"),
        }
    }

    #[test]
    fn insert_column_list_and_expressions_parse() {
        let plan =
            Planner::plan_sql("insert into gadgets (id, qty, note) values (1, 2 + 3, upper('hi'))")
                .expect("plan insert");
        match plan {
            Plan::InsertValues {
                columns,
                rows,
                on_conflict: _,
                ..
            } => {
                let cols = columns.expect("columns");
                assert_eq!(cols, vec!["id", "qty", "note"]);
                assert_eq!(rows.len(), 1);
                assert!(matches!(rows[0][2], InsertSource::Expr(_)));
            }
            other => panic!("unexpected plan: {other:?}"),
        }
    }

    #[test]
    fn insert_returning_clause_is_parsed() {
        let plan = Planner::plan_sql(
            "insert into gadgets(id) values (1) returning id, qty, upper(coalesce(note, 'x'))",
        )
        .expect("plan insert");
        match plan {
            Plan::InsertValues {
                returning,
                on_conflict: _,
                ..
            } => {
                assert!(returning.is_some(), "expected returning clause");
            }
            other => panic!("unexpected plan: {other:?}"),
        }
    }

    #[test]
    fn create_and_drop_index_parse() {
        let create = Planner::plan_sql("create index idx_things on items (id, qty)")
            .expect("plan create index");
        match create {
            Plan::CreateIndex {
                name,
                table,
                columns,
                if_not_exists,
                is_unique,
            } => {
                assert_eq!(name, "idx_things");
                assert_eq!(table.name, "items");
                assert_eq!(columns, vec!["id".to_string(), "qty".to_string()]);
                assert!(!if_not_exists);
                assert!(!is_unique);
            }
            other => panic!("unexpected plan: {other:?}"),
        }

        let drop =
            Planner::plan_sql("drop index if exists public.idx_things").expect("plan drop index");
        match drop {
            Plan::DropIndex {
                indexes, if_exists, ..
            } => {
                assert!(if_exists);
                assert_eq!(indexes.len(), 1);
                assert_eq!(
                    indexes[0].schema.as_ref().map(|s| s.as_str()),
                    Some("public")
                );
                assert_eq!(indexes[0].name, "idx_things");
            }
            other => panic!("unexpected plan: {other:?}"),
        }
    }

    #[test]
    fn alter_table_unique_constraint_parse() {
        let unnamed =
            Planner::plan_sql("alter table items add unique (qty)").expect("plan add unique");
        match unnamed {
            Plan::AlterTableAddConstraintUnique {
                table,
                name,
                columns,
            } => {
                assert_eq!(table.name, "items");
                assert!(name.is_none());
                assert_eq!(columns, vec!["qty".to_string()]);
            }
            other => panic!("unexpected plan: {other:?}"),
        }

        let named =
            Planner::plan_sql("alter table items add constraint items_qty_unique unique (qty)")
                .expect("plan add named unique");
        match named {
            Plan::AlterTableAddConstraintUnique {
                table,
                name,
                columns,
            } => {
                assert_eq!(table.name, "items");
                assert_eq!(name.as_deref(), Some("items_qty_unique"));
                assert_eq!(columns, vec!["qty".to_string()]);
            }
            other => panic!("unexpected plan: {other:?}"),
        }

        let drop = Planner::plan_sql("alter table items drop constraint items_qty_unique")
            .expect("plan drop unique");
        match drop {
            Plan::AlterTableDropConstraint {
                table,
                name,
                if_exists,
            } => {
                assert_eq!(table.name, "items");
                assert_eq!(name, "items_qty_unique");
                assert!(!if_exists);
            }
            other => panic!("unexpected plan: {other:?}"),
        }
    }

    #[test]
    fn show_server_version_parses() {
        let plan = Planner::plan_sql("show server_version").expect("plan show");
        match plan {
            Plan::ShowVariable { name, schema } => {
                assert_eq!(name, "server_version");
                assert_eq!(schema.fields.len(), 1);
                assert_eq!(schema.fields[0].name, "server_version");
            }
            other => panic!("unexpected plan: {other:?}"),
        }
    }

    #[test]
    fn set_client_min_messages_parses() {
        let plan = Planner::plan_sql("set client_min_messages = warning").expect("plan set");
        match plan {
            Plan::SetVariable { name, value } => {
                assert_eq!(name, "client_min_messages");
                assert_eq!(value, Some(vec!["warning".to_string()]));
            }
            other => panic!("unexpected plan: {other:?}"),
        }
    }

    #[test]
    fn insert_on_conflict_do_nothing_no_target() {
        let plan = Planner::plan_sql("insert into gadgets(id) values (1) on conflict do nothing")
            .expect("plan insert");
        match plan {
            Plan::InsertValues { on_conflict, .. } => match on_conflict.expect("on conflict") {
                OnConflictAction::DoNothing { target } => {
                    assert!(matches!(target, OnConflictTarget::None));
                }
                OnConflictAction::DoUpdate { .. } => {
                    unreachable!("do update not covered in this parser test")
                }
            },
            other => panic!("unexpected plan: {other:?}"),
        }
    }

    #[test]
    fn insert_on_conflict_do_nothing_columns() {
        let plan = Planner::plan_sql(
            "insert into gadgets(id, qty) values (1, 2) on conflict (id, qty) do nothing",
        )
        .expect("plan insert");
        match plan {
            Plan::InsertValues { on_conflict, .. } => match on_conflict.expect("on conflict") {
                OnConflictAction::DoNothing { target } => match target {
                    OnConflictTarget::Columns(cols) => assert_eq!(cols, vec!["id", "qty"]),
                    other => panic!("unexpected target: {other:?}"),
                },
                OnConflictAction::DoUpdate { .. } => {
                    unreachable!("do update not covered in this parser test")
                }
            },
            other => panic!("unexpected plan: {other:?}"),
        }
    }

    #[test]
    fn insert_on_conflict_do_nothing_constraint() {
        let plan = Planner::plan_sql(
            "insert into gadgets(id) values (1) on conflict on constraint gadgets_id_key do nothing",
        )
        .expect("plan insert");
        match plan {
            Plan::InsertValues { on_conflict, .. } => match on_conflict.expect("on conflict") {
                OnConflictAction::DoNothing { target } => match target {
                    OnConflictTarget::Constraint(name) => assert_eq!(name, "gadgets_id_key"),
                    other => panic!("unexpected target: {other:?}"),
                },
                OnConflictAction::DoUpdate { .. } => {
                    unreachable!("do update not covered in this parser test")
                }
            },
            other => panic!("unexpected plan: {other:?}"),
        }
    }

    #[test]
    fn with_single_cte_select_plan_construction() {
        let plan = Planner::plan_sql("with c as (select 1 as id) select id from c").expect("plan");
        match plan {
            Plan::With { ctes, body } => {
                assert_eq!(ctes.len(), 1);
                assert_eq!(ctes[0].name, "c");
                assert!(matches!(*ctes[0].plan.clone(), Plan::Projection { .. }));
                assert!(matches!(*body, Plan::Projection { .. }));
            }
            other => panic!("unexpected plan: {other:?}"),
        }
    }

    #[test]
    fn nested_aggregate_expression_is_planned() {
        let plan =
            Planner::plan_sql("select coalesce(sum(duration_seconds), 0) from observed_segments")
                .expect("plan");
        match plan {
            Plan::Projection { input, .. } => {
                assert!(matches!(*input, Plan::Aggregate { .. }));
            }
            other => panic!("unexpected plan: {other:?}"),
        }
    }

    #[test]
    fn with_multi_cte_plan_construction_in_declaration_order() {
        let plan = Planner::plan_sql(
            "with first as (select 1 as id), second as (select id from first) select id from second",
        )
        .expect("plan");
        match plan {
            Plan::With { ctes, body } => {
                let names: Vec<String> = ctes.into_iter().map(|cte| cte.name).collect();
                assert_eq!(names, vec!["first".to_string(), "second".to_string()]);
                assert!(matches!(*body, Plan::Projection { .. }));
            }
            other => panic!("unexpected plan: {other:?}"),
        }
    }

    #[test]
    fn with_update_from_cte_plans() {
        let plan = Planner::plan_sql(
            "with c as (select 1 as id) update t set x = 1 from c where t.id = c.id",
        );
        match plan.expect("plan") {
            Plan::With { body, .. } => match *body {
                Plan::Update { from, .. } => assert!(from.is_some()),
                other => panic!("unexpected body plan: {other:?}"),
            },
            other => panic!("unexpected plan: {other:?}"),
        }
    }

    #[test]
    fn with_insert_select_plans() {
        let plan =
            Planner::plan_sql("with c as (select 1 as id) insert into t(id) select id from c");
        match plan.expect("plan") {
            Plan::With { body, .. } => match *body {
                Plan::InsertSelect { .. } => {}
                other => panic!("unexpected body plan: {other:?}"),
            },
            other => panic!("unexpected plan: {other:?}"),
        }
    }

    #[test]
    fn with_delete_plans() {
        let plan = Planner::plan_sql(
            "with c as (select 1 as id) delete from t where id in (select id from c)",
        );
        match plan.expect("plan") {
            Plan::With { body, .. } => match *body {
                Plan::Delete { .. } => {}
                other => panic!("unexpected body plan: {other:?}"),
            },
            other => panic!("unexpected plan: {other:?}"),
        }
    }

    #[test]
    fn plan_sql_batch_single_statement() {
        let plans = Planner::plan_sql_batch("select 1").expect("plan batch");
        assert_eq!(plans.len(), 1);
        assert!(matches!(plans[0], Plan::Projection { .. }));
    }

    #[test]
    fn plan_sql_rejects_multiple_non_empty_statements() {
        let err = Planner::plan_sql("select 1; select 2").expect_err("expected planner error");
        assert!(
            err.to_string()
                .contains("cannot insert multiple commands into a prepared statement"),
            "unexpected planner error: {err}"
        );
    }

    #[test]
    fn plan_sql_batch_multiple_statements() {
        let plans = Planner::plan_sql_batch("select 1; select 2").expect("plan batch");
        assert_eq!(plans.len(), 2);
        assert!(matches!(plans[0], Plan::Projection { .. }));
        assert!(matches!(plans[1], Plan::Projection { .. }));
    }

    #[test]
    fn plan_sql_batch_empty_query_segments() {
        let semicolon_only = Planner::plan_sql_batch(";").expect("plan batch");
        assert_eq!(semicolon_only.len(), 2);
        assert!(matches!(semicolon_only[0], Plan::Empty));
        assert!(matches!(semicolon_only[1], Plan::Empty));

        let whitespace_only = Planner::plan_sql_batch("   ").expect("plan batch");
        assert_eq!(whitespace_only.len(), 1);
        assert!(matches!(whitespace_only[0], Plan::Empty));
    }

    #[test]
    fn plan_sql_batch_mixed_empty_and_non_empty_segments() {
        let plans = Planner::plan_sql_batch(" ; select 1;; select 2; ").expect("plan batch");
        assert_eq!(plans.len(), 5);
        assert!(matches!(plans[0], Plan::Empty));
        assert!(matches!(plans[1], Plan::Projection { .. }));
        assert!(matches!(plans[2], Plan::Empty));
        assert!(matches!(plans[3], Plan::Projection { .. }));
        assert!(matches!(plans[4], Plan::Empty));
    }
}