Tweak and export bulk-insert

This commit is contained in:
Christopher Baines 2025-07-09 12:50:57 +01:00
parent 2073e446b7
commit 2fc20fa37e

View file

@ -37,6 +37,7 @@
insert-missing-data insert-missing-data
update-or-insert update-or-insert
bulk-select bulk-select
bulk-insert
insert-and-return-id insert-and-return-id
prepare-insert-and-return-id)) prepare-insert-and-return-id))
@ -278,7 +279,8 @@ JOIN (VALUES "
table-name table-name
fields fields
data data
#:key (id-proc string->number)) #:key (id-proc string->number)
(returning '(id)))
(define field-strings (define field-strings
(map symbol->string fields)) (map symbol->string fields))
@ -298,33 +300,44 @@ INSERT INTO " table-name " (" (string-join field-strings ", ") ") VALUES
")")) ")"))
data) data)
", ") " ", ") "
ON CONFLICT DO NOTHING ON CONFLICT DO NOTHING"
RETURNING id")) (if (and returning
(not (null? returning)))
(string-append
"
RETURNING " (string-join (map symbol->string returning)
", "))
"")))
(if (null? data) (if (null? data)
#() #()
(let* ((query-result (exec-query conn query)) (if (and returning
(expected-ids (length data)) (not (null? returning)))
(returned-ids (length query-result))) (let* ((query-result (exec-query conn query))
(if (= expected-ids returned-ids) (expected-ids (length data))
(let ((result (returned-ids (length query-result)))
(make-vector returned-ids))) (if (= expected-ids returned-ids)
(fold (let ((result
(lambda (row index) (make-vector returned-ids)))
(match row (fold
((id) (lambda (row index)
(vector-set! result index (match row
(id-proc id)))) ((id)
(1+ index)) (vector-set! result index
0 (id-proc id))))
query-result) (1+ index))
result) 0
;; Can't match up the ids to the data, so just query for them query-result)
(bulk-select conn result)
table-name ;; Can't match up the ids to the data, so just query for them
fields (bulk-select conn
data table-name
#:id-proc id-proc))))) fields
data
#:id-proc id-proc)))
(begin
(exec-query conn query)
*unspecified*))))
(define* (insert-missing-data (define* (insert-missing-data
conn conn