-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsnooze-class.ss
436 lines (368 loc) · 15.6 KB
/
snooze-class.ss
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#lang scheme/base
(require "base.ss")
(require scheme/class
scheme/list
srfi/26
(planet untyped/unlib:3/gen)
(planet untyped/unlib:3/parameter)
"core/core.ss"
"common/common.ss"
"sql/sql.ss")
; Constructor ------------------------------------
; database<%> [#:connect-on-demand? boolean] -> snooze<%>
(define (make-snooze database #:connect-on-demand? [connect-on-demand? #f])
(new snooze% [database database] [connect-on-demand? connect-on-demand?]))
; Classes ----------------------------------------
(define snooze%
(class* object% (snooze<%>)
(inspect #f)
; Fields -------------------------------------
; (thread-cell (U connection #f))
;
; A thread-cell to store the current connection.
; See the current-connection method below for more information.
(field [current-connection-cell (make-thread-cell #f)])
; (parameter (U transaction-frame #f))
(field [current-transaction-frame (make-parameter #f)])
; (connection snooze-struct -> any) connection snooze-struct -> any
;
; A transparent procedure that wraps the body of any
; call-with-transaction block. Must return the same value
; as the transaction body.
(field [transaction-hook (lambda (continue conn struct) (continue conn struct))])
; (parameter (U (query real -> void) #f))
(field [query-logger (make-parameter #f)])
; (parameter (U ((listof guid) real -> void) #f))
(field [direct-find-logger (make-parameter #f)])
; Constructor --------------------------------
; database<%>
(init-field database)
; boolean
(init-field [connect-on-demand? #f])
; (U (query real -> void) #f)
(init [(init-query-logger query-logger) #f])
; (U ((listof guid) real -> void) #f)
(init [(init-direct-find-logger direct-find-logger) #f])
(super-new)
(when init-query-logger
(query-logger init-query-logger))
(when init-direct-find-logger
(direct-find-logger init-direct-find-logger))
(send database set-snooze! this)
; Public interface ---------------------------
; -> database<%>
(define/public (get-database)
database)
; database<%> -> void
(define/public (set-database! new-database)
(set! database new-database))
; -> ((connection snooze-struct -> any) connection snooze-struct -> any)
(define/public (get-transaction-hook)
transaction-hook)
; ((connection snooze-struct -> any) connection snooze-struct -> any) -> void
(define/public (set-transaction-hook! hook)
(set! transaction-hook hook))
; (-> any) -> any
(define/public (call-with-connection thunk)
(if (thread-cell-ref current-connection-cell)
(thunk)
(dynamic-wind (if connect-on-demand?
void
(cut connect))
(cut thunk)
(cut disconnect))))
; -> void
(define/public (connect)
(unless (thread-cell-ref current-connection-cell)
(thread-cell-set! current-connection-cell (send database connect))))
; -> void
(define/public (disconnect)
(when (thread-cell-ref current-connection-cell)
(send database disconnect (thread-cell-ref current-connection-cell))
(thread-cell-set! current-connection-cell #f)))
; -> void
(define (connect-on-demand)
(when (and connect-on-demand? (not (thread-cell-ref current-connection-cell)))
(connect)))
; -> connection
(define/public (current-connection)
(or (thread-cell-ref current-connection-cell)
(raise-exn exn:fail:snooze "no database connection: use call-with-connection to set one up")))
; entity -> void
(define/public (create-table entity)
(call-with-transaction (cut send database create-table (current-connection) entity)))
; entity -> void
(define/public (drop-table entity)
(connect-on-demand)
(call-with-transaction (cut send database drop-table (current-connection) entity)))
; snooze-struct -> snooze-struct
(define/public (save! struct)
(connect-on-demand)
(parameterize ([currently-saving struct])
(let ([guid (snooze-struct-guid struct)]
[entity (snooze-struct-entity struct)])
(call-with-transaction
(lambda ()
(transaction-frame-data-add! (get-current-transaction-frame) guid)
((entity-on-save entity)
(lambda (conn struct)
(transaction-frame-cache-add!
(get-current-transaction-frame)
(begin
(if (snooze-struct-saved? struct)
(send database update-struct conn struct)
(send database insert-struct conn struct)))))
(current-connection)
struct))))))
; snooze-struct -> snooze-struct
(define/public (delete! struct)
(unless (snooze-struct-saved? struct)
(raise-exn exn:fail:snooze (format "unsaved structs cannot be deleted ~a" struct)))
(connect-on-demand)
(parameterize ([currently-deleting struct])
(let ([guid (snooze-struct-guid struct)]
[entity (snooze-struct-entity struct)])
(call-with-transaction
(lambda ()
(transaction-frame-data-add! (get-current-transaction-frame) guid)
((entity-on-delete entity)
(lambda (conn struct)
(transaction-frame-cache-remove!
(get-current-transaction-frame)
(send database delete-struct conn struct)))
(current-connection)
struct))))))
; query -> (list-of result)
(define/public (find-all query)
(g:collect (g:find query)))
; select -> (U result #f)
(define/public (find-one query)
(let ([result ((g:find query))])
(and (not (g:end? result)) result)))
; select -> result-generator
(define/public (g:find select)
(connect-on-demand)
(call-with-log
(query-logger)
select
(lambda ()
(send database g:find
(current-connection)
select
(or (get-current-transaction-frame)
(transaction-frame-push #f))))))
; entity natural -> snooze-struct
(define/public (find-by-id entity id)
(let ([ans (find-by-guids (list (entity-make-guid entity id)))])
(and (pair? ans) (car ans))))
; database-guid -> snooze-struct
(define/public (find-by-guid guid)
(let ([ans (find-by-guids (list guid))])
(and (pair? ans) (car ans))))
; (listof database-guid) -> (listof snooze-struct)
(define/public (find-by-guids guids)
(connect-on-demand)
(call-with-log
(direct-find-logger)
guids
(lambda ()
(cond [(null? guids) null]
[(null? (cdr guids))
(g:collect (send (get-database) direct-find
(current-connection)
guids
(get-current-transaction-frame)))]
[else (let ([lookup (g:collect/hash
(send (get-database) direct-find
(current-connection)
(remove-duplicates guids)
(get-current-transaction-frame))
snooze-struct-guid)])
(map (cut hash-ref lookup <>) guids))]))))
; Takes:
; - a list of structs of the same entity;
; - a foreign key attribute from that entity.
;
; Iterates through the structs finding any unloaded database-guids in the foreign key attribute.
; Loads the related structs and cross references the foreign keys.
; Returns the original (listof struct) argument, mutated with the cross references in place.
;
; (listof snooze-struct) attribute -> (listof snooze-struct)
(define/public (load-related! structs attr)
(let ([entity (attribute-entity attr)]
[accessor (attribute-private-accessor attr)]
[mutator (attribute-private-mutator attr)])
; Quick type check:
(unless (and (guid-type? (attribute-type attr))
(memq attr (entity-data-attributes entity)))
(raise-type-error 'find-related! "foreign-key-attribute" attr))
(let*-values ([(to-mutate to-find)
; Work out which foreign keys need loading, and which structs need mutating:
(for/fold ([to-mutate null]
[to-find null])
([struct (in-list structs)])
(let ([val (accessor struct)])
(if (database-guid? val)
(values (cons struct to-mutate)
(cons val to-find))
(values to-mutate to-find))))]
; Look up the related structs:
[(found) (find-by-guids to-find)])
; Mutate the original structs:
(for ([struct (in-list to-mutate)]
[found (in-list found)])
(mutator struct found))
; Return the original argument:
structs)))
; Takes:
; - a list of structs of the same entity;
; - a foreign key attribute from that entity;
; - a list of structs of the foreign key type.
;
; Iterates through the structs finding any unloaded database-guids in the foreign key attribute.
; Loads the related structs and cross references the foreign keys.
; Returns the original (listof struct) argument, mutated with the cross references in place.
;
; (listof snooze-struct) attribute -> (listof snooze-struct)
(define/public (cross-reference-related! structs attr other-structs)
(let ([entity (attribute-entity attr)]
[accessor (attribute-private-accessor attr)]
[mutator (attribute-private-mutator attr)]
[lookup-table (make-hash)])
; database-guid -> (U database-guid snooze-struct)
(define (lookup guid)
(hash-ref lookup-table guid guid))
; Quick type check:
(unless (and (guid-type? (attribute-type attr))
(memq attr (entity-data-attributes entity)))
(raise-type-error 'find-related! "foreign-key-attribute" attr))
; Populate the lookup table:
(for ([struct (in-list other-structs)])
(hash-set! lookup-table (snooze-struct-guid struct) struct))
; Work out which foreign keys need loading, and which structs need mutating:
(for ([struct (in-list structs)])
(let ([val (accessor struct)])
(when (database-guid? val)
; Lookup returns:
; - the new struct if it's in lookup-table;
; - the original guid if the struct isn't in the lookup-table;
(mutator struct (lookup val)))))
; Return the original argument:
structs))
; thunk [#:metadata list] -> any
;
; If the database allows it, a transaction is started and the thunk argument
; is called. Some databases do not allow nested transactions, so a new
; transaction is not guaranteed at all times with all backends.
;
; If the thunk is allowed to finish gracefully, the transaction is committed.
;
; If, however, execution is terminated via an exception or escape
; continuation, the transaction is rolled back.
;
; A continuation barrier is installed around the transaction to prevent
; arbitrary jumps into and out of the body.
;
; You are advised to only allow a single thread to execute within a transaction body.
;
; The extra arguments are passed to the transaction hook (if it is present)
; but *not* to the body thunk.
(define/public (call-with-transaction #:metadata [metadata null] body)
(connect-on-demand)
(let ([conn (current-connection)])
(if (send database transaction-allowed? conn)
(call-with-transaction-frame
(lambda ()
(let ([hook (get-transaction-hook)])
(send database call-with-transaction
conn
(lambda ()
(hook (lambda _ (body)) conn metadata))))))
(body))))
; -> (U transaction-frame #f)
(define/public (get-current-transaction-frame)
(current-transaction-frame))
; (-> any) -> any
(define/private (call-with-transaction-frame thunk)
(let ([frame (transaction-frame-push (get-current-transaction-frame))]
[complete? #f])
(call-with-continuation-barrier
(lambda ()
(dynamic-wind
; Entry
void
; Body
(lambda ()
(parameterize ([current-transaction-frame frame])
(begin0
(thunk)
(set! complete? #t))))
; Exit
(lambda ()
(if complete?
(transaction-frame-commit! frame)
(transaction-frame-rollback! frame))))))))
; -> (listof symbol)
(define/public (table-names)
(connect-on-demand)
(send database table-names (current-connection)))
; (U symbol entity) -> boolean
(define/public (table-exists? table)
(connect-on-demand)
(send database table-exists? (current-connection) table))
; query -> string
(define/public (query->string query)
(let ([out (open-output-string)])
(send database debug-sql query out "~a")
(get-output-string out)))
; select
; [string]
; [output-port]
; ->
; select
;
; Prints an SQL string to stdout as a side effect.
(define/public (debug-sql query #:format [format "~a~n"] #:output-port [output-port (current-output-port)])
(send database debug-sql query output-port format))
; -> (query real -> void)
(define/public (get-query-logger)
(query-logger))
; (query real -> void) -> void
(define/public (set-query-logger! logger)
(query-logger logger))
; (query real -> void) (-> any) -> any
(define/public (call-with-query-logger logger thunk)
(parameterize ([query-logger logger])
(thunk)))
; -> (query real -> void)
(define/public (get-direct-find-logger)
(direct-find-logger))
; (query real -> void) -> void
(define/public (set-direct-find-logger! logger)
(direct-find-logger logger))
; (query real -> void) (-> any) -> any
(define/public (call-with-direct-find-logger logger thunk)
(parameterize ([direct-find-logger logger])
(thunk)))))
; Helpers ----------------------------------------
; Log a message and the time taken to perform a thunk.
; The message can be any type.
;
; (message real -> any)
; message
; (-> any)
; -> any
(define (call-with-log logger msg thunk)
(if logger
(let ([start #f])
(dynamic-wind
(lambda ()
(set! start (current-inexact-milliseconds)))
thunk
(lambda ()
(logger msg (- (current-inexact-milliseconds) start)))))
(thunk)))
; Provide statements -----------------------------
(provide/contract
[snooze% class?]
[make-snooze (->* ((is-a?/c database<%>)) (#:connect-on-demand? boolean?) any)])