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

agronholm / sqlacodegen / 23148155938

16 Mar 2026 02:14PM UTC coverage: 97.82% (-0.04%) from 97.861%
23148155938

Pull #470

github

web-flow
Merge 06def1035 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
                if isinstance(value, Decimal):
5✔
NEW
548
                    value = int(value)
×
549
                identity_kwargs[attr] = value
5✔
550

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

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

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

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

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

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

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

584
        return repr(value)
5✔
585

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

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

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

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

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

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

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

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

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

641
        return inherited_kwargs
5✔
642

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

858
        return name
5✔
859

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1035
                        column.server_default = None
5✔
1036

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

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

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

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

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

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

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

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

1095
        return coltype
5✔
1096

1097

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1384
        return relationships
5✔
1385

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

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

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

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

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

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

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

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

1472
            return default_name
5✔
1473

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

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

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

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

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

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

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

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

1559
            return resolved_name
5✔
1560

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1700
                column_type = column_type.item_type
5✔
1701

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1843
        return kwargs
5✔
1844

1845

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

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

1881

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

© 2026 Coveralls, Inc