0

我需要“漂亮地打印”一个 mysql 查询。查询非常长且复杂,在代码中执行此操作很麻烦。语言无关紧要,但我正在编写一个网络应用程序,所以 javascript(做客户端)或 ruby​​(服务器端)将是理想的。

有没有图书馆可以为我做这件事?

我想它会做这样的事情......

   s = "select foo, bar from baz join bif on baz.id = bif.id where bar = 10"

   f= format( s ) # this would return something like the following.

   f = "SELECT
         foo,
         bar
       FROM baz
       JOIN bif
       ON baz.id = bif.id
       WHERE bar = 10"
4

2 回答 2

2

如果您确实与语言无关,那么 Perl 模块SQL::Beautify将漂亮地打印您上面的示例查询。

一旦安装(例如通过发出cpan SQL::Beautify),您可以使用类似于以下的 oneliner 格式化您的查询字符串:

echo "select foo, bar from baz join bif on baz.id = bif.id where bar = 10" |\
perl -ne 'use SQL::Beautify; print SQL::Beautify->new(query => $_)->beautify;'

这将产生:

select
    foo,
    bar
from
    baz
    join bif on baz.id = bif.id
where
    bar = 10
于 2012-07-26T20:41:43.277 回答
1

我使用appspot 提供的sqlformat Web 服务解决了这个问题。我本可以使用上面的 Sql Beautify 方法编写自己的 Web 服务,但我不想在我们的代码库中引入一种新语言(我们只使用 ruby​​、python 和 javascript)。

# Hits the following web-service
# http://sqlformat.appspot.com/format/

# Github page
# https://github.com/andialbrecht/sqlparse/

# Documentation
# http://sqlformat.appspot.com/api/
# data - The SQL statement to format.
# remove_comments - Set to 1 to remove comments.
# keyword_case - How to convert keywords. Allowed values are 'lower', 'upper', 'capitalize'.
# identifier_case - How to convert identifiers. Allowed values are 'lower', 'upper', 'capitalize'.
#  - while this is an option I found it capitalizes table names which breaks the query. BE CAREFUL
# n_indents - An integer indicating the indendation depth.
# right_margin - An integer indicating the maximum line length.
# output_format - Transfer the statement into another programming language. Allowed values are 'python', 'php'

# {
#   :data => query,
#   :format => 'text',
#   :remove_comments => 1,
#   :keyword_case => 'upper',
#   :n_indents => 2,
# }

# or, just pass in a the query as a string and the above params will be the default

def DB::format_sql( params )
    if( params.class == String )
        params = {
            :data => params,
            :format => 'text',
            :remove_comments => 1,
            :keyword_case => 'upper',
            :n_indents => 2,
        }
    end

    res = Net::HTTP.post_form(URI.parse('http://sqlformat.appspot.com/format/'), params )
    return res.body
end
于 2013-02-11T17:15:14.603 回答