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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
|
(define-module (transform special-forms)
#:use-module (srfi srfi-1)
#:use-module (ice-9 regex)
#:use-module (ice-9 match)
#:use-module (srfi srfi-26)
#:use-module (transform sql)
#:use-module (transform table)
#:use-module (transform triples)
#:use-module (transform strings)
#:export (translate-forms
collect-forms
collect-keys
field->key
field->assoc-ref
collect-fields
find-clause
remove-namespace
column-id
id
syntax-let
map-alist
with-documentation
emit-short-turtle
define-transformer))
(define (emittable-object? o)
(cond
((null? o) #f)
((not o) #f)
((and (string? o) (string-blank? o)) #f)
(else #t)))
(define (emit-short-turtle subject po-alist)
;; Hot path: avoid rescanning remaining pairs on each step (O(n^2)).
;; Build filtered pairs and count in one pass.
(let collect ((pairs po-alist) (kept '()) (count 0))
(if (null? pairs)
(let loop ((pairs (reverse kept)) (index 0))
(match pairs
(((p . o) rest ...)
(if (zero? index)
(format #t "~a " subject)
(display "\t"))
(match o
((? symbol?)
(format #t "~a ~a" p (symbol->string o)))
((? string?)
(format #t "~a \"~a\"" p o))
(_
(format #t "~a ~s" p o)))
(if (< (+ index 1) count)
(display " ;\n")
(display " .\n"))
(loop rest (+ index 1)))
(() #f)))
(match (car pairs)
((p . o)
(if (emittable-object? o)
(collect (cdr pairs) (cons (cons p o) kept) (+ count 1))
(collect (cdr pairs) kept count)))))))
(define (make-short-turtle-emitter subject)
"Return two procedures: EMIT! and FINISH! for streaming short-turtle output."
(let ((first? #t)
(pending #f))
(define (emit-one pair tail)
(let ((p (car pair))
(o (cdr pair)))
(if first?
(format #t "~a " subject)
(display "\t"))
(match o
((? symbol?)
(format #t "~a ~a" p (symbol->string o)))
((? string?)
(format #t "~a \"~a\"" p o))
(_
(format #t "~a ~s" p o)))
(display tail)
(set! first? #f)))
(define (emit! predicate object)
(when (emittable-object? object)
(let ((current (cons predicate object)))
(when pending
(emit-one pending " ;\n"))
(set! pending current))))
(define (finish!)
(when pending
(emit-one pending " .\n")
(set! pending #f)))
(values emit! finish!)))
(define (key->assoc-ref alist x)
"Recursively translate (key k) forms in source X to (assoc-ref ALIST
k) forms."
(translate-forms 'key
;; (syntax-rules (key)
;; ((key k) (assoc-ref alist k)))
(lambda (x)
(syntax-case x (key)
((key k) #`(assoc-ref #,alist 'k))))
x))
(define (alist-delete* alist keys)
"Delete entries from ALIST whose key is equal (in the sense of
equal?) to any in KEYS, a list."
(remove (match-lambda
((key . value)
(member key keys))
(x (error "malformed alist element" x)))
alist))
(define (translate-forms from translator x)
"Recursively pass (FROM ...) forms in source X to TRANSLATOR, and
replace them with the return value."
(syntax-case x ()
;; Handle translation base case.
((head tail ...) (eq? (syntax->datum #'head)
from)
(translator x))
;; Recurse.
((head tail ...)
(cons (translate-forms from translator #'head)
(map (cut translate-forms from translator <>)
#'(tail ...))))
;; Handle leaf base case.
(leaf #'leaf)))
(define (collect-forms target x)
"Recursively collect (TARGET ...) forms in source X and return them
as a list."
(syntax-case x ()
;; Handle collection base case.
((head tail ...) (eq? (syntax->datum #'head)
target)
(list x))
;; Recurse.
((head tail ...)
(append (collect-forms target #'head)
(append-map (cut collect-forms target <>) #'(tail ...))))
;; Handle leaf base case.
(leaf (list))))
(define (collect-keys x)
"Recursively collect (key k) forms from source X and return as a
list of all K."
(map (syntax-rules (key)
((key k) 'k))
(collect-forms 'key x)))
(define-syntax map-alist
(lambda (x)
"Transform (aka map) ALIST, an association list, into another
association list. The returned association list may contain multiple
associations for the same key. equal? is used in all association list
key comparisons.
Syntax:
(map-alist alist
(verb key expression) ...
(else=> proc))
VERB must be one of set, filter-set, multiset and remove.
For the set VERB, KEY is set to the result of evaluating
EXPRESSION. Multiple set verbs on the same key will result in multiple
associations for that key.
For the filter-set VERB, KEY is set to the result of evaluating
EXPRESSION only if that result is not #f.
For the multiset VERB, EXPRESSION must return a list and KEY is
associated multiple times once with each element of the returned list.
For the remove VERB, KEY is discarded.
EXPRESSIONs must reference elements of ALIST using (key k) forms where
K is the key to be referenced from ALIST. K must not be quoted. That
is, if K is the symbol 'bar, it must be referenced as (key bar), not
as (key 'bar).
The else=> clause is optional.
If the else=> clause is present, PROC is passed all pairs of ALIST
that are not set by an earlier (verb key expression) action. PROC must
return #f or a pair to replace its input pair. If PROC returns #f,
that pair is discarded.
If the else=> clause is absent, all unset pairs are discarded.
Example:
(map-alist '((\"foo\" . 1)
(bar . 2)
(foobar . 5)
(fubar . 3))
(set spam (1+ (key \"foo\")))
(set ham (* 2 (key bar)))
(set eggs (* 3 (key bar)))
(set aal (+ (key \"foo\")
(key bar)))
(multiset vel (iota (* 2 (key bar))))
(remove foobar)
(else=> (match-lambda
((key . value)
(cons key (expt 2 value))))))
=> ((spam . 2) (ham . 4) (eggs . 6) (aal . 3)
(vel . 0) (vel . 1) (vel . 2) (vel . 3) (fubar . 8))"
(syntax-case x ()
((_ alist actions ...)
;; TODO: Check that all actions are valid.
(let* ((actions #'(actions ...))
(filter-set-keys
(filter-map (lambda (action)
(syntax-case action (filter-set)
((filter-set key expression) #'key)
(_ #f)))
actions))
(set/filter-pairs
(filter-map (lambda (action)
(syntax-case action (set filter-set)
((set key expression)
#`(cons 'key #,(key->assoc-ref #'evaluated-alist #'expression)))
((filter-set key expression)
#`(cons 'key #,(key->assoc-ref #'evaluated-alist #'expression)))
(_ #f)))
actions))
(multiset-exprs
(filter-map (lambda (action)
(syntax-case action (multiset)
((multiset key expression)
#`(map (cut cons 'key <>)
#,(key->assoc-ref #'evaluated-alist #'expression)))
(_ #f)))
actions))
(else-proc
(any (lambda (action)
(syntax-case action (else=>)
((else=> proc) #'proc)
(_ #f)))
actions))
(unspecified-keys
#`(list
;; Keys that were referenced
#,@(append-map (lambda (action)
(syntax-case action ()
((_ key expression)
(collect-keys #'expression))
(_ '())))
actions)
;; Keys that were deleted
#,@(filter-map (lambda (action)
(syntax-case action (remove)
((remove key) #''key)
(_ #f)))
actions)
;; Keys that were set
#,@(filter-map (lambda (action)
(syntax-case action ()
((_ key expression) #''key)
(_ #f)))
actions))))
#`(let ((evaluated-alist alist))
(append
;; Do set and filter-set.
#,(if (null? filter-set-keys)
#`(list #,@set/filter-pairs)
#`(remove (match-lambda
((key . #f)
(member key '#,filter-set-keys))
(_ #f))
(list #,@set/filter-pairs)))
;; Do multiset.
#,@multiset-exprs
;; Apply else=> only when explicitly present.
#,@(if else-proc
(list
#`(filter-map #,else-proc
(alist-delete* evaluated-alist
#,unspecified-keys)))
'()))))))))
(eval-when (expand load )
(define (field->datum x)
(translate-forms
'field
(lambda (x)
(syntax-case x (field)
((field (query alias))
#`(format #f "~a" (syntax->datum #'alias)))
((field table column)
#`(format #f "~a(~a)"
(syntax->datum #'table)
(syntax->datum #'column)))
((field table column alias)
#`(format #f "~a(~a)"
(syntax->datum #'table)
(syntax->datum #'alias)))))
x))
(define (field->key x)
(translate-forms 'field
(lambda (x)
#`(key #,(symbol->string
(syntax->datum
((syntax-rules (field)
((field (query alias)) alias)
((field table column) column)
((field table column alias) alias))
x)))))
x))
(define (field->assoc-ref alist x)
"Recursively translate field references in source X to (assoc-ref
ALIST field-name) forms."
(translate-forms 'field
(lambda (x)
#`(assoc-ref #,alist
#,(symbol->string
(syntax->datum
((syntax-rules (field)
((field (query alias)) alias)
((field table column) column)
((field table column alias) alias))
x)))))
x))
(define (collect-fields x)
(map (syntax-rules (field)
((field reference ...)
(reference ...)))
(collect-forms 'field x)))
(define (find-clause clauses key)
"Find (KEY ...) clause among CLAUSES, a list of syntax forms."
(find (lambda (x)
(syntax-case x ()
((clause-key _ ...)
(eq? (syntax->datum #'clause-key)
key))))
clauses))
(define (remove-namespace str)
"Remove RDF namespace prefix from STR."
(substring str (1+ (string-index str #\:))))
(define (column-id table-name column-name)
(string->identifier
"field" (string-append
;; We downcase table names in identifiers. So, we
;; distinguish between the user and User tables.
(if (string=? table-name "User")
"user2" table-name)
"__" column-name)))
(define (id table predicate)
(symbol->string
(string->identifier
"transform"
(string-append
table "_" (remove-namespace (symbol->string predicate)))))))
(define-syntax syntax-let
(syntax-rules ()
"Like match-let, but for syntax.
(syntax-let ((pattern literals expression))
body ...)
≡
(syntax-case expression ()
(pattern literals
body ...))
literals is optional. So,
(syntax-let ((pattern expression))
body ...)
≡
(syntax-case expression ()
(pattern
body ...))
"
((_ () body ...)
(begin body ...))
((_ ((pattern expression)
bindings ...)
body ...)
(syntax-case expression ()
(pattern
(syntax-let (bindings ...)
body ...))))
((_ ((pattern literals expression)
bindings ...)
body ...)
(syntax-case expression literals
(pattern
(syntax-let (bindings ...)
body ...))))))
(define-syntax define-transformer
(lambda (x)
"Define FUNCTION-NAME, a function that transforms a view of the database.
define-transformer consists of three order-agnostic clauses---tables,
schema-triples and triples---in the form shown below.
(define-transformer function-name
(tables (table ...) raw-forms ...)
(schema-triples
(subject predicate object) ...)
(triples subject
(verb predicate object) ...))
The tables clause specifies the database tables to be joined to
construct the view to be transformed. TABLE must be either of the form
TABLE-NAME or of the form (JOIN-OPERATOR TABLE-NAME
RAW-CONDITION). TABLE-NAME must, obviously, be the name of the
table. JOIN-OPERATOR must be one of join, left-join and
inner-join. RAW-CONDITION should be the join condition as a raw
string. This is usually something like
\"USING (SpeciesId)\". RAW-FORMS are expressions that must evaluate to
strings to be appended to the SQL query.
The schema-triples clause specifies the list of triples to be written
once when the transform starts.
The triples clause specifies the triples to be transformed once for each
row in the view. All triples have a common SUBJECT. The (verb
predicate object) clauses are described below.
VERB must either be set or multiset. For the set VERB, a single triple
(SUBJECT PREDICATE OBJECT-VALUE) is written where OBJECT-VALUE is the
result of evaluating OBJECT. For the multiset VERB, OBJECT must
evaluate to a list, and a triple (SUBJECT PREDICATE
OBJECT-VALUE-ELEMENT) is created for each element OBJECT-VALUE-ELEMENT
of that list.
The SUBJECT and OBJECT expressions in the triples clause must
reference database fields using a (field TABLE COLUMN) clause where
TABLE and COLUMN refer to the table and column of the field being
referenced. Database fields can also be referenced using (field TABLE
COLUMN ALIAS) where ALIAS is an alias for that column in the SQL
query. Specification of ALIAS is indeed a leak in the abstraction, and
must be remedied."
(syntax-case x (tables schema-triples triples)
((_ name clauses ...)
(syntax-let (((tables (primary-table other-tables ...) tables-raw ...) (tables)
(find-clause #'(clauses ...) 'tables))
(schema-triples-clause (or (find-clause #'(clauses ...) 'schema-triples)
#'(schema-triples)))
((triples subject predicate-clauses ...) (triples)
(find-clause #'(clauses ...) 'triples)))
#`(define* (name db #:key
(metadata? #f)
(data? #t)
(documentation? #f)
(keyset? #f)
(chunk-key "Id")
(limit #f)
(offset #f)
(cursor #f))
(let* ((base-sql
(select-query #,(collect-fields #'(subject predicate-clauses ...))
(primary-table other-tables ...)
tables-raw ...))
(chunk-keys
(if (list? chunk-key)
chunk-key
(list chunk-key)))
(chunk-key-exprs
(map (lambda (k)
(if (string-index k #\.)
k
(format #f "~a.~a"
#,(symbol->string (syntax->datum #'primary-table))
k)))
chunk-keys))
(sql-for-keyset
(prepend-select-expr
base-sql
(string-join
(map (lambda (expr idx)
(format #f "~a AS __chunk_key_~a" expr (+ idx 1)))
chunk-key-exprs
(iota (length chunk-key-exprs)))
", ")))
(sql
(cond
(keyset?
(append-order-limit
(if cursor
(append-filter-clause
sql-for-keyset
(build-keyset-where chunk-key-exprs cursor))
sql-for-keyset)
(build-keyset-order chunk-key-exprs)
(or limit 100000)))
((and limit offset)
(format #f "~a LIMIT ~a OFFSET ~a"
base-sql limit offset))
(else base-sql))))
(when metadata?
#,@(let ((table (symbol->string (syntax->datum #'primary-table)))
(subject-type (any (lambda (predicate)
(syntax-case predicate (rdf:type)
((_ rdf:type type) #'type)
(_ #f)))
#'(predicate-clauses ...))))
(map (lambda (predicate-clause)
(syntax-case predicate-clause ()
((_ predicate _)
;; Dump metadata about the transform itself.
#`(begin
(scm->triples
(map-alist '()
(set rdf:type 'gn-id:transform)
(set gn-term:createsPredicate 'predicate)
(filter-set gn-term:forSubjectType #,subject-type)
(multiset gn-term:dependsOn
'#,(map (lambda (field)
(match (syntax->datum field)
((table-name column-name _ ...)
(datum->syntax
x (column-id (symbol->string table-name)
(symbol->string column-name))))
(((query alias))
(datum->syntax
x (column-id query (symbol->string alias))))))
(collect-fields predicate-clause))))
#,(id table (syntax->datum #'predicate)))
;; Automatically create domain triples
;; for predicates.
(when #,subject-type
(triple 'predicate 'rdfs:domain #,subject-type))))
(_ (error "Invalid predicate clause:" predicate-clause))))
#'(predicate-clauses ...))))
(when documentation?
(format #t "~%## '~a'~%~%" (syntax->datum #'name))
#,(syntax-case #'schema-triples-clause (schema-triples)
((schema-triples (triple-subject triple-predicate triple-object) ...)
#`(begin
(when (not (list 'triple-subject ...))
(format #t "## Schema Triples:~%~%```text~%")
(for-each (lambda (s p o)
(format #t "~a -> ~a -> ~a~%" s p o))
(list 'triple-subject ...)
(list 'triple-predicate ...)
(list 'triple-object ...))
(format #t "```"))))
(_ (error "Invalid schema triples clause:" #'schema-triples-clause)))
(format #t "## Generated Triples:
The following SQL query was executed:
```sql
~a
```
The above query results to triples that have the form:
```text
"
(select-query #,(collect-fields #'(subject predicate-clauses ...))
(primary-table other-tables ...)
tables-raw ...))
(for-each (match-lambda
((predicate . object)
(format #t "~a -> ~a -> ~a ~%"
(if (symbol? #,(field->datum #'subject))
(symbol->string #,(field->datum #'subject))
#,(field->datum #'subject))
predicate
(if (symbol? object)
(symbol->string object)
object))))
(map-alist
'()
#,@(field->datum #'(predicate-clauses ...))))
(format #t "```~%Here's an example query:~%~%```sparql~%")
(documentation?)
(newline)
(let* ((result
(map-alist (sql-find
db
(format #f "~a LIMIT 1"
(select-query #,(collect-fields #'(subject predicate-clauses ...))
(primary-table other-tables ...)
tables-raw ...)))
#,@(field->key #'(predicate-clauses ...))))
(first-n (list-head result
(let ((n
(min 4 (truncate
(+ (exact-integer-sqrt (length result)) 1)))))
(if (< n 3)
(length result)
n)))))
(format #t "SELECT * WHERE { ~%")
(for-each (match-lambda
((predicate . object)
(match object
((or (? symbol? object)
(? (lambda (el) (string-match "^\\[ .* \\]$" el)) object))
(format #t " ?s ~a ~a .~%" predicate object))
((and (? string? object)
(? (lambda (el) (not (string-null? el))) object))
(format #t " ?s ~a \"~a\" .~%" predicate object))
(_ ""))))
first-n)
(format #t " ?s ?p ?o .~%}~%```~%"))
(format #t "~%Expected Result:~%~%```rdf~%")
(sql-for-each (lambda (row)
(scm->triples
(map-alist row #,@(field->key #'(predicate-clauses ...)))
#,(field->assoc-ref #'row #'subject)
(lambda (s p o)
(triple s p o))))
db
(format #f "~a LIMIT 1" base-sql))
(format #t "```~%~%"))
(when data?
#,(syntax-case #'schema-triples-clause (schema-triples)
((schema-triples (triple-subject triple-predicate triple-object) ...)
#`(for-each triple
(list 'triple-subject ...)
(list 'triple-predicate ...)
(list 'triple-object ...)))
(_ (error "Invalid schema triples clause:" #'schema-triples-clause)))
(let ((rows-written 0)
(last-cursor cursor))
(sql-for-each
(lambda (row)
(set! rows-written (+ rows-written 1))
(when keyset?
(set! last-cursor
(map (lambda (idx)
(assoc-ref row (format #f "__chunk_key_~a" (+ idx 1))))
(iota (if (list? chunk-key)
(length chunk-key)
1)))))
(let ((subject-val #,(field->assoc-ref #'row #'subject)))
(call-with-values
(lambda () (make-short-turtle-emitter subject-val))
(lambda (emit! finish!)
#,@(map (lambda (predicate-clause)
(syntax-case predicate-clause (set multiset filter-set)
((set predicate object)
#`(emit! 'predicate
#,(field->assoc-ref #'row #'object)))
((filter-set predicate object)
#`(let ((val #,(field->assoc-ref #'row #'object)))
(when val
(emit! 'predicate val))))
((multiset predicate object)
#`(for-each (lambda (val)
(emit! 'predicate val))
#,(field->assoc-ref #'row #'object)))
(_ (error "Invalid predicate clause:" predicate-clause))))
#'(predicate-clauses ...))
(finish!)))))
db
sql)
(if keyset?
(cons rows-written last-cursor)
rows-written)))))))
(_ (error "Invalid define-transformer syntax:" (syntax->datum x))))))
(define (sql-literal v)
(cond
((number? v) (number->string v))
((string? v)
(format #f "'~a'" (replace-substrings v '(("'" . "''")))))
((symbol? v)
(format #f "'~a'" (symbol->string v)))
(else
(format #f "'~a'" v))))
(define (normalize-keyset-cursor cursor key-count)
(cond
((not cursor) #f)
((and (= key-count 1) (not (list? cursor)))
(list cursor))
((and (list? cursor) (= (length cursor) key-count))
cursor)
(else
(error "Invalid keyset cursor, expected "
key-count " values, got: " cursor))))
(define (normalize-key-exprs key-spec)
"Accept either a list of SQL key expressions or a key count."
(cond
((list? key-spec) key-spec)
((number? key-spec)
(map (lambda (idx)
(format #f "__chunk_key_~a" (+ idx 1)))
(iota key-spec)))
(else
(error "Invalid key specification: " key-spec))))
(define (build-keyset-order key-spec)
(string-join
(normalize-key-exprs key-spec)
", "))
(define (build-keyset-where key-spec cursor)
(let* ((key-exprs (normalize-key-exprs key-spec))
(key-count (length key-exprs))
(vals (normalize-keyset-cursor cursor key-count)))
(unless vals
(error "build-keyset-where called with empty cursor"))
(string-join
(map (lambda (i)
(let ((eq-prefix
(string-join
(map (lambda (j)
(format #f "~a = ~a"
(list-ref key-exprs j)
(sql-literal (list-ref vals j))))
(iota i))
" AND "))
(gt-part
(format #f "~a > ~a"
(list-ref key-exprs i)
(sql-literal (list-ref vals i)))))
(if (zero? i)
gt-part
(string-append "(" eq-prefix " AND " gt-part ")"))))
(iota key-count))
" OR ")))
(define (find-sql-tail-start sql)
(let ((positions
(filter-map identity
(list (string-contains sql " GROUP BY ")
(string-contains sql " ORDER BY ")
(string-contains sql " LIMIT ")))))
(if (null? positions) #f (apply min positions))))
(define (append-filter-clause sql clause)
(let* ((tail-start (find-sql-tail-start sql))
(head (if tail-start (substring sql 0 tail-start) sql))
(tail (if tail-start (substring sql tail-start) "")))
(if (string-contains head " WHERE ")
(string-append head " AND (" clause ")" tail)
(string-append head " WHERE (" clause ")" tail))))
(define (append-order-limit sql order-expr limit)
(let* ((tail-start (find-sql-tail-start sql))
(head (if tail-start (substring sql 0 tail-start) sql))
(tail (if tail-start (substring sql tail-start) "")))
(string-append head tail
" ORDER BY " order-expr
" LIMIT " (number->string limit))))
(define (prepend-select-expr sql expr)
"Prepend EXPR to the SELECT list of SQL."
(cond
((and (>= (string-length sql) 16)
(string=? (substring sql 0 16) "SELECT DISTINCT "))
(string-append "SELECT DISTINCT " expr ", " (substring sql 16)))
((and (>= (string-length sql) 7)
(string=? (substring sql 0 7) "SELECT "))
(string-append "SELECT " expr ", " (substring sql 7)))
(else
(error "Expected SQL SELECT query" sql))))
(define (get-keyword-value args keyword default)
(let ((kv (memq keyword args)))
(if (and kv (>= (length kv) 2))
(cadr kv)
default)))
(define-syntax with-documentation
(syntax-rules ()
((_ (key value) ...)
(let* ((alist `((key . ,value) ...))
(name (assoc-ref alist 'name))
(connection (assoc-ref alist 'connection))
(table-metadata? (assoc-ref alist 'table-metadata?))
(prefixes (assoc-ref alist 'prefixes))
(inputs (assoc-ref alist 'inputs))
(outputs (assoc-ref alist 'outputs))
(total-rows (assoc-ref alist 'total-rows))
(rows-per-chunk (assoc-ref alist 'rows-per-chunk))
(keyset-pagination? (assoc-ref alist 'keyset-pagination?))
(chunk-key-field (assoc-ref alist 'chunk-key-field))
(chunking? (and total-rows rows-per-chunk))
(chunks (if chunking?
(ceiling (/ total-rows rows-per-chunk))
1))
(rdf-path (get-keyword-value outputs #:rdf #f))
(doc-path (get-keyword-value outputs #:documentation #f)))
(call-with-target-database
connection
(lambda (db)
(when doc-path
(with-output-to-file ;
doc-path
(lambda ()
(format #t "# ~a" name)
(for-each
(lambda (proc)
(proc db
#:metadata? #f
#:data? #f
#:documentation?
(lambda () (for-each
(match-lambda
((k v)
(begin
(prefix k v #f))))
prefixes))))
inputs))
#:encoding "UTF-8"))
;; Dumping the actual data
(when rdf-path
(if keyset-pagination?
;; Cursor-based chunking with configurable key column.
(let loop ((chunk-index 0)
(states (map (lambda (_) (cons #f #f)) inputs)))
(unless (every cdr states)
(let* ((out-file
(if (= chunk-index 0)
rdf-path
(string-append (path-without-extension rdf-path)
"." (number->string (+ chunk-index 1)) ".ttl")))
(next-states
(with-output-to-file
out-file
(lambda ()
(for-each
(match-lambda
((k v)
(prefix k v)))
prefixes)
(newline)
(let walk ((procs inputs)
(st states)
(acc '()))
(if (null? procs)
(reverse acc)
(let* ((state (car st))
(cursor (car state))
(done? (cdr state)))
(if done?
(walk (cdr procs) (cdr st) (cons state acc))
(let* ((result ((car procs)
db
#:metadata? table-metadata?
#:keyset? #t
#:chunk-key (or chunk-key-field "Id")
#:limit rows-per-chunk
#:cursor cursor))
(rows (car result))
(next-cursor (cdr result))
(proc-done? (or (= rows 0)
(< rows rows-per-chunk))))
(walk (cdr procs)
(cdr st)
(cons (cons next-cursor proc-done?) acc))))))))
#:encoding "UTF-8")))
(loop (+ chunk-index 1) next-states))))
;; Legacy OFFSET chunking.
(do ((i 0 (+ i 1)))
((>= i chunks))
(let* ((offset (* i (or rows-per-chunk 0)))
(out-file
(if (= chunks 1)
rdf-path
(string-append (path-without-extension rdf-path)
"." (number->string (+ i 1)) ".ttl"))))
(with-output-to-file
out-file
(lambda ()
(for-each
(match-lambda
((k v)
(prefix k v)))
prefixes)
(newline)
(for-each
(lambda (proc)
(proc db #:metadata? table-metadata?
#:limit rows-per-chunk
#:offset offset))
inputs))
#:encoding "UTF-8")))))))))))
|