#!/usr/bin/env bash # Copy the published app's data from Replit onto the VM, replacing the # VM's: the production PostgreSQL database and Replit Database (the # key-value store). It asks for each; press Enter to skip one. Both are # fetched first; the app is stopped only while they're swapped in. Run it # from your computer, so nothing lands in a log: # ssh -t my-replit.exe.xyz bin/app-import # The database can also be a dump file already on the VM (pg_dump's plain # SQL or --format=custom), such as one made in Replit's Shell. # From https://exe.dev/deploy/migrate-replit set -euo pipefail exec 9>"$HOME/.deploy.lock" && flock 9 # not during a deploy db=app # the database in ~/postgres/app.env kvfile=$HOME/replitdb.sqlite mkdir -p -m 700 "$HOME/replit" read -rsp "Production database URL, or a dump file on the VM (Enter to skip): " pg; echo >&2 read -rsp "REPLIT_DB_URL (Enter to skip): " kv; echo >&2 if [ -f "$pg" ]; then dump=$pg elif [ -n "$pg" ]; then echo "==> Dumping the production database" dump=$HOME/replit/production-$(date -u +%Y%m%d-%H%M%S).dump pg_dump --format=custom --no-owner --no-privileges --dbname="$pg" --file="$dump" fi if [ -n "$kv" ]; then echo "==> Copying Replit Database" rm -f "$kvfile.new" echo "$kv" | REPLITDB_FILE=$kvfile.new "$HOME/bin/replitdb" import fi restart() { sudo systemctl start replitdb app.target; } trap restart EXIT # whatever happens, start the app again sudo systemctl stop app.target if [ -n "$pg" ]; then echo "==> Replacing the database $db with $dump" dropdb --force "$db" createdb --owner="$db" "$db" # Restored as the app's role, so the app owns its tables; a superuser # for the while, so the dump can create extensions. psql -X -q -d postgres -c "ALTER ROLE $db SUPERUSER" trap 'psql -X -q -d postgres -c "ALTER ROLE $db NOSUPERUSER"; restart' EXIT if pg_restore --list "$dump" >/dev/null 2>&1; then pg_restore --dbname="$db" --role="$db" --no-owner --no-privileges --exit-on-error "$dump" else { echo "SET ROLE $db;"; cat "$dump"; } | psql -X -q -v ON_ERROR_STOP=1 -d "$db" >/dev/null fi vacuumdb --quiet --analyze-only --dbname="$db" psql -X -d "$db" -Atc "SELECT relname || ': ' || n_live_tup || ' rows' FROM pg_stat_user_tables ORDER BY relname" | sed 's/^/ /' fi if [ -n "$kv" ]; then echo "==> Replacing Replit Database" sudo systemctl stop replitdb rm -f "$kvfile"-* mv "$kvfile.new" "$kvfile" fi restart for path in $(cat "$HOME/app.health" 2>/dev/null || echo /); do for _ in $(seq 30); do code=$(curl -s -o /dev/null -m 10 -w '%{http_code}' "http://localhost:8000$path" || true) case $code in 000|5??) sleep 1 ;; *) break ;; esac done echo "==> $path: HTTP $code" done echo "==> Done: the app runs on the copied data. journalctl -u 'app-*' shows any errors."