0

mysql クエリを「プリティ プリント」する必要があります。クエリは非常に長く複雑で、コードでこれを行うのは面倒です。言語はそれほど重要ではありませんが、私は Web アプリを作成しているので、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)、次のようなワンライナーを使用してクエリ文字列をフォーマットできます。

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 に答える