Skip to content

Instantly share code, notes, and snippets.

Last active July 1, 2022 05:20
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Babashka Tasks for PostgreSQL Backups
; run `bb backup` to backup database
; run `bb restore` to restore latest backup
{:min-bb-version "0.4.0",
:tasks {; CONSTANTS
db-name "dev_blog",
backup-dir "backups",
now (str (java.time.LocalDateTime/now)),
create-backup-dir {:depends [backup-dir], :task (babashka.fs/create-dirs backup-dir)},
backup {:depends [db-name now backup-dir create-backup-dir],
:task (let [backup-path (str backup-dir "/" db-name "_backup:" now ".dump")
backup-command (str "pg_dump --format=custom " db-name)]
(do (println (str "Backing up database: " db-name))
(println (str "Backup location: " backup-path))
(if (-> (shell {:out backup-path} backup-command)
(= 0))
(println "Backup successful! 🚀")
(println "Errors occurred during backup ⚠️"))))},
restore {:depends [db-name backup-dir],
:task (let [latest-backup-path (-> (babashka.fs/list-dir backup-dir)
restore-command (str "pg_restore --clean --dbname=" db-name " " latest-backup-path)
do-restore? (do (println "Latest backup: " latest-backup-path)
(println "Restore command: " restore-command)
(println "Restore this backup? (y/n): ")
(= (first (line-seq ( *in*))) "y"))]
(if do-restore?
(do (println "Restoring database... ")
(if (-> (shell restore-command)
(= 0))
(println "Restoration successful! 🚀")
(println "Errors occurred during restoration ⚠️")))
(println "Skipping restoration...")))}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment