uqa-sql 0.6.3

PostgreSQL-compatible SQL compiler built on libpg_query
Documentation
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Typed diagnostic properties retain construction leases until the final renderer releases them.

use crate::SQLError;
use uqa_core::memory::{Produced, ProductionControl, ProductionVec};

#[cfg(test)]
mod tests;

/// Native optimizer estimates, independent of measurements from an invocation.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ExplainPlanEstimate {
    pub startup: f64,
    pub total: f64,
    pub rows: f64,
    pub width: Option<u64>,
}

/// One native query or source estimate from the root's original lexical traversal. Parent indices describe this captured plan, not a runtime operator identity.
#[derive(Debug)]
pub struct ExplainNodeEstimate {
    pub parent: Option<usize>,
    pub kind: &'static str,
    pub relation: Option<String>,
    pub estimate: ExplainPlanEstimate,
}

/// Accumulated work at an executed native plan boundary. Renderers divide rows and durations by completed loops; an unexecuted boundary retains zero loops.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ExplainNodeMetrics {
    pub rows: u64,
    pub loops: u64,
    pub startup: std::time::Duration,
    pub total: std::time::Duration,
}

/// One physical source or pipeline instance observed by the invocation. Its display index is independent of the cost tree.
#[derive(Debug, Clone, Copy)]
pub struct ExplainNodeExecution {
    pub kind: &'static str,
    pub io: uqa_core::io_usage::IOUsage,
    pub metrics: ExplainNodeMetrics,
}

/// Actual `DataRow` payload construction, excluding transport headers and network I/O.
#[derive(Debug, Clone, Copy, Default)]
pub struct ExplainSerializationMetrics {
    pub bytes: u64,
    pub elapsed: std::time::Duration,
    pub io: uqa_core::io_usage::IOUsage,
}

/// Native planning work captured before execution, with the session clock policy at its completion boundary.
#[derive(Debug, Clone, Copy, Default)]
pub struct ExplainPlanningMetrics {
    pub io: uqa_core::io_usage::IOUsage,
    pub io_timing: bool,
    pub memory: Option<ExplainPlanningMemory>,
}

/// Live exposed executable and resident constant storage before execution. Used bytes exclude unused container capacity; allocated bytes include it. Separately owned analysis/catalog and spill-file services, opaque dependency allocations and allocator bookkeeping are outside this observation. Neither quantity is a process total, execution peak or estimate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExplainPlanningMemory {
    pub used_bytes: usize,
    pub allocated_bytes: usize,
}

/// Physical diagnostic values keep numeric primitives inline and retain only admitted containers and copied text. Field names and fixed labels borrow static definitions.
#[derive(Debug)]
pub enum ExplainValue {
    Null,
    Bool(bool),
    Unsigned(u64),
    Float(f64),
    Label(&'static str),
    Text(Produced<String>),
    Object(Produced<Vec<(&'static str, Self)>>),
}

pub struct ExplainObject<'a> {
    fields: ProductionVec<'a, (&'static str, ExplainValue)>,
    control: ProductionControl<'a>,
}

impl<'a> ExplainObject<'a> {
    pub fn new(control: ProductionControl<'a>) -> Self {
        Self {
            fields: ProductionVec::new(control),
            control,
        }
    }

    pub fn insert(&mut self, key: &'static str, value: ExplainValue) -> Result<(), SQLError> {
        self.fields.push_produced(
            self.control
                .finish((key, value), self.control.empty_reservation())?,
        )?;
        Ok(())
    }

    pub fn text(&mut self, key: &'static str, value: &str) -> Result<(), SQLError> {
        self.insert(key, ExplainValue::Text(self.control.copy_text(value)?))
    }

    pub fn label(&mut self, key: &'static str, value: &'static str) -> Result<(), SQLError> {
        self.insert(key, ExplainValue::Label(value))
    }

    pub fn number(&mut self, key: &'static str, value: u64) -> Result<(), SQLError> {
        self.insert(key, ExplainValue::Unsigned(value))
    }

    pub fn optional_number(
        &mut self,
        key: &'static str,
        value: Option<u64>,
    ) -> Result<(), SQLError> {
        self.insert(
            key,
            value.map_or(ExplainValue::Null, ExplainValue::Unsigned),
        )
    }

    pub fn float(&mut self, key: &'static str, value: f64) -> Result<(), SQLError> {
        self.insert(key, ExplainValue::Float(value))
    }

    pub fn boolean(&mut self, key: &'static str, value: bool) -> Result<(), SQLError> {
        self.insert(key, ExplainValue::Bool(value))
    }

    pub fn null(&mut self, key: &'static str) -> Result<(), SQLError> {
        self.insert(key, ExplainValue::Null)
    }

    pub fn finish(self) -> Result<ExplainValue, SQLError> {
        let (mut fields, memory) = self.fields.finish()?.into_parts();
        fields.sort_unstable_by_key(|(key, _)| *key);
        Ok(ExplainValue::Object(self.control.finish(fields, memory)?))
    }
}