diff --git a/postgres.go b/postgres.go index 65bd5ab..7fd2d8b 100644 --- a/postgres.go +++ b/postgres.go @@ -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 diff --git a/postgres_test.go b/postgres_test.go index cc31d78..073b3b4 100644 --- a/postgres_test.go +++ b/postgres_test.go @@ -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 {