From b8fdf1c61646a18683b78bd14d043adf1447c85f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20SZKIBA?= Date: Fri, 21 Feb 2025 14:16:04 +0000 Subject: [PATCH] fix: accept Symbol type driver id parameter in open() --- releases/v1.0.3.md | 7 +++++++ sql/module.go | 29 ++++++++++++++++++++++++++++- sql/module_internal_test.go | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 releases/v1.0.3.md create mode 100644 sql/module_internal_test.go diff --git a/releases/v1.0.3.md b/releases/v1.0.3.md new file mode 100644 index 0000000..e8fd0e7 --- /dev/null +++ b/releases/v1.0.3.md @@ -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) diff --git a/sql/module.go b/sql/module.go index c618409..955069e 100644 --- a/sql/module.go +++ b/sql/module.go @@ -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) } diff --git a/sql/module_internal_test.go b/sql/module_internal_test.go new file mode 100644 index 0000000..d519d29 --- /dev/null +++ b/sql/module_internal_test.go @@ -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) +}