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

agronholm / sqlacodegen / 20851781149

09 Jan 2026 12:22PM UTC coverage: 97.471% (+0.1%) from 97.36%
20851781149

Pull #446

github

web-flow
Merge 2bc74b4c2 into 638861c40
Pull Request #446: Support native python enum generation

144 of 147 new or added lines in 5 files covered. (97.96%)

13 existing lines in 1 file now uncovered.

1619 of 1661 relevant lines covered (97.47%)

4.87 hits per line

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

96.52
/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
        "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_list = sorted(self.imports[package])
5✔
338
            imports = ", ".join(imports_list)
5✔
339

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

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

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

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

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

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

367
        return models
5✔
368

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

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

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

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

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

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

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

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

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

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

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

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

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

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

426
    def render_index(self, index: Index) -> str:
5✔
427
        extra_args = [repr(col.name) for col in index.columns]
5✔
428
        kwargs = {}
5✔
429
        if index.unique:
5✔
430
            kwargs["unique"] = True
5✔
431

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

568
            value = getattr(column_type, param.name, missing)
5✔
569

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

732
        return name
5✔
733

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

738
    def _create_enum_class(
5✔
739
        self, table_name: str, column_name: str, values: list[str]
740
    ) -> str:
741
        """
742
        Create a Python enum class name and register it.
743

744
        Returns the enum class name to use in generated code.
745
        """
746
        # Generate enum class name from table and column names
747
        # Convert to PascalCase: user_status -> UserStatus
748
        parts = []
5✔
749
        for part in table_name.split("_"):
5✔
750
            if part:
5✔
751
                parts.append(part.capitalize())
5✔
752

753
        for part in column_name.split("_"):
5✔
754
            if part:
5✔
755
                parts.append(part.capitalize())
5✔
756

757
        base_name = "".join(parts)
5✔
758

759
        # Ensure uniqueness
760
        enum_class_name = base_name
5✔
761
        counter = 1
5✔
762
        while enum_class_name in self.enum_values:
5✔
763
            # Check if it's the same enum (same values)
764
            if self.enum_values[enum_class_name] == values:
5✔
765
                # Reuse existing enum class
766
                return enum_class_name
5✔
767

768
            enum_class_name = f"{base_name}{counter}"
5✔
769
            counter += 1
5✔
770

771
        # Register the new enum class
772
        self.enum_values[enum_class_name] = values
5✔
773
        return enum_class_name
5✔
774

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

780
        self.add_module_import("enum")
5✔
781

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

791
                # Create a valid identifier from the enum value
792
                member_name = _re_invalid_identifier.sub("_", unescaped_value).upper()
5✔
793
                if not member_name:
5✔
NEW
794
                    member_name = "EMPTY"
×
795
                elif member_name[0].isdigit():
5✔
NEW
796
                    member_name = "_" + member_name
×
797
                elif iskeyword(member_name):
5✔
NEW
798
                    member_name += "_"
×
799
                #
800
                # # Re-escape for Python string literal
801
                # python_escaped = unescaped_value.replace("\\", "\\\\").replace(
802
                #     "'", "\\'"
803
                # )
804
                members.append(f"    {member_name} = {unescaped_value!r}")
5✔
805

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

811
        return "\n\n\n".join(enum_defs)
5✔
812

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

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

829
                # Turn VARCHAR columns with CHECK constraints like "column IN ('a', 'b')"
830
                # into synthetic Enum types with Python enum classes
831
                if (
5✔
832
                    "nosyntheticenums" not in self.options
833
                    and (match := _re_enum_check_constraint.match(sqltext))
834
                    and (colname_match := _re_column_name.match(match.group(1)))
835
                ):
836
                    colname = colname_match.group(3)
5✔
837
                    items = match.group(2)
5✔
838
                    if isinstance(table.c[colname].type, String) and not isinstance(
5✔
839
                        table.c[colname].type, Enum
840
                    ):
841
                        options = _re_enum_item.findall(items)
5✔
842
                        # Create Python enum class
843
                        enum_class_name = self._create_enum_class(
5✔
844
                            table.name, colname, options
845
                        )
846
                        self.enum_classes[(table.name, colname)] = enum_class_name
5✔
847
                        # Convert to Enum type but KEEP the constraint
848
                        table.c[colname].type = Enum(*options, native_enum=False)
5✔
849
                        continue
5✔
850

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

868
                        if existing_class:
5✔
869
                            enum_class_name = existing_class
5✔
870
                        else:
871
                            # Create new enum class from the enum's name
872
                            enum_class_name = self._enum_name_to_class_name(
5✔
873
                                column.type.name
874
                            )
875
                            # Register the enum values if not already registered
876
                            if enum_class_name not in self.enum_values:
5✔
877
                                self.enum_values[enum_class_name] = list(
5✔
878
                                    column.type.enums
879
                                )
880

881
                        self.enum_classes[(table.name, column.name)] = enum_class_name
5✔
882
                else:
883
                    # Unnamed enum - create enum class per column
884
                    if (table.name, column.name) not in self.enum_classes:
5✔
885
                        enum_class_name = self._create_enum_class(
5✔
886
                            table.name, column.name, list(column.type.enums)
887
                        )
888
                        self.enum_classes[(table.name, column.name)] = enum_class_name
5✔
889

890
            if not self.keep_dialect_types:
5✔
891
                try:
5✔
892
                    column.type = self.get_adapted_type(column.type)
5✔
893
                except CompileError:
5✔
894
                    continue
5✔
895

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

909
                        column.server_default = None
5✔
910

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

921
                # Hack to fix adaptation of the Enum class which is broken since
922
                # SQLAlchemy 1.2
923
                kw = {}
5✔
924
                if supercls is Enum:
5✔
925
                    kw["name"] = coltype.name
5✔
926
                    if coltype.schema:
5✔
927
                        kw["schema"] = coltype.schema
5✔
928

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

943
                try:
5✔
944
                    new_coltype = coltype.adapt(supercls)
5✔
945
                except TypeError:
5✔
946
                    # If the adaptation fails, don't try again
947
                    break
5✔
948

949
                for key, value in kw.items():
5✔
950
                    setattr(new_coltype, key, value)
5✔
951

952
                if isinstance(coltype, ARRAY):
5✔
953
                    new_coltype.item_type = self.get_adapted_type(new_coltype.item_type)
5✔
954

955
                try:
5✔
956
                    # If the adapted column type does not render the same as the
957
                    # original, don't substitute it
958
                    if new_coltype.compile(self.bind.engine.dialect) != compiled_type:
5✔
959
                        break
5✔
960
                except CompileError:
5✔
961
                    # If the adapted column type can't be compiled, don't substitute it
962
                    break
5✔
963

964
                # Stop on the first valid non-uppercase column type class
965
                coltype = new_coltype
5✔
966
                if supercls.__name__ != supercls.__name__.upper():
5✔
967
                    break
5✔
968

969
        return coltype
5✔
970

971

972
class DeclarativeGenerator(TablesGenerator):
5✔
973
    valid_options: ClassVar[set[str]] = TablesGenerator.valid_options | {
5✔
974
        "use_inflect",
975
        "nojoined",
976
        "nobidi",
977
        "noidsuffix",
978
    }
979

980
    def __init__(
5✔
981
        self,
982
        metadata: MetaData,
983
        bind: Connection | Engine,
984
        options: Sequence[str],
985
        *,
986
        indentation: str = "    ",
987
        base_class_name: str = "Base",
988
    ):
989
        super().__init__(metadata, bind, options, indentation=indentation)
5✔
990
        self.base_class_name: str = base_class_name
5✔
991
        self.inflect_engine = inflect.engine()
5✔
992

993
    def generate_base(self) -> None:
5✔
994
        self.base = Base(
5✔
995
            literal_imports=[LiteralImport("sqlalchemy.orm", "DeclarativeBase")],
996
            declarations=[
997
                f"class {self.base_class_name}(DeclarativeBase):",
998
                f"{self.indentation}pass",
999
            ],
1000
            metadata_ref=f"{self.base_class_name}.metadata",
1001
        )
1002

1003
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1004
        super().collect_imports(models)
5✔
1005
        if any(isinstance(model, ModelClass) for model in models):
5✔
1006
            self.add_literal_import("sqlalchemy.orm", "Mapped")
5✔
1007
            self.add_literal_import("sqlalchemy.orm", "mapped_column")
5✔
1008

1009
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1010
        super().collect_imports_for_model(model)
5✔
1011
        if isinstance(model, ModelClass):
5✔
1012
            if model.relationships:
5✔
1013
                self.add_literal_import("sqlalchemy.orm", "relationship")
5✔
1014

1015
    def generate_models(self) -> list[Model]:
5✔
1016
        models_by_table_name: dict[str, Model] = {}
5✔
1017

1018
        # Pick association tables from the metadata into their own set, don't process
1019
        # them normally
1020
        links: defaultdict[str, list[Model]] = defaultdict(lambda: [])
5✔
1021
        for table in self.metadata.sorted_tables:
5✔
1022
            qualified_name = qualified_table_name(table)
5✔
1023

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

1037
            # Only form model classes for tables that have a primary key and are not
1038
            # association tables
1039
            if not table.primary_key:
5✔
1040
                models_by_table_name[qualified_name] = Model(table)
5✔
1041
            else:
1042
                model = ModelClass(table)
5✔
1043
                models_by_table_name[qualified_name] = model
5✔
1044

1045
                # Fill in the columns
1046
                for column in table.c:
5✔
1047
                    column_attr = ColumnAttribute(model, column)
5✔
1048
                    model.columns.append(column_attr)
5✔
1049

1050
        # Add relationships
1051
        for model in models_by_table_name.values():
5✔
1052
            if isinstance(model, ModelClass):
5✔
1053
                self.generate_relationships(
5✔
1054
                    model, models_by_table_name, links[model.table.name]
1055
                )
1056

1057
        # Nest inherited classes in their superclasses to ensure proper ordering
1058
        if "nojoined" not in self.options:
5✔
1059
            for model in list(models_by_table_name.values()):
5✔
1060
                if not isinstance(model, ModelClass):
5✔
1061
                    continue
5✔
1062

1063
                pk_column_names = {col.name for col in model.table.primary_key.columns}
5✔
1064
                for constraint in model.table.foreign_key_constraints:
5✔
1065
                    if set(get_column_names(constraint)) == pk_column_names:
5✔
1066
                        target = models_by_table_name[
5✔
1067
                            qualified_table_name(constraint.elements[0].column.table)
1068
                        ]
1069
                        if isinstance(target, ModelClass):
5✔
1070
                            model.parent_class = target
5✔
1071
                            target.children.append(model)
5✔
1072

1073
        # Change base if we only have tables
1074
        if not any(
5✔
1075
            isinstance(model, ModelClass) for model in models_by_table_name.values()
1076
        ):
1077
            super().generate_base()
5✔
1078

1079
        # Collect the imports
1080
        self.collect_imports(models_by_table_name.values())
5✔
1081

1082
        # Rename models and their attributes that conflict with imports or other
1083
        # attributes
1084
        global_names = {
5✔
1085
            name for namespace in self.imports.values() for name in namespace
1086
        }
1087
        for model in models_by_table_name.values():
5✔
1088
            self.generate_model_name(model, global_names)
5✔
1089
            global_names.add(model.name)
5✔
1090

1091
        return list(models_by_table_name.values())
5✔
1092

1093
    def generate_relationships(
5✔
1094
        self,
1095
        source: ModelClass,
1096
        models_by_table_name: dict[str, Model],
1097
        association_tables: list[Model],
1098
    ) -> list[RelationshipAttribute]:
1099
        relationships: list[RelationshipAttribute] = []
5✔
1100
        reverse_relationship: RelationshipAttribute | None
1101

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

1121
                # Add uselist=False to One-to-One relationships
1122
                column_names = get_column_names(constraint)
5✔
1123
                if any(
5✔
1124
                    isinstance(c, (PrimaryKeyConstraint, UniqueConstraint))
1125
                    and {col.name for col in c.columns} == set(column_names)
1126
                    for c in constraint.table.constraints
1127
                ):
1128
                    r_type = RelationshipType.ONE_TO_ONE
5✔
1129
                else:
1130
                    r_type = RelationshipType.MANY_TO_ONE
5✔
1131

1132
                relationship = RelationshipAttribute(r_type, source, target, constraint)
5✔
1133
                source.relationships.append(relationship)
5✔
1134

1135
                # For self referential relationships, remote_side needs to be set
1136
                if source is target:
5✔
1137
                    relationship.remote_side = [
5✔
1138
                        source.get_column_attribute(col.name)
1139
                        for col in constraint.referred_table.primary_key
1140
                    ]
1141

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

1154
                # Generate the opposite end of the relationship in the target class
1155
                if "nobidi" not in self.options:
5✔
1156
                    if r_type is RelationshipType.MANY_TO_ONE:
5✔
1157
                        r_type = RelationshipType.ONE_TO_MANY
5✔
1158

1159
                    reverse_relationship = RelationshipAttribute(
5✔
1160
                        r_type,
1161
                        target,
1162
                        source,
1163
                        constraint,
1164
                        foreign_keys=relationship.foreign_keys,
1165
                        backref=relationship,
1166
                    )
1167
                    relationship.backref = reverse_relationship
5✔
1168
                    target.relationships.append(reverse_relationship)
5✔
1169

1170
                    # For self referential relationships, remote_side needs to be set
1171
                    if source is target:
5✔
1172
                        reverse_relationship.remote_side = [
5✔
1173
                            source.get_column_attribute(colname)
1174
                            for colname in constraint.column_keys
1175
                        ]
1176

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

1196
                # Generate the opposite end of the relationship in the target class
1197
                reverse_relationship = None
5✔
1198
                if "nobidi" not in self.options:
5✔
1199
                    reverse_relationship = RelationshipAttribute(
5✔
1200
                        RelationshipType.MANY_TO_MANY,
1201
                        target,
1202
                        source,
1203
                        fk_constraints[0],
1204
                        association_table,
1205
                        relationship,
1206
                    )
1207
                    relationship.backref = reverse_relationship
5✔
1208
                    target.relationships.append(reverse_relationship)
5✔
1209

1210
                # Add a primary/secondary join for self-referential many-to-many
1211
                # relationships
1212
                if source is target:
5✔
1213
                    both_relationships = [relationship]
5✔
1214
                    reverse_flags = [False, True]
5✔
1215
                    if reverse_relationship:
5✔
1216
                        both_relationships.append(reverse_relationship)
5✔
1217

1218
                    for relationship, reverse in zip(both_relationships, reverse_flags):
5✔
1219
                        if (
5✔
1220
                            not relationship.association_table
1221
                            or not relationship.constraint
1222
                        ):
UNCOV
1223
                            continue
×
1224

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

1255
        return relationships
5✔
1256

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

1268
            model.name = self.find_free_name(preferred_name, global_names)
5✔
1269

1270
            # Fill in the names for column attributes
1271
            local_names: set[str] = set()
5✔
1272
            for column_attr in model.columns:
5✔
1273
                self.generate_column_attr_name(column_attr, global_names, local_names)
5✔
1274
                local_names.add(column_attr.name)
5✔
1275

1276
            # Fill in the names for relationship attributes
1277
            for relationship in model.relationships:
5✔
1278
                self.generate_relationship_name(relationship, global_names, local_names)
5✔
1279
                local_names.add(relationship.name)
5✔
1280
        else:
1281
            super().generate_model_name(model, global_names)
5✔
1282

1283
    def generate_column_attr_name(
5✔
1284
        self,
1285
        column_attr: ColumnAttribute,
1286
        global_names: set[str],
1287
        local_names: set[str],
1288
    ) -> None:
1289
        column_attr.name = self.find_free_name(
5✔
1290
            column_attr.column.name, global_names, local_names
1291
        )
1292

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

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

1324
            if "use_inflect" in self.options:
5✔
1325
                inflected_name: str | Literal[False]
1326
                if relationship.type in (
5✔
1327
                    RelationshipType.ONE_TO_MANY,
1328
                    RelationshipType.MANY_TO_MANY,
1329
                ):
1330
                    if not self.inflect_engine.singular_noun(preferred_name):
5✔
UNCOV
1331
                        preferred_name = self.inflect_engine.plural_noun(preferred_name)
×
1332
                else:
1333
                    inflected_name = self.inflect_engine.singular_noun(preferred_name)
5✔
1334
                    if inflected_name:
5✔
1335
                        preferred_name = inflected_name
5✔
1336

1337
        relationship.name = self.find_free_name(
5✔
1338
            preferred_name, global_names, local_names
1339
        )
1340

1341
    def render_models(self, models: list[Model]) -> str:
5✔
1342
        rendered: list[str] = []
5✔
1343
        for model in models:
5✔
1344
            if isinstance(model, ModelClass):
5✔
1345
                rendered.append(self.render_class(model))
5✔
1346
            else:
1347
                rendered.append(f"{model.name} = {self.render_table(model.table)}")
5✔
1348

1349
        return "\n\n\n".join(rendered)
5✔
1350

1351
    def render_class(self, model: ModelClass) -> str:
5✔
1352
        sections: list[str] = []
5✔
1353

1354
        # Render class variables / special declarations
1355
        class_vars: str = self.render_class_variables(model)
5✔
1356
        if class_vars:
5✔
1357
            sections.append(class_vars)
5✔
1358

1359
        # Render column attributes
1360
        rendered_column_attributes: list[str] = []
5✔
1361
        for nullable in (False, True):
5✔
1362
            for column_attr in model.columns:
5✔
1363
                if column_attr.column.nullable is nullable:
5✔
1364
                    rendered_column_attributes.append(
5✔
1365
                        self.render_column_attribute(column_attr)
1366
                    )
1367

1368
        if rendered_column_attributes:
5✔
1369
            sections.append("\n".join(rendered_column_attributes))
5✔
1370

1371
        # Render relationship attributes
1372
        rendered_relationship_attributes: list[str] = [
5✔
1373
            self.render_relationship(relationship)
1374
            for relationship in model.relationships
1375
        ]
1376

1377
        if rendered_relationship_attributes:
5✔
1378
            sections.append("\n".join(rendered_relationship_attributes))
5✔
1379

1380
        declaration = self.render_class_declaration(model)
5✔
1381
        rendered_sections = "\n\n".join(
5✔
1382
            indent(section, self.indentation) for section in sections
1383
        )
1384
        return f"{declaration}\n{rendered_sections}"
5✔
1385

1386
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1387
        parent_class_name = (
5✔
1388
            model.parent_class.name if model.parent_class else self.base_class_name
1389
        )
1390
        return f"class {model.name}({parent_class_name}):"
5✔
1391

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

1395
        # Render constraints and indexes as __table_args__
1396
        table_args = self.render_table_args(model.table)
5✔
1397
        if table_args:
5✔
1398
            variables.append(f"__table_args__ = {table_args}")
5✔
1399

1400
        return "\n".join(variables)
5✔
1401

1402
    def render_table_args(self, table: Table) -> str:
5✔
1403
        args: list[str] = []
5✔
1404
        kwargs: dict[str, object] = {}
5✔
1405

1406
        # Render constraints
1407
        for constraint in sorted(table.constraints, key=get_constraint_sort_key):
5✔
1408
            if uses_default_name(constraint):
5✔
1409
                if isinstance(constraint, PrimaryKeyConstraint):
5✔
1410
                    continue
5✔
1411
                if (
5✔
1412
                    isinstance(constraint, (ForeignKeyConstraint, UniqueConstraint))
1413
                    and len(constraint.columns) == 1
1414
                ):
1415
                    continue
5✔
1416

1417
            args.append(self.render_constraint(constraint))
5✔
1418

1419
        # Render indexes
1420
        for index in sorted(table.indexes, key=lambda i: cast(str, i.name)):
5✔
1421
            if len(index.columns) > 1 or not uses_default_name(index):
5✔
1422
                args.append(self.render_index(index))
5✔
1423

1424
        if table.schema:
5✔
1425
            kwargs["schema"] = table.schema
5✔
1426

1427
        if table.comment:
5✔
1428
            kwargs["comment"] = table.comment
5✔
1429

1430
        # add info + dialect kwargs for dict context (__table_args__) (opt-in)
1431
        if self.include_dialect_options_and_info:
5✔
1432
            self._add_dialect_kwargs_and_info(table, kwargs, values_for_dict=True)
5✔
1433

1434
        if kwargs:
5✔
1435
            formatted_kwargs = pformat(kwargs)
5✔
1436
            if not args:
5✔
1437
                return formatted_kwargs
5✔
1438
            else:
1439
                args.append(formatted_kwargs)
5✔
1440

1441
        if args:
5✔
1442
            rendered_args = f",\n{self.indentation}".join(args)
5✔
1443
            if len(args) == 1:
5✔
1444
                rendered_args += ","
5✔
1445

1446
            return f"(\n{self.indentation}{rendered_args}\n)"
5✔
1447
        else:
1448
            return ""
5✔
1449

1450
    def render_column_python_type(self, column: Column[Any]) -> str:
5✔
1451
        def get_type_qualifiers() -> tuple[str, TypeEngine[Any], str]:
5✔
1452
            column_type = column.type
5✔
1453
            pre: list[str] = []
5✔
1454
            post_size = 0
5✔
1455
            if column.nullable:
5✔
1456
                self.add_literal_import("typing", "Optional")
5✔
1457
                pre.append("Optional[")
5✔
1458
                post_size += 1
5✔
1459

1460
            if isinstance(column_type, ARRAY):
5✔
1461
                dim = getattr(column_type, "dimensions", None) or 1
5✔
1462
                pre.extend("list[" for _ in range(dim))
5✔
1463
                post_size += dim
5✔
1464

1465
                column_type = column_type.item_type
5✔
1466

1467
            return "".join(pre), column_type, "]" * post_size
5✔
1468

1469
        def render_python_type(column_type: TypeEngine[Any]) -> str:
5✔
1470
            # Check if this is an enum column with a Python enum class
1471
            if isinstance(column_type, Enum):
5✔
1472
                table_name = column.table.name
5✔
1473
                column_name = column.name
5✔
1474
                if (table_name, column_name) in self.enum_classes:
5✔
1475
                    enum_class_name = self.enum_classes[(table_name, column_name)]
5✔
1476
                    return enum_class_name
5✔
1477

1478
            if isinstance(column_type, DOMAIN):
5✔
1479
                column_type = column_type.data_type
5✔
1480

1481
            try:
5✔
1482
                python_type = column_type.python_type
5✔
1483
                python_type_module = python_type.__module__
5✔
1484
                python_type_name = python_type.__name__
5✔
1485
            except NotImplementedError:
5✔
1486
                self.add_literal_import("typing", "Any")
5✔
1487
                return "Any"
5✔
1488

1489
            if python_type_module == "builtins":
5✔
1490
                return python_type_name
5✔
1491

1492
            self.add_module_import(python_type_module)
5✔
1493
            return f"{python_type_module}.{python_type_name}"
5✔
1494

1495
        pre, col_type, post = get_type_qualifiers()
5✔
1496
        column_python_type = f"{pre}{render_python_type(col_type)}{post}"
5✔
1497
        return column_python_type
5✔
1498

1499
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1500
        column = column_attr.column
5✔
1501
        rendered_column = self.render_column(column, column_attr.name != column.name)
5✔
1502
        rendered_column_python_type = self.render_column_python_type(column)
5✔
1503

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

1506
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1507
        def render_column_attrs(column_attrs: list[ColumnAttribute]) -> str:
5✔
1508
            rendered = []
5✔
1509
            for attr in column_attrs:
5✔
1510
                if attr.model is relationship.source:
5✔
1511
                    rendered.append(attr.name)
5✔
1512
                else:
UNCOV
1513
                    rendered.append(repr(f"{attr.model.name}.{attr.name}"))
×
1514

1515
            return "[" + ", ".join(rendered) + "]"
5✔
1516

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

1528
            if render_as_string:
5✔
1529
                return "'[" + ", ".join(rendered) + "]'"
5✔
1530
            else:
1531
                return "[" + ", ".join(rendered) + "]"
5✔
1532

1533
        def render_join(terms: list[JoinType]) -> str:
5✔
1534
            rendered_joins = []
5✔
1535
            for source, source_col, target, target_col in terms:
5✔
1536
                rendered = f"lambda: {source.name}.{source_col} == {target.name}."
5✔
1537
                if target.__class__ is Model:
5✔
1538
                    rendered += "c."
5✔
1539

1540
                rendered += str(target_col)
5✔
1541
                rendered_joins.append(rendered)
5✔
1542

1543
            if len(rendered_joins) > 1:
5✔
UNCOV
1544
                rendered = ", ".join(rendered_joins)
×
UNCOV
1545
                return f"and_({rendered})"
×
1546
            else:
1547
                return rendered_joins[0]
5✔
1548

1549
        # Render keyword arguments
1550
        kwargs: dict[str, Any] = {}
5✔
1551
        if relationship.type is RelationshipType.ONE_TO_ONE and relationship.constraint:
5✔
1552
            if relationship.constraint.referred_table is relationship.source.table:
5✔
1553
                kwargs["uselist"] = False
5✔
1554

1555
        # Add the "secondary" keyword for many-to-many relationships
1556
        if relationship.association_table:
5✔
1557
            table_ref = relationship.association_table.table.name
5✔
1558
            if relationship.association_table.schema:
5✔
1559
                table_ref = f"{relationship.association_table.schema}.{table_ref}"
5✔
1560

1561
            kwargs["secondary"] = repr(table_ref)
5✔
1562

1563
        if relationship.remote_side:
5✔
1564
            kwargs["remote_side"] = render_column_attrs(relationship.remote_side)
5✔
1565

1566
        if relationship.foreign_keys:
5✔
1567
            kwargs["foreign_keys"] = render_foreign_keys(relationship.foreign_keys)
5✔
1568

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

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

1575
        if relationship.backref:
5✔
1576
            kwargs["back_populates"] = repr(relationship.backref.name)
5✔
1577

1578
        rendered_relationship = render_callable(
5✔
1579
            "relationship", repr(relationship.target.name), kwargs=kwargs
1580
        )
1581

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

1601
        return (
5✔
1602
            f"{relationship.name}: Mapped[{relationship_type}] "
1603
            f"= {rendered_relationship}"
1604
        )
1605

1606

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

1629
    def generate_base(self) -> None:
5✔
1630
        self.base = Base(
5✔
1631
            literal_imports=[
1632
                LiteralImport("sqlalchemy.orm", "DeclarativeBase"),
1633
                LiteralImport("sqlalchemy.orm", "MappedAsDataclass"),
1634
            ],
1635
            declarations=[
1636
                (f"class {self.base_class_name}(MappedAsDataclass, DeclarativeBase):"),
1637
                f"{self.indentation}pass",
1638
            ],
1639
            metadata_ref=f"{self.base_class_name}.metadata",
1640
        )
1641

1642

1643
class SQLModelGenerator(DeclarativeGenerator):
5✔
1644
    def __init__(
5✔
1645
        self,
1646
        metadata: MetaData,
1647
        bind: Connection | Engine,
1648
        options: Sequence[str],
1649
        *,
1650
        indentation: str = "    ",
1651
        base_class_name: str = "SQLModel",
1652
    ):
1653
        super().__init__(
5✔
1654
            metadata,
1655
            bind,
1656
            options,
1657
            indentation=indentation,
1658
            base_class_name=base_class_name,
1659
        )
1660

1661
    @property
5✔
1662
    def views_supported(self) -> bool:
5✔
UNCOV
1663
        return False
×
1664

1665
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
1666
        self.add_import(Column)
5✔
1667
        return render_callable("Column", *args, kwargs=kwargs)
5✔
1668

1669
    def generate_base(self) -> None:
5✔
1670
        self.base = Base(
5✔
1671
            literal_imports=[],
1672
            declarations=[],
1673
            metadata_ref="",
1674
        )
1675

1676
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1677
        super(DeclarativeGenerator, self).collect_imports(models)
5✔
1678
        if any(isinstance(model, ModelClass) for model in models):
5✔
1679
            self.remove_literal_import("sqlalchemy", "MetaData")
5✔
1680
            self.add_literal_import("sqlmodel", "SQLModel")
5✔
1681
            self.add_literal_import("sqlmodel", "Field")
5✔
1682

1683
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1684
        super(DeclarativeGenerator, self).collect_imports_for_model(model)
5✔
1685
        if isinstance(model, ModelClass):
5✔
1686
            for column_attr in model.columns:
5✔
1687
                if column_attr.column.nullable:
5✔
1688
                    self.add_literal_import("typing", "Optional")
5✔
1689
                    break
5✔
1690

1691
            if model.relationships:
5✔
1692
                self.add_literal_import("sqlmodel", "Relationship")
5✔
1693

1694
    def render_module_variables(self, models: list[Model]) -> str:
5✔
1695
        declarations: list[str] = []
5✔
1696
        if any(not isinstance(model, ModelClass) for model in models):
5✔
UNCOV
1697
            if self.base.table_metadata_declaration is not None:
×
UNCOV
1698
                declarations.append(self.base.table_metadata_declaration)
×
1699

1700
        return "\n".join(declarations)
5✔
1701

1702
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1703
        if model.parent_class:
5✔
UNCOV
1704
            parent = model.parent_class.name
×
1705
        else:
1706
            parent = self.base_class_name
5✔
1707

1708
        superclass_part = f"({parent}, table=True)"
5✔
1709
        return f"class {model.name}{superclass_part}:"
5✔
1710

1711
    def render_class_variables(self, model: ModelClass) -> str:
5✔
1712
        variables = []
5✔
1713

1714
        if model.table.name != model.name.lower():
5✔
1715
            variables.append(f"__tablename__ = {model.table.name!r}")
5✔
1716

1717
        # Render constraints and indexes as __table_args__
1718
        table_args = self.render_table_args(model.table)
5✔
1719
        if table_args:
5✔
1720
            variables.append(f"__table_args__ = {table_args}")
5✔
1721

1722
        return "\n".join(variables)
5✔
1723

1724
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1725
        column = column_attr.column
5✔
1726
        rendered_column = self.render_column(column, True)
5✔
1727
        rendered_column_python_type = self.render_column_python_type(column)
5✔
1728

1729
        kwargs: dict[str, Any] = {}
5✔
1730
        if column.nullable:
5✔
1731
            kwargs["default"] = None
5✔
1732
        kwargs["sa_column"] = f"{rendered_column}"
5✔
1733

1734
        rendered_field = render_callable("Field", kwargs=kwargs)
5✔
1735

1736
        return f"{column_attr.name}: {rendered_column_python_type} = {rendered_field}"
5✔
1737

1738
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1739
        rendered = super().render_relationship(relationship).partition(" = ")[2]
5✔
1740
        args = self.render_relationship_args(rendered)
5✔
1741
        kwargs: dict[str, Any] = {}
5✔
1742
        annotation = repr(relationship.target.name)
5✔
1743

1744
        if relationship.type in (
5✔
1745
            RelationshipType.ONE_TO_MANY,
1746
            RelationshipType.MANY_TO_MANY,
1747
        ):
1748
            annotation = f"list[{annotation}]"
5✔
1749
        else:
1750
            self.add_literal_import("typing", "Optional")
5✔
1751
            annotation = f"Optional[{annotation}]"
5✔
1752

1753
        rendered_field = render_callable("Relationship", *args, kwargs=kwargs)
5✔
1754
        return f"{relationship.name}: {annotation} = {rendered_field}"
5✔
1755

1756
    def render_relationship_args(self, arguments: str) -> list[str]:
5✔
1757
        argument_list = arguments.split(",")
5✔
1758
        # delete ')' and ' ' from args
1759
        argument_list[-1] = argument_list[-1][:-1]
5✔
1760
        argument_list = [argument[1:] for argument in argument_list]
5✔
1761

1762
        rendered_args: list[str] = []
5✔
1763
        for arg in argument_list:
5✔
1764
            if "back_populates" in arg:
5✔
1765
                rendered_args.append(arg)
5✔
1766
            if "uselist=False" in arg:
5✔
1767
                rendered_args.append("sa_relationship_kwargs={'uselist': False}")
5✔
1768

1769
        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