pgrx_sql_entity_graph/postgres_hash/
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`#[derive(PostgresHash)]` 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::pgrx_sql::PgrxSql;
19use crate::to_sql::entity::ToSqlConfigEntity;
20use crate::to_sql::ToSql;
21use crate::{SqlGraphEntity, SqlGraphIdentifier};
22
23/// The output of a [`PostgresHash`](crate::postgres_hash::PostgresHash) from `quote::ToTokens::to_tokens`.
24#[derive(Debug, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
25pub struct PostgresHashEntity {
26    pub name: &'static str,
27    pub file: &'static str,
28    pub line: u32,
29    pub full_path: &'static str,
30    pub module_path: &'static str,
31    pub id: core::any::TypeId,
32    pub to_sql_config: ToSqlConfigEntity,
33}
34
35impl PostgresHashEntity {
36    pub(crate) fn fn_name(&self) -> String {
37        format!("{}_hash", self.name.to_lowercase())
38    }
39}
40
41impl From<PostgresHashEntity> for SqlGraphEntity {
42    fn from(val: PostgresHashEntity) -> Self {
43        SqlGraphEntity::Hash(val)
44    }
45}
46
47impl SqlGraphIdentifier for PostgresHashEntity {
48    fn dot_identifier(&self) -> String {
49        format!("hash {}", self.full_path)
50    }
51    fn rust_identifier(&self) -> String {
52        self.full_path.to_string()
53    }
54
55    fn file(&self) -> Option<&'static str> {
56        Some(self.file)
57    }
58
59    fn line(&self) -> Option<u32> {
60        Some(self.line)
61    }
62}
63
64impl ToSql for PostgresHashEntity {
65    fn to_sql(&self, _context: &PgrxSql) -> eyre::Result<String> {
66        let sql = format!("\n\
67                            -- {file}:{line}\n\
68                            -- {full_path}\n\
69                            CREATE OPERATOR FAMILY {name}_hash_ops USING hash;\n\
70                            CREATE OPERATOR CLASS {name}_hash_ops DEFAULT FOR TYPE {name} USING hash FAMILY {name}_hash_ops AS\n\
71                                \tOPERATOR    1   =  ({name}, {name}),\n\
72                                \tFUNCTION    1   {fn_name}({name});\
73                            ",
74                          name = self.name,
75                          full_path = self.full_path,
76                          file = self.file,
77                          line = self.line,
78                          fn_name = self.fn_name(),
79        );
80        Ok(sql)
81    }
82}