tags:

views:

73

answers:

3

I'm looking for a program that can take in an SQL string, (my environment is MySQL, but I could look at similar tools for other RDBMSs) parse it and render it again in a format that is more human-readable. I've seen some online ones, but I'm hoping for one that I can integrate into some internal logging tools.

For example, taking:

SELECT * FROM table JOIN other_table ON table.id = other_table.id WHERE column = 'value' AND column = 'value'

and converting it into:

SELECT *
FROM table
   JOIN other_table
      ON table.id = other_table.id
WHERE column = 'value'
   AND column = 'value'

My environment is specifically PHP, but I wouldn't mind spending time porting code.

A: 

You could have a peek at phpmyadmin and see how they are formatting SQL. They always pretty-print every query that was executed.

In libraries/common.inc.php there is a function called PMA_formatSql, this might be a good starting point.

Edit: It does not neccessarily display the SQL as HTML formatted string. Depending on the configuration (implemented as global :-( ) it does output the SQL as text.

halfdan
I have started poking around there, it appears to be a full-blown parser and then it generates HTML output, which is a bit overkill for what I'm doing here.
Dominic Barnes
`libraries/sqlparser.lib.php` and check out function `PMA_SQP_formatHtml`
webbiedave
@Dominic Barnes: How else can it properly format if it doesn't full-blown parse it?
webbiedave
Well, the parsing isn't so much of a problem, it's the HTML output that is not really going to help in a plain-text log.
Dominic Barnes
Edited post. Check PMA_formatSQL + what webbiedave said. You won't get any good formatting without parsing the SQL.
halfdan
@halfdan, I am looking around now and seeing what you are talking about in your edit. I'll see if it's something I can extract for use in my own code :)
Dominic Barnes
I was able to get text-formatted SQL by modifying function `PMA_formatSql` in `common.lib.php` to allow `query_only` as a valid `fmtType`. More work needs to be done to make it useful in your logging app but it's definitely possible.
webbiedave
A: 

Google has a javascript code prettifier which has a plugin for SQL:

http://code.google.com/p/google-code-prettify/

brendan
A: 

I've been using SQLYog as a querying tool, and it comes with a "prettyfier" built in that works with most of the queries I try. However, it's not free.

If this is to be used in your logging, you could probably make it look for and insert newline characters before specific keywords like FROM, WHERE, AND.

Fanis