pgx_utils/sql_entity_graph/pg_trigger/
entity.rs1use crate::sql_entity_graph::{
10 PgxSql, SqlGraphEntity, SqlGraphIdentifier, ToSql, ToSqlConfigEntity,
11};
12use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
13use core::fmt::Debug;
14use core::hash::Hash;
15
16#[derive(Debug, Clone, Hash, PartialEq, Eq)]
17pub struct PgTriggerEntity {
18 pub function_name: &'static str,
19 pub to_sql_config: ToSqlConfigEntity,
20 pub file: &'static str,
21 pub line: u32,
22 pub module_path: &'static str,
23 pub full_path: &'static str,
24}
25
26impl PgTriggerEntity {
27 fn wrapper_function_name(&self) -> String {
28 self.function_name.to_string() + "_wrapper"
29 }
30}
31
32impl Ord for PgTriggerEntity {
33 fn cmp(&self, other: &Self) -> Ordering {
34 self.full_path.cmp(other.full_path)
35 }
36}
37
38impl PartialOrd for PgTriggerEntity {
39 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
40 Some(self.cmp(other))
41 }
42}
43
44impl From<PgTriggerEntity> for SqlGraphEntity {
45 fn from(val: PgTriggerEntity) -> Self {
46 SqlGraphEntity::Trigger(val)
47 }
48}
49
50impl ToSql for PgTriggerEntity {
51 #[tracing::instrument(
52 level = "error",
53 skip(self, context),
54 fields(identifier = %self.rust_identifier()),
55 )]
56 fn to_sql(&self, context: &PgxSql) -> eyre::Result<String> {
57 let self_index = context.triggers[self];
58 let schema = context.schema_prefix_for(&self_index);
59
60 let sql = format!(
61 "\n\
62 -- {file}:{line}\n\
63 -- {full_path}\n\
64 CREATE FUNCTION {schema}\"{function_name}\"()\n\
65 \tRETURNS TRIGGER\n\
66 \tLANGUAGE c\n\
67 \tAS 'MODULE_PATHNAME', '{wrapper_function_name}';\
68 ",
69 schema = schema,
70 file = self.file,
71 line = self.line,
72 full_path = self.full_path,
73 function_name = self.function_name,
74 wrapper_function_name = self.wrapper_function_name(),
75 );
76 Ok(sql)
77 }
78}
79
80impl SqlGraphIdentifier for PgTriggerEntity {
81 fn dot_identifier(&self) -> String {
82 format!("trigger fn {}", self.full_path)
83 }
84 fn rust_identifier(&self) -> String {
85 self.full_path.to_string()
86 }
87
88 fn file(&self) -> Option<&'static str> {
89 Some(self.file)
90 }
91
92 fn line(&self) -> Option<u32> {
93 Some(self.line)
94 }
95}