-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.py
2152 lines (1974 loc) · 79.7 KB
/
core.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
from phrase_structures import *
from phrase_structures import _uniquecount, _count_uniqueness_specified
CMPERS = [CMP(' is between {0[0]} and {0[1]}', '在{0[0]}和{0[1]}之间', ' between {0[0]} and {0[1]}', 1),
CMP(' is equal to {0}', '是{0}', ' = {0}', 2), CMP(' is larger than {0}', '比{0}大', ' > {0}', 3),
CMP(' is smaller than {0}', '比{0}小', ' < {0}', 4), CMP(' is at least {0}', '最低{0}', ' >= {0}', 5),
CMP(' is at most {0}', '最高{0}', ' <= {0}', 6), CMP(' is not {0}', '不等于{0}', ' != {0}', 7),
CMP(' among {0}', '在{0}之中', ' in {0}', 8), CMP('{0}', '{0}', ' like {0}', 9),
CMP(" is not among {0}", '不在{0}之中', ' not in {0} ', 0)]
# these distributions are naturally proportional
num_tables_distribution = {False: transform2distribution_proportional(numpy.array([4361., 2200., 600., 60.])),
True: transform2distribution_proportional(numpy.array([459., 51., 5., 0.01]))}
num_wheres_distribution = {False: transform2distribution_proportional(numpy.array([3300., 2500., 900., 400, 1.])),
True: transform2distribution_proportional(numpy.array([4., 1.5, 0.2,
0.01,
0.]))} # padded each number with 10 to allow extreme queries with 4 where-conditions
num_selected_distribution = transform2distribution_proportional(numpy.array([0., 4800., 1700., 350., 40.]))
AGGR_SUBQDIST = transform2distribution_proportional(
numpy.array([310., 66., 44., 0., 0., 90.])) # only allow max, min, avg
def is_simple_query(qrynp):
phrase = qrynp.np
if len(phrase.table_ids) > 2:
return False
if len(phrase.queried_props) > 3:
return False
for cdt in phrase.cdts:
if isinstance(cdt.right, dict):
return False
if len(phrase.group_props) > 1:
return False
if len(phrase.having_cdts) > 0:
return False
if len(phrase.orderby_props) > 1:
return False
if phrase.np_2 is not None:
return False
return True
def fetch_join_rel(new_tid, table_ids, prop_rels, typenps, propertynps, allow_pseudo_rels=False):
relevant_prop_rels = []
for idx, rel in enumerate(prop_rels):
# allow only those relations whose types are both used in query
# only allow edges from new tid to current tables. (reversed edges assign very little prob, basically
# only when no normal directioned edges exist would reversed edges be sampled from this distribution)
if rel.table_ids[0] in table_ids and rel.table_ids[1] == new_tid:
relevant_prop_rels.append(rel)
elif rel.table_ids[0] == new_tid and rel.table_ids[1] in table_ids:
rel = copy.deepcopy(rel)
rel.score = 0.001
relevant_prop_rels.append(rel)
# if there are actual relations
if len(relevant_prop_rels) > 0:
scores = []
for rel in relevant_prop_rels:
scores.append(rel.score)
scores = numpy.array(scores)
dist = transform2distribution(scores)
try:
fetched_rel = numpy.random.choice(relevant_prop_rels, p=dist)
except Exception as e:
print(e)
raise
# if no actual relations exist
elif allow_pseudo_rels:
left_available_propids = typenps[new_tid].properties
right_available_propids = []
for tid in table_ids:
right_available_propids += typenps[tid].properties
pseudo_rels = []
for pid1 in left_available_propids:
for pid2 in right_available_propids:
if propertynps[pid1].dtype == propertynps[pid2].dtype:
pseudo_rels.append([pid1, pid2])
fetched_rel = random.choice(pseudo_rels)
fetched_rel = PROP_REL(fetched_rel[0], fetched_rel[1], propertynps[fetched_rel[0]].table_id,
propertynps[fetched_rel[1]].table_id, 1)
else:
raise AssertionError
redundant_propid = numpy.random.choice([fetched_rel.prop_ids[0], fetched_rel.prop_ids[1]], p=[0.2, 0.8])
cmper = copy.deepcopy(CMPERS[1]) # always use equality comparer
c_english = propertynps[fetched_rel.prop_ids[0]].c_english.format(
typenps[fetched_rel.table_ids[0]].c_english + '\'s ') + cmper.c_english.format(
propertynps[fetched_rel.prop_ids[1]].c_english.format(typenps[fetched_rel.table_ids[1]].c_english + '\'s '))
c_chinese = propertynps[fetched_rel.prop_ids[0]].c_chinese.format(
typenps[fetched_rel.table_ids[0]].c_chinese + '的') + cmper.c_chinese.format(
propertynps[fetched_rel.prop_ids[1]].c_chinese.format(typenps[fetched_rel.table_ids[1]].c_chinese + '的'))
z = propertynps[fetched_rel.prop_ids[0]].z + cmper.z.format(propertynps[fetched_rel.prop_ids[1]].z)
left = copy.deepcopy(propertynps[fetched_rel.prop_ids[0]])
right = copy.deepcopy(propertynps[fetched_rel.prop_ids[1]])
fetched_cdt = CDT(c_english, c_chinese, z, left, right, cmper)
return fetched_cdt, redundant_propid
# 'in' comparer in where conditions appear only in those occasions with c-i conditions
#
# use_aggr_for_left_prop is equal to true iff it is a having condition
def construct_cv_where_cdt(available_prop_ids, propertynps, typenps, use_aggr_for_left_prop=False, assigned_prop=None,
no_negative=False, type_to_count=None):
if assigned_prop is None:
# the left-value in where conditions cannot have aggregators
scores = [0] * len(available_prop_ids)
for idx, prop_id in enumerate(available_prop_ids):
if propertynps[prop_id].dtype in UNLIKELY_COND_DTYPES:
scores[idx] = -10000
elif propertynps[prop_id].dtype == 'id':
scores[idx] *= 0.3
# explicitly use softmax to convert into a distribution
scores = transform2distribution_softmax(numpy.array(scores))
chosen_prop_id = numpy.random.choice(available_prop_ids, p=scores)
chosen_prop = copy.deepcopy(propertynps[chosen_prop_id])
if use_aggr_for_left_prop:
# assign different distributions for aggregators according to the property dtypes
aggr_id = numpy.random.choice(numpy.arange(len(AGGREGATION_FUNCTIONS)), p=AGGR_DISTS[chosen_prop.dtype])
chosen_prop.set_aggr(aggr_id)
else:
chosen_prop = assigned_prop
# if there are single2multiple foreign key relationships between the multiple tables, the
if chosen_prop.dtype == 'star' and chosen_prop.aggr == 3 and type_to_count is not None:
assert isinstance(type_to_count, TYPENP)
chosen_prop.c_english = ' the number of %s ' % type_to_count.c_english
chosen_prop.c_chinese = '%s的数量' % type_to_count.c_chinese
if chosen_prop.aggr == 3:
assert (AGGREGATION_FUNCTIONS[3] == _uniquecount)
available_values = []
else:
available_values = chosen_prop.values
# for 'COUNT(...)' clauses, '<' and '>' comparison operators are allowed, just as for 'int'
if chosen_prop.aggr == 3:
cmper_distribution = numpy.array(CMP_DISTS['int'])
else:
cmper_distribution = numpy.array(CMP_DISTS[chosen_prop.dtype])
if SETTING in ['spider', 'chisp']:
assert (len(cmper_distribution) == 9)
elif SETTING == 'dusql':
assert len(cmper_distribution) == 10
else:
raise AssertionError
# forbid 'in' and 'not in' for c-v conditions
cmper_distribution[7] = 0
if SETTING == 'dusql':
cmper_distribution[9] = 0
cmper_distribution = transform2distribution_proportional(cmper_distribution)
if SETTING in ['spider', 'chisp']:
cmper = copy.deepcopy(numpy.random.choice(CMPERS[:-1], p=cmper_distribution))
elif SETTING == 'dusql':
cmper = copy.deepcopy(numpy.random.choice(CMPERS, p=cmper_distribution))
else:
raise AssertionError
if cmper.index == 1:
num_values = 2
else:
num_values = 1
if cmper.index == 2 and chosen_prop.dtype in ['int', 'double']:
cmper.c_english = ' is equal to {0}'
cmper.c_chinese = '与{0}相等'
if available_values is None:
raise AssertionError
# print("num_values: ", num_values)
if chosen_prop.aggr != 3:
value = copy.deepcopy(
numpy.random.choice(available_values, num_values,
replace=False)) # object 'value' is list of either length 1 or length 2
if cmper.index == 9:
assert len(value) == 1
v = value[0].z
rho = random.random()
if rho < 0.8:
v = cut_value_for_like(v, mode='mid')
cmper.set_mode('mid')
elif rho < 0.95:
v = cut_value_for_like(v, mode='head')
cmper.set_mode('head')
else:
v = cut_value_for_like(v, mode='tail')
cmper.set_mode('tail')
value = [VALUENP(v.strip('%'), v.strip('%'), v, value[0].dtype)]
else:
count_dist = [0, 100, 150, 40]
count_dist += [0.1] * 97
count_dist[5] += 5
for idx in range(10, 101, 10):
count_dist[idx] += 0.4
count_dist = transform2distribution_proportional(count_dist)
value = random.choices(range(101), k=num_values, weights=count_dist)
for i in range(len(value)):
value[i] = VALUENP(str(value[i]), str(value[i]), str(value[i]), 'int')
if SETTING in ['spider', 'chisp']:
assert cmper.index != 0
# set negative is moved below 'set_mode' in order to avoid 'starts with not xxx'
if cmper.index in [8, 9, 0]:
rho = random.random()
if rho < 0.1 and not no_negative and SETTING != 'dusql':
cmper.set_negative()
if num_values == 1:
if not isinstance(value[0], VALUENP):
raise AssertionError
value_ce = [value[0].c_english]
value_cc = [value[0].c_chinese]
value_z = '#' + value[0].z + '#'
else:
value_ce = []
value_cc = []
value_z = []
if value is None:
raise AssertionError
value.sort() # 'between' requires that the two values are in ascending order
if value is None:
raise AssertionError
for item in value:
value_ce.append(item.c_english)
value_cc.append(item.c_chinese)
value_z.append('#' + item.z + '#')
for i in range(len(value_ce)):
if value_ce[i].strip('\'\"') == 'T':
value_ce[i] = '\"True\"'
elif value_ce[i].strip('\'\"') == 'F':
value_ce[i] = '\"False\"'
if value_cc[i].strip('\'\"') == 'T':
value_cc[i] = '\"真\"'
elif value_cc[i].strip('\'\"') == 'F':
value_cc[i] = '\"假\"'
if '年份' in chosen_prop.c_chinese.format(''):
year_flag = True
for v in value_cc:
if not contains_4digits(v):
year_flag = False
if year_flag:
if cmper.index == 3:
cmper.c_chinese = '比{0}晚'
elif cmper.index == 4:
cmper.c_chinese = '比{0}早'
if 'year' in chosen_prop.c_english.format(''):
year_flag = True
for v in value_ce:
if not contains_4digits(v):
year_flag = False
if year_flag:
if cmper.index == 3:
cmper.c_english = ' is after {0}'
elif cmper.index == 4:
cmper.c_english = ' is before {0}'
if len(value_ce) == 1:
assert len(value_cc) == 1
value_ce = value_ce[0]
value_cc = value_cc[0]
if chosen_prop.dtype not in ['star']:
c_english = chosen_prop.c_english.format(
typenps[chosen_prop.table_id].c_english+'\'s ') + cmper.c_english.format(value_ce)
c_chinese = chosen_prop.c_chinese.format(
typenps[chosen_prop.table_id].c_chinese+'的') + cmper.c_chinese.format(value_cc)
else:
c_english = chosen_prop.c_english.format('') + cmper.c_english.format(value_ce)
c_chinese = chosen_prop.c_chinese.format('') + cmper.c_chinese.format(value_cc)
z = chosen_prop.z + ' ' + cmper.z.format(value_z)
cdt = CDT(c_english, c_chinese, z, chosen_prop, value, cmper)
return cdt
def construct_cc_where_cdt(available_prop_ids, propertynps, typenps, prop_mat, use_aggr_for_left_prop=False):
left_prop_id, right_prop_id = choose_proppair_for_cdt(available_prop_ids, available_prop_ids, propertynps, prop_mat)
if left_prop_id is None and right_prop_id is None:
return None
left_prop = copy.deepcopy(propertynps[left_prop_id])
right_prop = copy.deepcopy(propertynps[right_prop_id])
# there must not be aggregators in where conditions
assert (left_prop.aggr == 0)
assert (right_prop.aggr == 0)
if use_aggr_for_left_prop:
# assign different distributions for aggregators according to the property dtypes
aggr_id = numpy.random.choice(numpy.arange(len(AGGREGATION_FUNCTIONS)), p=AGGR_DISTS[left_prop.dtype])
left_prop.set_aggr(aggr_id)
# does not allow for 'between' comparer for column-column conditions or column-subquery conditions
cmper_distribution = transform2distribution_proportional(numpy.array(CMP_DISTS[left_prop.dtype][1:]))
cmper_distribution[6] = 0
cmper_distribution[7] = 0 # like operator at index 9-1-1=7 can never appear in c-c or c-i conditions
cmper_distribution = transform2distribution_proportional(cmper_distribution)
if SETTING in ['spider', 'chisp']:
cmper = copy.deepcopy(numpy.random.choice(CMPERS[1:-1], p=cmper_distribution))
elif SETTING == 'dusql':
cmper = copy.deepcopy(numpy.random.choice(CMPERS[1:], p=cmper_distribution))
else:
raise AssertionError
if SETTING in ['spider', 'chisp']:
assert cmper.index != 0
if cmper.index in [8, 9, 0]:
rho = random.random()
if rho < 0.1 and SETTING != 'dusql':
cmper.set_negative()
if '年份' in left_prop.c_chinese.format(''):
random_value = random.choice(left_prop.values)
if contains_4digits(random_value.z):
year_flag = True
else:
year_flag = False
if year_flag:
if cmper.index == 3:
cmper.c_chinese = '比{0}晚'
elif cmper.index == 4:
cmper.c_chinese = '比{0}早'
if left_prop.dtype not in ['star']:
c_english = left_prop.c_english.format(typenps[left_prop.table_id].c_english+'\'s ') + \
cmper.c_english.format(right_prop.c_english.format(typenps[right_prop.table_id].c_english+'\'s '))
c_chinese = left_prop.c_chinese.format(typenps[left_prop.table_id].c_chinese+'的') + \
cmper.c_chinese.format(right_prop.c_chinese.format(typenps[right_prop.table_id].c_chinese+'的'))
else:
c_english = left_prop.c_english.format('') + \
cmper.c_english.format(right_prop.c_english.format(''))
c_chinese = left_prop.c_chinese.format('') + \
cmper.c_chinese.format(right_prop.c_chinese.format(''))
cdt = CDT(c_english, c_chinese, None, left_prop, right_prop, cmper)
if 'year' in left_prop.c_english.format(''):
random_value = random.choice(left_prop.values)
if contains_4digits(random_value.z):
year_flag = True
else:
year_flag = False
if year_flag:
c_english.replace('is smaller than', 'is before')
c_english.replace('is larger than', 'is after')
return cdt
# sub-queries can be either around properties with foreign key relations or same names, but rarely anything else
def construct_ci_where_cdt(available_prop_ids, typenps, propertynps, type_mat, prop_mat, prop_rels, fk_rels,
use_aggr_for_left_prop=False, cursor=None, no_negative=False, verbose=False):
# only allow those with actual values
all_prop_ids = []
for i in range(len(propertynps)):
if propertynps[i].valid:
all_prop_ids.append(i)
assert len(all_prop_ids) > 0
left_prop_id, right_prop_id = choose_proppair_for_cdt(available_prop_ids, all_prop_ids, propertynps, prop_mat)
if left_prop_id is None and right_prop_id is None:
return None
left_prop = copy.deepcopy(propertynps[left_prop_id])
# does not allow for 'between' comparer for column-column conditions or column-subquery conditions
cmper_distribution = transform2distribution_proportional(numpy.array(CMP_DISTS[left_prop.dtype][1:]))
cmper_distribution[7] = 0 # like operator at index 9-1-1=7 can never appear in c-c or c-i conditions
cmper = None
if left_prop.dtype in CALCULABLE_DTYPES:
if SETTING in ['spider', 'chisp']:
cmper = copy.deepcopy(numpy.random.choice(CMPERS[1:-1], p=cmper_distribution))
elif SETTING in ['dusql']:
cmper = copy.deepcopy(numpy.random.choice(CMPERS[1:], p=cmper_distribution))
else:
raise AssertionError
else:
for item in CMPERS:
if SETTING in ['spider', 'chisp']:
if item.index == 8: # if the comparer is 'in'
cmper = copy.deepcopy(item)
elif SETTING == 'dusql':
if item.index in [8, 0]: # if the comparer is 'in' or 'not in'
cmper = copy.deepcopy(item)
else:
raise AssertionError
assert (cmper is not None)
if SETTING in ['spider', 'chisp']:
assert cmper.index != 0
if cmper.index in [8, 9, 0]:
rho = random.random()
if rho < 0.1 and not no_negative and SETTING != 'dusql':
cmper.set_negative()
# the aggregators can only be max, min or avg (means can't have aggregator for non-number dtypes)
if cmper.index != 8: # if comparer is not 'in'
use_aggr = numpy.random.choice(numpy.arange(len(AGGREGATION_FUNCTIONS)), p=AGGR_SUBQDIST)
else:
use_aggr = 0
prop4right_subq = copy.deepcopy(propertynps[right_prop_id])
prop4right_subq.set_aggr(use_aggr)
right_subq_np, right_subq_qrynp = scratch_build(typenps, propertynps, type_mat, prop_mat, prop_rels, fk_rels,
is_recursive=True,
specific_props=[prop4right_subq], cursor=cursor,
require_singlereturn=(cmper.index != 8), print_verbose=verbose,
is_recur=True)
if use_aggr_for_left_prop:
# assign different distributions for aggregators according to the property dtypes
aggr_id = numpy.random.choice(numpy.arange(len(AGGREGATION_FUNCTIONS)), p=AGGR_DISTS[left_prop.dtype])
left_prop.set_aggr(aggr_id)
if '年份' in left_prop.c_chinese.format(''):
random_value = random.choice(left_prop.values)
if contains_4digits(random_value.z):
year_flag = True
else:
year_flag = False
if year_flag:
if cmper.index == 3:
cmper.c_chinese = '比{0}晚'
elif cmper.index == 4:
cmper.c_chinese = '比{0}早'
if left_prop.dtype not in ['star']:
c_english = left_prop.c_english.format(typenps[left_prop.table_id].c_english+'\'s ') + cmper.c_english.format(
' ( ' + right_subq_qrynp.c_english + ' ) ')
c_chinese = left_prop.c_chinese.format(typenps[left_prop.table_id].c_chinese+'的') + \
cmper.c_chinese.format('(' + right_subq_qrynp.c_chinese + ')')
else:
c_english = left_prop.c_english.format('') + cmper.c_english.format(
' ( ' + right_subq_qrynp.c_english + ' ) ')
c_chinese = left_prop.c_chinese.format('') + \
cmper.c_chinese.format('(' + right_subq_qrynp.c_chinese + ')')
if 'year' in left_prop.c_english.format(''):
random_value = random.choice(left_prop.values)
if contains_4digits(random_value.z):
year_flag = True
else:
year_flag = False
if year_flag:
c_english.replace('is smaller than', 'is before')
c_english.replace('is larger than', 'is after')
z = left_prop.z + cmper.z.format(' ( ' + right_subq_qrynp.z + ' ) ')
cdt = CDT(c_english, c_chinese, z, left_prop, right_subq_qrynp, cmper)
return cdt
# convert a query in json format into a NP type object
# pid needs to +1 because 0 is occupied by * in SPIDER format
def np_from_entry(entry_sql, typenps, propertynps, fk_rels, finalize=False, is_recur=False):
table_ids = []
for item in entry_sql['from']['table_units']:
if item[0] == 'sql':
return "'from' not a table!"
elif item[0] == 'table_unit':
table_ids.append(item[1])
else:
raise AssertionError
join_cdts = []
for cond in entry_sql['from']['conds']:
if isinstance(cond, str):
assert cond == 'and'
continue
assert cond[1] == 2
assert cond[2][0] == 0 and cond[2][1][0] == 0 and cond[2][1][2] is False and cond[2][2] is None
assert cond[3][0] == 0 and cond[3][2] is False
pid1 = cond[2][1][1] - 1
pid2 = cond[3][1] - 1
assert pid1 >= 0 and pid2 >= 0
prop1 = copy.deepcopy(propertynps[pid1])
prop2 = copy.deepcopy(propertynps[pid2])
cmper = copy.deepcopy(CMPERS[1]) # always use equality comparer
c_english = propertynps[pid1].c_english.format(
typenps[prop1.table_id].c_english + '\'s ') + cmper.c_english.format(
propertynps[pid2].c_english.format(typenps[prop2.table_id].c_english + '\'s '))
c_chinese = propertynps[pid1].c_chinese.format(
typenps[prop1.table_id].c_chinese + '的') + cmper.c_chinese.format(
propertynps[pid2].c_chinese.format(typenps[prop2.table_id].c_chinese + '的'))
z = propertynps[pid1].z + cmper.z.format(propertynps[pid2].z)
fetched_cdt = CDT(c_english, c_chinese, z, prop1, prop2, cmper)
join_cdts.append(fetched_cdt)
tids_is_left = {item: False for item in table_ids}
tids_is_right = {item: False for item in table_ids}
for item in join_cdts:
if item.left.is_fk_left and item.right.is_fk_right:
tids_is_left[item.left.table_id] = True
tids_is_right[item.right.table_id] = True
elif item.left.is_fk_right and item.right.is_fk_left:
tids_is_left[item.right.table_id] = True
tids_is_right[item.left.table_id] = True
main_tid = []
join_simplifiable = True
if len(table_ids) > 1:
for tid in table_ids:
if tids_is_left[tid] is True and tids_is_right[tid] is False:
if len(main_tid) > 0:
print("!")
main_tid.append(tid)
# for cases where it's about two instances of the same table
elif len(tids_is_left) == 1 and len(tids_is_right) == 1:
main_tid.append(tid)
join_simplifiable = False
# if medium tables exist or multiple instances of same table exist, join conditions cannot be simplified
# because it'll lose the dependency hierarchy
elif tids_is_left[tid] is True and tids_is_right[tid] is True:
join_simplifiable = False
else:
main_tid = [table_ids[0]]
# check whether the tables joined together have multiple foreign-key reations, if so, then it's not simplifiable
if join_simplifiable and len(main_tid) > 0:
for item in join_cdts:
tid1 = item.left.table_id
tid2 = item.right.table_id
join_cdts_cnt = 0
for rel in fk_rels:
if rel.table_ids[0] == tid1 and rel.table_ids[1] == tid2:
join_cdts_cnt += 1
elif rel.table_ids[0] == tid2 and rel.table_ids[1] == tid1:
join_cdts_cnt += 1
# if there are multiple foreign key relationships between table pairs in this query, then by simplifying
# canonical utterance of join conditions ambiguity would occur
if join_cdts_cnt > 1:
join_simplifiable = False
queried_props = []
for item in entry_sql['select'][1]:
aggr = item[0]
if item[1][0] != 0:
return "calculation operator in select!"
pid = item[1][1][1] - 1
aggr_distinct = item[1][1][2]
assert item[1][2] is None
if pid < 0:
prop = copy.deepcopy(STAR_PROP)
prop.table_id = table_ids
assert aggr_distinct is False
else:
prop = copy.deepcopy(propertynps[pid]) # !!!
if aggr == 3:
prop.set_aggr(3, function=_count_uniqueness_specified, distinct=aggr_distinct)
if pid < 0:
# if there are single2multiple foreign key relationships between the multiple tables
#
# if there are multiple join-on heads, then it'd be unclear which one is to be counted,
# in such cases we rollback to using traditional 'number of entries'
if len(main_tid) == 1:
type_to_count = typenps[main_tid[0]]
prop.c_english = ' the number of %s ' % type_to_count.c_english
prop.c_chinese = '%s的数量' % type_to_count.c_chinese
else:
prop.set_aggr(aggr)
queried_props.append(prop)
cdts = []
cdt_linkers = []
for cond in entry_sql['where']:
if isinstance(cond, str):
assert cond == 'or' or cond == 'and'
cdt_linkers.append(cond)
continue
negative = cond[0]
cmper = None
cmper_idx = cond[1]
for item in CMPERS:
if item.index == cmper_idx:
cmper = copy.deepcopy(item)
break
assert cmper is not None
if cmper_idx == 9:
print(str(cond[3]))
if str(cond[3]).count('%') == 2:
cmper.set_mode('mid')
elif str(cond[3])[1] == '%':
cmper.set_mode('tail')
elif str(cond[3])[-2] == '%':
cmper.set_mode('head')
elif '%' not in str(cond[3]):
cmper.set_mode('mid')
else:
raise AssertionError
if negative and SETTING != 'dusql':
cmper.set_negative()
# does not support calculation operators
if cond[2][0] != 0:
return "calculation operator in 'where'!"
pid1 = cond[2][1][1] - 1
assert cond[2][1][0] == 0 and cond[2][1][2] is False and cond[2][2] is None
assert pid1 >= 0
chosen_prop = copy.deepcopy(propertynps[pid1])
value = cond[3]
if isinstance(value, list):
assert len(value) == 3
assert cond[4] is None
pid2 = value[1] - 1
assert pid2 >= 0
prop2 = copy.deepcopy(propertynps[pid2])
c_english = chosen_prop.c_english.format('') + cmper.c_english.format(prop2.c_english.format(''))
c_chinese = chosen_prop.c_chinese.format('') + cmper.c_chinese.format(prop2.c_chinese.format(''))
cdt = CDT(c_english, c_chinese, None, chosen_prop, prop2, cmper)
cdts.append(cdt)
elif isinstance(value, dict):
if cond[4] is not None:
return "between operator with sub-query and value!"
try:
pack = np_from_entry(value, typenps, propertynps, fk_rels, is_recur=is_recur)
except KeyError as e:
raise
if isinstance(pack, str):
return pack
else:
np_2, qrynp_2 = pack
c_english = chosen_prop.c_english.format('') + cmper.c_english.format(
' ( ' + qrynp_2.c_english + ' ) ')
c_chinese = chosen_prop.c_chinese.format('') + cmper.c_chinese.format('(' + qrynp_2.c_chinese + ')')
z = chosen_prop.z + cmper.z.format(' ( ' + qrynp_2.z + ' ) ')
cdt = CDT(c_english, c_chinese, z, chosen_prop, qrynp_2, cmper)
cdts.append(cdt)
else:
try:
value = VALUENP(str(value), str(value), str(value), chosen_prop.dtype)
value_z = '#' + value.z + '#'
value_str = value.z
except Exception as e:
raise
if cond[4] is not None:
try:
value_2 = cond[4]
value_2 = VALUENP(str(value_2), str(value_2), str(value_2), chosen_prop.dtype)
value_z_2 = '#' + value_2.z + '#'
value_str_2 = value_2.z
except Exception as e:
raise
value = [value, value_2]
value_str = [value_str, value_str_2]
value_z = [value_z, value_z_2]
else:
value = [value]
c_english = chosen_prop.c_english.format('') + cmper.c_english.format(value_str)
c_chinese = chosen_prop.c_chinese.format('') + cmper.c_chinese.format(value_str)
z = chosen_prop.z + ' ' + cmper.z.format(value_z)
cdt = CDT(c_english, c_chinese, z, chosen_prop, value, cmper)
cdts.append(cdt)
if len(cdts) > 0:
assert len(cdts) == (len(cdt_linkers) + 1)
group_props = []
for item in entry_sql['groupBy']:
assert item[0] == 0 and item[2] is False
gb_pid = item[1] - 1
assert gb_pid >= 0
gb_prop = copy.deepcopy(propertynps[gb_pid])
group_props.append(gb_prop)
having_cdts = []
if len(entry_sql['having']) > 1:
return "more than one having condition!"
for cond in entry_sql['having']:
assert cond[0] is False
cmper = None
cmper_idx = cond[1]
for item in CMPERS:
if item.index == cmper_idx:
cmper = copy.deepcopy(item)
assert cmper is not None
# does not support calculation operators
if cond[2][0] != 0:
return "calculation operator in 'having' condition!"
pid1 = cond[2][1][1] - 1
aggr = cond[2][1][0]
aggr_distinct = cond[2][1][2]
if pid1 < 0:
chosen_prop = copy.deepcopy(STAR_PROP)
chosen_prop.table_id = table_ids
assert aggr_distinct is False
else:
chosen_prop = copy.deepcopy(propertynps[pid1])
if aggr == 3:
chosen_prop.set_aggr(3, function=_count_uniqueness_specified, distinct=aggr_distinct)
if pid1 < 0:
# if there are single2multiple foreign key relationships between the multiple tables, the
if len(main_tid) == 1:
type_to_count = typenps[main_tid[0]]
chosen_prop.c_english = ' the number of %s ' % type_to_count.c_english
chosen_prop.c_chinese = '%s的数量' % type_to_count.c_chinese
else:
chosen_prop.set_aggr(aggr)
value = cond[3]
assert not isinstance(value, list)
if isinstance(value, dict):
assert cond[4] is None
try:
np_2, qrynp_2 = np_from_entry(value, typenps, propertynps, fk_rels, is_recur=True)
except KeyError as e:
raise
c_english = chosen_prop.c_english.format('') + cmper.c_english.format(
' ( ' + qrynp_2.c_english + ' ) ')
c_chinese = chosen_prop.c_chinese.format('') + cmper.c_chinese.format('(' + qrynp_2.c_chinese + ')')
z = chosen_prop.z + cmper.z.format(' ( ' + qrynp_2.z + ' ) ')
cdt = CDT(c_english, c_chinese, z, chosen_prop, qrynp_2, cmper)
having_cdts.append(cdt)
else:
try:
value = VALUENP(str(value), str(value), str(value), chosen_prop.dtype)
value_z = '#' + value.z + '#'
value_str = value.z
except Exception as e:
raise
if cond[4] is not None:
try:
value_2 = cond[4]
value_2 = VALUENP(str(value_2), str(value_2), str(value_2), chosen_prop.dtype)
value_z_2 = '#' + value_2.z + '#'
value_str_2 = value_2.z
except Exception as e:
raise
value = [value, value_2]
value_str = [value_str, value_str_2]
value_z = [value_z, value_z_2]
else:
value = [value]
c_english = chosen_prop.c_english.format('') + cmper.c_english.format(value_str)
c_chinese = chosen_prop.c_chinese.format('') + cmper.c_chinese.format(value_str)
z = chosen_prop.z + ' ' + cmper.z.format(value_z)
cdt = CDT(c_english, c_chinese, z, chosen_prop, value, cmper)
having_cdts.append(cdt)
orderby_props = []
orderby_order = None
if len(entry_sql['orderBy']) > 0:
orderby_order = entry_sql['orderBy'][0]
for item in entry_sql['orderBy'][1]:
if item[0] != 0:
return "calculation in 'orderBy' condition!"
if item[1][2] is not False:
pass
aggr = item[1][0]
ob_pid = item[1][1] - 1
if ob_pid < 0:
ob_prop = copy.deepcopy(STAR_PROP)
ob_prop.table_id = table_ids
else:
ob_prop = copy.deepcopy(propertynps[ob_pid])
if aggr == 3:
ob_prop.set_aggr(3, function=_count_uniqueness_specified, distinct=False)
if ob_pid < 0:
# if there are single2multiple foreign key relationships between the multiple tables, the
if len(main_tid) == 1:
type_to_count = typenps[main_tid[0]]
ob_prop.c_english = ' the number of %s ' % type_to_count.c_english
ob_prop.c_chinese = '%s的数量' % type_to_count.c_chinese
else:
ob_prop.set_aggr(aggr)
orderby_props.append(ob_prop)
else:
orderby_props = None
limit = entry_sql['limit']
has_union = False
has_except = False
has_intersect = False
np_2 = None
qrynp_2 = None
if entry_sql['intersect'] is not None:
assert entry_sql['union'] is None and entry_sql['except'] is None
try:
pack = np_from_entry(entry_sql['intersect'], typenps, propertynps, fk_rels, is_recur=is_recur)
has_intersect = True
except KeyError as e:
raise
if isinstance(pack, str):
return pack
else:
np_2, qrynp_2 = pack
if entry_sql['union'] is not None:
assert entry_sql['intersect'] is None and entry_sql['except'] is None
try:
pack = np_from_entry(entry_sql['union'], typenps, propertynps, fk_rels, is_recur=is_recur)
has_union = True
except KeyError as e:
raise
if isinstance(pack, str):
return pack
else:
np_2, qrynp_2 = pack
if entry_sql['except'] is not None:
assert entry_sql['union'] is None and entry_sql['intersect'] is None
try:
pack = np_from_entry(entry_sql['except'], typenps, propertynps, fk_rels, is_recur=is_recur)
has_except = True
except KeyError as e:
raise
if isinstance(pack, str):
return pack
else:
np_2, qrynp_2 = pack
distinct = entry_sql['select'][0]
if not join_simplifiable:
main_tid = []
final_np = NP(queried_props=queried_props, table_ids=table_ids, join_cdts=join_cdts, cdts=cdts,
cdt_linkers=cdt_linkers, group_props=group_props, having_cdts=having_cdts,
orderby_props=orderby_props,
orderby_order=orderby_order, limit=limit, np_2=np_2, qrynp_2=qrynp_2, has_union=has_union,
has_except=has_except, has_intersect=has_intersect, distinct=distinct, main_tids=main_tid)
final_qrynp = QRYNP(final_np, typenps=typenps, propertynps=propertynps, finalize_sequence=finalize,
is_recur=is_recur)
return final_np, final_qrynp
# convert a query in json format into a NP type object
# pid needs to +1 because 0 is occupied by * in SPIDER format
def np_from_entry_dusql(entry_sql, typenps, propertynps, fk_rels, finalize=False, is_recur=False):
table_ids = []
for item in entry_sql['from']['table_units']:
if item[0] == 'sql':
return "'from' not a table!"
elif item[0] == 'table_unit':
table_ids.append(item[1])
else:
raise AssertionError
join_cdts = []
for cond in entry_sql['from']['conds']:
if isinstance(cond, str):
assert cond == 'and'
continue
assert cond[1] == 2
assert cond[2][0] == 0 and cond[2][1][0] == 0 and cond[2][2] is None
pid1 = cond[2][1][1] - 1
pid2 = cond[3] - 1
assert pid1 >= 0 and pid2 >= 0
prop1 = copy.deepcopy(propertynps[pid1])
prop2 = copy.deepcopy(propertynps[pid2])
cmper = copy.deepcopy(CMPERS[1]) # always use equality comparer
c_english = propertynps[pid1].c_english.format(
typenps[prop1.table_id].c_english + '\'s ') + cmper.c_english.format(
propertynps[pid2].c_english.format(typenps[prop2.table_id].c_english + '\'s '))
c_chinese = propertynps[pid1].c_chinese.format(
typenps[prop1.table_id].c_chinese + '的') + cmper.c_chinese.format(
propertynps[pid2].c_chinese.format(typenps[prop2.table_id].c_chinese + '的'))
z = propertynps[pid1].z + cmper.z.format(propertynps[pid2].z)
fetched_cdt = CDT(c_english, c_chinese, z, prop1, prop2, cmper)
join_cdts.append(fetched_cdt)
tids_is_left = {item: False for item in table_ids}
tids_is_right = {item: False for item in table_ids}
for item in join_cdts:
if item.left.is_fk_left and item.right.is_fk_right:
tids_is_left[item.left.table_id] = True
tids_is_right[item.right.table_id] = True
elif item.left.is_fk_right and item.right.is_fk_left:
tids_is_left[item.right.table_id] = True
tids_is_right[item.left.table_id] = True
main_tid = []
join_simplifiable = True
if len(table_ids) > 1:
for tid in table_ids:
if tids_is_left[tid] is True and tids_is_right[tid] is False:
if len(main_tid) > 0:
print("!")
main_tid.append(tid)
# for cases where it's about two instances of the same table
elif len(tids_is_left) == 1 and len(tids_is_right) == 1:
main_tid.append(tid)
join_simplifiable = False
# if medium tables exist or multiple instances of same table exist, join conditions cannot be simplified
# because it'll lose the dependency hierarchy
elif tids_is_left[tid] is True and tids_is_right[tid] is True:
join_simplifiable = False
else:
main_tid = [table_ids[0]]
# check whether the tables joined together have multiple foreign-key reations, if so, then it's not simplifiable
if join_simplifiable and len(main_tid) > 0:
for item in join_cdts:
tid1 = item.left.table_id
tid2 = item.right.table_id
join_cdts_cnt = 0
for rel in fk_rels:
if rel.table_ids[0] == tid1 and rel.table_ids[1] == tid2:
join_cdts_cnt += 1
elif rel.table_ids[0] == tid2 and rel.table_ids[1] == tid1:
join_cdts_cnt += 1
# if there are multiple foreign key relationships between table pairs in this query, then by simplifying
# canonical utterance of join conditions ambiguity would occur
if join_cdts_cnt > 1:
join_simplifiable = False
queried_props = []
for item in entry_sql['select']:
aggr = item[0]
if item[1][0] != 0:
return "calculation operator in select!"
pid = item[1][1][1] - 1
assert item[1][2] is None
if pid < 0:
prop = copy.deepcopy(STAR_PROP)
prop.table_id = table_ids
else:
prop = copy.deepcopy(propertynps[pid]) # !!!
if aggr == 3:
prop.set_aggr(3, function=_count_uniqueness_specified, distinct=False)
if pid < 0:
# if there are single2multiple foreign key relationships between the multiple tables
#
# if there are multiple join-on heads, then it'd be unclear which one is to be counted,
# in such cases we rollback to using traditional 'number of entries'
if len(main_tid) == 1:
type_to_count = typenps[main_tid[0]]
prop.c_english = ' the number of %s ' % type_to_count.c_english
prop.c_chinese = '%s的数量' % type_to_count.c_chinese
else:
prop.set_aggr(aggr)
queried_props.append(prop)
cdts = []
cdt_linkers = []
for cond in entry_sql['where']:
if isinstance(cond, str):
assert cond == 'or' or cond == 'and'
cdt_linkers.append(cond)
continue
cmper = None
cmper_idx = cond[1]
for item in CMPERS:
if item.index == cmper_idx:
cmper = copy.deepcopy(item)
break
if cmper is None:
print(cmper_idx)
raise AssertionError
if cmper_idx == 0:
print("cmper_idx 0!")
if cmper_idx == 9:
print(str(cond[3]))
if len(str(cond[3])) == 1:
cmper.set_mode('equal')
elif str(cond[3]).count('%') == 2:
cmper.set_mode('mid')
elif str(cond[3])[1] == '%':
cmper.set_mode('tail')
elif str(cond[3])[-2] == '%':
cmper.set_mode('head')
elif '%' not in str(cond[3]):
cmper.set_mode('mid')
else:
raise AssertionError
# does not support calculation operators
if cond[2][0] != 0:
return "calculation operator in 'where'!"
pid1 = cond[2][1][1] - 1
assert cond[2][1][0] == 0 and cond[2][2] is None
assert pid1 >= 0
chosen_prop = copy.deepcopy(propertynps[pid1])
value = cond[3]
# should be impossible
if isinstance(value, list):
raise AssertionError
assert len(value) == 3
assert cond[4] is None
pid2 = value[1] - 1
assert pid2 >= 0
prop2 = copy.deepcopy(propertynps[pid2])
c_english = chosen_prop.c_english.format('') + cmper.c_english.format(prop2.c_english.format(''))
c_chinese = chosen_prop.c_chinese.format('') + cmper.c_chinese.format(prop2.c_chinese.format(''))
cdt = CDT(c_english, c_chinese, None, chosen_prop, prop2, cmper)
cdts.append(cdt)
elif isinstance(value, dict):
if cond[4] is not None: