-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb-backup.ps1
More file actions
82 lines (63 loc) · 2.42 KB
/
Copy pathdb-backup.ps1
File metadata and controls
82 lines (63 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env pwsh
<#
.SYNOPSIS
Chateando - PostgreSQL backup helper (Windows / PowerShell).
.DESCRIPTION
Creates a compressed pg_dump of the chateando database from the running
`postgres` service in docker compose and stores it in a host-side directory.
Old backups beyond -RetainDays are pruned.
.PARAMETER BackupDir
Output directory (default: ./backups).
.PARAMETER RetainDays
Days to keep backups (default: 14).
.PARAMETER ComposeFile
Docker compose file (default: docker-compose.yml).
.PARAMETER DbService
Compose service running Postgres (default: postgres).
.PARAMETER DbName
Database name (default: chateando).
.PARAMETER DbUser
Postgres role (default: chateando).
.EXAMPLE
./ops/db-backup.ps1
./ops/db-backup.ps1 -BackupDir D:\backups\chateando -RetainDays 30
#>
[CmdletBinding()]
param(
[string]$BackupDir = './backups',
[int]$RetainDays = 14,
[string]$ComposeFile = 'docker-compose.yml',
[string]$DbService = 'postgres',
[string]$DbName = 'chateando',
[string]$DbUser = 'chateando'
)
$ErrorActionPreference = 'Stop'
if (-not (Test-Path -LiteralPath $BackupDir)) {
New-Item -ItemType Directory -Force -Path $BackupDir | Out-Null
}
$timestamp = (Get-Date).ToUniversalTime().ToString("yyyyMMddTHHmmss") + 'Z'
$target = Join-Path $BackupDir ("chateando_${timestamp}.dump")
Write-Host "[backup] dumping $DbName via service '$DbService' -> $target"
# Use docker compose exec -T with redirected stdout to avoid TTY issues on Windows.
$dumpArgs = @(
'compose','-f',$ComposeFile,'exec','-T',$DbService,
'pg_dump','--format=custom','--no-owner','--no-privileges',
"--username=$DbUser",$DbName
)
# Stream pg_dump output directly into the target file.
& docker @dumpArgs | Set-Content -LiteralPath $target -AsByteStream
$item = Get-Item -LiteralPath $target
if ($item.Length -lt 1024) {
Remove-Item -LiteralPath $target -Force
throw "Dump file is suspiciously small ($($item.Length) bytes); aborted."
}
Write-Host "[backup] wrote $($item.Length) bytes."
Write-Host "[backup] pruning files older than $RetainDays day(s) from $BackupDir."
$cutoff = (Get-Date).AddDays(-1 * $RetainDays)
Get-ChildItem -Path $BackupDir -Filter 'chateando_*.dump' -File |
Where-Object { $_.LastWriteTime -lt $cutoff } |
ForEach-Object {
Write-Host " - removing $($_.FullName)"
Remove-Item -LiteralPath $_.FullName -Force
}
Write-Host "[backup] done."