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