Skip to content

Commit

Permalink
Merge pull request #465 from upper/hotfix/allow-varchar-primary-key
Browse files Browse the repository at this point in the history
postgresql: add test for varchar/string primary keys
  • Loading branch information
xiam authored Sep 25, 2018
2 parents 199d13d + 9bd268d commit d2cc681
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
11 changes: 10 additions & 1 deletion internal/sqladapter/collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ func (c *collection) InsertReturning(item interface{}) error {
col := tx.(Database).Collection(c.Name())

// Insert item as is and grab the returning ID.
var newItemRes db.Result
id, err := col.Insert(item)
if err != nil {
goto cancel
Expand All @@ -168,8 +169,16 @@ func (c *collection) InsertReturning(item interface{}) error {
goto cancel
}

if len(pks) > 1 {
newItemRes = col.Find(id)
} else {
// We have one primary key, build a explicit db.Cond with it to prevent
// string keys to be considered as raw conditions.
newItemRes = col.Find(db.Cond{pks[0]: id}) // We already checked that pks is not empty, so pks[0] is defined.
}

// Fetch the row that was just interted into newItem
err = col.Find(id).One(newItem)
err = newItemRes.One(newItem)
if err != nil {
goto cancel
}
Expand Down
41 changes: 41 additions & 0 deletions postgresql/adapter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,13 @@ func tearUp() error {
id INTEGER[3] PRIMARY KEY,
name VARCHAR(25)
)`,

`DROP TABLE IF EXISTS varchar_primary_key`,

`CREATE TABLE varchar_primary_key (
address VARCHAR(42) PRIMARY KEY NOT NULL,
name VARCHAR(25)
)`,
}

for _, s := range batch {
Expand Down Expand Up @@ -1015,6 +1022,40 @@ func TestUUIDInsert_Issue370(t *testing.T) {
}
}

func TestInsertVarcharPrimaryKey(t *testing.T) {
sess := mustOpen()
defer sess.Close()

{
type itemT struct {
Address string `db:"address"`
Name string `db:"name"`
}

item1 := itemT{
Address: "1234",
Name: "Jonny",
}

col := sess.Collection("varchar_primary_key")
err := col.Truncate()
assert.NoError(t, err)

err = col.InsertReturning(&item1)
assert.NoError(t, err)

var item2 itemT
err = col.Find(db.Cond{"address": item1.Address}).One(&item2)
assert.NoError(t, err)
assert.Equal(t, item1.Name, item2.Name)

var item3 itemT
err = col.Find(db.Cond{"address": item1.Address}).One(&item3)
assert.NoError(t, err)
assert.Equal(t, item1.Name, item3.Name)
}
}

func TestTxOptions_Issue409(t *testing.T) {
sess := mustOpen()
defer sess.Close()
Expand Down

0 comments on commit d2cc681

Please sign in to comment.