forked from SAP/python-pyodata
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
2835 lines (2127 loc) · 98.6 KB
/
model.py
File metadata and controls
2835 lines (2127 loc) · 98.6 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
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 <jakub.filak@sap.com>
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, too-many-public-methods
import base64
import collections
import datetime
from enum import Enum, auto
import io
import itertools
import logging
import re
import warnings
from abc import ABC, abstractmethod
from lxml import etree
from pyodata.exceptions import PyODataException, PyODataModelError, PyODataParserError
LOGGER_NAME = 'pyodata.model'
FIX_SCREWED_UP_MINIMAL_DATETIME_VALUE = False
FIX_SCREWED_UP_MAXIMUM_DATETIME_VALUE = False
IdentifierInfo = collections.namedtuple('IdentifierInfo', 'namespace name')
TypeInfo = collections.namedtuple('TypeInfo', 'namespace name is_collection')
def modlog():
return logging.getLogger(LOGGER_NAME)
class NullAssociation:
def __init__(self, name):
self.name = name
def __getattr__(self, item):
raise PyODataModelError('Cannot access this association. An error occurred during parsing '
'association metadata due to that annotation has been omitted.')
class NullType:
def __init__(self, name):
self.name = name
def __getattr__(self, item):
raise PyODataModelError(f'Cannot access this type. An error occurred during parsing '
f'type stated in xml({self.name}) was not found, therefore it has been replaced with NullType.')
class ErrorPolicy(ABC):
@abstractmethod
def resolve(self, ekseption):
pass
class PolicyFatal(ErrorPolicy):
def resolve(self, ekseption):
raise ekseption
class PolicyWarning(ErrorPolicy):
def __init__(self):
logging.basicConfig(format='%(levelname)s: %(message)s')
self._logger = logging.getLogger()
def resolve(self, ekseption):
self._logger.warning('[%s] %s', ekseption.__class__.__name__, str(ekseption))
class PolicyIgnore(ErrorPolicy):
def resolve(self, ekseption):
pass
class ParserError(Enum):
PROPERTY = auto()
ANNOTATION = auto()
ASSOCIATION = auto()
ENUM_TYPE = auto()
ENTITY_TYPE = auto()
COMPLEX_TYPE = auto()
class Config:
def __init__(self,
custom_error_policies=None,
default_error_policy=None,
xml_namespaces=None,
retain_null=False):
"""
:param custom_error_policies: {ParserError: ErrorPolicy} (default None)
Used to specified individual policies for XML tags. See documentation for more
details.
:param default_error_policy: ErrorPolicy (default PolicyFatal)
If custom policy is not specified for the tag, the default policy will be used.
:param xml_namespaces: {str: str} (default None)
:param retain_null: bool (default False)
If true, do not substitute missing (and null-able) values with default value.
"""
self._custom_error_policy = custom_error_policies
if default_error_policy is None:
default_error_policy = PolicyFatal()
self._default_error_policy = default_error_policy
if xml_namespaces is None:
xml_namespaces = {}
self._namespaces = xml_namespaces
self._retain_null = retain_null
def err_policy(self, error: ParserError):
if self._custom_error_policy is None:
return self._default_error_policy
return self._custom_error_policy.get(error, self._default_error_policy)
def set_default_error_policy(self, policy: ErrorPolicy):
self._custom_error_policy = None
self._default_error_policy = policy
def set_custom_error_policy(self, policies: dict):
self._custom_error_policy = policies
@property
def namespaces(self):
return self._namespaces
@namespaces.setter
def namespaces(self, value: dict):
self._namespaces = value
@property
def retain_null(self):
return self._retain_null
class Identifier:
def __init__(self, name):
super(Identifier, self).__init__()
self._name = name
def __repr__(self):
return f"{self.__class__.__name__}({self._name})"
def __str__(self):
return f"{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('.'.join(parts[:-1]), parts[-1])
class Types:
"""Repository of all available OData V2 primitive types + their Collection variants
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
"""
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\'\'', EdmBinaryTypTraits('(?:binary|X)')))
Types.register_type(Typ('Edm.Boolean', 'false', EdmBooleanTypTraits()))
Types.register_type(Typ('Edm.Byte', '0'))
Types.register_type(Typ('Edm.DateTime', 'datetime\'1753-01-01T00:00\'', EdmDateTimeTypTraits()))
Types.register_type(Typ('Edm.Decimal', '0.0M'))
Types.register_type(Typ('Edm.Double', '0.0d', EdmFPNumTypTraits.edm_double()))
Types.register_type(Typ('Edm.Single', '0.0f', EdmFPNumTypTraits.edm_single()))
Types.register_type(Typ('Edm.Float', '0.0d', EdmFPNumTypTraits.edm_float()))
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', EdmLongIntTypTraits()))
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\'1753-01-01T00:00:00Z\'', EdmDateTimeOffsetTypTraits()))
@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 = f'Collection({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 = f'Collection({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
identifier = Identifier.parse(type_name)
if identifier.namespace == 'Edm':
return TypeInfo(None, type_name, is_collection)
return TypeInfo(identifier.namespace, identifier.name, 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(f'Cannot encode value {value} without complex type information')
result = {}
for type_prop in edm_type.proprties():
if type_prop.name in value:
result[type_prop.name] = type_prop.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(f'Cannot decode value {value} without complex type information')
result = {}
for type_prop in edm_type.proprties():
if type_prop.name in value:
result[type_prop.name] = type_prop.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(f'Cannot decode value {value} without complex type information')
result = {}
for type_prop in edm_type.proprties():
if type_prop.name in value:
result[type_prop.name] = type_prop.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 to_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(f"^{self._prefix}'(.*)'$", value)
if not matches:
raise PyODataModelError(
f"Malformed value {value} for primitive Edm type. Expected format is {self._prefix}'value'")
return matches.group(1)
class EdmBinaryTypTraits(EdmPrefixedTypTraits):
"""Edm.Binary traits"""
def to_literal(self, value):
binary = base64.b64decode(value, validate=True)
return f"binary'{base64.b16encode(binary).decode()}'"
def from_literal(self, value):
binary = base64.b16decode(super().from_literal(value), casefold=True)
return base64.b64encode(binary).decode()
def ms_since_epoch_to_datetime(value, tzinfo):
"""Convert milliseconds since midnight 1.1.1970 to datetime"""
try:
# https://stackoverflow.com/questions/36179914/timestamp-out-of-range-for-platform-localtime-gmtime-function
return datetime.datetime(1970, 1, 1, tzinfo=tzinfo) + datetime.timedelta(milliseconds=int(value))
except (ValueError, OverflowError):
min_ticks = -62135596800000
max_ticks = 253402300799999
if FIX_SCREWED_UP_MINIMAL_DATETIME_VALUE and int(value) < min_ticks:
# Some service providers return false minimal date values.
# -62135596800000 is the lowest value PyOData could read.
# This workaround fixes this issue and returns 0001-01-01 00:00:00+00:00 in such a case.
return datetime.datetime(year=1, day=1, month=1, tzinfo=tzinfo)
if FIX_SCREWED_UP_MAXIMUM_DATETIME_VALUE and int(value) > max_ticks:
return datetime.datetime(year=9999, day=31, month=12, tzinfo=tzinfo)
raise PyODataModelError(f'Cannot decode datetime from value {value}. '
f'Possible value range: {min_ticks} to {max_ticks}. '
f'You may fix this by setting `FIX_SCREWED_UP_MINIMAL_DATETIME_VALUE` '
f' or `FIX_SCREWED_UP_MAXIMUM_DATETIME_VALUE` as a workaround.')
def parse_datetime_literal(value):
try:
return datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')
except ValueError:
try:
return datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S')
except ValueError:
try:
return datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M')
except ValueError:
raise PyODataModelError(f'Cannot decode datetime from value {value}.')
class EdmDateTimeTypTraits(EdmPrefixedTypTraits):
"""Edm.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(
f'Cannot convert value of type {type(value)} to literal. Datetime format is required.')
if value.tzinfo != datetime.timezone.utc:
raise PyODataModelError('Edm.DateTime accepts only UTC')
# Sets timezone to none to avoid including timezone information in the literal form.
return super(EdmDateTimeTypTraits, self).to_literal(value.replace(tzinfo=None).isoformat())
def to_json(self, value):
if isinstance(value, str):
return value
if value.tzinfo != datetime.timezone.utc:
raise PyODataModelError('Edm.DateTime accepts only UTC')
# Converts datetime into timestamp in milliseconds in UTC timezone as defined in ODATA specification
# https://www.odata.org/documentation/odata-version-2-0/json-format/
# See also: https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp
ticks = (value - datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)) / datetime.timedelta(milliseconds=1)
return f'/Date({int(ticks)})/'
def from_json(self, value):
if value is None:
return None
matches = re.match(r"^/Date\((?P<milliseconds_since_epoch>-?\d+)(?P<offset_in_minutes>[+-]\d+)?\)/$", value)
try:
milliseconds_since_epoch = matches.group('milliseconds_since_epoch')
except AttributeError:
raise PyODataModelError(
f"Malformed value {value} for primitive Edm.DateTime type."
" Expected format is /Date(<ticks>[±<offset>])/")
try:
offset_in_minutes = int(matches.group('offset_in_minutes') or 0)
timedelta = datetime.timedelta(minutes=offset_in_minutes)
except ValueError:
raise PyODataModelError(
f"Malformed value {value} for primitive Edm.DateTime type."
" Expected format is /Date(<ticks>[±<offset>])/")
except AttributeError:
timedelta = datetime.timedelta() # Missing offset is interpreted as UTC
# Might raise a PyODataModelError exception
return ms_since_epoch_to_datetime(milliseconds_since_epoch, datetime.timezone.utc) + timedelta
def from_literal(self, value):
if value is None:
return None
value = super(EdmDateTimeTypTraits, self).from_literal(value)
# Note: parse_datetime_literal raises a PyODataModelError exception on invalid formats
return parse_datetime_literal(value).replace(tzinfo=datetime.timezone.utc)
class EdmDateTimeOffsetTypTraits(EdmPrefixedTypTraits):
"""Edm.DateTimeOffset traits
Represents date and time, plus an offset in minutes from UTC, with values ranging from 12:00:00 midnight,
January 1, 1753 A.D. through 11:59:59 P.M, December 9999 A.D
Literal forms:
datetimeoffset'yyyy-mm-ddThh:mm[:ss]±ii:nn' (works for all time zones)
datetimeoffset'yyyy-mm-ddThh:mm[:ss]Z' (works only for UTC)
NOTE: Spaces are not allowed between datetimeoffset and quoted portion.
The datetime part is case-insensitive, the offset one is not.
Example 1: datetimeoffset'1970-01-01T00:00:01+00:30'
- /Date(1000+0030)/ (As DateTime, but with a 30 minutes timezone offset)
Example 1: datetimeoffset'1970-01-01T00:00:01-00:60'
- /Date(1000-0030)/ (As DateTime, but with a negative 60 minutes timezone offset)
https://blogs.sap.com/2017/01/05/date-and-time-in-sap-gateway-foundation/
"""
def __init__(self):
super(EdmDateTimeOffsetTypTraits, self).__init__('datetimeoffset')
def to_literal(self, value):
"""Convert python datetime representation to literal format"""
if not isinstance(value, datetime.datetime) or value.utcoffset() is None:
raise PyODataModelError(
f'Cannot convert value of type {type(value)} to literal. Datetime format including offset is required.')
return super(EdmDateTimeOffsetTypTraits, self).to_literal(value.isoformat())
def to_json(self, value):
# datetime.timestamp() does not work due to its limited precision
offset_in_minutes = int(value.utcoffset() / datetime.timedelta(minutes=1))
ticks = int((value - datetime.datetime(1970, 1, 1, tzinfo=value.tzinfo)) / datetime.timedelta(milliseconds=1))
return f'/Date({ticks}{offset_in_minutes:+05})/'
def from_json(self, value):
# special edge case:
# datetimeoffset'yyyy-mm-ddThh:mm[:ss]' = defaults to UTC, when offset value is not provided in response
# by service, but the metadata is EdmDateTimeOffset
# intentionally just for from_json, generation of to_json should always provide timezone info
matches = re.match(r"^/Date\((?P<milliseconds_since_epoch>-?\d+)(?P<offset_in_minutes>[+-]\d+)?\)/$", value)
try:
milliseconds_since_epoch = matches.group('milliseconds_since_epoch')
if matches.group('offset_in_minutes') is not None:
offset_in_minutes = int(matches.group('offset_in_minutes'))
else:
offset_in_minutes = 0
except (ValueError, AttributeError):
raise PyODataModelError(
f"Malformed value {value} for primitive Edm.DateTimeOffset type."
" Expected format is /Date(<ticks>±<offset>)/")
tzinfo = datetime.timezone(datetime.timedelta(minutes=offset_in_minutes))
# Might raise a PyODataModelError exception
return ms_since_epoch_to_datetime(milliseconds_since_epoch, tzinfo)
def from_literal(self, value):
if value is None:
return None
value = super(EdmDateTimeOffsetTypTraits, self).from_literal(value)
try:
# Note: parse_datetime_literal raises a PyODataModelError exception on invalid formats
if re.match(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z', value, flags=re.ASCII | re.IGNORECASE):
datetime_part = value[:-1]
tz_info = datetime.timezone.utc
else:
match = re.match(r'(?P<datetime>.+)(?P<sign>[\\+-])(?P<hours>\d{2}):(?P<minutes>\d{2})',
value,
flags=re.ASCII)
datetime_part = match.group('datetime')
tz_offset = datetime.timedelta(hours=int(match.group('hours')),
minutes=int(match.group('minutes')))
tz_sign = -1 if match.group('sign') == '-' else 1
tz_info = datetime.timezone(tz_sign * tz_offset)
return parse_datetime_literal(datetime_part).replace(tzinfo=tz_info)
except (ValueError, AttributeError):
raise PyODataModelError(f'Cannot decode datetimeoffset from value {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 EdmLongIntTypTraits(TypTraits):
"""All Edm Integer for big numbers traits"""
# pylint: disable=no-self-use
def to_literal(self, value):
return '%dL' % (value)
# pylint: disable=no-self-use
def from_json(self, value):
if value[-1] == 'L':
return int(value[:-1])
return int(value)
def from_literal(self, value):
return self.from_json(value)
class EdmFPNumTypTraits(TypTraits):
"""Edm Floating Point Number traits"""
def __init__(self, precision, suffix, conversion):
self.precision = precision
self.suffix = suffix
self.conversion = conversion
def __repr__(self):
parent = super(EdmFPNumTypTraits, self).__repr__()
return f'{parent}({self.precision},{self.suffix})'
@staticmethod
def edm_float():
return EdmFPNumTypTraits(7, 'd', '{:E}')
@staticmethod
def edm_double():
return EdmFPNumTypTraits(15, 'd', '{:E}')
@staticmethod
def edm_single():
return EdmFPNumTypTraits(7, 'f', '{:f}')
# pylint: disable=no-self-use
def to_literal(self, value):
return self.conversion.format(value)
def to_json(self, value):
return self.to_literal(value)
# pylint: disable=no-self-use
def from_json(self, value):
if not isinstance(value, str) or value[-1] != self.suffix:
return float(value)
return float(value[:-1])
def from_literal(self, value):
return self.from_json(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_literal(self._edm_type, value)
class EnumTypTrait(TypTraits):
def __init__(self, enum_type):
self._enum_type = enum_type
def to_literal(self, value):
return f'{value.parent.namespace}.{value}'
def from_json(self, value):
return getattr(self._enum_type, value)
def from_literal(self, value):
# remove namespaces
enum_value = value.split('.')[-1]
# remove enum type
name = enum_value.split("'")[1]
return getattr(self._enum_type, name)
class Typ(Identifier):
Types = None
Kinds = 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 f'Collection({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(f'Bad format: invalid list value {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(f'Bad format: invalid list value {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, fixed_length=None):
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()
self._fixed_length = bool(fixed_length)
@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(f'Cannot replace {self._typ} of {self} by {value}')
if value.name != self._type_info[1]:
raise RuntimeError(f'{value} cannot be the type of {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
@property
def fixed_length(self):
return self._fixed_length
def from_literal(self, value):
if value is None:
if not self.nullable:
raise PyODataException(f'Cannot convert null URL literal to value of {str(self)}')
return None
return self.typ.traits.from_literal(value)
def to_literal(self, value):
if value is None:
if not self.nullable:
raise PyODataException(f'Cannot convert None to URL literal of {str(self)}')
return None
return self.typ.traits.to_literal(value)
def from_json(self, value):
if value is None:
if not self.nullable:
raise PyODataException(f'Cannot convert null JSON to value of {str(self)}')
return None
return self.typ.traits.from_json(value)
def to_json(self, value):
if value is None:
if not self.nullable:
raise PyODataException(f'Cannot convert None to JSON of {str(self)}')
return None
return self.typ.traits.to_json(value)
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.enum_types = dict()
self.entity_sets = dict()
self.function_imports = dict()
self.associations = dict()
self.association_sets = dict()
# generated collections for ease of lookup (e.g. function import return type)
self._collections_entity_types = dict()
self._collections_complex_types = 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_enum_types(self):
return list(self.enum_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
if isinstance(etype, NullType):
return
collection_type_name = f'Collection({etype.name})'
self._collections_entity_types[collection_type_name] = Collection(etype.name, etype)
# TODO performance memory: this is generating collection for every entity type encoutered, regardless of such collection is really used.
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
if isinstance(ctype, NullType):
return
collection_type_name = f'Collection({ctype.name})'
self._collections_complex_types[collection_type_name] = Collection(ctype.name, ctype)
# TODO performance memory: this is generating collection for every entity type encoutered, regardless of such collection is really used.
def add_enum_type(self, etype):
"""Add new enum type to the type repository"""
self.enum_types[etype.name] = etype
class Declarations(dict):
def __getitem__(self, key):
try:
return super(Schema.Declarations, self).__getitem__(key)
except KeyError:
raise KeyError(f'There is no Schema Namespace {key}')
def __init__(self, config: Config):
super(Schema, self).__init__()
self._decls = Schema.Declarations()
self._config = config
self._is_valid = False
def __str__(self):
return f"{self.__class__.__name__}({','.join(self.namespaces)})"
@property
def namespaces(self):
return list(self._decls.keys())
@property
def config(self):
return self._config
@property
def is_valid(self):
"""Returns if metadata provided were parsed to schema without any problem regardless of Policies (Fatal, Warning, Ignore).
Policies affects behaviour o parser while this property represents status.
"""
return self._is_valid
def typ(self, type_name, namespace=None):
"""Returns either EntityType, ComplexType or EnumType that matches the name.
"""