Skip to main content

scythe_codegen/backends/
ruby_pg.rs

1use std::fmt::Write;
2use std::path::Path;
3
4use scythe_backend::manifest::{BackendManifest, load_manifest};
5use scythe_backend::naming::{
6    enum_type_name, enum_variant_name, fn_name, row_struct_name, to_pascal_case,
7};
8
9use scythe_core::analyzer::{AnalyzedQuery, CompositeInfo, EnumInfo};
10use scythe_core::errors::{ErrorCode, ScytheError};
11use scythe_core::parser::QueryCommand;
12
13use crate::backend_trait::{CodegenBackend, ResolvedColumn, ResolvedParam};
14
15const DEFAULT_MANIFEST_TOML: &str = include_str!("../../manifests/ruby-pg.toml");
16
17pub struct RubyPgBackend {
18    manifest: BackendManifest,
19}
20
21impl RubyPgBackend {
22    pub fn new(engine: &str) -> Result<Self, ScytheError> {
23        match engine {
24            "postgresql" | "postgres" | "pg" => {}
25            _ => {
26                return Err(ScytheError::new(
27                    ErrorCode::InternalError,
28                    format!("ruby-pg only supports PostgreSQL, got engine '{}'", engine),
29                ));
30            }
31        }
32        let manifest_path = Path::new("backends/ruby-pg/manifest.toml");
33        let manifest = if manifest_path.exists() {
34            load_manifest(manifest_path)
35                .map_err(|e| ScytheError::new(ErrorCode::InternalError, format!("manifest: {e}")))?
36        } else {
37            toml::from_str(DEFAULT_MANIFEST_TOML)
38                .map_err(|e| ScytheError::new(ErrorCode::InternalError, format!("manifest: {e}")))?
39        };
40        Ok(Self { manifest })
41    }
42}
43
44/// Map a neutral type to a Ruby type coercion method.
45fn ruby_coercion(neutral_type: &str) -> &'static str {
46    match neutral_type {
47        "int16" | "int32" | "int64" => ".to_i",
48        "float32" | "float64" => ".to_f",
49        "bool" => " == \"t\"",
50        _ => "",
51    }
52}
53
54impl CodegenBackend for RubyPgBackend {
55    fn name(&self) -> &str {
56        "ruby-pg"
57    }
58
59    fn manifest(&self) -> &scythe_backend::manifest::BackendManifest {
60        &self.manifest
61    }
62
63    fn file_header(&self) -> String {
64        "# frozen_string_literal: true\n\n# Auto-generated by scythe. Do not edit.\n\nmodule Queries"
65            .to_string()
66    }
67
68    fn file_footer(&self) -> String {
69        "end".to_string()
70    }
71
72    fn generate_row_struct(
73        &self,
74        query_name: &str,
75        columns: &[ResolvedColumn],
76    ) -> Result<String, ScytheError> {
77        let struct_name = row_struct_name(query_name, &self.manifest.naming);
78        let fields = columns
79            .iter()
80            .map(|c| format!(":{}", c.field_name))
81            .collect::<Vec<_>>()
82            .join(", ");
83        let mut out = String::new();
84        let _ = writeln!(out, "  {} = Data.define({})", struct_name, fields);
85        Ok(out)
86    }
87
88    fn generate_model_struct(
89        &self,
90        table_name: &str,
91        columns: &[ResolvedColumn],
92    ) -> Result<String, ScytheError> {
93        let name = to_pascal_case(table_name);
94        self.generate_row_struct(&name, columns)
95    }
96
97    fn generate_query_fn(
98        &self,
99        analyzed: &AnalyzedQuery,
100        struct_name: &str,
101        columns: &[ResolvedColumn],
102        params: &[ResolvedParam],
103    ) -> Result<String, ScytheError> {
104        let func_name = fn_name(&analyzed.name, &self.manifest.naming);
105        let sql = super::clean_sql(&analyzed.sql);
106        let mut out = String::new();
107
108        // Parameter list
109        let param_list = params
110            .iter()
111            .map(|p| p.field_name.clone())
112            .collect::<Vec<_>>()
113            .join(", ");
114        let sep = if param_list.is_empty() { "" } else { ", " };
115
116        let _ = writeln!(out, "  def self.{}(conn{}{})", func_name, sep, param_list);
117
118        // Build exec_params call
119        let param_array = if params.is_empty() {
120            "[]".to_string()
121        } else {
122            format!(
123                "[{}]",
124                params
125                    .iter()
126                    .map(|p| p.field_name.clone())
127                    .collect::<Vec<_>>()
128                    .join(", ")
129            )
130        };
131
132        match &analyzed.command {
133            QueryCommand::One => {
134                let _ = writeln!(
135                    out,
136                    "    result = conn.exec_params(\"{}\", {})",
137                    sql, param_array
138                );
139                let _ = writeln!(out, "    return nil if result.ntuples.zero?");
140                let _ = writeln!(out, "    row = result[0]");
141
142                // Build struct constructor
143                let fields = columns
144                    .iter()
145                    .map(|c| {
146                        let coercion = ruby_coercion(&c.neutral_type);
147                        if c.nullable {
148                            format!(
149                                "{}: row[\"{}\"]&.then {{ |v| v{} }}",
150                                c.field_name, c.name, coercion
151                            )
152                        } else {
153                            format!("{}: row[\"{}\"]{}", c.field_name, c.name, coercion)
154                        }
155                    })
156                    .collect::<Vec<_>>()
157                    .join(", ");
158                let _ = writeln!(out, "    {}.new({})", struct_name, fields);
159            }
160            QueryCommand::Many | QueryCommand::Batch => {
161                let _ = writeln!(
162                    out,
163                    "    result = conn.exec_params(\"{}\", {})",
164                    sql, param_array
165                );
166                let _ = writeln!(out, "    result.map do |row|");
167                let fields = columns
168                    .iter()
169                    .map(|c| {
170                        let coercion = ruby_coercion(&c.neutral_type);
171                        if c.nullable {
172                            format!(
173                                "{}: row[\"{}\"]&.then {{ |v| v{} }}",
174                                c.field_name, c.name, coercion
175                            )
176                        } else {
177                            format!("{}: row[\"{}\"]{}", c.field_name, c.name, coercion)
178                        }
179                    })
180                    .collect::<Vec<_>>()
181                    .join(", ");
182                let _ = writeln!(out, "      {}.new({})", struct_name, fields);
183                let _ = writeln!(out, "    end");
184            }
185            QueryCommand::Exec => {
186                let _ = writeln!(out, "    conn.exec_params(\"{}\", {})", sql, param_array);
187                let _ = writeln!(out, "    nil");
188            }
189            QueryCommand::ExecResult | QueryCommand::ExecRows => {
190                let _ = writeln!(
191                    out,
192                    "    result = conn.exec_params(\"{}\", {})",
193                    sql, param_array
194                );
195                let _ = writeln!(out, "    result.cmd_tuples.to_i");
196            }
197        }
198
199        let _ = write!(out, "  end");
200        Ok(out)
201    }
202
203    fn generate_enum_def(&self, enum_info: &EnumInfo) -> Result<String, ScytheError> {
204        let type_name = enum_type_name(&enum_info.sql_name, &self.manifest.naming);
205        let mut out = String::new();
206        let _ = writeln!(out, "  module {}", type_name);
207        for value in &enum_info.values {
208            let variant = enum_variant_name(value, &self.manifest.naming);
209            let _ = writeln!(out, "    {} = \"{}\"", variant, value);
210        }
211        // ALL constant
212        let all_values = enum_info
213            .values
214            .iter()
215            .map(|v| enum_variant_name(v, &self.manifest.naming))
216            .collect::<Vec<_>>()
217            .join(", ");
218        let _ = writeln!(out, "    ALL = [{}].freeze", all_values);
219        let _ = write!(out, "  end");
220        Ok(out)
221    }
222
223    fn generate_composite_def(&self, composite: &CompositeInfo) -> Result<String, ScytheError> {
224        let name = to_pascal_case(&composite.sql_name);
225        let mut out = String::new();
226        if composite.fields.is_empty() {
227            let _ = writeln!(out, "  {} = Data.define()", name);
228        } else {
229            let fields = composite
230                .fields
231                .iter()
232                .map(|f| format!(":{}", f.name))
233                .collect::<Vec<_>>()
234                .join(", ");
235            let _ = writeln!(out, "  {} = Data.define({})", name, fields);
236        }
237        Ok(out)
238    }
239}