package main import ( "fmt" "log" "time" ) type NoteService struct { db *DB } type NoteServiceQuery struct { Timestamp *string `db:"timestamp"` PlayerID *int64 `db:"player"` ID *int64 `db:"id"` } 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 } rows, err := ns.db.readConn.Query(sqlQuery) if err != nil { return res, fmt.Errorf("failed getting notes for query %q: %v", sqlQuery, err) } defer rows.Close() for rows.Next() { note := Note{} var ts string err := rows.Scan(¬e.ID, ¬e.Content, &ts, ¬e.Player.ID) if err != nil { return res, fmt.Errorf("failed scanning note: %v", err) } note.Timestamp, err = time.Parse(time.RFC3339, ts) if err != nil { return res, fmt.Errorf("failed parsing timestamp: %v", err) } res = append(res, note) } return res, nil } func (ns *NoteService) Create(content string, timestamp time.Time, player Player) (Note, error) { log.Printf("Creating note %q with timestamp %s and player %d", content, timestamp, player.ID) note := Note{} res, err := ns.db.writeConn.Exec("insert into note (content, timestamp, player) values (?, ?, ?)", content, timestamp.Format(time.RFC3339), player.ID) if err != nil { return note, fmt.Errorf("failed to insert note: %v", err) } id, err := res.LastInsertId() if err != nil { return note, fmt.Errorf("failed to get last insert id: %v", err) } log.Printf("Created note %q with timestamp %s and player %d with id %d", content, timestamp, player.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 }