0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

DB移行テストで何度も環境をリセットするためのWindowsバッチ作成

0
Last updated at Posted at 2026-05-12

PostgreSQLのテストをする際、手動で一つずつコマンドを叩くのがしんどくなったので、開発・テスト環境をサクッとリセットして「最新の統計情報」まで一気に作り直す汎用スクリプトを作成しました。

同じような「移行後の微調整」で消耗している方の参考になれば幸いです。

@echo off
setlocal
set PG_BIN=C:\Program Files\PostgreSQL\XX\bin
set DUMP_PATH=C:\temp\data.dump
set DB_NAME=db
set DB_USR=user
set DB_PW=user_pass
set PGPASSWORD=postgres_pass

set PATH=%PG_BIN%;%PATH%

psql -d postgres -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='%DB_NAME%' AND pid <> pg_backend_pid();"
psql -d postgres -c "DROP DATABASE IF EXISTS %DB_NAME%;"
psql -d postgres -c "DROP USER IF EXISTS %DB_USR%;"

psql -d postgres -c "CREATE USER %DB_USR% WITH PASSWORD '%DB_PW%';"
psql -d postgres -c "CREATE DATABASE %DB_NAME% OWNER %DB_USR% ENCODING 'UTF-8';"

psql -d %DB_NAME% -c "GRANT ALL ON TABLE pg_largeobject TO %DB_USR%;"
psql -d %DB_NAME% -c "ALTER ROLE %DB_USR% SET search_path TO %DB_USR%, public;"

pg_restore -v -d %DB_NAME% --no-owner --role=%DB_USR% "%DUMP_PATH%" > res.log 2>&1

(
  echo ALTER SCHEMA public RENAME TO %DB_USR%;
  echo ALTER SCHEMA %DB_USR% OWNER TO %DB_USR%;
  echo CREATE SCHEMA public AUTHORIZATION %DB_USR%;
  echo REINDEX DATABASE %DB_NAME%;
  echo ANALYZE;
) | psql -d %DB_NAME%
pause
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?