pgx_utils/sql_entity_graph/schema/
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`#[pg_schema]` related entities for Rust to SQL translation
12
13> Like all of the [`sql_entity_graph`][crate::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::sql_entity_graph::pgx_sql::PgxSql;
18use crate::sql_entity_graph::to_sql::ToSql;
19use crate::sql_entity_graph::{SqlGraphEntity, SqlGraphIdentifier};
20
21use std::cmp::Ordering;
22
23/// The output of a [`Schema`](crate::sql_entity_graph::schema::Schema) from `quote::ToTokens::to_tokens`.
24#[derive(Debug, Clone, Hash, PartialEq, Eq)]
25pub struct SchemaEntity {
26    pub module_path: &'static str,
27    pub name: &'static str,
28    pub file: &'static str,
29    pub line: u32,
30}
31
32impl Ord for SchemaEntity {
33    fn cmp(&self, other: &Self) -> Ordering {
34        self.file.cmp(other.file).then_with(|| self.file.cmp(other.file))
35    }
36}
37
38impl PartialOrd for SchemaEntity {
39    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
40        Some(self.cmp(other))
41    }
42}
43
44impl From<SchemaEntity> for SqlGraphEntity {
45    fn from(val: SchemaEntity) -> Self {
46        SqlGraphEntity::Schema(val)
47    }
48}
49
50impl SqlGraphIdentifier for SchemaEntity {
51    fn dot_identifier(&self) -> String {
52        format!("schema {}", self.module_path)
53    }
54    fn rust_identifier(&self) -> String {
55        self.module_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 SchemaEntity {
68    #[tracing::instrument(level = "debug", err, skip(self, _context), fields(identifier = %self.rust_identifier()))]
69    fn to_sql(&self, _context: &PgxSql) -> eyre::Result<String> {
70        let sql = format!(
71            "\n\
72                    -- {file}:{line}\n\
73                    CREATE SCHEMA IF NOT EXISTS {name}; /* {module_path} */\
74                ",
75            name = self.name,
76            file = self.file,
77            line = self.line,
78            module_path = self.module_path,
79        );
80        tracing::trace!(%sql);
81        Ok(sql)
82    }
83}