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

More than 1 year has passed since last update.

SQLfluffをPJに取り入れてみるよ②どんなルールに?

Last updated at Posted at 2024-08-21

はじめに

SQLfluffのSQLルールついてまとめてみました。

PJにSQLfluffを取り入れた話はこちら↓

どんなルールに?

以下を基に作成してみました。まずは最低限のルールにしています。

・SELECTする項目のカンマは前に
・エイリアス、修飾子を明示する
・サブクエリはWITH句にしない

使用したルールまとめ

Code Rule Rule
LT05 layout.long_lines 1行に何文字書くか(改行のタイミング)
ST05 structure.subquery サブクエリはWITH句に
LT04 layout.commas コンマの場所
AL01 aliasing.table テーブル名のエイリアス
AL02 aliasing.column カラム名のエイリアス
RF03 references.consistent 修飾子を付ける
.sqlfluff
[sqlfluff]
  dialect = snowflake
  templater = raw
  max_line_length = 80
  exclude_rules = L042

[sqlfluff:layout:type:comma]
  spacing_after = single
  line_position = leading

[sqlfluff:rules:aliasing.table]
  aliasing = explicit

[sqlfluff:rules:aliasing.column]
  aliasing = explicit

[sqlfluff:rules:references.consistent]
  force_enable = true

ルールについて解説

[sqlfluff]

dialect = snowflake
使用する方言を選択(他にもANSI,BigQuery,Databricksなどに対応)
※参考 https://docs.sqlfluff.com/en/stable/dialects.html

templater = raw
今回はSQLを呼び出すだけなのであまり関係ない
Pythonのコードの中でSQLを呼び出す場合など関数の受け渡しが必要な場合は指定
※参考 https://docs.sqlfluff.com/en/stable/configuration.html

exclude_rules = L042
除外したいルールを指定することも可能

※今回サブクエリはWITH句に変更するルールを除外
実際にはWITH句で書くのが正解かもしれないが、fix時にSQLの構成が大きく変わることは避けたいため

[sqlfluff:layout:type:comma] (カンマの場所)

spacing_after = single
カンマの後はスペース1個分間隔をあける

line_position = leading
カンマは行頭に(デフォルトは末尾(trailing))

参考:https://docs.sqlfluff.com/en/stable/layout.html#configuring-layout-and-spacing

[sqlfluff:rules:aliasing.table] (テーブルのエイリアス)

aliasing = explicit
テーブル名のエイリアスは明示

[sqlfluff:rules:aliasing.column] (列名のエイリアス)

aliasing = explicit
列名のエイリアスは明示

[sqlfluff:rules:references.consistent] (修飾子について)

force_enable = true
修飾子は必須

まとめ

今回は初めての取り組みだったので必要最小限のルールにしましたが、
これで終わりではなく、更に良いものになるようアップデートしていこうと思います。
参考になれば幸いです。

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