Skip to main content

schema_sql_generator/common/
procedure_generator.rs

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