-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgrammar.py
1560 lines (1264 loc) · 58.7 KB
/
grammar.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
"""
Usage: grammar.py DATASET DATAPATH MODE DB [options]
Run a simple SCFG grammar given an input DB
Arguments:
DATASET String name of dataset [default: spider]
DATAPATH String path to dir containing tables.json [default: data/spider]
MODE String status "all" or "one" for running tests on all db's or only one specified in arg DB below [default: one]
DB String name of DB to work with (e.g. "allergy_1") or "random" to randomly choose [default: random]
Options:
--debug Enable debug-level logging.
#Unsupported features to implement:
Example:
python grammar.py spider data/spider all random <----- this one to generate them all!
python grammar.py spider data/spider one random
python grammar.py spider data/spider one allergy_1
python grammar.py spider data/spider one sakila_1
"""
from docopt import docopt
import logging
import logzero
from logzero import logger as log
import random
import time
import string
from collections import defaultdict
import json
import os
from pathlib import Path
from src.data_processor.schema_loader import load_schema_graphs_spider
######## Global SCFG variables ########
q1 = 'Select'
w_all = 'all columns'
w_distinct = 'unique'
w_from = 'from' #of
w_where = 'when'
w_and = 'and'
w_equals = 'equals'
w_max = 'maximum'
w_min = 'minimum'
w_sum = 'the sum of'
w_count = 'the number of'
w_avg = 'the average value of'
w_orderby = random.choice(['ordered by', 'sorted by' ])
w_groupby = 'grouped by'
w_asc = 'in ascending order'
w_desc = 'in descending order'
w_like_start = 'starts with'
w_like_end= 'ends with'
w_not_like_start = 'does not start with'
w_not_like_end = 'does not end with'
w_having = 'with' #'having'
w_between = 'is between'
w_exists = 'there is a result for'
w_not_in = 'is not in'
w_is_in = 'is in'
#skip any tables or coluns with this name
sql_stopwords = ['and', 'as', 'asc', 'between', 'case', 'collate_nocase', 'cross_join', 'desc', 'else', 'end', 'from',
'full_join', 'full_outer_join', 'group_by', 'having', 'in', 'inner_join', 'is', 'is_not', 'join',
'left_join', 'left_outer_join', 'like', 'limit', 'none', 'not_between', 'not_in', 'not_like', 'offset',
'on', 'or', 'order_by', 'reserved', 'right_join', 'right_outer_join', 'select', 'then', 'union',
'union_all', 'except', 'intersect', 'using', 'when', 'where', 'binary_ops', 'unary_ops', 'with',
'durations', 'max', 'min', 'count', 'sum', 'avg']
random.seed(27)
#######################################
def aliasTable2TrueTableLUT(db):
alias2TrueTableDict = {} #badalias: (truealias, true_table)
"""
'get_table',
'get_table_by_name', 'get_table_id', 'get_table_scopes', 'index_table', 'indexed_table',
'is_table_name',
'node_index', 'node_rev_index',
'table_index',
'table_names', 'table_rev_index']
"""
for alias, i in db.table_index.items():
true_table_name = db.node_rev_index[i].name
true_alias = db.node_rev_index[i].normalized_name
alias2TrueTableDict[alias] = (true_alias, true_table_name)
return alias2TrueTableDict
def remove_prefix(text, prefix):
return text[text.startswith(prefix) and len(prefix):]
def badCol(column_name):
for p in string.punctuation:
if column_name.endswith(p) or column_name.startswith(p):
return True
return False
def getColAlias(db, table_name, true_col_name):
#print(f"db: {db}, table_name: {table_name}, true_col_name: {true_col_name}")
table1_index = db.table_index[table_name] # get the int for the table name
unflattened_relevant_column_indexs = db.get_current_schema_layout(
tables=[table1_index]) # [table1_index] # get the field ints for the table
relevant_column_indexs = [item for sublist in unflattened_relevant_column_indexs for item in sublist]
for colinx, field_info in zip(relevant_column_indexs, db.get_table(table1_index).fields):
col = db.get_field(colinx)
if true_col_name == col.name:
return col.normalized_name
return true_col_name
def getColsAndTypes(db, table_name):
#print(f"table name: {table_name}")
table1_index = db.table_index[table_name] # get the int for the table name
#print(f"table1_index: {table1_index}")
unflattened_relevant_column_indexs = db.get_current_schema_layout(tables=[table1_index]) # [table1_index] # get the field ints for the table
relevant_column_indexs = [item for sublist in unflattened_relevant_column_indexs for item in sublist]
column_candidates = [] #cleaned column names for relevant table
keep_column_indexes = [] #list of ints refering to column indexs. Will usually be the same as relevant_column_indexes
keep_column_types = []
for colinx, field_info in zip(relevant_column_indexs, db.get_table(table1_index).fields):
col = db.get_field(colinx)
#print(col.normalized_name) alias name
column_name = col.name
data_type = field_info.data_type
if " " not in column_name and column_name.lower() not in sql_stopwords and badCol(column_name) is False:
#skip problematic columns like 'Home Town' that break official Spider evaluation script.
column_candidates.append(column_name)
keep_column_indexes.append(colinx)
keep_column_types.append(data_type)
assert len(column_candidates) == len(keep_column_indexes) #each candidate column should have an associated type, or something is wrong
assert len(column_candidates) == len(keep_column_types)
return column_candidates, keep_column_types, keep_column_indexes
def getColumnIndex(db, table_name, column_name):
"""
For when you need to get the column index of a specific column for a table.
Column indexes are needed for getting the picklist, for example
"""
table1_index = db.table_index[table_name] # get the int for the table name
relevant_column_indexs = db.get_current_schema_layout()[table1_index]
col_index_dict = {} #columnName: 0
for colinx in relevant_column_indexs:
col = db.get_field(colinx)
col_name = col.name
#if " " not in column_name: #force ignore illformatted column names
col_index_dict[col_name] = colinx
specified_column_index = col_index_dict[column_name]
return specified_column_index
def precompute_compatibility(schema_graphs):
"""
Input: schema_graphs <SchemaGraphs> object with all loaded DB's;
Output: compatibility_dict <Dict>
{'db_name1':
{
'table_name1':
{'numColumns': Int,
'numberColumnsTypeNumber': Int,
'numberColumnsTypeText': Int,
'picklistProblem': Bool},
'table_name2': {dict about columns},
'table_name3': {dict about columns}
}
'db_name2': {dict of tables},
'db_name3': {dict of tables},
...
'db_nameN': {dict of tables}
}
"""
compatibility_dict = {}
for db_name, db_id in list(schema_graphs.db_index.items()):
db = schema_graphs[db_name]
list_of_tables = list(db.table_names)
table_dict = {}
for table_name in list_of_tables:
columns, coltypes, rel_indexs = getColsAndTypes(db, table_name) #true column names, not signatures!
numColumns = len(columns)
numberColumnsTypeNumber = coltypes.count("number")
numberColumnsTypeText = coltypes.count("text")
#check for picklist problems
list_of_picklists = [db.get_field_picklist(i) for i in rel_indexs]
num_bad_picklists = 0
for pl in list_of_picklists:
try:
random.choice(pl)
except Exception as e:
num_bad_picklists += 1
if num_bad_picklists >= 1:
picklistProblem = True
else:
picklistProblem = False
column_info_dict = {'numColumns': numColumns, 'numberColumnsTypeNumber': numberColumnsTypeNumber,
'numberColumnsTypeText': numberColumnsTypeText, 'picklistProblem': picklistProblem}
table_dict[table_name] = column_info_dict
if table_name == list_of_tables[-1]:
compatibility_dict[db_name] = table_dict
return compatibility_dict
def get_table_k_columns(db, table=None, k=1, type_constraint=None):
"""
Input: db <SchemaGraph object> ;
table <String> you can give the name of a specific table, otherwise a random one is chosen [default: None,
a random one is chosen] ;
k <Int> number of columns [default 1] ;
type_constraint <Str> [options: None, "text", "number", "time", "boolean"]
Output: table1 <Str> ;
columns: List of Strings if k>2, otherwise if k=1 just a String.
If a List of Strings for multiple columns is returned here, then string formatting must be handled in the
method where this function is called.
"""
original_k = k
if table is None:
table1 = random.choice(list(db.table_names)) # choose a random table
else:
table1 = table
column_candidates, column_types, relevant_indexs = getColsAndTypes(db, table1)
#prune column candidate by specified type constraint
if type_constraint is None:
filtered_column_candidates = column_candidates
else:
filtered_column_candidates = []
for col, type in zip(column_candidates, column_types):
if type == type_constraint:
filtered_column_candidates.append(col)
if len(filtered_column_candidates) == 0:
print(f"uh oh! there were no columns in table {table1} of specified type {type_constraint}...")
print(f"support for this exception needs to be added. Exit code: 111")
exit(111)
if k == 1:
kcols = random.choice(filtered_column_candidates) #string
#print(f"one col: {kcols}")
else:
#A check that k cannot be larger than len(column_candidates)
if k > len(filtered_column_candidates):
k = len(filtered_column_candidates) #change the length of k if k is too big
kcols = random.sample(filtered_column_candidates, k=k) #list of strings
#print(f"kcols: {kcols}")
if len(kcols) < original_k:
print(f"* ALERT!! the number of selected columns ({len(kcols)}) is less than what you asked for ({original_k})")
return table1, kcols
def is_stupid_var(var):
"""
Return True if the variable is problematic and needs re-formatting
Return False if the variable is fine the way it is
"""
if not isinstance(var, str): #if the var isnt a string, its fine.
return False
del_puncts = [p for p in string.punctuation if p != ','] #commas seem harmless, no?
if "'" in var:
return True
elif '\n' in var:
return True
elif 'None' in var:
return True
else:
for p in del_puncts: # if there's any punctuation at all, its probably wrecked
if p in var:
return True
try:
var.encode('ascii') #unicode characters break a lot of Spider eval scripts
except Exception:
return True
return False
def get_column_value(db, table, column):
"""
Chooses 1 value in the provided column for the given table and db.
Input: db <SchemaGraph>, table <String>, column <String>
Output: value <String>
"""
#This potentially also needs foreign key, primary key info though?
column_index = getColumnIndex(db, table, column)
picklist = db.get_field_picklist(column_index)
value = str(random.choice(picklist))
return value
#TODO: add a thing that forces the values to be the right datatype
def get_multiple_column_value(db, table, column, k=2):
"""
Chooses 1 value in the provided column for the given table and db.
Input: db <SchemaGraph>, table <String>, column <String>, k <Int> values
Output: value list <List>
"""
#This potentially also needs foreign key, primary key info though?
column_index = getColumnIndex(db, table, column)
picklist = db.get_field_picklist(column_index)
print(f"picklist: {picklist}")
max_num_k = len(picklist)
if k > max_num_k: #reset k to the number of things in the picklist, if k > length of picklist!
print(f"* ALERT!! the number of column values selected ({max_num_k}) is less than what you asked for ({k})")
k = max_num_k
value_list = random.sample(picklist, k=k)
print(f"value_list: {value_list}")
print(f"{[type(v) for v in value_list]}")
return value_list
def check_unique_column(db, table, column):
all_tables = list(db.table_names)
other_tables = [t for t in all_tables if t is not table]
other_columns = set()
for ot in other_tables:
cols, col_types, col_indexs = getColsAndTypes(db, ot)
[other_columns.add(c) for c in cols]
# print(f"other columns: {other_columns}")
# print(f"selected column: {column}")
if isinstance(column, str):
if column in other_columns:
return False #False, column is not unique
else:
return True
elif isinstance(column, list):
bools = []
for col in other_columns:
if col in other_columns:
bools.append(False)
else:
bools.apply(True)
if False in bools:
return False
else:
return True
############ SQL CONDITIONS ################
#to be used in WHERE clauses
def and1(db, table1, columns):
condition = 'and'
list_of_columns_as_strings = []
list_of_columns_as_sql = []
operator = 'equals'
symbol = '='
for i, c in enumerate(columns):
ac = getColAlias(db, table1, c)
val = get_column_value(db, table1, c)
# check to see if the value is problematic or not:
if is_stupid_var(val):
return "BADVAL", "BADVAL" # needs 2 objects to unpack"
try:
float(val)
formatted_sql_var = f"{val}"
except Exception as e:
formatted_sql_var = f"'{val}'"
if i == 0:
col_as_string = f"{ac} {operator} {val}"
col_as_sql = f"{c} {symbol} {formatted_sql_var}"
else:
col_as_string = f"{condition} {ac} {operator} {val}"
col_as_sql = f"{condition.upper()} {c} {symbol} {formatted_sql_var}"
list_of_columns_as_strings.append(col_as_string)
list_of_columns_as_sql.append(col_as_sql)
formatted_where_columns_with_vars = ' '.join(list_of_columns_as_strings)
formatted_where_columns_as_sql = ' '.join(list_of_columns_as_sql)
return formatted_where_columns_with_vars, formatted_where_columns_as_sql
def or1(db, table1, columns):
condition = 'or'
list_of_columns_as_strings = []
list_of_columns_as_sql = []
operator = 'equals'
symbol = '='
for i, c in enumerate(columns):
ac = getColAlias(db, table1, c)
val = get_column_value(db, table1, c)
# check to see if the value is problematic or not:
if is_stupid_var(val):
return "BADVAL", "BADVAL" # needs 2 objects to unpack"
try:
float(val)
formatted_sql_var = f"{val}"
except Exception as e:
formatted_sql_var = f"'{val}'"
if i == 0:
col_as_string = f"{ac} {operator} {val}"
col_as_sql = f"{c} {symbol} {formatted_sql_var}"
else:
col_as_string = f"{condition} {ac} {operator} {val}"
col_as_sql = f"{condition.upper()} {c} {symbol} {formatted_sql_var}"
list_of_columns_as_strings.append(col_as_string)
list_of_columns_as_sql.append(col_as_sql)
formatted_where_columns_with_vars = ' '.join(list_of_columns_as_strings)
formatted_where_columns_as_sql = ' '.join(list_of_columns_as_sql)
return formatted_where_columns_with_vars, formatted_where_columns_as_sql
#Can mix ANDs and ORs
def andor2(db, table1, columns):
list_of_columns_as_strings = []
list_of_columns_as_sql = []
operator = 'equals'
symbol = '='
for i, c in enumerate(columns):
condition = random.choice(['and', 'or'])
val = get_column_value(db, table1, c)
ac = getColAlias(db, table1, c)
if is_stupid_var(val):
return "BADVAL", "BADVAL" #needs 2 objects to unpack"
# scrubbed_val = re.sub('\n', '', val)
# formatted_sql_var = f"`'{scrubbed_val}'`" # if the var is problematic, add escape characters
try:
float(val)
formatted_sql_var = f"{val}"
except Exception as e:
formatted_sql_var = f"'{val}'"
if i == 0:
col_as_string = f"{ac} {operator} {val}"
col_as_sql = f"{c} {symbol} {formatted_sql_var}"
else:
col_as_string = f"{condition} {ac} {operator} {val}"
col_as_sql = f"{condition.upper()} {c} {symbol} {formatted_sql_var}"
list_of_columns_as_strings.append(col_as_string)
list_of_columns_as_sql.append(col_as_sql)
formatted_columns_with_vars = ' '.join(list_of_columns_as_strings)
formatted_columns_as_sql = ' '.join(list_of_columns_as_sql)
return formatted_columns_with_vars, formatted_columns_as_sql
#Requires "text" column type
def like1(db, table1, col, value):
starts_or_ends = random.choice([w_like_start, w_like_end])
acol = getColAlias(db, table1, col)
try:
if starts_or_ends is w_like_start:
letter = value[0]
formatted_letter = f"%{letter}"
else:
letter = value[-1]
formatted_letter = f"{letter}%"
except Exception as e:
return "BADVAL", "BADVAL"
if letter.lower() not in string.ascii_lowercase:
return "BADVAL", "BADVAL"
nlq_end = f"{acol} {starts_or_ends} {letter} "
sql_end = f"{col} LIKE '{formatted_letter}'"
return nlq_end, sql_end
def notlike1(db, table1, col, value):
starts_or_ends = random.choice([w_not_like_start, w_not_like_end])
acol = getColAlias(db, table1, col)
try:
if starts_or_ends is w_like_start:
letter = value[0]
formatted_letter = f"%{letter}"
else:
letter = value[-1]
formatted_letter = f"{letter}%"
except Exception as e:
return "BADVAL", "BADVAL"
if letter.lower() not in string.ascii_lowercase:
return "BADVAL", "BADVAL"
nlq_end = f"{acol} {starts_or_ends} {letter} "
sql_end = f"{col} NOT LIKE '{formatted_letter}'"
return nlq_end, sql_end
def between1(db, table1, column):
#get two random numeric values from the column
values = sorted(get_multiple_column_value(db, table1, column, k=2))
aliascol = getColAlias(db, table1, column)
try:
float(values[0])
float(values[1])
except Exception as e:
return "BADVAL", "BADVAL"
nlq_end = f"{aliascol} {w_between} {values[0]} {w_and} {values[1]}"
sql_end = f"{column} BETWEEN {values[0]} AND {values[1]}"
return nlq_end, sql_end
def wherenot3(db, col1, columns, table=None, tableLUT=None):
candidate_cols = [col for col in columns if col != col1]
col2 = random.choice(candidate_cols)
aliascol2 = getColAlias(db, table, col2)
nl_part, sql_part = select_col(db, table=table, tableLUT=tableLUT) #use most simple
sql_part = sql_part.strip(";")
nlq_end = f"{aliascol2} {w_not_in} \"{nl_part}\" "
sql_end = f"{col2} NOT IN ({sql_part})"
return nlq_end, sql_end
def wherein(db, col1, columns, table=None, tableLUT=None):
candidate_cols = [col for col in columns if col != col1]
col2 = random.choice(candidate_cols)
aliascol2 = getColAlias(db, table, col2)
nl_part, sql_part = select_col(db, table=table, tableLUT=tableLUT) #use most simple
sql_part = sql_part.strip(";")
nlq_end = f"{aliascol2} {w_is_in} \"{nl_part}\" "
sql_end = f"{col2} IN ({sql_part})"
return nlq_end, sql_end
def whereMaths(db, table=None, tableLUT=None):
table1, columns = get_table_k_columns(db, k=2, table=table, type_constraint="number")
if isinstance(columns, str):
return "BADVAL", "BADVAL"
# if len(columns) == 1:
# return "BADVAL", "BADVAL"
print(f"COLUMNS: {columns}")
col1 = columns[0]
col2 = columns[1]
val2 = get_column_value(db, table1, col2)
alias_col1 = getColAlias(db, table, col1)
alias_col2 = getColAlias(db, table, col2)
operatordict = {"less than": "<", "greater than": ">", "less than or equal to": "<=",
"greater than or equal to": ">="}
# <> breaks the sql parser :'(
operator, symbol = random.choice(list(operatordict.items()))
try:
float(val2)
except Exception as e: # force it to non numerical for string values! can't be >= elephant.
return "BADVAL", "BADVAL"
if is_stupid_var(val2):
return "BADVAL", "BADVAL" #needs 2 objects to unpack"
# scrubbed_val2 = re.sub('\n', '', val2)
# formatted_sql_var = f"`'{scrubbed_val2}'`" # if the var is problematic, add escape characters
try:
float(val2)
formatted_sql_var = f"{val2}"
except Exception as e:
return "BADVAL", "BADVAL"
decision = random.choice([(w_all, '*'), (alias_col1, col1)]) # decide to select all or select just the 1 column
if tableLUT is not None: # if there is a tableLUT, update table1 to be the gt name
lookup = tableLUT[table1]
gt_alias_table = lookup[0]
gt_table = lookup[1]
else:
gt_alias_table = table1
gt_table = table1
nlq = f"{q1} {decision[0]} {w_from} {gt_alias_table} {w_where} {alias_col2} is {operator} {val2}"
sql = f"SELECT {decision[1]} FROM {gt_table} WHERE {col2} {symbol} {formatted_sql_var} ;"
print("*****" * 10)
print(f"/ {nlq}")
print(f'\\ {sql}')
print("*****" * 10)
return nlq, sql
######################## SQL CLAUSES ########################
def select_col(db, table=None, tableLUT=None):
"""
Same as select1, except you cannot select all
"""
table1, col1 = get_table_k_columns(db, table)
aliascol = getColAlias(db, table1, col1)
decision = (aliascol, col1) # decide to select all or select just the 1 column
if tableLUT is not None: # if there is a tableLUT, update table1 to be the gt name
lookup = tableLUT[table1]
gt_alias_table = lookup[0]
gt_table = lookup[1]
else:
gt_alias_table = table1
gt_table = table1
# if decision is col1: # check if its a unique column
# unique_column = check_unique_column(db, table1, col1)
# if unique_column:
# nlq = f"{col1}"
# sql = f"{col1} FROM {table1} ;"
# else: # if the column names are not unique to the table in the DB, then we need a FROM table
nlq = f"{decision[0]} {w_from} {gt_alias_table}"
sql = f"SELECT {decision[1]} FROM {gt_table} ;"
print("*****" * 10)
print(f"/ {nlq}")
print(f'\\ {sql}')
print("*****" * 10)
return nlq, sql
def select1(db, table=None, tableLUT=None):
"""
Select either column1 or all columns from table1
Input: db <SchemaGraph object>
Output: String: natural language question; String: sql
"""
table1, col1 = get_table_k_columns(db, table)
alias_col1 = getColAlias(db, table1, col1)
decision = random.choice([(w_all, '*'), (alias_col1, col1)]) #decide to select all or select just the 1 column
if tableLUT is not None: # if there is a tableLUT, update table1 to be the gt name
lookup = tableLUT[table1]
gt_alias_table = lookup[0]
gt_table = lookup[1]
else:
gt_alias_table = table1
gt_table = table1
# if decision is col1: #check if its a unique column
# unique_column = check_unique_column(db, table1, col1)
# if unique_column:
# nlq = f"{q1} {col1}"
# sql = f"SELECT {col1} FROM {table1} ;"
# else: #if the column names are not unique to the table in the DB, then we need a FROM table
nlq = f"{q1} {decision[0]} {w_from} {gt_alias_table}"
sql = f"SELECT {decision[1]} FROM {gt_table} ;"
print("*****"*10)
print(f"/ {nlq}")
print(f'\\ {sql}')
print("*****" * 10)
return nlq, sql
def selectk(db, k, table=None, tableLUT=None):
"""
Select multiple columns from table1
Input: db <SchemaGraph object>, k <Int> number of desired columns
Output: String: natural language question; String: sql
"""
table1, columns = get_table_k_columns(db, k=k, table=table)
print(f"columns: {columns}")
alias_columns = [getColAlias(db, table, c) for c in columns]
print(f"alias columns: {alias_columns}")
alias_columns_as_string = ', '.join(alias_columns)
columns_as_string = ', '.join(columns)
#unique = check_unique_column(db, table, columns)
if tableLUT is not None: # if there is a tableLUT, update table1 to be the gt name
lookup = tableLUT[table1]
gt_alias_table = lookup[0]
gt_table = lookup[1]
else:
gt_alias_table = table1
gt_table = table1
nlq = f"{q1} {alias_columns_as_string} {w_from} {gt_alias_table}"
sql = f"SELECT {columns_as_string} FROM {gt_table} ;"
print("*****"*10)
print(f"/ {nlq}")
print(f'\\ {sql}')
print("*****" * 10)
return nlq, sql
def distinct1(db, table=None, tableLUT=None):
table1, col1 = get_table_k_columns(db, table=table)
aliascol = getColAlias(db, table1, col1)
if tableLUT is not None: # if there is a tableLUT, update table1 to be the gt name
lookup = tableLUT[table1]
gt_alias_table = lookup[0]
gt_table = lookup[1]
else:
gt_alias_table = table1
gt_table = table1
nlq = f"{q1} {w_distinct} {aliascol} {w_from} {gt_alias_table}"
sql = f"SELECT DISTINCT {col1} FROM {gt_table} ;"
print("*****"*10)
print(f"/ {nlq}")
print(f'\\ {sql}')
print("*****"*10)
return nlq, sql
def where1(db, table=None, tableLUT=None):
table1, columns = get_table_k_columns(db, k=2, table=table)
col1 = columns[0]
col2 = columns[1]
val2 = get_column_value(db, table1, col2)
aliascol1 = getColAlias(db, table1, col1)
aliascol2 = getColAlias(db, table1, col2)
if is_stupid_var(val2):
return "BADVAL", "BADVAL" #needs 2 objects to unpack"
# scrubbed_val2 = re.sub('\n', '', val2)
# formatted_sql_var = f"`'{scrubbed_val2}'`" #= if the var is problematic, add escape characters
else:
formatted_sql_var = f"'{val2}'"
if tableLUT is not None: # if there is a tableLUT, update table1 to be the gt name
lookup = tableLUT[table1]
gt_alias_table = lookup[0]
gt_table = lookup[1]
else:
gt_alias_table = table1
gt_table = table1
try:
aliascol1.encode('ascii')
aliascol2.encode('ascii')
val2.encode('ascii')
except UnicodeEncodeError:
print("hi")
print(aliascol1)
print(aliascol2)
print(val2)
nlq = f"{q1} {aliascol1} {w_from} {gt_alias_table} {w_where} {aliascol2} {w_equals} {val2}"
sql = f"SELECT {col1} FROM {gt_table} WHERE {col2} = {formatted_sql_var};"
print("*****"*10)
print(f"/ {nlq}")
print(f'\\ {sql}')
print("*****"*10)
return nlq, sql
def where2(db, table=None, tableLUT=None):
table1, columns = get_table_k_columns(db, k=2, table=table)
col1 = columns[0]
col2 = columns[1]
val2 = get_column_value(db, table1, col2)
aliascol1 = getColAlias(db, table1, col1)
aliascol2 = getColAlias(db, table1, col2)
operator = "equals"
symbol = "="
if is_stupid_var(val2):
return "BADVAL", "BADVAL" #needs 2 objects to unpack"
try:
float(val2)
formatted_sql_var = f"{val2}" #dont put quotes around numbers
except Exception as e:
formatted_sql_var = f"'{val2}'"
try:
float(val2)
except Exception as e:
return "BADVAL", "BADVAL"
decision = random.choice([(w_all, '*'), (aliascol1, col1)]) # decide to select all or select just the 1 column
if tableLUT is not None: # if there is a tableLUT, update table1 to be the gt name
lookup = tableLUT[table1]
gt_alias_table = lookup[0]
gt_table = lookup[1]
else:
gt_alias_table = table1
gt_table = table1
nlq = f"{q1} {decision[0]} {w_from} {gt_alias_table} {w_where} {aliascol2} {operator} {val2}"
sql = f"SELECT {decision[1]} FROM {gt_table} WHERE {col2} {symbol} {formatted_sql_var};"
print("*****" * 10)
print(f"/ {nlq}")
print(f'\\ {sql}')
print("*****" * 10)
return nlq, sql
def whereNotEquals(db, table=None, tableLUT=None):
table1, columns = get_table_k_columns(db, k=2, table=table)
col1 = columns[0]
col2 = columns[1]
val2 = get_column_value(db, table1, col2)
operator = "does not equal"
symbol = "!="
aliascol1 = getColAlias(db, table1, col1)
aliascol2 = getColAlias(db, table1, col2)
if is_stupid_var(val2):
return "BADVAL", "BADVAL" #needs 2 objects to unpack"
try:
float(val2)
formatted_sql_var = f"{val2}" #dont put quotes around numbers
except Exception as e:
formatted_sql_var = f"'{val2}'"
try:
float(val2)
except Exception as e:
return "BADVAL", "BADVAL"
decision = random.choice([(w_all, '*'), (aliascol1, col1)]) # decide to select all or select just the 1 column
if tableLUT is not None: # if there is a tableLUT, update table1 to be the gt name
lookup = tableLUT[table1]
gt_alias_table = lookup[0]
gt_table = lookup[1]
else:
gt_alias_table = table1
gt_table = table1
nlq = f"{q1} {decision[0]} {w_from} {gt_alias_table} {w_where} {aliascol2} {operator} {val2}"
sql = f"SELECT {decision[1]} FROM {gt_table} WHERE {col2} {symbol} {formatted_sql_var};"
print("*****" * 10)
print(f"/ {nlq}")
print(f'\\ {sql}')
print("*****" * 10)
return nlq, sql
#doesnt matter what datatype of column is. Just needs minimum 2 columns
def whereNested1(db, k=3, table=None, tableLUT=None):
nested_where_results_list = [] #list of triples tuple(nlq, sql, "str rule name")
table1, columns = get_table_k_columns(db, k=k, table=table)
immutable_table1 = table1 #never change this!!!! for the recursion
col1 = columns[0]
aliascol1 = getColAlias(db, table1, col1)
decision = random.choice([(w_all, '*'), (aliascol1, col1)]) # decide to select all or select just the 1 column
if tableLUT is not None: # if there is a tableLUT, update table1 to be the gt name
lookup = tableLUT[table1]
gt_alias_table = lookup[0]
gt_table = lookup[1]
else:
gt_alias_table = table1
gt_table = table1
base_nlq = f"{q1} {decision[0]} {w_from} {gt_alias_table} {w_where}"
base_sql = f"SELECT {decision[1]} FROM {gt_table} WHERE"
nlq_ending, sql_ending = and1(db, immutable_table1, columns)
if nlq_ending != "BADVAL":
nlq = f"{base_nlq} {nlq_ending}"
sql = f"{base_sql} {sql_ending} ;"
print("*****" * 10)
print(f"/ {nlq}")
print(f'\\ {sql}')
print("*****" * 10)
nested_where_results_list.append((nlq, sql, "and"))
nlq_ending, sql_ending = or1(db, immutable_table1, columns)
if nlq_ending != "BADVAL":
nlq = f"{base_nlq} {nlq_ending}"
sql = f"{base_sql} {sql_ending} ;"
print("*****" * 10)
print(f"/ {nlq}")
print(f'\\ {sql}')
print("*****" * 10)
nested_where_results_list.append((nlq, sql, "or"))
nlq_ending, sql_ending = andor2(db, immutable_table1, columns)
if nlq_ending != "BADVAL":
nlq = f"{base_nlq} {nlq_ending}"
sql = f"{base_sql} {sql_ending} ;"
print("*****" * 10)
print(f"/ {nlq}")
print(f'\\ {sql}')
print("*****" * 10)
nested_where_results_list.append((nlq, sql, "andandor"))
nlq_ending, sql_ending = wherenot3(db, col1, columns, table=immutable_table1, tableLUT=tableLUT)
nlq = f"{base_nlq} {nlq_ending}"
sql = f"{base_sql} {sql_ending} ;"
print("*****" * 10)
print(f"/ {nlq}")
print(f'\\ {sql}')
print("*****" * 10)
nested_where_results_list.append((nlq, sql, "not"))
nlq_ending, sql_ending = wherein(db, col1, columns, table=immutable_table1, tableLUT=tableLUT)
nlq = f"{base_nlq} {nlq_ending}"
sql = f"{base_sql} {sql_ending} ;"
print("*****" * 10)
print(f"/ {nlq}")
print(f'\\ {sql}')
print("*****" * 10)
nested_where_results_list.append((nlq, sql, "in"))
count_per_method = len(nested_where_results_list)
return nested_where_results_list, count_per_method
#requires at least two "text" type columns!
def whereNested2(db, k=2, table=None, tableLUT=None):
nested_where_results_list = [] # list of triples tuple(nlq, sql, "str rule name")
table1, columns = get_table_k_columns(db, k=k, table=table, type_constraint="text")
col1 = columns[0]
col2 = columns[1]
val2 = get_column_value(db, table1, col2)
aliascol1 = getColAlias(db, table1, col1)
decision = random.choice([(w_all, '*'), (aliascol1, col1)]) # decide to select all or select just the 1 column
if tableLUT is not None: # if there is a tableLUT, update table1 to be the gt name
if tableLUT is not None: # if there is a tableLUT, update table1 to be the gt name
lookup = tableLUT[table1]
gt_alias_table = lookup[0]
gt_table = lookup[1]
else:
gt_alias_table = table1
gt_table = table1
base_nlq = f"{q1} {decision[0]} {w_from} {gt_alias_table} {w_where}"
base_sql = f"SELECT {decision[1]} FROM {gt_table} WHERE"
nlq_end, sql_end = like1(db, table1, col2, val2) #this one shouldn't have any problem with "stupid vars"
if nlq_end != "BADVAL":
nlq = f"{base_nlq} {nlq_end}"
sql = f"{base_sql} {sql_end} ;"
print("*****" * 10)
print(f"/ {nlq}")
print(f'\\ {sql}')
print("*****" * 10)
nested_where_results_list.append((nlq, sql, "like"))
else:
print("LIKE was bad")
nlq_end, sql_end = notlike1(db, table1, col2, val2) #this one shouldn't have any problem with "stupid vars"
if nlq_end != "BADVAL":
nlq = f"{base_nlq} {nlq_end}"
sql = f"{base_sql} {sql_end} ;"
print("*****" * 10)
print(f"/ {nlq}")
print(f'\\ {sql}')
print("*****" * 10)
nested_where_results_list.append((nlq, sql, "notlike"))
else:
print("LIKE was bad")
count_per_method = len(nested_where_results_list)
return nested_where_results_list, count_per_method
#requires at least two "number" type columns!
def whereNested3(db, k=3, table=None, tableLUT=None):