Skip to content

Commit

Permalink
fix: accept Symbol type driver id parameter in open()
Browse files Browse the repository at this point in the history
  • Loading branch information
szkiba committed Feb 21, 2025
1 parent ac3d014 commit b8fdf1c
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 1 deletion.
7 changes: 7 additions & 0 deletions releases/v1.0.3.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
xk6-sql `v1.0.3` is here 🎉!

This release includes:

Bugfixes:

- [Symbol type driver parameter support](https://github.com/grafana/xk6-sql/issues/120): The `open()` function now accepts `Symbol` (class) type driver ids in addition to the primitive symbol type. This is because when a driver is imported with the `require()` function, it is not a primitive symbol that is imported, but a `Symbol` class type. Also fixes [#115](https://github.com/grafana/xk6-sql/issues/115)
29 changes: 28 additions & 1 deletion sql/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,37 @@ func (mod *module) Exports() modules.Exports {
// KeyValue is a simple key-value pair.
type KeyValue map[string]interface{}

func asSymbol(value sobek.Value) (*sobek.Symbol, bool) {
sym, ok := value.(*sobek.Symbol)
if ok {
return sym, ok
}

obj, ok := value.(*sobek.Object)
if !ok {
return nil, false
}

valueOf, ok := sobek.AssertFunction(obj.Get("valueOf"))
if !ok {
return nil, false
}

ret, err := valueOf(obj)
if err != nil {
return nil, false
}

sym, ok = ret.(*sobek.Symbol)

return sym, ok
}

// open establishes a connection to the specified database type using
// the provided connection string.
func (mod *module) Open(driverID sobek.Value, connectionString string) (*Database, error) {
driverSym, ok := driverID.(*sobek.Symbol)
driverSym, ok := asSymbol(driverID)

if !ok {
return nil, fmt.Errorf("%w: invalid driver parameter type", errUnsupportedDatabase)
}
Expand Down
33 changes: 33 additions & 0 deletions sql/module_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package sql

import (
"testing"

"github.com/grafana/sobek"
"github.com/stretchr/testify/require"
)

func Test_asSymbol(t *testing.T) {
t.Parallel()

symbol := sobek.NewSymbol("foo")

sym, ok := asSymbol(symbol)

require.True(t, ok)
require.Same(t, symbol, sym)

rt := sobek.New()

obj := symbol.ToObject(rt)

sym, ok = asSymbol(obj)

require.True(t, ok)
require.Same(t, symbol, sym)

sym, ok = asSymbol(sobek.Undefined())

require.False(t, ok)
require.Nil(t, sym)
}

0 comments on commit b8fdf1c

Please sign in to comment.