Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@drj42
Forked from levlaz/types_and_roles_demo.sql
Created September 5, 2018 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drj42/76277a1d67b6433445608a9826d48eaf to your computer and use it in GitHub Desktop.
Save drj42/76277a1d67b6433445608a9826d48eaf to your computer and use it in GitHub Desktop.
Create Types and Roles If Not Exist in PostgreSQL
BEGIN;
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'task_status') THEN
create type task_status AS ENUM ('todo', 'doing', 'blocked', 'done');
END IF;
END
$$;
CREATE TABLE IF NOT EXISTS
tasks (
id integer PRIMARY KEY,
title varchar(200),
status task_status NOT NULL DEFAULT 'todo',
created_date timestamp
);
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'reader') THEN
CREATE ROLE reader;
END IF;
END
$$;
GRANT SELECT ON tasks TO reader;
COMMIT;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment