Fix JSON.

This commit is contained in:
Nuno Cruces
2023-11-09 16:16:48 +00:00
parent 828788912e
commit 591480cd39
3 changed files with 14 additions and 23 deletions

View File

@@ -30,7 +30,6 @@ import (
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"io"
@@ -386,12 +385,12 @@ func (s *stmt) setupBindings(args []driver.NamedValue) error {
err = s.Stmt.BindBlob(id, a)
case sqlite3.ZeroBlob:
err = s.Stmt.BindZeroBlob(id, int64(a))
case interface{ Value() any }:
err = s.Stmt.BindPointer(id, a.Value())
case time.Time:
err = s.Stmt.BindTime(id, a, sqlite3.TimeFormatDefault)
case json.Marshaler:
err = s.Stmt.BindJSON(id, a)
case interface{ Pointer() any }:
err = s.Stmt.BindPointer(id, a.Pointer())
case interface{ JSON() any }:
err = s.Stmt.BindJSON(id, a.JSON())
case nil:
err = s.Stmt.BindNull(id)
default:
@@ -408,8 +407,10 @@ func (s *stmt) setupBindings(args []driver.NamedValue) error {
func (s *stmt) CheckNamedValue(arg *driver.NamedValue) error {
switch arg.Value.(type) {
case bool, int, int64, float64, string, []byte,
sqlite3.ZeroBlob, interface{ Value() any },
time.Time, json.Marshaler, nil:
sqlite3.ZeroBlob, time.Time,
interface{ Pointer() any },
interface{ JSON() any },
nil:
return nil
default:
return driver.ErrSkip

20
json.go
View File

@@ -9,26 +9,16 @@ import (
"github.com/ncruces/go-sqlite3/internal/util"
)
// JSON returns:
// a [json.Marshaler] that can be used as an argument to
// [database/sql.DB.Exec] and similar methods to
// store value as JSON; and
// a [database/sql.Scanner] that can be used as an argument to
// [database/sql.Row.Scan] and similar methods to
// decode JSON into value.
// JSON returns a value that can be used as an argument to
// [database/sql.DB.Exec], [database/sql.Row.Scan] and similar methods to
// store value as JSON, or decode JSON into value.
func JSON(value any) any {
return jsonValue{value}
}
type jsonValue struct{ any }
func (j jsonValue) MarshalJSON() ([]byte, error) {
return json.Marshal(j.any)
}
func (j jsonValue) UnmarshalJSON(data []byte) error {
return json.Unmarshal(data, j.any)
}
func (j jsonValue) JSON() any { return j.any }
func (j jsonValue) Scan(value any) error {
var buf []byte
@@ -52,5 +42,5 @@ func (j jsonValue) Scan(value any) error {
panic(util.AssertErr())
}
return j.UnmarshalJSON(buf)
return json.Unmarshal(buf, j.any)
}

View File

@@ -11,4 +11,4 @@ func Pointer[T any](val T) any {
type pointer[T any] struct{ val T }
func (p pointer[T]) Value() any { return p.val }
func (p pointer[T]) Pointer() any { return p.val }