Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Created November 15, 2024 17:01
Show Gist options
  • Save jgaskins/41719f1dff8eaf09855dd6af1c247d3b to your computer and use it in GitHub Desktop.
Save jgaskins/41719f1dff8eaf09855dd6af1c247d3b to your computer and use it in GitHub Desktop.
Parse Postgres TIMESTAMPs from JSON blobs
CREATE FUNCTION text_to_timestamp(text) RETURNS TIMESTAMP
LANGUAGE sql IMMUTABLE AS
$$
SELECT CASE
WHEN $1 ~ '^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(\.\d+)?$' THEN
CAST($1 AS timestamp without time zone)
END
$$;
CREATE TABLE t (
id SERIAL NOT NULL,
title VARCHAR(255) generated always as (item ->> 'title') stored,
start_date TIMESTAMP generated always as (text_to_timestamp(item ->> 'startDate')) stored,
item JSONB NOT NULL,
PRIMARY KEY(id)
)
@dbu
Copy link

dbu commented Nov 16, 2024

thanks a lot for these insights! i will add a thankyou in my talk at Symfony Con

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment