Add GetByID()

pull/2/head
Vinícius Garcia 2020-09-11 19:48:13 -03:00
parent 25e00fdad6
commit fbb7d9ffca
2 changed files with 55 additions and 0 deletions

View File

@ -2,6 +2,7 @@ package gpostgres
import (
"context"
"fmt"
"github.com/jinzhu/gorm"
)
@ -33,6 +34,16 @@ func (c Client) Find(
return it.Error
}
func (c Client) GetByID(
ctx context.Context,
item interface{},
id interface{},
) error {
it := c.db.Raw(fmt.Sprintf("select * from %s where id = ?", c.tableName), id)
it.Scan(item)
return it.Error
}
// Insert one or more instances on the database
//
// If the original instances have been passed by reference

View File

@ -59,6 +59,50 @@ func TestFind(t *testing.T) {
})
}
func TestGetByID(t *testing.T) {
err := createTable()
if err != nil {
t.Fatal("could not create test table!")
}
t.Run("should return 0 results correctly", func(t *testing.T) {
db := connectDB(t)
defer db.Close()
ctx := context.Background()
c := Client{
db: db,
tableName: "users",
}
u := User{}
err := c.GetByID(ctx, &u, 999)
assert.Equal(t, err, nil)
assert.Equal(t, User{}, u)
})
t.Run("should return a user correctly", func(t *testing.T) {
db := connectDB(t)
defer db.Close()
bia := &User{
Name: "Bia",
}
db.Create(&bia)
ctx := context.Background()
c := Client{
db: db,
tableName: "users",
}
result := User{}
err = c.GetByID(ctx, &result, bia.ID)
assert.Equal(t, err, nil)
assert.Equal(t, "Bia", result.Name)
assert.Equal(t, bia.ID, result.ID)
})
}
func TestInsert(t *testing.T) {
err := createTable()
if err != nil {