Fork me on GitHub
#hugsql
<
2022-09-29
>
Erlangga06:09:56

Hi, everyone I have a question in here, so what's the equivalent syntax of clojure.java.jdbc/with-db-transaction with jdbc/with-transaction in hugsql ? because when i use the clojure.java.jdbc/with-db-transaction the code works perfectly (according to the book i'm studying), but when i use the next.jdbc library, the error appears to be something like this : Execution error (ExceptionInfo) at hugsql.core/validate-parameters! (core.clj:83). Parameter Mismatch: :id parameter data not found. Here's the code :

(defn add-user-transaction [user]
  (clojure.java.jdbc/with-db-transaction [t-conn db]
                         (if-not 
                           (find-user t-conn {:id (:id user)})
                           (add-user! t-conn user))))

(defn add-user-transaction2 [user]
  (jdbc/with-transaction [t-conn db]
                         (if-not
                           (jdbc/execute! t-conn (find-user {:id (:id user)}))
                           (jdbc/execute! t-conn (add-user! user)))))
and here's the sql resources : - :name find-user :? :1 -- find the user with a matching ID SELECT * FROM users WHERE id = :id -- :name add-user! :! :n -- :doc adds a new user INSERT INTO users (id, pass) VALUES (:id, :pass) What I've missed in here? Am i doing it wrong?

lukasz14:09:49

HugSQL can generate two types of functions based on your SQL file: • find-user that has the following signature (find-user connection params) - it actually executes your query • find-user-sqlvec - which just generates the sql vec + your params that you can then pass to jdbc/execute so in your code you're using the first form - to fix it, you have to just call (find-user t-conn {:id (:id user}) and not pass anything to jdbc/execute!

lukasz14:09:18

2nd thing is, if you're using postgres or mysql you can use upserts to make this into a single query that either finds a user or creates a new one

Erlangga04:09:26

Thanks, After do trials and errors, read and learn some https://cljdoc.org/d/com.github.seancorfield/next.jdbc/1.3.834/doc/getting-started/transactions, i think i should use the upserts that you suggest (since in tutorial book use the postgresql) because everything i've tried, i'm always facing the error code in above or error like this : Execution error (IllegalArgumentException) at clojure.java.jdbc/get-connection (jdbc.clj:430). db-spec is a raw Connection object! Did you call get-connection in the wrong context? You should only call that to pass a Connection into prepare-statement. (and don't forget to close it via with-open or .close) Welp, much way to go to learn, Thank you!

👍 1