Towards Dev

A publication for sharing projects, ideas, codes, and new theories.

Follow publication

evaluate() PostgreSQL Function for Evaluating Stored Expressions (Part 2)

Christoph Bussler
Towards Dev
Published in
3 min readDec 20, 2022

--

Syntactic correctness of stored expressions

Checking correctness of stored expressions

Insert and update trigger

CREATE TRIGGER check_expression
BEFORE INSERT OR UPDATE
ON customer
FOR EACH ROW
EXECUTE FUNCTION check_expression();

check_expression() function

CREATE OR REPLACE FUNCTION check_expression()
RETURNS TRIGGER
LANGUAGE plpgsql
AS
$$
DECLARE
v_expression_valid BOOLEAN;
v_expression VARCHAR;
v_empty_object JSONB;
v_exception_text VARCHAR;
v_exception_hint VARCHAR;
v_message VARCHAR;
v_hint VARCHAR;

BEGIN
v_expression = NEW.interest;
v_empty_object = '{}';
BEGIN
v_expression_valid = evaluate(
v_empty_object, v_expression);
EXCEPTION
WHEN OTHERS THEN
GET STACKED DIAGNOSTICS
v_exception_text = MESSAGE_TEXT,
v_exception_hint = PG_EXCEPTION_HINT;
v_message = 'Expression is incorrect: ' ||
v_expression;
v_hint = v_exception_text || '; ' || v_exception_hint;
RAISE EXCEPTION '%', v_message USING HINT = v_hint;
END;
RETURN NEW;
END;
$$;
[P0001] ERROR: Expression is incorrect: 
(object -> 'price')::int < 100000 and object >> 'color' = 'silver'
[2022-12-17 06:25:34] Hint: operator does not exist:
jsonb >> unknown; No operator matches the given name and
argument types. You might need to add explicit type casts.

Improvements

Summary

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response