DO
$$
DECLARE
  uid UUID;
BEGIN
  SELECT user_id
  INTO uid
  FROM user_emails
  WHERE email = $(email);

  IF uid IS NULL
  THEN
    INSERT INTO users (display_name) VALUES ($(displayName)) RETURNING id INTO uid;
    INSERT INTO user_emails (user_id, email, "primary") VALUES (uid, $(email), TRUE);
  END IF;
END;
$$;

SELECT user_id FROM user_emails WHERE email=$(email);