Fork me on GitHub
#sql
<
2022-01-27
>
lvh16:01:07

Hi! I’m new to jdbc.next (ns alias jdbc)with honeysql (ns aliases hsql and h for the helpers). I had a question about how result set formatting works. I have a table called organizations and making queries like so: (-> (h/select :o/uuid) (h/from [:organizations :o])) . by default, my results seem to be qualified snake-case keywords. I know about (jdbc/with-options connectable jdbc/snake-kebab-opts) ; that’s a bit closer to what I want; but the thing that surprised me is that the namespace is :organizations and not :o — what do you do if you have e.g. a graph represented in sql and you have selects a la [:organizations :grandparent] [:organizations :parent] [:organizations :child] and you want the name of all 3? or am I just misunderstanding how this works?

lvh16:01:59

the honeysql helpers appear to let me use either :o or :organizations which is fine except in the face of ambiguity

lvh17:01:31

I found this in the docs: > Note: This is a deliberate difference from `clojure.java.jdbc` which would make column names unique by appending numeric suffixes. It was always poor practice to rely on `clojure.java.jdbc`’s renaming behavior and it added quite an overhead to result set building, which is why `next.jdbc` does not support it -- use explicit column aliasing in your SQL instead if you want unqualified column names! That sounds like what I want but maybe I misunderstand what “explicit” means here; I though the table alias was explicit; presumably the way to do this is something like (h/select [:grandparent/id :gid] [:parent/id :pid] [:child/id :cid]) ?

lvh17:01:29

(yep, that seems to be it, but please let me know if I’m missing something important 🙂

seancorfield19:01:03

@lvh Yes, the usual way that next.jdbc keeps column names from colliding is to ask JDBC "what table is this column from?" and producing a qualified keyword using the table name and the column label (the alias if present else the column). In the case where you're joining to the same table multiple times, that doesn't work (unless you are selecting a strictly disjoint set of columns from each of the multiple joins) so you have to manually alias the overlapping columns to make them unique.

seancorfield19:01:27

clojure.java.jdbc automatically renamed overlapping columns by adding a numeric suffix but that made it very hard to be certain that foo_1 and foo_2 really meant what you intended (and it was brittle in the face of changes to the order of clauses in the SQL).

seancorfield19:01:30

Unfortunately, JDBC doesn't provide getTableLabel() only getTableName() so I can't retrieve the alias used on table names in a query.

seancorfield19:01:45

(it provides getColumnLabel() and getColumnName())

seancorfield19:01:36

Oh, and also some databases won't give you the table name by default (MS SQL Server, as I recall, requires an option to trigger that) and some won't give you the table name at all (Oracle).