Skip to content

Commit

Permalink
Merge pull request #49 from mackee/feature/iter
Browse files Browse the repository at this point in the history
add: *SelectSQL.IterContext is returns iter.Seq2[*, error].
  • Loading branch information
mackee authored Sep 9, 2024
2 parents 99dda07 + d3864c2 commit 9efc604
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions template/select.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}

0 comments on commit 9efc604

Please sign in to comment.