Skip to content

Instantly share code, notes, and snippets.

@ycku
Created April 14, 2023 02:05
Show Gist options
  • Save ycku/37749bbe6b8b21288ca74a5c171584d1 to your computer and use it in GitHub Desktop.
Save ycku/37749bbe6b8b21288ca74a5c171584d1 to your computer and use it in GitHub Desktop.
檢查 query 語法是否能在 PostgreSQL 中執行,回傳 SQLSTATE
-- SELECT sqlcheck('select * from not_exist_table');
-- 42P01: undefined_table
-- SELECT sqlcheck('select * from not_exist_table wrong_syntax');
-- 42601: syntax_error
-- 語法檢查會優先於物件檢查
CREATE OR REPLACE FUNCTION sqlcheck(query text) RETURNS text AS
$$
DECLARE
sql text;
code text;
BEGIN
code='00000';
sql='EXPLAIN '||query;
EXECUTE sql;
RETURN code;
EXCEPTION WHEN OTHERS THEN
GET STACKED DIAGNOSTICS
code=RETURNED_SQLSTATE;
RETURN code;
END;
$$ language 'plpgsql';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment