#!/bin/bash

################################################################################
# This script extracts the DB name and the query that belongs to it from MySQL
# slowlog. Output is one #DB + query# per line even if the query in the source
# log is multiline. When there's no DB in the log line, its name is '-' (dash).
# Here is an example output line:
# Schema: DB1234567 SELECT FOUND_ROWS()
################################################################################

usage () {
	echo "Usage: just pipe slowlog content to me and I'll output it in single lines"
	exit 0
}

[[ $# -gt 0 ]] && usage

grep -Eve '^(use DB|SET (timestamp=|NAMES ))' | \
sed -nre '/^((#.*Schema: )|[^#])/p' | \
sed -re 's/;$/\n/' | \
sed -re '/[^\;]/{H;$!d} ; x ; s/\n/ /g ; s/^ // ; s/# Thread_id: [0-9]+[[:space:]]+(Schema: (DB[0-9]+)?)[[:space:]]+QC_hit: [^[:space:]]+/\1/g ; s/(Schema: (DB[0-9]+)? )*Schema: /Schema: / ; s/Schema:  /Schema: - / ; s/ +/ /g' \
< /dev/stdin

