51 lines
1.1 KiB
Go
51 lines
1.1 KiB
Go
package postgresql
|
|
|
|
import (
|
|
"git.hexq.cn/tiglog/mydb"
|
|
"git.hexq.cn/tiglog/mydb/internal/sqladapter"
|
|
)
|
|
|
|
type collectionAdapter struct {
|
|
}
|
|
|
|
func (*collectionAdapter) Insert(col sqladapter.Collection, item interface{}) (interface{}, error) {
|
|
pKey, err := col.PrimaryKeys()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
q := col.SQL().InsertInto(col.Name()).Values(item)
|
|
|
|
if len(pKey) == 0 {
|
|
// There is no primary key.
|
|
res, err := q.Exec()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Attempt to use LastInsertId() (probably won't work, but the Exec()
|
|
// succeeded, so we can safely ignore the error from LastInsertId()).
|
|
lastID, err := res.LastInsertId()
|
|
if err != nil {
|
|
return nil, nil
|
|
}
|
|
return lastID, nil
|
|
}
|
|
|
|
// Asking the database to return the primary key after insertion.
|
|
q = q.Returning(pKey...)
|
|
|
|
var keyMap mydb.Cond
|
|
if err := q.Iterator().One(&keyMap); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// The IDSetter interface does not match, look for another interface match.
|
|
if len(keyMap) == 1 {
|
|
return keyMap[pKey[0]], nil
|
|
}
|
|
|
|
// This was a compound key and no interface matched it, let's return a map.
|
|
return keyMap, nil
|
|
}
|