-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathcodegen.py
More file actions
720 lines (586 loc) · 31.1 KB
/
codegen.py
File metadata and controls
720 lines (586 loc) · 31.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
"""Contains the code generation logic and helper functions."""
from __future__ import unicode_literals, division, print_function, absolute_import
from collections import defaultdict
from keyword import iskeyword
import inspect
import sys
import re
from sqlalchemy import (Enum, ForeignKeyConstraint, PrimaryKeyConstraint, CheckConstraint, UniqueConstraint, Table,
Column)
from sqlalchemy.schema import ForeignKey
from sqlalchemy.util import OrderedDict
from sqlalchemy.types import Boolean, String
import sqlalchemy
try:
from sqlalchemy.sql.expression import text, TextClause
except ImportError:
# SQLAlchemy < 0.8
from sqlalchemy.sql.expression import text, _TextClause as TextClause
_re_boolean_check_constraint = re.compile(r"(?:(?:.*?)\.)?(.*?) IN \(0, 1\)")
_re_column_name = re.compile(r'(?:(["`]?)(?:.*)\1\.)?(["`]?)(.*)\2')
_re_enum_check_constraint = re.compile(r"(?:(?:.*?)\.)?(.*?) IN \((.+)\)")
_re_enum_item = re.compile(r"'(.*?)(?<!\\)'")
_re_invalid_identifier = re.compile(r'[^a-zA-Z0-9_]' if sys.version_info[0] < 3 else r'(?u)\W')
_re_invalid_relationship = re.compile(r'[^a-zA-Z0-9._()\[\]{}= \'",]')
_re_first_cap = re.compile('(.)([A-Z][a-z]+)')
_re_all_cap = re.compile('([a-z0-9])([A-Z])')
_flask_prepend = 'db.'
_dataclass = False
_sqla_orm = False
class _DummyInflectEngine(object):
def singular_noun(self, noun):
return noun
def plural_noun(self, noun): # needed for backrefs
import inflect
inflect_engine = inflect.engine()
return inflect_engine.plural_noun(noun)
# In SQLAlchemy 0.x, constraint.columns is sometimes a list, on 1.x onwards, always a ColumnCollection
def _get_column_names(constraint):
if isinstance(constraint.columns, list):
return constraint.columns
return list(constraint.columns.keys())
def _convert_to_valid_identifier(name):
assert name, 'Identifier cannot be empty'
if name[0].isdigit() or iskeyword(name):
name = '_' + name
return _re_invalid_identifier.sub('_', name)
def _get_compiled_expression(statement):
"""Returns the statement in a form where any placeholders have been filled in."""
if isinstance(statement, TextClause):
return statement.text
dialect = statement._from_objects[0].bind.dialect
compiler = statement._compiler(dialect)
# Adapted from http://stackoverflow.com/a/5698357/242021
class LiteralCompiler(compiler.__class__):
def visit_bindparam(self, bindparam, within_columns_clause=False, literal_binds=False, **kwargs):
return super(LiteralCompiler, self).render_literal_bindparam(
bindparam, within_columns_clause=within_columns_clause,
literal_binds=literal_binds, **kwargs
)
compiler = LiteralCompiler(dialect, statement)
return compiler.process(statement)
def _get_constraint_sort_key(constraint):
if isinstance(constraint, CheckConstraint):
return 'C{0}'.format(constraint.sqltext)
return constraint.__class__.__name__[0] + repr(_get_column_names(constraint))
def _get_common_fk_constraints(table1, table2):
"""Returns a set of foreign key constraints the two tables have against each other."""
c1 = set(c for c in table1.constraints if isinstance(c, ForeignKeyConstraint) and
c.elements[0].column.table == table2)
c2 = set(c for c in table2.constraints if isinstance(c, ForeignKeyConstraint) and
c.elements[0].column.table == table1)
return c1.union(c2)
def _getargspec_init(method):
try:
return inspect.getfullargspec(method)
except TypeError:
if method is object.__init__:
return inspect.getfullargspec(lambda self: None)
else:
return inspect.getfullargspec(lambda self, *args, **kwargs: None)
def _render_column_type(coltype):
args = []
if isinstance(coltype, Enum):
args.extend(repr(arg) for arg in coltype.enums)
if coltype.name is not None:
args.append('name={0!r}'.format(coltype.name))
else:
# All other types
argspec = _getargspec_init(coltype.__class__.__init__)
defaults = dict(zip(argspec.args[-len(argspec.defaults or ()):], argspec.defaults or ()))
missing = object()
use_kwargs = False
for attr in argspec.args[1:]:
# Remove annoyances like _warn_on_bytestring
if attr.startswith('_'):
continue
value = getattr(coltype, attr, missing)
default = defaults.get(attr, missing)
if value is missing or value == default:
use_kwargs = True
elif use_kwargs:
args.append('{0}={1}'.format(attr, repr(value)))
else:
args.append(repr(value))
text = _flask_prepend + coltype.__class__.__name__
# In case of ENUM from sqlalchemy.dialects, the flask used db.Enum
if text == "db.ENUM":
text = "db.Enum"
if args:
text += '({0})'.format(', '.join(args))
return text
def _render_column(column, show_name):
kwarg = []
is_sole_pk = column.primary_key and len(column.table.primary_key) == 1
dedicated_fks = [c for c in column.foreign_keys if len(c.constraint.columns) == 1]
is_unique = any(isinstance(c, UniqueConstraint) and set(c.columns) == set([column])
for c in column.table.constraints)
is_unique = is_unique or any(i.unique and set(i.columns) == set([column]) for i in column.table.indexes)
has_index = any(set(i.columns) == set([column]) for i in column.table.indexes)
# Render the column type if there are no foreign keys on it or any of them points back to itself
render_coltype = not dedicated_fks or any(fk.column is column for fk in dedicated_fks)
if column.key != column.name:
kwarg.append('key')
if column.primary_key:
kwarg.append('primary_key')
if not column.nullable and not is_sole_pk:
kwarg.append('nullable')
if is_unique:
column.unique = True
kwarg.append('unique')
elif has_index:
column.index = True
kwarg.append('index')
if column.server_default:
server_default = 'server_default=' + _flask_prepend + 'FetchedValue()'
comment = getattr(column, 'comment', None)
if _sqla_orm:
column_string = 'mapped_column'
else:
column_string = 'Column'
return _flask_prepend + '{0}({1})'.format(column_string, ', '.join(
([repr(column.name)] if show_name else []) +
([_render_column_type(column.type)] if render_coltype else []) +
[_render_constraint(x) for x in dedicated_fks] +
[repr(x) for x in column.constraints] +
['{0}={1}'.format(k, repr(getattr(column, k))) for k in kwarg] +
([server_default] if column.server_default else []) +
(['info={!r}'.format(comment)] if comment else [])
))
def _render_constraint(constraint):
def render_fk_options(*opts):
opts = [repr(opt) for opt in opts]
for attr in 'ondelete', 'onupdate', 'deferrable', 'initially', 'match':
value = getattr(constraint, attr, None)
if value:
opts.append('{0}={1!r}'.format(attr, value))
return ', '.join(opts)
if isinstance(constraint, ForeignKey):
remote_column = '{0}.{1}'.format(constraint.column.table.fullname, constraint.column.name)
return _flask_prepend + 'ForeignKey({0})'.format(render_fk_options(remote_column))
elif isinstance(constraint, ForeignKeyConstraint):
local_columns = _get_column_names(constraint)
remote_columns = ['{0}.{1}'.format(fk.column.table.fullname, fk.column.name)
for fk in constraint.elements]
return _flask_prepend + 'ForeignKeyConstraint({0})'.format(render_fk_options(local_columns, remote_columns))
elif isinstance(constraint, CheckConstraint):
return _flask_prepend + 'CheckConstraint({0!r})'.format(_get_compiled_expression(constraint.sqltext))
elif isinstance(constraint, UniqueConstraint):
columns = [repr(col.name) for col in constraint.columns]
return _flask_prepend + 'UniqueConstraint({0})'.format(', '.join(columns))
def _underscore(name):
"""Converts CamelCase to camel_case. See http://stackoverflow.com/questions/1175208"""
s1 = _re_first_cap.sub(r'\1_\2', name)
return _re_all_cap.sub(r'\1_\2', s1).lower()
def _is_model_descendant(model_a, model_b):
"""Check to see if model class A inherits from another model class B"""
if model_a.name == model_b.name:
return True
if not model_b.children:
return False
return any(_is_model_descendant(model_a, b) for b in model_b.children)
def _render_index(index):
columns = [repr(col.name) for col in index.columns]
return _flask_prepend + 'Index({0!r}, {1})'.format(index.name, ', '.join(columns))
class ImportCollector(OrderedDict):
def add_import(self, obj):
type_ = type(obj) if not isinstance(obj, type) else obj
pkgname = 'sqlalchemy' if hasattr(sqlalchemy, type_.__name__) else type_.__module__ # @UndefinedVariable
# pkgname = 'sqlalchemy' if type_.__name__ in sqlalchemy.__all__ else type_.__module__ # @UndefinedVariable
self.add_literal_import(pkgname, type_.__name__)
def add_literal_import(self, pkgname, name):
names = self.setdefault(pkgname, set())
names.add(name)
def render(self):
return '\n'.join('from {0} import {1}'.format(package, ', '.join(sorted(names)))
for package, names in self.items())
class Model(object):
def __init__(self, table):
super(Model, self).__init__()
self.table = table
self.schema = table.schema
# Adapt column types to the most reasonable generic types (ie. VARCHAR -> String)
for column in table.columns:
cls = column.type.__class__
for supercls in cls.__mro__:
if hasattr(supercls, '__visit_name__'):
cls = supercls
if supercls.__name__ != supercls.__name__.upper() and not supercls.__name__.startswith('_'):
break
column.type = column.type.adapt(cls)
def add_imports(self, collector):
if self.table.columns:
collector.add_import(Column)
for column in self.table.columns:
collector.add_import(column.type)
if column.server_default:
collector.add_literal_import('sqlalchemy.schema', 'FetchedValue')
for constraint in sorted(self.table.constraints, key=_get_constraint_sort_key):
if isinstance(constraint, ForeignKeyConstraint):
if len(constraint.columns) > 1:
collector.add_literal_import('sqlalchemy', 'ForeignKeyConstraint')
else:
collector.add_literal_import('sqlalchemy', 'ForeignKey')
elif isinstance(constraint, UniqueConstraint):
if len(constraint.columns) > 1:
collector.add_literal_import('sqlalchemy', 'UniqueConstraint')
elif not isinstance(constraint, PrimaryKeyConstraint):
collector.add_import(constraint)
for index in self.table.indexes:
if len(index.columns) > 1:
collector.add_import(index)
class ModelTable(Model):
def add_imports(self, collector):
super(ModelTable, self).add_imports(collector)
collector.add_import(Table)
def render(self):
met = ' metadata,' if _flask_prepend == '' else ''
text = 't_{0} = {1}Table(\n {0!r},{2}\n'.format(self.table.name, _flask_prepend, met)
for column in self.table.columns:
text += ' {0},\n'.format(_render_column(column, True))
for constraint in sorted(self.table.constraints, key=_get_constraint_sort_key):
if isinstance(constraint, PrimaryKeyConstraint):
continue
if isinstance(constraint, (ForeignKeyConstraint, UniqueConstraint)) and len(constraint.columns) == 1:
continue
text += ' {0},\n'.format(_render_constraint(constraint))
for index in self.table.indexes:
if len(index.columns) > 1:
text += ' {0},\n'.format(_render_index(index))
if self.schema:
text += " schema='{0}',\n".format(self.schema)
return text.rstrip('\n,') + '\n)'
class ModelClass(Model):
parent_name = 'Base'
def __init__(self, table, association_tables, inflect_engine, detect_joined, collector):
super(ModelClass, self).__init__(table)
self.name = self._tablename_to_classname(table.name, inflect_engine)
self.children = []
self.attributes = OrderedDict()
# Assign attribute names for columns
for column in table.columns:
self._add_attribute(column.name, column)
if _dataclass:
if column.type.python_type.__module__ != 'builtins':
collector.add_literal_import(column.type.python_type.__module__, column.type.python_type.__name__)
# Add many-to-one relationships
pk_column_names = set(col.name for col in table.primary_key.columns)
for constraint in sorted(table.constraints, key=_get_constraint_sort_key):
if isinstance(constraint, ForeignKeyConstraint):
target_cls = self._tablename_to_classname(constraint.elements[0].column.table.name, inflect_engine)
if (detect_joined and self.parent_name == 'Base' and
set(_get_column_names(constraint)) == pk_column_names):
self.parent_name = target_cls
else:
relationship_ = ManyToOneRelationship(self.name, target_cls, constraint, inflect_engine)
self._add_attribute(relationship_.preferred_name, relationship_)
# Add many-to-many relationships
for association_table in association_tables:
fk_constraints = [c for c in association_table.constraints if isinstance(c, ForeignKeyConstraint)]
fk_constraints.sort(key=_get_constraint_sort_key)
target_cls = self._tablename_to_classname(fk_constraints[1].elements[0].column.table.name, inflect_engine)
relationship_ = ManyToManyRelationship(self.name, target_cls, association_table, inflect_engine)
self._add_attribute(relationship_.preferred_name, relationship_)
@staticmethod
def _tablename_to_classname(tablename, inflect_engine):
camel_case_name = ''.join(part[:1].upper() + part[1:] for part in re.split(r'_|-', tablename))
return inflect_engine.singular_noun(camel_case_name) or camel_case_name
def _add_attribute(self, attrname, value):
attrname = tempname = _convert_to_valid_identifier(attrname)
counter = 1
while tempname in self.attributes:
tempname = attrname + str(counter)
counter += 1
self.attributes[tempname] = value
return tempname
def add_imports(self, collector):
super(ModelClass, self).add_imports(collector)
if any(isinstance(value, Relationship) for value in self.attributes.values()):
collector.add_literal_import('sqlalchemy.orm', 'relationship')
for child in self.children:
child.add_imports(collector)
def render(self):
global _dataclass
text = 'class {0}({1}):\n'.format(self.name, self.parent_name)
if _dataclass:
text = '@dataclass\n' + text
text += ' __tablename__ = {0!r}\n'.format(self.table.name)
# Render constraints and indexes as __table_args__
table_args = []
for constraint in sorted(self.table.constraints, key=_get_constraint_sort_key):
if isinstance(constraint, PrimaryKeyConstraint):
continue
if isinstance(constraint, (ForeignKeyConstraint, UniqueConstraint)) and len(constraint.columns) == 1:
continue
table_args.append(_render_constraint(constraint))
for index in self.table.indexes:
if len(index.columns) > 1:
table_args.append(_render_index(index))
table_kwargs = {}
if self.schema:
table_kwargs['schema'] = self.schema
kwargs_items = ', '.join('{0!r}: {1!r}'.format(key, table_kwargs[key]) for key in table_kwargs)
kwargs_items = '{{{0}}}'.format(kwargs_items) if kwargs_items else None
if table_kwargs and not table_args:
text += ' __table_args__ = {0}\n'.format(kwargs_items)
elif table_args:
if kwargs_items:
table_args.append(kwargs_items)
if len(table_args) == 1:
table_args[0] += ','
text += ' __table_args__ = (\n {0}\n )\n'.format(',\n '.join(table_args))
# Render columns
text += '\n'
for attr, column in self.attributes.items():
if isinstance(column, Column):
show_name = attr != column.name
if _dataclass:
if _sqla_orm:
text += ' ' + attr + ' : ' + 'Mapped[{0}]\n'.format(column.type.python_type.__name__)
else:
text += ' ' + attr + ' : ' + column.type.python_type.__name__ + '\n'
text += ' {0} = {1}\n'.format(attr, _render_column(column, show_name))
# Render relationships
if any(isinstance(value, Relationship) for value in self.attributes.values()):
text += '\n'
for attr, relationship in self.attributes.items():
if isinstance(relationship, Relationship):
text += ' {0} = {1}\n'.format(attr, relationship.render())
# Render subclasses
for child_class in self.children:
text += '\n\n' + child_class.render()
return text
class Relationship(object):
def __init__(self, source_cls, target_cls):
super(Relationship, self).__init__()
self.source_cls = source_cls
self.target_cls = target_cls
self.kwargs = OrderedDict()
self.backref_name = _underscore(self.source_cls)
def render(self):
text = _flask_prepend + 'relationship('
args = [repr(self.target_cls)]
if 'secondaryjoin' in self.kwargs:
text += '\n '
delimiter, end = ',\n ', '\n )'
else:
delimiter, end = ', ', ')'
args.extend([key + '=' + value for key, value in self.kwargs.items()])
return _re_invalid_relationship.sub('_', text + delimiter.join(args) + end)
def make_backref(self, relationships, classes):
backref = self.backref_name
original_backref = backref
# Check if backref already exists for relationship source_cls to target_cls and add suffix
suffix = 0
while (self.target_cls, backref) in [(x.target_cls, x.backref_name) for x in relationships]:
backref = original_backref + str('_{0}'.format(suffix))
suffix += 1
self.kwargs['backref'] = repr(backref)
# Check if any of the target_cls inherit from other target_cls
# If so, modify backref name of descendant
# "backref({0}, lazy='dynamic')".format(repr(backref))
for rel in [x for x in relationships if 'backref' in x.kwargs]:
if self.target_cls in classes and rel.target_cls in classes:
if _is_model_descendant(classes[self.target_cls], classes[rel.target_cls]):
self.backref_name = self.target_cls.lower() + '_' + backref
self.kwargs['backref'] = repr(self.backref_name)
if _is_model_descendant(classes[rel.target_cls], classes[self.target_cls]):
backref = rel.backref_name
rel.backref_name = rel.target_cls.lower() + '_' + backref
rel.kwargs['backref'] = repr(rel.backref_name)
class ManyToOneRelationship(Relationship):
def __init__(self, source_cls, target_cls, constraint, inflect_engine):
super(ManyToOneRelationship, self).__init__(source_cls, target_cls)
column_names = _get_column_names(constraint)
colname = column_names[0]
tablename = constraint.elements[0].column.table.name
if not colname.endswith('_id'):
self.preferred_name = inflect_engine.singular_noun(tablename) or tablename
else:
self.preferred_name = colname[:-3]
self.backref_name = inflect_engine.plural_noun(self.backref_name)
# Add uselist=False to One-to-One relationships
if any(isinstance(c, (PrimaryKeyConstraint, UniqueConstraint)) and
set(col.name for col in c.columns) == set(column_names)
for c in constraint.table.constraints):
self.kwargs['uselist'] = 'False'
# Handle self referential relationships
if source_cls == target_cls:
self.preferred_name = 'parent' if not colname.endswith('_id') else colname[:-3]
pk_col_names = [col.name for col in constraint.table.primary_key]
self.kwargs['remote_side'] = '[{0}]'.format(', '.join(pk_col_names))
# If the two tables share more than one foreign key constraint,
# SQLAlchemy needs an explicit primaryjoin to figure out which column(s) to join with
# common_fk_constraints = _get_common_fk_constraints(constraint.table, constraint.elements[0].column.table)
# if len(common_fk_constraints) > 1:
# self.kwargs['primaryjoin'] = "'{0}.{1} == {2}.{3}'".format(source_cls, constraint.columns[0], target_cls, constraint.elements[0].column.name)
if len(constraint.elements) > 1: # or
self.kwargs['primaryjoin'] = "'and_({0})'".format(', '.join(['{0}.{1} == {2}.{3}'.format(source_cls, k.parent.name, target_cls, k.column.name)
for k in constraint.elements]))
else:
self.kwargs['primaryjoin'] = "'{0}.{1} == {2}.{3}'".format(source_cls, column_names[0], target_cls,
constraint.elements[0].column.name)
class ManyToManyRelationship(Relationship):
def __init__(self, source_cls, target_cls, assocation_table, inflect_engine):
super(ManyToManyRelationship, self).__init__(source_cls, target_cls)
prefix = assocation_table.schema + '.' if assocation_table.schema is not None else ''
self.kwargs['secondary'] = repr(prefix + assocation_table.name)
constraints = [c for c in assocation_table.constraints if isinstance(c, ForeignKeyConstraint)]
constraints.sort(key=_get_constraint_sort_key)
colname = _get_column_names(constraints[1])[0]
tablename = constraints[1].elements[0].column.table.name
self.preferred_name = tablename if not colname.endswith('_id') else colname[:-3] + 's'
self.backref_name = inflect_engine.plural_noun(self.backref_name)
# Handle self referential relationships
if source_cls == target_cls:
self.preferred_name = 'parents' if not colname.endswith('_id') else colname[:-3] + 's'
pri_pairs = zip(_get_column_names(constraints[0]), constraints[0].elements)
sec_pairs = zip(_get_column_names(constraints[1]), constraints[1].elements)
pri_joins = ['{0}.{1} == {2}.c.{3}'.format(source_cls, elem.column.name, assocation_table.name, col)
for col, elem in pri_pairs]
sec_joins = ['{0}.{1} == {2}.c.{3}'.format(target_cls, elem.column.name, assocation_table.name, col)
for col, elem in sec_pairs]
self.kwargs['primaryjoin'] = (
repr('and_({0})'.format(', '.join(pri_joins))) if len(pri_joins) > 1 else repr(pri_joins[0]))
self.kwargs['secondaryjoin'] = (
repr('and_({0})'.format(', '.join(sec_joins))) if len(sec_joins) > 1 else repr(sec_joins[0]))
class CodeGenerator(object):
header = '# coding: utf-8'
footer = ''
def __init__(self, metadata, noindexes=False, noconstraints=False,
nojoined=False, noinflect=False, nobackrefs=False,
flask=False, ignore_cols=None, noclasses=False, nocomments=False, notables=False, dataclass=False, sqla_orm=False):
super(CodeGenerator, self).__init__()
if noinflect:
inflect_engine = _DummyInflectEngine()
else:
import inflect
inflect_engine = inflect.engine()
# exclude these column names from consideration when generating association tables
_ignore_columns = ignore_cols or []
self.flask = flask
if not self.flask:
global _flask_prepend
_flask_prepend = ''
self.nocomments = nocomments
self.dataclass = dataclass
if self.dataclass:
global _dataclass
_dataclass = True
self.sqla_orm = sqla_orm
global _sqla_orm
_sqla_orm = sqla_orm
# Pick association tables from the metadata into their own set, don't process them normally
links = defaultdict(lambda: [])
association_tables = set()
for table in metadata.tables.values():
# Link tables have exactly two foreign key constraints and all columns are involved in them
# except for special columns like id, inserted, and updated
fk_constraints = [constr for constr in table.constraints if isinstance(constr, ForeignKeyConstraint)]
if len(fk_constraints) == 2 and all(col.foreign_keys for col in table.columns if col.name not in _ignore_columns):
association_tables.add(table.name)
tablename = sorted(fk_constraints, key=_get_constraint_sort_key)[0].elements[0].column.table.name
links[tablename].append(table)
# Iterate through the tables and create model classes when possible
self.models = []
self.collector = ImportCollector()
classes = {}
for table in sorted(metadata.tables.values(), key=lambda t: (t.schema or '', t.name)):
# Support for Alembic and sqlalchemy-migrate -- never expose the schema version tables
if table.name in ('alembic_version', 'migrate_version'):
continue
if noindexes:
table.indexes.clear()
if noconstraints:
table.constraints = set([table.primary_key])
table.foreign_keys.clear()
for col in table.columns:
col.foreign_keys.clear()
else:
# Detect check constraints for boolean and enum columns
for constraint in table.constraints.copy():
if isinstance(constraint, CheckConstraint):
sqltext = _get_compiled_expression(constraint.sqltext)
# Turn any integer-like column with a CheckConstraint like "column IN (0, 1)" into a Boolean
match = _re_boolean_check_constraint.match(sqltext)
if match:
colname = _re_column_name.match(match.group(1)).group(3)
table.constraints.remove(constraint)
table.c[colname].type = Boolean()
continue
# Turn any string-type column with a CheckConstraint like "column IN (...)" into an Enum
match = _re_enum_check_constraint.match(sqltext)
if match:
colname = _re_column_name.match(match.group(1)).group(3)
items = match.group(2)
if isinstance(table.c[colname].type, String):
table.constraints.remove(constraint)
if not isinstance(table.c[colname].type, Enum):
options = _re_enum_item.findall(items)
table.c[colname].type = Enum(*options, native_enum=False)
continue
# Only generate classes when notables is set to True
if notables:
model = ModelClass(table, links[table.name], inflect_engine, not nojoined, self.collector)
classes[model.name] = model
elif not table.primary_key or table.name in association_tables or noclasses:
# Only form model classes for tables that have a primary key and are not association tables
model = ModelTable(table)
elif not noclasses:
model = ModelClass(table, links[table.name], inflect_engine, not nojoined, self.collector)
classes[model.name] = model
self.models.append(model)
# collect imports for models only if flask is not specified
if not self.flask:
model.add_imports(self.collector)
# Nest inherited classes in their superclasses to ensure proper ordering
for model in classes.values():
if model.parent_name != 'Base':
classes[model.parent_name].children.append(model)
self.models.remove(model)
# If backrefs are allowed. Resolve any relationships conflicts where one
# target class might inherit from another
if not nobackrefs:
for model in classes.values():
visited = []
for relationship in model.attributes.values():
if isinstance(relationship, Relationship):
relationship.make_backref(visited, classes)
visited.append(relationship)
if self.flask:
# Add Flask-SQLAlchemy support
self.collector.add_literal_import('flask_sqlalchemy', 'SQLAlchemy')
parent_name = 'db.Model'
for model in classes.values():
if model.parent_name == 'Base':
model.parent_name = parent_name
else:
if self.sqla_orm:
self.collector.add_literal_import('sqlalchemy.orm', 'DeclarativeBase')
self.collector.add_literal_import('sqlalchemy.orm', 'Mapped')
self.collector.add_literal_import('sqlalchemy.orm', 'mapped_column')
else:
self.collector.add_literal_import('sqlalchemy.ext.declarative', 'declarative_base')
self.collector.add_literal_import('sqlalchemy', 'MetaData')
if self.dataclass:
self.collector.add_literal_import('dataclasses', 'dataclass')
def render(self, outfile=sys.stdout):
print(self.header, file=outfile)
# Render the collected imports
print(self.collector.render() + '\n\n', file=outfile)
if self.flask:
print('db = SQLAlchemy()', file=outfile)
else:
if any(isinstance(model, ModelClass) for model in self.models):
if self.sqla_orm:
print('class Base(DeclarativeBase):\n pass', file=outfile)
else:
print('Base = declarative_base()\nmetadata = Base.metadata', file=outfile)
else:
print('metadata = MetaData()', file=outfile)
# Render the model tables and classes
for model in self.models:
print('\n\n', file=outfile)
print(model.render().rstrip('\n'), file=outfile)
if self.footer:
print(self.footer, file=outfile)