forked from rin-nas/postgresql-patterns-library
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathis_sql.sql
More file actions
40 lines (39 loc) · 1.17 KB
/
is_sql.sql
File metadata and controls
40 lines (39 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
-- check SQL syntax exactly in your PostgreSQL version
CREATE OR REPLACE FUNCTION is_sql(sql text, is_notice boolean default false)
returns boolean
returns null on null input
parallel unsafe --(ERROR: cannot start subtransactions during a parallel operation)
language plpgsql
AS
$$
DECLARE
exception_sqlstate text;
exception_message text;
exception_context text;
BEGIN
BEGIN
EXECUTE E'DO $IS_SQL$ BEGIN\nRETURN;\n' || trim(trailing E'; \r\n\t' from sql) || E';\nEND; $IS_SQL$;';
EXCEPTION WHEN syntax_error THEN
GET STACKED DIAGNOSTICS
exception_sqlstate = RETURNED_SQLSTATE,
exception_message = MESSAGE_TEXT,
exception_context = PG_EXCEPTION_CONTEXT;
IF is_notice THEN
RAISE NOTICE 'exception_sqlstate = %', exception_sqlstate;
RAISE NOTICE 'exception_context = %', exception_context;
RAISE NOTICE 'exception_message = %', exception_message;
END IF;
RETURN FALSE;
END;
RETURN TRUE;
END
$$;
-- TEST
do $$
begin
--positive
assert is_sql('SELECT x');
--negative
assert not is_sql('SELECTx', true);
end;
$$;