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

agronholm / sqlacodegen / 13578435790

28 Feb 2025 12:14AM UTC coverage: 97.078% (+0.02%) from 97.057%
13578435790

Pull #371

github

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

1362 of 1403 relevant lines covered (97.08%)

4.85 hits per line

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

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

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

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

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

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

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

79

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

85

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

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

96

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

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

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

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

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

124

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

343
        return models
5✔
344

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

623
        return name
5✔
624

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

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

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

659
                            continue
5✔
660

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

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

680
                        column.server_default = None
5✔
681

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

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

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

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

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

712
                try:
5✔
713
                    # If the adapted column type does not render the same as the
714
                    # original, don't substitute it
715
                    if new_coltype.compile(self.bind.engine.dialect) != compiled_type:
5✔
716
                        # Make an exception to the rule for Float and arrays of Float,
717
                        # since at least on PostgreSQL, Float can accurately represent
718
                        # both REAL and DOUBLE_PRECISION
719
                        if not isinstance(new_coltype, Float) and not (
5✔
720
                            isinstance(new_coltype, ARRAY)
721
                            and isinstance(new_coltype.item_type, Float)
722
                        ):
723
                            break
5✔
724
                except CompileError:
5✔
725
                    # If the adapted column type can't be compiled, don't substitute it
726
                    break
5✔
727

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

733
        return coltype
5✔
734

735

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1018
        return relationships
5✔
1019

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1333

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

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

1369

1370
class SQLModelGenerator(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 = "SQLModel",
1379
    ):
1380
        super().__init__(
5✔
1381
            metadata,
1382
            bind,
1383
            options,
1384
            indentation=indentation,
1385
            base_class_name=base_class_name,
1386
        )
1387

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1521
        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