pgrx_sql_entity_graph/pg_trigger/
entity.rs

1//LICENSE Portions Copyright 2019-2021 ZomboDB, LLC.
2//LICENSE
3//LICENSE Portions Copyright 2021-2023 Technology Concepts & Design, Inc.
4//LICENSE
5//LICENSE Portions Copyright 2023-2023 PgCentral Foundation, Inc. <contact@pgcentral.org>
6//LICENSE
7//LICENSE All rights reserved.
8//LICENSE
9//LICENSE Use of this source code is governed by the MIT license that can be found in the LICENSE file.
10/*!
11
12`#[pg_trigger]` related entities for Rust to SQL translation
13
14> Like all of the [`sql_entity_graph`][crate] APIs, this is considered **internal**
15> to the `pgrx` framework and very subject to change between versions. While you may use this, please do it with caution.
16
17*/
18use crate::{PgrxSql, SqlGraphEntity, SqlGraphIdentifier, ToSql, ToSqlConfigEntity};
19
20#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
21pub struct PgTriggerEntity {
22    pub function_name: &'static str,
23    pub to_sql_config: ToSqlConfigEntity,
24    pub file: &'static str,
25    pub line: u32,
26    pub module_path: &'static str,
27    pub full_path: &'static str,
28}
29
30impl PgTriggerEntity {
31    fn wrapper_function_name(&self) -> String {
32        self.function_name.to_string() + "_wrapper"
33    }
34}
35
36impl From<PgTriggerEntity> for SqlGraphEntity {
37    fn from(val: PgTriggerEntity) -> Self {
38        SqlGraphEntity::Trigger(val)
39    }
40}
41
42impl ToSql for PgTriggerEntity {
43    fn to_sql(&self, context: &PgrxSql) -> eyre::Result<String> {
44        let self_index = context.triggers[self];
45        let schema = context.schema_prefix_for(&self_index);
46
47        let PgTriggerEntity { file, line, full_path, function_name, .. } = self;
48        let sql = format!(
49            "\n\
50            -- {file}:{line}\n\
51            -- {full_path}\n\
52            CREATE FUNCTION {schema}\"{function_name}\"()\n\
53                \tRETURNS TRIGGER\n\
54                \tLANGUAGE c\n\
55                \tAS 'MODULE_PATHNAME', '{wrapper_function_name}';",
56            wrapper_function_name = self.wrapper_function_name(),
57        );
58        Ok(sql)
59    }
60}
61
62impl SqlGraphIdentifier for PgTriggerEntity {
63    fn dot_identifier(&self) -> String {
64        format!("trigger fn {}", self.full_path)
65    }
66    fn rust_identifier(&self) -> String {
67        self.full_path.to_string()
68    }
69
70    fn file(&self) -> Option<&'static str> {
71        Some(self.file)
72    }
73
74    fn line(&self) -> Option<u32> {
75        Some(self.line)
76    }
77}