forked from wireservice/csvkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
csvsql
executable file
·39 lines (30 loc) · 1.45 KB
/
csvsql
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
#!/usr/bin/env python
import os
import sys
from csvkit import sql
from csvkit import table
from csvkit.cli import CSVKitUtility
class CSVSQL(CSVKitUtility):
description = 'Generate a SQL CREATE TABLE statement for a CSV file.'
override_flags = 'l'
def add_arguments(self):
self.argparser.add_argument('-i', '--dialect', dest='dialect', choices=sql.DIALECTS,
help='Dialect of SQL to generate.')
self.argparser.add_argument('--inserts', dest='inserts', action='store_true',
help='In addition to generating a CREATE TABLE statement, also generate an INSERT statement for each row of data.')
def main(self):
if self.args.file.name != '<stdin>':
# Use filename as table name
table_name = os.path.splitext(os.path.split(self.args.file.name)[1])[0]
else:
table_name = 'csvsql_table'
csv_table = table.Table.from_csv(self.args.file, name=table_name, **self.reader_kwargs)
sql_table = sql.make_table(csv_table)
sys.stdout.write('%s\n' % sql.make_create_table_statement(sql_table, dialect=self.args.dialect))
if self.args.inserts:
sys.stdout.write('\n')
for row in csv_table.to_rows(serialize_dates=True):
sys.stdout.write('%s\n' % sql.make_insert_statement(sql_table, row, dialect=self.args.dialect))
if __name__ == '__main__':
utility = CSVSQL()
utility.main()