mirror of
https://github.com/VinGarcia/ksql.git
synced 2025-05-31 11:42:25 +00:00
Add GetByID()
This commit is contained in:
parent
25e00fdad6
commit
fbb7d9ffca
11
postgres.go
11
postgres.go
@ -2,6 +2,7 @@ package gpostgres
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
"github.com/jinzhu/gorm"
|
"github.com/jinzhu/gorm"
|
||||||
)
|
)
|
||||||
@ -33,6 +34,16 @@ func (c Client) Find(
|
|||||||
return it.Error
|
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
|
// Insert one or more instances on the database
|
||||||
//
|
//
|
||||||
// If the original instances have been passed by reference
|
// If the original instances have been passed by reference
|
||||||
|
@ -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) {
|
func TestInsert(t *testing.T) {
|
||||||
err := createTable()
|
err := createTable()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user