Skip to content

Commit d2cc681

Browse files
authored
Merge pull request #465 from upper/hotfix/allow-varchar-primary-key
postgresql: add test for varchar/string primary keys
2 parents 199d13d + 9bd268d commit d2cc681

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

internal/sqladapter/collection.go

+10-1
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,7 @@ func (c *collection) InsertReturning(item interface{}) error {
159159
col := tx.(Database).Collection(c.Name())
160160

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

172+
if len(pks) > 1 {
173+
newItemRes = col.Find(id)
174+
} else {
175+
// We have one primary key, build a explicit db.Cond with it to prevent
176+
// string keys to be considered as raw conditions.
177+
newItemRes = col.Find(db.Cond{pks[0]: id}) // We already checked that pks is not empty, so pks[0] is defined.
178+
}
179+
171180
// Fetch the row that was just interted into newItem
172-
err = col.Find(id).One(newItem)
181+
err = newItemRes.One(newItem)
173182
if err != nil {
174183
goto cancel
175184
}

postgresql/adapter_test.go

+41
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,13 @@ func tearUp() error {
213213
id INTEGER[3] PRIMARY KEY,
214214
name VARCHAR(25)
215215
)`,
216+
217+
`DROP TABLE IF EXISTS varchar_primary_key`,
218+
219+
`CREATE TABLE varchar_primary_key (
220+
address VARCHAR(42) PRIMARY KEY NOT NULL,
221+
name VARCHAR(25)
222+
)`,
216223
}
217224

218225
for _, s := range batch {
@@ -1015,6 +1022,40 @@ func TestUUIDInsert_Issue370(t *testing.T) {
10151022
}
10161023
}
10171024

1025+
func TestInsertVarcharPrimaryKey(t *testing.T) {
1026+
sess := mustOpen()
1027+
defer sess.Close()
1028+
1029+
{
1030+
type itemT struct {
1031+
Address string `db:"address"`
1032+
Name string `db:"name"`
1033+
}
1034+
1035+
item1 := itemT{
1036+
Address: "1234",
1037+
Name: "Jonny",
1038+
}
1039+
1040+
col := sess.Collection("varchar_primary_key")
1041+
err := col.Truncate()
1042+
assert.NoError(t, err)
1043+
1044+
err = col.InsertReturning(&item1)
1045+
assert.NoError(t, err)
1046+
1047+
var item2 itemT
1048+
err = col.Find(db.Cond{"address": item1.Address}).One(&item2)
1049+
assert.NoError(t, err)
1050+
assert.Equal(t, item1.Name, item2.Name)
1051+
1052+
var item3 itemT
1053+
err = col.Find(db.Cond{"address": item1.Address}).One(&item3)
1054+
assert.NoError(t, err)
1055+
assert.Equal(t, item1.Name, item3.Name)
1056+
}
1057+
}
1058+
10181059
func TestTxOptions_Issue409(t *testing.T) {
10191060
sess := mustOpen()
10201061
defer sess.Close()

0 commit comments

Comments
 (0)