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

agronholm / sqlacodegen / 16748862564

05 Aug 2025 11:33AM UTC coverage: 97.662% (-0.001%) from 97.663%
16748862564

Pull #419

github

web-flow
Merge 8b6794b27 into 296555629
Pull Request #419: Better nullability definitions for all generators

10 of 10 new or added lines in 2 files covered. (100.0%)

17 existing lines in 1 file now uncovered.

1420 of 1454 relevant lines covered (97.66%)

4.87 hits per line

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

96.9
/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]] = {"noindexes", "noconstraints", "nocomments"}
5✔
123
    stdlib_module_names: ClassVar[set[str]] = get_stdlib_module_names()
5✔
124

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

276
            if type_.__name__ in dialect_pkg.__all__:
5✔
277
                pkgname = dialect_pkgname
5✔
278
        elif type_ is getattr(sqlalchemy, type_.__name__, None):
5✔
279
            pkgname = "sqlalchemy"
5✔
280
        else:
281
            pkgname = type_.__module__
5✔
282

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

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

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

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

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

302
        def get_collection(package: str) -> list[str]:
5✔
303
            collection = thirdparty_imports
5✔
304
            if package == "__future__":
5✔
305
                collection = future_imports
×
306
            elif package in self.stdlib_module_names:
5✔
307
                collection = stdlib_imports
5✔
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
            return collection
5✔
312

313
        for package in sorted(self.imports):
5✔
314
            imports = ", ".join(sorted(self.imports[package]))
5✔
315

316
            collection = get_collection(package)
5✔
317
            collection.append(f"from {package} import {imports}")
5✔
318

319
        for module in sorted(self.module_imports):
5✔
320
            collection = get_collection(module)
5✔
321
            collection.append(f"import {module}")
5✔
322

323
        return [
5✔
324
            group
325
            for group in (future_imports, stdlib_imports, thirdparty_imports)
326
            if group
327
        ]
328

329
    def generate_models(self) -> list[Model]:
5✔
330
        models = [Model(table) for table in self.metadata.sorted_tables]
5✔
331

332
        # Collect the imports
333
        self.collect_imports(models)
5✔
334

335
        # Generate names for models
336
        global_names = {
5✔
337
            name for namespace in self.imports.values() for name in namespace
338
        }
339
        for model in models:
5✔
340
            self.generate_model_name(model, global_names)
5✔
341
            global_names.add(model.name)
5✔
342

343
        return models
5✔
344

345
    def generate_model_name(self, model: Model, global_names: set[str]) -> None:
5✔
346
        preferred_name = f"t_{model.table.name}"
5✔
347
        model.name = self.find_free_name(preferred_name, global_names)
5✔
348

349
    def render_module_variables(self, models: list[Model]) -> str:
5✔
350
        declarations = self.base.declarations
5✔
351

352
        if any(not isinstance(model, ModelClass) for model in models):
5✔
353
            if self.base.table_metadata_declaration is not None:
5✔
354
                declarations.append(self.base.table_metadata_declaration)
×
355

356
        return "\n".join(declarations)
5✔
357

358
    def render_models(self, models: list[Model]) -> str:
5✔
359
        rendered: list[str] = []
5✔
360
        for model in models:
5✔
361
            rendered_table = self.render_table(model.table)
5✔
362
            rendered.append(f"{model.name} = {rendered_table}")
5✔
363

364
        return "\n\n".join(rendered)
5✔
365

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

374
        for constraint in sorted(table.constraints, key=get_constraint_sort_key):
5✔
375
            if uses_default_name(constraint):
5✔
376
                if isinstance(constraint, PrimaryKeyConstraint):
5✔
377
                    continue
5✔
378
                elif isinstance(constraint, (ForeignKeyConstraint, UniqueConstraint)):
5✔
379
                    if len(constraint.columns) == 1:
5✔
380
                        continue
5✔
381

382
            args.append(self.render_constraint(constraint))
5✔
383

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

389
        if table.schema:
5✔
390
            kwargs["schema"] = repr(table.schema)
5✔
391

392
        table_comment = getattr(table, "comment", None)
5✔
393
        if table_comment:
5✔
394
            kwargs["comment"] = repr(table.comment)
5✔
395

396
        return render_callable("Table", *args, kwargs=kwargs, indentation="    ")
5✔
397

398
    def render_index(self, index: Index) -> str:
5✔
399
        extra_args = [repr(col.name) for col in index.columns]
5✔
400
        kwargs = {}
5✔
401
        if index.unique:
5✔
402
            kwargs["unique"] = True
5✔
403

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

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

444
        if show_name:
5✔
445
            args.append(repr(column.name))
5✔
446

447
        # Render the column type if there are no foreign keys on it or any of them
448
        # points back to itself
449
        if not dedicated_fks or any(fk.column is column for fk in dedicated_fks):
5✔
450
            args.append(self.render_column_type(column.type))
5✔
451

452
        for fk in dedicated_fks:
5✔
453
            args.append(self.render_constraint(fk))
5✔
454

455
        if column.default:
5✔
456
            args.append(repr(column.default))
5✔
457

458
        if column.key != column.name:
5✔
UNCOV
459
            kwargs["key"] = column.key
×
460
        if is_primary:
5✔
461
            kwargs["primary_key"] = True
5✔
462
        if not column.nullable and not column.primary_key:
5✔
463
            kwargs["nullable"] = False
5✔
464

465
        if is_unique:
5✔
466
            column.unique = True
5✔
467
            kwargs["unique"] = True
5✔
468
        if has_index:
5✔
469
            column.index = True
5✔
470
            kwarg.append("index")
5✔
471
            kwargs["index"] = True
5✔
472

473
        if isinstance(column.server_default, DefaultClause):
5✔
474
            kwargs["server_default"] = render_callable(
5✔
475
                "text", repr(cast(TextClause, column.server_default.arg).text)
476
            )
477
        elif isinstance(column.server_default, Computed):
5✔
478
            expression = str(column.server_default.sqltext)
5✔
479

480
            computed_kwargs = {}
5✔
481
            if column.server_default.persisted is not None:
5✔
482
                computed_kwargs["persisted"] = column.server_default.persisted
5✔
483

484
            args.append(
5✔
485
                render_callable("Computed", repr(expression), kwargs=computed_kwargs)
486
            )
487
        elif isinstance(column.server_default, Identity):
5✔
488
            args.append(repr(column.server_default))
5✔
489
        elif column.server_default:
5✔
UNCOV
490
            kwargs["server_default"] = repr(column.server_default)
×
491

492
        comment = getattr(column, "comment", None)
5✔
493
        if comment:
5✔
494
            kwargs["comment"] = repr(comment)
5✔
495

496
        return self.render_column_callable(is_table, *args, **kwargs)
5✔
497

498
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
499
        if is_table:
5✔
500
            self.add_import(Column)
5✔
501
            return render_callable("Column", *args, kwargs=kwargs)
5✔
502
        else:
503
            return render_callable("mapped_column", *args, kwargs=kwargs)
5✔
504

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

520
            value = getattr(coltype, param.name, missing)
5✔
521

522
            if isinstance(value, (JSONB, JSON)):
5✔
523
                # Remove astext_type if it's the default
524
                if (
5✔
525
                    isinstance(value.astext_type, Text)
526
                    and value.astext_type.length is None
527
                ):
528
                    value.astext_type = None  # type: ignore[assignment]
5✔
529
                else:
530
                    self.add_import(Text)
5✔
531

532
            default = defaults.get(param.name, missing)
5✔
533
            if isinstance(value, TextClause):
5✔
534
                self.add_literal_import("sqlalchemy", "text")
5✔
535
                rendered_value = render_callable("text", repr(value.text))
5✔
536
            else:
537
                rendered_value = repr(value)
5✔
538

539
            if value is missing or value == default:
5✔
540
                use_kwargs = True
5✔
541
            elif use_kwargs:
5✔
542
                kwargs[param.name] = rendered_value
5✔
543
            else:
544
                args.append(rendered_value)
5✔
545

546
        vararg = next(
5✔
547
            (
548
                param.name
549
                for param in sig.parameters.values()
550
                if param.kind is Parameter.VAR_POSITIONAL
551
            ),
552
            None,
553
        )
554
        if vararg and hasattr(coltype, vararg):
5✔
555
            varargs_repr = [repr(arg) for arg in getattr(coltype, vararg)]
5✔
556
            args.extend(varargs_repr)
5✔
557

558
        # These arguments cannot be autodetected from the Enum initializer
559
        if isinstance(coltype, Enum):
5✔
560
            for colname in "name", "schema":
5✔
561
                if (value := getattr(coltype, colname)) is not None:
5✔
562
                    kwargs[colname] = repr(value)
5✔
563

564
        if isinstance(coltype, (JSONB, JSON)):
5✔
565
            # Remove astext_type if it's the default
566
            if (
5✔
567
                isinstance(coltype.astext_type, Text)
568
                and coltype.astext_type.length is None
569
            ):
570
                del kwargs["astext_type"]
5✔
571

572
        if args or kwargs:
5✔
573
            return render_callable(coltype.__class__.__name__, *args, kwargs=kwargs)
5✔
574
        else:
575
            return coltype.__class__.__name__
5✔
576

577
    def render_constraint(self, constraint: Constraint | ForeignKey) -> str:
5✔
578
        def add_fk_options(*opts: Any) -> None:
5✔
579
            args.extend(repr(opt) for opt in opts)
5✔
580
            for attr in "ondelete", "onupdate", "deferrable", "initially", "match":
5✔
581
                value = getattr(constraint, attr, None)
5✔
582
                if value:
5✔
583
                    kwargs[attr] = repr(value)
5✔
584

585
        args: list[str] = []
5✔
586
        kwargs: dict[str, Any] = {}
5✔
587
        if isinstance(constraint, ForeignKey):
5✔
588
            remote_column = (
5✔
589
                f"{constraint.column.table.fullname}.{constraint.column.name}"
590
            )
591
            add_fk_options(remote_column)
5✔
592
        elif isinstance(constraint, ForeignKeyConstraint):
5✔
593
            local_columns = get_column_names(constraint)
5✔
594
            remote_columns = [
5✔
595
                f"{fk.column.table.fullname}.{fk.column.name}"
596
                for fk in constraint.elements
597
            ]
598
            add_fk_options(local_columns, remote_columns)
5✔
599
        elif isinstance(constraint, CheckConstraint):
5✔
600
            args.append(repr(get_compiled_expression(constraint.sqltext, self.bind)))
5✔
601
        elif isinstance(constraint, (UniqueConstraint, PrimaryKeyConstraint)):
5✔
602
            args.extend(repr(col.name) for col in constraint.columns)
5✔
603
        else:
UNCOV
604
            raise TypeError(
×
605
                f"Cannot render constraint of type {constraint.__class__.__name__}"
606
            )
607

608
        if isinstance(constraint, Constraint) and not uses_default_name(constraint):
5✔
609
            kwargs["name"] = repr(constraint.name)
5✔
610

611
        return render_callable(constraint.__class__.__name__, *args, kwargs=kwargs)
5✔
612

613
    def should_ignore_table(self, table: Table) -> bool:
5✔
614
        # Support for Alembic and sqlalchemy-migrate -- never expose the schema version
615
        # tables
616
        return table.name in ("alembic_version", "migrate_version")
5✔
617

618
    def find_free_name(
5✔
619
        self, name: str, global_names: set[str], local_names: Collection[str] = ()
620
    ) -> str:
621
        """
622
        Generate an attribute name that does not clash with other local or global names.
623
        """
624
        name = name.strip()
5✔
625
        assert name, "Identifier cannot be empty"
5✔
626
        name = _re_invalid_identifier.sub("_", name)
5✔
627
        if name[0].isdigit():
5✔
628
            name = "_" + name
5✔
629
        elif iskeyword(name) or name == "metadata":
5✔
630
            name += "_"
5✔
631

632
        original = name
5✔
633
        for i in count():
5✔
634
            if name not in global_names and name not in local_names:
5✔
635
                break
5✔
636

637
            name = original + (str(i) if i else "_")
5✔
638

639
        return name
5✔
640

641
    def fix_column_types(self, table: Table) -> None:
5✔
642
        """Adjust the reflected column types."""
643
        # Detect check constraints for boolean and enum columns
644
        for constraint in table.constraints.copy():
5✔
645
            if isinstance(constraint, CheckConstraint):
5✔
646
                sqltext = get_compiled_expression(constraint.sqltext, self.bind)
5✔
647

648
                # Turn any integer-like column with a CheckConstraint like
649
                # "column IN (0, 1)" into a Boolean
650
                match = _re_boolean_check_constraint.match(sqltext)
5✔
651
                if match:
5✔
652
                    colname_match = _re_column_name.match(match.group(1))
5✔
653
                    if colname_match:
5✔
654
                        colname = colname_match.group(3)
5✔
655
                        table.constraints.remove(constraint)
5✔
656
                        table.c[colname].type = Boolean()
5✔
657
                        continue
5✔
658

659
                # Turn any string-type column with a CheckConstraint like
660
                # "column IN (...)" into an Enum
661
                match = _re_enum_check_constraint.match(sqltext)
5✔
662
                if match:
5✔
663
                    colname_match = _re_column_name.match(match.group(1))
5✔
664
                    if colname_match:
5✔
665
                        colname = colname_match.group(3)
5✔
666
                        items = match.group(2)
5✔
667
                        if isinstance(table.c[colname].type, String):
5✔
668
                            table.constraints.remove(constraint)
5✔
669
                            if not isinstance(table.c[colname].type, Enum):
5✔
670
                                options = _re_enum_item.findall(items)
5✔
671
                                table.c[colname].type = Enum(
5✔
672
                                    *options, native_enum=False
673
                                )
674

675
                            continue
5✔
676

677
        for column in table.c:
5✔
678
            try:
5✔
679
                column.type = self.get_adapted_type(column.type)
5✔
680
            except CompileError:
5✔
681
                pass
5✔
682

683
            # PostgreSQL specific fix: detect sequences from server_default
684
            if column.server_default and self.bind.dialect.name == "postgresql":
5✔
685
                if isinstance(column.server_default, DefaultClause) and isinstance(
5✔
686
                    column.server_default.arg, TextClause
687
                ):
688
                    schema, seqname = decode_postgresql_sequence(
5✔
689
                        column.server_default.arg
690
                    )
691
                    if seqname:
5✔
692
                        # Add an explicit sequence
693
                        if seqname != f"{column.table.name}_{column.name}_seq":
5✔
694
                            column.default = sqlalchemy.Sequence(seqname, schema=schema)
5✔
695

696
                        column.server_default = None
5✔
697

698
    def get_adapted_type(self, coltype: Any) -> Any:
5✔
699
        compiled_type = coltype.compile(self.bind.engine.dialect)
5✔
700
        for supercls in coltype.__class__.__mro__:
5✔
701
            if not supercls.__name__.startswith("_") and hasattr(
5✔
702
                supercls, "__visit_name__"
703
            ):
704
                # Don't try to adapt UserDefinedType as it's not a proper column type
705
                if supercls is UserDefinedType or issubclass(supercls, TypeDecorator):
5✔
706
                    return coltype
5✔
707

708
                # Hack to fix adaptation of the Enum class which is broken since
709
                # SQLAlchemy 1.2
710
                kw = {}
5✔
711
                if supercls is Enum:
5✔
712
                    kw["name"] = coltype.name
5✔
713
                    if coltype.schema:
5✔
714
                        kw["schema"] = coltype.schema
5✔
715

716
                try:
5✔
717
                    new_coltype = coltype.adapt(supercls)
5✔
718
                except TypeError:
5✔
719
                    # If the adaptation fails, don't try again
720
                    break
5✔
721

722
                for key, value in kw.items():
5✔
723
                    setattr(new_coltype, key, value)
5✔
724

725
                if isinstance(coltype, ARRAY):
5✔
726
                    new_coltype.item_type = self.get_adapted_type(new_coltype.item_type)
5✔
727

728
                try:
5✔
729
                    # If the adapted column type does not render the same as the
730
                    # original, don't substitute it
731
                    if new_coltype.compile(self.bind.engine.dialect) != compiled_type:
5✔
732
                        break
5✔
733
                except CompileError:
5✔
734
                    # If the adapted column type can't be compiled, don't substitute it
735
                    break
5✔
736

737
                # Stop on the first valid non-uppercase column type class
738
                coltype = new_coltype
5✔
739
                if supercls.__name__ != supercls.__name__.upper():
5✔
740
                    break
5✔
741

742
        return coltype
5✔
743

744

745
class DeclarativeGenerator(TablesGenerator):
5✔
746
    valid_options: ClassVar[set[str]] = TablesGenerator.valid_options | {
5✔
747
        "use_inflect",
748
        "nojoined",
749
        "nobidi",
750
    }
751

752
    def __init__(
5✔
753
        self,
754
        metadata: MetaData,
755
        bind: Connection | Engine,
756
        options: Sequence[str],
757
        *,
758
        indentation: str = "    ",
759
        base_class_name: str = "Base",
760
    ):
761
        super().__init__(metadata, bind, options, indentation=indentation)
5✔
762
        self.base_class_name: str = base_class_name
5✔
763
        self.inflect_engine = inflect.engine()
5✔
764

765
    def generate_base(self) -> None:
5✔
766
        self.base = Base(
5✔
767
            literal_imports=[LiteralImport("sqlalchemy.orm", "DeclarativeBase")],
768
            declarations=[
769
                f"class {self.base_class_name}(DeclarativeBase):",
770
                f"{self.indentation}pass",
771
            ],
772
            metadata_ref=f"{self.base_class_name}.metadata",
773
        )
774

775
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
776
        super().collect_imports(models)
5✔
777
        if any(isinstance(model, ModelClass) for model in models):
5✔
778
            self.add_literal_import("sqlalchemy.orm", "Mapped")
5✔
779
            self.add_literal_import("sqlalchemy.orm", "mapped_column")
5✔
780

781
    def collect_imports_for_model(self, model: Model) -> None:
5✔
782
        super().collect_imports_for_model(model)
5✔
783
        if isinstance(model, ModelClass):
5✔
784
            if model.relationships:
5✔
785
                self.add_literal_import("sqlalchemy.orm", "relationship")
5✔
786

787
    def generate_models(self) -> list[Model]:
5✔
788
        models_by_table_name: dict[str, Model] = {}
5✔
789

790
        # Pick association tables from the metadata into their own set, don't process
791
        # them normally
792
        links: defaultdict[str, list[Model]] = defaultdict(lambda: [])
5✔
793
        for table in self.metadata.sorted_tables:
5✔
794
            qualified_name = qualified_table_name(table)
5✔
795

796
            # Link tables have exactly two foreign key constraints and all columns are
797
            # involved in them
798
            fk_constraints = sorted(
5✔
799
                table.foreign_key_constraints, key=get_constraint_sort_key
800
            )
801
            if len(fk_constraints) == 2 and all(
5✔
802
                col.foreign_keys for col in table.columns
803
            ):
804
                model = models_by_table_name[qualified_name] = Model(table)
5✔
805
                tablename = fk_constraints[0].elements[0].column.table.name
5✔
806
                links[tablename].append(model)
5✔
807
                continue
5✔
808

809
            # Only form model classes for tables that have a primary key and are not
810
            # association tables
811
            if not table.primary_key:
5✔
812
                models_by_table_name[qualified_name] = Model(table)
5✔
813
            else:
814
                model = ModelClass(table)
5✔
815
                models_by_table_name[qualified_name] = model
5✔
816

817
                # Fill in the columns
818
                for column in table.c:
5✔
819
                    column_attr = ColumnAttribute(model, column)
5✔
820
                    model.columns.append(column_attr)
5✔
821

822
        # Add relationships
823
        for model in models_by_table_name.values():
5✔
824
            if isinstance(model, ModelClass):
5✔
825
                self.generate_relationships(
5✔
826
                    model, models_by_table_name, links[model.table.name]
827
                )
828

829
        # Nest inherited classes in their superclasses to ensure proper ordering
830
        if "nojoined" not in self.options:
5✔
831
            for model in list(models_by_table_name.values()):
5✔
832
                if not isinstance(model, ModelClass):
5✔
833
                    continue
5✔
834

835
                pk_column_names = {col.name for col in model.table.primary_key.columns}
5✔
836
                for constraint in model.table.foreign_key_constraints:
5✔
837
                    if set(get_column_names(constraint)) == pk_column_names:
5✔
838
                        target = models_by_table_name[
5✔
839
                            qualified_table_name(constraint.elements[0].column.table)
840
                        ]
841
                        if isinstance(target, ModelClass):
5✔
842
                            model.parent_class = target
5✔
843
                            target.children.append(model)
5✔
844

845
        # Change base if we only have tables
846
        if not any(
5✔
847
            isinstance(model, ModelClass) for model in models_by_table_name.values()
848
        ):
849
            super().generate_base()
5✔
850

851
        # Collect the imports
852
        self.collect_imports(models_by_table_name.values())
5✔
853

854
        # Rename models and their attributes that conflict with imports or other
855
        # attributes
856
        global_names = {
5✔
857
            name for namespace in self.imports.values() for name in namespace
858
        }
859
        for model in models_by_table_name.values():
5✔
860
            self.generate_model_name(model, global_names)
5✔
861
            global_names.add(model.name)
5✔
862

863
        return list(models_by_table_name.values())
5✔
864

865
    def generate_relationships(
5✔
866
        self,
867
        source: ModelClass,
868
        models_by_table_name: dict[str, Model],
869
        association_tables: list[Model],
870
    ) -> list[RelationshipAttribute]:
871
        relationships: list[RelationshipAttribute] = []
5✔
872
        reverse_relationship: RelationshipAttribute | None
873

874
        # Add many-to-one (and one-to-many) relationships
875
        pk_column_names = {col.name for col in source.table.primary_key.columns}
5✔
876
        for constraint in sorted(
5✔
877
            source.table.foreign_key_constraints, key=get_constraint_sort_key
878
        ):
879
            target = models_by_table_name[
5✔
880
                qualified_table_name(constraint.elements[0].column.table)
881
            ]
882
            if isinstance(target, ModelClass):
5✔
883
                if "nojoined" not in self.options:
5✔
884
                    if set(get_column_names(constraint)) == pk_column_names:
5✔
885
                        parent = models_by_table_name[
5✔
886
                            qualified_table_name(constraint.elements[0].column.table)
887
                        ]
888
                        if isinstance(parent, ModelClass):
5✔
889
                            source.parent_class = parent
5✔
890
                            parent.children.append(source)
5✔
891
                            continue
5✔
892

893
                # Add uselist=False to One-to-One relationships
894
                column_names = get_column_names(constraint)
5✔
895
                if any(
5✔
896
                    isinstance(c, (PrimaryKeyConstraint, UniqueConstraint))
897
                    and {col.name for col in c.columns} == set(column_names)
898
                    for c in constraint.table.constraints
899
                ):
900
                    r_type = RelationshipType.ONE_TO_ONE
5✔
901
                else:
902
                    r_type = RelationshipType.MANY_TO_ONE
5✔
903

904
                relationship = RelationshipAttribute(r_type, source, target, constraint)
5✔
905
                source.relationships.append(relationship)
5✔
906

907
                # For self referential relationships, remote_side needs to be set
908
                if source is target:
5✔
909
                    relationship.remote_side = [
5✔
910
                        source.get_column_attribute(col.name)
911
                        for col in constraint.referred_table.primary_key
912
                    ]
913

914
                # If the two tables share more than one foreign key constraint,
915
                # SQLAlchemy needs an explicit primaryjoin to figure out which column(s)
916
                # it needs
917
                common_fk_constraints = get_common_fk_constraints(
5✔
918
                    source.table, target.table
919
                )
920
                if len(common_fk_constraints) > 1:
5✔
921
                    relationship.foreign_keys = [
5✔
922
                        source.get_column_attribute(key)
923
                        for key in constraint.column_keys
924
                    ]
925

926
                # Generate the opposite end of the relationship in the target class
927
                if "nobidi" not in self.options:
5✔
928
                    if r_type is RelationshipType.MANY_TO_ONE:
5✔
929
                        r_type = RelationshipType.ONE_TO_MANY
5✔
930

931
                    reverse_relationship = RelationshipAttribute(
5✔
932
                        r_type,
933
                        target,
934
                        source,
935
                        constraint,
936
                        foreign_keys=relationship.foreign_keys,
937
                        backref=relationship,
938
                    )
939
                    relationship.backref = reverse_relationship
5✔
940
                    target.relationships.append(reverse_relationship)
5✔
941

942
                    # For self referential relationships, remote_side needs to be set
943
                    if source is target:
5✔
944
                        reverse_relationship.remote_side = [
5✔
945
                            source.get_column_attribute(colname)
946
                            for colname in constraint.column_keys
947
                        ]
948

949
        # Add many-to-many relationships
950
        for association_table in association_tables:
5✔
951
            fk_constraints = sorted(
5✔
952
                association_table.table.foreign_key_constraints,
953
                key=get_constraint_sort_key,
954
            )
955
            target = models_by_table_name[
5✔
956
                qualified_table_name(fk_constraints[1].elements[0].column.table)
957
            ]
958
            if isinstance(target, ModelClass):
5✔
959
                relationship = RelationshipAttribute(
5✔
960
                    RelationshipType.MANY_TO_MANY,
961
                    source,
962
                    target,
963
                    fk_constraints[1],
964
                    association_table,
965
                )
966
                source.relationships.append(relationship)
5✔
967

968
                # Generate the opposite end of the relationship in the target class
969
                reverse_relationship = None
5✔
970
                if "nobidi" not in self.options:
5✔
971
                    reverse_relationship = RelationshipAttribute(
5✔
972
                        RelationshipType.MANY_TO_MANY,
973
                        target,
974
                        source,
975
                        fk_constraints[0],
976
                        association_table,
977
                        relationship,
978
                    )
979
                    relationship.backref = reverse_relationship
5✔
980
                    target.relationships.append(reverse_relationship)
5✔
981

982
                # Add a primary/secondary join for self-referential many-to-many
983
                # relationships
984
                if source is target:
5✔
985
                    both_relationships = [relationship]
5✔
986
                    reverse_flags = [False, True]
5✔
987
                    if reverse_relationship:
5✔
988
                        both_relationships.append(reverse_relationship)
5✔
989

990
                    for relationship, reverse in zip(both_relationships, reverse_flags):
5✔
991
                        if (
5✔
992
                            not relationship.association_table
993
                            or not relationship.constraint
994
                        ):
UNCOV
995
                            continue
×
996

997
                        constraints = sorted(
5✔
998
                            relationship.constraint.table.foreign_key_constraints,
999
                            key=get_constraint_sort_key,
1000
                            reverse=reverse,
1001
                        )
1002
                        pri_pairs = zip(
5✔
1003
                            get_column_names(constraints[0]), constraints[0].elements
1004
                        )
1005
                        sec_pairs = zip(
5✔
1006
                            get_column_names(constraints[1]), constraints[1].elements
1007
                        )
1008
                        relationship.primaryjoin = [
5✔
1009
                            (
1010
                                relationship.source,
1011
                                elem.column.name,
1012
                                relationship.association_table,
1013
                                col,
1014
                            )
1015
                            for col, elem in pri_pairs
1016
                        ]
1017
                        relationship.secondaryjoin = [
5✔
1018
                            (
1019
                                relationship.target,
1020
                                elem.column.name,
1021
                                relationship.association_table,
1022
                                col,
1023
                            )
1024
                            for col, elem in sec_pairs
1025
                        ]
1026

1027
        return relationships
5✔
1028

1029
    def generate_model_name(self, model: Model, global_names: set[str]) -> None:
5✔
1030
        if isinstance(model, ModelClass):
5✔
1031
            preferred_name = _re_invalid_identifier.sub("_", model.table.name)
5✔
1032
            preferred_name = "".join(
5✔
1033
                part[:1].upper() + part[1:] for part in preferred_name.split("_")
1034
            )
1035
            if "use_inflect" in self.options:
5✔
1036
                singular_name = self.inflect_engine.singular_noun(preferred_name)
5✔
1037
                if singular_name:
5✔
1038
                    preferred_name = singular_name
5✔
1039

1040
            model.name = self.find_free_name(preferred_name, global_names)
5✔
1041

1042
            # Fill in the names for column attributes
1043
            local_names: set[str] = set()
5✔
1044
            for column_attr in model.columns:
5✔
1045
                self.generate_column_attr_name(column_attr, global_names, local_names)
5✔
1046
                local_names.add(column_attr.name)
5✔
1047

1048
            # Fill in the names for relationship attributes
1049
            for relationship in model.relationships:
5✔
1050
                self.generate_relationship_name(relationship, global_names, local_names)
5✔
1051
                local_names.add(relationship.name)
5✔
1052
        else:
1053
            super().generate_model_name(model, global_names)
5✔
1054

1055
    def generate_column_attr_name(
5✔
1056
        self,
1057
        column_attr: ColumnAttribute,
1058
        global_names: set[str],
1059
        local_names: set[str],
1060
    ) -> None:
1061
        column_attr.name = self.find_free_name(
5✔
1062
            column_attr.column.name, global_names, local_names
1063
        )
1064

1065
    def generate_relationship_name(
5✔
1066
        self,
1067
        relationship: RelationshipAttribute,
1068
        global_names: set[str],
1069
        local_names: set[str],
1070
    ) -> None:
1071
        # Self referential reverse relationships
1072
        preferred_name: str
1073
        if (
5✔
1074
            relationship.type
1075
            in (RelationshipType.ONE_TO_MANY, RelationshipType.ONE_TO_ONE)
1076
            and relationship.source is relationship.target
1077
            and relationship.backref
1078
            and relationship.backref.name
1079
        ):
1080
            preferred_name = relationship.backref.name + "_reverse"
5✔
1081
        else:
1082
            preferred_name = relationship.target.table.name
5✔
1083

1084
            # If there's a constraint with a single column that ends with "_id", use the
1085
            # preceding part as the relationship name
1086
            if relationship.constraint:
5✔
1087
                is_source = relationship.source.table is relationship.constraint.table
5✔
1088
                if is_source or relationship.type not in (
5✔
1089
                    RelationshipType.ONE_TO_ONE,
1090
                    RelationshipType.ONE_TO_MANY,
1091
                ):
1092
                    column_names = [c.name for c in relationship.constraint.columns]
5✔
1093
                    if len(column_names) == 1 and column_names[0].endswith("_id"):
5✔
1094
                        preferred_name = column_names[0][:-3]
5✔
1095

1096
            if "use_inflect" in self.options:
5✔
1097
                inflected_name: str | Literal[False]
1098
                if relationship.type in (
5✔
1099
                    RelationshipType.ONE_TO_MANY,
1100
                    RelationshipType.MANY_TO_MANY,
1101
                ):
1102
                    if not self.inflect_engine.singular_noun(preferred_name):
5✔
UNCOV
1103
                        preferred_name = self.inflect_engine.plural_noun(preferred_name)
×
1104
                else:
1105
                    inflected_name = self.inflect_engine.singular_noun(preferred_name)
5✔
1106
                    if inflected_name:
5✔
1107
                        preferred_name = inflected_name
5✔
1108

1109
        relationship.name = self.find_free_name(
5✔
1110
            preferred_name, global_names, local_names
1111
        )
1112

1113
    def render_models(self, models: list[Model]) -> str:
5✔
1114
        rendered: list[str] = []
5✔
1115
        for model in models:
5✔
1116
            if isinstance(model, ModelClass):
5✔
1117
                rendered.append(self.render_class(model))
5✔
1118
            else:
1119
                rendered.append(f"{model.name} = {self.render_table(model.table)}")
5✔
1120

1121
        return "\n\n\n".join(rendered)
5✔
1122

1123
    def render_class(self, model: ModelClass) -> str:
5✔
1124
        sections: list[str] = []
5✔
1125

1126
        # Render class variables / special declarations
1127
        class_vars: str = self.render_class_variables(model)
5✔
1128
        if class_vars:
5✔
1129
            sections.append(class_vars)
5✔
1130

1131
        # Render column attributes
1132
        rendered_column_attributes: list[str] = []
5✔
1133
        for nullable in (False, True):
5✔
1134
            for column_attr in model.columns:
5✔
1135
                if column_attr.column.nullable is nullable:
5✔
1136
                    rendered_column_attributes.append(
5✔
1137
                        self.render_column_attribute(column_attr)
1138
                    )
1139

1140
        if rendered_column_attributes:
5✔
1141
            sections.append("\n".join(rendered_column_attributes))
5✔
1142

1143
        # Render relationship attributes
1144
        rendered_relationship_attributes: list[str] = [
5✔
1145
            self.render_relationship(relationship)
1146
            for relationship in model.relationships
1147
        ]
1148

1149
        if rendered_relationship_attributes:
5✔
1150
            sections.append("\n".join(rendered_relationship_attributes))
5✔
1151

1152
        declaration = self.render_class_declaration(model)
5✔
1153
        rendered_sections = "\n\n".join(
5✔
1154
            indent(section, self.indentation) for section in sections
1155
        )
1156
        return f"{declaration}\n{rendered_sections}"
5✔
1157

1158
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1159
        parent_class_name = (
5✔
1160
            model.parent_class.name if model.parent_class else self.base_class_name
1161
        )
1162
        return f"class {model.name}({parent_class_name}):"
5✔
1163

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

1167
        # Render constraints and indexes as __table_args__
1168
        table_args = self.render_table_args(model.table)
5✔
1169
        if table_args:
5✔
1170
            variables.append(f"__table_args__ = {table_args}")
5✔
1171

1172
        return "\n".join(variables)
5✔
1173

1174
    def render_table_args(self, table: Table) -> str:
5✔
1175
        args: list[str] = []
5✔
1176
        kwargs: dict[str, str] = {}
5✔
1177

1178
        # Render constraints
1179
        for constraint in sorted(table.constraints, key=get_constraint_sort_key):
5✔
1180
            if uses_default_name(constraint):
5✔
1181
                if isinstance(constraint, PrimaryKeyConstraint):
5✔
1182
                    continue
5✔
1183
                if (
5✔
1184
                    isinstance(constraint, (ForeignKeyConstraint, UniqueConstraint))
1185
                    and len(constraint.columns) == 1
1186
                ):
1187
                    continue
5✔
1188

1189
            args.append(self.render_constraint(constraint))
5✔
1190

1191
        # Render indexes
1192
        for index in sorted(table.indexes, key=lambda i: cast(str, i.name)):
5✔
1193
            if len(index.columns) > 1 or not uses_default_name(index):
5✔
1194
                args.append(self.render_index(index))
5✔
1195

1196
        if table.schema:
5✔
1197
            kwargs["schema"] = table.schema
5✔
1198

1199
        if table.comment:
5✔
1200
            kwargs["comment"] = table.comment
5✔
1201

1202
        if kwargs:
5✔
1203
            formatted_kwargs = pformat(kwargs)
5✔
1204
            if not args:
5✔
1205
                return formatted_kwargs
5✔
1206
            else:
1207
                args.append(formatted_kwargs)
5✔
1208

1209
        if args:
5✔
1210
            rendered_args = f",\n{self.indentation}".join(args)
5✔
1211
            if len(args) == 1:
5✔
1212
                rendered_args += ","
5✔
1213

1214
            return f"(\n{self.indentation}{rendered_args}\n)"
5✔
1215
        else:
1216
            return ""
5✔
1217

1218
    def render_column_python_type(self, column: Column[Any]) -> str:
5✔
1219
        def get_type_qualifiers() -> tuple[str, TypeEngine[Any], str]:
5✔
1220
            column_type = column.type
5✔
1221
            pre: list[str] = []
5✔
1222
            post_size = 0
5✔
1223
            if column.nullable:
5✔
1224
                self.add_literal_import("typing", "Optional")
5✔
1225
                pre.append("Optional[")
5✔
1226
                post_size += 1
5✔
1227

1228
            if isinstance(column_type, ARRAY):
5✔
1229
                dim = getattr(column_type, "dimensions", None) or 1
5✔
1230
                pre.extend("list[" for _ in range(dim))
5✔
1231
                post_size += dim
5✔
1232

1233
                column_type = column_type.item_type
5✔
1234

1235
            return "".join(pre), column_type, "]" * post_size
5✔
1236

1237
        def render_python_type(column_type: TypeEngine[Any]) -> str:
5✔
1238
            if isinstance(column_type, DOMAIN):
5✔
1239
                python_type = column_type.data_type.python_type
5✔
1240
            else:
1241
                python_type = column_type.python_type
5✔
1242

1243
            python_type_name = python_type.__name__
5✔
1244
            python_type_module = python_type.__module__
5✔
1245
            if python_type_module == "builtins":
5✔
1246
                return python_type_name
5✔
1247

1248
            try:
5✔
1249
                self.add_module_import(python_type_module)
5✔
1250
                return f"{python_type_module}.{python_type_name}"
5✔
UNCOV
1251
            except NotImplementedError:
×
UNCOV
1252
                self.add_literal_import("typing", "Any")
×
UNCOV
1253
                return "Any"
×
1254

1255
        pre, col_type, post = get_type_qualifiers()
5✔
1256
        column_python_type = f"{pre}{render_python_type(col_type)}{post}"
5✔
1257
        return column_python_type
5✔
1258

1259
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1260
        column = column_attr.column
5✔
1261
        rendered_column = self.render_column(column, column_attr.name != column.name)
5✔
1262
        rendered_column_python_type = self.render_column_python_type(column)
5✔
1263

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

1266
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1267
        def render_column_attrs(column_attrs: list[ColumnAttribute]) -> str:
5✔
1268
            rendered = []
5✔
1269
            for attr in column_attrs:
5✔
1270
                if attr.model is relationship.source:
5✔
1271
                    rendered.append(attr.name)
5✔
1272
                else:
UNCOV
1273
                    rendered.append(repr(f"{attr.model.name}.{attr.name}"))
×
1274

1275
            return "[" + ", ".join(rendered) + "]"
5✔
1276

1277
        def render_foreign_keys(column_attrs: list[ColumnAttribute]) -> str:
5✔
1278
            rendered = []
5✔
1279
            render_as_string = False
5✔
1280
            # Assume that column_attrs are all in relationship.source or none
1281
            for attr in column_attrs:
5✔
1282
                if attr.model is relationship.source:
5✔
1283
                    rendered.append(attr.name)
5✔
1284
                else:
1285
                    rendered.append(f"{attr.model.name}.{attr.name}")
5✔
1286
                    render_as_string = True
5✔
1287

1288
            if render_as_string:
5✔
1289
                return "'[" + ", ".join(rendered) + "]'"
5✔
1290
            else:
1291
                return "[" + ", ".join(rendered) + "]"
5✔
1292

1293
        def render_join(terms: list[JoinType]) -> str:
5✔
1294
            rendered_joins = []
5✔
1295
            for source, source_col, target, target_col in terms:
5✔
1296
                rendered = f"lambda: {source.name}.{source_col} == {target.name}."
5✔
1297
                if target.__class__ is Model:
5✔
1298
                    rendered += "c."
5✔
1299

1300
                rendered += str(target_col)
5✔
1301
                rendered_joins.append(rendered)
5✔
1302

1303
            if len(rendered_joins) > 1:
5✔
UNCOV
1304
                rendered = ", ".join(rendered_joins)
×
UNCOV
1305
                return f"and_({rendered})"
×
1306
            else:
1307
                return rendered_joins[0]
5✔
1308

1309
        # Render keyword arguments
1310
        kwargs: dict[str, Any] = {}
5✔
1311
        if relationship.type is RelationshipType.ONE_TO_ONE and relationship.constraint:
5✔
1312
            if relationship.constraint.referred_table is relationship.source.table:
5✔
1313
                kwargs["uselist"] = False
5✔
1314

1315
        # Add the "secondary" keyword for many-to-many relationships
1316
        if relationship.association_table:
5✔
1317
            table_ref = relationship.association_table.table.name
5✔
1318
            if relationship.association_table.schema:
5✔
1319
                table_ref = f"{relationship.association_table.schema}.{table_ref}"
5✔
1320

1321
            kwargs["secondary"] = repr(table_ref)
5✔
1322

1323
        if relationship.remote_side:
5✔
1324
            kwargs["remote_side"] = render_column_attrs(relationship.remote_side)
5✔
1325

1326
        if relationship.foreign_keys:
5✔
1327
            kwargs["foreign_keys"] = render_foreign_keys(relationship.foreign_keys)
5✔
1328

1329
        if relationship.primaryjoin:
5✔
1330
            kwargs["primaryjoin"] = render_join(relationship.primaryjoin)
5✔
1331

1332
        if relationship.secondaryjoin:
5✔
1333
            kwargs["secondaryjoin"] = render_join(relationship.secondaryjoin)
5✔
1334

1335
        if relationship.backref:
5✔
1336
            kwargs["back_populates"] = repr(relationship.backref.name)
5✔
1337

1338
        rendered_relationship = render_callable(
5✔
1339
            "relationship", repr(relationship.target.name), kwargs=kwargs
1340
        )
1341

1342
        relationship_type: str
1343
        if relationship.type == RelationshipType.ONE_TO_MANY:
5✔
1344
            relationship_type = f"list['{relationship.target.name}']"
5✔
1345
        elif relationship.type in (
5✔
1346
            RelationshipType.ONE_TO_ONE,
1347
            RelationshipType.MANY_TO_ONE,
1348
        ):
1349
            relationship_type = f"'{relationship.target.name}'"
5✔
1350
            if relationship.constraint and any(
5✔
1351
                col.nullable for col in relationship.constraint.columns
1352
            ):
1353
                self.add_literal_import("typing", "Optional")
5✔
1354
                relationship_type = f"Optional[{relationship_type}]"
5✔
1355
        elif relationship.type == RelationshipType.MANY_TO_MANY:
5✔
1356
            relationship_type = f"list['{relationship.target.name}']"
5✔
1357
        else:
UNCOV
1358
            self.add_literal_import("typing", "Any")
×
UNCOV
1359
            relationship_type = "Any"
×
1360

1361
        return (
5✔
1362
            f"{relationship.name}: Mapped[{relationship_type}] "
1363
            f"= {rendered_relationship}"
1364
        )
1365

1366

1367
class DataclassGenerator(DeclarativeGenerator):
5✔
1368
    def __init__(
5✔
1369
        self,
1370
        metadata: MetaData,
1371
        bind: Connection | Engine,
1372
        options: Sequence[str],
1373
        *,
1374
        indentation: str = "    ",
1375
        base_class_name: str = "Base",
1376
        quote_annotations: bool = False,
1377
        metadata_key: str = "sa",
1378
    ):
1379
        super().__init__(
5✔
1380
            metadata,
1381
            bind,
1382
            options,
1383
            indentation=indentation,
1384
            base_class_name=base_class_name,
1385
        )
1386
        self.metadata_key: str = metadata_key
5✔
1387
        self.quote_annotations: bool = quote_annotations
5✔
1388

1389
    def generate_base(self) -> None:
5✔
1390
        self.base = Base(
5✔
1391
            literal_imports=[
1392
                LiteralImport("sqlalchemy.orm", "DeclarativeBase"),
1393
                LiteralImport("sqlalchemy.orm", "MappedAsDataclass"),
1394
            ],
1395
            declarations=[
1396
                (f"class {self.base_class_name}(MappedAsDataclass, DeclarativeBase):"),
1397
                f"{self.indentation}pass",
1398
            ],
1399
            metadata_ref=f"{self.base_class_name}.metadata",
1400
        )
1401

1402

1403
class SQLModelGenerator(DeclarativeGenerator):
5✔
1404
    def __init__(
5✔
1405
        self,
1406
        metadata: MetaData,
1407
        bind: Connection | Engine,
1408
        options: Sequence[str],
1409
        *,
1410
        indentation: str = "    ",
1411
        base_class_name: str = "SQLModel",
1412
    ):
1413
        super().__init__(
5✔
1414
            metadata,
1415
            bind,
1416
            options,
1417
            indentation=indentation,
1418
            base_class_name=base_class_name,
1419
        )
1420

1421
    @property
5✔
1422
    def views_supported(self) -> bool:
5✔
UNCOV
1423
        return False
×
1424

1425
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
1426
        self.add_import(Column)
5✔
1427
        return render_callable("Column", *args, kwargs=kwargs)
5✔
1428

1429
    def generate_base(self) -> None:
5✔
1430
        self.base = Base(
5✔
1431
            literal_imports=[],
1432
            declarations=[],
1433
            metadata_ref="",
1434
        )
1435

1436
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1437
        super(DeclarativeGenerator, self).collect_imports(models)
5✔
1438
        if any(isinstance(model, ModelClass) for model in models):
5✔
1439
            self.remove_literal_import("sqlalchemy", "MetaData")
5✔
1440
            self.add_literal_import("sqlmodel", "SQLModel")
5✔
1441
            self.add_literal_import("sqlmodel", "Field")
5✔
1442

1443
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1444
        super(DeclarativeGenerator, self).collect_imports_for_model(model)
5✔
1445
        if isinstance(model, ModelClass):
5✔
1446
            for column_attr in model.columns:
5✔
1447
                if column_attr.column.nullable:
5✔
1448
                    self.add_literal_import("typing", "Optional")
5✔
1449
                    break
5✔
1450

1451
            if model.relationships:
5✔
1452
                self.add_literal_import("sqlmodel", "Relationship")
5✔
1453

1454
    def render_module_variables(self, models: list[Model]) -> str:
5✔
1455
        declarations: list[str] = []
5✔
1456
        if any(not isinstance(model, ModelClass) for model in models):
5✔
UNCOV
1457
            if self.base.table_metadata_declaration is not None:
×
UNCOV
1458
                declarations.append(self.base.table_metadata_declaration)
×
1459

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

1462
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1463
        if model.parent_class:
5✔
UNCOV
1464
            parent = model.parent_class.name
×
1465
        else:
1466
            parent = self.base_class_name
5✔
1467

1468
        superclass_part = f"({parent}, table=True)"
5✔
1469
        return f"class {model.name}{superclass_part}:"
5✔
1470

1471
    def render_class_variables(self, model: ModelClass) -> str:
5✔
1472
        variables = []
5✔
1473

1474
        if model.table.name != model.name.lower():
5✔
1475
            variables.append(f"__tablename__ = {model.table.name!r}")
5✔
1476

1477
        # Render constraints and indexes as __table_args__
1478
        table_args = self.render_table_args(model.table)
5✔
1479
        if table_args:
5✔
1480
            variables.append(f"__table_args__ = {table_args}")
5✔
1481

1482
        return "\n".join(variables)
5✔
1483

1484
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1485
        column = column_attr.column
5✔
1486
        rendered_column = self.render_column(column, True)
5✔
1487
        rendered_column_python_type = self.render_column_python_type(column)
5✔
1488

1489
        kwargs: dict[str, Any] = {}
5✔
1490
        if column.nullable:
5✔
1491
            kwargs["default"] = None
5✔
1492
        kwargs["sa_column"] = f"{rendered_column}"
5✔
1493

1494
        rendered_field = render_callable("Field", kwargs=kwargs)
5✔
1495

1496
        return f"{column_attr.name}: {rendered_column_python_type} = {rendered_field}"
5✔
1497

1498
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1499
        rendered = super().render_relationship(relationship).partition(" = ")[2]
5✔
1500
        args = self.render_relationship_args(rendered)
5✔
1501
        kwargs: dict[str, Any] = {}
5✔
1502
        annotation = repr(relationship.target.name)
5✔
1503

1504
        if relationship.type in (
5✔
1505
            RelationshipType.ONE_TO_MANY,
1506
            RelationshipType.MANY_TO_MANY,
1507
        ):
1508
            annotation = f"list[{annotation}]"
5✔
1509
        else:
1510
            self.add_literal_import("typing", "Optional")
5✔
1511
            annotation = f"Optional[{annotation}]"
5✔
1512

1513
        rendered_field = render_callable("Relationship", *args, kwargs=kwargs)
5✔
1514
        return f"{relationship.name}: {annotation} = {rendered_field}"
5✔
1515

1516
    def render_relationship_args(self, arguments: str) -> list[str]:
5✔
1517
        argument_list = arguments.split(",")
5✔
1518
        # delete ')' and ' ' from args
1519
        argument_list[-1] = argument_list[-1][:-1]
5✔
1520
        argument_list = [argument[1:] for argument in argument_list]
5✔
1521

1522
        rendered_args: list[str] = []
5✔
1523
        for arg in argument_list:
5✔
1524
            if "back_populates" in arg:
5✔
1525
                rendered_args.append(arg)
5✔
1526
            if "uselist=False" in arg:
5✔
1527
                rendered_args.append("sa_relationship_kwargs={'uselist': False}")
5✔
1528

1529
        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