2026-10-07 16:53:03 -06:00
|
|
|
package models
|
2026-10-09 15:38:08 -06:00
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
2026-10-14 23:57:16 -06:00
|
|
|
"database/sql"
|
2026-10-14 14:26:18 -06:00
|
|
|
"errors"
|
2026-10-09 15:38:08 -06:00
|
|
|
|
|
|
|
|
"github.com/jmoiron/sqlx"
|
2026-10-14 14:26:18 -06:00
|
|
|
"github.com/mattn/go-sqlite3"
|
2026-10-09 15:38:08 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type Chat struct {
|
2026-10-20 15:33:45 -06:00
|
|
|
ID int64 `db:"id"`
|
2026-10-14 14:26:18 -06:00
|
|
|
Name string `db:"name"`
|
2026-10-09 15:38:08 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type ChatModel struct {
|
|
|
|
|
ctx context.Context
|
|
|
|
|
db *sqlx.DB
|
2026-10-20 15:23:28 -06:00
|
|
|
|
|
|
|
|
// Cached on first ListChats().
|
|
|
|
|
chats []*Chat
|
2026-10-09 15:38:08 -06:00
|
|
|
}
|
2026-10-14 14:26:18 -06:00
|
|
|
|
|
|
|
|
func NewChatModel(ctx context.Context, db *sqlx.DB) *ChatModel {
|
2026-10-20 15:23:28 -06:00
|
|
|
return &ChatModel{ctx, db, nil}
|
2026-10-14 14:26:18 -06:00
|
|
|
}
|
|
|
|
|
|
2026-10-20 15:33:45 -06:00
|
|
|
func (cm *ChatModel) AddChat(id int64, name string) (chat *Chat, err error) {
|
2026-10-20 15:23:28 -06:00
|
|
|
cm.chats = nil
|
2026-10-14 23:57:16 -06:00
|
|
|
chat = &Chat{}
|
|
|
|
|
err = cm.db.GetContext(cm.ctx, chat,
|
2026-10-14 14:26:18 -06:00
|
|
|
`insert into chats (id, name) values (?, ?)`, id, name)
|
|
|
|
|
if err != nil {
|
2026-10-14 23:57:16 -06:00
|
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
|
|
|
return chat, nil
|
|
|
|
|
}
|
2026-10-20 15:23:28 -06:00
|
|
|
if serr, ok := errors.AsType[sqlite3.Error](err); ok {
|
2026-10-14 14:26:18 -06:00
|
|
|
switch serr.ExtendedCode {
|
2026-10-14 23:57:16 -06:00
|
|
|
case sqlite3.ErrConstraintUnique, sqlite3.ErrConstraintPrimaryKey:
|
2026-10-14 14:26:18 -06:00
|
|
|
return nil, ErrUniqueConstraint.Do(err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
return chat, nil
|
|
|
|
|
}
|
2026-10-20 15:16:47 -06:00
|
|
|
|
|
|
|
|
func (cm *ChatModel) ListChats() ([]*Chat, error) {
|
2026-10-20 15:23:28 -06:00
|
|
|
if cm.chats != nil {
|
|
|
|
|
return cm.chats, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-20 15:16:47 -06:00
|
|
|
var chats []*Chat
|
|
|
|
|
err := cm.db.GetContext(cm.ctx, chats,
|
|
|
|
|
`select id, name from chats where id < 0`)
|
|
|
|
|
if err != nil {
|
|
|
|
|
if errors.Is(err, sql.ErrNoRows) {
|
2026-10-20 15:23:28 -06:00
|
|
|
cm.chats = chats
|
2026-10-20 15:16:47 -06:00
|
|
|
return chats, nil
|
|
|
|
|
}
|
2026-10-20 15:23:28 -06:00
|
|
|
if serr, ok := errors.AsType[sqlite3.Error](err); ok {
|
2026-10-20 15:16:47 -06:00
|
|
|
switch serr.ExtendedCode {
|
|
|
|
|
case sqlite3.ErrConstraintUnique, sqlite3.ErrConstraintPrimaryKey:
|
|
|
|
|
return nil, ErrUniqueConstraint.Do(err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2026-10-20 15:23:28 -06:00
|
|
|
cm.chats = chats
|
2026-10-20 15:16:47 -06:00
|
|
|
return chats, nil
|
|
|
|
|
}
|