Initial insert in handler
parent
8e42f69a70
commit
0a978da3ac
@ -0,0 +1,66 @@
|
|||||||
|
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
|
||||||
|
}
|
Loading…
Reference in New Issue