(define-module(database postgres-resx)#:export(for-each-tuple object<-result result-field->object-list result->object-alist result->object-alists result->object-rows)#:use-module((database postgres)#:select(pg-nfields pg-ntuples pg-getvalue pg-fname)))
(define(for-each-tuple proc result)(let*((nfields(pg-nfields result))(ntuples(pg-ntuples result))(field-range(iota nfields)))(and(< 0 nfields)(< 0 ntuples)(do((tn 0(#{1+}# tn)))((= tn ntuples)#t)(apply proc(map(lambda(fn)(pg-getvalue result tn fn))field-range))))))
(define(object<-result result objectifier)(objectifier(pg-getvalue result 0 0)))
(define(result-field->object-list result fn objectifier)(let loop((tn(#{1-}#(pg-ntuples result)))(acc '()))(if(> 0 tn)acc(loop(#{1-}# tn)(cons(objectifier(pg-getvalue result tn fn))acc)))))
(define(result->object-alist result objectifiers)(let((fn -1))(map(lambda(objectifier)(set! fn(#{1+}# fn))(cons(string->symbol(pg-fname result fn))(result-field->object-list result fn objectifier)))objectifiers)))
(define(result->object-alists result objectifiers)(let((oa(result->object-alist result objectifiers)))(let((names(map car oa)))(apply map(lambda slice(map cons names slice))(map cdr oa)))))
(define(result->object-rows result objectifiers)(let*((acc(list #f))(tp acc))(for-each-tuple(lambda ls(set-cdr! tp(list(map(lambda(proc string)(proc string))objectifiers ls)))(set! tp(cdr tp)))result)(cdr acc)))
