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

agronholm / sqlacodegen / 20546461175

28 Dec 2025 12:37AM UTC coverage: 96.918% (-0.4%) from 97.36%
20546461175

Pull #446

github

web-flow
Merge c9eafe8a0 into 90831a745
Pull Request #446: support native python enum generation

110 of 119 new or added lines in 4 files covered. (92.44%)

1 existing line in 1 file now uncovered.

1604 of 1655 relevant lines covered (96.92%)

4.84 hits per line

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

95.83
/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, 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
        "noenums",
127
        "include_dialect_options",
128
        "keep_dialect_types",
129
    }
130
    stdlib_module_names: ClassVar[set[str]] = get_stdlib_module_names()
5✔
131

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

335
        for package in sorted(self.imports):
5✔
336
            imports_list = sorted(self.imports[package])
5✔
337
            imports = ", ".join(imports_list)
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
        if index.unique:
5✔
429
            kwargs["unique"] = True
5✔
430

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

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

474
        if show_name:
5✔
475
            args.append(repr(column.name))
5✔
476

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

482
        for fk in dedicated_fks:
5✔
483
            args.append(self.render_constraint(fk))
5✔
484

485
        if column.default:
5✔
486
            args.append(repr(column.default))
5✔
487

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

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

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

512
            computed_kwargs = {}
5✔
513
            if column.server_default.persisted is not None:
5✔
514
                computed_kwargs["persisted"] = column.server_default.persisted
5✔
515

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

524
        comment = getattr(column, "comment", None)
5✔
525
        if comment:
5✔
526
            kwargs["comment"] = repr(comment)
5✔
527

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

532
        return self.render_column_callable(is_table, *args, **kwargs)
5✔
533

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

541
    def render_column_type(
5✔
542
        self, coltype: TypeEngine[Any], column: Column[Any] | None = None
543
    ) -> str:
544
        # Check if this is an enum column with a Python enum class
545
        if isinstance(coltype, Enum) and column is not None:
5✔
546
            table_name = column.table.name
5✔
547
            column_name = column.name
5✔
548
            if (table_name, column_name) in self.enum_classes:
5✔
549
                enum_class_name = self.enum_classes[(table_name, column_name)]
5✔
550
                # Import SQLAlchemy Enum (will be handled in collect_imports)
551
                self.add_import(Enum)
5✔
552
                # Return the Python enum class as the type parameter
553
                return f"Enum({enum_class_name})"
5✔
554

555
        args = []
5✔
556
        kwargs: dict[str, Any] = {}
5✔
557
        sig = inspect.signature(coltype.__class__.__init__)
5✔
558
        defaults = {param.name: param.default for param in sig.parameters.values()}
5✔
559
        missing = object()
5✔
560
        use_kwargs = False
5✔
561
        for param in list(sig.parameters.values())[1:]:
5✔
562
            # Remove annoyances like _warn_on_bytestring
563
            if param.name.startswith("_"):
5✔
564
                continue
5✔
565
            elif param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD):
5✔
566
                use_kwargs = True
5✔
567
                continue
5✔
568

569
            value = getattr(coltype, param.name, missing)
5✔
570

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

581
            default = defaults.get(param.name, missing)
5✔
582
            if isinstance(value, TextClause):
5✔
583
                self.add_literal_import("sqlalchemy", "text")
5✔
584
                rendered_value = render_callable("text", repr(value.text))
5✔
585
            else:
586
                rendered_value = repr(value)
5✔
587

588
            if value is missing or value == default:
5✔
589
                use_kwargs = True
5✔
590
            elif use_kwargs:
5✔
591
                kwargs[param.name] = rendered_value
5✔
592
            else:
593
                args.append(rendered_value)
5✔
594

595
        vararg = next(
5✔
596
            (
597
                param.name
598
                for param in sig.parameters.values()
599
                if param.kind is Parameter.VAR_POSITIONAL
600
            ),
601
            None,
602
        )
603
        if vararg and hasattr(coltype, vararg):
5✔
604
            varargs_repr = [repr(arg) for arg in getattr(coltype, vararg)]
5✔
605
            args.extend(varargs_repr)
5✔
606

607
        # These arguments cannot be autodetected from the Enum initializer
608
        if isinstance(coltype, Enum):
5✔
609
            for colname in "name", "schema":
5✔
610
                if (value := getattr(coltype, colname)) is not None:
5✔
UNCOV
611
                    kwargs[colname] = repr(value)
×
612

613
        if isinstance(coltype, (JSONB, JSON)):
5✔
614
            # Remove astext_type if it's the default
615
            if (
5✔
616
                isinstance(coltype.astext_type, Text)
617
                and coltype.astext_type.length is None
618
            ):
619
                del kwargs["astext_type"]
5✔
620

621
        if args or kwargs:
5✔
622
            return render_callable(coltype.__class__.__name__, *args, kwargs=kwargs)
5✔
623
        else:
624
            return coltype.__class__.__name__
5✔
625

626
    def render_constraint(self, constraint: Constraint | ForeignKey) -> str:
5✔
627
        def add_fk_options(*opts: Any) -> None:
5✔
628
            args.extend(repr(opt) for opt in opts)
5✔
629
            for attr in "ondelete", "onupdate", "deferrable", "initially", "match":
5✔
630
                value = getattr(constraint, attr, None)
5✔
631
                if value:
5✔
632
                    kwargs[attr] = repr(value)
5✔
633

634
        args: list[str] = []
5✔
635
        kwargs: dict[str, Any] = {}
5✔
636
        if isinstance(constraint, ForeignKey):
5✔
637
            remote_column = (
5✔
638
                f"{constraint.column.table.fullname}.{constraint.column.name}"
639
            )
640
            add_fk_options(remote_column)
5✔
641
        elif isinstance(constraint, ForeignKeyConstraint):
5✔
642
            local_columns = get_column_names(constraint)
5✔
643
            remote_columns = [
5✔
644
                f"{fk.column.table.fullname}.{fk.column.name}"
645
                for fk in constraint.elements
646
            ]
647
            add_fk_options(local_columns, remote_columns)
5✔
648
        elif isinstance(constraint, CheckConstraint):
5✔
649
            args.append(repr(get_compiled_expression(constraint.sqltext, self.bind)))
5✔
650
        elif isinstance(constraint, (UniqueConstraint, PrimaryKeyConstraint)):
5✔
651
            args.extend(repr(col.name) for col in constraint.columns)
5✔
652
        else:
653
            raise TypeError(
×
654
                f"Cannot render constraint of type {constraint.__class__.__name__}"
655
            )
656

657
        if isinstance(constraint, Constraint) and not uses_default_name(constraint):
5✔
658
            kwargs["name"] = repr(constraint.name)
5✔
659

660
        return render_callable(constraint.__class__.__name__, *args, kwargs=kwargs)
5✔
661

662
    def _add_dialect_kwargs_and_info(
5✔
663
        self, obj: Any, target_kwargs: dict[str, object], *, values_for_dict: bool
664
    ) -> None:
665
        """
666
        Merge SchemaItem-like object's .info and .dialect_kwargs into target_kwargs.
667
        - values_for_dict=True: keep raw values so pretty-printer emits repr() (for __table_args__ dict)
668
        - values_for_dict=False: set values to repr() strings (for callable kwargs)
669
        """
670
        info_dict = getattr(obj, "info", None)
5✔
671
        if info_dict:
5✔
672
            target_kwargs["info"] = info_dict if values_for_dict else repr(info_dict)
5✔
673

674
        dialect_keys: list[str]
675
        try:
5✔
676
            dialect_keys = sorted(getattr(obj, "dialect_kwargs"))
5✔
677
        except Exception:
×
678
            return
×
679

680
        dialect_kwargs = getattr(obj, "dialect_kwargs", {})
5✔
681
        for key in dialect_keys:
5✔
682
            try:
5✔
683
                value = dialect_kwargs[key]
5✔
684
            except Exception:
×
685
                continue
×
686

687
            # Render values:
688
            # - callable context (values_for_dict=False): produce a string expression.
689
            #   primitives use repr(value); custom objects stringify then repr().
690
            # - dict context (values_for_dict=True): pass raw primitives / str;
691
            #   custom objects become str(value) so pformat quotes them.
692
            if values_for_dict:
5✔
693
                if isinstance(value, type(None) | bool | int | float):
5✔
694
                    target_kwargs[key] = value
×
695
                elif isinstance(value, str | dict | list):
5✔
696
                    target_kwargs[key] = value
5✔
697
                else:
698
                    target_kwargs[key] = str(value)
5✔
699
            else:
700
                if isinstance(
5✔
701
                    value, type(None) | bool | int | float | str | dict | list
702
                ):
703
                    target_kwargs[key] = repr(value)
5✔
704
                else:
705
                    target_kwargs[key] = repr(str(value))
5✔
706

707
    def should_ignore_table(self, table: Table) -> bool:
5✔
708
        # Support for Alembic and sqlalchemy-migrate -- never expose the schema version
709
        # tables
710
        return table.name in ("alembic_version", "migrate_version")
5✔
711

712
    def find_free_name(
5✔
713
        self, name: str, global_names: set[str], local_names: Collection[str] = ()
714
    ) -> str:
715
        """
716
        Generate an attribute name that does not clash with other local or global names.
717
        """
718
        name = name.strip()
5✔
719
        assert name, "Identifier cannot be empty"
5✔
720
        name = _re_invalid_identifier.sub("_", name)
5✔
721
        if name[0].isdigit():
5✔
722
            name = "_" + name
5✔
723
        elif iskeyword(name) or name == "metadata":
5✔
724
            name += "_"
5✔
725

726
        original = name
5✔
727
        for i in count():
5✔
728
            if name not in global_names and name not in local_names:
5✔
729
                break
5✔
730

731
            name = original + (str(i) if i else "_")
5✔
732

733
        return name
5✔
734

735
    def _enum_name_to_class_name(self, enum_name: str) -> str:
5✔
736
        """Convert a database enum name to a Python class name (PascalCase)."""
737
        parts = []
5✔
738
        for part in enum_name.split("_"):
5✔
739
            if part:
5✔
740
                parts.append(part.capitalize())
5✔
741
        return "".join(parts)
5✔
742

743
    def _create_enum_class(
5✔
744
        self, table_name: str, column_name: str, values: list[str]
745
    ) -> str:
746
        """
747
        Create a Python enum class name and register it.
748

749
        Returns the enum class name to use in generated code.
750
        """
751
        # Generate enum class name from table and column names
752
        # Convert to PascalCase: user_status -> UserStatus
753
        parts = []
5✔
754
        for part in table_name.split("_"):
5✔
755
            if part:
5✔
756
                parts.append(part.capitalize())
5✔
757
        for part in column_name.split("_"):
5✔
758
            if part:
5✔
759
                parts.append(part.capitalize())
5✔
760

761
        base_name = "".join(parts)
5✔
762

763
        # Ensure uniqueness
764
        enum_class_name = base_name
5✔
765
        counter = 1
5✔
766
        while enum_class_name in self.enum_values:
5✔
767
            # Check if it's the same enum (same values)
NEW
768
            if self.enum_values[enum_class_name] == values:
×
769
                # Reuse existing enum class
NEW
770
                return enum_class_name
×
NEW
771
            enum_class_name = f"{base_name}{counter}"
×
NEW
772
            counter += 1
×
773

774
        # Register the new enum class
775
        self.enum_values[enum_class_name] = values
5✔
776
        return enum_class_name
5✔
777

778
    def render_enum_classes(self) -> str:
5✔
779
        """Render Python enum class definitions."""
780
        if not self.enum_values:
5✔
781
            return ""
5✔
782

783
        self.add_module_import("enum")
5✔
784

785
        enum_defs = []
5✔
786
        for enum_class_name, values in sorted(self.enum_values.items()):
5✔
787
            # Create enum members with valid Python identifiers
788
            members = []
5✔
789
            for value in values:
5✔
790
                # Unescape SQL escape sequences (e.g., \' -> ')
791
                # The value from the CHECK constraint has SQL escaping
792
                unescaped_value = value.replace("\\'", "'").replace("\\\\", "\\")
5✔
793

794
                # Create a valid identifier from the enum value
795
                member_name = _re_invalid_identifier.sub("_", unescaped_value).upper()
5✔
796
                if not member_name:
5✔
NEW
797
                    member_name = "EMPTY"
×
798
                elif member_name[0].isdigit():
5✔
NEW
799
                    member_name = "_" + member_name
×
800
                elif iskeyword(member_name):
5✔
NEW
801
                    member_name += "_"
×
802

803
                # Re-escape for Python string literal
804
                python_escaped = unescaped_value.replace("\\", "\\\\").replace(
5✔
805
                    "'", "\\'"
806
                )
807
                members.append(f"    {member_name} = '{python_escaped}'")
5✔
808

809
            enum_def = f"class {enum_class_name}(str, enum.Enum):\n" + "\n".join(
5✔
810
                members
811
            )
812
            enum_defs.append(enum_def)
5✔
813

814
        return "\n\n\n".join(enum_defs)
5✔
815

816
    def fix_column_types(self, table: Table) -> None:
5✔
817
        """Adjust the reflected column types."""
818
        # Detect check constraints for boolean and enum columns
819
        for constraint in table.constraints.copy():
5✔
820
            if isinstance(constraint, CheckConstraint):
5✔
821
                sqltext = get_compiled_expression(constraint.sqltext, self.bind)
5✔
822

823
                # Turn any integer-like column with a CheckConstraint like
824
                # "column IN (0, 1)" into a Boolean
825
                if match := _re_boolean_check_constraint.match(sqltext):
5✔
826
                    if colname_match := _re_column_name.match(match.group(1)):
5✔
827
                        colname = colname_match.group(3)
5✔
828
                        table.constraints.remove(constraint)
5✔
829
                        table.c[colname].type = Boolean()
5✔
830
                        continue
5✔
831

832
                # Turn any string-type column with a CheckConstraint like
833
                # "column IN (...)" into an Enum
834
                if match := _re_enum_check_constraint.match(sqltext):
5✔
835
                    if colname_match := _re_column_name.match(match.group(1)):
5✔
836
                        colname = colname_match.group(3)
5✔
837
                        items = match.group(2)
5✔
838
                        if isinstance(table.c[colname].type, String):
5✔
839
                            table.constraints.remove(constraint)
5✔
840
                            if not isinstance(table.c[colname].type, Enum):
5✔
841
                                options = _re_enum_item.findall(items)
5✔
842
                                # Create Python enum class (unless noenums option is set)
843
                                if "noenums" not in self.options:
5✔
844
                                    enum_class_name = self._create_enum_class(
5✔
845
                                        table.name, colname, options
846
                                    )
847
                                    # Store the enum for this column
848
                                    self.enum_classes[(table.name, colname)] = (
5✔
849
                                        enum_class_name
850
                                    )
851
                                table.c[colname].type = Enum(
5✔
852
                                    *options, native_enum=False
853
                                )
854

855
                            continue
5✔
856

857
        for column in table.c:
5✔
858
            # Handle native database Enum types (e.g., PostgreSQL ENUM)
859
            if (
5✔
860
                "noenums" not in self.options
861
                and isinstance(column.type, Enum)
862
                and column.type.enums
863
            ):
864
                if column.type.name:
5✔
865
                    # Named enum - create shared enum class if not already created
866
                    if (table.name, column.name) not in self.enum_classes:
5✔
867
                        # Check if we've already created an enum for this name
868
                        existing_class = None
5✔
869
                        for (t, c), cls in self.enum_classes.items():
5✔
870
                            if cls == self._enum_name_to_class_name(column.type.name):
5✔
871
                                existing_class = cls
5✔
872
                                break
5✔
873

874
                        if existing_class:
5✔
875
                            enum_class_name = existing_class
5✔
876
                        else:
877
                            # Create new enum class from the enum's name
878
                            enum_class_name = self._enum_name_to_class_name(
5✔
879
                                column.type.name
880
                            )
881
                            # Register the enum values if not already registered
882
                            if enum_class_name not in self.enum_values:
5✔
883
                                self.enum_values[enum_class_name] = list(
5✔
884
                                    column.type.enums
885
                                )
886

887
                        self.enum_classes[(table.name, column.name)] = enum_class_name
5✔
888
                else:
889
                    # Unnamed enum - create enum class per column
890
                    if (table.name, column.name) not in self.enum_classes:
5✔
NEW
891
                        enum_class_name = self._create_enum_class(
×
892
                            table.name, column.name, list(column.type.enums)
893
                        )
NEW
894
                        self.enum_classes[(table.name, column.name)] = enum_class_name
×
895

896
            if not self.keep_dialect_types:
5✔
897
                try:
5✔
898
                    column.type = self.get_adapted_type(column.type)
5✔
899
                except CompileError:
5✔
900
                    continue
5✔
901

902
            # PostgreSQL specific fix: detect sequences from server_default
903
            if column.server_default and self.bind.dialect.name == "postgresql":
5✔
904
                if isinstance(column.server_default, DefaultClause) and isinstance(
5✔
905
                    column.server_default.arg, TextClause
906
                ):
907
                    schema, seqname = decode_postgresql_sequence(
5✔
908
                        column.server_default.arg
909
                    )
910
                    if seqname:
5✔
911
                        # Add an explicit sequence
912
                        if seqname != f"{column.table.name}_{column.name}_seq":
5✔
913
                            column.default = sqlalchemy.Sequence(seqname, schema=schema)
5✔
914

915
                        column.server_default = None
5✔
916

917
    def get_adapted_type(self, coltype: Any) -> Any:
5✔
918
        compiled_type = coltype.compile(self.bind.engine.dialect)
5✔
919
        for supercls in coltype.__class__.__mro__:
5✔
920
            if not supercls.__name__.startswith("_") and hasattr(
5✔
921
                supercls, "__visit_name__"
922
            ):
923
                # Don't try to adapt UserDefinedType as it's not a proper column type
924
                if supercls is UserDefinedType or issubclass(supercls, TypeDecorator):
5✔
925
                    return coltype
5✔
926

927
                # Hack to fix adaptation of the Enum class which is broken since
928
                # SQLAlchemy 1.2
929
                kw = {}
5✔
930
                if supercls is Enum:
5✔
931
                    kw["name"] = coltype.name
5✔
932
                    if coltype.schema:
5✔
933
                        kw["schema"] = coltype.schema
5✔
934

935
                # Hack to fix Postgres DOMAIN type adaptation, broken as of SQLAlchemy 2.0.42
936
                # For additional information - https://github.com/agronholm/sqlacodegen/issues/416#issuecomment-3417480599
937
                if supercls is DOMAIN:
5✔
938
                    if coltype.default:
5✔
939
                        kw["default"] = coltype.default
×
940
                    if coltype.constraint_name is not None:
5✔
941
                        kw["constraint_name"] = coltype.constraint_name
5✔
942
                    if coltype.not_null:
5✔
943
                        kw["not_null"] = coltype.not_null
×
944
                    if coltype.check is not None:
5✔
945
                        kw["check"] = coltype.check
5✔
946
                    if coltype.create_type:
5✔
947
                        kw["create_type"] = coltype.create_type
5✔
948

949
                try:
5✔
950
                    new_coltype = coltype.adapt(supercls)
5✔
951
                except TypeError:
5✔
952
                    # If the adaptation fails, don't try again
953
                    break
5✔
954

955
                for key, value in kw.items():
5✔
956
                    setattr(new_coltype, key, value)
5✔
957

958
                if isinstance(coltype, ARRAY):
5✔
959
                    new_coltype.item_type = self.get_adapted_type(new_coltype.item_type)
5✔
960

961
                try:
5✔
962
                    # If the adapted column type does not render the same as the
963
                    # original, don't substitute it
964
                    if new_coltype.compile(self.bind.engine.dialect) != compiled_type:
5✔
965
                        break
5✔
966
                except CompileError:
5✔
967
                    # If the adapted column type can't be compiled, don't substitute it
968
                    break
5✔
969

970
                # Stop on the first valid non-uppercase column type class
971
                coltype = new_coltype
5✔
972
                if supercls.__name__ != supercls.__name__.upper():
5✔
973
                    break
5✔
974

975
        return coltype
5✔
976

977

978
class DeclarativeGenerator(TablesGenerator):
5✔
979
    valid_options: ClassVar[set[str]] = TablesGenerator.valid_options | {
5✔
980
        "use_inflect",
981
        "nojoined",
982
        "nobidi",
983
        "noidsuffix",
984
    }
985

986
    def __init__(
5✔
987
        self,
988
        metadata: MetaData,
989
        bind: Connection | Engine,
990
        options: Sequence[str],
991
        *,
992
        indentation: str = "    ",
993
        base_class_name: str = "Base",
994
    ):
995
        super().__init__(metadata, bind, options, indentation=indentation)
5✔
996
        self.base_class_name: str = base_class_name
5✔
997
        self.inflect_engine = inflect.engine()
5✔
998

999
    def generate_base(self) -> None:
5✔
1000
        self.base = Base(
5✔
1001
            literal_imports=[LiteralImport("sqlalchemy.orm", "DeclarativeBase")],
1002
            declarations=[
1003
                f"class {self.base_class_name}(DeclarativeBase):",
1004
                f"{self.indentation}pass",
1005
            ],
1006
            metadata_ref=f"{self.base_class_name}.metadata",
1007
        )
1008

1009
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1010
        super().collect_imports(models)
5✔
1011
        if any(isinstance(model, ModelClass) for model in models):
5✔
1012
            self.add_literal_import("sqlalchemy.orm", "Mapped")
5✔
1013
            self.add_literal_import("sqlalchemy.orm", "mapped_column")
5✔
1014

1015
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1016
        super().collect_imports_for_model(model)
5✔
1017
        if isinstance(model, ModelClass):
5✔
1018
            if model.relationships:
5✔
1019
                self.add_literal_import("sqlalchemy.orm", "relationship")
5✔
1020

1021
    def generate_models(self) -> list[Model]:
5✔
1022
        models_by_table_name: dict[str, Model] = {}
5✔
1023

1024
        # Pick association tables from the metadata into their own set, don't process
1025
        # them normally
1026
        links: defaultdict[str, list[Model]] = defaultdict(lambda: [])
5✔
1027
        for table in self.metadata.sorted_tables:
5✔
1028
            qualified_name = qualified_table_name(table)
5✔
1029

1030
            # Link tables have exactly two foreign key constraints and all columns are
1031
            # involved in them
1032
            fk_constraints = sorted(
5✔
1033
                table.foreign_key_constraints, key=get_constraint_sort_key
1034
            )
1035
            if len(fk_constraints) == 2 and all(
5✔
1036
                col.foreign_keys for col in table.columns
1037
            ):
1038
                model = models_by_table_name[qualified_name] = Model(table)
5✔
1039
                tablename = fk_constraints[0].elements[0].column.table.name
5✔
1040
                links[tablename].append(model)
5✔
1041
                continue
5✔
1042

1043
            # Only form model classes for tables that have a primary key and are not
1044
            # association tables
1045
            if not table.primary_key:
5✔
1046
                models_by_table_name[qualified_name] = Model(table)
5✔
1047
            else:
1048
                model = ModelClass(table)
5✔
1049
                models_by_table_name[qualified_name] = model
5✔
1050

1051
                # Fill in the columns
1052
                for column in table.c:
5✔
1053
                    column_attr = ColumnAttribute(model, column)
5✔
1054
                    model.columns.append(column_attr)
5✔
1055

1056
        # Add relationships
1057
        for model in models_by_table_name.values():
5✔
1058
            if isinstance(model, ModelClass):
5✔
1059
                self.generate_relationships(
5✔
1060
                    model, models_by_table_name, links[model.table.name]
1061
                )
1062

1063
        # Nest inherited classes in their superclasses to ensure proper ordering
1064
        if "nojoined" not in self.options:
5✔
1065
            for model in list(models_by_table_name.values()):
5✔
1066
                if not isinstance(model, ModelClass):
5✔
1067
                    continue
5✔
1068

1069
                pk_column_names = {col.name for col in model.table.primary_key.columns}
5✔
1070
                for constraint in model.table.foreign_key_constraints:
5✔
1071
                    if set(get_column_names(constraint)) == pk_column_names:
5✔
1072
                        target = models_by_table_name[
5✔
1073
                            qualified_table_name(constraint.elements[0].column.table)
1074
                        ]
1075
                        if isinstance(target, ModelClass):
5✔
1076
                            model.parent_class = target
5✔
1077
                            target.children.append(model)
5✔
1078

1079
        # Change base if we only have tables
1080
        if not any(
5✔
1081
            isinstance(model, ModelClass) for model in models_by_table_name.values()
1082
        ):
1083
            super().generate_base()
5✔
1084

1085
        # Collect the imports
1086
        self.collect_imports(models_by_table_name.values())
5✔
1087

1088
        # Rename models and their attributes that conflict with imports or other
1089
        # attributes
1090
        global_names = {
5✔
1091
            name for namespace in self.imports.values() for name in namespace
1092
        }
1093
        for model in models_by_table_name.values():
5✔
1094
            self.generate_model_name(model, global_names)
5✔
1095
            global_names.add(model.name)
5✔
1096

1097
        return list(models_by_table_name.values())
5✔
1098

1099
    def generate_relationships(
5✔
1100
        self,
1101
        source: ModelClass,
1102
        models_by_table_name: dict[str, Model],
1103
        association_tables: list[Model],
1104
    ) -> list[RelationshipAttribute]:
1105
        relationships: list[RelationshipAttribute] = []
5✔
1106
        reverse_relationship: RelationshipAttribute | None
1107

1108
        # Add many-to-one (and one-to-many) relationships
1109
        pk_column_names = {col.name for col in source.table.primary_key.columns}
5✔
1110
        for constraint in sorted(
5✔
1111
            source.table.foreign_key_constraints, key=get_constraint_sort_key
1112
        ):
1113
            target = models_by_table_name[
5✔
1114
                qualified_table_name(constraint.elements[0].column.table)
1115
            ]
1116
            if isinstance(target, ModelClass):
5✔
1117
                if "nojoined" not in self.options:
5✔
1118
                    if set(get_column_names(constraint)) == pk_column_names:
5✔
1119
                        parent = models_by_table_name[
5✔
1120
                            qualified_table_name(constraint.elements[0].column.table)
1121
                        ]
1122
                        if isinstance(parent, ModelClass):
5✔
1123
                            source.parent_class = parent
5✔
1124
                            parent.children.append(source)
5✔
1125
                            continue
5✔
1126

1127
                # Add uselist=False to One-to-One relationships
1128
                column_names = get_column_names(constraint)
5✔
1129
                if any(
5✔
1130
                    isinstance(c, (PrimaryKeyConstraint, UniqueConstraint))
1131
                    and {col.name for col in c.columns} == set(column_names)
1132
                    for c in constraint.table.constraints
1133
                ):
1134
                    r_type = RelationshipType.ONE_TO_ONE
5✔
1135
                else:
1136
                    r_type = RelationshipType.MANY_TO_ONE
5✔
1137

1138
                relationship = RelationshipAttribute(r_type, source, target, constraint)
5✔
1139
                source.relationships.append(relationship)
5✔
1140

1141
                # For self referential relationships, remote_side needs to be set
1142
                if source is target:
5✔
1143
                    relationship.remote_side = [
5✔
1144
                        source.get_column_attribute(col.name)
1145
                        for col in constraint.referred_table.primary_key
1146
                    ]
1147

1148
                # If the two tables share more than one foreign key constraint,
1149
                # SQLAlchemy needs an explicit primaryjoin to figure out which column(s)
1150
                # it needs
1151
                common_fk_constraints = get_common_fk_constraints(
5✔
1152
                    source.table, target.table
1153
                )
1154
                if len(common_fk_constraints) > 1:
5✔
1155
                    relationship.foreign_keys = [
5✔
1156
                        source.get_column_attribute(key)
1157
                        for key in constraint.column_keys
1158
                    ]
1159

1160
                # Generate the opposite end of the relationship in the target class
1161
                if "nobidi" not in self.options:
5✔
1162
                    if r_type is RelationshipType.MANY_TO_ONE:
5✔
1163
                        r_type = RelationshipType.ONE_TO_MANY
5✔
1164

1165
                    reverse_relationship = RelationshipAttribute(
5✔
1166
                        r_type,
1167
                        target,
1168
                        source,
1169
                        constraint,
1170
                        foreign_keys=relationship.foreign_keys,
1171
                        backref=relationship,
1172
                    )
1173
                    relationship.backref = reverse_relationship
5✔
1174
                    target.relationships.append(reverse_relationship)
5✔
1175

1176
                    # For self referential relationships, remote_side needs to be set
1177
                    if source is target:
5✔
1178
                        reverse_relationship.remote_side = [
5✔
1179
                            source.get_column_attribute(colname)
1180
                            for colname in constraint.column_keys
1181
                        ]
1182

1183
        # Add many-to-many relationships
1184
        for association_table in association_tables:
5✔
1185
            fk_constraints = sorted(
5✔
1186
                association_table.table.foreign_key_constraints,
1187
                key=get_constraint_sort_key,
1188
            )
1189
            target = models_by_table_name[
5✔
1190
                qualified_table_name(fk_constraints[1].elements[0].column.table)
1191
            ]
1192
            if isinstance(target, ModelClass):
5✔
1193
                relationship = RelationshipAttribute(
5✔
1194
                    RelationshipType.MANY_TO_MANY,
1195
                    source,
1196
                    target,
1197
                    fk_constraints[1],
1198
                    association_table,
1199
                )
1200
                source.relationships.append(relationship)
5✔
1201

1202
                # Generate the opposite end of the relationship in the target class
1203
                reverse_relationship = None
5✔
1204
                if "nobidi" not in self.options:
5✔
1205
                    reverse_relationship = RelationshipAttribute(
5✔
1206
                        RelationshipType.MANY_TO_MANY,
1207
                        target,
1208
                        source,
1209
                        fk_constraints[0],
1210
                        association_table,
1211
                        relationship,
1212
                    )
1213
                    relationship.backref = reverse_relationship
5✔
1214
                    target.relationships.append(reverse_relationship)
5✔
1215

1216
                # Add a primary/secondary join for self-referential many-to-many
1217
                # relationships
1218
                if source is target:
5✔
1219
                    both_relationships = [relationship]
5✔
1220
                    reverse_flags = [False, True]
5✔
1221
                    if reverse_relationship:
5✔
1222
                        both_relationships.append(reverse_relationship)
5✔
1223

1224
                    for relationship, reverse in zip(both_relationships, reverse_flags):
5✔
1225
                        if (
5✔
1226
                            not relationship.association_table
1227
                            or not relationship.constraint
1228
                        ):
1229
                            continue
×
1230

1231
                        constraints = sorted(
5✔
1232
                            relationship.constraint.table.foreign_key_constraints,
1233
                            key=get_constraint_sort_key,
1234
                            reverse=reverse,
1235
                        )
1236
                        pri_pairs = zip(
5✔
1237
                            get_column_names(constraints[0]), constraints[0].elements
1238
                        )
1239
                        sec_pairs = zip(
5✔
1240
                            get_column_names(constraints[1]), constraints[1].elements
1241
                        )
1242
                        relationship.primaryjoin = [
5✔
1243
                            (
1244
                                relationship.source,
1245
                                elem.column.name,
1246
                                relationship.association_table,
1247
                                col,
1248
                            )
1249
                            for col, elem in pri_pairs
1250
                        ]
1251
                        relationship.secondaryjoin = [
5✔
1252
                            (
1253
                                relationship.target,
1254
                                elem.column.name,
1255
                                relationship.association_table,
1256
                                col,
1257
                            )
1258
                            for col, elem in sec_pairs
1259
                        ]
1260

1261
        return relationships
5✔
1262

1263
    def generate_model_name(self, model: Model, global_names: set[str]) -> None:
5✔
1264
        if isinstance(model, ModelClass):
5✔
1265
            preferred_name = _re_invalid_identifier.sub("_", model.table.name)
5✔
1266
            preferred_name = "".join(
5✔
1267
                part[:1].upper() + part[1:] for part in preferred_name.split("_")
1268
            )
1269
            if "use_inflect" in self.options:
5✔
1270
                singular_name = self.inflect_engine.singular_noun(preferred_name)
5✔
1271
                if singular_name:
5✔
1272
                    preferred_name = singular_name
5✔
1273

1274
            model.name = self.find_free_name(preferred_name, global_names)
5✔
1275

1276
            # Fill in the names for column attributes
1277
            local_names: set[str] = set()
5✔
1278
            for column_attr in model.columns:
5✔
1279
                self.generate_column_attr_name(column_attr, global_names, local_names)
5✔
1280
                local_names.add(column_attr.name)
5✔
1281

1282
            # Fill in the names for relationship attributes
1283
            for relationship in model.relationships:
5✔
1284
                self.generate_relationship_name(relationship, global_names, local_names)
5✔
1285
                local_names.add(relationship.name)
5✔
1286
        else:
1287
            super().generate_model_name(model, global_names)
5✔
1288

1289
    def generate_column_attr_name(
5✔
1290
        self,
1291
        column_attr: ColumnAttribute,
1292
        global_names: set[str],
1293
        local_names: set[str],
1294
    ) -> None:
1295
        column_attr.name = self.find_free_name(
5✔
1296
            column_attr.column.name, global_names, local_names
1297
        )
1298

1299
    def generate_relationship_name(
5✔
1300
        self,
1301
        relationship: RelationshipAttribute,
1302
        global_names: set[str],
1303
        local_names: set[str],
1304
    ) -> None:
1305
        # Self referential reverse relationships
1306
        preferred_name: str
1307
        if (
5✔
1308
            relationship.type
1309
            in (RelationshipType.ONE_TO_MANY, RelationshipType.ONE_TO_ONE)
1310
            and relationship.source is relationship.target
1311
            and relationship.backref
1312
            and relationship.backref.name
1313
        ):
1314
            preferred_name = relationship.backref.name + "_reverse"
5✔
1315
        else:
1316
            preferred_name = relationship.target.table.name
5✔
1317

1318
            # If there's a constraint with a single column that ends with "_id", use the
1319
            # preceding part as the relationship name
1320
            if relationship.constraint and "noidsuffix" not in self.options:
5✔
1321
                is_source = relationship.source.table is relationship.constraint.table
5✔
1322
                if is_source or relationship.type not in (
5✔
1323
                    RelationshipType.ONE_TO_ONE,
1324
                    RelationshipType.ONE_TO_MANY,
1325
                ):
1326
                    column_names = [c.name for c in relationship.constraint.columns]
5✔
1327
                    if len(column_names) == 1 and column_names[0].endswith("_id"):
5✔
1328
                        preferred_name = column_names[0][:-3]
5✔
1329

1330
            if "use_inflect" in self.options:
5✔
1331
                inflected_name: str | Literal[False]
1332
                if relationship.type in (
5✔
1333
                    RelationshipType.ONE_TO_MANY,
1334
                    RelationshipType.MANY_TO_MANY,
1335
                ):
1336
                    if not self.inflect_engine.singular_noun(preferred_name):
5✔
1337
                        preferred_name = self.inflect_engine.plural_noun(preferred_name)
×
1338
                else:
1339
                    inflected_name = self.inflect_engine.singular_noun(preferred_name)
5✔
1340
                    if inflected_name:
5✔
1341
                        preferred_name = inflected_name
5✔
1342

1343
        relationship.name = self.find_free_name(
5✔
1344
            preferred_name, global_names, local_names
1345
        )
1346

1347
    def render_models(self, models: list[Model]) -> str:
5✔
1348
        rendered: list[str] = []
5✔
1349
        for model in models:
5✔
1350
            if isinstance(model, ModelClass):
5✔
1351
                rendered.append(self.render_class(model))
5✔
1352
            else:
1353
                rendered.append(f"{model.name} = {self.render_table(model.table)}")
5✔
1354

1355
        return "\n\n\n".join(rendered)
5✔
1356

1357
    def render_class(self, model: ModelClass) -> str:
5✔
1358
        sections: list[str] = []
5✔
1359

1360
        # Render class variables / special declarations
1361
        class_vars: str = self.render_class_variables(model)
5✔
1362
        if class_vars:
5✔
1363
            sections.append(class_vars)
5✔
1364

1365
        # Render column attributes
1366
        rendered_column_attributes: list[str] = []
5✔
1367
        for nullable in (False, True):
5✔
1368
            for column_attr in model.columns:
5✔
1369
                if column_attr.column.nullable is nullable:
5✔
1370
                    rendered_column_attributes.append(
5✔
1371
                        self.render_column_attribute(column_attr)
1372
                    )
1373

1374
        if rendered_column_attributes:
5✔
1375
            sections.append("\n".join(rendered_column_attributes))
5✔
1376

1377
        # Render relationship attributes
1378
        rendered_relationship_attributes: list[str] = [
5✔
1379
            self.render_relationship(relationship)
1380
            for relationship in model.relationships
1381
        ]
1382

1383
        if rendered_relationship_attributes:
5✔
1384
            sections.append("\n".join(rendered_relationship_attributes))
5✔
1385

1386
        declaration = self.render_class_declaration(model)
5✔
1387
        rendered_sections = "\n\n".join(
5✔
1388
            indent(section, self.indentation) for section in sections
1389
        )
1390
        return f"{declaration}\n{rendered_sections}"
5✔
1391

1392
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1393
        parent_class_name = (
5✔
1394
            model.parent_class.name if model.parent_class else self.base_class_name
1395
        )
1396
        return f"class {model.name}({parent_class_name}):"
5✔
1397

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

1401
        # Render constraints and indexes as __table_args__
1402
        table_args = self.render_table_args(model.table)
5✔
1403
        if table_args:
5✔
1404
            variables.append(f"__table_args__ = {table_args}")
5✔
1405

1406
        return "\n".join(variables)
5✔
1407

1408
    def render_table_args(self, table: Table) -> str:
5✔
1409
        args: list[str] = []
5✔
1410
        kwargs: dict[str, object] = {}
5✔
1411

1412
        # Render constraints
1413
        for constraint in sorted(table.constraints, key=get_constraint_sort_key):
5✔
1414
            if uses_default_name(constraint):
5✔
1415
                if isinstance(constraint, PrimaryKeyConstraint):
5✔
1416
                    continue
5✔
1417
                if (
5✔
1418
                    isinstance(constraint, (ForeignKeyConstraint, UniqueConstraint))
1419
                    and len(constraint.columns) == 1
1420
                ):
1421
                    continue
5✔
1422

1423
            args.append(self.render_constraint(constraint))
5✔
1424

1425
        # Render indexes
1426
        for index in sorted(table.indexes, key=lambda i: cast(str, i.name)):
5✔
1427
            if len(index.columns) > 1 or not uses_default_name(index):
5✔
1428
                args.append(self.render_index(index))
5✔
1429

1430
        if table.schema:
5✔
1431
            kwargs["schema"] = table.schema
5✔
1432

1433
        if table.comment:
5✔
1434
            kwargs["comment"] = table.comment
5✔
1435

1436
        # add info + dialect kwargs for dict context (__table_args__) (opt-in)
1437
        if self.include_dialect_options_and_info:
5✔
1438
            self._add_dialect_kwargs_and_info(table, kwargs, values_for_dict=True)
5✔
1439

1440
        if kwargs:
5✔
1441
            formatted_kwargs = pformat(kwargs)
5✔
1442
            if not args:
5✔
1443
                return formatted_kwargs
5✔
1444
            else:
1445
                args.append(formatted_kwargs)
5✔
1446

1447
        if args:
5✔
1448
            rendered_args = f",\n{self.indentation}".join(args)
5✔
1449
            if len(args) == 1:
5✔
1450
                rendered_args += ","
5✔
1451

1452
            return f"(\n{self.indentation}{rendered_args}\n)"
5✔
1453
        else:
1454
            return ""
5✔
1455

1456
    def render_column_python_type(self, column: Column[Any]) -> str:
5✔
1457
        def get_type_qualifiers() -> tuple[str, TypeEngine[Any], str]:
5✔
1458
            column_type = column.type
5✔
1459
            pre: list[str] = []
5✔
1460
            post_size = 0
5✔
1461
            if column.nullable:
5✔
1462
                self.add_literal_import("typing", "Optional")
5✔
1463
                pre.append("Optional[")
5✔
1464
                post_size += 1
5✔
1465

1466
            if isinstance(column_type, ARRAY):
5✔
1467
                dim = getattr(column_type, "dimensions", None) or 1
5✔
1468
                pre.extend("list[" for _ in range(dim))
5✔
1469
                post_size += dim
5✔
1470

1471
                column_type = column_type.item_type
5✔
1472

1473
            return "".join(pre), column_type, "]" * post_size
5✔
1474

1475
        def render_python_type(column_type: TypeEngine[Any]) -> str:
5✔
1476
            # Check if this is an enum column with a Python enum class
1477
            if isinstance(column_type, Enum):
5✔
1478
                table_name = column.table.name
5✔
1479
                column_name = column.name
5✔
1480
                if (table_name, column_name) in self.enum_classes:
5✔
1481
                    enum_class_name = self.enum_classes[(table_name, column_name)]
5✔
1482
                    return enum_class_name
5✔
1483

1484
            if isinstance(column_type, DOMAIN):
5✔
1485
                column_type = column_type.data_type
5✔
1486

1487
            try:
5✔
1488
                python_type = column_type.python_type
5✔
1489
                python_type_module = python_type.__module__
5✔
1490
                python_type_name = python_type.__name__
5✔
1491
            except NotImplementedError:
5✔
1492
                self.add_literal_import("typing", "Any")
5✔
1493
                return "Any"
5✔
1494

1495
            if python_type_module == "builtins":
5✔
1496
                return python_type_name
5✔
1497

1498
            self.add_module_import(python_type_module)
5✔
1499
            return f"{python_type_module}.{python_type_name}"
5✔
1500

1501
        pre, col_type, post = get_type_qualifiers()
5✔
1502
        column_python_type = f"{pre}{render_python_type(col_type)}{post}"
5✔
1503
        return column_python_type
5✔
1504

1505
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1506
        column = column_attr.column
5✔
1507
        rendered_column = self.render_column(column, column_attr.name != column.name)
5✔
1508
        rendered_column_python_type = self.render_column_python_type(column)
5✔
1509

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

1512
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1513
        def render_column_attrs(column_attrs: list[ColumnAttribute]) -> str:
5✔
1514
            rendered = []
5✔
1515
            for attr in column_attrs:
5✔
1516
                if attr.model is relationship.source:
5✔
1517
                    rendered.append(attr.name)
5✔
1518
                else:
1519
                    rendered.append(repr(f"{attr.model.name}.{attr.name}"))
×
1520

1521
            return "[" + ", ".join(rendered) + "]"
5✔
1522

1523
        def render_foreign_keys(column_attrs: list[ColumnAttribute]) -> str:
5✔
1524
            rendered = []
5✔
1525
            render_as_string = False
5✔
1526
            # Assume that column_attrs are all in relationship.source or none
1527
            for attr in column_attrs:
5✔
1528
                if attr.model is relationship.source:
5✔
1529
                    rendered.append(attr.name)
5✔
1530
                else:
1531
                    rendered.append(f"{attr.model.name}.{attr.name}")
5✔
1532
                    render_as_string = True
5✔
1533

1534
            if render_as_string:
5✔
1535
                return "'[" + ", ".join(rendered) + "]'"
5✔
1536
            else:
1537
                return "[" + ", ".join(rendered) + "]"
5✔
1538

1539
        def render_join(terms: list[JoinType]) -> str:
5✔
1540
            rendered_joins = []
5✔
1541
            for source, source_col, target, target_col in terms:
5✔
1542
                rendered = f"lambda: {source.name}.{source_col} == {target.name}."
5✔
1543
                if target.__class__ is Model:
5✔
1544
                    rendered += "c."
5✔
1545

1546
                rendered += str(target_col)
5✔
1547
                rendered_joins.append(rendered)
5✔
1548

1549
            if len(rendered_joins) > 1:
5✔
1550
                rendered = ", ".join(rendered_joins)
×
1551
                return f"and_({rendered})"
×
1552
            else:
1553
                return rendered_joins[0]
5✔
1554

1555
        # Render keyword arguments
1556
        kwargs: dict[str, Any] = {}
5✔
1557
        if relationship.type is RelationshipType.ONE_TO_ONE and relationship.constraint:
5✔
1558
            if relationship.constraint.referred_table is relationship.source.table:
5✔
1559
                kwargs["uselist"] = False
5✔
1560

1561
        # Add the "secondary" keyword for many-to-many relationships
1562
        if relationship.association_table:
5✔
1563
            table_ref = relationship.association_table.table.name
5✔
1564
            if relationship.association_table.schema:
5✔
1565
                table_ref = f"{relationship.association_table.schema}.{table_ref}"
5✔
1566

1567
            kwargs["secondary"] = repr(table_ref)
5✔
1568

1569
        if relationship.remote_side:
5✔
1570
            kwargs["remote_side"] = render_column_attrs(relationship.remote_side)
5✔
1571

1572
        if relationship.foreign_keys:
5✔
1573
            kwargs["foreign_keys"] = render_foreign_keys(relationship.foreign_keys)
5✔
1574

1575
        if relationship.primaryjoin:
5✔
1576
            kwargs["primaryjoin"] = render_join(relationship.primaryjoin)
5✔
1577

1578
        if relationship.secondaryjoin:
5✔
1579
            kwargs["secondaryjoin"] = render_join(relationship.secondaryjoin)
5✔
1580

1581
        if relationship.backref:
5✔
1582
            kwargs["back_populates"] = repr(relationship.backref.name)
5✔
1583

1584
        rendered_relationship = render_callable(
5✔
1585
            "relationship", repr(relationship.target.name), kwargs=kwargs
1586
        )
1587

1588
        relationship_type: str
1589
        if relationship.type == RelationshipType.ONE_TO_MANY:
5✔
1590
            relationship_type = f"list['{relationship.target.name}']"
5✔
1591
        elif relationship.type in (
5✔
1592
            RelationshipType.ONE_TO_ONE,
1593
            RelationshipType.MANY_TO_ONE,
1594
        ):
1595
            relationship_type = f"'{relationship.target.name}'"
5✔
1596
            if relationship.constraint and any(
5✔
1597
                col.nullable for col in relationship.constraint.columns
1598
            ):
1599
                self.add_literal_import("typing", "Optional")
5✔
1600
                relationship_type = f"Optional[{relationship_type}]"
5✔
1601
        elif relationship.type == RelationshipType.MANY_TO_MANY:
5✔
1602
            relationship_type = f"list['{relationship.target.name}']"
5✔
1603
        else:
1604
            self.add_literal_import("typing", "Any")
×
1605
            relationship_type = "Any"
×
1606

1607
        return (
5✔
1608
            f"{relationship.name}: Mapped[{relationship_type}] "
1609
            f"= {rendered_relationship}"
1610
        )
1611

1612

1613
class DataclassGenerator(DeclarativeGenerator):
5✔
1614
    def __init__(
5✔
1615
        self,
1616
        metadata: MetaData,
1617
        bind: Connection | Engine,
1618
        options: Sequence[str],
1619
        *,
1620
        indentation: str = "    ",
1621
        base_class_name: str = "Base",
1622
        quote_annotations: bool = False,
1623
        metadata_key: str = "sa",
1624
    ):
1625
        super().__init__(
5✔
1626
            metadata,
1627
            bind,
1628
            options,
1629
            indentation=indentation,
1630
            base_class_name=base_class_name,
1631
        )
1632
        self.metadata_key: str = metadata_key
5✔
1633
        self.quote_annotations: bool = quote_annotations
5✔
1634

1635
    def generate_base(self) -> None:
5✔
1636
        self.base = Base(
5✔
1637
            literal_imports=[
1638
                LiteralImport("sqlalchemy.orm", "DeclarativeBase"),
1639
                LiteralImport("sqlalchemy.orm", "MappedAsDataclass"),
1640
            ],
1641
            declarations=[
1642
                (f"class {self.base_class_name}(MappedAsDataclass, DeclarativeBase):"),
1643
                f"{self.indentation}pass",
1644
            ],
1645
            metadata_ref=f"{self.base_class_name}.metadata",
1646
        )
1647

1648

1649
class SQLModelGenerator(DeclarativeGenerator):
5✔
1650
    def __init__(
5✔
1651
        self,
1652
        metadata: MetaData,
1653
        bind: Connection | Engine,
1654
        options: Sequence[str],
1655
        *,
1656
        indentation: str = "    ",
1657
        base_class_name: str = "SQLModel",
1658
    ):
1659
        super().__init__(
5✔
1660
            metadata,
1661
            bind,
1662
            options,
1663
            indentation=indentation,
1664
            base_class_name=base_class_name,
1665
        )
1666

1667
    @property
5✔
1668
    def views_supported(self) -> bool:
5✔
1669
        return False
×
1670

1671
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
1672
        self.add_import(Column)
5✔
1673
        return render_callable("Column", *args, kwargs=kwargs)
5✔
1674

1675
    def generate_base(self) -> None:
5✔
1676
        self.base = Base(
5✔
1677
            literal_imports=[],
1678
            declarations=[],
1679
            metadata_ref="",
1680
        )
1681

1682
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1683
        super(DeclarativeGenerator, self).collect_imports(models)
5✔
1684
        if any(isinstance(model, ModelClass) for model in models):
5✔
1685
            self.remove_literal_import("sqlalchemy", "MetaData")
5✔
1686
            self.add_literal_import("sqlmodel", "SQLModel")
5✔
1687
            self.add_literal_import("sqlmodel", "Field")
5✔
1688

1689
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1690
        super(DeclarativeGenerator, self).collect_imports_for_model(model)
5✔
1691
        if isinstance(model, ModelClass):
5✔
1692
            for column_attr in model.columns:
5✔
1693
                if column_attr.column.nullable:
5✔
1694
                    self.add_literal_import("typing", "Optional")
5✔
1695
                    break
5✔
1696

1697
            if model.relationships:
5✔
1698
                self.add_literal_import("sqlmodel", "Relationship")
5✔
1699

1700
    def render_module_variables(self, models: list[Model]) -> str:
5✔
1701
        declarations: list[str] = []
5✔
1702
        if any(not isinstance(model, ModelClass) for model in models):
5✔
1703
            if self.base.table_metadata_declaration is not None:
×
1704
                declarations.append(self.base.table_metadata_declaration)
×
1705

1706
        return "\n".join(declarations)
5✔
1707

1708
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1709
        if model.parent_class:
5✔
1710
            parent = model.parent_class.name
×
1711
        else:
1712
            parent = self.base_class_name
5✔
1713

1714
        superclass_part = f"({parent}, table=True)"
5✔
1715
        return f"class {model.name}{superclass_part}:"
5✔
1716

1717
    def render_class_variables(self, model: ModelClass) -> str:
5✔
1718
        variables = []
5✔
1719

1720
        if model.table.name != model.name.lower():
5✔
1721
            variables.append(f"__tablename__ = {model.table.name!r}")
5✔
1722

1723
        # Render constraints and indexes as __table_args__
1724
        table_args = self.render_table_args(model.table)
5✔
1725
        if table_args:
5✔
1726
            variables.append(f"__table_args__ = {table_args}")
5✔
1727

1728
        return "\n".join(variables)
5✔
1729

1730
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1731
        column = column_attr.column
5✔
1732
        rendered_column = self.render_column(column, True)
5✔
1733
        rendered_column_python_type = self.render_column_python_type(column)
5✔
1734

1735
        kwargs: dict[str, Any] = {}
5✔
1736
        if column.nullable:
5✔
1737
            kwargs["default"] = None
5✔
1738
        kwargs["sa_column"] = f"{rendered_column}"
5✔
1739

1740
        rendered_field = render_callable("Field", kwargs=kwargs)
5✔
1741

1742
        return f"{column_attr.name}: {rendered_column_python_type} = {rendered_field}"
5✔
1743

1744
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1745
        rendered = super().render_relationship(relationship).partition(" = ")[2]
5✔
1746
        args = self.render_relationship_args(rendered)
5✔
1747
        kwargs: dict[str, Any] = {}
5✔
1748
        annotation = repr(relationship.target.name)
5✔
1749

1750
        if relationship.type in (
5✔
1751
            RelationshipType.ONE_TO_MANY,
1752
            RelationshipType.MANY_TO_MANY,
1753
        ):
1754
            annotation = f"list[{annotation}]"
5✔
1755
        else:
1756
            self.add_literal_import("typing", "Optional")
5✔
1757
            annotation = f"Optional[{annotation}]"
5✔
1758

1759
        rendered_field = render_callable("Relationship", *args, kwargs=kwargs)
5✔
1760
        return f"{relationship.name}: {annotation} = {rendered_field}"
5✔
1761

1762
    def render_relationship_args(self, arguments: str) -> list[str]:
5✔
1763
        argument_list = arguments.split(",")
5✔
1764
        # delete ')' and ' ' from args
1765
        argument_list[-1] = argument_list[-1][:-1]
5✔
1766
        argument_list = [argument[1:] for argument in argument_list]
5✔
1767

1768
        rendered_args: list[str] = []
5✔
1769
        for arg in argument_list:
5✔
1770
            if "back_populates" in arg:
5✔
1771
                rendered_args.append(arg)
5✔
1772
            if "uselist=False" in arg:
5✔
1773
                rendered_args.append("sa_relationship_kwargs={'uselist': False}")
5✔
1774

1775
        return rendered_args
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