From d245bbd600811762a74544aeff6086a6c94dd7f3 Mon Sep 17 00:00:00 2001
From: Chris Lovering <chris.lovering.95@gmail.com>
Date: Tue, 7 Sep 2021 09:59:18 +0100
Subject: Create and populate metricity in a single connection

---
 postgres/init.sql | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)

(limited to 'postgres/init.sql')

diff --git a/postgres/init.sql b/postgres/init.sql
index ea748480..ee1acd8d 100644
--- a/postgres/init.sql
+++ b/postgres/init.sql
@@ -1,3 +1,24 @@
+DO
+$do$
+DECLARE
+  _db TEXT := %s;
+  _user TEXT := %s;
+  _password TEXT := %s;
+BEGIN
+  CREATE EXTENSION IF NOT EXISTS dblink;
+  IF EXISTS (SELECT 1 FROM pg_database WHERE datname = _db) THEN
+    RAISE NOTICE 'Database already exists';
+  ELSE
+    PERFORM dblink_connect(
+        'host=localhost user=' || _user ||
+        ' password=' || _password ||
+        ' dbname=' || current_database()
+    );
+    PERFORM dblink_exec('CREATE DATABASE ' || _db);
+  END IF;
+END
+$do$;
+
 CREATE TABLE IF NOT EXISTS users (
     id varchar,
     joined_at timestamp,
-- 
cgit v1.2.3

