uqa-execution 0.6.0

Volcano physical operators with row-batch pipelines
Documentation
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! `pg_get_constraintdef` and the domain rows of `pg_constraint`, as `pg_get_constraintdef_worker` prints definitions and `domainAddCheckConstraint` records them.

use std::fmt::Write;

use uqa_core::Value;
use uqa_sql::ast::{ForeignKeyAction, ForeignKeyMatch};
use uqa_sql::expr::quote_ident;
use uqa_sql::SQLError;

use crate::catalog::context::CatalogContext;
use crate::catalog::tuples::constraint::ConstraintTuple;
use crate::catalog::{CatalogReadView, RelationNameResolution};

use super::super::helpers::constraints::{
    constraint_catalog_row_by_oid, domain_constraint_by_oid, ConstraintCatalogKind,
    ConstraintCatalogRow, DomainConstraint,
};
use super::super::helpers::oids::namespace_oid;
use super::super::helpers::rows::{bool_value, int_value, row, str_value};

pub fn pg_get_constraintdef_value(
    context: &CatalogContext<'_>,
    arguments: &[Value],
) -> Result<Value, SQLError> {
    let (oid, pretty) = match arguments {
        [oid] => (oid, &Value::Bool(false)),
        [oid, pretty] => (oid, pretty),
        _ => {
            return Err(SQLError::BadArity {
                name: "pg_get_constraintdef".into(),
                expected: "1 or 2".into(),
                actual: arguments.len(),
            })
        }
    };
    let (Value::Int(oid), Value::Bool(pretty)) = (oid, pretty) else {
        if matches!(oid, Value::Null) || matches!(pretty, Value::Null) {
            return Ok(Value::Null);
        }
        return Err(SQLError::TypeMismatch(
            "pg_get_constraintdef requires oid and boolean arguments".into(),
        ));
    };
    let catalog = context.catalog_read_view();
    let resolution = context.session_execution_view().relation_name_resolution();
    if let Some(constraint) = constraint_catalog_row_by_oid(&catalog, &resolution, *oid)? {
        return relation_constraint_definition(context, &catalog, &resolution, constraint, *pretty)
            .map(Value::Str);
    }
    domain_constraint_definition(context, &catalog, &resolution, *oid, *pretty)
        .map(|definition| definition.map_or(Value::Null, Value::Str))
}

fn relation_constraint_definition(
    context: &CatalogContext<'_>,
    catalog: &CatalogReadView,
    resolution: &RelationNameResolution,
    constraint: &ConstraintCatalogRow,
    pretty: bool,
) -> Result<String, SQLError> {
    let mut definition = match constraint.kind {
        ConstraintCatalogKind::NotNull => {
            let column = constraint
                .columns
                .first()
                .ok_or_else(|| SQLError::Internal("NOT NULL constraint has no column".into()))?;
            format!("NOT NULL {}", quote_ident(&column.name))
        }
        ConstraintCatalogKind::Check => format!(
            "CHECK ({})",
            super::super::expression_nodes::constraint_text(context, catalog, constraint, pretty)?
        ),
        ConstraintCatalogKind::PrimaryKey | ConstraintCatalogKind::Unique { .. } => {
            key_constraint_definition(catalog, constraint)?
        }
        ConstraintCatalogKind::ForeignKey => {
            foreign_key_definition(catalog, resolution, constraint)?
        }
    };
    if constraint.state.no_inherit()
        && matches!(
            constraint.kind,
            ConstraintCatalogKind::NotNull | ConstraintCatalogKind::Check
        )
    {
        definition.push_str(" NO INHERIT");
    }
    if constraint.state.deferrable() {
        definition.push_str(" DEFERRABLE");
    }
    if constraint.state.initially_deferred() {
        definition.push_str(" INITIALLY DEFERRED");
    }
    // Validation is irrelevant for a constraint that is not enforced.
    if !constraint.state.enforced() {
        definition.push_str(" NOT ENFORCED");
    } else if !constraint.state.validated() {
        definition.push_str(" NOT VALID");
    }
    Ok(definition)
}

/// `PRIMARY KEY` or `UNIQUE` with its key columns and the non-key columns its index includes.
fn key_constraint_definition(
    catalog: &CatalogReadView,
    constraint: &ConstraintCatalogRow,
) -> Result<String, SQLError> {
    let mut definition = if constraint.kind == ConstraintCatalogKind::PrimaryKey {
        "PRIMARY KEY ".to_string()
    } else if constraint.kind.nulls_distinct() == Some(false) {
        "UNIQUE NULLS NOT DISTINCT ".to_string()
    } else {
        "UNIQUE ".to_string()
    };
    let mut keys = constraint
        .columns
        .iter()
        .map(|column| quote_ident(&column.name))
        .collect::<Vec<_>>();
    if constraint.period {
        if let Some(last) = keys.last_mut() {
            last.push_str(" WITHOUT OVERLAPS");
        }
    }
    write!(definition, "({})", keys.join(", ")).expect("writing to a String cannot fail");
    let index_oid = super::catalog_index_for_constraint(catalog, constraint.object_id)?
        .map_or(0, super::CatalogIndexRelation::oid);
    if let Some(index) = super::catalog_index_by_oid(catalog, index_oid)? {
        let included = &index.definition.included_columns;
        if !included.is_empty() {
            let included = included
                .iter()
                .map(|name| quote_ident(name))
                .collect::<Vec<_>>();
            write!(definition, " INCLUDE ({})", included.join(", "))
                .expect("writing to a String cannot fail");
        }
    }
    Ok(definition)
}

/// `FOREIGN KEY` with the referenced relation named as the search path finds it, its match type and its referential actions.
fn foreign_key_definition(
    catalog: &CatalogReadView,
    resolution: &RelationNameResolution,
    constraint: &ConstraintCatalogRow,
) -> Result<String, SQLError> {
    let foreign_key = constraint
        .foreign_key
        .as_ref()
        .ok_or_else(|| SQLError::Internal("FOREIGN KEY constraint has no referenced key".into()))?;
    let referenced_name = format!(
        "{}.{}",
        quote_ident(&foreign_key.schema),
        quote_ident(&foreign_key.table)
    );
    let mut bound = resolution.clone();
    bound.set_lookup_mode(crate::catalog::RelationLookupMode::Bound);
    let referenced = catalog
        .table(&bound, &referenced_name)?
        .ok_or_else(|| SQLError::UnknownTable(referenced_name.clone()))?;
    let mut remote = foreign_key
        .column_ordinals
        .iter()
        .map(|ordinal| {
            uqa_sql::catalog::relation_attributes::column_by_number(&referenced.columns, *ordinal)
                .map(|column| quote_ident(&column.name))
                .ok_or_else(|| SQLError::Internal("referenced key column disappeared".into()))
        })
        .collect::<Result<Vec<_>, _>>()?;
    let mut local = constraint
        .columns
        .iter()
        .map(|column| quote_ident(&column.name))
        .collect::<Vec<_>>();
    if constraint.period {
        for keys in [&mut local, &mut remote] {
            if let Some(last) = keys.last_mut() {
                *last = format!("PERIOD {last}");
            }
        }
    }
    let mut definition = format!(
        "FOREIGN KEY ({}) REFERENCES {}({})",
        local.join(", "),
        relation_display_name(catalog, resolution, &foreign_key.schema, &foreign_key.table)?,
        remote.join(", ")
    );
    if foreign_key.match_type == ForeignKeyMatch::Full {
        definition.push_str(" MATCH FULL");
    }
    if let Some(action) = foreign_key_action(foreign_key.on_update) {
        write!(definition, " ON UPDATE {action}").expect("writing to a String cannot fail");
    }
    if let Some(action) = foreign_key_action(foreign_key.on_delete) {
        write!(definition, " ON DELETE {action}").expect("writing to a String cannot fail");
        if !foreign_key.delete_set_ordinals.is_empty() {
            let columns = foreign_key
                .delete_set_ordinals
                .iter()
                .map(|ordinal| {
                    constraint
                        .columns
                        .iter()
                        .find(|column| column.table_ordinal == *ordinal)
                        .map(|column| quote_ident(&column.name))
                        .ok_or_else(|| {
                            SQLError::Internal("foreign-key delete column disappeared".into())
                        })
                })
                .collect::<Result<Vec<_>, _>>()?;
            write!(definition, " ({})", columns.join(", "))
                .expect("writing to a String cannot fail");
        }
    }
    Ok(definition)
}

const fn foreign_key_action(action: ForeignKeyAction) -> Option<&'static str> {
    match action {
        ForeignKeyAction::NoAction => None,
        ForeignKeyAction::Restrict => Some("RESTRICT"),
        ForeignKeyAction::Cascade => Some("CASCADE"),
        ForeignKeyAction::SetNull => Some("SET NULL"),
        ForeignKeyAction::SetDefault => Some("SET DEFAULT"),
    }
}

/// `generate_relation_name`: a relation the search path finds by its bare name prints unqualified.
fn relation_display_name(
    catalog: &CatalogReadView,
    resolution: &RelationNameResolution,
    schema: &str,
    table: &str,
) -> Result<String, SQLError> {
    let canonical = format!("{}.{}", quote_ident(schema), quote_ident(table));
    let visible = catalog
        .relation_kind_resolution(resolution, &quote_ident(table))?
        .into_found()
        .is_some_and(|(found, _)| {
            found == canonical
                || uqa_core::RelationIdentity::from_legacy_name(&found)
                    .is_ok_and(|identity| identity.schema == schema && identity.name == table)
        });
    Ok(if visible {
        quote_ident(table)
    } else {
        canonical
    })
}

fn domain_constraint_definition(
    context: &CatalogContext<'_>,
    catalog: &CatalogReadView,
    resolution: &RelationNameResolution,
    oid: i64,
    pretty: bool,
) -> Result<Option<String>, SQLError> {
    match domain_constraint_by_oid(catalog, resolution, oid)? {
        Some(DomainConstraint::NotNull) => Ok(Some("NOT NULL".into())),
        Some(DomainConstraint::Check(domain, check)) => {
            let node = super::super::expression_nodes::domain_node(
                context,
                catalog,
                domain,
                &check.expression,
            )?;
            let expression = super::super::expression_nodes::render(
                &CatalogContext {
                    catalog,
                    ..*context
                },
                &[],
                &node.into(),
                pretty,
            )?;
            let validation = if check.validated { "" } else { " NOT VALID" };
            Ok(Some(format!("CHECK ({expression}){validation}")))
        }
        None => Ok(None),
    }
}

/// `pg_constraint` rows of domain constraints: they constrain a type rather than a relation.
pub fn domain_constraint_tuples(
    context: Option<&CatalogContext<'_>>,
    catalog: &CatalogReadView,
    request: &super::super::CatalogRequest,
) -> Result<Vec<ConstraintTuple>, SQLError> {
    let mut rows = Vec::new();
    for domain in catalog.domains() {
        let _ =
            visit_domain_constraint_tuples(context, catalog, domain, request, &mut |_, tuple| {
                rows.push(tuple);
                Ok(std::ops::ControlFlow::Continue(()))
            })?;
    }
    Ok(rows)
}

/// Construct one domain's tuples with their immutable logical identities. Publication callers can consume each typed row without materializing unrelated domains or deriving identity from a rendered field; a successful break does not inspect later constraints.
pub(crate) fn visit_domain_constraint_tuples(
    context: Option<&CatalogContext<'_>>,
    catalog: &CatalogReadView,
    domain: &uqa_sql::catalog::domain::StoredDomain,
    request: &super::super::CatalogRequest,
    visitor: &mut dyn FnMut(
        uqa_core::catalog_identity::CatalogObjectIdentity,
        ConstraintTuple,
    ) -> Result<std::ops::ControlFlow<()>, SQLError>,
) -> Result<std::ops::ControlFlow<()>, SQLError> {
    let namespace = namespace_oid(catalog, &domain.identity.schema);
    let not_null = domain.definition.not_null.iter().map(|constraint| {
        (
            constraint.name.as_deref(),
            constraint.catalog_identity,
            "n",
            true,
            None,
        )
    });
    let checks = domain.definition.checks.iter().map(|constraint| {
        (
            constraint.name.as_deref(),
            constraint.catalog_identity,
            "c",
            constraint.validated,
            Some(&constraint.expression),
        )
    });
    for (name, identity, kind, validated, expression) in not_null.chain(checks) {
        let (Some(name), Some(identity)) = (name, identity) else {
            return Err(SQLError::Internal(format!(
                "constraint of domain {} has no catalog identity",
                domain.identity.qualified_name()
            )));
        };
        let expression = match (
            context,
            expression
                .filter(|_| request.includes("conbin") && request.matches_name("conname", name)),
        ) {
            (Some(context), Some(expression)) => Some(super::super::expression_nodes::domain_node(
                context, catalog, domain, expression,
            )?),
            _ => None,
        };
        let fields = row([
            ("oid", int_value(identity.oid)),
            ("conname", str_value(name.to_string())),
            ("connamespace", int_value(namespace)),
            ("contype", str_value(kind)),
            ("condeferrable", bool_value(false)),
            ("condeferred", bool_value(false)),
            ("conenforced", bool_value(true)),
            ("convalidated", bool_value(validated)),
            ("conrelid", int_value(0)),
            ("contypid", int_value(i64::from(domain.oid))),
            ("conindid", int_value(0)),
            ("conparentid", int_value(0)),
            ("confrelid", int_value(0)),
            ("confupdtype", str_value(" ")),
            ("confdeltype", str_value(" ")),
            ("confmatchtype", str_value(" ")),
            ("conislocal", bool_value(true)),
            ("coninhcount", int_value(0)),
            ("connoinherit", bool_value(false)),
            ("conperiod", bool_value(false)),
            ("conkey", Value::Null),
            ("confkey", Value::Null),
            ("conpfeqop", Value::Null),
            ("conppeqop", Value::Null),
            ("conffeqop", Value::Null),
            ("conexclop", Value::Null),
        ]);
        if visitor(identity, ConstraintTuple::new(fields, expression))?.is_break() {
            return Ok(std::ops::ControlFlow::Break(()));
        }
    }
    Ok(std::ops::ControlFlow::Continue(()))
}

#[cfg(test)]
mod tests;