no_mistakes_postgres_engine/catalog/
bounded.rs1use super::{parse_postgres_expression, snapshot::SnapshotIndex};
2pub use no_mistakes_postgres_sql::bound_expr::{canonical_bound_expr, conjuncts_of};
3use no_mistakes_postgres_sql::erased_visit_fn::visit_expressions;
4use no_mistakes_postgres_sql::parse_postgres_sql;
5use sqlparser::ast::{Expr, Statement, Value};
6use std::ops::ControlFlow;
7
8#[derive(Debug, Clone)]
10pub struct BoundedUniqueIndex {
11 pub name: String,
12 pub keys: Vec<Expr>,
13 pub predicate: Vec<Expr>,
14 pub nulls_not_distinct: bool,
15}
16
17pub(super) fn from_snapshot(name: &str, index: &SnapshotIndex) -> Option<BoundedUniqueIndex> {
18 let supported = (index.unique || index.primary)
19 && index.valid
20 && index.ready
21 && index.live.unwrap_or(true)
22 && index.immediate.unwrap_or(true)
23 && index.access_method.eq_ignore_ascii_case("btree")
24 && index
25 .keys
26 .iter()
27 .all(|key| key.ordering_supported.unwrap_or(true));
28 if !supported || index.keys.is_empty() {
29 return None;
30 }
31 let keys = index
32 .keys
33 .iter()
34 .map(|key| {
35 let expr = parse_postgres_expression(&key.expression)?;
36 (!contains_placeholder(&expr)).then(|| canonical_bound_expr(&expr))
37 })
38 .collect::<Option<Vec<_>>>()?;
39 let predicate = match index.predicate.as_deref() {
40 Some(text) => {
41 let expr = parse_postgres_expression(text)?;
42 if contains_placeholder(&expr) {
43 return None;
44 }
45 Some(canonical_bound_expr(&expr))
46 }
47 None => None,
48 };
49 let mut conjuncts = Vec::new();
50 if let Some(predicate) = predicate {
51 conjuncts_of(&predicate, &mut conjuncts);
52 }
53 let nulls_not_distinct = parse_postgres_sql(&index.definition)
54 .ok()
55 .and_then(|statements| statements.into_iter().next())
56 .is_some_and(|statement| {
57 matches!(statement, Statement::CreateIndex(index) if index.nulls_distinct == Some(false))
58 });
59 if conjuncts.is_empty()
61 && !nulls_not_distinct
62 && index
63 .keys
64 .iter()
65 .all(|key| super::names::plain_column(&key.expression).is_some())
66 {
67 return None;
68 }
69 Some(BoundedUniqueIndex {
70 name: name.to_string(),
71 keys,
72 predicate: conjuncts,
73 nulls_not_distinct,
74 })
75}
76
77fn contains_placeholder(expr: &Expr) -> bool {
78 visit_expressions(expr, |child| {
79 if matches!(child, Expr::Value(value) if matches!(value.value, Value::Placeholder(_))) {
80 ControlFlow::Break(())
81 } else {
82 ControlFlow::Continue(())
83 }
84 })
85 .is_break()
86}