Check syntax of sql for PostgreSQL
Low maintenance activity. Last release 14 months ago, commits in 0 of the last 26 weeks. Weaker on commit activity and recent releases.
pip install pgsanityPgSanity
PgSanity checks the syntax of Postgresql SQL files.
It does this by leveraging the ecpg command which is traditionally used for preparing C files with embedded SQL for compilation. However, as part of that preparation, ecpg checks the embedded SQL statements for syntax errors using the exact same parser that is in PostgreSQL.
So the approach that PgSanity takes is to take a file that has a list of bare SQL in it, make that file look like a C file with embedded SQL, run it through ecpg and let ecpg report on the syntax errors of the SQL.
Installation
Dependencies
- Python >= 3.9
- May also work with older Pythons >= 3
- ecpg
- Ubuntu/Debian:
sudo apt-get install libecpg-dev - RHEL/CentOS:
sudo yum install postgresql-devel - Arch:
sudo pacman -S postgresql-libs
- Ubuntu/Debian:
Getting PgSanity
PgSanity is available in the Python Package Index, so you can install it with pip or uv. Here's PgSanity's page on PyPI.
pip install pgsanityoruv pip install pgsanity- If you don't have pip you can get it on Ubuntu/Debian by running:
sudo apt install python3-pip
- If you don't have pip you can get it on Ubuntu/Debian by running:
It is also available in the FreeBSD ports as databases/pgsanity. You can install it with one of those commands:
pkg install py36-pgsanitypkg install py27-pgsanitycd /usr/ports/databases/pgsanity && make install clean
Usage
PgSanity accepts filenames as parameters and it will report SQL syntax errors which exist in those files. PgSanity will exit with a status code of 0 if the syntax of the SQL looks good and a 1 if any errors were found.
$ pgsanity file_with_sql.sql
$ echo $?
0
$ pgsanity good1.sql good2.sql bad.sql
bad.sql: line 1: ERROR: syntax error at or near "bogus_token"
$ echo $?
1
Since pgsanity can handle multiple filenames as parameters it is very comfortable to use with find & xargs.
$ find -name '*.sql' | xargs pgsanity
./sql/bad1.sql: line 59: ERROR: syntax error at or near ";"
./sql/bad2.sql: line 41: ERROR: syntax error at or near "insert"
./sql/bad3.sql: line 57: ERROR: syntax error at or near "update"