Skip to content

Commit

Permalink
fix: Using rowScan before defer cancel() (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
ViBiOh authored Apr 29, 2020
1 parent 5677290 commit 4fcd836
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
6 changes: 3 additions & 3 deletions pkg/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,16 +127,16 @@ func RowsClose(rows *sql.Rows, err error) error {
}

// GetRow execute single row query
func GetRow(ctx context.Context, db *sql.DB, query string, args ...interface{}) *sql.Row {
func GetRow(ctx context.Context, db *sql.DB, scanner func(RowScanner) error, query string, args ...interface{}) error {
tx := ReadTx(ctx)

ctx, cancel := context.WithTimeout(ctx, SQLTimeout)
defer cancel()

if tx != nil {
return tx.QueryRowContext(ctx, query, args...)
return scanner(tx.QueryRowContext(ctx, query, args...))
}
return db.QueryRowContext(ctx, query, args...)
return scanner(db.QueryRowContext(ctx, query, args...))
}

// Create execute query with a RETURNING id
Expand Down
5 changes: 4 additions & 1 deletion pkg/db/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,10 @@ func TestGetRow(t *testing.T) {
}

var got uint64
gotErr := GetRow(ctx, mockDb, "SELECT id FROM item WHERE id = $1", 1).Scan(&got)
testScanItem := func(row RowScanner) error {
return row.Scan(&got)
}
gotErr := GetRow(ctx, mockDb, testScanItem, "SELECT id FROM item WHERE id = $1", 1)

failed := false

Expand Down

0 comments on commit 4fcd836

Please sign in to comment.