Reputation: 3519
I need to create a new database using PostgreSQL and need to initialise the "database" by creating the database and the tables.
I was thinking of creating a init.sql file and using the file
together with Docker
when initialising the docker image.
I need an example which takes care of initialising
(creating schemas and tables conditionally based on schema versions) the database.
I have the following pseudo example and would like to see a real Postgres example.
pseudo example:
1) create database if it does not exist
2) set or increment database design version
// create version 0 tables
3) create tables if it does not exist
// create version 1 tables
4) create future version tables and apply table alterations
Upvotes: 2
Views: 386
Reputation: 1373
CREATE DATABASE can only be executed as a single statement. So it cannot be run inside a function or DO statement.
And
DO
$do$
BEGIN
IF EXISTS (SELECT 1 FROM pg_database WHERE datname = 'mydb') THEN
RAISE NOTICE 'Database already exists';
ELSE
PERFORM dblink_exec('dbname=' || current_database() -- current db
, 'CREATE DATABASE mydb');
END IF;
END
$do$;
Upvotes: 2