Rework query to return lists

This commit is contained in:
2024-10-27 19:07:47 +01:00
parent 91a3a0f4f7
commit b86d586c42
4 changed files with 222 additions and 148 deletions

View File

@@ -14,20 +14,30 @@ type NoteServiceQuery struct {
ID *int64 `db:"id"`
}
func (ns *NoteService) Query(query NoteServiceQuery) (Note, error) {
note := Note{}
func (ns *NoteService) Query(query NoteServiceQuery) ([]Note, error) {
res := []Note{}
sqlQuery := "SELECT id, content, timestamp, player FROM note"
whereQuery := BuildWhereQuery(query)
if whereQuery != "" {
sqlQuery += " " + whereQuery
}
err := ns.db.readConn.QueryRow(sqlQuery).Scan(&note.ID, &note.Content, &note.Timestamp, &note.Player.ID)
rows, err := ns.db.readConn.Query(sqlQuery)
if err != nil {
return note, fmt.Errorf("failed getting note for query %q: %v", sqlQuery, err)
return res, fmt.Errorf("failed getting notes for query %q: %v", sqlQuery, err)
}
defer rows.Close()
for rows.Next() {
note := Note{}
err := rows.Scan(&note.ID, &note.Content, &note.Timestamp, &note.Player.ID)
if err != nil {
return res, fmt.Errorf("failed scanning note: %v", err)
}
res = append(res, note)
}
return note, nil
return res, nil
}
func (ns *NoteService) Create(content string, timestamp time.Time, player Player) (Note, error) {
@@ -42,5 +52,13 @@ func (ns *NoteService) Create(content string, timestamp time.Time, player Player
return note, fmt.Errorf("failed to get last insert id: %v", err)
}
return ns.Query(NoteServiceQuery{ID: &id})
qres, err := ns.Query(NoteServiceQuery{ID: &id})
if err != nil {
return note, fmt.Errorf("failed getting note for id %d: %v", id, err)
}
if len(qres) > 1 {
return note, fmt.Errorf("more than one note found for id %d", id)
}
return qres[0], nil
}