Skip to content

Instantly share code, notes, and snippets.

Embed
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)),
; TASKS
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)
(:exit)
(= 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)
(sort)
(reverse)
(first)
(str))
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 (clojure.java.io/reader *in*))) "y"))]
(if do-restore?
(do (println "Restoring database... ")
(if (-> (shell restore-command)
(:exit)
(= 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