guestbook/internal/models/guestbookcomment.go

77 lines
2.5 KiB
Go
Raw Normal View History

2024-10-16 04:34:57 +00:00
package models
import (
"database/sql"
2024-11-11 19:55:01 +00:00
"time"
2024-10-16 04:34:57 +00:00
)
type GuestbookComment struct {
2024-11-11 19:55:01 +00:00
ID int64
ShortId uint64
GuestbookId int64
ParentId int64
2024-10-16 04:34:57 +00:00
AuthorName string
AuthorEmail string
AuthorSite string
CommentText string
PageUrl string
2024-11-11 19:55:01 +00:00
Created time.Time
2024-10-16 04:34:57 +00:00
IsPublished bool
IsDeleted bool
}
type GuestbookCommentModel struct {
DB *sql.DB
}
2024-11-11 19:55:01 +00:00
func (m *GuestbookCommentModel) Insert(shortId uint64, guestbookId, parentId int64, authorName,
authorEmail, authorSite, commentText, pageUrl string, isPublished bool) (int64, error) {
stmt := `INSERT INTO guestbook_comments (ShortId, GuestbookId, ParentId, AuthorName,
AuthorEmail, AuthorSite, CommentText, PageUrl, Created, IsPublished, IsDeleted)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, FALSE)`
result, err := m.DB.Exec(stmt, shortId, guestbookId, parentId, authorName, authorEmail,
authorSite, commentText, pageUrl, time.Now().UTC(), isPublished)
if err != nil {
return -1, err
}
id, err := result.LastInsertId()
2024-10-16 04:34:57 +00:00
if err != nil {
2024-11-11 19:55:01 +00:00
return -1, err
2024-10-16 04:34:57 +00:00
}
return id, nil
}
2024-11-11 19:55:01 +00:00
func (m *GuestbookCommentModel) Get(shortId uint64) (GuestbookComment, error) {
stmt := `SELECT Id, ShortId, GuestbookId, ParentId, AuthorName, AuthorEmail, AuthorSite,
CommentText, PageUrl, Created, IsPublished, IsDeleted FROM guestbook_comments WHERE ShortId = ?`
row := m.DB.QueryRow(stmt, shortId)
2024-10-16 04:34:57 +00:00
var c GuestbookComment
2024-11-11 19:55:01 +00:00
err := row.Scan(&c.ID, &c.ShortId, &c.GuestbookId, &c.ParentId, &c.AuthorName, &c.AuthorEmail, &c.AuthorSite, &c.CommentText, &c.PageUrl, &c.Created, &c.IsPublished, &c.IsDeleted)
2024-10-16 04:34:57 +00:00
if err != nil {
return GuestbookComment{}, err
}
return c, nil
}
2024-11-11 19:55:01 +00:00
func (m *GuestbookCommentModel) GetAll(guestbookId int64) ([]GuestbookComment, error) {
stmt := `SELECT Id, ShortId, GuestbookId, ParentId, AuthorName, AuthorEmail, AuthorSite,
CommentText, PageUrl, Created, IsPublished, IsDeleted FROM guestbook_comments WHERE GuestbookId = ? AND IsDeleted = FALSE ORDER BY Created DESC`
rows, err := m.DB.Query(stmt, guestbookId)
if err != nil {
return nil, err
}
var comments []GuestbookComment
for rows.Next() {
var c GuestbookComment
2024-11-11 19:55:01 +00:00
err = rows.Scan(&c.ID, &c.ShortId, &c.GuestbookId, &c.ParentId, &c.AuthorName, &c.AuthorEmail, &c.AuthorSite, &c.CommentText, &c.PageUrl, &c.Created, &c.IsPublished, &c.IsDeleted)
if err != nil {
return nil, err
}
comments = append(comments, c)
}
if err = rows.Err(); err != nil {
return nil, err
}
return comments, nil
2024-10-16 04:34:57 +00:00
}