/
result_set.clj
273 lines (226 loc) · 8.1 KB
/
result_set.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
(ns qbits.alia.result-set
(:require
[qbits.alia.gettable-by-index :as gettable-by-index]
[qbits.alia.completable-future :as cf]
[qbits.alia.error :as err])
(:import
[com.datastax.oss.driver.api.core
CqlIdentifier]
[com.datastax.oss.driver.api.core.cql
ResultSet
AsyncResultSet
Row
ColumnDefinitions
ColumnDefinition]
[java.util.concurrent Executor CompletionStage ExecutionException]))
;; defintes the interface of the object given to the :result-set-fn
;; for `qbits.alia/execute` queries, along with ISeqable and IReduceInit
(defprotocol PResultSet
(execution-infos [this]))
;; defines the interface of the object given to the :result-set-fn
;; for each page of `qbits.alia/execute-async` queries, along with
;; ISeqable and IReduceInit
(defprotocol PAsyncResultSet
(execution-info [this]))
;; defines the type returned by execute-async
(defprotocol PAsyncResultSetPage
(has-more-pages? [this]
"returns true when there are more pages to fetch")
(fetch-next-page [this]
"returns a `CompletedFuture<PAsyncResultSetPage>` of the next
page, or, if `this` was the final page, or the next page
is empty, returns `CompletedFuture<nil>`"))
;; Shamelessly inspired from https://github.com/ghadishayban/squee's
;; monoid'ish appoach
(defprotocol RowGenerator
(init-row [this] "Constructs a row base")
(conj-row [this r k v] "Adds a entry/col to a row")
(finalize-row [this r] "\"completes\" the row"))
(defn create-row-gen->map-like
"create a row-generator for map-like things"
[{constructor :constructor
table-ns? :table-ns?}]
(reify RowGenerator
(init-row [_] (transient {}))
(conj-row [_ row col-def v]
(if table-ns?
(let [^CqlIdentifier col-name (.getName ^ColumnDefinition col-def)
^CqlIdentifier col-table (.getTable ^ColumnDefinition col-def)]
(assoc!
row
(keyword (.asInternal col-table) (.asInternal col-name))
v))
(let [^CqlIdentifier col-name (.getName ^ColumnDefinition col-def)]
(assoc!
row
(keyword (.asInternal col-name))
v))))
(finalize-row [_ row]
(if constructor
(constructor (persistent! row))
(persistent! row)))))
(def row-gen->map
"Row Generator that returns map instances"
(create-row-gen->map-like {}))
(def row-gen->ns-map
"row-generator creating maps with table-namespaced keys"
(create-row-gen->map-like {:table-ns? true}))
(defn row-gen->record
"Row Generator that builds record instances"
[record-ctor]
(create-row-gen->map-like {:constructor record-ctor}))
(defn row-gen->ns-record
"Row Generator that builds record instances with table-namspaced keys"
[record-ctor]
(create-row-gen->map-like {:constructor record-ctor
:table-ns? true}))
(def row-gen->vector
"Row Generator that builds vector instances"
(reify RowGenerator
(init-row [_] (transient []))
(conj-row [_ row _ v] (conj! row v))
(finalize-row [_ row] (persistent! row))))
(defn decode-row
[^Row row rg decode]
(let [^ColumnDefinitions cdefs (.getColumnDefinitions row)
len (.size cdefs)]
(loop [idx (int 0)
r (init-row rg)]
(if (= idx len)
(finalize-row rg r)
(recur (unchecked-inc-int idx)
(let [^ColumnDefinition cdef (.get cdefs idx)]
(conj-row rg r
cdef
(gettable-by-index/deserialize row idx decode))))))))
(defn row-decoder-xform
[row-generator
{decoder :decoder :as codec}]
(map
#(decode-row % (or row-generator row-gen->map) decoder)))
(defn ->result-set
"ISeqable and IReduceInit support for a ResultSet, to
be given to the :result-set-fn for sync query results
cf: clojure.lang.Eduction - the returned object is similar, but
also permits the retrieval of execution-infos"
[^ResultSet rs decoder-xform]
(reify ResultSet
PResultSet
(execution-infos [this]
(.getExecutionInfos rs))
java.lang.Iterable
(iterator [this]
(clojure.lang.TransformerIterator/create
decoder-xform
(clojure.lang.RT/iter rs)))
clojure.lang.IReduceInit
(reduce [this f init]
(transduce decoder-xform (completing f) init rs))
clojure.lang.Sequential))
(defn result-set
[^ResultSet rs
result-set-fn
row-generator
codec]
((or result-set-fn seq) (->result-set
rs
(row-decoder-xform row-generator codec))))
(defn ->iterable-async-result-set
"ISeqable and IReduceInit support for an AsyncResultSet, to
be given to the :result-set-fn to create the :current-page object
cf: clojure.lang.Eduction - the returned object is similar, but
also permits the retrieval of execution-info"
[^AsyncResultSet async-result-set decoder-xform]
(reify
PAsyncResultSet
(execution-info [this]
(.getExecutionInfo async-result-set))
java.lang.Iterable
(iterator [this]
(clojure.lang.TransformerIterator/create
decoder-xform
(clojure.lang.RT/iter
(.currentPage async-result-set))))
clojure.lang.IReduceInit
(reduce [this f init]
(transduce
decoder-xform
(completing f)
init
(.currentPage async-result-set)))
clojure.lang.Sequential))
(declare handle-async-result-set-completion-stage)
;; the primary type returned by execute-async
(defrecord AliaAsyncResultSetPage [^AsyncResultSet async-result-set
current-page
opts]
PAsyncResultSet
(execution-info [this]
(.getExecutionInfo async-result-set))
PAsyncResultSetPage
(has-more-pages? [this]
(.hasMorePages async-result-set))
(fetch-next-page [this]
(if (true? (.hasMorePages async-result-set))
(handle-async-result-set-completion-stage
(.fetchNextPage async-result-set)
opts)
;; return a CompletedFuture<nil> rather than plain nil
;; so the consumer get to expect a uniform type
(cf/completed-future nil))))
(defn async-result-set-page
"make a single `AliaAsyncResultSetPage` of an `execute-async` result
if the current-page is the last page and is empty then `nil` is returned
the records from the current page are in the `:current-page` field
which is constructed from an `Iterable`/`IReduceInit` `AsyncResultSet`
wrapper by the `:result-set-fn` (which defaults to `clojure.core/seq`)
subsequent pages can be fetched with `PAsyncResultSetPage/fetch-next-page`,
which is defined as a record rather than an opaque type to aid with debugging"
[^AsyncResultSet ars
{result-set-fn :result-set-fn
row-generator :row-generator
codec :codec
:as opts}]
(let [empty-page? (= 0 (.remaining ars))
hmp? (.hasMorePages ars)]
(cond
;; if the :page-size lines up with the result-set size, then
;; an empty page happens
(and (true? empty-page?)
(false? hmp?))
nil
(false? empty-page?)
(let [iterable-ars (->iterable-async-result-set
ars
(row-decoder-xform row-generator codec))
current-page ((or result-set-fn seq) iterable-ars)]
(map->AliaAsyncResultSetPage
{:async-result-set ars
:current-page current-page
:opts opts}))
:else
(throw
(ex-info
"empty page before end of results?"
{:async-result-set ars})))))
(defn handle-async-result-set-completion-stage
"handle a `CompletionStage` resulting from an `.executeAsync` of a query
when successful, applies the `:row-generator` and `:result-set-fn`
to the current page
when failed, decorates the exception with query and value details"
[^CompletionStage completion-stage
{:keys [codec
result-set-fn
row-generator
executor
statement
values]
:as opts}]
(cf/handle-completion-stage
completion-stage
(fn [async-result-set]
(async-result-set-page async-result-set opts))
(fn [err]
(throw
(err/ex->ex-info err {:statement statement :values values})))
opts))