mod catalog;
use crate::types::SqlMigrationDefinition;
use sqlparser::ast::{
ArgMode, ArrayElemTypeDef, DataType, ExactNumberInfo, Ident, ObjectName, OperateFunctionArg,
TimezoneInfo,
};
pub(super) fn function_identity(
name: &ObjectName,
args: &[OperateFunctionArg],
) -> Option<SqlMigrationDefinition> {
Some(SqlMigrationDefinition {
name: super::qualified_name(name)?.into(),
argument_types: Some(
args.iter()
.filter(|arg| arg.mode != Some(ArgMode::Out))
.map(|arg| canonical_type(&arg.data_type))
.collect::<Option<_>>()?,
),
})
}
pub(super) fn canonical_type(data_type: &DataType) -> Option<String> {
use DataType::*;
match data_type {
Array(
ArrayElemTypeDef::SquareBracket(inner, _) | ArrayElemTypeDef::Qualified(inner, _),
) => {
let element = canonical_type(inner)?;
Some(if element.ends_with("[]") {
element
} else {
format!("{element}[]")
})
}
Custom(name, _) => {
let unqualified = name.0.len() == 1;
let [schema, name] = super::qualified_name(name)?;
if let Some(catalog) = (schema == "pg_catalog" || unqualified)
.then(|| catalog::alias(&name))
.flatten()
{
return Some(catalog);
}
Some(format!(
"{}.{}",
Ident::with_quote('"', schema),
Ident::with_quote('"', name)
))
}
_ => builtin_name(data_type).map(|name| format!("pg_catalog.{name}")),
}
}
fn builtin_name(data_type: &DataType) -> Option<&'static str> {
use DataType::*;
Some(match data_type {
Int(_) | Int4(_) | Integer(_) => "int4",
Int2(_) | SmallInt(_) => "int2",
Int8(_) | BigInt(_) => "int8",
Bool | Boolean => "bool",
Float4 | Real | Float(ExactNumberInfo::Precision(1..=24)) => "float4",
Float8
| DoublePrecision
| Float(ExactNumberInfo::None | ExactNumberInfo::Precision(25..=53)) => "float8",
Dec(_) | Decimal(_) | Numeric(_) => "numeric",
CharVarying(_) | CharacterVarying(_) | Varchar(_) => "varchar",
Char(_) | Character(_) => "bpchar",
Timestamp(_, TimezoneInfo::WithTimeZone | TimezoneInfo::Tz) => "timestamptz",
Timestamp(_, _) => "timestamp",
Time(_, TimezoneInfo::WithTimeZone | TimezoneInfo::Tz) => "timetz",
Time(_, _) => "time",
Bit(_) => "bit",
BitVarying(_) | VarBit(_) => "varbit",
Interval { .. } => "interval",
Uuid => "uuid",
Text => "text",
Bytea => "bytea",
Date => "date",
JSON => "json",
JSONB => "jsonb",
Regclass => "regclass",
TsVector => "tsvector",
TsQuery => "tsquery",
_ => return None,
})
}