sqlcoro

package module
v0.0.0-...-908ab32 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 11, 2020 License: MIT Imports: 2 Imported by: 1

Documentation

Overview

Package sqlcoro provides a database/sql rows iterator based on github.com/tcard/coro. Under the hood, it calls Next, Err and Close on a Rows appropriately and returns any error that those may produce.

Example
package main

import (
	"context"
	"database/sql"
	"fmt"
	"reflect"

	"github.com/tcard/coro"
	"github.com/tcard/sqlcoro"
	"github.com/tcard/sqler"
)

func main() {
	// rows would actually be a valid *sql.Rows, wrapped as a sqler.Rows.
	rows := &exampleRows{
		{13, "foo"},
		{42, "bar"},
	}

	// You'll typically want to tie the iterator's lifetime to its consumer's this
	// way, but it's not necessary to do so. See coro documentation for details.
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	coroOption := coro.KillOnContextDone(ctx)

	nextRow := sqlcoro.IterateRows(rows, coroOption)

	var row sqler.Row
	var err error
	for nextRow(&row, &err) {
		var id int
		var name string

		err := row.Scan(&id, &name)
		if err != nil {
			_ = err // handle
			return
		}

		fmt.Println("ID:", id, "Name:", name)
	}
	if err != nil {
		_ = err // handle
	}

}

type exampleRows [][]interface{}

func (r *exampleRows) Next() bool {
	return len(*r) > 0
}

func (r *exampleRows) Scan(dest ...interface{}) error {
	for i, d := range dest {
		reflect.ValueOf(d).Elem().Set(reflect.ValueOf((*r)[0][i]))
	}
	*r = (*r)[1:]
	return nil
}

func (r *exampleRows) Err() error {
	return nil
}

func (r *exampleRows) Close() error {
	return nil
}

func (*exampleRows) ColumnTypes() ([]*sql.ColumnType, error) { panic("not provided") }
func (*exampleRows) Columns() ([]string, error)              { panic("not provided") }
func (*exampleRows) NextResultSet() bool                     { panic("not provided") }
Output:

ID: 13 Name: foo
ID: 42 Name: bar

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type NextFunc

type NextFunc func(yielded *sqler.Row, returned *error) (alive bool)

func IterateRows

func IterateRows(rows sqler.Rows, options ...coro.SetOption) NextFunc

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL