Skip to content

Commit 1a30ef7

Browse files
authored
Merge pull request #13 from Bibimbap-Team/12-setup-database
Setup database
2 parents cfde571 + a0a56f2 commit 1a30ef7

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

.env

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
DATABASE_URL="postgres://postgres:password@localhost:5432/bibimbap"
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
CREATE TABLE member (
2+
id uuid NOT NULL PRIMARY KEY,
3+
name TEXT NOT NULL,
4+
email TEXT NOT NULL UNIQUE,
5+
created_at timestamptz NOT NULL
6+
);

scripts/init_db.sh

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#!/usr/bin/env bash
2+
set -x
3+
set -eo pipefail
4+
5+
# Check that both psql and sqlx-cli are installed
6+
if ! [ -x "$(command -v psql)" ]; then
7+
echo "Error: psql is not installed."
8+
exit 1
9+
fi
10+
11+
if ! [ -x "$(command -v sqlx)" ]; then
12+
echo "Error: sqlx is not installed."
13+
echo >&2 "Use:"
14+
echo >&2 " cargo install --version=\"0.8.0\" sqlx-cli --no-default-features --features rustls,postgres"
15+
echo >&2 " to install it."
16+
exit 1
17+
fi
18+
19+
DB_USER=${POSTGRES_USER:=postgres}
20+
DB_PASSWORD="${POSTGRES_PASSWORD:=password}"
21+
DB_NAME="${POSTGRES_DB:=bibimbap}"
22+
DB_PORT="${POSTGRES_PORT:=5432}"
23+
DB_HOST="${POSTGRES_HOST:=localhost}"
24+
25+
# Launch Postgres using Docker
26+
# Allow skipping Docker if a dockerized Postgres database is already running
27+
if [[ -z "${SKIP_DOCKER}" ]]
28+
then
29+
docker run \
30+
-e POSTGRES_USER=${DB_USER} \
31+
-e POSTGRES_PASSWORD=${DB_PASSWORD} \
32+
-e POSTGRES_DB=${DB_NAME} \
33+
-p "${DB_PORT}":5432 \
34+
-d postgres \
35+
postgres -N 1000
36+
fi
37+
38+
export PGPASSWORD="${DB_PASSWORD}"
39+
until psql -h "${DB_HOST}" -U "${DB_USER}" -p "${DB_PORT}" -d "postgres" -c '\q'; do
40+
>&2 echo "Postgres is still unavailable - sleeping"
41+
sleep 1
42+
done
43+
44+
>&2 echo "Postgres is up and running on port ${DB_PORT} - running migrations now!"
45+
46+
DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}
47+
export DATABASE_URL
48+
sqlx database create
49+
sqlx migrate run
50+
51+
>&2 echo "Postgres has been migrated, ready to go!"

0 commit comments

Comments
 (0)