sql-testing-tools 0.1.4__tar.gz → 0.1.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.1
2
+ Name: sql_testing_tools
3
+ Version: 0.1.6
4
+ Description-Content-Type: text/markdown
5
+ Requires-Dist: sqlparse>=0.5.1
6
+ Requires-Dist: requests>=2.32.3
7
+
8
+ A library that normalizes simple SQL queries and compares them first by equality of the normalized string and then using the cosette API.
9
+
10
+
11
+ ### [Beta in Development!]
12
+ [![Build and Test](https://github.com/ValentinHerrmann/sql_testing_tools/actions/workflows/python-build.yml/badge.svg)](https://github.com/ValentinHerrmann/sql_testing_tools/actions/workflows/python-build.yml)
13
+ [![Build and Test](https://github.com/ValentinHerrmann/sql_testing_tools/actions/workflows/python-unittests.yml/badge.svg)](https://github.com/ValentinHerrmann/sql_testing_tools/actions/workflows/python-unittests.yml)
14
+
15
+
16
+
17
+ ### V0.1.4 + V0.1.5
18
+ - V0.1.5 is just a reupload of V0.1.4
19
+ - Chained conditions (with AND,OR and Paranthesises) in WHERE statement
20
+
21
+ ### V0.1.3
22
+ - SELECT: columns with our without table prefix
23
+ - FROM: one or more table from DB; no queries as tables!
24
+ - WHERE: single conditions; no Paranthesises!
25
+ - GROUP BY one or more columns
@@ -1,3 +1,3 @@
1
- [Beta in Development]
1
+ **[Beta in Development!]**
2
2
 
3
3
  This project is a wrapper for packaging [SQL_Testing_Tools](https://github.com/ValentinHerrmann/sql_testing_tools) into a Wheel and upload it to PyPi.
@@ -6,7 +6,7 @@ with open("sql_testing_tools/README.md", "r") as fh:
6
6
 
7
7
  setup(
8
8
  name='sql_testing_tools',
9
- version='0.1.4',
9
+ version='0.1.6',
10
10
  packages=find_packages(),
11
11
  install_requires=[
12
12
  'sqlparse>=0.5.1',
@@ -0,0 +1,210 @@
1
+ try:
2
+ import BaseAccess as Ba
3
+ import TokenProcessing as Tp
4
+ except ImportError:
5
+ from . import BaseAccess as Ba
6
+ from . import TokenProcessing as Tp
7
+
8
+ import requests
9
+ import sqlparse
10
+
11
+ from sqlparse.sql import Identifier, IdentifierList, Where, Comparison, Function, Parenthesis
12
+ from sqlparse.tokens import Keyword, DML, Name, Wildcard
13
+
14
+
15
+
16
+ def normalizeSQLQuery(query, baseDict):
17
+ try:
18
+ query = query.replace("\"", "'")
19
+ parsed = sqlparse.parse(query)[0]
20
+ parsed.tokens = [token for token in parsed.tokens if not token.is_whitespace]
21
+ except Exception as e:
22
+ raise Exception(f"\nSyntax-Fehler in der SQL-Abfrage.")
23
+
24
+ formatted_query = []
25
+ alias_map = {}
26
+
27
+ # First pass to process FROM clause and populate alias_map
28
+ for token in parsed.tokens:
29
+ if token.is_whitespace:
30
+ continue
31
+ elif token.ttype is Keyword and token.value.upper() == 'FROM':
32
+ formatted_query.append('FROM')
33
+ pass
34
+ elif isinstance(token, Identifier) and formatted_query and formatted_query[-1] == 'FROM':
35
+ il = IdentifierList([token])
36
+ formatted_query.append(Tp._from(il, alias_map, baseDict))
37
+ Tp._from(il, alias_map, baseDict)
38
+ elif isinstance(token, IdentifierList) and formatted_query and formatted_query[-1] == 'FROM':
39
+ formatted_query.append(Tp._from(token, alias_map, baseDict))
40
+ Tp._from(token, alias_map, baseDict)
41
+
42
+ formatted_query = []
43
+
44
+ # Second pass to process SELECT and WHERE clauses
45
+ for token in parsed.tokens:
46
+ if token.is_whitespace:
47
+ continue
48
+ elif token.ttype is DML and token.value.upper() == 'SELECT':
49
+ formatted_query.append('SELECT')
50
+ elif token.ttype is Keyword and token.value.upper() == 'FROM':
51
+ formatted_query.append('FROM')
52
+ elif token.ttype is Keyword and token.value.upper() == 'GROUP BY':
53
+ formatted_query.append('GROUP BY')
54
+ elif (isinstance(token, IdentifierList) or isinstance(token, Identifier)) and formatted_query and formatted_query[-1] == 'FROM':
55
+ formatted_query.append(Tp._from(token, alias_map, baseDict))
56
+ elif (isinstance(token, IdentifierList) or isinstance(token, Identifier)) and formatted_query and formatted_query[-1] == 'GROUP BY':
57
+ formatted_query.append(Tp._groupby(token, alias_map, baseDict))
58
+ elif isinstance(token, Where):
59
+ formatted_query.append('WHERE')
60
+ formatted_query.append(Tp._where(token, alias_map, baseDict))
61
+ elif formatted_query and formatted_query[-1] == 'SELECT' and (isinstance(token, IdentifierList) or isinstance(token, Function) or isinstance(token, Identifier)):
62
+ if isinstance(token, Function):
63
+ token = IdentifierList([token])
64
+ formatted_query.append(Tp._select(token, alias_map, baseDict))
65
+ else:
66
+ formatted_query.append(str(token))
67
+
68
+ return " ".join(formatted_query)
69
+
70
+
71
+ def findTableForColumn(data_dict, target_value, relevantTables):
72
+ l = []
73
+ for key, value_list in data_dict.items():
74
+ if key.lower() in relevantTables:
75
+ for sublist in value_list:
76
+ if sublist and sublist[0].lower() == target_value.lower():
77
+ l.append(key)
78
+ if len(l) == 0:
79
+ for key, value_list in data_dict.items():
80
+ for sublist in value_list:
81
+ if sublist and sublist[0].lower() == target_value.lower():
82
+ l.append(key)
83
+ return l
84
+
85
+
86
+ def getTableScheme(table_name: str, tableDict: dict):
87
+ tab = tableDict[table_name]
88
+
89
+ # Format the schema
90
+ schema = "(" + ",".join([f"{col[0]}:{col[1]}" for col in tab]) + ")"
91
+ return schema
92
+
93
+ def getCosetteKeyFromFile():
94
+ try:
95
+ with open("cosette_apikey.txt", "r") as f:
96
+ return f.read()
97
+ except FileNotFoundError:
98
+ return "NOKEY"
99
+
100
+ def buildAndSendCosetteRequest(baseDict, sql, sol):
101
+
102
+ err = ""
103
+ for i in range(2):
104
+ try:
105
+ apiKey=getCosetteKeyFromFile()
106
+
107
+
108
+ schema = ""
109
+ for tab in baseDict.keys():
110
+ schema += f"schema sch{tab}{getTableScheme(tab, baseDict)};\n"
111
+ for tab in baseDict.keys():
112
+ schema += f"table {tab}(sch{tab});\n"
113
+
114
+ q1 = "query q1\n`"+sql+"`;\n"
115
+ q2 = "query q2\n`"+sol+"`;\n"
116
+
117
+ cosette = "-- random Kommentar\n" + schema + q1 + q2 + "verify q1 q2;\n"
118
+ print(cosette)
119
+
120
+ r = requests.post("https://demo.cosette.cs.washington.edu/solve",data={"api_key": apiKey, "query": cosette}, verify=False)
121
+
122
+ print(r.text)
123
+ return (r.json()['result'],r.text)
124
+ #return r.json()['result']
125
+
126
+ except Exception as e:
127
+ err = str(e)
128
+ return ("ERR", err)
129
+
130
+
131
+ def checkColumns(sqlPath, solPath):
132
+ bd = Ba.getTableDict()
133
+ sql = normalizeSQLQuery(Ba.getSQLFromFile(sqlPath), bd)
134
+ sol = normalizeSQLQuery(Ba.getSQLFromFile(solPath), bd)
135
+
136
+ if("SELECT" in sql and "FROM" in sql):
137
+ start = str.find(sql, "SELECT")
138
+ end = str.find(sql, "FROM")
139
+ submission = str.strip(sql[start:end])
140
+ print("'"+submission+"'")
141
+
142
+ start = str.find(sol, "SELECT")
143
+ end = str.find(sol, "FROM")
144
+ solution = str.strip(sol[start:end])
145
+ print("'"+solution+"'")
146
+
147
+ if submission == solution:
148
+ return ""
149
+ return "Ausgegebene Spalten sind nicht korrekt (oder nicht automatisch überprüfbar)."
150
+
151
+
152
+ def checkTables(sqlPath, solPath):
153
+ bd = Ba.getTableDict()
154
+ sql = normalizeSQLQuery(Ba.getSQLFromFile(sqlPath), bd)
155
+ sol = normalizeSQLQuery(Ba.getSQLFromFile(solPath), bd)
156
+
157
+ if("SELECT" in sql and "FROM" in sql):
158
+ endFromKeywords = ["WHERE", "GROUP", "ORDER", "LIMIT", ";"]
159
+
160
+ start = str.find(sql, "FROM")
161
+ end = -1
162
+
163
+
164
+ for keyword in endFromKeywords:
165
+ if(str.find(sql, keyword) != -1):
166
+ end = str.find(sql, keyword)
167
+ break
168
+ if(end == -1):
169
+ end = len(sql)
170
+
171
+ submission = str.strip(sql[start:end])
172
+ print("'"+submission+"'")
173
+
174
+ start = str.find(sol, "FROM")
175
+ end = -1
176
+
177
+ for keyword in endFromKeywords:
178
+ if(str.find(sol, keyword) != -1):
179
+ end = str.find(sol, keyword)
180
+ break
181
+ if(end == -1):
182
+ end = len(sol)
183
+
184
+ solution = str.strip(sol[start:end])
185
+ print("'"+solution+"'")
186
+
187
+ if submission == solution:
188
+ return ""
189
+ return "Verwendete Tabellen sind nicht korrekt (oder nicht automatisch überprüfbar)."
190
+
191
+
192
+ def checkEquality(sqlPath, solPath):
193
+ bd = Ba.getTableDict()
194
+ sql = normalizeSQLQuery(Ba.getSQLFromFile(sqlPath), bd)
195
+ sol = normalizeSQLQuery(Ba.getSQLFromFile(solPath), bd)
196
+ if(sql=='' or sol==''):
197
+ return "\n\nSQL-Datei ist leer. Aufgabe wurde noch nicht bearbeitet."
198
+
199
+ if(sql==sol):
200
+ return ""
201
+
202
+ result = buildAndSendCosetteRequest(bd, sql, sol)
203
+
204
+ if(result[0] == "ERR"):
205
+ return "\n\nFehler bei der automatischen Überprüfung der Abgabe. Es kann keine Aussage über die Korrektheit der Abgabe getroffen werden."
206
+ elif(result[0] != "EQ"):
207
+ return "\n\nDie Abgabe stimmt nicht mit der Musterlösung überein."
208
+ return ""
209
+
210
+
@@ -0,0 +1,361 @@
1
+ import sqlparse
2
+ from sqlparse.sql import Identifier, IdentifierList, Where, Comparison, Function, Parenthesis
3
+ from sqlparse.tokens import Keyword, DML, Name, Wildcard, Whitespace
4
+
5
+ try:
6
+ import Helper as He
7
+ except ImportError:
8
+ from . import Helper as He
9
+
10
+
11
+
12
+
13
+ #####################################
14
+ #####################################
15
+
16
+ def _identifier(identifier, alias_map, baseDict: dict):
17
+ if isinstance(identifier, Identifier):
18
+ if identifier.get_real_name() and identifier.get_parent_name() and identifier.get_parent_name().lower() in alias_map.keys():
19
+ return f"{alias_map[identifier.get_parent_name().lower()].lower()}.{identifier.get_real_name().lower()}"
20
+ elif identifier.get_real_name():
21
+ tables = He.findTableForColumn(baseDict, identifier.get_real_name(), alias_map.keys())
22
+ if len(tables) == 1:
23
+ alias_map[tables[0].lower()] = tables[0]
24
+ return f"{tables[0].lower()}.{identifier.get_real_name().lower()}"
25
+ else:
26
+ return f"{identifier.get_real_name().lower()}"
27
+ return str(identifier)
28
+
29
+
30
+ #####################################
31
+ #####################################
32
+
33
+
34
+ def _select(select, alias_map, baseDict: dict, insideFunction=False):
35
+ select_tokens = []
36
+ for token in select.tokens:
37
+ if isinstance(token, IdentifierList):
38
+ for identifier in token.get_identifiers():
39
+ select_tokens.append(f"{_identifier(identifier, alias_map, baseDict).lower()} as {identifier.get_real_name().lower()}")
40
+ elif isinstance(token, Identifier):
41
+ if insideFunction:
42
+ select_tokens.append(_identifier(token, alias_map, baseDict).lower())
43
+ else:
44
+ select_tokens.append(f"{_identifier(token, alias_map, baseDict).lower()} as {token.get_real_name().lower()}")
45
+ elif isinstance(token, Function):
46
+ #select_tokens.append(f"{token.get_name().lower()}({_identifier(token.get_parameters(), alias_map, baseDict).lower()})")
47
+ for par in token.tokens:
48
+ if isinstance(par, Identifier):
49
+ select_tokens.append(par.get_name().lower()+"(")
50
+ if isinstance(par, Parenthesis):
51
+ select_tokens[-1] += _select(par, alias_map, baseDict, True)+") as funcResult"
52
+ elif token.ttype is Wildcard:
53
+ select_tokens.append("*")
54
+ else:
55
+ continue
56
+ select_tokens.sort()
57
+ return ",".join(select_tokens)
58
+
59
+
60
+ #####################################
61
+ #####################################
62
+
63
+
64
+ def _from(from_, alias_map, baseDict: dict):
65
+ from_tokens = []
66
+ if hasattr(from_, 'tokens'):
67
+ for token in from_.tokens:
68
+ if isinstance(token, IdentifierList):
69
+ for identifier in token.get_identifiers():
70
+ alias_map[identifier.get_real_name().lower()] = identifier.get_alias() or identifier.get_real_name()
71
+ from_tokens.append(f"{identifier.get_real_name().lower()} {alias_map[identifier.get_real_name().lower()].lower()}")
72
+ elif isinstance(token, Identifier):
73
+ alias_map[token.get_real_name().lower()] = token.get_alias() or token.get_real_name()
74
+ from_tokens.append(f"{token.get_real_name().lower()} {alias_map[token.get_real_name().lower()].lower()}")
75
+ elif token.ttype is not None and token.ttype is Name:
76
+ alias_map[token.value.lower()] = token.value.lower()
77
+ from_tokens.append(f"{token.value.lower()} {alias_map[token.value.lower()].lower()}")
78
+ else:
79
+ continue
80
+ from_tokens.sort()
81
+ return ",".join(from_tokens)
82
+
83
+
84
+ #####################################
85
+ #####################################
86
+
87
+
88
+ def _groupby(groupby_, alias_map, baseDict: dict):
89
+ groupby_tokens = []
90
+ if(isinstance(groupby_, Identifier)):
91
+ groupby_tokens.append(_identifier(groupby_, alias_map, baseDict).lower())
92
+ elif isinstance(groupby_, IdentifierList):
93
+ for identifier in groupby_.get_identifiers():
94
+ groupby_tokens.append(_identifier(identifier, alias_map, baseDict).lower())
95
+ groupby_tokens.sort()
96
+ return ",".join(groupby_tokens)
97
+
98
+ def _condition(token, alias_map, baseDict: dict):
99
+ left, operator, right = [t for t in token.tokens if not t.is_whitespace]
100
+
101
+ flipAllowed = True
102
+ leftLiteral = False
103
+ rightLiteral = False
104
+
105
+ if is_value(right):
106
+ flipAllowed = False
107
+ rightLiteral = True
108
+
109
+ if is_value(left):
110
+ left, right = right, left
111
+ if operator.value == ">":
112
+ operator.value = "<"
113
+ elif operator.value == "<":
114
+ operator.value = ">"
115
+ leftLiteral = rightLiteral
116
+ rightLiteral = True
117
+ flipAllowed = False
118
+
119
+ left = _identifier(left, alias_map, baseDict)
120
+ right = _identifier(right, alias_map, baseDict)
121
+
122
+ if flipAllowed and left.lower() >= right.lower():
123
+ left, right = right, left
124
+ if operator.value == ">":
125
+ operator = "<"
126
+ elif operator.value == "<":
127
+ operator = ">"
128
+
129
+ return f"{left if leftLiteral else left.lower()} {operator} {right if rightLiteral else right.lower()}"
130
+
131
+ def is_value(token):
132
+ return token.ttype in (sqlparse.tokens.Token.Literal.Number.Integer,
133
+ sqlparse.tokens.Token.Literal.Number.Float,
134
+ sqlparse.tokens.Token.Literal.String.Single,
135
+ sqlparse.tokens.Token.Literal.String.Symbol)
136
+
137
+
138
+
139
+ #####################################
140
+ #####################################
141
+
142
+
143
+ def _paranthesis(parenthesis, alias_map, baseDict: dict):
144
+ toks = []
145
+
146
+ bracketsRequired = True
147
+ closeBracketsAfterNext = False
148
+
149
+ and_count = sum(1 for token in parenthesis.tokens if token.ttype is Keyword and token.value == "AND") # Zähle "AND"-Tokens
150
+ or_count = sum(1 for token in parenthesis.tokens if token.ttype is Keyword and token.value == "OR") # Zähle "AND"-Tokens
151
+
152
+
153
+ if(and_count==1 and or_count == 0):
154
+ val = _2element_par(parenthesis, alias_map, baseDict, "AND")
155
+ return val
156
+ elif(and_count==0 and or_count == 1):
157
+ val = _2element_par(parenthesis, alias_map, baseDict, "OR")
158
+ return val
159
+
160
+
161
+
162
+
163
+
164
+
165
+ for token in parenthesis.tokens:
166
+ if isinstance(token, Comparison):
167
+ toks.append(_condition(token, alias_map, baseDict))
168
+ elif isinstance(token, Parenthesis):
169
+ toks.append(_paranthesis(token, alias_map, baseDict))
170
+
171
+ elif token.ttype is Keyword: #AND,OR
172
+ if token.value == "AND":
173
+ pass
174
+ elif token.value == "OR":
175
+ pass
176
+ elif token.value == "NOT":
177
+ pass
178
+
179
+ elif token.value == '(':
180
+ toks.append(token.value)
181
+ else:
182
+ continue
183
+ x = parenthesis.flatten()
184
+ return " ".join(toks)
185
+
186
+
187
+ def _2element_par(parenthesis, alias_map, baseDict: dict, keyword):
188
+ toks = []
189
+
190
+ for token in parenthesis.tokens:
191
+ if isinstance(token, Comparison):
192
+ toks.append(_condition(token, alias_map, baseDict))
193
+ elif isinstance(token, Parenthesis):
194
+ toks.append(_paranthesis(token, alias_map, baseDict))
195
+ toks = toks.sort()
196
+ fill = (" "+keyword+" ")
197
+ return fill.join(toks)
198
+
199
+
200
+ def count_keywordValues(tokens, values):
201
+ return len([token for token in tokens if token.ttype is Keyword and token.value.upper() in values])
202
+
203
+
204
+ def find_index_of_keyword(tokens, keyword):
205
+ for index, token in enumerate(tokens):
206
+ if token.ttype is Keyword and token.value.upper() == keyword:
207
+ return index
208
+ return -1 # Wenn kein AND-Token gefunden wird
209
+
210
+
211
+ def _where(where, alias_map, baseDict: dict):
212
+ conditions = []
213
+ current_condition = []
214
+
215
+
216
+
217
+ isParanthesis = isinstance(where, Parenthesis)
218
+
219
+
220
+ and_count = where.normalized.upper().count(" AND ")
221
+ or_count = where.normalized.upper().count(" OR ")
222
+
223
+
224
+ # No AND / OR
225
+ if and_count + or_count == 0:
226
+ return _where_simpleCondition(where, alias_map, baseDict)
227
+
228
+ # only ANDs / only ORs
229
+ elif and_count == 0 or or_count == 0:
230
+ return _where_sameStrengthKeywords(where, alias_map, baseDict, " AND " if and_count > 0 else " OR ")
231
+
232
+ # ANDs and ORs
233
+
234
+ where_tokens = [token for token in where.tokens if token.ttype is not Whitespace and token.value != "WHERE"]
235
+
236
+ # count keywords on top level
237
+ top_and_count = count_keywordValues(where_tokens, ["AND"])
238
+ top_or_count = count_keywordValues(where_tokens, ["OR"])
239
+
240
+ # two conditions on top level
241
+ if top_and_count + top_or_count == 1:
242
+ keyword = " AND " if top_and_count == 1 else " OR "
243
+ return _where_twoConditionsOnTopLevel(where, alias_map, baseDict, keyword, isParanthesis)
244
+ else:
245
+ where_tokens = _where_addBracketsAroundAND(where, alias_map, baseDict)
246
+ return _where(Where(where_tokens), alias_map, baseDict)
247
+
248
+ def _where_addBracketsAroundAND(where, alias_map, baseDict: dict):
249
+ index = find_index_of_keyword(where.tokens, "AND")
250
+ par = Parenthesis(where.tokens[index-2:index+3])
251
+ where_tokens = where.tokens[:index-2] + [par] + where.tokens[index+3:]
252
+ return where_tokens
253
+
254
+
255
+
256
+ # for token in where.tokens:
257
+ # if token.is_whitespace or (token.ttype is Keyword and token.value.upper() == "WHERE"):
258
+ # continue
259
+
260
+ # if token.ttype is Keyword and token.value.upper() in ('AND', 'OR'):
261
+ # if current_condition:
262
+ # conditions.append(''.join(str(t) for t in current_condition).strip())
263
+ # current_condition = []
264
+ # conditions.append(token.value.upper())
265
+ # else:
266
+ # current_condition.append(token)
267
+
268
+ # if current_condition:
269
+ # conditions.append(''.join(str(t) for t in current_condition).strip())
270
+
271
+ # sorted_conditions = []
272
+ # current_group = []
273
+ # last_connector = ""
274
+
275
+ # if "OR" not in conditions:
276
+ # for condition in conditions:
277
+ # if condition == 'AND':
278
+ # pass
279
+ # else:
280
+ # current_group.append(condition)
281
+
282
+ # if current_group:
283
+ # sorted_conditions.extend(sorted(current_group))
284
+
285
+ # return " AND ".join(sorted_conditions)
286
+ # else:
287
+ # return " ".join(conditions)
288
+
289
+ # where_index = query.upper().find('WHERE')
290
+
291
+ # normalized_query = query[:where_index + 5] + ' ' + ' '.join(sorted_conditions)
292
+
293
+
294
+
295
+ def _where_simpleCondition(where, alias_map, baseDict: dict):
296
+ cond = []
297
+ for tok in where.tokens:
298
+ if isinstance(tok, Comparison):
299
+ cond.append(_condition(tok, alias_map, baseDict))
300
+ elif isinstance(tok, Parenthesis):
301
+ for _tok in tok.tokens:
302
+ if isinstance(_tok, Comparison):
303
+ cond.append(_condition(_tok, alias_map, baseDict))
304
+ elif isinstance(_tok, Parenthesis):
305
+ tok = _tok
306
+ return "".join(cond)
307
+
308
+ def _where_sameStrengthKeywords(where, alias_map, baseDict: dict, keyword: str):
309
+ cond = []
310
+ for tok in where.tokens:
311
+ if isinstance(tok, Comparison):
312
+ cond.append(_condition(tok, alias_map, baseDict))
313
+ elif isinstance(tok, Parenthesis):
314
+ for _tok in tok.tokens:
315
+ if isinstance(_tok, Comparison):
316
+ cond.append(_condition(_tok, alias_map, baseDict))
317
+ elif isinstance(_tok, Parenthesis):
318
+ tok = _tok
319
+ cond.sort()
320
+ return keyword.join(cond)
321
+
322
+ def _where_twoConditionsOnTopLevel(where, alias_map, baseDict: dict, keyword, isParanthesis):
323
+ current_condition = []
324
+ for tok in where.tokens:
325
+ if isinstance(tok, Comparison):
326
+ current_condition.append(_condition(tok, alias_map, baseDict))
327
+ elif isinstance(tok, Parenthesis):
328
+ current_condition.append(_where(tok, alias_map, baseDict))
329
+ current_condition.sort()
330
+ if keyword == " AND " or isParanthesis:
331
+ return "(" + keyword.join(current_condition) + ")"
332
+ else:
333
+ return keyword.join(current_condition)
334
+
335
+
336
+
337
+
338
+ # def _where_xx(where, alias_map, baseDict: dict):
339
+ # where_tokens = []
340
+ # for token in where.tokens:
341
+
342
+ # if isinstance(token, Comparison):
343
+ # left, operator, right = [t for t in token.tokens if not t.is_whitespace]
344
+ # left = _identifier(left, alias_map, baseDict)
345
+ # right = _identifier(right, alias_map, baseDict)
346
+ # if left.lower() >= right.lower():
347
+ # left, right = right, left
348
+ # if operator.value == ">":
349
+ # operator = "<"
350
+ # elif operator.value == "<":
351
+ # operator = ">"
352
+
353
+ # where_tokens.append(f"{left.lower()} {operator} {right.lower()}")
354
+ # elif token.ttype is Keyword:
355
+ # where_tokens.append(token.value.upper())
356
+ # elif token.is_whitespace or (token.ttype is Keyword and token.value.upper() == "WHERE"):
357
+ # continue
358
+ # else:
359
+ # where_tokens.append(str(token))
360
+ # return " ".join(where_tokens)
361
+
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.1
2
+ Name: sql_testing_tools
3
+ Version: 0.1.6
4
+ Description-Content-Type: text/markdown
5
+ Requires-Dist: sqlparse>=0.5.1
6
+ Requires-Dist: requests>=2.32.3
7
+
8
+ A library that normalizes simple SQL queries and compares them first by equality of the normalized string and then using the cosette API.
9
+
10
+
11
+ ### [Beta in Development!]
12
+ [![Build and Test](https://github.com/ValentinHerrmann/sql_testing_tools/actions/workflows/python-build.yml/badge.svg)](https://github.com/ValentinHerrmann/sql_testing_tools/actions/workflows/python-build.yml)
13
+ [![Build and Test](https://github.com/ValentinHerrmann/sql_testing_tools/actions/workflows/python-unittests.yml/badge.svg)](https://github.com/ValentinHerrmann/sql_testing_tools/actions/workflows/python-unittests.yml)
14
+
15
+
16
+
17
+ ### V0.1.4 + V0.1.5
18
+ - V0.1.5 is just a reupload of V0.1.4
19
+ - Chained conditions (with AND,OR and Paranthesises) in WHERE statement
20
+
21
+ ### V0.1.3
22
+ - SELECT: columns with our without table prefix
23
+ - FROM: one or more table from DB; no queries as tables!
24
+ - WHERE: single conditions; no Paranthesises!
25
+ - GROUP BY one or more columns
@@ -2,6 +2,7 @@ README.md
2
2
  setup.py
3
3
  sql_testing_tools/BaseAccess.py
4
4
  sql_testing_tools/Helper.py
5
+ sql_testing_tools/TokenProcessing.py
5
6
  sql_testing_tools/__init__.py
6
7
  sql_testing_tools.egg-info/PKG-INFO
7
8
  sql_testing_tools.egg-info/SOURCES.txt
@@ -1,10 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: sql_testing_tools
3
- Version: 0.1.4
4
- Description-Content-Type: text/markdown
5
- Requires-Dist: sqlparse>=0.5.1
6
- Requires-Dist: requests>=2.32.3
7
-
8
- [Beta in Development]
9
-
10
- A library that normalizes simple SQL queries and compares them first by equality of the normalized string and then using the cosette API.
@@ -1,410 +0,0 @@
1
- import os
2
- from . import BaseAccess as Ba
3
-
4
-
5
- try:
6
- import sqlparse
7
- except ImportError:
8
- print("Trying to Install required module: sqlparse\n")
9
- os.system('pip install sqlparse')
10
- import sqlparse
11
-
12
-
13
- try:
14
- import requests
15
- except ImportError:
16
- print("Trying to Install required module: requests\n")
17
- os.system('pip install requests')
18
- import requests
19
-
20
- from sqlparse.sql import Identifier, IdentifierList, Where, Comparison, Function, Parenthesis
21
- from sqlparse.tokens import Keyword, DML, Name, Wildcard
22
-
23
-
24
- def normalizeSQLQuery(query, baseDict):
25
- try:
26
- query = query.replace("\"", "'")
27
- parsed = sqlparse.parse(query)[0]
28
- parsed.tokens = [token for token in parsed.tokens if not token.is_whitespace]
29
- except Exception as e:
30
- raise Exception(f"\nSyntax-Fehler in der SQL-Abfrage.")
31
-
32
- formatted_query = []
33
- alias_map = {}
34
-
35
- def process_identifier(identifier, alias_map, baseDict: dict):
36
- if isinstance(identifier, Identifier):
37
- if identifier.get_real_name() and identifier.get_parent_name() and identifier.get_parent_name().lower() in alias_map.keys():
38
- return f"{alias_map[identifier.get_parent_name().lower()].lower()}.{identifier.get_real_name().lower()}"
39
- elif identifier.get_real_name():
40
- tables = findTableForColumn(baseDict, identifier.get_real_name(), alias_map.keys())
41
- if len(tables) == 1:
42
- alias_map[tables[0].lower()] = tables[0]
43
- return f"{tables[0].lower()}.{identifier.get_real_name().lower()}"
44
- else:
45
- return f"{identifier.get_real_name().lower()}"
46
- return str(identifier)
47
-
48
- def process_select(select, alias_map, insideFunction=False):
49
- select_tokens = []
50
- for token in select.tokens:
51
- if isinstance(token, IdentifierList):
52
- for identifier in token.get_identifiers():
53
- select_tokens.append(f"{process_identifier(identifier, alias_map, baseDict).lower()} as {identifier.get_real_name().lower()}")
54
- elif isinstance(token, Identifier):
55
- if insideFunction:
56
- select_tokens.append(process_identifier(token, alias_map, baseDict).lower())
57
- else:
58
- select_tokens.append(f"{process_identifier(token, alias_map, baseDict).lower()} as {token.get_real_name().lower()}")
59
- elif isinstance(token, Function):
60
- #select_tokens.append(f"{token.get_name().lower()}({process_identifier(token.get_parameters(), alias_map, baseDict).lower()})")
61
- for par in token.tokens:
62
- if isinstance(par, Identifier):
63
- select_tokens.append(par.get_name().lower()+"(")
64
- if isinstance(par, Parenthesis):
65
- select_tokens[-1] += process_select(par, alias_map, True)+") as funcResult"
66
- elif token.ttype is Wildcard:
67
- select_tokens.append("*")
68
- else:
69
- continue
70
- select_tokens.sort()
71
- return ",".join(select_tokens)
72
-
73
- def process_from(from_, alias_map):
74
- from_tokens = []
75
- if hasattr(from_, 'tokens'):
76
- for token in from_.tokens:
77
- if isinstance(token, IdentifierList):
78
- for identifier in token.get_identifiers():
79
- alias_map[identifier.get_real_name().lower()] = identifier.get_alias() or identifier.get_real_name()
80
- from_tokens.append(f"{identifier.get_real_name().lower()} {alias_map[identifier.get_real_name().lower()].lower()}")
81
- elif isinstance(token, Identifier):
82
- alias_map[token.get_real_name().lower()] = token.get_alias() or token.get_real_name()
83
- from_tokens.append(f"{token.get_real_name().lower()} {alias_map[token.get_real_name().lower()].lower()}")
84
- elif token.ttype is not None and token.ttype is Name:
85
- alias_map[token.value.lower()] = token.value.lower()
86
- from_tokens.append(f"{token.value.lower()} {alias_map[token.value.lower()].lower()}")
87
- else:
88
- continue
89
- from_tokens.sort()
90
- return ",".join(from_tokens)
91
-
92
- def process_groupby(groupby_, alias_map):
93
- groupby_tokens = []
94
- if(isinstance(groupby_, Identifier)):
95
- groupby_tokens.append(process_identifier(groupby_, alias_map, baseDict).lower())
96
- elif isinstance(token, IdentifierList):
97
- for identifier in token.get_identifiers():
98
- groupby_tokens.append(process_identifier(identifier, alias_map, baseDict).lower())
99
- groupby_tokens.sort()
100
- return ",".join(groupby_tokens)
101
-
102
- def process_condition(token, alias_map, baseDict):
103
- left, operator, right = [t for t in token.tokens if not t.is_whitespace]
104
-
105
- flipAllowed = True
106
- leftLiteral = False
107
- rightLiteral = False
108
-
109
- if is_value(right):
110
- flipAllowed = False
111
- rightLiteral = True
112
-
113
- if is_value(left):
114
- left, right = right, left
115
- if operator.value == ">":
116
- operator.value = "<"
117
- elif operator.value == "<":
118
- operator.value = ">"
119
- leftLiteral = rightLiteral
120
- rightLiteral = True
121
- flipAllowed = False
122
-
123
- left = process_identifier(left, alias_map, baseDict)
124
- right = process_identifier(right, alias_map, baseDict)
125
-
126
- if flipAllowed and left.lower() >= right.lower():
127
- left, right = right, left
128
- if operator.value == ">":
129
- operator = "<"
130
- elif operator.value == "<":
131
- operator = ">"
132
-
133
- return f"{left if leftLiteral else left.lower()} {operator} {right if rightLiteral else right.lower()}"
134
-
135
- def is_value(token):
136
- return token.ttype in (sqlparse.tokens.Token.Literal.Number.Integer,
137
- sqlparse.tokens.Token.Literal.Number.Float,
138
- sqlparse.tokens.Token.Literal.String.Single,
139
- sqlparse.tokens.Token.Literal.String.Symbol)
140
-
141
- def process_paranthesis(parenthesis, alias_map, baseDict):
142
- toks = []
143
-
144
- bracketsRequired = True
145
-
146
-
147
- for token in parenthesis.tokens:
148
- if isinstance(token, Comparison):
149
- toks.append(process_condition(token, alias_map, baseDict))
150
- elif isinstance(token, Parenthesis):
151
- toks.append(process_paranthesis(token, alias_map, baseDict))
152
-
153
- elif token.value == '(':
154
- toks.append(token.value)
155
- else:
156
- continue
157
- x = parenthesis.flatten()
158
- return " ".join(toks)
159
-
160
- def process_where(where, alias_map, baseDict):
161
- conditions = []
162
- current_condition = []
163
-
164
- for token in where.tokens:
165
- if token.is_whitespace or (token.ttype is Keyword and token.value.upper() == "WHERE"):
166
- continue
167
-
168
- if token.ttype is Keyword and token.value.upper() in ('AND', 'OR'):
169
- if current_condition:
170
- conditions.append(''.join(str(t) for t in current_condition).strip())
171
- current_condition = []
172
- conditions.append(token.value.upper())
173
- elif isinstance(token, Comparison):
174
- current_condition.append(process_condition(token, alias_map, baseDict))
175
- elif isinstance(token, Parenthesis):
176
- current_condition.append(process_paranthesis(token, alias_map, baseDict))
177
- else:
178
- current_condition.append(token)
179
-
180
- if current_condition:
181
- conditions.append(''.join(str(t) for t in current_condition).strip())
182
-
183
- sorted_conditions = []
184
- current_group = []
185
- last_connector = ""
186
-
187
- if "OR" not in conditions:
188
- for condition in conditions:
189
- if condition == 'AND':
190
- pass
191
- else:
192
- current_group.append(condition)
193
-
194
- if current_group:
195
- sorted_conditions.extend(sorted(current_group))
196
-
197
- return " AND ".join(sorted_conditions)
198
- else:
199
- return " ".join(conditions)
200
-
201
- where_index = query.upper().find('WHERE')
202
- normalized_query = query[:where_index + 5] + ' ' + ' '.join(sorted_conditions)
203
-
204
- def process_where_xx(where, alias_map, baseDict):
205
- where_tokens = []
206
- for token in where.tokens:
207
-
208
- if isinstance(token, Comparison):
209
- left, operator, right = [t for t in token.tokens if not t.is_whitespace]
210
- left = process_identifier(left, alias_map, baseDict)
211
- right = process_identifier(right, alias_map, baseDict)
212
- if left.lower() >= right.lower():
213
- left, right = right, left
214
- if operator.value == ">":
215
- operator = "<"
216
- elif operator.value == "<":
217
- operator = ">"
218
-
219
- where_tokens.append(f"{left.lower()} {operator} {right.lower()}")
220
- elif token.ttype is Keyword:
221
- where_tokens.append(token.value.upper())
222
- elif token.is_whitespace or (token.ttype is Keyword and token.value.upper() == "WHERE"):
223
- continue
224
- else:
225
- where_tokens.append(str(token))
226
- return " ".join(where_tokens)
227
-
228
- # First pass to process FROM clause and populate alias_map
229
- for token in parsed.tokens:
230
- if token.is_whitespace:
231
- continue
232
- elif token.ttype is Keyword and token.value.upper() == 'FROM':
233
- formatted_query.append('FROM')
234
- pass
235
- elif isinstance(token, Identifier) and formatted_query and formatted_query[-1] == 'FROM':
236
- il = IdentifierList([token])
237
- formatted_query.append(process_from(il, alias_map))
238
- process_from(il, alias_map)
239
- elif isinstance(token, IdentifierList) and formatted_query and formatted_query[-1] == 'FROM':
240
- formatted_query.append(process_from(token, alias_map))
241
- process_from(token, alias_map)
242
-
243
- formatted_query = []
244
-
245
- # Second pass to process SELECT and WHERE clauses
246
- for token in parsed.tokens:
247
- if token.is_whitespace:
248
- continue
249
- elif token.ttype is DML and token.value.upper() == 'SELECT':
250
- formatted_query.append('SELECT')
251
- elif token.ttype is Keyword and token.value.upper() == 'FROM':
252
- formatted_query.append('FROM')
253
- elif token.ttype is Keyword and token.value.upper() == 'GROUP BY':
254
- formatted_query.append('GROUP BY')
255
- elif (isinstance(token, IdentifierList) or isinstance(token, Identifier)) and formatted_query and formatted_query[-1] == 'FROM':
256
- formatted_query.append(process_from(token, alias_map))
257
- elif (isinstance(token, IdentifierList) or isinstance(token, Identifier)) and formatted_query and formatted_query[-1] == 'GROUP BY':
258
- formatted_query.append(process_groupby(token, alias_map))
259
- elif isinstance(token, Where):
260
- formatted_query.append('WHERE')
261
- formatted_query.append(process_where(token, alias_map, baseDict))
262
- elif formatted_query and formatted_query[-1] == 'SELECT' and (isinstance(token, IdentifierList) or isinstance(token, Function) or isinstance(token, Identifier)):
263
- if isinstance(token, Function):
264
- token = IdentifierList([token])
265
- formatted_query.append(process_select(token, alias_map))
266
- else:
267
- formatted_query.append(str(token))
268
-
269
- return " ".join(formatted_query)
270
-
271
-
272
- def findTableForColumn(data_dict, target_value, relevantTables):
273
- l = []
274
- for key, value_list in data_dict.items():
275
- if key.lower() in relevantTables:
276
- for sublist in value_list:
277
- if sublist and sublist[0].lower() == target_value.lower():
278
- l.append(key)
279
- if len(l) == 0:
280
- for key, value_list in data_dict.items():
281
- for sublist in value_list:
282
- if sublist and sublist[0].lower() == target_value.lower():
283
- l.append(key)
284
- return l
285
-
286
-
287
- def getTableScheme(table_name: str, tableDict: dict):
288
- tab = tableDict[table_name]
289
-
290
- # Format the schema
291
- schema = "(" + ",".join([f"{col[0]}:{col[1]}" for col in tab]) + ")"
292
- return schema
293
-
294
- def getCosetteKeyFromFile():
295
- try:
296
- with open("cosette_apikey.txt", "r") as f:
297
- return f.read()
298
- except FileNotFoundError:
299
- return "NOKEY"
300
-
301
- def buildAndSendCosetteRequest(baseDict, sql, sol):
302
-
303
- err = ""
304
- for i in range(2):
305
- try:
306
- apiKey=getCosetteKeyFromFile()
307
-
308
-
309
- schema = ""
310
- for tab in baseDict.keys():
311
- schema += f"schema sch{tab}{getTableScheme(tab, baseDict)};\n"
312
- for tab in baseDict.keys():
313
- schema += f"table {tab}(sch{tab});\n"
314
-
315
- q1 = "query q1\n`"+sql+"`;\n"
316
- q2 = "query q2\n`"+sol+"`;\n"
317
-
318
- cosette = "-- random Kommentar\n" + schema + q1 + q2 + "verify q1 q2;\n"
319
- print(cosette)
320
-
321
- r = requests.post("https://demo.cosette.cs.washington.edu/solve",data={"api_key": apiKey, "query": cosette}, verify=False)
322
-
323
- print(r.text)
324
- return (r.json()['result'],r.text)
325
- #return r.json()['result']
326
-
327
- except Exception as e:
328
- err = str(e)
329
- return ("ERR", err)
330
-
331
-
332
- def checkColumns(sqlPath, solPath):
333
- bd = Ba.getTableDict()
334
- sql = normalizeSQLQuery(Ba.getSQLFromFile(sqlPath), bd)
335
- sol = normalizeSQLQuery(Ba.getSQLFromFile(solPath), bd)
336
-
337
- if("SELECT" in sql and "FROM" in sql):
338
- start = str.find(sql, "SELECT")
339
- end = str.find(sql, "FROM")
340
- submission = str.strip(sql[start:end])
341
- print("'"+submission+"'")
342
-
343
- start = str.find(sol, "SELECT")
344
- end = str.find(sol, "FROM")
345
- solution = str.strip(sol[start:end])
346
- print("'"+solution+"'")
347
-
348
- if submission == solution:
349
- return ""
350
- return "Ausgegebene Spalten sind nicht korrekt (oder nicht automatisch überprüfbar)."
351
-
352
-
353
- def checkTables(sqlPath, solPath):
354
- bd = Ba.getTableDict()
355
- sql = normalizeSQLQuery(Ba.getSQLFromFile(sqlPath), bd)
356
- sol = normalizeSQLQuery(Ba.getSQLFromFile(solPath), bd)
357
-
358
- if("SELECT" in sql and "FROM" in sql):
359
- endFromKeywords = ["WHERE", "GROUP", "ORDER", "LIMIT", ";"]
360
-
361
- start = str.find(sql, "FROM")
362
- end = -1
363
-
364
-
365
- for keyword in endFromKeywords:
366
- if(str.find(sql, keyword) != -1):
367
- end = str.find(sql, keyword)
368
- break
369
- if(end == -1):
370
- end = len(sql)
371
-
372
- submission = str.strip(sql[start:end])
373
- print("'"+submission+"'")
374
-
375
- start = str.find(sol, "FROM")
376
- end = -1
377
-
378
- for keyword in endFromKeywords:
379
- if(str.find(sol, keyword) != -1):
380
- end = str.find(sol, keyword)
381
- break
382
- if(end == -1):
383
- end = len(sol)
384
-
385
- solution = str.strip(sol[start:end])
386
- print("'"+solution+"'")
387
-
388
- if submission == solution:
389
- return ""
390
- return "Verwendete Tabellen sind nicht korrekt (oder nicht automatisch überprüfbar)."
391
-
392
-
393
- def checkEquality(sqlPath, solPath):
394
- bd = Ba.getTableDict()
395
- sql = normalizeSQLQuery(Ba.getSQLFromFile(sqlPath), bd)
396
- sol = normalizeSQLQuery(Ba.getSQLFromFile(solPath), bd)
397
- if(sql=='' or sol==''):
398
- return "\n\nSQL-Datei ist leer. Aufgabe wurde noch nicht bearbeitet."
399
-
400
- if(sql==sol):
401
- return ""
402
-
403
- result = buildAndSendCosetteRequest(bd, sql, sol)
404
-
405
- if(result[0] == "ERR"):
406
- return "\n\nFehler bei der automatischen Überprüfung der Abgabe. Es kann keine Aussage über die Korrektheit der Abgabe getroffen werden."
407
- elif(result[0] != "EQ"):
408
- return "\n\nDie Abgabe stimmt nicht mit der Musterlösung überein."
409
- return ""
410
-
@@ -1,10 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: sql_testing_tools
3
- Version: 0.1.4
4
- Description-Content-Type: text/markdown
5
- Requires-Dist: sqlparse>=0.5.1
6
- Requires-Dist: requests>=2.32.3
7
-
8
- [Beta in Development]
9
-
10
- A library that normalizes simple SQL queries and compares them first by equality of the normalized string and then using the cosette API.