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

agronholm / sqlacodegen / 16350832724

17 Jul 2025 04:38PM UTC coverage: 97.663% (+0.3%) from 97.379%
16350832724

Pull #411

github

web-flow
Merge 4165a4b90 into e4c32c5e7
Pull Request #411: Fixed same-name imports from wrong package

32 of 32 new or added lines in 3 files covered. (100.0%)

1 existing line in 1 file now uncovered.

1421 of 1455 relevant lines covered (97.66%)

4.87 hits per line

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

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

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

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

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

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

74

75
@dataclass
5✔
76
class LiteralImport:
5✔
77
    pkgname: str
5✔
78
    name: str
5✔
79

80

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

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

91

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

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

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

107
    @property
5✔
108
    @abstractmethod
5✔
109
    def views_supported(self) -> bool:
5✔
110
        pass
×
111

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

119

120
@dataclass(eq=False)
5✔
121
class TablesGenerator(CodeGenerator):
5✔
122
    valid_options: ClassVar[set[str]] = {"noindexes", "noconstraints", "nocomments"}
5✔
123
    stdlib_module_names: ClassVar[set[str]] = get_stdlib_module_names()
5✔
124

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

276
            if type_.__name__ in dialect_pkg.__all__:
5✔
277
                pkgname = dialect_pkgname
5✔
278
        elif type_.__name__ in dir(sqlalchemy) and type_ == getattr(
5✔
279
            sqlalchemy, type_.__name__
280
        ):
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
        def get_collection(package: str) -> list[str]:
5✔
305
            collection = thirdparty_imports
5✔
306
            if package == "__future__":
5✔
307
                collection = future_imports
×
308
            elif package in self.stdlib_module_names:
5✔
309
                collection = stdlib_imports
5✔
310
            elif package in sys.modules:
5✔
311
                if "site-packages" not in (sys.modules[package].__file__ or ""):
5✔
312
                    collection = stdlib_imports
5✔
313
            return collection
5✔
314

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

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

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

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

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

334
        # Collect the imports
335
        self.collect_imports(models)
5✔
336

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

345
        return models
5✔
346

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

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

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

358
        return "\n".join(declarations)
5✔
359

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

366
        return "\n\n".join(rendered)
5✔
367

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

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

384
            args.append(self.render_constraint(constraint))
5✔
385

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

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

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

398
        return render_callable("Table", *args, kwargs=kwargs, indentation="    ")
5✔
399

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

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

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

447
        if show_name:
5✔
448
            args.append(repr(column.name))
5✔
449

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

455
        for fk in dedicated_fks:
5✔
456
            args.append(self.render_constraint(fk))
5✔
457

458
        if column.default:
5✔
459
            args.append(repr(column.default))
5✔
460

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

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

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

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

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

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

499
        return self.render_column_callable(is_table, *args, **kwargs)
5✔
500

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

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

523
            value = getattr(coltype, param.name, missing)
5✔
524

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

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

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

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

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

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

575
        if args or kwargs:
5✔
576
            return render_callable(coltype.__class__.__name__, *args, kwargs=kwargs)
5✔
577
        else:
578
            return coltype.__class__.__name__
5✔
579

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

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

611
        if isinstance(constraint, Constraint) and not uses_default_name(constraint):
5✔
612
            kwargs["name"] = repr(constraint.name)
5✔
613

614
        return render_callable(constraint.__class__.__name__, *args, kwargs=kwargs)
5✔
615

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

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

635
        original = name
5✔
636
        for i in count():
5✔
637
            if name not in global_names and name not in local_names:
5✔
638
                break
5✔
639

640
            name = original + (str(i) if i else "_")
5✔
641

642
        return name
5✔
643

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

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

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

678
                            continue
5✔
679

680
        for column in table.c:
5✔
681
            try:
5✔
682
                column.type = self.get_adapted_type(column.type)
5✔
683
            except CompileError:
5✔
684
                pass
5✔
685

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

699
                        column.server_default = None
5✔
700

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

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

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

725
                for key, value in kw.items():
5✔
726
                    setattr(new_coltype, key, value)
5✔
727

728
                if isinstance(coltype, ARRAY):
5✔
729
                    new_coltype.item_type = self.get_adapted_type(new_coltype.item_type)
5✔
730

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

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

745
        return coltype
5✔
746

747

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

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

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

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

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

790
    def generate_models(self) -> list[Model]:
5✔
791
        models_by_table_name: dict[str, Model] = {}
5✔
792

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

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

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

820
                # Fill in the columns
821
                for column in table.c:
5✔
822
                    column_attr = ColumnAttribute(model, column)
5✔
823
                    model.columns.append(column_attr)
5✔
824

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

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

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

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

854
        # Collect the imports
855
        self.collect_imports(models_by_table_name.values())
5✔
856

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

866
        return list(models_by_table_name.values())
5✔
867

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

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

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

907
                relationship = RelationshipAttribute(r_type, source, target, constraint)
5✔
908
                source.relationships.append(relationship)
5✔
909

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

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

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

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

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

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

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

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

993
                    for relationship, reverse in zip(both_relationships, reverse_flags):
5✔
994
                        if (
5✔
995
                            not relationship.association_table
996
                            or not relationship.constraint
997
                        ):
998
                            continue
×
999

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

1030
        return relationships
5✔
1031

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

1043
            model.name = self.find_free_name(preferred_name, global_names)
5✔
1044

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

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

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

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

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

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

1112
        relationship.name = self.find_free_name(
5✔
1113
            preferred_name, global_names, local_names
1114
        )
1115

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

1124
        return "\n\n\n".join(rendered)
5✔
1125

1126
    def render_class(self, model: ModelClass) -> str:
5✔
1127
        sections: list[str] = []
5✔
1128

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

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

1143
        if rendered_column_attributes:
5✔
1144
            sections.append("\n".join(rendered_column_attributes))
5✔
1145

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

1152
        if rendered_relationship_attributes:
5✔
1153
            sections.append("\n".join(rendered_relationship_attributes))
5✔
1154

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

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

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

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

1175
        return "\n".join(variables)
5✔
1176

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

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

1192
            args.append(self.render_constraint(constraint))
5✔
1193

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

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

1202
        if table.comment:
5✔
1203
            kwargs["comment"] = table.comment
5✔
1204

1205
        if kwargs:
5✔
1206
            formatted_kwargs = pformat(kwargs)
5✔
1207
            if not args:
5✔
1208
                return formatted_kwargs
5✔
1209
            else:
1210
                args.append(formatted_kwargs)
5✔
1211

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

1217
            return f"(\n{self.indentation}{rendered_args}\n)"
5✔
1218
        else:
1219
            return ""
5✔
1220

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

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

1236
                column_type = column_type.item_type
5✔
1237

1238
            return "".join(pre), column_type, "]" * post_size
5✔
1239

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

1246
            python_type_name = python_type.__name__
5✔
1247
            python_type_module = python_type.__module__
5✔
1248
            if python_type_module == "builtins":
5✔
1249
                return python_type_name
5✔
1250

1251
            try:
5✔
1252
                self.add_module_import(python_type_module)
5✔
1253
                return f"{python_type_module}.{python_type_name}"
5✔
1254
            except NotImplementedError:
×
1255
                self.add_literal_import("typing", "Any")
×
1256
                return "Any"
×
1257

1258
        pre, col_type, post = get_type_qualifiers()
5✔
1259
        column_python_type = f"{pre}{render_python_type(col_type)}{post}"
5✔
1260
        return column_python_type
5✔
1261

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

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

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

1278
            return "[" + ", ".join(rendered) + "]"
5✔
1279

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

1291
            if render_as_string:
5✔
1292
                return "'[" + ", ".join(rendered) + "]'"
5✔
1293
            else:
1294
                return "[" + ", ".join(rendered) + "]"
5✔
1295

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

1303
                rendered += str(target_col)
5✔
1304
                rendered_joins.append(rendered)
5✔
1305

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

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

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

1324
            kwargs["secondary"] = repr(table_ref)
5✔
1325

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

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

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

1335
        if relationship.secondaryjoin:
5✔
1336
            kwargs["secondaryjoin"] = render_join(relationship.secondaryjoin)
5✔
1337

1338
        if relationship.backref:
5✔
1339
            kwargs["back_populates"] = repr(relationship.backref.name)
5✔
1340

1341
        rendered_relationship = render_callable(
5✔
1342
            "relationship", repr(relationship.target.name), kwargs=kwargs
1343
        )
1344

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

1364
        return (
5✔
1365
            f"{relationship.name}: Mapped[{relationship_type}] "
1366
            f"= {rendered_relationship}"
1367
        )
1368

1369

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

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

1405

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

1424
    @property
5✔
1425
    def views_supported(self) -> bool:
5✔
1426
        return False
×
1427

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

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

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

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

1454
            if model.relationships:
5✔
1455
                self.add_literal_import("sqlmodel", "Relationship")
5✔
1456

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

1463
        return "\n".join(declarations)
5✔
1464

1465
    def render_class_declaration(self, model: ModelClass) -> str:
5✔
1466
        if model.parent_class:
5✔
1467
            parent = model.parent_class.name
×
1468
        else:
1469
            parent = self.base_class_name
5✔
1470

1471
        superclass_part = f"({parent}, table=True)"
5✔
1472
        return f"class {model.name}{superclass_part}:"
5✔
1473

1474
    def render_class_variables(self, model: ModelClass) -> str:
5✔
1475
        variables = []
5✔
1476

1477
        if model.table.name != model.name.lower():
5✔
1478
            variables.append(f"__tablename__ = {model.table.name!r}")
5✔
1479

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

1485
        return "\n".join(variables)
5✔
1486

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

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

1497
        rendered_field = render_callable("Field", kwargs=kwargs)
5✔
1498

1499
        return f"{column_attr.name}: {rendered_column_python_type} = {rendered_field}"
5✔
1500

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

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

1516
        rendered_field = render_callable("Relationship", *args, kwargs=kwargs)
5✔
1517
        return f"{relationship.name}: {annotation} = {rendered_field}"
5✔
1518

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

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

1532
        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