userStore find buggy

This commit is contained in:
Ruidy Nemausat 2020-03-16 16:23:23 +01:00
parent 9bef392094
commit db947b17f3
5 changed files with 36 additions and 6 deletions

View file

@ -2,3 +2,4 @@
- [x] The mail field is case sensitive. Convert mail to lowercase before they are sent to InsertUser
- [] All errors are fatal. Provide proper error handling.
- [] Refactor UserStore code

View file

@ -33,9 +33,10 @@ func UsePSQL() {
// log.Print(u)
u1 := model.NewUser(3, 20, "paul", "newman", "PdsNz@FDKML.COM")
store.Update(16, u1)
log.Print(store.Get(1))
log.Println(store.Get(1))
// store.Delete(8)
log.Print(store.GetAll())
log.Println(store.GetAll())
log.Println(store.Find("first_name", "John"))
}
func sqlExec(db *sql.DB, s string) {
@ -58,6 +59,6 @@ type Store interface {
Get(id int) (model.User, error)
GetAll(id int) ([]model.User, error)
Delete(id int)
// Find(id int)
Find(ex string)
Update(id int, i interface{})
}

View file

@ -14,12 +14,18 @@ const (
// QueryGet is the SQL command used to retrieve a user from the table
QueryGet = `
SELECT * FROM users WHERE id=$1;
SELECT * FROM users WHERE id = $1;
`
// QueryGetAll is the SQL command used to retrieve all users from the database.
QueryGetAll = `
SELECT * FROM users;
SELECT * FROM users ORDER BY id;
`
// QueryFind is the SQL command used to retrieve all users from the table
// which satisfy the specified condition
QueryFind = `
SELECT * FROM users WHERE $1 = $2;
`
// QueryInsert is the SQL command used to insert a user in the table.

View file

@ -39,6 +39,28 @@ func (us UserStore) GetAll() ([]model.User, error) {
return users, nil
}
// Find retrieves a user from the database using an expression
func (us UserStore) Find(k interface{}, v interface{}) ([]model.User, error) {
var id, age int
var firstName, lastName, email string
rows, err := us.db.Query(QueryFind, k, v)
if err != nil {
return nil, err
}
var users []model.User
for rows.Next() {
err := rows.Scan(&id, &age, &firstName, &lastName, &email)
if err != nil {
log.Fatal(err) // too severe
}
u := model.NewUser(id, age, firstName, lastName, email)
users = append(users, u)
}
return users, nil
}
// Get retrieves the user identified by 'id' from database
func (us UserStore) Get(uid int) (model.User, error) {
var id, age int

View file

@ -18,7 +18,7 @@ func TestUser() User {
id: 42,
firstName: "John",
lastName: "Doe",
email: "jddddSZ@mail.com",
email: "jd@mail.com",
age: 42,
}
}