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

agronholm / sqlacodegen / 23157148095

16 Mar 2026 05:29PM UTC coverage: 97.82% (-0.04%) from 97.861%
23157148095

Pull #470

github

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

11 of 12 new or added lines in 1 file covered. (91.67%)

21 existing lines in 2 files now uncovered.

1840 of 1881 relevant lines covered (97.82%)

4.89 hits per line

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

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

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

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

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

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

75

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

81

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

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

92

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

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

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

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

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

120

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

367
        return models
5✔
368

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

548
                if isinstance(value, Decimal):
5✔
NEW
549
                    value = int(value)
×
550

551
                identity_kwargs[attr] = value
5✔
552

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

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

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

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

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

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

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

586
        return repr(value)
5✔
587

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

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

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

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

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

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

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

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

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

643
        return inherited_kwargs
5✔
644

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

860
        return name
5✔
861

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1037
                        column.server_default = None
5✔
1038

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

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

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

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

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

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

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

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

1097
        return coltype
5✔
1098

1099

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1386
        return relationships
5✔
1387

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

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

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

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

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

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

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

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

1474
            return default_name
5✔
1475

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

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

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

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

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

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

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

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

1561
            return resolved_name
5✔
1562

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1702
                column_type = column_type.item_type
5✔
1703

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1845
        return kwargs
5✔
1846

1847

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

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

1883

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

© 2026 Coveralls, Inc