#!/bin/sh # Applies Nanga Kathai SQL (schema, then storage buckets) that has not been applied yet. # Safe to run again after adding new migration files. # # Usage: sh apply-migrations.sh [supabase-project-dir] set -eu HERE="$(cd "$(dirname "$0")" && pwd)" PROJECT="${1:-$HOME/nk-backend/supabase-project}" cd "$PROJECT" # Keep the project's copy in step with the repo. mkdir -p nk/migrations cp "$HERE/../supabase/migrations/"*.sql nk/migrations/ cp "$HERE/sql/"*.sql nk/sql/ PGPASSWORD="$(grep -E '^POSTGRES_PASSWORD=' .env | cut -d= -f2-)" psql_db() { docker compose exec -T -e PGPASSWORD="$PGPASSWORD" db \ psql -h localhost -U postgres -d postgres -v ON_ERROR_STOP=1 -q "$@" } psql_db -c "create table if not exists public.nk_schema_migrations ( name text primary key, applied_at timestamptz not null default now()); alter table public.nk_schema_migrations enable row level security;" for f in nk/migrations/*.sql nk/sql/*.sql; do name="$(basename "$f")" done_already="$(psql_db -tA -c "select 1 from public.nk_schema_migrations where name = '$name'")" if [ "$done_already" = "1" ]; then echo "skip $name" continue fi echo "apply $name" { cat "$f"; printf "\ninsert into public.nk_schema_migrations (name) values ('%s');\n" "$name"; } | psql_db -1 -f - done echo "Migrations up to date."