forked from SAP/python-pyodata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
2071 lines (1548 loc) · 70.6 KB
/
model.py
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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Simple representation of Metadata of OData V2
Author: Jakub Filak <[email protected]>
Date: 2017-08-21
"""
# pylint: disable=missing-docstring,too-many-instance-attributes,too-many-arguments,protected-access,no-member,line-too-long,logging-format-interpolation,too-few-public-methods,too-many-lines
import collections
import datetime
import enum
import io
import itertools
import logging
import re
from lxml import etree
from pyodata.exceptions import PyODataException, PyODataModelError
LOGGER_NAME = 'pyodata.model'
IdentifierInfo = collections.namedtuple('IdentifierInfo', 'namespace name')
TypeInfo = collections.namedtuple('TypeInfo', 'namespace name is_collection')
def modlog():
return logging.getLogger(LOGGER_NAME)
class Identifier:
def __init__(self, name):
super(Identifier, self).__init__()
self._name = name
def __repr__(self):
return "{0}({1})".format(self.__class__.__name__, self._name)
def __str__(self):
return "{0}({1})".format(self.__class__.__name__, self._name)
@property
def name(self):
return self._name
@staticmethod
def parse(value):
parts = value.split('.')
if len(parts) == 1:
return IdentifierInfo(None, value)
return IdentifierInfo(parts[0], parts[1])
class Types:
"""Repository of all available OData types
Since each type has instance of appropriate type, this
repository acts as central storage for all instances. The
rule is: don't create any type instances if not necessary,
always reuse existing instances if possible
"""
# dictionary of all registered types (primitive, complex and collection variants)
Types = None
@staticmethod
def _build_types():
"""Create and register instances of all primitive Edm types"""
if Types.Types is None:
Types.Types = {}
Types.register_type(Typ('Null', 'null'))
Types.register_type(Typ('Edm.Binary', 'binary\'\''))
Types.register_type(Typ('Edm.Boolean', 'false', EdmBooleanTypTraits()))
Types.register_type(Typ('Edm.Byte', '0'))
Types.register_type(Typ('Edm.DateTime', 'datetime\'2000-01-01T00:00\'', EdmDateTimeTypTraits()))
Types.register_type(Typ('Edm.Decimal', '0.0M'))
Types.register_type(Typ('Edm.Double', '0.0d'))
Types.register_type(Typ('Edm.Single', '0.0f'))
Types.register_type(
Typ('Edm.Guid', 'guid\'00000000-0000-0000-0000-000000000000\'', EdmPrefixedTypTraits('guid')))
Types.register_type(Typ('Edm.Int16', '0', EdmIntTypTraits()))
Types.register_type(Typ('Edm.Int32', '0', EdmIntTypTraits()))
Types.register_type(Typ('Edm.Int64', '0L', EdmIntTypTraits()))
Types.register_type(Typ('Edm.SByte', '0'))
Types.register_type(Typ('Edm.String', '\'\'', EdmStringTypTraits()))
Types.register_type(Typ('Edm.Time', 'time\'PT00H00M\''))
Types.register_type(Typ('Edm.DateTimeOffset', 'datetimeoffset\'0000-00-00T00:00:00\''))
@staticmethod
def register_type(typ):
"""Add new type to the type repository as well as its collection variant"""
# build types hierarchy on first use (lazy creation)
if Types.Types is None:
Types._build_types()
# register type only if it doesn't exist
# pylint: disable=unsupported-membership-test
if typ.name not in Types.Types:
# pylint: disable=unsupported-assignment-operation
Types.Types[typ.name] = typ
# automatically create and register collection variant if not exists
collection_name = 'Collection({})'.format(typ.name)
# pylint: disable=unsupported-membership-test
if collection_name not in Types.Types:
collection_typ = Collection(typ.name, typ)
# pylint: disable=unsupported-assignment-operation
Types.Types[collection_name] = collection_typ
@staticmethod
def from_name(name):
# build types hierarchy on first use (lazy creation)
if Types.Types is None:
Types._build_types()
search_name = name
# detect if name represents collection
is_collection = name.lower().startswith('collection(') and name.endswith(')')
if is_collection:
name = name[11:-1] # strip collection() decorator
search_name = 'Collection({})'.format(name)
# pylint: disable=unsubscriptable-object
return Types.Types[search_name]
@staticmethod
def parse_type_name(type_name):
# detect if name represents collection
is_collection = type_name.lower().startswith('collection(') and type_name.endswith(')')
if is_collection:
type_name = type_name[11:-1] # strip collection() decorator
parts = type_name.split('.')
if len(parts) == 1:
return TypeInfo(None, type_name, is_collection)
if len(parts) > 1 and parts[0] == 'Edm':
return TypeInfo(None, type_name, is_collection)
return TypeInfo(parts[0], parts[1], is_collection)
class EdmStructTypeSerializer:
"""Basic implementation of (de)serialization for Edm complex types
All properties existing in related Edm type are taken
into account, others are ignored
TODO: it can happen that inifinite recurision occurs for cases
when property types are referencich each other. We need some research
here to avoid such cases.
"""
@staticmethod
def to_literal(edm_type, value):
# pylint: disable=no-self-use
if not edm_type:
raise PyODataException('Cannot encode value {} without complex type information'.format(value))
result = {}
for type_prop in edm_type.proprties():
if type_prop.name in value:
result[type_prop.name] = type_prop.typ.traits.to_literal(value[type_prop.name])
return result
@staticmethod
def from_json(edm_type, value):
# pylint: disable=no-self-use
if not edm_type:
raise PyODataException('Cannot decode value {} without complex type information'.format(value))
result = {}
for type_prop in edm_type.proprties():
if type_prop.name in value:
result[type_prop.name] = type_prop.typ.traits.from_json(value[type_prop.name])
return result
@staticmethod
def from_literal(edm_type, value):
# pylint: disable=no-self-use
if not edm_type:
raise PyODataException('Cannot decode value {} without complex type information'.format(value))
result = {}
for type_prop in edm_type.proprties():
if type_prop.name in value:
result[type_prop.name] = type_prop.typ.traits.from_literal(value[type_prop.name])
return result
class TypTraits:
"""Encapsulated differences between types"""
def __repr__(self):
return self.__class__.__name__
# pylint: disable=no-self-use
def to_literal(self, value):
return value
# pylint: disable=no-self-use
def from_json(self, value):
return value
def from_literal(self, value):
return value
class EdmPrefixedTypTraits(TypTraits):
"""Is good for all types where values have form: prefix'value'"""
def __init__(self, prefix):
super(EdmPrefixedTypTraits, self).__init__()
self._prefix = prefix
def to_literal(self, value):
return '{}\'{}\''.format(self._prefix, value)
def from_literal(self, value):
matches = re.match("^{}'(.*)'$".format(self._prefix), value)
if not matches:
raise PyODataModelError(
"Malformed value {0} for primitive Edm type. Expected format is {1}'value'".format(value, self._prefix))
return matches.group(1)
class EdmDateTimeTypTraits(EdmPrefixedTypTraits):
"""Emd.DateTime traits
Represents date and time with values ranging from 12:00:00 midnight,
January 1, 1753 A.D. through 11:59:59 P.M, December 9999 A.D.
Literal form:
datetime'yyyy-mm-ddThh:mm[:ss[.fffffff]]'
NOTE: Spaces are not allowed between datetime and quoted portion.
datetime is case-insensitive
Example 1: datetime'2000-12-12T12:00'
JSON has following format: /Date(1516614510000)/
https://blogs.sap.com/2017/01/05/date-and-time-in-sap-gateway-foundation/
"""
def __init__(self):
super(EdmDateTimeTypTraits, self).__init__('datetime')
def to_literal(self, value):
"""Convert python datetime representation to literal format
None: this could be done also via formatting string:
value.strftime('%Y-%m-%dT%H:%M:%S.%f')
"""
if not isinstance(value, datetime.datetime):
raise PyODataModelError(
'Cannot convert value of type {} to literal. Datetime format is required.'.format(type(value)))
return super(EdmDateTimeTypTraits, self).to_literal(value.isoformat())
def from_json(self, value):
if value is None:
return None
matches = re.match(r"^/Date\((.*)\)/$", value)
if not matches:
raise PyODataModelError(
"Malformed value {0} for primitive Edm type. Expected format is /Date(value)/".format(value))
value = matches.group(1)
try:
# https://stackoverflow.com/questions/36179914/timestamp-out-of-range-for-platform-localtime-gmtime-function
value = datetime.datetime(1970, 1, 1) + datetime.timedelta(milliseconds=int(value))
except ValueError:
raise PyODataModelError('Cannot decode datetime from value {}.'.format(value))
return value
def from_literal(self, value):
if value is None:
return None
value = super(EdmDateTimeTypTraits, self).from_literal(value)
try:
value = datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')
except ValueError:
try:
value = datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S')
except ValueError:
try:
value = datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M')
except ValueError:
raise PyODataModelError('Cannot decode datetime from value {}.'.format(value))
return value
class EdmStringTypTraits(TypTraits):
"""Edm.String traits"""
# pylint: disable=no-self-use
def to_literal(self, value):
return '\'%s\'' % (value)
# pylint: disable=no-self-use
def from_json(self, value):
return value.strip('\'')
def from_literal(self, value):
return value.strip('\'')
class EdmBooleanTypTraits(TypTraits):
"""Edm.Boolean traits"""
# pylint: disable=no-self-use
def to_literal(self, value):
return 'true' if value else 'false'
# pylint: disable=no-self-use
def from_json(self, value):
return value
def from_literal(self, value):
return value == 'true'
class EdmIntTypTraits(TypTraits):
"""All Edm Integer traits"""
# pylint: disable=no-self-use
def to_literal(self, value):
return '%d' % (value)
# pylint: disable=no-self-use
def from_json(self, value):
return int(value)
def from_literal(self, value):
return int(value)
class EdmStructTypTraits(TypTraits):
"""Edm structural types (EntityType, ComplexType) traits"""
def __init__(self, edm_type=None):
super(EdmStructTypTraits, self).__init__()
self._edm_type = edm_type
# pylint: disable=no-self-use
def to_literal(self, value):
return EdmStructTypeSerializer.to_literal(self._edm_type, value)
# pylint: disable=no-self-use
def from_json(self, value):
return EdmStructTypeSerializer.from_json(self._edm_type, value)
def from_literal(self, value):
return EdmStructTypeSerializer.from_json(self._edm_type, value)
class Typ(Identifier):
Types = None
Kinds = enum.Enum('Kinds', 'Primitive Complex')
def __init__(self, name, null_value, traits=TypTraits(), kind=None):
super(Typ, self).__init__(name)
self._null_value = null_value
self._kind = kind if kind is not None else Typ.Kinds.Primitive # no way how to us enum value for parameter default value
self._traits = traits
@property
def null_value(self):
return self._null_value
@property
def traits(self):
return self._traits
@property
def is_collection(self):
return False
@property
def kind(self):
return self._kind
class Collection(Typ):
"""Represents collection items"""
def __init__(self, name, item_type):
super(Collection, self).__init__(name, [], kind=item_type.kind)
self._item_type = item_type
def __repr__(self):
return 'Collection({})'.format(repr(self._item_type))
@property
def is_collection(self):
return True
@property
def item_type(self):
return self._item_type
@property
def traits(self):
return self
# pylint: disable=no-self-use
def to_literal(self, value):
if not isinstance(value, list):
raise PyODataException('Bad format: invalid list value {}'.format(value))
return [self._item_type.traits.to_literal(v) for v in value]
# pylint: disable=no-self-use
def from_json(self, value):
if not isinstance(value, list):
raise PyODataException('Bad format: invalid list value {}'.format(value))
return [self._item_type.traits.from_json(v) for v in value]
class VariableDeclaration(Identifier):
MAXIMUM_LENGTH = -1
def __init__(self, name, type_info, nullable, max_length, precision, scale):
super(VariableDeclaration, self).__init__(name)
self._type_info = type_info
self._typ = None
self._nullable = bool(nullable)
if not max_length:
self._max_length = None
elif max_length.upper() == 'MAX':
self._max_length = VariableDeclaration.MAXIMUM_LENGTH
else:
self._max_length = int(max_length)
if not precision:
self._precision = 0
else:
self._precision = int(precision)
if not scale:
self._scale = 0
else:
self._scale = int(scale)
self._check_scale_value()
@property
def type_info(self):
return self._type_info
@property
def typ(self):
return self._typ
@typ.setter
def typ(self, value):
if self._typ is not None:
raise RuntimeError('Cannot replace {0} of {1} by {2}'.format(self._typ, self, value))
if value.name != self._type_info[1]:
raise RuntimeError('{0} cannot be the type of {1}'.format(value, self))
self._typ = value
@property
def nullable(self):
return self._nullable
@property
def max_length(self):
return self._max_length
@property
def precision(self):
return self._precision
@property
def scale(self):
return self._scale
def _check_scale_value(self):
if self._scale > self._precision:
raise PyODataModelError('Scale value ({}) must be less than or equal to precision value ({})'
.format(self._scale, self._precision))
class Schema:
class Declaration:
def __init__(self, namespace):
super(Schema.Declaration, self).__init__()
self.namespace = namespace
self.entity_types = dict()
self.complex_types = dict()
self.entity_sets = dict()
self.function_imports = dict()
self.associations = dict()
self.association_sets = dict()
def list_entity_types(self):
return list(self.entity_types.values())
def list_complex_types(self):
return list(self.complex_types.values())
def list_entity_sets(self):
return list(self.entity_sets.values())
def list_function_imports(self):
return list(self.function_imports.values())
def list_associations(self):
return list(self.associations.values())
def list_association_sets(self):
return list(self.association_sets.values())
def add_entity_type(self, etype):
"""Add new type to the type repository as well as its collection variant"""
self.entity_types[etype.name] = etype
# automatically create and register collection variant if not exists
collection_type_name = 'Collection({})'.format(etype.name)
self.entity_types[collection_type_name] = Collection(etype.name, etype)
def add_complex_type(self, ctype):
"""Add new complex type to the type repository as well as its collection variant"""
self.complex_types[ctype.name] = ctype
# automatically create and register collection variant if not exists
collection_type_name = 'Collection({})'.format(ctype.name)
self.complex_types[collection_type_name] = Collection(ctype.name, ctype)
class Declarations(dict):
def __getitem__(self, key):
try:
return super(Schema.Declarations, self).__getitem__(key)
except KeyError:
raise KeyError('There is no Schema Namespace {}'.format(key))
def __init__(self):
super(Schema, self).__init__()
self._decls = Schema.Declarations()
def __str__(self):
return "{0}({1})".format(self.__class__.__name__, ','.join(self.namespaces))
@property
def namespaces(self):
return list(self._decls.keys())
def typ(self, type_name, namespace=None):
"""Returns either EntityType or ComplexType that matches the name.
"""
for type_space in (self.entity_type, self.complex_type):
try:
return type_space(type_name, namespace=namespace)
except KeyError:
pass
raise KeyError('Type {} does not exist in Schema{}'
.format(type_name, ' Namespace ' + namespace if namespace else ''))
def entity_type(self, type_name, namespace=None):
if namespace is not None:
try:
return self._decls[namespace].entity_types[type_name]
except KeyError:
raise KeyError('EntityType {} does not exist in Schema Namespace {}'.format(type_name, namespace))
for decl in list(self._decls.values()):
try:
return decl.entity_types[type_name]
except KeyError:
pass
raise KeyError('EntityType {} does not exist in any Schema Namespace'.format(type_name))
def complex_type(self, type_name, namespace=None):
if namespace is not None:
try:
return self._decls[namespace].complex_types[type_name]
except KeyError:
raise KeyError('ComplexType {} does not exist in Schema Namespace {}'.format(type_name, namespace))
for decl in list(self._decls.values()):
try:
return decl.complex_types[type_name]
except KeyError:
pass
raise KeyError('ComplexType {} does not exist in any Schema Namespace'.format(type_name))
def get_type(self, type_info):
# construct search name based on collection information
search_name = type_info[1] if not type_info[2] else 'Collection({})'.format(type_info[1])
# first look for type in primitive types
try:
return Types.from_name(search_name)
except KeyError:
pass
# then look for type in entity types
try:
return self.entity_type(search_name, type_info[0])
except KeyError:
pass
# then look for type in complex types
try:
return self.complex_type(search_name, type_info[0])
except KeyError:
pass
raise PyODataModelError(
'Neither primitive types nor types parsed from service metadata contain requested type {}'.format(type_info[
1]))
@property
def entity_types(self):
return [
entity_type
for entity_type in itertools.chain(*(decl.list_entity_types() for decl in list(self._decls.values())))
]
@property
def complex_types(self):
return [
complex_type
for complex_type in itertools.chain(*(decl.list_complex_types() for decl in list(self._decls.values())))
]
def entity_set(self, set_name, namespace=None):
if namespace is not None:
try:
return self._decls[namespace].entity_sets[set_name]
except KeyError:
raise KeyError('EntitySet {} does not exist in Schema Namespace {}'.format(set_name, namespace))
for decl in list(self._decls.values()):
try:
return decl.entity_sets[set_name]
except KeyError:
pass
raise KeyError('EntitySet {} does not exist in any Schema Namespace'.format(set_name))
@property
def entity_sets(self):
return [
entity_set
for entity_set in itertools.chain(*(decl.list_entity_sets() for decl in list(self._decls.values())))
]
def function_import(self, function_import, namespace=None):
if namespace is not None:
try:
return self._decls[namespace].function_imports[function_import]
except KeyError:
raise KeyError('FunctionImport {} does not exist in Schema Namespace {}'
.format(function_import, namespace))
for decl in list(self._decls.values()):
try:
return decl.function_imports[function_import]
except KeyError:
pass
raise KeyError('FunctionImport {} does not exist in any Schema Namespace'.format(function_import))
@property
def function_imports(self):
return [
func_import
for func_import in itertools.chain(*(decl.list_function_imports() for decl in list(self._decls.values())))
]
def association(self, association_name, namespace=None):
if namespace is not None:
try:
return self._decls[namespace].associations[association_name]
except KeyError:
raise KeyError('Association {} does not exist in namespace {}'.format(association_name, namespace))
for decl in list(self._decls.values()):
try:
return decl.associations[association_name]
except KeyError:
pass
@property
def associations(self):
return [
association
for association in itertools.chain(*(decl.list_associations() for decl in list(self._decls.values())))
]
def association_set_by_association(self, association_name, namespace=None):
if namespace is not None:
for association_set in list(self._decls[namespace].association_sets.values()):
if association_set.association_type.name == association_name:
return association_set
raise KeyError('Association Set for Association {} does not exist in Schema Namespace {}'.format(
association_name, namespace))
for decl in list(self._decls.values()):
for association_set in list(decl.association_sets.values()):
if association_set.association_type.name == association_name:
return association_set
raise KeyError('Association Set for Association {} does not exist in any Schema Namespace'.format(
association_name))
def association_set(self, set_name, namespace=None):
if namespace is not None:
try:
return self._decls[namespace].association_sets[set_name]
except KeyError:
raise KeyError('Association set {} does not exist in namespace {}'.format(set_name, namespace))
for decl in list(self._decls.values()):
try:
return decl.association_sets[set_name]
except KeyError:
pass
@property
def association_sets(self):
return [
association_set
for association_set in itertools.chain(*(decl.list_association_sets()
for decl in list(self._decls.values())))
]
def check_role_property_names(self, role, entity_type_name, namespace):
for proprty in role.property_names:
try:
entity_type = self.entity_type(entity_type_name, namespace)
except KeyError:
raise PyODataModelError('EntityType {} does not exist in Schema Namespace {}'
.format(entity_type_name, namespace))
try:
entity_type.proprty(proprty)
except KeyError:
raise PyODataModelError('Property {} does not exist in {}'.format(proprty, entity_type.name))
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
@staticmethod
def from_etree(schema_nodes):
schema = Schema()
# Parse Schema nodes by parts to get over the problem of not-yet known
# entity types referenced by entity sets, function imports and
# annotations.
# First, process EntityType and ComplexType nodes. They have almost no dependencies on other elements.
for schema_node in schema_nodes:
namespace = schema_node.get('Namespace')
decl = Schema.Declaration(namespace)
schema._decls[namespace] = decl
for complex_type in schema_node.xpath('edm:ComplexType', namespaces=NAMESPACES):
ctype = ComplexType.from_etree(complex_type)
decl.add_complex_type(ctype)
for entity_type in schema_node.xpath('edm:EntityType', namespaces=NAMESPACES):
etype = EntityType.from_etree(entity_type)
decl.add_entity_type(etype)
# resolve types of properties
for stype in itertools.chain(schema.entity_types, schema.complex_types):
if stype.kind == Typ.Kinds.Complex:
# skip collections (no need to assign any types since type of collection
# items is resolved separately
if stype.is_collection:
continue
for prop in stype.proprties():
prop.typ = schema.get_type(prop.type_info)
# Then, process Associations nodes because they refer EntityTypes and
# they are referenced by AssociationSets.
for schema_node in schema_nodes:
namespace = schema_node.get('Namespace')
decl = schema._decls[namespace]
for association in schema_node.xpath('edm:Association', namespaces=NAMESPACES):
assoc = Association.from_etree(association)
for end_role in assoc.end_roles:
try:
# search and assign entity type (it must exist)
if end_role.entity_type_info.namespace is None:
end_role.entity_type_info.namespace = namespace
etype = schema.entity_type(end_role.entity_type_info.name, end_role.entity_type_info.namespace)
end_role.entity_type = etype
except KeyError:
raise PyODataModelError(
'EntityType {} does not exist in Schema Namespace {}'
.format(end_role.entity_type_info.name, end_role.entity_type_info.namespace))
if assoc.referential_constraint is not None:
role_names = [end_role.role for end_role in assoc.end_roles]
principal_role = assoc.referential_constraint.principal
# Check if the role was defined in the current association
if principal_role.name not in role_names:
raise RuntimeError(
'Role {} was not defined in association {}'.format(principal_role.name, assoc.name))
# Check if principal role properties exist
role_name = principal_role.name
entity_type_name = assoc.end_by_role(role_name).entity_type_name
schema.check_role_property_names(principal_role, entity_type_name, namespace)
dependent_role = assoc.referential_constraint.dependent
# Check if the role was defined in the current association
if dependent_role.name not in role_names:
raise RuntimeError(
'Role {} was not defined in association {}'.format(dependent_role.name, assoc.name))
# Check if dependent role properties exist
role_name = dependent_role.name
entity_type_name = assoc.end_by_role(role_name).entity_type_name
schema.check_role_property_names(dependent_role, entity_type_name, namespace)
decl.associations[assoc.name] = assoc
# resolve navigation properties
for stype in schema.entity_types:
# skip collections
if stype.is_collection:
continue
for nav_prop in stype.nav_proprties:
assoc = schema.association(nav_prop.association_info.name, nav_prop.association_info.namespace)
nav_prop.association = assoc
# Then, process EntitySet, FunctionImport and AssociationSet nodes.
for schema_node in schema_nodes:
namespace = schema_node.get('Namespace')
decl = schema._decls[namespace]
for entity_set in schema_node.xpath('edm:EntityContainer/edm:EntitySet', namespaces=NAMESPACES):
eset = EntitySet.from_etree(entity_set)
eset.entity_type = schema.entity_type(eset.entity_type_info[1], namespace=eset.entity_type_info[0])
decl.entity_sets[eset.name] = eset
for function_import in schema_node.xpath('edm:EntityContainer/edm:FunctionImport', namespaces=NAMESPACES):
efn = FunctionImport.from_etree(function_import)
# complete type information for return type and parameters
efn.return_type = schema.get_type(efn.return_type_info)
for param in efn.parameters:
param.typ = schema.get_type(param.type_info)
decl.function_imports[efn.name] = efn
for association_set in schema_node.xpath('edm:EntityContainer/edm:AssociationSet', namespaces=NAMESPACES):
assoc_set = AssociationSet.from_etree(association_set)
try:
assoc_set.association_type = schema.association(assoc_set.association_type_name,
assoc_set.association_type_namespace)
except KeyError:
raise PyODataModelError(
'Association {} does not exist in namespace {}'
.format(assoc_set.association_type_name, assoc_set.association_type_namespace))
for key, value in list(assoc_set.end_roles.items()):
# Check if entity set exists in current scheme
try:
schema.entity_set(key, namespace)
except KeyError:
raise PyODataModelError('EntitySet {} does not exist in Schema Namespace {}'
.format(key, namespace))
# Check if role is defined in Association
if assoc_set.association_type.end_by_role(value) is None:
raise PyODataModelError('Role {} is not defined in association {}'
.format(value, assoc_set.association_type_name))
decl.association_sets[assoc_set.name] = assoc_set
# Finally, process Annotation nodes when all Scheme nodes are completely processed.
for schema_node in schema_nodes:
for annotation_group in schema_node.xpath('edm:Annotations', namespaces=ANNOTATION_NAMESPACES):
for annotation in ExternalAnnontation.from_etree(annotation_group):
if not annotation.element_namespace != schema.namespaces:
modlog().warning('{0} not in the namespaces {1}'.format(annotation, ','.join(schema.namespaces)))
continue
if annotation.kind == Annotation.Kinds.ValueHelper:
try:
annotation.entity_set = schema.entity_set(
annotation.collection_path, namespace=annotation.element_namespace)
except KeyError:
raise RuntimeError('Entity Set {0} for {1} does not exist'
.format(annotation.collection_path, annotation))
try:
vh_type = schema.typ(
annotation.proprty_entity_type_name, namespace=annotation.element_namespace)
except KeyError:
raise RuntimeError('Target Type {0} of {1} does not exist'.format(
annotation.proprty_entity_type_name, annotation))
try:
target_proprty = vh_type.proprty(annotation.proprty_name)
except KeyError:
raise RuntimeError('Target Property {0} of {1} as defined in {2} does not exist'.format(
annotation.proprty_name, vh_type, annotation))
annotation.proprty = target_proprty
target_proprty.value_helper = annotation
return schema
class StructType(Typ):
def __init__(self, name, label, is_value_list):
super(StructType, self).__init__(name, None, EdmStructTypTraits(self), Typ.Kinds.Complex)
self._label = label
self._is_value_list = is_value_list
self._key = list()
self._properties = dict()
@property
def label(self):
return self._label
@property
def is_value_list(self):
return self._is_value_list
def proprty(self, property_name):
return self._properties[property_name]
def proprties(self):
return list(self._properties.values())
@classmethod
def from_etree(cls, type_node):
name = type_node.get('Name')
label = sap_attribute_get_string(type_node, 'label')
is_value_list = sap_attribute_get_bool(type_node, 'value-list', False)
stype = cls(name, label, is_value_list)
for proprty in type_node.xpath('edm:Property', namespaces=NAMESPACES):
stp = StructTypeProperty.from_etree(proprty)
if stp.name in stype._properties:
raise KeyError('{0} already has property {1}'.format(stype, stp.name))
stype._properties[stp.name] = stp
# We have to update the property when
# all properites are loaded because
# there might be links between them.
for ctp in list(stype._properties.values()):
ctp.struct_type = stype
return stype
# implementation of Typ interface
@property