use super::walk_schema_expr_mut;
use crate::ast::{ColumnType, Expr};
use crate::expr::EngineHook;
use crate::plan::{QueryPlan, UnifiedPlan};
use crate::{SQLError, ScalarExpr};
use uqa_core::Value;
mod production;
pub use production::read_prepared_oid_alias_constants_owned;
pub(crate) use production::read_unknown_constant_with_control;
pub trait OidAliasInput {
fn resolve_oid_alias_input(&self, ty: &ColumnType, name: &str)
-> Result<Option<i64>, SQLError>;
fn resolve_oid_alias_input_with_control(
&self,
ty: &ColumnType,
name: &str,
control: &uqa_core::memory::ProductionControl<'_>,
) -> Result<Option<i64>, SQLError> {
control.check()?;
let result = self.resolve_oid_alias_input(ty, name)?;
control.check()?;
Ok(result)
}
}
impl<T: EngineHook + ?Sized> OidAliasInput for T {
fn resolve_oid_alias_input_with_control(
&self,
ty: &ColumnType,
name: &str,
control: &uqa_core::memory::ProductionControl<'_>,
) -> Result<Option<i64>, SQLError> {
EngineHook::resolve_oid_alias_input_with_control(self, ty, name, control)
}
fn resolve_oid_alias_input(
&self,
ty: &ColumnType,
name: &str,
) -> Result<Option<i64>, SQLError> {
match ty {
ColumnType::Regclass => EngineHook::resolve_regclass_input(self, name),
ColumnType::Regtype => EngineHook::resolve_regtype_input(self, name),
ColumnType::Regproc => EngineHook::resolve_regproc(self, name),
ColumnType::Regprocedure => EngineHook::resolve_regprocedure_input(self, name),
ColumnType::Regnamespace => EngineHook::resolve_regnamespace(self, name),
ColumnType::Regcollation => EngineHook::resolve_regcollation(self, name),
ColumnType::Regrole => EngineHook::resolve_regrole(self, name),
other => Err(SQLError::Internal(format!(
"{} is not an OID alias type read at analysis",
other.sql_name()
))),
}
}
}
fn is_alias(ty: &ColumnType) -> bool {
matches!(
ty,
ColumnType::Regclass
| ColumnType::Regtype
| ColumnType::Regproc
| ColumnType::Regprocedure
| ColumnType::Regcollation
| ColumnType::Regnamespace
)
}
fn alias_type(ty: &str) -> Option<(ColumnType, bool)> {
if !ty
.as_bytes()
.windows(3)
.any(|window| window.eq_ignore_ascii_case(b"reg"))
{
return None;
}
match ColumnType::from_sql_name(ty).ok()? {
ColumnType::Array(element) if is_alias(&element) => Some((*element, true)),
element if is_alias(&element) => Some((element, false)),
_ => None,
}
}
fn read_constant<C: OidAliasInput + ?Sized>(
catalog: &C,
ty: &ColumnType,
text: &str,
array: bool,
) -> Result<Value, SQLError> {
production::read_constant_with_control(
catalog,
ty,
text,
array,
&uqa_core::memory::ProductionControl::uncontrolled(),
)?
.into_uncontrolled()
.map_err(|_| SQLError::Internal("ordinary OID input owner".into()))
}
fn constant_type(ty: ColumnType, array: bool) -> ColumnType {
if array {
ColumnType::Array(Box::new(ty))
} else {
ty
}
}
pub fn read_oid_alias_constants<C: OidAliasInput + ?Sized>(
catalog: &C,
expression: &mut Expr,
) -> Result<(), SQLError> {
let mut failure = None;
let outcome = walk_schema_expr_mut(expression, &mut |node| {
let Expr::Cast { expr, ty, .. } = node else {
return Ok(());
};
let Some((alias, array)) = alias_type(ty) else {
return Ok(());
};
let Expr::Literal(Value::Str(text)) = expr.as_ref() else {
return Ok(());
};
match read_constant(catalog, &alias, text, array) {
Ok(value) => {
**expr = Expr::TypedLiteral {
collation_oid: None,
composite_source: None,
value,
ty: constant_type(alias, array).catalog_name(),
};
Ok(())
}
Err(error) => {
failure = Some(error);
Err(String::new())
}
}
});
match (outcome, failure) {
(Ok(()), _) => Ok(()),
(Err(_), Some(error)) => Err(error),
(Err(message), None) => Err(SQLError::Internal(message)),
}
}
fn sequence_argument_mut(expression: &mut ScalarExpr) -> Option<&mut ScalarExpr> {
let ScalarExpr::Func { name, args, .. } = expression else {
return None;
};
if !is_sequence_function(name) {
return None;
}
args.first_mut()
.filter(|argument| matches!(argument, ScalarExpr::Literal(Value::Str(_))))
}
fn is_sequence_function(name: &str) -> bool {
let local = name
.get(..11)
.filter(|prefix| prefix.eq_ignore_ascii_case("pg_catalog."))
.map_or(name, |_| &name[11..]);
["nextval", "currval", "setval"]
.iter()
.any(|candidate| local.eq_ignore_ascii_case(candidate))
}
fn read_scalar_constant<C: OidAliasInput + ?Sized>(
catalog: &C,
expression: &mut ScalarExpr,
keep_relations: bool,
failure: &mut Option<SQLError>,
) {
if failure.is_some() {
return;
}
if let Some(argument) = sequence_argument_mut(expression) {
let ScalarExpr::Literal(Value::Str(text)) = &*argument else {
unreachable!("sequence argument is an unknown literal");
};
match read_constant(catalog, &ColumnType::Regclass, text, false) {
Ok(value) => {
if !keep_relations {
*argument = ScalarExpr::TypedLiteral {
collation_oid: None,
composite_source: None,
value,
ty: ColumnType::Regclass.catalog_name(),
bound_type: Some(ColumnType::Regclass),
parameter_index: None,
};
}
}
Err(error) => *failure = Some(error),
}
return;
}
let ScalarExpr::Cast { expr, ty, .. } = expression else {
return;
};
let Some((alias, array)) = alias_type(ty) else {
return;
};
let ScalarExpr::Literal(Value::Str(text)) = expr.as_ref() else {
return;
};
match read_constant(catalog, &alias, text, array) {
Ok(value) => {
if keep_relations && matches!(alias, ColumnType::Regclass) {
return;
}
let bound_type = constant_type(alias, array);
**expr = ScalarExpr::TypedLiteral {
collation_oid: None,
composite_source: None,
value,
ty: bound_type.catalog_name(),
bound_type: Some(bound_type),
parameter_index: None,
};
}
Err(error) => *failure = Some(error),
}
}
pub fn read_oid_alias_constants_in_plan<C: OidAliasInput + ?Sized>(
catalog: &C,
plan: &mut QueryPlan,
) -> Result<(), SQLError> {
let mut failure = None;
plan.rewrite_scalar_expressions(&mut |root| {
root.visit_mut(&mut |expression| {
read_scalar_constant(catalog, expression, false, &mut failure);
});
});
failure.map_or(Ok(()), Err)
}
pub fn read_prepared_oid_alias_constants<C: OidAliasInput + ?Sized>(
catalog: &C,
plan: &mut UnifiedPlan,
) -> Result<(), SQLError> {
let mut failure = None;
plan.rewrite_scalar_expressions(&mut |root| {
root.visit_mut(&mut |expression| {
read_scalar_constant(catalog, expression, false, &mut failure);
});
});
failure.map_or(Ok(()), Err)
}