layerware/hugsql

Add :r result type for returning inserted values

robinheghan opened this issue · 2 comments

YeSQL allows you to suffix your sql fns with <! to return the created row.
Maybe hugsql should have a :r result type that does the same?

Yes, I'm looking at how to reliably and consistently do this across different databases and different library backends. From a library perspective, it seems to hinge on whether or not .getGeneratedKeys is supported. clojure.java.jdbc does support this. I think clojure.jdbc support is currently commented out in the code.

I'm looking at supporting the single record created and multiple records created for a forthcoming multi-insert functionality.

Also, if you are using a database that supports the RETURNING syntax for INSERTS (like Postgresql), you can support this directly in your SQL statement.

As of 0.4.0, we have commands :insert, or :i! for short, that have behavior similar to Yesql's <! suffix. Specifically, the underlying adapter and libraries must support the JDBC call to .getGeneratedKeys. The return value of this is quite varied across libraries. See Insert for some samples from the test suite.

Implementation note: Since the support for this varies so much, I decided not to change the HugSQLAdapter protocol by adding an insert function. Instead, I now pass the :command and :result along to the adapter in the options and allow the execute function to conditionally change behavior if it encounters a command type that will change which underlying function it should call. You can see an example of this in the adapter code for clojure.java.jdbc.