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

agronholm / sqlacodegen / 23147926526

16 Mar 2026 02:09PM UTC coverage: 97.879% (+0.02%) from 97.861%
23147926526

Pull #470

github

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

15 of 15 new or added lines in 2 files covered. (100.0%)

23 existing lines in 2 files now uncovered.

1846 of 1886 relevant lines covered (97.88%)

4.89 hits per line

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

97.07
/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
            identity_defaults = {
5✔
528
                p.name: p.default
529
                for p in inspect.signature(Identity).parameters.values()
530
            }
531
            for attr in (
5✔
532
                "always",
533
                "on_null",
534
                "start",
535
                "increment",
536
                "minvalue",
537
                "maxvalue",
538
                "nominvalue",
539
                "nomaxvalue",
540
                "cycle",
541
                "cache",
542
                "order",
543
            ):
544
                value = getattr(identity, attr, None)
5✔
545
                if value is None or value == identity_defaults.get(attr):
5✔
546
                    continue
5✔
547
                if isinstance(value, Decimal):
5✔
548
                    self.add_module_import("decimal")
5✔
549
                    value = f"decimal.Decimal('{value}')"
5✔
550
                identity_kwargs[attr] = value
5✔
551

552
            args.append(render_callable("Identity", kwargs=identity_kwargs))
5✔
553
        elif column.server_default:
5✔
UNCOV
554
            kwargs["server_default"] = repr(column.server_default)
×
555

556
        comment = getattr(column, "comment", None)
5✔
557
        if comment:
5✔
558
            kwargs["comment"] = repr(comment)
5✔
559

560
        # add column info + dialect kwargs for callable context (opt-in)
561
        if self.include_dialect_options_and_info:
5✔
562
            self._add_dialect_kwargs_and_info(column, kwargs, values_for_dict=False)
5✔
563

564
        return self.render_column_callable(is_table, *args, **kwargs)
5✔
565

566
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
567
        if is_table:
5✔
568
            self.add_import(Column)
5✔
569
            return render_callable("Column", *args, kwargs=kwargs)
5✔
570
        else:
571
            return render_callable("mapped_column", *args, kwargs=kwargs)
5✔
572

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

581
        if isinstance(value, TextClause):
5✔
582
            self.add_literal_import("sqlalchemy", "text")
5✔
583
            return render_callable("text", repr(value.text))
5✔
584

585
        return repr(value)
5✔
586

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

605
        inherited_kwargs: dict[str, str] = {}
5✔
606
        for supercls in column_type.__class__.__mro__[1:]:
5✔
607
            if supercls is object:
5✔
608
                break
5✔
609

610
            try:
5✔
611
                super_sig = inspect.signature(supercls.__init__)
5✔
UNCOV
612
            except (TypeError, ValueError):
×
UNCOV
613
                continue
×
614

615
            for super_param in list(super_sig.parameters.values())[1:]:
5✔
616
                if super_param.name.startswith("_"):
5✔
617
                    continue
5✔
618

619
                if super_param.kind in (
5✔
620
                    Parameter.POSITIONAL_ONLY,
621
                    Parameter.VAR_POSITIONAL,
622
                    Parameter.VAR_KEYWORD,
623
                ):
624
                    continue
5✔
625

626
                if super_param.name in seen_param_names:
5✔
627
                    continue
5✔
628

629
                seen_param_names.add(super_param.name)
5✔
630
                value = getattr(column_type, super_param.name, missing)
5✔
631
                if value is missing:
5✔
632
                    continue
5✔
633

634
                default = super_param.default
5✔
635
                if default is not Parameter.empty and value == default:
5✔
636
                    continue
5✔
637

638
                inherited_kwargs[super_param.name] = self._render_column_type_value(
5✔
639
                    value
640
                )
641

642
        return inherited_kwargs
5✔
643

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

657
                if column_type.schema is not None:
5✔
658
                    extra_kwargs += f", schema={column_type.schema!r}"
5✔
659

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

662
        args = []
5✔
663
        kwargs: dict[str, Any] = {}
5✔
664

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

676
                if column_type.item_type.schema is not None:
5✔
677
                    extra_kwargs += f", schema={column_type.item_type.schema!r}"
5✔
678

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

683
                return render_callable("ARRAY", rendered_enum, kwargs=kwargs)
5✔
684

685
        sig = inspect.signature(column_type.__class__.__init__)
5✔
686
        defaults = {param.name: param.default for param in sig.parameters.values()}
5✔
687
        missing = object()
5✔
688
        use_kwargs = False
5✔
689
        seen_param_names: set[str] = set()
5✔
690

691
        for param in list(sig.parameters.values())[1:]:
5✔
692
            # Remove annoyances like _warn_on_bytestring
693
            if param.name.startswith("_"):
5✔
694
                continue
5✔
695
            elif param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD):
5✔
696
                use_kwargs = True
5✔
697
                continue
5✔
698

699
            seen_param_names.add(param.name)
5✔
700
            value = getattr(column_type, param.name, missing)
5✔
701
            default = defaults.get(param.name, missing)
5✔
702
            if value is missing or value == default:
5✔
703
                use_kwargs = True
5✔
704
                continue
5✔
705

706
            rendered_value = self._render_column_type_value(value)
5✔
707
            if use_kwargs:
5✔
708
                kwargs[param.name] = rendered_value
5✔
709
            else:
710
                args.append(rendered_value)
5✔
711

712
        kwargs.update(
5✔
713
            self._collect_inherited_init_kwargs(
714
                column_type, sig, seen_param_names, missing
715
            )
716
        )
717

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

730
        # These arguments cannot be autodetected from the Enum initializer
731
        if isinstance(column_type, Enum):
5✔
732
            for colname in "name", "schema":
5✔
733
                if (value := getattr(column_type, colname)) is not None:
5✔
734
                    kwargs[colname] = repr(value)
5✔
735

736
        if isinstance(column_type, (JSONB, JSON)):
5✔
737
            # Remove astext_type if it's the default
738
            if (
5✔
739
                isinstance(column_type.astext_type, Text)
740
                and column_type.astext_type.length is None
741
            ):
742
                del kwargs["astext_type"]
5✔
743

744
        if args or kwargs:
5✔
745
            return render_callable(column_type.__class__.__name__, *args, kwargs=kwargs)
5✔
746
        else:
747
            return column_type.__class__.__name__
5✔
748

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

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

780
        if isinstance(constraint, Constraint) and not uses_default_name(constraint):
5✔
781
            kwargs["name"] = repr(constraint.name)
5✔
782

783
        return render_callable(constraint.__class__.__name__, *args, kwargs=kwargs)
5✔
784

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

797
        dialect_keys: list[str]
798
        try:
5✔
799
            dialect_keys = sorted(getattr(obj, "dialect_kwargs"))
5✔
UNCOV
800
        except Exception:
×
UNCOV
801
            return
×
802

803
        dialect_kwargs = getattr(obj, "dialect_kwargs", {})
5✔
804
        for key in dialect_keys:
5✔
805
            try:
5✔
806
                value = dialect_kwargs[key]
5✔
UNCOV
807
            except Exception:
×
UNCOV
808
                continue
×
809

810
            if isinstance(value, list | dict) and not value:
5✔
811
                continue
5✔
812

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

833
    def should_ignore_table(self, table: Table) -> bool:
5✔
834
        # Support for Alembic and sqlalchemy-migrate -- never expose the schema version
835
        # tables
836
        return table.name in ("alembic_version", "migrate_version")
5✔
837

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

852
        original = name
5✔
853
        for i in count():
5✔
854
            if name not in global_names and name not in local_names:
5✔
855
                break
5✔
856

857
            name = original + (str(i) if i else "_")
5✔
858

859
        return name
5✔
860

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

865
    def _create_enum_class(
5✔
866
        self, table_name: str, column_name: str, values: list[str]
867
    ) -> str:
868
        """
869
        Create a Python enum class name and register it.
870

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

881
        # Ensure uniqueness
882
        enum_class_name = base_name
5✔
883
        for counter in count(1):
5✔
884
            if enum_class_name not in self.enum_values:
5✔
885
                break
5✔
886

887
            # Check if it's the same enum (same values)
888
            if self.enum_values[enum_class_name] == values:
5✔
889
                # Reuse existing enum class
890
                return enum_class_name
5✔
891

892
            enum_class_name = f"{base_name}{counter}"
5✔
893

894
        # Register the new enum class
895
        self.enum_values[enum_class_name] = values
5✔
896
        return enum_class_name
5✔
897

898
    def render_enum_classes(self) -> str:
5✔
899
        """Render Python enum class definitions."""
900
        if not self.enum_values:
5✔
901
            return ""
5✔
902

903
        self.add_module_import("enum")
5✔
904

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

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

929
            enum_def = f"class {enum_class_name}(str, enum.Enum):\n" + "\n".join(
5✔
930
                members
931
            )
932
            enum_defs.append(enum_def)
5✔
933

934
        return "\n\n\n".join(enum_defs)
5✔
935

936
    def fix_column_types(self, table: Table) -> None:
5✔
937
        """Adjust the reflected column types."""
938

939
        def fix_enum_column(col_name: str, enum_type: Enum) -> None:
5✔
940
            if (table.name, col_name) in self.enum_classes:
5✔
941
                return
5✔
942

943
            if enum_type.name:
5✔
944
                existing_class = None
5✔
945
                for (_, _), cls in self.enum_classes.items():
5✔
946
                    if cls == self._enum_name_to_class_name(enum_type.name):
5✔
947
                        existing_class = cls
5✔
948
                        break
5✔
949

950
                if existing_class:
5✔
951
                    enum_class_name = existing_class
5✔
952
                else:
953
                    enum_class_name = self._enum_name_to_class_name(enum_type.name)
5✔
954
                    if enum_class_name not in self.enum_values:
5✔
955
                        self.enum_values[enum_class_name] = list(enum_type.enums)
5✔
956
            else:
957
                enum_class_name = self._create_enum_class(
5✔
958
                    table.name, col_name, list(enum_type.enums)
959
                )
960

961
            self.enum_classes[(table.name, col_name)] = enum_class_name
5✔
962

963
        # Detect check constraints for boolean and enum columns
964
        for constraint in table.constraints.copy():
5✔
965
            if isinstance(constraint, CheckConstraint):
5✔
966
                sqltext = get_compiled_expression(constraint.sqltext, self.bind)
5✔
967

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

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

999
        for column in table.c:
5✔
1000
            # Handle native database Enum types (e.g., PostgreSQL ENUM)
1001
            if (
5✔
1002
                "nonativeenums" not in self.options
1003
                and isinstance(column.type, Enum)
1004
                and column.type.enums
1005
            ):
1006
                fix_enum_column(column.name, column.type)
5✔
1007

1008
            # Handle ARRAY columns with Enum item types (e.g., PostgreSQL ARRAY(ENUM))
1009
            elif (
5✔
1010
                "nonativeenums" not in self.options
1011
                and isinstance(column.type, ARRAY)
1012
                and isinstance(column.type.item_type, Enum)
1013
                and column.type.item_type.enums
1014
            ):
1015
                fix_enum_column(column.name, column.type.item_type)
5✔
1016

1017
            if not self.keep_dialect_types:
5✔
1018
                try:
5✔
1019
                    column.type = self.get_adapted_type(column.type)
5✔
1020
                except CompileError:
5✔
1021
                    continue
5✔
1022

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

1036
                        column.server_default = None
5✔
1037

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

1048
                # Hack to fix adaptation of the Enum class which is broken since
1049
                # SQLAlchemy 1.2
1050
                kw = {}
5✔
1051
                if supercls is Enum:
5✔
1052
                    kw["name"] = coltype.name
5✔
1053
                    if coltype.schema:
5✔
1054
                        kw["schema"] = coltype.schema
5✔
1055

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

1070
                try:
5✔
1071
                    new_coltype = coltype.adapt(supercls)
5✔
1072
                except TypeError:
5✔
1073
                    # If the adaptation fails, don't try again
1074
                    break
5✔
1075

1076
                for key, value in kw.items():
5✔
1077
                    setattr(new_coltype, key, value)
5✔
1078

1079
                if isinstance(coltype, ARRAY):
5✔
1080
                    new_coltype.item_type = self.get_adapted_type(new_coltype.item_type)
5✔
1081

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

1091
                # Stop on the first valid non-uppercase column type class
1092
                coltype = new_coltype
5✔
1093
                if supercls.__name__ != supercls.__name__.upper():
5✔
1094
                    break
5✔
1095

1096
        return coltype
5✔
1097

1098

1099
class DeclarativeGenerator(TablesGenerator):
5✔
1100
    valid_options: ClassVar[set[str]] = TablesGenerator.valid_options | {
5✔
1101
        "use_inflect",
1102
        "nojoined",
1103
        "nobidi",
1104
        "noidsuffix",
1105
        "nofknames",
1106
    }
1107

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

1123
    def generate_base(self) -> None:
5✔
1124
        self.base = Base(
5✔
1125
            literal_imports=[LiteralImport("sqlalchemy.orm", "DeclarativeBase")],
1126
            declarations=[
1127
                f"class {self.base_class_name}(DeclarativeBase):",
1128
                f"{self.indentation}pass",
1129
            ],
1130
            metadata_ref=f"{self.base_class_name}.metadata",
1131
        )
1132

1133
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1134
        super().collect_imports(models)
5✔
1135
        if any(isinstance(model, ModelClass) for model in models):
5✔
1136
            self.add_literal_import("sqlalchemy.orm", "Mapped")
5✔
1137
            self.add_literal_import("sqlalchemy.orm", "mapped_column")
5✔
1138

1139
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1140
        super().collect_imports_for_model(model)
5✔
1141
        if isinstance(model, ModelClass):
5✔
1142
            if model.relationships:
5✔
1143
                self.add_literal_import("sqlalchemy.orm", "relationship")
5✔
1144

1145
    def generate_models(self) -> list[Model]:
5✔
1146
        models_by_table_name: dict[str, Model] = {}
5✔
1147

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

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

1167
            # Only form model classes for tables that have a primary key and are not
1168
            # association tables
1169
            if not table.primary_key:
5✔
1170
                models_by_table_name[qualified_name] = Model(table)
5✔
1171
            else:
1172
                model = ModelClass(table)
5✔
1173
                models_by_table_name[qualified_name] = model
5✔
1174

1175
                # Fill in the columns
1176
                for column in table.c:
5✔
1177
                    column_attr = ColumnAttribute(model, column)
5✔
1178
                    model.columns.append(column_attr)
5✔
1179

1180
        # Add relationships
1181
        for model in models_by_table_name.values():
5✔
1182
            if isinstance(model, ModelClass):
5✔
1183
                self.generate_relationships(
5✔
1184
                    model, models_by_table_name, links[model.table.name]
1185
                )
1186

1187
        # Nest inherited classes in their superclasses to ensure proper ordering
1188
        if "nojoined" not in self.options:
5✔
1189
            for model in list(models_by_table_name.values()):
5✔
1190
                if not isinstance(model, ModelClass):
5✔
1191
                    continue
5✔
1192

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

1203
        # Change base if we only have tables
1204
        if not any(
5✔
1205
            isinstance(model, ModelClass) for model in models_by_table_name.values()
1206
        ):
1207
            super().generate_base()
5✔
1208

1209
        # Collect the imports
1210
        self.collect_imports(models_by_table_name.values())
5✔
1211

1212
        # Rename models and their attributes that conflict with imports or other
1213
        # attributes
1214
        global_names = {
5✔
1215
            name for namespace in self.imports.values() for name in namespace
1216
        }
1217
        for model in models_by_table_name.values():
5✔
1218
            self.generate_model_name(model, global_names)
5✔
1219
            global_names.add(model.name)
5✔
1220

1221
        return list(models_by_table_name.values())
5✔
1222

1223
    def generate_relationships(
5✔
1224
        self,
1225
        source: ModelClass,
1226
        models_by_table_name: dict[str, Model],
1227
        association_tables: list[Model],
1228
    ) -> list[RelationshipAttribute]:
1229
        relationships: list[RelationshipAttribute] = []
5✔
1230
        reverse_relationship: RelationshipAttribute | None
1231

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

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

1262
                relationship = RelationshipAttribute(r_type, source, target, constraint)
5✔
1263
                source.relationships.append(relationship)
5✔
1264

1265
                # For self referential relationships, remote_side needs to be set
1266
                if source is target:
5✔
1267
                    relationship.remote_side = [
5✔
1268
                        source.get_column_attribute(col.name)
1269
                        for col in constraint.referred_table.primary_key
1270
                    ]
1271

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

1284
                # Generate the opposite end of the relationship in the target class
1285
                if "nobidi" not in self.options:
5✔
1286
                    if r_type is RelationshipType.MANY_TO_ONE:
5✔
1287
                        r_type = RelationshipType.ONE_TO_MANY
5✔
1288

1289
                    reverse_relationship = RelationshipAttribute(
5✔
1290
                        r_type,
1291
                        target,
1292
                        source,
1293
                        constraint,
1294
                        foreign_keys=relationship.foreign_keys,
1295
                        backref=relationship,
1296
                    )
1297
                    relationship.backref = reverse_relationship
5✔
1298
                    target.relationships.append(reverse_relationship)
5✔
1299

1300
                    # For self referential relationships, remote_side needs to be set
1301
                    if source is target:
5✔
1302
                        reverse_relationship.remote_side = [
5✔
1303
                            source.get_column_attribute(colname)
1304
                            for colname in constraint.column_keys
1305
                        ]
1306

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

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

1340
                # Add a primary/secondary join for self-referential many-to-many
1341
                # relationships
1342
                if source is target:
5✔
1343
                    both_relationships = [relationship]
5✔
1344
                    reverse_flags = [False, True]
5✔
1345
                    if reverse_relationship:
5✔
1346
                        both_relationships.append(reverse_relationship)
5✔
1347

1348
                    for relationship, reverse in zip(both_relationships, reverse_flags):
5✔
1349
                        if (
5✔
1350
                            not relationship.association_table
1351
                            or not relationship.constraint
1352
                        ):
UNCOV
1353
                            continue
×
1354

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

1385
        return relationships
5✔
1386

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

1398
            model.name = self.find_free_name(preferred_name, global_names)
5✔
1399

1400
            # Fill in the names for column attributes
1401
            local_names: set[str] = set()
5✔
1402
            for column_attr in model.columns:
5✔
1403
                self.generate_column_attr_name(column_attr, global_names, local_names)
5✔
1404
                local_names.add(column_attr.name)
5✔
1405

1406
            # Fill in the names for relationship attributes
1407
            for relationship in model.relationships:
5✔
1408
                self.generate_relationship_name(relationship, global_names, local_names)
5✔
1409
                local_names.add(relationship.name)
5✔
1410
        else:
1411
            super().generate_model_name(model, global_names)
5✔
1412

1413
    def generate_column_attr_name(
5✔
1414
        self,
1415
        column_attr: ColumnAttribute,
1416
        global_names: set[str],
1417
        local_names: set[str],
1418
    ) -> None:
1419
        column_attr.name = self.find_free_name(
5✔
1420
            column_attr.column.name, global_names, local_names
1421
        )
1422

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

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

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

1473
            return default_name
5✔
1474

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

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

1488
            # For self-referential relationships, don't prepend the table name
1489
            if relationship.source is relationship.target:
5✔
UNCOV
1490
                return fk_qualifier
×
1491
            else:
1492
                return f"{relationship.target.table.name}_{fk_qualifier}"
5✔
1493

1494
        def resolve_preferred_name() -> str:
5✔
1495
            resolved_name = relationship.target.table.name
5✔
1496

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

1513
            if use_fk_based_naming:
5✔
1514
                if relationship.type == RelationshipType.MANY_TO_MANY:
5✔
1515
                    resolved_name = get_m2m_qualified_name(resolved_name)
5✔
1516
                elif relationship.constraint:
5✔
1517
                    resolved_name = get_fk_qualified_name(relationship.constraint)
5✔
1518

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

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

1560
            return resolved_name
5✔
1561

1562
        if (
5✔
1563
            relationship.type
1564
            in (RelationshipType.ONE_TO_MANY, RelationshipType.ONE_TO_ONE)
1565
            and relationship.source is relationship.target
1566
            and relationship.backref
1567
            and relationship.backref.name
1568
        ):
1569
            preferred_name = relationship.backref.name + "_reverse"
5✔
1570
        else:
1571
            preferred_name = resolve_preferred_name()
5✔
1572

1573
        relationship.name = self.find_free_name(
5✔
1574
            preferred_name, global_names, local_names
1575
        )
1576

1577
    def render_models(self, models: list[Model]) -> str:
5✔
1578
        rendered: list[str] = []
5✔
1579
        for model in models:
5✔
1580
            if isinstance(model, ModelClass):
5✔
1581
                rendered.append(self.render_class(model))
5✔
1582
            else:
1583
                rendered.append(f"{model.name} = {self.render_table(model.table)}")
5✔
1584

1585
        return "\n\n\n".join(rendered)
5✔
1586

1587
    def render_class(self, model: ModelClass) -> str:
5✔
1588
        sections: list[str] = []
5✔
1589

1590
        # Render class variables / special declarations
1591
        class_vars: str = self.render_class_variables(model)
5✔
1592
        if class_vars:
5✔
1593
            sections.append(class_vars)
5✔
1594

1595
        # Render column attributes
1596
        rendered_column_attributes: list[str] = []
5✔
1597
        for nullable in (False, True):
5✔
1598
            for column_attr in model.columns:
5✔
1599
                if column_attr.column.nullable is nullable:
5✔
1600
                    rendered_column_attributes.append(
5✔
1601
                        self.render_column_attribute(column_attr)
1602
                    )
1603

1604
        if rendered_column_attributes:
5✔
1605
            sections.append("\n".join(rendered_column_attributes))
5✔
1606

1607
        # Render relationship attributes
1608
        rendered_relationship_attributes: list[str] = [
5✔
1609
            self.render_relationship(relationship)
1610
            for relationship in model.relationships
1611
        ]
1612

1613
        if rendered_relationship_attributes:
5✔
1614
            sections.append("\n".join(rendered_relationship_attributes))
5✔
1615

1616
        declaration = self.render_class_declaration(model)
5✔
1617
        rendered_sections = "\n\n".join(
5✔
1618
            indent(section, self.indentation) for section in sections
1619
        )
1620
        return f"{declaration}\n{rendered_sections}"
5✔
1621

1622
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1623
        parent_class_name = (
5✔
1624
            model.parent_class.name if model.parent_class else self.base_class_name
1625
        )
1626
        return f"class {model.name}({parent_class_name}):"
5✔
1627

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

1631
        # Render constraints and indexes as __table_args__
1632
        table_args = self.render_table_args(model.table)
5✔
1633
        if table_args:
5✔
1634
            variables.append(f"__table_args__ = {table_args}")
5✔
1635

1636
        return "\n".join(variables)
5✔
1637

1638
    def render_table_args(self, table: Table) -> str:
5✔
1639
        args: list[str] = []
5✔
1640
        kwargs: dict[str, object] = {}
5✔
1641

1642
        # Render constraints
1643
        for constraint in sorted(table.constraints, key=get_constraint_sort_key):
5✔
1644
            if uses_default_name(constraint):
5✔
1645
                if isinstance(constraint, PrimaryKeyConstraint):
5✔
1646
                    continue
5✔
1647
                if (
5✔
1648
                    isinstance(constraint, (ForeignKeyConstraint, UniqueConstraint))
1649
                    and len(constraint.columns) == 1
1650
                ):
1651
                    continue
5✔
1652

1653
            args.append(self.render_constraint(constraint))
5✔
1654

1655
        # Render indexes
1656
        for index in sorted(table.indexes, key=lambda i: cast(str, i.name)):
5✔
1657
            if len(index.columns) > 1 or not uses_default_name(index):
5✔
1658
                args.append(self.render_index(index))
5✔
1659

1660
        if table.schema:
5✔
1661
            kwargs["schema"] = table.schema
5✔
1662

1663
        if table.comment:
5✔
1664
            kwargs["comment"] = table.comment
5✔
1665

1666
        # add info + dialect kwargs for dict context (__table_args__) (opt-in)
1667
        if self.include_dialect_options_and_info:
5✔
1668
            self._add_dialect_kwargs_and_info(table, kwargs, values_for_dict=True)
5✔
1669

1670
        if kwargs:
5✔
1671
            formatted_kwargs = pformat(kwargs)
5✔
1672
            if not args:
5✔
1673
                return formatted_kwargs
5✔
1674
            else:
1675
                args.append(formatted_kwargs)
5✔
1676

1677
        if args:
5✔
1678
            rendered_args = f",\n{self.indentation}".join(args)
5✔
1679
            if len(args) == 1:
5✔
1680
                rendered_args += ","
5✔
1681

1682
            return f"(\n{self.indentation}{rendered_args}\n)"
5✔
1683
        else:
1684
            return ""
5✔
1685

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

1696
            if isinstance(column_type, ARRAY):
5✔
1697
                dim = getattr(column_type, "dimensions", None) or 1
5✔
1698
                pre.extend("list[" for _ in range(dim))
5✔
1699
                post_size += dim
5✔
1700

1701
                column_type = column_type.item_type
5✔
1702

1703
            return "".join(pre), column_type, "]" * post_size
5✔
1704

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

1714
            if isinstance(column_type, DOMAIN):
5✔
1715
                column_type = column_type.data_type
5✔
1716

1717
            try:
5✔
1718
                python_type = column_type.python_type
5✔
1719
                python_type_module = python_type.__module__
5✔
1720
                python_type_name = python_type.__name__
5✔
1721
            except NotImplementedError:
5✔
1722
                self.add_literal_import("typing", "Any")
5✔
1723
                return "Any"
5✔
1724

1725
            if python_type_module == "builtins":
5✔
1726
                return python_type_name
5✔
1727

1728
            self.add_module_import(python_type_module)
5✔
1729
            return f"{python_type_module}.{python_type_name}"
5✔
1730

1731
        pre, col_type, post = get_type_qualifiers()
5✔
1732
        column_python_type = f"{pre}{render_python_type(col_type)}{post}"
5✔
1733
        return column_python_type
5✔
1734

1735
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1736
        column = column_attr.column
5✔
1737
        rendered_column = self.render_column(column, column_attr.name != column.name)
5✔
1738
        rendered_column_python_type = self.render_column_python_type(column)
5✔
1739

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

1742
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1743
        kwargs = self.render_relationship_arguments(relationship)
5✔
1744
        annotation = self.render_relationship_annotation(relationship)
5✔
1745
        rendered_relationship = render_callable(
5✔
1746
            "relationship", repr(relationship.target.name), kwargs=kwargs
1747
        )
1748
        return f"{relationship.name}: Mapped[{annotation}] = {rendered_relationship}"
5✔
1749

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

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

1780
            joined = "[" + ", ".join(rendered) + "]"
5✔
1781
            return repr(joined) if render_as_string else joined
5✔
1782

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

1794
            if render_as_string:
5✔
1795
                return "'[" + ", ".join(rendered) + "]'"
5✔
1796
            else:
1797
                return "[" + ", ".join(rendered) + "]"
5✔
1798

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

1806
                rendered += str(target_col)
5✔
1807
                rendered_joins.append(rendered)
5✔
1808

1809
            if len(rendered_joins) > 1:
5✔
UNCOV
1810
                rendered = ", ".join(rendered_joins)
×
UNCOV
1811
                return f"and_({rendered})"
×
1812
            else:
1813
                return rendered_joins[0]
5✔
1814

1815
        # Render keyword arguments
1816
        kwargs: dict[str, Any] = {}
5✔
1817
        if relationship.type is RelationshipType.ONE_TO_ONE and relationship.constraint:
5✔
1818
            if relationship.constraint.referred_table is relationship.source.table:
5✔
1819
                kwargs["uselist"] = False
5✔
1820

1821
        # Add the "secondary" keyword for many-to-many relationships
1822
        if relationship.association_table:
5✔
1823
            table_ref = relationship.association_table.table.name
5✔
1824
            if relationship.association_table.schema:
5✔
1825
                table_ref = f"{relationship.association_table.schema}.{table_ref}"
5✔
1826

1827
            kwargs["secondary"] = repr(table_ref)
5✔
1828

1829
        if relationship.remote_side:
5✔
1830
            kwargs["remote_side"] = render_column_attrs(relationship.remote_side)
5✔
1831

1832
        if relationship.foreign_keys:
5✔
1833
            kwargs["foreign_keys"] = render_foreign_keys(relationship.foreign_keys)
5✔
1834

1835
        if relationship.primaryjoin:
5✔
1836
            kwargs["primaryjoin"] = render_join(relationship.primaryjoin)
5✔
1837

1838
        if relationship.secondaryjoin:
5✔
1839
            kwargs["secondaryjoin"] = render_join(relationship.secondaryjoin)
5✔
1840

1841
        if relationship.backref:
5✔
1842
            kwargs["back_populates"] = repr(relationship.backref.name)
5✔
1843

1844
        return kwargs
5✔
1845

1846

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

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

1882

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

1902
    @property
5✔
1903
    def views_supported(self) -> bool:
5✔
UNCOV
1904
        return False
×
1905

1906
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
1907
        self.add_import(Column)
5✔
1908
        return render_callable("Column", *args, kwargs=kwargs)
5✔
1909

1910
    def render_table(self, table: Table) -> str:
5✔
1911
        # Hack to fix #465 without breaking backwards compatibility
1912
        self.base.metadata_ref = "SQLModel.metadata"
5✔
1913

1914
        return super().render_table(table)
5✔
1915

1916
    def generate_base(self) -> None:
5✔
1917
        self.base = Base(
5✔
1918
            literal_imports=[],
1919
            declarations=[],
1920
            metadata_ref="SQLModel.metadata",
1921
        )
1922

1923
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1924
        super(DeclarativeGenerator, self).collect_imports(models)
5✔
1925
        if any(isinstance(model, ModelClass) for model in models):
5✔
1926
            self.add_literal_import("sqlmodel", "Field")
5✔
1927

1928
        if models:
5✔
1929
            self.remove_literal_import("sqlalchemy", "MetaData")
5✔
1930
            self.add_literal_import("sqlmodel", "SQLModel")
5✔
1931

1932
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1933
        super(DeclarativeGenerator, self).collect_imports_for_model(model)
5✔
1934
        if isinstance(model, ModelClass):
5✔
1935
            for column_attr in model.columns:
5✔
1936
                if column_attr.column.nullable:
5✔
1937
                    self.add_literal_import("typing", "Optional")
5✔
1938
                    break
5✔
1939

1940
            if model.relationships:
5✔
1941
                self.add_literal_import("sqlmodel", "Relationship")
5✔
1942

1943
    def render_module_variables(self, models: list[Model]) -> str:
5✔
1944
        declarations: list[str] = []
5✔
1945
        if any(not isinstance(model, ModelClass) for model in models):
5✔
1946
            if self.base.table_metadata_declaration is not None:
5✔
UNCOV
1947
                declarations.append(self.base.table_metadata_declaration)
×
1948

1949
        return "\n".join(declarations)
5✔
1950

1951
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1952
        if model.parent_class:
5✔
UNCOV
1953
            parent = model.parent_class.name
×
1954
        else:
1955
            parent = self.base_class_name
5✔
1956

1957
        superclass_part = f"({parent}, table=True)"
5✔
1958
        return f"class {model.name}{superclass_part}:"
5✔
1959

1960
    def render_class_variables(self, model: ModelClass) -> str:
5✔
1961
        variables = []
5✔
1962

1963
        if model.table.name != model.name.lower():
5✔
1964
            variables.append(f"__tablename__ = {model.table.name!r}")
5✔
1965

1966
        # Render constraints and indexes as __table_args__
1967
        table_args = self.render_table_args(model.table)
5✔
1968
        if table_args:
5✔
1969
            variables.append(f"__table_args__ = {table_args}")
5✔
1970

1971
        return "\n".join(variables)
5✔
1972

1973
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1974
        column = column_attr.column
5✔
1975
        rendered_column = self.render_column(column, True)
5✔
1976
        rendered_column_python_type = self.render_column_python_type(column)
5✔
1977

1978
        kwargs: dict[str, Any] = {}
5✔
1979
        if column.nullable:
5✔
1980
            kwargs["default"] = None
5✔
1981
        kwargs["sa_column"] = f"{rendered_column}"
5✔
1982

1983
        rendered_field = render_callable("Field", kwargs=kwargs)
5✔
1984

1985
        return f"{column_attr.name}: {rendered_column_python_type} = {rendered_field}"
5✔
1986

1987
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1988
        kwargs = self.render_relationship_arguments(relationship)
5✔
1989
        annotation = self.render_relationship_annotation(relationship)
5✔
1990

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

2000
        if non_native_kwargs:
5✔
2001
            native_kwargs["sa_relationship_kwargs"] = (
5✔
2002
                "{"
2003
                + ", ".join(
2004
                    f"{key!r}: {value}" for key, value in non_native_kwargs.items()
2005
                )
2006
                + "}"
2007
            )
2008

2009
        rendered_field = render_callable("Relationship", kwargs=native_kwargs)
5✔
2010
        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