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

agronholm / sqlacodegen / 13488544061

24 Feb 2025 12:41AM UTC coverage: 97.046% (+0.004%) from 97.042%
13488544061

Pull #371

github

web-flow
Merge 7083c12f4 into e5ee452e0
Pull Request #371: Fixed MySQL DOUBLE column type rendering

1347 of 1388 relevant lines covered (97.05%)

4.85 hits per line

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

96.01
/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
1✔
67
else:
68
    pass
4✔
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✔
107
            raise ValueError("Unrecognized options: " + ", ".join(invalid_options))
×
108

109
    @property
5✔
110
    @abstractmethod
5✔
111
    def views_supported(self) -> bool:
5✔
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✔
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✔
161
                self.metadata.remove(table)
×
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✔
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✔
308
                collection = future_imports
×
309
            elif package in self.builtin_module_names:
5✔
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✔
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✔
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✔
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✔
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
                use_kwargs = True
5✔
516
                continue
5✔
517

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

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

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

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

553
        if args or kwargs:
5✔
554
            return render_callable(coltype.__class__.__name__, *args, kwargs=kwargs)
5✔
555
        else:
556
            return coltype.__class__.__name__
5✔
557

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

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

589
        if isinstance(constraint, Constraint) and not uses_default_name(constraint):
5✔
590
            kwargs["name"] = repr(constraint.name)
5✔
591

592
        return render_callable(constraint.__class__.__name__, *args, kwargs=kwargs)
5✔
593

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

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

613
        original = name
5✔
614
        for i in count():
5✔
615
            if name not in global_names and name not in local_names:
5✔
616
                break
5✔
617

618
            name = original + (str(i) if i else "_")
5✔
619

620
        return name
5✔
621

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

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

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

656
                            continue
5✔
657

658
        for column in table.c:
5✔
659
            try:
5✔
660
                column.type = self.get_adapted_type(column.type)
5✔
661
            except CompileError:
5✔
662
                pass
5✔
663

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

677
                        column.server_default = None
5✔
678

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

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

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

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

705
                try:
5✔
706
                    # If the adapted column type does not render the same as the
707
                    # original, don't substitute it
708
                    if new_coltype.compile(self.bind.engine.dialect) != compiled_type:
5✔
709
                        if self.bind.dialect.name != "postgresql":
5✔
710
                            break
5✔
711

712
                        # Make an exception to the rule for Float and arrays of Float,
713
                        # since at least on PostgreSQL, Float can accurately represent
714
                        # both REAL and DOUBLE_PRECISION
715
                        if not isinstance(new_coltype, Float) and not (
5✔
716
                            isinstance(new_coltype, ARRAY)
717
                            and isinstance(new_coltype.item_type, Float)
718
                        ):
719
                            break
5✔
720
                except CompileError:
5✔
721
                    # If the adapted column type can't be compiled, don't substitute it
722
                    break
5✔
723

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

729
        return coltype
5✔
730

731

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

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

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

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

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

774
    def generate_models(self) -> list[Model]:
5✔
775
        models_by_table_name: dict[str, Model] = {}
5✔
776

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

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

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

804
                # Fill in the columns
805
                for column in table.c:
5✔
806
                    column_attr = ColumnAttribute(model, column)
5✔
807
                    model.columns.append(column_attr)
5✔
808

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

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

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

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

838
        # Collect the imports
839
        self.collect_imports(models_by_table_name.values())
5✔
840

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

850
        return list(models_by_table_name.values())
5✔
851

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

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

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

891
                relationship = RelationshipAttribute(r_type, source, target, constraint)
5✔
892
                source.relationships.append(relationship)
5✔
893

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

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

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

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

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

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

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

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

977
                    for relationship, reverse in zip(both_relationships, reverse_flags):
5✔
978
                        if (
5✔
979
                            not relationship.association_table
980
                            or not relationship.constraint
981
                        ):
982
                            continue
×
983

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

1014
        return relationships
5✔
1015

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

1027
            model.name = self.find_free_name(preferred_name, global_names)
5✔
1028

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

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

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

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

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

1083
            if "use_inflect" in self.options:
5✔
1084
                if relationship.type in (
5✔
1085
                    RelationshipType.ONE_TO_MANY,
1086
                    RelationshipType.MANY_TO_MANY,
1087
                ):
1088
                    inflected_name = self.inflect_engine.plural_noun(preferred_name)
×
1089
                    if inflected_name:
×
1090
                        preferred_name = inflected_name
×
1091
                else:
1092
                    inflected_name = self.inflect_engine.singular_noun(preferred_name)
5✔
1093
                    if inflected_name:
5✔
1094
                        preferred_name = inflected_name
5✔
1095

1096
        relationship.name = self.find_free_name(
5✔
1097
            preferred_name, global_names, local_names
1098
        )
1099

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

1108
        return "\n\n\n".join(rendered)
5✔
1109

1110
    def render_class(self, model: ModelClass) -> str:
5✔
1111
        sections: list[str] = []
5✔
1112

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

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

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

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

1136
        if rendered_relationship_attributes:
5✔
1137
            sections.append("\n".join(rendered_relationship_attributes))
5✔
1138

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

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

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

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

1159
        return "\n".join(variables)
5✔
1160

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

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

1176
            args.append(self.render_constraint(constraint))
5✔
1177

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

1183
        if table.schema:
5✔
1184
            kwargs["schema"] = table.schema
5✔
1185

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

1189
        if kwargs:
5✔
1190
            formatted_kwargs = pformat(kwargs)
5✔
1191
            if not args:
5✔
1192
                return formatted_kwargs
5✔
1193
            else:
1194
                args.append(formatted_kwargs)
5✔
1195

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

1201
            return f"(\n{self.indentation}{rendered_args}\n)"
5✔
1202
        else:
1203
            return ""
5✔
1204

1205
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1206
        column = column_attr.column
5✔
1207
        rendered_column = self.render_column(column, column_attr.name != column.name)
5✔
1208

1209
        try:
5✔
1210
            python_type = column.type.python_type
5✔
1211
            python_type_name = python_type.__name__
5✔
1212
            if python_type.__module__ == "builtins":
5✔
1213
                column_python_type = python_type_name
5✔
1214
            else:
1215
                python_type_module = python_type.__module__
5✔
1216
                column_python_type = f"{python_type_module}.{python_type_name}"
5✔
1217
                self.add_module_import(python_type_module)
5✔
1218
        except NotImplementedError:
×
1219
            self.add_literal_import("typing", "Any")
×
1220
            column_python_type = "Any"
×
1221

1222
        if column.nullable:
5✔
1223
            self.add_literal_import("typing", "Optional")
5✔
1224
            column_python_type = f"Optional[{column_python_type}]"
5✔
1225
        return f"{column_attr.name}: Mapped[{column_python_type}] = {rendered_column}"
5✔
1226

1227
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1228
        def render_column_attrs(column_attrs: list[ColumnAttribute]) -> str:
5✔
1229
            rendered = []
5✔
1230
            for attr in column_attrs:
5✔
1231
                if attr.model is relationship.source:
5✔
1232
                    rendered.append(attr.name)
5✔
1233
                else:
1234
                    rendered.append(repr(f"{attr.model.name}.{attr.name}"))
×
1235

1236
            return "[" + ", ".join(rendered) + "]"
5✔
1237

1238
        def render_foreign_keys(column_attrs: list[ColumnAttribute]) -> str:
5✔
1239
            rendered = []
5✔
1240
            render_as_string = False
5✔
1241
            # Assume that column_attrs are all in relationship.source or none
1242
            for attr in column_attrs:
5✔
1243
                if attr.model is relationship.source:
5✔
1244
                    rendered.append(attr.name)
5✔
1245
                else:
1246
                    rendered.append(f"{attr.model.name}.{attr.name}")
5✔
1247
                    render_as_string = True
5✔
1248

1249
            if render_as_string:
5✔
1250
                return "'[" + ", ".join(rendered) + "]'"
5✔
1251
            else:
1252
                return "[" + ", ".join(rendered) + "]"
5✔
1253

1254
        def render_join(terms: list[JoinType]) -> str:
5✔
1255
            rendered_joins = []
5✔
1256
            for source, source_col, target, target_col in terms:
5✔
1257
                rendered = f"lambda: {source.name}.{source_col} == {target.name}."
5✔
1258
                if target.__class__ is Model:
5✔
1259
                    rendered += "c."
5✔
1260

1261
                rendered += str(target_col)
5✔
1262
                rendered_joins.append(rendered)
5✔
1263

1264
            if len(rendered_joins) > 1:
5✔
1265
                rendered = ", ".join(rendered_joins)
×
1266
                return f"and_({rendered})"
×
1267
            else:
1268
                return rendered_joins[0]
5✔
1269

1270
        # Render keyword arguments
1271
        kwargs: dict[str, Any] = {}
5✔
1272
        if relationship.type is RelationshipType.ONE_TO_ONE and relationship.constraint:
5✔
1273
            if relationship.constraint.referred_table is relationship.source.table:
5✔
1274
                kwargs["uselist"] = False
5✔
1275

1276
        # Add the "secondary" keyword for many-to-many relationships
1277
        if relationship.association_table:
5✔
1278
            table_ref = relationship.association_table.table.name
5✔
1279
            if relationship.association_table.schema:
5✔
1280
                table_ref = f"{relationship.association_table.schema}.{table_ref}"
5✔
1281

1282
            kwargs["secondary"] = repr(table_ref)
5✔
1283

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

1287
        if relationship.foreign_keys:
5✔
1288
            kwargs["foreign_keys"] = render_foreign_keys(relationship.foreign_keys)
5✔
1289

1290
        if relationship.primaryjoin:
5✔
1291
            kwargs["primaryjoin"] = render_join(relationship.primaryjoin)
5✔
1292

1293
        if relationship.secondaryjoin:
5✔
1294
            kwargs["secondaryjoin"] = render_join(relationship.secondaryjoin)
5✔
1295

1296
        if relationship.backref:
5✔
1297
            kwargs["back_populates"] = repr(relationship.backref.name)
5✔
1298

1299
        rendered_relationship = render_callable(
5✔
1300
            "relationship", repr(relationship.target.name), kwargs=kwargs
1301
        )
1302

1303
        relationship_type: str
1304
        if relationship.type == RelationshipType.ONE_TO_MANY:
5✔
1305
            self.add_literal_import("typing", "List")
5✔
1306
            relationship_type = f"List['{relationship.target.name}']"
5✔
1307
        elif relationship.type in (
5✔
1308
            RelationshipType.ONE_TO_ONE,
1309
            RelationshipType.MANY_TO_ONE,
1310
        ):
1311
            relationship_type = f"'{relationship.target.name}'"
5✔
1312
            if relationship.constraint and any(
5✔
1313
                col.nullable for col in relationship.constraint.columns
1314
            ):
1315
                self.add_literal_import("typing", "Optional")
5✔
1316
                relationship_type = f"Optional[{relationship_type}]"
5✔
1317
        elif relationship.type == RelationshipType.MANY_TO_MANY:
5✔
1318
            self.add_literal_import("typing", "List")
5✔
1319
            relationship_type = f"List['{relationship.target.name}']"
5✔
1320
        else:
1321
            self.add_literal_import("typing", "Any")
×
1322
            relationship_type = "Any"
×
1323

1324
        return (
5✔
1325
            f"{relationship.name}: Mapped[{relationship_type}] "
1326
            f"= {rendered_relationship}"
1327
        )
1328

1329

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

1352
    def generate_base(self) -> None:
5✔
1353
        self.base = Base(
5✔
1354
            literal_imports=[
1355
                LiteralImport("sqlalchemy.orm", "DeclarativeBase"),
1356
                LiteralImport("sqlalchemy.orm", "MappedAsDataclass"),
1357
            ],
1358
            declarations=[
1359
                (f"class {self.base_class_name}(MappedAsDataclass, DeclarativeBase):"),
1360
                f"{self.indentation}pass",
1361
            ],
1362
            metadata_ref=f"{self.base_class_name}.metadata",
1363
        )
1364

1365

1366
class SQLModelGenerator(DeclarativeGenerator):
5✔
1367
    def __init__(
5✔
1368
        self,
1369
        metadata: MetaData,
1370
        bind: Connection | Engine,
1371
        options: Sequence[str],
1372
        *,
1373
        indentation: str = "    ",
1374
        base_class_name: str = "SQLModel",
1375
    ):
1376
        super().__init__(
5✔
1377
            metadata,
1378
            bind,
1379
            options,
1380
            indentation=indentation,
1381
            base_class_name=base_class_name,
1382
        )
1383

1384
    @property
5✔
1385
    def views_supported(self) -> bool:
5✔
1386
        return False
×
1387

1388
    def render_column_callable(self, is_table: bool, *args: Any, **kwargs: Any) -> str:
5✔
1389
        self.add_import(Column)
5✔
1390
        return render_callable("Column", *args, kwargs=kwargs)
5✔
1391

1392
    def generate_base(self) -> None:
5✔
1393
        self.base = Base(
5✔
1394
            literal_imports=[],
1395
            declarations=[],
1396
            metadata_ref="",
1397
        )
1398

1399
    def collect_imports(self, models: Iterable[Model]) -> None:
5✔
1400
        super(DeclarativeGenerator, self).collect_imports(models)
5✔
1401
        if any(isinstance(model, ModelClass) for model in models):
5✔
1402
            self.remove_literal_import("sqlalchemy", "MetaData")
5✔
1403
            self.add_literal_import("sqlmodel", "SQLModel")
5✔
1404
            self.add_literal_import("sqlmodel", "Field")
5✔
1405

1406
    def collect_imports_for_model(self, model: Model) -> None:
5✔
1407
        super(DeclarativeGenerator, self).collect_imports_for_model(model)
5✔
1408
        if isinstance(model, ModelClass):
5✔
1409
            for column_attr in model.columns:
5✔
1410
                if column_attr.column.nullable:
5✔
1411
                    self.add_literal_import("typing", "Optional")
5✔
1412
                    break
5✔
1413

1414
            if model.relationships:
5✔
1415
                self.add_literal_import("sqlmodel", "Relationship")
5✔
1416

1417
            for relationship_attr in model.relationships:
5✔
1418
                if relationship_attr.type in (
5✔
1419
                    RelationshipType.ONE_TO_MANY,
1420
                    RelationshipType.MANY_TO_MANY,
1421
                ):
1422
                    self.add_literal_import("typing", "List")
5✔
1423

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1517
        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