scythe-codegen 0.6.8

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
use std::fmt::Write;

use scythe_backend::manifest::BackendManifest;
use scythe_backend::naming::{
    enum_type_name, enum_variant_name, fn_name, row_struct_name, to_pascal_case,
};
use scythe_backend::types::resolve_type;

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

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

const DEFAULT_MANIFEST_TOML: &str = include_str!("../../manifests/csharp-oracle.toml");

pub struct CsharpOracleBackend {
    manifest: BackendManifest,
}

impl CsharpOracleBackend {
    pub fn new(engine: &str) -> Result<Self, ScytheError> {
        match engine {
            "oracle" => {}
            _ => {
                return Err(ScytheError::new(
                    ErrorCode::InternalError,
                    format!(
                        "csharp-oracle only supports Oracle, got engine '{}'",
                        engine
                    ),
                ));
            }
        }
        let manifest = super::load_or_default_manifest(
            "backends/csharp-oracle/manifest.toml",
            DEFAULT_MANIFEST_TOML,
        )?;
        Ok(Self { manifest })
    }
}

/// Map a neutral type to an OracleDbType variant for output parameters.
fn oracle_db_type(neutral_type: &str) -> &'static str {
    match neutral_type {
        "int32" | "int64" => "OracleDbType.Int64",
        "float32" | "float64" => "OracleDbType.Double",
        "decimal" => "OracleDbType.Decimal",
        "date" | "datetime" | "datetime_tz" => "OracleDbType.Date",
        _ => "OracleDbType.Varchar2",
    }
}

/// Cast an Oracle output parameter value to the appropriate C# type.
fn oracle_out_cast(neutral_type: &str, param_expr: &str) -> String {
    match neutral_type {
        "int32" => format!(
            "((Oracle.ManagedDataAccess.Types.OracleDecimal){}).ToInt32()",
            param_expr
        ),
        "int64" => format!(
            "((Oracle.ManagedDataAccess.Types.OracleDecimal){}).ToInt64()",
            param_expr
        ),
        "float32" | "float64" => format!(
            "((Oracle.ManagedDataAccess.Types.OracleDecimal){}).ToDouble()",
            param_expr
        ),
        "decimal" => format!(
            "((Oracle.ManagedDataAccess.Types.OracleDecimal){}).ToDecimal()",
            param_expr
        ),
        "date" | "datetime" | "datetime_tz" => format!(
            "((Oracle.ManagedDataAccess.Types.OracleDate){}).Value",
            param_expr
        ),
        _ => format!(
            "((Oracle.ManagedDataAccess.Types.OracleString){}).Value",
            param_expr
        ),
    }
}

/// Map a neutral type to an OracleDataReader method.
fn reader_method(neutral_type: &str) -> &'static str {
    match neutral_type {
        "bool" => "GetBoolean",
        "int16" => "GetInt16",
        "int32" => "GetInt32",
        "int64" => "GetInt64",
        "float32" => "GetFloat",
        "float64" => "GetDouble",
        "string" | "json" | "inet" | "interval" | "uuid" => "GetString",
        "decimal" => "GetDecimal",
        "date" | "datetime" => "GetDateTime",
        "datetime_tz" => "GetFieldValue<DateTimeOffset>",
        "time" | "time_tz" => "GetFieldValue<TimeOnly>",
        _ => "GetValue",
    }
}

impl CodegenBackend for CsharpOracleBackend {
    fn name(&self) -> &str {
        "csharp-oracle"
    }

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

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

    fn file_header(&self) -> String {
        "// Auto-generated by scythe. Do not edit.\n#nullable enable\n\nusing Oracle.ManagedDataAccess.Client;\n\npublic static class Queries {"
            .to_string()
    }

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

    fn generate_row_struct(
        &self,
        query_name: &str,
        columns: &[ResolvedColumn],
    ) -> Result<String, ScytheError> {
        let struct_name = row_struct_name(query_name, &self.manifest.naming);
        let mut out = String::new();
        let _ = writeln!(out, "public record {}(", struct_name);
        for (i, c) in columns.iter().enumerate() {
            let field = to_pascal_case(&c.field_name);
            let sep = if i + 1 < columns.len() { "," } else { "" };
            let _ = writeln!(out, "    {} {}{}", c.full_type, field, sep);
        }
        let _ = write!(out, ");");
        Ok(out)
    }

    fn generate_model_struct(
        &self,
        table_name: &str,
        columns: &[ResolvedColumn],
    ) -> Result<String, ScytheError> {
        let name = to_pascal_case(table_name);
        self.generate_row_struct(&name, columns)
    }

    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 = super::rewrite_pg_placeholders(
            &super::clean_sql_oneline_with_optional(
                &analyzed.sql,
                &analyzed.optional_params,
                &analyzed.params,
            ),
            |n| format!(":{n}"),
        );
        let mut out = String::new();

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

        if matches!(analyzed.command, QueryCommand::Batch) {
            let batch_fn_name = format!("{}Batch", func_name);
            if params.len() > 1 {
                let params_record_name = format!("{}BatchParams", to_pascal_case(&analyzed.name));
                let _ = writeln!(out, "public record {}(", params_record_name);
                for (i, p) in params.iter().enumerate() {
                    let field = to_pascal_case(&p.field_name);
                    let sep = if i + 1 < params.len() { "," } else { "" };
                    let _ = writeln!(out, "    {} {}{}", p.full_type, field, sep);
                }
                let _ = writeln!(out, ");");
                let _ = writeln!(out);
                let _ = writeln!(
                    out,
                    "public static async Task {}(OracleConnection conn, List<{}> items) {{",
                    batch_fn_name, params_record_name
                );
            } else if params.len() == 1 {
                let _ = writeln!(
                    out,
                    "public static async Task {}(OracleConnection conn, List<{}> items) {{",
                    batch_fn_name, params[0].full_type
                );
            } else {
                let _ = writeln!(
                    out,
                    "public static async Task {}(OracleConnection conn, int count) {{",
                    batch_fn_name
                );
            }
            let _ = writeln!(out, "    using var tx = conn.BeginTransaction();");
            let _ = writeln!(out, "    try {{");
            if params.is_empty() {
                let _ = writeln!(out, "        for (int i = 0; i < count; i++) {{");
            } else {
                let _ = writeln!(out, "        foreach (var item in items) {{");
            }
            let _ = writeln!(
                out,
                "            using var cmd = new OracleCommand(\"{}\", conn);",
                sql
            );
            for (i, p) in params.iter().enumerate() {
                let value_expr = if params.len() > 1 {
                    format!("item.{}", to_pascal_case(&p.field_name))
                } else {
                    "item".to_string()
                };
                let _ = format!("{}", i); // suppress unused i warning
                let _ = writeln!(
                    out,
                    "            cmd.Parameters.Add(new OracleParameter {{ Value = (object){} ?? DBNull.Value }});",
                    value_expr
                );
            }
            let _ = writeln!(out, "            await cmd.ExecuteNonQueryAsync();");
            let _ = writeln!(out, "        }}");
            let _ = writeln!(out, "        tx.Commit();");
            let _ = writeln!(out, "    }} catch {{");
            let _ = writeln!(out, "        tx.Rollback();");
            let _ = writeln!(out, "        throw;");
            let _ = writeln!(out, "    }}");
            let _ = write!(out, "}}");
            return Ok(out);
        }

        let return_type = match &analyzed.command {
            QueryCommand::One | QueryCommand::Opt => format!("{}?", struct_name),
            QueryCommand::Many => format!("List<{}>", struct_name),
            QueryCommand::Exec => "void".to_string(),
            QueryCommand::ExecResult | QueryCommand::ExecRows => "int".to_string(),
            QueryCommand::Batch | QueryCommand::Grouped => unreachable!(),
        };

        let is_async_void = return_type == "void";
        let task_type = if is_async_void {
            "Task".to_string()
        } else {
            format!("Task<{}>", return_type)
        };

        // For Oracle RETURNING queries, the SQL must include "INTO :out0, :out1, …" so that
        // Oracle binds the output values. Compute the effective SQL before emitting any code.
        let is_one_returning = matches!(analyzed.command, QueryCommand::One | QueryCommand::Opt)
            && sql.to_uppercase().contains("RETURNING");

        let effective_sql = if is_one_returning {
            let into_clause = columns
                .iter()
                .enumerate()
                .map(|(i, _)| format!(":out{i}"))
                .collect::<Vec<_>>()
                .join(", ");
            format!("{} INTO {}", sql, into_clause)
        } else {
            sql.clone()
        };

        let _ = writeln!(
            out,
            "public static async {} {}(OracleConnection conn{}{}) {{",
            task_type, func_name, sep, param_list
        );

        let _ = writeln!(
            out,
            "    using var cmd = new OracleCommand(\"{}\", conn);",
            effective_sql
        );
        for p in params.iter() {
            let _ = writeln!(
                out,
                "    cmd.Parameters.Add(new OracleParameter {{ Value = (object){} ?? DBNull.Value }});",
                p.field_name
            );
        }

        match &analyzed.command {
            QueryCommand::One | QueryCommand::Opt => {
                if is_one_returning {
                    // Add output parameters and execute without a reader.
                    // VARCHAR2 output params need an explicit size or Oracle ODP.NET returns empty strings.
                    for (i, col) in columns.iter().enumerate() {
                        let db_type = oracle_db_type(&col.neutral_type);
                        let size_part = if db_type == "OracleDbType.Varchar2" {
                            " Size = 4000,".to_string()
                        } else {
                            String::new()
                        };
                        let _ = writeln!(
                            out,
                            "    cmd.Parameters.Add(new OracleParameter {{ ParameterName = \"out{i}\", \
                             OracleDbType = {db_type},{size_part} Direction = System.Data.ParameterDirection.Output }});"
                        );
                    }
                    let _ = writeln!(out, "    await cmd.ExecuteNonQueryAsync();");
                    let _ = writeln!(out, "    return new {}(", struct_name);
                    for (i, col) in columns.iter().enumerate() {
                        let param_expr = format!("cmd.Parameters[\"out{i}\"].Value");
                        let cast = oracle_out_cast(&col.neutral_type, &param_expr);
                        let sep = if i + 1 < columns.len() { "," } else { "" };
                        let _ = writeln!(out, "        {cast}{sep}");
                    }
                    let _ = writeln!(out, "    );");
                } else {
                    let _ = writeln!(
                        out,
                        "    using var reader = await cmd.ExecuteReaderAsync();"
                    );
                    let _ = writeln!(out, "    if (!await reader.ReadAsync()) return null;");
                    let _ = writeln!(out, "    return new {}(", struct_name);
                    for (i, col) in columns.iter().enumerate() {
                        let method = reader_method(&col.neutral_type);
                        let sep = if i + 1 < columns.len() { "," } else { "" };
                        if col.nullable {
                            let _ = writeln!(
                                out,
                                "        reader.IsDBNull({i}) ? null : reader.{method}({i}){sep}"
                            );
                        } else {
                            let _ = writeln!(out, "        reader.{method}({i}){sep}");
                        }
                    }
                    let _ = writeln!(out, "    );");
                }
            }
            QueryCommand::Many => {
                let _ = writeln!(
                    out,
                    "    using var reader = await cmd.ExecuteReaderAsync();"
                );
                let _ = writeln!(out, "    var results = new List<{}>();", struct_name);
                let _ = writeln!(out, "    while (await reader.ReadAsync()) {{");
                let _ = writeln!(out, "        results.Add(new {}(", struct_name);
                for (i, col) in columns.iter().enumerate() {
                    let method = reader_method(&col.neutral_type);
                    let sep = if i + 1 < columns.len() { "," } else { "" };
                    if col.nullable {
                        let _ = writeln!(
                            out,
                            "            reader.IsDBNull({i}) ? null : reader.{method}({i}){sep}"
                        );
                    } else {
                        let _ = writeln!(out, "            reader.{method}({i}){sep}");
                    }
                }
                let _ = writeln!(out, "        ));");
                let _ = writeln!(out, "    }}");
                let _ = writeln!(out, "    return results;");
            }
            QueryCommand::Exec => {
                let _ = writeln!(out, "    await cmd.ExecuteNonQueryAsync();");
            }
            QueryCommand::ExecResult | QueryCommand::ExecRows => {
                let _ = writeln!(out, "    return await cmd.ExecuteNonQueryAsync();");
            }
            QueryCommand::Batch | QueryCommand::Grouped => unreachable!(),
        }

        let _ = write!(out, "}}");
        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, "public enum {} {{", type_name);
        for value in &enum_info.values {
            let variant = enum_variant_name(value, &self.manifest.naming);
            let _ = writeln!(out, "    {},", variant);
        }
        let _ = write!(out, "}}");
        Ok(out)
    }

    fn generate_composite_def(&self, composite: &CompositeInfo) -> Result<String, ScytheError> {
        let name = to_pascal_case(&composite.sql_name);
        let mut out = String::new();
        if composite.fields.is_empty() {
            let _ = writeln!(out, "public record {}();", name);
        } else {
            let _ = writeln!(out, "public record {}(", name);
            for (i, field) in composite.fields.iter().enumerate() {
                let cs_type = resolve_type(&field.neutral_type, &self.manifest, false)
                    .map(|t| t.into_owned())
                    .unwrap_or_else(|_| "object".to_string());
                let field_name = to_pascal_case(&field.name);
                let sep = if i + 1 < composite.fields.len() {
                    ","
                } else {
                    ""
                };
                let _ = writeln!(out, "    {} {}{}", cs_type, field_name, sep);
            }
            let _ = write!(out, ");");
        }
        Ok(out)
    }
}