You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
1.8 KiB
Go
67 lines
1.8 KiB
Go
package model
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
"log/slog"
|
|
"time"
|
|
)
|
|
|
|
type Snippet struct {
|
|
ID int
|
|
Title string
|
|
Content string
|
|
CreatedAt time.Time
|
|
UpdatedAt time.Time
|
|
ExpiresAt time.Time
|
|
}
|
|
|
|
type SnippetService struct {
|
|
DB *sql.DB
|
|
}
|
|
|
|
// Insert inserts a new SnippetModel into the database
|
|
func (s *SnippetService) Insert(title, content string, expiresAt int) (int, error) {
|
|
slog.Debug(fmt.Sprintf("Inserting new snippet. Title: %s", title))
|
|
stmt, err := s.DB.Prepare("INSERT INTO snippets (title, content, expires_at) VALUES ($1, $2, DATETIME(CURRENT_TIMESTAMP, '+' || $3 || ' DAY'))")
|
|
if err != nil {
|
|
slog.Debug("The prepared statement has an error")
|
|
return 0, err
|
|
}
|
|
defer stmt.Close()
|
|
|
|
// stmt.Exec returns a sql.Result. That also has access to the statement metadata
|
|
// use _ if you don't care about the result and only want to check the err.
|
|
|
|
// Exec will NOT reserve a connection. unlike db.Query which returns a sql.Rows that
|
|
// will hold on to a connection until .Close() is called.
|
|
res, err := stmt.Exec(title, content, expiresAt)
|
|
if err != nil {
|
|
slog.Debug("SQL DDL returned an error.")
|
|
return 0, err
|
|
}
|
|
|
|
// Use the LastInsertId() method on the result to get the ID of our
|
|
// newly inserted record in the snippets table.
|
|
lastId, err := res.LastInsertId()
|
|
if err != nil {
|
|
slog.Debug("An error occured when retrieving insert result id.")
|
|
return 0, err
|
|
}
|
|
|
|
// The ID returned has the type int64, so we convert it to an int type
|
|
// before returning.
|
|
slog.Debug(fmt.Sprintf("Inserted new snippet. Snippet pk: %d", int(lastId)))
|
|
return int(lastId), nil
|
|
}
|
|
|
|
// Get retrieves a specific Snippet by ID
|
|
func (s *SnippetService) Get(id int) (Snippet, error) {
|
|
return Snippet{}, nil
|
|
}
|
|
|
|
// Latest retrieves up to latest 10 Snippets from the database.
|
|
func (s *SnippetService) Lastest() (Snippet, error) {
|
|
return Snippet{}, nil
|
|
}
|