-
Notifications
You must be signed in to change notification settings - Fork 1
/
pgdump2sql.py
executable file
·83 lines (63 loc) · 2.43 KB
/
pgdump2sql.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
#!/usr/bin/env python
# encoding: utf-8
'''
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
COPYING for more details.
'''
import argparse
import re as regex
parser = argparse.ArgumentParser(description='Converts Postgres data dumps to SQL scripts')
parser.add_argument('infile', type=file, help='The pgAdmin3 data dump file to convert')
parser.add_argument('outfile', type=argparse.FileType('w'), help='The output file to write to')
parser.add_argument('-I', '--sortidx', metavar='n', type=int, default=0, help='The column to use when sorting data. Default is 0.')
parser.add_argument('-T', '--tables', metavar='table', nargs='+', type=str, help='Tables to export')
args = parser.parse_args()
fin = args.infile
fout = args.outfile
content = fin.read()
lines = content.split('\n')
def parse_definition(str):
# 'COPY {definition} FROM stdin;'
return str[5:-12]
def export_table(table, out):
global args
definition = table[0]
table_name = definition.split()[0]
if args.tables != None and table_name not in args.tables:
return
print("Exporting table %s" % table_name)
out.write('-- %s\n' % definition)
del table[0]
if args.sortidx != None:
try:
table = sorted(table, key=lambda x: int(x.split('\t')[args.sortidx]))
except ValueError: pass # Column is not a number
for line in table:
line = "'" + line.replace('\\N', 'null');
line = "', '".join(line.replace('\n', '').split('\t'))
line = regex.sub(r"'?null'?", 'null', line)
if not line.endswith('null'):
line += "'"
line = line.replace("'f'", "'0'").replace("'t'", "'1'")
out.write("INSERT INTO {1} VALUES ({0});\n".format(line, definition));
out.write('\n\n')
count = content.count('\nCOPY')
print('Found %d table%s' % (count, "s" if count > 1 else ""))
in_table = False
table = []
for line in lines:
if not in_table and line.startswith('COPY'):
in_table = True
table.append(parse_definition(line))
continue
if in_table and line.startswith('\\.'):
export_table(table, fout)
in_table = False
table = []
if in_table:
table.append(line)
fin.close()
fout.close()