0

I have one SQL table in postgress database having multiple JSON type columns. We want to do some kind of validation on those JSON coulmns before inserting the data.

Our target is to have validation using stored procedure, which call noSQL queries and respond error in case of any validation failure on that JSON column.

Example -

lets say we have 5 to 6 JSON columns in User table, JSON columns like -

Personal Information, Accounts, OwnerDetails etc, and these coulmns having complex JSON like list of JSON data or JSON within JSON.

Now we want to validate each column one by one and in case of error, return unique error code.

1
  • I am not going to do your work. I showcased below how to proceed with the validation of columns of JSON datatype. Commented Nov 26, 2015 at 13:50

1 Answer 1

1

When using the JSON type, we can easily define constraints on the JSON fields. Here is a basic demonstration:

CREATE FUNCTION is_valid_description(descr text) RETURNS BOOLEAN AS
    'SELECT length($1) > 10;'
LANGUAGE sql;

CREATE TABLE wizards (
    id SERIAL, 
    data JSON,
    CONSTRAINT validate_name CHECK ((data->>'name') IS NOT NULL AND length(data->>'name') > 0),
    CONSTRAINT validate_description CHECK ((data->>'description') IS NOT NULL AND (is_valid_description(data->>'description')))
);

We check for constraints on two JSON fields of the data column. In one case, we use a stored procedure written in SQL, but we could write more complex functions with PL/pgSQL, or in Perl or Python.

We may also want to enforce uniqueness on one of the fields:

CREATE UNIQUE INDEX ui_wizards_name ON wizards((data->>'name'));

Validation and uniqueness constraints are then enforced when inserting or updating rows.

-- violates check constraint "validate_description" 
INSERT INTO wizards(data) VALUES('{
    "name": "Kirikou", 
    "description": "A witch"
}');

-- passes
INSERT INTO wizards(data) VALUES('{
    "name": "Kirikou", 
    "description": "A witch of African descent"
}');

-- violates unique constraint "ui_wizards_name"
INSERT INTO wizards(data) VALUES('{
    "name": "Kirikou", 
    "description": "The same witch of African descent"
}');

Code to play with on http://sqlfiddle.com/#!15/23974/2.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.