Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use TEXT columns to serialize JSON structs & arrays. #2

Merged
merged 4 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions arrays.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
)

// Deprecated: use JSONArray instead
type Array[T any] []T

func (arr *Array[T]) Scan(value interface{}) error {
Expand Down
88 changes: 88 additions & 0 deletions json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package sqltypes

import (
"database/sql/driver"
"encoding/json"
"fmt"
)

type JSON[T any] struct {
V *T
}

func NewJSON[T any](val *T) JSON[T] {
return JSON[T]{V: val}
}

func (s *JSON[T]) Scan(value interface{}) error {
if value == nil {
return nil
}

var val T
switch value.(type) {
case []byte:
if err := json.Unmarshal(value.([]byte), &val); err != nil {
return fmt.Errorf("sqltypes: cannot unmarshal struct: %w", err)
}
case string:
if err := json.Unmarshal([]byte(value.(string)), &val); err != nil {
return fmt.Errorf("sqltypes: cannot unmarshal struct: %w", err)
}
default:
return fmt.Errorf("sqltypes: unknown array type %T", value)
}
*s = NewJSON(&val)

return nil
}

func (s JSON[T]) Value() (driver.Value, error) {
if s.V == nil {
return nil, nil
}
value, err := json.Marshal(s.V)
if err != nil {
return nil, err
}
return string(value), nil
}

type JSONArray[T any] struct {
V T
}

func NewJSONArray[T any](val *T) JSONArray[T] {
return JSONArray[T]{V: *val}
}

func (s *JSONArray[T]) Scan(value interface{}) error {
if value == nil {
return nil
}

var val T
switch value.(type) {
case []byte:
if err := json.Unmarshal(value.([]byte), &val); err != nil {
return fmt.Errorf("sqltypes: cannot unmarshal struct: %w", err)
}
case string:
if err := json.Unmarshal([]byte(value.(string)), &val); err != nil {
return fmt.Errorf("sqltypes: cannot unmarshal struct: %w", err)
}
default:
return fmt.Errorf("sqltypes: unknown array type %T", value)
}
*s = NewJSONArray(&val)

return nil
}

func (s JSONArray[T]) Value() (driver.Value, error) {
value, err := json.Marshal(s.V)
if err != nil {
return nil, err
}
return string(value), nil
}
99 changes: 99 additions & 0 deletions json_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package sqltypes

import (
"database/sql"
"testing"

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

type testJSON struct {
Foo string
}

func TestJSONValue(t *testing.T) {
db := connectDB(t)
defer db.Close()

var st JSON[testJSON]
st.V = &testJSON{Foo: "bar"}
_, err := db.Exec("INSERT INTO test_types (name, value_str) VALUES (?, ?)", "foo", st)
require.NoError(t, err)

var val string
require.NoError(t, db.QueryRow("SELECT value_str FROM test_types WHERE name = ?", "foo").Scan(&val))

require.Equal(t, `{"Foo":"bar"}`, val)
}

func TestJSONValueNil(t *testing.T) {
db := connectDB(t)
defer db.Close()

var st JSON[testJSON]
_, err := db.Exec("INSERT INTO test_types (name, value_str) VALUES (?, ?)", "foo", st)
require.NoError(t, err)

var val sql.NullString
require.NoError(t, db.QueryRow("SELECT value_str FROM test_types WHERE name = ?", "foo").Scan(&val))

require.False(t, val.Valid)
}

func TestJSONScan(t *testing.T) {
db := connectDB(t)
defer db.Close()

_, err := db.Exec("INSERT INTO test_types (name, value_str) VALUES (?, ?)", "foo", `{"Foo":"bar"}`)
require.NoError(t, err)

var st JSON[testJSON]
require.NoError(t, db.QueryRow("SELECT value_str FROM test_types WHERE name = ?", "foo").Scan(&st))

require.NotNil(t, st.V)
require.Equal(t, st.V.Foo, "bar")
}

func TestJSONScanNil(t *testing.T) {
db := connectDB(t)
defer db.Close()

_, err := db.Exec("INSERT INTO test_types (name, value_str) VALUES (?, ?)", "foo", nil)
require.NoError(t, err)

var st JSON[testJSON]
require.NoError(t, db.QueryRow("SELECT value_str FROM test_types WHERE name = ?", "foo").Scan(&st))

require.Nil(t, st.V)
}

func TestJSONSaveLoad(t *testing.T) {
db := connectDB(t)
defer db.Close()

var st JSON[testJSON]
st.V = &testJSON{Foo: "bar"}
_, err := db.Exec("INSERT INTO test_types (name, value_str) VALUES (?, ?)", "foo", st)
require.NoError(t, err)

var other JSON[testJSON]
require.NoError(t, db.QueryRow("SELECT value_str FROM test_types WHERE name = ?", "foo").Scan(&other))

require.NotNil(t, st.V)
require.Equal(t, st.V.Foo, "bar")
}

func TestJSONArray(t *testing.T) {
db := connectDB(t)
defer db.Close()

st := JSONArray[[]string]{V: []string{"foo", "bar"}}
_, err := db.Exec("INSERT INTO test_types (name, value_str) VALUES (?, ?)", "foo", st)
require.NoError(t, err)

var other JSON[[]string]
require.NoError(t, db.QueryRow("SELECT value_str FROM test_types WHERE name = ?", "foo").Scan(&other))

require.NotNil(t, st.V)
require.Len(t, st.V, 2)
}
1 change: 1 addition & 0 deletions struct.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
)

// Deprecated: use JSON instead
type Struct[T any] struct {
V *T
}
Expand Down