Skip to content

Instantly share code, notes, and snippets.

@stelcodes
Last active July 1, 2022 05:20
Show Gist options
  • Save stelcodes/a8c3b8f4b9c07ef784675750ab91079e to your computer and use it in GitHub Desktop.
Save stelcodes/a8c3b8f4b9c07ef784675750ab91079e to your computer and use it in GitHub Desktop.
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