如何将数据库列映射到 Racket 结构列表中的结构?
How do I map database columns to a struct in a list of structs in Racket?
我有一个名为 attendance-events 的列表,由 struct 类型的 attendance-event 组成。该结构定义为
(define-struct attendance-event (date flag))
"date" 是事件的日期,"flag" 是表示事件类型的 2 个字符的值。
在我的数据库中,我选择 "select date, code from attendance_table",我希望将这两列添加到每一行的出勤事件列表中。
那么,如何做到这一点?
我发现在将数据库行转换为哈希表后,使用它们会容易得多。以下函数将 query
函数返回的 rows-result
类型转换为不可变哈希列表:
(require (planet jphelps/loop)) ;; Use the loop macro from Common Lisp.
(define (rows-result->hash results)
(let ((header (rows-result-headers results)))
(loop for row in (rows-result-rows results)
collect (loop for ((_ . name) (_ . decltype)) in header
for column across row
with-collection-type hash/immutable
collect (cons name column)))))
然后你可以像这样包装 query
函数:
(define (simple-query query-text conn . params)
(rows-result->hash (apply query (list* conn query-text params))))
最后,创建您的结构:
(loop for row in (simple-query "select date,code from attendance_table;")
collect (make-attendance-event (hash-ref row 'date) (hash-ref row 'code)))
这将执行查询和 returns attendance-event
结构的列表:
(for/list ([(date code)
(in-query conn "select date, code from attendance_table")])
(make-attendance-event date code))
我有一个名为 attendance-events 的列表,由 struct 类型的 attendance-event 组成。该结构定义为
(define-struct attendance-event (date flag))
"date" 是事件的日期,"flag" 是表示事件类型的 2 个字符的值。
在我的数据库中,我选择 "select date, code from attendance_table",我希望将这两列添加到每一行的出勤事件列表中。
那么,如何做到这一点?
我发现在将数据库行转换为哈希表后,使用它们会容易得多。以下函数将 query
函数返回的 rows-result
类型转换为不可变哈希列表:
(require (planet jphelps/loop)) ;; Use the loop macro from Common Lisp.
(define (rows-result->hash results)
(let ((header (rows-result-headers results)))
(loop for row in (rows-result-rows results)
collect (loop for ((_ . name) (_ . decltype)) in header
for column across row
with-collection-type hash/immutable
collect (cons name column)))))
然后你可以像这样包装 query
函数:
(define (simple-query query-text conn . params)
(rows-result->hash (apply query (list* conn query-text params))))
最后,创建您的结构:
(loop for row in (simple-query "select date,code from attendance_table;")
collect (make-attendance-event (hash-ref row 'date) (hash-ref row 'code)))
这将执行查询和 returns attendance-event
结构的列表:
(for/list ([(date code)
(in-query conn "select date, code from attendance_table")])
(make-attendance-event date code))