sqlalchemy_A_mapper.py 20.7 KB
Newer Older
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
# (C) Semantix Information Technologies.
#
# Semantix Information Technologies is licensing the code of the
# Data Modelling Tools (DMT) in the following dual-license mode:
#
# Commercial Developer License:
#       The DMT Commercial Developer License is the suggested version
# to use for the development of proprietary and/or commercial software.
# This version is for developers/companies who do not want to comply
# with the terms of the GNU Lesser General Public License version 2.1.
#
# GNU LGPL v. 2.1:
#       This version of DMT is the one to use for the development of
# applications, when you are willing to comply with the terms of the
# GNU Lesser General Public License version 2.1.
#
# Note that in both cases, there are no charges (royalties) for the
# generated code.
#
'''This contains the implementation of model level mapping
of ASN.1 constructs to SQL Alchemy ones. It is used as a backend of
Semantix's code generator A.'''

import os
import re

from commonPy.asnAST import (
    AsnMetaMember, AsnChoice, AsnSet, AsnSequence, AsnSequenceOf,
    AsnSetOf, isSequenceVariable)
from commonPy.asnParser import g_names, g_leafTypeDict, CleanNameForAST
from commonPy.utility import panic, warn
32
from commonPy.cleanupNodes import SetOfBadTypenames
33
34

g_sqlalchemyOutput = None
35
g_innerTypes = {}  # type: Dict[str, int]
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
g_uniqueStringOfASN1files = ""
g_outputDir = "."
g_asnFiles = None


# ====== Dummy stubs =====
# The output can't contain forward declarations,
# so this follows the FixupAst/OnShutdown pattern.

def OnBasic(unused_nodeTypename, unused_node, unused_leafTypeDict):
    pass


def OnSequence(unused_nodeTypename, unused_node, unused_leafTypeDict):
    pass


def OnSet(unused_nodeTypename, unused_node, unused_leafTypeDict):
    pass  # pragma: no cover


def OnEnumerated(unused_nodeTypename, unused_node, unused_leafTypeDict):
    pass


def OnSequenceOf(unused_nodeTypename, unused_node, unused_leafTypeDict):
    pass


def OnSetOf(unused_nodeTypename, unused_node, unused_leafTypeDict):
    pass  # pragma: no cover


def OnChoice(unused_nodeTypename, unused_unused_node,
             unused_unused_leafTypeDict):
    pass
# ====== End of dummy stubs =====


def Version():
76
    print("$Id$")  # pragma: no cover
77
78


79
g_dependencyGraph = {}  # type: Dict[str, Dict[str, int]]
80
81
82
83
84
85
86
87


def FixupAstForSQLAlchemy():
    '''
    Find all the SEQUENCE, CHOICE and SEQUENCE OFs
    and make sure the contained types are not "naked" (i.e. unnamed)
    '''
    internalNo = 1
88
89
90

    def neededToAddPseudoType():
        nonlocal internalNo
91
        addedNewPseudoType = False
92
        listOfTypenames = sorted(list(g_names.keys()) + list(g_innerTypes.keys()))
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
        for nodeTypename in listOfTypenames:
            node = g_names[nodeTypename]
            if isinstance(node, (AsnChoice, AsnSequence, AsnSet)):
                for child in node._members:
                    if not isinstance(child[1], AsnMetaMember):
                        internalName = newname = \
                            "TaStE_" + \
                            CleanNameForAST(child[0].capitalize() + "_type")
                        while internalName in g_names:
                            internalName = (newname + "_%d") % internalNo  # pragma: no cover
                            internalNo += 1                                # pragma: no cover
                        g_names[internalName] = child[1]
                        child[1]._isArtificial = True
                        g_leafTypeDict[internalName] = child[1]._leafType
                        child[1] = AsnMetaMember(
                            asnFilename=child[1]._asnFilename,
                            containedType=internalName)
                        addedNewPseudoType = True
                        g_innerTypes[internalName] = 1
                        g_dependencyGraph.setdefault(nodeTypename, {})
                        g_dependencyGraph[nodeTypename][internalName] = 1
                    else:
                        g_dependencyGraph.setdefault(nodeTypename, {})
                        g_dependencyGraph[nodeTypename][
                            child[1]._containedType] = 1
            elif isinstance(node, (AsnSequenceOf, AsnSetOf)):
                if not isinstance(node._containedType, str):
                    internalName = newname = "TaStE_" + "internalSeqOf_type"
                    while internalName in g_names:
                        internalName = (newname + "_%d") % internalNo  # pragma: no cover
                        internalNo += 1                                # pragma: no cover
                    g_names[internalName] = node._containedType
                    node._containedType._isArtificial = True
                    g_leafTypeDict[internalName] = \
                        node._containedType._leafType
                    node._containedType = internalName
                    addedNewPseudoType = True
                    g_innerTypes[internalName] = 1
                    g_dependencyGraph.setdefault(nodeTypename, {})
                    g_dependencyGraph[nodeTypename][internalName] = 1
                else:
                    g_dependencyGraph.setdefault(nodeTypename, {})
                    g_dependencyGraph[nodeTypename][node._containedType] = 1
136
137
138
139
140
        return addedNewPseudoType

    while True:
        if not neededToAddPseudoType():
            break
141
142
143
144
145


g_bStartupRun = False


146
def OnStartup(unused_modelingLanguage, asnFiles, outputDir, unused_badTypes):
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
    '''
    SQL cannot represent unnamed inner types
    e.g. this...
        SEQUENCE (SIZE(20)) OF INTEGER (0 .. 12)
    ...would need the declaration of an "inner" type
    that would carry the constraint (0..12).

    We do this AST "fixup" via a call to FixupAstForSQLAlchemy
    '''
    global g_uniqueStringOfASN1files
    if isinstance(asnFiles, str):
        g_uniqueStringOfASN1files = \
            CleanName(
                asnFiles.lower().replace(".asn1", "").replace(".asn", ""))
    else:
        g_uniqueStringOfASN1files = \
            "_".join(
                CleanName(
                    x.lower().replace(".asn1", "").replace(".asn", ""))
                for x in asnFiles)  # pragma: no cover
    global g_bStartupRun  # pragma: no cover
    if g_bStartupRun:
        # Must run only once, no more.
        return  # pragma: no cover
    g_bStartupRun = True
    global g_outputDir
    g_outputDir = outputDir
    global g_asnFiles
    g_asnFiles = asnFiles
    FixupAstForSQLAlchemy()


def CleanName(fieldName):
    return re.sub(r'[^a-zA-Z0-9_]', '_', fieldName)


def CreateBasic(nodeTypename, node, leafTypeDict):
    cleanTypename = CleanName(nodeTypename)
    baseType = leafTypeDict[node._leafType]
    baseSqlType = {
        'INTEGER': 'Integer',
        'REAL': 'Float',
        'BOOLEAN': 'Boolean',
        'OCTET STRING': 'String'
    }[baseType]
    constraint = ""
    if baseType == 'OCTET STRING':
        constraint += "(" + str(node._range[-1]) + ")"
195
        # defValue = '""'
196
197
198
    elif baseType in ['INTEGER', 'REAL'] and node._range:
        constraint += ", CheckConstraint('data>=%s and data<=%s')" % (
            node._range[0], node._range[-1])
199
200
201
        # defValue = node._range[-1]
    # else:
        # defValue = 'False'
202
203
204
205
206
207
208
209
    constraint += ", nullable=False"
    g_sqlalchemyOutput.write(
        '''
class {cleanTypename}_SQL(Base):
    __tablename__ = '{cleanTypename}'
    __table_args__ = (UniqueConstraint('iid'),)
    iid = Column(Integer, primary_key=True)
    data = Column({baseSqlType}{constraint})
210
211
212
'''.format(cleanTypename=cleanTypename,
           baseSqlType=baseSqlType,
           constraint=constraint))
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

    getter = "Get"
    setter = "Set"
    if baseType not in ['INTEGER', 'REAL', 'BOOLEAN']:
        getter = "GetPyString"
        setter = "SetFromPyString"

    g_sqlalchemyOutput.write('''
    @staticmethod
    def loadFromDB(session, iid):
        return session.query(
            {cleanTypename}_SQL).filter({cleanTypename}_SQL.iid == iid).first()

    @property
    def asn1(self):
        if hasattr(self, "_cache"):
            return self._cache
        pyObj = {cleanTypename}()
        self.assignToASN1object(pyObj)
        self._cache = pyObj
        return pyObj

    def assignToASN1object(self, pyObj):
        pyObj.{setter}(self.data)

    def __init__(self, pyObj):
        self.data = pyObj.{getter}()

    def save(self, session):
        session.add(self)
        session.commit()
        return self.iid

246
247
'''.format(setter=setter, getter=getter,
           cleanTypename=cleanTypename))
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


def CreateSequence(nodeTypename, node, unused_leafTypeDict, isChoice=False):
    cleanTypename = CleanName(nodeTypename)
    choiceField = ''
    if isChoice:
        choiceField = \
            '    kind = Column(Integer, nullable=False)\n'

    memberAssignments = []
    if isChoice:
        memberAssignments.append('pyObj.kind.Set(self.kind)')
        for c in node._members:
            cleanFieldname = CleanName(c[0])
            memberAssignments.append(
                'if self.kind == DV.' + c[-1] + ':')
            memberAssignments.append('    pyObj.Reset(state)')
            assert isinstance(c[1], AsnMetaMember)
            containedTypename = CleanName(c[1]._containedType)
            memberAssignments.append(
                '    self.' + cleanFieldname + '.assignToASN1object(' +
                'pyObj.' + cleanFieldname + ')')
    else:
        for c in node._members:
            memberAssignments.append('pyObj.Reset(state)')
            cleanFieldname = CleanName(c[0])
            assert isinstance(c[1], AsnMetaMember)
            containedTypename = CleanName(c[1]._containedType)
            memberAssignments.append(
                'self.' + cleanFieldname + '.assignToASN1object(' +
                'pyObj.' + cleanFieldname + ')')

    g_sqlalchemyOutput.write(
        '''
class {cleanTypename}_SQL(Base):
    __tablename__ = '{cleanTypename}'
    __table_args__ = (UniqueConstraint('iid'),)
    iid = Column(Integer, primary_key=True)
{choiceField}
    @staticmethod
    def loadFromDB(session, iid):
        return session.query(
            {cleanTypename}_SQL).filter({cleanTypename}_SQL.iid == iid).first()

    @property
    def asn1(self):
        if hasattr(self, "_cache"):
            return self._cache
        pyObj = {cleanTypename}()
        self.assignToASN1object(pyObj)
        self._cache = pyObj
        return pyObj

    def assignToASN1object(self, pyObj):
        state = pyObj.GetState()
        {assignMembers}
        pyObj.Reset(state)

    def save(self, session):
        session.add(self)
        session.commit()
        return self.iid
'''.format(cleanTypename=cleanTypename, choiceField=choiceField,
           assignMembers="\n        ".join(memberAssignments)))

    nullable = "True" if isChoice else "False"
    for c in node._members:
        cleanFieldname = CleanName(c[0])
        childNode = c[1]
        assert isinstance(childNode, AsnMetaMember)
        containedTypename = CleanName(c[1]._containedType)
        g_sqlalchemyOutput.write(
            '\n    fk_%s_iid = Column(Integer, ' % cleanFieldname)
        g_sqlalchemyOutput.write(
            "ForeignKey('{containedTypename}.iid'), nullable={nl})".format(
323
324
                nl=nullable,
                containedTypename=containedTypename))
325
326
327
328
        g_sqlalchemyOutput.write(
            '''
    {relation} = relationship(
        "{containedTypename}_SQL",
329
330
        foreign_keys=[fk_{relation}_iid])'''.format(relation=cleanFieldname,
                                                    containedTypename=containedTypename))
331
332
333
334
335
336
337
338
339
340
341
342
343
    g_sqlalchemyOutput.write('\n\n    def __init__(self, pyObj):\n')
    g_sqlalchemyOutput.write('        state = pyObj.GetState()\n')
    if isChoice:
        g_sqlalchemyOutput.write('        self.kind = pyObj.kind.Get()\n')
        g_sqlalchemyOutput.write('        pyObj.Reset(state)\n')
    for c in node._members:
        cleanFieldname = CleanName(c[0])
        childNode = c[1]
        assert isinstance(childNode, AsnMetaMember)
        containedTypename = CleanName(c[1]._containedType)
        if isChoice:
            g_sqlalchemyOutput.write(
                '        '
344
                'if self.kind == DV.' + c[-1] + ':\n')
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
            g_sqlalchemyOutput.write(
                '            '
                'self.{cleanFieldname} = '
                '{containedTypename}_SQL(pyObj.{cleanFieldname})\n'.format(
                    cleanFieldname=cleanFieldname,
                    containedTypename=containedTypename))
            g_sqlalchemyOutput.write(
                '            pyObj.Reset(state)\n')
        else:
            g_sqlalchemyOutput.write(
                '        '
                'self.{cleanFieldname} = '
                '{containedTypename}_SQL(pyObj.{cleanFieldname})\n'.format(
                    cleanFieldname=cleanFieldname,
                    containedTypename=containedTypename))
            g_sqlalchemyOutput.write(
                '        pyObj.Reset(state)\n')
    g_sqlalchemyOutput.write('\n')


def CreateEnumerated(nodeTypename, node, unused_leafTypeDict):
366
367
    checkConstraint = ' OR '.join('data=' + x[1] for x in node._members)
    constants = '\n    '.join(CleanName(x[0]) + ' = ' + x[1]
368
                              for x in node._members)
369
    # defValue = CleanName(nodeTypename) + "_SQL." + CleanName(node._members[0][0])
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
    g_sqlalchemyOutput.write('''
class {cleanTypename}_SQL(Base):
    __tablename__ = '{cleanTypename}'
    __table_args__ = (UniqueConstraint('iid'),)
    {constants}
    iid = Column(Integer, primary_key=True)
    data = Column(Integer, CheckConstraint('{constraint}'), nullable=False)

    @staticmethod
    def loadFromDB(session, iid):
        return session.query(
            {cleanTypename}_SQL).filter({cleanTypename}_SQL.iid == iid).first()

    @property
    def asn1(self):
        if hasattr(self, "_cache"):
            return self._cache
        pyObj = {cleanTypename}()
        self.assignToASN1object(pyObj)
        self._cache = pyObj
        return pyObj

    def assignToASN1object(self, pyObj):
        pyObj.Set(self.data)

    def __init__(self, pyObj):
        self.data = pyObj.Get()

    def save(self, session):
        session.add(self)
        session.commit()
        return self.iid

403
404
405
'''.format(cleanTypename=CleanName(nodeTypename),
           constraint=checkConstraint,
           constants=constants))
406
407
408
409
410
411
412
413


def CreateSequenceOf(nodeTypename, node, unused_leafTypeDict):
    cleanTypename = CleanName(nodeTypename)
    reftype = node._containedType
    reftype = CleanName(reftype)
    constraint = ""
    if node._range != []:
414
415
        constraint = \
            ", CheckConstraint('idx>=0 AND idx<%s')" % (node._range[-1])
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

    # The detail table, containing the index of the cell
    # and the foreign key to the actual data
    g_sqlalchemyOutput.write('''
class {cleanTypename}_indexes_SQL(Base):
    __tablename__ = '{cleanTypename}_indexes'
    __table_args__ = (UniqueConstraint('idx', 'fk_{cleanTypename}_iid'),)
    iid = Column(Integer, primary_key=True)
    idx = Column(Integer{constraint}, nullable=False)
    fk_{cleanTypename}_iid = Column(
        Integer,
        ForeignKey('{cleanTypename}.iid'),
        nullable=False)
    fk_{reftype}_iid = Column(
        Integer,
        ForeignKey('{reftype}.iid'),
        nullable=False)
    array = relationship(
        "{cleanTypename}_SQL",
        foreign_keys=[fk_{cleanTypename}_iid],
        backref='arrIndexes_{cleanTypename}')
    data = relationship(
        "{reftype}_SQL",
        foreign_keys=[fk_{reftype}_iid])

    def save(self, session):
        session.add(self)
        session.commit()
        return self.iid
'''.format(reftype=reftype,
           cleanTypename=cleanTypename,
           constraint=constraint))

    # The master table
    if isSequenceVariable(node):
        setLength = \
            '        ' + \
            'pyObj.SetLength(len(self.arrIndexes_%s))' % cleanTypename
    else:
        setLength = ''
    g_sqlalchemyOutput.write('''
class {cleanTypename}_SQL(Base):
    __tablename__ = '{cleanTypename}'
    iid = Column(Integer, primary_key=True)

    @staticmethod
    def loadFromDB(session, iid):
        return session.query(
            {cleanTypename}_SQL).filter({cleanTypename}_SQL.iid == iid).first()

    @property
    def asn1(self):
        if hasattr(self, "_cache"):
            return self._cache
        pyObj = {cleanTypename}()
        self.assignToASN1object(pyObj)
        self._cache = pyObj
        return pyObj

    def assignToASN1object(self, pyObj):
        state = pyObj.GetState()
{setLength}
        for idx, idxObj in enumerate(self.arrIndexes_{cleanTypename}):
            pyObj.Reset(state)
            idxObj.data.assignToASN1object(pyObj[idxObj.idx])
        pyObj.Reset(state)

    def save(self, session):
        session.add(self)
        for c in self._children:
            session.add(c[0])
            session.add(c[1])
        session.commit()
        return self.iid

    def __init__(self, pyObj):
        self._children = []
        state = pyObj.GetState()
        for i in xrange(pyObj.GetLength()):
            pyObj.Reset(state)
            newIndex = {cleanTypename}_indexes_SQL()
            newIndex.idx = i
            newIndex.array = self
            newData = {reftype}_SQL(pyObj[i])
            newIndex.data = newData
            self._children.append((newIndex, newData))

        pyObj.Reset(state)

'''.format(cleanTypename=cleanTypename, setLength=setLength,
506
           reftype=reftype))
507
508
509
510
511
512
513
514
515
516
517
518

    if not isinstance(reftype, str):
        panic("FixupAstForSQLAlchemy failed to create a pseudoType for %s" %
              nodeTypename)  # pragma: no cover


def CreateChoice(nodeTypename, node, _):
    CreateSequence(nodeTypename, node, _, isChoice=True)

g_bShutdownRun = False


519
def OnShutdown(badTypes: SetOfBadTypenames):
520
521
522
523
524
525
526
527
528
529
    global g_bShutdownRun
    if g_bShutdownRun:
        return   # pragma: no cover
    g_bShutdownRun = True

    global g_sqlalchemyOutput
    g_sqlalchemyOutput = open(
        g_outputDir + os.sep + g_uniqueStringOfASN1files + "_model.py", 'w')
    d = g_asnFiles if isinstance(g_asnFiles, str) else '","'.join(g_asnFiles)
    typenameList = []
530
    for nodeTypename in sorted(list(g_innerTypes.keys()) + list(g_names.keys())):
531
        if nodeTypename in badTypes:
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
            continue
        if nodeTypename not in typenameList:
            typenameList.append(nodeTypename)

    g_sqlalchemyOutput.write('''
#  SQLAlchemy models for types used in "{d}"

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

from sqlalchemy import (Column, Integer, String, Boolean, Float,
                        ForeignKey, CheckConstraint, UniqueConstraint)
from sqlalchemy.orm import relationship

from {d_cleaned} import (
    {types}
)

import DV

'''.format(d=d, d_cleaned=CleanName(d),
           types=", ".join(
               CleanName(x)
               for x in typenameList
               if not g_names[x]._isArtificial)))
    typesDoneSoFar = {}

    workRemains = True
    while workRemains:
        workRemains = False
        for nodeTypename in typenameList:

            # only emit for types with no more dependencies
            if nodeTypename in g_dependencyGraph and \
                    g_dependencyGraph[nodeTypename]:
                continue

            # only emit each type once
            if nodeTypename in typesDoneSoFar:
                continue
            typesDoneSoFar[nodeTypename] = 1

            # if we process even one type, deps may be removed,
            # so scan again next time
            workRemains = True

            # make sure we know what leaf type this node is
            node = g_names[nodeTypename]
580
            assert nodeTypename in g_leafTypeDict
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
            leafType = g_leafTypeDict[nodeTypename]
            if leafType in ['BOOLEAN', 'INTEGER', 'REAL', 'OCTET STRING']:
                CreateBasic(nodeTypename, node, g_leafTypeDict)
            elif leafType in ['SEQUENCE', 'SET']:
                CreateSequence(nodeTypename, node, g_leafTypeDict)
            elif leafType == 'CHOICE':
                CreateChoice(nodeTypename, node, g_leafTypeDict)
            elif leafType in ['SEQUENCEOF', 'SETOF']:
                CreateSequenceOf(nodeTypename, node, g_leafTypeDict)
            elif leafType == 'ENUMERATED':
                CreateEnumerated(nodeTypename, node, g_leafTypeDict)
            else:  # pragma: no cover
                warn("Ignoring unsupported node type: %s (%s)" % (
                    leafType, nodeTypename))  # pragma: no cover

            # eliminate nodeTypename from dependency lists
            for t in typenameList:
                if t in g_dependencyGraph and \
                        nodeTypename in g_dependencyGraph[t]:
                    del g_dependencyGraph[t][nodeTypename]
601
602
    # g_sqlalchemyOutput.write('if __name__ == "__main__":\n')
    # g_sqlalchemyOutput.write('    Base.metadata.create_all(engine)\n')
603
604
605
    g_sqlalchemyOutput.close()

# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4