Skip to main content

Introduction to SQLFluff: How to make your SQL code clean and error-free

happy man Image by Jake Aldridge from Pixabay

You know oftentimes, the cause of runtime or compile errors and hours of debugging agony is all due to simply a missing semicolon. Have you ever had such experience? If you had, you are not alone. There are two ways to avoid these unfortunate situations: either become a perfect developer who never makes mistakes, or use helpful tools such as linters that can catch these errors early on.

I am nowhere near being a perfect developer who never makes a mistake. In fact, I'm probably the opposite of a perfect developer, so even if I wanted to, I wouldn’t be able to teach you how to become a perfect developer. But what I can teach you is using linters. A Wikipedia defines a linter as a "static code analysis tool used to flag programming errors, bugs, stylistic errors and suspicious constructs."

If you're not convinced yet on using linters, consider this scenario: in a large project with multiple members, different people tend to write code in different formats. Differing formats often make code reviews difficult and cause inconsistency in source code. It would be easier and more consistent for everyone if all team members wrote the code in the same format. A linter can help you with this issue too. Hopefully, now you see the value of using linters.

There are linters for almost every programming language. In many cases there is more than one good linters for a particular language. However, when it comes to SQL, as far as I know, there are fewer options. But it can't be a reason to feel discouraged though, SQLFull, the most popular linter for SQL, is an excellent tool. In this article I will explain what it is and how to use it.

SQLFLuff

SQLFluff is the most popular linter for SQL language. It touts itself as being a "SQL linter for humans". It helps not only with catching syntax errors but also fixing them. It supports multiple dialects of SQL language such as PostgreSQL, MySQL and even Snowflake.
You can find the official documentation here: Docs.

Installation

SQLFluff can be installed as

Easier and less error-prone way of running SQLFluff is as a command line tool. We will also discuss using it as a pre-commit hook at a later section.

Installing SQLFluff as a command line tool

Note: to install SQLFluff, you need Python and pip (or any other package manager such as poetry, pipenv). This example uses pip.

Install SQLFluff by running the following command on the terminal:

pip install sqlfluff

Check the installation by running: (expected output is something like this: 3.2.4)

sqlfluff version
# 3.2.4

Usage

SQLFluff has 3 main commands: lint : this command shows the syntax errors format : formats the code (mainly it fixes new line, indentation and white spaces) fix: fixes the syntax errors such as missing comma, semicolon, new line etc.

To lint a file named test.sql, run:

sqlfluff lint test.sql --dialect snowflake

The results looks like below:

== [test.sql] FAIL
L:   1 | P:   1 | LT01 | Expected only single space before 'SELECT' keyword.
                       | Found '  '. [layout.spacing]
L:   1 | P:   1 | LT02 | First line should not be indented.
                       | [layout.indent]
L:   1 | P:   1 | LT13 | Files must not begin with newlines or whitespace.
                       | [layout.start_of_file]
L:   1 | P:  11 | LT01 | Expected only single space before binary operator '+'.
                       | Found '  '. [layout.spacing]
L:   1 | P:  14 | LT01 | Expected only single space before naked identifier.
                       | Found '  '. [layout.spacing]
L:   1 | P:  27 | LT01 | Unnecessary trailing whitespace at end of file.
                       | [layout.spacing]
L:   1 | P:  27 | LT12 | Files must end with a single trailing newline.
                       | [layout.end_of_file]
All Finished 📜 🎉!

Output shows test.sql file has only formatting error.

Understanding the linting output:

Linting output shows the L (line number) and P (position) that caused the error, and the rule index that threw the error, in this case LT01. After the rule index there is a short explanation as for what is the problem. This LT01 rule concerns with layout spacing and checks for inappropriate spacing such as excessive whitespace, trailing whitespace at the end of a line and also the wrong spacing between elements on the line.
You can find all the rules and their definitions here: Rule Index.

SQLFluff comes with default rules. You can quickly check those rules in command line by running:

sqlfluff rules

It is possible to specify the rules we want to check against or exclude certain rules.

Specifying the rules:

sqlfluff lint test.sql --rules LT02,LT12,CP01,ST06,LT09,LT01

Excluding rules:

sqlfluff fix test.sql --exclude-rules LT01

SQLFluff may not recognize some keywords certain SQl dialects uses. When it happens it throws parsing error. Workaround of this problem is to tell SQLFluff to ignore parsing errors.

sqlfluff fix test.sql --ignore parsing

Other command line configurations can be find here: CLI Config.

Config File

Configuring SQLFluff using cli may be little tedious, instead we can use config files. SQLFluff comes with default configurations. However, based on your preference, you can overwrite default configurations.

SQLFluff supports following config file types:

  • setup.cfg
  • tox.ini
  • pep8.ini
  • .sqlfluff
  • pyproject.toml

In below example we change 7 configuration rules. Note: The rest of the rules stay the same as default.

.sqlfluff file

[sqlfluff]

dialect = snowflake

exclude_rules = ST06

# Number of passes to run before admitting defeat
runaway_limit = 2

large_file_skip_byte_limit = 2000000

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

The same configuration in TOML file format:

[tool.sqlfluff]

dialect = snowflake

exclude_rules = ST06

runaway_limit = 2

large_file_skip_byte_limit = 2000000

[tool.sqlfluff.layout.type.comma]
line_position = leading

Explanation of the above configuration:

dialect = snowflake sets the dialect of the SQLFluff to Snowflake syntax. exclude_rules = ST06 excludes the rule ST06. Rule ST06 orders select targets in ascending complexity. For instance, it puts * above other select targets like below:

select
    *,
    a,
    b,
    row_number() over (partition by id order by date) as y
from my_table;

However, I don't want to change the order of the columns, so I'm disabling the ST06 rule.

runaway_limit = 2 specifies the number of times the SQLFluff tries to find errors/improvements in a given block of code before moving on. large_file_skip_byte_limit = 2000000 instructs SQLFluff to ignore the file if the sql file size is larger than 2000000 bytes (2MB). line_position = leading it puts the commas at the beginning of each line. Note, very large files can make the SQLFluff parser effectively hang.

Result of line_position = leading rule:

select
    a
    ,b
    ,c
from my_table;

Pre-Commit

Git is an indispensable tool for every developer. It helps with version control and collaboration. Git can also call some functions while carrying out its usual job. For example, before committing changes to a repository, git can call certain functions, these functions are called pre-commit hooks. A tool called pre-commit can help with setting up and configuring these functions (pre-commit hooks). We can set-up pre-commit hooks to run SQLFluff automatically whenever we try to commit our changes. If SQLFluff finds error in our sql files, it throws error and Git prevents the changes from being committed to the repository.

Setting up pre-commit

pip install pre-commit

# check installation
pre-commit --version
# pre-commit v4.0.1

create a file named .pre-commit-config.yaml. in your repository's root directory. Inside the file write below:

repos:
  - repo: https://github.com/sqlfluff/sqlfluff
    rev: stable_version
    hooks:
      - id: sqlfluff-lint
      - id: sqlfluff-fix

pre-commit uses SQLFluff configurations specified in .sqlfluff file. But If you don't want to use .sqlfluff file for whatever reason, you can also write the configurations directly on .pre-commit-config.yaml file as below.

repos:
  - repo: https://github.com/sqlfluff/sqlfluff
    rev: stable_version
    hooks:
      - id: sqlfluff-lint
        args:
            - '--dialect'
            - 'snowflake'
            - '--exclude-rules'
            - 'ST06'
            - '--runaway-limit'
            - '2'
            - '--layout-type'
            - 'comma'
            - '--line-position'
            - 'leading'

      - id: sqlfluff-fix
            args:
            - '--dialect'
            - 'snowflake'
            - '--exclude-rules'
            - 'ST06'
            - '--runaway-limit'
            - '2'
            - '--layout-type'
            - 'comma'
            - '--line-position'
            - 'leading'

Run pre-commit install to set up the git hook scripts. Now, whenever you run git commit, SQLFluff linting and fixing commands will run before the commit. If SQLFluff finds no errors, commit is made, but if it finds errors commit is not made. SQlFluff outputs the errors to the terminal and fixes them as much as it can. After that you need to run git add and git commit commands once again. 
You can find more info on using SQLFluff with pre-commit here: Pre-commit docs.

Comments

Popular posts from this blog

How To Use KeePassXC Cli

There are similarly named programs: KeePass, KeePassX and KeePassXC (many of which are each others’ forks). Program Condition KeePass primarily for Windows. KeePassX no longer actively maintained. KeePassXC actively maintained and runs natively on Linux, macOS and Windows . Note: GUI version of the KeePassXC has more features than cli version. GUI version has variety of shortcuts as well. Regarding how to use GUI version of the KeePassXC, visit Getting Started Guide . Below features are available only in GUI version. Setting “Name” and “Description” fields of passwords database. Nesting Groups. Creating entry attributes ( open issue ). Adding Timed One-Time Passwords (TOTP). Adding entry with the same title as existing entry. KeePassXC stores all the passwords in passwords database. A passwords database (hereafter referred to as database) is an (encrypted) binary file. It can have any or no extension, but the .kdbx extension is commonly used. The ...

Git squash merge explained

There are many ways to integrate changes in git: regular / normal git merge, git squash merge, git rebase etc. This article explains git squash merge by comparing it to regular merge. Let’s use below example: In the repository with default main branch, after two commits, a new feature branch is created. Some work happened in feature branch. feature branch now has 2 commits that it shares with main branch, and three exclusive commits (exists only in feature branch). In the meantime, others worked on main branch and added two new commits (exists only in main branch). git log output of the main branch: c72d4a9 ( HEAD - > main ) fourth commit on main 2c3dd61 third commit on main 0c2eec3 second commit on main 9b968e8 first commit on main git log output of the feature branch: 786650f ( HEAD - > feature ) third commit on feature 21cbaf1 second commit on feature 677bc7f first commit on feature 0c2eec3 second commit on main 9b968e8 first commit on mai...

例を使ってSnowflakeストアドプロシージャを学びましょう

Image by Gerd Altmann from Pixabay データベースの操作において、反復的なタスクや複雑なロジックの実行は、時間と労力を要する作業になりがちです。Snowflakeストアドプロシージャは、こうした課題を解決するための強力な機能であり、SQLクエリを拡張して、より効率的かつ安全なデータ処理を実現します。 本稿では、Snowflakeストアドプロシージャの基本的な概念から、JavaScript、Python、そしてSnowflake Scripting (SQL)といった複数のプログラミング言語を使った作成方法、さらにはセキュリティ対策まで、実践的な知識を提供します。 小売業におけるキャンペーン管理を例に、県名に応じてキャンペーン情報と割引率を一括更新するストアドプロシージャを実装します。 ストアドプロシージャと言うのは ストアドプロシージャを関数の一つ種類と考えてもいいです。ストアドプロシージャを記述して、 SQL を実行する手続き型コードでシステムを拡張できます。ストアドプロシージャを作成すると、何度でも再利用できます。 値を明示的に返すことが許可されていますが、必須ではないです。ストアドプロシージャを実行するロールの権限だけではなく、プロシージャを所有するロールの権限でも実行出来ます。 サポートされている言語: Java JavaScript Python Scala Snowflake Scripting (SQL) ストアドプロシージャの形: CREATE OR REPLACE PROCEDURE プロシージャ名(arguments argumentsのタイプ) RETURNS レターんタイプ LANGUAGE 言語 -- (例:python, JavaScript等) -- RUNTIME_VERSION = '3.8' (言語がpython, java, scalaなら必要 ) -- PACKAGES = ('snowflake-snowpark-python') (言語がpython, java, scalaなら必要 ) -- HANDLER = 'run' (言語がpython, java, scalaなら必要 ) EXECUTE AS ...

Snowflake Load History vs Copy History: 7 differences

Image by Icons8_team from Pixabay Tracking data loads in Snowflake is crucial to maintaining data health and performance. Load History and Copy History are features that provide valuable information about past data loads. Understanding these features can help you efficiently troubleshoot, audit, and analyze performance. You might be wondering why two functions exist to achieve the same goal, what are the differences, which one I am supposed to use and when? In this article we will provide you with all the answers. So, let's learn what are the differences and when to use which! Load History vs Copy History: 7 differences Differences 1 and 2: views vs table function and Account Usage vs information Schema Here things get little confusing, bare with me, there are two Load History views, a view that belongs to Information Schema and a view that belongs to Account Usage schema . As for Copy History, there are Copy History table function of Information schema and a Copy H...

WinMerge のセットアップと使う方

WinMerge は、Windows 用のオープン ソースの差分およびマージ ツールです。WinMerge は、フォルダーとファイルの両方を比較し、違いを理解して扱いやすい視覚的なテキスト形式で表示します。この記事でWinMerge のセットアップと使う方を教えます。 source: https://winmerge.org WinMerge をダウンロード WinMerge のウェブサイト に行って、「WinMerge-2.16.44-x64-Setup.exe」ボタンを押し、WinMerge 2.16 をダウンロードしてください。 WinMerge をインストール ダウンロードされたソフトウェアをクリックし、ポップアップ画面で「Next」を押してください 「Languages」部分をスクロールダウンし、「Japanese menus and dialogs」を選択し、「Next」ボタンを押してください ターミナル等からも WinMerge をアクセス出来ようにする為に「Add WinMerge folder to your system path」オプションを選択し、希望によって他のオプション選択してください 「Enable Explorer context menu Integration」オプションを選択したら、フォルダ/ファイルを右キリックし、コンテクストメニューから WinMerge を開くようになります。 「Install」ボタンを押し、「Next」ボタンを押し、その後、「Finish」ボタンを押してください 言語を日本語にする もし WinMerge の言語が日本語じゃなくて、英語なら、「Edit」タブから「Options」を押してください。 ポップアップ画面で右側の下にある「Languages」と言うドロップダウンメニューから日本語を選択し、「OK」ボタンを押してください WinMerge を使う方 「ファイル」タッブから「開く」を押し 参照ボタンを押し、比較したいフォルダ・ファイルを指定 比較したいフォルダを指定する方法: ポップアップ画面から対象のフォルダーを選択し、「Open」を押してくだい 何も選択しないで、「Open」を押してくだい 右側下にある「比較」ボタンを押し ...

From Generic to Genius: Fine-tuning LLMs for Superior Accuracy in Snowflake

TL;DR: Cortex Fine-tuning is a fully managed service that lets you fine-tune popular LLMs using your data, all within Snowflake. While large language models (LLMs) are revolutionizing various fields, their "out-of-the-box" capabilities might not always align perfectly with your specific needs. This is where the power of fine-tuning comes into play. As it will be explained in this article, this feature empowers you to take a base LLM and customize it to excel in your particular domain. Here's the brief summary of why you might want to leverage Snowflake's fine-tuning capabilities: Unlocking Domain Expertise : Pre-trained LLMs are trained on massive, general datasets. Fine-tuning allows you to build upon this foundation and train the LLM further using data specific to your field, such as legal documents, medical records, or financial data. This empowers the LLM to understand complex terminology and patterns unique to your domain, leading to more accurate a...

脱初心者! Git ワークフローを理解して開発効率アップ

Git – チーム開発に必須のバージョン管理システムですが、その真価を発揮するにはワークフローの理解が欠かせません。 色々な人は Git の使い方を良く知っていますが、Git を仕事やワークフローに統合する方法を余り良く知らない人もいます。本記事では、Git をワークフローに組み込むことで、開発プロセスがどのように効率化され、チーム全体のパフォーマンスが向上するのかを解説します。Centralized Workflow から Forking Workflow まで、代表的な 9 つのワークフローの特徴を分かりやすく紹介します。それぞれのメリット・デメリット、そして最適なユースケースを理解することで、あなたのプロジェクトに最適なワークフローを選択し、開発をスムーズに進めましょう! Centralized Workflow Feature branching/GitHub Flow Trunk Based Flow Git Feature Flow Git Flow Enhanced Git Flow One Flow GitLab Flow Forking Workflow 分かりやすくするために、同じコンセプトを説明するに一つ以上の図を使った場合があります。 Centralized Workflow 説明: 集中化ワークフローではプロジェクトにおけるすべての変更の単一の入力箇所として中央リポジトリを使用します。デフォルトの開発用ブランチは main と呼ばれ、すべての変更がこのブランチにコミットされます。 集中化ワークフローでは main 以外のブランチは不要です。チームメンバー全員がひとつのブランチで作業し、変更を直接中央リポジトリにプッシュします。 メリット: SVN のような集中型バージョン管理システムから移行する小規模チームに最適。 デメリット: お互いのコードが邪魔になり (お互いの変更を上書きするように)、プロダクション環境にバグをい入れる可能性が高くて、複数のメンバいるチームでこのフローを使いにくい。 地図: graph TD; A[Central Repository] -->|Clone| B1[Developer A's Local Repo] A --...

Streamline Your Workflow: Send Snowflake Alerts to Slack

Do you know integrating Snowflake and Slack can make your life as a data engineer much easier?  Here's why: Real-time error catching and debugging : Instead of constantly checking logs for errors, you can set up Snowflake to automatically ping you in a Slack channel when something goes wrong. This is like having a dedicated assistant who watches for errors in your code and immediately lets you know so you can fix them faster. This is achieved through the use of webhooks, which are essentially automated HTTP requests that Snowflake sends to Slack when triggered by an event. Keep everyone in the loop : Slack integration also means you can keep your entire team informed about the status of data pipelines and other processes. You can configure Snowflake to send notifications to a shared channel whenever a pipeline completes, fails, or encounters an issue. This keeps everyone on the same page and avoids unnecessary status update meetings. This integration turns Slack ...

SQLFluff入門:SQLコードをクリーンかつエラーフリーに

コードを書いた後に実行したとき、エラーが発生するとイライラします。さらに厄介なのは、そのエラーの原因が分からないときです。また、複数のメンバーがいる大規模なプロジェクトでは、メンバーごとにコードの書き方が異なる傾向があり、その結果、コードレビューが難しくなり、ソースコードに不整合が生じます。コードを実行する前にエラーを検出できた方が良いと思いませんか?さらに、チームメンバー全員が同じフォーマットでコードを書けば、もっと効率的になるでしょう。 SQLFluffと言うツールがこの全ての事を実現させます。 SQLFluffは何でしょう? SQLFluffは、SQLファイル用の最も人気のあるリンターです。構文エラーを検出すると、そのエラーが発生した行番号や位置、エラーの原因が表示されます。SQLFluffはエラーの検出だけでなく、SQLコードのフォーマットや構文エラーの修正も可能です。PostgreSQL、MySQL、Google BigQuery、Snowflakeなど、複数の SQL 言語 をサポートしています。つまり、SQLコードを実行する前に構文エラーを検出・修正できるので、非常に役立ち、重要な作業に集中することができます。また、SQLFluffは非常に設定が簡単で、コンマの位置、文字の大文字小文字、インデントなどのルールを簡単に設定できます。 エンジニアは自分のパソコンにSQLFluffをインストールし、SQLFluffを利用してコードのエラーを検出・修正した後にGitにコミットし、GitLabやGitHubなどにプッシュすることをお勧めします。 全てのドキュメントはこちらにあります : Docs 。 インストール SQLFluff は以下のようにインストールできます VSCode エクステンション プリコミットフック コマンドラインツール CI/CDパイプラインツール SQLFluffをコマンドラインツールとして設定し、実行してくださいのが一番簡単です。また、この記事でプレコミットフックとしての使い方も説明します。 SQLFluffをコマンドラインツールとしてインストール 注意点: SQLFluffをインストールするにはPythonとpip (またはpoetryやpipenvなどのパッケージマネージャ)が必要です。この...