Added lab script for timescaledb init

This commit is contained in:
marius 2023-05-06 13:04:57 +00:00
parent f3679bd834
commit d1778f78a4

View File

@ -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};"