-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathq.py
executable file
·3640 lines (2937 loc) · 159 KB
/
q.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2021 Harel Ben-Attia
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details (doc/LICENSE contains
# a copy of it)
#
#
# Name : q (With respect to The Q Continuum)
# Author : Harel Ben-Attia - [email protected], harelba @ github, @harelba on twitter
#
#
# q allows performing SQL-like statements on tabular text data.
#
# Its purpose is to bring SQL expressive power to manipulating text data using the Linux command line.
#
# Full Documentation and details in https://harelba.github.io/q/
#
# Run with --help for command line details
#
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import OrderedDict
from sqlite3.dbapi2 import OperationalError
from uuid import uuid4
q_version = '3.1.6'
#__all__ = [ 'QTextAsData' ]
import os
import sys
import sqlite3
import glob
from argparse import ArgumentParser
import codecs
import locale
import time
import re
from six.moves import configparser, range, filter
import traceback
import csv
import uuid
import math
import six
import io
import json
import datetime
import hashlib
if six.PY2:
assert False, 'Python 2 is not longer supported by q'
long = int
unicode = six.text_type
DEBUG = bool(os.environ.get('Q_DEBUG', None)) or '-V' in sys.argv
SQL_DEBUG = False
if DEBUG:
def xprint(*args,**kwargs):
print(datetime.datetime.utcnow().isoformat()," DEBUG ",*args,file=sys.stderr,**kwargs)
def iprint(*args,**kwargs):
print(datetime.datetime.utcnow().isoformat()," INFO ",*args,file=sys.stderr,**kwargs)
def sqlprint(*args,**kwargs):
pass
else:
def xprint(*args,**kwargs): pass
def iprint(*args,**kwargs): pass
def sqlprint(*args,**kwargs): pass
if SQL_DEBUG:
def sqlprint(*args,**kwargs):
print(datetime.datetime.utcnow().isoformat(), " SQL ", *args, file=sys.stderr, **kwargs)
def get_stdout_encoding(encoding_override=None):
if encoding_override is not None and encoding_override != 'none':
return encoding_override
if sys.stdout.isatty():
return sys.stdout.encoding
else:
return locale.getpreferredencoding()
SHOW_SQL = False
sha_algorithms = {
1 : hashlib.sha1,
224: hashlib.sha224,
256: hashlib.sha256,
386: hashlib.sha384,
512: hashlib.sha512
}
def sha(data,algorithm,encoding):
try:
f = sha_algorithms[algorithm]
return f(six.text_type(data).encode(encoding)).hexdigest()
except Exception as e:
print(e)
# For backward compatibility only (doesn't handle encoding well enough)
def sha1(data):
return hashlib.sha1(six.text_type(data).encode('utf-8')).hexdigest()
# TODO Add caching of compiled regexps - Will be added after benchmarking capability is baked in
def regexp(regular_expression, data):
if data is not None:
if not isinstance(data, str) and not isinstance(data, unicode):
data = str(data)
return re.search(regular_expression, data) is not None
else:
return False
def regexp_extract(regular_expression, data,group_number):
if data is not None:
if not isinstance(data, str) and not isinstance(data, unicode):
data = str(data)
m = re.search(regular_expression, data)
if m is not None:
return m.groups()[group_number]
else:
return False
def md5(data,encoding):
m = hashlib.md5()
m.update(six.text_type(data).encode(encoding))
return m.hexdigest()
def sqrt(data):
return math.sqrt(data)
def power(data,p):
return data**p
def file_ext(data):
if data is None:
return None
return os.path.splitext(data)[1]
def file_folder(data):
if data is None:
return None
return os.path.split(data)[0]
def file_basename(data):
if data is None:
return None
return os.path.split(data)[1]
def file_basename_no_ext(data):
if data is None:
return None
return os.path.split(os.path.splitext(data)[0])[-1]
def percentile(l, p):
# TODO Alpha implementation, need to provide multiple interpolation methods, and add tests
if not l:
return None
k = p*(len(l) - 1)
f = math.floor(k)
c = math.ceil(k)
if c == f:
return l[int(k)]
return (c-k) * l[int(f)] + (k-f) * l[int(c)]
# TODO Streaming Percentile to prevent memory consumption blowup for large datasets
class StrictPercentile(object):
def __init__(self):
self.values = []
self.p = None
def step(self,value,p):
if self.p is None:
self.p = p
self.values.append(value)
def finalize(self):
if len(self.values) == 0 or (self.p < 0 or self.p > 1):
return None
else:
return percentile(sorted(self.values),self.p)
class StdevPopulation(object):
def __init__(self):
self.M = 0.0
self.S = 0.0
self.k = 0
def step(self, value):
try:
# Ignore nulls
if value is None:
return
val = float(value) # if fails, skips this iteration, which also ignores nulls
tM = self.M
self.k += 1
self.M += ((val - tM) / self.k)
self.S += ((val - tM) * (val - self.M))
except ValueError:
# TODO propagate udf errors to console
raise Exception("Data is not numeric when calculating stddev (%s)" % value)
def finalize(self):
if self.k <= 1: # avoid division by zero
return None
else:
return math.sqrt(self.S / (self.k))
class StdevSample(object):
def __init__(self):
self.M = 0.0
self.S = 0.0
self.k = 0
def step(self, value):
try:
# Ignore nulls
if value is None:
return
val = float(value) # if fails, skips this iteration, which also ignores nulls
tM = self.M
self.k += 1
self.M += ((val - tM) / self.k)
self.S += ((val - tM) * (val - self.M))
except ValueError:
# TODO propagate udf errors to console
raise Exception("Data is not numeric when calculating stddev (%s)" % value)
def finalize(self):
if self.k <= 1: # avoid division by zero
return None
else:
return math.sqrt(self.S / (self.k-1))
class FunctionType(object):
REGULAR = 1
AGG = 2
class UserFunctionDef(object):
def __init__(self,func_type,name,usage,description,func_or_obj,param_count):
self.func_type = func_type
self.name = name
self.usage = usage
self.description = description
self.func_or_obj = func_or_obj
self.param_count = param_count
user_functions = [
UserFunctionDef(FunctionType.REGULAR,
"regexp","regexp(<regular_expression>,<expr>) = <1|0>",
"Find regexp in string expression. Returns 1 if found or 0 if not",
regexp,
2),
UserFunctionDef(FunctionType.REGULAR,
"regexp_extract","regexp_extract(<regular_expression>,<expr>,group_number) = <substring|null>",
"Get regexp capture group content",
regexp_extract,
3),
UserFunctionDef(FunctionType.REGULAR,
"sha","sha(<expr>,<encoding>,<algorithm>) = <hex-string-of-sha>",
"Calculate sha of some expression. Algorithm can be one of 1,224,256,384,512. For now encoding must be manually provided. Will use the input encoding automatically in the future.",
sha,
3),
UserFunctionDef(FunctionType.REGULAR,
"sha1","sha1(<expr>) = <hex-string-of-sha>",
"Exists for backward compatibility only, since it doesn't handle encoding properly. Calculates sha1 of some expression",
sha1,
1),
UserFunctionDef(FunctionType.REGULAR,
"md5","md5(<expr>,<encoding>) = <hex-string-of-md5>",
"Calculate md5 of expression. Returns a hex-string of the result. Currently requires to manually provide the encoding of the data. Will be taken automatically from the input encoding in the future.",
md5,
2),
UserFunctionDef(FunctionType.REGULAR,
"sqrt","sqrt(<expr>) = <square-root>",
"Calculate the square root of the expression",
sqrt,
1),
UserFunctionDef(FunctionType.REGULAR,
"power","power(<expr1>,<expr2>) = <expr1-to-the-power-of-expr2>",
"Raise expr1 to the power of expr2",
power,
2),
UserFunctionDef(FunctionType.REGULAR,
"file_ext","file_ext(<expr>) = <filename-extension-or-empty-string>",
"Get the extension of a filename",
file_ext,
1),
UserFunctionDef(FunctionType.REGULAR,
"file_folder","file_folder(<expr>) = <folder-name-of-filename>",
"Get the folder part of a filename",
file_folder,
1),
UserFunctionDef(FunctionType.REGULAR,
"file_basename","file_basename(<expr>) = <basename-of-filename-including-extension>",
"Get the basename of a filename, including extension if any",
file_basename,
1),
UserFunctionDef(FunctionType.REGULAR,
"file_basename_no_ext","file_basename_no_ext(<expr>) = <basename-of-filename-without-extension>",
"Get the basename of a filename, without the extension if there is one",
file_basename_no_ext,
1),
UserFunctionDef(FunctionType.AGG,
"percentile","percentile(<expr>,<percentile-in-the-range-0-to-1>) = <percentile-value>",
"Calculate the strict percentile of a set of a values.",
StrictPercentile,
2),
UserFunctionDef(FunctionType.AGG,
"stddev_pop","stddev_pop(<expr>) = <stddev-value>",
"Calculate the population standard deviation of a set of values",
StdevPopulation,
1),
UserFunctionDef(FunctionType.AGG,
"stddev_sample","stddev_sample(<expr>) = <stddev-value>",
"Calculate the sample standard deviation of a set of values",
StdevSample,
1)
]
def print_user_functions():
for udf in user_functions:
print("Function: %s" % udf.name)
print(" Usage: %s" % udf.usage)
print(" Description: %s" % udf.description)
class Sqlite3DBResults(object):
def __init__(self,query_column_names,results):
self.query_column_names = query_column_names
self.results = results
def __str__(self):
return "Sqlite3DBResults<result_count=%d,query_column_names=%s>" % (len(self.results),str(self.query_column_names))
__repr__ = __str__
def get_sqlite_type_affinity(sqlite_type):
sqlite_type = sqlite_type.upper()
if 'INT' in sqlite_type:
return 'INTEGER'
elif 'CHAR' in sqlite_type or 'TEXT' in sqlite_type or 'CLOB' in sqlite_type:
return 'TEXT'
elif 'BLOB' in sqlite_type:
return 'BLOB'
elif 'REAL' in sqlite_type or 'FLOA' in sqlite_type or 'DOUB' in sqlite_type:
return 'REAL'
else:
return 'NUMERIC'
def sqlite_type_to_python_type(sqlite_type):
SQLITE_AFFINITY_TO_PYTHON_TYPE_NAMES = {
'INTEGER': long,
'TEXT': unicode,
'BLOB': bytes,
'REAL': float,
'NUMERIC': float
}
return SQLITE_AFFINITY_TO_PYTHON_TYPE_NAMES[get_sqlite_type_affinity(sqlite_type)]
class Sqlite3DB(object):
# TODO Add metadata table with qsql file version
QCATALOG_TABLE_NAME = '_qcatalog'
NUMERIC_COLUMN_TYPES = {int, long, float}
PYTHON_TO_SQLITE_TYPE_NAMES = { str: 'TEXT', int: 'INT', long : 'INT' , float: 'REAL', None: 'TEXT' }
def __str__(self):
return "Sqlite3DB<url=%s>" % self.sqlite_db_url
__repr__ = __str__
def __init__(self, db_id, sqlite_db_url, sqlite_db_filename, create_qcatalog, show_sql=SHOW_SQL):
self.show_sql = show_sql
self.create_qcatalog = create_qcatalog
self.db_id = db_id
# TODO Is this needed anymore?
self.sqlite_db_filename = sqlite_db_filename
self.sqlite_db_url = sqlite_db_url
self.conn = sqlite3.connect(self.sqlite_db_url, uri=True)
self.last_temp_table_id = 10000
self.cursor = self.conn.cursor()
self.add_user_functions()
if create_qcatalog:
self.create_qcatalog_table()
else:
xprint('Not creating qcatalog for db_id %s' % db_id)
def retrieve_all_table_names(self):
return [x[0] for x in self.execute_and_fetch("select tbl_name from sqlite_master where type='table'").results]
def get_sqlite_table_info(self,table_name):
return self.execute_and_fetch('PRAGMA table_info(%s)' % table_name).results
def get_sqlite_database_list(self):
return self.execute_and_fetch('pragma database_list').results
def find_new_table_name(self,planned_table_name):
existing_table_names = self.retrieve_all_table_names()
possible_indices = range(1,1000)
for index in possible_indices:
if index == 1:
suffix = ''
else:
suffix = '_%s' % index
table_name_attempt = '%s%s' % (planned_table_name,suffix)
if table_name_attempt not in existing_table_names:
xprint("Found free table name %s in db %s for planned table name %s" % (table_name_attempt,self.db_id,planned_table_name))
return table_name_attempt
# TODO Add test for this
raise Exception('Cannot find free table name in db %s for planned table name %s' % (self.db_id,planned_table_name))
def create_qcatalog_table(self):
if not self.qcatalog_table_exists():
xprint("qcatalog table does not exist. Creating it")
r = self.conn.execute("""CREATE TABLE %s (
qcatalog_entry_id text not null primary key,
content_signature_key text,
temp_table_name text,
content_signature text,
creation_time text,
source_type text,
source text)""" % self.QCATALOG_TABLE_NAME).fetchall()
else:
xprint("qcatalog table already exists. No need to create it")
def qcatalog_table_exists(self):
return sqlite_table_exists(self.conn,self.QCATALOG_TABLE_NAME)
def calculate_content_signature_key(self,content_signature):
assert type(content_signature) == OrderedDict
pp = json.dumps(content_signature,sort_keys=True)
xprint("Calculating content signature for:",pp,six.b(pp))
return hashlib.sha1(six.b(pp)).hexdigest()
def add_to_qcatalog_table(self, temp_table_name, content_signature, creation_time,source_type, source):
assert source is not None
assert source_type is not None
content_signature_key = self.calculate_content_signature_key(content_signature)
xprint("db_id: %s Adding to qcatalog table: %s. Calculated signature key %s" % (self.db_id, temp_table_name,content_signature_key))
r = self.execute_and_fetch(
'INSERT INTO %s (qcatalog_entry_id,content_signature_key, temp_table_name,content_signature,creation_time,source_type,source) VALUES (?,?,?,?,?,?,?)' % self.QCATALOG_TABLE_NAME,
(str(uuid4()),content_signature_key,temp_table_name,json.dumps(content_signature),creation_time,source_type,source))
# Ensure transaction is completed
self.conn.commit()
def get_from_qcatalog(self, content_signature):
content_signature_key = self.calculate_content_signature_key(content_signature)
xprint("Finding table in db_id %s that matches content signature key %s" % (self.db_id,content_signature_key))
field_names = ["content_signature_key", "temp_table_name", "content_signature", "creation_time","source_type","source","qcatalog_entry_id"]
q = "SELECT %s FROM %s where content_signature_key = ?" % (",".join(field_names),self.QCATALOG_TABLE_NAME)
r = self.execute_and_fetch(q,(content_signature_key,))
if r is None:
return None
if len(r.results) == 0:
return None
if len(r.results) > 1:
raise Exception("Bug - Exactly one result should have been provided: %s" % str(r.results))
d = dict(zip(field_names,r.results[0]))
return d
def get_from_qcatalog_using_table_name(self, temp_table_name):
xprint("getting from qcatalog using table name")
field_names = ["content_signature", "temp_table_name","creation_time","source_type","source","content_signature_key","qcatalog_entry_id"]
q = "SELECT %s FROM %s where temp_table_name = ?" % (",".join(field_names),self.QCATALOG_TABLE_NAME)
xprint("Query from qcatalog %s params %s" % (q,str(temp_table_name,)))
r = self.execute_and_fetch(q,(temp_table_name,))
xprint("results: ",r.results)
if r is None:
return None
if len(r.results) == 0:
return None
if len(r.results) > 1:
raise Exception("Bug - Exactly one result should have been provided: %s" % str(r.results))
d = dict(zip(field_names,r.results[0]))
# content_signature should be the first in the list of field_names
cs = OrderedDict(json.loads(r.results[0][0]))
if self.calculate_content_signature_key(cs) != d['content_signature_key']:
raise Exception('Table contains an invalid entry - content signature key is not matching the actual content signature')
return d
def get_all_from_qcatalog(self):
xprint("getting from qcatalog using table name")
field_names = ["temp_table_name", "content_signature", "creation_time","source_type","source","qcatalog_entry_id"]
q = "SELECT %s FROM %s" % (",".join(field_names),self.QCATALOG_TABLE_NAME)
xprint("Query from qcatalog %s" % q)
r = self.execute_and_fetch(q)
if r is None:
return None
def convert(res):
d = dict(zip(field_names, res))
cs = OrderedDict(json.loads(res[1]))
d['content_signature_key'] = self.calculate_content_signature_key(cs)
return d
rr = [convert(r) for r in r.results]
return rr
def done(self):
xprint("Closing database %s" % self.db_id)
try:
self.conn.commit()
self.conn.close()
xprint("Database %s closed" % self.db_id)
except Exception as e:
xprint("Could not close database %s" % self.db_id)
raise
def add_user_functions(self):
for udf in user_functions:
if type(udf.func_or_obj) == type(object):
self.conn.create_aggregate(udf.name,udf.param_count,udf.func_or_obj)
elif type(udf.func_or_obj) == type(md5):
self.conn.create_function(udf.name,udf.param_count,udf.func_or_obj)
else:
raise Exception("Invalid user function definition %s" % str(udf))
def is_numeric_type(self, column_type):
return column_type in Sqlite3DB.NUMERIC_COLUMN_TYPES
def update_many(self, sql, params):
try:
sqlprint(sql, " params: " + str(params))
self.cursor.executemany(sql, params)
_ = self.cursor.fetchall()
finally:
pass # cursor.close()
def execute_and_fetch(self, q,params = None):
try:
try:
if self.show_sql:
print(repr(q))
if params is None:
r = self.cursor.execute(q)
else:
r = self.cursor.execute(q,params)
if self.cursor.description is not None:
# we decode the column names, so they can be encoded to any output format later on
query_column_names = [c[0] for c in self.cursor.description]
else:
query_column_names = None
result = self.cursor.fetchall()
finally:
pass # cursor.close()
except OperationalError as e:
raise SqliteOperationalErrorException("Failed executing sqlite query %s with params %s . error: %s" % (q,params,str(e)),e)
return Sqlite3DBResults(query_column_names,result)
def _get_as_list_str(self, l):
return ",".join(['"%s"' % x.replace('"', '""') for x in l])
def generate_insert_row(self, table_name, column_names):
col_names_str = self._get_as_list_str(column_names)
question_marks = ", ".join(["?" for i in range(0, len(column_names))])
return 'INSERT INTO %s (%s) VALUES (%s)' % (table_name, col_names_str, question_marks)
# Get a list of column names so order will be preserved (Could have used OrderedDict, but
# then we would need python 2.7)
def generate_create_table(self, table_name, column_names, column_dict):
# Convert dict from python types to db types
column_name_to_db_type = dict(
(n, Sqlite3DB.PYTHON_TO_SQLITE_TYPE_NAMES[t]) for n, t in six.iteritems(column_dict))
column_defs = ','.join(['"%s" %s' % (
n.replace('"', '""'), column_name_to_db_type[n]) for n in column_names])
return 'CREATE TABLE %s (%s)' % (table_name, column_defs)
def generate_temp_table_name(self):
# WTF - From my own past mutable-self
self.last_temp_table_id += 1
tn = "temp_table_%s" % self.last_temp_table_id
return tn
def generate_drop_table(self, table_name):
return "DROP TABLE %s" % table_name
def drop_table(self, table_name):
return self.execute_and_fetch(self.generate_drop_table(table_name))
def attach_and_copy_table(self, from_db, relevant_table,stop_after_analysis):
xprint("Attaching %s into db %s and copying table %s into it" % (from_db,self,relevant_table))
temp_db_id = 'temp_db_id'
q = "attach '%s' as %s" % (from_db.sqlite_db_url,temp_db_id)
xprint("Attach query: %s" % q)
c = self.execute_and_fetch(q)
new_temp_table_name = 'temp_table_%s' % (self.last_temp_table_id + 1)
fully_qualified_table_name = '%s.%s' % (temp_db_id,relevant_table)
if stop_after_analysis:
limit = ' limit 100'
else:
limit = ''
copy_query = 'create table %s as select * from %s %s' % (new_temp_table_name,fully_qualified_table_name,limit)
copy_results = self.execute_and_fetch(copy_query)
xprint("Copied %s.%s into %s in db_id %s. Results %s" % (temp_db_id,relevant_table,new_temp_table_name,self.db_id,copy_results))
self.last_temp_table_id += 1
xprint("Copied table into %s. Detaching db that was attached temporarily" % self.db_id)
q = "detach database %s" % temp_db_id
xprint("detach query: %s" % q)
c = self.execute_and_fetch(q)
xprint(c)
return new_temp_table_name
class CouldNotConvertStringToNumericValueException(Exception):
def __init__(self, msg):
self.msg = msg
def __str(self):
return repr(self.msg)
class SqliteOperationalErrorException(Exception):
def __init__(self, msg,original_error):
self.msg = msg
self.original_error = original_error
def __str(self):
return repr(self.msg) + "//" + repr(self.original_error)
class IncorrectDefaultValueException(Exception):
def __init__(self, option_type,option,actual_value):
self.option_type = option_type
self.option = option
self.actual_value = actual_value
def __str__(self):
return repr(self)
class NonExistentTableNameInQsql(Exception):
def __init__(self, qsql_filename,table_name,existing_table_names):
self.qsql_filename = qsql_filename
self.table_name = table_name
self.existing_table_names = existing_table_names
class NonExistentTableNameInSqlite(Exception):
def __init__(self, qsql_filename,table_name,existing_table_names):
self.qsql_filename = qsql_filename
self.table_name = table_name
self.existing_table_names = existing_table_names
class TooManyTablesInQsqlException(Exception):
def __init__(self, qsql_filename,existing_table_names):
self.qsql_filename = qsql_filename
self.existing_table_names = existing_table_names
class NoTableInQsqlExcption(Exception):
def __init__(self, qsql_filename):
self.qsql_filename = qsql_filename
class TooManyTablesInSqliteException(Exception):
def __init__(self, qsql_filename,existing_table_names):
self.qsql_filename = qsql_filename
self.existing_table_names = existing_table_names
class NoTablesInSqliteException(Exception):
def __init__(self, sqlite_filename):
self.sqlite_filename = sqlite_filename
class ColumnMaxLengthLimitExceededException(Exception):
def __init__(self, msg):
self.msg = msg
def __str(self):
return repr(self.msg)
class CouldNotParseInputException(Exception):
def __init__(self, msg):
self.msg = msg
def __str(self):
return repr(self.msg)
class BadHeaderException(Exception):
def __init__(self, msg):
self.msg = msg
def __str(self):
return repr(self.msg)
class EncodedQueryException(Exception):
def __init__(self, msg):
self.msg = msg
def __str(self):
return repr(self.msg)
class CannotUnzipDataStreamException(Exception):
def __init__(self):
pass
class UniversalNewlinesExistException(Exception):
def __init__(self):
pass
class EmptyDataException(Exception):
def __init__(self):
pass
class MissingHeaderException(Exception):
def __init__(self,msg):
self.msg = msg
class InvalidQueryException(Exception):
def __init__(self,msg):
self.msg = msg
class TooManyAttachedDatabasesException(Exception):
def __init__(self,msg):
self.msg = msg
class FileNotFoundException(Exception):
def __init__(self, msg):
self.msg = msg
def __str(self):
return repr(self.msg)
class UnknownFileTypeException(Exception):
def __init__(self, msg):
self.msg = msg
def __str(self):
return repr(self.msg)
class ColumnCountMismatchException(Exception):
def __init__(self, msg):
self.msg = msg
class ContentSignatureNotFoundException(Exception):
def __init__(self, msg):
self.msg = msg
class StrictModeColumnCountMismatchException(Exception):
def __init__(self,atomic_fn, expected_col_count,actual_col_count,lines_read):
self.atomic_fn = atomic_fn
self.expected_col_count = expected_col_count
self.actual_col_count = actual_col_count
self.lines_read = lines_read
class FluffyModeColumnCountMismatchException(Exception):
def __init__(self,atomic_fn, expected_col_count,actual_col_count,lines_read):
self.atomic_fn = atomic_fn
self.expected_col_count = expected_col_count
self.actual_col_count = actual_col_count
self.lines_read = lines_read
class ContentSignatureDiffersException(Exception):
def __init__(self,original_filename, other_filename, filenames_str,key,source_value,signature_value):
self.original_filename = original_filename
self.other_filename = other_filename
self.filenames_str = filenames_str
self.key = key
self.source_value = source_value
self.signature_value = signature_value
class ContentSignatureDataDiffersException(Exception):
def __init__(self,msg):
self.msg = msg
class InvalidQSqliteFileException(Exception):
def __init__(self,msg):
self.msg = msg
class MaximumSourceFilesExceededException(Exception):
def __init__(self,msg):
self.msg = msg
# Simplistic Sql "parsing" class... We'll eventually require a real SQL parser which will provide us with a parse tree
#
# A "qtable" is a filename which behaves like an SQL table...
class Sql(object):
def __init__(self, sql, data_streams):
# Currently supports only standard SELECT statements
# Holds original SQL
self.sql = sql
# Holds sql parts
self.sql_parts = sql.split()
self.data_streams = data_streams
self.qtable_metadata_dict = OrderedDict()
# Set of qtable names
self.qtable_names = []
# Dict from qtable names to their positions in sql_parts. Value here is a *list* of positions,
# since it is possible that the same qtable_name (file) is referenced in multiple positions
# and we don't want the database table to be recreated for each
# reference
self.qtable_name_positions = {}
# Dict from qtable names to their effective (actual database) table
# names
self.qtable_name_effective_table_names = {}
self.query_column_names = None
# Go over all sql parts
idx = 0
while idx < len(self.sql_parts):
# Get the part string
part = self.sql_parts[idx]
# If it's a FROM or a JOIN
if part.upper() in ['FROM', 'JOIN']:
# and there is nothing after it,
if idx == len(self.sql_parts) - 1:
# Just fail
raise InvalidQueryException(
'FROM/JOIN is missing a table name after it')
qtable_name = self.sql_parts[idx + 1]
# Otherwise, the next part contains the qtable name. In most cases the next part will be only the qtable name.
# We handle one special case here, where this is a subquery as a column: "SELECT (SELECT ... FROM qtable),100 FROM ...".
# In that case, there will be an ending paranthesis as part of the name, and we want to handle this case gracefully.
# This is obviously a hack of a hack :) Just until we have
# complete parsing capabilities
if ')' in qtable_name:
leftover = qtable_name[qtable_name.index(')'):]
self.sql_parts.insert(idx + 2, leftover)
qtable_name = qtable_name[:qtable_name.index(')')]
self.sql_parts[idx + 1] = qtable_name
if qtable_name[0] != '(':
normalized_qtable_name = self.normalize_qtable_name(qtable_name)
xprint("Normalized qtable name for %s is %s" % (qtable_name,normalized_qtable_name))
self.qtable_names += [normalized_qtable_name]
if normalized_qtable_name not in self.qtable_name_positions.keys():
self.qtable_name_positions[normalized_qtable_name] = []
self.qtable_name_positions[normalized_qtable_name].append(idx + 1)
self.sql_parts[idx + 1] = normalized_qtable_name
idx += 2
else:
idx += 1
else:
idx += 1
xprint("Final sql parts: %s" % self.sql_parts)
def normalize_qtable_name(self,qtable_name):
if self.data_streams.is_data_stream(qtable_name):
return qtable_name
if ':::' in qtable_name:
qsql_filename, table_name = qtable_name.split(":::", 1)
return '%s:::%s' % (os.path.realpath(os.path.abspath(qsql_filename)),table_name)
else:
return os.path.realpath(os.path.abspath(qtable_name))
def set_effective_table_name(self, qtable_name, effective_table_name):
if qtable_name in self.qtable_name_effective_table_names.keys():
if self.qtable_name_effective_table_names[qtable_name] != effective_table_name:
raise Exception(
"Already set effective table name for qtable %s. Trying to change the effective table name from %s to %s" %
(qtable_name,self.qtable_name_effective_table_names[qtable_name],effective_table_name))
xprint("Setting effective table name for %s - effective table name is set to %s" % (qtable_name,effective_table_name))
self.qtable_name_effective_table_names[
qtable_name] = effective_table_name
def get_effective_sql(self,table_name_mapping=None):
if len(list(filter(lambda x: x is None, self.qtable_name_effective_table_names))) != 0:
assert False, 'There are qtables without effective tables'
effective_sql = [x for x in self.sql_parts]
xprint("Effective table names",self.qtable_name_effective_table_names)
for qtable_name, positions in six.iteritems(self.qtable_name_positions):
xprint("Positions for qtable name %s are %s" % (qtable_name,positions))
for pos in positions:
if table_name_mapping is not None:
x = self.qtable_name_effective_table_names[qtable_name]
effective_sql[pos] = table_name_mapping[x]
else:
effective_sql[pos] = self.qtable_name_effective_table_names[qtable_name]
return " ".join(effective_sql)
def get_qtable_name_effective_table_names(self):
return self.qtable_name_effective_table_names
def execute_and_fetch(self, db):
x = self.get_effective_sql()
xprint("Final query: %s" % x)
db_results_obj = db.execute_and_fetch(x)
return db_results_obj
def materialize_using(self,loaded_table_structures_dict):
xprint("Materializing sql object: %s" % str(self.qtable_names))
xprint("loaded table structures dict %s" % loaded_table_structures_dict)
for qtable_name in self.qtable_names:
table_structure = loaded_table_structures_dict[qtable_name]
table_name_in_disk_db = table_structure.get_table_name_for_querying()
effective_table_name = '%s.%s' % (table_structure.db_id, table_name_in_disk_db)
# for a single file - no need to create a union, just use the table name
self.set_effective_table_name(qtable_name, effective_table_name)
xprint("Materialized filename %s to effective table name %s" % (qtable_name,effective_table_name))
class TableColumnInferer(object):
def __init__(self, input_params):
self.inferred = False
self.mode = input_params.parsing_mode
self.rows = []
self.skip_header = input_params.skip_header
self.header_row = None
self.header_row_filename = None
self.expected_column_count = input_params.expected_column_count
self.input_delimiter = input_params.delimiter
self.disable_column_type_detection = input_params.disable_column_type_detection
def _generate_content_signature(self):
return OrderedDict({
"inferred": self.inferred,
"mode": self.mode,
"rows": "\n".join([",".join(x) for x in self.rows]),
"skip_header": self.skip_header,