From d3864c25d70439fe393bdae162b3237d563bfe16 Mon Sep 17 00:00:00 2001 From: mackee Date: Mon, 9 Sep 2024 11:24:15 +0900 Subject: [PATCH] add: *SelectSQL.IterContext is returns iter.Seq2[*, error]. --- template/select.tmpl | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/template/select.tmpl b/template/select.tmpl index e94bd86..df39786 100644 --- a/template/select.tmpl +++ b/template/select.tmpl @@ -245,4 +245,47 @@ func (q {{ $camelName }}SelectSQL) Scan(s sqlla.Scanner) ({{ .StructName }}, err ) return row, err } + +// IterContext returns iter.Seq2[{{ .StructName }}, error] and closer. +// +// The returned Iter.Seq2 assembles and executes a query in the first iteration. +// Therefore, the first iteration may return an error in assembling or executing the query. +// Subsequent iterations read rows. Again, the read may return an error. +// +// closer is a function that closes the row reader object. Execution of this function is idempotent. +// Be sure to call it when you are done using iter.Seq2. +func (q {{ $camelName }}SelectSQL) IterContext(ctx context.Context, db sqlla.DB) (func (func ({{ .StructName }}, error) bool), func() error) { + var rowClose func() error + closer := func() error { + if rowClose != nil { + err := rowClose() + rowClose = nil + return err + } + return nil + } + + q.Columns = {{ $camelName }}AllColumns + query, args, err := q.ToSql() + return func (yield func({{ .StructName}}, error) bool) { + if err != nil { + var r {{ .StructName }} + yield(r, err) + return + } + rows, err := db.QueryContext(ctx, query, args...) + if err != nil { + var r {{ .StructName }} + yield(r, err) + return + } + rowClose = rows.Close + for rows.Next() { + r, err := q.Scan(rows) + if !yield(r, err) { + break + } + } + }, closer +} {{ end }}