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

agronholm / sqlacodegen / 27067649426

06 Jun 2026 04:28PM UTC coverage: 97.794% (-0.05%) from 97.839%
27067649426

Pull #480

github

web-flow
Merge ff9f661c2 into 42b3b39a3
Pull Request #480: Preserve dialect-specific ARRAY types instead of adapting to generic ARRAY

5 of 5 new or added lines in 1 file covered. (100.0%)

1 existing line in 1 file now uncovered.

1862 of 1904 relevant lines covered (97.79%)

4.89 hits per line

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

96.91
/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
        is_autoincrement = (
5✔
475
            isinstance(column.autoincrement, bool) and column.autoincrement
476
        )
477
        has_index = any(
5✔
478
            set(i.columns) == {column} and uses_default_name(i)
479
            for i in column.table.indexes
480
        )
481

482
        if show_name:
5✔
483
            args.append(repr(column.name))
5✔
484

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

490
        for fk in dedicated_fks:
5✔
491
            args.append(self.render_constraint(fk))
5✔
492

493
        if column.default:
5✔
494
            args.append(repr(column.default))
5✔
495

496
        if column.key != column.name:
5✔
497
            kwargs["key"] = column.key
×
498
        if is_primary:
5✔
499
            kwargs["primary_key"] = True
5✔
500
        if is_autoincrement and is_primary:
5✔
501
            kwargs["autoincrement"] = True
5✔
502
        if not column.nullable and not column.primary_key:
5✔
503
            kwargs["nullable"] = False
5✔
504
        if column.nullable and is_part_of_composite_pk:
5✔
505
            kwargs["nullable"] = True
5✔
506

507
        if is_unique:
5✔
508
            column.unique = True
5✔
509
            kwargs["unique"] = True
5✔
510
        if has_index:
5✔
511
            column.index = True
5✔
512
            kwarg.append("index")
5✔
513
            kwargs["index"] = True
5✔
514

515
        if isinstance(column.server_default, DefaultClause):
5✔
516
            kwargs["server_default"] = render_callable(
5✔
517
                "text", repr(cast(TextClause, column.server_default.arg).text)
518
            )
519
        elif isinstance(column.server_default, Computed):
5✔
520
            expression = str(column.server_default.sqltext)
5✔
521

522
            computed_kwargs = {}
5✔
523
            if column.server_default.persisted is not None:
5✔
524
                computed_kwargs["persisted"] = column.server_default.persisted
5✔
525

526
            args.append(
5✔
527
                render_callable("Computed", repr(expression), kwargs=computed_kwargs)
528
            )
529
        elif isinstance(column.server_default, Identity):
5✔
530
            identity = column.server_default
5✔
531
            identity_kwargs: dict[str, Any] = {}
5✔
532

533
            for name, param in inspect.signature(Identity).parameters.items():
5✔
534
                if name == "self" or param.kind in (
5✔
535
                    Parameter.VAR_POSITIONAL,
536
                    Parameter.VAR_KEYWORD,
537
                ):
538
                    continue
×
539

540
                value = getattr(identity, name, None)
5✔
541
                if value is None:
5✔
542
                    continue
5✔
543

544
                if isinstance(value, Decimal):
5✔
545
                    value = int(value)
5✔
546

547
                if param.default is not Parameter.empty and value == param.default:
5✔
548
                    continue
5✔
549

550
                identity_kwargs[name] = value
5✔
551

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

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

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

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

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

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

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

585
        return repr(value)
5✔
586

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

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

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

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

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

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

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

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

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

642
        return inherited_kwargs
5✔
643

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

859
        return name
5✔
860

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1036
                        column.server_default = None
5✔
1037

1038
    def get_adapted_type(self, coltype: Any) -> Any:
5✔
1039
        # The generic ``sqlalchemy.ARRAY`` does not implement operators such as
1040
        # ``.contains()`` that dialect-specific ARRAY types (notably
1041
        # ``sqlalchemy.dialects.postgresql.ARRAY``) provide. Adapting a
1042
        # dialect-specific ARRAY to the generic one would silently break user
1043
        # code that relies on those operators at runtime (see GH-441), so we
1044
        # keep the original ARRAY class and only adapt its item type.
1045
        if isinstance(coltype, ARRAY) and type(coltype) is not ARRAY:
5✔
1046
            coltype.item_type = self.get_adapted_type(coltype.item_type)
5✔
1047
            return coltype
5✔
1048

1049
        compiled_type = coltype.compile(self.bind.engine.dialect)
5✔
1050
        for supercls in coltype.__class__.__mro__:
5✔
1051
            if not supercls.__name__.startswith("_") and hasattr(
5✔
1052
                supercls, "__visit_name__"
1053
            ):
1054
                # Don't try to adapt UserDefinedType as it's not a proper column type
1055
                if supercls is UserDefinedType or issubclass(supercls, TypeDecorator):
5✔
1056
                    return coltype
5✔
1057

1058
                # Hack to fix adaptation of the Enum class which is broken since
1059
                # SQLAlchemy 1.2
1060
                kw = {}
5✔
1061
                if supercls is Enum:
5✔
1062
                    kw["name"] = coltype.name
5✔
1063
                    if coltype.schema:
5✔
1064
                        kw["schema"] = coltype.schema
5✔
1065

1066
                # Hack to fix Postgres DOMAIN type adaptation, broken as of SQLAlchemy 2.0.42
1067
                # For additional information - https://github.com/agronholm/sqlacodegen/issues/416#issuecomment-3417480599
1068
                if supercls is DOMAIN:
5✔
1069
                    if coltype.default:
5✔
1070
                        kw["default"] = coltype.default
×
1071
                    if coltype.constraint_name is not None:
5✔
1072
                        kw["constraint_name"] = coltype.constraint_name
5✔
1073
                    if coltype.not_null:
5✔
1074
                        kw["not_null"] = coltype.not_null
×
1075
                    if coltype.check is not None:
5✔
1076
                        kw["check"] = coltype.check
5✔
1077
                    if coltype.create_type:
5✔
1078
                        kw["create_type"] = coltype.create_type
5✔
1079

1080
                try:
5✔
1081
                    new_coltype = coltype.adapt(supercls)
5✔
1082
                except TypeError:
5✔
1083
                    # If the adaptation fails, don't try again
1084
                    break
5✔
1085

1086
                for key, value in kw.items():
5✔
1087
                    setattr(new_coltype, key, value)
5✔
1088

1089
                if isinstance(coltype, ARRAY):
5✔
UNCOV
1090
                    new_coltype.item_type = self.get_adapted_type(new_coltype.item_type)
×
1091

1092
                try:
5✔
1093
                    # If the adapted column type does not render the same as the
1094
                    # original, don't substitute it
1095
                    if new_coltype.compile(self.bind.engine.dialect) != compiled_type:
5✔
1096
                        break
5✔
1097
                except CompileError:
5✔
1098
                    # If the adapted column type can't be compiled, don't substitute it
1099
                    break
5✔
1100

1101
                # Stop on the first valid non-uppercase column type class
1102
                coltype = new_coltype
5✔
1103
                if supercls.__name__ != supercls.__name__.upper():
5✔
1104
                    break
5✔
1105

1106
        return coltype
5✔
1107

1108

1109
class DeclarativeGenerator(TablesGenerator):
5✔
1110
    valid_options: ClassVar[set[str]] = TablesGenerator.valid_options | {
5✔
1111
        "use_inflect",
1112
        "nojoined",
1113
        "nobidi",
1114
        "noidsuffix",
1115
        "nofknames",
1116
    }
1117

1118
    def __init__(
5✔
1119
        self,
1120
        metadata: MetaData,
1121
        bind: Connection | Engine,
1122
        options: Sequence[str],
1123
        *,
1124
        indentation: str = "    ",
1125
        base_class_name: str = "Base",
1126
        explicit_foreign_keys: bool = False,
1127
    ):
1128
        super().__init__(metadata, bind, options, indentation=indentation)
5✔
1129
        self.base_class_name: str = base_class_name
5✔
1130
        self.inflect_engine = inflect.engine()
5✔
1131
        self.explicit_foreign_keys = explicit_foreign_keys
5✔
1132

1133
    def generate_base(self) -> None:
5✔
1134
        self.base = Base(
5✔
1135
            literal_imports=[LiteralImport("sqlalchemy.orm", "DeclarativeBase")],
1136
            declarations=[
1137
                f"class {self.base_class_name}(DeclarativeBase):",
1138
                f"{self.indentation}pass",
1139
            ],
1140
            metadata_ref=f"{self.base_class_name}.metadata",
1141
        )
1142

1143
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1144
        super().collect_imports(models)
5✔
1145
        if any(isinstance(model, ModelClass) for model in models):
5✔
1146
            self.add_literal_import("sqlalchemy.orm", "Mapped")
5✔
1147
            self.add_literal_import("sqlalchemy.orm", "mapped_column")
5✔
1148

1149
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1150
        super().collect_imports_for_model(model)
5✔
1151
        if isinstance(model, ModelClass):
5✔
1152
            if model.relationships:
5✔
1153
                self.add_literal_import("sqlalchemy.orm", "relationship")
5✔
1154

1155
    def generate_models(self) -> list[Model]:
5✔
1156
        models_by_table_name: dict[str, Model] = {}
5✔
1157

1158
        # Pick association tables from the metadata into their own set, don't process
1159
        # them normally
1160
        links: defaultdict[str, list[Model]] = defaultdict(lambda: [])
5✔
1161
        for table in self.metadata.sorted_tables:
5✔
1162
            qualified_name = qualified_table_name(table)
5✔
1163

1164
            # Link tables have exactly two foreign key constraints and all columns are
1165
            # involved in them
1166
            fk_constraints = sorted(
5✔
1167
                table.foreign_key_constraints, key=get_constraint_sort_key
1168
            )
1169
            if len(fk_constraints) == 2 and all(
5✔
1170
                col.foreign_keys for col in table.columns
1171
            ):
1172
                model = models_by_table_name[qualified_name] = Model(table)
5✔
1173
                tablename = fk_constraints[0].elements[0].column.table.name
5✔
1174
                links[tablename].append(model)
5✔
1175
                continue
5✔
1176

1177
            # Only form model classes for tables that have a primary key and are not
1178
            # association tables
1179
            if not table.primary_key:
5✔
1180
                models_by_table_name[qualified_name] = Model(table)
5✔
1181
            else:
1182
                model = ModelClass(table)
5✔
1183
                models_by_table_name[qualified_name] = model
5✔
1184

1185
                # Fill in the columns
1186
                for column in table.c:
5✔
1187
                    column_attr = ColumnAttribute(model, column)
5✔
1188
                    model.columns.append(column_attr)
5✔
1189

1190
        # Add relationships
1191
        for model in models_by_table_name.values():
5✔
1192
            if isinstance(model, ModelClass):
5✔
1193
                self.generate_relationships(
5✔
1194
                    model, models_by_table_name, links[model.table.name]
1195
                )
1196

1197
        # Nest inherited classes in their superclasses to ensure proper ordering
1198
        if "nojoined" not in self.options:
5✔
1199
            for model in list(models_by_table_name.values()):
5✔
1200
                if not isinstance(model, ModelClass):
5✔
1201
                    continue
5✔
1202

1203
                pk_column_names = {col.name for col in model.table.primary_key.columns}
5✔
1204
                for constraint in model.table.foreign_key_constraints:
5✔
1205
                    if set(get_column_names(constraint)) == pk_column_names:
5✔
1206
                        target = models_by_table_name[
5✔
1207
                            qualified_table_name(constraint.elements[0].column.table)
1208
                        ]
1209
                        if isinstance(target, ModelClass):
5✔
1210
                            model.parent_class = target
5✔
1211
                            target.children.append(model)
5✔
1212

1213
        # Change base if we only have tables
1214
        if not any(
5✔
1215
            isinstance(model, ModelClass) for model in models_by_table_name.values()
1216
        ):
1217
            super().generate_base()
5✔
1218

1219
        # Collect the imports
1220
        self.collect_imports(models_by_table_name.values())
5✔
1221

1222
        # Rename models and their attributes that conflict with imports or other
1223
        # attributes
1224
        global_names = {
5✔
1225
            name for namespace in self.imports.values() for name in namespace
1226
        }
1227
        for model in models_by_table_name.values():
5✔
1228
            self.generate_model_name(model, global_names)
5✔
1229
            global_names.add(model.name)
5✔
1230

1231
        return list(models_by_table_name.values())
5✔
1232

1233
    def generate_relationships(
5✔
1234
        self,
1235
        source: ModelClass,
1236
        models_by_table_name: dict[str, Model],
1237
        association_tables: list[Model],
1238
    ) -> list[RelationshipAttribute]:
1239
        relationships: list[RelationshipAttribute] = []
5✔
1240
        reverse_relationship: RelationshipAttribute | None
1241

1242
        # Add many-to-one (and one-to-many) relationships
1243
        pk_column_names = {col.name for col in source.table.primary_key.columns}
5✔
1244
        for constraint in sorted(
5✔
1245
            source.table.foreign_key_constraints, key=get_constraint_sort_key
1246
        ):
1247
            target = models_by_table_name[
5✔
1248
                qualified_table_name(constraint.elements[0].column.table)
1249
            ]
1250
            if isinstance(target, ModelClass):
5✔
1251
                if "nojoined" not in self.options:
5✔
1252
                    if set(get_column_names(constraint)) == pk_column_names:
5✔
1253
                        parent = models_by_table_name[
5✔
1254
                            qualified_table_name(constraint.elements[0].column.table)
1255
                        ]
1256
                        if isinstance(parent, ModelClass):
5✔
1257
                            source.parent_class = parent
5✔
1258
                            parent.children.append(source)
5✔
1259
                            continue
5✔
1260

1261
                # Add uselist=False to One-to-One relationships
1262
                column_names = get_column_names(constraint)
5✔
1263
                if any(
5✔
1264
                    isinstance(c, (PrimaryKeyConstraint, UniqueConstraint))
1265
                    and {col.name for col in c.columns} == set(column_names)
1266
                    for c in constraint.table.constraints
1267
                ):
1268
                    r_type = RelationshipType.ONE_TO_ONE
5✔
1269
                else:
1270
                    r_type = RelationshipType.MANY_TO_ONE
5✔
1271

1272
                relationship = RelationshipAttribute(r_type, source, target, constraint)
5✔
1273
                source.relationships.append(relationship)
5✔
1274

1275
                # For self referential relationships, remote_side needs to be set
1276
                if source is target:
5✔
1277
                    relationship.remote_side = [
5✔
1278
                        source.get_column_attribute(col.name)
1279
                        for col in constraint.referred_table.primary_key
1280
                    ]
1281

1282
                # If the two tables share more than one foreign key constraint,
1283
                # SQLAlchemy needs an explicit primaryjoin to figure out which column(s)
1284
                # it needs
1285
                common_fk_constraints = get_common_fk_constraints(
5✔
1286
                    source.table, target.table
1287
                )
1288
                if len(common_fk_constraints) > 1:
5✔
1289
                    relationship.foreign_keys = [
5✔
1290
                        source.get_column_attribute(key)
1291
                        for key in constraint.column_keys
1292
                    ]
1293

1294
                # Generate the opposite end of the relationship in the target class
1295
                if "nobidi" not in self.options:
5✔
1296
                    if r_type is RelationshipType.MANY_TO_ONE:
5✔
1297
                        r_type = RelationshipType.ONE_TO_MANY
5✔
1298

1299
                    reverse_relationship = RelationshipAttribute(
5✔
1300
                        r_type,
1301
                        target,
1302
                        source,
1303
                        constraint,
1304
                        foreign_keys=relationship.foreign_keys,
1305
                        backref=relationship,
1306
                    )
1307
                    relationship.backref = reverse_relationship
5✔
1308
                    target.relationships.append(reverse_relationship)
5✔
1309

1310
                    # For self referential relationships, remote_side needs to be set
1311
                    if source is target:
5✔
1312
                        reverse_relationship.remote_side = [
5✔
1313
                            source.get_column_attribute(colname)
1314
                            for colname in constraint.column_keys
1315
                        ]
1316

1317
        # Add many-to-many relationships
1318
        for association_table in association_tables:
5✔
1319
            fk_constraints = sorted(
5✔
1320
                association_table.table.foreign_key_constraints,
1321
                key=get_constraint_sort_key,
1322
            )
1323
            target = models_by_table_name[
5✔
1324
                qualified_table_name(fk_constraints[1].elements[0].column.table)
1325
            ]
1326
            if isinstance(target, ModelClass):
5✔
1327
                relationship = RelationshipAttribute(
5✔
1328
                    RelationshipType.MANY_TO_MANY,
1329
                    source,
1330
                    target,
1331
                    fk_constraints[1],
1332
                    association_table,
1333
                )
1334
                source.relationships.append(relationship)
5✔
1335

1336
                # Generate the opposite end of the relationship in the target class
1337
                reverse_relationship = None
5✔
1338
                if "nobidi" not in self.options:
5✔
1339
                    reverse_relationship = RelationshipAttribute(
5✔
1340
                        RelationshipType.MANY_TO_MANY,
1341
                        target,
1342
                        source,
1343
                        fk_constraints[0],
1344
                        association_table,
1345
                        relationship,
1346
                    )
1347
                    relationship.backref = reverse_relationship
5✔
1348
                    target.relationships.append(reverse_relationship)
5✔
1349

1350
                # Add a primary/secondary join for self-referential many-to-many
1351
                # relationships
1352
                if source is target:
5✔
1353
                    both_relationships = [relationship]
5✔
1354
                    reverse_flags = [False, True]
5✔
1355
                    if reverse_relationship:
5✔
1356
                        both_relationships.append(reverse_relationship)
5✔
1357

1358
                    for relationship, reverse in zip(both_relationships, reverse_flags):
5✔
1359
                        if (
5✔
1360
                            not relationship.association_table
1361
                            or not relationship.constraint
1362
                        ):
1363
                            continue
×
1364

1365
                        constraints = sorted(
5✔
1366
                            relationship.constraint.table.foreign_key_constraints,
1367
                            key=get_constraint_sort_key,
1368
                            reverse=reverse,
1369
                        )
1370
                        pri_pairs = zip(
5✔
1371
                            get_column_names(constraints[0]), constraints[0].elements
1372
                        )
1373
                        sec_pairs = zip(
5✔
1374
                            get_column_names(constraints[1]), constraints[1].elements
1375
                        )
1376
                        relationship.primaryjoin = [
5✔
1377
                            (
1378
                                relationship.source,
1379
                                elem.column.name,
1380
                                relationship.association_table,
1381
                                col,
1382
                            )
1383
                            for col, elem in pri_pairs
1384
                        ]
1385
                        relationship.secondaryjoin = [
5✔
1386
                            (
1387
                                relationship.target,
1388
                                elem.column.name,
1389
                                relationship.association_table,
1390
                                col,
1391
                            )
1392
                            for col, elem in sec_pairs
1393
                        ]
1394

1395
        return relationships
5✔
1396

1397
    def generate_model_name(self, model: Model, global_names: set[str]) -> None:
5✔
1398
        if isinstance(model, ModelClass):
5✔
1399
            preferred_name = _re_invalid_identifier.sub("_", model.table.name)
5✔
1400
            preferred_name = "".join(
5✔
1401
                part[:1].upper() + part[1:] for part in preferred_name.split("_")
1402
            )
1403
            if "use_inflect" in self.options:
5✔
1404
                singular_name = self.inflect_engine.singular_noun(preferred_name)
5✔
1405
                if singular_name:
5✔
1406
                    preferred_name = singular_name
5✔
1407

1408
            model.name = self.find_free_name(preferred_name, global_names)
5✔
1409

1410
            # Fill in the names for column attributes
1411
            local_names: set[str] = set()
5✔
1412
            for column_attr in model.columns:
5✔
1413
                self.generate_column_attr_name(column_attr, global_names, local_names)
5✔
1414
                local_names.add(column_attr.name)
5✔
1415

1416
            # Fill in the names for relationship attributes
1417
            for relationship in model.relationships:
5✔
1418
                self.generate_relationship_name(relationship, global_names, local_names)
5✔
1419
                local_names.add(relationship.name)
5✔
1420
        else:
1421
            super().generate_model_name(model, global_names)
5✔
1422

1423
    def generate_column_attr_name(
5✔
1424
        self,
1425
        column_attr: ColumnAttribute,
1426
        global_names: set[str],
1427
        local_names: set[str],
1428
    ) -> None:
1429
        column_attr.name = self.find_free_name(
5✔
1430
            column_attr.column.name, global_names, local_names
1431
        )
1432

1433
    def generate_relationship_name(
5✔
1434
        self,
1435
        relationship: RelationshipAttribute,
1436
        global_names: set[str],
1437
        local_names: set[str],
1438
    ) -> None:
1439
        def strip_id_suffix(name: str) -> str:
5✔
1440
            # Strip _id only if at the end or followed by underscore (e.g., "course_id" -> "course", "course_id_1" -> "course_1")
1441
            # But don't strip from "parent_id1" (where id is followed by a digit without underscore)
1442
            return re.sub(r"_id(?=_|$)", "", name)
5✔
1443

1444
        def get_m2m_qualified_name(default_name: str) -> str:
5✔
1445
            """Generate qualified name for many-to-many relationship when multiple junction tables exist."""
1446
            # Check if there are multiple M2M relationships to the same target
1447
            target_m2m_relationships = [
5✔
1448
                r
1449
                for r in relationship.source.relationships
1450
                if r.target is relationship.target
1451
                and r.type == RelationshipType.MANY_TO_MANY
1452
            ]
1453

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

1483
            return default_name
5✔
1484

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

1489
            if len(column_names) == 1:
5✔
1490
                # Single column FK: strip _id suffix if present
1491
                fk_qualifier = strip_id_suffix(column_names[0])
5✔
1492
            else:
1493
                # Multi-column FK: concatenate all column names (strip _id from each)
1494
                fk_qualifier = "_".join(
5✔
1495
                    strip_id_suffix(col_name) for col_name in column_names
1496
                )
1497

1498
            # For self-referential relationships, don't prepend the table name
1499
            if relationship.source is relationship.target:
5✔
1500
                return fk_qualifier
×
1501
            else:
1502
                return f"{relationship.target.table.name}_{fk_qualifier}"
5✔
1503

1504
        def resolve_preferred_name() -> str:
5✔
1505
            resolved_name = relationship.target.table.name
5✔
1506

1507
            # For reverse relationships with multiple FKs to the same table, use the FK
1508
            # column name to create a more descriptive relationship name
1509
            # For M2M relationships with multiple junction tables, use the junction table name
1510
            use_fk_based_naming = "nofknames" not in self.options and (
5✔
1511
                (
1512
                    relationship.constraint
1513
                    and relationship.type
1514
                    in (RelationshipType.ONE_TO_MANY, RelationshipType.ONE_TO_ONE)
1515
                    and relationship.foreign_keys
1516
                )
1517
                or (
1518
                    relationship.type == RelationshipType.MANY_TO_MANY
1519
                    and relationship.association_table
1520
                )
1521
            )
1522

1523
            if use_fk_based_naming:
5✔
1524
                if relationship.type == RelationshipType.MANY_TO_MANY:
5✔
1525
                    resolved_name = get_m2m_qualified_name(resolved_name)
5✔
1526
                elif relationship.constraint:
5✔
1527
                    resolved_name = get_fk_qualified_name(relationship.constraint)
5✔
1528

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

1557
            if "use_inflect" in self.options:
5✔
1558
                inflected_name: str | Literal[False]
1559
                if relationship.type in (
5✔
1560
                    RelationshipType.ONE_TO_MANY,
1561
                    RelationshipType.MANY_TO_MANY,
1562
                ):
1563
                    if not self.inflect_engine.singular_noun(resolved_name):
5✔
1564
                        resolved_name = self.inflect_engine.plural_noun(resolved_name)
5✔
1565
                else:
1566
                    inflected_name = self.inflect_engine.singular_noun(resolved_name)
5✔
1567
                    if inflected_name:
5✔
1568
                        resolved_name = inflected_name
5✔
1569

1570
            return resolved_name
5✔
1571

1572
        if (
5✔
1573
            relationship.type
1574
            in (RelationshipType.ONE_TO_MANY, RelationshipType.ONE_TO_ONE)
1575
            and relationship.source is relationship.target
1576
            and relationship.backref
1577
            and relationship.backref.name
1578
        ):
1579
            preferred_name = relationship.backref.name + "_reverse"
5✔
1580
        else:
1581
            preferred_name = resolve_preferred_name()
5✔
1582

1583
        relationship.name = self.find_free_name(
5✔
1584
            preferred_name, global_names, local_names
1585
        )
1586

1587
    def render_models(self, models: list[Model]) -> str:
5✔
1588
        rendered: list[str] = []
5✔
1589
        for model in models:
5✔
1590
            if isinstance(model, ModelClass):
5✔
1591
                rendered.append(self.render_class(model))
5✔
1592
            else:
1593
                rendered.append(f"{model.name} = {self.render_table(model.table)}")
5✔
1594

1595
        return "\n\n\n".join(rendered)
5✔
1596

1597
    def render_class(self, model: ModelClass) -> str:
5✔
1598
        sections: list[str] = []
5✔
1599

1600
        # Render class variables / special declarations
1601
        class_vars: str = self.render_class_variables(model)
5✔
1602
        if class_vars:
5✔
1603
            sections.append(class_vars)
5✔
1604

1605
        # Render column attributes
1606
        rendered_column_attributes: list[str] = []
5✔
1607
        for nullable in (False, True):
5✔
1608
            for column_attr in model.columns:
5✔
1609
                if column_attr.column.nullable is nullable:
5✔
1610
                    rendered_column_attributes.append(
5✔
1611
                        self.render_column_attribute(column_attr)
1612
                    )
1613

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

1617
        # Render relationship attributes
1618
        rendered_relationship_attributes: list[str] = [
5✔
1619
            self.render_relationship(relationship)
1620
            for relationship in model.relationships
1621
        ]
1622

1623
        if rendered_relationship_attributes:
5✔
1624
            sections.append("\n".join(rendered_relationship_attributes))
5✔
1625

1626
        declaration = self.render_class_declaration(model)
5✔
1627
        rendered_sections = "\n\n".join(
5✔
1628
            indent(section, self.indentation) for section in sections
1629
        )
1630
        return f"{declaration}\n{rendered_sections}"
5✔
1631

1632
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1633
        parent_class_name = (
5✔
1634
            model.parent_class.name if model.parent_class else self.base_class_name
1635
        )
1636
        return f"class {model.name}({parent_class_name}):"
5✔
1637

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

1641
        # Render constraints and indexes as __table_args__
1642
        table_args = self.render_table_args(model.table)
5✔
1643
        if table_args:
5✔
1644
            variables.append(f"__table_args__ = {table_args}")
5✔
1645

1646
        return "\n".join(variables)
5✔
1647

1648
    def render_table_args(self, table: Table) -> str:
5✔
1649
        args: list[str] = []
5✔
1650
        kwargs: dict[str, object] = {}
5✔
1651

1652
        # Render constraints
1653
        for constraint in sorted(table.constraints, key=get_constraint_sort_key):
5✔
1654
            if uses_default_name(constraint):
5✔
1655
                if isinstance(constraint, PrimaryKeyConstraint):
5✔
1656
                    continue
5✔
1657
                if (
5✔
1658
                    isinstance(constraint, (ForeignKeyConstraint, UniqueConstraint))
1659
                    and len(constraint.columns) == 1
1660
                ):
1661
                    continue
5✔
1662

1663
            args.append(self.render_constraint(constraint))
5✔
1664

1665
        # Render indexes
1666
        for index in sorted(table.indexes, key=lambda i: cast(str, i.name)):
5✔
1667
            if len(index.columns) > 1 or not uses_default_name(index):
5✔
1668
                args.append(self.render_index(index))
5✔
1669

1670
        if table.schema:
5✔
1671
            kwargs["schema"] = table.schema
5✔
1672

1673
        if table.comment:
5✔
1674
            kwargs["comment"] = table.comment
5✔
1675

1676
        # add info + dialect kwargs for dict context (__table_args__) (opt-in)
1677
        if self.include_dialect_options_and_info:
5✔
1678
            self._add_dialect_kwargs_and_info(table, kwargs, values_for_dict=True)
5✔
1679

1680
        if kwargs:
5✔
1681
            formatted_kwargs = pformat(kwargs)
5✔
1682
            if not args:
5✔
1683
                return formatted_kwargs
5✔
1684
            else:
1685
                args.append(formatted_kwargs)
5✔
1686

1687
        if args:
5✔
1688
            rendered_args = f",\n{self.indentation}".join(args)
5✔
1689
            if len(args) == 1:
5✔
1690
                rendered_args += ","
5✔
1691

1692
            return f"(\n{self.indentation}{rendered_args}\n)"
5✔
1693
        else:
1694
            return ""
5✔
1695

1696
    def render_column_python_type(self, column: Column[Any]) -> str:
5✔
1697
        def get_type_qualifiers() -> tuple[str, TypeEngine[Any], str]:
5✔
1698
            column_type = column.type
5✔
1699
            pre: list[str] = []
5✔
1700
            post_size = 0
5✔
1701
            if column.nullable:
5✔
1702
                self.add_literal_import("typing", "Optional")
5✔
1703
                pre.append("Optional[")
5✔
1704
                post_size += 1
5✔
1705

1706
            if isinstance(column_type, ARRAY):
5✔
1707
                dim = getattr(column_type, "dimensions", None) or 1
5✔
1708
                pre.extend("list[" for _ in range(dim))
5✔
1709
                post_size += dim
5✔
1710

1711
                column_type = column_type.item_type
5✔
1712

1713
            return "".join(pre), column_type, "]" * post_size
5✔
1714

1715
        def render_python_type(column_type: TypeEngine[Any]) -> str:
5✔
1716
            # Check if this is an enum column with a Python enum class
1717
            if isinstance(column_type, Enum):
5✔
1718
                table_name = column.table.name
5✔
1719
                column_name = column.name
5✔
1720
                if (table_name, column_name) in self.enum_classes:
5✔
1721
                    enum_class_name = self.enum_classes[(table_name, column_name)]
5✔
1722
                    return enum_class_name
5✔
1723

1724
            if isinstance(column_type, DOMAIN):
5✔
1725
                column_type = column_type.data_type
5✔
1726

1727
            try:
5✔
1728
                python_type = column_type.python_type
5✔
1729
                python_type_module = python_type.__module__
5✔
1730
                python_type_name = python_type.__name__
5✔
1731
            except NotImplementedError:
5✔
1732
                self.add_literal_import("typing", "Any")
5✔
1733
                return "Any"
5✔
1734

1735
            if python_type_module == "builtins":
5✔
1736
                return python_type_name
5✔
1737

1738
            self.add_module_import(python_type_module)
5✔
1739
            return f"{python_type_module}.{python_type_name}"
5✔
1740

1741
        pre, col_type, post = get_type_qualifiers()
5✔
1742
        column_python_type = f"{pre}{render_python_type(col_type)}{post}"
5✔
1743
        return column_python_type
5✔
1744

1745
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1746
        column = column_attr.column
5✔
1747
        rendered_column = self.render_column(column, column_attr.name != column.name)
5✔
1748
        rendered_column_python_type = self.render_column_python_type(column)
5✔
1749

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

1752
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1753
        kwargs = self.render_relationship_arguments(relationship)
5✔
1754
        annotation = self.render_relationship_annotation(relationship)
5✔
1755
        rendered_relationship = render_callable(
5✔
1756
            "relationship", repr(relationship.target.name), kwargs=kwargs
1757
        )
1758
        return f"{relationship.name}: Mapped[{annotation}] = {rendered_relationship}"
5✔
1759

1760
    def render_relationship_annotation(
5✔
1761
        self, relationship: RelationshipAttribute
1762
    ) -> str:
1763
        match relationship.type:
5✔
1764
            case RelationshipType.ONE_TO_MANY:
5✔
1765
                return f"list[{relationship.target.name!r}]"
5✔
1766
            case RelationshipType.ONE_TO_ONE | RelationshipType.MANY_TO_ONE:
5✔
1767
                if relationship.constraint and any(
5✔
1768
                    col.nullable for col in relationship.constraint.columns
1769
                ):
1770
                    self.add_literal_import("typing", "Optional")
5✔
1771
                    return f"Optional[{relationship.target.name!r}]"
5✔
1772
                else:
1773
                    return f"'{relationship.target.name}'"
5✔
1774
            case RelationshipType.MANY_TO_MANY:
5✔
1775
                return f"list[{relationship.target.name!r}]"
5✔
1776

1777
    def render_relationship_arguments(
5✔
1778
        self, relationship: RelationshipAttribute
1779
    ) -> Mapping[str, Any]:
1780
        def render_column_attrs(column_attrs: list[ColumnAttribute]) -> str:
5✔
1781
            rendered = []
5✔
1782
            render_as_string = False
5✔
1783
            for attr in column_attrs:
5✔
1784
                if not self.explicit_foreign_keys and attr.model is relationship.source:
5✔
1785
                    rendered.append(attr.name)
5✔
1786
                else:
1787
                    rendered.append(f"{attr.model.name}.{attr.name}")
5✔
1788
                    render_as_string = True
5✔
1789

1790
            joined = "[" + ", ".join(rendered) + "]"
5✔
1791
            return repr(joined) if render_as_string else joined
5✔
1792

1793
        def render_foreign_keys(column_attrs: list[ColumnAttribute]) -> str:
5✔
1794
            rendered = []
5✔
1795
            render_as_string = False
5✔
1796
            # Assume that column_attrs are all in relationship.source or none
1797
            for attr in column_attrs:
5✔
1798
                if not self.explicit_foreign_keys and attr.model is relationship.source:
5✔
1799
                    rendered.append(attr.name)
5✔
1800
                else:
1801
                    rendered.append(f"{attr.model.name}.{attr.name}")
5✔
1802
                    render_as_string = True
5✔
1803

1804
            if render_as_string:
5✔
1805
                return "'[" + ", ".join(rendered) + "]'"
5✔
1806
            else:
1807
                return "[" + ", ".join(rendered) + "]"
5✔
1808

1809
        def render_join(terms: list[JoinType]) -> str:
5✔
1810
            rendered_joins = []
5✔
1811
            for source, source_col, target, target_col in terms:
5✔
1812
                rendered = f"lambda: {source.name}.{source_col} == {target.name}."
5✔
1813
                if target.__class__ is Model:
5✔
1814
                    rendered += "c."
5✔
1815

1816
                rendered += str(target_col)
5✔
1817
                rendered_joins.append(rendered)
5✔
1818

1819
            if len(rendered_joins) > 1:
5✔
1820
                rendered = ", ".join(rendered_joins)
×
1821
                return f"and_({rendered})"
×
1822
            else:
1823
                return rendered_joins[0]
5✔
1824

1825
        # Render keyword arguments
1826
        kwargs: dict[str, Any] = {}
5✔
1827
        if relationship.type is RelationshipType.ONE_TO_ONE and relationship.constraint:
5✔
1828
            if relationship.constraint.referred_table is relationship.source.table:
5✔
1829
                kwargs["uselist"] = False
5✔
1830

1831
        # Add the "secondary" keyword for many-to-many relationships
1832
        if relationship.association_table:
5✔
1833
            table_ref = relationship.association_table.table.name
5✔
1834
            if relationship.association_table.schema:
5✔
1835
                table_ref = f"{relationship.association_table.schema}.{table_ref}"
5✔
1836

1837
            kwargs["secondary"] = repr(table_ref)
5✔
1838

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

1842
        if relationship.foreign_keys:
5✔
1843
            kwargs["foreign_keys"] = render_foreign_keys(relationship.foreign_keys)
5✔
1844

1845
        if relationship.primaryjoin:
5✔
1846
            kwargs["primaryjoin"] = render_join(relationship.primaryjoin)
5✔
1847

1848
        if relationship.secondaryjoin:
5✔
1849
            kwargs["secondaryjoin"] = render_join(relationship.secondaryjoin)
5✔
1850

1851
        if relationship.backref:
5✔
1852
            kwargs["back_populates"] = repr(relationship.backref.name)
5✔
1853

1854
        return kwargs
5✔
1855

1856

1857
class DataclassGenerator(DeclarativeGenerator):
5✔
1858
    def __init__(
5✔
1859
        self,
1860
        metadata: MetaData,
1861
        bind: Connection | Engine,
1862
        options: Sequence[str],
1863
        *,
1864
        indentation: str = "    ",
1865
        base_class_name: str = "Base",
1866
        quote_annotations: bool = False,
1867
        metadata_key: str = "sa",
1868
    ):
1869
        super().__init__(
5✔
1870
            metadata,
1871
            bind,
1872
            options,
1873
            indentation=indentation,
1874
            base_class_name=base_class_name,
1875
        )
1876
        self.metadata_key: str = metadata_key
5✔
1877
        self.quote_annotations: bool = quote_annotations
5✔
1878

1879
    def generate_base(self) -> None:
5✔
1880
        self.base = Base(
5✔
1881
            literal_imports=[
1882
                LiteralImport("sqlalchemy.orm", "DeclarativeBase"),
1883
                LiteralImport("sqlalchemy.orm", "MappedAsDataclass"),
1884
            ],
1885
            declarations=[
1886
                (f"class {self.base_class_name}(MappedAsDataclass, DeclarativeBase):"),
1887
                f"{self.indentation}pass",
1888
            ],
1889
            metadata_ref=f"{self.base_class_name}.metadata",
1890
        )
1891

1892

1893
class SQLModelGenerator(DeclarativeGenerator):
5✔
1894
    def __init__(
5✔
1895
        self,
1896
        metadata: MetaData,
1897
        bind: Connection | Engine,
1898
        options: Sequence[str],
1899
        *,
1900
        indentation: str = "    ",
1901
        base_class_name: str = "SQLModel",
1902
    ):
1903
        super().__init__(
5✔
1904
            metadata,
1905
            bind,
1906
            options,
1907
            indentation=indentation,
1908
            base_class_name=base_class_name,
1909
            explicit_foreign_keys=True,
1910
        )
1911

1912
    @property
5✔
1913
    def views_supported(self) -> bool:
5✔
1914
        return False
×
1915

1916
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
1917
        self.add_import(Column)
5✔
1918
        return render_callable("Column", *args, kwargs=kwargs)
5✔
1919

1920
    def render_table(self, table: Table) -> str:
5✔
1921
        # Hack to fix #465 without breaking backwards compatibility
1922
        self.base.metadata_ref = "SQLModel.metadata"
5✔
1923

1924
        return super().render_table(table)
5✔
1925

1926
    def generate_base(self) -> None:
5✔
1927
        self.base = Base(
5✔
1928
            literal_imports=[],
1929
            declarations=[],
1930
            metadata_ref="SQLModel.metadata",
1931
        )
1932

1933
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1934
        super(DeclarativeGenerator, self).collect_imports(models)
5✔
1935
        if any(isinstance(model, ModelClass) for model in models):
5✔
1936
            self.add_literal_import("sqlmodel", "Field")
5✔
1937

1938
        if models:
5✔
1939
            self.remove_literal_import("sqlalchemy", "MetaData")
5✔
1940
            self.add_literal_import("sqlmodel", "SQLModel")
5✔
1941

1942
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1943
        super(DeclarativeGenerator, self).collect_imports_for_model(model)
5✔
1944
        if isinstance(model, ModelClass):
5✔
1945
            for column_attr in model.columns:
5✔
1946
                if column_attr.column.nullable:
5✔
1947
                    self.add_literal_import("typing", "Optional")
5✔
1948
                    break
5✔
1949

1950
            if model.relationships:
5✔
1951
                self.add_literal_import("sqlmodel", "Relationship")
5✔
1952

1953
    def render_module_variables(self, models: list[Model]) -> str:
5✔
1954
        declarations: list[str] = []
5✔
1955
        if any(not isinstance(model, ModelClass) for model in models):
5✔
1956
            if self.base.table_metadata_declaration is not None:
5✔
1957
                declarations.append(self.base.table_metadata_declaration)
×
1958

1959
        return "\n".join(declarations)
5✔
1960

1961
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1962
        if model.parent_class:
5✔
1963
            parent = model.parent_class.name
×
1964
        else:
1965
            parent = self.base_class_name
5✔
1966

1967
        superclass_part = f"({parent}, table=True)"
5✔
1968
        return f"class {model.name}{superclass_part}:"
5✔
1969

1970
    def render_class_variables(self, model: ModelClass) -> str:
5✔
1971
        variables = []
5✔
1972

1973
        if model.table.name != model.name.lower():
5✔
1974
            variables.append(f"__tablename__ = {model.table.name!r}")
5✔
1975

1976
        # Render constraints and indexes as __table_args__
1977
        table_args = self.render_table_args(model.table)
5✔
1978
        if table_args:
5✔
1979
            variables.append(f"__table_args__ = {table_args}")
5✔
1980

1981
        return "\n".join(variables)
5✔
1982

1983
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1984
        column = column_attr.column
5✔
1985
        rendered_column = self.render_column(column, True)
5✔
1986
        rendered_column_python_type = self.render_column_python_type(column)
5✔
1987

1988
        kwargs: dict[str, Any] = {}
5✔
1989
        if column.nullable:
5✔
1990
            kwargs["default"] = None
5✔
1991
        kwargs["sa_column"] = f"{rendered_column}"
5✔
1992

1993
        rendered_field = render_callable("Field", kwargs=kwargs)
5✔
1994

1995
        return f"{column_attr.name}: {rendered_column_python_type} = {rendered_field}"
5✔
1996

1997
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1998
        kwargs = self.render_relationship_arguments(relationship)
5✔
1999
        annotation = self.render_relationship_annotation(relationship)
5✔
2000

2001
        native_kwargs: dict[str, Any] = {}
5✔
2002
        non_native_kwargs: dict[str, Any] = {}
5✔
2003
        for key, value in kwargs.items():
5✔
2004
            # The following keyword arguments are natively supported in Relationship
2005
            if key in ("back_populates", "cascade_delete", "passive_deletes"):
5✔
2006
                native_kwargs[key] = value
5✔
2007
            else:
2008
                non_native_kwargs[key] = value
5✔
2009

2010
        if non_native_kwargs:
5✔
2011
            native_kwargs["sa_relationship_kwargs"] = (
5✔
2012
                "{"
2013
                + ", ".join(
2014
                    f"{key!r}: {value}" for key, value in non_native_kwargs.items()
2015
                )
2016
                + "}"
2017
            )
2018

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