use super::{QueryPlan, SchemaScope};
use crate::{
routines::RoutineResolution, schema::RecordFields, ColumnType, RowSchema, SQLError, SQLParam,
ScalarExpr,
};
pub(super) fn input_fields(expression: &ScalarExpr, schema: &RowSchema) -> Option<RecordFields> {
schema.input_record_metadata(expression)?.types.clone()
}
pub(super) fn common_fields<'a>(
fields: impl IntoIterator<Item = Option<&'a RecordFields>>,
) -> Option<RecordFields> {
let mut fields = fields.into_iter();
let first = fields.next()??;
fields
.all(|other| other == Some(first))
.then(|| first.clone())
}
impl SchemaScope {
pub(super) fn bind_record_fields(
&mut self,
routines: &dyn RoutineResolution,
expression: &ScalarExpr,
schema: &RowSchema,
subqueries: &[QueryPlan],
params: &[SQLParam],
) -> Result<Option<RecordFields>, SQLError> {
let owner = self.control().capture();
let control = owner.control();
control.check()?;
if let Some(fields) = input_fields(expression, schema) {
return Ok(Some(fields));
}
match expression {
ScalarExpr::Row(fields) => {
let mut types = uqa_core::memory::ProductionVec::new(control);
for field in fields {
let expanded =
crate::semantics::row_star_fields_with_control(field, schema, &control)?;
if let Some(expanded) = expanded {
for field in expanded.iter() {
push_type(
&mut types,
self.bind_record_field_type(
routines, field, schema, subqueries, params,
)?,
&control,
)?;
}
} else {
push_type(
&mut types,
self.bind_record_field_type(
routines, field, schema, subqueries, params,
)?,
&control,
)?;
}
}
Ok(Some(RecordFields::from_produced(
types.finish()?,
&control,
)?))
}
ScalarExpr::Cast { expr, ty, .. } if record_cast(routines, ty, &control)? => {
self.bind_record_fields(routines, expr, schema, subqueries, params)
}
ScalarExpr::Case {
when, else_branch, ..
} => {
let mut first = None;
let mut equal = true;
for expression in when
.iter()
.map(|(_, value)| value)
.chain(else_branch.iter().map(AsRef::as_ref))
{
control.check()?;
if !matches!(expression, ScalarExpr::Literal(uqa_core::Value::Null)) {
let fields = self
.bind_record_fields(routines, expression, schema, subqueries, params)?;
if let Some(first) = &first {
equal &= first == &fields;
} else {
first = Some(fields);
}
}
}
Ok(first.filter(|_| equal).flatten())
}
ScalarExpr::ScalarSubquery(index) => {
let query = subqueries.get(*index).ok_or_else(|| {
SQLError::Internal("record subquery slot is outside its plan".into())
})?;
let output = self.bind_query(routines, query, params, Some(schema))?;
Ok(output.record_fields(0).cloned())
}
_ => {
let ty = self.bind_expression_type_with_control(
routines, expression, schema, subqueries, params,
)?;
let Some(mut ty) = ty.as_deref() else {
return Ok(None);
};
while let ColumnType::Domain { base, .. } = ty {
ty = base;
}
let ColumnType::Composite(reference) = ty else {
return Ok(None);
};
let descriptor = crate::expr::composites::descriptor_with_control(
routines.composite_types(),
reference.oid,
&control,
)?;
Ok(Some(RecordFields::from_types_with_control(
descriptor
.attributes
.iter()
.map(|attribute| Some(&attribute.ty)),
&control,
)?))
}
}
}
fn bind_record_field_type(
&mut self,
routines: &dyn RoutineResolution,
field: &ScalarExpr,
schema: &RowSchema,
subqueries: &[QueryPlan],
params: &[SQLParam],
) -> Result<Option<uqa_core::memory::Produced<ColumnType>>, SQLError> {
if matches!(
field,
ScalarExpr::Literal(uqa_core::Value::Str(_) | uqa_core::Value::Null)
) {
Ok(None)
} else {
self.bind_expression_type_with_control(routines, field, schema, subqueries, params)
}
}
}
fn push_type(
types: &mut uqa_core::memory::ProductionVec<'_, Option<ColumnType>>,
ty: Option<uqa_core::memory::Produced<ColumnType>>,
control: &uqa_core::memory::ProductionControl<'_>,
) -> Result<(), SQLError> {
let (ty, memory) = match ty {
Some(ty) => {
let (ty, memory) = ty.into_parts();
(Some(ty), memory)
}
None => (None, control.empty_reservation()),
};
types.push_produced(control.finish(ty, memory)?)?;
Ok(())
}
fn record_cast(
routines: &dyn RoutineResolution,
name: &str,
control: &uqa_core::memory::ProductionControl<'_>,
) -> Result<bool, SQLError> {
if let Some(ty) = routines.resolve_type_name_with_control(name, control)? {
return Ok(matches!(*ty, ColumnType::Record));
}
match ColumnType::from_sql_name_with_control(name, control) {
Ok(ty) => Ok(matches!(*ty, ColumnType::Record)),
Err(error) if matches!(error.sqlstate(), Some("53200" | "57014")) => Err(error),
Err(_) => Ok(false),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
struct Routines;
impl crate::FunctionTypeResolver for Routines {
fn resolve_function_type(
&self,
_: &str,
_: Option<&crate::ast::FunctionBinding>,
_: &[Option<String>],
_: &[Option<ColumnType>],
_: bool,
) -> Result<Option<ColumnType>, SQLError> {
Ok(None)
}
}
impl RoutineResolution for Routines {}
#[test]
fn record_fields_follow_ctes_derived_columns_and_identical_case_branches() {
for sql in [
"SELECT ROW(1,2::bigint)",
"WITH r AS(SELECT ROW(1,2::bigint) AS v) SELECT v FROM r",
"SELECT x.v FROM (SELECT ROW(1,2::bigint) AS v) x",
"SELECT CASE WHEN true THEN ROW(1,2::bigint) ELSE ROW(3,4::bigint) END",
] {
let crate::plan::UnifiedPlan::Query(query) =
crate::plan::UnifiedPlan::lower(crate::compile(sql).unwrap().remove(0))
else {
panic!("query");
};
let schema = crate::binding::analyze_query_plan_schema_with_catalog(
&Routines,
&query,
&[],
crate::binding::fixture::catalog(BTreeMap::new()),
crate::binding::fixture::resolution(
vec!["public".into()],
"pg_temp_fixture".into(),
),
)
.unwrap();
assert_eq!(
schema.record_fields(0).unwrap().as_ref(),
&[Some(ColumnType::Integer), Some(ColumnType::BigInteger)],
"{sql}"
);
}
}
#[test]
fn unknown_record_fields_remain_unknown_and_different_case_descriptors_remain_dynamic() {
for (sql, expected) in [
("SELECT ROW('1',NULL)", Some(vec![None, None])),
(
"SELECT CASE WHEN true THEN ROW(1,2::bigint) ELSE ROW(3,4) END",
None,
),
] {
let crate::plan::UnifiedPlan::Query(query) =
crate::plan::UnifiedPlan::lower(crate::compile(sql).unwrap().remove(0))
else {
panic!("query");
};
let schema = crate::binding::analyze_query_plan_schema_with_catalog(
&Routines,
&query,
&[],
crate::binding::fixture::catalog(BTreeMap::new()),
crate::binding::fixture::resolution(
vec!["public".into()],
"pg_temp_fixture".into(),
),
)
.unwrap();
assert_eq!(
schema.record_fields(0).map(|fields| fields.to_vec()),
expected,
"{sql}"
);
}
}
}