From 54d1b93b2dc865ab2d3a975dcf3bfe074717c86a Mon Sep 17 00:00:00 2001 From: lyx0 <66651385+lyx0@users.noreply.github.com> Date: Mon, 8 Aug 2022 23:58:38 +0200 Subject: [PATCH] add database models for twitch channel --- internal/data/channel.go | 58 ++++++++++++++++++++++++++++++++++++++++ internal/data/models.go | 7 +++++ 2 files changed, 65 insertions(+) create mode 100644 internal/data/channel.go create mode 100644 internal/data/models.go diff --git a/internal/data/channel.go b/internal/data/channel.go new file mode 100644 index 0000000..6c66450 --- /dev/null +++ b/internal/data/channel.go @@ -0,0 +1,58 @@ +package data + +import ( + "database/sql" + "errors" + "time" +) + +type Channel struct { + ID int `json:"id"` + JoinedAt time.Time `json:"-"` + Login string `json:"login"` + TwitchID string `json:"twitchid"` + Announce bool `json:"announce"` +} + +type ChannelModel struct { + DB *sql.DB +} + +func (c ChannelModel) Insert(channel *Channel) error { + query := ` + INSERT INTO channels (login, twitchid, announce) + VALUES ($1, $2, $3) + RETURNING id, created_at` + + args := []interface{}{channel.Login, channel.TwitchID, channel.Announce} + + return c.DB.QueryRow(query, args...).Scan(&channel.ID, &channel.JoinedAt) +} + +func (c ChannelModel) Get(login string) (*Channel, error) { + query := ` + SELECT id, joined_at, login, twitchid, announce + FROM channels + WHERE login = $1` + + var channel Channel + + err := c.DB.QueryRow(query, login).Scan( + &channel.ID, + &channel.JoinedAt, + &channel.Login, + &channel.TwitchID, + &channel.Announce, + ) + + if err != nil { + switch { + case errors.Is(err, sql.ErrNoRows): + return nil, ErrRecordNotFound + default: + return nil, err + } + } + + return &channel, nil +} diff --git a/internal/data/models.go b/internal/data/models.go new file mode 100644 index 0000000..4d3ac9b --- /dev/null +++ b/internal/data/models.go @@ -0,0 +1,7 @@ +package data + +import "errors" + +var ( + ErrRecordNotFound = errors.New("record not found") +)