From d1778f78a4f0e6c6e84ab46631dfcd23901eddf4 Mon Sep 17 00:00:00 2001 From: marius Date: Sat, 6 May 2023 13:04:57 +0000 Subject: [PATCH] Added lab script for timescaledb init --- timescaledb/init_logsdb.sh | 44 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 timescaledb/init_logsdb.sh diff --git a/timescaledb/init_logsdb.sh b/timescaledb/init_logsdb.sh new file mode 100644 index 0000000..9eb884d --- /dev/null +++ b/timescaledb/init_logsdb.sh @@ -0,0 +1,44 @@ +#!/bin/bash +set -eu + +DB_NAME="logs" +DB_USER="myuser" +DB_PASSWORD="mypassword" +LOGS_USER="logs_user" +LOGS_USER_PASSWORD="logs_user_password" + +# Create the database +sudo -u postgres psql -c \ + "CREATE DATABASE ${DB_NAME} WITH ENCODING 'UTF-8' \ + LC_COLLATE 'en_US.UTF-8' LC_CTYPE 'en_US.UTF-8' TEMPLATE template0;" + +# Create the user +sudo -u postgres psql -c \ + "CREATE USER ${DB_USER} WITH PASSWORD '${DB_PASSWORD}';" +sudo -u postgres psql -c \ + "GRANT ALL PRIVILEGES ON DATABASE ${DB_NAME} TO ${DB_USER};" +sudo -u postgres psql -c \ + "ALTER USER ${DB_USER} VALID UNTIL 'infinity';" + +# Create the logs_user +sudo -u postgres psql -c \ + "CREATE USER ${LOGS_USER} WITH PASSWORD '${LOGS_USER_PASSWORD}';" + +# Enable the TimescaleDB extension +sudo -u postgres psql -d "${DB_NAME}" -c \ + "CREATE EXTENSION IF NOT EXISTS timescaledb CASCADE;" + +sudo -u postgres psql -d "${DB_NAME}" -c "CREATE EXTENSION IF NOT EXISTS timescaledb;" + + +# Create the logs table +sudo -u postgres psql -d "${DB_NAME}" -c "CREATE TABLE logs (id SERIAL, timestamp TIMESTAMPTZ NOT NULL, log_data JSONB NOT NULL, PRIMARY KEY (id, timestamp));" + + + +# Convert the table into a TimescaleDB hypertable +sudo -u postgres psql -d "${DB_NAME}" -c "CREATE TABLE logs (id SERIAL, timestamp TIMESTAMPTZ NOT NULL, log_data JSONB NOT NULL, PRIMARY KEY (id, timestamp));" + +# Grant INSERT privilege to logs_user on the logs table +sudo -u postgres psql -d "${DB_NAME}" -c \ + "GRANT INSERT ON TABLE logs TO ${LOGS_USER};" \ No newline at end of file