The anbt-sql-formatter
of the first answer is available as a gem, you can install it with:
gem install anbt-sql-formatter
Here an example of the usage:
require "anbt-sql-formatter/formatter"
rule = AnbtSql::Rule.new
formatter = AnbtSql::Formatter.new(rule)
[
"SELECT `col1`, `col2` FROM `table` WHERE ((`col1` = 1) AND (`col2` = 5))",
"SELECT `col1`, `col2` FROM `table` WHERE (`col1` = 1) AND (`col2` = 5)",
"SELECT `col1` FROM `table` WHERE (`col1` IN (SELECT * FROM `table21` WHERE (`col2` = 5)))",
"SELECT `col1` FROM `table` INNER JOIN `tab2` ON (`tab1`.`id` = `tab2`.`id1`) WHERE ((`id` >= 1) AND (`id` <= 5))",
].each{|sql_cmd|
puts "======"
puts sql_cmd
puts formatter.format(sql_cmd)
}
The result:
======
SELECT `col1`, `col2` FROM `table` WHERE ((`col1` = 1) AND (`col2` = 5))
SELECT
`col1`
,`col2`
FROM
`table`
WHERE
(
(
`col1` = 1
)
AND (
`col2` = 5
)
)
======
SELECT `col1`, `col2` FROM `table` WHERE (`col1` = 1) AND (`col2` = 5)
SELECT
`col1`
,`col2`
FROM
`table`
WHERE
(
`col1` = 1
)
AND (
`col2` = 5
)
======
SELECT `col1` FROM `table` WHERE (`col1` IN (SELECT * FROM `table21` WHERE (`col2` = 5)))
SELECT
`col1`
FROM
`table`
WHERE
(
`col1` IN (
SELECT
*
FROM
`table21`
WHERE
(
`col2` = 5
)
)
)
======
SELECT `col1` FROM `table` INNER JOIN `tab2` ON (`tab1`.`id` = `tab2`.`id1`) WHERE ((`id` >= 1) AND (`id` <= 5))
SELECT
`col1`
FROM
`table` INNER JOIN `tab2`
ON (
`tab1`.`id` = `tab2`.`id1`
)
WHERE
(
(
`id` >= 1
)
AND (
`id` <= 5
)
)
There is also the possibility to extend the rules, e.g.
# User defined additional functions:
%w(count sum substr date coalesce).each{|func_name|
rule.function_names << func_name.upcase
}
org.hibernate.jdbc.util.BasicFormatterImpl
– Wedded