heya folks.. i’m trying to use honey with the good ol clojure.java.jdbc, but i’m not really sure how to do insert!
given the format that comes out of a honeysql/format
:
(-> (insert-into :accounts) (columns :email :password) (values [["<mailto:hi@me.com|hi@me.com>" "pw"]]) sql/format)
> ["INSERT INTO accounts (email, password) VALUES (?, ?)" "<mailto:hi@me.com|hi@me.com>" "pw"]
but the expected format for insert doesn’t line up very well jdbc/insert! :table-name { map of columns -> values }
certainly this is a common problem, how do people thread from honey -> jdbc?
i can get away ( i think ) with just doing a jdbc/query [" not really a query, just regular SQL insert into "]
but that seems wonky to me
@lwhorton if you are returning rows, INSERT INTO ... RETURNING ...
then you use jdbc/query
. Otherwise use jdbc/execute!
in your example, you'd use (jdbc/execute! some-db-reference (sql/format ...))
aha, thanks :thumbsup:
@lwhorton Also note that with the most recent java.jdbc
versions, you can pass {:return-keys true}
to execute!
and get back the generated keys (assuming your driver/DB supports that).
To be honest, tho', I think using java.jdbc/insert!
directly is nicer than going through HoneySQL:
(jdbc/insert! db-spec :accounts {:email "<mailto:hi@me.com|hi@me.com>" :password "pw"})
There's also insert-multi!
for inserting a sequence of records (hash maps).
@seancorfield I almost never use jdbc/insert! because most of my inserts end up using RETURNING due to wanting data from triggers
@bja interesting. I don't think I've ever used returning
...
it might just be a pgsql extension
Perhaps adding support for returning
to insert!
would be possible/worthwhile?
it's especially useful with UPSERT or ON CONFLICT ... in postgres
possibly. I just use honeysql-postgres to support it
the only time I ever step outside of jdbc/query and jdbc/execute! involves DDL (which I handle outside of clojure) and server-side cursors
Looks like returning is DB-specific. I thought Postgres already returned the whole inserted record anyway?
(at least it does in the test suite for java.jdbc
).