0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SQL フォーマッタを手書きトークナイザで実装した

0
Posted at

作ったもの

SQL Formatterhttps://sen.ltd/portfolio/sql-formatter/

スクリーンショット

  • 手書きトークナイザ(キーワード / 文字列 / 数値 / 演算子 / コメント)
  • インデント可変整形
  • キーワード大小変換(UPPER / lower / Capitalize)
  • minify(単一行出力)
  • シンタックスハイライト
  • サンプルクエリ

vanilla JS、ゼロ依存、ビルド不要node --test で 57 ケース。

SQL の文字列エスケープ

C 系言語に慣れているとバックスラッシュだと思いがちだが、SQL はシングルクォートの二重化:

'O''Brien'  -- → O'Brien

最初の実装でたいてい間違える。

整形戦略: 空白を捨ててから再構築

if (tok.type === 'whitespace') continue; // 捨てる
if (CLAUSE_STARTERS.has(upper)) out.push('\n' + indent(depth));

元の空白は全部捨てて、句の先頭(SELECT / FROM / WHERE / JOIN)で改行を入れ直す。これで出力が決定的(冪等)になる。

パーサは不要

SQL の完全パースはベンダー依存の地獄だが、フォーマッタは句の境界がわかれば十分。トークンレベルで境界検出できるので、パーサジェネレータは要らない。

トークナイザ ~150 行、フォーマッタ ~100 行で実用的な SQL の 90% に対応。

シリーズ

100+ 公開ポートフォリオ シリーズの #79 です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?