Created
November 2, 2010 19:02
-
-
Save davidsantiago/660113 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; My two attempts. The first is to make create-database ignore the error return | |
;; with chain-or. I can't get anything to compile here. Have tried with/without | |
;; stevedore/script, with/without ~(apply...). | |
;; Second attempt: ensure-database-exists function. Uses a defscript. This will | |
;; output the if statement desired, but at a seemingly random place earlier in the | |
;; script unrelated to the conditional. It will also not escape as-user or db-name, | |
;; although it will escape the (format ...). | |
(defn create-database | |
"Create a database if it does not exist. | |
You can specify database parameters by including a keyed parameter called | |
:db-parameters, which indicates a vector of strings or keywords that will get | |
translated in order to the options to the create database command. Passes on | |
key/value arguments it does not understand to postgresql-script. | |
Example: (create-database \"my-database\" :db-parameters [:encoding \"'LATIN1'\"])" | |
[request db-name & rest] | |
(let [{:keys [db-parameters] :as options} rest | |
db-parameters-str (str/join " " (map as-str db-parameters))] | |
(stevedore/script (chain-or ~(apply postgresql-script | |
request | |
(format "CREATE DATABASE %s %s;" db-name db-parameters-str) | |
rest) | |
true)))) | |
(defscript database-exists? [as-user db-name]) | |
(stevedore/defimpl database-exists? :default [as-user db-name] | |
(sudo "-u" ~as-user psql "-t -c" | |
~(format "\"select count(1) from pg_database where datname='%s'\"" | |
db-name))) | |
(defn ensure-database-exists | |
[request db-name & rest] | |
(let [{:keys [as-user] :or {as-user "postgres"}} rest] | |
(-> request | |
(resource-when/resource-when | |
(= @(database-exists? as-user db-name) "0") | |
(apply-> create-database db-name rest))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment