LoginSignup
3
3

More than 3 years have passed since last update.

PostgreSQLのクエリを静的チェックする

Last updated at Posted at 2019-07-19

PostgreSQLをつかってたり、あるいはAWS Redshiftを利用している場合、クエリのチェックをしたい時がある。

pgsanity を利用すると、クエリが有効であるかを確認できる。

インストール

$ pip install pgsanity

Getting PgSanity

動作確認

installすると、pgsanityコマンドが利用可能になる。引数として対象のsqlファイルを指定すればいい。

SQLクエリのサンプルを用意していて実行してみる。

target.sql
select * from hogehoge;

上記ファイルを対象として静的チェックするには以下のコマンドで可能だ。

command1
$ pgsanity target.sql

出力がない場合、静的チェックにおいては問題がない。

失敗時

ためしに、ファイルを以下のように変更してみる

target.sql
select * from;

すると、command1を実行してみると、以下のように結果がでる。

line 1: ERROR: syntax error at or near ";"

このように、構文のおかしいクエリを検出できる。

Pythonのテストコードとして利用

pgsanity をpythonのアプリのテストコードとして利用することも可能だ。

以下のようにクラスを発行するclassがあるとする。

sample.py
from textwrap import dedent

class Sample():
    def query(self):
        return dedent("""\
            select * from hoge;
        """)

# hoge = Sample()
# print(hoge.query()) -> select * from hoge;

これのテストコードは以下のようになる。

test_sample.py
import unittest
from sample import Sample
from pgsanity import pgsanity

class TestSample(unittest.TestCase):
    def test_query(self):
        hoge = Sample()
        result, message = pgsanity.check_string(hoge.query())
        self.assertTrue(result, 'failed:' + message)

実行してみる

$ python -m unittest discover -v

結果

test_query (test_sample.TestSample) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.010s

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