def handle_sql_file(filename, debug=False): with open(filename) as f: lines = f.read() try: sql = format_sql(lines, debug) except InvalidSQL as e: print_non_data(e) return lines = '\n'.join(sql) return lines
def main(args=sys.argv[1:]): args = _get_args(args) filenames = _get_filenames(args.paths, args.recursive) if args.types: filenames = filter(lambda fn: fn.endswith(tuple(args.types)), filenames) for filename in filenames: print_non_data(filename) if filename.lower().endswith('.py'): lines = handle_py_file(filename, args.debug) else: lines = handle_sql_file(filename, args.debug) _write_back(filename, lines, args.dry_run)
def handle_py_file(filename, debug=False): with open(filename) as f: lines = f.read() for old_query, query, indent in get_statements(lines): if debug: print_non_data('Found query: %s' % query) try: fmt = format_sql(query, debug) except InvalidSQL as e: print_non_data(e) continue fs = [] for line in fmt: s = '%s%s' % (indent, line) fs.append(s.rstrip()) lines = lines.replace(old_query, '\n%s ' % '\n'.join(fs)) return lines
def format_sql(s, debug=False): tokens = list(tokenize(s)) if debug: print_non_data('Tokens: %s' % tokens) parsed = list(parse(tokens)) if debug: print_non_data('Statements: %s' % parsed) styled = style(parsed) if debug: print_non_data('Output: %s' % styled) return styled