-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquery_builder.py
More file actions
1343 lines (1080 loc) · 49.4 KB
/
query_builder.py
File metadata and controls
1343 lines (1080 loc) · 49.4 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
import datetime
import inspect
from collections import defaultdict
from io import StringIO
import django
from django.db.models import Aggregate
from neomodel import StructuredNode, Q
from neomodel.properties import Property
from utils import str_to_class, db, is_collection
from neomodel.relationship_manager import RelationshipDefinition
class SearchType:
REL_PROP = 1 # relationship property
RECUR_PROP = 2 # recursively process property filter
RECUR_NSET = 3 # recursively process the node set
ID = 4 # id
PROP = 5 # node property
class KeywordArgument:
def __init__(self, negated, parameter, operator, value, type=SearchType.PROP):
self.negated = negated
self.parameter = parameter
self.operator = operator
self.value = value
self.type = type
def __iter__(self):
yield self.negated
yield self.parameter
yield self.operator
yield self.value
yield self.type
def __len__(self):
return 4
def __str__(self):
return f'[negated: {self.negated}, parameter: {self.parameter}, operator: {self.operator},' \
f' value: {self.value.__class__ if isinstance(self.value, AdvancedNodeSet) else self.value}]'
def __repr__(self):
return str(self)
class RelKeywordArgument:
def __init__(self, rel_path: "RelPath", keyword_argument: KeywordArgument):
self.rel_path = rel_path
self.keyword_argument = keyword_argument
def __iter__(self):
yield self.rel_path
yield self.keyword_argument
def __repr__(self):
return str(self)
def __str__(self):
return f'[rel_path: {self.rel_path}, keyword_argument: {self.keyword_argument}]'
class RelPath:
def __init__(self, node_name, rel_type, rel_direction, cls):
self.node_name = node_name
self.rel_type = rel_type
self.rel_direction = rel_direction
self.left = self.right = '-'
to = rel_direction == 1
if to:
self.right = '->'
else:
self.left = '<-'
self.cls = cls
def __repr__(self):
return str(self)
def __str__(self):
return f'[node_name: {self.node_name}, rel_type: {self.rel_type}, rel_direction: {self.rel_direction}, cls: {self.cls.__name__}]'
class NodeRelationshipDetail:
def __init__(self, cls):
self.cls = cls
self.relationships = {k: v for k, v in vars(cls).items() if
isinstance(v, RelationshipDefinition)}
self.linked_nodes = {v._raw_class.lower(): str_to_class(v._raw_class) for k, v in self.relationships.items()}
self.node_properties = {k for k, v in vars(cls).items() if isinstance(v, Property)}
self.linked_nodes[self.cls_name.lower()] = self.cls
@property
def cls_name(self):
return self.cls.__name__
def is_node_property(self, property_name):
return property_name.lower() in self.node_properties
def is_node_relationship(self, name):
return name in self.relationships
def is_connected_with(self, node):
if inspect.isclass(node) and issubclass(node, StructuredNode):
node_name = node.__name__
else:
node_name = node
return node_name.lower() in self.linked_nodes
def get_linkedNode_cls(self, node_name):
try:
return self.linked_nodes[node_name.lower()]
except KeyError:
raise KeyError(f"Node {self.cls_name} has no relationship with {node_name.capitalize()}")
def get_rel_detail(self, name=None, inverse=False) -> RelPath:
"""
get the connected node's class name and the relationship type with it
e.g: image -- belong to --> user
Image.get_rel_detail('user') -> ConnectedNode('User', 'belong_to', direction, User.__class__)
"""
rel = None
try:
rel = self.relationships[name]
except KeyError:
for v in self.relationships.values():
if v._raw_class == name:
rel = v
if rel is None:
raise KeyError(f"Node {self.cls_name} has no relationship with {name.capitalize()}")
rel_type = rel.definition['relation_type']
direction = rel.definition['direction']
connected_node_name = rel._raw_class
if inverse:
return RelPath(self.cls_name, rel_type, -direction, self.cls)
else:
return RelPath(connected_node_name, rel_type, direction, self.get_linkedNode_cls(connected_node_name))
class _OPERATORS_CLASS:
_OPERATORS = {'gt': '>', 'gte': '>=', 'ne': '<>', 'lt': '<', 'lte': '<=',
'startswith': 'STARTS WITH', 'endswith': 'ENDS WITH', 'in': 'IN',
'contains': 'CONTAINS', 'eq': '='}
GT = _OPERATORS['gt']
GTE = _OPERATORS['gte']
NE = _OPERATORS['ne']
LT = _OPERATORS['lt']
LTE = _OPERATORS['lte']
STARTSWITH = _OPERATORS['startswith']
ENDSWITH = _OPERATORS['endswith']
IN = _OPERATORS['in']
CONTAINS = _OPERATORS['contains']
EQ = _OPERATORS['eq']
def __getitem__(self, key):
operator = self._OPERATORS.get(key, None)
if operator is None:
raise KeyError(f"There is no operator named `{key}`")
return operator
def __contains__(self, key):
return self._OPERATORS.get(key, None) is not None
OPERATORS = _OPERATORS_CLASS()
class CypherKeyWords:
class KeyWord:
def __init__(self, name: str, alias=None):
self.name = name
self.alias = alias
def __eq__(self, other):
if isinstance(other, str):
return other == self.name or other in self.alias
elif isinstance(other, CypherKeyWords.KeyWord):
return id(other) == id(self)
return False
def __repr__(self):
return self.name
def __add__(self, other):
return self.name + other
RETURN = KeyWord(name="RETURN")
MATCH = KeyWord(name="MATCH")
WHERE = KeyWord(name="WHERE")
WITH = KeyWord(name="WITH")
AND = KeyWord(name="AND", alias={"and"})
NOT = KeyWord(name="NOT")
OR = KeyWord(name="OR", alias={"or"})
UNION = KeyWord(name="UNION")
DISTINCT = KeyWord(name="DISTINCT")
ORDER_BY = KeyWord(name="ORDER BY")
SKIP = KeyWord(name="SKIP")
LIMIT = KeyWord(name="LIMIT")
class Variable:
def __init__(self, newly_created, name, flush=False):
self.newly_created = newly_created
self.name = name
self.flush = flush
def __str__(self):
return f'newly_created: {self.newly_created}, name: {self.name}, flush: {self.flush}'
def __repr__(self):
return str(self)
class ASTTree:
def __init__(self, root: "Statement" = None):
self.root: "Statement" = root if root else Statement(None)
self.leaf: "Statement" = self.root
def add_to_last(self, stmt: "Statement"):
self.leaf.child = stmt
self.leaf = stmt
def add_to_head(self, stmt: "Statement"):
temp = self.root.child
stmt.child = temp
self.root.child = stmt
def get_cypher(self):
return self.root.get_cypher().cypher
def get_var(self, key):
return self.root._get_var(key)
def get_type_counter(self, type):
return self.root._get_type_counter(type)
class Statement:
def __init__(self, node, counter=0):
self.variable_name = None
self.parent = None
self.child = None
self._node = node
self._counter = counter
self._variable_table = {}
self._type_counter = defaultdict(int)
def get_cypher(self, parent: "Statement" = None) -> "StatementResult":
parent = parent if parent else self
if self.child:
return self.child.get_cypher(parent)
return StatementResult("", None)
def _next_var(self, key):
if self.parent:
return self.parent._next_var(key)
else:
"""
create a variable for the given key
"""
variable = self._variable_table.get(key)
if not variable:
variable = Variable(True, f"var_{key}_{self._get_type_counter(key)}")
self._variable_table[key] = variable
else:
if variable.flush:
self._update_type_counter(key)
self._variable_table[key] = None
variable.newly_created = False
return variable
def _get_var(self, key):
if self.parent:
return self.parent._get_var(key)
else:
return self._variable_table.get(key)
def _clear_variable_table(self, clear_all=True):
if self.parent:
self.parent._clear_variable_table()
else:
if clear_all:
self._variable_table.clear()
else:
self._variable_table = {
self._node: self._variable_table[self._node]}
def _get_type_counter(self, type):
if self.parent:
return self.parent._get_type_counter(type)
else:
c = self._type_counter[type]
if c == 0:
c = self._counter
self._type_counter[type] = c
return c
def _update_type_counter(self, type, newV=None):
if self.parent:
return self.parent._update_type_counter(type, newV)
else:
if newV is not None:
self._type_counter[type] = max(newV, self._type_counter[type])
else:
c = self._get_type_counter(type)
c += 1
self._type_counter[type] = c
return c
def _update_variable_table(self, node_type, new_var):
if self.parent:
self.parent._update_variable_table(node_type, new_var)
else:
self._variable_table[node_type] = new_var
def _need_reflush(self, node_type):
if self.parent:
self.parent._need_reflush(node_type)
else:
variable = self._variable_table[node_type]
self._variable_table[node_type] = Variable(False, variable.name, flush=True)
class Query(Statement):
def __init__(self, node, parent: "Statement" = None):
super().__init__(node)
if parent:
self.return_var = parent._get_var(node)
class RecursiveStatement(Statement):
def __init__(self, rel_kw: "RelKeywordArgument", parent_filter_cls=None):
super().__init__(None)
self.rel_kw = rel_kw
self.parent_filter_cls = parent_filter_cls
def get_cypher(self, parent: "Statement" = None):
self.parent = parent
adv_filter = self.rel_kw.keyword_argument.value
node_name = adv_filter.cls.__name__
c = self._update_type_counter(type=node_name)
result = QueryBuilder(adv_filter)._build_query(without_return=True, counter=c)
self._update_type_counter(type=node_name, newV=result.type_counter + 1)
new_node_name = f'{node_name}_{result.type_counter}'
self._update_variable_table(new_node_name, Variable(False, result.returned_var))
self.rel_kw.rel_path.node_name = new_node_name
if self.child:
child_result = self.child.get_cypher(parent)
return StatementResult(f'{result.cypher}{child_result.cypher}', child_result.returned_var)
filter_result = QueryBuilder(adv_filter)._build_query(without_return=True)
return StatementResult(f'{filter_result.cypher}', self._get_var(node_name))
class MergeStatement(Statement):
def __init__(self, node, connector: CypherKeyWords.KeyWord):
super().__init__(node)
self.connector = connector
def get_cypher(self, parent: "Statement" = None):
self.parent = parent
if self.child:
return StatementResult(f'{self._get_cypher().cypher}{self.child.get_cypher(parent).cypher}', None)
return StatementResult(self._get_cypher().cypher, None)
def _get_cypher(self):
cypher = ''
# if there are more queries, add the keyword UNION if the connector is OR
if self.connector == CypherKeyWords.OR:
cypher = f'{CypherKeyWords.RETURN} {self._next_var(self._node).name}\n{CypherKeyWords.UNION}\n'
self._clear_variable_table()
elif self.connector == CypherKeyWords.AND:
cypher = f'{CypherKeyWords.WITH} {self._next_var(self._node).name}\n'
self._clear_variable_table(False)
return StatementResult(cypher, None)
class MatchStatement(Statement):
def __init__(self, node: str):
super().__init__(node)
self.variable_name = None
self.child = None
def get_cypher(self, parent: "Statement" = None) -> "StatementResult":
self.parent = parent
if self.child:
result = self._get_cypher()
child_result = self.child.get_cypher(parent)
return StatementResult(result.cypher + ' ' + child_result.cypher, result.returned_var)
else:
return self._get_cypher()
def _get_cypher(self):
variable = self._next_var(self._node)
self.variable_name = variable.name
if variable.newly_created:
stmt = f'{CypherKeyWords.MATCH} ({variable.name}:{self._node})'
else:
stmt = f'{CypherKeyWords.MATCH} ({variable.name})'
return StatementResult(stmt, variable.name)
class RelationStatement(Statement):
def __init__(self, start_node, relationship_def: RelKeywordArgument):
super().__init__(start_node)
self.relationship_def = relationship_def
kw = relationship_def.keyword_argument
self.match_stmt = MatchStatement(start_node)
self.search_type = kw.type
if kw.type == SearchType.REL_PROP:
self.where_stmt = WhereStatement(relationship_def.rel_path.rel_type,
AttributeConditions([relationship_def]))
else:
self.where_stmt = WhereStatement(relationship_def.rel_path.rel_type, AttributeConditions())
def get_cypher(self, parent: "Statement" = None):
self.parent = parent
result = self._get_cypher()
if self.search_type != SearchType.REL_PROP:
where_cypher = "\n"
elif self.search_type == SearchType.REL_PROP:
where_cypher = self.where_stmt.get_cypher(parent).cypher
else:
where_cypher = ""
if self.child:
child_result = self.child.get_cypher(parent)
return StatementResult(f'{result.cypher} {where_cypher}{child_result.cypher}', result.returned_var)
return StatementResult(result.cypher + ' ' + where_cypher, result.returned_var)
def _get_cypher(self):
rel_path = self.relationship_def.rel_path
rel_node_name = rel_path.node_name
rel_variable = self._next_var(rel_path.rel_type)
connected_node_variable = self._next_var(rel_node_name)
if connected_node_variable.newly_created:
# if this variable has already been created
rel_stmt = self._write_relationship_stmt(rel_path, rel_variable.name,
connected_node_variable.name, declare=True)
else:
rel_stmt = self._write_relationship_stmt(rel_path, rel_variable.name,
connected_node_variable.name)
match_result = self.match_stmt.get_cypher(self.parent)
return StatementResult(match_result.cypher + rel_stmt, match_result.returned_var)
def _write_relationship_stmt(self, rel_def: RelPath, rel_variable_name, connected_node_variable_name,
declare=False):
if declare:
return f"{rel_def.left}[{rel_variable_name}:`{rel_def.rel_type}`]{rel_def.right}({connected_node_variable_name}:{rel_def.node_name})"
else:
return f"{rel_def.left}[{rel_variable_name}:`{rel_def.rel_type}`]{rel_def.right}({connected_node_variable_name})"
class WhereStatement(Statement):
def __init__(self, node, where_conditions: "AttributeConditions"):
super().__init__(node)
self.node = node
self.where_conditions = where_conditions
self.cypher = StringIO()
def get_cypher(self, parent: "Statement" = None):
self.parent = parent
variable = self._next_var(self.node)
if self.where_conditions.degree() > 0:
self._write(CypherKeyWords.WHERE.name, space=True)
self._write_where_stmt(StructuredNode, self.where_conditions.and_conditions, CypherKeyWords.AND,
variable.name)
if self.where_conditions.degree() > 1:
self._add_merge_key_word(CypherKeyWords.AND)
self._write_where_stmt(StructuredNode, self.where_conditions.or_conditions, CypherKeyWords.OR,
variable.name)
cypher = self.cypher.getvalue()
if cypher:
cypher += '\n'
if self.child:
child_result = self.child.get_cypher(parent)
return StatementResult(cypher + child_result.cypher, child_result.returned_var)
else:
return StatementResult(cypher, None)
def _write_where_stmt(self, target_type: type, condition_list: list, connector: CypherKeyWords.KeyWord, var: str,
continuation: bool = False):
"""
Write where statement for the current MATCH query
"""
if not condition_list:
return
if connector == CypherKeyWords.OR and len(condition_list) > 1:
self._write('(')
self._write_property_filters(condition_list, connector, target_type, var)
if connector == CypherKeyWords.OR and len(condition_list) > 1:
self._write(') ')
def _write_property_filters(self, condition_list: list, connector: CypherKeyWords.KeyWord, target_type: type,
var: str):
for j, condition in enumerate(condition_list):
if isinstance(condition, RelKeywordArgument):
rel_path, condition = condition
negated, param, operator, v, type = condition
not_ = CypherKeyWords.NOT + ' ' if negated else ''
if type == SearchType.ID:
if is_collection(v):
self._write_id_stmt(not_, var, operator, _convert_nodes_to_ids(target_type, v))
else:
_check_type(v, target_type)
v = _to_id(v)
self._write_id_stmt(not_, var, OPERATORS.EQ, v)
elif type == SearchType.REL_PROP:
rel_type = rel_path.rel_type
self._write_value_stmt(not_, self._next_var(rel_type).name, param, operator,
_change_if_v_not_adequate(v))
else:
if operator == OPERATORS.IN and not isinstance(v, list):
v = list(v) if isinstance(v, tuple) else [v]
self._write_value_stmt(not_, var, param, operator, _change_if_v_not_adequate(v))
if j + 1 < len(condition_list):
self._add_merge_key_word(connector)
def _add_merge_key_word(self, connector: CypherKeyWords.KeyWord):
self._write(connector.name, space=True)
def _write(self, s, space=False):
if space:
self.cypher.write(s + ' ')
else:
self.cypher.write(s)
def _new_line(self):
self._write("\n")
def _write_id_stmt(self, negated: str, variable_name: str, operator: str, value: int):
self._write(f"{negated}ID({variable_name}) {operator} {value} ")
def _write_value_stmt(self, negated: str, variable_name: str, param: str, operator: str, value):
self._write(f"{negated}{variable_name}.{param} {operator} {value} ")
class ReturnStatement(Statement):
def __init__(self, node_detail: NodeRelationshipDetail, filter: "AdvancedNodeSet", without_return=False):
super().__init__(node_detail.cls_name)
self.filter = filter
self.node_detail = node_detail
self.without_return = without_return
self.cypher = StringIO()
def get_cypher(self, parent: "Statement" = None):
self.parent = parent
child_result = self.child.get_cypher(parent)
result = self._get_cypher(child_result.returned_var)
return StatementResult(child_result.cypher + result.cypher, child_result.returned_var)
def _get_cypher(self, variable=None):
aggregate = self.filter._aggregate
if not self.without_return:
if variable is None:
variable = self._next_var(self._node).name
count_records = self.filter._count_records
orderby_params = self.filter._order_by
if not aggregate and not count_records:
orderby_params = self._create_orderby_params(variable, orderby_params)
self._write_return_stmt(variable, aggregate, count_records)
if not aggregate:
self._write_order_by_stmt(orderby_params)
self._write_skip_stmt()
self._write_limit_stmt()
self._write("\n")
return StatementResult(self.cypher.getvalue(), variable)
def _write(self, s, space=True):
if space:
self.cypher.write(s + ' ')
else:
self.cypher.write(s)
def _write_limit_stmt(self):
lmt = self.filter._limit
if lmt:
self._write(f"{CypherKeyWords.LIMIT} {lmt} ")
def _write_skip_stmt(self):
skp = self.filter._skip
if skp:
self._write(f"{CypherKeyWords.SKIP} {skp} ")
def _write_order_by_stmt(self, orderby_params):
if orderby_params:
orderby_stmt = ', '.join([f"{o[0]}.{o[1]} {o[2]}" for o in orderby_params])
self._write(f" {CypherKeyWords.ORDER_BY} {orderby_stmt}")
def _write_return_stmt(self, variable: str, aggregate: Aggregate, count=False):
if aggregate:
self._write(f' {CypherKeyWords.RETURN} {aggregate.name}({variable}.{aggregate.identity[1][1][0]})')
return
self._write_distinct_stmt(variable)
self._write(f' {CypherKeyWords.RETURN.name} ')
if count:
self._write(f' COUNT({variable})')
else:
select = self.filter._select
if select:
self._transform_select(select)
self._write_select_stmt(select, variable)
else:
self._write(variable)
def _transform_select(self, select):
for i, prop in enumerate(select):
if not self._check_if_current_node_property(prop):
if prop == 'id':
select[i] = (True, prop)
else:
raise AttributeError(
f"{self.node_detail.cls_name} does not have property '{prop}'!")
else:
select[i] = (False, prop)
def _write_select_stmt(self, select: list, variable: str):
for i, prop in enumerate(select):
id_prop, prop = prop
if i > 0:
self._write(", ")
if id_prop:
self._write(f"ID({variable}) ")
else:
self._write(f"{variable}.{prop} ")
def _write_distinct_stmt(self, variable: str):
if self.filter._distinct:
self._write(f"{CypherKeyWords.WITH} {CypherKeyWords.DISTINCT} {variable} ")
def _create_orderby_params(self, cls_var, odby):
orderby_params = []
# verify if order_by properties belong to the current node or to some node directly connected with it
for o in odby:
prop, order = o
is_current_node_property = self._check_if_current_node_property(prop)
# check if is a property of a directly connected node
is_directly_connected_node_property = self._check_if_connected_node_property(self.node_detail.cls, prop)
if not is_current_node_property and not is_directly_connected_node_property and prop != 'id':
raise AttributeError(
f"{self.node_detail.cls_name} does not have property '{prop}'!")
orderby_params.append((cls_var, prop, order))
return orderby_params
def _check_if_current_node_property(self, prop_name):
return self.node_detail.is_node_property(prop_name)
def _check_if_connected_node_property(self, clzz, prop_name):
self.node_detail.get_linkedNode_cls(clzz.__name__)
directly_connected_node = _get_node_detail(clzz)
return directly_connected_node.is_node_property(prop_name)
class Conditions:
def __init__(self, and_conditions, or_conditions):
self.and_conditions = and_conditions
self.or_conditions = or_conditions
def __bool__(self):
return len(self.and_conditions) + len(self.or_conditions) > 0
def degree(self):
return int(bool(self.and_conditions)) + int(bool(self.or_conditions))
class RelConditions(Conditions):
def __init__(self):
super().__init__(defaultdict(list), defaultdict(list))
def __bool__(self):
return len(self.and_conditions) + len(self.or_conditions) > 0
def degree(self):
return int(bool(self.and_conditions)) + int(bool(self.or_conditions))
def add(self, key, value, AND=True):
if AND:
self.and_conditions[key].append(value)
else:
self.or_conditions[key].append(value)
def extend(self, key, list_, AND=True):
if AND:
self.and_conditions[key].extend(list_)
else:
self.or_conditions[key].extend(list_)
def merge(self, rel_conditions: "RelConditions"):
def _merge(dictA, dictB):
for k in dictB.keys():
dictA[k].extend(dictB[k])
_merge(self.and_conditions, rel_conditions.and_conditions)
_merge(self.or_conditions, rel_conditions.or_conditions)
class AttributeConditions(Conditions):
def __init__(self, and_conditions=None, or_conditions=None):
super().__init__(and_conditions, or_conditions)
if or_conditions is None:
self.or_conditions = []
if and_conditions is None:
self.and_conditions = []
def __getitem__(self, item):
if item == CypherKeyWords.AND:
return self.and_conditions
return self.or_conditions
def add(self, value, AND=True):
if AND:
self.and_conditions.append(value)
else:
self.or_conditions.append(value)
def merge(self, attr_conditions: "AttributeConditions"):
self.and_conditions.extend(attr_conditions.and_conditions)
self.or_conditions.extend(attr_conditions.or_conditions)
class AttributeRelConditions:
def __init__(self):
# attribute conditions for the current Node
self.rel_conditions = RelConditions()
# relationships directly used by the current Node
self.attr_conditions = AttributeConditions()
def merge(self, conditions):
self.rel_conditions.merge(conditions.rel_conditions)
self.attr_conditions.merge(conditions.attr_conditions)
def add_attr_condition(self, condition, AND=True):
self.attr_conditions.add(condition, AND)
def add_rel_condition(self, key, condition, AND=True):
self.rel_conditions.add(key, condition, AND)
class QueryParser:
def __init__(self, node_cls_detail):
self.node_cls_detail = node_cls_detail
def parse_param_list(self, connector, param_list, negated=False):
param_list = remove_duplication(param_list)
is_AND = connector == CypherKeyWords.AND
conditions = AttributeRelConditions()
for param_v in param_list:
if isinstance(param_v, Q):
conditions.merge(self.parse_param_list(param_v.connector, param_v.children, param_v.negated))
continue
param, v = param_v # e.g: Q(user__username='root') -> param = 'user__username', v = 'root'
if is_collection(v) and not isinstance(v, AdvancedNodeSet):
v = list(v)
split_param = param.split("__")
operator = OPERATORS.EQ # default operator
if self.node_cls_detail.is_node_property(split_param[0]):
param = split_param[0]
if len(split_param) > 1:
# if it is a query like age__gte=10
# convert 'gte' to operator '>='
operator = OPERATORS[split_param[1]]
conditions.add_attr_condition(KeywordArgument(negated, param, operator, v),
is_AND)
elif split_param[0] in ('in_', 'in'):
# e.g: Image.filter(in_=[list of images or list of ids])
conditions.add_attr_condition(KeywordArgument(negated, None, OPERATORS.IN, v, type=SearchType.ID),
is_AND)
elif split_param[0] == 'id':
# e.g: Image.filter(id=1)
conditions.add_attr_condition(KeywordArgument(negated, None, operator, v, type=SearchType.ID),
is_AND)
elif split_param[0].startswith('rel_'):
# search based on relationship property
if len(split_param) > 2:
# e.g: rel_tag__quantity__gte=10.
# The relationship that connects the current node and Tag node has property `quantity` >= 10
operator = OPERATORS[split_param[2]]
rel_kwarg = self._convert_rel_condition_to_argument(split_param[0][4:],
KeywordArgument(negated, split_param[1], operator,
v,
type=SearchType.REL_PROP))
conditions.add_rel_condition(split_param[0][4:], rel_kwarg, is_AND)
else:
# relationship search
if len(split_param) == 1:
if isinstance(v, AdvancedNodeSet):
# e.g: Image.filter(tag=Tag.filter(name='a')) where `tag` is a declared property in Image
# class that represents the relationship between Image and Tag
rel_kwarg = self._convert_rel_condition_to_argument(split_param[0],
KeywordArgument(negated, None, operator, v,
type=SearchType.RECUR_NSET))
else:
# e.g: Image.filter(tag=Tag())
rel_kwarg = self._convert_rel_condition_to_argument(split_param[0],
KeywordArgument(negated, None, operator, v,
type=SearchType.ID))
else:
# e.g: Image.filter(tag__name__startswith='a')
rel_kwarg = self._convert_rel_condition_to_argument(split_param[0],
KeywordArgument(negated,
f"{'__'.join(split_param[1:])}",
operator, v,
type=SearchType.RECUR_PROP))
conditions.add_rel_condition(split_param[0], rel_kwarg, is_AND)
return conditions
def _convert_rel_condition_to_argument(self, connected_node_name, kwarg: KeywordArgument):
rel_kwarg = None
param, v, type = kwarg.parameter, kwarg.value, kwarg.type
if type != SearchType.ID and not self.node_cls_detail.is_node_relationship(connected_node_name):
if type == SearchType.RECUR_NSET:
# There is no defined relationship between Image and Tag in the class Image
# But we have the relationship declared in the class Tag
# So we can do something like: Image.filter(tag=Tag.filter(name='abc'))
detail = _get_node_detail(v.cls)
if detail.is_connected_with(self.node_cls_detail.cls):
rel_path = detail.get_rel_detail(self.node_cls_detail.cls_name, inverse=True)
rel_kwarg = RelKeywordArgument(rel_path, kwarg)
else:
raise ValueError(
f"There is no connection between {self.node_cls_detail.cls_name} and {v.cls.__name__}")
else:
# e.g: Image.filter(tag__name='a')
# e.g: Image.filter(tag=Q(name='a'))
# Note that, Image does not have any property called `tag`,
# but we know that the relationship between Image and tag is declared in the class Tag.
# So we can use Tag class' name as a property.
try:
connected_class = str_to_class(connected_node_name)
detail = _get_node_detail(connected_class)
if detail.is_connected_with(self.node_cls_detail.cls):
rel_path = detail.get_rel_detail(self.node_cls_detail.cls_name, inverse=True)
if type in (SearchType.ID, SearchType.REL_PROP):
# e.g: Image.filter(tag=Tag())
rel_kwarg = RelKeywordArgument(rel_path, kwarg)
else:
# type == SearchType.RECUR_PROP
# e.g: Image.filter(tag__name='a')
rel_kwarg = RelKeywordArgument(rel_path,
KeywordArgument(kwarg.negated,
kwarg.parameter,
kwarg.operator,
detail.cls.filter(
**{param: v})))
else:
self._no_property_error(connected_node_name)
except KeyError:
self._no_property_error(connected_node_name)
else:
rel_path = self.node_cls_detail.get_rel_detail(connected_node_name)
if type == SearchType.RECUR_PROP:
# need to be recursively processed
rel_kwarg = RelKeywordArgument(rel_path,
KeywordArgument(kwarg.negated, kwarg.parameter,
kwarg.operator,
rel_path.cls.filter(**{param: v})))
else:
# type == SearchType.RECUR_NSET
rel_kwarg = RelKeywordArgument(rel_path, kwarg)
return rel_kwarg
def _no_property_error(self, rel):
raise ValueError(
f"There is no property or connected Node called {rel} in {self.node_cls_detail.cls_name}")
class StatementBuilder:
def convert_params_to_statements(self, ast: ASTTree, node_name, conditions: AttributeRelConditions):
if conditions.attr_conditions.degree() > 0:
statement = MatchStatement(node_name)
ast.add_to_last(statement)
where_stmt = WhereStatement(node_name, conditions.attr_conditions)
ast.add_to_last(where_stmt)
def _rel_stmt(conditions, connector):
for key in conditions:
for i, value in enumerate(conditions[key]):
value: RelKeywordArgument = value
if isinstance(value.keyword_argument.value, AdvancedNodeSet):
stmt = RecursiveStatement(value)
ast.add_to_last(stmt)
stmt = RelationStatement(node_name, value)
ast.add_to_last(stmt)
if i + 1 < len(conditions[key]):
merge = MergeStatement(node_name, connector)
ast.add_to_last(merge)
_rel_stmt(conditions.rel_conditions.and_conditions, CypherKeyWords.AND)
_rel_stmt(conditions.rel_conditions.or_conditions, CypherKeyWords.OR)
if conditions.attr_conditions.degree() == 0 and not isinstance(ast.leaf, RelationStatement):
# if there is no where statement for the current node, we can place the match statement at the end
ast.add_to_last(MatchStatement(node_name))
class QueryBuilderResult:
def __init__(self, cypher, returned_var, type_counter):
self.cypher = cypher
self.returned_var = returned_var
self.type_counter = type_counter
class StatementResult:
def __init__(self, cypher, returned_var):
self.cypher = cypher
self.returned_var = returned_var
def _space(space):
return " " if space else ""
def _convert_nodes_to_ids(target_type, nodes):
"""
convert a list of nodes to a list of ids
"""
check = _check_type
if is_collection(nodes):
if nodes:
return [_to_id(e) for e in nodes if check(e, target_type)]
raise ValueError("Empty collection detected")
return nodes
def _to_id(e):
if isinstance(e, int):
return e
else:
return e.id
def _check_type(given_obj, target_type):
"""
check type of given object
"""
if not isinstance(given_obj, StructuredNode) and \
not isinstance(given_obj, target_type) and \
not isinstance(given_obj, int):
raise ValueError(f"Invalid ID values!")
return True
def _change_if_v_not_adequate(v):
if isinstance(v, str):
return f"'{v}'"
if isinstance(v, datetime.datetime):
return v.timestamp()