2012-07-26 47 views
0

我需要'漂亮'打印'mysql查詢。查詢非常長且複雜,在代碼中執行此操作非常麻煩。語言並不重要,但我正在編寫一個Web應用程序,所以JavaScript(做客戶端)或Ruby(服務器端)將是理想的。Ruby MySQL格式化程序

是否有任何圖書館會爲我做這個?

我想它會做這樣的事情...

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" 

回答

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 
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