Fork me on GitHub

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?


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


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


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.


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


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


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))
   (keyword (str (name k) "_" (swap! -last-id (fn [id]
                                                (if (= Long/MAX_VALUE)
                                                  (inc id))))))))


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