scythe-codegen 0.19.0

Polyglot code generation backends for scythe
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
use std::fmt::Write;

use scythe_backend::manifest::BackendManifest;
use scythe_backend::naming::{composite_type_name, enum_type_name, enum_variant_name, fn_name};

use scythe_core::analyzer::{AnalyzedQuery, CompositeInfo, EnumInfo};
use scythe_core::errors::{ErrorCode, ScytheError};
use scythe_core::parser::QueryCommand;

use crate::backend_trait::{CodegenBackend, GroupedQueryFn, RbsGenerationContext, ResolvedColumn, ResolvedParam};

const DEFAULT_MANIFEST_TOML: &str = include_str!("../../manifests/ruby-tiny-tds.toml");

/// Check if a neutral type should not be escaped (numeric or boolean types).
/// Neutral types are core type identifiers like "int32", "bool", "decimal".
fn is_numeric_or_bool_type(neutral_type: &str) -> bool {
    let base_type = if neutral_type.contains('<') {
        neutral_type.split('<').next().unwrap_or("")
    } else {
        neutral_type
    };

    matches!(
        base_type,
        "bool" | "int16" | "int32" | "int64" | "float32" | "float64" | "decimal"
    )
}

/// Check if a neutral type is specifically a boolean.
fn is_bool_type(neutral_type: &str) -> bool {
    let base_type = if neutral_type.contains('<') {
        neutral_type.split('<').next().unwrap_or("")
    } else {
        neutral_type
    };
    base_type == "bool"
}

/// Generate the inline SQL interpolation for a parameter value.
/// Returns the string that replaces `@pN` directly in the SQL body.
/// - Booleans: `#{var ? 1 : 0}`
/// - Other numeric/decimal types: `#{var}`
/// - Nullable strings: `#{var.nil? ? 'NULL' : "'#{client.escape(var)}'"}`
/// - Non-nullable strings: `'#{client.escape(var)}'`
/// - `var_access` is used to reference the variable (e.g., "id" or "item[:id]")
fn generate_inline_value(neutral_type: &str, var_access: &str, nullable: bool) -> String {
    if is_bool_type(neutral_type) {
        format!("#{{{} ? 1 : 0}}", var_access)
    } else if is_numeric_or_bool_type(neutral_type) {
        format!("#{{{}}}", var_access)
    } else if nullable {
        format!(
            "#{{ {}.nil? ? 'NULL' : \"'#{{client.escape({})}}'\"}}",
            var_access, var_access
        )
    } else {
        format!("'#{{client.escape({})}}'", var_access)
    }
}

/// Replace `@p1`, `@p2`, ... placeholders in the SQL string with inline Ruby interpolations.
fn inline_params(sql: &str, params: &[(String, String, bool)]) -> String {
    let mut result = sql.to_string();
    for (index, (neutral_type, var_access, nullable)) in params.iter().enumerate().rev() {
        let placeholder = format!("@p{}", index + 1);
        let value = generate_inline_value(neutral_type, var_access, *nullable);
        result = result.replace(&placeholder, &value);
    }
    result
}

pub struct RubyTinyTdsBackend {
    manifest: BackendManifest,
}

impl RubyTinyTdsBackend {
    pub fn new(engine: &str) -> Result<Self, ScytheError> {
        match engine {
            "mssql" => {}
            _ => {
                return Err(ScytheError::new(
                    ErrorCode::InvalidConfig,
                    format!("ruby-tiny-tds only supports MSSQL, got engine '{}'", engine),
                ));
            }
        }
        let manifest = super::parse_manifest(DEFAULT_MANIFEST_TOML)?;
        Ok(Self { manifest })
    }
}

/// Rewrite $1, $2, ... to @p1, @p2, ... for MSSQL.
impl CodegenBackend for RubyTinyTdsBackend {
    fn name(&self) -> &str {
        "ruby-tiny-tds"
    }

    fn manifest(&self) -> &scythe_backend::manifest::BackendManifest {
        &self.manifest
    }

    fn manifest_mut(&mut self) -> &mut scythe_backend::manifest::BackendManifest {
        &mut self.manifest
    }

    fn supported_engines(&self) -> &[&str] {
        &["mssql"]
    }

    fn generate_rbs_file(&self, context: &RbsGenerationContext) -> Option<String> {
        Some(super::ruby_rbs::generate_rbs_content(
            context,
            "TinyTds::Client",
            &self.manifest,
        ))
    }

    fn file_preamble(&self) -> String {
        "# frozen_string_literal: true\n".to_string()
    }

    fn file_header(&self) -> String {
        format!(
            "require \"tiny_tds\"\n\nmodule Queries\n{}",
            super::ruby_rbs::RECORD_NOT_FOUND_CLASS
        )
    }

    fn file_footer(&self) -> String {
        "end".to_string()
    }

    fn generate_struct_decl(
        &self,
        struct_name: &str,
        _query_name: &str,
        columns: &[ResolvedColumn],
    ) -> Result<String, ScytheError> {
        let fields = columns
            .iter()
            .map(|c| format!(":{}", c.field_name))
            .collect::<Vec<_>>()
            .join(", ");
        let mut out = String::new();
        let _ = writeln!(out, "  {} = Data.define({})", struct_name, fields);
        Ok(out)
    }

    fn generate_query_fn(
        &self,
        analyzed: &AnalyzedQuery,
        struct_name: &str,
        columns: &[ResolvedColumn],
        params: &[ResolvedParam],
    ) -> Result<String, ScytheError> {
        let func_name = fn_name(&analyzed.name, &self.manifest.naming);
        let sql = crate::sql_literal::escape_ruby_double_quoted(&super::rewrite_pg_placeholders(
            &super::clean_sql_with_optional(&analyzed.sql, &analyzed.optional_params, &analyzed.params),
            |n| format!("@p{n}"),
        ));
        let mut out = String::new();

        let param_list = params
            .iter()
            .map(|p| p.field_name.clone())
            .collect::<Vec<_>>()
            .join(", ");
        let sep = if param_list.is_empty() { "" } else { ", " };

        // WARNING: TinyTDS does not support native parameterized queries.
        if !matches!(analyzed.command, QueryCommand::Batch) {
            let _ = writeln!(out, "  def self.{}(client{}{})", func_name, sep, param_list);
        }

        match &analyzed.command {
            QueryCommand::One => {
                if params.is_empty() {
                    let _ = writeln!(out, "    result = client.execute(\"{}\").first", sql);
                } else {
                    let params_info: Vec<(String, String, bool)> = params
                        .iter()
                        .map(|p| (p.neutral_type.clone(), p.field_name.clone(), p.nullable))
                        .collect();
                    let inlined_sql = inline_params(&sql, &params_info);
                    let _ = writeln!(out, "    sql = \"{}\"", inlined_sql);
                    let _ = writeln!(out, "    result = client.execute(sql).first");
                }
                let _ = writeln!(
                    out,
                    "    raise RecordNotFound, \"{}: no row found\" if result.nil?",
                    func_name
                );

                let fields = columns
                    .iter()
                    .map(|c| format!("{}: result[\"{}\"]", c.field_name, c.name))
                    .collect::<Vec<_>>()
                    .join(", ");
                let _ = writeln!(out, "    {}.new({})", struct_name, fields);
            }
            QueryCommand::Opt => {
                if params.is_empty() {
                    let _ = writeln!(out, "    result = client.execute(\"{}\").first", sql);
                } else {
                    let params_info: Vec<(String, String, bool)> = params
                        .iter()
                        .map(|p| (p.neutral_type.clone(), p.field_name.clone(), p.nullable))
                        .collect();
                    let inlined_sql = inline_params(&sql, &params_info);
                    let _ = writeln!(out, "    sql = \"{}\"", inlined_sql);
                    let _ = writeln!(out, "    result = client.execute(sql).first");
                }
                let _ = writeln!(out, "    return nil if result.nil?");

                let fields = columns
                    .iter()
                    .map(|c| format!("{}: result[\"{}\"]", c.field_name, c.name))
                    .collect::<Vec<_>>()
                    .join(", ");
                let _ = writeln!(out, "    {}.new({})", struct_name, fields);
            }
            QueryCommand::Batch => {
                let batch_fn_name = format!("{}_batch", func_name);
                let _ = writeln!(out, "  def self.{}(client, items)", batch_fn_name);
                let _ = writeln!(out, "    items.each do |item|");
                if params.is_empty() {
                    let _ = writeln!(out, "      client.execute(\"{}\").do", sql);
                } else {
                    let params_info: Vec<(String, String, bool)> = params
                        .iter()
                        .map(|p| {
                            let var_access = if params.len() == 1 {
                                "item".to_string()
                            } else {
                                format!("item[:{}]", p.field_name)
                            };
                            (p.neutral_type.clone(), var_access, p.nullable)
                        })
                        .collect();
                    let inlined_sql = inline_params(&sql, &params_info);
                    let _ = writeln!(out, "      sql = \"{}\"", inlined_sql);
                    let _ = writeln!(out, "      client.execute(sql).do");
                }
                let _ = writeln!(out, "    end");
                let _ = write!(out, "  end");
                return Ok(out);
            }
            QueryCommand::Many => {
                if params.is_empty() {
                    let _ = writeln!(out, "    results = client.execute(\"{}\")", sql);
                } else {
                    let params_info: Vec<(String, String, bool)> = params
                        .iter()
                        .map(|p| (p.neutral_type.clone(), p.field_name.clone(), p.nullable))
                        .collect();
                    let inlined_sql = inline_params(&sql, &params_info);
                    let _ = writeln!(out, "    sql = \"{}\"", inlined_sql);
                    let _ = writeln!(out, "    results = client.execute(sql)");
                }
                let _ = writeln!(out, "    results.map do |row|");
                let fields = columns
                    .iter()
                    .map(|c| format!("{}: row[\"{}\"]", c.field_name, c.name))
                    .collect::<Vec<_>>()
                    .join(", ");
                let _ = writeln!(out, "      {}.new({})", struct_name, fields);
                let _ = writeln!(out, "    end");
            }
            QueryCommand::Exec => {
                if params.is_empty() {
                    let _ = writeln!(out, "    client.execute(\"{}\").do", sql);
                } else {
                    let params_info: Vec<(String, String, bool)> = params
                        .iter()
                        .map(|p| (p.neutral_type.clone(), p.field_name.clone(), p.nullable))
                        .collect();
                    let inlined_sql = inline_params(&sql, &params_info);
                    let _ = writeln!(out, "    sql = \"{}\"", inlined_sql);
                    let _ = writeln!(out, "    client.execute(sql).do");
                }
                let _ = writeln!(out, "    nil");
            }
            QueryCommand::ExecResult | QueryCommand::ExecRows => {
                if params.is_empty() {
                    let _ = writeln!(out, "    client.execute(\"{}\").affected_rows", sql);
                } else {
                    let params_info: Vec<(String, String, bool)> = params
                        .iter()
                        .map(|p| (p.neutral_type.clone(), p.field_name.clone(), p.nullable))
                        .collect();
                    let inlined_sql = inline_params(&sql, &params_info);
                    let _ = writeln!(out, "    sql = \"{}\"", inlined_sql);
                    let _ = writeln!(out, "    client.execute(sql).affected_rows");
                }
            }
            QueryCommand::Grouped => unreachable!("handled by generate_grouped_query_fn"),
        }

        let _ = write!(out, "  end");
        Ok(out)
    }

    fn generate_grouped_structs(
        &self,
        parent_struct_name: &str,
        child_struct_name: &str,
        parent_columns: &[ResolvedColumn],
        child_columns: &[ResolvedColumn],
        _key_column: &str,
    ) -> Result<String, ScytheError> {
        Ok(super::ruby_rbs::generate_grouped_structs_ruby(
            parent_struct_name,
            child_struct_name,
            parent_columns,
            child_columns,
        ))
    }

    fn generate_grouped_query_fn(&self, request: &GroupedQueryFn<'_>) -> Result<String, ScytheError> {
        let analyzed = request.analyzed;
        let parent_struct_name = request.parent_struct_name;
        let child_struct_name = request.child_struct_name;
        let parent_columns = request.parent_columns;
        let child_columns = request.child_columns;
        let params = request.params;
        let key_column = request.key_column;

        let func_name = fn_name(&analyzed.name, &self.manifest.naming);
        let sql = crate::sql_literal::escape_ruby_double_quoted(&super::clean_sql_with_optional(
            &analyzed.sql,
            &analyzed.optional_params,
            &analyzed.params,
        ));

        let param_list = params
            .iter()
            .map(|p| p.field_name.clone())
            .collect::<Vec<_>>()
            .join(", ");
        let sep = if param_list.is_empty() { "" } else { ", " };

        let sql_with_placeholders = {
            let mut s = sql.clone();
            let mut n = 1u32;
            while let Some(pos) = s.find('$') {
                let end = s[pos + 1..]
                    .find(|c: char| !c.is_ascii_digit())
                    .map_or(s.len(), |i| pos + 1 + i);
                s.replace_range(pos..end, &format!("@p{n}"));
                n += 1;
            }
            s
        };

        let final_sql = if params.is_empty() {
            sql_with_placeholders.clone()
        } else {
            sql_with_placeholders
        };

        let mut out = String::new();
        let _ = writeln!(out, "  def self.{}(client{}{})", func_name, sep, param_list);
        if params.is_empty() {
            let _ = writeln!(out, "    results = client.execute(\"{}\")", final_sql);
        } else {
            let _ = writeln!(out, "    sql = \"{}\"", final_sql);
            let params_hash = params
                .iter()
                .enumerate()
                .map(|(i, p)| format!("\"@p{}\": {}", i + 1, p.field_name))
                .collect::<Vec<_>>()
                .join(", ");
            let _ = writeln!(out, "    results = client.execute(sql, {{{}}})", params_hash);
        }
        let _ = writeln!(out, "    _index = {{}}");
        let _ = writeln!(out, "    _entries = []");
        let _ = writeln!(out, "    results.each do |row|");
        let _ = writeln!(out, "      key = row[\"{}\"]", key_column);
        let _ = writeln!(out, "      unless _index.key?(key)");
        let _ = writeln!(out, "        _index[key] = _entries.size");
        let _ = writeln!(out, "        _entries << {{");
        for col in parent_columns {
            let _ = writeln!(out, "          {}: row[\"{}\"],", col.field_name, col.name);
        }
        let _ = writeln!(out, "          children: []");
        let _ = writeln!(out, "        }}");
        let _ = writeln!(out, "      end");
        let _ = writeln!(
            out,
            "      _entries[_index[key]][:children] << {}.new(",
            child_struct_name
        );
        for col in child_columns {
            let _ = writeln!(out, "        {}: row[\"{}\"],", col.field_name, col.name);
        }
        let _ = writeln!(out, "      )");
        let _ = writeln!(out, "    end");
        let _ = writeln!(out, "    _entries.map {{ |e| {}.new(**e) }}", parent_struct_name);
        let _ = write!(out, "  end");

        Ok(out)
    }

    fn generate_enum_def(&self, enum_info: &EnumInfo) -> Result<String, ScytheError> {
        let type_name = enum_type_name(&enum_info.sql_name, &self.manifest.naming);
        let mut out = String::new();
        let _ = writeln!(out, "  module {}", type_name);
        for value in &enum_info.values {
            let variant = enum_variant_name(value, &self.manifest.naming);
            let _ = writeln!(out, "    {} = \"{}\"", variant, value);
        }
        let all_values = enum_info
            .values
            .iter()
            .map(|v| enum_variant_name(v, &self.manifest.naming))
            .collect::<Vec<_>>()
            .join(", ");
        let _ = writeln!(out, "    ALL = [{}].freeze", all_values);
        let _ = write!(out, "  end");
        Ok(out)
    }

    fn generate_composite_def(&self, composite: &CompositeInfo) -> Result<String, ScytheError> {
        let name = composite_type_name(&composite.sql_name, &self.manifest.naming);
        let mut out = String::new();
        if composite.fields.is_empty() {
            let _ = writeln!(out, "  {} = Data.define()", name);
        } else {
            let fields = composite
                .fields
                .iter()
                .map(|f| format!(":{}", f.name))
                .collect::<Vec<_>>()
                .join(", ");
            let _ = writeln!(out, "  {} = Data.define({})", name, fields);
        }
        Ok(out)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use scythe_core::analyzer::{AnalyzedColumn, AnalyzedQuery, GroupByConfig};
    use scythe_core::parser::QueryCommand;

    fn make_grouped_query() -> AnalyzedQuery {
        let parent_cols = vec![
            AnalyzedColumn {
                name: "id".to_string(),
                neutral_type: "int32".to_string(),
                nullable: false,
                ..Default::default()
            },
            AnalyzedColumn {
                name: "name".to_string(),
                neutral_type: "string".to_string(),
                nullable: false,
                ..Default::default()
            },
            AnalyzedColumn {
                name: "email".to_string(),
                neutral_type: "string".to_string(),
                nullable: false,
                ..Default::default()
            },
        ];
        let child_cols = vec![
            AnalyzedColumn {
                name: "order_id".to_string(),
                neutral_type: "int32".to_string(),
                nullable: false,
                ..Default::default()
            },
            AnalyzedColumn {
                name: "total".to_string(),
                neutral_type: "decimal".to_string(),
                nullable: true,
                ..Default::default()
            },
            AnalyzedColumn {
                name: "order_date".to_string(),
                neutral_type: "datetime".to_string(),
                nullable: false,
                ..Default::default()
            },
        ];
        let all_cols = [parent_cols.clone(), child_cols.clone()].concat();
        AnalyzedQuery::build(|aq| {
            aq.name = "GetUsersWithOrders".to_string();
            aq.command = QueryCommand::Grouped;
            aq.sql = "SELECT u.id, u.name, u.email, o.id AS order_id, o.total, o.created_at AS order_date\nFROM users u\nJOIN orders o ON o.user_id = u.id".to_string();
            aq.columns = all_cols;
            aq.params = vec![];
            aq.deprecated = None;
            aq.source_table = None;
            aq.composites = vec![];
            aq.enums = vec![];
            aq.optional_params = vec![];
            aq.group_by = Some(GroupByConfig {
                table: "users".to_string(),
                key_column: "id".to_string(),
                parent_columns: parent_cols,
                child_columns: child_cols,
            });
            aq.custom = vec![];
        })
    }

    #[test]
    fn test_grouped_ruby_tiny_tds_structs() {
        let backend = RubyTinyTdsBackend::new("mssql").unwrap();
        let query = make_grouped_query();
        let result = crate::generate_with_backend(&query, &backend).unwrap();

        let row_struct = result.row_struct.as_deref().unwrap();
        assert!(
            row_struct.contains("GetUsersWithOrdersChildRow = Data.define(:order_id, :total, :order_date)"),
            "missing child struct; got:\n{row_struct}"
        );
        assert!(
            row_struct.contains("GetUsersWithOrdersRow = Data.define(:id, :name, :email, :children)"),
            "missing parent struct; got:\n{row_struct}"
        );
        let child_pos = row_struct.find("GetUsersWithOrdersChildRow").unwrap();
        let parent_pos = row_struct.find("GetUsersWithOrdersRow = Data.define").unwrap();
        assert!(child_pos < parent_pos, "child struct must appear before parent struct");
    }

    #[test]
    fn test_grouped_ruby_tiny_tds_query_fn() {
        let backend = RubyTinyTdsBackend::new("mssql").unwrap();
        let query = make_grouped_query();
        let result = crate::generate_with_backend(&query, &backend).unwrap();

        let query_fn = result.query_fn.as_deref().unwrap();
        assert!(
            query_fn.contains("def self.get_users_with_orders(client)"),
            "missing fn; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("client.execute("),
            "must use client.execute; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("key = row[\"id\"]"),
            "must access key by string; got:\n{query_fn}"
        );
        assert!(query_fn.contains("_index = {}"), "must use _index; got:\n{query_fn}");
        assert!(
            query_fn.contains("GetUsersWithOrdersChildRow.new("),
            "must construct child struct; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("GetUsersWithOrdersRow.new(**e)"),
            "must fold into parent; got:\n{query_fn}"
        );
    }
}