Skip to content

Commit

Permalink
feat: implement buffered row iterator
Browse files Browse the repository at this point in the history
To be used for reading interleaved rows where the rows need to be
buffered before iterating.
  • Loading branch information
ericwenn committed Mar 2, 2021
1 parent e9c8580 commit bdda8af
Show file tree
Hide file tree
Showing 10 changed files with 778 additions and 0 deletions.
40 changes: 40 additions & 0 deletions internal/codegen/databasecodegen/rowiterator.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,13 @@ func (g RowIteratorCodeGenerator) StreamingType() string {
return "streaming" + strcase.UpperCamelCase(string(g.Table.Name)) + "RowIterator"
}

func (g RowIteratorCodeGenerator) BufferedType() string {
return "buffered" + strcase.UpperCamelCase(string(g.Table.Name)) + "RowIterator"
}

func (g RowIteratorCodeGenerator) GenerateCode(f *codegen.File) {
spannerPkg := f.Import("cloud.google.com/go/spanner")
iteratorPkg := f.Import("google.golang.org/api/iterator")
row := RowCodeGenerator(g)
f.P()
f.P("type ", g.InterfaceType(), " interface {")
Expand Down Expand Up @@ -53,4 +58,39 @@ func (g RowIteratorCodeGenerator) GenerateCode(f *codegen.File) {
f.P("return f(&row)")
f.P("})")
f.P("}")
f.P()
f.P("type ", g.BufferedType(), " struct {")
f.P("rows []*", row.Type())
f.P("err error")
f.P("}")
f.P()
f.P("func (i *", g.BufferedType(), ") Next() (*", row.Type(), ", error) {")
f.P("if i.err != nil {")
f.P("return nil, i.err")
f.P("}")
f.P("if len(i.rows) == 0 {")
f.P("return nil, ", iteratorPkg, ".Done")
f.P("}")
f.P("next := i.rows[0]")
f.P("i.rows = i.rows[1:]")
f.P("return next, nil")
f.P("}")
f.P()
f.P("func (i *", g.BufferedType(), ") Do(f func(row *", row.Type(), ") error) error {")
f.P("for {")
f.P("row, err := i.Next()")
f.P("switch err {")
f.P("case ", iteratorPkg, ".Done:")
f.P("return nil")
f.P("case nil:")
f.P("if err = f(row); err != nil {")
f.P("return err")
f.P("}")
f.P("default:")
f.P("return err")
f.P("}")
f.P("}")
f.P("}")
f.P()
f.P("func (i *", g.BufferedType(), ") Stop() {}")
}
36 changes: 36 additions & 0 deletions internal/codegen/databasecodegen/testdata/1.sql.database.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

70 changes: 70 additions & 0 deletions internal/codegen/databasecodegen/testdata/2.sql.database.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

105 changes: 105 additions & 0 deletions internal/codegen/databasecodegen/testdata/3.sql.database.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit bdda8af

Please sign in to comment.