1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
package sqlitex
import (
"errors"
"github.com/go-llsqlite/crawshaw"
)
var ErrNoResults = errors.New("sqlite: statement has no results")
var ErrMultipleResults = errors.New("sqlite: statement has multiple result rows")
func resultSetup(stmt *sqlite.Stmt) error {
hasRow, err := stmt.Step()
if err != nil {
stmt.Reset()
return err
}
if !hasRow {
stmt.Reset()
return ErrNoResults
}
return nil
}
func resultTeardown(stmt *sqlite.Stmt) error {
hasRow, err := stmt.Step()
if err != nil {
stmt.Reset()
return err
}
if hasRow {
stmt.Reset()
return ErrMultipleResults
}
return stmt.Reset()
}
// ResultInt steps the Stmt once and returns the first column as an int.
//
// If there are no rows in the result set, ErrNoResults is returned.
//
// If there are multiple rows, ErrMultipleResults is returned with the first
// result.
//
// The Stmt is always Reset, so repeated calls will always return the first
// result.
func ResultInt(stmt *sqlite.Stmt) (int, error) {
res, err := ResultInt64(stmt)
return int(res), err
}
// ResultInt64 steps the Stmt once and returns the first column as an int64.
//
// If there are no rows in the result set, ErrNoResults is returned.
//
// If there are multiple rows, ErrMultipleResults is returned with the first
// result.
//
// The Stmt is always Reset, so repeated calls will always return the first
// result.
func ResultInt64(stmt *sqlite.Stmt) (int64, error) {
if err := resultSetup(stmt); err != nil {
return 0, err
}
return stmt.ColumnInt64(0), resultTeardown(stmt)
}
// ResultText steps the Stmt once and returns the first column as a string.
//
// If there are no rows in the result set, ErrNoResults is returned.
//
// If there are multiple rows, ErrMultipleResults is returned with the first
// result.
//
// The Stmt is always Reset, so repeated calls will always return the first
// result.
func ResultText(stmt *sqlite.Stmt) (string, error) {
if err := resultSetup(stmt); err != nil {
return "", err
}
return stmt.ColumnText(0), resultTeardown(stmt)
}
// ResultFloat steps the Stmt once and returns the first column as a float64.
//
// If there are no rows in the result set, ErrNoResults is returned.
//
// If there are multiple rows, ErrMultipleResults is returned with the first
// result.
//
// The Stmt is always Reset, so repeated calls will always return the first
// result.
func ResultFloat(stmt *sqlite.Stmt) (float64, error) {
if err := resultSetup(stmt); err != nil {
return 0, err
}
return stmt.ColumnFloat(0), resultTeardown(stmt)
}
|