Skip to content

Commit

Permalink
feat: create-db.sh
Browse files Browse the repository at this point in the history
  • Loading branch information
yamcodes committed Oct 9, 2023
1 parent 145492c commit 24e94f6
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 2 deletions.
2 changes: 1 addition & 1 deletion .devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"studio": "bun db:studio"
},
// "postCreateCommand": "bun db:migrate && bun db:seed",
"postCreateCommand": "./scripts/wait-for-it.sh db:5432 -t 60 -- bun db:migrate && bun db:seed",
"postCreateCommand": "./scripts/create-db.sh",
"customizations": {
"vscode": {
"extensions": [
Expand Down
6 changes: 5 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ services:
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
- POSTGRES_DB=${POSTGRES_DB}
healthcheck:
test: [ "CMD-SHELL", "pg_isready -d medium -U postgres" ]
test:
[
"CMD-SHELL",
"PGPASSWORD=$${POSTGRES_PASSWORD} psql -U $${POSTGRES_USER} -d $${POSTGRES_DB} -c 'SELECT 1;' || exit 1"
]
interval: 1s
timeout: 5s
retries: 10
Expand Down
7 changes: 7 additions & 0 deletions scripts/create-db.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/bin/bash

# Source .env file to get environment variables
source .env

# Run wait-for-it.sh with the sourced environment variables
./wait-for-it.sh db:5432 -- strict --timeout=60 -- psql -h db -U ${POSTGRES_USER} -d ${POSTGRES_DB} -c 'SELECT 1;' && bun db:migrate && bun db:seed
18 changes: 18 additions & 0 deletions scripts/wait-for-it.sh → scripts/wait-for-db.sh
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
#!/usr/bin/env bash

# wait-for-db.sh modifies wait-for-it.sh to work with postgresql by waiting for a specific database to be ready
# see original: https://github.com/vishnubob/wait-for-it

# Use this script to test if a given TCP host/port are available

WAITFORIT_cmdname=${0##*/}
Expand Down Expand Up @@ -179,4 +183,18 @@ if [[ $WAITFORIT_CLI != "" ]]; then
exec "${WAITFORIT_CLI[@]}"
else
exit $WAITFORIT_RESULT
fi

# wait for db
if [ "$WAITFORIT_TIMEOUT" -gt 0 ]; then
echo "wait-for-db.sh: timeout occurred after waiting $WAITFORIT_TIMEOUT seconds for $WAITFORIT_HOST:$WAITFORIT_PORT"
else
echo "wait-for-db.sh: $WAITFORIT_HOST:$WAITFORIT_PORT is available after $((WAITFORIT_end_ts - WAITFORIT_start_ts)) seconds"
PGPASSWORD=${POSTGRES_PASSWORD} psql -h $HOST -U ${POSTGRES_USER} -d ${POSTGRES_DB} -c 'SELECT 1;' &>/dev/null
if [ $? -eq 0 ]; then
echo "wait-for-db.sh: database is ready"
else
echo "wait-for-db.sh: database is not ready"
exit 1
fi
fi

0 comments on commit 24e94f6

Please sign in to comment.