save first version
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ClaimMessage struct {
|
||||
TicketID int64
|
||||
MessageID string
|
||||
LastReupAt time.Time
|
||||
}
|
||||
|
||||
type ClaimMessageRepo struct{ db *sql.DB }
|
||||
|
||||
func NewClaimMessageRepo(db *sql.DB) *ClaimMessageRepo { return &ClaimMessageRepo{db: db} }
|
||||
|
||||
func (r *ClaimMessageRepo) Upsert(ctx context.Context, ticketID int64, messageID string, at time.Time) error {
|
||||
_, err := r.db.ExecContext(ctx, `
|
||||
INSERT INTO claim_messages(ticket_id, message_id, last_reup_at) VALUES(?,?,?)
|
||||
ON CONFLICT(ticket_id) DO UPDATE SET message_id=excluded.message_id, last_reup_at=excluded.last_reup_at`,
|
||||
ticketID, messageID, at.UTC())
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *ClaimMessageRepo) Get(ctx context.Context, ticketID int64) (*ClaimMessage, error) {
|
||||
var cm ClaimMessage
|
||||
err := r.db.QueryRowContext(ctx,
|
||||
`SELECT ticket_id, message_id, last_reup_at FROM claim_messages WHERE ticket_id=?`, ticketID,
|
||||
).Scan(&cm.TicketID, &cm.MessageID, &cm.LastReupAt)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return &cm, err
|
||||
}
|
||||
|
||||
func (r *ClaimMessageRepo) Delete(ctx context.Context, ticketID int64) error {
|
||||
_, err := r.db.ExecContext(ctx, `DELETE FROM claim_messages WHERE ticket_id=?`, ticketID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *ClaimMessageRepo) ListAll(ctx context.Context) ([]*ClaimMessage, error) {
|
||||
rows, err := r.db.QueryContext(ctx, `SELECT ticket_id, message_id, last_reup_at FROM claim_messages`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var result []*ClaimMessage
|
||||
for rows.Next() {
|
||||
var cm ClaimMessage
|
||||
if err := rows.Scan(&cm.TicketID, &cm.MessageID, &cm.LastReupAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, &cm)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
func Open(path string) (*sql.DB, error) {
|
||||
db, err := sql.Open("sqlite", path+"?_journal=WAL&_timeout=5000&_fk=true")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db.SetMaxOpenConns(1) // SQLite is single-writer
|
||||
if err := migrate(db); err != nil {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("migrate: %w", err)
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func migrate(db *sql.DB) error {
|
||||
ctx := context.Background()
|
||||
if _, err := db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)`); err != nil {
|
||||
return err
|
||||
}
|
||||
var version int
|
||||
db.QueryRowContext(ctx, `SELECT COALESCE(MAX(version),0) FROM schema_version`).Scan(&version) //nolint
|
||||
|
||||
migrations := []string{
|
||||
// v1: core schema
|
||||
`CREATE TABLE IF NOT EXISTS tickets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
ticket_number INTEGER NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
panel TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
channel_id TEXT NOT NULL UNIQUE,
|
||||
opened_at DATETIME NOT NULL,
|
||||
claimed_by TEXT,
|
||||
claimed_at DATETIME,
|
||||
closed_at DATETIME,
|
||||
closed_by TEXT,
|
||||
reason TEXT,
|
||||
transcript_path TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'open'
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_tickets_user ON tickets(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_tickets_status ON tickets(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_tickets_type ON tickets(type);
|
||||
CREATE TABLE IF NOT EXISTS claim_messages (
|
||||
ticket_id INTEGER PRIMARY KEY,
|
||||
message_id TEXT NOT NULL,
|
||||
last_reup_at DATETIME NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS convocation_counter (
|
||||
id INTEGER PRIMARY KEY CHECK(id=1),
|
||||
count INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
INSERT OR IGNORE INTO convocation_counter(id,count) VALUES(1,0);`,
|
||||
}
|
||||
|
||||
for i, m := range migrations {
|
||||
v := i + 1
|
||||
if v <= version {
|
||||
continue
|
||||
}
|
||||
if _, err := db.ExecContext(ctx, m); err != nil {
|
||||
return fmt.Errorf("migration v%d: %w", v, err)
|
||||
}
|
||||
if _, err := db.ExecContext(ctx, `INSERT INTO schema_version(version) VALUES(?)`, v); err != nil {
|
||||
return fmt.Errorf("record migration v%d: %w", v, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func openTestDB(t *testing.T) (*TicketRepo, *ClaimMessageRepo) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "test.db")
|
||||
sqldb, err := Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { sqldb.Close() })
|
||||
return NewTicketRepo(sqldb), NewClaimMessageRepo(sqldb)
|
||||
}
|
||||
|
||||
func TestInsertAndGet(t *testing.T) {
|
||||
repo, _ := openTestDB(t)
|
||||
ctx := context.Background()
|
||||
ticket := &Ticket{
|
||||
UserID: "user1",
|
||||
Panel: "support_panel",
|
||||
Type: "support",
|
||||
ChannelID: "chan1",
|
||||
OpenedAt: time.Now(),
|
||||
}
|
||||
if err := repo.Insert(ctx, ticket); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ticket.ID == 0 {
|
||||
t.Fatal("expected non-zero ID")
|
||||
}
|
||||
if ticket.TicketNumber != 1 {
|
||||
t.Errorf("ticket_number = %d, want 1", ticket.TicketNumber)
|
||||
}
|
||||
|
||||
got, err := repo.GetByChannelID(ctx, "chan1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.UserID != "user1" {
|
||||
t.Errorf("user_id = %q, want user1", got.UserID)
|
||||
}
|
||||
if got.Status != "open" {
|
||||
t.Errorf("status = %q, want open", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicketNumberPerType(t *testing.T) {
|
||||
repo, _ := openTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
tk := &Ticket{UserID: "u", Panel: "p", Type: "support", ChannelID: "c" + string(rune('a'+i)), OpenedAt: time.Now()}
|
||||
if err := repo.Insert(ctx, tk); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// mod type starts its own counter at 1
|
||||
tk2 := &Ticket{UserID: "u", Panel: "p", Type: "mod", ChannelID: "cx", OpenedAt: time.Now()}
|
||||
if err := repo.Insert(ctx, tk2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tk2.TicketNumber != 1 {
|
||||
t.Errorf("mod ticket_number = %d, want 1", tk2.TicketNumber)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHasOpenTicket(t *testing.T) {
|
||||
repo, _ := openTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
tk := &Ticket{UserID: "u1", Panel: "p", Type: "support", ChannelID: "c1", OpenedAt: time.Now()}
|
||||
repo.Insert(ctx, tk)
|
||||
|
||||
found, err := repo.HasOpenTicket(ctx, "u1", "support")
|
||||
if err != nil || found == nil {
|
||||
t.Fatal("expected open ticket")
|
||||
}
|
||||
repo.SetClosed(ctx, tk.ID, "staff1", "resolved", "", time.Now())
|
||||
found, _ = repo.HasOpenTicket(ctx, "u1", "support")
|
||||
if found != nil {
|
||||
t.Fatal("expected no open ticket after close")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaimMessages(t *testing.T) {
|
||||
_, claims := openTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
err := claims.Upsert(ctx, 1, "msg1", time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cm, err := claims.Get(ctx, 1)
|
||||
if err != nil || cm == nil {
|
||||
t.Fatal("expected claim message")
|
||||
}
|
||||
if cm.MessageID != "msg1" {
|
||||
t.Errorf("message_id = %q, want msg1", cm.MessageID)
|
||||
}
|
||||
|
||||
// Upsert updates
|
||||
claims.Upsert(ctx, 1, "msg2", time.Now())
|
||||
cm, _ = claims.Get(ctx, 1)
|
||||
if cm.MessageID != "msg2" {
|
||||
t.Errorf("after update message_id = %q, want msg2", cm.MessageID)
|
||||
}
|
||||
|
||||
claims.Delete(ctx, 1)
|
||||
cm, _ = claims.Get(ctx, 1)
|
||||
if cm != nil {
|
||||
t.Fatal("expected nil after delete")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationIdempotent(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "test.db")
|
||||
db1, err := Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db1.Close()
|
||||
// Open again — migrations must not fail or duplicate
|
||||
db2, err := Open(path)
|
||||
if err != nil {
|
||||
t.Fatalf("second open: %v", err)
|
||||
}
|
||||
db2.Close()
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Ticket struct {
|
||||
ID int64
|
||||
TicketNumber int
|
||||
UserID string
|
||||
Panel string
|
||||
Type string
|
||||
ChannelID string
|
||||
OpenedAt time.Time
|
||||
ClaimedBy sql.NullString
|
||||
ClaimedAt sql.NullTime
|
||||
ClosedAt sql.NullTime
|
||||
ClosedBy sql.NullString
|
||||
Reason sql.NullString
|
||||
TranscriptPath sql.NullString
|
||||
Status string
|
||||
}
|
||||
|
||||
type TicketRepo struct{ db *sql.DB }
|
||||
|
||||
func NewTicketRepo(db *sql.DB) *TicketRepo { return &TicketRepo{db: db} }
|
||||
|
||||
// nextNumber returns the next ticket_number for the given type within a transaction.
|
||||
func (r *TicketRepo) nextNumber(ctx context.Context, tx *sql.Tx, ticketType string) (int, error) {
|
||||
var n int
|
||||
err := tx.QueryRowContext(ctx,
|
||||
`SELECT COALESCE(MAX(ticket_number),0)+1 FROM tickets WHERE type=?`, ticketType,
|
||||
).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (r *TicketRepo) Insert(ctx context.Context, t *Ticket) error {
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback() //nolint
|
||||
|
||||
n, err := r.nextNumber(ctx, tx, t.Type)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t.TicketNumber = n
|
||||
|
||||
res, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO tickets(ticket_number,user_id,panel,type,channel_id,opened_at,status)
|
||||
VALUES(?,?,?,?,?,?,?)`,
|
||||
n, t.UserID, t.Panel, t.Type, t.ChannelID, t.OpenedAt.UTC(), "open",
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert ticket: %w", err)
|
||||
}
|
||||
t.ID, _ = res.LastInsertId()
|
||||
t.Status = "open"
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// InsertWithNumber inserts a ticket where TicketNumber is already set (e.g. convocations).
|
||||
func (r *TicketRepo) InsertWithNumber(ctx context.Context, t *Ticket) error {
|
||||
res, err := r.db.ExecContext(ctx, `
|
||||
INSERT INTO tickets(ticket_number,user_id,panel,type,channel_id,opened_at,status)
|
||||
VALUES(?,?,?,?,?,?,?)`,
|
||||
t.TicketNumber, t.UserID, t.Panel, t.Type, t.ChannelID, t.OpenedAt.UTC(), "open",
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert ticket with number: %w", err)
|
||||
}
|
||||
t.ID, _ = res.LastInsertId()
|
||||
t.Status = "open"
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *TicketRepo) GetByChannelID(ctx context.Context, channelID string) (*Ticket, error) {
|
||||
row := r.db.QueryRowContext(ctx, `
|
||||
SELECT id,ticket_number,user_id,panel,type,channel_id,opened_at,
|
||||
claimed_by,claimed_at,closed_at,closed_by,reason,transcript_path,status
|
||||
FROM tickets WHERE channel_id=?`, channelID)
|
||||
return scanTicket(row)
|
||||
}
|
||||
|
||||
func (r *TicketRepo) GetByID(ctx context.Context, id int64) (*Ticket, error) {
|
||||
row := r.db.QueryRowContext(ctx, `
|
||||
SELECT id,ticket_number,user_id,panel,type,channel_id,opened_at,
|
||||
claimed_by,claimed_at,closed_at,closed_by,reason,transcript_path,status
|
||||
FROM tickets WHERE id=?`, id)
|
||||
return scanTicket(row)
|
||||
}
|
||||
|
||||
func (r *TicketRepo) HasOpenTicket(ctx context.Context, userID, ticketType string) (*Ticket, error) {
|
||||
row := r.db.QueryRowContext(ctx, `
|
||||
SELECT id,ticket_number,user_id,panel,type,channel_id,opened_at,
|
||||
claimed_by,claimed_at,closed_at,closed_by,reason,transcript_path,status
|
||||
FROM tickets WHERE user_id=? AND type=? AND status IN('open','claimed')
|
||||
LIMIT 1`, userID, ticketType)
|
||||
t, err := scanTicket(row)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return t, err
|
||||
}
|
||||
|
||||
func (r *TicketRepo) SetClaimed(ctx context.Context, id int64, staffID string, at time.Time) error {
|
||||
_, err := r.db.ExecContext(ctx,
|
||||
`UPDATE tickets SET status='claimed', claimed_by=?, claimed_at=? WHERE id=?`,
|
||||
staffID, at.UTC(), id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *TicketRepo) SetClosed(ctx context.Context, id int64, closedBy, reason, transcriptPath string, at time.Time) error {
|
||||
_, err := r.db.ExecContext(ctx, `
|
||||
UPDATE tickets SET status='closed', closed_at=?, closed_by=?, reason=?, transcript_path=?
|
||||
WHERE id=?`,
|
||||
at.UTC(), closedBy, reason, transcriptPath, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *TicketRepo) SetClosedByChannel(ctx context.Context, channelID, reason string) error {
|
||||
_, err := r.db.ExecContext(ctx, `
|
||||
UPDATE tickets SET status='closed', closed_at=?, reason=?
|
||||
WHERE channel_id=? AND status IN('open','claimed')`,
|
||||
time.Now().UTC(), reason, channelID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *TicketRepo) ListOpen(ctx context.Context) ([]*Ticket, error) {
|
||||
rows, err := r.db.QueryContext(ctx, `
|
||||
SELECT id,ticket_number,user_id,panel,type,channel_id,opened_at,
|
||||
claimed_by,claimed_at,closed_at,closed_by,reason,transcript_path,status
|
||||
FROM tickets WHERE status='open'`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanTickets(rows)
|
||||
}
|
||||
|
||||
func (r *TicketRepo) UpdateChannelID(ctx context.Context, id int64, newChannelID string) error {
|
||||
_, err := r.db.ExecContext(ctx, `UPDATE tickets SET channel_id=? WHERE id=?`, newChannelID, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *TicketRepo) NextConvocationNumber(ctx context.Context) (int, error) {
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer tx.Rollback() //nolint
|
||||
var n int
|
||||
if err := tx.QueryRowContext(ctx, `UPDATE convocation_counter SET count=count+1 WHERE id=1 RETURNING count`).Scan(&n); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return n, tx.Commit()
|
||||
}
|
||||
|
||||
func scanTicket(row *sql.Row) (*Ticket, error) {
|
||||
var t Ticket
|
||||
err := row.Scan(&t.ID, &t.TicketNumber, &t.UserID, &t.Panel, &t.Type, &t.ChannelID,
|
||||
&t.OpenedAt, &t.ClaimedBy, &t.ClaimedAt, &t.ClosedAt, &t.ClosedBy,
|
||||
&t.Reason, &t.TranscriptPath, &t.Status)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
func scanTickets(rows *sql.Rows) ([]*Ticket, error) {
|
||||
var result []*Ticket
|
||||
for rows.Next() {
|
||||
var t Ticket
|
||||
if err := rows.Scan(&t.ID, &t.TicketNumber, &t.UserID, &t.Panel, &t.Type, &t.ChannelID,
|
||||
&t.OpenedAt, &t.ClaimedBy, &t.ClaimedAt, &t.ClosedAt, &t.ClosedBy,
|
||||
&t.Reason, &t.TranscriptPath, &t.Status); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, &t)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
Reference in New Issue
Block a user