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

agronholm / sqlacodegen / 15438192709

04 Jun 2025 09:03AM UTC coverage: 97.246%. First build
15438192709

push

github

web-flow
Double pluralization of names (#262)

* prevent relationship names to be double pluralized

* Add test for double pluralized relationship

* Add test for singular table name

* Makes sure that a singular table name with a one-to-many relationship does not end up with a relationship name of 'False' because of self.inflect_engine.singular_noun(preferred_name) returns False with a singular preferred_name in generate_relationship_name().

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Shorten long line

* Delete test_generators.py

* Re-added double_pluralization tests

* Updated change log

* Update src/sqlacodegen/generators.py

Co-authored-by: Alex Grönholm <alex.gronholm@nextday.fi>

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Alex Grönholm <alex.gronholm@nextday.fi>
Co-authored-by: Idan Sheinberg <ishinberg0@gmail.com>

6 of 7 new or added lines in 2 files covered. (85.71%)

1377 of 1416 relevant lines covered (97.25%)

4.86 hits per line

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

96.28
/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
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 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
    qualified_table_name,
63
    render_callable,
64
    uses_default_name,
65
)
66

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

73

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

79

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

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

90

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

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

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

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

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

118

119
@dataclass(eq=False)
5✔
120
class TablesGenerator(CodeGenerator):
5✔
121
    valid_options: ClassVar[set[str]] = {"noindexes", "noconstraints", "nocomments"}
5✔
122
    builtin_module_names: ClassVar[set[str]] = set(sys.builtin_module_names) | {
5✔
123
        "dataclasses"
124
    }
125

126
    def __init__(
5✔
127
        self,
128
        metadata: MetaData,
129
        bind: Connection | Engine,
130
        options: Sequence[str],
131
        *,
132
        indentation: str = "    ",
133
    ):
134
        super().__init__(metadata, bind, options)
5✔
135
        self.indentation: str = indentation
5✔
136
        self.imports: dict[str, set[str]] = defaultdict(set)
5✔
137
        self.module_imports: set[str] = set()
5✔
138

139
    @property
5✔
140
    def views_supported(self) -> bool:
5✔
141
        return True
×
142

143
    def generate_base(self) -> None:
5✔
144
        self.base = Base(
5✔
145
            literal_imports=[LiteralImport("sqlalchemy", "MetaData")],
146
            declarations=["metadata = MetaData()"],
147
            metadata_ref="metadata",
148
        )
149

150
    def generate(self) -> str:
5✔
151
        self.generate_base()
5✔
152

153
        sections: list[str] = []
5✔
154

155
        # Remove unwanted elements from the metadata
156
        for table in list(self.metadata.tables.values()):
5✔
157
            if self.should_ignore_table(table):
5✔
158
                self.metadata.remove(table)
×
159
                continue
×
160

161
            if "noindexes" in self.options:
5✔
162
                table.indexes.clear()
5✔
163

164
            if "noconstraints" in self.options:
5✔
165
                table.constraints.clear()
5✔
166

167
            if "nocomments" in self.options:
5✔
168
                table.comment = None
5✔
169

170
            for column in table.columns:
5✔
171
                if "nocomments" in self.options:
5✔
172
                    column.comment = None
5✔
173

174
        # Use information from column constraints to figure out the intended column
175
        # types
176
        for table in self.metadata.tables.values():
5✔
177
            self.fix_column_types(table)
5✔
178

179
        # Generate the models
180
        models: list[Model] = self.generate_models()
5✔
181

182
        # Render module level variables
183
        variables = self.render_module_variables(models)
5✔
184
        if variables:
5✔
185
            sections.append(variables + "\n")
5✔
186

187
        # Render models
188
        rendered_models = self.render_models(models)
5✔
189
        if rendered_models:
5✔
190
            sections.append(rendered_models)
5✔
191

192
        # Render collected imports
193
        groups = self.group_imports()
5✔
194
        imports = "\n\n".join("\n".join(line for line in group) for group in groups)
5✔
195
        if imports:
5✔
196
            sections.insert(0, imports)
5✔
197

198
        return "\n\n".join(sections) + "\n"
5✔
199

200
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
201
        for literal_import in self.base.literal_imports:
5✔
202
            self.add_literal_import(literal_import.pkgname, literal_import.name)
5✔
203

204
        for model in models:
5✔
205
            self.collect_imports_for_model(model)
5✔
206

207
    def collect_imports_for_model(self, model: Model) -> None:
5✔
208
        if model.__class__ is Model:
5✔
209
            self.add_import(Table)
5✔
210

211
        for column in model.table.c:
5✔
212
            self.collect_imports_for_column(column)
5✔
213

214
        for constraint in model.table.constraints:
5✔
215
            self.collect_imports_for_constraint(constraint)
5✔
216

217
        for index in model.table.indexes:
5✔
218
            self.collect_imports_for_constraint(index)
5✔
219

220
    def collect_imports_for_column(self, column: Column[Any]) -> None:
5✔
221
        self.add_import(column.type)
5✔
222

223
        if isinstance(column.type, ARRAY):
5✔
224
            self.add_import(column.type.item_type.__class__)
5✔
225
        elif isinstance(column.type, JSONB):
5✔
226
            if (
5✔
227
                not isinstance(column.type.astext_type, Text)
228
                or column.type.astext_type.length is not None
229
            ):
230
                self.add_import(column.type.astext_type)
5✔
231

232
        if column.default:
5✔
233
            self.add_import(column.default)
5✔
234

235
        if column.server_default:
5✔
236
            if isinstance(column.server_default, (Computed, Identity)):
5✔
237
                self.add_import(column.server_default)
5✔
238
            elif isinstance(column.server_default, DefaultClause):
5✔
239
                self.add_literal_import("sqlalchemy", "text")
5✔
240

241
    def collect_imports_for_constraint(self, constraint: Constraint | Index) -> None:
5✔
242
        if isinstance(constraint, Index):
5✔
243
            if len(constraint.columns) > 1 or not uses_default_name(constraint):
5✔
244
                self.add_literal_import("sqlalchemy", "Index")
5✔
245
        elif isinstance(constraint, PrimaryKeyConstraint):
5✔
246
            if not uses_default_name(constraint):
5✔
247
                self.add_literal_import("sqlalchemy", "PrimaryKeyConstraint")
5✔
248
        elif isinstance(constraint, UniqueConstraint):
5✔
249
            if len(constraint.columns) > 1 or not uses_default_name(constraint):
5✔
250
                self.add_literal_import("sqlalchemy", "UniqueConstraint")
5✔
251
        elif isinstance(constraint, ForeignKeyConstraint):
5✔
252
            if len(constraint.columns) > 1 or not uses_default_name(constraint):
5✔
253
                self.add_literal_import("sqlalchemy", "ForeignKeyConstraint")
5✔
254
            else:
255
                self.add_import(ForeignKey)
5✔
256
        else:
257
            self.add_import(constraint)
5✔
258

259
    def add_import(self, obj: Any) -> None:
5✔
260
        # Don't store builtin imports
261
        if getattr(obj, "__module__", "builtins") == "builtins":
5✔
262
            return
5✔
263

264
        type_ = type(obj) if not isinstance(obj, type) else obj
5✔
265
        pkgname = type_.__module__
5✔
266

267
        # The column types have already been adapted towards generic types if possible,
268
        # so if this is still a vendor specific type (e.g., MySQL INTEGER) be sure to
269
        # use that rather than the generic sqlalchemy type as it might have different
270
        # constructor parameters.
271
        if pkgname.startswith("sqlalchemy.dialects."):
5✔
272
            dialect_pkgname = ".".join(pkgname.split(".")[0:3])
5✔
273
            dialect_pkg = import_module(dialect_pkgname)
5✔
274

275
            if type_.__name__ in dialect_pkg.__all__:
5✔
276
                pkgname = dialect_pkgname
5✔
277
        elif type_.__name__ in dir(sqlalchemy):
5✔
278
            pkgname = "sqlalchemy"
5✔
279
        else:
280
            pkgname = type_.__module__
5✔
281

282
        self.add_literal_import(pkgname, type_.__name__)
5✔
283

284
    def add_literal_import(self, pkgname: str, name: str) -> None:
5✔
285
        names = self.imports.setdefault(pkgname, set())
5✔
286
        names.add(name)
5✔
287

288
    def remove_literal_import(self, pkgname: str, name: str) -> None:
5✔
289
        names = self.imports.setdefault(pkgname, set())
5✔
290
        if name in names:
5✔
291
            names.remove(name)
×
292

293
    def add_module_import(self, pgkname: str) -> None:
5✔
294
        self.module_imports.add(pgkname)
5✔
295

296
    def group_imports(self) -> list[list[str]]:
5✔
297
        future_imports: list[str] = []
5✔
298
        stdlib_imports: list[str] = []
5✔
299
        thirdparty_imports: list[str] = []
5✔
300

301
        for package in sorted(self.imports):
5✔
302
            imports = ", ".join(sorted(self.imports[package]))
5✔
303
            collection = thirdparty_imports
5✔
304
            if package == "__future__":
5✔
305
                collection = future_imports
×
306
            elif package in self.builtin_module_names:
5✔
307
                collection = stdlib_imports
×
308
            elif package in sys.modules:
5✔
309
                if "site-packages" not in (sys.modules[package].__file__ or ""):
5✔
310
                    collection = stdlib_imports
5✔
311

312
            collection.append(f"from {package} import {imports}")
5✔
313

314
        for module in sorted(self.module_imports):
5✔
315
            thirdparty_imports.append(f"import {module}")
5✔
316

317
        return [
5✔
318
            group
319
            for group in (future_imports, stdlib_imports, thirdparty_imports)
320
            if group
321
        ]
322

323
    def generate_models(self) -> list[Model]:
5✔
324
        models = [Model(table) for table in self.metadata.sorted_tables]
5✔
325

326
        # Collect the imports
327
        self.collect_imports(models)
5✔
328

329
        # Generate names for models
330
        global_names = {
5✔
331
            name for namespace in self.imports.values() for name in namespace
332
        }
333
        for model in models:
5✔
334
            self.generate_model_name(model, global_names)
5✔
335
            global_names.add(model.name)
5✔
336

337
        return models
5✔
338

339
    def generate_model_name(self, model: Model, global_names: set[str]) -> None:
5✔
340
        preferred_name = f"t_{model.table.name}"
5✔
341
        model.name = self.find_free_name(preferred_name, global_names)
5✔
342

343
    def render_module_variables(self, models: list[Model]) -> str:
5✔
344
        declarations = self.base.declarations
5✔
345

346
        if any(not isinstance(model, ModelClass) for model in models):
5✔
347
            if self.base.table_metadata_declaration is not None:
5✔
348
                declarations.append(self.base.table_metadata_declaration)
×
349

350
        return "\n".join(declarations)
5✔
351

352
    def render_models(self, models: list[Model]) -> str:
5✔
353
        rendered: list[str] = []
5✔
354
        for model in models:
5✔
355
            rendered_table = self.render_table(model.table)
5✔
356
            rendered.append(f"{model.name} = {rendered_table}")
5✔
357

358
        return "\n\n".join(rendered)
5✔
359

360
    def render_table(self, table: Table) -> str:
5✔
361
        args: list[str] = [f"{table.name!r}, {self.base.metadata_ref}"]
5✔
362
        kwargs: dict[str, object] = {}
5✔
363
        for column in table.columns:
5✔
364
            # Cast is required because of a bug in the SQLAlchemy stubs regarding
365
            # Table.columns
366
            args.append(self.render_column(column, True, is_table=True))
5✔
367

368
        for constraint in sorted(table.constraints, key=get_constraint_sort_key):
5✔
369
            if uses_default_name(constraint):
5✔
370
                if isinstance(constraint, PrimaryKeyConstraint):
5✔
371
                    continue
5✔
372
                elif isinstance(constraint, (ForeignKeyConstraint, UniqueConstraint)):
5✔
373
                    if len(constraint.columns) == 1:
5✔
374
                        continue
5✔
375

376
            args.append(self.render_constraint(constraint))
5✔
377

378
        for index in sorted(table.indexes, key=lambda i: i.name):
5✔
379
            # One-column indexes should be rendered as index=True on columns
380
            if len(index.columns) > 1 or not uses_default_name(index):
5✔
381
                args.append(self.render_index(index))
5✔
382

383
        if table.schema:
5✔
384
            kwargs["schema"] = repr(table.schema)
5✔
385

386
        table_comment = getattr(table, "comment", None)
5✔
387
        if table_comment:
5✔
388
            kwargs["comment"] = repr(table.comment)
5✔
389

390
        return render_callable("Table", *args, kwargs=kwargs, indentation="    ")
5✔
391

392
    def render_index(self, index: Index) -> str:
5✔
393
        extra_args = [repr(col.name) for col in index.columns]
5✔
394
        kwargs = {}
5✔
395
        if index.unique:
5✔
396
            kwargs["unique"] = True
5✔
397

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

400
    # TODO find better solution for is_table
401
    def render_column(
5✔
402
        self, column: Column[Any], show_name: bool, is_table: bool = False
403
    ) -> str:
404
        args = []
5✔
405
        kwargs: dict[str, Any] = {}
5✔
406
        kwarg = []
5✔
407
        is_sole_pk = column.primary_key and len(column.table.primary_key) == 1
5✔
408
        dedicated_fks = [
5✔
409
            c
410
            for c in column.foreign_keys
411
            if c.constraint
412
            and len(c.constraint.columns) == 1
413
            and uses_default_name(c.constraint)
414
        ]
415
        is_unique = any(
5✔
416
            isinstance(c, UniqueConstraint)
417
            and set(c.columns) == {column}
418
            and uses_default_name(c)
419
            for c in column.table.constraints
420
        )
421
        is_unique = is_unique or any(
5✔
422
            i.unique and set(i.columns) == {column} and uses_default_name(i)
423
            for i in column.table.indexes
424
        )
425
        is_primary = (
5✔
426
            any(
427
                isinstance(c, PrimaryKeyConstraint)
428
                and column.name in c.columns
429
                and uses_default_name(c)
430
                for c in column.table.constraints
431
            )
432
            or column.primary_key
433
        )
434
        has_index = any(
5✔
435
            set(i.columns) == {column} and uses_default_name(i)
436
            for i in column.table.indexes
437
        )
438

439
        if show_name:
5✔
440
            args.append(repr(column.name))
5✔
441

442
        # Render the column type if there are no foreign keys on it or any of them
443
        # points back to itself
444
        if not dedicated_fks or any(fk.column is column for fk in dedicated_fks):
5✔
445
            args.append(self.render_column_type(column.type))
5✔
446

447
        for fk in dedicated_fks:
5✔
448
            args.append(self.render_constraint(fk))
5✔
449

450
        if column.default:
5✔
451
            args.append(repr(column.default))
5✔
452

453
        if column.key != column.name:
5✔
454
            kwargs["key"] = column.key
×
455
        if is_primary:
5✔
456
            kwargs["primary_key"] = True
5✔
457
        if not column.nullable and not is_sole_pk and is_table:
5✔
458
            kwargs["nullable"] = False
×
459

460
        if is_unique:
5✔
461
            column.unique = True
5✔
462
            kwargs["unique"] = True
5✔
463
        if has_index:
5✔
464
            column.index = True
5✔
465
            kwarg.append("index")
5✔
466
            kwargs["index"] = True
5✔
467

468
        if isinstance(column.server_default, DefaultClause):
5✔
469
            kwargs["server_default"] = render_callable(
5✔
470
                "text", repr(column.server_default.arg.text)
471
            )
472
        elif isinstance(column.server_default, Computed):
5✔
473
            expression = str(column.server_default.sqltext)
5✔
474

475
            computed_kwargs = {}
5✔
476
            if column.server_default.persisted is not None:
5✔
477
                computed_kwargs["persisted"] = column.server_default.persisted
5✔
478

479
            args.append(
5✔
480
                render_callable("Computed", repr(expression), kwargs=computed_kwargs)
481
            )
482
        elif isinstance(column.server_default, Identity):
5✔
483
            args.append(repr(column.server_default))
5✔
484
        elif column.server_default:
5✔
485
            kwargs["server_default"] = repr(column.server_default)
×
486

487
        comment = getattr(column, "comment", None)
5✔
488
        if comment:
5✔
489
            kwargs["comment"] = repr(comment)
5✔
490

491
        return self.render_column_callable(is_table, *args, **kwargs)
5✔
492

493
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
494
        if is_table:
5✔
495
            self.add_import(Column)
5✔
496
            return render_callable("Column", *args, kwargs=kwargs)
5✔
497
        else:
498
            return render_callable("mapped_column", *args, kwargs=kwargs)
5✔
499

500
    def render_column_type(self, coltype: object) -> str:
5✔
501
        args = []
5✔
502
        kwargs: dict[str, Any] = {}
5✔
503
        sig = inspect.signature(coltype.__class__.__init__)
5✔
504
        defaults = {param.name: param.default for param in sig.parameters.values()}
5✔
505
        missing = object()
5✔
506
        use_kwargs = False
5✔
507
        for param in list(sig.parameters.values())[1:]:
5✔
508
            # Remove annoyances like _warn_on_bytestring
509
            if param.name.startswith("_"):
5✔
510
                continue
5✔
511
            elif param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD):
5✔
512
                use_kwargs = True
5✔
513
                continue
5✔
514

515
            value = getattr(coltype, param.name, missing)
5✔
516
            default = defaults.get(param.name, missing)
5✔
517
            if value is missing or value == default:
5✔
518
                use_kwargs = True
5✔
519
            elif use_kwargs:
5✔
520
                kwargs[param.name] = repr(value)
5✔
521
            else:
522
                args.append(repr(value))
5✔
523

524
        vararg = next(
5✔
525
            (
526
                param.name
527
                for param in sig.parameters.values()
528
                if param.kind is Parameter.VAR_POSITIONAL
529
            ),
530
            None,
531
        )
532
        if vararg and hasattr(coltype, vararg):
5✔
533
            varargs_repr = [repr(arg) for arg in getattr(coltype, vararg)]
5✔
534
            args.extend(varargs_repr)
5✔
535

536
        # These arguments cannot be autodetected from the Enum initializer
537
        if isinstance(coltype, Enum):
5✔
538
            for colname in "name", "schema":
5✔
539
                if (value := getattr(coltype, colname)) is not None:
5✔
540
                    kwargs[colname] = repr(value)
5✔
541

542
        if isinstance(coltype, JSONB):
5✔
543
            # Remove astext_type if it's the default
544
            if (
5✔
545
                isinstance(coltype.astext_type, Text)
546
                and coltype.astext_type.length is None
547
            ):
548
                del kwargs["astext_type"]
5✔
549

550
        if args or kwargs:
5✔
551
            return render_callable(coltype.__class__.__name__, *args, kwargs=kwargs)
5✔
552
        else:
553
            return coltype.__class__.__name__
5✔
554

555
    def render_constraint(self, constraint: Constraint | ForeignKey) -> str:
5✔
556
        def add_fk_options(*opts: Any) -> None:
5✔
557
            args.extend(repr(opt) for opt in opts)
5✔
558
            for attr in "ondelete", "onupdate", "deferrable", "initially", "match":
5✔
559
                value = getattr(constraint, attr, None)
5✔
560
                if value:
5✔
561
                    kwargs[attr] = repr(value)
5✔
562

563
        args: list[str] = []
5✔
564
        kwargs: dict[str, Any] = {}
5✔
565
        if isinstance(constraint, ForeignKey):
5✔
566
            remote_column = (
5✔
567
                f"{constraint.column.table.fullname}.{constraint.column.name}"
568
            )
569
            add_fk_options(remote_column)
5✔
570
        elif isinstance(constraint, ForeignKeyConstraint):
5✔
571
            local_columns = get_column_names(constraint)
5✔
572
            remote_columns = [
5✔
573
                f"{fk.column.table.fullname}.{fk.column.name}"
574
                for fk in constraint.elements
575
            ]
576
            add_fk_options(local_columns, remote_columns)
5✔
577
        elif isinstance(constraint, CheckConstraint):
5✔
578
            args.append(repr(get_compiled_expression(constraint.sqltext, self.bind)))
5✔
579
        elif isinstance(constraint, (UniqueConstraint, PrimaryKeyConstraint)):
5✔
580
            args.extend(repr(col.name) for col in constraint.columns)
5✔
581
        else:
582
            raise TypeError(
×
583
                f"Cannot render constraint of type {constraint.__class__.__name__}"
584
            )
585

586
        if isinstance(constraint, Constraint) and not uses_default_name(constraint):
5✔
587
            kwargs["name"] = repr(constraint.name)
5✔
588

589
        return render_callable(constraint.__class__.__name__, *args, kwargs=kwargs)
5✔
590

591
    def should_ignore_table(self, table: Table) -> bool:
5✔
592
        # Support for Alembic and sqlalchemy-migrate -- never expose the schema version
593
        # tables
594
        return table.name in ("alembic_version", "migrate_version")
5✔
595

596
    def find_free_name(
5✔
597
        self, name: str, global_names: set[str], local_names: Collection[str] = ()
598
    ) -> str:
599
        """
600
        Generate an attribute name that does not clash with other local or global names.
601
        """
602
        name = name.strip()
5✔
603
        assert name, "Identifier cannot be empty"
5✔
604
        name = _re_invalid_identifier.sub("_", name)
5✔
605
        if name[0].isdigit():
5✔
606
            name = "_" + name
5✔
607
        elif iskeyword(name) or name == "metadata":
5✔
608
            name += "_"
5✔
609

610
        original = name
5✔
611
        for i in count():
5✔
612
            if name not in global_names and name not in local_names:
5✔
613
                break
5✔
614

615
            name = original + (str(i) if i else "_")
5✔
616

617
        return name
5✔
618

619
    def fix_column_types(self, table: Table) -> None:
5✔
620
        """Adjust the reflected column types."""
621
        # Detect check constraints for boolean and enum columns
622
        for constraint in table.constraints.copy():
5✔
623
            if isinstance(constraint, CheckConstraint):
5✔
624
                sqltext = get_compiled_expression(constraint.sqltext, self.bind)
5✔
625

626
                # Turn any integer-like column with a CheckConstraint like
627
                # "column IN (0, 1)" into a Boolean
628
                match = _re_boolean_check_constraint.match(sqltext)
5✔
629
                if match:
5✔
630
                    colname_match = _re_column_name.match(match.group(1))
5✔
631
                    if colname_match:
5✔
632
                        colname = colname_match.group(3)
5✔
633
                        table.constraints.remove(constraint)
5✔
634
                        table.c[colname].type = Boolean()
5✔
635
                        continue
5✔
636

637
                # Turn any string-type column with a CheckConstraint like
638
                # "column IN (...)" into an Enum
639
                match = _re_enum_check_constraint.match(sqltext)
5✔
640
                if match:
5✔
641
                    colname_match = _re_column_name.match(match.group(1))
5✔
642
                    if colname_match:
5✔
643
                        colname = colname_match.group(3)
5✔
644
                        items = match.group(2)
5✔
645
                        if isinstance(table.c[colname].type, String):
5✔
646
                            table.constraints.remove(constraint)
5✔
647
                            if not isinstance(table.c[colname].type, Enum):
5✔
648
                                options = _re_enum_item.findall(items)
5✔
649
                                table.c[colname].type = Enum(
5✔
650
                                    *options, native_enum=False
651
                                )
652

653
                            continue
5✔
654

655
        for column in table.c:
5✔
656
            try:
5✔
657
                column.type = self.get_adapted_type(column.type)
5✔
658
            except CompileError:
5✔
659
                pass
5✔
660

661
            # PostgreSQL specific fix: detect sequences from server_default
662
            if column.server_default and self.bind.dialect.name == "postgresql":
5✔
663
                if isinstance(column.server_default, DefaultClause) and isinstance(
5✔
664
                    column.server_default.arg, TextClause
665
                ):
666
                    schema, seqname = decode_postgresql_sequence(
5✔
667
                        column.server_default.arg
668
                    )
669
                    if seqname:
5✔
670
                        # Add an explicit sequence
671
                        if seqname != f"{column.table.name}_{column.name}_seq":
5✔
672
                            column.default = sqlalchemy.Sequence(seqname, schema=schema)
5✔
673

674
                        column.server_default = None
5✔
675

676
    def get_adapted_type(self, coltype: Any) -> Any:
5✔
677
        compiled_type = coltype.compile(self.bind.engine.dialect)
5✔
678
        for supercls in coltype.__class__.__mro__:
5✔
679
            if not supercls.__name__.startswith("_") and hasattr(
5✔
680
                supercls, "__visit_name__"
681
            ):
682
                # Don't try to adapt UserDefinedType as it's not a proper column type
683
                if supercls is UserDefinedType or issubclass(supercls, TypeDecorator):
5✔
684
                    return coltype
5✔
685

686
                # Hack to fix adaptation of the Enum class which is broken since
687
                # SQLAlchemy 1.2
688
                kw = {}
5✔
689
                if supercls is Enum:
5✔
690
                    kw["name"] = coltype.name
5✔
691
                    if coltype.schema:
5✔
692
                        kw["schema"] = coltype.schema
5✔
693

694
                try:
5✔
695
                    new_coltype = coltype.adapt(supercls)
5✔
696
                except TypeError:
5✔
697
                    # If the adaptation fails, don't try again
698
                    break
5✔
699

700
                for key, value in kw.items():
5✔
701
                    setattr(new_coltype, key, value)
5✔
702

703
                if isinstance(coltype, ARRAY):
5✔
704
                    new_coltype.item_type = self.get_adapted_type(new_coltype.item_type)
5✔
705

706
                try:
5✔
707
                    # If the adapted column type does not render the same as the
708
                    # original, don't substitute it
709
                    if new_coltype.compile(self.bind.engine.dialect) != compiled_type:
5✔
710
                        break
5✔
711
                except CompileError:
5✔
712
                    # If the adapted column type can't be compiled, don't substitute it
713
                    break
5✔
714

715
                # Stop on the first valid non-uppercase column type class
716
                coltype = new_coltype
5✔
717
                if supercls.__name__ != supercls.__name__.upper():
5✔
718
                    break
5✔
719

720
        return coltype
5✔
721

722

723
class DeclarativeGenerator(TablesGenerator):
5✔
724
    valid_options: ClassVar[set[str]] = TablesGenerator.valid_options | {
5✔
725
        "use_inflect",
726
        "nojoined",
727
        "nobidi",
728
    }
729

730
    def __init__(
5✔
731
        self,
732
        metadata: MetaData,
733
        bind: Connection | Engine,
734
        options: Sequence[str],
735
        *,
736
        indentation: str = "    ",
737
        base_class_name: str = "Base",
738
    ):
739
        super().__init__(metadata, bind, options, indentation=indentation)
5✔
740
        self.base_class_name: str = base_class_name
5✔
741
        self.inflect_engine = inflect.engine()
5✔
742

743
    def generate_base(self) -> None:
5✔
744
        self.base = Base(
5✔
745
            literal_imports=[LiteralImport("sqlalchemy.orm", "DeclarativeBase")],
746
            declarations=[
747
                f"class {self.base_class_name}(DeclarativeBase):",
748
                f"{self.indentation}pass",
749
            ],
750
            metadata_ref=f"{self.base_class_name}.metadata",
751
        )
752

753
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
754
        super().collect_imports(models)
5✔
755
        if any(isinstance(model, ModelClass) for model in models):
5✔
756
            self.add_literal_import("sqlalchemy.orm", "Mapped")
5✔
757
            self.add_literal_import("sqlalchemy.orm", "mapped_column")
5✔
758

759
    def collect_imports_for_model(self, model: Model) -> None:
5✔
760
        super().collect_imports_for_model(model)
5✔
761
        if isinstance(model, ModelClass):
5✔
762
            if model.relationships:
5✔
763
                self.add_literal_import("sqlalchemy.orm", "relationship")
5✔
764

765
    def generate_models(self) -> list[Model]:
5✔
766
        models_by_table_name: dict[str, Model] = {}
5✔
767

768
        # Pick association tables from the metadata into their own set, don't process
769
        # them normally
770
        links: defaultdict[str, list[Model]] = defaultdict(lambda: [])
5✔
771
        for table in self.metadata.sorted_tables:
5✔
772
            qualified_name = qualified_table_name(table)
5✔
773

774
            # Link tables have exactly two foreign key constraints and all columns are
775
            # involved in them
776
            fk_constraints = sorted(
5✔
777
                table.foreign_key_constraints, key=get_constraint_sort_key
778
            )
779
            if len(fk_constraints) == 2 and all(
5✔
780
                col.foreign_keys for col in table.columns
781
            ):
782
                model = models_by_table_name[qualified_name] = Model(table)
5✔
783
                tablename = fk_constraints[0].elements[0].column.table.name
5✔
784
                links[tablename].append(model)
5✔
785
                continue
5✔
786

787
            # Only form model classes for tables that have a primary key and are not
788
            # association tables
789
            if not table.primary_key:
5✔
790
                models_by_table_name[qualified_name] = Model(table)
5✔
791
            else:
792
                model = ModelClass(table)
5✔
793
                models_by_table_name[qualified_name] = model
5✔
794

795
                # Fill in the columns
796
                for column in table.c:
5✔
797
                    column_attr = ColumnAttribute(model, column)
5✔
798
                    model.columns.append(column_attr)
5✔
799

800
        # Add relationships
801
        for model in models_by_table_name.values():
5✔
802
            if isinstance(model, ModelClass):
5✔
803
                self.generate_relationships(
5✔
804
                    model, models_by_table_name, links[model.table.name]
805
                )
806

807
        # Nest inherited classes in their superclasses to ensure proper ordering
808
        if "nojoined" not in self.options:
5✔
809
            for model in list(models_by_table_name.values()):
5✔
810
                if not isinstance(model, ModelClass):
5✔
811
                    continue
5✔
812

813
                pk_column_names = {col.name for col in model.table.primary_key.columns}
5✔
814
                for constraint in model.table.foreign_key_constraints:
5✔
815
                    if set(get_column_names(constraint)) == pk_column_names:
5✔
816
                        target = models_by_table_name[
5✔
817
                            qualified_table_name(constraint.elements[0].column.table)
818
                        ]
819
                        if isinstance(target, ModelClass):
5✔
820
                            model.parent_class = target
5✔
821
                            target.children.append(model)
5✔
822

823
        # Change base if we only have tables
824
        if not any(
5✔
825
            isinstance(model, ModelClass) for model in models_by_table_name.values()
826
        ):
827
            super().generate_base()
5✔
828

829
        # Collect the imports
830
        self.collect_imports(models_by_table_name.values())
5✔
831

832
        # Rename models and their attributes that conflict with imports or other
833
        # attributes
834
        global_names = {
5✔
835
            name for namespace in self.imports.values() for name in namespace
836
        }
837
        for model in models_by_table_name.values():
5✔
838
            self.generate_model_name(model, global_names)
5✔
839
            global_names.add(model.name)
5✔
840

841
        return list(models_by_table_name.values())
5✔
842

843
    def generate_relationships(
5✔
844
        self,
845
        source: ModelClass,
846
        models_by_table_name: dict[str, Model],
847
        association_tables: list[Model],
848
    ) -> list[RelationshipAttribute]:
849
        relationships: list[RelationshipAttribute] = []
5✔
850
        reverse_relationship: RelationshipAttribute | None
851

852
        # Add many-to-one (and one-to-many) relationships
853
        pk_column_names = {col.name for col in source.table.primary_key.columns}
5✔
854
        for constraint in sorted(
5✔
855
            source.table.foreign_key_constraints, key=get_constraint_sort_key
856
        ):
857
            target = models_by_table_name[
5✔
858
                qualified_table_name(constraint.elements[0].column.table)
859
            ]
860
            if isinstance(target, ModelClass):
5✔
861
                if "nojoined" not in self.options:
5✔
862
                    if set(get_column_names(constraint)) == pk_column_names:
5✔
863
                        parent = models_by_table_name[
5✔
864
                            qualified_table_name(constraint.elements[0].column.table)
865
                        ]
866
                        if isinstance(parent, ModelClass):
5✔
867
                            source.parent_class = parent
5✔
868
                            parent.children.append(source)
5✔
869
                            continue
5✔
870

871
                # Add uselist=False to One-to-One relationships
872
                column_names = get_column_names(constraint)
5✔
873
                if any(
5✔
874
                    isinstance(c, (PrimaryKeyConstraint, UniqueConstraint))
875
                    and {col.name for col in c.columns} == set(column_names)
876
                    for c in constraint.table.constraints
877
                ):
878
                    r_type = RelationshipType.ONE_TO_ONE
5✔
879
                else:
880
                    r_type = RelationshipType.MANY_TO_ONE
5✔
881

882
                relationship = RelationshipAttribute(r_type, source, target, constraint)
5✔
883
                source.relationships.append(relationship)
5✔
884

885
                # For self referential relationships, remote_side needs to be set
886
                if source is target:
5✔
887
                    relationship.remote_side = [
5✔
888
                        source.get_column_attribute(col.name)
889
                        for col in constraint.referred_table.primary_key
890
                    ]
891

892
                # If the two tables share more than one foreign key constraint,
893
                # SQLAlchemy needs an explicit primaryjoin to figure out which column(s)
894
                # it needs
895
                common_fk_constraints = get_common_fk_constraints(
5✔
896
                    source.table, target.table
897
                )
898
                if len(common_fk_constraints) > 1:
5✔
899
                    relationship.foreign_keys = [
5✔
900
                        source.get_column_attribute(key)
901
                        for key in constraint.column_keys
902
                    ]
903

904
                # Generate the opposite end of the relationship in the target class
905
                if "nobidi" not in self.options:
5✔
906
                    if r_type is RelationshipType.MANY_TO_ONE:
5✔
907
                        r_type = RelationshipType.ONE_TO_MANY
5✔
908

909
                    reverse_relationship = RelationshipAttribute(
5✔
910
                        r_type,
911
                        target,
912
                        source,
913
                        constraint,
914
                        foreign_keys=relationship.foreign_keys,
915
                        backref=relationship,
916
                    )
917
                    relationship.backref = reverse_relationship
5✔
918
                    target.relationships.append(reverse_relationship)
5✔
919

920
                    # For self referential relationships, remote_side needs to be set
921
                    if source is target:
5✔
922
                        reverse_relationship.remote_side = [
5✔
923
                            source.get_column_attribute(colname)
924
                            for colname in constraint.column_keys
925
                        ]
926

927
        # Add many-to-many relationships
928
        for association_table in association_tables:
5✔
929
            fk_constraints = sorted(
5✔
930
                association_table.table.foreign_key_constraints,
931
                key=get_constraint_sort_key,
932
            )
933
            target = models_by_table_name[
5✔
934
                qualified_table_name(fk_constraints[1].elements[0].column.table)
935
            ]
936
            if isinstance(target, ModelClass):
5✔
937
                relationship = RelationshipAttribute(
5✔
938
                    RelationshipType.MANY_TO_MANY,
939
                    source,
940
                    target,
941
                    fk_constraints[1],
942
                    association_table,
943
                )
944
                source.relationships.append(relationship)
5✔
945

946
                # Generate the opposite end of the relationship in the target class
947
                reverse_relationship = None
5✔
948
                if "nobidi" not in self.options:
5✔
949
                    reverse_relationship = RelationshipAttribute(
5✔
950
                        RelationshipType.MANY_TO_MANY,
951
                        target,
952
                        source,
953
                        fk_constraints[0],
954
                        association_table,
955
                        relationship,
956
                    )
957
                    relationship.backref = reverse_relationship
5✔
958
                    target.relationships.append(reverse_relationship)
5✔
959

960
                # Add a primary/secondary join for self-referential many-to-many
961
                # relationships
962
                if source is target:
5✔
963
                    both_relationships = [relationship]
5✔
964
                    reverse_flags = [False, True]
5✔
965
                    if reverse_relationship:
5✔
966
                        both_relationships.append(reverse_relationship)
5✔
967

968
                    for relationship, reverse in zip(both_relationships, reverse_flags):
5✔
969
                        if (
5✔
970
                            not relationship.association_table
971
                            or not relationship.constraint
972
                        ):
973
                            continue
×
974

975
                        constraints = sorted(
5✔
976
                            relationship.constraint.table.foreign_key_constraints,
977
                            key=get_constraint_sort_key,
978
                            reverse=reverse,
979
                        )
980
                        pri_pairs = zip(
5✔
981
                            get_column_names(constraints[0]), constraints[0].elements
982
                        )
983
                        sec_pairs = zip(
5✔
984
                            get_column_names(constraints[1]), constraints[1].elements
985
                        )
986
                        relationship.primaryjoin = [
5✔
987
                            (
988
                                relationship.source,
989
                                elem.column.name,
990
                                relationship.association_table,
991
                                col,
992
                            )
993
                            for col, elem in pri_pairs
994
                        ]
995
                        relationship.secondaryjoin = [
5✔
996
                            (
997
                                relationship.target,
998
                                elem.column.name,
999
                                relationship.association_table,
1000
                                col,
1001
                            )
1002
                            for col, elem in sec_pairs
1003
                        ]
1004

1005
        return relationships
5✔
1006

1007
    def generate_model_name(self, model: Model, global_names: set[str]) -> None:
5✔
1008
        if isinstance(model, ModelClass):
5✔
1009
            preferred_name = _re_invalid_identifier.sub("_", model.table.name)
5✔
1010
            preferred_name = "".join(
5✔
1011
                part[:1].upper() + part[1:] for part in preferred_name.split("_")
1012
            )
1013
            if "use_inflect" in self.options:
5✔
1014
                singular_name = self.inflect_engine.singular_noun(preferred_name)
5✔
1015
                if singular_name:
5✔
1016
                    preferred_name = singular_name
5✔
1017

1018
            model.name = self.find_free_name(preferred_name, global_names)
5✔
1019

1020
            # Fill in the names for column attributes
1021
            local_names: set[str] = set()
5✔
1022
            for column_attr in model.columns:
5✔
1023
                self.generate_column_attr_name(column_attr, global_names, local_names)
5✔
1024
                local_names.add(column_attr.name)
5✔
1025

1026
            # Fill in the names for relationship attributes
1027
            for relationship in model.relationships:
5✔
1028
                self.generate_relationship_name(relationship, global_names, local_names)
5✔
1029
                local_names.add(relationship.name)
5✔
1030
        else:
1031
            super().generate_model_name(model, global_names)
5✔
1032

1033
    def generate_column_attr_name(
5✔
1034
        self,
1035
        column_attr: ColumnAttribute,
1036
        global_names: set[str],
1037
        local_names: set[str],
1038
    ) -> None:
1039
        column_attr.name = self.find_free_name(
5✔
1040
            column_attr.column.name, global_names, local_names
1041
        )
1042

1043
    def generate_relationship_name(
5✔
1044
        self,
1045
        relationship: RelationshipAttribute,
1046
        global_names: set[str],
1047
        local_names: set[str],
1048
    ) -> None:
1049
        # Self referential reverse relationships
1050
        preferred_name: str
1051
        if (
5✔
1052
            relationship.type
1053
            in (RelationshipType.ONE_TO_MANY, RelationshipType.ONE_TO_ONE)
1054
            and relationship.source is relationship.target
1055
            and relationship.backref
1056
            and relationship.backref.name
1057
        ):
1058
            preferred_name = relationship.backref.name + "_reverse"
5✔
1059
        else:
1060
            preferred_name = relationship.target.table.name
5✔
1061

1062
            # If there's a constraint with a single column that ends with "_id", use the
1063
            # preceding part as the relationship name
1064
            if relationship.constraint:
5✔
1065
                is_source = relationship.source.table is relationship.constraint.table
5✔
1066
                if is_source or relationship.type not in (
5✔
1067
                    RelationshipType.ONE_TO_ONE,
1068
                    RelationshipType.ONE_TO_MANY,
1069
                ):
1070
                    column_names = [c.name for c in relationship.constraint.columns]
5✔
1071
                    if len(column_names) == 1 and column_names[0].endswith("_id"):
5✔
1072
                        preferred_name = column_names[0][:-3]
5✔
1073

1074
            if "use_inflect" in self.options:
5✔
1075
                if relationship.type in (
5✔
1076
                    RelationshipType.ONE_TO_MANY,
1077
                    RelationshipType.MANY_TO_MANY,
1078
                ):
1079
                    if not self.inflect_engine.singular_noun(preferred_name):
5✔
NEW
1080
                        preferred_name = self.inflect_engine.plural_noun(preferred_name)
×
1081
                else:
1082
                    inflected_name = self.inflect_engine.singular_noun(preferred_name)
5✔
1083
                    if inflected_name:
5✔
1084
                        preferred_name = inflected_name
5✔
1085

1086
        relationship.name = self.find_free_name(
5✔
1087
            preferred_name, global_names, local_names
1088
        )
1089

1090
    def render_models(self, models: list[Model]) -> str:
5✔
1091
        rendered: list[str] = []
5✔
1092
        for model in models:
5✔
1093
            if isinstance(model, ModelClass):
5✔
1094
                rendered.append(self.render_class(model))
5✔
1095
            else:
1096
                rendered.append(f"{model.name} = {self.render_table(model.table)}")
5✔
1097

1098
        return "\n\n\n".join(rendered)
5✔
1099

1100
    def render_class(self, model: ModelClass) -> str:
5✔
1101
        sections: list[str] = []
5✔
1102

1103
        # Render class variables / special declarations
1104
        class_vars: str = self.render_class_variables(model)
5✔
1105
        if class_vars:
5✔
1106
            sections.append(class_vars)
5✔
1107

1108
        # Render column attributes
1109
        rendered_column_attributes: list[str] = []
5✔
1110
        for nullable in (False, True):
5✔
1111
            for column_attr in model.columns:
5✔
1112
                if column_attr.column.nullable is nullable:
5✔
1113
                    rendered_column_attributes.append(
5✔
1114
                        self.render_column_attribute(column_attr)
1115
                    )
1116

1117
        if rendered_column_attributes:
5✔
1118
            sections.append("\n".join(rendered_column_attributes))
5✔
1119

1120
        # Render relationship attributes
1121
        rendered_relationship_attributes: list[str] = [
5✔
1122
            self.render_relationship(relationship)
1123
            for relationship in model.relationships
1124
        ]
1125

1126
        if rendered_relationship_attributes:
5✔
1127
            sections.append("\n".join(rendered_relationship_attributes))
5✔
1128

1129
        declaration = self.render_class_declaration(model)
5✔
1130
        rendered_sections = "\n\n".join(
5✔
1131
            indent(section, self.indentation) for section in sections
1132
        )
1133
        return f"{declaration}\n{rendered_sections}"
5✔
1134

1135
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1136
        parent_class_name = (
5✔
1137
            model.parent_class.name if model.parent_class else self.base_class_name
1138
        )
1139
        return f"class {model.name}({parent_class_name}):"
5✔
1140

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

1144
        # Render constraints and indexes as __table_args__
1145
        table_args = self.render_table_args(model.table)
5✔
1146
        if table_args:
5✔
1147
            variables.append(f"__table_args__ = {table_args}")
5✔
1148

1149
        return "\n".join(variables)
5✔
1150

1151
    def render_table_args(self, table: Table) -> str:
5✔
1152
        args: list[str] = []
5✔
1153
        kwargs: dict[str, str] = {}
5✔
1154

1155
        # Render constraints
1156
        for constraint in sorted(table.constraints, key=get_constraint_sort_key):
5✔
1157
            if uses_default_name(constraint):
5✔
1158
                if isinstance(constraint, PrimaryKeyConstraint):
5✔
1159
                    continue
5✔
1160
                if (
5✔
1161
                    isinstance(constraint, (ForeignKeyConstraint, UniqueConstraint))
1162
                    and len(constraint.columns) == 1
1163
                ):
1164
                    continue
5✔
1165

1166
            args.append(self.render_constraint(constraint))
5✔
1167

1168
        # Render indexes
1169
        for index in sorted(table.indexes, key=lambda i: i.name):
5✔
1170
            if len(index.columns) > 1 or not uses_default_name(index):
5✔
1171
                args.append(self.render_index(index))
5✔
1172

1173
        if table.schema:
5✔
1174
            kwargs["schema"] = table.schema
5✔
1175

1176
        if table.comment:
5✔
1177
            kwargs["comment"] = table.comment
5✔
1178

1179
        if kwargs:
5✔
1180
            formatted_kwargs = pformat(kwargs)
5✔
1181
            if not args:
5✔
1182
                return formatted_kwargs
5✔
1183
            else:
1184
                args.append(formatted_kwargs)
5✔
1185

1186
        if args:
5✔
1187
            rendered_args = f",\n{self.indentation}".join(args)
5✔
1188
            if len(args) == 1:
5✔
1189
                rendered_args += ","
5✔
1190

1191
            return f"(\n{self.indentation}{rendered_args}\n)"
5✔
1192
        else:
1193
            return ""
5✔
1194

1195
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1196
        column = column_attr.column
5✔
1197
        rendered_column = self.render_column(column, column_attr.name != column.name)
5✔
1198

1199
        def get_type_qualifiers() -> tuple[str, TypeEngine[Any], str]:
5✔
1200
            column_type = column.type
5✔
1201
            pre: list[str] = []
5✔
1202
            post_size = 0
5✔
1203
            if column.nullable:
5✔
1204
                self.add_literal_import("typing", "Optional")
5✔
1205
                pre.append("Optional[")
5✔
1206
                post_size += 1
5✔
1207

1208
            if isinstance(column_type, ARRAY):
5✔
1209
                dim = getattr(column_type, "dimensions", None) or 1
5✔
1210
                pre.extend("list[" for _ in range(dim))
5✔
1211
                post_size += dim
5✔
1212

1213
                column_type = column_type.item_type
5✔
1214

1215
            return "".join(pre), column_type, "]" * post_size
5✔
1216

1217
        def render_python_type(column_type: TypeEngine[Any]) -> str:
5✔
1218
            python_type = column_type.python_type
5✔
1219
            python_type_name = python_type.__name__
5✔
1220
            python_type_module = python_type.__module__
5✔
1221
            if python_type_module == "builtins":
5✔
1222
                return python_type_name
5✔
1223

1224
            try:
5✔
1225
                self.add_module_import(python_type_module)
5✔
1226
                return f"{python_type_module}.{python_type_name}"
5✔
1227
            except NotImplementedError:
×
1228
                self.add_literal_import("typing", "Any")
×
1229
                return "Any"
×
1230

1231
        pre, col_type, post = get_type_qualifiers()
5✔
1232
        column_python_type = f"{pre}{render_python_type(col_type)}{post}"
5✔
1233
        return f"{column_attr.name}: Mapped[{column_python_type}] = {rendered_column}"
5✔
1234

1235
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1236
        def render_column_attrs(column_attrs: list[ColumnAttribute]) -> str:
5✔
1237
            rendered = []
5✔
1238
            for attr in column_attrs:
5✔
1239
                if attr.model is relationship.source:
5✔
1240
                    rendered.append(attr.name)
5✔
1241
                else:
1242
                    rendered.append(repr(f"{attr.model.name}.{attr.name}"))
×
1243

1244
            return "[" + ", ".join(rendered) + "]"
5✔
1245

1246
        def render_foreign_keys(column_attrs: list[ColumnAttribute]) -> str:
5✔
1247
            rendered = []
5✔
1248
            render_as_string = False
5✔
1249
            # Assume that column_attrs are all in relationship.source or none
1250
            for attr in column_attrs:
5✔
1251
                if attr.model is relationship.source:
5✔
1252
                    rendered.append(attr.name)
5✔
1253
                else:
1254
                    rendered.append(f"{attr.model.name}.{attr.name}")
5✔
1255
                    render_as_string = True
5✔
1256

1257
            if render_as_string:
5✔
1258
                return "'[" + ", ".join(rendered) + "]'"
5✔
1259
            else:
1260
                return "[" + ", ".join(rendered) + "]"
5✔
1261

1262
        def render_join(terms: list[JoinType]) -> str:
5✔
1263
            rendered_joins = []
5✔
1264
            for source, source_col, target, target_col in terms:
5✔
1265
                rendered = f"lambda: {source.name}.{source_col} == {target.name}."
5✔
1266
                if target.__class__ is Model:
5✔
1267
                    rendered += "c."
5✔
1268

1269
                rendered += str(target_col)
5✔
1270
                rendered_joins.append(rendered)
5✔
1271

1272
            if len(rendered_joins) > 1:
5✔
1273
                rendered = ", ".join(rendered_joins)
×
1274
                return f"and_({rendered})"
×
1275
            else:
1276
                return rendered_joins[0]
5✔
1277

1278
        # Render keyword arguments
1279
        kwargs: dict[str, Any] = {}
5✔
1280
        if relationship.type is RelationshipType.ONE_TO_ONE and relationship.constraint:
5✔
1281
            if relationship.constraint.referred_table is relationship.source.table:
5✔
1282
                kwargs["uselist"] = False
5✔
1283

1284
        # Add the "secondary" keyword for many-to-many relationships
1285
        if relationship.association_table:
5✔
1286
            table_ref = relationship.association_table.table.name
5✔
1287
            if relationship.association_table.schema:
5✔
1288
                table_ref = f"{relationship.association_table.schema}.{table_ref}"
5✔
1289

1290
            kwargs["secondary"] = repr(table_ref)
5✔
1291

1292
        if relationship.remote_side:
5✔
1293
            kwargs["remote_side"] = render_column_attrs(relationship.remote_side)
5✔
1294

1295
        if relationship.foreign_keys:
5✔
1296
            kwargs["foreign_keys"] = render_foreign_keys(relationship.foreign_keys)
5✔
1297

1298
        if relationship.primaryjoin:
5✔
1299
            kwargs["primaryjoin"] = render_join(relationship.primaryjoin)
5✔
1300

1301
        if relationship.secondaryjoin:
5✔
1302
            kwargs["secondaryjoin"] = render_join(relationship.secondaryjoin)
5✔
1303

1304
        if relationship.backref:
5✔
1305
            kwargs["back_populates"] = repr(relationship.backref.name)
5✔
1306

1307
        rendered_relationship = render_callable(
5✔
1308
            "relationship", repr(relationship.target.name), kwargs=kwargs
1309
        )
1310

1311
        relationship_type: str
1312
        if relationship.type == RelationshipType.ONE_TO_MANY:
5✔
1313
            relationship_type = f"list['{relationship.target.name}']"
5✔
1314
        elif relationship.type in (
5✔
1315
            RelationshipType.ONE_TO_ONE,
1316
            RelationshipType.MANY_TO_ONE,
1317
        ):
1318
            relationship_type = f"'{relationship.target.name}'"
5✔
1319
            if relationship.constraint and any(
5✔
1320
                col.nullable for col in relationship.constraint.columns
1321
            ):
1322
                self.add_literal_import("typing", "Optional")
5✔
1323
                relationship_type = f"Optional[{relationship_type}]"
5✔
1324
        elif relationship.type == RelationshipType.MANY_TO_MANY:
5✔
1325
            relationship_type = f"list['{relationship.target.name}']"
5✔
1326
        else:
1327
            self.add_literal_import("typing", "Any")
×
1328
            relationship_type = "Any"
×
1329

1330
        return (
5✔
1331
            f"{relationship.name}: Mapped[{relationship_type}] "
1332
            f"= {rendered_relationship}"
1333
        )
1334

1335

1336
class DataclassGenerator(DeclarativeGenerator):
5✔
1337
    def __init__(
5✔
1338
        self,
1339
        metadata: MetaData,
1340
        bind: Connection | Engine,
1341
        options: Sequence[str],
1342
        *,
1343
        indentation: str = "    ",
1344
        base_class_name: str = "Base",
1345
        quote_annotations: bool = False,
1346
        metadata_key: str = "sa",
1347
    ):
1348
        super().__init__(
5✔
1349
            metadata,
1350
            bind,
1351
            options,
1352
            indentation=indentation,
1353
            base_class_name=base_class_name,
1354
        )
1355
        self.metadata_key: str = metadata_key
5✔
1356
        self.quote_annotations: bool = quote_annotations
5✔
1357

1358
    def generate_base(self) -> None:
5✔
1359
        self.base = Base(
5✔
1360
            literal_imports=[
1361
                LiteralImport("sqlalchemy.orm", "DeclarativeBase"),
1362
                LiteralImport("sqlalchemy.orm", "MappedAsDataclass"),
1363
            ],
1364
            declarations=[
1365
                (f"class {self.base_class_name}(MappedAsDataclass, DeclarativeBase):"),
1366
                f"{self.indentation}pass",
1367
            ],
1368
            metadata_ref=f"{self.base_class_name}.metadata",
1369
        )
1370

1371

1372
class SQLModelGenerator(DeclarativeGenerator):
5✔
1373
    def __init__(
5✔
1374
        self,
1375
        metadata: MetaData,
1376
        bind: Connection | Engine,
1377
        options: Sequence[str],
1378
        *,
1379
        indentation: str = "    ",
1380
        base_class_name: str = "SQLModel",
1381
    ):
1382
        super().__init__(
5✔
1383
            metadata,
1384
            bind,
1385
            options,
1386
            indentation=indentation,
1387
            base_class_name=base_class_name,
1388
        )
1389

1390
    @property
5✔
1391
    def views_supported(self) -> bool:
5✔
1392
        return False
×
1393

1394
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
1395
        self.add_import(Column)
5✔
1396
        return render_callable("Column", *args, kwargs=kwargs)
5✔
1397

1398
    def generate_base(self) -> None:
5✔
1399
        self.base = Base(
5✔
1400
            literal_imports=[],
1401
            declarations=[],
1402
            metadata_ref="",
1403
        )
1404

1405
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1406
        super(DeclarativeGenerator, self).collect_imports(models)
5✔
1407
        if any(isinstance(model, ModelClass) for model in models):
5✔
1408
            self.remove_literal_import("sqlalchemy", "MetaData")
5✔
1409
            self.add_literal_import("sqlmodel", "SQLModel")
5✔
1410
            self.add_literal_import("sqlmodel", "Field")
5✔
1411

1412
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1413
        super(DeclarativeGenerator, self).collect_imports_for_model(model)
5✔
1414
        if isinstance(model, ModelClass):
5✔
1415
            for column_attr in model.columns:
5✔
1416
                if column_attr.column.nullable:
5✔
1417
                    self.add_literal_import("typing", "Optional")
5✔
1418
                    break
5✔
1419

1420
            if model.relationships:
5✔
1421
                self.add_literal_import("sqlmodel", "Relationship")
5✔
1422

1423
    def collect_imports_for_column(self, column: Column[Any]) -> None:
5✔
1424
        super().collect_imports_for_column(column)
5✔
1425
        try:
5✔
1426
            python_type = column.type.python_type
5✔
1427
        except NotImplementedError:
×
1428
            self.add_literal_import("typing", "Any")
×
1429
        else:
1430
            self.add_import(python_type)
5✔
1431

1432
    def render_module_variables(self, models: list[Model]) -> str:
5✔
1433
        declarations: list[str] = []
5✔
1434
        if any(not isinstance(model, ModelClass) for model in models):
5✔
1435
            if self.base.table_metadata_declaration is not None:
×
1436
                declarations.append(self.base.table_metadata_declaration)
×
1437

1438
        return "\n".join(declarations)
5✔
1439

1440
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1441
        if model.parent_class:
5✔
1442
            parent = model.parent_class.name
×
1443
        else:
1444
            parent = self.base_class_name
5✔
1445

1446
        superclass_part = f"({parent}, table=True)"
5✔
1447
        return f"class {model.name}{superclass_part}:"
5✔
1448

1449
    def render_class_variables(self, model: ModelClass) -> str:
5✔
1450
        variables = []
5✔
1451

1452
        if model.table.name != model.name.lower():
5✔
1453
            variables.append(f"__tablename__ = {model.table.name!r}")
5✔
1454

1455
        # Render constraints and indexes as __table_args__
1456
        table_args = self.render_table_args(model.table)
5✔
1457
        if table_args:
5✔
1458
            variables.append(f"__table_args__ = {table_args}")
5✔
1459

1460
        return "\n".join(variables)
5✔
1461

1462
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1463
        column = column_attr.column
5✔
1464
        try:
5✔
1465
            python_type = column.type.python_type
5✔
1466
        except NotImplementedError:
×
1467
            python_type_name = "Any"
×
1468
        else:
1469
            python_type_name = python_type.__name__
5✔
1470

1471
        kwargs: dict[str, Any] = {}
5✔
1472
        if (
5✔
1473
            column.autoincrement and column.name in column.table.primary_key
1474
        ) or column.nullable:
1475
            self.add_literal_import("typing", "Optional")
5✔
1476
            kwargs["default"] = None
5✔
1477
            python_type_name = f"Optional[{python_type_name}]"
5✔
1478

1479
        rendered_column = self.render_column(column, True)
5✔
1480
        kwargs["sa_column"] = f"{rendered_column}"
5✔
1481
        rendered_field = render_callable("Field", kwargs=kwargs)
5✔
1482
        return f"{column_attr.name}: {python_type_name} = {rendered_field}"
5✔
1483

1484
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1485
        rendered = super().render_relationship(relationship).partition(" = ")[2]
5✔
1486
        args = self.render_relationship_args(rendered)
5✔
1487
        kwargs: dict[str, Any] = {}
5✔
1488
        annotation = repr(relationship.target.name)
5✔
1489

1490
        if relationship.type in (
5✔
1491
            RelationshipType.ONE_TO_MANY,
1492
            RelationshipType.MANY_TO_MANY,
1493
        ):
1494
            annotation = f"list[{annotation}]"
5✔
1495
        else:
1496
            self.add_literal_import("typing", "Optional")
5✔
1497
            annotation = f"Optional[{annotation}]"
5✔
1498

1499
        rendered_field = render_callable("Relationship", *args, kwargs=kwargs)
5✔
1500
        return f"{relationship.name}: {annotation} = {rendered_field}"
5✔
1501

1502
    def render_relationship_args(self, arguments: str) -> list[str]:
5✔
1503
        argument_list = arguments.split(",")
5✔
1504
        # delete ')' and ' ' from args
1505
        argument_list[-1] = argument_list[-1][:-1]
5✔
1506
        argument_list = [argument[1:] for argument in argument_list]
5✔
1507

1508
        rendered_args: list[str] = []
5✔
1509
        for arg in argument_list:
5✔
1510
            if "back_populates" in arg:
5✔
1511
                rendered_args.append(arg)
5✔
1512
            if "uselist=False" in arg:
5✔
1513
                rendered_args.append("sa_relationship_kwargs={'uselist': False}")
5✔
1514

1515
        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