Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I drop or create a database from clojure.java.jdbc?

I would like to create/drop a database from clojure.java.jdbc. This fails:

(require '[clojure.java.jdbc :as sql])

(def db
  {:classname "org.postgresql.Driver"
   :subprotocol "postgresql"
   :subname "//localhost/postgres"
   :user "postgres"})

(defn drop-database [name]
  (sql/do-commands (str "drop database " name)))

(sql/with-connection db 
  (drop-database "db_name"))

because do-commands starts a transaction, and apparently you can't drop or create databases inside a transaction. Any ideas?

Thanks!

like image 434
prismofeverything Avatar asked Oct 20 '11 08:10

prismofeverything


2 Answers

Take the source for do-commands (here) and remove the call to transaction:

(defn drop-database [name]
  (sql/with-connection db
    (with-open [s (.createStatement (sql/connection))]
      (.addBatch s (str "drop database " name))
      (seq (.executeBatch s)))))
like image 138
Brian Carper Avatar answered Nov 15 '22 16:11

Brian Carper


The transactionless execution functionality was rolled into db-do-commands.

Now this slightly simpler version is working:

(jdbc/db-do-commands postgres-db false "CREATE DATABASE foo")

If you don't specify false as the second argument, it won't work as it will attempt to start a transaction.

like image 42
amoe Avatar answered Nov 15 '22 15:11

amoe