mockgres 0.0.29

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
476
477
478
479
480
481
482
483
484
485
use super::expr::parse_scalar_expr;
use crate::catalog::SchemaName;
use crate::engine::{DataType, IdentitySpec, ObjName, ScalarExpr, Value, fe, fe_code};
use pg_query::protobuf::a_const::Val;
use pg_query::protobuf::{AConst, ColumnDef, TypeName};
use pg_query::{Node, NodeEnum};
use pgwire::error::PgWireResult;

type ColumnDefSpec = (
    String,
    DataType,
    bool,
    Option<ScalarExpr>,
    Option<IdentitySpec>,
);

pub(super) fn const_to_value(c: &AConst) -> PgWireResult<Value> {
    if c.val.is_none() {
        return Ok(Value::Null);
    }
    let v = c.val.as_ref().unwrap();
    match v {
        Val::Ival(i) => Ok(Value::Int64(i.ival as i64)),
        Val::Fval(f) => match f.fval.parse::<i64>() {
            Ok(value) => Ok(Value::Int64(value)),
            Err(_) => {
                Ok(Value::from_f64(f.fval.parse::<f64>().map_err(|e| {
                    pgwire::error::PgWireError::ApiError(Box::new(e))
                })?))
            }
        },
        Val::Boolval(b) => Ok(Value::Bool(b.boolval)),
        Val::Sval(s) => Ok(Value::Text(s.sval.clone())),
        Val::Bsval(_) => Err(fe("bitstring const not yet supported")),
    }
}

pub(super) fn map_type(cd: &ColumnDef) -> PgWireResult<DataType> {
    let typ = cd.type_name.as_ref().ok_or_else(|| fe("missing type"))?;
    parse_type_name(typ)
}

pub(super) fn parse_type_name(typ: &TypeName) -> PgWireResult<DataType> {
    let mut tokens: Vec<String> = typ
        .names
        .iter()
        .filter_map(|n| {
            n.node.as_ref().and_then(|nn| {
                if let NodeEnum::String(s) = nn {
                    Some(s.sval.to_ascii_lowercase())
                } else {
                    None
                }
            })
        })
        .collect();
    tokens.retain(|t| t != "pg_catalog" && t != "public");
    if tokens.is_empty() {
        return Err(fe("bad type name"));
    }
    let last = tokens.last().unwrap().as_str();
    let dt = if tokens.len() >= 2
        && tokens[tokens.len() - 2] == "double"
        && tokens[tokens.len() - 1] == "precision"
    {
        DataType::Float8
    } else if tokens.len() >= 4
        && tokens[tokens.len() - 4] == "timestamp"
        && tokens[tokens.len() - 3] == "without"
        && tokens[tokens.len() - 2] == "time"
        && tokens[tokens.len() - 1] == "zone"
    {
        DataType::Timestamp
    } else if tokens.len() >= 4
        && tokens[tokens.len() - 4] == "timestamp"
        && tokens[tokens.len() - 3] == "with"
        && tokens[tokens.len() - 2] == "time"
        && tokens[tokens.len() - 1] == "zone"
    {
        DataType::Timestamptz
    } else {
        match last {
            "smallint" | "int2" => DataType::Int2,
            "int" | "int4" | "integer" | "serial" | "serial4" => DataType::Int4,
            "bigint" | "int8" | "bigserial" | "serial8" => DataType::Int8,
            "smallserial" | "serial2" => DataType::Int2,
            "float4" | "real" | "float8" | "double" | "numeric" | "decimal" => DataType::Float8,
            "text" | "spgist_text" | "xml" | "refcursor" | "testxmldomain" | "timetz" => {
                DataType::Text
            }
            "casttesttype" => DataType::Text,
            "time" => DataType::Time(parse_character_length(typ)?),
            "varchar" => DataType::Varchar(parse_character_length(typ)?),
            "name" => DataType::Name,
            "bpchar" | "character" => DataType::BpChar(parse_character_length(typ)?),
            "char" if typ.typmods.is_empty() => DataType::PgChar,
            "char" => DataType::BpChar(parse_character_length(typ)?),
            "point" => DataType::Point,
            "lseg" => DataType::Lseg,
            "line" => DataType::Line,
            "circle" => DataType::Circle,
            "box" => DataType::Box,
            "tid" => DataType::Tid,
            "pg_lsn" => DataType::PgLsn,
            "macaddr" => DataType::MacAddr,
            "macaddr8" => DataType::MacAddr8,
            "path" => DataType::Path,
            "json" => DataType::Json,
            "jsonb" => DataType::Jsonb,
            "bool" | "boolean" => DataType::Bool,
            "testboolxmldomain" => DataType::Bool,
            "oid" => DataType::Oid,
            "date" => DataType::Date,
            "testdatexmldomain" => DataType::Date,
            "timestamp" => DataType::Timestamp,
            "timestamptz" => DataType::Timestamptz,
            "bytea" => DataType::Bytea,
            "interval" => DataType::Interval,
            "regtype" => DataType::Text,
            "void" => DataType::Void,
            other => return Err(fe(format!("unsupported type: {other}"))),
        }
    };
    Ok(dt)
}

fn parse_character_length(typ: &TypeName) -> PgWireResult<Option<usize>> {
    if typ.typmods.is_empty() {
        return Ok(None);
    }
    if typ.typmods.len() != 1 {
        return Err(fe("character type accepts one length modifier"));
    }
    let value = typ.typmods[0]
        .node
        .as_ref()
        .ok_or_else(|| fe("invalid character length"))?;
    let NodeEnum::AConst(value) = value else {
        return Err(fe("invalid character length"));
    };
    let Some(Val::Ival(length)) = value.val.as_ref() else {
        return Err(fe("invalid character length"));
    };
    if length.ival < 1 {
        return Err(fe_code("22023", "length for type char must be at least 1"));
    }
    if length.ival > 10_485_760 {
        return Err(fe_code(
            "22023",
            "length for type char cannot exceed 10485760",
        ));
    }
    Ok(Some(length.ival as usize))
}

pub(super) fn parse_column_def(cd: &ColumnDef) -> PgWireResult<ColumnDefSpec> {
    let serial = cd.type_name.as_ref().is_some_and(|typ| {
        typ.names.iter().any(|name| {
            matches!(
                name.node.as_ref(),
                Some(NodeEnum::String(name))
                    if matches!(
                        name.sval.to_ascii_lowercase().as_str(),
                        "serial" | "serial2" | "serial4" | "serial8" | "smallserial" | "bigserial"
                    )
            )
        })
    });
    let dt = map_type(cd)?;
    let default_node = cd
        .raw_default
        .as_ref()
        .and_then(|n| n.node.as_ref())
        .or_else(|| cd.cooked_default.as_ref().and_then(|n| n.node.as_ref()))
        .or_else(|| {
            cd.constraints.iter().find_map(|c| {
                let Some(NodeEnum::Constraint(cons)) = c.node.as_ref() else {
                    return None;
                };
                if cons.contype == pg_query::protobuf::ConstrType::ConstrDefault as i32 {
                    cons.raw_expr.as_ref().and_then(|n| n.node.as_ref())
                } else {
                    None
                }
            })
        });
    let mut nullable = !cd
        .constraints
        .iter()
        .any(|c| matches!(c.node.as_ref(), Some(NodeEnum::Constraint(cons)) if cons.contype == pg_query::protobuf::ConstrType::ConstrNotnull as i32));
    let default = match default_node {
        Some(node) => {
            let expr = parse_scalar_expr(node)?;
            ensure_default_expr_is_const(&expr)?;
            Some(expr)
        }
        None => None,
    };
    let identity = if serial {
        Some(IdentitySpec {
            always: false,
            start_with: 1,
            increment_by: 1,
        })
    } else {
        parse_identity_spec(cd)?
    };
    if let Some(spec) = &identity {
        if !matches!(dt, DataType::Int2 | DataType::Int4 | DataType::Int8) {
            return Err(fe("IDENTITY columns must be SMALLINT, INT, or BIGINT"));
        }
        if spec.increment_by == 0 {
            return Err(fe("IDENTITY INCREMENT BY cannot be zero"));
        }
    }
    let name = cd.colname.clone();
    if name.is_empty() {
        return Err(fe("column must have a name"));
    }
    if identity.is_some() && default.is_some() {
        return Err(fe(format!(
            "identity column {name} cannot have an explicit DEFAULT"
        )));
    }
    if identity.is_some() {
        nullable = false;
    }
    Ok((name, dt, nullable, default, identity))
}

fn ensure_default_expr_is_const(expr: &ScalarExpr) -> PgWireResult<()> {
    match expr {
        ScalarExpr::Literal(_) => Ok(()),
        ScalarExpr::Column(..) | ScalarExpr::ColumnIdx(_) | ScalarExpr::ExcludedIdx(_) => {
            Err(fe("DEFAULT expressions cannot reference columns"))
        }
        ScalarExpr::Param { .. } => Err(fe("DEFAULT expressions cannot reference parameters")),
        ScalarExpr::BinaryOp { left, right, .. } => {
            ensure_default_expr_is_const(left)?;
            ensure_default_expr_is_const(right)
        }
        ScalarExpr::UnaryOp { expr, .. } | ScalarExpr::Cast { expr, .. } => {
            ensure_default_expr_is_const(expr)
        }
        ScalarExpr::Func { args, .. } => {
            for arg in args {
                ensure_default_expr_is_const(arg)?;
            }
            Ok(())
        }
        ScalarExpr::WindowRowNumber(_) => {
            Err(fe("DEFAULT expressions cannot contain window functions"))
        }
        ScalarExpr::Predicate(expr) => ensure_default_bool_expr_is_const(expr),
        ScalarExpr::Subquery(_) => Err(fe("DEFAULT expressions cannot contain subqueries")),
        ScalarExpr::Case {
            when_then,
            else_expr,
        } => {
            for (cond, result) in when_then {
                ensure_default_bool_expr_is_const(cond)?;
                ensure_default_expr_is_const(result)?;
            }
            if let Some(expr) = else_expr {
                ensure_default_expr_is_const(expr)?;
            }
            Ok(())
        }
    }
}

fn ensure_default_bool_expr_is_const(expr: &crate::engine::BoolExpr) -> PgWireResult<()> {
    use crate::engine::BoolExpr;

    match expr {
        BoolExpr::Literal(_) => Ok(()),
        BoolExpr::Comparison { lhs, rhs, .. } => {
            ensure_default_expr_is_const(lhs)?;
            ensure_default_expr_is_const(rhs)
        }
        BoolExpr::And(parts) | BoolExpr::Or(parts) => {
            for part in parts {
                ensure_default_bool_expr_is_const(part)?;
            }
            Ok(())
        }
        BoolExpr::Not(inner) => ensure_default_bool_expr_is_const(inner),
        BoolExpr::IsNull { expr, .. } => ensure_default_expr_is_const(expr),
        BoolExpr::InSubquery { .. } | BoolExpr::InListValues { .. } => {
            Err(fe("DEFAULT expressions cannot contain subqueries"))
        }
    }
}

fn parse_identity_spec(cd: &ColumnDef) -> PgWireResult<Option<IdentitySpec>> {
    let mut spec: Option<IdentitySpec> = None;
    for constraint in &cd.constraints {
        let Some(NodeEnum::Constraint(cons)) = constraint.node.as_ref() else {
            continue;
        };
        if cons.contype != pg_query::protobuf::ConstrType::ConstrIdentity as i32 {
            continue;
        }
        if spec.is_some() {
            return Err(fe(format!(
                "column {} specifies IDENTITY more than once",
                cd.colname
            )));
        }
        let always = match cons.generated_when.as_str() {
            "a" | "A" => true,
            "" | "d" | "D" => false,
            other => {
                return Err(fe(format!(
                    "unsupported IDENTITY generation mode {other:?}"
                )));
            }
        };
        let mut start_with = None;
        let mut increment_by = None;
        for opt in &cons.options {
            let Some(NodeEnum::DefElem(def)) = opt.node.as_ref() else {
                continue;
            };
            match def.defname.as_str() {
                "start" => start_with = Some(parse_identity_option_value(&def.arg)?),
                "increment" => increment_by = Some(parse_identity_option_value(&def.arg)?),
                _ => {}
            }
        }
        spec = Some(IdentitySpec {
            always,
            start_with: start_with.unwrap_or(1),
            increment_by: increment_by.unwrap_or(1),
        });
    }
    Ok(spec)
}

fn parse_identity_option_value(arg: &Option<Box<Node>>) -> PgWireResult<i128> {
    let node = arg
        .as_ref()
        .and_then(|n| n.node.as_ref())
        .ok_or_else(|| fe("IDENTITY option requires a value"))?;
    match node {
        NodeEnum::Integer(i) => Ok(i.ival as i128),
        NodeEnum::AConst(c) => match const_to_value(c)? {
            Value::Int64(v) => Ok(v as i128),
            Value::Text(s) => s
                .parse::<i128>()
                .map_err(|_| fe("IDENTITY option requires integer")),
            _ => Err(fe("IDENTITY option requires integer literal")),
        },
        _ => Err(fe("IDENTITY option requires integer literal")),
    }
}

pub(super) fn parse_index_columns(params: &[pg_query::Node]) -> PgWireResult<Vec<String>> {
    if params.is_empty() {
        return Err(fe("index requires at least one column"));
    }
    let mut cols = Vec::with_capacity(params.len());
    for p in params {
        let node = p.node.as_ref().ok_or_else(|| fe("bad index column"))?;
        let NodeEnum::IndexElem(elem) = node else {
            return Err(fe("index expressions not supported"));
        };
        if elem.expr.is_some() {
            return Err(fe("expression indexes not supported"));
        }
        if elem.name.is_empty() {
            return Err(fe("index column name required"));
        }
        cols.push(elem.name.clone());
    }
    Ok(cols)
}

pub(super) fn parse_obj_name_from_list(node: &NodeEnum) -> PgWireResult<ObjName> {
    let mut parts = Vec::new();
    match node {
        NodeEnum::List(list) => {
            for item in &list.items {
                let Some(NodeEnum::String(s)) = item.node.as_ref() else {
                    return Err(fe("bad qualified name component"));
                };
                parts.push(s.sval.clone());
            }
        }
        NodeEnum::String(s) => parts.push(s.sval.clone()),
        _ => return Err(fe("bad qualified name")),
    }
    if parts.is_empty() {
        return Err(fe("empty name"));
    }
    let name = parts.pop().unwrap();
    let schema = if parts.is_empty() {
        None
    } else {
        Some(SchemaName::new(parts.join(".")))
    };
    Ok(ObjName { schema, name })
}

pub(super) fn parse_set_value(args: &[pg_query::Node]) -> PgWireResult<Vec<String>> {
    if args.is_empty() {
        return Err(fe("SET requires value"));
    }
    let mut values = Vec::with_capacity(args.len());
    for arg in args {
        let node = arg.node.as_ref().ok_or_else(|| fe("bad SET value"))?;
        let Some(v) = try_parse_literal(node)? else {
            return Err(fe("unsupported SET value"));
        };
        values.push(literal_value_to_string(v)?);
    }
    Ok(values)
}

pub(super) fn literal_value_to_string(value: Value) -> PgWireResult<String> {
    Ok(match value {
        Value::Text(s) => s,
        Value::Int64(i) => i.to_string(),
        Value::Bool(b) => {
            if b {
                "true".into()
            } else {
                "false".into()
            }
        }
        _ => return Err(fe("SET literal type not supported")),
    })
}

pub(super) fn try_parse_literal(node: &NodeEnum) -> PgWireResult<Option<Value>> {
    match node {
        NodeEnum::AConst(c) => Ok(Some(const_to_value(c)?)),
        NodeEnum::AExpr(ax) => {
            let is_minus = ax.name.iter().any(|nn| {
                matches!(
                    nn.node.as_ref(),
                    Some(NodeEnum::String(s)) if s.sval == "-"
                )
            });
            if is_minus {
                let rhs = ax
                    .rexpr
                    .as_ref()
                    .and_then(|n| n.node.as_ref())
                    .ok_or_else(|| fe("bad unary minus"))?;
                match rhs {
                    NodeEnum::AConst(c) => match const_to_value(c)? {
                        Value::Int64(i) => Ok(Some(Value::Int64(-i))),
                        Value::Float64Bits(b) => Ok(Some(Value::from_f64(-f64::from_bits(b)))),
                        Value::Null => Err(fe("minus over null")),
                        Value::Text(_)
                        | Value::PgChar(_)
                        | Value::Point(_)
                        | Value::Lseg(_)
                        | Value::Line(_)
                        | Value::Circle(_)
                        | Value::Box(_)
                        | Value::Tid(_)
                        | Value::Oid(_)
                        | Value::PgLsn(_)
                        | Value::MacAddr(_)
                        | Value::MacAddr8(_)
                        | Value::Path(_)
                        | Value::Bool(_)
                        | Value::Date(_)
                        | Value::TimeMicros(_)
                        | Value::TimestampMicros(_)
                        | Value::TimestamptzMicros(_)
                        | Value::Bytes(_)
                        | Value::IntervalMicros(_) => Err(fe("minus over non-numeric literal")),
                    },
                    _ => Err(fe("minus over non-const")),
                }
            } else {
                Ok(None)
            }
        }
        _ => Ok(None),
    }
}