FAQ: PostgreSQL database backup and restore procedure
This procedure is for the Pleasanter database (Implem.Pleasanter) created using the installation procedure in the user manual.
## When restoring to the same environment
If you want to restore to the same environment as the environment in which the backup was taken, follow the steps below.
### Backup
Get a backup file. In this procedure, get it under the /backup directory.
```
su - postgres
pg_dump -Fc Implem.Pleasanter > /backup/Implem.Pleasanter.dump
```
### Restore
After getting a backup with the above command, delete and re-create the database (Implem.Pleasanter) using SQL, then restore with the pg_restore command.
```
psql -U postgres -c 'drop database "Implem.Pleasanter";'
psql -U postgres -c 'create database "Implem.Pleasanter";'
pg_restore -d Implem.Pleasanter /backup/Implem.Pleasanter.dump
```
## When restoring to a different environment
If you want to restore in a different environment (destination) from the environment where the backup was taken (source), follow the procedure below.
### Backup
Get a backup of the roles and databases in the source. *Since role information is required to restore the database, also get a backup of the roles.
```
pg_dumpall --roles-only > /backup/Implem.Pleasanter_role.dump
pg_dump -Fc Implem.Pleasanter > /backup/Implem.Pleasanter.dump
```
### Restore
Copy the two backup files obtained in the above backup to the destination and use each file to restore. The following procedure assumes that you have copied the backup file to the /backup directory.
#### Creating a database
Use the following command to create a database and add the full-text search module (pg_trgm).
```
psql -U postgres -c 'create database "Implem.Pleasanter";'
psql -U postgres -c 'create extension if not exists pg_trgm;'
```
#### Restoring a database
Use the following command to restore the role and database. *It is not necessary to configure the database by running CodeDefiner before running the following command.
```
psql -f /backup/Implem.Pleasanter_role.dump
pg_restore -d Implem.Pleasanter /backup/Implem.Pleasanter.dump
```
## Backing up regularly
If you want to back up regularly and delete backup files, you can do so by setting up cron as shown below.
*The following cron settings will delete files older than one week at 1:00 every day and take a backup at 2:00.
```
# crontab -u postgres -e
```
### Take a database backup at 2:00 every day
```
00 02 * * * /bin/pg_dump -Fc "Implem.Pleasanter" > /backup/`date "+%Y%m%d"`_Implem.Pleasanter.dump
```
### Delete files older than one week at 1:00 every day
```
00 01 * * * /bin/find /backup -maxdepth 1 -mtime +7 -type f -delete
```