
CREATE OR REPLACE FUNCTION now_utc() RETURNS timestamp without time zone
    LANGUAGE sql
    AS $$
SELECT now() at time zone 'utc'
$$;

CREATE OR REPLACE FUNCTION lu_on_row_update() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
BEGIN
NEW.updated_at := now_utc();
INSERT INTO lu_entities_history ("table", "data") VALUES(TG_TABLE_NAME, to_json(OLD));
return NEW;
END
$$;

CREATE OR REPLACE FUNCTION lu_on_row_update_no_history() RETURNS trigger
    LANGUAGE plpgsql
    AS $$

BEGIN
NEW.updated_at := now_utc();
return NEW;
END

$$;



CREATE TABLE articles (
  id character varying(255) NOT NULL,
  text text NOT NULL,
  picture_url text,
  picture_caption text,
  type character varying(255) NOT NULL,
  created_at timestamp without time zone DEFAULT now_utc() NOT NULL,
  updated_at timestamp without time zone
);

CREATE TABLE articles_fields (
  article_id character varying(255) NOT NULL,
  property character varying(255) NOT NULL,
  "value" text NOT NULL,
  type character varying(255) NOT NULL
);


ALTER TABLE articles
  ADD CONSTRAINT articles_pkey PRIMARY KEY (id);

ALTER TABLE articles_fields
  ADD CONSTRAINT articles_fields_pkey PRIMARY KEY (article_id, property);

ALTER TABLE articles_fields
  ADD CONSTRAINT articles_fields_article_id_fkey FOREIGN KEY (article_id) REFERENCES articles(id) ON UPDATE CASCADE ON DELETE CASCADE;

CREATE TRIGGER articles_lu_on_row_update_no_history
  BEFORE UPDATE ON articles
  FOR EACH ROW
  EXECUTE PROCEDURE lu_on_row_update_no_history();
