uqa-execution 0.6.2

Volcano physical operators with row-batch pipelines
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
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Index relation and catalog projection.

use uqa_core::Value;
use uqa_sql::{ResultRow, SQLError};

use crate::catalog::index::{index_definition, IndexDefinition};
use crate::catalog::{CatalogReadView, RelationNameResolution};
use uqa_core::RelationIdentity;

use super::super::helpers::index_definitions::{index_columns, indexdef};
use super::super::helpers::oids::{relation_oid, split_schema_name};
use super::super::helpers::rows::{
    bool_value, catalog_int2vector, catalog_usize, int_value, row, str_value,
};
use super::table_relation_oid_from;

#[derive(Debug, Clone)]
pub struct CatalogIndexRelation {
    pub relation: RelationIdentity,
    pub table_name: String,
    pub index_type: String,
    pub columns: Vec<uqa_sql::ast::IndexKey>,
    pub definition: IndexDefinition,
    pub primary: bool,
    pub relkind: &'static str,
    pub is_partition: bool,
    pub has_children: bool,
    pub parent_index_oid: Option<i64>,
}

impl CatalogIndexRelation {
    pub fn oid(&self) -> i64 {
        self.definition.catalog.as_ref().map_or_else(
            || relation_oid(self.relkind, &self.relation.schema, &self.relation.name),
            |catalog| catalog.identity.oid,
        )
    }

    /// Stored key types and included-column types define both `pg_attribute` and storage dependencies.
    pub(crate) fn attributes(
        &self,
        table_columns: &[uqa_sql::ast::ColumnDef],
        columns_declared: bool,
    ) -> Result<Vec<uqa_sql::ast::ColumnDef>, SQLError> {
        let mut columns =
            Vec::with_capacity(self.columns.len() + self.definition.included_columns.len());
        for (position, key) in self.columns.iter().enumerate() {
            let source = key
                .column()
                .and_then(|name| table_columns.iter().find(|column| column.name == name));
            let name = self
                .definition
                .key_names
                .get(position)
                .map(String::as_str)
                .or_else(|| key.column())
                .unwrap_or("expr");
            let ty = self
                .definition
                .key_types
                .get(position)
                .or_else(|| source.map(|column| &column.ty))
                // Document tables have no declared row schema. Their plain fields
                // use the same text catalog type as SQL index binding; predecessor
                // and direct-API declarations need not store key_types.
                .or_else(|| {
                    (!columns_declared && table_columns.is_empty() && key.column().is_some())
                        .then_some(&uqa_sql::ast::ColumnType::Text)
                })
                .cloned()
                .ok_or_else(|| {
                    SQLError::Internal("missing expression index attribute type".into())
                })?;
            columns.push(uqa_sql::ast::ColumnDef::nullable(name, ty));
        }
        for (position, name) in self.definition.included_columns.iter().enumerate() {
            let ty = table_columns
                .iter()
                .find(|column| column.name == *name)
                .map(|column| &column.ty)
                .or_else(|| {
                    (!columns_declared && table_columns.is_empty())
                        .then_some(&uqa_sql::ast::ColumnType::Text)
                })
                .ok_or_else(|| SQLError::UnknownColumn(name.clone()))?;
            let attribute_name = self
                .definition
                .key_names
                .get(self.columns.len() + position)
                .unwrap_or(name);
            columns.push(uqa_sql::ast::ColumnDef::nullable(
                attribute_name,
                ty.clone(),
            ));
        }
        Ok(columns)
    }
}

#[cfg(test)]
mod attributes_tests;
mod cache;
pub(crate) mod legacy;
pub(in crate::catalog) use cache::IndexRelations;
pub(crate) use cache::{catalog_index_by_name, catalog_index_by_oid, catalog_index_for_constraint};

pub fn catalog_index_relations<'a>(
    catalog: &'a CatalogReadView,
    _resolution: &RelationNameResolution,
) -> Result<&'a [CatalogIndexRelation], SQLError> {
    cache::catalog_index_relations(catalog)
}

fn build_index_relations(catalog: &CatalogReadView) -> Result<Vec<CatalogIndexRelation>, SQLError> {
    let mut rows = Vec::new();
    let mut addresses = std::collections::BTreeMap::new();
    let mut parents = std::collections::BTreeSet::new();
    for row in catalog.catalog_indexes() {
        #[cfg(test)]
        cache::record_decode();
        let definition =
            index_definition(row).map_err(|error| SQLError::Internal(error.to_string()))?;
        let identity = definition.catalog.as_ref().ok_or_else(|| {
            SQLError::Internal(format!(
                "index `{}` has no catalog identity",
                row.relation.qualified_name()
            ))
        })?;
        addresses.insert(identity.identity.object_id, identity.identity.oid);
        parents.extend(definition.relationships.parent_index);
        rows.push((row, definition));
    }
    rows.into_iter()
        .map(|(row, definition)| {
            let table =
                RelationIdentity::from_legacy_name(&row.table_name).map_err(SQLError::Internal)?;
            let table = catalog
                .snapshot()
                .tables
                .get(&table)
                .ok_or_else(|| SQLError::UnknownTable(row.table_name.clone()))?;
            let identity = definition
                .catalog
                .as_ref()
                .expect("validated index identity");
            identity
                .validate(table.object_id)
                .map_err(|error| SQLError::Internal(error.to_string()))?;
            definition
                .relationships
                .validate(identity.identity.object_id)
                .map_err(|error| SQLError::Internal(error.to_string()))?;
            let primary = if let Some(owner) = definition.relationships.owning_constraint {
                let key = table
                    .keys
                    .iter()
                    .find(|key| key.catalog_identity.is_some_and(|id| id.object_id == owner))
                    .ok_or_else(|| {
                        SQLError::Internal(format!(
                            "index `{}` has no owning constraint",
                            row.relation.qualified_name()
                        ))
                    })?;
                key.kind == uqa_sql::ast::TableKeyConstraintKind::PrimaryKey
            } else {
                false
            };
            let parent_index_oid = definition
                .relationships
                .parent_index
                .map(|parent| {
                    addresses.get(&parent).copied().ok_or_else(|| {
                        SQLError::Internal(format!(
                            "index `{}` has no parent index",
                            row.relation.qualified_name()
                        ))
                    })
                })
                .transpose()?;
            Ok(CatalogIndexRelation {
                relation: row.relation.clone(),
                table_name: row.table_name.clone(),
                index_type: row.index_type.clone(),
                columns: index_columns(&row.columns_json)?,
                primary,
                relkind: if table.hierarchy.partition_spec.is_some() {
                    "I"
                } else {
                    "i"
                },
                is_partition: parent_index_oid.is_some(),
                has_children: parents.contains(&identity.identity.object_id),
                parent_index_oid,
                definition,
            })
        })
        .collect()
}

pub fn index_access_method_oid(method: &str) -> i64 {
    match method.to_ascii_lowercase().as_str() {
        "" | "btree" => 403,
        "hash" => 405,
        "gist" => 783,
        "gin" => 2_742,
        "spgist" => 4_000,
        "brin" => 3_580,
        _ => 0,
    }
}

fn index_key_ordinals(
    index: &CatalogIndexRelation,
    table_cols: &[uqa_sql::ast::ColumnDef],
) -> Result<Vec<i64>, SQLError> {
    index
        .columns
        .iter()
        .map(uqa_sql::ast::IndexKey::column)
        .chain(
            index
                .definition
                .included_columns
                .iter()
                .map(|name| Some(name.as_str())),
        )
        .map(|column| {
            column
                .and_then(|name| table_cols.iter().position(|item| item.name == name))
                .map(|position| {
                    super::super::helpers::rows::column_ordinal(position, &table_cols[position])
                })
                .transpose()
                .map(|ordinal| ordinal.unwrap_or(0))
        })
        .collect()
}

pub fn build_pg_index(
    context: &crate::catalog::context::CatalogContext<'_>,
    catalog: &CatalogReadView,
    resolution: &RelationNameResolution,
    request: &super::super::CatalogRequest,
) -> Result<Vec<ResultRow>, SQLError> {
    let mut rows = Vec::new();
    for index in catalog_index_relations(catalog, resolution)? {
        let table_cols = &catalog
            .table(resolution, &index.table_name)?
            .ok_or_else(|| SQLError::UnknownTable(index.table_name.clone()))?
            .columns;
        let keys = index_key_ordinals(index, table_cols)?;
        let expressions = index
            .columns
            .iter()
            .filter_map(|key| match key {
                uqa_sql::ast::IndexKey::Expression(expression) => Some(expression.as_ref()),
                uqa_sql::ast::IndexKey::Column(_) => None,
            })
            .filter(|_| request.includes("indexprs"))
            .map(|expression| {
                super::super::expression_nodes::encode(
                    context, catalog, table_cols, None, expression, None,
                )
                .map(uqa_sql::catalog::node_tree::Field::from)
            })
            .collect::<Result<Vec<_>, _>>()?;
        let column_count = catalog_usize(index.columns.len(), "pg_index column count")?;
        let total_count = catalog_usize(
            index.columns.len() + index.definition.included_columns.len(),
            "pg_index total column count",
        )?;
        rows.push(row([
            ("indexrelid", int_value(index.oid())),
            (
                "indrelid",
                int_value(table_relation_oid_from(
                    catalog,
                    resolution,
                    &index.table_name,
                )?),
            ),
            ("indnatts", int_value(total_count)),
            ("indnkeyatts", int_value(column_count)),
            ("indisunique", bool_value(index.definition.unique)),
            (
                "indnullsnotdistinct",
                bool_value(index.definition.nulls_not_distinct),
            ),
            ("indisprimary", bool_value(index.primary)),
            ("indisexclusion", bool_value(false)),
            ("indimmediate", bool_value(true)),
            ("indisclustered", bool_value(false)),
            ("indisvalid", bool_value(true)),
            ("indcheckxmin", bool_value(false)),
            ("indisready", bool_value(true)),
            ("indislive", bool_value(true)),
            ("indisreplident", bool_value(false)),
            (
                "indkey",
                catalog_int2vector(
                    keys.into_iter().map(Value::Int).collect(),
                    "pg_index.indkey",
                )?,
            ),
            ("indcollation", Value::Null),
            ("indclass", Value::Null),
            ("indoption", index_options(index)?),
            (
                "indexprs",
                if expressions.is_empty() {
                    Value::Null
                } else {
                    Value::Str(uqa_sql::catalog::node_tree::Field::List(expressions).to_string())
                },
            ),
            (
                "indpred",
                index
                    .definition
                    .predicate
                    .as_deref()
                    .filter(|_| request.includes("indpred"))
                    .map(|predicate| {
                        super::super::expression_nodes::encode(
                            context,
                            catalog,
                            table_cols,
                            None,
                            predicate,
                            Some(&uqa_sql::ColumnType::Boolean),
                        )
                        .map(|node| node.to_string())
                    })
                    .transpose()?
                    .map_or(Value::Null, Value::Str),
            ),
        ]));
    }
    Ok(rows)
}

fn index_options(index: &CatalogIndexRelation) -> Result<Value, SQLError> {
    catalog_int2vector(
        (0..index.columns.len())
            .map(|position| {
                let order = index
                    .definition
                    .column_order
                    .get(position)
                    .copied()
                    .unwrap_or_default();
                Value::Int(i64::from(order.descending) + 2 * i64::from(order.nulls_first))
            })
            .collect(),
        "pg_index.indoption",
    )
}

pub fn build_pg_indexes(
    output: Option<&dyn uqa_sql::expr::EngineHook>,
    catalog: &CatalogReadView,
    resolution: &RelationNameResolution,
) -> Result<Vec<ResultRow>, SQLError> {
    let mut rows = Vec::new();
    for index in catalog_index_relations(catalog, resolution)? {
        let (schema, table) = split_schema_name(&index.table_name)?;
        let qualified_table = format!(
            "{}.{}",
            uqa_sql::expr::quote_ident(if schema.starts_with("pg_temp_") {
                "pg_temp"
            } else {
                &schema
            }),
            uqa_sql::expr::quote_ident(&table)
        );
        let index_target = if index.relkind == "I" {
            format!("ONLY {qualified_table}")
        } else {
            qualified_table
        };
        rows.push(row([
            ("schemaname", str_value(schema)),
            ("tablename", str_value(table.clone())),
            ("indexname", str_value(index.relation.name.clone())),
            ("tablespace", Value::Null),
            (
                "indexdef",
                str_value(indexdef(
                    output,
                    catalog,
                    resolution,
                    index,
                    &index_target,
                    false,
                )?),
            ),
        ]));
    }
    Ok(rows)
}