Skip to content

Instantly share code, notes, and snippets.

@dankkom
Last active May 1, 2023 21:03
Show Gist options
  • Save dankkom/876fc77f4e3939cc743920d637d7a7d7 to your computer and use it in GitHub Desktop.
Save dankkom/876fc77f4e3939cc743920d637d7a7d7 to your computer and use it in GitHub Desktop.
Script para fazer backup/dump de base de dados PostgreSQL
import argparse
import datetime as dt
import getpass
import os
import subprocess
import zlib
from pathlib import Path
def compute_crc32(filepath: Path) -> dict[str, str]:
crc = 0
with open(filepath, "rb") as f:
while chunk := f.read(8192):
crc = zlib.crc32(chunk, crc)
return "{:08X}".format(crc & 0xFFFFFFFF)
def create_backup(username: str, database_name: str, dest_dir: Path):
now = dt.datetime.now()
filepath = dest_dir / f"{database_name}-backup-{now:%Y-%m-%d-%H-%M}"
cmd = [
"pg_dump",
"-U",
username,
"-d",
database_name,
"-f",
str(filepath),
]
subprocess.run(cmd)
crc32 = compute_crc32(filepath)
new_filepath = dest_dir / f"{filepath.name}[{crc32}].sql"
filepath.rename(new_filepath)
return new_filepath
def compress(filepath: Path, remove_original: bool = False):
dest_filepath = filepath.parent / f"{filepath.name}.7z"
# https://stackoverflow.com/a/28474846
cmd = [
"7z",
"a",
"-m0=lzma2",
"-mx=9",
"-aoa",
str(dest_filepath.absolute()),
str(filepath.absolute()),
]
subprocess.run(cmd)
if remove_original:
filepath.unlink()
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("-U", "--user", dest="user", required=True)
parser.add_argument("-d", "--database", dest="database", required=True)
parser.add_argument("-dest-dir", type=Path, required=True)
parser.add_argument("--remove-uncompressed-sql", action="store_true")
return parser.parse_args()
def main():
args = get_args()
pgpassword = getpass.getpass(prompt="Password:")
os.environ.update({"PGPASSWORD": pgpassword})
filepath = create_backup(
username=args.user,
database_name=args.database,
dest_dir=args.dest_dir,
)
compress(filepath, remove_original=args.remove_uncompressed_sql)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment