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

agronholm / sqlacodegen / 12938863942

23 Jan 2025 10:01PM UTC coverage: 97.025% (-2.0%) from 99.035%
12938863942

push

github

web-flow
SQLModel Code generation fixes  (#358)

12 of 15 new or added lines in 1 file covered. (80.0%)

33 existing lines in 3 files now uncovered.

1337 of 1378 relevant lines covered (97.02%)

4.85 hits per line

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

95.97
/src/sqlacodegen/generators.py
1
from __future__ import annotations
5✔
2

3
import inspect
5✔
4
import re
5✔
5
import sys
5✔
6
from abc import ABCMeta, abstractmethod
5✔
7
from collections import defaultdict
5✔
8
from collections.abc import Collection, Iterable, Sequence
5✔
9
from dataclasses import dataclass
5✔
10
from importlib import import_module
5✔
11
from inspect import Parameter
5✔
12
from itertools import count
5✔
13
from keyword import iskeyword
5✔
14
from pprint import pformat
5✔
15
from textwrap import indent
5✔
16
from typing import Any, ClassVar
5✔
17

18
import inflect
5✔
19
import sqlalchemy
5✔
20
from sqlalchemy import (
5✔
21
    ARRAY,
22
    Boolean,
23
    CheckConstraint,
24
    Column,
25
    Computed,
26
    Constraint,
27
    DefaultClause,
28
    Enum,
29
    Float,
30
    ForeignKey,
31
    ForeignKeyConstraint,
32
    Identity,
33
    Index,
34
    MetaData,
35
    PrimaryKeyConstraint,
36
    String,
37
    Table,
38
    Text,
39
    UniqueConstraint,
40
)
41
from sqlalchemy.dialects.postgresql import JSONB
5✔
42
from sqlalchemy.engine import Connection, Engine
5✔
43
from sqlalchemy.exc import CompileError
5✔
44
from sqlalchemy.sql.elements import TextClause
5✔
45

46
from .models import (
5✔
47
    ColumnAttribute,
48
    JoinType,
49
    Model,
50
    ModelClass,
51
    RelationshipAttribute,
52
    RelationshipType,
53
)
54
from .utils import (
5✔
55
    decode_postgresql_sequence,
56
    get_column_names,
57
    get_common_fk_constraints,
58
    get_compiled_expression,
59
    get_constraint_sort_key,
60
    qualified_table_name,
61
    render_callable,
62
    uses_default_name,
63
)
64

65
if sys.version_info < (3, 10):
5✔
66
    pass
2✔
67
else:
68
    pass
3✔
69

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

76

77
@dataclass
5✔
78
class LiteralImport:
5✔
79
    pkgname: str
5✔
80
    name: str
5✔
81

82

83
@dataclass
5✔
84
class Base:
5✔
85
    """Representation of MetaData for Tables, respectively Base for classes"""
86

87
    literal_imports: list[LiteralImport]
5✔
88
    declarations: list[str]
5✔
89
    metadata_ref: str
5✔
90
    decorator: str | None = None
5✔
91
    table_metadata_declaration: str | None = None
5✔
92

93

94
class CodeGenerator(metaclass=ABCMeta):
5✔
95
    valid_options: ClassVar[set[str]] = set()
5✔
96

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

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

109
    @property
5✔
110
    @abstractmethod
5✔
111
    def views_supported(self) -> bool:
5✔
NEW
112
        pass
×
113

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

121

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

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

142
    @property
5✔
143
    def views_supported(self) -> bool:
5✔
NEW
144
        return True
×
145

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

153
    def generate(self) -> str:
5✔
154
        self.generate_base()
5✔
155

156
        sections: list[str] = []
5✔
157

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

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

167
            if "noconstraints" in self.options:
5✔
168
                table.constraints.clear()
5✔
169

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

173
            for column in table.columns:
5✔
174
                if "nocomments" in self.options:
5✔
175
                    column.comment = None
5✔
176

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

182
        # Generate the models
183
        models: list[Model] = self.generate_models()
5✔
184

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

190
        # Render models
191
        rendered_models = self.render_models(models)
5✔
192
        if rendered_models:
5✔
193
            sections.append(rendered_models)
5✔
194

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

201
        return "\n\n".join(sections) + "\n"
5✔
202

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

207
        for model in models:
5✔
208
            self.collect_imports_for_model(model)
5✔
209

210
    def collect_imports_for_model(self, model: Model) -> None:
5✔
211
        if model.__class__ is Model:
5✔
212
            self.add_import(Table)
5✔
213

214
        for column in model.table.c:
5✔
215
            self.collect_imports_for_column(column)
5✔
216

217
        for constraint in model.table.constraints:
5✔
218
            self.collect_imports_for_constraint(constraint)
5✔
219

220
        for index in model.table.indexes:
5✔
221
            self.collect_imports_for_constraint(index)
5✔
222

223
    def collect_imports_for_column(self, column: Column[Any]) -> None:
5✔
224
        self.add_import(column.type)
5✔
225

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

235
        if column.default:
5✔
236
            self.add_import(column.default)
5✔
237

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

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

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

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

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

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

285
        self.add_literal_import(pkgname, type_.__name__)
5✔
286

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

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

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

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

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

315
            collection.append(f"from {package} import {imports}")
5✔
316

317
        for module in sorted(self.module_imports):
5✔
318
            thirdparty_imports.append(f"import {module}")
5✔
319

320
        return [
5✔
321
            group
322
            for group in (future_imports, stdlib_imports, thirdparty_imports)
323
            if group
324
        ]
325

326
    def generate_models(self) -> list[Model]:
5✔
327
        models = [Model(table) for table in self.metadata.sorted_tables]
5✔
328

329
        # Collect the imports
330
        self.collect_imports(models)
5✔
331

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

340
        return models
5✔
341

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

346
    def render_module_variables(self, models: list[Model]) -> str:
5✔
347
        declarations = self.base.declarations
5✔
348

349
        if any(not isinstance(model, ModelClass) for model in models):
5✔
350
            if self.base.table_metadata_declaration is not None:
5✔
UNCOV
351
                declarations.append(self.base.table_metadata_declaration)
×
352

353
        return "\n".join(declarations)
5✔
354

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

361
        return "\n\n".join(rendered)
5✔
362

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

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

379
            args.append(self.render_constraint(constraint))
5✔
380

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

386
        if table.schema:
5✔
387
            kwargs["schema"] = repr(table.schema)
5✔
388

389
        table_comment = getattr(table, "comment", None)
5✔
390
        if table_comment:
5✔
391
            kwargs["comment"] = repr(table.comment)
5✔
392

393
        return render_callable("Table", *args, kwargs=kwargs, indentation="    ")
5✔
394

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

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

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

442
        if show_name:
5✔
443
            args.append(repr(column.name))
5✔
444

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

450
        for fk in dedicated_fks:
5✔
451
            args.append(self.render_constraint(fk))
5✔
452

453
        if column.default:
5✔
454
            args.append(repr(column.default))
5✔
455

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

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

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

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

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

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

494
        return self.render_column_callable(is_table, *args, **kwargs)
5✔
495

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

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

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

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

538
        if isinstance(coltype, Enum) and coltype.name is not None:
5✔
539
            kwargs["name"] = repr(coltype.name)
5✔
540

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

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

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

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

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

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

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

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

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

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

616
        return name
5✔
617

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

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

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

652
                            continue
5✔
653

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

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

673
                        column.server_default = None
5✔
674

675
    def get_adapted_type(self, coltype: Any) -> Any:
5✔
676
        compiled_type = coltype.compile(self.bind.engine.dialect)
5✔
677
        for supercls in coltype.__class__.__mro__:
5✔
678
            if not supercls.__name__.startswith("_") and hasattr(
5✔
679
                supercls, "__visit_name__"
680
            ):
681
                # Hack to fix adaptation of the Enum class which is broken since
682
                # SQLAlchemy 1.2
683
                kw = {}
5✔
684
                if supercls is Enum:
5✔
685
                    kw["name"] = coltype.name
5✔
686

687
                try:
5✔
688
                    new_coltype = coltype.adapt(supercls)
5✔
689
                except TypeError:
5✔
690
                    # If the adaptation fails, don't try again
691
                    break
5✔
692

693
                for key, value in kw.items():
5✔
694
                    setattr(new_coltype, key, value)
5✔
695

696
                if isinstance(coltype, ARRAY):
5✔
697
                    new_coltype.item_type = self.get_adapted_type(new_coltype.item_type)
5✔
698

699
                try:
5✔
700
                    # If the adapted column type does not render the same as the
701
                    # original, don't substitute it
702
                    if new_coltype.compile(self.bind.engine.dialect) != compiled_type:
5✔
703
                        # Make an exception to the rule for Float and arrays of Float,
704
                        # since at least on PostgreSQL, Float can accurately represent
705
                        # both REAL and DOUBLE_PRECISION
706
                        if not isinstance(new_coltype, Float) and not (
5✔
707
                            isinstance(new_coltype, ARRAY)
708
                            and isinstance(new_coltype.item_type, Float)
709
                        ):
710
                            break
5✔
711
                except CompileError:
5✔
712
                    # If the adapted column type can't be compiled, don't substitute it
713
                    break
5✔
714

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

720
        return coltype
5✔
721

722

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1005
        return relationships
5✔
1006

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1200
        try:
5✔
1201
            python_type = column.type.python_type
5✔
1202
            python_type_name = python_type.__name__
5✔
1203
            if python_type.__module__ == "builtins":
5✔
1204
                column_python_type = python_type_name
5✔
1205
            else:
1206
                python_type_module = python_type.__module__
5✔
1207
                column_python_type = f"{python_type_module}.{python_type_name}"
5✔
1208
                self.add_module_import(python_type_module)
5✔
UNCOV
1209
        except NotImplementedError:
×
UNCOV
1210
            self.add_literal_import("typing", "Any")
×
UNCOV
1211
            column_python_type = "Any"
×
1212

1213
        if column.nullable:
5✔
1214
            self.add_literal_import("typing", "Optional")
5✔
1215
            column_python_type = f"Optional[{column_python_type}]"
5✔
1216
        return f"{column_attr.name}: Mapped[{column_python_type}] = {rendered_column}"
5✔
1217

1218
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1219
        def render_column_attrs(column_attrs: list[ColumnAttribute]) -> str:
5✔
1220
            rendered = []
5✔
1221
            for attr in column_attrs:
5✔
1222
                if attr.model is relationship.source:
5✔
1223
                    rendered.append(attr.name)
5✔
1224
                else:
UNCOV
1225
                    rendered.append(repr(f"{attr.model.name}.{attr.name}"))
×
1226

1227
            return "[" + ", ".join(rendered) + "]"
5✔
1228

1229
        def render_foreign_keys(column_attrs: list[ColumnAttribute]) -> str:
5✔
1230
            rendered = []
5✔
1231
            render_as_string = False
5✔
1232
            # Assume that column_attrs are all in relationship.source or none
1233
            for attr in column_attrs:
5✔
1234
                if attr.model is relationship.source:
5✔
1235
                    rendered.append(attr.name)
5✔
1236
                else:
1237
                    rendered.append(f"{attr.model.name}.{attr.name}")
5✔
1238
                    render_as_string = True
5✔
1239

1240
            if render_as_string:
5✔
1241
                return "'[" + ", ".join(rendered) + "]'"
5✔
1242
            else:
1243
                return "[" + ", ".join(rendered) + "]"
5✔
1244

1245
        def render_join(terms: list[JoinType]) -> str:
5✔
1246
            rendered_joins = []
5✔
1247
            for source, source_col, target, target_col in terms:
5✔
1248
                rendered = f"lambda: {source.name}.{source_col} == {target.name}."
5✔
1249
                if target.__class__ is Model:
5✔
1250
                    rendered += "c."
5✔
1251

1252
                rendered += str(target_col)
5✔
1253
                rendered_joins.append(rendered)
5✔
1254

1255
            if len(rendered_joins) > 1:
5✔
UNCOV
1256
                rendered = ", ".join(rendered_joins)
×
UNCOV
1257
                return f"and_({rendered})"
×
1258
            else:
1259
                return rendered_joins[0]
5✔
1260

1261
        # Render keyword arguments
1262
        kwargs: dict[str, Any] = {}
5✔
1263
        if relationship.type is RelationshipType.ONE_TO_ONE and relationship.constraint:
5✔
1264
            if relationship.constraint.referred_table is relationship.source.table:
5✔
1265
                kwargs["uselist"] = False
5✔
1266

1267
        # Add the "secondary" keyword for many-to-many relationships
1268
        if relationship.association_table:
5✔
1269
            table_ref = relationship.association_table.table.name
5✔
1270
            if relationship.association_table.schema:
5✔
1271
                table_ref = f"{relationship.association_table.schema}.{table_ref}"
5✔
1272

1273
            kwargs["secondary"] = repr(table_ref)
5✔
1274

1275
        if relationship.remote_side:
5✔
1276
            kwargs["remote_side"] = render_column_attrs(relationship.remote_side)
5✔
1277

1278
        if relationship.foreign_keys:
5✔
1279
            kwargs["foreign_keys"] = render_foreign_keys(relationship.foreign_keys)
5✔
1280

1281
        if relationship.primaryjoin:
5✔
1282
            kwargs["primaryjoin"] = render_join(relationship.primaryjoin)
5✔
1283

1284
        if relationship.secondaryjoin:
5✔
1285
            kwargs["secondaryjoin"] = render_join(relationship.secondaryjoin)
5✔
1286

1287
        if relationship.backref:
5✔
1288
            kwargs["back_populates"] = repr(relationship.backref.name)
5✔
1289

1290
        rendered_relationship = render_callable(
5✔
1291
            "relationship", repr(relationship.target.name), kwargs=kwargs
1292
        )
1293

1294
        relationship_type: str
1295
        if relationship.type == RelationshipType.ONE_TO_MANY:
5✔
1296
            self.add_literal_import("typing", "List")
5✔
1297
            relationship_type = f"List['{relationship.target.name}']"
5✔
1298
        elif relationship.type in (
5✔
1299
            RelationshipType.ONE_TO_ONE,
1300
            RelationshipType.MANY_TO_ONE,
1301
        ):
1302
            relationship_type = f"'{relationship.target.name}'"
5✔
1303
        elif relationship.type == RelationshipType.MANY_TO_MANY:
5✔
1304
            self.add_literal_import("typing", "List")
5✔
1305
            relationship_type = f"List['{relationship.target.name}']"
5✔
1306
        else:
UNCOV
1307
            self.add_literal_import("typing", "Any")
×
UNCOV
1308
            relationship_type = "Any"
×
1309

1310
        return (
5✔
1311
            f"{relationship.name}: Mapped[{relationship_type}] "
1312
            f"= {rendered_relationship}"
1313
        )
1314

1315

1316
class DataclassGenerator(DeclarativeGenerator):
5✔
1317
    def __init__(
5✔
1318
        self,
1319
        metadata: MetaData,
1320
        bind: Connection | Engine,
1321
        options: Sequence[str],
1322
        *,
1323
        indentation: str = "    ",
1324
        base_class_name: str = "Base",
1325
        quote_annotations: bool = False,
1326
        metadata_key: str = "sa",
1327
    ):
1328
        super().__init__(
5✔
1329
            metadata,
1330
            bind,
1331
            options,
1332
            indentation=indentation,
1333
            base_class_name=base_class_name,
1334
        )
1335
        self.metadata_key: str = metadata_key
5✔
1336
        self.quote_annotations: bool = quote_annotations
5✔
1337

1338
    def generate_base(self) -> None:
5✔
1339
        self.base = Base(
5✔
1340
            literal_imports=[
1341
                LiteralImport("sqlalchemy.orm", "DeclarativeBase"),
1342
                LiteralImport("sqlalchemy.orm", "MappedAsDataclass"),
1343
            ],
1344
            declarations=[
1345
                (
1346
                    f"class {self.base_class_name}(MappedAsDataclass, "
1347
                    "DeclarativeBase):"
1348
                ),
1349
                f"{self.indentation}pass",
1350
            ],
1351
            metadata_ref=f"{self.base_class_name}.metadata",
1352
        )
1353

1354

1355
class SQLModelGenerator(DeclarativeGenerator):
5✔
1356
    def __init__(
5✔
1357
        self,
1358
        metadata: MetaData,
1359
        bind: Connection | Engine,
1360
        options: Sequence[str],
1361
        *,
1362
        indentation: str = "    ",
1363
        base_class_name: str = "SQLModel",
1364
    ):
1365
        super().__init__(
5✔
1366
            metadata,
1367
            bind,
1368
            options,
1369
            indentation=indentation,
1370
            base_class_name=base_class_name,
1371
        )
1372

1373
    @property
5✔
1374
    def views_supported(self) -> bool:
5✔
NEW
1375
        return False
×
1376

1377
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
1378
        self.add_import(Column)
5✔
1379
        return render_callable("Column", *args, kwargs=kwargs)
5✔
1380

1381
    def generate_base(self) -> None:
5✔
1382
        self.base = Base(
5✔
1383
            literal_imports=[],
1384
            declarations=[],
1385
            metadata_ref="",
1386
        )
1387

1388
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1389
        super(DeclarativeGenerator, self).collect_imports(models)
5✔
1390
        if any(isinstance(model, ModelClass) for model in models):
5✔
1391
            self.remove_literal_import("sqlalchemy", "MetaData")
5✔
1392
            self.add_literal_import("sqlmodel", "SQLModel")
5✔
1393
            self.add_literal_import("sqlmodel", "Field")
5✔
1394

1395
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1396
        super(DeclarativeGenerator, self).collect_imports_for_model(model)
5✔
1397
        if isinstance(model, ModelClass):
5✔
1398
            for column_attr in model.columns:
5✔
1399
                if column_attr.column.nullable:
5✔
1400
                    self.add_literal_import("typing", "Optional")
5✔
1401
                    break
5✔
1402

1403
            if model.relationships:
5✔
1404
                self.add_literal_import("sqlmodel", "Relationship")
5✔
1405

1406
            for relationship_attr in model.relationships:
5✔
1407
                if relationship_attr.type in (
5✔
1408
                    RelationshipType.ONE_TO_MANY,
1409
                    RelationshipType.MANY_TO_MANY,
1410
                ):
1411
                    self.add_literal_import("typing", "List")
5✔
1412

1413
    def collect_imports_for_column(self, column: Column[Any]) -> None:
5✔
1414
        super().collect_imports_for_column(column)
5✔
1415
        try:
5✔
1416
            python_type = column.type.python_type
5✔
UNCOV
1417
        except NotImplementedError:
×
UNCOV
1418
            self.add_literal_import("typing", "Any")
×
1419
        else:
1420
            self.add_import(python_type)
5✔
1421

1422
    def render_module_variables(self, models: list[Model]) -> str:
5✔
1423
        declarations: list[str] = []
5✔
1424
        if any(not isinstance(model, ModelClass) for model in models):
5✔
UNCOV
1425
            if self.base.table_metadata_declaration is not None:
×
UNCOV
1426
                declarations.append(self.base.table_metadata_declaration)
×
1427

1428
        return "\n".join(declarations)
5✔
1429

1430
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1431
        if model.parent_class:
5✔
UNCOV
1432
            parent = model.parent_class.name
×
1433
        else:
1434
            parent = self.base_class_name
5✔
1435

1436
        superclass_part = f"({parent}, table=True)"
5✔
1437
        return f"class {model.name}{superclass_part}:"
5✔
1438

1439
    def render_class_variables(self, model: ModelClass) -> str:
5✔
1440
        variables = []
5✔
1441

1442
        if model.table.name != model.name.lower():
5✔
1443
            variables.append(f"__tablename__ = {model.table.name!r}")
5✔
1444

1445
        # Render constraints and indexes as __table_args__
1446
        table_args = self.render_table_args(model.table)
5✔
1447
        if table_args:
5✔
1448
            variables.append(f"__table_args__ = {table_args}")
5✔
1449

1450
        return "\n".join(variables)
5✔
1451

1452
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1453
        column = column_attr.column
5✔
1454
        try:
5✔
1455
            python_type = column.type.python_type
5✔
UNCOV
1456
        except NotImplementedError:
×
UNCOV
1457
            python_type_name = "Any"
×
1458
        else:
1459
            python_type_name = python_type.__name__
5✔
1460

1461
        kwargs: dict[str, Any] = {}
5✔
1462
        if (
5✔
1463
            column.autoincrement and column.name in column.table.primary_key
1464
        ) or column.nullable:
1465
            self.add_literal_import("typing", "Optional")
5✔
1466
            kwargs["default"] = None
5✔
1467
            python_type_name = f"Optional[{python_type_name}]"
5✔
1468

1469
        rendered_column = self.render_column(column, True)
5✔
1470
        kwargs["sa_column"] = f"{rendered_column}"
5✔
1471
        rendered_field = render_callable("Field", kwargs=kwargs)
5✔
1472
        return f"{column_attr.name}: {python_type_name} = {rendered_field}"
5✔
1473

1474
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1475
        rendered = super().render_relationship(relationship).partition(" = ")[2]
5✔
1476
        args = self.render_relationship_args(rendered)
5✔
1477
        kwargs: dict[str, Any] = {}
5✔
1478
        annotation = repr(relationship.target.name)
5✔
1479

1480
        if relationship.type in (
5✔
1481
            RelationshipType.ONE_TO_MANY,
1482
            RelationshipType.MANY_TO_MANY,
1483
        ):
1484
            self.add_literal_import("typing", "List")
5✔
1485
            annotation = f"List[{annotation}]"
5✔
1486
        else:
1487
            self.add_literal_import("typing", "Optional")
5✔
1488
            annotation = f"Optional[{annotation}]"
5✔
1489

1490
        rendered_field = render_callable("Relationship", *args, kwargs=kwargs)
5✔
1491
        return f"{relationship.name}: {annotation} = {rendered_field}"
5✔
1492

1493
    def render_relationship_args(self, arguments: str) -> list[str]:
5✔
1494
        argument_list = arguments.split(",")
5✔
1495
        # delete ')' and ' ' from args
1496
        argument_list[-1] = argument_list[-1][:-1]
5✔
1497
        argument_list = [argument[1:] for argument in argument_list]
5✔
1498

1499
        rendered_args: list[str] = []
5✔
1500
        for arg in argument_list:
5✔
1501
            if "back_populates" in arg:
5✔
1502
                rendered_args.append(arg)
5✔
1503
            if "uselist=False" in arg:
5✔
1504
                rendered_args.append("sa_relationship_kwargs={'uselist': False}")
5✔
1505

1506
        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

© 2025 Coveralls, Inc