Move sessions, messages, turns and full-text search off the per-process SQLite file onto Postgres behind the existing messaging.SessionStore contract. New adapter internal/gateway/session_store_postgres.go, sqlc queries/gateway.sql, migration 0003_gateway.sql, regenerated postgresdb. FTS5 becomes a STORED generated tsvector column over (sender, text) plus GIN. plainto_tsquery is the tsvector analog of ftsMatchQuery's quote-escaping: query text is parsed as plain text, never query syntax, and the surviving terms are ANDed. MessagePage.Truncated stays always-false on Postgres too: the result set is counted exactly. On internal/domain/messaging/session_store.go: this is a comment-only edit to the MessagePage.Truncated doc comment (the brief's own "change the comment" instruction). It changes no type, method or value, so L2 and the import lane still build against an unchanged contract and the wire is unaffected. No interface widened or altered. Semantics preserved verbatim: - The timestamp clamp is SQL-atomic (INSERT ... SELECT MAX(ts)+1). Appends to one session are serialised by a transaction-scoped advisory lock keyed on the session so two concurrent appends cannot read the same MAX(ts); a Go clamp would race (proven by the new cross-handle monotonicity test). - Session ordering is GREATEST(last_active_at, created_at) with a matching expression index. - ClaimTurn is insert-first (ON CONFLICT DO NOTHING), with a race test across two handles. State outside the store is NOT made shared by this change, and none of it is silently improved or worsened: - sessionTracker.active, Router.titling and per-session persona selection are in-memory, per-process caches; a second Gateway still diverges from the first. - messaging.Turns lanes and the per-process recovery latch stay per-process. - RecoverTurns still fails every turn owned by another process, so a second Gateway starting would still fail the first's in-flight turns. This lane does NOT make that safe and does not try to: the safeguard is D4.1's single-Gateway advisory serve-ownership lock (not implemented here), which prevents a second Gateway from serving at all. The turn-recovery semantics are left exactly as they were. Production openers still return SQLite; this lane adds the adapter and tests only. The cutover and the state-sharing questions remain follow-up work.
845 lines
21 KiB
Go
845 lines
21 KiB
Go
// Code generated by sqlc. DO NOT EDIT.
|
|
// versions:
|
|
// sqlc v1.31.1
|
|
// source: gateway.sql
|
|
|
|
package postgresdb
|
|
|
|
import (
|
|
"context"
|
|
)
|
|
|
|
const countMessages = `-- name: CountMessages :one
|
|
SELECT COUNT(*) FROM messages WHERE session_id = $1
|
|
`
|
|
|
|
func (q *Queries) CountMessages(ctx context.Context, sessionID string) (int64, error) {
|
|
row := q.db.QueryRow(ctx, countMessages, sessionID)
|
|
var count int64
|
|
err := row.Scan(&count)
|
|
return count, err
|
|
}
|
|
|
|
const deleteMessagesByID = `-- name: DeleteMessagesByID :exec
|
|
DELETE FROM messages WHERE session_id = $1 AND message_id = ANY($2::text[])
|
|
`
|
|
|
|
type DeleteMessagesByIDParams struct {
|
|
SessionID string
|
|
Ids []string
|
|
}
|
|
|
|
func (q *Queries) DeleteMessagesByID(ctx context.Context, arg DeleteMessagesByIDParams) error {
|
|
_, err := q.db.Exec(ctx, deleteMessagesByID, arg.SessionID, arg.Ids)
|
|
return err
|
|
}
|
|
|
|
const deleteRecentMessages = `-- name: DeleteRecentMessages :execrows
|
|
DELETE FROM messages WHERE id IN (
|
|
SELECT m.id FROM messages m WHERE m.session_id = $1 ORDER BY m.ts DESC LIMIT $2
|
|
)
|
|
`
|
|
|
|
type DeleteRecentMessagesParams struct {
|
|
SessionID string
|
|
Limit int32
|
|
}
|
|
|
|
func (q *Queries) DeleteRecentMessages(ctx context.Context, arg DeleteRecentMessagesParams) (int64, error) {
|
|
result, err := q.db.Exec(ctx, deleteRecentMessages, arg.SessionID, arg.Limit)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return result.RowsAffected(), nil
|
|
}
|
|
|
|
const deleteSession = `-- name: DeleteSession :exec
|
|
DELETE FROM sessions WHERE session_id = $1
|
|
`
|
|
|
|
func (q *Queries) DeleteSession(ctx context.Context, sessionID string) error {
|
|
_, err := q.db.Exec(ctx, deleteSession, sessionID)
|
|
return err
|
|
}
|
|
|
|
const deleteSessionMessages = `-- name: DeleteSessionMessages :exec
|
|
DELETE FROM messages WHERE session_id = $1
|
|
`
|
|
|
|
func (q *Queries) DeleteSessionMessages(ctx context.Context, sessionID string) error {
|
|
_, err := q.db.Exec(ctx, deleteSessionMessages, sessionID)
|
|
return err
|
|
}
|
|
|
|
const deleteSessionTurns = `-- name: DeleteSessionTurns :exec
|
|
DELETE FROM turns WHERE session_id = $1
|
|
`
|
|
|
|
func (q *Queries) DeleteSessionTurns(ctx context.Context, sessionID string) error {
|
|
_, err := q.db.Exec(ctx, deleteSessionTurns, sessionID)
|
|
return err
|
|
}
|
|
|
|
const finalizeTurn = `-- name: FinalizeTurn :execrows
|
|
UPDATE turns SET status = $2, error = $3, updated_at = $4
|
|
WHERE turn_id = $1 AND attempt = $5 AND owner_id = $6
|
|
`
|
|
|
|
type FinalizeTurnParams struct {
|
|
TurnID string
|
|
Status string
|
|
Error string
|
|
UpdatedAt int64
|
|
Attempt int64
|
|
OwnerID string
|
|
}
|
|
|
|
func (q *Queries) FinalizeTurn(ctx context.Context, arg FinalizeTurnParams) (int64, error) {
|
|
result, err := q.db.Exec(ctx, finalizeTurn,
|
|
arg.TurnID,
|
|
arg.Status,
|
|
arg.Error,
|
|
arg.UpdatedAt,
|
|
arg.Attempt,
|
|
arg.OwnerID,
|
|
)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return result.RowsAffected(), nil
|
|
}
|
|
|
|
const insertMessageAt = `-- name: InsertMessageAt :exec
|
|
INSERT INTO messages (message_id, session_id, source_id, sender, sender_id, role, text, ts)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
|
ON CONFLICT (session_id, message_id) DO NOTHING
|
|
`
|
|
|
|
type InsertMessageAtParams struct {
|
|
MessageID string
|
|
SessionID string
|
|
SourceID string
|
|
Sender string
|
|
SenderID string
|
|
Role string
|
|
Text string
|
|
Ts int64
|
|
}
|
|
|
|
// Rewriting history places records deliberately, so no clamp applies.
|
|
func (q *Queries) InsertMessageAt(ctx context.Context, arg InsertMessageAtParams) error {
|
|
_, err := q.db.Exec(ctx, insertMessageAt,
|
|
arg.MessageID,
|
|
arg.SessionID,
|
|
arg.SourceID,
|
|
arg.Sender,
|
|
arg.SenderID,
|
|
arg.Role,
|
|
arg.Text,
|
|
arg.Ts,
|
|
)
|
|
return err
|
|
}
|
|
|
|
const insertMessageClamped = `-- name: InsertMessageClamped :exec
|
|
INSERT INTO messages (message_id, session_id, source_id, sender, sender_id, role, text, ts)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, (
|
|
SELECT CASE
|
|
WHEN MAX(m.ts) IS NOT NULL AND MAX(m.ts) >= $8 THEN MAX(m.ts) + 1
|
|
ELSE $8
|
|
END
|
|
FROM messages m WHERE m.session_id = $2
|
|
))
|
|
ON CONFLICT (session_id, message_id) DO NOTHING
|
|
`
|
|
|
|
type InsertMessageClampedParams struct {
|
|
MessageID string
|
|
SessionID string
|
|
SourceID string
|
|
Sender string
|
|
SenderID string
|
|
Role string
|
|
Text string
|
|
Ts int64
|
|
}
|
|
|
|
// The append path's strictly-increasing timestamp. The clamp is computed in
|
|
// SQL, not in Go: the CASE assigns MAX(ts)+1 when the caller's timestamp is
|
|
// not ahead of the session's newest, else the caller's timestamp. A Go-side
|
|
// read-then-write would race two concurrent appends to the same session.
|
|
func (q *Queries) InsertMessageClamped(ctx context.Context, arg InsertMessageClampedParams) error {
|
|
_, err := q.db.Exec(ctx, insertMessageClamped,
|
|
arg.MessageID,
|
|
arg.SessionID,
|
|
arg.SourceID,
|
|
arg.Sender,
|
|
arg.SenderID,
|
|
arg.Role,
|
|
arg.Text,
|
|
arg.Ts,
|
|
)
|
|
return err
|
|
}
|
|
|
|
const insertTurn = `-- name: InsertTurn :execrows
|
|
|
|
INSERT INTO turns (turn_id, session_id, source_id, status, attempt, owner_id,
|
|
input_message_id, assistant_message_id, partial_text,
|
|
response_text, tool_calls, error, created_at, updated_at)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
|
|
ON CONFLICT (turn_id) DO NOTHING
|
|
`
|
|
|
|
type InsertTurnParams struct {
|
|
TurnID string
|
|
SessionID string
|
|
SourceID string
|
|
Status string
|
|
Attempt int64
|
|
OwnerID string
|
|
InputMessageID string
|
|
AssistantMessageID string
|
|
PartialText string
|
|
ResponseText string
|
|
ToolCalls string
|
|
Error string
|
|
CreatedAt int64
|
|
UpdatedAt int64
|
|
}
|
|
|
|
// ── Turns ───────────────────────────────────────────────────────────────────
|
|
func (q *Queries) InsertTurn(ctx context.Context, arg InsertTurnParams) (int64, error) {
|
|
result, err := q.db.Exec(ctx, insertTurn,
|
|
arg.TurnID,
|
|
arg.SessionID,
|
|
arg.SourceID,
|
|
arg.Status,
|
|
arg.Attempt,
|
|
arg.OwnerID,
|
|
arg.InputMessageID,
|
|
arg.AssistantMessageID,
|
|
arg.PartialText,
|
|
arg.ResponseText,
|
|
arg.ToolCalls,
|
|
arg.Error,
|
|
arg.CreatedAt,
|
|
arg.UpdatedAt,
|
|
)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return result.RowsAffected(), nil
|
|
}
|
|
|
|
const listRecoverableTurns = `-- name: ListRecoverableTurns :many
|
|
SELECT turn_id, session_id, source_id, status, attempt, owner_id,
|
|
input_message_id, assistant_message_id, partial_text,
|
|
response_text, tool_calls, error, created_at, updated_at
|
|
FROM turns WHERE status IN ('accepted', 'running', 'partial') ORDER BY updated_at ASC
|
|
`
|
|
|
|
func (q *Queries) ListRecoverableTurns(ctx context.Context) ([]Turn, error) {
|
|
rows, err := q.db.Query(ctx, listRecoverableTurns)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var items []Turn
|
|
for rows.Next() {
|
|
var i Turn
|
|
if err := rows.Scan(
|
|
&i.TurnID,
|
|
&i.SessionID,
|
|
&i.SourceID,
|
|
&i.Status,
|
|
&i.Attempt,
|
|
&i.OwnerID,
|
|
&i.InputMessageID,
|
|
&i.AssistantMessageID,
|
|
&i.PartialText,
|
|
&i.ResponseText,
|
|
&i.ToolCalls,
|
|
&i.Error,
|
|
&i.CreatedAt,
|
|
&i.UpdatedAt,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const listSessions = `-- name: ListSessions :many
|
|
SELECT session_id, platform, bot_user, channel_id, thread_id,
|
|
title, parent_session_id, branch_name, created_at, last_active_at
|
|
FROM sessions
|
|
ORDER BY GREATEST(last_active_at, created_at) DESC
|
|
`
|
|
|
|
func (q *Queries) ListSessions(ctx context.Context) ([]Session, error) {
|
|
rows, err := q.db.Query(ctx, listSessions)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var items []Session
|
|
for rows.Next() {
|
|
var i Session
|
|
if err := rows.Scan(
|
|
&i.SessionID,
|
|
&i.Platform,
|
|
&i.BotUser,
|
|
&i.ChannelID,
|
|
&i.ThreadID,
|
|
&i.Title,
|
|
&i.ParentSessionID,
|
|
&i.BranchName,
|
|
&i.CreatedAt,
|
|
&i.LastActiveAt,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const lockSessionMessages = `-- name: LockSessionMessages :exec
|
|
|
|
SELECT pg_advisory_xact_lock(hashtextextended('messages:' || $1::text, 0))
|
|
`
|
|
|
|
// ── Messages ────────────────────────────────────────────────────────────────
|
|
// Serialises message appends per session so the monotonic clamp's MAX(ts)
|
|
// read cannot race a concurrent append of the same session. Transaction-scoped:
|
|
// released at commit/rollback, which is exactly the lifetime of the append.
|
|
func (q *Queries) LockSessionMessages(ctx context.Context, dollar_1 string) error {
|
|
_, err := q.db.Exec(ctx, lockSessionMessages, dollar_1)
|
|
return err
|
|
}
|
|
|
|
const messageID = `-- name: MessageID :one
|
|
SELECT message_id FROM messages WHERE session_id = $1 AND message_id = $2
|
|
`
|
|
|
|
type MessageIDParams struct {
|
|
SessionID string
|
|
MessageID string
|
|
}
|
|
|
|
func (q *Queries) MessageID(ctx context.Context, arg MessageIDParams) (string, error) {
|
|
row := q.db.QueryRow(ctx, messageID, arg.SessionID, arg.MessageID)
|
|
var message_id string
|
|
err := row.Scan(&message_id)
|
|
return message_id, err
|
|
}
|
|
|
|
const nextReplyAfterTs = `-- name: NextReplyAfterTs :one
|
|
SELECT sender, text FROM messages
|
|
WHERE session_id = $1 AND ts > $2 ORDER BY ts ASC LIMIT 1
|
|
`
|
|
|
|
type NextReplyAfterTsParams struct {
|
|
SessionID string
|
|
Ts int64
|
|
}
|
|
|
|
type NextReplyAfterTsRow struct {
|
|
Sender string
|
|
Text string
|
|
}
|
|
|
|
func (q *Queries) NextReplyAfterTs(ctx context.Context, arg NextReplyAfterTsParams) (NextReplyAfterTsRow, error) {
|
|
row := q.db.QueryRow(ctx, nextReplyAfterTs, arg.SessionID, arg.Ts)
|
|
var i NextReplyAfterTsRow
|
|
err := row.Scan(&i.Sender, &i.Text)
|
|
return i, err
|
|
}
|
|
|
|
const recentMessages = `-- name: RecentMessages :many
|
|
SELECT m.message_id, m.source_id, m.sender, m.sender_id, m.role, m.text, m.ts,
|
|
COALESCE(s.channel_id, '') AS channel_id, COALESCE(s.thread_id, '') AS thread_id
|
|
FROM (
|
|
SELECT msg.message_id, msg.source_id, msg.sender, msg.sender_id, msg.role, msg.text, msg.ts, msg.session_id
|
|
FROM messages msg WHERE msg.session_id = $1 ORDER BY msg.ts DESC LIMIT $2
|
|
) m
|
|
LEFT JOIN sessions s ON s.session_id = m.session_id
|
|
ORDER BY m.ts ASC
|
|
`
|
|
|
|
type RecentMessagesParams struct {
|
|
SessionID string
|
|
Limit int32
|
|
}
|
|
|
|
type RecentMessagesRow struct {
|
|
MessageID string
|
|
SourceID string
|
|
Sender string
|
|
SenderID string
|
|
Role string
|
|
Text string
|
|
Ts int64
|
|
ChannelID string
|
|
ThreadID string
|
|
}
|
|
|
|
func (q *Queries) RecentMessages(ctx context.Context, arg RecentMessagesParams) ([]RecentMessagesRow, error) {
|
|
rows, err := q.db.Query(ctx, recentMessages, arg.SessionID, arg.Limit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var items []RecentMessagesRow
|
|
for rows.Next() {
|
|
var i RecentMessagesRow
|
|
if err := rows.Scan(
|
|
&i.MessageID,
|
|
&i.SourceID,
|
|
&i.Sender,
|
|
&i.SenderID,
|
|
&i.Role,
|
|
&i.Text,
|
|
&i.Ts,
|
|
&i.ChannelID,
|
|
&i.ThreadID,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const recentTurns = `-- name: RecentTurns :many
|
|
SELECT turn_id, session_id, source_id, status, attempt, owner_id,
|
|
input_message_id, assistant_message_id, partial_text,
|
|
response_text, tool_calls, error, created_at, updated_at
|
|
FROM turns WHERE session_id = $1 ORDER BY created_at DESC LIMIT $2
|
|
`
|
|
|
|
type RecentTurnsParams struct {
|
|
SessionID string
|
|
Limit int32
|
|
}
|
|
|
|
func (q *Queries) RecentTurns(ctx context.Context, arg RecentTurnsParams) ([]Turn, error) {
|
|
rows, err := q.db.Query(ctx, recentTurns, arg.SessionID, arg.Limit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var items []Turn
|
|
for rows.Next() {
|
|
var i Turn
|
|
if err := rows.Scan(
|
|
&i.TurnID,
|
|
&i.SessionID,
|
|
&i.SourceID,
|
|
&i.Status,
|
|
&i.Attempt,
|
|
&i.OwnerID,
|
|
&i.InputMessageID,
|
|
&i.AssistantMessageID,
|
|
&i.PartialText,
|
|
&i.ResponseText,
|
|
&i.ToolCalls,
|
|
&i.Error,
|
|
&i.CreatedAt,
|
|
&i.UpdatedAt,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const recoverTurns = `-- name: RecoverTurns :exec
|
|
UPDATE turns SET status = 'failed', error = 'recovered after process restart', updated_at = $1
|
|
WHERE status IN ('accepted', 'running', 'partial') AND owner_id <> $2
|
|
`
|
|
|
|
type RecoverTurnsParams struct {
|
|
UpdatedAt int64
|
|
OwnerID string
|
|
}
|
|
|
|
func (q *Queries) RecoverTurns(ctx context.Context, arg RecoverTurnsParams) error {
|
|
_, err := q.db.Exec(ctx, recoverTurns, arg.UpdatedAt, arg.OwnerID)
|
|
return err
|
|
}
|
|
|
|
const retryTurn = `-- name: RetryTurn :execrows
|
|
UPDATE turns SET status = $2, attempt = $3, owner_id = $4, error = $5, updated_at = $6
|
|
WHERE turn_id = $1 AND attempt = $7 AND owner_id = $8
|
|
`
|
|
|
|
type RetryTurnParams struct {
|
|
TurnID string
|
|
Status string
|
|
Attempt int64
|
|
OwnerID string
|
|
Error string
|
|
UpdatedAt int64
|
|
Attempt_2 int64
|
|
OwnerID_2 string
|
|
}
|
|
|
|
func (q *Queries) RetryTurn(ctx context.Context, arg RetryTurnParams) (int64, error) {
|
|
result, err := q.db.Exec(ctx, retryTurn,
|
|
arg.TurnID,
|
|
arg.Status,
|
|
arg.Attempt,
|
|
arg.OwnerID,
|
|
arg.Error,
|
|
arg.UpdatedAt,
|
|
arg.Attempt_2,
|
|
arg.OwnerID_2,
|
|
)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return result.RowsAffected(), nil
|
|
}
|
|
|
|
const saveSession = `-- name: SaveSession :exec
|
|
|
|
|
|
INSERT INTO sessions (session_id, platform, bot_user, channel_id, thread_id,
|
|
title, parent_session_id, branch_name, created_at, last_active_at)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
|
ON CONFLICT (session_id) DO UPDATE SET
|
|
platform = EXCLUDED.platform,
|
|
bot_user = EXCLUDED.bot_user,
|
|
channel_id = EXCLUDED.channel_id,
|
|
thread_id = EXCLUDED.thread_id,
|
|
title = EXCLUDED.title,
|
|
parent_session_id = EXCLUDED.parent_session_id,
|
|
branch_name = EXCLUDED.branch_name,
|
|
created_at = EXCLUDED.created_at,
|
|
last_active_at = EXCLUDED.last_active_at
|
|
`
|
|
|
|
type SaveSessionParams struct {
|
|
SessionID string
|
|
Platform string
|
|
BotUser string
|
|
ChannelID string
|
|
ThreadID string
|
|
Title string
|
|
ParentSessionID string
|
|
BranchName string
|
|
CreatedAt int64
|
|
LastActiveAt int64
|
|
}
|
|
|
|
// Gateway conversation queries: sessions, messages, turns, full-text search.
|
|
// These back internal/gateway's PostgreSQL SessionStore.
|
|
// ── Sessions ────────────────────────────────────────────────────────────────
|
|
func (q *Queries) SaveSession(ctx context.Context, arg SaveSessionParams) error {
|
|
_, err := q.db.Exec(ctx, saveSession,
|
|
arg.SessionID,
|
|
arg.Platform,
|
|
arg.BotUser,
|
|
arg.ChannelID,
|
|
arg.ThreadID,
|
|
arg.Title,
|
|
arg.ParentSessionID,
|
|
arg.BranchName,
|
|
arg.CreatedAt,
|
|
arg.LastActiveAt,
|
|
)
|
|
return err
|
|
}
|
|
|
|
const saveTurn = `-- name: SaveTurn :execrows
|
|
UPDATE turns SET
|
|
session_id = $2, source_id = $3, status = $4, attempt = $5, owner_id = $6,
|
|
input_message_id = $7, assistant_message_id = $8, partial_text = $9,
|
|
response_text = $10, tool_calls = $11, error = $12, created_at = $13, updated_at = $14
|
|
WHERE turn_id = $1 AND attempt = $5 AND owner_id = $6
|
|
`
|
|
|
|
type SaveTurnParams struct {
|
|
TurnID string
|
|
SessionID string
|
|
SourceID string
|
|
Status string
|
|
Attempt int64
|
|
OwnerID string
|
|
InputMessageID string
|
|
AssistantMessageID string
|
|
PartialText string
|
|
ResponseText string
|
|
ToolCalls string
|
|
Error string
|
|
CreatedAt int64
|
|
UpdatedAt int64
|
|
}
|
|
|
|
func (q *Queries) SaveTurn(ctx context.Context, arg SaveTurnParams) (int64, error) {
|
|
result, err := q.db.Exec(ctx, saveTurn,
|
|
arg.TurnID,
|
|
arg.SessionID,
|
|
arg.SourceID,
|
|
arg.Status,
|
|
arg.Attempt,
|
|
arg.OwnerID,
|
|
arg.InputMessageID,
|
|
arg.AssistantMessageID,
|
|
arg.PartialText,
|
|
arg.ResponseText,
|
|
arg.ToolCalls,
|
|
arg.Error,
|
|
arg.CreatedAt,
|
|
arg.UpdatedAt,
|
|
)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return result.RowsAffected(), nil
|
|
}
|
|
|
|
const searchMessagesCount = `-- name: SearchMessagesCount :one
|
|
SELECT COUNT(*) FROM messages
|
|
WHERE session_id = $1 AND search @@ plainto_tsquery('simple', $2)
|
|
`
|
|
|
|
type SearchMessagesCountParams struct {
|
|
SessionID string
|
|
PlaintoTsquery string
|
|
}
|
|
|
|
func (q *Queries) SearchMessagesCount(ctx context.Context, arg SearchMessagesCountParams) (int64, error) {
|
|
row := q.db.QueryRow(ctx, searchMessagesCount, arg.SessionID, arg.PlaintoTsquery)
|
|
var count int64
|
|
err := row.Scan(&count)
|
|
return count, err
|
|
}
|
|
|
|
const searchMessagesPage = `-- name: SearchMessagesPage :many
|
|
SELECT m.message_id, m.source_id, m.sender, m.sender_id, m.role, m.text, m.ts,
|
|
COALESCE(s.channel_id, '') AS channel_id, COALESCE(s.thread_id, '') AS thread_id
|
|
FROM messages m
|
|
LEFT JOIN sessions s ON s.session_id = m.session_id
|
|
WHERE m.session_id = $1 AND m.search @@ plainto_tsquery('simple', $2)
|
|
ORDER BY ts_rank(m.search, plainto_tsquery('simple', $2)) DESC, m.ts DESC, m.id DESC
|
|
LIMIT $3 OFFSET $4
|
|
`
|
|
|
|
type SearchMessagesPageParams struct {
|
|
SessionID string
|
|
PlaintoTsquery string
|
|
Limit int32
|
|
Offset int32
|
|
}
|
|
|
|
type SearchMessagesPageRow struct {
|
|
MessageID string
|
|
SourceID string
|
|
Sender string
|
|
SenderID string
|
|
Role string
|
|
Text string
|
|
Ts int64
|
|
ChannelID string
|
|
ThreadID string
|
|
}
|
|
|
|
func (q *Queries) SearchMessagesPage(ctx context.Context, arg SearchMessagesPageParams) ([]SearchMessagesPageRow, error) {
|
|
rows, err := q.db.Query(ctx, searchMessagesPage,
|
|
arg.SessionID,
|
|
arg.PlaintoTsquery,
|
|
arg.Limit,
|
|
arg.Offset,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var items []SearchMessagesPageRow
|
|
for rows.Next() {
|
|
var i SearchMessagesPageRow
|
|
if err := rows.Scan(
|
|
&i.MessageID,
|
|
&i.SourceID,
|
|
&i.Sender,
|
|
&i.SenderID,
|
|
&i.Role,
|
|
&i.Text,
|
|
&i.Ts,
|
|
&i.ChannelID,
|
|
&i.ThreadID,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const sessionByID = `-- name: SessionByID :one
|
|
SELECT session_id, platform, bot_user, channel_id, thread_id,
|
|
title, parent_session_id, branch_name, created_at, last_active_at
|
|
FROM sessions WHERE session_id = $1
|
|
`
|
|
|
|
func (q *Queries) SessionByID(ctx context.Context, sessionID string) (Session, error) {
|
|
row := q.db.QueryRow(ctx, sessionByID, sessionID)
|
|
var i Session
|
|
err := row.Scan(
|
|
&i.SessionID,
|
|
&i.Platform,
|
|
&i.BotUser,
|
|
&i.ChannelID,
|
|
&i.ThreadID,
|
|
&i.Title,
|
|
&i.ParentSessionID,
|
|
&i.BranchName,
|
|
&i.CreatedAt,
|
|
&i.LastActiveAt,
|
|
)
|
|
return i, err
|
|
}
|
|
|
|
const sessionsByChannel = `-- name: SessionsByChannel :many
|
|
SELECT session_id, platform, bot_user, channel_id, thread_id,
|
|
title, parent_session_id, branch_name, created_at, last_active_at
|
|
FROM sessions
|
|
WHERE platform = $1 AND channel_id = $2
|
|
ORDER BY GREATEST(last_active_at, created_at) DESC
|
|
`
|
|
|
|
type SessionsByChannelParams struct {
|
|
Platform string
|
|
ChannelID string
|
|
}
|
|
|
|
func (q *Queries) SessionsByChannel(ctx context.Context, arg SessionsByChannelParams) ([]Session, error) {
|
|
rows, err := q.db.Query(ctx, sessionsByChannel, arg.Platform, arg.ChannelID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var items []Session
|
|
for rows.Next() {
|
|
var i Session
|
|
if err := rows.Scan(
|
|
&i.SessionID,
|
|
&i.Platform,
|
|
&i.BotUser,
|
|
&i.ChannelID,
|
|
&i.ThreadID,
|
|
&i.Title,
|
|
&i.ParentSessionID,
|
|
&i.BranchName,
|
|
&i.CreatedAt,
|
|
&i.LastActiveAt,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const sourceMessageTs = `-- name: SourceMessageTs :one
|
|
SELECT ts FROM messages
|
|
WHERE session_id = $1 AND message_id IN ($2, $3)
|
|
ORDER BY CASE WHEN message_id = $3 THEN 0 ELSE 1 END
|
|
LIMIT 1
|
|
`
|
|
|
|
type SourceMessageTsParams struct {
|
|
SessionID string
|
|
MessageID string
|
|
MessageID_2 string
|
|
}
|
|
|
|
func (q *Queries) SourceMessageTs(ctx context.Context, arg SourceMessageTsParams) (int64, error) {
|
|
row := q.db.QueryRow(ctx, sourceMessageTs, arg.SessionID, arg.MessageID, arg.MessageID_2)
|
|
var ts int64
|
|
err := row.Scan(&ts)
|
|
return ts, err
|
|
}
|
|
|
|
const touchSession = `-- name: TouchSession :exec
|
|
UPDATE sessions SET last_active_at = $2 WHERE session_id = $1
|
|
`
|
|
|
|
type TouchSessionParams struct {
|
|
SessionID string
|
|
LastActiveAt int64
|
|
}
|
|
|
|
func (q *Queries) TouchSession(ctx context.Context, arg TouchSessionParams) error {
|
|
_, err := q.db.Exec(ctx, touchSession, arg.SessionID, arg.LastActiveAt)
|
|
return err
|
|
}
|
|
|
|
const turnAttemptOwner = `-- name: TurnAttemptOwner :one
|
|
SELECT attempt, owner_id FROM turns WHERE turn_id = $1
|
|
`
|
|
|
|
type TurnAttemptOwnerRow struct {
|
|
Attempt int64
|
|
OwnerID string
|
|
}
|
|
|
|
func (q *Queries) TurnAttemptOwner(ctx context.Context, turnID string) (TurnAttemptOwnerRow, error) {
|
|
row := q.db.QueryRow(ctx, turnAttemptOwner, turnID)
|
|
var i TurnAttemptOwnerRow
|
|
err := row.Scan(&i.Attempt, &i.OwnerID)
|
|
return i, err
|
|
}
|
|
|
|
const turnByID = `-- name: TurnByID :one
|
|
SELECT turn_id, session_id, source_id, status, attempt, owner_id,
|
|
input_message_id, assistant_message_id, partial_text,
|
|
response_text, tool_calls, error, created_at, updated_at
|
|
FROM turns WHERE turn_id = $1
|
|
`
|
|
|
|
func (q *Queries) TurnByID(ctx context.Context, turnID string) (Turn, error) {
|
|
row := q.db.QueryRow(ctx, turnByID, turnID)
|
|
var i Turn
|
|
err := row.Scan(
|
|
&i.TurnID,
|
|
&i.SessionID,
|
|
&i.SourceID,
|
|
&i.Status,
|
|
&i.Attempt,
|
|
&i.OwnerID,
|
|
&i.InputMessageID,
|
|
&i.AssistantMessageID,
|
|
&i.PartialText,
|
|
&i.ResponseText,
|
|
&i.ToolCalls,
|
|
&i.Error,
|
|
&i.CreatedAt,
|
|
&i.UpdatedAt,
|
|
)
|
|
return i, err
|
|
}
|