rupg-analyze 0.1.84

Name resolution, type resolution, the query tree, the rewriter for views and rules.
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
//! The casts of `parse_coerce.c`: which casts exist in each context, the expression of a cast, the common type of a list of expressions, and the cast to `boolean` of a condition.

use rupg_common::{Error, Result, SqlState};
use rupg_pgcatalog::builtin;
use rupg_types::{Value, oid};

use crate::Analyzer;
use crate::expr::{CastForm, Expr, ExprKind, Func, FuncForm};
use crate::types;

/// `CoercionContext`: where a cast happens. A cast is allowed in its own context and in each later one.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Context {
    /// An expression, such as the argument of a function.
    Implicit,
    /// The value of `INSERT` and `UPDATE`.
    Assignment,
    /// `COERCION_PLPGSQL`: the value of an assignment of PL/pgSQL. When no other cast exists, the output function of the source and the input function of the target make the cast.
    Plpgsql,
    /// `CAST(x AS type)` and `x::type`.
    Explicit,
}

/// `CoercionPathType`: how a cast happens.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Path {
    None,
    /// The function with this OID.
    Func(u32),
    /// No change of the binary form.
    Relabel,
    /// Each element of an array, with the cast of the element type.
    ArrayCoerce,
    /// The output function of the source, then the input function of the target.
    ViaIo,
}

/// `find_coercion_pathway`.
pub fn find_path(target: u32, source: u32, context: Context) -> Path {
    let (target, source) = (types::base(target), types::base(source));
    if source == target {
        return Path::Relabel;
    }
    if source == oid::INTERNAL || target == oid::INTERNAL {
        return Path::None;
    }
    if let Some(cast) = builtin::cast(source, target) {
        let allowed = match cast.context {
            b'i' => Context::Implicit,
            b'a' => Context::Assignment,
            _ => Context::Explicit,
        };
        if context < allowed {
            return Path::None;
        }
        return match cast.method {
            b'f' => Path::Func(cast.func),
            b'i' => Path::ViaIo,
            _ => Path::Relabel,
        };
    }
    if target != oid::OIDVECTOR && target != oid::INT2VECTOR {
        let (target_element, source_element) = (types::element(target), types::element(source));
        if target_element != 0
            && source_element != 0
            && find_path(target_element, source_element, context) != Path::None
        {
            return Path::ArrayCoerce;
        }
    }
    // Any type has an I/O cast to a string type in assignment, and a string type has an explicit I/O cast to any type. In PL/pgSQL, any type has an I/O cast to any type.
    if (context >= Context::Assignment && types::category(target) == types::STRING)
        || (context >= Context::Explicit && types::category(source) == types::STRING)
        || context == Context::Plpgsql
    {
        Path::ViaIo
    } else {
        Path::None
    }
}

/// `coerce_to_target_type` with `COERCION_EXPLICIT` and `COERCE_EXPLICIT_CAST` for an expression whose type is known, to a type that is not a domain, as the cast `$1::text` in the body of a SQL function that `inline_function` puts in a query. `None` when the type has no such cast.
pub fn explicit_cast(expr: Expr, target: u32) -> Option<Expr> {
    if expr.ty == target {
        return Some(expr);
    }
    let location = expr.location;
    match find_path(target, expr.ty, Context::Explicit) {
        Path::None | Path::ArrayCoerce => None,
        Path::Relabel => Some(Expr {
            kind: ExprKind::Relabel(Box::new(expr), CastForm::Explicit),
            ty: target,
            typmod: -1,
            location,
        }),
        Path::ViaIo => Some(Expr {
            kind: ExprKind::CoerceViaIo(Box::new(expr), CastForm::Explicit),
            ty: target,
            typmod: -1,
            location,
        }),
        Path::Func(func) => Some(build_cast(
            expr,
            func,
            target,
            -1,
            Context::Explicit,
            FuncForm::ExplicitCast,
            location,
        )),
    }
}

/// `can_coerce_type`: true if each input type has a cast to its target type in the context.
pub fn can_coerce(inputs: &[u32], targets: &[u32], context: Context) -> bool {
    let mut generic = false;
    for (&input, &target) in inputs.iter().zip(targets) {
        if input == target {
            continue;
        }
        if input == oid::INTERNAL || target == oid::INTERNAL {
            return false;
        }
        if target == oid::ANY {
            continue;
        }
        if types::is_polymorphic(target) {
            generic = true;
            continue;
        }
        if input == oid::UNKNOWN {
            continue;
        }
        // A composite type is a `record`, and an array of a composite type is a `record[]`.
        if (target == oid::RECORD && types::is_complex(input))
            || (target == oid::RECORD_ARRAY && types::is_complex(types::element(input)))
        {
            continue;
        }
        // `coerce_record_to_complex` casts a `record` to a composite type field by field.
        if input == oid::RECORD && types::is_complex(types::base(target)) {
            continue;
        }
        if find_path(target, input, context) != Path::None {
            continue;
        }
        return false;
    }
    !generic || crate::poly::consistent(inputs, targets)
}

/// `select_common_type_from_oids`: the type that all the types can take. A list of only `unknown` gives `text`. When two types are in different categories, the error gives the two types and the index of the second.
pub(crate) fn common_of(tys: &[u32]) -> std::result::Result<u32, (u32, u32, usize)> {
    let Some(&first) = tys.first() else { return Ok(oid::TEXT) };
    if first != oid::UNKNOWN && tys.iter().all(|&t| t == first) {
        return Ok(first);
    }
    let mut ptype = types::base(first);
    let (mut pcategory, mut ppreferred) = types::category_preferred(ptype);
    for (i, &next) in tys.iter().enumerate().skip(1) {
        let ntype = types::base(next);
        if ntype == oid::UNKNOWN || ntype == ptype {
            continue;
        }
        let (ncategory, npreferred) = types::category_preferred(ntype);
        if ptype == oid::UNKNOWN {
            (ptype, pcategory, ppreferred) = (ntype, ncategory, npreferred);
        } else if ncategory != pcategory {
            return Err((ptype, ntype, i));
        } else if !ppreferred
            && can_coerce(&[ptype], &[ntype], Context::Implicit)
            && !can_coerce(&[ntype], &[ptype], Context::Implicit)
        {
            (ptype, pcategory, ppreferred) = (ntype, ncategory, npreferred);
        }
    }
    Ok(if ptype == oid::UNKNOWN { oid::TEXT } else { ptype })
}

/// `find_typmod_coercion_function`: the function that applies a typmod to a value of the type, and whether it applies to each element of an array.
fn typmod_function(ty: u32) -> Option<(u32, bool)> {
    let (ty, array) = match types::element(ty) {
        0 => (ty, false),
        element => (element, true),
    };
    builtin::cast(ty, ty).filter(|cast| cast.func != 0).map(|cast| (cast.func, array))
}

impl Analyzer<'_> {
    /// `coerce_to_target_type`: the expression cast to the type and the typmod, or `None` if the cast does not exist in the context.
    pub(crate) fn coerce_to_target(
        &mut self,
        expr: Expr,
        target: u32,
        typmod: i32,
        context: Context,
        location: Option<usize>,
    ) -> Result<Option<Expr>> {
        if !can_coerce(&[expr.ty], &[target], context) {
            return Ok(None);
        }
        let input = (expr.ty, expr.typmod);
        let expr = self.coerce(expr, target, typmod, context, location)?;
        // A length cast hides the cast below it, which the analyzer made in the same step, as `hide_coercion_node` does. With no length cast, the cast stays as it is.
        let length = typmod >= 0 && (expr.typmod != typmod || expr.ty != target);
        let hide =
            length && (expr.ty, expr.typmod) != input && !matches!(expr.kind, ExprKind::Const(_));
        let mut expr = self.coerce_typmod(expr, target, typmod, context, location);
        if hide
            && let ExprKind::Func(Func { args, .. }) = &mut expr.kind
            && let Some(arg) = args.first_mut()
        {
            hide_cast(arg);
        }
        Ok(Some(expr))
    }

    /// `coerce_type`: the expression cast to the type. The caller has checked that the cast exists.
    pub(crate) fn coerce(
        &mut self,
        expr: Expr,
        target: u32,
        typmod: i32,
        context: Context,
        location: Option<usize>,
    ) -> Result<Expr> {
        let input = expr.ty;
        if target == input {
            return Ok(expr);
        }
        if matches!(
            target,
            oid::ANY
                | oid::ANYELEMENT
                | oid::ANYNONARRAY
                | oid::ANYCOMPATIBLE
                | oid::ANYCOMPATIBLENONARRAY
        ) {
            return Ok(expr);
        }
        if types::is_polymorphic(target) && input != oid::UNKNOWN {
            return Ok(expr);
        }
        // `coerce_type` keeps the type of a composite value for `record` and for `record[]`, with no `RelabelType`.
        if (target == oid::RECORD && types::is_complex(input))
            || (target == oid::RECORD_ARRAY && types::is_complex(types::element(input)))
        {
            return Ok(expr);
        }
        if input == oid::RECORD && types::is_complex(types::base(target)) {
            return self.coerce_record_to_complex(expr, target, context, location);
        }
        if input == oid::UNKNOWN {
            if let ExprKind::Const(value) = &expr.kind {
                // The input function takes the typmod only for `interval`. The caller applies any other typmod with a length cast.
                let (base, base_typmod) = types::base_typmod(target, typmod);
                let input_typmod = if base == oid::INTERVAL { base_typmod } else { -1 };
                let value = match value {
                    Value::Text(text) => {
                        let text = text.clone();
                        // The place of the literal replaces any place that the input function gives, as `pcb_error_callback` does.
                        self.env.input_at(base, &text, input_typmod, expr.location).map_err(
                            |e| match expr.location {
                                Some(at) => e.with_position(Some(at)),
                                None => e,
                            },
                        )?
                    }
                    _ => Value::Null,
                };
                let constant = Expr::constant(value, base, input_typmod, expr.location);
                return Ok(coerce_to_domain(constant, target, context, location, false));
            }
            if let ExprKind::Param(n) = expr.kind
                && let Some(ty) = self.param_type(n, target, expr.location)?
            {
                return Ok(Expr {
                    kind: ExprKind::Param(n),
                    ty,
                    typmod: -1,
                    location: expr.location,
                });
            }
        }
        let (form, cast) = if context == Context::Explicit {
            (FuncForm::ExplicitCast, CastForm::Explicit)
        } else {
            (FuncForm::ImplicitCast, CastForm::Implicit)
        };
        // A cast to a domain casts to the base type, then checks the constraints of the domain.
        let (base, base_typmod) = types::base_typmod(target, typmod);
        match find_path(target, input, context) {
            Path::None => Err(Error::internal(format!(
                "failed to find conversion function from {} to {}",
                types::name(input),
                types::name(target)
            ))),
            Path::Relabel if base != target => {
                Ok(coerce_to_domain(expr, target, context, location, false))
            }
            Path::Relabel => Ok(Expr {
                kind: ExprKind::Relabel(Box::new(expr), cast),
                ty: target,
                typmod: -1,
                location,
            }),
            Path::ViaIo => {
                let expr = Expr {
                    kind: ExprKind::CoerceViaIo(Box::new(expr), cast),
                    ty: base,
                    typmod: -1,
                    location,
                };
                Ok(coerce_to_domain(expr, target, context, location, true))
            }
            Path::Func(func) => {
                let expr = build_cast(expr, func, base, base_typmod, context, form, location);
                Ok(coerce_to_domain(expr, target, context, location, true))
            }
            // ArrayCoerceExpr with a relabel of each element: the array keeps its values.
            Path::ArrayCoerce
                if find_path(types::element(target), types::element(input), context)
                    == Path::Relabel =>
            {
                Ok(Expr {
                    kind: ExprKind::Relabel(Box::new(expr), cast),
                    ty: target,
                    typmod: -1,
                    location,
                })
            }
            Path::ArrayCoerce => {
                let test = Expr {
                    kind: ExprKind::CaseTest,
                    ty: types::element(input),
                    typmod: expr.typmod,
                    location: None,
                };
                let element = self
                    .coerce_to_target(test, types::element(target), typmod, context, location)?
                    .ok_or_else(|| {
                        Error::internal("failed to coerce array element type as expected")
                    })?;
                let typmod = element.typmod;
                Ok(Expr {
                    kind: ExprKind::ArrayCoerce {
                        arg: Box::new(expr),
                        element: Box::new(element),
                        form: cast,
                    },
                    ty: target,
                    typmod,
                    location,
                })
            }
        }
    }

    /// `coerce_record_to_complex`: a `ROW` expression with each field cast to the type of the column of the composite type. The cast to a domain over a composite type then checks the domain.
    fn coerce_record_to_complex(
        &mut self,
        expr: Expr,
        target: u32,
        context: Context,
        location: Option<usize>,
    ) -> Result<Expr> {
        let at = location.or(expr.location);
        let base = types::base(target);
        let cannot = |detail: Option<String>| {
            let error = Error::new(
                SqlState::CANNOT_COERCE,
                format!("cannot cast type record to {}", types::name(target)),
            );
            match detail {
                Some(detail) => error.with_detail(detail),
                None => error,
            }
            .at_opt(at)
        };
        let ExprKind::Row(args, _) = expr.kind else { return Err(cannot(None)) };
        let columns = self.row_columns(base).ok_or_else(|| cannot(None))?;
        if args.len() < columns.len() {
            return Err(cannot(Some("Input has too few columns.".into())));
        }
        if args.len() > columns.len() {
            return Err(cannot(Some("Input has too many columns.".into())));
        }
        let mut fields = Vec::with_capacity(args.len());
        for (i, (arg, column)) in args.into_iter().zip(&columns).enumerate() {
            let (from, arg_at) = (arg.ty, arg.location);
            let field = self.coerce_to_target(arg, column.ty, column.typmod, context, None)?;
            let Some(field) = field else {
                return Err(Error::new(
                    SqlState::CANNOT_COERCE,
                    format!("cannot cast type {} to {}", types::name(from), types::name(column.ty)),
                )
                .with_detail(format!(
                    "Cannot cast type record to {} in column {}.",
                    types::name(target),
                    i + 1
                ))
                .at_opt(location.or(arg_at)));
            };
            fields.push(field);
        }
        let form =
            if context == Context::Explicit { CastForm::Explicit } else { CastForm::Implicit };
        let row = Expr { kind: ExprKind::Row(fields, form), ty: base, typmod: -1, location };
        Ok(if base == target {
            row
        } else {
            coerce_to_domain(row, target, context, location, false)
        })
    }

    /// `coerce_type_typmod`: the length cast of a type that has a typmod, or a relabel that shows the typmod. The cast shows as explicit in the explicit context.
    pub(crate) fn coerce_typmod(
        &mut self,
        expr: Expr,
        target: u32,
        typmod: i32,
        context: Context,
        location: Option<usize>,
    ) -> Expr {
        let explicit = context == Context::Explicit;
        typmod_cast(expr, target, typmod, context, explicit, location)
    }
}

/// `coerce_type_typmod` with the form of the cast: explicit when `explicit` is true, else implicit.
fn typmod_cast(
    expr: Expr,
    target: u32,
    typmod: i32,
    context: Context,
    explicit: bool,
    location: Option<usize>,
) -> Expr {
    if typmod < 0 || expr.typmod == typmod && expr.ty == target {
        return expr;
    }
    let (form, cast) = if explicit {
        (FuncForm::ExplicitCast, CastForm::Explicit)
    } else {
        (FuncForm::ImplicitCast, CastForm::Implicit)
    };
    match typmod_function(target) {
        Some((func, false)) => build_cast(expr, func, target, typmod, context, form, location),
        // An ArrayCoerceExpr applies the function to each element.
        Some((func, true)) => {
            let ty = types::element(target);
            let test = Expr { kind: ExprKind::CaseTest, ty, typmod: expr.typmod, location: None };
            let element = build_cast(test, func, ty, typmod, context, form, location);
            Expr {
                kind: ExprKind::ArrayCoerce {
                    arg: Box::new(expr),
                    element: Box::new(element),
                    form: cast,
                },
                ty: target,
                typmod,
                location,
            }
        }
        None => {
            let mut expr = expr;
            if let ExprKind::Const(_) = expr.kind {
                expr.typmod = typmod;
                expr
            } else {
                Expr { kind: ExprKind::Relabel(Box::new(expr), cast), ty: target, typmod, location }
            }
        }
    }
}

impl Analyzer<'_> {
    /// `select_common_type`: the type that all the expressions can take, for `CASE`, `COALESCE` and the others that `context` names.
    pub(crate) fn common_type(&self, exprs: &[Expr], context: &str) -> Result<u32> {
        let tys: Vec<u32> = exprs.iter().map(|e| e.ty).collect();
        common_of(&tys).map_err(|(p, n, i)| {
            Error::new(
                SqlState::DATATYPE_MISMATCH,
                format!(
                    "{context} types {} and {} cannot be matched",
                    types::name(p),
                    types::name(n)
                ),
            )
            .at_opt(exprs[i].place())
        })
    }

    /// `coerce_to_common_type`.
    pub(crate) fn coerce_to_common(
        &mut self,
        expr: Expr,
        target: u32,
        context: &str,
    ) -> Result<Expr> {
        if expr.ty == target {
            return Ok(expr);
        }
        if !can_coerce(&[expr.ty], &[target], Context::Implicit) {
            return Err(Error::new(
                SqlState::CANNOT_COERCE,
                format!(
                    "{context} could not convert type {} to {}",
                    types::name(expr.ty),
                    types::name(target)
                ),
            )
            .at_opt(expr.place()));
        }
        self.coerce(expr, target, -1, Context::Implicit, None)
    }

    /// `coerce_to_boolean`: the condition of `construct`, such as `WHERE` or `AND`, cast to `boolean`.
    pub(crate) fn coerce_to_boolean(&mut self, expr: Expr, construct: &str) -> Result<Expr> {
        self.coerce_to_specific(expr, oid::BOOL, construct)
    }

    /// `coerce_to_specific_type`: the expression as a value of the type, with an assignment cast, for a clause such as `LIMIT`. The value cannot be a set.
    pub(crate) fn coerce_to_specific(
        &mut self,
        expr: Expr,
        target: u32,
        construct: &str,
    ) -> Result<Expr> {
        let ty = expr.ty;
        let place = expr.place();
        let coerced = if ty == target {
            Some(expr)
        } else {
            self.coerce_to_target(expr, target, -1, Context::Assignment, None)?
        };
        match coerced {
            Some(expr) if expr.first_set_call().is_some() => Err(Error::new(
                SqlState::DATATYPE_MISMATCH,
                format!("argument of {construct} must not return a set"),
            )
            .at_opt(expr.place())),
            Some(expr) => Ok(expr),
            None => Err(Error::new(
                SqlState::DATATYPE_MISMATCH,
                format!(
                    "argument of {construct} must be type {}, not type {}",
                    types::name(target),
                    types::name(ty)
                ),
            )
            .at_opt(place)),
        }
    }
}

/// `coerce_to_domain`: the expression, which has the base type of the domain `target`, with the typmod of the domain and a `CoerceToDomain` node above it. When `hide` is true, the cast below shows as implicit, as `hide_coercion_node` does. For a type that is not a domain, the expression does not change.
fn coerce_to_domain(
    mut expr: Expr,
    target: u32,
    context: Context,
    location: Option<usize>,
    hide: bool,
) -> Expr {
    let (base, typmod) = types::base_typmod(target, -1);
    if base == target {
        return expr;
    }
    if hide {
        hide_cast(&mut expr);
    }
    let expr = typmod_cast(expr, base, typmod, context, false, location);
    let form = if context == Context::Explicit { CastForm::Explicit } else { CastForm::Implicit };
    Expr { kind: ExprKind::CoerceToDomain(Box::new(expr), form), ty: target, typmod: -1, location }
}

/// `hide_coercion_node`: a cast that the analyzer made shows as implicit.
pub(crate) fn hide_cast(expr: &mut Expr) {
    match &mut expr.kind {
        ExprKind::Func(Func { form, .. })
            if matches!(form, FuncForm::ExplicitCast | FuncForm::ImplicitCast) =>
        {
            *form = FuncForm::ImplicitCast;
        }
        ExprKind::Relabel(_, form)
        | ExprKind::CoerceViaIo(_, form)
        | ExprKind::ArrayCoerce { form, .. }
        | ExprKind::Row(_, form)
        | ExprKind::CoerceToDomain(_, form) => *form = CastForm::Implicit,
        _ => {}
    }
}

/// `build_coercion_expression` for a cast function. A function of two arguments takes the typmod, and one of three also takes true for an explicit cast.
fn build_cast(
    expr: Expr,
    func: u32,
    target: u32,
    typmod: i32,
    context: Context,
    form: FuncForm,
    location: Option<usize>,
) -> Expr {
    let nargs = builtin::proc_by_oid(func).map_or(1, |p| p.nargs);
    let mut args = vec![expr];
    if nargs >= 2 {
        args.push(Expr::constant(Value::Int4(typmod), oid::INT4, -1, None));
    }
    if nargs >= 3 {
        args.push(Expr::constant(Value::Bool(context == Context::Explicit), oid::BOOL, -1, None));
    }
    // A length cast shows the typmod that it applies, as `exprTypmod` reads it from the second argument.
    let typmod = if nargs >= 2 && typmod_function(target).is_some_and(|(f, _)| f == func) {
        typmod
    } else {
        -1
    };
    Expr {
        kind: ExprKind::Func(Func { oid: func, args, form, variadic: false, retset: false }),
        ty: target,
        typmod,
        location,
    }
}

/// A place on an error when there is one.
pub(crate) trait AtOpt {
    fn at_opt(self, location: Option<usize>) -> Self;
}

impl AtOpt for Error {
    fn at_opt(self, location: Option<usize>) -> Error {
        match location {
            Some(at) => self.at(at),
            None => self,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn paths() {
        assert_eq!(find_path(oid::INT8, oid::INT4, Context::Implicit), Path::Func(481));
        assert_eq!(find_path(oid::INT4, oid::INT8, Context::Implicit), Path::None);
        assert_eq!(find_path(oid::INT4, oid::INT8, Context::Assignment), Path::Func(480));
        assert_eq!(find_path(oid::TEXT, oid::VARCHAR, Context::Implicit), Path::Relabel);
        assert_eq!(find_path(oid::TEXT, oid::INT4, Context::Implicit), Path::None);
        assert_eq!(find_path(oid::TEXT, oid::INT4, Context::Assignment), Path::ViaIo);
        assert_eq!(find_path(oid::INT4, oid::TEXT, Context::Explicit), Path::ViaIo);
        assert_eq!(
            find_path(oid::INT8_ARRAY, oid::INT4_ARRAY, Context::Implicit),
            Path::ArrayCoerce
        );
        assert_eq!(find_path(oid::OID_ARRAY, oid::OIDVECTOR, Context::Implicit), Path::ArrayCoerce);
        assert_eq!(find_path(oid::OIDVECTOR, oid::OID_ARRAY, Context::Explicit), Path::None);
        assert!(can_coerce(&[oid::UNKNOWN, oid::INT2], &[oid::INT4, oid::INT4], Context::Implicit));
        assert!(!can_coerce(&[oid::TEXT], &[oid::INT4], Context::Implicit));
        assert_eq!(typmod_function(oid::VARCHAR).map(|(_, a)| a), Some(false));
        assert_eq!(typmod_function(oid::INT4), None);
    }
}