use crate::sql_entity_graph::pgx_sql::PgxSql;
use crate::sql_entity_graph::to_sql::ToSqlFn;
use crate::sql_entity_graph::SqlGraphEntity;
#[derive(Default, Clone)]
pub struct ToSqlConfigEntity {
pub enabled: bool,
pub callback: Option<ToSqlFn>,
pub content: Option<&'static str>,
}
impl ToSqlConfigEntity {
pub fn to_sql(
&self,
entity: &SqlGraphEntity,
context: &PgxSql,
) -> Option<eyre::Result<String>> {
use eyre::{eyre, WrapErr};
if !self.enabled {
return Some(Ok(format!(
"\n\
{sql_anchor_comment}\n\
-- Skipped due to `#[pgx(sql = false)]`\n",
sql_anchor_comment = entity.sql_anchor_comment(),
)));
}
if let Some(content) = self.content {
let module_pathname = context.get_module_pathname();
let content = content.replace("@MODULE_PATHNAME@", &module_pathname);
return Some(Ok(format!(
"\n\
{sql_anchor_comment}\n\
{content}\n\
",
content = content,
sql_anchor_comment = entity.sql_anchor_comment()
)));
}
if let Some(callback) = self.callback {
let content = callback(entity, context)
.map_err(|e| eyre!(e))
.wrap_err("Failed to run specified `#[pgx(sql = path)] function`");
return match content {
Ok(content) => {
let module_pathname = &context.get_module_pathname();
let content = content.replace("@MODULE_PATHNAME@", &module_pathname);
Some(Ok(format!(
"\n\
{sql_anchor_comment}\n\
{content}\
",
content = content,
sql_anchor_comment = entity.sql_anchor_comment(),
)))
}
Err(e) => Some(Err(e)),
};
}
None
}
}
impl std::cmp::PartialEq for ToSqlConfigEntity {
fn eq(&self, other: &Self) -> bool {
(self.enabled, self.content, self.callback.map(|f| f as usize))
== (other.enabled, other.content, other.callback.map(|f| f as usize))
}
}
impl std::cmp::Eq for ToSqlConfigEntity {}
impl std::hash::Hash for ToSqlConfigEntity {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.enabled.hash(state);
self.callback.map(|cb| cb as usize).hash(state);
self.content.hash(state);
}
}
impl std::fmt::Debug for ToSqlConfigEntity {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let callback = self.callback.map(|cb| cb as usize);
f.debug_struct("ToSqlConfigEntity")
.field("enabled", &self.enabled)
.field("callback", &format_args!("{:?}", &callback))
.field("content", &self.content)
.finish()
}
}