0

I have a function I made to get the name of a table and the one or more columns and create the table in postgres sql. I created a static version as well to test. The static version works fine, however the dynamic verison only worked when I wrote it only to take one column as an argument. Now that I'm trying to have multiple columns as an arg it throws an exception. Here is the code:

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


(def db
    {:classname "org.postgresql.Driver"
     :subprotocol "postgresql"
     :subname "mydb"
     :username "username"
     :password "password"})

    (defn StaticCreateTable
      []
    (j/with-connection db
        (j/create-table "records3" 
     ["RecID", "int", "PRIMARY KEY"]
     ["TreeID", "int"]
     ["Bubba", "varchar(30)"])
         (println "Success!")))

    (defn DynamicCreateTable2
      [map]
      (j/with-connection db
        (j/create-table (:tablename map) (for [i (:columns map)] i))
        (println "Success!")))

This is what I input:

(DynamicCreateTable2 {:tablename "Creators3" 
:columns [
["CreatorID", "int", "PRIMARY KEY"]
["Number", "int"]]} )

Any help would be greatly appreciated

1 Answer 1

2

For starters (for [i (:columns map)] i) is the same as (:columns map)

The exception you are getting is because the columns are being passed in within a sequence, instead of being individual args to create-table.

 (apply j/create-table (:tablename map) (:columns map))

Will do what you want.

apply turns lists into individual args to its function argument.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that did the trick, I did originally have (:columns map) but before using apply it still was not working. I appreciate it noisesmith!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.