Handle nullable values and Rows.Err
Handle nullable values and Rows.Err
SQL NULL represents missing or unknown data, not an empty string. sql.NullString stores String and Valid; inspect Valid before using the value. QueryContext returns Rows, which must be closed. Next returns false for both end of stream and iteration failure, so check Rows.Err after the loop.
package main
import ( "context" "database/sql" "database/sql/driver" "errors" "fmt" "io")
// fixtureDriver is a teaching double, not a SQL engine.type fixtureDriver struct{}type fixtureConn struct{ mode string }type fixtureTx struct{}type fixtureRows struct { values [][]driver.Value fail bool index int}
func (fixtureDriver) Open(name string) (driver.Conn, error) { if name == "offline" { return nil, errors.New("fixture offline") } return &fixtureConn{mode: name}, nil}func (c *fixtureConn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("prepare not implemented in fixture")}func (c *fixtureConn) Close() error { return nil }func (c *fixtureConn) Begin() (driver.Tx, error) { return &fixtureTx{}, nil }func (c *fixtureConn) Ping(ctx context.Context) error { return ctx.Err() }func (t *fixtureTx) Commit() error { return nil }func (t *fixtureTx) Rollback() error { return nil }func (c *fixtureConn) QueryContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Rows, error) { if err := ctx.Err(); err != nil { return nil, err } switch q { case "SELECT name FROM books WHERE id = ?": if len(args) != 1 { return nil, errors.New("one argument required") } if args[0].Value == int64(7) { return &fixtureRows{values: [][]driver.Value{{"Go"}}}, nil } return &fixtureRows{}, nil case "SELECT name FROM books": return &fixtureRows{values: [][]driver.Value{{"Go"}, {nil}}, fail: c.mode == "broken"}, nil default: return nil, errors.New("unsupported fixture query") }}func (c *fixtureConn) ExecContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Result, error) { if err := ctx.Err(); err != nil { return nil, err } if q != "UPDATE books SET name = ? WHERE id = ?" || len(args) != 2 { return nil, errors.New("unsupported fixture update") } if args[1].Value == int64(7) { return driver.RowsAffected(1), nil } return driver.RowsAffected(0), nil}func (r *fixtureRows) Columns() []string { return []string{"name"} }func (r *fixtureRows) Close() error { return nil }func (r *fixtureRows) Next(dest []driver.Value) error { if r.index == len(r.values) { if r.fail { return errors.New("fixture stream interrupted") } return io.EOF } copy(dest, r.values[r.index]) r.index++ return nil}func must(err error) { if err != nil { panic(err) }}func openFixture(mode string) *sql.DB { db, err := sql.Open("bytemind-fixture", mode) must(err) return db}func init() { sql.Register("bytemind-fixture", fixtureDriver{}) }
func main() { db := openFixture("ready") defer db.Close() rows, err := db.QueryContext(context.Background(), "SELECT name FROM books") must(err) defer rows.Close() for rows.Next() { var name sql.NullString must(rows.Scan(&name)) if name.Valid { fmt.Println(name.String) } else { fmt.Println("missing") } } must(rows.Err())}Each successful Next permits a Scan. The deferred close releases resources even if an early return occurs. For a real function return any Scan or iteration error rather than emitting incomplete success. A nullable wrapper preserves the distinction between empty and absent.
Expected output:
GomissingDetect a partial stream failure
package main
import ( "context" "database/sql" "database/sql/driver" "errors" "fmt" "io")
// fixtureDriver is a teaching double, not a SQL engine.type fixtureDriver struct{}type fixtureConn struct{ mode string }type fixtureTx struct{}type fixtureRows struct { values [][]driver.Value fail bool index int}
func (fixtureDriver) Open(name string) (driver.Conn, error) { if name == "offline" { return nil, errors.New("fixture offline") } return &fixtureConn{mode: name}, nil}func (c *fixtureConn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("prepare not implemented in fixture")}func (c *fixtureConn) Close() error { return nil }func (c *fixtureConn) Begin() (driver.Tx, error) { return &fixtureTx{}, nil }func (c *fixtureConn) Ping(ctx context.Context) error { return ctx.Err() }func (t *fixtureTx) Commit() error { return nil }func (t *fixtureTx) Rollback() error { return nil }func (c *fixtureConn) QueryContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Rows, error) { if err := ctx.Err(); err != nil { return nil, err } switch q { case "SELECT name FROM books WHERE id = ?": if len(args) != 1 { return nil, errors.New("one argument required") } if args[0].Value == int64(7) { return &fixtureRows{values: [][]driver.Value{{"Go"}}}, nil } return &fixtureRows{}, nil case "SELECT name FROM books": return &fixtureRows{values: [][]driver.Value{{"Go"}, {nil}}, fail: c.mode == "broken"}, nil default: return nil, errors.New("unsupported fixture query") }}func (c *fixtureConn) ExecContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Result, error) { if err := ctx.Err(); err != nil { return nil, err } if q != "UPDATE books SET name = ? WHERE id = ?" || len(args) != 2 { return nil, errors.New("unsupported fixture update") } if args[1].Value == int64(7) { return driver.RowsAffected(1), nil } return driver.RowsAffected(0), nil}func (r *fixtureRows) Columns() []string { return []string{"name"} }func (r *fixtureRows) Close() error { return nil }func (r *fixtureRows) Next(dest []driver.Value) error { if r.index == len(r.values) { if r.fail { return errors.New("fixture stream interrupted") } return io.EOF } copy(dest, r.values[r.index]) r.index++ return nil}func must(err error) { if err != nil { panic(err) }}func openFixture(mode string) *sql.DB { db, err := sql.Open("bytemind-fixture", mode) must(err) return db}func init() { sql.Register("bytemind-fixture", fixtureDriver{}) }
func main() { db := openFixture("broken") defer db.Close() rows, err := db.QueryContext(context.Background(), "SELECT name FROM books") must(err) defer rows.Close() n := 0 for rows.Next() { var v sql.NullString must(rows.Scan(&v)) n++ } fmt.Println(n, rows.Err() != nil)}Two rows arrived before a synthetic error. Next alone would make this look like a successful complete result. Check Rows.Err even when rows were received. Do not retry halfway through a streamed response unless the protocol defines safe resume semantics.
Expected output:
2 trueTry it locally
Use NullString.Scan to compare nil with an empty string. Print Valid for each.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Database 05: Handle nullable values and Rows.Err
Check the lesson objective before moving on.
What distinguishes NULL from empty text?
After Next returns false, what checks stream failure?