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

agronholm / sqlacodegen / 22294400921

23 Feb 2026 05:44AM UTC coverage: 97.668% (-0.05%) from 97.718%
22294400921

push

github

web-flow
Fix inherited kwargs rendering for MySQL CHAR collation (#464)

* Render inherited kwargs for **kwargs column types

Closes #285.

* Address PR #464 review feedback

- extract helper methods from render_column_type() for readability\n- split inherited init kwargs collection into a dedicated helper\n- add CHANGES.rst Unreleased entry for #285 fix\n- ensure pre-commit hooks pass

* Update CHANGES.rst with contributor details

Added contributor information for a fix regarding inherited keyword arguments in dialect-specific types.

---------

Co-authored-by: Idan Sheinberg <ishinberg0@gmail.com>

54 of 56 new or added lines in 3 files covered. (96.43%)

1801 of 1844 relevant lines covered (97.67%)

4.88 hits per line

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

96.72
/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 importlib import import_module
5✔
11
from inspect import Parameter
5✔
12
from itertools import count
5✔
13
from keyword import iskeyword
5✔
14
from pprint import pformat
5✔
15
from textwrap import indent
5✔
16
from typing import Any, ClassVar, Literal, cast
5✔
17

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

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

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

74

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

80

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

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

91

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

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

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

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

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

119

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

366
        return models
5✔
367

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

477
        if show_name:
5✔
478
            args.append(repr(column.name))
5✔
479

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

485
        for fk in dedicated_fks:
5✔
486
            args.append(self.render_constraint(fk))
5✔
487

488
        if column.default:
5✔
489
            args.append(repr(column.default))
5✔
490

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

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

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

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

519
            args.append(
5✔
520
                render_callable("Computed", repr(expression), kwargs=computed_kwargs)
521
            )
522
        elif isinstance(column.server_default, Identity):
5✔
523
            args.append(repr(column.server_default))
5✔
524
        elif column.server_default:
5✔
525
            kwargs["server_default"] = repr(column.server_default)
×
526

527
        comment = getattr(column, "comment", None)
5✔
528
        if comment:
5✔
529
            kwargs["comment"] = repr(comment)
5✔
530

531
        # add column info + dialect kwargs for callable context (opt-in)
532
        if self.include_dialect_options_and_info:
5✔
533
            self._add_dialect_kwargs_and_info(column, kwargs, values_for_dict=False)
5✔
534

535
        return self.render_column_callable(is_table, *args, **kwargs)
5✔
536

537
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
538
        if is_table:
5✔
539
            self.add_import(Column)
5✔
540
            return render_callable("Column", *args, kwargs=kwargs)
5✔
541
        else:
542
            return render_callable("mapped_column", *args, kwargs=kwargs)
5✔
543

544
    def _render_column_type_value(self, value: Any) -> str:
5✔
545
        if isinstance(value, (JSONB, JSON)):
5✔
546
            # Remove astext_type if it's the default
547
            if isinstance(value.astext_type, Text) and value.astext_type.length is None:
5✔
548
                value.astext_type = None  # type: ignore[assignment]
5✔
549
            else:
550
                self.add_import(Text)
5✔
551

552
        if isinstance(value, TextClause):
5✔
553
            self.add_literal_import("sqlalchemy", "text")
5✔
554
            return render_callable("text", repr(value.text))
5✔
555

556
        return repr(value)
5✔
557

558
    def _collect_inherited_init_kwargs(
5✔
559
        self,
560
        column_type: Any,
561
        init_sig: inspect.Signature,
562
        seen_param_names: set[str],
563
        missing: object,
564
    ) -> dict[str, str]:
565
        has_var_keyword = any(
5✔
566
            param.kind is Parameter.VAR_KEYWORD
567
            for param in init_sig.parameters.values()
568
        )
569
        has_var_positional = any(
5✔
570
            param.kind is Parameter.VAR_POSITIONAL
571
            for param in init_sig.parameters.values()
572
        )
573
        if not has_var_keyword or has_var_positional:
5✔
574
            return {}
5✔
575

576
        inherited_kwargs: dict[str, str] = {}
5✔
577
        for supercls in column_type.__class__.__mro__[1:]:
5✔
578
            if supercls is object:
5✔
579
                break
5✔
580

581
            try:
5✔
582
                super_sig = inspect.signature(supercls.__init__)
5✔
NEW
583
            except (TypeError, ValueError):
×
NEW
584
                continue
×
585

586
            for super_param in list(super_sig.parameters.values())[1:]:
5✔
587
                if super_param.name.startswith("_"):
5✔
588
                    continue
5✔
589

590
                if super_param.kind in (
5✔
591
                    Parameter.POSITIONAL_ONLY,
592
                    Parameter.VAR_POSITIONAL,
593
                    Parameter.VAR_KEYWORD,
594
                ):
595
                    continue
5✔
596

597
                if super_param.name in seen_param_names:
5✔
598
                    continue
5✔
599

600
                seen_param_names.add(super_param.name)
5✔
601
                value = getattr(column_type, super_param.name, missing)
5✔
602
                if value is missing:
5✔
603
                    continue
5✔
604

605
                default = super_param.default
5✔
606
                if default is not Parameter.empty and value == default:
5✔
607
                    continue
5✔
608

609
                inherited_kwargs[super_param.name] = self._render_column_type_value(
5✔
610
                    value
611
                )
612

613
        return inherited_kwargs
5✔
614

615
    def render_column_type(self, column: Column[Any]) -> str:
5✔
616
        column_type = column.type
5✔
617
        # Check if this is an enum column with a Python enum class
618
        if isinstance(column_type, Enum) and column is not None:
5✔
619
            if enum_class_name := self.enum_classes.get(
5✔
620
                (column.table.name, column.name)
621
            ):
622
                # Import SQLAlchemy Enum (will be handled in collect_imports)
623
                self.add_import(Enum)
5✔
624
                extra_kwargs = ""
5✔
625
                if column_type.name is not None:
5✔
626
                    extra_kwargs += f", name={column_type.name!r}"
5✔
627

628
                if column_type.schema is not None:
5✔
629
                    extra_kwargs += f", schema={column_type.schema!r}"
5✔
630

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

633
        args = []
5✔
634
        kwargs: dict[str, Any] = {}
5✔
635

636
        # Check if this is an ARRAY column with an Enum item type mapped to a Python enum class
637
        if isinstance(column_type, ARRAY) and isinstance(column_type.item_type, Enum):
5✔
638
            if enum_class_name := self.enum_classes.get(
5✔
639
                (column.table.name, column.name)
640
            ):
641
                self.add_import(ARRAY)
5✔
642
                self.add_import(Enum)
5✔
643
                extra_kwargs = ""
5✔
644
                if column_type.item_type.name is not None:
5✔
645
                    extra_kwargs += f", name={column_type.item_type.name!r}"
5✔
646

647
                if column_type.item_type.schema is not None:
5✔
648
                    extra_kwargs += f", schema={column_type.item_type.schema!r}"
5✔
649

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

654
                return render_callable("ARRAY", rendered_enum, kwargs=kwargs)
5✔
655

656
        sig = inspect.signature(column_type.__class__.__init__)
5✔
657
        defaults = {param.name: param.default for param in sig.parameters.values()}
5✔
658
        missing = object()
5✔
659
        use_kwargs = False
5✔
660
        seen_param_names: set[str] = set()
5✔
661

662
        for param in list(sig.parameters.values())[1:]:
5✔
663
            # Remove annoyances like _warn_on_bytestring
664
            if param.name.startswith("_"):
5✔
665
                continue
5✔
666
            elif param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD):
5✔
667
                use_kwargs = True
5✔
668
                continue
5✔
669

670
            seen_param_names.add(param.name)
5✔
671
            value = getattr(column_type, param.name, missing)
5✔
672
            default = defaults.get(param.name, missing)
5✔
673
            if value is missing or value == default:
5✔
674
                use_kwargs = True
5✔
675
                continue
5✔
676

677
            rendered_value = self._render_column_type_value(value)
5✔
678
            if use_kwargs:
5✔
679
                kwargs[param.name] = rendered_value
5✔
680
            else:
681
                args.append(rendered_value)
5✔
682

683
        kwargs.update(
5✔
684
            self._collect_inherited_init_kwargs(
685
                column_type, sig, seen_param_names, missing
686
            )
687
        )
688

689
        vararg = next(
5✔
690
            (
691
                param.name
692
                for param in sig.parameters.values()
693
                if param.kind is Parameter.VAR_POSITIONAL
694
            ),
695
            None,
696
        )
697
        if vararg and hasattr(column_type, vararg):
5✔
698
            varargs_repr = [repr(arg) for arg in getattr(column_type, vararg)]
5✔
699
            args.extend(varargs_repr)
5✔
700

701
        # These arguments cannot be autodetected from the Enum initializer
702
        if isinstance(column_type, Enum):
5✔
703
            for colname in "name", "schema":
5✔
704
                if (value := getattr(column_type, colname)) is not None:
5✔
705
                    kwargs[colname] = repr(value)
5✔
706

707
        if isinstance(column_type, (JSONB, JSON)):
5✔
708
            # Remove astext_type if it's the default
709
            if (
5✔
710
                isinstance(column_type.astext_type, Text)
711
                and column_type.astext_type.length is None
712
            ):
713
                del kwargs["astext_type"]
5✔
714

715
        if args or kwargs:
5✔
716
            return render_callable(column_type.__class__.__name__, *args, kwargs=kwargs)
5✔
717
        else:
718
            return column_type.__class__.__name__
5✔
719

720
    def render_constraint(self, constraint: Constraint | ForeignKey) -> str:
5✔
721
        def add_fk_options(*opts: Any) -> None:
5✔
722
            args.extend(repr(opt) for opt in opts)
5✔
723
            for attr in "ondelete", "onupdate", "deferrable", "initially", "match":
5✔
724
                value = getattr(constraint, attr, None)
5✔
725
                if value:
5✔
726
                    kwargs[attr] = repr(value)
5✔
727

728
        args: list[str] = []
5✔
729
        kwargs: dict[str, Any] = {}
5✔
730
        if isinstance(constraint, ForeignKey):
5✔
731
            remote_column = (
5✔
732
                f"{constraint.column.table.fullname}.{constraint.column.name}"
733
            )
734
            add_fk_options(remote_column)
5✔
735
        elif isinstance(constraint, ForeignKeyConstraint):
5✔
736
            local_columns = get_column_names(constraint)
5✔
737
            remote_columns = [
5✔
738
                f"{fk.column.table.fullname}.{fk.column.name}"
739
                for fk in constraint.elements
740
            ]
741
            add_fk_options(local_columns, remote_columns)
5✔
742
        elif isinstance(constraint, CheckConstraint):
5✔
743
            args.append(repr(get_compiled_expression(constraint.sqltext, self.bind)))
5✔
744
        elif isinstance(constraint, (UniqueConstraint, PrimaryKeyConstraint)):
5✔
745
            args.extend(repr(col.name) for col in constraint.columns)
5✔
746
        else:
747
            raise TypeError(
×
748
                f"Cannot render constraint of type {constraint.__class__.__name__}"
749
            )
750

751
        if isinstance(constraint, Constraint) and not uses_default_name(constraint):
5✔
752
            kwargs["name"] = repr(constraint.name)
5✔
753

754
        return render_callable(constraint.__class__.__name__, *args, kwargs=kwargs)
5✔
755

756
    def _add_dialect_kwargs_and_info(
5✔
757
        self, obj: Any, target_kwargs: dict[str, object], *, values_for_dict: bool
758
    ) -> None:
759
        """
760
        Merge SchemaItem-like object's .info and .dialect_kwargs into target_kwargs.
761
        - values_for_dict=True: keep raw values so pretty-printer emits repr() (for __table_args__ dict)
762
        - values_for_dict=False: set values to repr() strings (for callable kwargs)
763
        """
764
        info_dict = getattr(obj, "info", None)
5✔
765
        if info_dict:
5✔
766
            target_kwargs["info"] = info_dict if values_for_dict else repr(info_dict)
5✔
767

768
        dialect_keys: list[str]
769
        try:
5✔
770
            dialect_keys = sorted(getattr(obj, "dialect_kwargs"))
5✔
771
        except Exception:
×
772
            return
×
773

774
        dialect_kwargs = getattr(obj, "dialect_kwargs", {})
5✔
775
        for key in dialect_keys:
5✔
776
            try:
5✔
777
                value = dialect_kwargs[key]
5✔
778
            except Exception:
×
779
                continue
×
780

781
            # Render values:
782
            # - callable context (values_for_dict=False): produce a string expression.
783
            #   primitives use repr(value); custom objects stringify then repr().
784
            # - dict context (values_for_dict=True): pass raw primitives / str;
785
            #   custom objects become str(value) so pformat quotes them.
786
            if values_for_dict:
5✔
787
                if isinstance(value, type(None) | bool | int | float):
5✔
788
                    target_kwargs[key] = value
×
789
                elif isinstance(value, str | dict | list):
5✔
790
                    target_kwargs[key] = value
5✔
791
                else:
792
                    target_kwargs[key] = str(value)
5✔
793
            else:
794
                if isinstance(
5✔
795
                    value, type(None) | bool | int | float | str | dict | list
796
                ):
797
                    target_kwargs[key] = repr(value)
5✔
798
                else:
799
                    target_kwargs[key] = repr(str(value))
5✔
800

801
    def should_ignore_table(self, table: Table) -> bool:
5✔
802
        # Support for Alembic and sqlalchemy-migrate -- never expose the schema version
803
        # tables
804
        return table.name in ("alembic_version", "migrate_version")
5✔
805

806
    def find_free_name(
5✔
807
        self, name: str, global_names: set[str], local_names: Collection[str] = ()
808
    ) -> str:
809
        """
810
        Generate an attribute name that does not clash with other local or global names.
811
        """
812
        name = name.strip()
5✔
813
        assert name, "Identifier cannot be empty"
5✔
814
        name = _re_invalid_identifier.sub("_", name)
5✔
815
        if name[0].isdigit():
5✔
816
            name = "_" + name
5✔
817
        elif iskeyword(name) or name == "metadata":
5✔
818
            name += "_"
5✔
819

820
        original = name
5✔
821
        for i in count():
5✔
822
            if name not in global_names and name not in local_names:
5✔
823
                break
5✔
824

825
            name = original + (str(i) if i else "_")
5✔
826

827
        return name
5✔
828

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

833
    def _create_enum_class(
5✔
834
        self, table_name: str, column_name: str, values: list[str]
835
    ) -> str:
836
        """
837
        Create a Python enum class name and register it.
838

839
        Returns the enum class name to use in generated code.
840
        """
841
        # Generate enum class name from table and column names
842
        # Convert to PascalCase: user_status -> UserStatus
843
        base_name = "".join(
5✔
844
            part.capitalize()
845
            for part in table_name.split("_") + column_name.split("_")
846
            if part
847
        )
848

849
        # Ensure uniqueness
850
        enum_class_name = base_name
5✔
851
        for counter in count(1):
5✔
852
            if enum_class_name not in self.enum_values:
5✔
853
                break
5✔
854

855
            # Check if it's the same enum (same values)
856
            if self.enum_values[enum_class_name] == values:
5✔
857
                # Reuse existing enum class
858
                return enum_class_name
5✔
859

860
            enum_class_name = f"{base_name}{counter}"
5✔
861

862
        # Register the new enum class
863
        self.enum_values[enum_class_name] = values
5✔
864
        return enum_class_name
5✔
865

866
    def render_enum_classes(self) -> str:
5✔
867
        """Render Python enum class definitions."""
868
        if not self.enum_values:
5✔
869
            return ""
5✔
870

871
        self.add_module_import("enum")
5✔
872

873
        enum_defs = []
5✔
874
        for enum_class_name, values in sorted(self.enum_values.items()):
5✔
875
            # Create enum members with valid Python identifiers
876
            members = []
5✔
877
            for value in values:
5✔
878
                # Unescape SQL escape sequences (e.g., \' -> ')
879
                # The value from the CHECK constraint has SQL escaping
880
                unescaped_value = value.replace("\\'", "'").replace("\\\\", "\\")
5✔
881

882
                # Create a valid identifier from the enum value
883
                member_name = _re_invalid_identifier.sub("_", unescaped_value).upper()
5✔
884
                if not member_name:
5✔
885
                    member_name = "EMPTY"
×
886
                elif member_name[0].isdigit():
5✔
887
                    member_name = "_" + member_name
×
888
                elif iskeyword(member_name):
5✔
889
                    member_name += "_"
×
890
                #
891
                # # Re-escape for Python string literal
892
                # python_escaped = unescaped_value.replace("\\", "\\\\").replace(
893
                #     "'", "\\'"
894
                # )
895
                members.append(f"    {member_name} = {unescaped_value!r}")
5✔
896

897
            enum_def = f"class {enum_class_name}(str, enum.Enum):\n" + "\n".join(
5✔
898
                members
899
            )
900
            enum_defs.append(enum_def)
5✔
901

902
        return "\n\n\n".join(enum_defs)
5✔
903

904
    def fix_column_types(self, table: Table) -> None:
5✔
905
        """Adjust the reflected column types."""
906

907
        def fix_enum_column(col_name: str, enum_type: Enum) -> None:
5✔
908
            if (table.name, col_name) in self.enum_classes:
5✔
909
                return
5✔
910

911
            if enum_type.name:
5✔
912
                existing_class = None
5✔
913
                for (_, _), cls in self.enum_classes.items():
5✔
914
                    if cls == self._enum_name_to_class_name(enum_type.name):
5✔
915
                        existing_class = cls
5✔
916
                        break
5✔
917

918
                if existing_class:
5✔
919
                    enum_class_name = existing_class
5✔
920
                else:
921
                    enum_class_name = self._enum_name_to_class_name(enum_type.name)
5✔
922
                    if enum_class_name not in self.enum_values:
5✔
923
                        self.enum_values[enum_class_name] = list(enum_type.enums)
5✔
924
            else:
925
                enum_class_name = self._create_enum_class(
5✔
926
                    table.name, col_name, list(enum_type.enums)
927
                )
928

929
            self.enum_classes[(table.name, col_name)] = enum_class_name
5✔
930

931
        # Detect check constraints for boolean and enum columns
932
        for constraint in table.constraints.copy():
5✔
933
            if isinstance(constraint, CheckConstraint):
5✔
934
                sqltext = get_compiled_expression(constraint.sqltext, self.bind)
5✔
935

936
                # Turn any integer-like column with a CheckConstraint like
937
                # "column IN (0, 1)" into a Boolean
938
                if match := _re_boolean_check_constraint.match(sqltext):
5✔
939
                    if colname_match := _re_column_name.match(match.group(1)):
5✔
940
                        colname = colname_match.group(3)
5✔
941
                        table.constraints.remove(constraint)
5✔
942
                        table.c[colname].type = Boolean()
5✔
943
                        continue
5✔
944

945
                # Turn VARCHAR columns with CHECK constraints like "column IN ('a', 'b')"
946
                # into synthetic Enum types with Python enum classes
947
                if (
5✔
948
                    "nosyntheticenums" not in self.options
949
                    and (match := _re_enum_check_constraint.match(sqltext))
950
                    and (colname_match := _re_column_name.match(match.group(1)))
951
                ):
952
                    colname = colname_match.group(3)
5✔
953
                    items = match.group(2)
5✔
954
                    if isinstance(table.c[colname].type, String) and not isinstance(
5✔
955
                        table.c[colname].type, Enum
956
                    ):
957
                        options = _re_enum_item.findall(items)
5✔
958
                        # Create Python enum class
959
                        enum_class_name = self._create_enum_class(
5✔
960
                            table.name, colname, options
961
                        )
962
                        self.enum_classes[(table.name, colname)] = enum_class_name
5✔
963
                        # Convert to Enum type but KEEP the constraint
964
                        table.c[colname].type = Enum(*options, native_enum=False)
5✔
965
                        continue
5✔
966

967
        for column in table.c:
5✔
968
            # Handle native database Enum types (e.g., PostgreSQL ENUM)
969
            if (
5✔
970
                "nonativeenums" not in self.options
971
                and isinstance(column.type, Enum)
972
                and column.type.enums
973
            ):
974
                fix_enum_column(column.name, column.type)
5✔
975

976
            # Handle ARRAY columns with Enum item types (e.g., PostgreSQL ARRAY(ENUM))
977
            elif (
5✔
978
                "nonativeenums" not in self.options
979
                and isinstance(column.type, ARRAY)
980
                and isinstance(column.type.item_type, Enum)
981
                and column.type.item_type.enums
982
            ):
983
                fix_enum_column(column.name, column.type.item_type)
5✔
984

985
            if not self.keep_dialect_types:
5✔
986
                try:
5✔
987
                    column.type = self.get_adapted_type(column.type)
5✔
988
                except CompileError:
5✔
989
                    continue
5✔
990

991
            # PostgreSQL specific fix: detect sequences from server_default
992
            if column.server_default and self.bind.dialect.name == "postgresql":
5✔
993
                if isinstance(column.server_default, DefaultClause) and isinstance(
5✔
994
                    column.server_default.arg, TextClause
995
                ):
996
                    schema, seqname = decode_postgresql_sequence(
5✔
997
                        column.server_default.arg
998
                    )
999
                    if seqname:
5✔
1000
                        # Add an explicit sequence
1001
                        if seqname != f"{column.table.name}_{column.name}_seq":
5✔
1002
                            column.default = sqlalchemy.Sequence(seqname, schema=schema)
5✔
1003

1004
                        column.server_default = None
5✔
1005

1006
    def get_adapted_type(self, coltype: Any) -> Any:
5✔
1007
        compiled_type = coltype.compile(self.bind.engine.dialect)
5✔
1008
        for supercls in coltype.__class__.__mro__:
5✔
1009
            if not supercls.__name__.startswith("_") and hasattr(
5✔
1010
                supercls, "__visit_name__"
1011
            ):
1012
                # Don't try to adapt UserDefinedType as it's not a proper column type
1013
                if supercls is UserDefinedType or issubclass(supercls, TypeDecorator):
5✔
1014
                    return coltype
5✔
1015

1016
                # Hack to fix adaptation of the Enum class which is broken since
1017
                # SQLAlchemy 1.2
1018
                kw = {}
5✔
1019
                if supercls is Enum:
5✔
1020
                    kw["name"] = coltype.name
5✔
1021
                    if coltype.schema:
5✔
1022
                        kw["schema"] = coltype.schema
5✔
1023

1024
                # Hack to fix Postgres DOMAIN type adaptation, broken as of SQLAlchemy 2.0.42
1025
                # For additional information - https://github.com/agronholm/sqlacodegen/issues/416#issuecomment-3417480599
1026
                if supercls is DOMAIN:
5✔
1027
                    if coltype.default:
5✔
1028
                        kw["default"] = coltype.default
×
1029
                    if coltype.constraint_name is not None:
5✔
1030
                        kw["constraint_name"] = coltype.constraint_name
5✔
1031
                    if coltype.not_null:
5✔
1032
                        kw["not_null"] = coltype.not_null
×
1033
                    if coltype.check is not None:
5✔
1034
                        kw["check"] = coltype.check
5✔
1035
                    if coltype.create_type:
5✔
1036
                        kw["create_type"] = coltype.create_type
5✔
1037

1038
                try:
5✔
1039
                    new_coltype = coltype.adapt(supercls)
5✔
1040
                except TypeError:
5✔
1041
                    # If the adaptation fails, don't try again
1042
                    break
5✔
1043

1044
                for key, value in kw.items():
5✔
1045
                    setattr(new_coltype, key, value)
5✔
1046

1047
                if isinstance(coltype, ARRAY):
5✔
1048
                    new_coltype.item_type = self.get_adapted_type(new_coltype.item_type)
5✔
1049

1050
                try:
5✔
1051
                    # If the adapted column type does not render the same as the
1052
                    # original, don't substitute it
1053
                    if new_coltype.compile(self.bind.engine.dialect) != compiled_type:
5✔
1054
                        break
5✔
1055
                except CompileError:
5✔
1056
                    # If the adapted column type can't be compiled, don't substitute it
1057
                    break
5✔
1058

1059
                # Stop on the first valid non-uppercase column type class
1060
                coltype = new_coltype
5✔
1061
                if supercls.__name__ != supercls.__name__.upper():
5✔
1062
                    break
5✔
1063

1064
        return coltype
5✔
1065

1066

1067
class DeclarativeGenerator(TablesGenerator):
5✔
1068
    valid_options: ClassVar[set[str]] = TablesGenerator.valid_options | {
5✔
1069
        "use_inflect",
1070
        "nojoined",
1071
        "nobidi",
1072
        "noidsuffix",
1073
        "nofknames",
1074
    }
1075

1076
    def __init__(
5✔
1077
        self,
1078
        metadata: MetaData,
1079
        bind: Connection | Engine,
1080
        options: Sequence[str],
1081
        *,
1082
        indentation: str = "    ",
1083
        base_class_name: str = "Base",
1084
        explicit_foreign_keys: bool = False,
1085
    ):
1086
        super().__init__(metadata, bind, options, indentation=indentation)
5✔
1087
        self.base_class_name: str = base_class_name
5✔
1088
        self.inflect_engine = inflect.engine()
5✔
1089
        self.explicit_foreign_keys = explicit_foreign_keys
5✔
1090

1091
    def generate_base(self) -> None:
5✔
1092
        self.base = Base(
5✔
1093
            literal_imports=[LiteralImport("sqlalchemy.orm", "DeclarativeBase")],
1094
            declarations=[
1095
                f"class {self.base_class_name}(DeclarativeBase):",
1096
                f"{self.indentation}pass",
1097
            ],
1098
            metadata_ref=f"{self.base_class_name}.metadata",
1099
        )
1100

1101
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1102
        super().collect_imports(models)
5✔
1103
        if any(isinstance(model, ModelClass) for model in models):
5✔
1104
            self.add_literal_import("sqlalchemy.orm", "Mapped")
5✔
1105
            self.add_literal_import("sqlalchemy.orm", "mapped_column")
5✔
1106

1107
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1108
        super().collect_imports_for_model(model)
5✔
1109
        if isinstance(model, ModelClass):
5✔
1110
            if model.relationships:
5✔
1111
                self.add_literal_import("sqlalchemy.orm", "relationship")
5✔
1112

1113
    def generate_models(self) -> list[Model]:
5✔
1114
        models_by_table_name: dict[str, Model] = {}
5✔
1115

1116
        # Pick association tables from the metadata into their own set, don't process
1117
        # them normally
1118
        links: defaultdict[str, list[Model]] = defaultdict(lambda: [])
5✔
1119
        for table in self.metadata.sorted_tables:
5✔
1120
            qualified_name = qualified_table_name(table)
5✔
1121

1122
            # Link tables have exactly two foreign key constraints and all columns are
1123
            # involved in them
1124
            fk_constraints = sorted(
5✔
1125
                table.foreign_key_constraints, key=get_constraint_sort_key
1126
            )
1127
            if len(fk_constraints) == 2 and all(
5✔
1128
                col.foreign_keys for col in table.columns
1129
            ):
1130
                model = models_by_table_name[qualified_name] = Model(table)
5✔
1131
                tablename = fk_constraints[0].elements[0].column.table.name
5✔
1132
                links[tablename].append(model)
5✔
1133
                continue
5✔
1134

1135
            # Only form model classes for tables that have a primary key and are not
1136
            # association tables
1137
            if not table.primary_key:
5✔
1138
                models_by_table_name[qualified_name] = Model(table)
5✔
1139
            else:
1140
                model = ModelClass(table)
5✔
1141
                models_by_table_name[qualified_name] = model
5✔
1142

1143
                # Fill in the columns
1144
                for column in table.c:
5✔
1145
                    column_attr = ColumnAttribute(model, column)
5✔
1146
                    model.columns.append(column_attr)
5✔
1147

1148
        # Add relationships
1149
        for model in models_by_table_name.values():
5✔
1150
            if isinstance(model, ModelClass):
5✔
1151
                self.generate_relationships(
5✔
1152
                    model, models_by_table_name, links[model.table.name]
1153
                )
1154

1155
        # Nest inherited classes in their superclasses to ensure proper ordering
1156
        if "nojoined" not in self.options:
5✔
1157
            for model in list(models_by_table_name.values()):
5✔
1158
                if not isinstance(model, ModelClass):
5✔
1159
                    continue
5✔
1160

1161
                pk_column_names = {col.name for col in model.table.primary_key.columns}
5✔
1162
                for constraint in model.table.foreign_key_constraints:
5✔
1163
                    if set(get_column_names(constraint)) == pk_column_names:
5✔
1164
                        target = models_by_table_name[
5✔
1165
                            qualified_table_name(constraint.elements[0].column.table)
1166
                        ]
1167
                        if isinstance(target, ModelClass):
5✔
1168
                            model.parent_class = target
5✔
1169
                            target.children.append(model)
5✔
1170

1171
        # Change base if we only have tables
1172
        if not any(
5✔
1173
            isinstance(model, ModelClass) for model in models_by_table_name.values()
1174
        ):
1175
            super().generate_base()
5✔
1176

1177
        # Collect the imports
1178
        self.collect_imports(models_by_table_name.values())
5✔
1179

1180
        # Rename models and their attributes that conflict with imports or other
1181
        # attributes
1182
        global_names = {
5✔
1183
            name for namespace in self.imports.values() for name in namespace
1184
        }
1185
        for model in models_by_table_name.values():
5✔
1186
            self.generate_model_name(model, global_names)
5✔
1187
            global_names.add(model.name)
5✔
1188

1189
        return list(models_by_table_name.values())
5✔
1190

1191
    def generate_relationships(
5✔
1192
        self,
1193
        source: ModelClass,
1194
        models_by_table_name: dict[str, Model],
1195
        association_tables: list[Model],
1196
    ) -> list[RelationshipAttribute]:
1197
        relationships: list[RelationshipAttribute] = []
5✔
1198
        reverse_relationship: RelationshipAttribute | None
1199

1200
        # Add many-to-one (and one-to-many) relationships
1201
        pk_column_names = {col.name for col in source.table.primary_key.columns}
5✔
1202
        for constraint in sorted(
5✔
1203
            source.table.foreign_key_constraints, key=get_constraint_sort_key
1204
        ):
1205
            target = models_by_table_name[
5✔
1206
                qualified_table_name(constraint.elements[0].column.table)
1207
            ]
1208
            if isinstance(target, ModelClass):
5✔
1209
                if "nojoined" not in self.options:
5✔
1210
                    if set(get_column_names(constraint)) == pk_column_names:
5✔
1211
                        parent = models_by_table_name[
5✔
1212
                            qualified_table_name(constraint.elements[0].column.table)
1213
                        ]
1214
                        if isinstance(parent, ModelClass):
5✔
1215
                            source.parent_class = parent
5✔
1216
                            parent.children.append(source)
5✔
1217
                            continue
5✔
1218

1219
                # Add uselist=False to One-to-One relationships
1220
                column_names = get_column_names(constraint)
5✔
1221
                if any(
5✔
1222
                    isinstance(c, (PrimaryKeyConstraint, UniqueConstraint))
1223
                    and {col.name for col in c.columns} == set(column_names)
1224
                    for c in constraint.table.constraints
1225
                ):
1226
                    r_type = RelationshipType.ONE_TO_ONE
5✔
1227
                else:
1228
                    r_type = RelationshipType.MANY_TO_ONE
5✔
1229

1230
                relationship = RelationshipAttribute(r_type, source, target, constraint)
5✔
1231
                source.relationships.append(relationship)
5✔
1232

1233
                # For self referential relationships, remote_side needs to be set
1234
                if source is target:
5✔
1235
                    relationship.remote_side = [
5✔
1236
                        source.get_column_attribute(col.name)
1237
                        for col in constraint.referred_table.primary_key
1238
                    ]
1239

1240
                # If the two tables share more than one foreign key constraint,
1241
                # SQLAlchemy needs an explicit primaryjoin to figure out which column(s)
1242
                # it needs
1243
                common_fk_constraints = get_common_fk_constraints(
5✔
1244
                    source.table, target.table
1245
                )
1246
                if len(common_fk_constraints) > 1:
5✔
1247
                    relationship.foreign_keys = [
5✔
1248
                        source.get_column_attribute(key)
1249
                        for key in constraint.column_keys
1250
                    ]
1251

1252
                # Generate the opposite end of the relationship in the target class
1253
                if "nobidi" not in self.options:
5✔
1254
                    if r_type is RelationshipType.MANY_TO_ONE:
5✔
1255
                        r_type = RelationshipType.ONE_TO_MANY
5✔
1256

1257
                    reverse_relationship = RelationshipAttribute(
5✔
1258
                        r_type,
1259
                        target,
1260
                        source,
1261
                        constraint,
1262
                        foreign_keys=relationship.foreign_keys,
1263
                        backref=relationship,
1264
                    )
1265
                    relationship.backref = reverse_relationship
5✔
1266
                    target.relationships.append(reverse_relationship)
5✔
1267

1268
                    # For self referential relationships, remote_side needs to be set
1269
                    if source is target:
5✔
1270
                        reverse_relationship.remote_side = [
5✔
1271
                            source.get_column_attribute(colname)
1272
                            for colname in constraint.column_keys
1273
                        ]
1274

1275
        # Add many-to-many relationships
1276
        for association_table in association_tables:
5✔
1277
            fk_constraints = sorted(
5✔
1278
                association_table.table.foreign_key_constraints,
1279
                key=get_constraint_sort_key,
1280
            )
1281
            target = models_by_table_name[
5✔
1282
                qualified_table_name(fk_constraints[1].elements[0].column.table)
1283
            ]
1284
            if isinstance(target, ModelClass):
5✔
1285
                relationship = RelationshipAttribute(
5✔
1286
                    RelationshipType.MANY_TO_MANY,
1287
                    source,
1288
                    target,
1289
                    fk_constraints[1],
1290
                    association_table,
1291
                )
1292
                source.relationships.append(relationship)
5✔
1293

1294
                # Generate the opposite end of the relationship in the target class
1295
                reverse_relationship = None
5✔
1296
                if "nobidi" not in self.options:
5✔
1297
                    reverse_relationship = RelationshipAttribute(
5✔
1298
                        RelationshipType.MANY_TO_MANY,
1299
                        target,
1300
                        source,
1301
                        fk_constraints[0],
1302
                        association_table,
1303
                        relationship,
1304
                    )
1305
                    relationship.backref = reverse_relationship
5✔
1306
                    target.relationships.append(reverse_relationship)
5✔
1307

1308
                # Add a primary/secondary join for self-referential many-to-many
1309
                # relationships
1310
                if source is target:
5✔
1311
                    both_relationships = [relationship]
5✔
1312
                    reverse_flags = [False, True]
5✔
1313
                    if reverse_relationship:
5✔
1314
                        both_relationships.append(reverse_relationship)
5✔
1315

1316
                    for relationship, reverse in zip(both_relationships, reverse_flags):
5✔
1317
                        if (
5✔
1318
                            not relationship.association_table
1319
                            or not relationship.constraint
1320
                        ):
1321
                            continue
×
1322

1323
                        constraints = sorted(
5✔
1324
                            relationship.constraint.table.foreign_key_constraints,
1325
                            key=get_constraint_sort_key,
1326
                            reverse=reverse,
1327
                        )
1328
                        pri_pairs = zip(
5✔
1329
                            get_column_names(constraints[0]), constraints[0].elements
1330
                        )
1331
                        sec_pairs = zip(
5✔
1332
                            get_column_names(constraints[1]), constraints[1].elements
1333
                        )
1334
                        relationship.primaryjoin = [
5✔
1335
                            (
1336
                                relationship.source,
1337
                                elem.column.name,
1338
                                relationship.association_table,
1339
                                col,
1340
                            )
1341
                            for col, elem in pri_pairs
1342
                        ]
1343
                        relationship.secondaryjoin = [
5✔
1344
                            (
1345
                                relationship.target,
1346
                                elem.column.name,
1347
                                relationship.association_table,
1348
                                col,
1349
                            )
1350
                            for col, elem in sec_pairs
1351
                        ]
1352

1353
        return relationships
5✔
1354

1355
    def generate_model_name(self, model: Model, global_names: set[str]) -> None:
5✔
1356
        if isinstance(model, ModelClass):
5✔
1357
            preferred_name = _re_invalid_identifier.sub("_", model.table.name)
5✔
1358
            preferred_name = "".join(
5✔
1359
                part[:1].upper() + part[1:] for part in preferred_name.split("_")
1360
            )
1361
            if "use_inflect" in self.options:
5✔
1362
                singular_name = self.inflect_engine.singular_noun(preferred_name)
5✔
1363
                if singular_name:
5✔
1364
                    preferred_name = singular_name
5✔
1365

1366
            model.name = self.find_free_name(preferred_name, global_names)
5✔
1367

1368
            # Fill in the names for column attributes
1369
            local_names: set[str] = set()
5✔
1370
            for column_attr in model.columns:
5✔
1371
                self.generate_column_attr_name(column_attr, global_names, local_names)
5✔
1372
                local_names.add(column_attr.name)
5✔
1373

1374
            # Fill in the names for relationship attributes
1375
            for relationship in model.relationships:
5✔
1376
                self.generate_relationship_name(relationship, global_names, local_names)
5✔
1377
                local_names.add(relationship.name)
5✔
1378
        else:
1379
            super().generate_model_name(model, global_names)
5✔
1380

1381
    def generate_column_attr_name(
5✔
1382
        self,
1383
        column_attr: ColumnAttribute,
1384
        global_names: set[str],
1385
        local_names: set[str],
1386
    ) -> None:
1387
        column_attr.name = self.find_free_name(
5✔
1388
            column_attr.column.name, global_names, local_names
1389
        )
1390

1391
    def generate_relationship_name(
5✔
1392
        self,
1393
        relationship: RelationshipAttribute,
1394
        global_names: set[str],
1395
        local_names: set[str],
1396
    ) -> None:
1397
        def strip_id_suffix(name: str) -> str:
5✔
1398
            # Strip _id only if at the end or followed by underscore (e.g., "course_id" -> "course", "course_id_1" -> "course_1")
1399
            # But don't strip from "parent_id1" (where id is followed by a digit without underscore)
1400
            return re.sub(r"_id(?=_|$)", "", name)
5✔
1401

1402
        def get_m2m_qualified_name(default_name: str) -> str:
5✔
1403
            """Generate qualified name for many-to-many relationship when multiple junction tables exist."""
1404
            # Check if there are multiple M2M relationships to the same target
1405
            target_m2m_relationships = [
5✔
1406
                r
1407
                for r in relationship.source.relationships
1408
                if r.target is relationship.target
1409
                and r.type == RelationshipType.MANY_TO_MANY
1410
            ]
1411

1412
            # Only use junction-based naming when there are multiple M2M to same target
1413
            if len(target_m2m_relationships) > 1:
5✔
1414
                if relationship.source is relationship.target:
5✔
1415
                    # Self-referential: use FK column name from junction table
1416
                    # (e.g., "parent_id" -> "parent", "child_id" -> "child")
1417
                    if relationship.constraint:
5✔
1418
                        column_names = [c.name for c in relationship.constraint.columns]
5✔
1419
                        if len(column_names) == 1:
5✔
1420
                            fk_qualifier = strip_id_suffix(column_names[0])
5✔
1421
                        else:
1422
                            fk_qualifier = "_".join(
×
1423
                                strip_id_suffix(col_name) for col_name in column_names
1424
                            )
1425
                        return fk_qualifier
5✔
1426
                elif relationship.association_table:
5✔
1427
                    # Normal: use junction table name as qualifier
1428
                    junction_name = relationship.association_table.table.name
5✔
1429
                    fk_qualifier = strip_id_suffix(junction_name)
5✔
1430
                    return f"{relationship.target.table.name}_{fk_qualifier}"
5✔
1431
            else:
1432
                # Single M2M: use simple name from junction table FK column
1433
                # (e.g., "right_id" -> "right" instead of "right_table")
1434
                if relationship.constraint and "noidsuffix" not in self.options:
5✔
1435
                    column_names = [c.name for c in relationship.constraint.columns]
5✔
1436
                    if len(column_names) == 1:
5✔
1437
                        stripped_name = strip_id_suffix(column_names[0])
5✔
1438
                        if stripped_name != column_names[0]:
5✔
1439
                            return stripped_name
5✔
1440

1441
            return default_name
5✔
1442

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

1447
            if len(column_names) == 1:
5✔
1448
                # Single column FK: strip _id suffix if present
1449
                fk_qualifier = strip_id_suffix(column_names[0])
5✔
1450
            else:
1451
                # Multi-column FK: concatenate all column names (strip _id from each)
1452
                fk_qualifier = "_".join(
5✔
1453
                    strip_id_suffix(col_name) for col_name in column_names
1454
                )
1455

1456
            # For self-referential relationships, don't prepend the table name
1457
            if relationship.source is relationship.target:
5✔
1458
                return fk_qualifier
×
1459
            else:
1460
                return f"{relationship.target.table.name}_{fk_qualifier}"
5✔
1461

1462
        def resolve_preferred_name() -> str:
5✔
1463
            resolved_name = relationship.target.table.name
5✔
1464

1465
            # For reverse relationships with multiple FKs to the same table, use the FK
1466
            # column name to create a more descriptive relationship name
1467
            # For M2M relationships with multiple junction tables, use the junction table name
1468
            use_fk_based_naming = "nofknames" not in self.options and (
5✔
1469
                (
1470
                    relationship.constraint
1471
                    and relationship.type
1472
                    in (RelationshipType.ONE_TO_MANY, RelationshipType.ONE_TO_ONE)
1473
                    and relationship.foreign_keys
1474
                )
1475
                or (
1476
                    relationship.type == RelationshipType.MANY_TO_MANY
1477
                    and relationship.association_table
1478
                )
1479
            )
1480

1481
            if use_fk_based_naming:
5✔
1482
                if relationship.type == RelationshipType.MANY_TO_MANY:
5✔
1483
                    resolved_name = get_m2m_qualified_name(resolved_name)
5✔
1484
                elif relationship.constraint:
5✔
1485
                    resolved_name = get_fk_qualified_name(relationship.constraint)
5✔
1486

1487
            # If there's a constraint with a single column that contains "_id", use the
1488
            # stripped version as the relationship name
1489
            elif relationship.constraint and "noidsuffix" not in self.options:
5✔
1490
                is_source = relationship.source.table is relationship.constraint.table
5✔
1491
                if is_source or relationship.type not in (
5✔
1492
                    RelationshipType.ONE_TO_ONE,
1493
                    RelationshipType.ONE_TO_MANY,
1494
                ):
1495
                    column_names = [c.name for c in relationship.constraint.columns]
5✔
1496
                    if len(column_names) == 1:
5✔
1497
                        stripped_name = strip_id_suffix(column_names[0])
5✔
1498
                        # Only use the stripped name if it actually changed (had _id in it)
1499
                        if stripped_name != column_names[0]:
5✔
1500
                            resolved_name = stripped_name
5✔
1501
                    else:
1502
                        # For composite FKs, check if there are multiple FKs to the same target
1503
                        target_relationships = [
5✔
1504
                            r
1505
                            for r in relationship.source.relationships
1506
                            if r.target is relationship.target
1507
                            and r.type == relationship.type
1508
                        ]
1509
                        if len(target_relationships) > 1:
5✔
1510
                            # Multiple FKs to same table - use concatenated column names
1511
                            resolved_name = "_".join(
5✔
1512
                                strip_id_suffix(col_name) for col_name in column_names
1513
                            )
1514

1515
            if "use_inflect" in self.options:
5✔
1516
                inflected_name: str | Literal[False]
1517
                if relationship.type in (
5✔
1518
                    RelationshipType.ONE_TO_MANY,
1519
                    RelationshipType.MANY_TO_MANY,
1520
                ):
1521
                    if not self.inflect_engine.singular_noun(resolved_name):
5✔
1522
                        resolved_name = self.inflect_engine.plural_noun(resolved_name)
5✔
1523
                else:
1524
                    inflected_name = self.inflect_engine.singular_noun(resolved_name)
5✔
1525
                    if inflected_name:
5✔
1526
                        resolved_name = inflected_name
5✔
1527

1528
            return resolved_name
5✔
1529

1530
        if (
5✔
1531
            relationship.type
1532
            in (RelationshipType.ONE_TO_MANY, RelationshipType.ONE_TO_ONE)
1533
            and relationship.source is relationship.target
1534
            and relationship.backref
1535
            and relationship.backref.name
1536
        ):
1537
            preferred_name = relationship.backref.name + "_reverse"
5✔
1538
        else:
1539
            preferred_name = resolve_preferred_name()
5✔
1540

1541
        relationship.name = self.find_free_name(
5✔
1542
            preferred_name, global_names, local_names
1543
        )
1544

1545
    def render_models(self, models: list[Model]) -> str:
5✔
1546
        rendered: list[str] = []
5✔
1547
        for model in models:
5✔
1548
            if isinstance(model, ModelClass):
5✔
1549
                rendered.append(self.render_class(model))
5✔
1550
            else:
1551
                rendered.append(f"{model.name} = {self.render_table(model.table)}")
5✔
1552

1553
        return "\n\n\n".join(rendered)
5✔
1554

1555
    def render_class(self, model: ModelClass) -> str:
5✔
1556
        sections: list[str] = []
5✔
1557

1558
        # Render class variables / special declarations
1559
        class_vars: str = self.render_class_variables(model)
5✔
1560
        if class_vars:
5✔
1561
            sections.append(class_vars)
5✔
1562

1563
        # Render column attributes
1564
        rendered_column_attributes: list[str] = []
5✔
1565
        for nullable in (False, True):
5✔
1566
            for column_attr in model.columns:
5✔
1567
                if column_attr.column.nullable is nullable:
5✔
1568
                    rendered_column_attributes.append(
5✔
1569
                        self.render_column_attribute(column_attr)
1570
                    )
1571

1572
        if rendered_column_attributes:
5✔
1573
            sections.append("\n".join(rendered_column_attributes))
5✔
1574

1575
        # Render relationship attributes
1576
        rendered_relationship_attributes: list[str] = [
5✔
1577
            self.render_relationship(relationship)
1578
            for relationship in model.relationships
1579
        ]
1580

1581
        if rendered_relationship_attributes:
5✔
1582
            sections.append("\n".join(rendered_relationship_attributes))
5✔
1583

1584
        declaration = self.render_class_declaration(model)
5✔
1585
        rendered_sections = "\n\n".join(
5✔
1586
            indent(section, self.indentation) for section in sections
1587
        )
1588
        return f"{declaration}\n{rendered_sections}"
5✔
1589

1590
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1591
        parent_class_name = (
5✔
1592
            model.parent_class.name if model.parent_class else self.base_class_name
1593
        )
1594
        return f"class {model.name}({parent_class_name}):"
5✔
1595

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

1599
        # Render constraints and indexes as __table_args__
1600
        table_args = self.render_table_args(model.table)
5✔
1601
        if table_args:
5✔
1602
            variables.append(f"__table_args__ = {table_args}")
5✔
1603

1604
        return "\n".join(variables)
5✔
1605

1606
    def render_table_args(self, table: Table) -> str:
5✔
1607
        args: list[str] = []
5✔
1608
        kwargs: dict[str, object] = {}
5✔
1609

1610
        # Render constraints
1611
        for constraint in sorted(table.constraints, key=get_constraint_sort_key):
5✔
1612
            if uses_default_name(constraint):
5✔
1613
                if isinstance(constraint, PrimaryKeyConstraint):
5✔
1614
                    continue
5✔
1615
                if (
5✔
1616
                    isinstance(constraint, (ForeignKeyConstraint, UniqueConstraint))
1617
                    and len(constraint.columns) == 1
1618
                ):
1619
                    continue
5✔
1620

1621
            args.append(self.render_constraint(constraint))
5✔
1622

1623
        # Render indexes
1624
        for index in sorted(table.indexes, key=lambda i: cast(str, i.name)):
5✔
1625
            if len(index.columns) > 1 or not uses_default_name(index):
5✔
1626
                args.append(self.render_index(index))
5✔
1627

1628
        if table.schema:
5✔
1629
            kwargs["schema"] = table.schema
5✔
1630

1631
        if table.comment:
5✔
1632
            kwargs["comment"] = table.comment
5✔
1633

1634
        # add info + dialect kwargs for dict context (__table_args__) (opt-in)
1635
        if self.include_dialect_options_and_info:
5✔
1636
            self._add_dialect_kwargs_and_info(table, kwargs, values_for_dict=True)
5✔
1637

1638
        if kwargs:
5✔
1639
            formatted_kwargs = pformat(kwargs)
5✔
1640
            if not args:
5✔
1641
                return formatted_kwargs
5✔
1642
            else:
1643
                args.append(formatted_kwargs)
5✔
1644

1645
        if args:
5✔
1646
            rendered_args = f",\n{self.indentation}".join(args)
5✔
1647
            if len(args) == 1:
5✔
1648
                rendered_args += ","
5✔
1649

1650
            return f"(\n{self.indentation}{rendered_args}\n)"
5✔
1651
        else:
1652
            return ""
5✔
1653

1654
    def render_column_python_type(self, column: Column[Any]) -> str:
5✔
1655
        def get_type_qualifiers() -> tuple[str, TypeEngine[Any], str]:
5✔
1656
            column_type = column.type
5✔
1657
            pre: list[str] = []
5✔
1658
            post_size = 0
5✔
1659
            if column.nullable:
5✔
1660
                self.add_literal_import("typing", "Optional")
5✔
1661
                pre.append("Optional[")
5✔
1662
                post_size += 1
5✔
1663

1664
            if isinstance(column_type, ARRAY):
5✔
1665
                dim = getattr(column_type, "dimensions", None) or 1
5✔
1666
                pre.extend("list[" for _ in range(dim))
5✔
1667
                post_size += dim
5✔
1668

1669
                column_type = column_type.item_type
5✔
1670

1671
            return "".join(pre), column_type, "]" * post_size
5✔
1672

1673
        def render_python_type(column_type: TypeEngine[Any]) -> str:
5✔
1674
            # Check if this is an enum column with a Python enum class
1675
            if isinstance(column_type, Enum):
5✔
1676
                table_name = column.table.name
5✔
1677
                column_name = column.name
5✔
1678
                if (table_name, column_name) in self.enum_classes:
5✔
1679
                    enum_class_name = self.enum_classes[(table_name, column_name)]
5✔
1680
                    return enum_class_name
5✔
1681

1682
            if isinstance(column_type, DOMAIN):
5✔
1683
                column_type = column_type.data_type
5✔
1684

1685
            try:
5✔
1686
                python_type = column_type.python_type
5✔
1687
                python_type_module = python_type.__module__
5✔
1688
                python_type_name = python_type.__name__
5✔
1689
            except NotImplementedError:
5✔
1690
                self.add_literal_import("typing", "Any")
5✔
1691
                return "Any"
5✔
1692

1693
            if python_type_module == "builtins":
5✔
1694
                return python_type_name
5✔
1695

1696
            self.add_module_import(python_type_module)
5✔
1697
            return f"{python_type_module}.{python_type_name}"
5✔
1698

1699
        pre, col_type, post = get_type_qualifiers()
5✔
1700
        column_python_type = f"{pre}{render_python_type(col_type)}{post}"
5✔
1701
        return column_python_type
5✔
1702

1703
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1704
        column = column_attr.column
5✔
1705
        rendered_column = self.render_column(column, column_attr.name != column.name)
5✔
1706
        rendered_column_python_type = self.render_column_python_type(column)
5✔
1707

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

1710
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1711
        kwargs = self.render_relationship_arguments(relationship)
5✔
1712
        annotation = self.render_relationship_annotation(relationship)
5✔
1713
        rendered_relationship = render_callable(
5✔
1714
            "relationship", repr(relationship.target.name), kwargs=kwargs
1715
        )
1716
        return f"{relationship.name}: Mapped[{annotation}] = {rendered_relationship}"
5✔
1717

1718
    def render_relationship_annotation(
5✔
1719
        self, relationship: RelationshipAttribute
1720
    ) -> str:
1721
        match relationship.type:
5✔
1722
            case RelationshipType.ONE_TO_MANY:
5✔
1723
                return f"list[{relationship.target.name!r}]"
5✔
1724
            case RelationshipType.ONE_TO_ONE | RelationshipType.MANY_TO_ONE:
5✔
1725
                if relationship.constraint and any(
5✔
1726
                    col.nullable for col in relationship.constraint.columns
1727
                ):
1728
                    self.add_literal_import("typing", "Optional")
5✔
1729
                    return f"Optional[{relationship.target.name!r}]"
5✔
1730
                else:
1731
                    return f"'{relationship.target.name}'"
5✔
1732
            case RelationshipType.MANY_TO_MANY:
5✔
1733
                return f"list[{relationship.target.name!r}]"
5✔
1734

1735
    def render_relationship_arguments(
5✔
1736
        self, relationship: RelationshipAttribute
1737
    ) -> Mapping[str, Any]:
1738
        def render_column_attrs(column_attrs: list[ColumnAttribute]) -> str:
5✔
1739
            rendered = []
5✔
1740
            for attr in column_attrs:
5✔
1741
                if attr.model is relationship.source:
5✔
1742
                    rendered.append(attr.name)
5✔
1743
                else:
1744
                    rendered.append(repr(f"{attr.model.name}.{attr.name}"))
×
1745

1746
            return "[" + ", ".join(rendered) + "]"
5✔
1747

1748
        def render_foreign_keys(column_attrs: list[ColumnAttribute]) -> str:
5✔
1749
            rendered = []
5✔
1750
            render_as_string = False
5✔
1751
            # Assume that column_attrs are all in relationship.source or none
1752
            for attr in column_attrs:
5✔
1753
                if not self.explicit_foreign_keys and attr.model is relationship.source:
5✔
1754
                    rendered.append(attr.name)
5✔
1755
                else:
1756
                    rendered.append(f"{attr.model.name}.{attr.name}")
5✔
1757
                    render_as_string = True
5✔
1758

1759
            if render_as_string:
5✔
1760
                return "'[" + ", ".join(rendered) + "]'"
5✔
1761
            else:
1762
                return "[" + ", ".join(rendered) + "]"
5✔
1763

1764
        def render_join(terms: list[JoinType]) -> str:
5✔
1765
            rendered_joins = []
5✔
1766
            for source, source_col, target, target_col in terms:
5✔
1767
                rendered = f"lambda: {source.name}.{source_col} == {target.name}."
5✔
1768
                if target.__class__ is Model:
5✔
1769
                    rendered += "c."
5✔
1770

1771
                rendered += str(target_col)
5✔
1772
                rendered_joins.append(rendered)
5✔
1773

1774
            if len(rendered_joins) > 1:
5✔
1775
                rendered = ", ".join(rendered_joins)
×
1776
                return f"and_({rendered})"
×
1777
            else:
1778
                return rendered_joins[0]
5✔
1779

1780
        # Render keyword arguments
1781
        kwargs: dict[str, Any] = {}
5✔
1782
        if relationship.type is RelationshipType.ONE_TO_ONE and relationship.constraint:
5✔
1783
            if relationship.constraint.referred_table is relationship.source.table:
5✔
1784
                kwargs["uselist"] = False
5✔
1785

1786
        # Add the "secondary" keyword for many-to-many relationships
1787
        if relationship.association_table:
5✔
1788
            table_ref = relationship.association_table.table.name
5✔
1789
            if relationship.association_table.schema:
5✔
1790
                table_ref = f"{relationship.association_table.schema}.{table_ref}"
5✔
1791

1792
            kwargs["secondary"] = repr(table_ref)
5✔
1793

1794
        if relationship.remote_side:
5✔
1795
            kwargs["remote_side"] = render_column_attrs(relationship.remote_side)
5✔
1796

1797
        if relationship.foreign_keys:
5✔
1798
            kwargs["foreign_keys"] = render_foreign_keys(relationship.foreign_keys)
5✔
1799

1800
        if relationship.primaryjoin:
5✔
1801
            kwargs["primaryjoin"] = render_join(relationship.primaryjoin)
5✔
1802

1803
        if relationship.secondaryjoin:
5✔
1804
            kwargs["secondaryjoin"] = render_join(relationship.secondaryjoin)
5✔
1805

1806
        if relationship.backref:
5✔
1807
            kwargs["back_populates"] = repr(relationship.backref.name)
5✔
1808

1809
        return kwargs
5✔
1810

1811

1812
class DataclassGenerator(DeclarativeGenerator):
5✔
1813
    def __init__(
5✔
1814
        self,
1815
        metadata: MetaData,
1816
        bind: Connection | Engine,
1817
        options: Sequence[str],
1818
        *,
1819
        indentation: str = "    ",
1820
        base_class_name: str = "Base",
1821
        quote_annotations: bool = False,
1822
        metadata_key: str = "sa",
1823
    ):
1824
        super().__init__(
5✔
1825
            metadata,
1826
            bind,
1827
            options,
1828
            indentation=indentation,
1829
            base_class_name=base_class_name,
1830
        )
1831
        self.metadata_key: str = metadata_key
5✔
1832
        self.quote_annotations: bool = quote_annotations
5✔
1833

1834
    def generate_base(self) -> None:
5✔
1835
        self.base = Base(
5✔
1836
            literal_imports=[
1837
                LiteralImport("sqlalchemy.orm", "DeclarativeBase"),
1838
                LiteralImport("sqlalchemy.orm", "MappedAsDataclass"),
1839
            ],
1840
            declarations=[
1841
                (f"class {self.base_class_name}(MappedAsDataclass, DeclarativeBase):"),
1842
                f"{self.indentation}pass",
1843
            ],
1844
            metadata_ref=f"{self.base_class_name}.metadata",
1845
        )
1846

1847

1848
class SQLModelGenerator(DeclarativeGenerator):
5✔
1849
    def __init__(
5✔
1850
        self,
1851
        metadata: MetaData,
1852
        bind: Connection | Engine,
1853
        options: Sequence[str],
1854
        *,
1855
        indentation: str = "    ",
1856
        base_class_name: str = "SQLModel",
1857
    ):
1858
        super().__init__(
5✔
1859
            metadata,
1860
            bind,
1861
            options,
1862
            indentation=indentation,
1863
            base_class_name=base_class_name,
1864
            explicit_foreign_keys=True,
1865
        )
1866

1867
    @property
5✔
1868
    def views_supported(self) -> bool:
5✔
1869
        return False
×
1870

1871
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
1872
        self.add_import(Column)
5✔
1873
        return render_callable("Column", *args, kwargs=kwargs)
5✔
1874

1875
    def generate_base(self) -> None:
5✔
1876
        self.base = Base(
5✔
1877
            literal_imports=[],
1878
            declarations=[],
1879
            metadata_ref="",
1880
        )
1881

1882
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1883
        super(DeclarativeGenerator, self).collect_imports(models)
5✔
1884
        if any(isinstance(model, ModelClass) for model in models):
5✔
1885
            self.remove_literal_import("sqlalchemy", "MetaData")
5✔
1886
            self.add_literal_import("sqlmodel", "SQLModel")
5✔
1887
            self.add_literal_import("sqlmodel", "Field")
5✔
1888

1889
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1890
        super(DeclarativeGenerator, self).collect_imports_for_model(model)
5✔
1891
        if isinstance(model, ModelClass):
5✔
1892
            for column_attr in model.columns:
5✔
1893
                if column_attr.column.nullable:
5✔
1894
                    self.add_literal_import("typing", "Optional")
5✔
1895
                    break
5✔
1896

1897
            if model.relationships:
5✔
1898
                self.add_literal_import("sqlmodel", "Relationship")
5✔
1899

1900
    def render_module_variables(self, models: list[Model]) -> str:
5✔
1901
        declarations: list[str] = []
5✔
1902
        if any(not isinstance(model, ModelClass) for model in models):
5✔
1903
            if self.base.table_metadata_declaration is not None:
×
1904
                declarations.append(self.base.table_metadata_declaration)
×
1905

1906
        return "\n".join(declarations)
5✔
1907

1908
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1909
        if model.parent_class:
5✔
1910
            parent = model.parent_class.name
×
1911
        else:
1912
            parent = self.base_class_name
5✔
1913

1914
        superclass_part = f"({parent}, table=True)"
5✔
1915
        return f"class {model.name}{superclass_part}:"
5✔
1916

1917
    def render_class_variables(self, model: ModelClass) -> str:
5✔
1918
        variables = []
5✔
1919

1920
        if model.table.name != model.name.lower():
5✔
1921
            variables.append(f"__tablename__ = {model.table.name!r}")
5✔
1922

1923
        # Render constraints and indexes as __table_args__
1924
        table_args = self.render_table_args(model.table)
5✔
1925
        if table_args:
5✔
1926
            variables.append(f"__table_args__ = {table_args}")
5✔
1927

1928
        return "\n".join(variables)
5✔
1929

1930
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1931
        column = column_attr.column
5✔
1932
        rendered_column = self.render_column(column, True)
5✔
1933
        rendered_column_python_type = self.render_column_python_type(column)
5✔
1934

1935
        kwargs: dict[str, Any] = {}
5✔
1936
        if column.nullable:
5✔
1937
            kwargs["default"] = None
5✔
1938
        kwargs["sa_column"] = f"{rendered_column}"
5✔
1939

1940
        rendered_field = render_callable("Field", kwargs=kwargs)
5✔
1941

1942
        return f"{column_attr.name}: {rendered_column_python_type} = {rendered_field}"
5✔
1943

1944
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1945
        kwargs = self.render_relationship_arguments(relationship)
5✔
1946
        annotation = self.render_relationship_annotation(relationship)
5✔
1947

1948
        native_kwargs: dict[str, Any] = {}
5✔
1949
        non_native_kwargs: dict[str, Any] = {}
5✔
1950
        for key, value in kwargs.items():
5✔
1951
            # The following keyword arguments are natively supported in Relationship
1952
            if key in ("back_populates", "cascade_delete", "passive_deletes"):
5✔
1953
                native_kwargs[key] = value
5✔
1954
            else:
1955
                non_native_kwargs[key] = value
5✔
1956

1957
        if non_native_kwargs:
5✔
1958
            native_kwargs["sa_relationship_kwargs"] = (
5✔
1959
                "{"
1960
                + ", ".join(
1961
                    f"{key!r}: {value}" for key, value in non_native_kwargs.items()
1962
                )
1963
                + "}"
1964
            )
1965

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

© 2026 Coveralls, Inc