-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsql
More file actions
executable file
·98 lines (84 loc) · 3.42 KB
/
csql
File metadata and controls
executable file
·98 lines (84 loc) · 3.42 KB
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# csv / sql query engine
# Copyright © 2011 Jeff Epler <jepler@unpythonic.net>
#
# 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 2 of the License, 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import csv
import optparse
import os
import sqlite3
import sys
def sniff(csvfile):
return csv.Sniffer().sniff(file(csvfile).read(40960))
def find_columns(csvfile):
base, ext = os.path.splitext(csvfile)
candidates = [ base + ".cols", os.path.basename(base) + ".cols" ]
for c in candidates:
if os.path.isfile(c): return c
raise SystemExit, "Could not find columns for %r (Tried %s)" % (
csvfile, ", ".join(repr(c) for c in candidates))
parser = optparse.OptionParser(usage="%prog [options] csvfile sqlquery")
parser.add_option("-c", "--columns",
help="File specifying columns (default: guess based on input file)",
metavar="example.cols", dest="columns")
parser.add_option("-d", "--in-dialect",
help="Dialect of input file (default: autodetected)",
metavar="excel|excel-tab|auto", dest="in_dialect")
parser.add_option("-D", "--out-dialect",
help="Dialect of output file (default: same as input)",
metavar="excel|excel-tab|input", dest="out_dialect")
parser.set_defaults(columns=None, in_dialect='auto', out_dialect='input')
options, args = parser.parse_args()
if len(args) != 2:
parser.print_help()
raise SystemExit
csvfile, sqlquery = args
if options.in_dialect == 'auto':
options.in_dialect = sniff(csvfile)
elif options.in_dialect not in csv.list_dialects():
raise SystemExit, "Dialect %r not known" % options.in_dialect
if options.out_dialect == 'input':
options.out_dialect = options.in_dialect
if options.columns is None:
options.columns = find_columns(csvfile)
csvfile = csv.reader(file(csvfile), options.in_dialect)
columns = [line.strip() for line in file(options.columns)]
conn = sqlite3.connect(':memory:')
conn.text_factory = str
c = conn.cursor()
c.execute('create table t (' + ','.join(columns) + ')')
toolong = []
tooshort = []
params = ','.join('?' * len(columns))
for row in csvfile:
if len(row) < len(columns):
tooshort.append(row)
row = row + [None] * (len(columns) - len(row))
elif len(row) > len(columns):
toolong.append(row)
row = row[:len(columns)]
assert len(row) == len(columns)
c.execute('insert into t values (%s)' % params, row)
if tooshort:
print >>sys.stderr, "Warning: %d rows were shorter than expected" % len(tooshort)
print >>sys.stderr, tooshort[0]
if toolong:
print >>sys.stderr, "Warning: %d rows were longer than expected" % len(toolong)
print >>sys.stderr, toolong[0]
writer = csv.writer(sys.stdout, dialect=options.out_dialect)
c.execute(sqlquery)
for row in c:
writer.writerow(row)