georgysavva / scany

Library for scanning data from a database into Go structs and more
MIT License
1.24k stars 67 forks source link

Can't catch `context.Cancelled` error #69

Closed suessflorian closed 2 years ago

suessflorian commented 2 years ago

I usually use fmt.Errorf and the wrap directive, which allows me to check if a context compliant method has exited due to a closed context via err == context.Cancelled. Seems like I can't do this with `scany'.

Reproducing minimal example:

package main

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

    "github.com/georgysavva/scany/sqlscan"

    _ "github.com/mattn/go-sqlite3" // sqlite driver
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    cancel()
    if _, err := os.Create("test.db"); err != nil {
        panic(err)
    }

    conn, err := sql.Open("sqlite3", "./data.db")
    if err != nil {
        panic(err)
    }
    defer conn.Close()

    if _, err := conn.Exec("CREATE TABLE bla(blu int)"); err != nil {
        panic(err)
    }

    bla := struct{ Blu int }{}
    if err := sqlscan.Get(ctx, conn, &bla, "INSERT INTO bla(blu) VALUES(1) RETURNING *", 1); err != nil && err != context.Canceled {
        panic(err)
    }
    fmt.Print("should reach here...")
}

accompanied go.mod:

module reproduce

go 1.16

require (
    github.com/georgysavva/scany v0.2.9
    github.com/mattn/go-sqlite3 v2.0.1+incompatible
)

Upon running this I get:

 Documents/cancelledContext % go run .
panic: scany: query one result row: context canceled

goroutine 1 [running]:
main.main()
    ~/Documents/cancelledContext/main.go:30 +0x385
exit status 2
georgysavva commented 2 years ago

Hello! Have you tried errors.Is() function? Check out this article for more details: https://go.dev/blog/go1.13-errors