Re: How to get the size of JSONB in bytes?

From: Petr Korobeinikov <pkorobeinikov(at)gmail(dot)com>
To: Dmitry Savenko <ds(at)dsavenko(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: How to get the size of JSONB in bytes?
Date: 2015-12-15 14:24:23
Message-ID: CAJL5ff-emqZCzOodvjX3uQ97JhSs1hQTykaeCU_R8GRyfAhhLw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Craig Ringer 2015-12-15 15:00:15 Re: BDR
Previous Message Dmitry Savenko 2015-12-15 13:20:03 How to get the size of JSONB in bytes?