2007/12/23
      
      Emacs で SQL を整形する
perltidy を使ってみたり(*)、 elisp を使ってみたりして SQL を整形する方法を模索していましたが、最終的に専用のバックエンドを使うのが一番うまくいったので、それを紹介します。
(*) 文字列連結演算子の改行の扱いをうまく制御できなかった
バックエンドの準備
バックエンドとして blancoSqlFormatter というライブラリを使います(*)。
(*) http://sourceforge.jp/projects/blancofw/files/?release_id=27764#27764
Java のライブラリです。休日ハックに Java を使うとすごく不愉快になるのはなぜでしょうか。まあいいです。
% mkdir ~/opt % unzip balcoSqlFormatter-0.1.0.src.zip -d ~/opt
Java のクライアントを書きます。
~/opt/blancoSqlFormatter/SqlBeautify.java:
import java.io.InputStream;
import blanco.commons.sql.format.BlancoSqlFormatter;
import blanco.commons.sql.format.BlancoSqlRule;
public class SqlBeautify {
    public static void main(String[] args) throws Exception {
        InputStream is = System.in;
        StringBuilder sb = new StringBuilder();
        byte[] buffer = new byte[4096];
        int read;
        while ((read = is.read(buffer)) != -1) {
            sb.append(new String(buffer, 0, read));
        }
        System.out.println(new BlancoSqlFormatter(new BlancoSqlRule()).format(sb.toString()));
    }
}
コンパイルします。
% cd ~/opt/blancoSqlFormatter % CLASSPATH=$CLASSPATH:blancosqlformatter-0.1.0.jar javac SqlBeautify.java
シェルスクリプトのバックエンドを書きます。
~/bin/sqlbeautify:
#!/bin/sh BSF_HOME=$HOME/opt/blancoSqlFormatter BSF_LIB=$BSF_HOME/blancosqlformatter-0.1.0.jar env CLASSPATH=$CLASSPATH:$BSF_HOME:$BSF_LIB java SqlBeautify
実行可能にします。
% chmod +x ~/bin/sqlbeautify
こんな感じに使います。
% echo ”SELECT name,value FROM v\$sysstat WHERE name IN ('db block gets','consistent gets', 'physical reads');” | sqlbeautify
SELECT
        name
        ,VALUE
    FROM
        v$sysstat
    WHERE
        name IN (
            'db block gets'
            ,'consistent gets'
            ,'physical reads'
        )
;
Emacs から使う
以下の関数を記述します。
~/.emacs:
(defun sql-beautify-region (start end)
  "Beautify SQL in region between START and END."
  (interactive "r")
  (save-excursion
    (shell-command-on-region start end "sqlbeautify" nil t)))
(defun sql-beautify-buffer ()
 "Beautify SQL in buffer."
 (interactive)
 (sql-beautify-region (point-min) (point-max)))
M-x sql-beautify-buffer とか M-x sql-beautify-region で使えます。
- The URL to Trackback this entry is:
- http://dev.ariel-networks.com/Members/matsuyama/sql-beautifying-in-emacs/tbping
 
 
             
            