Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Scanning sql.NullInt64 value fails when row is created via FromCSVString #140

Closed
craigfitzpatrick opened this issue Sep 13, 2018 · 1 comment

Comments

@craigfitzpatrick
Copy link

craigfitzpatrick commented Sep 13, 2018

When you create a row with a null value using the sqlmock.FromCSVString function, sql.Rows.Scan fails with a conversion error while scanning that value. The following test:

func TestNullScanFromCSV(t *testing.T) {

	const query string = "select nullable from TableWithNulls"

	db, mock, err := New()
	if err != nil {
		t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
	}
	defer db.Close()

	rs := NewRows([]string{"nullable"}).AddRow(1).AddRow(nil).FromCSVString("null")

	mock.ExpectQuery(query).WillReturnRows(rs)

	var expectedResults = []sql.NullInt64{
		{Valid: true, Int64: 1},
		{Valid: false, Int64: 0},
		{Valid: false, Int64: 0},
	}

	rows, err := db.Query(query)
	if err != nil {
		t.Fatalf("an error '%s' was not expected when querying a stub database connection", err)
	}
	defer rows.Close()

	var actualResults []sql.NullInt64
	for rows.Next() {
		var ni sql.NullInt64
		if err = rows.Scan(&ni); err != nil {
			t.Fatalf("an error '%s' was not expected while scanning row from mocked recordset", err)
		}
		actualResults = append(actualResults, ni)
	}

	if len(expectedResults) != len(actualResults) {
		t.Fatalf("unexpected row count: wanted %d, got %d", len(expectedResults), len(actualResults))
	}

	for i, v := range actualResults {
		if v != expectedResults[i] {
			t.Fatalf("unexpected value in row %d: wanted %v, got %v", i, expectedResults[i], v)
		}
	}

	if err = mock.ExpectationsWereMet(); err != nil {
		t.Fatal(err)
	}
}

Demonstrates the failure:

$ go test go-sqlmock -run ^TestNullScanFromCSV$
--- FAIL: TestNullScanFromCSV (0.00s)
	rows_test.go:349: an error 'sql: Scan error on column index 0: converting driver.Value type []uint8 ("") to a int64: invalid syntax' was not expected while scanning row from mocked recordset
FAIL
FAIL	go-sqlmock	0.002s

I believe that the fix is a simple as changing the return type of sqlmock.CSVColumnParser and have submitted pull request #141 with that change.

@craigfitzpatrick
Copy link
Author

As per l3pp4rd's suggestion, I have reopened my pull request against the v2 branch (see pull request #142), because the change I suggested is backwards incompatible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants