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

agronholm / sqlacodegen / 13531179453

25 Feb 2025 09:20PM UTC coverage: 97.061% (+0.004%) from 97.057%
13531179453

Pull #371

github

web-flow
Merge b9f16da50 into 6da9a0b29
Pull Request #371: Fixed MySQL DOUBLE column type rendering

1 of 1 new or added line in 1 file covered. (100.0%)

32 existing lines in 1 file now uncovered.

1354 of 1395 relevant lines covered (97.06%)

4.85 hits per line

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

96.03
/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
    TypeDecorator,
40
    UniqueConstraint,
41
)
42
from sqlalchemy.dialects.postgresql import JSONB
5✔
43
from sqlalchemy.engine import Connection, Engine
5✔
44
from sqlalchemy.exc import CompileError
5✔
45
from sqlalchemy.sql.elements import TextClause
5✔
46
from sqlalchemy.sql.type_api import UserDefinedType
5✔
47

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

67
if sys.version_info < (3, 10):
5✔
68
    pass
1✔
69
else:
70
    pass
4✔
71

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

78

79
@dataclass
5✔
80
class LiteralImport:
5✔
81
    pkgname: str
5✔
82
    name: str
5✔
83

84

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

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

95

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

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

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

111
    @property
5✔
112
    @abstractmethod
5✔
113
    def views_supported(self) -> bool:
5✔
UNCOV
114
        pass
×
115

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

123

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

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

144
    @property
5✔
145
    def views_supported(self) -> bool:
5✔
UNCOV
146
        return True
×
147

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

155
    def generate(self) -> str:
5✔
156
        self.generate_base()
5✔
157

158
        sections: list[str] = []
5✔
159

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

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

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

172
            if "nocomments" in self.options:
5✔
173
                table.comment = None
5✔
174

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

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

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

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

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

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

203
        return "\n\n".join(sections) + "\n"
5✔
204

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

209
        for model in models:
5✔
210
            self.collect_imports_for_model(model)
5✔
211

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

216
        for column in model.table.c:
5✔
217
            self.collect_imports_for_column(column)
5✔
218

219
        for constraint in model.table.constraints:
5✔
220
            self.collect_imports_for_constraint(constraint)
5✔
221

222
        for index in model.table.indexes:
5✔
223
            self.collect_imports_for_constraint(index)
5✔
224

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

342
        return models
5✔
343

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

594
        return render_callable(constraint.__class__.__name__, *args, kwargs=kwargs)
5✔
595

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

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

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

620
            name = original + (str(i) if i else "_")
5✔
621

622
        return name
5✔
623

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

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

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

658
                            continue
5✔
659

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

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

679
                        column.server_default = None
5✔
680

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

691
                # Hack to fix adaptation of the Enum class which is broken since
692
                # SQLAlchemy 1.2
693
                kw = {}
5✔
694
                if supercls is Enum:
5✔
695
                    kw["name"] = coltype.name
5✔
696
                    if coltype.schema:
5✔
697
                        kw["schema"] = coltype.schema
5✔
698

699
                try:
5✔
700
                    new_coltype = coltype.adapt(supercls)
5✔
701
                except TypeError:
5✔
702
                    # If the adaptation fails, don't try again
703
                    break
5✔
704

705
                for key, value in kw.items():
5✔
706
                    setattr(new_coltype, key, value)
5✔
707

708
                if isinstance(coltype, ARRAY):
5✔
709
                    new_coltype.item_type = self.get_adapted_type(new_coltype.item_type)
5✔
710

711
                try:
5✔
712
                    # If the adapted column type does not render the same as the
713
                    # original, don't substitute it
714
                    if new_coltype.compile(self.bind.engine.dialect) != compiled_type:
5✔
715
                        if self.bind.dialect.name != "postgresql":
5✔
716
                            break
5✔
717

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

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

735
        return coltype
5✔
736

737

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

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

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

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

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

780
    def generate_models(self) -> list[Model]:
5✔
781
        models_by_table_name: dict[str, Model] = {}
5✔
782

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

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

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

810
                # Fill in the columns
811
                for column in table.c:
5✔
812
                    column_attr = ColumnAttribute(model, column)
5✔
813
                    model.columns.append(column_attr)
5✔
814

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

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

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

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

844
        # Collect the imports
845
        self.collect_imports(models_by_table_name.values())
5✔
846

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

856
        return list(models_by_table_name.values())
5✔
857

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

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

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

897
                relationship = RelationshipAttribute(r_type, source, target, constraint)
5✔
898
                source.relationships.append(relationship)
5✔
899

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

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

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

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

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

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

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

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

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

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

1020
        return relationships
5✔
1021

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

1033
            model.name = self.find_free_name(preferred_name, global_names)
5✔
1034

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

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

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

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

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

1089
            if "use_inflect" in self.options:
5✔
1090
                if relationship.type in (
5✔
1091
                    RelationshipType.ONE_TO_MANY,
1092
                    RelationshipType.MANY_TO_MANY,
1093
                ):
UNCOV
1094
                    inflected_name = self.inflect_engine.plural_noun(preferred_name)
×
UNCOV
1095
                    if inflected_name:
×
UNCOV
1096
                        preferred_name = inflected_name
×
1097
                else:
1098
                    inflected_name = self.inflect_engine.singular_noun(preferred_name)
5✔
1099
                    if inflected_name:
5✔
1100
                        preferred_name = inflected_name
5✔
1101

1102
        relationship.name = self.find_free_name(
5✔
1103
            preferred_name, global_names, local_names
1104
        )
1105

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

1114
        return "\n\n\n".join(rendered)
5✔
1115

1116
    def render_class(self, model: ModelClass) -> str:
5✔
1117
        sections: list[str] = []
5✔
1118

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

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

1133
        if rendered_column_attributes:
5✔
1134
            sections.append("\n".join(rendered_column_attributes))
5✔
1135

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

1142
        if rendered_relationship_attributes:
5✔
1143
            sections.append("\n".join(rendered_relationship_attributes))
5✔
1144

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

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

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

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

1165
        return "\n".join(variables)
5✔
1166

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

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

1182
            args.append(self.render_constraint(constraint))
5✔
1183

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

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

1192
        if table.comment:
5✔
1193
            kwargs["comment"] = table.comment
5✔
1194

1195
        if kwargs:
5✔
1196
            formatted_kwargs = pformat(kwargs)
5✔
1197
            if not args:
5✔
1198
                return formatted_kwargs
5✔
1199
            else:
1200
                args.append(formatted_kwargs)
5✔
1201

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

1207
            return f"(\n{self.indentation}{rendered_args}\n)"
5✔
1208
        else:
1209
            return ""
5✔
1210

1211
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1212
        column = column_attr.column
5✔
1213
        rendered_column = self.render_column(column, column_attr.name != column.name)
5✔
1214

1215
        try:
5✔
1216
            python_type = column.type.python_type
5✔
1217
            python_type_name = python_type.__name__
5✔
1218
            if python_type.__module__ == "builtins":
5✔
1219
                column_python_type = python_type_name
5✔
1220
            else:
1221
                python_type_module = python_type.__module__
5✔
1222
                column_python_type = f"{python_type_module}.{python_type_name}"
5✔
1223
                self.add_module_import(python_type_module)
5✔
UNCOV
1224
        except NotImplementedError:
×
UNCOV
1225
            self.add_literal_import("typing", "Any")
×
UNCOV
1226
            column_python_type = "Any"
×
1227

1228
        if column.nullable:
5✔
1229
            self.add_literal_import("typing", "Optional")
5✔
1230
            column_python_type = f"Optional[{column_python_type}]"
5✔
1231
        return f"{column_attr.name}: Mapped[{column_python_type}] = {rendered_column}"
5✔
1232

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

1242
            return "[" + ", ".join(rendered) + "]"
5✔
1243

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

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

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

1267
                rendered += str(target_col)
5✔
1268
                rendered_joins.append(rendered)
5✔
1269

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

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

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

1288
            kwargs["secondary"] = repr(table_ref)
5✔
1289

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

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

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

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

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

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

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

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

1335

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

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

1371

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

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

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

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

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

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

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

1423
            for relationship_attr in model.relationships:
5✔
1424
                if relationship_attr.type in (
5✔
1425
                    RelationshipType.ONE_TO_MANY,
1426
                    RelationshipType.MANY_TO_MANY,
1427
                ):
1428
                    self.add_literal_import("typing", "List")
5✔
1429

1430
    def collect_imports_for_column(self, column: Column[Any]) -> None:
5✔
1431
        super().collect_imports_for_column(column)
5✔
1432
        try:
5✔
1433
            python_type = column.type.python_type
5✔
UNCOV
1434
        except NotImplementedError:
×
UNCOV
1435
            self.add_literal_import("typing", "Any")
×
1436
        else:
1437
            self.add_import(python_type)
5✔
1438

1439
    def render_module_variables(self, models: list[Model]) -> str:
5✔
1440
        declarations: list[str] = []
5✔
1441
        if any(not isinstance(model, ModelClass) for model in models):
5✔
UNCOV
1442
            if self.base.table_metadata_declaration is not None:
×
UNCOV
1443
                declarations.append(self.base.table_metadata_declaration)
×
1444

1445
        return "\n".join(declarations)
5✔
1446

1447
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1448
        if model.parent_class:
5✔
UNCOV
1449
            parent = model.parent_class.name
×
1450
        else:
1451
            parent = self.base_class_name
5✔
1452

1453
        superclass_part = f"({parent}, table=True)"
5✔
1454
        return f"class {model.name}{superclass_part}:"
5✔
1455

1456
    def render_class_variables(self, model: ModelClass) -> str:
5✔
1457
        variables = []
5✔
1458

1459
        if model.table.name != model.name.lower():
5✔
1460
            variables.append(f"__tablename__ = {model.table.name!r}")
5✔
1461

1462
        # Render constraints and indexes as __table_args__
1463
        table_args = self.render_table_args(model.table)
5✔
1464
        if table_args:
5✔
1465
            variables.append(f"__table_args__ = {table_args}")
5✔
1466

1467
        return "\n".join(variables)
5✔
1468

1469
    def render_column_attribute(self, column_attr: ColumnAttribute) -> str:
5✔
1470
        column = column_attr.column
5✔
1471
        try:
5✔
1472
            python_type = column.type.python_type
5✔
UNCOV
1473
        except NotImplementedError:
×
UNCOV
1474
            python_type_name = "Any"
×
1475
        else:
1476
            python_type_name = python_type.__name__
5✔
1477

1478
        kwargs: dict[str, Any] = {}
5✔
1479
        if (
5✔
1480
            column.autoincrement and column.name in column.table.primary_key
1481
        ) or column.nullable:
1482
            self.add_literal_import("typing", "Optional")
5✔
1483
            kwargs["default"] = None
5✔
1484
            python_type_name = f"Optional[{python_type_name}]"
5✔
1485

1486
        rendered_column = self.render_column(column, True)
5✔
1487
        kwargs["sa_column"] = f"{rendered_column}"
5✔
1488
        rendered_field = render_callable("Field", kwargs=kwargs)
5✔
1489
        return f"{column_attr.name}: {python_type_name} = {rendered_field}"
5✔
1490

1491
    def render_relationship(self, relationship: RelationshipAttribute) -> str:
5✔
1492
        rendered = super().render_relationship(relationship).partition(" = ")[2]
5✔
1493
        args = self.render_relationship_args(rendered)
5✔
1494
        kwargs: dict[str, Any] = {}
5✔
1495
        annotation = repr(relationship.target.name)
5✔
1496

1497
        if relationship.type in (
5✔
1498
            RelationshipType.ONE_TO_MANY,
1499
            RelationshipType.MANY_TO_MANY,
1500
        ):
1501
            self.add_literal_import("typing", "List")
5✔
1502
            annotation = f"List[{annotation}]"
5✔
1503
        else:
1504
            self.add_literal_import("typing", "Optional")
5✔
1505
            annotation = f"Optional[{annotation}]"
5✔
1506

1507
        rendered_field = render_callable("Relationship", *args, kwargs=kwargs)
5✔
1508
        return f"{relationship.name}: {annotation} = {rendered_field}"
5✔
1509

1510
    def render_relationship_args(self, arguments: str) -> list[str]:
5✔
1511
        argument_list = arguments.split(",")
5✔
1512
        # delete ')' and ' ' from args
1513
        argument_list[-1] = argument_list[-1][:-1]
5✔
1514
        argument_list = [argument[1:] for argument in argument_list]
5✔
1515

1516
        rendered_args: list[str] = []
5✔
1517
        for arg in argument_list:
5✔
1518
            if "back_populates" in arg:
5✔
1519
                rendered_args.append(arg)
5✔
1520
            if "uselist=False" in arg:
5✔
1521
                rendered_args.append("sa_relationship_kwargs={'uselist': False}")
5✔
1522

1523
        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