PostgreSQL syntax check without running the query

前端 未结 8 1814
时光取名叫无心
时光取名叫无心 2020-12-24 05:03

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 h

相关标签:
8条回答
  • 2020-12-24 05:34

    One way would be to put it into a transaction that you roll back at the end:

    BEGIN;
    <query>;
    <query>;
    <query>;
    ROLLBACK;
    

    Be aware that there are some effects that cannot be rolled back, like dblink calls, or anything written to the file system or incremented sequences.

    I would advise cloning your database for testing purposes.

    0 讨论(0)
  • 2020-12-24 05:35

    You could just wrap it in SELECT 1 ( <your query> ) AS a WHERE 1 = 0;

    It'll fail on validation but it won't actually execute. Here's an example query plan:

    Result  (cost=0.00..0.01 rows=1 width=0)
      One-Time Filter: false
    
    0 讨论(0)
  • 2020-12-24 05:36

    Use this trick to validate PostgreSQL code syntax:

    DO $SYNTAX_CHECK$ BEGIN RETURN;
        -- insert your SQL code here
    END; $SYNTAX_CHECK$;
    
    0 讨论(0)
  • 2020-12-24 05:38

    You can run queries iside postgresql function and raise exception in the end. All changes will be rolled back. For example:

    CREATE OR REPLACE FUNCTION run_test(_sp character varying)
      RETURNS character varying AS
    $BODY$
    BEGIN
      EXECUTE 'SELECT ' || _sp;
      RAISE EXCEPTION '#OK';
    EXCEPTION
      WHEN others THEN
        RETURN SQLERRM;
    END;
    $BODY$
      LANGUAGE plpgsql VOLATILE
      COST 100;
    

    Another sollution - plpgsql_check extension (on github), the next incarnation of pgpsql_lint

    0 讨论(0)
  • 2020-12-24 05:48

    EXPLAIN (without ANALYZE) will parse the query and prepare an execution plan, without actually executing it.

    https://www.postgresql.org/docs/current/static/sql-explain.html

    0 讨论(0)
  • 2020-12-24 05:53

    I'm usually use Mimer online SQL validator, the only thing is that it check SQL syntax for standard SQL :

    • SQL-92
    • SQL-99
    • SQL-03

    and not specific for the PostgreSQL ... However if you write code following the standard you can use it and it work well ...

    0 讨论(0)
提交回复
热议问题