Skip to main content

schema_sql_generator/common/
function_generator.rs

1use crate::common::generator_context::GeneratorContext;
2use crate::common::sql_writer::SqlWriter;
3use schema_model::model::function::Function;
4
5pub trait FunctionGenerator {
6    fn output_functions(&self);
7    fn output_function(
8        &self,
9        writer: &mut SqlWriter,
10        statement_separator: &str,
11        function: &Function,
12    );
13
14}
15
16pub struct DefaultFunctionGenerator {
17    context: GeneratorContext,
18}
19
20impl DefaultFunctionGenerator {
21    pub fn new(context: GeneratorContext) -> Self {
22        Self {
23            context,
24        }
25    }
26
27    pub fn context(&self) -> &GeneratorContext {
28        &self.context
29    }
30
31    /// Same iteration/filtering logic as `output_functions`, but dispatches each
32    /// function through `generator` rather than `self`. Rust has no virtual dispatch on
33    /// concrete types, so a dialect wrapper (e.g. `SqlServerFunctionGenerator`) that
34    /// overrides `output_function` but delegates `output_functions` straight to this
35    /// struct would otherwise never see its own override invoked - callers that need
36    /// their override honored should pass `self` (as a `&dyn FunctionGenerator`) here
37    /// instead of calling `output_functions` directly.
38    pub fn output_functions_via(&self, generator: &dyn FunctionGenerator) {
39        let database_type = self.context.settings().database_type();
40        let statement_separator = self.context.settings().statement_separator();
41        let database_model = self.context.settings().database_model();
42
43        self.context.with_writer(|writer| {
44            database_model.schemas().iter().for_each(|schema| {
45                schema
46                    .functions()
47                    .iter()
48                    .filter(|function| function.database_type() == database_type)
49                    .for_each(|function| {
50                        generator.output_function(writer, statement_separator, function);
51                    })
52            });
53        });
54    }
55}
56
57impl FunctionGenerator for DefaultFunctionGenerator {
58    fn output_functions(&self) {
59        self.output_functions_via(self);
60    }
61
62    fn output_function(&self, writer: &mut SqlWriter, statement_separator: &str, function: &Function) {
63        writer.print(function.sql());
64        writer.println(statement_separator);
65        writer.newline();
66    }
67}