fix Connector implementation

This commit is contained in:
syumai 2023-02-26 12:07:38 +09:00
parent 14b5f8fda4
commit bd02c8bd45
3 changed files with 25 additions and 22 deletions

View File

@ -4,12 +4,11 @@ import (
"context"
"database/sql/driver"
"errors"
"github.com/syumai/workers/cloudflare/internal/cfruntimecontext"
"syscall/js"
)
type Conn struct {
dbName string
dbObj js.Value
}
var (
@ -19,20 +18,16 @@ var (
)
func (c *Conn) Prepare(query string) (driver.Stmt, error) {
return nil, errors.New("d1: Prepare is not implemented. please use PrepareContext instead")
}
func (c *Conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
dbObj := cfruntimecontext.GetRuntimeContextEnv(ctx).Get(c.dbName)
if dbObj.IsUndefined() {
return nil, ErrDatabaseNotFound
}
stmtObj := dbObj.Call("prepare", query)
stmtObj := c.dbObj.Call("prepare", query)
return &stmt{
stmtObj: stmtObj,
}, nil
}
func (c *Conn) PrepareContext(_ context.Context, query string) (driver.Stmt, error) {
return c.Prepare(query)
}
func (c *Conn) Close() error {
// do nothing
return nil

View File

@ -3,20 +3,33 @@ package d1
import (
"context"
"database/sql/driver"
"syscall/js"
"github.com/syumai/workers/cloudflare/internal/cfruntimecontext"
)
type Connector struct {
name string
dbObj js.Value
}
var (
_ driver.Connector = (*Connector)(nil)
)
// Connect returns Conn object of D1.
// OpenConnector returns Connector of D1.
// This method checks DB existence. If DB was not found, this function returns error.
func OpenConnector(ctx context.Context, name string) (driver.Connector, error) {
v := cfruntimecontext.GetRuntimeContextEnv(ctx).Get(name)
if v.IsUndefined() {
return nil, ErrDatabaseNotFound
}
return &Connector{dbObj: v}, nil
}
// Connect returns Conn of D1.
// This method doesn't check DB existence, so this function never return errors.
func (c *Connector) Connect(context.Context) (driver.Conn, error) {
return &Conn{dbName: c.name}, nil
return &Conn{dbObj: c.dbObj}, nil
}
func (c *Connector) Driver() driver.Driver {

View File

@ -13,14 +13,9 @@ func init() {
type Driver struct{}
var (
_ driver.Driver = (*Driver)(nil)
_ driver.DriverContext = (*Driver)(nil)
_ driver.Driver = (*Driver)(nil)
)
func (d *Driver) Open(string) (driver.Conn, error) {
return nil, errors.New("d1: Open is not supported. use OpenConnector and Connector's Connect method instead")
}
func (d *Driver) OpenConnector(name string) (driver.Connector, error) {
return &Connector{name: name}, nil
return nil, errors.New("d1: Open is not supported. use d1.OpenConnector and sql.OpenDB instead")
}