1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
//LICENSE Portions Copyright 2019-2021 ZomboDB, LLC.
//LICENSE
//LICENSE Portions Copyright 2021-2023 Technology Concepts & Design, Inc.
//LICENSE
//LICENSE Portions Copyright 2023-2023 PgCentral Foundation, Inc. <contact@pgcentral.org>
//LICENSE
//LICENSE All rights reserved.
//LICENSE
//LICENSE Use of this source code is governed by the MIT license that can be found in the LICENSE file.
/*!
`#[pg_aggregate]` related entities for Rust to SQL translation
> Like all of the [`sql_entity_graph`][crate::pgrx_sql_entity_graph] APIs, this is considered **internal**
to the `pgrx` framework and very subject to change between versions. While you may use this, please do it with caution.
*/
use crate::aggregate::options::{FinalizeModify, ParallelOption};
use crate::metadata::SqlMapping;
use crate::pgrx_sql::PgrxSql;
use crate::to_sql::entity::ToSqlConfigEntity;
use crate::to_sql::ToSql;
use crate::{SqlGraphEntity, SqlGraphIdentifier, UsedTypeEntity};
use core::any::TypeId;
use eyre::{eyre, WrapErr};
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct AggregateTypeEntity {
pub used_ty: UsedTypeEntity,
pub name: Option<&'static str>,
}
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct PgAggregateEntity {
pub full_path: &'static str,
pub module_path: &'static str,
pub file: &'static str,
pub line: u32,
pub ty_id: TypeId,
pub name: &'static str,
/// If the aggregate is an ordered set aggregate.
///
/// See [the PostgreSQL ordered set docs](https://www.postgresql.org/docs/current/xaggr.html#XAGGR-ORDERED-SET-AGGREGATES).
pub ordered_set: bool,
/// The `arg_data_type` list.
///
/// Corresponds to `Args` in [`pgrx::aggregate::Aggregate`].
pub args: Vec<AggregateTypeEntity>,
/// The direct argument list, appearing before `ORDER BY` in ordered set aggregates.
///
/// Corresponds to `OrderBy` in [`pgrx::aggregate::Aggregate`].
pub direct_args: Option<Vec<AggregateTypeEntity>>,
/// The `STYPE` and `name` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
///
/// The implementor of an [`pgrx::aggregate::Aggregate`].
pub stype: AggregateTypeEntity,
/// The `SFUNC` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
///
/// Corresponds to `state` in [`pgrx::aggregate::Aggregate`].
pub sfunc: &'static str,
/// The `FINALFUNC` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
///
/// Corresponds to `finalize` in [`pgrx::aggregate::Aggregate`].
pub finalfunc: Option<&'static str>,
/// The `FINALFUNC_MODIFY` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
///
/// Corresponds to `FINALIZE_MODIFY` in [`pgrx::aggregate::Aggregate`].
pub finalfunc_modify: Option<FinalizeModify>,
/// The `COMBINEFUNC` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
///
/// Corresponds to `combine` in [`pgrx::aggregate::Aggregate`].
pub combinefunc: Option<&'static str>,
/// The `SERIALFUNC` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
///
/// Corresponds to `serial` in [`pgrx::aggregate::Aggregate`].
pub serialfunc: Option<&'static str>,
/// The `DESERIALFUNC` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
///
/// Corresponds to `deserial` in [`pgrx::aggregate::Aggregate`].
pub deserialfunc: Option<&'static str>,
/// The `INITCOND` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
///
/// Corresponds to `INITIAL_CONDITION` in [`pgrx::aggregate::Aggregate`].
pub initcond: Option<&'static str>,
/// The `MSFUNC` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
///
/// Corresponds to `moving_state` in [`pgrx::aggregate::Aggregate`].
pub msfunc: Option<&'static str>,
/// The `MINVFUNC` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
///
/// Corresponds to `moving_state_inverse` in [`pgrx::aggregate::Aggregate`].
pub minvfunc: Option<&'static str>,
/// The `MSTYPE` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
///
/// Corresponds to `MovingState` in [`pgrx::aggregate::Aggregate`].
pub mstype: Option<UsedTypeEntity>,
// The `MSSPACE` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
//
// TODO: Currently unused.
// pub msspace: &'static str,
/// The `MFINALFUNC` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
///
/// Corresponds to `moving_state_finalize` in [`pgrx::aggregate::Aggregate`].
pub mfinalfunc: Option<&'static str>,
/// The `MFINALFUNC_MODIFY` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
///
/// Corresponds to `MOVING_FINALIZE_MODIFY` in [`pgrx::aggregate::Aggregate`].
pub mfinalfunc_modify: Option<FinalizeModify>,
/// The `MINITCOND` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
///
/// Corresponds to `MOVING_INITIAL_CONDITION` in [`pgrx::aggregate::Aggregate`].
pub minitcond: Option<&'static str>,
/// The `SORTOP` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
///
/// Corresponds to `SORT_OPERATOR` in [`pgrx::aggregate::Aggregate`].
pub sortop: Option<&'static str>,
/// The `PARALLEL` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
///
/// Corresponds to `PARALLEL` in [`pgrx::aggregate::Aggregate`].
pub parallel: Option<ParallelOption>,
/// The `HYPOTHETICAL` parameter for [`CREATE AGGREGATE`](https://www.postgresql.org/docs/current/sql-createaggregate.html)
///
/// Corresponds to `hypothetical` in [`pgrx::aggregate::Aggregate`].
pub hypothetical: bool,
pub to_sql_config: ToSqlConfigEntity,
}
impl From<PgAggregateEntity> for SqlGraphEntity {
fn from(val: PgAggregateEntity) -> Self {
SqlGraphEntity::Aggregate(val)
}
}
impl SqlGraphIdentifier for PgAggregateEntity {
fn dot_identifier(&self) -> String {
format!("aggregate {}", self.full_path)
}
fn rust_identifier(&self) -> String {
self.full_path.to_string()
}
fn file(&self) -> Option<&'static str> {
Some(self.file)
}
fn line(&self) -> Option<u32> {
Some(self.line)
}
}
impl ToSql for PgAggregateEntity {
fn to_sql(&self, context: &PgrxSql) -> eyre::Result<String> {
let self_index = context.aggregates[self];
let mut optional_attributes = Vec::new();
let schema = context.schema_prefix_for(&self_index);
if let Some(value) = self.finalfunc {
optional_attributes.push((
format!("\tFINALFUNC = {}\"{}\"", schema, value),
format!("/* {}::final */", self.full_path),
));
}
if let Some(value) = self.finalfunc_modify {
optional_attributes.push((
format!("\tFINALFUNC_MODIFY = {}", value.to_sql(context)?),
format!("/* {}::FINALIZE_MODIFY */", self.full_path),
));
}
if let Some(value) = self.combinefunc {
optional_attributes.push((
format!("\tCOMBINEFUNC = {}\"{}\"", schema, value),
format!("/* {}::combine */", self.full_path),
));
}
if let Some(value) = self.serialfunc {
optional_attributes.push((
format!("\tSERIALFUNC = {}\"{}\"", schema, value),
format!("/* {}::serial */", self.full_path),
));
}
if let Some(value) = self.deserialfunc {
optional_attributes.push((
format!("\tDESERIALFUNC ={} \"{}\"", schema, value),
format!("/* {}::deserial */", self.full_path),
));
}
if let Some(value) = self.initcond {
optional_attributes.push((
format!("\tINITCOND = '{}'", value),
format!("/* {}::INITIAL_CONDITION */", self.full_path),
));
}
if let Some(value) = self.msfunc {
optional_attributes.push((
format!("\tMSFUNC = {}\"{}\"", schema, value),
format!("/* {}::moving_state */", self.full_path),
));
}
if let Some(value) = self.minvfunc {
optional_attributes.push((
format!("\tMINVFUNC = {}\"{}\"", schema, value),
format!("/* {}::moving_state_inverse */", self.full_path),
));
}
if let Some(value) = self.mfinalfunc {
optional_attributes.push((
format!("\tMFINALFUNC = {}\"{}\"", schema, value),
format!("/* {}::moving_state_finalize */", self.full_path),
));
}
if let Some(value) = self.mfinalfunc_modify {
optional_attributes.push((
format!("\tMFINALFUNC_MODIFY = {}", value.to_sql(context)?),
format!("/* {}::MOVING_FINALIZE_MODIFY */", self.full_path),
));
}
if let Some(value) = self.minitcond {
optional_attributes.push((
format!("\tMINITCOND = '{}'", value),
format!("/* {}::MOVING_INITIAL_CONDITION */", self.full_path),
));
}
if let Some(value) = self.sortop {
optional_attributes.push((
format!("\tSORTOP = \"{}\"", value),
format!("/* {}::SORT_OPERATOR */", self.full_path),
));
}
if let Some(value) = self.parallel {
optional_attributes.push((
format!("\tPARALLEL = {}", value.to_sql(context)?),
format!("/* {}::PARALLEL */", self.full_path),
));
}
if self.hypothetical {
optional_attributes.push((
String::from("\tHYPOTHETICAL"),
format!("/* {}::hypothetical */", self.full_path),
))
}
let map_ty = |used_ty: &UsedTypeEntity| -> eyre::Result<String> {
match used_ty.metadata.argument_sql {
Ok(SqlMapping::As(ref argument_sql)) => Ok(argument_sql.to_string()),
Ok(SqlMapping::Composite { array_brackets }) => used_ty
.composite_type
.map(|v| if array_brackets { format!("{v}[]") } else { format!("{v}") })
.ok_or_else(|| {
eyre!("Macro expansion time suggested a composite_type!() in return")
}),
Ok(SqlMapping::Source { array_brackets }) => {
let sql = context
.source_only_to_sql_type(used_ty.ty_source)
.map(|v| if array_brackets { format!("{v}[]") } else { format!("{v}") })
.ok_or_else(|| {
eyre!("Macro expansion time suggested a source only mapping in return")
})?;
Ok(sql)
}
Ok(SqlMapping::Skip) => {
Err(eyre!("Cannot use skipped SQL translatable type as aggregate const type"))
}
Err(err) => match context.source_only_to_sql_type(used_ty.ty_source) {
Some(source_only_mapping) => Ok(source_only_mapping.to_string()),
None => return Err(err).wrap_err("While mapping argument"),
},
}
};
let stype_sql = map_ty(&self.stype.used_ty).wrap_err("Mapping state type")?;
let mut stype_schema = String::from("");
for (ty_item, ty_index) in context.types.iter() {
if ty_item.id_matches(&self.stype.used_ty.ty_id) {
stype_schema = context.schema_prefix_for(ty_index);
break;
}
}
if String::is_empty(&stype_schema) {
for (ty_item, ty_index) in context.enums.iter() {
if ty_item.id_matches(&self.stype.used_ty.ty_id) {
stype_schema = context.schema_prefix_for(ty_index);
break;
}
}
}
if let Some(value) = &self.mstype {
let mstype_sql = map_ty(&value).wrap_err("Mapping moving state type")?;
optional_attributes.push((
format!("\tMSTYPE = {}", mstype_sql),
format!("/* {}::MovingState = {} */", self.full_path, value.full_path),
));
}
let mut optional_attributes_string = String::new();
for (index, (optional_attribute, comment)) in optional_attributes.iter().enumerate() {
let optional_attribute_string = format!(
"{optional_attribute}{maybe_comma} {comment}{maybe_newline}",
optional_attribute = optional_attribute,
maybe_comma = if index == optional_attributes.len() - 1 { "" } else { "," },
comment = comment,
maybe_newline = if index == optional_attributes.len() - 1 { "" } else { "\n" }
);
optional_attributes_string += &optional_attribute_string;
}
let sql = format!(
"\n\
-- {file}:{line}\n\
-- {full_path}\n\
CREATE AGGREGATE {schema}{name} ({direct_args}{maybe_order_by}{args})\n\
(\n\
\tSFUNC = {schema}\"{sfunc}\", /* {full_path}::state */\n\
\tSTYPE = {stype_schema}{stype}{maybe_comma_after_stype} /* {stype_full_path} */\
{optional_attributes}\
);\
",
schema = schema,
name = self.name,
full_path = self.full_path,
file = self.file,
line = self.line,
sfunc = self.sfunc,
stype_schema = stype_schema,
stype = stype_sql,
stype_full_path = self.stype.used_ty.full_path,
maybe_comma_after_stype = if optional_attributes.len() == 0 { "" } else { "," },
args = {
let mut args = Vec::new();
for (idx, arg) in self.args.iter().enumerate() {
let graph_index = context
.graph
.neighbors_undirected(self_index)
.find(|neighbor| match &context.graph[*neighbor] {
SqlGraphEntity::Type(ty) => ty.id_matches(&arg.used_ty.ty_id),
SqlGraphEntity::Enum(en) => en.id_matches(&arg.used_ty.ty_id),
SqlGraphEntity::BuiltinType(defined) => {
defined == &arg.used_ty.full_path
}
_ => false,
})
.ok_or_else(|| {
eyre!("Could not find arg type in graph. Got: {:?}", arg.used_ty)
})?;
let needs_comma = idx < (self.args.len() - 1);
let buf = format!("\
\t{name}{variadic}{schema_prefix}{sql_type}{maybe_comma}/* {full_path} */\
",
schema_prefix = context.schema_prefix_for(&graph_index),
// First try to match on [`TypeId`] since it's most reliable.
sql_type = match arg.used_ty.metadata.argument_sql {
Ok(SqlMapping::As(ref argument_sql)) => {
argument_sql.to_string()
}
Ok(SqlMapping::Composite {
array_brackets,
}) => {
arg.used_ty
.composite_type
.map(|v| {
if array_brackets {
format!("{v}[]")
} else {
format!("{v}")
}
})
.ok_or_else(|| {
eyre!(
"Macro expansion time suggested a composite_type!() in return"
)
})?
}
Ok(SqlMapping::Source {
array_brackets,
}) => {
let sql = context
.source_only_to_sql_type(arg.used_ty.ty_source)
.map(|v| {
if array_brackets {
format!("{v}[]")
} else {
format!("{v}")
}
})
.ok_or_else(|| {
eyre!(
"Macro expansion time suggested a source only mapping in return"
)
})?;
sql
}
Ok(SqlMapping::Skip) => return Err(eyre!("Got a skipped SQL translatable type in aggregate args, this is not permitted")),
Err(err) => {
match context.source_only_to_sql_type(arg.used_ty.ty_source) {
Some(source_only_mapping) => {
source_only_mapping.to_string()
}
None => return Err(err).wrap_err("While mapping argument"),
}
}
},
variadic = if arg.used_ty.variadic { "VARIADIC " } else { "" },
maybe_comma = if needs_comma { ", " } else { " " },
full_path = arg.used_ty.full_path,
name = if let Some(name) = arg.name {
format!(r#""{}" "#, name)
} else { "".to_string() },
);
args.push(buf);
}
"\n".to_string() + &args.join("\n") + "\n"
},
direct_args = if let Some(direct_args) = &self.direct_args {
let mut args = Vec::new();
for (idx, arg) in direct_args.iter().enumerate() {
let graph_index = context
.graph
.neighbors_undirected(self_index)
.find(|neighbor| match &context.graph[*neighbor] {
SqlGraphEntity::Type(ty) => ty.id_matches(&arg.used_ty.ty_id),
SqlGraphEntity::Enum(en) => en.id_matches(&arg.used_ty.ty_id),
SqlGraphEntity::BuiltinType(defined) => {
defined == &arg.used_ty.full_path
}
_ => false,
})
.ok_or_else(|| eyre!("Could not find arg type in graph. Got: {:?}", arg))?;
let needs_comma = idx < (direct_args.len() - 1);
let buf = format!(
"\
\t{maybe_name}{schema_prefix}{sql_type}{maybe_comma}/* {full_path} */\
",
schema_prefix = context.schema_prefix_for(&graph_index),
// First try to match on [`TypeId`] since it's most reliable.
sql_type = map_ty(&arg.used_ty).wrap_err("Mapping direct arg type")?,
maybe_name = if let Some(name) = arg.name {
"\"".to_string() + name + "\" "
} else {
"".to_string()
},
maybe_comma = if needs_comma { ", " } else { " " },
full_path = arg.used_ty.full_path,
);
args.push(buf);
}
"\n".to_string() + &args.join("\n") + "\n"
} else {
String::default()
},
maybe_order_by = if self.ordered_set { "\tORDER BY" } else { "" },
optional_attributes = String::from("\n")
+ &optional_attributes_string
+ if optional_attributes.len() == 0 { "" } else { "\n" },
);
Ok(sql)
}
}