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

[Driver] Fix prepared insert statements raising not enough query arguments #21

Merged
merged 2 commits into from
Feb 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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