Re: How to get the size of JSONB in bytes? - Mailing list pgsql-general

From Petr Korobeinikov
Subject Re: How to get the size of JSONB in bytes?
Date
Msg-id CAJL5ff-emqZCzOodvjX3uQ97JhSs1hQTykaeCU_R8GRyfAhhLw@mail.gmail.com
Whole thread Raw
In response to How to get the size of JSONB in bytes?  (Dmitry Savenko <ds@dsavenko.com>)
Responses Re: How to get the size of JSONB in bytes?  (Jim Nasby <Jim.Nasby@BlueTreble.com>)
List pgsql-general
This doesn't work because it can't cast JSONB to 'bytea'. I tried casting to 'text', still no luck. Could anyone please help me?

You can use check-constraint like this:

# create table t (
    jb jsonb
);
# alter table t add constraint jb_length_check CHECK (length(jb::text) < 16); -- 16 is example value
# insert into t values ('{"key":"v"}');
INSERT 0 1
# insert into t values ('{"key":"value"}');
ERROR:  new row for relation "t" violates check constraint "jb_length_check"
DETAIL:  Failing row contains ({"key": "value"}).
 
Also, is there a better approach to impose a size limit, then writing triggers? I need it to be fairly flexible, e.g. 10Kb is not a constant, it may even be different for different documents (rows) in the same table.

The better approach is extract your length-validation logic into your application.

pgsql-general by date:

Previous
From: Dmitry Savenko
Date:
Subject: How to get the size of JSONB in bytes?
Next
From: Craig Ringer
Date:
Subject: Re: BDR