Fork me on GitHub
#honeysql
<
2021-08-01
>
p-himik16:08:50

Is there a common approach towards approaching aliases/CTE names generation in reusable subquery-generating functions? I have a lot of functions that generate small clauses, some of which require aliases due to nesting or names for some CTEs. Hard-coding them can't work because the same function can be used multiple times for the same query. Passing them can't work because the overall internal API is rather generic - the caller just cares about the changes it should make to the sqlmap, it doesn't care about which tiny function requires which aliases/names. I'm about to implement a mechanism similar to (gensym) with just a plain atom and ID increment + rollover (paranoid, I know). But maybe there's a known solution, maybe even a function somewhere for that, that I just can't find?

deleted16:08:45

I was reading that and thinking "wow, sounds like gensym" and sure enough 😂

p-himik16:08:33

gensym can't alleviate my paranoia - it doesn't have roll-over. :)

p-himik16:08:26

A single swap! with if should be simpler though. I should've been more clear - the crux of the issue is not getting a unique identifier itself but rather having it work automagically. I've glanced at the source and there doesn't seem to be such a thing, but I could be blind.

p-himik16:08:29

But why can't I just use the counter itself? Just like gensym does. So an alias would be something like :G_234975 .

p-himik16:08:24

Nah, given my overflow paranoia it makes sense. Although that would have to be one large query to fit repeating IDs.

p-himik16:08:38

Java doesn't have built-in unsigned number types though. And overflowing a long leads to an exception. And better be explicit about it anyway:

(def -last-id (atom 1))

(defn get-alias
  ([]
   (get-alias :alias))
  ([k]
   (keyword (str (name k) "_" (swap! -last-id (fn [id]
                                                (if (= Long/MAX_VALUE)
                                                  1
                                                  (inc id))))))))

p-himik17:08:41

Makes sense! Especially given that it shouldn't happen at all in a realistic scenario.