3 # Test suite for pg_scribe --init command
6 # - Creates temporary test databases
7 # - Tests various --init scenarios
8 # - Verifies expected outcomes
9 # - Cleans up all resources
14 # Colors for test output
19 NC='\033[0m' # No Color
22 SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
23 PG_SCRIBE="$SCRIPT_DIR/scripts/pg_scribe"
24 TEST_DIR="/tmp/pg_scribe_test_$$"
25 TEST_DB_PREFIX="pg_scribe_test_$$"
26 PGUSER="${PGUSER:-postgres}"
34 DATABASES_TO_CLEANUP=()
41 echo -e "${BLUE}TEST:${NC} $*"
45 echo -e "${GREEN}PASS:${NC} $*"
50 echo -e "${RED}FAIL:${NC} $*"
55 echo -e "${YELLOW}INFO:${NC} $*"
65 psql -U "$PGUSER" -d "$dbname" -tAq "$@"
71 run_psql "$dbname" -c "$query" 2>/dev/null || true
76 log_info "Creating test database: $dbname"
79 psql -U "$PGUSER" -d postgres -c "DROP DATABASE IF EXISTS $dbname;" &>/dev/null || true
82 psql -U "$PGUSER" -d postgres -c "CREATE DATABASE $dbname;" &>/dev/null
84 DATABASES_TO_CLEANUP+=("$dbname")
87 # shellcheck disable=SC2317 # Function called from cleanup trap handler
90 log_info "Dropping test database: $dbname"
92 # Terminate connections
93 psql -U "$PGUSER" -d postgres -c "
94 SELECT pg_terminate_backend(pid)
96 WHERE datname = '$dbname' AND pid <> pg_backend_pid();
100 psql -U "$PGUSER" -d postgres -c "DROP DATABASE IF EXISTS $dbname;" &>/dev/null || true
103 # shellcheck disable=SC2317 # Function called from cleanup trap handler
104 drop_replication_slot() {
107 log_info "Dropping replication slot: $slot"
109 # Check if slot exists
111 exists=$(query_db "$dbname" "
112 SELECT 1 FROM pg_replication_slots WHERE slot_name = '$slot';
115 if [[ -n "$exists" ]]; then
117 query_db "$dbname" "SELECT pg_drop_replication_slot('$slot');" || true
121 check_slot_exists() {
125 exists=$(query_db "$dbname" "
126 SELECT 1 FROM pg_replication_slots WHERE slot_name = '$slot';
131 check_extension_exists() {
135 exists=$(query_db "$dbname" "
136 SELECT 1 FROM pg_extension WHERE extname = '$extension';
141 create_table_with_pk() {
145 CREATE TABLE $table (
146 id SERIAL PRIMARY KEY,
148 created_at TIMESTAMP DEFAULT now()
153 create_table_without_pk() {
157 CREATE TABLE $table (
168 test_basic_init_success() {
170 log_test "Basic --init success"
172 local dbname="${TEST_DB_PREFIX}_basic"
173 local slot="test_slot_basic"
174 local backup_dir="$TEST_DIR/basic"
177 create_test_db "$dbname"
178 create_table_with_pk "$dbname" "users"
179 mkdir -p "$backup_dir"
182 if "$PG_SCRIBE" --init -d "$dbname" -f "$backup_dir" -S "$slot" -U "$PGUSER" &>/dev/null; then
183 # Verify slot created
184 if ! check_slot_exists "$dbname" "$slot"; then
185 log_fail "Replication slot not created"
189 # Verify extension installed
190 if ! check_extension_exists "$dbname" "wal2sql"; then
191 log_fail "wal2sql extension not installed"
195 # Verify files created (use compgen to check for glob matches)
196 local base_files=("$backup_dir"/base-*.sql)
197 if [[ ! -f "${base_files[0]}" ]]; then
198 log_fail "Base backup file not created"
202 local globals_files=("$backup_dir"/globals-*.sql)
203 if [[ ! -f "${globals_files[0]}" ]]; then
204 log_fail "Globals backup file not created"
208 if [[ ! -f "$backup_dir/pg_scribe_metadata.txt" ]]; then
209 log_fail "Metadata file not created"
213 # Verify metadata content
214 if ! grep -q "Database: $dbname" "$backup_dir/pg_scribe_metadata.txt"; then
215 log_fail "Metadata missing database name"
219 if ! grep -q "Replication Slot: $slot" "$backup_dir/pg_scribe_metadata.txt"; then
220 log_fail "Metadata missing slot name"
224 log_pass "Basic init successful"
227 log_fail "Init command failed"
232 test_init_validation_failure() {
234 log_test "Init validation failure (table without replica identity)"
236 local dbname="${TEST_DB_PREFIX}_nopk"
237 local slot="test_slot_nopk"
238 local backup_dir="$TEST_DIR/nopk"
240 # Setup - create table WITHOUT primary key
241 create_test_db "$dbname"
242 create_table_without_pk "$dbname" "bad_table"
243 mkdir -p "$backup_dir"
245 # Run init - should fail with exit code 5
247 "$PG_SCRIBE" --init -d "$dbname" -f "$backup_dir" -S "$slot" -U "$PGUSER" &>/dev/null || exit_code=$?
249 if [[ $exit_code -eq 5 ]]; then
250 # Verify slot was NOT created
251 if check_slot_exists "$dbname" "$slot"; then
252 log_fail "Replication slot should not be created on validation failure"
256 log_pass "Validation failure detected correctly"
259 log_fail "Expected exit code 5, got $exit_code"
264 test_init_force_flag() {
266 log_test "Init with --force flag (bypass validation)"
268 local dbname="${TEST_DB_PREFIX}_force"
269 local slot="test_slot_force"
270 local backup_dir="$TEST_DIR/force"
272 # Setup - create table WITHOUT primary key
273 create_test_db "$dbname"
274 create_table_without_pk "$dbname" "bad_table"
275 mkdir -p "$backup_dir"
277 # Run init with --force - should succeed despite validation failure
278 if "$PG_SCRIBE" --init -d "$dbname" -f "$backup_dir" -S "$slot" -U "$PGUSER" --force &>/dev/null; then
279 # Verify slot was created
280 if ! check_slot_exists "$dbname" "$slot"; then
281 log_fail "Replication slot should be created with --force"
285 log_pass "Force flag bypassed validation"
288 log_fail "Init with --force should succeed"
293 test_init_non_idempotency() {
295 log_test "Init refuses to run on already-initialized directory"
297 local dbname="${TEST_DB_PREFIX}_nonidempotent"
298 local slot="test_slot_nonidempotent"
299 local backup_dir="$TEST_DIR/nonidempotent"
302 create_test_db "$dbname"
303 create_table_with_pk "$dbname" "users"
304 mkdir -p "$backup_dir"
306 # Run init first time
307 if ! "$PG_SCRIBE" --init -d "$dbname" -f "$backup_dir" -S "$slot" -U "$PGUSER" &>/dev/null; then
308 log_fail "First init failed"
312 # Run init second time - should FAIL with validation error
314 "$PG_SCRIBE" --init -d "$dbname" -f "$backup_dir" -S "$slot" -U "$PGUSER" &>/dev/null || exit_code=$?
316 if [[ $exit_code -eq 5 ]]; then
317 # Verify slot still exists from first init
318 if ! check_slot_exists "$dbname" "$slot"; then
319 log_fail "Replication slot should still exist from first init"
323 # Verify only 1 base backup file (from first init)
325 base_count=$(find "$backup_dir" -maxdepth 1 -name 'base-*.sql' 2>/dev/null | wc -l)
326 if [[ $base_count -ne 1 ]]; then
327 log_fail "Expected 1 base backup file, got $base_count"
331 log_pass "Init correctly refuses to reinitialize"
334 log_fail "Expected exit code 5 (validation error), got $exit_code"
339 test_init_multiple_tables() {
341 log_test "Init with multiple tables"
343 local dbname="${TEST_DB_PREFIX}_multi"
344 local slot="test_slot_multi"
345 local backup_dir="$TEST_DIR/multi"
347 # Setup - create multiple tables
348 create_test_db "$dbname"
349 create_table_with_pk "$dbname" "users"
350 create_table_with_pk "$dbname" "orders"
351 create_table_with_pk "$dbname" "products"
354 query_db "$dbname" "INSERT INTO users (name) VALUES ('Alice'), ('Bob');"
355 query_db "$dbname" "INSERT INTO orders (name) VALUES ('Order1');"
356 query_db "$dbname" "INSERT INTO products (name) VALUES ('Widget');"
358 mkdir -p "$backup_dir"
361 if "$PG_SCRIBE" --init -d "$dbname" -f "$backup_dir" -S "$slot" -U "$PGUSER" &>/dev/null; then
362 # Verify base backup contains all tables
364 base_file=$(find "$backup_dir" -maxdepth 1 -name 'base-*.sql' -print -quit)
366 if ! grep -q "CREATE TABLE public.users" "$base_file"; then
367 log_fail "Base backup missing users table"
371 if ! grep -q "CREATE TABLE public.orders" "$base_file"; then
372 log_fail "Base backup missing orders table"
376 if ! grep -q "CREATE TABLE public.products" "$base_file"; then
377 log_fail "Base backup missing products table"
381 log_pass "Multiple tables backed up successfully"
384 log_fail "Init failed"
389 test_init_with_unlogged_table() {
391 log_test "Init with unlogged table (warning but success)"
393 local dbname="${TEST_DB_PREFIX}_unlogged"
394 local slot="test_slot_unlogged"
395 local backup_dir="$TEST_DIR/unlogged"
398 create_test_db "$dbname"
399 create_table_with_pk "$dbname" "normal_table"
400 query_db "$dbname" "CREATE UNLOGGED TABLE unlogged_table (id SERIAL PRIMARY KEY, data TEXT);"
401 mkdir -p "$backup_dir"
403 # Run init - should succeed with warning (exit code 0 or 10)
404 local output_file="$TEST_DIR/unlogged_output.txt"
406 "$PG_SCRIBE" --init -d "$dbname" -f "$backup_dir" -S "$slot" -U "$PGUSER" &>"$output_file" || exit_code=$?
408 # Exit code 0 (success) or 10 (warning) are both acceptable
409 if [[ $exit_code -eq 0 || $exit_code -eq 10 ]]; then
410 # Check for warning message
411 if ! grep -i "unlogged" "$output_file"; then
412 log_fail "Expected warning about unlogged table"
416 # Verify backup was created
417 local base_files=("$backup_dir"/base-*.sql)
418 if [[ ! -f "${base_files[0]}" ]]; then
419 log_fail "Base backup file not created"
423 log_pass "Unlogged table warning shown correctly"
426 log_fail "Init failed with exit code $exit_code"
431 test_backup_content_validity() {
433 log_test "Verify backup SQL is valid"
435 local dbname="${TEST_DB_PREFIX}_valid"
436 local slot="test_slot_valid"
437 local backup_dir="$TEST_DIR/valid"
438 local restore_dbname="${TEST_DB_PREFIX}_restored"
441 create_test_db "$dbname"
442 create_table_with_pk "$dbname" "test_data"
443 query_db "$dbname" "INSERT INTO test_data (name) VALUES ('Test Row 1'), ('Test Row 2');"
444 mkdir -p "$backup_dir"
447 if ! "$PG_SCRIBE" --init -d "$dbname" -f "$backup_dir" -S "$slot" -U "$PGUSER" &>/dev/null; then
448 log_fail "Init failed"
452 # Try to restore the backup to a new database
453 create_test_db "$restore_dbname"
456 base_file=$(find "$backup_dir" -maxdepth 1 -name 'base-*.sql' -print -quit)
458 globals_file=$(find "$backup_dir" -maxdepth 1 -name 'globals-*.sql' -print -quit)
460 # Apply globals (roles, etc.)
461 if ! psql -U "$PGUSER" -d postgres -f "$globals_file" &>/dev/null; then
462 log_fail "Failed to restore globals"
467 if ! psql -U "$PGUSER" -d "$restore_dbname" -f "$base_file" &>/dev/null; then
468 log_fail "Failed to restore base backup"
474 count=$(query_db "$restore_dbname" "SELECT COUNT(*) FROM test_data;")
475 if [[ "$count" -ne 2 ]]; then
476 log_fail "Expected 2 rows, got $count"
480 log_pass "Backup SQL is valid and restorable"
488 # shellcheck disable=SC2317 # Function called via trap handler
490 log_info "Cleaning up test resources..."
492 # Drop replication slots
493 for dbname in "${DATABASES_TO_CLEANUP[@]}"; do
494 # Try to drop any slots for this database
495 for slot in test_slot_basic test_slot_nopk test_slot_force test_slot_nonidempotent test_slot_multi test_slot_unlogged test_slot_valid; do
496 drop_replication_slot "$dbname" "$slot" 2>/dev/null || true
501 for dbname in "${DATABASES_TO_CLEANUP[@]}"; do
502 drop_test_db "$dbname"
505 # Remove test directory
506 if [[ -d "$TEST_DIR" ]]; then
510 log_info "Cleanup complete"
518 echo "========================================"
519 echo "pg_scribe --init Test Suite"
520 echo "========================================"
523 # Verify pg_scribe exists
524 if [[ ! -x "$PG_SCRIBE" ]]; then
525 echo "ERROR: pg_scribe not found or not executable: $PG_SCRIBE"
529 # Verify PostgreSQL is running
530 if ! psql -U "$PGUSER" -d postgres -c "SELECT 1;" &>/dev/null; then
531 echo "ERROR: Cannot connect to PostgreSQL"
535 # Verify wal_level is logical
537 wal_level=$(psql -U "$PGUSER" -d postgres -tAq -c "SHOW wal_level;")
538 if [[ "$wal_level" != "logical" ]]; then
539 echo "ERROR: wal_level must be 'logical', currently: $wal_level"
540 echo "Update ~/.pgenv/pgsql/data/postgresql.conf and restart PostgreSQL"
544 # Create test directory
547 # Set up cleanup trap
548 trap cleanup EXIT INT TERM
550 echo "Running tests..."
553 # Run all tests (use || true to prevent set -e from exiting)
554 test_basic_init_success || true
555 test_init_validation_failure || true
556 test_init_force_flag || true
557 test_init_non_idempotency || true
558 test_init_multiple_tables || true
559 test_init_with_unlogged_table || true
560 test_backup_content_validity || true
564 echo "========================================"
566 echo "========================================"
567 echo "Tests run: $TESTS_RUN"
568 echo -e "Tests passed: ${GREEN}$TESTS_PASSED${NC}"
569 echo -e "Tests failed: ${RED}$TESTS_FAILED${NC}"
572 if [[ $TESTS_FAILED -eq 0 ]]; then
573 echo -e "${GREEN}All tests passed!${NC}"
576 echo -e "${RED}Some tests failed!${NC}"