phoneof/database/messages.go

50 lines
1.1 KiB
Go
Raw Normal View History

2025-01-03 04:47:07 -05:00
package database
import (
"database/sql"
"time"
)
type Message struct {
Id string
FrenId string
Message string
Time time.Time
FrenSent bool
}
type ListMessageQuery struct {
FrenId string
Before time.Time
Limit int
}
func ListMessages(dbConn *sql.DB, query ListMessageQuery) ([]Message, error) {
rows, err := dbConn.Query(`SELECT id, fren_id, message, time, fren_sent FROM messages WHERE fren_id = ? AND time < ? ORDER BY time ASC LIMIT ?;`, query.FrenId, query.Before, query.Limit)
if err != nil {
return nil, err
}
defer rows.Close()
messages := []Message{}
for rows.Next() {
var message Message
err := rows.Scan(&message.Id, &message.FrenId, &message.Message, &message.Time, &message.FrenSent)
if err != nil {
return nil, err
}
messages = append(messages, message)
}
return messages, nil
}
func SaveMessage(db *sql.DB, message *Message) (*Message, error) {
_, err := db.Exec("INSERT OR REPLACE INTO messages (id, fren_id, message, time, fren_sent) VALUES (?, ?, ?, ?, ?)", message.Id, message.FrenId, message.Message, message.Time, message.FrenSent)
if err != nil {
return nil, err
}
return message, nil
}