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

agronholm / sqlacodegen / 15439598815

04 Jun 2025 10:10AM UTC coverage: 97.278% (+0.03%) from 97.246%
15439598815

Pull #338

github

web-flow
Merge 6c4887a5d into d860a6756
Pull Request #338: Handle TextClause objects in DOMAIN expressions

22 of 23 new or added lines in 3 files covered. (95.65%)

25 existing lines in 1 file now uncovered.

1394 of 1433 relevant lines covered (97.28%)

4.86 hits per line

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

96.32
/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, 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
        elif isinstance(column.type, DOMAIN):
5✔
232
            self.add_import(column.type.data_type.__class__)
5✔
233
            if isinstance(column.type.default, TextClause) or isinstance(
5✔
234
                column.type.check, TextClause
235
            ):
236
                self.add_literal_import("sqlalchemy", "text")
5✔
237

238
        if column.default:
5✔
239
            self.add_import(column.default)
5✔
240

241
        if column.server_default:
5✔
242
            if isinstance(column.server_default, (Computed, Identity)):
5✔
243
                self.add_import(column.server_default)
5✔
244
            elif isinstance(column.server_default, DefaultClause):
5✔
245
                self.add_literal_import("sqlalchemy", "text")
5✔
246

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

265
    def add_import(self, obj: Any) -> None:
5✔
266
        # Don't store builtin imports
267
        if getattr(obj, "__module__", "builtins") == "builtins":
5✔
268
            return
5✔
269

270
        type_ = type(obj) if not isinstance(obj, type) else obj
5✔
271
        pkgname = type_.__module__
5✔
272

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

281
            if type_.__name__ in dialect_pkg.__all__:
5✔
282
                pkgname = dialect_pkgname
5✔
283
        elif type_.__name__ in dir(sqlalchemy):
5✔
284
            pkgname = "sqlalchemy"
5✔
285
        else:
286
            pkgname = type_.__module__
5✔
287

288
        self.add_literal_import(pkgname, type_.__name__)
5✔
289

290
    def add_literal_import(self, pkgname: str, name: str) -> None:
5✔
291
        names = self.imports.setdefault(pkgname, set())
5✔
292
        names.add(name)
5✔
293

294
    def remove_literal_import(self, pkgname: str, name: str) -> None:
5✔
295
        names = self.imports.setdefault(pkgname, set())
5✔
296
        if name in names:
5✔
UNCOV
297
            names.remove(name)
×
298

299
    def add_module_import(self, pgkname: str) -> None:
5✔
300
        self.module_imports.add(pgkname)
5✔
301

302
    def group_imports(self) -> list[list[str]]:
5✔
303
        future_imports: list[str] = []
5✔
304
        stdlib_imports: list[str] = []
5✔
305
        thirdparty_imports: list[str] = []
5✔
306

307
        for package in sorted(self.imports):
5✔
308
            imports = ", ".join(sorted(self.imports[package]))
5✔
309
            collection = thirdparty_imports
5✔
310
            if package == "__future__":
5✔
UNCOV
311
                collection = future_imports
×
312
            elif package in self.builtin_module_names:
5✔
UNCOV
313
                collection = stdlib_imports
×
314
            elif package in sys.modules:
5✔
315
                if "site-packages" not in (sys.modules[package].__file__ or ""):
5✔
316
                    collection = stdlib_imports
5✔
317

318
            collection.append(f"from {package} import {imports}")
5✔
319

320
        for module in sorted(self.module_imports):
5✔
321
            thirdparty_imports.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✔
UNCOV
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
        is_sole_pk = column.primary_key and len(column.table.primary_key) == 1
5✔
414
        dedicated_fks = [
5✔
415
            c
416
            for c in column.foreign_keys
417
            if c.constraint
418
            and len(c.constraint.columns) == 1
419
            and uses_default_name(c.constraint)
420
        ]
421
        is_unique = any(
5✔
422
            isinstance(c, UniqueConstraint)
423
            and set(c.columns) == {column}
424
            and uses_default_name(c)
425
            for c in column.table.constraints
426
        )
427
        is_unique = is_unique or any(
5✔
428
            i.unique and set(i.columns) == {column} and uses_default_name(i)
429
            for i in column.table.indexes
430
        )
431
        is_primary = (
5✔
432
            any(
433
                isinstance(c, PrimaryKeyConstraint)
434
                and column.name in c.columns
435
                and uses_default_name(c)
436
                for c in column.table.constraints
437
            )
438
            or column.primary_key
439
        )
440
        has_index = any(
5✔
441
            set(i.columns) == {column} and uses_default_name(i)
442
            for i in column.table.indexes
443
        )
444

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

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

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

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

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

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

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

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

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

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

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

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

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

521
            value = getattr(coltype, param.name, missing)
5✔
522
            default = defaults.get(param.name, missing)
5✔
523
            if value is missing or value == default:
5✔
524
                use_kwargs = True
5✔
525
            elif use_kwargs:
5✔
526
                kwargs[param.name] = repr(value)
5✔
527
            else:
528
                args.append(repr(value))
5✔
529

530
        vararg = next(
5✔
531
            (
532
                param.name
533
                for param in sig.parameters.values()
534
                if param.kind is Parameter.VAR_POSITIONAL
535
            ),
536
            None,
537
        )
538
        if vararg and hasattr(coltype, vararg):
5✔
539
            varargs_repr = [repr(arg) for arg in getattr(coltype, vararg)]
5✔
540
            args.extend(varargs_repr)
5✔
541

542
        # These arguments cannot be autodetected from the Enum initializer
543
        if isinstance(coltype, Enum):
5✔
544
            for colname in "name", "schema":
5✔
545
                if (value := getattr(coltype, colname)) is not None:
5✔
546
                    kwargs[colname] = repr(value)
5✔
547

548
        if isinstance(coltype, JSONB):
5✔
549
            # Remove astext_type if it's the default
550
            if (
5✔
551
                isinstance(coltype.astext_type, Text)
552
                and coltype.astext_type.length is None
553
            ):
554
                del kwargs["astext_type"]
5✔
555

556
        if isinstance(coltype, DOMAIN):
5✔
557
            if isinstance(coltype.default, TextClause):
5✔
NEW
UNCOV
558
                kwargs["default"] = render_callable("text", repr(coltype.default.text))
×
559
            if isinstance(coltype.check, TextClause):
5✔
560
                kwargs["check"] = render_callable("text", repr(coltype.check.text))
5✔
561

562
        if args or kwargs:
5✔
563
            return render_callable(coltype.__class__.__name__, *args, kwargs=kwargs)
5✔
564
        else:
565
            return coltype.__class__.__name__
5✔
566

567
    def render_constraint(self, constraint: Constraint | ForeignKey) -> str:
5✔
568
        def add_fk_options(*opts: Any) -> None:
5✔
569
            args.extend(repr(opt) for opt in opts)
5✔
570
            for attr in "ondelete", "onupdate", "deferrable", "initially", "match":
5✔
571
                value = getattr(constraint, attr, None)
5✔
572
                if value:
5✔
573
                    kwargs[attr] = repr(value)
5✔
574

575
        args: list[str] = []
5✔
576
        kwargs: dict[str, Any] = {}
5✔
577
        if isinstance(constraint, ForeignKey):
5✔
578
            remote_column = (
5✔
579
                f"{constraint.column.table.fullname}.{constraint.column.name}"
580
            )
581
            add_fk_options(remote_column)
5✔
582
        elif isinstance(constraint, ForeignKeyConstraint):
5✔
583
            local_columns = get_column_names(constraint)
5✔
584
            remote_columns = [
5✔
585
                f"{fk.column.table.fullname}.{fk.column.name}"
586
                for fk in constraint.elements
587
            ]
588
            add_fk_options(local_columns, remote_columns)
5✔
589
        elif isinstance(constraint, CheckConstraint):
5✔
590
            args.append(repr(get_compiled_expression(constraint.sqltext, self.bind)))
5✔
591
        elif isinstance(constraint, (UniqueConstraint, PrimaryKeyConstraint)):
5✔
592
            args.extend(repr(col.name) for col in constraint.columns)
5✔
593
        else:
UNCOV
594
            raise TypeError(
×
595
                f"Cannot render constraint of type {constraint.__class__.__name__}"
596
            )
597

598
        if isinstance(constraint, Constraint) and not uses_default_name(constraint):
5✔
599
            kwargs["name"] = repr(constraint.name)
5✔
600

601
        return render_callable(constraint.__class__.__name__, *args, kwargs=kwargs)
5✔
602

603
    def should_ignore_table(self, table: Table) -> bool:
5✔
604
        # Support for Alembic and sqlalchemy-migrate -- never expose the schema version
605
        # tables
606
        return table.name in ("alembic_version", "migrate_version")
5✔
607

608
    def find_free_name(
5✔
609
        self, name: str, global_names: set[str], local_names: Collection[str] = ()
610
    ) -> str:
611
        """
612
        Generate an attribute name that does not clash with other local or global names.
613
        """
614
        name = name.strip()
5✔
615
        assert name, "Identifier cannot be empty"
5✔
616
        name = _re_invalid_identifier.sub("_", name)
5✔
617
        if name[0].isdigit():
5✔
618
            name = "_" + name
5✔
619
        elif iskeyword(name) or name == "metadata":
5✔
620
            name += "_"
5✔
621

622
        original = name
5✔
623
        for i in count():
5✔
624
            if name not in global_names and name not in local_names:
5✔
625
                break
5✔
626

627
            name = original + (str(i) if i else "_")
5✔
628

629
        return name
5✔
630

631
    def fix_column_types(self, table: Table) -> None:
5✔
632
        """Adjust the reflected column types."""
633
        # Detect check constraints for boolean and enum columns
634
        for constraint in table.constraints.copy():
5✔
635
            if isinstance(constraint, CheckConstraint):
5✔
636
                sqltext = get_compiled_expression(constraint.sqltext, self.bind)
5✔
637

638
                # Turn any integer-like column with a CheckConstraint like
639
                # "column IN (0, 1)" into a Boolean
640
                match = _re_boolean_check_constraint.match(sqltext)
5✔
641
                if match:
5✔
642
                    colname_match = _re_column_name.match(match.group(1))
5✔
643
                    if colname_match:
5✔
644
                        colname = colname_match.group(3)
5✔
645
                        table.constraints.remove(constraint)
5✔
646
                        table.c[colname].type = Boolean()
5✔
647
                        continue
5✔
648

649
                # Turn any string-type column with a CheckConstraint like
650
                # "column IN (...)" into an Enum
651
                match = _re_enum_check_constraint.match(sqltext)
5✔
652
                if match:
5✔
653
                    colname_match = _re_column_name.match(match.group(1))
5✔
654
                    if colname_match:
5✔
655
                        colname = colname_match.group(3)
5✔
656
                        items = match.group(2)
5✔
657
                        if isinstance(table.c[colname].type, String):
5✔
658
                            table.constraints.remove(constraint)
5✔
659
                            if not isinstance(table.c[colname].type, Enum):
5✔
660
                                options = _re_enum_item.findall(items)
5✔
661
                                table.c[colname].type = Enum(
5✔
662
                                    *options, native_enum=False
663
                                )
664

665
                            continue
5✔
666

667
        for column in table.c:
5✔
668
            try:
5✔
669
                column.type = self.get_adapted_type(column.type)
5✔
670
            except CompileError:
5✔
671
                pass
5✔
672

673
            # PostgreSQL specific fix: detect sequences from server_default
674
            if column.server_default and self.bind.dialect.name == "postgresql":
5✔
675
                if isinstance(column.server_default, DefaultClause) and isinstance(
5✔
676
                    column.server_default.arg, TextClause
677
                ):
678
                    schema, seqname = decode_postgresql_sequence(
5✔
679
                        column.server_default.arg
680
                    )
681
                    if seqname:
5✔
682
                        # Add an explicit sequence
683
                        if seqname != f"{column.table.name}_{column.name}_seq":
5✔
684
                            column.default = sqlalchemy.Sequence(seqname, schema=schema)
5✔
685

686
                        column.server_default = None
5✔
687

688
    def get_adapted_type(self, coltype: Any) -> Any:
5✔
689
        compiled_type = coltype.compile(self.bind.engine.dialect)
5✔
690
        for supercls in coltype.__class__.__mro__:
5✔
691
            if not supercls.__name__.startswith("_") and hasattr(
5✔
692
                supercls, "__visit_name__"
693
            ):
694
                # Don't try to adapt UserDefinedType as it's not a proper column type
695
                if supercls is UserDefinedType or issubclass(supercls, TypeDecorator):
5✔
696
                    return coltype
5✔
697

698
                # Hack to fix adaptation of the Enum class which is broken since
699
                # SQLAlchemy 1.2
700
                kw = {}
5✔
701
                if supercls is Enum:
5✔
702
                    kw["name"] = coltype.name
5✔
703
                    if coltype.schema:
5✔
704
                        kw["schema"] = coltype.schema
5✔
705

706
                try:
5✔
707
                    new_coltype = coltype.adapt(supercls)
5✔
708
                except TypeError:
5✔
709
                    # If the adaptation fails, don't try again
710
                    break
5✔
711

712
                for key, value in kw.items():
5✔
713
                    setattr(new_coltype, key, value)
5✔
714

715
                if isinstance(coltype, ARRAY):
5✔
716
                    new_coltype.item_type = self.get_adapted_type(new_coltype.item_type)
5✔
717

718
                try:
5✔
719
                    # If the adapted column type does not render the same as the
720
                    # original, don't substitute it
721
                    if new_coltype.compile(self.bind.engine.dialect) != compiled_type:
5✔
722
                        break
5✔
723
                except CompileError:
5✔
724
                    # If the adapted column type can't be compiled, don't substitute it
725
                    break
5✔
726

727
                # Stop on the first valid non-uppercase column type class
728
                coltype = new_coltype
5✔
729
                if supercls.__name__ != supercls.__name__.upper():
5✔
730
                    break
5✔
731

732
        return coltype
5✔
733

734

735
class DeclarativeGenerator(TablesGenerator):
5✔
736
    valid_options: ClassVar[set[str]] = TablesGenerator.valid_options | {
5✔
737
        "use_inflect",
738
        "nojoined",
739
        "nobidi",
740
    }
741

742
    def __init__(
5✔
743
        self,
744
        metadata: MetaData,
745
        bind: Connection | Engine,
746
        options: Sequence[str],
747
        *,
748
        indentation: str = "    ",
749
        base_class_name: str = "Base",
750
    ):
751
        super().__init__(metadata, bind, options, indentation=indentation)
5✔
752
        self.base_class_name: str = base_class_name
5✔
753
        self.inflect_engine = inflect.engine()
5✔
754

755
    def generate_base(self) -> None:
5✔
756
        self.base = Base(
5✔
757
            literal_imports=[LiteralImport("sqlalchemy.orm", "DeclarativeBase")],
758
            declarations=[
759
                f"class {self.base_class_name}(DeclarativeBase):",
760
                f"{self.indentation}pass",
761
            ],
762
            metadata_ref=f"{self.base_class_name}.metadata",
763
        )
764

765
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
766
        super().collect_imports(models)
5✔
767
        if any(isinstance(model, ModelClass) for model in models):
5✔
768
            self.add_literal_import("sqlalchemy.orm", "Mapped")
5✔
769
            self.add_literal_import("sqlalchemy.orm", "mapped_column")
5✔
770

771
    def collect_imports_for_model(self, model: Model) -> None:
5✔
772
        super().collect_imports_for_model(model)
5✔
773
        if isinstance(model, ModelClass):
5✔
774
            if model.relationships:
5✔
775
                self.add_literal_import("sqlalchemy.orm", "relationship")
5✔
776

777
    def generate_models(self) -> list[Model]:
5✔
778
        models_by_table_name: dict[str, Model] = {}
5✔
779

780
        # Pick association tables from the metadata into their own set, don't process
781
        # them normally
782
        links: defaultdict[str, list[Model]] = defaultdict(lambda: [])
5✔
783
        for table in self.metadata.sorted_tables:
5✔
784
            qualified_name = qualified_table_name(table)
5✔
785

786
            # Link tables have exactly two foreign key constraints and all columns are
787
            # involved in them
788
            fk_constraints = sorted(
5✔
789
                table.foreign_key_constraints, key=get_constraint_sort_key
790
            )
791
            if len(fk_constraints) == 2 and all(
5✔
792
                col.foreign_keys for col in table.columns
793
            ):
794
                model = models_by_table_name[qualified_name] = Model(table)
5✔
795
                tablename = fk_constraints[0].elements[0].column.table.name
5✔
796
                links[tablename].append(model)
5✔
797
                continue
5✔
798

799
            # Only form model classes for tables that have a primary key and are not
800
            # association tables
801
            if not table.primary_key:
5✔
802
                models_by_table_name[qualified_name] = Model(table)
5✔
803
            else:
804
                model = ModelClass(table)
5✔
805
                models_by_table_name[qualified_name] = model
5✔
806

807
                # Fill in the columns
808
                for column in table.c:
5✔
809
                    column_attr = ColumnAttribute(model, column)
5✔
810
                    model.columns.append(column_attr)
5✔
811

812
        # Add relationships
813
        for model in models_by_table_name.values():
5✔
814
            if isinstance(model, ModelClass):
5✔
815
                self.generate_relationships(
5✔
816
                    model, models_by_table_name, links[model.table.name]
817
                )
818

819
        # Nest inherited classes in their superclasses to ensure proper ordering
820
        if "nojoined" not in self.options:
5✔
821
            for model in list(models_by_table_name.values()):
5✔
822
                if not isinstance(model, ModelClass):
5✔
823
                    continue
5✔
824

825
                pk_column_names = {col.name for col in model.table.primary_key.columns}
5✔
826
                for constraint in model.table.foreign_key_constraints:
5✔
827
                    if set(get_column_names(constraint)) == pk_column_names:
5✔
828
                        target = models_by_table_name[
5✔
829
                            qualified_table_name(constraint.elements[0].column.table)
830
                        ]
831
                        if isinstance(target, ModelClass):
5✔
832
                            model.parent_class = target
5✔
833
                            target.children.append(model)
5✔
834

835
        # Change base if we only have tables
836
        if not any(
5✔
837
            isinstance(model, ModelClass) for model in models_by_table_name.values()
838
        ):
839
            super().generate_base()
5✔
840

841
        # Collect the imports
842
        self.collect_imports(models_by_table_name.values())
5✔
843

844
        # Rename models and their attributes that conflict with imports or other
845
        # attributes
846
        global_names = {
5✔
847
            name for namespace in self.imports.values() for name in namespace
848
        }
849
        for model in models_by_table_name.values():
5✔
850
            self.generate_model_name(model, global_names)
5✔
851
            global_names.add(model.name)
5✔
852

853
        return list(models_by_table_name.values())
5✔
854

855
    def generate_relationships(
5✔
856
        self,
857
        source: ModelClass,
858
        models_by_table_name: dict[str, Model],
859
        association_tables: list[Model],
860
    ) -> list[RelationshipAttribute]:
861
        relationships: list[RelationshipAttribute] = []
5✔
862
        reverse_relationship: RelationshipAttribute | None
863

864
        # Add many-to-one (and one-to-many) relationships
865
        pk_column_names = {col.name for col in source.table.primary_key.columns}
5✔
866
        for constraint in sorted(
5✔
867
            source.table.foreign_key_constraints, key=get_constraint_sort_key
868
        ):
869
            target = models_by_table_name[
5✔
870
                qualified_table_name(constraint.elements[0].column.table)
871
            ]
872
            if isinstance(target, ModelClass):
5✔
873
                if "nojoined" not in self.options:
5✔
874
                    if set(get_column_names(constraint)) == pk_column_names:
5✔
875
                        parent = models_by_table_name[
5✔
876
                            qualified_table_name(constraint.elements[0].column.table)
877
                        ]
878
                        if isinstance(parent, ModelClass):
5✔
879
                            source.parent_class = parent
5✔
880
                            parent.children.append(source)
5✔
881
                            continue
5✔
882

883
                # Add uselist=False to One-to-One relationships
884
                column_names = get_column_names(constraint)
5✔
885
                if any(
5✔
886
                    isinstance(c, (PrimaryKeyConstraint, UniqueConstraint))
887
                    and {col.name for col in c.columns} == set(column_names)
888
                    for c in constraint.table.constraints
889
                ):
890
                    r_type = RelationshipType.ONE_TO_ONE
5✔
891
                else:
892
                    r_type = RelationshipType.MANY_TO_ONE
5✔
893

894
                relationship = RelationshipAttribute(r_type, source, target, constraint)
5✔
895
                source.relationships.append(relationship)
5✔
896

897
                # For self referential relationships, remote_side needs to be set
898
                if source is target:
5✔
899
                    relationship.remote_side = [
5✔
900
                        source.get_column_attribute(col.name)
901
                        for col in constraint.referred_table.primary_key
902
                    ]
903

904
                # If the two tables share more than one foreign key constraint,
905
                # SQLAlchemy needs an explicit primaryjoin to figure out which column(s)
906
                # it needs
907
                common_fk_constraints = get_common_fk_constraints(
5✔
908
                    source.table, target.table
909
                )
910
                if len(common_fk_constraints) > 1:
5✔
911
                    relationship.foreign_keys = [
5✔
912
                        source.get_column_attribute(key)
913
                        for key in constraint.column_keys
914
                    ]
915

916
                # Generate the opposite end of the relationship in the target class
917
                if "nobidi" not in self.options:
5✔
918
                    if r_type is RelationshipType.MANY_TO_ONE:
5✔
919
                        r_type = RelationshipType.ONE_TO_MANY
5✔
920

921
                    reverse_relationship = RelationshipAttribute(
5✔
922
                        r_type,
923
                        target,
924
                        source,
925
                        constraint,
926
                        foreign_keys=relationship.foreign_keys,
927
                        backref=relationship,
928
                    )
929
                    relationship.backref = reverse_relationship
5✔
930
                    target.relationships.append(reverse_relationship)
5✔
931

932
                    # For self referential relationships, remote_side needs to be set
933
                    if source is target:
5✔
934
                        reverse_relationship.remote_side = [
5✔
935
                            source.get_column_attribute(colname)
936
                            for colname in constraint.column_keys
937
                        ]
938

939
        # Add many-to-many relationships
940
        for association_table in association_tables:
5✔
941
            fk_constraints = sorted(
5✔
942
                association_table.table.foreign_key_constraints,
943
                key=get_constraint_sort_key,
944
            )
945
            target = models_by_table_name[
5✔
946
                qualified_table_name(fk_constraints[1].elements[0].column.table)
947
            ]
948
            if isinstance(target, ModelClass):
5✔
949
                relationship = RelationshipAttribute(
5✔
950
                    RelationshipType.MANY_TO_MANY,
951
                    source,
952
                    target,
953
                    fk_constraints[1],
954
                    association_table,
955
                )
956
                source.relationships.append(relationship)
5✔
957

958
                # Generate the opposite end of the relationship in the target class
959
                reverse_relationship = None
5✔
960
                if "nobidi" not in self.options:
5✔
961
                    reverse_relationship = RelationshipAttribute(
5✔
962
                        RelationshipType.MANY_TO_MANY,
963
                        target,
964
                        source,
965
                        fk_constraints[0],
966
                        association_table,
967
                        relationship,
968
                    )
969
                    relationship.backref = reverse_relationship
5✔
970
                    target.relationships.append(reverse_relationship)
5✔
971

972
                # Add a primary/secondary join for self-referential many-to-many
973
                # relationships
974
                if source is target:
5✔
975
                    both_relationships = [relationship]
5✔
976
                    reverse_flags = [False, True]
5✔
977
                    if reverse_relationship:
5✔
978
                        both_relationships.append(reverse_relationship)
5✔
979

980
                    for relationship, reverse in zip(both_relationships, reverse_flags):
5✔
981
                        if (
5✔
982
                            not relationship.association_table
983
                            or not relationship.constraint
984
                        ):
UNCOV
985
                            continue
×
986

987
                        constraints = sorted(
5✔
988
                            relationship.constraint.table.foreign_key_constraints,
989
                            key=get_constraint_sort_key,
990
                            reverse=reverse,
991
                        )
992
                        pri_pairs = zip(
5✔
993
                            get_column_names(constraints[0]), constraints[0].elements
994
                        )
995
                        sec_pairs = zip(
5✔
996
                            get_column_names(constraints[1]), constraints[1].elements
997
                        )
998
                        relationship.primaryjoin = [
5✔
999
                            (
1000
                                relationship.source,
1001
                                elem.column.name,
1002
                                relationship.association_table,
1003
                                col,
1004
                            )
1005
                            for col, elem in pri_pairs
1006
                        ]
1007
                        relationship.secondaryjoin = [
5✔
1008
                            (
1009
                                relationship.target,
1010
                                elem.column.name,
1011
                                relationship.association_table,
1012
                                col,
1013
                            )
1014
                            for col, elem in sec_pairs
1015
                        ]
1016

1017
        return relationships
5✔
1018

1019
    def generate_model_name(self, model: Model, global_names: set[str]) -> None:
5✔
1020
        if isinstance(model, ModelClass):
5✔
1021
            preferred_name = _re_invalid_identifier.sub("_", model.table.name)
5✔
1022
            preferred_name = "".join(
5✔
1023
                part[:1].upper() + part[1:] for part in preferred_name.split("_")
1024
            )
1025
            if "use_inflect" in self.options:
5✔
1026
                singular_name = self.inflect_engine.singular_noun(preferred_name)
5✔
1027
                if singular_name:
5✔
1028
                    preferred_name = singular_name
5✔
1029

1030
            model.name = self.find_free_name(preferred_name, global_names)
5✔
1031

1032
            # Fill in the names for column attributes
1033
            local_names: set[str] = set()
5✔
1034
            for column_attr in model.columns:
5✔
1035
                self.generate_column_attr_name(column_attr, global_names, local_names)
5✔
1036
                local_names.add(column_attr.name)
5✔
1037

1038
            # Fill in the names for relationship attributes
1039
            for relationship in model.relationships:
5✔
1040
                self.generate_relationship_name(relationship, global_names, local_names)
5✔
1041
                local_names.add(relationship.name)
5✔
1042
        else:
1043
            super().generate_model_name(model, global_names)
5✔
1044

1045
    def generate_column_attr_name(
5✔
1046
        self,
1047
        column_attr: ColumnAttribute,
1048
        global_names: set[str],
1049
        local_names: set[str],
1050
    ) -> None:
1051
        column_attr.name = self.find_free_name(
5✔
1052
            column_attr.column.name, global_names, local_names
1053
        )
1054

1055
    def generate_relationship_name(
5✔
1056
        self,
1057
        relationship: RelationshipAttribute,
1058
        global_names: set[str],
1059
        local_names: set[str],
1060
    ) -> None:
1061
        # Self referential reverse relationships
1062
        preferred_name: str
1063
        if (
5✔
1064
            relationship.type
1065
            in (RelationshipType.ONE_TO_MANY, RelationshipType.ONE_TO_ONE)
1066
            and relationship.source is relationship.target
1067
            and relationship.backref
1068
            and relationship.backref.name
1069
        ):
1070
            preferred_name = relationship.backref.name + "_reverse"
5✔
1071
        else:
1072
            preferred_name = relationship.target.table.name
5✔
1073

1074
            # If there's a constraint with a single column that ends with "_id", use the
1075
            # preceding part as the relationship name
1076
            if relationship.constraint:
5✔
1077
                is_source = relationship.source.table is relationship.constraint.table
5✔
1078
                if is_source or relationship.type not in (
5✔
1079
                    RelationshipType.ONE_TO_ONE,
1080
                    RelationshipType.ONE_TO_MANY,
1081
                ):
1082
                    column_names = [c.name for c in relationship.constraint.columns]
5✔
1083
                    if len(column_names) == 1 and column_names[0].endswith("_id"):
5✔
1084
                        preferred_name = column_names[0][:-3]
5✔
1085

1086
            if "use_inflect" in self.options:
5✔
1087
                inflected_name: str | Literal[False]
1088
                if relationship.type in (
5✔
1089
                    RelationshipType.ONE_TO_MANY,
1090
                    RelationshipType.MANY_TO_MANY,
1091
                ):
1092
                    if not self.inflect_engine.singular_noun(preferred_name):
5✔
UNCOV
1093
                        preferred_name = self.inflect_engine.plural_noun(preferred_name)
×
1094
                else:
1095
                    inflected_name = self.inflect_engine.singular_noun(preferred_name)
5✔
1096
                    if inflected_name:
5✔
1097
                        preferred_name = inflected_name
5✔
1098

1099
        relationship.name = self.find_free_name(
5✔
1100
            preferred_name, global_names, local_names
1101
        )
1102

1103
    def render_models(self, models: list[Model]) -> str:
5✔
1104
        rendered: list[str] = []
5✔
1105
        for model in models:
5✔
1106
            if isinstance(model, ModelClass):
5✔
1107
                rendered.append(self.render_class(model))
5✔
1108
            else:
1109
                rendered.append(f"{model.name} = {self.render_table(model.table)}")
5✔
1110

1111
        return "\n\n\n".join(rendered)
5✔
1112

1113
    def render_class(self, model: ModelClass) -> str:
5✔
1114
        sections: list[str] = []
5✔
1115

1116
        # Render class variables / special declarations
1117
        class_vars: str = self.render_class_variables(model)
5✔
1118
        if class_vars:
5✔
1119
            sections.append(class_vars)
5✔
1120

1121
        # Render column attributes
1122
        rendered_column_attributes: list[str] = []
5✔
1123
        for nullable in (False, True):
5✔
1124
            for column_attr in model.columns:
5✔
1125
                if column_attr.column.nullable is nullable:
5✔
1126
                    rendered_column_attributes.append(
5✔
1127
                        self.render_column_attribute(column_attr)
1128
                    )
1129

1130
        if rendered_column_attributes:
5✔
1131
            sections.append("\n".join(rendered_column_attributes))
5✔
1132

1133
        # Render relationship attributes
1134
        rendered_relationship_attributes: list[str] = [
5✔
1135
            self.render_relationship(relationship)
1136
            for relationship in model.relationships
1137
        ]
1138

1139
        if rendered_relationship_attributes:
5✔
1140
            sections.append("\n".join(rendered_relationship_attributes))
5✔
1141

1142
        declaration = self.render_class_declaration(model)
5✔
1143
        rendered_sections = "\n\n".join(
5✔
1144
            indent(section, self.indentation) for section in sections
1145
        )
1146
        return f"{declaration}\n{rendered_sections}"
5✔
1147

1148
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1149
        parent_class_name = (
5✔
1150
            model.parent_class.name if model.parent_class else self.base_class_name
1151
        )
1152
        return f"class {model.name}({parent_class_name}):"
5✔
1153

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

1157
        # Render constraints and indexes as __table_args__
1158
        table_args = self.render_table_args(model.table)
5✔
1159
        if table_args:
5✔
1160
            variables.append(f"__table_args__ = {table_args}")
5✔
1161

1162
        return "\n".join(variables)
5✔
1163

1164
    def render_table_args(self, table: Table) -> str:
5✔
1165
        args: list[str] = []
5✔
1166
        kwargs: dict[str, str] = {}
5✔
1167

1168
        # Render constraints
1169
        for constraint in sorted(table.constraints, key=get_constraint_sort_key):
5✔
1170
            if uses_default_name(constraint):
5✔
1171
                if isinstance(constraint, PrimaryKeyConstraint):
5✔
1172
                    continue
5✔
1173
                if (
5✔
1174
                    isinstance(constraint, (ForeignKeyConstraint, UniqueConstraint))
1175
                    and len(constraint.columns) == 1
1176
                ):
1177
                    continue
5✔
1178

1179
            args.append(self.render_constraint(constraint))
5✔
1180

1181
        # Render indexes
1182
        for index in sorted(table.indexes, key=lambda i: cast(str, i.name)):
5✔
1183
            if len(index.columns) > 1 or not uses_default_name(index):
5✔
1184
                args.append(self.render_index(index))
5✔
1185

1186
        if table.schema:
5✔
1187
            kwargs["schema"] = table.schema
5✔
1188

1189
        if table.comment:
5✔
1190
            kwargs["comment"] = table.comment
5✔
1191

1192
        if kwargs:
5✔
1193
            formatted_kwargs = pformat(kwargs)
5✔
1194
            if not args:
5✔
1195
                return formatted_kwargs
5✔
1196
            else:
1197
                args.append(formatted_kwargs)
5✔
1198

1199
        if args:
5✔
1200
            rendered_args = f",\n{self.indentation}".join(args)
5✔
1201
            if len(args) == 1:
5✔
1202
                rendered_args += ","
5✔
1203

1204
            return f"(\n{self.indentation}{rendered_args}\n)"
5✔
1205
        else:
1206
            return ""
5✔
1207

1208
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1209
        column = column_attr.column
5✔
1210
        rendered_column = self.render_column(column, column_attr.name != column.name)
5✔
1211

1212
        def get_type_qualifiers() -> tuple[str, TypeEngine[Any], str]:
5✔
1213
            column_type = column.type
5✔
1214
            pre: list[str] = []
5✔
1215
            post_size = 0
5✔
1216
            if column.nullable:
5✔
1217
                self.add_literal_import("typing", "Optional")
5✔
1218
                pre.append("Optional[")
5✔
1219
                post_size += 1
5✔
1220

1221
            if isinstance(column_type, ARRAY):
5✔
1222
                dim = getattr(column_type, "dimensions", None) or 1
5✔
1223
                pre.extend("list[" for _ in range(dim))
5✔
1224
                post_size += dim
5✔
1225

1226
                column_type = column_type.item_type
5✔
1227

1228
            return "".join(pre), column_type, "]" * post_size
5✔
1229

1230
        def render_python_type(column_type: TypeEngine[Any]) -> str:
5✔
1231
            python_type = column_type.python_type
5✔
1232
            python_type_name = python_type.__name__
5✔
1233
            python_type_module = python_type.__module__
5✔
1234
            if python_type_module == "builtins":
5✔
1235
                return python_type_name
5✔
1236

1237
            try:
5✔
1238
                self.add_module_import(python_type_module)
5✔
1239
                return f"{python_type_module}.{python_type_name}"
5✔
UNCOV
1240
            except NotImplementedError:
×
UNCOV
1241
                self.add_literal_import("typing", "Any")
×
UNCOV
1242
                return "Any"
×
1243

1244
        pre, col_type, post = get_type_qualifiers()
5✔
1245
        column_python_type = f"{pre}{render_python_type(col_type)}{post}"
5✔
1246
        return f"{column_attr.name}: Mapped[{column_python_type}] = {rendered_column}"
5✔
1247

1248
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1249
        def render_column_attrs(column_attrs: list[ColumnAttribute]) -> str:
5✔
1250
            rendered = []
5✔
1251
            for attr in column_attrs:
5✔
1252
                if attr.model is relationship.source:
5✔
1253
                    rendered.append(attr.name)
5✔
1254
                else:
UNCOV
1255
                    rendered.append(repr(f"{attr.model.name}.{attr.name}"))
×
1256

1257
            return "[" + ", ".join(rendered) + "]"
5✔
1258

1259
        def render_foreign_keys(column_attrs: list[ColumnAttribute]) -> str:
5✔
1260
            rendered = []
5✔
1261
            render_as_string = False
5✔
1262
            # Assume that column_attrs are all in relationship.source or none
1263
            for attr in column_attrs:
5✔
1264
                if attr.model is relationship.source:
5✔
1265
                    rendered.append(attr.name)
5✔
1266
                else:
1267
                    rendered.append(f"{attr.model.name}.{attr.name}")
5✔
1268
                    render_as_string = True
5✔
1269

1270
            if render_as_string:
5✔
1271
                return "'[" + ", ".join(rendered) + "]'"
5✔
1272
            else:
1273
                return "[" + ", ".join(rendered) + "]"
5✔
1274

1275
        def render_join(terms: list[JoinType]) -> str:
5✔
1276
            rendered_joins = []
5✔
1277
            for source, source_col, target, target_col in terms:
5✔
1278
                rendered = f"lambda: {source.name}.{source_col} == {target.name}."
5✔
1279
                if target.__class__ is Model:
5✔
1280
                    rendered += "c."
5✔
1281

1282
                rendered += str(target_col)
5✔
1283
                rendered_joins.append(rendered)
5✔
1284

1285
            if len(rendered_joins) > 1:
5✔
UNCOV
1286
                rendered = ", ".join(rendered_joins)
×
UNCOV
1287
                return f"and_({rendered})"
×
1288
            else:
1289
                return rendered_joins[0]
5✔
1290

1291
        # Render keyword arguments
1292
        kwargs: dict[str, Any] = {}
5✔
1293
        if relationship.type is RelationshipType.ONE_TO_ONE and relationship.constraint:
5✔
1294
            if relationship.constraint.referred_table is relationship.source.table:
5✔
1295
                kwargs["uselist"] = False
5✔
1296

1297
        # Add the "secondary" keyword for many-to-many relationships
1298
        if relationship.association_table:
5✔
1299
            table_ref = relationship.association_table.table.name
5✔
1300
            if relationship.association_table.schema:
5✔
1301
                table_ref = f"{relationship.association_table.schema}.{table_ref}"
5✔
1302

1303
            kwargs["secondary"] = repr(table_ref)
5✔
1304

1305
        if relationship.remote_side:
5✔
1306
            kwargs["remote_side"] = render_column_attrs(relationship.remote_side)
5✔
1307

1308
        if relationship.foreign_keys:
5✔
1309
            kwargs["foreign_keys"] = render_foreign_keys(relationship.foreign_keys)
5✔
1310

1311
        if relationship.primaryjoin:
5✔
1312
            kwargs["primaryjoin"] = render_join(relationship.primaryjoin)
5✔
1313

1314
        if relationship.secondaryjoin:
5✔
1315
            kwargs["secondaryjoin"] = render_join(relationship.secondaryjoin)
5✔
1316

1317
        if relationship.backref:
5✔
1318
            kwargs["back_populates"] = repr(relationship.backref.name)
5✔
1319

1320
        rendered_relationship = render_callable(
5✔
1321
            "relationship", repr(relationship.target.name), kwargs=kwargs
1322
        )
1323

1324
        relationship_type: str
1325
        if relationship.type == RelationshipType.ONE_TO_MANY:
5✔
1326
            relationship_type = f"list['{relationship.target.name}']"
5✔
1327
        elif relationship.type in (
5✔
1328
            RelationshipType.ONE_TO_ONE,
1329
            RelationshipType.MANY_TO_ONE,
1330
        ):
1331
            relationship_type = f"'{relationship.target.name}'"
5✔
1332
            if relationship.constraint and any(
5✔
1333
                col.nullable for col in relationship.constraint.columns
1334
            ):
1335
                self.add_literal_import("typing", "Optional")
5✔
1336
                relationship_type = f"Optional[{relationship_type}]"
5✔
1337
        elif relationship.type == RelationshipType.MANY_TO_MANY:
5✔
1338
            relationship_type = f"list['{relationship.target.name}']"
5✔
1339
        else:
UNCOV
1340
            self.add_literal_import("typing", "Any")
×
UNCOV
1341
            relationship_type = "Any"
×
1342

1343
        return (
5✔
1344
            f"{relationship.name}: Mapped[{relationship_type}] "
1345
            f"= {rendered_relationship}"
1346
        )
1347

1348

1349
class DataclassGenerator(DeclarativeGenerator):
5✔
1350
    def __init__(
5✔
1351
        self,
1352
        metadata: MetaData,
1353
        bind: Connection | Engine,
1354
        options: Sequence[str],
1355
        *,
1356
        indentation: str = "    ",
1357
        base_class_name: str = "Base",
1358
        quote_annotations: bool = False,
1359
        metadata_key: str = "sa",
1360
    ):
1361
        super().__init__(
5✔
1362
            metadata,
1363
            bind,
1364
            options,
1365
            indentation=indentation,
1366
            base_class_name=base_class_name,
1367
        )
1368
        self.metadata_key: str = metadata_key
5✔
1369
        self.quote_annotations: bool = quote_annotations
5✔
1370

1371
    def generate_base(self) -> None:
5✔
1372
        self.base = Base(
5✔
1373
            literal_imports=[
1374
                LiteralImport("sqlalchemy.orm", "DeclarativeBase"),
1375
                LiteralImport("sqlalchemy.orm", "MappedAsDataclass"),
1376
            ],
1377
            declarations=[
1378
                (f"class {self.base_class_name}(MappedAsDataclass, DeclarativeBase):"),
1379
                f"{self.indentation}pass",
1380
            ],
1381
            metadata_ref=f"{self.base_class_name}.metadata",
1382
        )
1383

1384

1385
class SQLModelGenerator(DeclarativeGenerator):
5✔
1386
    def __init__(
5✔
1387
        self,
1388
        metadata: MetaData,
1389
        bind: Connection | Engine,
1390
        options: Sequence[str],
1391
        *,
1392
        indentation: str = "    ",
1393
        base_class_name: str = "SQLModel",
1394
    ):
1395
        super().__init__(
5✔
1396
            metadata,
1397
            bind,
1398
            options,
1399
            indentation=indentation,
1400
            base_class_name=base_class_name,
1401
        )
1402

1403
    @property
5✔
1404
    def views_supported(self) -> bool:
5✔
UNCOV
1405
        return False
×
1406

1407
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
1408
        self.add_import(Column)
5✔
1409
        return render_callable("Column", *args, kwargs=kwargs)
5✔
1410

1411
    def generate_base(self) -> None:
5✔
1412
        self.base = Base(
5✔
1413
            literal_imports=[],
1414
            declarations=[],
1415
            metadata_ref="",
1416
        )
1417

1418
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1419
        super(DeclarativeGenerator, self).collect_imports(models)
5✔
1420
        if any(isinstance(model, ModelClass) for model in models):
5✔
1421
            self.remove_literal_import("sqlalchemy", "MetaData")
5✔
1422
            self.add_literal_import("sqlmodel", "SQLModel")
5✔
1423
            self.add_literal_import("sqlmodel", "Field")
5✔
1424

1425
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1426
        super(DeclarativeGenerator, self).collect_imports_for_model(model)
5✔
1427
        if isinstance(model, ModelClass):
5✔
1428
            for column_attr in model.columns:
5✔
1429
                if column_attr.column.nullable:
5✔
1430
                    self.add_literal_import("typing", "Optional")
5✔
1431
                    break
5✔
1432

1433
            if model.relationships:
5✔
1434
                self.add_literal_import("sqlmodel", "Relationship")
5✔
1435

1436
    def collect_imports_for_column(self, column: Column[Any]) -> None:
5✔
1437
        super().collect_imports_for_column(column)
5✔
1438
        try:
5✔
1439
            python_type = column.type.python_type
5✔
UNCOV
1440
        except NotImplementedError:
×
UNCOV
1441
            self.add_literal_import("typing", "Any")
×
1442
        else:
1443
            self.add_import(python_type)
5✔
1444

1445
    def render_module_variables(self, models: list[Model]) -> str:
5✔
1446
        declarations: list[str] = []
5✔
1447
        if any(not isinstance(model, ModelClass) for model in models):
5✔
UNCOV
1448
            if self.base.table_metadata_declaration is not None:
×
UNCOV
1449
                declarations.append(self.base.table_metadata_declaration)
×
1450

1451
        return "\n".join(declarations)
5✔
1452

1453
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1454
        if model.parent_class:
5✔
UNCOV
1455
            parent = model.parent_class.name
×
1456
        else:
1457
            parent = self.base_class_name
5✔
1458

1459
        superclass_part = f"({parent}, table=True)"
5✔
1460
        return f"class {model.name}{superclass_part}:"
5✔
1461

1462
    def render_class_variables(self, model: ModelClass) -> str:
5✔
1463
        variables = []
5✔
1464

1465
        if model.table.name != model.name.lower():
5✔
1466
            variables.append(f"__tablename__ = {model.table.name!r}")
5✔
1467

1468
        # Render constraints and indexes as __table_args__
1469
        table_args = self.render_table_args(model.table)
5✔
1470
        if table_args:
5✔
1471
            variables.append(f"__table_args__ = {table_args}")
5✔
1472

1473
        return "\n".join(variables)
5✔
1474

1475
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1476
        column = column_attr.column
5✔
1477
        try:
5✔
1478
            python_type = column.type.python_type
5✔
UNCOV
1479
        except NotImplementedError:
×
UNCOV
1480
            python_type_name = "Any"
×
1481
        else:
1482
            python_type_name = python_type.__name__
5✔
1483

1484
        kwargs: dict[str, Any] = {}
5✔
1485
        if (
5✔
1486
            column.autoincrement and column.name in column.table.primary_key
1487
        ) or column.nullable:
1488
            self.add_literal_import("typing", "Optional")
5✔
1489
            kwargs["default"] = None
5✔
1490
            python_type_name = f"Optional[{python_type_name}]"
5✔
1491

1492
        rendered_column = self.render_column(column, True)
5✔
1493
        kwargs["sa_column"] = f"{rendered_column}"
5✔
1494
        rendered_field = render_callable("Field", kwargs=kwargs)
5✔
1495
        return f"{column_attr.name}: {python_type_name} = {rendered_field}"
5✔
1496

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

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

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

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

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

1528
        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