]> git.phdru.name Git - sqlconvert.git/blob - scripts/mysql-to-sql.py
c40563fed0e7d849554eac67358026789bbc090f
[sqlconvert.git] / scripts / mysql-to-sql.py
1 #! /usr/bin/env python
2 from __future__ import print_function
3
4 import argparse
5 import sys
6
7 from mysql2sql.print_tokens import print_tokens
8 from mysql2sql.process_tokens import requote_names, StatementGrouper
9
10
11 def main(infile, outfile):
12     grouper = StatementGrouper()
13     for line in infile:
14         grouper.process_line(line)
15         if grouper.statements:
16             for statement in grouper.get_statements():
17                 requote_names(statement)
18                 print_tokens(statement, outfile=outfile)
19     tokens = grouper.close()
20     if tokens:
21         for token in tokens:
22             print_tokens(token, outfile=outfile)
23
24
25 if __name__ == '__main__':
26     parser = argparse.ArgumentParser(description='Convert MySQL to SQL')
27     parser.add_argument('-o', '--outfile', help='output file name')
28     parser.add_argument('infile', help='input file name')
29     parser.add_argument('output_file', nargs='?', help='output file name')
30     args = parser.parse_args()
31
32     if args.infile:
33         if args.infile == '-':
34             infile = sys.stdin
35         else:
36             infile = open(args.infile, 'rt')
37     else:
38         infile = sys.stdin
39
40     if infile.isatty():
41         print("Error: cannot read from console", file=sys.stderr)
42         parser.print_help()
43         sys.exit(1)
44
45     if args.outfile:
46         if args.output_file:
47             print("Error: too many output files", file=sys.stderr)
48             parser.print_help()
49             sys.exit(1)
50
51         outfile = args.outfile
52
53     elif args.output_file:
54         outfile = args.output_file
55
56     else:
57         outfile = '-'
58
59     if outfile == '-':
60         outfile = sys.stdout
61     else:
62         try:
63             outfile = open(outfile, 'wt')
64         except:
65             if infile is not sys.stdin:
66                 infile.close()
67             raise
68
69     main(infile, outfile)