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

agronholm / sqlacodegen / 13505851754

24 Feb 2025 07:08PM UTC coverage: 97.055% (+0.005%) from 97.05%
13505851754

Pull #371

github

web-flow
Merge 95f51166f into 70e1a5c07
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.

1351 of 1392 relevant lines covered (97.05%)

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

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

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

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

77

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

83

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

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

94

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

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

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

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

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

122

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

341
        return models
5✔
342

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

621
        return name
5✔
622

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

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

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

657
                            continue
5✔
658

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

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

678
                        column.server_default = None
5✔
679

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

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

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

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

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

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

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

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

734
        return coltype
5✔
735

736

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1019
        return relationships
5✔
1020

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1334

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

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

1370

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1522
        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