Skip to content

Commit

Permalink
Support []byte arguments to D1 Query/Exec
Browse files Browse the repository at this point in the history
  • Loading branch information
ben-krieger committed Oct 30, 2024
1 parent ad33cfb commit 27c56b8
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
11 changes: 8 additions & 3 deletions cloudflare/d1/rows.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,14 @@ func convertRowColumnValueToAny(v js.Value) (driver.Value, error) {
case js.TypeString:
return v.String(), nil
case js.TypeObject:
// TODO: handle BLOB type (ArrayBuffer).
// see: https://developers.cloudflare.com/d1/platform/client-api/#type-conversion
return nil, errors.New("d1: row column value type object is not currently supported")
// handle BLOB type (ArrayBuffer).
src := js.Global().Get("Uint8Array").New(v)
dst := make([]byte, src.Length())
n := js.CopyBytesToGo(dst, src)
if n == 0 {
return nil, errors.New("d1: row column value type object is not currently supported")
}
return dst[:n], nil
}
return nil, errors.New("d1: unexpected row column value type")
}
Expand Down
18 changes: 15 additions & 3 deletions cloudflare/d1/stmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,17 @@ func (s *stmt) Exec([]driver.Value) (driver.Result, error) {
}

// ExecContext executes prepared statement.
// Given []drier.NamedValue's `Name` field will be ignored because Cloudflare D1 client doesn't support it.
// Given []driver.NamedValue's `Name` field will be ignored because Cloudflare D1 client doesn't support it.
func (s *stmt) ExecContext(_ context.Context, args []driver.NamedValue) (driver.Result, error) {
argValues := make([]any, len(args))
for i, arg := range args {
argValues[i] = arg.Value
if src, ok := arg.Value.([]byte); ok {
dst := js.Global().Get("Uint8Array").New(len(src))
js.CopyBytesToJS(dst, src)
argValues[i] = dst
} else {
argValues[i] = arg.Value
}
}
resultPromise := s.stmtObj.Call("bind", argValues...).Call("run")
resultObj, err := jsutil.AwaitPromise(resultPromise)
Expand All @@ -57,7 +63,13 @@ func (s *stmt) Query([]driver.Value) (driver.Rows, error) {
func (s *stmt) QueryContext(_ context.Context, args []driver.NamedValue) (driver.Rows, error) {
argValues := make([]any, len(args))
for i, arg := range args {
argValues[i] = arg.Value
if src, ok := arg.Value.([]byte); ok {
dst := js.Global().Get("Uint8Array").New(len(src))
js.CopyBytesToJS(dst, src)
argValues[i] = dst
} else {
argValues[i] = arg.Value
}
}
resultPromise := s.stmtObj.Call("bind", argValues...).Call("raw", map[string]any{"columnNames": true})
rowsArray, err := jsutil.AwaitPromise(resultPromise)
Expand Down

0 comments on commit 27c56b8

Please sign in to comment.