~subsetpark/doozer

doozer/doozer/from.janet -rw-r--r-- 11.6 KiB
4a8e0e3e — Zach Smith update docs 1 year, 2 months ago
                                                                                
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
(import /doozer/common)
(import /doozer/compose)

## Atoms

(defn- make-value
  [val &opt sym]
  (default sym (gensym))
  @{:atom true
    :value val
    :symbol (keyword sym)})

(defn- make-expr-atom
  "Handle direct references to a SQL field"
  [field]
  (if (symbol? field)
    @{:atom true
      :implied-table true
      :column (string field)}
    (make-value field)))

(defn- make-column-ref
  "Handle `.` syntax, making a `foo.bar` column reference"
  [[tab col]]
  (if (symbol? tab)
    # Mark this as a table-reference, so that it can be resolved later on
    @{:atom true
      :table-ref (string tab)
      :column (string col)}
    # If a table was specified as a non-symbol, pass it in and don't try to
    # resolve it
    @{:atom true
      :table (string tab)
      :column (string col)}))

##

(defn- validate-length
  [expr-type n form]
  (unless (= n (length form))
    (errorf (string "Query parsing error: expression of type `%s` "
                    "expects exactly %n element(s) "
                    "(got: %q)")
            (string expr-type) n form))
  form)

(defn- make-subquery
  [query]
  @{:subquery query})

## Parsing

(defn- make-expression
  [form]
  (if-not (indexed? form)
    (make-expr-atom form)
    (let [head (first form)
          rest (array/slice form 1)]
      (case head
        # undocumented: this is useful for deterministic test output.
        'override-sym (make-value ;rest)
        '@ (let [[val] (validate-length :variable 1 rest)]
             (make-value val))
        '. (make-column-ref rest)
        'subquery (let [[subquery] (validate-length :subquery 1 rest)]
                    (make-subquery subquery))
        'fn (let [fun (first rest)
                  rest (array/slice rest 1)]
              @{:apply fun
                :args (map make-expression rest)})
        'raw (let [fragment (first rest)
                   rest (array/slice rest 1)]
               @{:fragment fragment
                 :args (map make-expression rest)})
        (if (common/operators head)
          @{:op (keyword head)
            :args (map make-expression rest)}
          (make-expr-atom form))))))

(defn- make-source
  [form]
  (match form
    @[(@ 'as) inner-form as] @{:source (make-source inner-form)
                               :as (string as)}
    (q (string? q)) @{:table q}
    @[(@ 'subquery) q] (make-subquery q)
    form))

(defn- make-select
  [form]
  (match form
    @[(@ 'as) expr alias] @{:referent (make-expression expr)
                            :as (string alias)}
    (make-expression form)))

(defn- make-join
  [[binding join-expr] &opt alias]

  (defn do-construct
    [{:table tab :on inner-expr :as as :type join-type}]
    (when (and alias as) (error "Received two different aliases for a single join"))

    (default as (or alias (common/make-alias tab)))
    (default join-type :inner)

    @{:type join-type
      :as as
      :table tab
      :on (make-expression inner-expr)
      :binding (string binding)})

  (match join-expr
    @[(@ 'as) inner-join alias] (make-join [binding inner-join] alias)
    @[tab on-expr] (do-construct {:table tab :on on-expr})
    join (do-construct join)))

(defn- dsl-to-query
  [forms]

  (def joins @[])
  (def wheres @[])
  (var selects @[])
  (var limit nil)

  # Define handlers for each form type. Since the same form can appear more
  # than once, these are subprocedures which can be re-called as necessary.

  (defn handle-joins
    [rest]
    (let [new-joins (->> rest (partition 2) (map make-join))]
      (array/concat joins new-joins)))

  (defn handle-wheres
    [rest]
    (let [new-wheres (map make-expression rest)]
      (array/concat wheres new-wheres)))

  (defn handle-selects
    [rest]
    (when (not (empty? selects))
      (errorf "Cannot specify multiple `select`s; already selecting %q" selects))

    (let [new-selects (map make-select rest)]
      (set selects new-selects)))

  (defn handle-limit
    [rest]
    (when (not (nil? limit))
      (errorf "Cannot specify multiple `limit`s; already limiting to %q" limit))

    (set limit (first rest)))

  (each form forms
    (defn err [] (errorf "Encountered unknown form in query: %q" form))
    (unless (indexed? form) (err))

    (def head (first form))
    (def rest (array/slice form 1))
    (case head
      'join (handle-joins rest)
      'where (handle-wheres rest)
      'select (handle-selects rest)
      'limit (handle-limit rest)
      (err)))

  {:join joins
   :where wheres
   :select selects
   :limit limit})

#
# DSL
#

(defmacro from
  ````
  Construct a new doozer query.

  `query-or-table` can be one of two datatypes:
  - A string, which should be the name of a table present in the database;
  - A symbol bound to an existing query structure.

  The query-or-table reference can be wrapped in an `as` s-expression, eg.:

  ```
  (select (as "artists" "main_artists_table"))
  ```

  to specify the table alias used in the query.

  `forms` may be headed by an optional binding symbol, followed by any number
  of s-expressions, each of which must be headed by one of the following
  symbols:

  ### where

  `where` should be followed by a sequence of *relations*, which will be
  translated in to `WHERE` statements in SQL. An example of a query with a
  where statement:

  ```
  (from "artists" a (where (= name "Steely Dan")))
  ```

  This is equivalent to the SQL:

  ```sql
  SELECT * FROM artists AS _0000da WHERE _0000da.name = 'Steely Dan'
  ```

  In other words, `(= name "Steely Dan")` is treated as a simple relation where
  a single bare symbol, in this case `name`, is expected to be a column present
  on `artists` and "Steely Dan" is a user-inputted string.

  That query can also be written as:

  ```
  (from "artists" a (where (= (. a name) "Steely Dan")))
  ```

  Inside of a relation expression, a `.` s-expression is exquivalent to the SQL
  `table.column`.

  Finally, a two-tuple with the first element `@` can be used to reference an
  existing variable:

  ```
  (def my-name "Metallica")
  (to-sql (from "artists" a (where (= name (@ my-name)))))
  ```

  ### join

  `join` should be following by an alternating sequence of *bindings* and
  *join expressions*, in the same style as the `let` function. For instance:

  ```
  (from "artists" a (join alb {:table "albums" :on (= ArtistId (. a ArtistId))}))
  ```

  Which is equivalent to the SQL:

  ```sql
  SELECT * FROM artists AS _0000e1
  JOIN albums AS _0000e2 ON _0000e2.ArtistId = _0000e1.ArtistId
  ```

  Join expressions can be written in two different ways. In addition to the
  more explicit, struct syntax seen above, they can also be written as a simple
  two-tuple of `table` and `on`:

  ```
  (from "artists" a (join alb ["albums" (= (. alb ArtistId) (. a ArtistId))]))
  ```

  The above example also demonstrates that `ArtistId` and `(alb ArtistId)` are
  equivalent; in analog to WHERE above, a single symbol in a join expression
  should be a column present on the table being joined.

  The struct syntax also affords an keys:

  - `:as` will specify the AS value for the join, instead of having a unique
  symbol as in the above examples. This user-specified name can then be used in
  subsequent compositions onto this query (see `where`). However, it also poses
  the risk of name collision and subtle bugs, so it shouldn't be used if it's
  not required.
  - `:type` : The type of the join, as supported by your SQL backend. Defaults
  to `:inner`.

  The binding value in a join can be used in WHERE clauses:

  ```
  (from "artists" a
    (join alb {:table "albums" :on (= ArtistId (. a ArtistId))})
    (where (= (. alb title) "Ride The Lightning")))
  ```

  ### select

  `select` should be followed by a list of relation expressions (see Expression
  API, below) to select.

  ## Query Composition

  In addition to create new queries, `from` can be used to compose and reuse
  existing queries.

  If `query-or-table` is a symbol, it will be looked up and treated as an
  existing query structure. A new structure will be created which combines the
  parameters of the existing query with the ones specified in the `from` call.
  Thus, small, modular queries can be written once and combined as necessary.

  ## Expression API

  Expressions, such as those found in WHERE clauses or SELECT statements, can
  be in any of the following forms:

  - `<symbol>`: interpreted as a column name in the implicit row (see `where`
  and `join`, above)
  - `<non-symbol>`: the value will be (safely) interpolated into the query as a
  literal value (NB: the value types that can be sensibly interpolated into a
  query are implementation-dependent)
  - `(. <table-symbol> <column-symbol>)`: interpreted as a qualified table/row
  reference
  - `(. <table-string> <column-symbol>)`: interpreted as a qualified table/row
  reference, as above; however, `table-string` treated as a literal reference
  to a table name (instead of to the binding used in when writing the query
  form) and is directly interpolated into the resulting query
  - `(@ <variable-symbol>)`: the value of the variable at `variable-symbol`
  will be interpolated into the query
  - `(fn <function-string> & args)`: the SQL function `function-string` will be
  called on `args`; eg., `(fn "count" id)` or `(fn "coalesce" name "Default Name")`
  - `(raw <fragment-string> & args)`: Using `?` as placeholders in the fragment
  string, `args` will be (safely) interpolated into the fragment and the
  fragment will be **unsafely** interpolated into the SQL query. eg.,
  `(fragment "? || ?" (. "artists" name) "!")`
  - `(subquery <query>)`: `query` will be treated as a subquery inside the
  larger expression. `query` here can either be a symbol bound to an existent
  query structure, or a form constructing a new one.
  ````
  [query-or-table & forms]
  (def maybe-binding (first forms))
  (let [query-or-table (make-source query-or-table)
        [binding forms] (if (symbol? maybe-binding)
                          [maybe-binding (array/slice forms 1)]
                          [nil forms])
        query (dsl-to-query forms)]
    ~(,compose/compose-query ,query-or-table ',binding ,query)))

(defn where
  ```
  Given an existing query, create a new query with an additional single
  `where` clause.

  Any unqualified symbol references will be treated, as in `from`, as
  references to columns on the main query table. No new bindings can be created
  with this function; however, existing named bindings can be referred to. See the
  `:as` key in the `:join` section of the `from` documentation for details.
  ```
  [query where-expr]
  (let [where-query (dsl-to-query [['where where-expr]])]
    (compose/compose-query query nil where-query)))

(defn join
  ```
  Given an existing query, create a new query with an additional single
  `join` clause.

  Any unqualified symbol references will be treated, as in `from`, as
  references to columns on the joined table. No new bindings can be created
  with this function; however, existing named bindings can be referred to. See the
  `:as` key in the `:join` section of the `from` documentation for details.
  ```
  [query join-expr]
  (let [join-query (dsl-to-query [['join '_ join-expr]])]
    (compose/compose-query query nil join-query)))

(defn select
  ```
  Given an existing query, create a new query with an additional single
  `select` clause.

  Any unqualified symbol references will be treated, as in `from`, as
  references to columns on the main query table. No new bindings can be created
  with this function; however, existing named bindings can be referred to. See the
  `:as` key in the `:join` section of the `from` documentation for details.
  ```
  [query & select-exprs]
  (let [select-query (dsl-to-query [['select ;select-exprs]])]
    (compose/compose-query query nil select-query)))