Skip to content

Instantly share code, notes, and snippets.

@davydany
Last active August 29, 2015 14:01
Show Gist options
  • Save davydany/8c9f53cdbb4ed216b284 to your computer and use it in GitHub Desktop.
Save davydany/8c9f53cdbb4ed216b284 to your computer and use it in GitHub Desktop.
Takes a log file with multipe SELECT query that was split across multiple lines, and extracts the SELECT query and prints it out on stdout.
"""
******************************************************************
WARNING: THIS DOES NOT TAKE INTO ACCOUNT NESTED SELECT QUERIES.
******************************************************************
Select Query query_extractor
============================
Takes a log file with multipe SELECT query that was split across
multiple lines, and extracts the SELECT query and prints it out on
stdout.
Usage:
select_query_extractor.py <filename>
******************************************************************
WARNING: THIS DOES NOT TAKE INTO ACCOUNT NESTED SELECT QUERIES.
******************************************************************
"""
import os
import sys
from argparse import ArgumentParser
query_keywords = ("SELECT", "FROM", "WHERE", "LIMIT", "ORDER BY" )
def query_extractor(line):
is_query = False
for keyword in query_keywords:
if keyword in line:
is_query = True
line = line[line.find(keyword):].strip()
return line if is_query else ''
def runner(filepath):
with open(filepath) as f:
lines = f.readlines()
extracted = map(query_extractor, lines)
for line in extracted:
if line:
if query_keywords[0] in line:
print "\n===================="
sys.stdout.write(" %s " % line)
print "\n===================="
if __name__ == "__main__":
parser = ArgumentParser(description='Takes a log file and returns out SELECT query information')
parser.add_argument('filepath', type=str)
args = parser.parse_args()
filepath = os.path.abspath(args.filepath)
runner(filepath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment