Skip to content

Instantly share code, notes, and snippets.

@viccherubini
Created September 17, 2025 21:32
Show Gist options
  • Save viccherubini/25a12ba466b8ab1371f580d1398dea16 to your computer and use it in GitHub Desktop.
Save viccherubini/25a12ba466b8ab1371f580d1398dea16 to your computer and use it in GitHub Desktop.
PostgreSQL database dump script
#!/usr/bin/env php
<?php
// Data from the following tables
// will not be included in the dump
$excludeTableDataTables = [
'event',
'sessions',
];
$pgPassPath = sprintf('%s/.pgpass', (string) getenv('HOME'));
if (!is_file($pgPassPath)) {
echo(sprintf("Missing .pgpass file in '%s', aborting.\n", $pgPassPath));
exit(1);
}
$pgPassBits = explode(':', trim((string) @file_get_contents($pgPassPath)), 5);
if (5 !== count($pgPassBits)) {
echo("Invalid .pgpass format, aborting.\n");
exit(1);
}
$filePath = __DIR__ . "/{$pgPassBits[2]}.sql";
if (file_exists($filePath)) {
unlink($filePath);
}
$pgDumpArguments = array_map(function (string $table): string {
return sprintf("--exclude-table-data '%s'", $table);
}, $excludeTableDataTables);
$pgDumpCommand = vsprintf("pg_dump --host='%s' --username='%s' --dbname='%s' --file='%s' %s", [
$pgPassBits[0], $pgPassBits[3], $pgPassBits[2], $filePath, implode(' ', $pgDumpArguments),
]);
echo(sprintf("[%s] Beginning database dump.\n\n", date('Y-m-d H:i:s', time())));
echo(sprintf(" %s\n\n", $pgDumpCommand));
shell_exec(trim($pgDumpCommand));
echo(sprintf("[%s] Finished database dump.\n\n", date('Y-m-d H:i:s', time())));
echo(sprintf(" scp %s@%s:%s\n\n", get_current_user(), gethostname(), $filePath));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment