Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL syntax check without running the query

I want to verify the syntax of files containing sql queries before they can be committed in my CVS project.

In order to do that, I have a commitinfo script, but I have trouble finding out if the sql commands are valid. psql does not seem to have a dryrun mode, and constructing my own postgresql-dialact tester from the grammar (that is in the source) seems like a long stretch.

The scripts may contain multiple queries, so an EXPLAIN cannot be wrapped around them.

Any hints?

like image 336
Rob Audenaerde Avatar asked Nov 25 '11 16:11

Rob Audenaerde


People also ask

How do you check what queries are running in Postgres?

A simple select * from pg_stat_activity will provide a snapshot of what is happening on your PostgreSQL database, with one line per current transaction, and the key columns: datname: The database name that the query is running on.

What does <> mean in PostgreSQL?

<> is the standard SQL operator meaning "not equal". Many databases, including postgresql, supports != as a synonym for <> . They're exactly the same in postgresql.

Is there if statement in PostgreSQL?

PostgreSQL has an IF statement executes `statements` if a condition is true. If the condition evaluates to false, the control is passed to the next statement after the END IF part.


1 Answers

I recently wrote up a utility to statically check the syntax of SQL for PostgreSQL. It leverages ecpg, the embedded SQL C preproccessor for postgres, to check the SQL syntax, so it uses the exact same parser that is built in to Postgres itself.

You can check it out on github: http://github.com/markdrago/pgsanity. You can give the README a skim to get a better idea of how it works and to get directions for how to install it. Here's a short example of how pgsanity can be used:

$ pgsanity good1.sql good2.sql bad.sql bad.sql: line 1: ERROR: syntax error at or near "bogus_token"  $ 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" 
like image 131
Mark Drago Avatar answered Sep 21 '22 16:09

Mark Drago