-- how to check whether a given text is a valid base64 encoded string in plain
-- (Postgre)SQL 
CREATE FUNCTION is_valid_base64(text) RETURNS boolean AS $$
  SELECT length($1) % 4 = 0 AND
         length(trim('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
                     from trim(trailing '=' from $1))) = 0 AND
         replace(encode(decode($1, 'base64'), 'base64'), E'\n', '') = $1;
$$ LANGUAGE SQL IMMUTABLE;
