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

From Dmitry Savenko
Subject How to get the size of JSONB in bytes?
Date
Msg-id 1450185603.3748585.467962769.17EA0B11@webmail.messagingengine.com
Whole thread Raw
Responses Re: How to get the size of JSONB in bytes?  (Petr Korobeinikov <pkorobeinikov@gmail.com>)
List pgsql-general
Hi,
 
I want to impose size restrictions on JSONB documents stored in my table. Say, no document over 10Kb must be inserted in the table. For that, I try to write a trigger like this (jdoc here is of JSONB type):
 
create function check_document() returns trigger as $$
begin
    if 10 * 1024 < octet_length(new.jdoc::bytea) then
        raise exception 'Document is too big';
    end if;
    return new;
end
$$ language plpgsql;
 
create trigger check_document_trg
    before insert or update
    on documents
    for each row
    execute procedure check_document();
 
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?
 
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.
 
Best regards,
Dmitry.

pgsql-general by date:

Previous
From: Paul
Date:
Subject: Re: Trigger function, C, lookup of attribute type
Next
From: Petr Korobeinikov
Date:
Subject: Re: How to get the size of JSONB in bytes?