• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

agronholm / sqlacodegen / 21780407216

07 Feb 2026 12:53PM UTC coverage: 97.572% (+0.05%) from 97.519%
21780407216

Pull #455

github

web-flow
Merge 6094294b2 into e9bfd344c
Pull Request #455: Support enum arrays

55 of 55 new or added lines in 3 files covered. (100.0%)

11 existing lines in 1 file now uncovered.

1728 of 1771 relevant lines covered (97.57%)

4.88 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.59
/src/sqlacodegen/generators.py
1
from __future__ import annotations
5✔
2

3
import inspect
5✔
4
import re
5✔
5
import sys
5✔
6
from abc import ABCMeta, abstractmethod
5✔
7
from collections import defaultdict
5✔
8
from collections.abc import Collection, Iterable, Sequence
5✔
9
from dataclasses import dataclass
5✔
10
from importlib import import_module
5✔
11
from inspect import Parameter
5✔
12
from itertools import count
5✔
13
from keyword import iskeyword
5✔
14
from pprint import pformat
5✔
15
from textwrap import indent
5✔
16
from typing import Any, ClassVar, Literal, cast
5✔
17

18
import inflect
5✔
19
import sqlalchemy
5✔
20
from sqlalchemy import (
5✔
21
    ARRAY,
22
    Boolean,
23
    CheckConstraint,
24
    Column,
25
    Computed,
26
    Constraint,
27
    DefaultClause,
28
    Enum,
29
    ForeignKey,
30
    ForeignKeyConstraint,
31
    Identity,
32
    Index,
33
    MetaData,
34
    PrimaryKeyConstraint,
35
    String,
36
    Table,
37
    Text,
38
    TypeDecorator,
39
    UniqueConstraint,
40
)
41
from sqlalchemy.dialects.postgresql import DOMAIN, JSON, JSONB
5✔
42
from sqlalchemy.engine import Connection, Engine
5✔
43
from sqlalchemy.exc import CompileError
5✔
44
from sqlalchemy.sql.elements import TextClause
5✔
45
from sqlalchemy.sql.type_api import UserDefinedType
5✔
46
from sqlalchemy.types import TypeEngine
5✔
47

48
from .models import (
5✔
49
    ColumnAttribute,
50
    JoinType,
51
    Model,
52
    ModelClass,
53
    RelationshipAttribute,
54
    RelationshipType,
55
)
56
from .utils import (
5✔
57
    decode_postgresql_sequence,
58
    get_column_names,
59
    get_common_fk_constraints,
60
    get_compiled_expression,
61
    get_constraint_sort_key,
62
    get_stdlib_module_names,
63
    qualified_table_name,
64
    render_callable,
65
    uses_default_name,
66
)
67

68
_re_boolean_check_constraint = re.compile(r"(?:.*?\.)?(.*?) IN \(0, 1\)")
5✔
69
_re_column_name = re.compile(r'(?:(["`]?).*\1\.)?(["`]?)(.*)\2')
5✔
70
_re_enum_check_constraint = re.compile(r"(?:.*?\.)?(.*?) IN \((.+)\)")
5✔
71
_re_enum_item = re.compile(r"'(.*?)(?<!\\)'")
5✔
72
_re_invalid_identifier = re.compile(r"(?u)\W")
5✔
73

74

75
@dataclass
5✔
76
class LiteralImport:
5✔
77
    pkgname: str
5✔
78
    name: str
5✔
79

80

81
@dataclass
5✔
82
class Base:
5✔
83
    """Representation of MetaData for Tables, respectively Base for classes"""
84

85
    literal_imports: list[LiteralImport]
5✔
86
    declarations: list[str]
5✔
87
    metadata_ref: str
5✔
88
    decorator: str | None = None
5✔
89
    table_metadata_declaration: str | None = None
5✔
90

91

92
class CodeGenerator(metaclass=ABCMeta):
5✔
93
    valid_options: ClassVar[set[str]] = set()
5✔
94

95
    def __init__(
5✔
96
        self, metadata: MetaData, bind: Connection | Engine, options: Sequence[str]
97
    ):
98
        self.metadata: MetaData = metadata
5✔
99
        self.bind: Connection | Engine = bind
5✔
100
        self.options: set[str] = set(options)
5✔
101

102
        # Validate options
103
        invalid_options = {opt for opt in options if opt not in self.valid_options}
5✔
104
        if invalid_options:
5✔
105
            raise ValueError("Unrecognized options: " + ", ".join(invalid_options))
×
106

107
    @property
5✔
108
    @abstractmethod
5✔
109
    def views_supported(self) -> bool:
5✔
110
        pass
×
111

112
    @abstractmethod
5✔
113
    def generate(self) -> str:
5✔
114
        """
115
        Generate the code for the given metadata.
116
        .. note:: May modify the metadata.
117
        """
118

119

120
@dataclass(eq=False)
5✔
121
class TablesGenerator(CodeGenerator):
5✔
122
    valid_options: ClassVar[set[str]] = {
5✔
123
        "noindexes",
124
        "noconstraints",
125
        "nocomments",
126
        "nonativeenums",
127
        "nosyntheticenums",
128
        "include_dialect_options",
129
        "keep_dialect_types",
130
    }
131
    stdlib_module_names: ClassVar[set[str]] = get_stdlib_module_names()
5✔
132

133
    def __init__(
5✔
134
        self,
135
        metadata: MetaData,
136
        bind: Connection | Engine,
137
        options: Sequence[str],
138
        *,
139
        indentation: str = "    ",
140
    ):
141
        super().__init__(metadata, bind, options)
5✔
142
        self.indentation: str = indentation
5✔
143
        self.imports: dict[str, set[str]] = defaultdict(set)
5✔
144
        self.module_imports: set[str] = set()
5✔
145

146
        # Render SchemaItem.info and dialect kwargs (Table/Column) into output
147
        self.include_dialect_options_and_info: bool = (
5✔
148
            "include_dialect_options" in self.options
149
        )
150
        # Keep dialect-specific types instead of adapting to generic SQLAlchemy types
151
        self.keep_dialect_types: bool = "keep_dialect_types" in self.options
5✔
152

153
        # Track Python enum classes: maps (table_name, column_name) -> enum_class_name
154
        self.enum_classes: dict[tuple[str, str], str] = {}
5✔
155
        # Track enum values: maps enum_class_name -> list of values
156
        self.enum_values: dict[str, list[str]] = {}
5✔
157

158
    @property
5✔
159
    def views_supported(self) -> bool:
5✔
160
        return True
×
161

162
    def generate_base(self) -> None:
5✔
163
        self.base = Base(
5✔
164
            literal_imports=[LiteralImport("sqlalchemy", "MetaData")],
165
            declarations=["metadata = MetaData()"],
166
            metadata_ref="metadata",
167
        )
168

169
    def generate(self) -> str:
5✔
170
        self.generate_base()
5✔
171

172
        sections: list[str] = []
5✔
173

174
        # Remove unwanted elements from the metadata
175
        for table in list(self.metadata.tables.values()):
5✔
176
            if self.should_ignore_table(table):
5✔
177
                self.metadata.remove(table)
×
178
                continue
×
179

180
            if "noindexes" in self.options:
5✔
181
                table.indexes.clear()
5✔
182

183
            if "noconstraints" in self.options:
5✔
184
                table.constraints.clear()
5✔
185

186
            if "nocomments" in self.options:
5✔
187
                table.comment = None
5✔
188

189
            for column in table.columns:
5✔
190
                if "nocomments" in self.options:
5✔
191
                    column.comment = None
5✔
192

193
        # Use information from column constraints to figure out the intended column
194
        # types
195
        for table in self.metadata.tables.values():
5✔
196
            self.fix_column_types(table)
5✔
197

198
        # Generate the models
199
        models: list[Model] = self.generate_models()
5✔
200

201
        # Render module level variables
202
        if variables := self.render_module_variables(models):
5✔
203
            sections.append(variables + "\n")
5✔
204

205
        # Render enum classes
206
        if enum_classes := self.render_enum_classes():
5✔
207
            sections.append(enum_classes + "\n")
5✔
208

209
        # Render models
210
        if rendered_models := self.render_models(models):
5✔
211
            sections.append(rendered_models)
5✔
212

213
        # Render collected imports
214
        groups = self.group_imports()
5✔
215
        if imports := "\n\n".join(
5✔
216
            "\n".join(line for line in group) for group in groups
217
        ):
218
            sections.insert(0, imports)
5✔
219

220
        return "\n\n".join(sections) + "\n"
5✔
221

222
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
223
        for literal_import in self.base.literal_imports:
5✔
224
            self.add_literal_import(literal_import.pkgname, literal_import.name)
5✔
225

226
        for model in models:
5✔
227
            self.collect_imports_for_model(model)
5✔
228

229
    def collect_imports_for_model(self, model: Model) -> None:
5✔
230
        if model.__class__ is Model:
5✔
231
            self.add_import(Table)
5✔
232

233
        for column in model.table.c:
5✔
234
            self.collect_imports_for_column(column)
5✔
235

236
        for constraint in model.table.constraints:
5✔
237
            self.collect_imports_for_constraint(constraint)
5✔
238

239
        for index in model.table.indexes:
5✔
240
            self.collect_imports_for_constraint(index)
5✔
241

242
    def collect_imports_for_column(self, column: Column[Any]) -> None:
5✔
243
        self.add_import(column.type)
5✔
244

245
        if isinstance(column.type, ARRAY):
5✔
246
            self.add_import(column.type.item_type.__class__)
5✔
247
        elif isinstance(column.type, (JSONB, JSON)):
5✔
248
            if (
5✔
249
                not isinstance(column.type.astext_type, Text)
250
                or column.type.astext_type.length is not None
251
            ):
252
                self.add_import(column.type.astext_type)
5✔
253
        elif isinstance(column.type, DOMAIN):
5✔
254
            self.add_import(column.type.data_type.__class__)
5✔
255

256
        if column.default:
5✔
257
            self.add_import(column.default)
5✔
258

259
        if column.server_default:
5✔
260
            if isinstance(column.server_default, (Computed, Identity)):
5✔
261
                self.add_import(column.server_default)
5✔
262
            elif isinstance(column.server_default, DefaultClause):
5✔
263
                self.add_literal_import("sqlalchemy", "text")
5✔
264

265
    def collect_imports_for_constraint(self, constraint: Constraint | Index) -> None:
5✔
266
        if isinstance(constraint, Index):
5✔
267
            if len(constraint.columns) > 1 or not uses_default_name(constraint):
5✔
268
                self.add_literal_import("sqlalchemy", "Index")
5✔
269
        elif isinstance(constraint, PrimaryKeyConstraint):
5✔
270
            if not uses_default_name(constraint):
5✔
271
                self.add_literal_import("sqlalchemy", "PrimaryKeyConstraint")
5✔
272
        elif isinstance(constraint, UniqueConstraint):
5✔
273
            if len(constraint.columns) > 1 or not uses_default_name(constraint):
5✔
274
                self.add_literal_import("sqlalchemy", "UniqueConstraint")
5✔
275
        elif isinstance(constraint, ForeignKeyConstraint):
5✔
276
            if len(constraint.columns) > 1 or not uses_default_name(constraint):
5✔
277
                self.add_literal_import("sqlalchemy", "ForeignKeyConstraint")
5✔
278
            else:
279
                self.add_import(ForeignKey)
5✔
280
        else:
281
            self.add_import(constraint)
5✔
282

283
    def add_import(self, obj: Any) -> None:
5✔
284
        # Don't store builtin imports
285
        if getattr(obj, "__module__", "builtins") == "builtins":
5✔
286
            return
×
287

288
        type_ = type(obj) if not isinstance(obj, type) else obj
5✔
289
        pkgname = type_.__module__
5✔
290

291
        # The column types have already been adapted towards generic types if possible,
292
        # so if this is still a vendor specific type (e.g., MySQL INTEGER) be sure to
293
        # use that rather than the generic sqlalchemy type as it might have different
294
        # constructor parameters.
295
        if pkgname.startswith("sqlalchemy.dialects."):
5✔
296
            dialect_pkgname = ".".join(pkgname.split(".")[0:3])
5✔
297
            dialect_pkg = import_module(dialect_pkgname)
5✔
298

299
            if type_.__name__ in dialect_pkg.__all__:
5✔
300
                pkgname = dialect_pkgname
5✔
301
        elif type_ is getattr(sqlalchemy, type_.__name__, None):
5✔
302
            pkgname = "sqlalchemy"
5✔
303
        else:
304
            pkgname = type_.__module__
5✔
305

306
        self.add_literal_import(pkgname, type_.__name__)
5✔
307

308
    def add_literal_import(self, pkgname: str, name: str) -> None:
5✔
309
        names = self.imports.setdefault(pkgname, set())
5✔
310
        names.add(name)
5✔
311

312
    def remove_literal_import(self, pkgname: str, name: str) -> None:
5✔
313
        names = self.imports.setdefault(pkgname, set())
5✔
314
        if name in names:
5✔
315
            names.remove(name)
×
316

317
    def add_module_import(self, pgkname: str) -> None:
5✔
318
        self.module_imports.add(pgkname)
5✔
319

320
    def group_imports(self) -> list[list[str]]:
5✔
321
        future_imports: list[str] = []
5✔
322
        stdlib_imports: list[str] = []
5✔
323
        thirdparty_imports: list[str] = []
5✔
324

325
        def get_collection(package: str) -> list[str]:
5✔
326
            collection = thirdparty_imports
5✔
327
            if package == "__future__":
5✔
328
                collection = future_imports
×
329
            elif package in self.stdlib_module_names:
5✔
330
                collection = stdlib_imports
5✔
331
            elif package in sys.modules:
5✔
332
                if "site-packages" not in (sys.modules[package].__file__ or ""):
5✔
333
                    collection = stdlib_imports
5✔
334
            return collection
5✔
335

336
        for package in sorted(self.imports):
5✔
337
            imports = ", ".join(sorted(self.imports[package]))
5✔
338

339
            collection = get_collection(package)
5✔
340
            collection.append(f"from {package} import {imports}")
5✔
341

342
        for module in sorted(self.module_imports):
5✔
343
            collection = get_collection(module)
5✔
344
            collection.append(f"import {module}")
5✔
345

346
        return [
5✔
347
            group
348
            for group in (future_imports, stdlib_imports, thirdparty_imports)
349
            if group
350
        ]
351

352
    def generate_models(self) -> list[Model]:
5✔
353
        models = [Model(table) for table in self.metadata.sorted_tables]
5✔
354

355
        # Collect the imports
356
        self.collect_imports(models)
5✔
357

358
        # Generate names for models
359
        global_names = {
5✔
360
            name for namespace in self.imports.values() for name in namespace
361
        }
362
        for model in models:
5✔
363
            self.generate_model_name(model, global_names)
5✔
364
            global_names.add(model.name)
5✔
365

366
        return models
5✔
367

368
    def generate_model_name(self, model: Model, global_names: set[str]) -> None:
5✔
369
        preferred_name = f"t_{model.table.name}"
5✔
370
        model.name = self.find_free_name(preferred_name, global_names)
5✔
371

372
    def render_module_variables(self, models: list[Model]) -> str:
5✔
373
        declarations = self.base.declarations
5✔
374

375
        if any(not isinstance(model, ModelClass) for model in models):
5✔
376
            if self.base.table_metadata_declaration is not None:
5✔
377
                declarations.append(self.base.table_metadata_declaration)
×
378

379
        return "\n".join(declarations)
5✔
380

381
    def render_models(self, models: list[Model]) -> str:
5✔
382
        rendered: list[str] = []
5✔
383
        for model in models:
5✔
384
            rendered_table = self.render_table(model.table)
5✔
385
            rendered.append(f"{model.name} = {rendered_table}")
5✔
386

387
        return "\n\n".join(rendered)
5✔
388

389
    def render_table(self, table: Table) -> str:
5✔
390
        args: list[str] = [f"{table.name!r}, {self.base.metadata_ref}"]
5✔
391
        kwargs: dict[str, object] = {}
5✔
392
        for column in table.columns:
5✔
393
            # Cast is required because of a bug in the SQLAlchemy stubs regarding
394
            # Table.columns
395
            args.append(self.render_column(column, True, is_table=True))
5✔
396

397
        for constraint in sorted(table.constraints, key=get_constraint_sort_key):
5✔
398
            if uses_default_name(constraint):
5✔
399
                if isinstance(constraint, PrimaryKeyConstraint):
5✔
400
                    continue
5✔
401
                elif isinstance(constraint, (ForeignKeyConstraint, UniqueConstraint)):
5✔
402
                    if len(constraint.columns) == 1:
5✔
403
                        continue
5✔
404

405
            args.append(self.render_constraint(constraint))
5✔
406

407
        for index in sorted(table.indexes, key=lambda i: cast(str, i.name)):
5✔
408
            # One-column indexes should be rendered as index=True on columns
409
            if len(index.columns) > 1 or not uses_default_name(index):
5✔
410
                args.append(self.render_index(index))
5✔
411

412
        if table.schema:
5✔
413
            kwargs["schema"] = repr(table.schema)
5✔
414

415
        table_comment = getattr(table, "comment", None)
5✔
416
        if table_comment:
5✔
417
            kwargs["comment"] = repr(table.comment)
5✔
418

419
        # add info + dialect kwargs for callable context (opt-in)
420
        if self.include_dialect_options_and_info:
5✔
421
            self._add_dialect_kwargs_and_info(table, kwargs, values_for_dict=False)
5✔
422

423
        return render_callable("Table", *args, kwargs=kwargs, indentation="    ")
5✔
424

425
    def render_index(self, index: Index) -> str:
5✔
426
        extra_args = [repr(col.name) for col in index.columns]
5✔
427
        kwargs = {
5✔
428
            key: repr(value) if isinstance(value, str) else value
429
            for key, value in sorted(index.kwargs.items(), key=lambda item: item[0])
430
        }
431
        if index.unique:
5✔
432
            kwargs["unique"] = True
5✔
433

434
        return render_callable("Index", repr(index.name), *extra_args, kwargs=kwargs)
5✔
435

436
    # TODO find better solution for is_table
437
    def render_column(
5✔
438
        self, column: Column[Any], show_name: bool, is_table: bool = False
439
    ) -> str:
440
        args = []
5✔
441
        kwargs: dict[str, Any] = {}
5✔
442
        kwarg = []
5✔
443
        is_part_of_composite_pk = (
5✔
444
            column.primary_key and len(column.table.primary_key) > 1
445
        )
446
        dedicated_fks = [
5✔
447
            c
448
            for c in column.foreign_keys
449
            if c.constraint
450
            and len(c.constraint.columns) == 1
451
            and uses_default_name(c.constraint)
452
        ]
453
        is_unique = any(
5✔
454
            isinstance(c, UniqueConstraint)
455
            and set(c.columns) == {column}
456
            and uses_default_name(c)
457
            for c in column.table.constraints
458
        )
459
        is_unique = is_unique or any(
5✔
460
            i.unique and set(i.columns) == {column} and uses_default_name(i)
461
            for i in column.table.indexes
462
        )
463
        is_primary = (
5✔
464
            any(
465
                isinstance(c, PrimaryKeyConstraint)
466
                and column.name in c.columns
467
                and uses_default_name(c)
468
                for c in column.table.constraints
469
            )
470
            or column.primary_key
471
        )
472
        has_index = any(
5✔
473
            set(i.columns) == {column} and uses_default_name(i)
474
            for i in column.table.indexes
475
        )
476

477
        if show_name:
5✔
478
            args.append(repr(column.name))
5✔
479

480
        # Render the column type if there are no foreign keys on it or any of them
481
        # points back to itself
482
        if not dedicated_fks or any(fk.column is column for fk in dedicated_fks):
5✔
483
            args.append(self.render_column_type(column))
5✔
484

485
        for fk in dedicated_fks:
5✔
486
            args.append(self.render_constraint(fk))
5✔
487

488
        if column.default:
5✔
489
            args.append(repr(column.default))
5✔
490

491
        if column.key != column.name:
5✔
492
            kwargs["key"] = column.key
×
493
        if is_primary:
5✔
494
            kwargs["primary_key"] = True
5✔
495
        if not column.nullable and not column.primary_key:
5✔
496
            kwargs["nullable"] = False
5✔
497
        if column.nullable and is_part_of_composite_pk:
5✔
498
            kwargs["nullable"] = True
5✔
499

500
        if is_unique:
5✔
501
            column.unique = True
5✔
502
            kwargs["unique"] = True
5✔
503
        if has_index:
5✔
504
            column.index = True
5✔
505
            kwarg.append("index")
5✔
506
            kwargs["index"] = True
5✔
507

508
        if isinstance(column.server_default, DefaultClause):
5✔
509
            kwargs["server_default"] = render_callable(
5✔
510
                "text", repr(cast(TextClause, column.server_default.arg).text)
511
            )
512
        elif isinstance(column.server_default, Computed):
5✔
513
            expression = str(column.server_default.sqltext)
5✔
514

515
            computed_kwargs = {}
5✔
516
            if column.server_default.persisted is not None:
5✔
517
                computed_kwargs["persisted"] = column.server_default.persisted
5✔
518

519
            args.append(
5✔
520
                render_callable("Computed", repr(expression), kwargs=computed_kwargs)
521
            )
522
        elif isinstance(column.server_default, Identity):
5✔
523
            args.append(repr(column.server_default))
5✔
524
        elif column.server_default:
5✔
525
            kwargs["server_default"] = repr(column.server_default)
×
526

527
        comment = getattr(column, "comment", None)
5✔
528
        if comment:
5✔
529
            kwargs["comment"] = repr(comment)
5✔
530

531
        # add column info + dialect kwargs for callable context (opt-in)
532
        if self.include_dialect_options_and_info:
5✔
533
            self._add_dialect_kwargs_and_info(column, kwargs, values_for_dict=False)
5✔
534

535
        return self.render_column_callable(is_table, *args, **kwargs)
5✔
536

537
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
538
        if is_table:
5✔
539
            self.add_import(Column)
5✔
540
            return render_callable("Column", *args, kwargs=kwargs)
5✔
541
        else:
542
            return render_callable("mapped_column", *args, kwargs=kwargs)
5✔
543

544
    def render_column_type(self, column: Column[Any]) -> str:
5✔
545
        column_type = column.type
5✔
546
        # Check if this is an enum column with a Python enum class
547
        if isinstance(column_type, Enum) and column is not None:
5✔
548
            if enum_class_name := self.enum_classes.get(
5✔
549
                (column.table.name, column.name)
550
            ):
551
                # Import SQLAlchemy Enum (will be handled in collect_imports)
552
                self.add_import(Enum)
5✔
553
                return f"Enum({enum_class_name}, values_callable=lambda cls: [member.value for member in cls])"
5✔
554

555
        args = []
5✔
556
        kwargs: dict[str, Any] = {}
5✔
557

558
        # Check if this is an ARRAY column with an Enum item type mapped to a Python enum class
559
        if isinstance(column_type, ARRAY) and isinstance(column_type.item_type, Enum):
5✔
560
            if enum_class_name := self.enum_classes.get(
5✔
561
                (column.table.name, column.name)
562
            ):
563
                self.add_import(ARRAY)
5✔
564
                self.add_import(Enum)
5✔
565
                rendered_enum = f"Enum({enum_class_name}, values_callable=lambda cls: [member.value for member in cls])"
5✔
566
                if column_type.dimensions is not None:
5✔
567
                    kwargs["dimensions"] = repr(column_type.dimensions)
5✔
568

569
                return render_callable("ARRAY", rendered_enum, kwargs=kwargs)
5✔
570

571
        sig = inspect.signature(column_type.__class__.__init__)
5✔
572
        defaults = {param.name: param.default for param in sig.parameters.values()}
5✔
573
        missing = object()
5✔
574
        use_kwargs = False
5✔
575
        for param in list(sig.parameters.values())[1:]:
5✔
576
            # Remove annoyances like _warn_on_bytestring
577
            if param.name.startswith("_"):
5✔
578
                continue
5✔
579
            elif param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD):
5✔
580
                use_kwargs = True
5✔
581
                continue
5✔
582

583
            value = getattr(column_type, param.name, missing)
5✔
584

585
            if isinstance(value, (JSONB, JSON)):
5✔
586
                # Remove astext_type if it's the default
587
                if (
5✔
588
                    isinstance(value.astext_type, Text)
589
                    and value.astext_type.length is None
590
                ):
591
                    value.astext_type = None  # type: ignore[assignment]
5✔
592
                else:
593
                    self.add_import(Text)
5✔
594

595
            default = defaults.get(param.name, missing)
5✔
596
            if isinstance(value, TextClause):
5✔
597
                self.add_literal_import("sqlalchemy", "text")
5✔
598
                rendered_value = render_callable("text", repr(value.text))
5✔
599
            else:
600
                rendered_value = repr(value)
5✔
601

602
            if value is missing or value == default:
5✔
603
                use_kwargs = True
5✔
604
            elif use_kwargs:
5✔
605
                kwargs[param.name] = rendered_value
5✔
606
            else:
607
                args.append(rendered_value)
5✔
608

609
        vararg = next(
5✔
610
            (
611
                param.name
612
                for param in sig.parameters.values()
613
                if param.kind is Parameter.VAR_POSITIONAL
614
            ),
615
            None,
616
        )
617
        if vararg and hasattr(column_type, vararg):
5✔
618
            varargs_repr = [repr(arg) for arg in getattr(column_type, vararg)]
5✔
619
            args.extend(varargs_repr)
5✔
620

621
        # These arguments cannot be autodetected from the Enum initializer
622
        if isinstance(column_type, Enum):
5✔
623
            for colname in "name", "schema":
5✔
624
                if (value := getattr(column_type, colname)) is not None:
5✔
625
                    kwargs[colname] = repr(value)
5✔
626

627
        if isinstance(column_type, (JSONB, JSON)):
5✔
628
            # Remove astext_type if it's the default
629
            if (
5✔
630
                isinstance(column_type.astext_type, Text)
631
                and column_type.astext_type.length is None
632
            ):
633
                del kwargs["astext_type"]
5✔
634

635
        if args or kwargs:
5✔
636
            return render_callable(column_type.__class__.__name__, *args, kwargs=kwargs)
5✔
637
        else:
638
            return column_type.__class__.__name__
5✔
639

640
    def render_constraint(self, constraint: Constraint | ForeignKey) -> str:
5✔
641
        def add_fk_options(*opts: Any) -> None:
5✔
642
            args.extend(repr(opt) for opt in opts)
5✔
643
            for attr in "ondelete", "onupdate", "deferrable", "initially", "match":
5✔
644
                value = getattr(constraint, attr, None)
5✔
645
                if value:
5✔
646
                    kwargs[attr] = repr(value)
5✔
647

648
        args: list[str] = []
5✔
649
        kwargs: dict[str, Any] = {}
5✔
650
        if isinstance(constraint, ForeignKey):
5✔
651
            remote_column = (
5✔
652
                f"{constraint.column.table.fullname}.{constraint.column.name}"
653
            )
654
            add_fk_options(remote_column)
5✔
655
        elif isinstance(constraint, ForeignKeyConstraint):
5✔
656
            local_columns = get_column_names(constraint)
5✔
657
            remote_columns = [
5✔
658
                f"{fk.column.table.fullname}.{fk.column.name}"
659
                for fk in constraint.elements
660
            ]
661
            add_fk_options(local_columns, remote_columns)
5✔
662
        elif isinstance(constraint, CheckConstraint):
5✔
663
            args.append(repr(get_compiled_expression(constraint.sqltext, self.bind)))
5✔
664
        elif isinstance(constraint, (UniqueConstraint, PrimaryKeyConstraint)):
5✔
665
            args.extend(repr(col.name) for col in constraint.columns)
5✔
666
        else:
667
            raise TypeError(
×
668
                f"Cannot render constraint of type {constraint.__class__.__name__}"
669
            )
670

671
        if isinstance(constraint, Constraint) and not uses_default_name(constraint):
5✔
672
            kwargs["name"] = repr(constraint.name)
5✔
673

674
        return render_callable(constraint.__class__.__name__, *args, kwargs=kwargs)
5✔
675

676
    def _add_dialect_kwargs_and_info(
5✔
677
        self, obj: Any, target_kwargs: dict[str, object], *, values_for_dict: bool
678
    ) -> None:
679
        """
680
        Merge SchemaItem-like object's .info and .dialect_kwargs into target_kwargs.
681
        - values_for_dict=True: keep raw values so pretty-printer emits repr() (for __table_args__ dict)
682
        - values_for_dict=False: set values to repr() strings (for callable kwargs)
683
        """
684
        info_dict = getattr(obj, "info", None)
5✔
685
        if info_dict:
5✔
686
            target_kwargs["info"] = info_dict if values_for_dict else repr(info_dict)
5✔
687

688
        dialect_keys: list[str]
689
        try:
5✔
690
            dialect_keys = sorted(getattr(obj, "dialect_kwargs"))
5✔
691
        except Exception:
×
692
            return
×
693

694
        dialect_kwargs = getattr(obj, "dialect_kwargs", {})
5✔
695
        for key in dialect_keys:
5✔
696
            try:
5✔
697
                value = dialect_kwargs[key]
5✔
698
            except Exception:
×
699
                continue
×
700

701
            # Render values:
702
            # - callable context (values_for_dict=False): produce a string expression.
703
            #   primitives use repr(value); custom objects stringify then repr().
704
            # - dict context (values_for_dict=True): pass raw primitives / str;
705
            #   custom objects become str(value) so pformat quotes them.
706
            if values_for_dict:
5✔
707
                if isinstance(value, type(None) | bool | int | float):
5✔
708
                    target_kwargs[key] = value
×
709
                elif isinstance(value, str | dict | list):
5✔
710
                    target_kwargs[key] = value
5✔
711
                else:
712
                    target_kwargs[key] = str(value)
5✔
713
            else:
714
                if isinstance(
5✔
715
                    value, type(None) | bool | int | float | str | dict | list
716
                ):
717
                    target_kwargs[key] = repr(value)
5✔
718
                else:
719
                    target_kwargs[key] = repr(str(value))
5✔
720

721
    def should_ignore_table(self, table: Table) -> bool:
5✔
722
        # Support for Alembic and sqlalchemy-migrate -- never expose the schema version
723
        # tables
724
        return table.name in ("alembic_version", "migrate_version")
5✔
725

726
    def find_free_name(
5✔
727
        self, name: str, global_names: set[str], local_names: Collection[str] = ()
728
    ) -> str:
729
        """
730
        Generate an attribute name that does not clash with other local or global names.
731
        """
732
        name = name.strip()
5✔
733
        assert name, "Identifier cannot be empty"
5✔
734
        name = _re_invalid_identifier.sub("_", name)
5✔
735
        if name[0].isdigit():
5✔
736
            name = "_" + name
5✔
737
        elif iskeyword(name) or name == "metadata":
5✔
738
            name += "_"
5✔
739

740
        original = name
5✔
741
        for i in count():
5✔
742
            if name not in global_names and name not in local_names:
5✔
743
                break
5✔
744

745
            name = original + (str(i) if i else "_")
5✔
746

747
        return name
5✔
748

749
    def _enum_name_to_class_name(self, enum_name: str) -> str:
5✔
750
        """Convert a database enum name to a Python class name (PascalCase)."""
751
        return "".join(part.capitalize() for part in enum_name.split("_") if part)
5✔
752

753
    def _create_enum_class(
5✔
754
        self, table_name: str, column_name: str, values: list[str]
755
    ) -> str:
756
        """
757
        Create a Python enum class name and register it.
758

759
        Returns the enum class name to use in generated code.
760
        """
761
        # Generate enum class name from table and column names
762
        # Convert to PascalCase: user_status -> UserStatus
763
        base_name = "".join(
5✔
764
            part.capitalize()
765
            for part in table_name.split("_") + column_name.split("_")
766
            if part
767
        )
768

769
        # Ensure uniqueness
770
        enum_class_name = base_name
5✔
771
        for counter in count(1):
5✔
772
            if enum_class_name not in self.enum_values:
5✔
773
                break
5✔
774

775
            # Check if it's the same enum (same values)
776
            if self.enum_values[enum_class_name] == values:
5✔
777
                # Reuse existing enum class
778
                return enum_class_name
5✔
779

780
            enum_class_name = f"{base_name}{counter}"
5✔
781

782
        # Register the new enum class
783
        self.enum_values[enum_class_name] = values
5✔
784
        return enum_class_name
5✔
785

786
    def render_enum_classes(self) -> str:
5✔
787
        """Render Python enum class definitions."""
788
        if not self.enum_values:
5✔
789
            return ""
5✔
790

791
        self.add_module_import("enum")
5✔
792

793
        enum_defs = []
5✔
794
        for enum_class_name, values in sorted(self.enum_values.items()):
5✔
795
            # Create enum members with valid Python identifiers
796
            members = []
5✔
797
            for value in values:
5✔
798
                # Unescape SQL escape sequences (e.g., \' -> ')
799
                # The value from the CHECK constraint has SQL escaping
800
                unescaped_value = value.replace("\\'", "'").replace("\\\\", "\\")
5✔
801

802
                # Create a valid identifier from the enum value
803
                member_name = _re_invalid_identifier.sub("_", unescaped_value).upper()
5✔
804
                if not member_name:
5✔
805
                    member_name = "EMPTY"
×
806
                elif member_name[0].isdigit():
5✔
807
                    member_name = "_" + member_name
×
808
                elif iskeyword(member_name):
5✔
809
                    member_name += "_"
×
810
                #
811
                # # Re-escape for Python string literal
812
                # python_escaped = unescaped_value.replace("\\", "\\\\").replace(
813
                #     "'", "\\'"
814
                # )
815
                members.append(f"    {member_name} = {unescaped_value!r}")
5✔
816

817
            enum_def = f"class {enum_class_name}(str, enum.Enum):\n" + "\n".join(
5✔
818
                members
819
            )
820
            enum_defs.append(enum_def)
5✔
821

822
        return "\n\n\n".join(enum_defs)
5✔
823

824
    def fix_column_types(self, table: Table) -> None:
5✔
825
        """Adjust the reflected column types."""
826

827
        def fix_enum_column(col_name: str, enum_type: Enum) -> None:
5✔
828
            if (table.name, col_name) in self.enum_classes:
5✔
829
                return
5✔
830

831
            if enum_type.name:
5✔
832
                existing_class = None
5✔
833
                for (_, _), cls in self.enum_classes.items():
5✔
834
                    if cls == self._enum_name_to_class_name(enum_type.name):
5✔
835
                        existing_class = cls
5✔
836
                        break
5✔
837

838
                if existing_class:
5✔
839
                    enum_class_name = existing_class
5✔
840
                else:
841
                    enum_class_name = self._enum_name_to_class_name(enum_type.name)
5✔
842
                    if enum_class_name not in self.enum_values:
5✔
843
                        self.enum_values[enum_class_name] = list(enum_type.enums)
5✔
844
            else:
845
                enum_class_name = self._create_enum_class(
5✔
846
                    table.name, col_name, list(enum_type.enums)
847
                )
848

849
            self.enum_classes[(table.name, col_name)] = enum_class_name
5✔
850

851
        # Detect check constraints for boolean and enum columns
852
        for constraint in table.constraints.copy():
5✔
853
            if isinstance(constraint, CheckConstraint):
5✔
854
                sqltext = get_compiled_expression(constraint.sqltext, self.bind)
5✔
855

856
                # Turn any integer-like column with a CheckConstraint like
857
                # "column IN (0, 1)" into a Boolean
858
                if match := _re_boolean_check_constraint.match(sqltext):
5✔
859
                    if colname_match := _re_column_name.match(match.group(1)):
5✔
860
                        colname = colname_match.group(3)
5✔
861
                        table.constraints.remove(constraint)
5✔
862
                        table.c[colname].type = Boolean()
5✔
863
                        continue
5✔
864

865
                # Turn VARCHAR columns with CHECK constraints like "column IN ('a', 'b')"
866
                # into synthetic Enum types with Python enum classes
867
                if (
5✔
868
                    "nosyntheticenums" not in self.options
869
                    and (match := _re_enum_check_constraint.match(sqltext))
870
                    and (colname_match := _re_column_name.match(match.group(1)))
871
                ):
872
                    colname = colname_match.group(3)
5✔
873
                    items = match.group(2)
5✔
874
                    if isinstance(table.c[colname].type, String) and not isinstance(
5✔
875
                        table.c[colname].type, Enum
876
                    ):
877
                        options = _re_enum_item.findall(items)
5✔
878
                        # Create Python enum class
879
                        enum_class_name = self._create_enum_class(
5✔
880
                            table.name, colname, options
881
                        )
882
                        self.enum_classes[(table.name, colname)] = enum_class_name
5✔
883
                        # Convert to Enum type but KEEP the constraint
884
                        table.c[colname].type = Enum(*options, native_enum=False)
5✔
885
                        continue
5✔
886

887
        for column in table.c:
5✔
888
            # Handle native database Enum types (e.g., PostgreSQL ENUM)
889
            if (
5✔
890
                "nonativeenums" not in self.options
891
                and isinstance(column.type, Enum)
892
                and column.type.enums
893
            ):
894
                fix_enum_column(column.name, column.type)
5✔
895
            # Handle ARRAY columns with Enum item types (e.g., PostgreSQL ARRAY(ENUM))
896
            elif (
5✔
897
                "nonativeenums" not in self.options
898
                and isinstance(column.type, ARRAY)
899
                and isinstance(column.type.item_type, Enum)
900
                and column.type.item_type.enums
901
            ):
902
                fix_enum_column(column.name, column.type.item_type)
5✔
903

904
            if not self.keep_dialect_types:
5✔
905
                try:
5✔
906
                    column.type = self.get_adapted_type(column.type)
5✔
907
                except CompileError:
5✔
908
                    continue
5✔
909

910
            # PostgreSQL specific fix: detect sequences from server_default
911
            if column.server_default and self.bind.dialect.name == "postgresql":
5✔
912
                if isinstance(column.server_default, DefaultClause) and isinstance(
5✔
913
                    column.server_default.arg, TextClause
914
                ):
915
                    schema, seqname = decode_postgresql_sequence(
5✔
916
                        column.server_default.arg
917
                    )
918
                    if seqname:
5✔
919
                        # Add an explicit sequence
920
                        if seqname != f"{column.table.name}_{column.name}_seq":
5✔
921
                            column.default = sqlalchemy.Sequence(seqname, schema=schema)
5✔
922

923
                        column.server_default = None
5✔
924

925
    def get_adapted_type(self, coltype: Any) -> Any:
5✔
926
        compiled_type = coltype.compile(self.bind.engine.dialect)
5✔
927
        for supercls in coltype.__class__.__mro__:
5✔
928
            if not supercls.__name__.startswith("_") and hasattr(
5✔
929
                supercls, "__visit_name__"
930
            ):
931
                # Don't try to adapt UserDefinedType as it's not a proper column type
932
                if supercls is UserDefinedType or issubclass(supercls, TypeDecorator):
5✔
933
                    return coltype
5✔
934

935
                # Hack to fix adaptation of the Enum class which is broken since
936
                # SQLAlchemy 1.2
937
                kw = {}
5✔
938
                if supercls is Enum:
5✔
939
                    kw["name"] = coltype.name
5✔
940
                    if coltype.schema:
5✔
941
                        kw["schema"] = coltype.schema
5✔
942

943
                # Hack to fix Postgres DOMAIN type adaptation, broken as of SQLAlchemy 2.0.42
944
                # For additional information - https://github.com/agronholm/sqlacodegen/issues/416#issuecomment-3417480599
945
                if supercls is DOMAIN:
5✔
946
                    if coltype.default:
5✔
UNCOV
947
                        kw["default"] = coltype.default
×
948
                    if coltype.constraint_name is not None:
5✔
949
                        kw["constraint_name"] = coltype.constraint_name
5✔
950
                    if coltype.not_null:
5✔
UNCOV
951
                        kw["not_null"] = coltype.not_null
×
952
                    if coltype.check is not None:
5✔
953
                        kw["check"] = coltype.check
5✔
954
                    if coltype.create_type:
5✔
955
                        kw["create_type"] = coltype.create_type
5✔
956

957
                try:
5✔
958
                    new_coltype = coltype.adapt(supercls)
5✔
959
                except TypeError:
5✔
960
                    # If the adaptation fails, don't try again
961
                    break
5✔
962

963
                for key, value in kw.items():
5✔
964
                    setattr(new_coltype, key, value)
5✔
965

966
                if isinstance(coltype, ARRAY):
5✔
967
                    new_coltype.item_type = self.get_adapted_type(new_coltype.item_type)
5✔
968

969
                try:
5✔
970
                    # If the adapted column type does not render the same as the
971
                    # original, don't substitute it
972
                    if new_coltype.compile(self.bind.engine.dialect) != compiled_type:
5✔
973
                        break
5✔
974
                except CompileError:
5✔
975
                    # If the adapted column type can't be compiled, don't substitute it
976
                    break
5✔
977

978
                # Stop on the first valid non-uppercase column type class
979
                coltype = new_coltype
5✔
980
                if supercls.__name__ != supercls.__name__.upper():
5✔
981
                    break
5✔
982

983
        return coltype
5✔
984

985

986
class DeclarativeGenerator(TablesGenerator):
5✔
987
    valid_options: ClassVar[set[str]] = TablesGenerator.valid_options | {
5✔
988
        "use_inflect",
989
        "nojoined",
990
        "nobidi",
991
        "noidsuffix",
992
        "nofknames",
993
    }
994

995
    def __init__(
5✔
996
        self,
997
        metadata: MetaData,
998
        bind: Connection | Engine,
999
        options: Sequence[str],
1000
        *,
1001
        indentation: str = "    ",
1002
        base_class_name: str = "Base",
1003
    ):
1004
        super().__init__(metadata, bind, options, indentation=indentation)
5✔
1005
        self.base_class_name: str = base_class_name
5✔
1006
        self.inflect_engine = inflect.engine()
5✔
1007

1008
    def generate_base(self) -> None:
5✔
1009
        self.base = Base(
5✔
1010
            literal_imports=[LiteralImport("sqlalchemy.orm", "DeclarativeBase")],
1011
            declarations=[
1012
                f"class {self.base_class_name}(DeclarativeBase):",
1013
                f"{self.indentation}pass",
1014
            ],
1015
            metadata_ref=f"{self.base_class_name}.metadata",
1016
        )
1017

1018
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1019
        super().collect_imports(models)
5✔
1020
        if any(isinstance(model, ModelClass) for model in models):
5✔
1021
            self.add_literal_import("sqlalchemy.orm", "Mapped")
5✔
1022
            self.add_literal_import("sqlalchemy.orm", "mapped_column")
5✔
1023

1024
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1025
        super().collect_imports_for_model(model)
5✔
1026
        if isinstance(model, ModelClass):
5✔
1027
            if model.relationships:
5✔
1028
                self.add_literal_import("sqlalchemy.orm", "relationship")
5✔
1029

1030
    def generate_models(self) -> list[Model]:
5✔
1031
        models_by_table_name: dict[str, Model] = {}
5✔
1032

1033
        # Pick association tables from the metadata into their own set, don't process
1034
        # them normally
1035
        links: defaultdict[str, list[Model]] = defaultdict(lambda: [])
5✔
1036
        for table in self.metadata.sorted_tables:
5✔
1037
            qualified_name = qualified_table_name(table)
5✔
1038

1039
            # Link tables have exactly two foreign key constraints and all columns are
1040
            # involved in them
1041
            fk_constraints = sorted(
5✔
1042
                table.foreign_key_constraints, key=get_constraint_sort_key
1043
            )
1044
            if len(fk_constraints) == 2 and all(
5✔
1045
                col.foreign_keys for col in table.columns
1046
            ):
1047
                model = models_by_table_name[qualified_name] = Model(table)
5✔
1048
                tablename = fk_constraints[0].elements[0].column.table.name
5✔
1049
                links[tablename].append(model)
5✔
1050
                continue
5✔
1051

1052
            # Only form model classes for tables that have a primary key and are not
1053
            # association tables
1054
            if not table.primary_key:
5✔
1055
                models_by_table_name[qualified_name] = Model(table)
5✔
1056
            else:
1057
                model = ModelClass(table)
5✔
1058
                models_by_table_name[qualified_name] = model
5✔
1059

1060
                # Fill in the columns
1061
                for column in table.c:
5✔
1062
                    column_attr = ColumnAttribute(model, column)
5✔
1063
                    model.columns.append(column_attr)
5✔
1064

1065
        # Add relationships
1066
        for model in models_by_table_name.values():
5✔
1067
            if isinstance(model, ModelClass):
5✔
1068
                self.generate_relationships(
5✔
1069
                    model, models_by_table_name, links[model.table.name]
1070
                )
1071

1072
        # Nest inherited classes in their superclasses to ensure proper ordering
1073
        if "nojoined" not in self.options:
5✔
1074
            for model in list(models_by_table_name.values()):
5✔
1075
                if not isinstance(model, ModelClass):
5✔
1076
                    continue
5✔
1077

1078
                pk_column_names = {col.name for col in model.table.primary_key.columns}
5✔
1079
                for constraint in model.table.foreign_key_constraints:
5✔
1080
                    if set(get_column_names(constraint)) == pk_column_names:
5✔
1081
                        target = models_by_table_name[
5✔
1082
                            qualified_table_name(constraint.elements[0].column.table)
1083
                        ]
1084
                        if isinstance(target, ModelClass):
5✔
1085
                            model.parent_class = target
5✔
1086
                            target.children.append(model)
5✔
1087

1088
        # Change base if we only have tables
1089
        if not any(
5✔
1090
            isinstance(model, ModelClass) for model in models_by_table_name.values()
1091
        ):
1092
            super().generate_base()
5✔
1093

1094
        # Collect the imports
1095
        self.collect_imports(models_by_table_name.values())
5✔
1096

1097
        # Rename models and their attributes that conflict with imports or other
1098
        # attributes
1099
        global_names = {
5✔
1100
            name for namespace in self.imports.values() for name in namespace
1101
        }
1102
        for model in models_by_table_name.values():
5✔
1103
            self.generate_model_name(model, global_names)
5✔
1104
            global_names.add(model.name)
5✔
1105

1106
        return list(models_by_table_name.values())
5✔
1107

1108
    def generate_relationships(
5✔
1109
        self,
1110
        source: ModelClass,
1111
        models_by_table_name: dict[str, Model],
1112
        association_tables: list[Model],
1113
    ) -> list[RelationshipAttribute]:
1114
        relationships: list[RelationshipAttribute] = []
5✔
1115
        reverse_relationship: RelationshipAttribute | None
1116

1117
        # Add many-to-one (and one-to-many) relationships
1118
        pk_column_names = {col.name for col in source.table.primary_key.columns}
5✔
1119
        for constraint in sorted(
5✔
1120
            source.table.foreign_key_constraints, key=get_constraint_sort_key
1121
        ):
1122
            target = models_by_table_name[
5✔
1123
                qualified_table_name(constraint.elements[0].column.table)
1124
            ]
1125
            if isinstance(target, ModelClass):
5✔
1126
                if "nojoined" not in self.options:
5✔
1127
                    if set(get_column_names(constraint)) == pk_column_names:
5✔
1128
                        parent = models_by_table_name[
5✔
1129
                            qualified_table_name(constraint.elements[0].column.table)
1130
                        ]
1131
                        if isinstance(parent, ModelClass):
5✔
1132
                            source.parent_class = parent
5✔
1133
                            parent.children.append(source)
5✔
1134
                            continue
5✔
1135

1136
                # Add uselist=False to One-to-One relationships
1137
                column_names = get_column_names(constraint)
5✔
1138
                if any(
5✔
1139
                    isinstance(c, (PrimaryKeyConstraint, UniqueConstraint))
1140
                    and {col.name for col in c.columns} == set(column_names)
1141
                    for c in constraint.table.constraints
1142
                ):
1143
                    r_type = RelationshipType.ONE_TO_ONE
5✔
1144
                else:
1145
                    r_type = RelationshipType.MANY_TO_ONE
5✔
1146

1147
                relationship = RelationshipAttribute(r_type, source, target, constraint)
5✔
1148
                source.relationships.append(relationship)
5✔
1149

1150
                # For self referential relationships, remote_side needs to be set
1151
                if source is target:
5✔
1152
                    relationship.remote_side = [
5✔
1153
                        source.get_column_attribute(col.name)
1154
                        for col in constraint.referred_table.primary_key
1155
                    ]
1156

1157
                # If the two tables share more than one foreign key constraint,
1158
                # SQLAlchemy needs an explicit primaryjoin to figure out which column(s)
1159
                # it needs
1160
                common_fk_constraints = get_common_fk_constraints(
5✔
1161
                    source.table, target.table
1162
                )
1163
                if len(common_fk_constraints) > 1:
5✔
1164
                    relationship.foreign_keys = [
5✔
1165
                        source.get_column_attribute(key)
1166
                        for key in constraint.column_keys
1167
                    ]
1168

1169
                # Generate the opposite end of the relationship in the target class
1170
                if "nobidi" not in self.options:
5✔
1171
                    if r_type is RelationshipType.MANY_TO_ONE:
5✔
1172
                        r_type = RelationshipType.ONE_TO_MANY
5✔
1173

1174
                    reverse_relationship = RelationshipAttribute(
5✔
1175
                        r_type,
1176
                        target,
1177
                        source,
1178
                        constraint,
1179
                        foreign_keys=relationship.foreign_keys,
1180
                        backref=relationship,
1181
                    )
1182
                    relationship.backref = reverse_relationship
5✔
1183
                    target.relationships.append(reverse_relationship)
5✔
1184

1185
                    # For self referential relationships, remote_side needs to be set
1186
                    if source is target:
5✔
1187
                        reverse_relationship.remote_side = [
5✔
1188
                            source.get_column_attribute(colname)
1189
                            for colname in constraint.column_keys
1190
                        ]
1191

1192
        # Add many-to-many relationships
1193
        for association_table in association_tables:
5✔
1194
            fk_constraints = sorted(
5✔
1195
                association_table.table.foreign_key_constraints,
1196
                key=get_constraint_sort_key,
1197
            )
1198
            target = models_by_table_name[
5✔
1199
                qualified_table_name(fk_constraints[1].elements[0].column.table)
1200
            ]
1201
            if isinstance(target, ModelClass):
5✔
1202
                relationship = RelationshipAttribute(
5✔
1203
                    RelationshipType.MANY_TO_MANY,
1204
                    source,
1205
                    target,
1206
                    fk_constraints[1],
1207
                    association_table,
1208
                )
1209
                source.relationships.append(relationship)
5✔
1210

1211
                # Generate the opposite end of the relationship in the target class
1212
                reverse_relationship = None
5✔
1213
                if "nobidi" not in self.options:
5✔
1214
                    reverse_relationship = RelationshipAttribute(
5✔
1215
                        RelationshipType.MANY_TO_MANY,
1216
                        target,
1217
                        source,
1218
                        fk_constraints[0],
1219
                        association_table,
1220
                        relationship,
1221
                    )
1222
                    relationship.backref = reverse_relationship
5✔
1223
                    target.relationships.append(reverse_relationship)
5✔
1224

1225
                # Add a primary/secondary join for self-referential many-to-many
1226
                # relationships
1227
                if source is target:
5✔
1228
                    both_relationships = [relationship]
5✔
1229
                    reverse_flags = [False, True]
5✔
1230
                    if reverse_relationship:
5✔
1231
                        both_relationships.append(reverse_relationship)
5✔
1232

1233
                    for relationship, reverse in zip(both_relationships, reverse_flags):
5✔
1234
                        if (
5✔
1235
                            not relationship.association_table
1236
                            or not relationship.constraint
1237
                        ):
UNCOV
1238
                            continue
×
1239

1240
                        constraints = sorted(
5✔
1241
                            relationship.constraint.table.foreign_key_constraints,
1242
                            key=get_constraint_sort_key,
1243
                            reverse=reverse,
1244
                        )
1245
                        pri_pairs = zip(
5✔
1246
                            get_column_names(constraints[0]), constraints[0].elements
1247
                        )
1248
                        sec_pairs = zip(
5✔
1249
                            get_column_names(constraints[1]), constraints[1].elements
1250
                        )
1251
                        relationship.primaryjoin = [
5✔
1252
                            (
1253
                                relationship.source,
1254
                                elem.column.name,
1255
                                relationship.association_table,
1256
                                col,
1257
                            )
1258
                            for col, elem in pri_pairs
1259
                        ]
1260
                        relationship.secondaryjoin = [
5✔
1261
                            (
1262
                                relationship.target,
1263
                                elem.column.name,
1264
                                relationship.association_table,
1265
                                col,
1266
                            )
1267
                            for col, elem in sec_pairs
1268
                        ]
1269

1270
        return relationships
5✔
1271

1272
    def generate_model_name(self, model: Model, global_names: set[str]) -> None:
5✔
1273
        if isinstance(model, ModelClass):
5✔
1274
            preferred_name = _re_invalid_identifier.sub("_", model.table.name)
5✔
1275
            preferred_name = "".join(
5✔
1276
                part[:1].upper() + part[1:] for part in preferred_name.split("_")
1277
            )
1278
            if "use_inflect" in self.options:
5✔
1279
                singular_name = self.inflect_engine.singular_noun(preferred_name)
5✔
1280
                if singular_name:
5✔
1281
                    preferred_name = singular_name
5✔
1282

1283
            model.name = self.find_free_name(preferred_name, global_names)
5✔
1284

1285
            # Fill in the names for column attributes
1286
            local_names: set[str] = set()
5✔
1287
            for column_attr in model.columns:
5✔
1288
                self.generate_column_attr_name(column_attr, global_names, local_names)
5✔
1289
                local_names.add(column_attr.name)
5✔
1290

1291
            # Fill in the names for relationship attributes
1292
            for relationship in model.relationships:
5✔
1293
                self.generate_relationship_name(relationship, global_names, local_names)
5✔
1294
                local_names.add(relationship.name)
5✔
1295
        else:
1296
            super().generate_model_name(model, global_names)
5✔
1297

1298
    def generate_column_attr_name(
5✔
1299
        self,
1300
        column_attr: ColumnAttribute,
1301
        global_names: set[str],
1302
        local_names: set[str],
1303
    ) -> None:
1304
        column_attr.name = self.find_free_name(
5✔
1305
            column_attr.column.name, global_names, local_names
1306
        )
1307

1308
    def generate_relationship_name(
5✔
1309
        self,
1310
        relationship: RelationshipAttribute,
1311
        global_names: set[str],
1312
        local_names: set[str],
1313
    ) -> None:
1314
        def strip_id_suffix(name: str) -> str:
5✔
1315
            # Strip _id only if at the end or followed by underscore (e.g., "course_id" -> "course", "course_id_1" -> "course_1")
1316
            # But don't strip from "parent_id1" (where id is followed by a digit without underscore)
1317
            return re.sub(r"_id(?=_|$)", "", name)
5✔
1318

1319
        def get_m2m_qualified_name(default_name: str) -> str:
5✔
1320
            """Generate qualified name for many-to-many relationship when multiple junction tables exist."""
1321
            # Check if there are multiple M2M relationships to the same target
1322
            target_m2m_relationships = [
5✔
1323
                r
1324
                for r in relationship.source.relationships
1325
                if r.target is relationship.target
1326
                and r.type == RelationshipType.MANY_TO_MANY
1327
            ]
1328

1329
            # Only use junction-based naming when there are multiple M2M to same target
1330
            if len(target_m2m_relationships) > 1:
5✔
1331
                if relationship.source is relationship.target:
5✔
1332
                    # Self-referential: use FK column name from junction table
1333
                    # (e.g., "parent_id" -> "parent", "child_id" -> "child")
1334
                    if relationship.constraint:
5✔
1335
                        column_names = [c.name for c in relationship.constraint.columns]
5✔
1336
                        if len(column_names) == 1:
5✔
1337
                            fk_qualifier = strip_id_suffix(column_names[0])
5✔
1338
                        else:
UNCOV
1339
                            fk_qualifier = "_".join(
×
1340
                                strip_id_suffix(col_name) for col_name in column_names
1341
                            )
1342
                        return fk_qualifier
5✔
1343
                elif relationship.association_table:
5✔
1344
                    # Normal: use junction table name as qualifier
1345
                    junction_name = relationship.association_table.table.name
5✔
1346
                    fk_qualifier = strip_id_suffix(junction_name)
5✔
1347
                    return f"{relationship.target.table.name}_{fk_qualifier}"
5✔
1348
            else:
1349
                # Single M2M: use simple name from junction table FK column
1350
                # (e.g., "right_id" -> "right" instead of "right_table")
1351
                if relationship.constraint and "noidsuffix" not in self.options:
5✔
1352
                    column_names = [c.name for c in relationship.constraint.columns]
5✔
1353
                    if len(column_names) == 1:
5✔
1354
                        stripped_name = strip_id_suffix(column_names[0])
5✔
1355
                        if stripped_name != column_names[0]:
5✔
1356
                            return stripped_name
5✔
1357

1358
            return default_name
5✔
1359

1360
        def get_fk_qualified_name(constraint: ForeignKeyConstraint) -> str:
5✔
1361
            """Generate qualified name for one-to-many/one-to-one relationship using FK column names."""
1362
            column_names = [c.name for c in constraint.columns]
5✔
1363

1364
            if len(column_names) == 1:
5✔
1365
                # Single column FK: strip _id suffix if present
1366
                fk_qualifier = strip_id_suffix(column_names[0])
5✔
1367
            else:
1368
                # Multi-column FK: concatenate all column names (strip _id from each)
1369
                fk_qualifier = "_".join(
5✔
1370
                    strip_id_suffix(col_name) for col_name in column_names
1371
                )
1372

1373
            # For self-referential relationships, don't prepend the table name
1374
            if relationship.source is relationship.target:
5✔
UNCOV
1375
                return fk_qualifier
×
1376
            else:
1377
                return f"{relationship.target.table.name}_{fk_qualifier}"
5✔
1378

1379
        def resolve_preferred_name() -> str:
5✔
1380
            resolved_name = relationship.target.table.name
5✔
1381

1382
            # For reverse relationships with multiple FKs to the same table, use the FK
1383
            # column name to create a more descriptive relationship name
1384
            # For M2M relationships with multiple junction tables, use the junction table name
1385
            use_fk_based_naming = "nofknames" not in self.options and (
5✔
1386
                (
1387
                    relationship.constraint
1388
                    and relationship.type
1389
                    in (RelationshipType.ONE_TO_MANY, RelationshipType.ONE_TO_ONE)
1390
                    and relationship.foreign_keys
1391
                )
1392
                or (
1393
                    relationship.type == RelationshipType.MANY_TO_MANY
1394
                    and relationship.association_table
1395
                )
1396
            )
1397

1398
            if use_fk_based_naming:
5✔
1399
                if relationship.type == RelationshipType.MANY_TO_MANY:
5✔
1400
                    resolved_name = get_m2m_qualified_name(resolved_name)
5✔
1401
                elif relationship.constraint:
5✔
1402
                    resolved_name = get_fk_qualified_name(relationship.constraint)
5✔
1403

1404
            # If there's a constraint with a single column that contains "_id", use the
1405
            # stripped version as the relationship name
1406
            elif relationship.constraint and "noidsuffix" not in self.options:
5✔
1407
                is_source = relationship.source.table is relationship.constraint.table
5✔
1408
                if is_source or relationship.type not in (
5✔
1409
                    RelationshipType.ONE_TO_ONE,
1410
                    RelationshipType.ONE_TO_MANY,
1411
                ):
1412
                    column_names = [c.name for c in relationship.constraint.columns]
5✔
1413
                    if len(column_names) == 1:
5✔
1414
                        stripped_name = strip_id_suffix(column_names[0])
5✔
1415
                        # Only use the stripped name if it actually changed (had _id in it)
1416
                        if stripped_name != column_names[0]:
5✔
1417
                            resolved_name = stripped_name
5✔
1418
                    else:
1419
                        # For composite FKs, check if there are multiple FKs to the same target
1420
                        target_relationships = [
5✔
1421
                            r
1422
                            for r in relationship.source.relationships
1423
                            if r.target is relationship.target
1424
                            and r.type == relationship.type
1425
                        ]
1426
                        if len(target_relationships) > 1:
5✔
1427
                            # Multiple FKs to same table - use concatenated column names
1428
                            resolved_name = "_".join(
5✔
1429
                                strip_id_suffix(col_name) for col_name in column_names
1430
                            )
1431

1432
            if "use_inflect" in self.options:
5✔
1433
                inflected_name: str | Literal[False]
1434
                if relationship.type in (
5✔
1435
                    RelationshipType.ONE_TO_MANY,
1436
                    RelationshipType.MANY_TO_MANY,
1437
                ):
1438
                    if not self.inflect_engine.singular_noun(resolved_name):
5✔
1439
                        resolved_name = self.inflect_engine.plural_noun(resolved_name)
5✔
1440
                else:
1441
                    inflected_name = self.inflect_engine.singular_noun(resolved_name)
5✔
1442
                    if inflected_name:
5✔
1443
                        resolved_name = inflected_name
5✔
1444

1445
            return resolved_name
5✔
1446

1447
        if (
5✔
1448
            relationship.type
1449
            in (RelationshipType.ONE_TO_MANY, RelationshipType.ONE_TO_ONE)
1450
            and relationship.source is relationship.target
1451
            and relationship.backref
1452
            and relationship.backref.name
1453
        ):
1454
            preferred_name = relationship.backref.name + "_reverse"
5✔
1455
        else:
1456
            preferred_name = resolve_preferred_name()
5✔
1457

1458
        relationship.name = self.find_free_name(
5✔
1459
            preferred_name, global_names, local_names
1460
        )
1461

1462
    def render_models(self, models: list[Model]) -> str:
5✔
1463
        rendered: list[str] = []
5✔
1464
        for model in models:
5✔
1465
            if isinstance(model, ModelClass):
5✔
1466
                rendered.append(self.render_class(model))
5✔
1467
            else:
1468
                rendered.append(f"{model.name} = {self.render_table(model.table)}")
5✔
1469

1470
        return "\n\n\n".join(rendered)
5✔
1471

1472
    def render_class(self, model: ModelClass) -> str:
5✔
1473
        sections: list[str] = []
5✔
1474

1475
        # Render class variables / special declarations
1476
        class_vars: str = self.render_class_variables(model)
5✔
1477
        if class_vars:
5✔
1478
            sections.append(class_vars)
5✔
1479

1480
        # Render column attributes
1481
        rendered_column_attributes: list[str] = []
5✔
1482
        for nullable in (False, True):
5✔
1483
            for column_attr in model.columns:
5✔
1484
                if column_attr.column.nullable is nullable:
5✔
1485
                    rendered_column_attributes.append(
5✔
1486
                        self.render_column_attribute(column_attr)
1487
                    )
1488

1489
        if rendered_column_attributes:
5✔
1490
            sections.append("\n".join(rendered_column_attributes))
5✔
1491

1492
        # Render relationship attributes
1493
        rendered_relationship_attributes: list[str] = [
5✔
1494
            self.render_relationship(relationship)
1495
            for relationship in model.relationships
1496
        ]
1497

1498
        if rendered_relationship_attributes:
5✔
1499
            sections.append("\n".join(rendered_relationship_attributes))
5✔
1500

1501
        declaration = self.render_class_declaration(model)
5✔
1502
        rendered_sections = "\n\n".join(
5✔
1503
            indent(section, self.indentation) for section in sections
1504
        )
1505
        return f"{declaration}\n{rendered_sections}"
5✔
1506

1507
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1508
        parent_class_name = (
5✔
1509
            model.parent_class.name if model.parent_class else self.base_class_name
1510
        )
1511
        return f"class {model.name}({parent_class_name}):"
5✔
1512

1513
    def render_class_variables(self, model: ModelClass) -> str:
5✔
1514
        variables = [f"__tablename__ = {model.table.name!r}"]
5✔
1515

1516
        # Render constraints and indexes as __table_args__
1517
        table_args = self.render_table_args(model.table)
5✔
1518
        if table_args:
5✔
1519
            variables.append(f"__table_args__ = {table_args}")
5✔
1520

1521
        return "\n".join(variables)
5✔
1522

1523
    def render_table_args(self, table: Table) -> str:
5✔
1524
        args: list[str] = []
5✔
1525
        kwargs: dict[str, object] = {}
5✔
1526

1527
        # Render constraints
1528
        for constraint in sorted(table.constraints, key=get_constraint_sort_key):
5✔
1529
            if uses_default_name(constraint):
5✔
1530
                if isinstance(constraint, PrimaryKeyConstraint):
5✔
1531
                    continue
5✔
1532
                if (
5✔
1533
                    isinstance(constraint, (ForeignKeyConstraint, UniqueConstraint))
1534
                    and len(constraint.columns) == 1
1535
                ):
1536
                    continue
5✔
1537

1538
            args.append(self.render_constraint(constraint))
5✔
1539

1540
        # Render indexes
1541
        for index in sorted(table.indexes, key=lambda i: cast(str, i.name)):
5✔
1542
            if len(index.columns) > 1 or not uses_default_name(index):
5✔
1543
                args.append(self.render_index(index))
5✔
1544

1545
        if table.schema:
5✔
1546
            kwargs["schema"] = table.schema
5✔
1547

1548
        if table.comment:
5✔
1549
            kwargs["comment"] = table.comment
5✔
1550

1551
        # add info + dialect kwargs for dict context (__table_args__) (opt-in)
1552
        if self.include_dialect_options_and_info:
5✔
1553
            self._add_dialect_kwargs_and_info(table, kwargs, values_for_dict=True)
5✔
1554

1555
        if kwargs:
5✔
1556
            formatted_kwargs = pformat(kwargs)
5✔
1557
            if not args:
5✔
1558
                return formatted_kwargs
5✔
1559
            else:
1560
                args.append(formatted_kwargs)
5✔
1561

1562
        if args:
5✔
1563
            rendered_args = f",\n{self.indentation}".join(args)
5✔
1564
            if len(args) == 1:
5✔
1565
                rendered_args += ","
5✔
1566

1567
            return f"(\n{self.indentation}{rendered_args}\n)"
5✔
1568
        else:
1569
            return ""
5✔
1570

1571
    def render_column_python_type(self, column: Column[Any]) -> str:
5✔
1572
        def get_type_qualifiers() -> tuple[str, TypeEngine[Any], str]:
5✔
1573
            column_type = column.type
5✔
1574
            pre: list[str] = []
5✔
1575
            post_size = 0
5✔
1576
            if column.nullable:
5✔
1577
                self.add_literal_import("typing", "Optional")
5✔
1578
                pre.append("Optional[")
5✔
1579
                post_size += 1
5✔
1580

1581
            if isinstance(column_type, ARRAY):
5✔
1582
                dim = getattr(column_type, "dimensions", None) or 1
5✔
1583
                pre.extend("list[" for _ in range(dim))
5✔
1584
                post_size += dim
5✔
1585

1586
                column_type = column_type.item_type
5✔
1587

1588
            return "".join(pre), column_type, "]" * post_size
5✔
1589

1590
        def render_python_type(column_type: TypeEngine[Any]) -> str:
5✔
1591
            # Check if this is an enum column with a Python enum class
1592
            if isinstance(column_type, Enum):
5✔
1593
                table_name = column.table.name
5✔
1594
                column_name = column.name
5✔
1595
                if (table_name, column_name) in self.enum_classes:
5✔
1596
                    enum_class_name = self.enum_classes[(table_name, column_name)]
5✔
1597
                    return enum_class_name
5✔
1598

1599
            if isinstance(column_type, DOMAIN):
5✔
1600
                column_type = column_type.data_type
5✔
1601

1602
            try:
5✔
1603
                python_type = column_type.python_type
5✔
1604
                python_type_module = python_type.__module__
5✔
1605
                python_type_name = python_type.__name__
5✔
1606
            except NotImplementedError:
5✔
1607
                self.add_literal_import("typing", "Any")
5✔
1608
                return "Any"
5✔
1609

1610
            if python_type_module == "builtins":
5✔
1611
                return python_type_name
5✔
1612

1613
            self.add_module_import(python_type_module)
5✔
1614
            return f"{python_type_module}.{python_type_name}"
5✔
1615

1616
        pre, col_type, post = get_type_qualifiers()
5✔
1617
        column_python_type = f"{pre}{render_python_type(col_type)}{post}"
5✔
1618
        return column_python_type
5✔
1619

1620
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1621
        column = column_attr.column
5✔
1622
        rendered_column = self.render_column(column, column_attr.name != column.name)
5✔
1623
        rendered_column_python_type = self.render_column_python_type(column)
5✔
1624

1625
        return f"{column_attr.name}: Mapped[{rendered_column_python_type}] = {rendered_column}"
5✔
1626

1627
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1628
        def render_column_attrs(column_attrs: list[ColumnAttribute]) -> str:
5✔
1629
            rendered = []
5✔
1630
            for attr in column_attrs:
5✔
1631
                if attr.model is relationship.source:
5✔
1632
                    rendered.append(attr.name)
5✔
1633
                else:
UNCOV
1634
                    rendered.append(repr(f"{attr.model.name}.{attr.name}"))
×
1635

1636
            return "[" + ", ".join(rendered) + "]"
5✔
1637

1638
        def render_foreign_keys(column_attrs: list[ColumnAttribute]) -> str:
5✔
1639
            rendered = []
5✔
1640
            render_as_string = False
5✔
1641
            # Assume that column_attrs are all in relationship.source or none
1642
            for attr in column_attrs:
5✔
1643
                if attr.model is relationship.source:
5✔
1644
                    rendered.append(attr.name)
5✔
1645
                else:
1646
                    rendered.append(f"{attr.model.name}.{attr.name}")
5✔
1647
                    render_as_string = True
5✔
1648

1649
            if render_as_string:
5✔
1650
                return "'[" + ", ".join(rendered) + "]'"
5✔
1651
            else:
1652
                return "[" + ", ".join(rendered) + "]"
5✔
1653

1654
        def render_join(terms: list[JoinType]) -> str:
5✔
1655
            rendered_joins = []
5✔
1656
            for source, source_col, target, target_col in terms:
5✔
1657
                rendered = f"lambda: {source.name}.{source_col} == {target.name}."
5✔
1658
                if target.__class__ is Model:
5✔
1659
                    rendered += "c."
5✔
1660

1661
                rendered += str(target_col)
5✔
1662
                rendered_joins.append(rendered)
5✔
1663

1664
            if len(rendered_joins) > 1:
5✔
UNCOV
1665
                rendered = ", ".join(rendered_joins)
×
1666
                return f"and_({rendered})"
×
1667
            else:
1668
                return rendered_joins[0]
5✔
1669

1670
        # Render keyword arguments
1671
        kwargs: dict[str, Any] = {}
5✔
1672
        if relationship.type is RelationshipType.ONE_TO_ONE and relationship.constraint:
5✔
1673
            if relationship.constraint.referred_table is relationship.source.table:
5✔
1674
                kwargs["uselist"] = False
5✔
1675

1676
        # Add the "secondary" keyword for many-to-many relationships
1677
        if relationship.association_table:
5✔
1678
            table_ref = relationship.association_table.table.name
5✔
1679
            if relationship.association_table.schema:
5✔
1680
                table_ref = f"{relationship.association_table.schema}.{table_ref}"
5✔
1681

1682
            kwargs["secondary"] = repr(table_ref)
5✔
1683

1684
        if relationship.remote_side:
5✔
1685
            kwargs["remote_side"] = render_column_attrs(relationship.remote_side)
5✔
1686

1687
        if relationship.foreign_keys:
5✔
1688
            kwargs["foreign_keys"] = render_foreign_keys(relationship.foreign_keys)
5✔
1689

1690
        if relationship.primaryjoin:
5✔
1691
            kwargs["primaryjoin"] = render_join(relationship.primaryjoin)
5✔
1692

1693
        if relationship.secondaryjoin:
5✔
1694
            kwargs["secondaryjoin"] = render_join(relationship.secondaryjoin)
5✔
1695

1696
        if relationship.backref:
5✔
1697
            kwargs["back_populates"] = repr(relationship.backref.name)
5✔
1698

1699
        rendered_relationship = render_callable(
5✔
1700
            "relationship", repr(relationship.target.name), kwargs=kwargs
1701
        )
1702

1703
        relationship_type: str
1704
        if relationship.type == RelationshipType.ONE_TO_MANY:
5✔
1705
            relationship_type = f"list['{relationship.target.name}']"
5✔
1706
        elif relationship.type in (
5✔
1707
            RelationshipType.ONE_TO_ONE,
1708
            RelationshipType.MANY_TO_ONE,
1709
        ):
1710
            relationship_type = f"'{relationship.target.name}'"
5✔
1711
            if relationship.constraint and any(
5✔
1712
                col.nullable for col in relationship.constraint.columns
1713
            ):
1714
                self.add_literal_import("typing", "Optional")
5✔
1715
                relationship_type = f"Optional[{relationship_type}]"
5✔
1716
        elif relationship.type == RelationshipType.MANY_TO_MANY:
5✔
1717
            relationship_type = f"list['{relationship.target.name}']"
5✔
1718
        else:
UNCOV
1719
            self.add_literal_import("typing", "Any")
×
1720
            relationship_type = "Any"
×
1721

1722
        return (
5✔
1723
            f"{relationship.name}: Mapped[{relationship_type}] "
1724
            f"= {rendered_relationship}"
1725
        )
1726

1727

1728
class DataclassGenerator(DeclarativeGenerator):
5✔
1729
    def __init__(
5✔
1730
        self,
1731
        metadata: MetaData,
1732
        bind: Connection | Engine,
1733
        options: Sequence[str],
1734
        *,
1735
        indentation: str = "    ",
1736
        base_class_name: str = "Base",
1737
        quote_annotations: bool = False,
1738
        metadata_key: str = "sa",
1739
    ):
1740
        super().__init__(
5✔
1741
            metadata,
1742
            bind,
1743
            options,
1744
            indentation=indentation,
1745
            base_class_name=base_class_name,
1746
        )
1747
        self.metadata_key: str = metadata_key
5✔
1748
        self.quote_annotations: bool = quote_annotations
5✔
1749

1750
    def generate_base(self) -> None:
5✔
1751
        self.base = Base(
5✔
1752
            literal_imports=[
1753
                LiteralImport("sqlalchemy.orm", "DeclarativeBase"),
1754
                LiteralImport("sqlalchemy.orm", "MappedAsDataclass"),
1755
            ],
1756
            declarations=[
1757
                (f"class {self.base_class_name}(MappedAsDataclass, DeclarativeBase):"),
1758
                f"{self.indentation}pass",
1759
            ],
1760
            metadata_ref=f"{self.base_class_name}.metadata",
1761
        )
1762

1763

1764
class SQLModelGenerator(DeclarativeGenerator):
5✔
1765
    def __init__(
5✔
1766
        self,
1767
        metadata: MetaData,
1768
        bind: Connection | Engine,
1769
        options: Sequence[str],
1770
        *,
1771
        indentation: str = "    ",
1772
        base_class_name: str = "SQLModel",
1773
    ):
1774
        super().__init__(
5✔
1775
            metadata,
1776
            bind,
1777
            options,
1778
            indentation=indentation,
1779
            base_class_name=base_class_name,
1780
        )
1781

1782
    @property
5✔
1783
    def views_supported(self) -> bool:
5✔
UNCOV
1784
        return False
×
1785

1786
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
1787
        self.add_import(Column)
5✔
1788
        return render_callable("Column", *args, kwargs=kwargs)
5✔
1789

1790
    def generate_base(self) -> None:
5✔
1791
        self.base = Base(
5✔
1792
            literal_imports=[],
1793
            declarations=[],
1794
            metadata_ref="",
1795
        )
1796

1797
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1798
        super(DeclarativeGenerator, self).collect_imports(models)
5✔
1799
        if any(isinstance(model, ModelClass) for model in models):
5✔
1800
            self.remove_literal_import("sqlalchemy", "MetaData")
5✔
1801
            self.add_literal_import("sqlmodel", "SQLModel")
5✔
1802
            self.add_literal_import("sqlmodel", "Field")
5✔
1803

1804
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1805
        super(DeclarativeGenerator, self).collect_imports_for_model(model)
5✔
1806
        if isinstance(model, ModelClass):
5✔
1807
            for column_attr in model.columns:
5✔
1808
                if column_attr.column.nullable:
5✔
1809
                    self.add_literal_import("typing", "Optional")
5✔
1810
                    break
5✔
1811

1812
            if model.relationships:
5✔
1813
                self.add_literal_import("sqlmodel", "Relationship")
5✔
1814

1815
    def render_module_variables(self, models: list[Model]) -> str:
5✔
1816
        declarations: list[str] = []
5✔
1817
        if any(not isinstance(model, ModelClass) for model in models):
5✔
UNCOV
1818
            if self.base.table_metadata_declaration is not None:
×
1819
                declarations.append(self.base.table_metadata_declaration)
×
1820

1821
        return "\n".join(declarations)
5✔
1822

1823
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1824
        if model.parent_class:
5✔
UNCOV
1825
            parent = model.parent_class.name
×
1826
        else:
1827
            parent = self.base_class_name
5✔
1828

1829
        superclass_part = f"({parent}, table=True)"
5✔
1830
        return f"class {model.name}{superclass_part}:"
5✔
1831

1832
    def render_class_variables(self, model: ModelClass) -> str:
5✔
1833
        variables = []
5✔
1834

1835
        if model.table.name != model.name.lower():
5✔
1836
            variables.append(f"__tablename__ = {model.table.name!r}")
5✔
1837

1838
        # Render constraints and indexes as __table_args__
1839
        table_args = self.render_table_args(model.table)
5✔
1840
        if table_args:
5✔
1841
            variables.append(f"__table_args__ = {table_args}")
5✔
1842

1843
        return "\n".join(variables)
5✔
1844

1845
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1846
        column = column_attr.column
5✔
1847
        rendered_column = self.render_column(column, True)
5✔
1848
        rendered_column_python_type = self.render_column_python_type(column)
5✔
1849

1850
        kwargs: dict[str, Any] = {}
5✔
1851
        if column.nullable:
5✔
1852
            kwargs["default"] = None
5✔
1853
        kwargs["sa_column"] = f"{rendered_column}"
5✔
1854

1855
        rendered_field = render_callable("Field", kwargs=kwargs)
5✔
1856

1857
        return f"{column_attr.name}: {rendered_column_python_type} = {rendered_field}"
5✔
1858

1859
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1860
        rendered = super().render_relationship(relationship).partition(" = ")[2]
5✔
1861
        args = self.render_relationship_args(rendered)
5✔
1862
        kwargs: dict[str, Any] = {}
5✔
1863
        annotation = repr(relationship.target.name)
5✔
1864

1865
        if relationship.type in (
5✔
1866
            RelationshipType.ONE_TO_MANY,
1867
            RelationshipType.MANY_TO_MANY,
1868
        ):
1869
            annotation = f"list[{annotation}]"
5✔
1870
        else:
1871
            self.add_literal_import("typing", "Optional")
5✔
1872
            annotation = f"Optional[{annotation}]"
5✔
1873

1874
        rendered_field = render_callable("Relationship", *args, kwargs=kwargs)
5✔
1875
        return f"{relationship.name}: {annotation} = {rendered_field}"
5✔
1876

1877
    def render_relationship_args(self, arguments: str) -> list[str]:
5✔
1878
        argument_list = arguments.split(",")
5✔
1879
        # delete ')' and ' ' from args
1880
        argument_list[-1] = argument_list[-1][:-1]
5✔
1881
        argument_list = [argument[1:] for argument in argument_list]
5✔
1882

1883
        rendered_args: list[str] = []
5✔
1884
        for arg in argument_list:
5✔
1885
            if "back_populates" in arg:
5✔
1886
                rendered_args.append(arg)
5✔
1887
            if "uselist=False" in arg:
5✔
1888
                rendered_args.append("sa_relationship_kwargs={'uselist': False}")
5✔
1889

1890
        return rendered_args
5✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc