korma / Korma

Tasty SQL for Clojure.
http://sqlkorma.com
1.48k stars 222 forks source link

An Insert does not return the last inserted ID as described in the documentation #326

Open johnboy14 opened 8 years ago

johnboy14 commented 8 years ago

When I try to insert the following user, I do not get the last inserted ID as stated in the documentation for the insert function. Instead I just get Nil back. Any idea why this is?. I'm using the latest version and persisting to a MySQL database.

(defentity users
           (table :user_info)
           (database user_db)
           (prepare (fn [{topics :topics :as v}]
                      (if topics
                        (assoc v :topics (apply str (interpose "," topics))))))
           (transform (fn [{topics :topics :as v}]
                        (if topics
                          (assoc v :topics (split topics #","))))))
(defn create-user [user]
  (insert users
          (values user)))
immoh commented 8 years ago

The return value depends on the underlying JDBC driver. For MySQL, the driver only returns the generated key:

(exec-raw "create table users (id int auto_increment primary key, name varchar(100))")
=> (0)
(insert :users (values [{:name "foo"}]))
=> {:generated_key 1}

In your case the transform function returns nil if topics is nil and that could be the reason why you're getting nil as return value. I am not completely sure why the transform function is called in the first place but you can fix the transform function in the following way:

(transform (fn [{topics :topics :as v}]
             (if topics
               (assoc v :topics (split topics #","))
               v)))
johnboy14 commented 8 years ago

This solves the problem with the ids so thank you, but my test case did include topics.