Skip to main content

no_mistakes_postgres_engine/catalog/
resolve.rs

1use super::expressions::order_prefix_matches_skipping_pinned;
2use super::{
3    names::{normalize_identifier, normalize_table_name, plain_column},
4    normalize_expression, order_prefix_matches, ArbiterTable, CanonicalIndex, CanonicalOrderKey,
5    ResolvedArbiter, SchemaCatalog,
6};
7impl SchemaCatalog {
8    pub fn resolve_columns(
9        &self,
10        table: &str,
11        target: &[String],
12        predicate: Option<&str>,
13    ) -> ResolvedArbiter {
14        let Some(table) = self.arbiter_table(table) else {
15            return ResolvedArbiter::Unresolved;
16        };
17        let mut target = target
18            .iter()
19            .map(|key| normalize_expression(key))
20            .collect::<Vec<_>>();
21        target.sort();
22        resolve_candidates(
23            table
24                .indexes
25                .iter()
26                .filter(|index| {
27                    index.predicate.as_deref() == predicate.map(normalize_expression).as_deref()
28                })
29                .filter(|index| {
30                    let mut keys = index
31                        .keys
32                        .iter()
33                        .map(|key| normalize_expression(&key.expression))
34                        .collect::<Vec<_>>();
35                    keys.sort();
36                    keys == target
37                })
38                .cloned()
39                .collect(),
40        )
41    }
42    pub fn resolve_constraint(&self, table: &str, name: &str) -> ResolvedArbiter {
43        let Some(table) = self.arbiter_table(table) else {
44            return ResolvedArbiter::Unresolved;
45        };
46        let name = normalize_identifier(name);
47        let direct: Vec<_> = table
48            .indexes
49            .iter()
50            .filter(|index| index.constraint_backed && normalize_identifier(&index.name) == name)
51            .cloned()
52            .collect();
53        if !direct.is_empty() {
54            return resolve_candidates(direct);
55        }
56        let Some(columns) = table.unique_constraints.get(&name) else {
57            return ResolvedArbiter::Unresolved;
58        };
59        resolve_candidates(
60            table
61                .indexes
62                .iter()
63                .filter(|index| {
64                    index.constraint_backed
65                        && index
66                            .keys
67                            .iter()
68                            .map(|key| normalize_expression(&key.expression))
69                            .collect::<Vec<_>>()
70                            == *columns
71                })
72                .cloned()
73                .collect(),
74        )
75    }
76    pub fn has_canonical_prefix(&self, table: &str, order: &[CanonicalOrderKey]) -> bool {
77        self.arbiter_table(table).is_some_and(|table| {
78            table
79                .indexes
80                .iter()
81                .filter(|index| index.ordering_supported && index.predicate.is_none())
82                .any(|index| order_prefix_matches(order, &index.keys, true))
83        })
84    }
85    pub fn has_canonical_prefix_for_qualifiers(
86        &self,
87        table: &str,
88        qualifiers: &[String],
89        order: &[CanonicalOrderKey],
90        pinned: &[String],
91    ) -> bool {
92        self.arbiter_table(table).is_some_and(|table| {
93            table
94                .indexes
95                .iter()
96                .filter(|index| index.ordering_supported && index.predicate.is_none())
97                .any(|index| {
98                    order_prefix_matches_skipping_pinned(order, &index.keys, qualifiers, pinned)
99                })
100        })
101    }
102    /// Column sets that hold at most one row per value: valid, ready, live, immediate,
103    /// non-partial unique or primary indexes whose keys are all plain columns.
104    ///
105    /// A partial index only covers some rows and a deferrable one may hold duplicates
106    /// inside a transaction, so neither proves uniqueness. Expression keys are not columns.
107    pub fn unique_keys(&self, table: &str) -> Vec<Vec<String>> {
108        // The same relation `relation()` finds, so a bare name reaches a schema-qualified entry.
109        let Some(table) = self
110            .relation(table)
111            .and_then(|relation| self.arbiter_table(&relation.name))
112        else {
113            return Vec::new();
114        };
115        table
116            .indexes
117            .iter()
118            // A key whose operator class or collation is not the column's default may treat
119            // values as distinct that an equality on the column treats as equal.
120            .filter(|index| {
121                index.immediate && index.predicate.is_none() && index.ordering_supported
122            })
123            .filter_map(|index| {
124                index
125                    .keys
126                    .iter()
127                    .map(|key| plain_column(&key.expression))
128                    .collect::<Option<Vec<_>>>()
129            })
130            .collect()
131    }
132    /// Preparsed unique index evidence for bounded-row proofs, including partial and expression
133    /// indexes. Ordinary `unique_keys` intentionally retains its unconditional column contract.
134    pub fn bounded_unique_indexes(&self, table: &str) -> &[super::BoundedUniqueIndex] {
135        self.relation(table)
136            .and_then(|relation| self.arbiter_table(&relation.name))
137            .map_or(&[], |table| table.bounded_indexes.as_slice())
138    }
139    /// Whether equality on `columns` holds `table` to at most one row: some unique key of
140    /// [`Self::unique_keys`] lies wholly among them.
141    pub fn columns_pin_one_row(&self, table: &str, columns: &[String]) -> bool {
142        let pinned: Vec<String> = columns.iter().map(|c| normalize_identifier(c)).collect();
143        self.unique_keys(table)
144            .iter()
145            .any(|key| !key.is_empty() && key.iter().all(|column| pinned.contains(column)))
146    }
147    /// Whether `column` of a base table cannot hold NULL. `ctid` never does.
148    /// Any other column uses the base-table identity, so a view that shares the name does not count.
149    pub fn column_is_not_null(&self, table: &str, column: &str) -> bool {
150        column == "ctid"
151            || self.bounded_relation(table).is_some_and(|table| {
152                table
153                    .columns
154                    .iter()
155                    .any(|candidate| candidate.name == column && !candidate.nullable)
156            })
157    }
158    fn arbiter_table(&self, table: &str) -> Option<&ArbiterTable> {
159        let key = normalize_table_name(table);
160        self.tables.get(&key).or_else(|| {
161            let schema = self.schema.as_ref()?;
162            let schema_identifier = format!("\"{}\"", schema.replace('"', "\"\""));
163            let prefix = format!("{}.", normalize_table_name(&schema_identifier));
164            self.tables.get(key.strip_prefix(&prefix)?)
165        })
166    }
167}
168fn resolve_candidates(candidates: Vec<CanonicalIndex>) -> ResolvedArbiter {
169    if candidates
170        .iter()
171        .any(|index| !index.immediate || !index.ordering_supported)
172    {
173        return ResolvedArbiter::Unresolved;
174    }
175    let Some(first) = candidates.first() else {
176        return ResolvedArbiter::Unresolved;
177    };
178    if candidates
179        .iter()
180        .all(|candidate| candidate.keys == first.keys)
181    {
182        ResolvedArbiter::Exact(first.clone())
183    } else {
184        ResolvedArbiter::Ambiguous
185    }
186}