Created
April 14, 2023 02:05
-
-
Save ycku/37749bbe6b8b21288ca74a5c171584d1 to your computer and use it in GitHub Desktop.
檢查 query 語法是否能在 PostgreSQL 中執行,回傳 SQLSTATE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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