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

agronholm / sqlacodegen / 23212143380

17 Mar 2026 07:16PM UTC coverage: 97.832% (-0.03%) from 97.861%
23212143380

Pull #470

github

web-flow
Merge cb1696cfc into 9234437e1
Pull Request #470: Improve Identity server_default rendering for Decimal values

21 of 22 new or added lines in 2 files covered. (95.45%)

1 existing line in 1 file now uncovered.

1850 of 1891 relevant lines covered (97.83%)

4.89 hits per line

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

96.98
/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, Mapping, Sequence
5✔
9
from dataclasses import dataclass
5✔
10
from decimal import Decimal
5✔
11
from importlib import import_module
5✔
12
from inspect import Parameter
5✔
13
from itertools import count
5✔
14
from keyword import iskeyword
5✔
15
from pprint import pformat
5✔
16
from textwrap import indent
5✔
17
from typing import Any, ClassVar, Literal, cast
5✔
18

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

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

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

75

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

81

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

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

92

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

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

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

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

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

120

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

367
        return models
5✔
368

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

479
        if show_name:
5✔
480
            args.append(repr(column.name))
5✔
481

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

487
        for fk in dedicated_fks:
5✔
488
            args.append(self.render_constraint(fk))
5✔
489

490
        if column.default:
5✔
491
            args.append(repr(column.default))
5✔
492

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

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

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

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

521
            args.append(
5✔
522
                render_callable("Computed", repr(expression), kwargs=computed_kwargs)
523
            )
524
        elif isinstance(column.server_default, Identity):
5✔
525
            identity = column.server_default
5✔
526
            identity_kwargs: dict[str, Any] = {}
5✔
527

528
            for name, param in inspect.signature(Identity).parameters.items():
5✔
529
                if name == "self" or param.kind in (
5✔
530
                    Parameter.VAR_POSITIONAL,
531
                    Parameter.VAR_KEYWORD,
532
                ):
NEW
533
                    continue
×
534

535
                value = getattr(identity, name, None)
5✔
536
                if value is None:
5✔
537
                    continue
5✔
538

539
                if isinstance(value, Decimal):
5✔
540
                    value = int(value)
5✔
541

542
                if param.default is not Parameter.empty and value == param.default:
5✔
543
                    continue
5✔
544

545
                identity_kwargs[name] = value
5✔
546

547
            args.append(render_callable("Identity", kwargs=identity_kwargs))
5✔
548
        elif column.server_default:
5✔
549
            kwargs["server_default"] = repr(column.server_default)
×
550

551
        comment = getattr(column, "comment", None)
5✔
552
        if comment:
5✔
553
            kwargs["comment"] = repr(comment)
5✔
554

555
        # add column info + dialect kwargs for callable context (opt-in)
556
        if self.include_dialect_options_and_info:
5✔
557
            self._add_dialect_kwargs_and_info(column, kwargs, values_for_dict=False)
5✔
558

559
        return self.render_column_callable(is_table, *args, **kwargs)
5✔
560

561
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
562
        if is_table:
5✔
563
            self.add_import(Column)
5✔
564
            return render_callable("Column", *args, kwargs=kwargs)
5✔
565
        else:
566
            return render_callable("mapped_column", *args, kwargs=kwargs)
5✔
567

568
    def _render_column_type_value(self, value: Any) -> str:
5✔
569
        if isinstance(value, (JSONB, JSON)):
5✔
570
            # Remove astext_type if it's the default
571
            if isinstance(value.astext_type, Text) and value.astext_type.length is None:
5✔
572
                value.astext_type = None  # type: ignore[assignment]
5✔
573
            else:
574
                self.add_import(Text)
5✔
575

576
        if isinstance(value, TextClause):
5✔
577
            self.add_literal_import("sqlalchemy", "text")
5✔
578
            return render_callable("text", repr(value.text))
5✔
579

580
        return repr(value)
5✔
581

582
    def _collect_inherited_init_kwargs(
5✔
583
        self,
584
        column_type: Any,
585
        init_sig: inspect.Signature,
586
        seen_param_names: set[str],
587
        missing: object,
588
    ) -> dict[str, str]:
589
        has_var_keyword = any(
5✔
590
            param.kind is Parameter.VAR_KEYWORD
591
            for param in init_sig.parameters.values()
592
        )
593
        has_var_positional = any(
5✔
594
            param.kind is Parameter.VAR_POSITIONAL
595
            for param in init_sig.parameters.values()
596
        )
597
        if not has_var_keyword or has_var_positional:
5✔
598
            return {}
5✔
599

600
        inherited_kwargs: dict[str, str] = {}
5✔
601
        for supercls in column_type.__class__.__mro__[1:]:
5✔
602
            if supercls is object:
5✔
603
                break
5✔
604

605
            try:
5✔
606
                super_sig = inspect.signature(supercls.__init__)
5✔
607
            except (TypeError, ValueError):
×
608
                continue
×
609

610
            for super_param in list(super_sig.parameters.values())[1:]:
5✔
611
                if super_param.name.startswith("_"):
5✔
612
                    continue
5✔
613

614
                if super_param.kind in (
5✔
615
                    Parameter.POSITIONAL_ONLY,
616
                    Parameter.VAR_POSITIONAL,
617
                    Parameter.VAR_KEYWORD,
618
                ):
619
                    continue
5✔
620

621
                if super_param.name in seen_param_names:
5✔
622
                    continue
5✔
623

624
                seen_param_names.add(super_param.name)
5✔
625
                value = getattr(column_type, super_param.name, missing)
5✔
626
                if value is missing:
5✔
627
                    continue
5✔
628

629
                default = super_param.default
5✔
630
                if default is not Parameter.empty and value == default:
5✔
631
                    continue
5✔
632

633
                inherited_kwargs[super_param.name] = self._render_column_type_value(
5✔
634
                    value
635
                )
636

637
        return inherited_kwargs
5✔
638

639
    def render_column_type(self, column: Column[Any]) -> str:
5✔
640
        column_type = column.type
5✔
641
        # Check if this is an enum column with a Python enum class
642
        if isinstance(column_type, Enum) and column is not None:
5✔
643
            if enum_class_name := self.enum_classes.get(
5✔
644
                (column.table.name, column.name)
645
            ):
646
                # Import SQLAlchemy Enum (will be handled in collect_imports)
647
                self.add_import(Enum)
5✔
648
                extra_kwargs = ""
5✔
649
                if column_type.name is not None:
5✔
650
                    extra_kwargs += f", name={column_type.name!r}"
5✔
651

652
                if column_type.schema is not None:
5✔
653
                    extra_kwargs += f", schema={column_type.schema!r}"
5✔
654

655
                return f"Enum({enum_class_name}, values_callable=lambda cls: [member.value for member in cls]{extra_kwargs})"
5✔
656

657
        args = []
5✔
658
        kwargs: dict[str, Any] = {}
5✔
659

660
        # Check if this is an ARRAY column with an Enum item type mapped to a Python enum class
661
        if isinstance(column_type, ARRAY) and isinstance(column_type.item_type, Enum):
5✔
662
            if enum_class_name := self.enum_classes.get(
5✔
663
                (column.table.name, column.name)
664
            ):
665
                self.add_import(ARRAY)
5✔
666
                self.add_import(Enum)
5✔
667
                extra_kwargs = ""
5✔
668
                if column_type.item_type.name is not None:
5✔
669
                    extra_kwargs += f", name={column_type.item_type.name!r}"
5✔
670

671
                if column_type.item_type.schema is not None:
5✔
672
                    extra_kwargs += f", schema={column_type.item_type.schema!r}"
5✔
673

674
                rendered_enum = f"Enum({enum_class_name}, values_callable=lambda cls: [member.value for member in cls]{extra_kwargs})"
5✔
675
                if column_type.dimensions is not None:
5✔
676
                    kwargs["dimensions"] = repr(column_type.dimensions)
5✔
677

678
                return render_callable("ARRAY", rendered_enum, kwargs=kwargs)
5✔
679

680
        sig = inspect.signature(column_type.__class__.__init__)
5✔
681
        defaults = {param.name: param.default for param in sig.parameters.values()}
5✔
682
        missing = object()
5✔
683
        use_kwargs = False
5✔
684
        seen_param_names: set[str] = set()
5✔
685

686
        for param in list(sig.parameters.values())[1:]:
5✔
687
            # Remove annoyances like _warn_on_bytestring
688
            if param.name.startswith("_"):
5✔
689
                continue
5✔
690
            elif param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD):
5✔
691
                use_kwargs = True
5✔
692
                continue
5✔
693

694
            seen_param_names.add(param.name)
5✔
695
            value = getattr(column_type, param.name, missing)
5✔
696
            default = defaults.get(param.name, missing)
5✔
697
            if value is missing or value == default:
5✔
698
                use_kwargs = True
5✔
699
                continue
5✔
700

701
            rendered_value = self._render_column_type_value(value)
5✔
702
            if use_kwargs:
5✔
703
                kwargs[param.name] = rendered_value
5✔
704
            else:
705
                args.append(rendered_value)
5✔
706

707
        kwargs.update(
5✔
708
            self._collect_inherited_init_kwargs(
709
                column_type, sig, seen_param_names, missing
710
            )
711
        )
712

713
        vararg = next(
5✔
714
            (
715
                param.name
716
                for param in sig.parameters.values()
717
                if param.kind is Parameter.VAR_POSITIONAL
718
            ),
719
            None,
720
        )
721
        if vararg and hasattr(column_type, vararg):
5✔
722
            varargs_repr = [repr(arg) for arg in getattr(column_type, vararg)]
5✔
723
            args.extend(varargs_repr)
5✔
724

725
        # These arguments cannot be autodetected from the Enum initializer
726
        if isinstance(column_type, Enum):
5✔
727
            for colname in "name", "schema":
5✔
728
                if (value := getattr(column_type, colname)) is not None:
5✔
729
                    kwargs[colname] = repr(value)
5✔
730

731
        if isinstance(column_type, (JSONB, JSON)):
5✔
732
            # Remove astext_type if it's the default
733
            if (
5✔
734
                isinstance(column_type.astext_type, Text)
735
                and column_type.astext_type.length is None
736
            ):
737
                del kwargs["astext_type"]
5✔
738

739
        if args or kwargs:
5✔
740
            return render_callable(column_type.__class__.__name__, *args, kwargs=kwargs)
5✔
741
        else:
742
            return column_type.__class__.__name__
5✔
743

744
    def render_constraint(self, constraint: Constraint | ForeignKey) -> str:
5✔
745
        def add_fk_options(*opts: Any) -> None:
5✔
746
            args.extend(repr(opt) for opt in opts)
5✔
747
            for attr in "ondelete", "onupdate", "deferrable", "initially", "match":
5✔
748
                value = getattr(constraint, attr, None)
5✔
749
                if value:
5✔
750
                    kwargs[attr] = repr(value)
5✔
751

752
        args: list[str] = []
5✔
753
        kwargs: dict[str, Any] = {}
5✔
754
        if isinstance(constraint, ForeignKey):
5✔
755
            remote_column = (
5✔
756
                f"{constraint.column.table.fullname}.{constraint.column.name}"
757
            )
758
            add_fk_options(remote_column)
5✔
759
        elif isinstance(constraint, ForeignKeyConstraint):
5✔
760
            local_columns = get_column_names(constraint)
5✔
761
            remote_columns = [
5✔
762
                f"{fk.column.table.fullname}.{fk.column.name}"
763
                for fk in constraint.elements
764
            ]
765
            add_fk_options(local_columns, remote_columns)
5✔
766
        elif isinstance(constraint, CheckConstraint):
5✔
767
            args.append(repr(get_compiled_expression(constraint.sqltext, self.bind)))
5✔
768
        elif isinstance(constraint, (UniqueConstraint, PrimaryKeyConstraint)):
5✔
769
            args.extend(repr(col.name) for col in constraint.columns)
5✔
770
        else:
771
            raise TypeError(
×
772
                f"Cannot render constraint of type {constraint.__class__.__name__}"
773
            )
774

775
        if isinstance(constraint, Constraint) and not uses_default_name(constraint):
5✔
776
            kwargs["name"] = repr(constraint.name)
5✔
777

778
        return render_callable(constraint.__class__.__name__, *args, kwargs=kwargs)
5✔
779

780
    def _add_dialect_kwargs_and_info(
5✔
781
        self, obj: Any, target_kwargs: dict[str, object], *, values_for_dict: bool
782
    ) -> None:
783
        """
784
        Merge SchemaItem-like object's .info and .dialect_kwargs into target_kwargs.
785
        - values_for_dict=True: keep raw values so pretty-printer emits repr() (for __table_args__ dict)
786
        - values_for_dict=False: set values to repr() strings (for callable kwargs)
787
        """
788
        info_dict = getattr(obj, "info", None)
5✔
789
        if info_dict:
5✔
790
            target_kwargs["info"] = info_dict if values_for_dict else repr(info_dict)
5✔
791

792
        dialect_keys: list[str]
793
        try:
5✔
794
            dialect_keys = sorted(getattr(obj, "dialect_kwargs"))
5✔
795
        except Exception:
×
796
            return
×
797

798
        dialect_kwargs = getattr(obj, "dialect_kwargs", {})
5✔
799
        for key in dialect_keys:
5✔
800
            try:
5✔
801
                value = dialect_kwargs[key]
5✔
802
            except Exception:
×
803
                continue
×
804

805
            if isinstance(value, list | dict) and not value:
5✔
806
                continue
5✔
807

808
            # Render values:
809
            # - callable context (values_for_dict=False): produce a string expression.
810
            #   primitives use repr(value); custom objects stringify then repr().
811
            # - dict context (values_for_dict=True): pass raw primitives / str;
812
            #   custom objects become str(value) so pformat quotes them.
813
            if values_for_dict:
5✔
814
                if isinstance(value, type(None) | bool | int | float):
5✔
815
                    target_kwargs[key] = value
×
816
                elif isinstance(value, str | dict | list):
5✔
817
                    target_kwargs[key] = value
5✔
818
                else:
819
                    target_kwargs[key] = str(value)
5✔
820
            else:
821
                if isinstance(
5✔
822
                    value, type(None) | bool | int | float | str | dict | list
823
                ):
824
                    target_kwargs[key] = repr(value)
5✔
825
                else:
826
                    target_kwargs[key] = repr(str(value))
5✔
827

828
    def should_ignore_table(self, table: Table) -> bool:
5✔
829
        # Support for Alembic and sqlalchemy-migrate -- never expose the schema version
830
        # tables
831
        return table.name in ("alembic_version", "migrate_version")
5✔
832

833
    def find_free_name(
5✔
834
        self, name: str, global_names: set[str], local_names: Collection[str] = ()
835
    ) -> str:
836
        """
837
        Generate an attribute name that does not clash with other local or global names.
838
        """
839
        name = name.strip()
5✔
840
        assert name, "Identifier cannot be empty"
5✔
841
        name = _re_invalid_identifier.sub("_", name)
5✔
842
        if name[0].isdigit():
5✔
843
            name = "_" + name
5✔
844
        elif iskeyword(name) or name == "metadata":
5✔
845
            name += "_"
5✔
846

847
        original = name
5✔
848
        for i in count():
5✔
849
            if name not in global_names and name not in local_names:
5✔
850
                break
5✔
851

852
            name = original + (str(i) if i else "_")
5✔
853

854
        return name
5✔
855

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

860
    def _create_enum_class(
5✔
861
        self, table_name: str, column_name: str, values: list[str]
862
    ) -> str:
863
        """
864
        Create a Python enum class name and register it.
865

866
        Returns the enum class name to use in generated code.
867
        """
868
        # Generate enum class name from table and column names
869
        # Convert to PascalCase: user_status -> UserStatus
870
        base_name = "".join(
5✔
871
            part.capitalize()
872
            for part in table_name.split("_") + column_name.split("_")
873
            if part
874
        )
875

876
        # Ensure uniqueness
877
        enum_class_name = base_name
5✔
878
        for counter in count(1):
5✔
879
            if enum_class_name not in self.enum_values:
5✔
880
                break
5✔
881

882
            # Check if it's the same enum (same values)
883
            if self.enum_values[enum_class_name] == values:
5✔
884
                # Reuse existing enum class
885
                return enum_class_name
5✔
886

887
            enum_class_name = f"{base_name}{counter}"
5✔
888

889
        # Register the new enum class
890
        self.enum_values[enum_class_name] = values
5✔
891
        return enum_class_name
5✔
892

893
    def render_enum_classes(self) -> str:
5✔
894
        """Render Python enum class definitions."""
895
        if not self.enum_values:
5✔
896
            return ""
5✔
897

898
        self.add_module_import("enum")
5✔
899

900
        enum_defs = []
5✔
901
        for enum_class_name, values in sorted(self.enum_values.items()):
5✔
902
            # Create enum members with valid Python identifiers
903
            members = []
5✔
904
            for value in values:
5✔
905
                # Unescape SQL escape sequences (e.g., \' -> ')
906
                # The value from the CHECK constraint has SQL escaping
907
                unescaped_value = value.replace("\\'", "'").replace("\\\\", "\\")
5✔
908

909
                # Create a valid identifier from the enum value
910
                member_name = _re_invalid_identifier.sub("_", unescaped_value).upper()
5✔
911
                if not member_name:
5✔
912
                    member_name = "EMPTY"
×
913
                elif member_name[0].isdigit():
5✔
914
                    member_name = "_" + member_name
×
915
                elif iskeyword(member_name):
5✔
916
                    member_name += "_"
×
917
                #
918
                # # Re-escape for Python string literal
919
                # python_escaped = unescaped_value.replace("\\", "\\\\").replace(
920
                #     "'", "\\'"
921
                # )
922
                members.append(f"    {member_name} = {unescaped_value!r}")
5✔
923

924
            enum_def = f"class {enum_class_name}(str, enum.Enum):\n" + "\n".join(
5✔
925
                members
926
            )
927
            enum_defs.append(enum_def)
5✔
928

929
        return "\n\n\n".join(enum_defs)
5✔
930

931
    def fix_column_types(self, table: Table) -> None:
5✔
932
        """Adjust the reflected column types."""
933

934
        def fix_enum_column(col_name: str, enum_type: Enum) -> None:
5✔
935
            if (table.name, col_name) in self.enum_classes:
5✔
936
                return
5✔
937

938
            if enum_type.name:
5✔
939
                existing_class = None
5✔
940
                for (_, _), cls in self.enum_classes.items():
5✔
941
                    if cls == self._enum_name_to_class_name(enum_type.name):
5✔
942
                        existing_class = cls
5✔
943
                        break
5✔
944

945
                if existing_class:
5✔
946
                    enum_class_name = existing_class
5✔
947
                else:
948
                    enum_class_name = self._enum_name_to_class_name(enum_type.name)
5✔
949
                    if enum_class_name not in self.enum_values:
5✔
950
                        self.enum_values[enum_class_name] = list(enum_type.enums)
5✔
951
            else:
952
                enum_class_name = self._create_enum_class(
5✔
953
                    table.name, col_name, list(enum_type.enums)
954
                )
955

956
            self.enum_classes[(table.name, col_name)] = enum_class_name
5✔
957

958
        # Detect check constraints for boolean and enum columns
959
        for constraint in table.constraints.copy():
5✔
960
            if isinstance(constraint, CheckConstraint):
5✔
961
                sqltext = get_compiled_expression(constraint.sqltext, self.bind)
5✔
962

963
                # Turn any integer-like column with a CheckConstraint like
964
                # "column IN (0, 1)" into a Boolean
965
                if match := _re_boolean_check_constraint.match(sqltext):
5✔
966
                    if colname_match := _re_column_name.match(match.group(1)):
5✔
967
                        colname = colname_match.group(3)
5✔
968
                        table.constraints.remove(constraint)
5✔
969
                        table.c[colname].type = Boolean()
5✔
970
                        continue
5✔
971

972
                # Turn VARCHAR columns with CHECK constraints like "column IN ('a', 'b')"
973
                # into synthetic Enum types with Python enum classes
974
                if (
5✔
975
                    "nosyntheticenums" not in self.options
976
                    and (match := _re_enum_check_constraint.match(sqltext))
977
                    and (colname_match := _re_column_name.match(match.group(1)))
978
                ):
979
                    colname = colname_match.group(3)
5✔
980
                    items = match.group(2)
5✔
981
                    if isinstance(table.c[colname].type, String) and not isinstance(
5✔
982
                        table.c[colname].type, Enum
983
                    ):
984
                        options = _re_enum_item.findall(items)
5✔
985
                        # Create Python enum class
986
                        enum_class_name = self._create_enum_class(
5✔
987
                            table.name, colname, options
988
                        )
989
                        self.enum_classes[(table.name, colname)] = enum_class_name
5✔
990
                        # Convert to Enum type but KEEP the constraint
991
                        table.c[colname].type = Enum(*options, native_enum=False)
5✔
992
                        continue
5✔
993

994
        for column in table.c:
5✔
995
            # Handle native database Enum types (e.g., PostgreSQL ENUM)
996
            if (
5✔
997
                "nonativeenums" not in self.options
998
                and isinstance(column.type, Enum)
999
                and column.type.enums
1000
            ):
1001
                fix_enum_column(column.name, column.type)
5✔
1002

1003
            # Handle ARRAY columns with Enum item types (e.g., PostgreSQL ARRAY(ENUM))
1004
            elif (
5✔
1005
                "nonativeenums" not in self.options
1006
                and isinstance(column.type, ARRAY)
1007
                and isinstance(column.type.item_type, Enum)
1008
                and column.type.item_type.enums
1009
            ):
1010
                fix_enum_column(column.name, column.type.item_type)
5✔
1011

1012
            if not self.keep_dialect_types:
5✔
1013
                try:
5✔
1014
                    column.type = self.get_adapted_type(column.type)
5✔
1015
                except CompileError:
5✔
1016
                    continue
5✔
1017

1018
            # PostgreSQL specific fix: detect sequences from server_default
1019
            if column.server_default and self.bind.dialect.name == "postgresql":
5✔
1020
                if isinstance(column.server_default, DefaultClause) and isinstance(
5✔
1021
                    column.server_default.arg, TextClause
1022
                ):
1023
                    schema, seqname = decode_postgresql_sequence(
5✔
1024
                        column.server_default.arg
1025
                    )
1026
                    if seqname:
5✔
1027
                        # Add an explicit sequence
1028
                        if seqname != f"{column.table.name}_{column.name}_seq":
5✔
1029
                            column.default = sqlalchemy.Sequence(seqname, schema=schema)
5✔
1030

1031
                        column.server_default = None
5✔
1032

1033
    def get_adapted_type(self, coltype: Any) -> Any:
5✔
1034
        compiled_type = coltype.compile(self.bind.engine.dialect)
5✔
1035
        for supercls in coltype.__class__.__mro__:
5✔
1036
            if not supercls.__name__.startswith("_") and hasattr(
5✔
1037
                supercls, "__visit_name__"
1038
            ):
1039
                # Don't try to adapt UserDefinedType as it's not a proper column type
1040
                if supercls is UserDefinedType or issubclass(supercls, TypeDecorator):
5✔
1041
                    return coltype
5✔
1042

1043
                # Hack to fix adaptation of the Enum class which is broken since
1044
                # SQLAlchemy 1.2
1045
                kw = {}
5✔
1046
                if supercls is Enum:
5✔
1047
                    kw["name"] = coltype.name
5✔
1048
                    if coltype.schema:
5✔
1049
                        kw["schema"] = coltype.schema
5✔
1050

1051
                # Hack to fix Postgres DOMAIN type adaptation, broken as of SQLAlchemy 2.0.42
1052
                # For additional information - https://github.com/agronholm/sqlacodegen/issues/416#issuecomment-3417480599
1053
                if supercls is DOMAIN:
5✔
1054
                    if coltype.default:
5✔
1055
                        kw["default"] = coltype.default
×
1056
                    if coltype.constraint_name is not None:
5✔
1057
                        kw["constraint_name"] = coltype.constraint_name
5✔
1058
                    if coltype.not_null:
5✔
1059
                        kw["not_null"] = coltype.not_null
×
1060
                    if coltype.check is not None:
5✔
1061
                        kw["check"] = coltype.check
5✔
1062
                    if coltype.create_type:
5✔
1063
                        kw["create_type"] = coltype.create_type
5✔
1064

1065
                try:
5✔
1066
                    new_coltype = coltype.adapt(supercls)
5✔
1067
                except TypeError:
5✔
1068
                    # If the adaptation fails, don't try again
1069
                    break
5✔
1070

1071
                for key, value in kw.items():
5✔
1072
                    setattr(new_coltype, key, value)
5✔
1073

1074
                if isinstance(coltype, ARRAY):
5✔
1075
                    new_coltype.item_type = self.get_adapted_type(new_coltype.item_type)
5✔
1076

1077
                try:
5✔
1078
                    # If the adapted column type does not render the same as the
1079
                    # original, don't substitute it
1080
                    if new_coltype.compile(self.bind.engine.dialect) != compiled_type:
5✔
1081
                        break
5✔
1082
                except CompileError:
5✔
1083
                    # If the adapted column type can't be compiled, don't substitute it
1084
                    break
5✔
1085

1086
                # Stop on the first valid non-uppercase column type class
1087
                coltype = new_coltype
5✔
1088
                if supercls.__name__ != supercls.__name__.upper():
5✔
1089
                    break
5✔
1090

1091
        return coltype
5✔
1092

1093

1094
class DeclarativeGenerator(TablesGenerator):
5✔
1095
    valid_options: ClassVar[set[str]] = TablesGenerator.valid_options | {
5✔
1096
        "use_inflect",
1097
        "nojoined",
1098
        "nobidi",
1099
        "noidsuffix",
1100
        "nofknames",
1101
    }
1102

1103
    def __init__(
5✔
1104
        self,
1105
        metadata: MetaData,
1106
        bind: Connection | Engine,
1107
        options: Sequence[str],
1108
        *,
1109
        indentation: str = "    ",
1110
        base_class_name: str = "Base",
1111
        explicit_foreign_keys: bool = False,
1112
    ):
1113
        super().__init__(metadata, bind, options, indentation=indentation)
5✔
1114
        self.base_class_name: str = base_class_name
5✔
1115
        self.inflect_engine = inflect.engine()
5✔
1116
        self.explicit_foreign_keys = explicit_foreign_keys
5✔
1117

1118
    def generate_base(self) -> None:
5✔
1119
        self.base = Base(
5✔
1120
            literal_imports=[LiteralImport("sqlalchemy.orm", "DeclarativeBase")],
1121
            declarations=[
1122
                f"class {self.base_class_name}(DeclarativeBase):",
1123
                f"{self.indentation}pass",
1124
            ],
1125
            metadata_ref=f"{self.base_class_name}.metadata",
1126
        )
1127

1128
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1129
        super().collect_imports(models)
5✔
1130
        if any(isinstance(model, ModelClass) for model in models):
5✔
1131
            self.add_literal_import("sqlalchemy.orm", "Mapped")
5✔
1132
            self.add_literal_import("sqlalchemy.orm", "mapped_column")
5✔
1133

1134
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1135
        super().collect_imports_for_model(model)
5✔
1136
        if isinstance(model, ModelClass):
5✔
1137
            if model.relationships:
5✔
1138
                self.add_literal_import("sqlalchemy.orm", "relationship")
5✔
1139

1140
    def generate_models(self) -> list[Model]:
5✔
1141
        models_by_table_name: dict[str, Model] = {}
5✔
1142

1143
        # Pick association tables from the metadata into their own set, don't process
1144
        # them normally
1145
        links: defaultdict[str, list[Model]] = defaultdict(lambda: [])
5✔
1146
        for table in self.metadata.sorted_tables:
5✔
1147
            qualified_name = qualified_table_name(table)
5✔
1148

1149
            # Link tables have exactly two foreign key constraints and all columns are
1150
            # involved in them
1151
            fk_constraints = sorted(
5✔
1152
                table.foreign_key_constraints, key=get_constraint_sort_key
1153
            )
1154
            if len(fk_constraints) == 2 and all(
5✔
1155
                col.foreign_keys for col in table.columns
1156
            ):
1157
                model = models_by_table_name[qualified_name] = Model(table)
5✔
1158
                tablename = fk_constraints[0].elements[0].column.table.name
5✔
1159
                links[tablename].append(model)
5✔
1160
                continue
5✔
1161

1162
            # Only form model classes for tables that have a primary key and are not
1163
            # association tables
1164
            if not table.primary_key:
5✔
1165
                models_by_table_name[qualified_name] = Model(table)
5✔
1166
            else:
1167
                model = ModelClass(table)
5✔
1168
                models_by_table_name[qualified_name] = model
5✔
1169

1170
                # Fill in the columns
1171
                for column in table.c:
5✔
1172
                    column_attr = ColumnAttribute(model, column)
5✔
1173
                    model.columns.append(column_attr)
5✔
1174

1175
        # Add relationships
1176
        for model in models_by_table_name.values():
5✔
1177
            if isinstance(model, ModelClass):
5✔
1178
                self.generate_relationships(
5✔
1179
                    model, models_by_table_name, links[model.table.name]
1180
                )
1181

1182
        # Nest inherited classes in their superclasses to ensure proper ordering
1183
        if "nojoined" not in self.options:
5✔
1184
            for model in list(models_by_table_name.values()):
5✔
1185
                if not isinstance(model, ModelClass):
5✔
1186
                    continue
5✔
1187

1188
                pk_column_names = {col.name for col in model.table.primary_key.columns}
5✔
1189
                for constraint in model.table.foreign_key_constraints:
5✔
1190
                    if set(get_column_names(constraint)) == pk_column_names:
5✔
1191
                        target = models_by_table_name[
5✔
1192
                            qualified_table_name(constraint.elements[0].column.table)
1193
                        ]
1194
                        if isinstance(target, ModelClass):
5✔
1195
                            model.parent_class = target
5✔
1196
                            target.children.append(model)
5✔
1197

1198
        # Change base if we only have tables
1199
        if not any(
5✔
1200
            isinstance(model, ModelClass) for model in models_by_table_name.values()
1201
        ):
1202
            super().generate_base()
5✔
1203

1204
        # Collect the imports
1205
        self.collect_imports(models_by_table_name.values())
5✔
1206

1207
        # Rename models and their attributes that conflict with imports or other
1208
        # attributes
1209
        global_names = {
5✔
1210
            name for namespace in self.imports.values() for name in namespace
1211
        }
1212
        for model in models_by_table_name.values():
5✔
1213
            self.generate_model_name(model, global_names)
5✔
1214
            global_names.add(model.name)
5✔
1215

1216
        return list(models_by_table_name.values())
5✔
1217

1218
    def generate_relationships(
5✔
1219
        self,
1220
        source: ModelClass,
1221
        models_by_table_name: dict[str, Model],
1222
        association_tables: list[Model],
1223
    ) -> list[RelationshipAttribute]:
1224
        relationships: list[RelationshipAttribute] = []
5✔
1225
        reverse_relationship: RelationshipAttribute | None
1226

1227
        # Add many-to-one (and one-to-many) relationships
1228
        pk_column_names = {col.name for col in source.table.primary_key.columns}
5✔
1229
        for constraint in sorted(
5✔
1230
            source.table.foreign_key_constraints, key=get_constraint_sort_key
1231
        ):
1232
            target = models_by_table_name[
5✔
1233
                qualified_table_name(constraint.elements[0].column.table)
1234
            ]
1235
            if isinstance(target, ModelClass):
5✔
1236
                if "nojoined" not in self.options:
5✔
1237
                    if set(get_column_names(constraint)) == pk_column_names:
5✔
1238
                        parent = models_by_table_name[
5✔
1239
                            qualified_table_name(constraint.elements[0].column.table)
1240
                        ]
1241
                        if isinstance(parent, ModelClass):
5✔
1242
                            source.parent_class = parent
5✔
1243
                            parent.children.append(source)
5✔
1244
                            continue
5✔
1245

1246
                # Add uselist=False to One-to-One relationships
1247
                column_names = get_column_names(constraint)
5✔
1248
                if any(
5✔
1249
                    isinstance(c, (PrimaryKeyConstraint, UniqueConstraint))
1250
                    and {col.name for col in c.columns} == set(column_names)
1251
                    for c in constraint.table.constraints
1252
                ):
1253
                    r_type = RelationshipType.ONE_TO_ONE
5✔
1254
                else:
1255
                    r_type = RelationshipType.MANY_TO_ONE
5✔
1256

1257
                relationship = RelationshipAttribute(r_type, source, target, constraint)
5✔
1258
                source.relationships.append(relationship)
5✔
1259

1260
                # For self referential relationships, remote_side needs to be set
1261
                if source is target:
5✔
1262
                    relationship.remote_side = [
5✔
1263
                        source.get_column_attribute(col.name)
1264
                        for col in constraint.referred_table.primary_key
1265
                    ]
1266

1267
                # If the two tables share more than one foreign key constraint,
1268
                # SQLAlchemy needs an explicit primaryjoin to figure out which column(s)
1269
                # it needs
1270
                common_fk_constraints = get_common_fk_constraints(
5✔
1271
                    source.table, target.table
1272
                )
1273
                if len(common_fk_constraints) > 1:
5✔
1274
                    relationship.foreign_keys = [
5✔
1275
                        source.get_column_attribute(key)
1276
                        for key in constraint.column_keys
1277
                    ]
1278

1279
                # Generate the opposite end of the relationship in the target class
1280
                if "nobidi" not in self.options:
5✔
1281
                    if r_type is RelationshipType.MANY_TO_ONE:
5✔
1282
                        r_type = RelationshipType.ONE_TO_MANY
5✔
1283

1284
                    reverse_relationship = RelationshipAttribute(
5✔
1285
                        r_type,
1286
                        target,
1287
                        source,
1288
                        constraint,
1289
                        foreign_keys=relationship.foreign_keys,
1290
                        backref=relationship,
1291
                    )
1292
                    relationship.backref = reverse_relationship
5✔
1293
                    target.relationships.append(reverse_relationship)
5✔
1294

1295
                    # For self referential relationships, remote_side needs to be set
1296
                    if source is target:
5✔
1297
                        reverse_relationship.remote_side = [
5✔
1298
                            source.get_column_attribute(colname)
1299
                            for colname in constraint.column_keys
1300
                        ]
1301

1302
        # Add many-to-many relationships
1303
        for association_table in association_tables:
5✔
1304
            fk_constraints = sorted(
5✔
1305
                association_table.table.foreign_key_constraints,
1306
                key=get_constraint_sort_key,
1307
            )
1308
            target = models_by_table_name[
5✔
1309
                qualified_table_name(fk_constraints[1].elements[0].column.table)
1310
            ]
1311
            if isinstance(target, ModelClass):
5✔
1312
                relationship = RelationshipAttribute(
5✔
1313
                    RelationshipType.MANY_TO_MANY,
1314
                    source,
1315
                    target,
1316
                    fk_constraints[1],
1317
                    association_table,
1318
                )
1319
                source.relationships.append(relationship)
5✔
1320

1321
                # Generate the opposite end of the relationship in the target class
1322
                reverse_relationship = None
5✔
1323
                if "nobidi" not in self.options:
5✔
1324
                    reverse_relationship = RelationshipAttribute(
5✔
1325
                        RelationshipType.MANY_TO_MANY,
1326
                        target,
1327
                        source,
1328
                        fk_constraints[0],
1329
                        association_table,
1330
                        relationship,
1331
                    )
1332
                    relationship.backref = reverse_relationship
5✔
1333
                    target.relationships.append(reverse_relationship)
5✔
1334

1335
                # Add a primary/secondary join for self-referential many-to-many
1336
                # relationships
1337
                if source is target:
5✔
1338
                    both_relationships = [relationship]
5✔
1339
                    reverse_flags = [False, True]
5✔
1340
                    if reverse_relationship:
5✔
1341
                        both_relationships.append(reverse_relationship)
5✔
1342

1343
                    for relationship, reverse in zip(both_relationships, reverse_flags):
5✔
1344
                        if (
5✔
1345
                            not relationship.association_table
1346
                            or not relationship.constraint
1347
                        ):
1348
                            continue
×
1349

1350
                        constraints = sorted(
5✔
1351
                            relationship.constraint.table.foreign_key_constraints,
1352
                            key=get_constraint_sort_key,
1353
                            reverse=reverse,
1354
                        )
1355
                        pri_pairs = zip(
5✔
1356
                            get_column_names(constraints[0]), constraints[0].elements
1357
                        )
1358
                        sec_pairs = zip(
5✔
1359
                            get_column_names(constraints[1]), constraints[1].elements
1360
                        )
1361
                        relationship.primaryjoin = [
5✔
1362
                            (
1363
                                relationship.source,
1364
                                elem.column.name,
1365
                                relationship.association_table,
1366
                                col,
1367
                            )
1368
                            for col, elem in pri_pairs
1369
                        ]
1370
                        relationship.secondaryjoin = [
5✔
1371
                            (
1372
                                relationship.target,
1373
                                elem.column.name,
1374
                                relationship.association_table,
1375
                                col,
1376
                            )
1377
                            for col, elem in sec_pairs
1378
                        ]
1379

1380
        return relationships
5✔
1381

1382
    def generate_model_name(self, model: Model, global_names: set[str]) -> None:
5✔
1383
        if isinstance(model, ModelClass):
5✔
1384
            preferred_name = _re_invalid_identifier.sub("_", model.table.name)
5✔
1385
            preferred_name = "".join(
5✔
1386
                part[:1].upper() + part[1:] for part in preferred_name.split("_")
1387
            )
1388
            if "use_inflect" in self.options:
5✔
1389
                singular_name = self.inflect_engine.singular_noun(preferred_name)
5✔
1390
                if singular_name:
5✔
1391
                    preferred_name = singular_name
5✔
1392

1393
            model.name = self.find_free_name(preferred_name, global_names)
5✔
1394

1395
            # Fill in the names for column attributes
1396
            local_names: set[str] = set()
5✔
1397
            for column_attr in model.columns:
5✔
1398
                self.generate_column_attr_name(column_attr, global_names, local_names)
5✔
1399
                local_names.add(column_attr.name)
5✔
1400

1401
            # Fill in the names for relationship attributes
1402
            for relationship in model.relationships:
5✔
1403
                self.generate_relationship_name(relationship, global_names, local_names)
5✔
1404
                local_names.add(relationship.name)
5✔
1405
        else:
1406
            super().generate_model_name(model, global_names)
5✔
1407

1408
    def generate_column_attr_name(
5✔
1409
        self,
1410
        column_attr: ColumnAttribute,
1411
        global_names: set[str],
1412
        local_names: set[str],
1413
    ) -> None:
1414
        column_attr.name = self.find_free_name(
5✔
1415
            column_attr.column.name, global_names, local_names
1416
        )
1417

1418
    def generate_relationship_name(
5✔
1419
        self,
1420
        relationship: RelationshipAttribute,
1421
        global_names: set[str],
1422
        local_names: set[str],
1423
    ) -> None:
1424
        def strip_id_suffix(name: str) -> str:
5✔
1425
            # Strip _id only if at the end or followed by underscore (e.g., "course_id" -> "course", "course_id_1" -> "course_1")
1426
            # But don't strip from "parent_id1" (where id is followed by a digit without underscore)
1427
            return re.sub(r"_id(?=_|$)", "", name)
5✔
1428

1429
        def get_m2m_qualified_name(default_name: str) -> str:
5✔
1430
            """Generate qualified name for many-to-many relationship when multiple junction tables exist."""
1431
            # Check if there are multiple M2M relationships to the same target
1432
            target_m2m_relationships = [
5✔
1433
                r
1434
                for r in relationship.source.relationships
1435
                if r.target is relationship.target
1436
                and r.type == RelationshipType.MANY_TO_MANY
1437
            ]
1438

1439
            # Only use junction-based naming when there are multiple M2M to same target
1440
            if len(target_m2m_relationships) > 1:
5✔
1441
                if relationship.source is relationship.target:
5✔
1442
                    # Self-referential: use FK column name from junction table
1443
                    # (e.g., "parent_id" -> "parent", "child_id" -> "child")
1444
                    if relationship.constraint:
5✔
1445
                        column_names = [c.name for c in relationship.constraint.columns]
5✔
1446
                        if len(column_names) == 1:
5✔
1447
                            fk_qualifier = strip_id_suffix(column_names[0])
5✔
1448
                        else:
1449
                            fk_qualifier = "_".join(
×
1450
                                strip_id_suffix(col_name) for col_name in column_names
1451
                            )
1452
                        return fk_qualifier
5✔
1453
                elif relationship.association_table:
5✔
1454
                    # Normal: use junction table name as qualifier
1455
                    junction_name = relationship.association_table.table.name
5✔
1456
                    fk_qualifier = strip_id_suffix(junction_name)
5✔
1457
                    return f"{relationship.target.table.name}_{fk_qualifier}"
5✔
1458
            else:
1459
                # Single M2M: use simple name from junction table FK column
1460
                # (e.g., "right_id" -> "right" instead of "right_table")
1461
                if relationship.constraint and "noidsuffix" not in self.options:
5✔
1462
                    column_names = [c.name for c in relationship.constraint.columns]
5✔
1463
                    if len(column_names) == 1:
5✔
1464
                        stripped_name = strip_id_suffix(column_names[0])
5✔
1465
                        if stripped_name != column_names[0]:
5✔
1466
                            return stripped_name
5✔
1467

1468
            return default_name
5✔
1469

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

1474
            if len(column_names) == 1:
5✔
1475
                # Single column FK: strip _id suffix if present
1476
                fk_qualifier = strip_id_suffix(column_names[0])
5✔
1477
            else:
1478
                # Multi-column FK: concatenate all column names (strip _id from each)
1479
                fk_qualifier = "_".join(
5✔
1480
                    strip_id_suffix(col_name) for col_name in column_names
1481
                )
1482

1483
            # For self-referential relationships, don't prepend the table name
1484
            if relationship.source is relationship.target:
5✔
1485
                return fk_qualifier
×
1486
            else:
1487
                return f"{relationship.target.table.name}_{fk_qualifier}"
5✔
1488

1489
        def resolve_preferred_name() -> str:
5✔
1490
            resolved_name = relationship.target.table.name
5✔
1491

1492
            # For reverse relationships with multiple FKs to the same table, use the FK
1493
            # column name to create a more descriptive relationship name
1494
            # For M2M relationships with multiple junction tables, use the junction table name
1495
            use_fk_based_naming = "nofknames" not in self.options and (
5✔
1496
                (
1497
                    relationship.constraint
1498
                    and relationship.type
1499
                    in (RelationshipType.ONE_TO_MANY, RelationshipType.ONE_TO_ONE)
1500
                    and relationship.foreign_keys
1501
                )
1502
                or (
1503
                    relationship.type == RelationshipType.MANY_TO_MANY
1504
                    and relationship.association_table
1505
                )
1506
            )
1507

1508
            if use_fk_based_naming:
5✔
1509
                if relationship.type == RelationshipType.MANY_TO_MANY:
5✔
1510
                    resolved_name = get_m2m_qualified_name(resolved_name)
5✔
1511
                elif relationship.constraint:
5✔
1512
                    resolved_name = get_fk_qualified_name(relationship.constraint)
5✔
1513

1514
            # If there's a constraint with a single column that contains "_id", use the
1515
            # stripped version as the relationship name
1516
            elif relationship.constraint and "noidsuffix" not in self.options:
5✔
1517
                is_source = relationship.source.table is relationship.constraint.table
5✔
1518
                if is_source or relationship.type not in (
5✔
1519
                    RelationshipType.ONE_TO_ONE,
1520
                    RelationshipType.ONE_TO_MANY,
1521
                ):
1522
                    column_names = [c.name for c in relationship.constraint.columns]
5✔
1523
                    if len(column_names) == 1:
5✔
1524
                        stripped_name = strip_id_suffix(column_names[0])
5✔
1525
                        # Only use the stripped name if it actually changed (had _id in it)
1526
                        if stripped_name != column_names[0]:
5✔
1527
                            resolved_name = stripped_name
5✔
1528
                    else:
1529
                        # For composite FKs, check if there are multiple FKs to the same target
1530
                        target_relationships = [
5✔
1531
                            r
1532
                            for r in relationship.source.relationships
1533
                            if r.target is relationship.target
1534
                            and r.type == relationship.type
1535
                        ]
1536
                        if len(target_relationships) > 1:
5✔
1537
                            # Multiple FKs to same table - use concatenated column names
1538
                            resolved_name = "_".join(
5✔
1539
                                strip_id_suffix(col_name) for col_name in column_names
1540
                            )
1541

1542
            if "use_inflect" in self.options:
5✔
1543
                inflected_name: str | Literal[False]
1544
                if relationship.type in (
5✔
1545
                    RelationshipType.ONE_TO_MANY,
1546
                    RelationshipType.MANY_TO_MANY,
1547
                ):
1548
                    if not self.inflect_engine.singular_noun(resolved_name):
5✔
1549
                        resolved_name = self.inflect_engine.plural_noun(resolved_name)
5✔
1550
                else:
1551
                    inflected_name = self.inflect_engine.singular_noun(resolved_name)
5✔
1552
                    if inflected_name:
5✔
1553
                        resolved_name = inflected_name
5✔
1554

1555
            return resolved_name
5✔
1556

1557
        if (
5✔
1558
            relationship.type
1559
            in (RelationshipType.ONE_TO_MANY, RelationshipType.ONE_TO_ONE)
1560
            and relationship.source is relationship.target
1561
            and relationship.backref
1562
            and relationship.backref.name
1563
        ):
1564
            preferred_name = relationship.backref.name + "_reverse"
5✔
1565
        else:
1566
            preferred_name = resolve_preferred_name()
5✔
1567

1568
        relationship.name = self.find_free_name(
5✔
1569
            preferred_name, global_names, local_names
1570
        )
1571

1572
    def render_models(self, models: list[Model]) -> str:
5✔
1573
        rendered: list[str] = []
5✔
1574
        for model in models:
5✔
1575
            if isinstance(model, ModelClass):
5✔
1576
                rendered.append(self.render_class(model))
5✔
1577
            else:
1578
                rendered.append(f"{model.name} = {self.render_table(model.table)}")
5✔
1579

1580
        return "\n\n\n".join(rendered)
5✔
1581

1582
    def render_class(self, model: ModelClass) -> str:
5✔
1583
        sections: list[str] = []
5✔
1584

1585
        # Render class variables / special declarations
1586
        class_vars: str = self.render_class_variables(model)
5✔
1587
        if class_vars:
5✔
1588
            sections.append(class_vars)
5✔
1589

1590
        # Render column attributes
1591
        rendered_column_attributes: list[str] = []
5✔
1592
        for nullable in (False, True):
5✔
1593
            for column_attr in model.columns:
5✔
1594
                if column_attr.column.nullable is nullable:
5✔
1595
                    rendered_column_attributes.append(
5✔
1596
                        self.render_column_attribute(column_attr)
1597
                    )
1598

1599
        if rendered_column_attributes:
5✔
1600
            sections.append("\n".join(rendered_column_attributes))
5✔
1601

1602
        # Render relationship attributes
1603
        rendered_relationship_attributes: list[str] = [
5✔
1604
            self.render_relationship(relationship)
1605
            for relationship in model.relationships
1606
        ]
1607

1608
        if rendered_relationship_attributes:
5✔
1609
            sections.append("\n".join(rendered_relationship_attributes))
5✔
1610

1611
        declaration = self.render_class_declaration(model)
5✔
1612
        rendered_sections = "\n\n".join(
5✔
1613
            indent(section, self.indentation) for section in sections
1614
        )
1615
        return f"{declaration}\n{rendered_sections}"
5✔
1616

1617
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1618
        parent_class_name = (
5✔
1619
            model.parent_class.name if model.parent_class else self.base_class_name
1620
        )
1621
        return f"class {model.name}({parent_class_name}):"
5✔
1622

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

1626
        # Render constraints and indexes as __table_args__
1627
        table_args = self.render_table_args(model.table)
5✔
1628
        if table_args:
5✔
1629
            variables.append(f"__table_args__ = {table_args}")
5✔
1630

1631
        return "\n".join(variables)
5✔
1632

1633
    def render_table_args(self, table: Table) -> str:
5✔
1634
        args: list[str] = []
5✔
1635
        kwargs: dict[str, object] = {}
5✔
1636

1637
        # Render constraints
1638
        for constraint in sorted(table.constraints, key=get_constraint_sort_key):
5✔
1639
            if uses_default_name(constraint):
5✔
1640
                if isinstance(constraint, PrimaryKeyConstraint):
5✔
1641
                    continue
5✔
1642
                if (
5✔
1643
                    isinstance(constraint, (ForeignKeyConstraint, UniqueConstraint))
1644
                    and len(constraint.columns) == 1
1645
                ):
1646
                    continue
5✔
1647

1648
            args.append(self.render_constraint(constraint))
5✔
1649

1650
        # Render indexes
1651
        for index in sorted(table.indexes, key=lambda i: cast(str, i.name)):
5✔
1652
            if len(index.columns) > 1 or not uses_default_name(index):
5✔
1653
                args.append(self.render_index(index))
5✔
1654

1655
        if table.schema:
5✔
1656
            kwargs["schema"] = table.schema
5✔
1657

1658
        if table.comment:
5✔
1659
            kwargs["comment"] = table.comment
5✔
1660

1661
        # add info + dialect kwargs for dict context (__table_args__) (opt-in)
1662
        if self.include_dialect_options_and_info:
5✔
1663
            self._add_dialect_kwargs_and_info(table, kwargs, values_for_dict=True)
5✔
1664

1665
        if kwargs:
5✔
1666
            formatted_kwargs = pformat(kwargs)
5✔
1667
            if not args:
5✔
1668
                return formatted_kwargs
5✔
1669
            else:
1670
                args.append(formatted_kwargs)
5✔
1671

1672
        if args:
5✔
1673
            rendered_args = f",\n{self.indentation}".join(args)
5✔
1674
            if len(args) == 1:
5✔
1675
                rendered_args += ","
5✔
1676

1677
            return f"(\n{self.indentation}{rendered_args}\n)"
5✔
1678
        else:
1679
            return ""
5✔
1680

1681
    def render_column_python_type(self, column: Column[Any]) -> str:
5✔
1682
        def get_type_qualifiers() -> tuple[str, TypeEngine[Any], str]:
5✔
1683
            column_type = column.type
5✔
1684
            pre: list[str] = []
5✔
1685
            post_size = 0
5✔
1686
            if column.nullable:
5✔
1687
                self.add_literal_import("typing", "Optional")
5✔
1688
                pre.append("Optional[")
5✔
1689
                post_size += 1
5✔
1690

1691
            if isinstance(column_type, ARRAY):
5✔
1692
                dim = getattr(column_type, "dimensions", None) or 1
5✔
1693
                pre.extend("list[" for _ in range(dim))
5✔
1694
                post_size += dim
5✔
1695

1696
                column_type = column_type.item_type
5✔
1697

1698
            return "".join(pre), column_type, "]" * post_size
5✔
1699

1700
        def render_python_type(column_type: TypeEngine[Any]) -> str:
5✔
1701
            # Check if this is an enum column with a Python enum class
1702
            if isinstance(column_type, Enum):
5✔
1703
                table_name = column.table.name
5✔
1704
                column_name = column.name
5✔
1705
                if (table_name, column_name) in self.enum_classes:
5✔
1706
                    enum_class_name = self.enum_classes[(table_name, column_name)]
5✔
1707
                    return enum_class_name
5✔
1708

1709
            if isinstance(column_type, DOMAIN):
5✔
1710
                column_type = column_type.data_type
5✔
1711

1712
            try:
5✔
1713
                python_type = column_type.python_type
5✔
1714
                python_type_module = python_type.__module__
5✔
1715
                python_type_name = python_type.__name__
5✔
1716
            except NotImplementedError:
5✔
1717
                self.add_literal_import("typing", "Any")
5✔
1718
                return "Any"
5✔
1719

1720
            if python_type_module == "builtins":
5✔
1721
                return python_type_name
5✔
1722

1723
            self.add_module_import(python_type_module)
5✔
1724
            return f"{python_type_module}.{python_type_name}"
5✔
1725

1726
        pre, col_type, post = get_type_qualifiers()
5✔
1727
        column_python_type = f"{pre}{render_python_type(col_type)}{post}"
5✔
1728
        return column_python_type
5✔
1729

1730
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1731
        column = column_attr.column
5✔
1732
        rendered_column = self.render_column(column, column_attr.name != column.name)
5✔
1733
        rendered_column_python_type = self.render_column_python_type(column)
5✔
1734

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

1737
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1738
        kwargs = self.render_relationship_arguments(relationship)
5✔
1739
        annotation = self.render_relationship_annotation(relationship)
5✔
1740
        rendered_relationship = render_callable(
5✔
1741
            "relationship", repr(relationship.target.name), kwargs=kwargs
1742
        )
1743
        return f"{relationship.name}: Mapped[{annotation}] = {rendered_relationship}"
5✔
1744

1745
    def render_relationship_annotation(
5✔
1746
        self, relationship: RelationshipAttribute
1747
    ) -> str:
1748
        match relationship.type:
5✔
1749
            case RelationshipType.ONE_TO_MANY:
5✔
1750
                return f"list[{relationship.target.name!r}]"
5✔
1751
            case RelationshipType.ONE_TO_ONE | RelationshipType.MANY_TO_ONE:
5✔
1752
                if relationship.constraint and any(
5✔
1753
                    col.nullable for col in relationship.constraint.columns
1754
                ):
1755
                    self.add_literal_import("typing", "Optional")
5✔
1756
                    return f"Optional[{relationship.target.name!r}]"
5✔
1757
                else:
1758
                    return f"'{relationship.target.name}'"
5✔
1759
            case RelationshipType.MANY_TO_MANY:
5✔
1760
                return f"list[{relationship.target.name!r}]"
5✔
1761

1762
    def render_relationship_arguments(
5✔
1763
        self, relationship: RelationshipAttribute
1764
    ) -> Mapping[str, Any]:
1765
        def render_column_attrs(column_attrs: list[ColumnAttribute]) -> str:
5✔
1766
            rendered = []
5✔
1767
            render_as_string = False
5✔
1768
            for attr in column_attrs:
5✔
1769
                if not self.explicit_foreign_keys and attr.model is relationship.source:
5✔
1770
                    rendered.append(attr.name)
5✔
1771
                else:
1772
                    rendered.append(f"{attr.model.name}.{attr.name}")
5✔
1773
                    render_as_string = True
5✔
1774

1775
            joined = "[" + ", ".join(rendered) + "]"
5✔
1776
            return repr(joined) if render_as_string else joined
5✔
1777

1778
        def render_foreign_keys(column_attrs: list[ColumnAttribute]) -> str:
5✔
1779
            rendered = []
5✔
1780
            render_as_string = False
5✔
1781
            # Assume that column_attrs are all in relationship.source or none
1782
            for attr in column_attrs:
5✔
1783
                if not self.explicit_foreign_keys and attr.model is relationship.source:
5✔
1784
                    rendered.append(attr.name)
5✔
1785
                else:
1786
                    rendered.append(f"{attr.model.name}.{attr.name}")
5✔
1787
                    render_as_string = True
5✔
1788

1789
            if render_as_string:
5✔
1790
                return "'[" + ", ".join(rendered) + "]'"
5✔
1791
            else:
1792
                return "[" + ", ".join(rendered) + "]"
5✔
1793

1794
        def render_join(terms: list[JoinType]) -> str:
5✔
1795
            rendered_joins = []
5✔
1796
            for source, source_col, target, target_col in terms:
5✔
1797
                rendered = f"lambda: {source.name}.{source_col} == {target.name}."
5✔
1798
                if target.__class__ is Model:
5✔
1799
                    rendered += "c."
5✔
1800

1801
                rendered += str(target_col)
5✔
1802
                rendered_joins.append(rendered)
5✔
1803

1804
            if len(rendered_joins) > 1:
5✔
1805
                rendered = ", ".join(rendered_joins)
×
1806
                return f"and_({rendered})"
×
1807
            else:
1808
                return rendered_joins[0]
5✔
1809

1810
        # Render keyword arguments
1811
        kwargs: dict[str, Any] = {}
5✔
1812
        if relationship.type is RelationshipType.ONE_TO_ONE and relationship.constraint:
5✔
1813
            if relationship.constraint.referred_table is relationship.source.table:
5✔
1814
                kwargs["uselist"] = False
5✔
1815

1816
        # Add the "secondary" keyword for many-to-many relationships
1817
        if relationship.association_table:
5✔
1818
            table_ref = relationship.association_table.table.name
5✔
1819
            if relationship.association_table.schema:
5✔
1820
                table_ref = f"{relationship.association_table.schema}.{table_ref}"
5✔
1821

1822
            kwargs["secondary"] = repr(table_ref)
5✔
1823

1824
        if relationship.remote_side:
5✔
1825
            kwargs["remote_side"] = render_column_attrs(relationship.remote_side)
5✔
1826

1827
        if relationship.foreign_keys:
5✔
1828
            kwargs["foreign_keys"] = render_foreign_keys(relationship.foreign_keys)
5✔
1829

1830
        if relationship.primaryjoin:
5✔
1831
            kwargs["primaryjoin"] = render_join(relationship.primaryjoin)
5✔
1832

1833
        if relationship.secondaryjoin:
5✔
1834
            kwargs["secondaryjoin"] = render_join(relationship.secondaryjoin)
5✔
1835

1836
        if relationship.backref:
5✔
1837
            kwargs["back_populates"] = repr(relationship.backref.name)
5✔
1838

1839
        return kwargs
5✔
1840

1841

1842
class DataclassGenerator(DeclarativeGenerator):
5✔
1843
    def __init__(
5✔
1844
        self,
1845
        metadata: MetaData,
1846
        bind: Connection | Engine,
1847
        options: Sequence[str],
1848
        *,
1849
        indentation: str = "    ",
1850
        base_class_name: str = "Base",
1851
        quote_annotations: bool = False,
1852
        metadata_key: str = "sa",
1853
    ):
1854
        super().__init__(
5✔
1855
            metadata,
1856
            bind,
1857
            options,
1858
            indentation=indentation,
1859
            base_class_name=base_class_name,
1860
        )
1861
        self.metadata_key: str = metadata_key
5✔
1862
        self.quote_annotations: bool = quote_annotations
5✔
1863

1864
    def generate_base(self) -> None:
5✔
1865
        self.base = Base(
5✔
1866
            literal_imports=[
1867
                LiteralImport("sqlalchemy.orm", "DeclarativeBase"),
1868
                LiteralImport("sqlalchemy.orm", "MappedAsDataclass"),
1869
            ],
1870
            declarations=[
1871
                (f"class {self.base_class_name}(MappedAsDataclass, DeclarativeBase):"),
1872
                f"{self.indentation}pass",
1873
            ],
1874
            metadata_ref=f"{self.base_class_name}.metadata",
1875
        )
1876

1877

1878
class SQLModelGenerator(DeclarativeGenerator):
5✔
1879
    def __init__(
5✔
1880
        self,
1881
        metadata: MetaData,
1882
        bind: Connection | Engine,
1883
        options: Sequence[str],
1884
        *,
1885
        indentation: str = "    ",
1886
        base_class_name: str = "SQLModel",
1887
    ):
1888
        super().__init__(
5✔
1889
            metadata,
1890
            bind,
1891
            options,
1892
            indentation=indentation,
1893
            base_class_name=base_class_name,
1894
            explicit_foreign_keys=True,
1895
        )
1896

1897
    @property
5✔
1898
    def views_supported(self) -> bool:
5✔
1899
        return False
×
1900

1901
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
1902
        self.add_import(Column)
5✔
1903
        return render_callable("Column", *args, kwargs=kwargs)
5✔
1904

1905
    def render_table(self, table: Table) -> str:
5✔
1906
        # Hack to fix #465 without breaking backwards compatibility
1907
        self.base.metadata_ref = "SQLModel.metadata"
5✔
1908

1909
        return super().render_table(table)
5✔
1910

1911
    def generate_base(self) -> None:
5✔
1912
        self.base = Base(
5✔
1913
            literal_imports=[],
1914
            declarations=[],
1915
            metadata_ref="SQLModel.metadata",
1916
        )
1917

1918
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1919
        super(DeclarativeGenerator, self).collect_imports(models)
5✔
1920
        if any(isinstance(model, ModelClass) for model in models):
5✔
1921
            self.add_literal_import("sqlmodel", "Field")
5✔
1922

1923
        if models:
5✔
1924
            self.remove_literal_import("sqlalchemy", "MetaData")
5✔
1925
            self.add_literal_import("sqlmodel", "SQLModel")
5✔
1926

1927
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1928
        super(DeclarativeGenerator, self).collect_imports_for_model(model)
5✔
1929
        if isinstance(model, ModelClass):
5✔
1930
            for column_attr in model.columns:
5✔
1931
                if column_attr.column.nullable:
5✔
1932
                    self.add_literal_import("typing", "Optional")
5✔
1933
                    break
5✔
1934

1935
            if model.relationships:
5✔
1936
                self.add_literal_import("sqlmodel", "Relationship")
5✔
1937

1938
    def render_module_variables(self, models: list[Model]) -> str:
5✔
1939
        declarations: list[str] = []
5✔
1940
        if any(not isinstance(model, ModelClass) for model in models):
5✔
1941
            if self.base.table_metadata_declaration is not None:
5✔
1942
                declarations.append(self.base.table_metadata_declaration)
×
1943

1944
        return "\n".join(declarations)
5✔
1945

1946
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1947
        if model.parent_class:
5✔
1948
            parent = model.parent_class.name
×
1949
        else:
1950
            parent = self.base_class_name
5✔
1951

1952
        superclass_part = f"({parent}, table=True)"
5✔
1953
        return f"class {model.name}{superclass_part}:"
5✔
1954

1955
    def render_class_variables(self, model: ModelClass) -> str:
5✔
1956
        variables = []
5✔
1957

1958
        if model.table.name != model.name.lower():
5✔
1959
            variables.append(f"__tablename__ = {model.table.name!r}")
5✔
1960

1961
        # Render constraints and indexes as __table_args__
1962
        table_args = self.render_table_args(model.table)
5✔
1963
        if table_args:
5✔
1964
            variables.append(f"__table_args__ = {table_args}")
5✔
1965

1966
        return "\n".join(variables)
5✔
1967

1968
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1969
        column = column_attr.column
5✔
1970
        rendered_column = self.render_column(column, True)
5✔
1971
        rendered_column_python_type = self.render_column_python_type(column)
5✔
1972

1973
        kwargs: dict[str, Any] = {}
5✔
1974
        if column.nullable:
5✔
1975
            kwargs["default"] = None
5✔
1976
        kwargs["sa_column"] = f"{rendered_column}"
5✔
1977

1978
        rendered_field = render_callable("Field", kwargs=kwargs)
5✔
1979

1980
        return f"{column_attr.name}: {rendered_column_python_type} = {rendered_field}"
5✔
1981

1982
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1983
        kwargs = self.render_relationship_arguments(relationship)
5✔
1984
        annotation = self.render_relationship_annotation(relationship)
5✔
1985

1986
        native_kwargs: dict[str, Any] = {}
5✔
1987
        non_native_kwargs: dict[str, Any] = {}
5✔
1988
        for key, value in kwargs.items():
5✔
1989
            # The following keyword arguments are natively supported in Relationship
1990
            if key in ("back_populates", "cascade_delete", "passive_deletes"):
5✔
1991
                native_kwargs[key] = value
5✔
1992
            else:
1993
                non_native_kwargs[key] = value
5✔
1994

1995
        if non_native_kwargs:
5✔
1996
            native_kwargs["sa_relationship_kwargs"] = (
5✔
1997
                "{"
1998
                + ", ".join(
1999
                    f"{key!r}: {value}" for key, value in non_native_kwargs.items()
2000
                )
2001
                + "}"
2002
            )
2003

2004
        rendered_field = render_callable("Relationship", kwargs=native_kwargs)
5✔
2005
        return f"{relationship.name}: {annotation} = {rendered_field}"
5✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc