Skip to content

Commit

Permalink
[Driver] Fix prepared insert statements raising `not enough query arg…
Browse files Browse the repository at this point in the history
…uments` (#171)

* [Driver] Fix prepared insert statements raising `not enough query arguments`

* use different test table name
  • Loading branch information
ohaibbq authored Mar 9, 2024
1 parent 5f9498b commit 5416a73
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
63 changes: 63 additions & 0 deletions driver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,66 @@ CREATE TABLE IF NOT EXISTS Singers (
}
})
}

func TestPreparedStatements(t *testing.T) {
t.Run("prepared select", func(t *testing.T) {
db, err := sql.Open("zetasqlite", ":memory:")
if err != nil {
t.Fatal(err)
}
if _, err := db.Exec(`
CREATE TABLE IF NOT EXISTS Singers (
SingerId INT64 NOT NULL,
FirstName STRING(1024),
LastName STRING(1024),
SingerInfo BYTES(MAX)
)`); err != nil {
t.Fatal(err)
}
stmt, err := db.Prepare("SELECT * FROM Singers WHERE SingerId = ?")
if err != nil {
t.Fatal(err)
}
rows, err := stmt.Query("123")
if err != nil {
t.Fatal(err)
}
if rows.Next() {
t.Fatal("found unexpected row; expected no rows")
}
})
t.Run("prepared insert", func(t *testing.T) {
db, err := sql.Open("zetasqlite", ":memory:")
if err != nil {
t.Fatal(err)
}
if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS Items (ItemId INT64 NOT NULL)`); err != nil {
t.Fatal(err)
}
if _, err := db.Exec("INSERT `Items` (`ItemId`) VALUES (123)"); err != nil {
t.Fatal(err)
}

// Test that executing without args fails
_, err = db.Exec("INSERT `Items` (`ItemId`) VALUES (?)")
if err == nil {
t.Fatal("expected error when inserting without args; got no error")
}

stmt, err := db.Prepare("INSERT `Items` (`ItemId`) VALUES (?)")
if err != nil {
t.Fatal(err)
}
if _, err := stmt.Exec(456); err != nil {
t.Fatal(err)
}

rows, err := db.Query("SELECT * FROM Items WHERE ItemId = 456")
if err != nil {
t.Fatal(err)
}
if !rows.Next() {
t.Fatal("expected no rows; expected one row")
}
})
}
3 changes: 3 additions & 0 deletions internal/analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -696,6 +696,9 @@ func getParamsFromNode(node ast.Node) []*ast.ParameterNode {
}

func getArgsFromParams(values []driver.NamedValue, params []*ast.ParameterNode) ([]interface{}, error) {
if values == nil {
return nil, nil
}
argNum := len(params)
if len(values) < argNum {
return nil, fmt.Errorf("not enough query arguments")
Expand Down

0 comments on commit 5416a73

Please sign in to comment.