|
| 1 | +"""Generator: SchemaForge IR → C# Entity Framework Core entity classes.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +from ..ir import Schema, Column, ColumnType |
| 5 | + |
| 6 | +from ._base import resolve_type, build_type_string |
| 7 | + |
| 8 | + |
| 9 | +class EntityFrameworkGenerator: |
| 10 | + """Convert Schema IR to C# Entity Framework Core entity classes.""" |
| 11 | + |
| 12 | + _TYPE_MAP: dict[ColumnType, str] = { |
| 13 | + ColumnType.STRING: "string", |
| 14 | + ColumnType.INTEGER: "int", |
| 15 | + ColumnType.FLOAT: "double", |
| 16 | + ColumnType.BOOLEAN: "bool", |
| 17 | + ColumnType.DATETIME: "DateTime", |
| 18 | + ColumnType.DATE: "DateOnly", |
| 19 | + ColumnType.TIME: "TimeOnly", |
| 20 | + ColumnType.TEXT: "string", |
| 21 | + ColumnType.BLOB: "byte[]", |
| 22 | + ColumnType.JSON: "string", |
| 23 | + ColumnType.UUID: "Guid", |
| 24 | + ColumnType.ENUM: "string", |
| 25 | + ColumnType.DECIMAL: "decimal", |
| 26 | + } |
| 27 | + |
| 28 | + def __init__(self, type_config=None): |
| 29 | + """Initialize generator with optional type config.""" |
| 30 | + self.type_config = type_config |
| 31 | + |
| 32 | + def generate(self, schema: Schema) -> str: |
| 33 | + """Generate C# entity classes from schema IR.""" |
| 34 | + parts: list[str] = [ |
| 35 | + "using System;", |
| 36 | + "using System.ComponentModel.DataAnnotations;", |
| 37 | + "using System.ComponentModel.DataAnnotations.Schema;", |
| 38 | + "", |
| 39 | + "namespace SchemaForge.Models;", |
| 40 | + "", |
| 41 | + ] |
| 42 | + |
| 43 | + for table in schema.tables: |
| 44 | + parts.append(self._generate_class(table)) |
| 45 | + |
| 46 | + return "\n".join(parts) |
| 47 | + |
| 48 | + def _generate_class(self, table) -> str: |
| 49 | + """Generate a single entity class.""" |
| 50 | + lines: list[str] = [] |
| 51 | + |
| 52 | + # [Table] annotation if name differs from class name |
| 53 | + class_name = self._to_pascal(table.name) |
| 54 | + if table.name.lower() != class_name.lower(): |
| 55 | + lines.append(f'[Table("{table.name}")]') |
| 56 | + |
| 57 | + lines.append(f"public class {class_name}") |
| 58 | + lines.append("{") |
| 59 | + |
| 60 | + for col in table.columns: |
| 61 | + lines.append(f" {self._property_def(col)}") |
| 62 | + |
| 63 | + lines.append("}") |
| 64 | + return "\n".join(lines) |
| 65 | + |
| 66 | + def _property_def(self, col: Column) -> str: |
| 67 | + """Generate a C# property with data annotations.""" |
| 68 | + annotations: list[str] = [] |
| 69 | + cs_type = resolve_type(col, self._TYPE_MAP) |
| 70 | + prop_name = self._to_pascal(col.name) |
| 71 | + |
| 72 | + # Data annotations |
| 73 | + if col.primary_key: |
| 74 | + annotations.append("[Key]") |
| 75 | + |
| 76 | + if not col.nullable and not col.primary_key: |
| 77 | + annotations.append("[Required]") |
| 78 | + |
| 79 | + if col.type == ColumnType.STRING and "length" in col.type_args: |
| 80 | + annotations.append(f"[MaxLength({col.type_args['length']})]") |
| 81 | + |
| 82 | + if col.type == ColumnType.DECIMAL: |
| 83 | + p = col.type_args.get("precision", 10) |
| 84 | + s = col.type_args.get("scale", 2) |
| 85 | + annotations.append(f"[Column(TypeName = \"decimal({p},{s})\")]") |
| 86 | + |
| 87 | + if col.unique and not col.primary_key: |
| 88 | + # EF Index attribute |
| 89 | + pass # Handled at the DbContext level, not on properties |
| 90 | + |
| 91 | + # Handle nullable reference types |
| 92 | + is_nullable = col.nullable and cs_type != "byte[]" |
| 93 | + cs_type_str = f"{cs_type}?" if is_nullable else cs_type |
| 94 | + |
| 95 | + # Default value |
| 96 | + default_str = "" |
| 97 | + if col.default is not None: |
| 98 | + if isinstance(col.default, bool): |
| 99 | + default_str = f" = {str(col.default).lower()};" |
| 100 | + elif isinstance(col.default, str) and col.default.startswith("fn:"): |
| 101 | + pass # Skip function defaults in C# |
| 102 | + elif isinstance(col.default, str): |
| 103 | + default_str = f' = "{col.default}";' |
| 104 | + elif isinstance(col.default, (int, float)): |
| 105 | + default_str = f" = {col.default};" |
| 106 | + |
| 107 | + ann_str = " ".join(annotations) |
| 108 | + if ann_str: |
| 109 | + ann_str += "\n " |
| 110 | + |
| 111 | + # Use List<T> for JSON columns (simple approximation) |
| 112 | + if col.type == ColumnType.JSON: |
| 113 | + cs_type_str = "string" |
| 114 | + |
| 115 | + return f"{ann_str}public {cs_type_str} {prop_name} {{ get; set; }}{default_str}" |
| 116 | + |
| 117 | + def _to_pascal(self, name: str) -> str: |
| 118 | + """Convert snake_case to PascalCase.""" |
| 119 | + parts = name.split("_") |
| 120 | + return "".join(p.capitalize() for p in parts if p) |
0 commit comments