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

Support for partial updates #396

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions db.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,9 @@ type Unmarshaler interface {
UnmarshalDB(interface{}) error
}

// Changeset represents the differences between two states of the same struct.
type Changeset map[string]interface{}

// Cond is a map that defines conditions for a query and satisfies the
// Constraints and Compound interfaces.
//
Expand Down
21 changes: 21 additions & 0 deletions internal/sqladapter/collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"upper.io/db.v3"
"upper.io/db.v3/internal/sqladapter/exql"
"upper.io/db.v3/lib/reflectx"
"upper.io/db.v3/lib/sqlbuilder"
)

var mapper = reflectx.NewMapper("db")
Expand Down Expand Up @@ -158,6 +159,10 @@ func (c *collection) InsertReturning(item interface{}) error {

col := tx.(Database).Collection(c.Name())

if mapper, ok := item.(sqlbuilder.Mapper); ok {
_ = mapper.Store(nil)
}

// Insert item as is and grab the returning ID.
id, err := col.Insert(item)
if err != nil {
Expand Down Expand Up @@ -195,6 +200,10 @@ func (c *collection) InsertReturning(item interface{}) error {
goto cancel
}

if mapper, ok := item.(sqlbuilder.Mapper); ok {
_ = mapper.Store(item)
}

if !inTx {
// This is only executed if t.Database() was **not** a transaction and if
// sess was created with sess.NewTransaction().
Expand All @@ -220,6 +229,14 @@ func (c *collection) UpdateReturning(item interface{}) error {
return fmt.Errorf("Expecting a pointer but got %T", item)
}

if mapper, ok := item.(sqlbuilder.Mapper); ok {
values, err := mapper.Changeset()
if err == nil && len(values) == 0 {
// No operation.
return nil
}
}

// Grab primary keys
pks := c.PrimaryKeys()
if len(pks) == 0 {
Expand Down Expand Up @@ -287,6 +304,10 @@ func (c *collection) UpdateReturning(item interface{}) error {
panic("default")
}

if mapper, ok := item.(sqlbuilder.Mapper); ok {
mapper.Store(item)
}

if !inTx {
// This is only executed if t.Database() was **not** a transaction and if
// sess was created with sess.NewTransaction().
Expand Down
70 changes: 70 additions & 0 deletions internal/sqladapter/testing/adapter.go.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -1960,3 +1960,73 @@ func TestCustomType(t *testing.T) {

assert.Equal(t, "foo: some name", string(bar.Custom.Val))
}

func TestDirtyEntity(t *testing.T) {
type entityTest struct {
artistType `db:",inline"`

sqlbuilder.Entity
}

sess := mustOpen()
defer sess.Close()

artist := sess.Collection("artist")

err := artist.Truncate()
assert.NoError(t, err)

var newArtist entityTest
newArtist.Name = "Celia"

for i := 0; i < 5; i++ {
err = artist.InsertReturning(&newArtist)
if i == 0 {
assert.NoError(t, err)
assert.NotZero(t, newArtist.ID)
} else {
assert.Error(t, err)
}
}

var newArtist2 entityTest
newArtist2.Name = "María"
err = artist.InsertReturning(&newArtist2)
assert.NoError(t, err)
assert.NotZero(t, newArtist2.ID)

for i := 0; i < 5; i++ {
newArtist2.Name = "Another name"
err = artist.UpdateReturning(&newArtist2)
assert.NoError(t, err)
}

var newArtist3 entityTest
artist.Find().One(&newArtist3)

err = artist.UpdateReturning(&newArtist3)
assert.NoError(t, err)

newArtist3.Name = "Waka"
err = artist.UpdateReturning(&newArtist3)
assert.NoError(t, err)

for i := 0; i < 5; i++ {
newArtist3.Name = fmt.Sprintf("Artist %d", i)
err = artist.UpdateReturning(&newArtist3)
assert.NoError(t, err)
}

newArtist4 := entityTest{}
newArtist4.Name = "Alex"
for i := 0; i < 5; i++ {
id, err := artist.Insert(&newArtist4)
assert.NoError(t, err)

err = artist.Find(id).Update(&newArtist4)
assert.NoError(t, err)

err = artist.Find(id).Update(&newArtist4)
assert.NoError(t, err)
}
}
34 changes: 32 additions & 2 deletions lib/sqlbuilder/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import (
"database/sql"
"errors"
"fmt"
"log"
"reflect"
"regexp"
"sort"
Expand Down Expand Up @@ -243,6 +242,33 @@ func (b *sqlBuilder) Update(table string) Updater {

// Map receives a pointer to map or struct and maps it to columns and values.
func Map(item interface{}, options *MapOptions) ([]string, []interface{}, error) {

if mapper, ok := item.(Mapper); ok {
changeset, err := mapper.changesetWithOptions(options)
if err != nil {
if err == ErrMapperNotInitialized {
return doMap(item, options)
}
return nil, nil, err
}

var fv fieldValue
fv.values = make([]interface{}, 0, len(changeset))
fv.fields = make([]string, 0, len(changeset))

for field := range changeset {
fv.fields = append(fv.fields, field)
fv.values = append(fv.values, changeset[field])
}

sort.Sort(&fv)
return fv.fields, fv.values, nil
}

return doMap(item, options)
}

func doMap(item interface{}, options *MapOptions) ([]string, []interface{}, error) {
var fv fieldValue
if options == nil {
options = &defaultMapOptions
Expand Down Expand Up @@ -515,6 +541,11 @@ func (iter *iterator) next(dst ...interface{}) error {
defer iter.Close()
return err
}
if mapper, ok := dst[0].(Mapper); ok {
if err := mapper.Store(dst[0]); err != nil {
return err
}
}
return nil
}

Expand Down Expand Up @@ -562,7 +593,6 @@ func newSqlgenProxy(db *sql.DB, t *exql.Template) *exprProxy {
}

func (p *exprProxy) Context() context.Context {
log.Printf("Missing context")
return context.Background()
}

Expand Down
87 changes: 87 additions & 0 deletions lib/sqlbuilder/entity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package sqlbuilder

import (
"errors"
"sync"

"upper.io/db.v3"
)

var ErrMapperNotInitialized = errors.New("Mapper not initialized")

// Mapper defines methods for structs that can keep track of their values at
// some point. Store is used to record the state of a struct and Changeset is
// used to return the differences between that state and the current state.
type Mapper interface {
Store(interface{}) error
Changeset() (db.Changeset, error)

changesetWithOptions(options *MapOptions) (db.Changeset, error)
}

// Entity can be embedded by structs in order for them to keep track of changes
// automatically.
//
// Example:
//
// type Foo struct {
// ...
// sqlbuilder.Entity
// }
type Entity struct {
initialValues db.Changeset
ref interface{}
mu sync.RWMutex
}

var _ = Mapper(&Entity{})

func (e *Entity) changesetWithOptions(options *MapOptions) (db.Changeset, error) {
e.mu.RLock()
defer e.mu.RUnlock()

if e.ref == nil {
return nil, ErrMapperNotInitialized
}

cols, vals, err := doMap(e.ref, options)
if err != nil {
return nil, err
}

var changeset db.Changeset
for i := range vals {
if vals[i] == e.initialValues[cols[i]] {
continue
}
if changeset == nil {
changeset = make(db.Changeset)
}
changeset[cols[i]] = vals[i]
}
return changeset, nil
}

// Changeset returns the differences between the current state and the last
// recorded state.
func (e *Entity) Changeset() (db.Changeset, error) {
return e.changesetWithOptions(nil)
}

// Store records the current state of the struct.
func (e *Entity) Store(v interface{}) error {
cols, vals, err := doMap(v, nil)
if err != nil {
return err
}

e.mu.Lock()
e.initialValues = make(db.Changeset)
for i := range cols {
e.initialValues[cols[i]] = vals[i]
}
e.ref = v
e.mu.Unlock()

return nil
}
Loading