provenance.py 9.45 KB
Newer Older
haoyuz3's avatar
debug  
haoyuz3 committed
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
import psycopg2
import sqlparse as sp
import argparse
import sys
import copy
import time
import operator
import provenanceUtils as ut
import traceback

#When craeting the auxillary provenance tables, need to add a column called provtuple, which is a sorted array
#[t1, t2, t3...]

tablesWithProvenance = {}

twojoins = ["INNERJOIN", "LEFTJOIN", "RIGHTJOIN", "FULLJOIN", "NATURALJOIN"]
threejoins = ["LEFTOUTERJOIN", "RIGHTOUTERJOIN", "FULLOUTERJOIN"]

def tablesInQuery(query):
    output = []
    tokens = query.split(" ")
    tokens = list(filter(lambda a: a != "", tokens))
    state = "not in"
    idx = 0
    while idx < len(tokens):
        if tokens[idx] == "":
            idx += 1
            continue
        if state == "not in":
            if tokens[idx].upper() == "FROM":
                state = "from in"
            if tokens[idx].upper() == "JOIN":
                state = "join in"
        elif state == "from in":
            if tokens[idx].upper() in ["WHERE", "ON"]:
                state = "not in"
                idx += 1
                continue
            if tokens[idx].upper() == "JOIN":
                state = "join in"
                idx += 1
                continue
            if (tokens[idx]+tokens[idx+1]).upper() in twojoins:
                state = "join in"
                idx += 2
                continue
            if (tokens[idx]+tokens[idx+1]+tokens[idx+2]).upper() in threejoins:
                state = "join in"
                idx += 3
                continue
            if "SELECT" in tokens[idx].upper():
                idx += 1
                state = "not in"
                continue
            if "," in tokens[idx]:
                output.append(tokens[idx].split(",")[0])
            else:
                if tokens[idx + 1].upper() == "AS":
                    output.append(tokens[idx])
                    idx += 2
                elif "," in tokens[idx + 1]:
                    output.append(tokens[idx])
                    idx += 1
                elif tokens[idx+1].upper() == "WHERE" :
                    state = "not in"
                    output.append(tokens[idx])
                    idx += 1
                elif tokens[idx+2].upper() == "WHERE":
                    state = "not in"
                    output.append(tokens[idx])
                    idx += 2
                elif (tokens[idx+2]+tokens[idx+3]).upper() in twojoins:
                    output.append(tokens[idx])
                    idx += 1
                elif (tokens[idx+2]+tokens[idx+3]+tokens[idx+4]).upper() in threejoins:
                    output.append(tokens[idx])
                    idx += 1
                else:
                    output.append(tokens[idx])
        elif state == "join in":
            if tokens[idx].upper() in ["WHERE", "ON"]:
                state = "not in"
                idx += 1
                continue
            if tokens[idx].upper() == "JOIN":
                state = "join in"
                idx += 1
                continue
            if (tokens[idx]+tokens[idx+1]).upper() in twojoins:
                state = "join in"
                idx += 2
                continue
            if (tokens[idx]+tokens[idx+1]+tokens[idx+2]).upper() in threejoins:
                state = "join in"
                idx += 3
                continue
            if "SELECT" in tokens[idx].upper():
                idx += 1
                state = "not in"
                continue
            if tokens[idx+2].upper() == "USING":
                output.append(tokens[idx])
                idx += 2
                state = "not in"
                continue
            if tokens[idx + 1].upper() == "AS":
                output.append(tokens[idx])
                idx += 2
            elif tokens[idx+1].upper() in ["WHERE", "ON", "JOIN"] or (tokens[idx+1]+tokens[idx+2]).upper() in twojoins or (tokens[idx+1]+tokens[idx+2]+tokens[idx+3]).upper() in threejoins:
                output.append(tokens[idx])
            else:
                output.append(tokens[idx])
                idx+=1
        idx += 1
                

    
    return list(set(output))

            


    '''parsed = sp.parse(query)[0]
    output = []
    state = ""
    for token in parsed.tokens:
        cur = token.value
        if cur == " ":
            continue
        if cur.lower() == "from":
            state = "first table"
            continue
        if state == "first table":
            if "(" not in cur and "join" in cur:
                state = "second table"
                continue
            if "(" in cur and ")" in cur:
                #subquery
                output.extend(tablesInQuery(cur[cur.index("(")+1 : len(cur) - 1 - cur[::-1].index(")")]))
            else:
                output.append(cur.split("as")[0].strip())
            continue
        
        if state == "second table":
            if "(" in cur and ")" in cur:
                #subquery
                output.extend(tablesInQuery(cur[cur.index("(")+1 : len(cur) - 1 - cur[::-1].index(")")]))
            else:
                output.append(cur.split("as")[0].strip())
            break

    return list(set(output))'''



#Preprocess query
def preprocess_query(query, cur, conn):
    tables = tablesInQuery(query)
    output = []
    for table in tables:
        if table not in tablesWithProvenance:
            cmdAddProvtuple = "select \"add_provtuple\"('{}')".format(table)
            command1 = "select add_provenance('{}');".format(table)
            command2 = "select create_provenance_mapping('{}_provtuple_mapping','{}','provtuple');".format(table, table)
            ut.commitAndExecute(conn, cur, cmdAddProvtuple)
            ut.commitAndExecute(conn, cur, command1)
            ut.commitAndExecute(conn, cur, command2)
            tablesWithProvenance[table] = 1
        formula = " formula(provenance(), '{}_provtuple_mapping'), ".format(table)
        index = query.find('select') + 6
        tmp = query[:index] + formula + query[index:]
        output.append(tmp)
        
    return (tables,output)

#formulas:[[formula1, formula2, ...],
#           [formula1, ...]
#           ...
#         ]
#fs: [formula1, formula2, ...]

def process_formula(fs, tables):
    base_formula = ut.baseFormula(fs[0])
    for i, formula in enumerate(fs):
        base_formula = ut.remove1sAndAddTablename(formula, tables[i], base_formula)
    return base_formula

def get_header(query):
    parsed = sp.parse(query)[0]
    headers = (parsed.tokens)[2].value.split(",")
    output = ""
    for h in headers:
        h = h.strip()
        header = ""
        if "." in h:
            header = h.split(".")[1]
        else:
            header = h
        output += header + "   |   "
    return output


def exe_query(query, out_file, cur, conn):
    out_file.write(query + "\n")
    print("executing query: " + query)
    tables, queries = preprocess_query(query, cur, conn)
    result_t = None
    formulas = []
    for processed_query in queries:
        ut.commitAndExecute(conn, cur, processed_query)
        output = cur.fetchall()
        if result_t == None:
            result_t = output
        for i, tu in enumerate(output):
            if len(formulas) == i:
                formulas.append([tu[0]])
            else:
                formulas[i].append(tu[0])
    
    processed_formulas = []
    for fs in formulas:
        rowformula = process_formula(fs, tables)
        processed_formulas.append(rowformula)
    result__ = []
    for i, row in enumerate(result_t):
        rowl = list(row)
        rowl[0] = processed_formulas[i]
        result__.append(rowl)

    # Combine rows with same output
    result = ut.combineSameRow(result__)
    
    # Now print the processed query
    header = get_header(query)
    out_file.write("provenance formula   |   " + header+ "provsql-token"+"\n\n")
    for row in result:
        line = " | ".join(str(elem) for elem in row)
        out_file.write(line+"\n")
    out_file.write("\n---------------------------\n\n")
    

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("env", help="Environment configuration file")
    parser.add_argument("-q", "--query", help="Relative path for query file.")
    parser.add_argument("-o", "--output", help="Relative path for output file. Default as stdout")
    args = parser.parse_args() 

    env_config = ''
    queries = []
    out_file = sys.stdout
    with open(args.env) as fp:
        line = fp.readline()
        while line:
            tmp = line.strip()
            env_config  = env_config + tmp + ' '
            line = fp.readline()
    print("database configuration " + env_config)

    if args.query:
        with open(args.query) as fp:
            line = fp.readline()
            while line:
                queries.append(line.strip())
                line = fp.readline()
    else:
        print("Please specify at least one query file.")
        exit(1)

    if args.output:
        out_file = open(args.output, 'w')
    
    conn = None
    try:
        print('connecting to databse...')
        conn = psycopg2.connect(env_config)
        cur = conn.cursor()
        ut.commitAndExecute(conn, cur, 'SET search_path TO public, provsql;')

        for query in queries:
            exe_query(query, out_file, cur, conn)
            print("FINISHED: "+query)

        print("Done!")
    except (Exception, psycopg2.DatabaseError) as error:
        print(traceback.format_exc())
        exit(1)
    finally:
        out_file.close()
        if conn is not None:
            conn.close()
            print('Database connection closed.')

if __name__ == '__main__':
    main()