pgrx_sql_entity_graph/postgres_enum/
entity.rs1use crate::mapping::RustSqlMapping;
19use crate::pgrx_sql::PgrxSql;
20use crate::to_sql::entity::ToSqlConfigEntity;
21use crate::to_sql::ToSql;
22use crate::{SqlGraphEntity, SqlGraphIdentifier, TypeMatch};
23use std::collections::BTreeSet;
24
25#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
27pub struct PostgresEnumEntity {
28 pub name: &'static str,
29 pub file: &'static str,
30 pub line: u32,
31 pub full_path: &'static str,
32 pub module_path: &'static str,
33 pub mappings: BTreeSet<RustSqlMapping>,
34 pub variants: Vec<&'static str>,
35 pub to_sql_config: ToSqlConfigEntity,
36}
37
38impl TypeMatch for PostgresEnumEntity {
39 fn id_matches(&self, candidate: &core::any::TypeId) -> bool {
40 self.mappings.iter().any(|tester| *candidate == tester.id)
41 }
42}
43
44impl From<PostgresEnumEntity> for SqlGraphEntity {
45 fn from(val: PostgresEnumEntity) -> Self {
46 SqlGraphEntity::Enum(val)
47 }
48}
49
50impl SqlGraphIdentifier for PostgresEnumEntity {
51 fn dot_identifier(&self) -> String {
52 format!("enum {}", self.full_path)
53 }
54 fn rust_identifier(&self) -> String {
55 self.full_path.to_string()
56 }
57
58 fn file(&self) -> Option<&'static str> {
59 Some(self.file)
60 }
61
62 fn line(&self) -> Option<u32> {
63 Some(self.line)
64 }
65}
66
67impl ToSql for PostgresEnumEntity {
68 fn to_sql(&self, context: &PgrxSql) -> eyre::Result<String> {
69 let self_index = context.enums[self];
70 let sql = format!(
71 "\n\
72 -- {file}:{line}\n\
73 -- {full_path}\n\
74 CREATE TYPE {schema}{name} AS ENUM (\n\
75 {variants}\
76 );\
77 ",
78 schema = context.schema_prefix_for(&self_index),
79 full_path = self.full_path,
80 file = self.file,
81 line = self.line,
82 name = self.name,
83 variants = self
84 .variants
85 .iter()
86 .map(|variant| format!("\t'{variant}'"))
87 .collect::<Vec<_>>()
88 .join(",\n")
89 + "\n",
90 );
91 Ok(sql)
92 }
93}