hello everyone
what is the best way to handle sql errors?
for example: if i have some columns with UNIQUE constraints and try to ingest that twice so i got error from sql, how can i reflect that into my code ?
without write a clojure code to check if the record is already there before i ingest it into the db
Which DB is it?
@dharrigan posgtresql
(try (sql operation) (catch SomeException e (recover-from-it "etc")))
i'm trying to get the duplicate error from sql, i'm using honeysql i got: Exception in execute!, is there a way to get that exception ?
I don't understand what you're asking. try
/`catch` is how you catch exceptions.
Perhaps if you share the code you're trying to use and provide a bit more detail about the exception and explain why it isn't what you want...?
For example:
(try
(jdbc/insert! db-spec :user_activity all-activity)
(catch SQLIntegrityConstraintViolationException _))
where we already imported that:
(:import (java.sql SQLIntegrityConstraintViolationException))
I do something different
basically I ignore
i.e.,g on conflict do nothing
since it already exists in the db
@dharrigan That sort of thing is DB-specific tho'...
yes, but he's mentioned he uses postgres
so might as well use the feature of postgres
mysql has a similar feature
why not use it? 🙂
keep things generic, where appropriate, but specific when needed
Fair point. I was trying to answer the exception-based stuff in his question, and since I don't use PG, I didn't think about SQL-level stuff.
(and I'm not sure that PG-specific SQL would fit into HoneySQL's DSL off the top of my head)
true, I use this:
(defmethod fmt/format-clause :on-conflict-do-nothing [[_ _] _]
(str "ON CONFLICT DO NOTHING"))
(defhelper on-conflict-do-nothing [m _]
(assoc m :on-conflict-do-nothing []))
I think also, there is more power in the on conflict, i.e., you can tell postgresql to do something else if that condition is raised
and it happens on the db, doesn't involve a round-trip back to the server
but yes, your point is valid too - if he chooses to go the exception route, totally fine in my books as well
Looks like MySQL has ON DUPLICATE KEY UPDATE x=x
(where x
is arbitrarily one of the columns, as I understand what I'm seeing on SO).
ANSI has a MERGE
statement (but not all databases support that -- "of course").
🙂
xkcd 927 comes to mind
As someone who spent eight years on the ANSI C++ Standards Committee I can only say "preach" as far as that cartoon is concerned 🙂