I am in the process of creating a backup script for my server running PostgreSQL on Windows 2022.
I am rather new to Postgres and I've searched this until I'm blue in the face but my switches seem to contradict each other when I'm running the script.
Here's my script so far:
@echo off
cls
set PGHOST=localhost
set PGUSER=someuser
set PGPASSWORD=somepassword
set PGPORT=5432
set PGDB=gitlab
echo This script will restore a PostgreSQL database dump file.
set /p "dmpfile=Enter dump file name to restore: "
set /p "pgdb=Enter the new database name (gitlab): "
if "%pgdb%" equ "" set "pgdb=gitlab"
echo.
echo Importing %dmpfile% into database %pgdb%
echo.
echo off
echo Creating database %pgdb%
echo.
createdb -h %pghost% -p %pgport% -U %pguser% -T template0 %pgdb%
echo.
echo Importing %dmpfile%
echo.
pg_restore --create --dbname %pgdb% %dmpfile%
If I do not have the createdb line, I'm getting this message:
pg_restore: error: connection to server at "localhost" (::1), port 5432 failed: FATAL: database "gitlab" does not exist
If I do create the database with createdb, then when the restore runs, I'm getting this message:
pg_restore: error: could not execute query: ERROR: database "gitlab" already exists Command was: CREATE DATABASE gitlab WITH TEMPLATE = template0 ENCODING = 'UTF8' LOCALE_PROVIDER = libc LOCALE = 'English_United States.1252';
I don't get it. If I create it, it says it already exists, if I don't it complains that it doesn't exist.
What am I doing wrong?
pg_restore --clean --create --dbname %pgdb% %dmpfile%set "variable=value"to define an environment variable. How to stop Windows command interpreter from quitting batch file execution on an incorrect user input? This answer explains how to prevent an unexpected exit of the batch file processing on user makes a mistake on entering a string on a prompt.==should be used for a string comparison and not theEQUinteger comparison operator. DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/ This forum topic describes whyecho/orecho(should be used instead ofecho.which results in accessing the file system to find a file with nameecho.%dmpfile%in the command lines should be enclosed in", except the value assigned to the environment variabledmpfileis already enclosed in"which in this case depends on the user input on prompt.