about summary refs log tree commit diff stats
path: root/tests_integration/pg_helper.sh
blob: 73c5ac194a50cb6b75e6448cc90580f20630ea14 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#!/usr/bin/env bash
#
# PostgreSQL lifecycle helper for integration tests.
# Manages a temporary PG instance: init, start, stop, db creation.
#
# Usage:
#   pg_helper.sh init        — initialize data directory
#   pg_helper.sh start       — start the server
#   pg_helper.sh stop        — stop the server
#   pg_helper.sh create-db   — create the test database
#   pg_helper.sh drop-db     — drop the test database
#   pg_helper.sh status      — print status
#
# Environment variables (with defaults):
#   __EPUBE_PG_PORT        — port for the test PG instance (default: 55432)
#   __EPUBE_PG_DATA_DIR    — temp data directory (default: auto-created in /tmp)
#   __EPUBE_PG_USER        — database user (default: epube_test)
#   __EPUBE_PG_PASS        — database password (default: epube_test)
#   __EPUBE_PG_DB          — database name (default: epube_test)
#   __EPUBE_PG_BIN_DIR     — PostgreSQL bin directory (default: detected)
#

set -euo pipefail

# ── Helpers ──────────────────────────────────────────────────────────────────

log() {
	echo "[$(date '+%H:%M:%S')] [pg_helper] $*"
}

die() {
	echo "ERROR: $*" >&2
	exit 1
}

wait_for_pg() {
	local max_wait="${1:-30}"
	local waited=0

	while ! "$PG_BIN_DIR"/pg_isready -h localhost -p "$PG_PORT" -q 2>/dev/null; do
		if (( waited >= max_wait )); then
			die "PostgreSQL did not start within ${max_wait}s"
		fi
		sleep 0.5
		(( waited++ ))
	done
}

# ── Configuration ────────────────────────────────────────────────────────────

PG_PORT="${__EPUBE_PG_PORT:-55432}"
PG_USER="${__EPUBE_PG_USER:-epube_test}"
PG_PASS="${__EPUBE_PG_PASS:-epube_test}"
PG_DB="${__EPUBE_PG_DB:-epube_test}"

# Superuser for admin operations (created by initdb, matches OS user)
PG_SUPERUSER="${__EPUBE_PG_SUPERUSER:-$(whoami)}"

# Auto-detect PG bin directory
if [[ -n "${__EPUBE_PG_BIN_DIR:-}" ]]; then
	PG_BIN_DIR="$__EPUBE_PG_BIN_DIR"
else
	# Try common locations for PostgreSQL
	for candidate in \
		"/usr/bin" \
		"/usr/lib/postgresql/16/bin" \
		"/usr/local/pgsql/bin" \
	; do
		if [[ -x "$candidate/pg_ctl" ]]; then
			PG_BIN_DIR="$candidate"
			break
		fi
	done
	[[ -z "${PG_BIN_DIR:-}" ]] && die "Cannot find pg_ctl. Set __EPUBE_PG_BIN_DIR."
fi

# Create a unique temp data directory (use PID to avoid collisions)
if [[ -n "${__EPUBE_PG_DATA_DIR:-}" ]]; then
	PG_DATA_DIR="$__EPUBE_PG_DATA_DIR"
else
	# Use a deterministic name based on port so init/start/use all share the same dir
	PG_DATA_DIR="/tmp/ttrss-pg-${PG_PORT}"
fi

PG_LOG_FILE="$PG_DATA_DIR/pg.log"
PG_PID_FILE="$PG_DATA_DIR/postmaster.pid"

# ── Commands ─────────────────────────────────────────────────────────────────

cmd_init() {
	if [[ -f "$PG_DATA_DIR/PG_VERSION" ]]; then
		log "Data directory already initialized: $PG_DATA_DIR"
		return 0
	fi
	log "Initializing PostgreSQL data directory: $PG_DATA_DIR"
	"$PG_BIN_DIR"/initdb --auth=trust --auth-host=md5 --encoding=UTF8 -D "$PG_DATA_DIR" 2>&1 | tail -3
	log "Data directory initialized."
}

cmd_start() {
	if [[ -f "$PG_PID_FILE" ]] && "$PG_BIN_DIR"/pg_isready -h localhost -p "$PG_PORT" -q 2>/dev/null; then
		log "PostgreSQL already running on port $PG_PORT."
		return 0
	fi

	log "Starting PostgreSQL on port $PG_PORT ..."
	"$PG_BIN_DIR"/pg_ctl start \
		-D "$PG_DATA_DIR" \
		-l "$PG_LOG_FILE" \
		-o "-c port=$PG_PORT -c unix_socket_directories=." \
		-w

	# Trust all local connections (TCP and socket) for testing
	cat > "$PG_DATA_DIR/pg_hba.conf" <<'HBA'
# TYPE  DATABASE        USER            ADDRESS                 METHOD
local   all             all                                     trust
host    all             all             127.0.0.1/32            trust
host    all             all             ::1/128                 trust
HBA

	# Reload to pick up new pg_hba.conf
	"$PG_BIN_DIR"/pg_ctl reload -D "$PG_DATA_DIR" -w

	wait_for_pg 30
	log "PostgreSQL started on port $PG_PORT."
}

cmd_stop() {
	if [[ ! -f "$PG_PID_FILE" ]]; then
		log "PostgreSQL not running."
		return 0
	fi

	log "Stopping PostgreSQL ..."
	"$PG_BIN_DIR"/pg_ctl stop -D "$PG_DATA_DIR" -w 2>/dev/null || true
	rm -f "$PG_PID_FILE"
	log "PostgreSQL stopped."
}

cmd_create_user() {
	log "Creating user '$PG_USER' ..."
	"$PG_BIN_DIR"/createuser -h localhost -p "$PG_PORT" -U "$PG_SUPERUSER" --superuser "$PG_USER" 2>/dev/null || true
	log "User ready."
}

cmd_create_db() {
	log "Creating database '$PG_DB' ..."
	# Create user first if it doesn't exist
	"$PG_BIN_DIR"/createuser -h localhost -p "$PG_PORT" -U "$PG_SUPERUSER" --superuser "$PG_USER" 2>/dev/null || true
	"$PG_BIN_DIR"/createdb -h localhost -p "$PG_PORT" -U "$PG_SUPERUSER" "$PG_DB" 2>/dev/null || true
	log "Database ready."
}

cmd_drop_db() {
	log "Dropping database '$PG_DB' ..."
	"$PG_BIN_DIR"/dropdb -h localhost -p "$PG_PORT" -U "$PG_USER" "$PG_DB" --if-exists 2>/dev/null || true
}

cmd_status() {
	if [[ -f "$PG_PID_FILE" ]]; then
		echo "running (pid: $(cat "$PG_PID_FILE" | head -1))"
	else
		echo "stopped"
	fi
}

# ── Main ─────────────────────────────────────────────────────────────────────

case "${1:-help}" in
	init)       cmd_init ;;
	start)      cmd_start ;;
	stop)       cmd_stop ;;
	create-user) cmd_create_user ;;
	create-db)  cmd_create_db ;;
	drop-db)    cmd_drop_db ;;
	status)     cmd_status ;;
	cleanup)    cmd_stop; rm -rf "$PG_DATA_DIR"; log "Cleaned up $PG_DATA_DIR" ;;
	*)
		echo "Usage: $0 {init|start|stop|create-user|create-db|drop-db|status|cleanup}"
		exit 1
		;;
esac