threadr-rewritten/models/thread.go

76 lines
2.5 KiB
Go

package models
import (
"database/sql"
"time"
)
type Thread struct {
ID int
BoardID int
Title string
CreatedAt time.Time
UpdatedAt time.Time
CreatedByUserID int
AcceptedAnswerPostID *int
}
func GetThreadByID(db *sql.DB, id int) (*Thread, error) {
query := "SELECT id, board_id, title, created_at, updated_at, created_by_user_id, accepted_answer_post_id FROM threads WHERE id = ?"
row := db.QueryRow(query, id)
thread := &Thread{}
var createdAtStr string
var updatedAtStr string
err := row.Scan(&thread.ID, &thread.BoardID, &thread.Title, &createdAtStr, &updatedAtStr, &thread.CreatedByUserID, &thread.AcceptedAnswerPostID)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, err
}
thread.CreatedAt, err = time.Parse("2006-01-02 15:04:05", createdAtStr)
if err != nil {
thread.CreatedAt = time.Time{}
}
thread.UpdatedAt, err = time.Parse("2006-01-02 15:04:05", updatedAtStr)
if err != nil {
thread.UpdatedAt = time.Time{}
}
return thread, nil
}
func GetThreadsByBoardID(db *sql.DB, boardID int) ([]Thread, error) {
query := "SELECT id, board_id, title, created_at, updated_at, created_by_user_id, accepted_answer_post_id FROM threads WHERE board_id = ? ORDER BY updated_at DESC"
rows, err := db.Query(query, boardID)
if err != nil {
return nil, err
}
defer rows.Close()
var threads []Thread
for rows.Next() {
thread := Thread{}
var createdAtStr string
var updatedAtStr string
err := rows.Scan(&thread.ID, &thread.BoardID, &thread.Title, &createdAtStr, &updatedAtStr, &thread.CreatedByUserID, &thread.AcceptedAnswerPostID)
if err != nil {
return nil, err
}
thread.CreatedAt, err = time.Parse("2006-01-02 15:04:05", createdAtStr)
if err != nil {
thread.CreatedAt = time.Time{}
}
thread.UpdatedAt, err = time.Parse("2006-01-02 15:04:05", updatedAtStr)
if err != nil {
thread.UpdatedAt = time.Time{}
}
threads = append(threads, thread)
}
return threads, nil
}
func CreateThread(db *sql.DB, thread Thread) error {
query := "INSERT INTO threads (board_id, title, created_by_user_id, created_at, updated_at, type) VALUES (?, ?, ?, NOW(), NOW(), 'classic')"
_, err := db.Exec(query, thread.BoardID, thread.Title, thread.CreatedByUserID)
return err
}