pgx_sql_entity_graph/postgres_hash/
entity.rs

1/*
2Portions Copyright 2019-2021 ZomboDB, LLC.
3Portions Copyright 2021-2022 Technology Concepts & Design, Inc. <support@tcdi.com>
4
5All rights reserved.
6
7Use of this source code is governed by the MIT license that can be found in the LICENSE file.
8*/
9/*!
10
11`#[derive(PostgresHash)]` related entities for Rust to SQL translation
12
13> Like all of the [`sql_entity_graph`][crate::pgx_sql_entity_graph] APIs, this is considered **internal**
14to the `pgx` framework and very subject to change between versions. While you may use this, please do it with caution.
15
16*/
17use crate::pgx_sql::PgxSql;
18use crate::to_sql::entity::ToSqlConfigEntity;
19use crate::to_sql::ToSql;
20use crate::{SqlGraphEntity, SqlGraphIdentifier};
21
22/// The output of a [`PostgresHash`](crate::postgres_hash::PostgresHash) from `quote::ToTokens::to_tokens`.
23#[derive(Debug, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
24pub struct PostgresHashEntity {
25    pub name: &'static str,
26    pub file: &'static str,
27    pub line: u32,
28    pub full_path: &'static str,
29    pub module_path: &'static str,
30    pub id: core::any::TypeId,
31    pub to_sql_config: ToSqlConfigEntity,
32}
33
34impl PostgresHashEntity {
35    pub(crate) fn fn_name(&self) -> String {
36        format!("{}_hash", self.name.to_lowercase())
37    }
38}
39
40impl From<PostgresHashEntity> for SqlGraphEntity {
41    fn from(val: PostgresHashEntity) -> Self {
42        SqlGraphEntity::Hash(val)
43    }
44}
45
46impl SqlGraphIdentifier for PostgresHashEntity {
47    fn dot_identifier(&self) -> String {
48        format!("hash {}", self.full_path)
49    }
50    fn rust_identifier(&self) -> String {
51        self.full_path.to_string()
52    }
53
54    fn file(&self) -> Option<&'static str> {
55        Some(self.file)
56    }
57
58    fn line(&self) -> Option<u32> {
59        Some(self.line)
60    }
61}
62
63impl ToSql for PostgresHashEntity {
64    fn to_sql(&self, _context: &PgxSql) -> eyre::Result<String> {
65        let sql = format!("\n\
66                            -- {file}:{line}\n\
67                            -- {full_path}\n\
68                            CREATE OPERATOR FAMILY {name}_hash_ops USING hash;\n\
69                            CREATE OPERATOR CLASS {name}_hash_ops DEFAULT FOR TYPE {name} USING hash FAMILY {name}_hash_ops AS\n\
70                                \tOPERATOR    1   =  ({name}, {name}),\n\
71                                \tFUNCTION    1   {fn_name}({name});\
72                            ",
73                          name = self.name,
74                          full_path = self.full_path,
75                          file = self.file,
76                          line = self.line,
77                          fn_name = self.fn_name(),
78        );
79        Ok(sql)
80    }
81}