fix: golangci-lint v2 config and lint-clean production code
- Fix .golangci.yml for v2 format (linters-settings -> linters.settings) - All production code now passes golangci-lint with zero issues - Line length 88, funlen 80/50, cyclop 15, dupl 100 - Extract shared helpers in db (scanChannels, scanInt64s, scanMessages) - Split runMigrations into applyMigration/execMigration - Fix fanOut return signature (remove unused int64) - Add fanOutSilent helper to avoid dogsled - Rewrite CLI code for lint compliance (nlreturn, wsl_v5, noctx, etc) - Rename CLI api package to chatapi to avoid revive var-naming - Fix all noinlineerr, mnd, perfsprint, funcorder issues - Fix db tests: extract helpers, add t.Parallel, proper error checks - Broker tests already clean - Handler integration tests still have lint issues (next commit)
This commit is contained in:
@@ -16,13 +16,11 @@ import (
|
||||
"git.eeqj.de/sneak/chat/internal/logger"
|
||||
"go.uber.org/fx"
|
||||
|
||||
_ "github.com/joho/godotenv/autoload" // loads .env file
|
||||
_ "modernc.org/sqlite" // SQLite driver
|
||||
_ "github.com/joho/godotenv/autoload" // .env
|
||||
_ "modernc.org/sqlite" // driver
|
||||
)
|
||||
|
||||
const (
|
||||
minMigrationParts = 2
|
||||
)
|
||||
const minMigrationParts = 2
|
||||
|
||||
// SchemaFiles contains embedded SQL migration files.
|
||||
//
|
||||
@@ -37,15 +35,18 @@ type Params struct {
|
||||
Config *config.Config
|
||||
}
|
||||
|
||||
// Database manages the SQLite database connection and migrations.
|
||||
// Database manages the SQLite connection and migrations.
|
||||
type Database struct {
|
||||
db *sql.DB
|
||||
log *slog.Logger
|
||||
params *Params
|
||||
}
|
||||
|
||||
// New creates a new Database instance and registers lifecycle hooks.
|
||||
func New(lc fx.Lifecycle, params Params) (*Database, error) {
|
||||
// New creates a new Database and registers lifecycle hooks.
|
||||
func New(
|
||||
lc fx.Lifecycle,
|
||||
params Params,
|
||||
) (*Database, error) {
|
||||
s := new(Database)
|
||||
s.params = ¶ms
|
||||
s.log = params.Logger.Get()
|
||||
@@ -55,13 +56,16 @@ func New(lc fx.Lifecycle, params Params) (*Database, error) {
|
||||
lc.Append(fx.Hook{
|
||||
OnStart: func(ctx context.Context) error {
|
||||
s.log.Info("Database OnStart Hook")
|
||||
|
||||
return s.connect(ctx)
|
||||
},
|
||||
OnStop: func(_ context.Context) error {
|
||||
s.log.Info("Database OnStop Hook")
|
||||
|
||||
if s.db != nil {
|
||||
return s.db.Close()
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
})
|
||||
@@ -84,20 +88,29 @@ func (s *Database) connect(ctx context.Context) error {
|
||||
|
||||
d, err := sql.Open("sqlite", dbURL)
|
||||
if err != nil {
|
||||
s.log.Error("failed to open database", "error", err)
|
||||
s.log.Error(
|
||||
"failed to open database", "error", err,
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
err = d.PingContext(ctx)
|
||||
if err != nil {
|
||||
s.log.Error("failed to ping database", "error", err)
|
||||
s.log.Error(
|
||||
"failed to ping database", "error", err,
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
s.db = d
|
||||
s.log.Info("database connected")
|
||||
|
||||
if _, err := s.db.ExecContext(ctx, "PRAGMA foreign_keys = ON"); err != nil {
|
||||
_, err = s.db.ExecContext(
|
||||
ctx, "PRAGMA foreign_keys = ON",
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("enable foreign keys: %w", err)
|
||||
}
|
||||
|
||||
@@ -110,14 +123,17 @@ type migration struct {
|
||||
sql string
|
||||
}
|
||||
|
||||
func (s *Database) runMigrations(ctx context.Context) error {
|
||||
func (s *Database) runMigrations(
|
||||
ctx context.Context,
|
||||
) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version INTEGER PRIMARY KEY,
|
||||
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`)
|
||||
version INTEGER PRIMARY KEY,
|
||||
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP)`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create schema_migrations table: %w", err)
|
||||
return fmt.Errorf(
|
||||
"create schema_migrations: %w", err,
|
||||
)
|
||||
}
|
||||
|
||||
migrations, err := s.loadMigrations()
|
||||
@@ -126,74 +142,125 @@ func (s *Database) runMigrations(ctx context.Context) error {
|
||||
}
|
||||
|
||||
for _, m := range migrations {
|
||||
var exists int
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
"SELECT COUNT(*) FROM schema_migrations WHERE version = ?",
|
||||
m.version,
|
||||
).Scan(&exists)
|
||||
err = s.applyMigration(ctx, m)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check migration %d: %w", m.version, err)
|
||||
}
|
||||
if exists > 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
s.log.Info("applying migration", "version", m.version, "name", m.name)
|
||||
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin tx for migration %d: %w", m.version, err)
|
||||
}
|
||||
|
||||
_, err = tx.ExecContext(ctx, m.sql)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
return fmt.Errorf("apply migration %d (%s): %w", m.version, m.name, err)
|
||||
}
|
||||
|
||||
_, err = tx.ExecContext(ctx,
|
||||
"INSERT INTO schema_migrations (version) VALUES (?)",
|
||||
m.version,
|
||||
)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
return fmt.Errorf("record migration %d: %w", m.version, err)
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("commit migration %d: %w", m.version, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
s.log.Info("database migrations complete")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Database) loadMigrations() ([]migration, error) {
|
||||
func (s *Database) applyMigration(
|
||||
ctx context.Context,
|
||||
m migration,
|
||||
) error {
|
||||
var exists int
|
||||
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT COUNT(*) FROM schema_migrations
|
||||
WHERE version = ?`,
|
||||
m.version,
|
||||
).Scan(&exists)
|
||||
if err != nil {
|
||||
return fmt.Errorf(
|
||||
"check migration %d: %w", m.version, err,
|
||||
)
|
||||
}
|
||||
|
||||
if exists > 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
s.log.Info(
|
||||
"applying migration",
|
||||
"version", m.version,
|
||||
"name", m.name,
|
||||
)
|
||||
|
||||
return s.execMigration(ctx, m)
|
||||
}
|
||||
|
||||
func (s *Database) execMigration(
|
||||
ctx context.Context,
|
||||
m migration,
|
||||
) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf(
|
||||
"begin tx for migration %d: %w",
|
||||
m.version, err,
|
||||
)
|
||||
}
|
||||
|
||||
_, err = tx.ExecContext(ctx, m.sql)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
|
||||
return fmt.Errorf(
|
||||
"apply migration %d (%s): %w",
|
||||
m.version, m.name, err,
|
||||
)
|
||||
}
|
||||
|
||||
_, err = tx.ExecContext(ctx,
|
||||
`INSERT INTO schema_migrations (version)
|
||||
VALUES (?)`,
|
||||
m.version,
|
||||
)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
|
||||
return fmt.Errorf(
|
||||
"record migration %d: %w",
|
||||
m.version, err,
|
||||
)
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Database) loadMigrations() (
|
||||
[]migration,
|
||||
error,
|
||||
) {
|
||||
entries, err := fs.ReadDir(SchemaFiles, "schema")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read schema dir: %w", err)
|
||||
return nil, fmt.Errorf(
|
||||
"read schema dir: %w", err,
|
||||
)
|
||||
}
|
||||
|
||||
var migrations []migration
|
||||
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
|
||||
if entry.IsDir() ||
|
||||
!strings.HasSuffix(entry.Name(), ".sql") {
|
||||
continue
|
||||
}
|
||||
|
||||
parts := strings.SplitN(entry.Name(), "_", minMigrationParts)
|
||||
parts := strings.SplitN(
|
||||
entry.Name(), "_", minMigrationParts,
|
||||
)
|
||||
if len(parts) < minMigrationParts {
|
||||
continue
|
||||
}
|
||||
|
||||
version, err := strconv.Atoi(parts[0])
|
||||
if err != nil {
|
||||
version, parseErr := strconv.Atoi(parts[0])
|
||||
if parseErr != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
content, err := SchemaFiles.ReadFile("schema/" + entry.Name())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read migration %s: %w", entry.Name(), err)
|
||||
content, readErr := SchemaFiles.ReadFile(
|
||||
"schema/" + entry.Name(),
|
||||
)
|
||||
if readErr != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"read migration %s: %w",
|
||||
entry.Name(), readErr,
|
||||
)
|
||||
}
|
||||
|
||||
migrations = append(migrations, migration{
|
||||
|
||||
47
internal/db/export_test.go
Normal file
47
internal/db/export_test.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
//nolint:gochecknoglobals // test counter
|
||||
var testDBCounter atomic.Int64
|
||||
|
||||
// NewTestDatabase creates an in-memory database for testing.
|
||||
func NewTestDatabase() (*Database, error) {
|
||||
n := testDBCounter.Add(1)
|
||||
|
||||
dsn := fmt.Sprintf(
|
||||
"file:testdb%d?mode=memory"+
|
||||
"&cache=shared&_pragma=foreign_keys(1)",
|
||||
n,
|
||||
)
|
||||
|
||||
d, err := sql.Open("sqlite", dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
database := &Database{db: d, log: slog.Default()}
|
||||
|
||||
err = database.runMigrations(context.Background())
|
||||
if err != nil {
|
||||
closeErr := d.Close()
|
||||
if closeErr != nil {
|
||||
return nil, closeErr
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return database, nil
|
||||
}
|
||||
|
||||
// Close closes the underlying database connection.
|
||||
func (s *Database) Close() error {
|
||||
return s.db.Close()
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package db
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
@@ -11,13 +12,20 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
tokenBytes = 32
|
||||
defaultPollLimit = 100
|
||||
defaultHistLimit = 50
|
||||
)
|
||||
|
||||
func generateToken() string {
|
||||
b := make([]byte, 32)
|
||||
b := make([]byte, tokenBytes)
|
||||
_, _ = rand.Read(b)
|
||||
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// IRCMessage is the IRC envelope format for all messages.
|
||||
// IRCMessage is the IRC envelope for all messages.
|
||||
type IRCMessage struct {
|
||||
ID string `json:"id"`
|
||||
Command string `json:"command"`
|
||||
@@ -26,8 +34,7 @@ type IRCMessage struct {
|
||||
Body json.RawMessage `json:"body,omitempty"`
|
||||
TS string `json:"ts"`
|
||||
Meta json.RawMessage `json:"meta,omitempty"`
|
||||
// Internal DB fields (not in JSON)
|
||||
DBID int64 `json:"-"`
|
||||
DBID int64 `json:"-"`
|
||||
}
|
||||
|
||||
// ChannelInfo is a lightweight channel representation.
|
||||
@@ -45,352 +52,572 @@ type MemberInfo struct {
|
||||
}
|
||||
|
||||
// CreateUser registers a new user with the given nick.
|
||||
func (s *Database) CreateUser(ctx context.Context, nick string) (int64, string, error) {
|
||||
func (s *Database) CreateUser(
|
||||
ctx context.Context,
|
||||
nick string,
|
||||
) (int64, string, error) {
|
||||
token := generateToken()
|
||||
now := time.Now()
|
||||
|
||||
res, err := s.db.ExecContext(ctx,
|
||||
"INSERT INTO users (nick, token, created_at, last_seen) VALUES (?, ?, ?, ?)",
|
||||
`INSERT INTO users
|
||||
(nick, token, created_at, last_seen)
|
||||
VALUES (?, ?, ?, ?)`,
|
||||
nick, token, now, now)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
|
||||
id, _ := res.LastInsertId()
|
||||
|
||||
return id, token, nil
|
||||
}
|
||||
|
||||
// GetUserByToken returns user id and nick for a given auth token.
|
||||
func (s *Database) GetUserByToken(ctx context.Context, token string) (int64, string, error) {
|
||||
// GetUserByToken returns user id and nick for a token.
|
||||
func (s *Database) GetUserByToken(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) (int64, string, error) {
|
||||
var id int64
|
||||
|
||||
var nick string
|
||||
err := s.db.QueryRowContext(ctx, "SELECT id, nick FROM users WHERE token = ?", token).Scan(&id, &nick)
|
||||
|
||||
err := s.db.QueryRowContext(
|
||||
ctx,
|
||||
"SELECT id, nick FROM users WHERE token = ?",
|
||||
token,
|
||||
).Scan(&id, &nick)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
_, _ = s.db.ExecContext(ctx, "UPDATE users SET last_seen = ? WHERE id = ?", time.Now(), id)
|
||||
|
||||
_, _ = s.db.ExecContext(
|
||||
ctx,
|
||||
"UPDATE users SET last_seen = ? WHERE id = ?",
|
||||
time.Now(), id,
|
||||
)
|
||||
|
||||
return id, nick, nil
|
||||
}
|
||||
|
||||
// GetUserByNick returns user id for a given nick.
|
||||
func (s *Database) GetUserByNick(ctx context.Context, nick string) (int64, error) {
|
||||
func (s *Database) GetUserByNick(
|
||||
ctx context.Context,
|
||||
nick string,
|
||||
) (int64, error) {
|
||||
var id int64
|
||||
err := s.db.QueryRowContext(ctx, "SELECT id FROM users WHERE nick = ?", nick).Scan(&id)
|
||||
|
||||
err := s.db.QueryRowContext(
|
||||
ctx,
|
||||
"SELECT id FROM users WHERE nick = ?",
|
||||
nick,
|
||||
).Scan(&id)
|
||||
|
||||
return id, err
|
||||
}
|
||||
|
||||
// GetChannelByName returns the channel ID for a given name.
|
||||
func (s *Database) GetChannelByName(ctx context.Context, name string) (int64, error) {
|
||||
// GetChannelByName returns the channel ID for a name.
|
||||
func (s *Database) GetChannelByName(
|
||||
ctx context.Context,
|
||||
name string,
|
||||
) (int64, error) {
|
||||
var id int64
|
||||
err := s.db.QueryRowContext(ctx, "SELECT id FROM channels WHERE name = ?", name).Scan(&id)
|
||||
|
||||
err := s.db.QueryRowContext(
|
||||
ctx,
|
||||
"SELECT id FROM channels WHERE name = ?",
|
||||
name,
|
||||
).Scan(&id)
|
||||
|
||||
return id, err
|
||||
}
|
||||
|
||||
// GetOrCreateChannel returns the channel id, creating it if needed.
|
||||
func (s *Database) GetOrCreateChannel(ctx context.Context, name string) (int64, error) {
|
||||
// GetOrCreateChannel returns channel id, creating if needed.
|
||||
func (s *Database) GetOrCreateChannel(
|
||||
ctx context.Context,
|
||||
name string,
|
||||
) (int64, error) {
|
||||
var id int64
|
||||
err := s.db.QueryRowContext(ctx, "SELECT id FROM channels WHERE name = ?", name).Scan(&id)
|
||||
|
||||
err := s.db.QueryRowContext(
|
||||
ctx,
|
||||
"SELECT id FROM channels WHERE name = ?",
|
||||
name,
|
||||
).Scan(&id)
|
||||
if err == nil {
|
||||
return id, nil
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
|
||||
res, err := s.db.ExecContext(ctx,
|
||||
"INSERT INTO channels (name, created_at, updated_at) VALUES (?, ?, ?)",
|
||||
`INSERT INTO channels
|
||||
(name, created_at, updated_at)
|
||||
VALUES (?, ?, ?)`,
|
||||
name, now, now)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("create channel: %w", err)
|
||||
}
|
||||
|
||||
id, _ = res.LastInsertId()
|
||||
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// JoinChannel adds a user to a channel.
|
||||
func (s *Database) JoinChannel(ctx context.Context, channelID, userID int64) error {
|
||||
func (s *Database) JoinChannel(
|
||||
ctx context.Context,
|
||||
channelID, userID int64,
|
||||
) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
"INSERT OR IGNORE INTO channel_members (channel_id, user_id, joined_at) VALUES (?, ?, ?)",
|
||||
`INSERT OR IGNORE INTO channel_members
|
||||
(channel_id, user_id, joined_at)
|
||||
VALUES (?, ?, ?)`,
|
||||
channelID, userID, time.Now())
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// PartChannel removes a user from a channel.
|
||||
func (s *Database) PartChannel(ctx context.Context, channelID, userID int64) error {
|
||||
func (s *Database) PartChannel(
|
||||
ctx context.Context,
|
||||
channelID, userID int64,
|
||||
) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
"DELETE FROM channel_members WHERE channel_id = ? AND user_id = ?",
|
||||
`DELETE FROM channel_members
|
||||
WHERE channel_id = ? AND user_id = ?`,
|
||||
channelID, userID)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteChannelIfEmpty deletes a channel if it has no members.
|
||||
func (s *Database) DeleteChannelIfEmpty(ctx context.Context, channelID int64) error {
|
||||
// DeleteChannelIfEmpty removes a channel with no members.
|
||||
func (s *Database) DeleteChannelIfEmpty(
|
||||
ctx context.Context,
|
||||
channelID int64,
|
||||
) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`DELETE FROM channels WHERE id = ? AND NOT EXISTS
|
||||
(SELECT 1 FROM channel_members WHERE channel_id = ?)`,
|
||||
`DELETE FROM channels WHERE id = ?
|
||||
AND NOT EXISTS
|
||||
(SELECT 1 FROM channel_members
|
||||
WHERE channel_id = ?)`,
|
||||
channelID, channelID)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ListChannels returns all channels the user has joined.
|
||||
func (s *Database) ListChannels(ctx context.Context, userID int64) ([]ChannelInfo, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT c.id, c.name, c.topic FROM channels c
|
||||
INNER JOIN channel_members cm ON cm.channel_id = c.id
|
||||
WHERE cm.user_id = ? ORDER BY c.name`, userID)
|
||||
// scanChannels scans rows into a ChannelInfo slice.
|
||||
func scanChannels(
|
||||
rows *sql.Rows,
|
||||
) ([]ChannelInfo, error) {
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var out []ChannelInfo
|
||||
|
||||
for rows.Next() {
|
||||
var ch ChannelInfo
|
||||
|
||||
err := rows.Scan(&ch.ID, &ch.Name, &ch.Topic)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
out = append(out, ch)
|
||||
}
|
||||
|
||||
err := rows.Err()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var channels []ChannelInfo
|
||||
for rows.Next() {
|
||||
var ch ChannelInfo
|
||||
if err := rows.Scan(&ch.ID, &ch.Name, &ch.Topic); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channels = append(channels, ch)
|
||||
|
||||
if out == nil {
|
||||
out = []ChannelInfo{}
|
||||
}
|
||||
if channels == nil {
|
||||
channels = []ChannelInfo{}
|
||||
}
|
||||
return channels, nil
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ListAllChannels returns all channels.
|
||||
func (s *Database) ListAllChannels(ctx context.Context) ([]ChannelInfo, error) {
|
||||
// ListChannels returns channels the user has joined.
|
||||
func (s *Database) ListChannels(
|
||||
ctx context.Context,
|
||||
userID int64,
|
||||
) ([]ChannelInfo, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
"SELECT id, name, topic FROM channels ORDER BY name")
|
||||
`SELECT c.id, c.name, c.topic
|
||||
FROM channels c
|
||||
INNER JOIN channel_members cm
|
||||
ON cm.channel_id = c.id
|
||||
WHERE cm.user_id = ?
|
||||
ORDER BY c.name`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var channels []ChannelInfo
|
||||
for rows.Next() {
|
||||
var ch ChannelInfo
|
||||
if err := rows.Scan(&ch.ID, &ch.Name, &ch.Topic); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channels = append(channels, ch)
|
||||
|
||||
return scanChannels(rows)
|
||||
}
|
||||
|
||||
// ListAllChannels returns every channel.
|
||||
func (s *Database) ListAllChannels(
|
||||
ctx context.Context,
|
||||
) ([]ChannelInfo, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT id, name, topic
|
||||
FROM channels ORDER BY name`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if channels == nil {
|
||||
channels = []ChannelInfo{}
|
||||
}
|
||||
return channels, nil
|
||||
|
||||
return scanChannels(rows)
|
||||
}
|
||||
|
||||
// ChannelMembers returns all members of a channel.
|
||||
func (s *Database) ChannelMembers(ctx context.Context, channelID int64) ([]MemberInfo, error) {
|
||||
func (s *Database) ChannelMembers(
|
||||
ctx context.Context,
|
||||
channelID int64,
|
||||
) ([]MemberInfo, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT u.id, u.nick, u.last_seen FROM users u
|
||||
INNER JOIN channel_members cm ON cm.user_id = u.id
|
||||
WHERE cm.channel_id = ? ORDER BY u.nick`, channelID)
|
||||
`SELECT u.id, u.nick, u.last_seen
|
||||
FROM users u
|
||||
INNER JOIN channel_members cm
|
||||
ON cm.user_id = u.id
|
||||
WHERE cm.channel_id = ?
|
||||
ORDER BY u.nick`, channelID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var members []MemberInfo
|
||||
|
||||
for rows.Next() {
|
||||
var m MemberInfo
|
||||
if err := rows.Scan(&m.ID, &m.Nick, &m.LastSeen); err != nil {
|
||||
|
||||
err = rows.Scan(&m.ID, &m.Nick, &m.LastSeen)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
members = append(members, m)
|
||||
}
|
||||
|
||||
err = rows.Err()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if members == nil {
|
||||
members = []MemberInfo{}
|
||||
}
|
||||
|
||||
return members, nil
|
||||
}
|
||||
|
||||
// GetChannelMemberIDs returns user IDs of all members in a channel.
|
||||
func (s *Database) GetChannelMemberIDs(ctx context.Context, channelID int64) ([]int64, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
"SELECT user_id FROM channel_members WHERE channel_id = ?", channelID)
|
||||
// scanInt64s scans rows into an int64 slice.
|
||||
func scanInt64s(rows *sql.Rows) ([]int64, error) {
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var ids []int64
|
||||
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
|
||||
err := rows.Scan(&id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ids = append(ids, id)
|
||||
}
|
||||
|
||||
err := rows.Err()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var ids []int64
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// GetUserChannelIDs returns channel IDs the user is a member of.
|
||||
func (s *Database) GetUserChannelIDs(ctx context.Context, userID int64) ([]int64, error) {
|
||||
// GetChannelMemberIDs returns user IDs in a channel.
|
||||
func (s *Database) GetChannelMemberIDs(
|
||||
ctx context.Context,
|
||||
channelID int64,
|
||||
) ([]int64, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
"SELECT channel_id FROM channel_members WHERE user_id = ?", userID)
|
||||
`SELECT user_id FROM channel_members
|
||||
WHERE channel_id = ?`, channelID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var ids []int64
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
|
||||
return scanInt64s(rows)
|
||||
}
|
||||
|
||||
// GetUserChannelIDs returns channel IDs the user is in.
|
||||
func (s *Database) GetUserChannelIDs(
|
||||
ctx context.Context,
|
||||
userID int64,
|
||||
) ([]int64, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT channel_id FROM channel_members
|
||||
WHERE user_id = ?`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
|
||||
return scanInt64s(rows)
|
||||
}
|
||||
|
||||
// InsertMessage stores a message and returns its DB ID.
|
||||
func (s *Database) InsertMessage(ctx context.Context, command, from, to string, body json.RawMessage, meta json.RawMessage) (int64, string, error) {
|
||||
func (s *Database) InsertMessage(
|
||||
ctx context.Context,
|
||||
command, from, to string,
|
||||
body json.RawMessage,
|
||||
meta json.RawMessage,
|
||||
) (int64, string, error) {
|
||||
msgUUID := uuid.New().String()
|
||||
now := time.Now().UTC()
|
||||
|
||||
if body == nil {
|
||||
body = json.RawMessage("[]")
|
||||
}
|
||||
|
||||
if meta == nil {
|
||||
meta = json.RawMessage("{}")
|
||||
}
|
||||
|
||||
res, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO messages (uuid, command, msg_from, msg_to, body, meta, created_at)
|
||||
`INSERT INTO messages
|
||||
(uuid, command, msg_from, msg_to,
|
||||
body, meta, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
msgUUID, command, from, to, string(body), string(meta), now)
|
||||
msgUUID, command, from, to,
|
||||
string(body), string(meta), now)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
|
||||
id, _ := res.LastInsertId()
|
||||
|
||||
return id, msgUUID, nil
|
||||
}
|
||||
|
||||
// EnqueueMessage adds a message to a user's delivery queue.
|
||||
func (s *Database) EnqueueMessage(ctx context.Context, userID, messageID int64) error {
|
||||
// EnqueueMessage adds a message to a user's queue.
|
||||
func (s *Database) EnqueueMessage(
|
||||
ctx context.Context,
|
||||
userID, messageID int64,
|
||||
) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
"INSERT OR IGNORE INTO client_queues (user_id, message_id, created_at) VALUES (?, ?, ?)",
|
||||
`INSERT OR IGNORE INTO client_queues
|
||||
(user_id, message_id, created_at)
|
||||
VALUES (?, ?, ?)`,
|
||||
userID, messageID, time.Now())
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// PollMessages returns queued messages for a user after a given queue ID.
|
||||
func (s *Database) PollMessages(ctx context.Context, userID int64, afterQueueID int64, limit int) ([]IRCMessage, int64, error) {
|
||||
// PollMessages returns queued messages for a user.
|
||||
func (s *Database) PollMessages(
|
||||
ctx context.Context,
|
||||
userID, afterQueueID int64,
|
||||
limit int,
|
||||
) ([]IRCMessage, int64, error) {
|
||||
if limit <= 0 {
|
||||
limit = 100
|
||||
limit = defaultPollLimit
|
||||
}
|
||||
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT cq.id, m.uuid, m.command, m.msg_from, m.msg_to, m.body, m.meta, m.created_at
|
||||
`SELECT cq.id, m.uuid, m.command,
|
||||
m.msg_from, m.msg_to,
|
||||
m.body, m.meta, m.created_at
|
||||
FROM client_queues cq
|
||||
INNER JOIN messages m ON m.id = cq.message_id
|
||||
INNER JOIN messages m
|
||||
ON m.id = cq.message_id
|
||||
WHERE cq.user_id = ? AND cq.id > ?
|
||||
ORDER BY cq.id ASC LIMIT ?`, userID, afterQueueID, limit)
|
||||
ORDER BY cq.id ASC LIMIT ?`,
|
||||
userID, afterQueueID, limit)
|
||||
if err != nil {
|
||||
return nil, afterQueueID, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
msgs, lastQID, scanErr := scanMessages(
|
||||
rows, afterQueueID,
|
||||
)
|
||||
if scanErr != nil {
|
||||
return nil, afterQueueID, scanErr
|
||||
}
|
||||
|
||||
return msgs, lastQID, nil
|
||||
}
|
||||
|
||||
// GetHistory returns message history for a target.
|
||||
func (s *Database) GetHistory(
|
||||
ctx context.Context,
|
||||
target string,
|
||||
beforeID int64,
|
||||
limit int,
|
||||
) ([]IRCMessage, error) {
|
||||
if limit <= 0 {
|
||||
limit = defaultHistLimit
|
||||
}
|
||||
|
||||
rows, err := s.queryHistory(
|
||||
ctx, target, beforeID, limit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgs, _, scanErr := scanMessages(rows, 0)
|
||||
if scanErr != nil {
|
||||
return nil, scanErr
|
||||
}
|
||||
|
||||
if msgs == nil {
|
||||
msgs = []IRCMessage{}
|
||||
}
|
||||
|
||||
reverseMessages(msgs)
|
||||
|
||||
return msgs, nil
|
||||
}
|
||||
|
||||
func (s *Database) queryHistory(
|
||||
ctx context.Context,
|
||||
target string,
|
||||
beforeID int64,
|
||||
limit int,
|
||||
) (*sql.Rows, error) {
|
||||
if beforeID > 0 {
|
||||
return s.db.QueryContext(ctx,
|
||||
`SELECT id, uuid, command, msg_from,
|
||||
msg_to, body, meta, created_at
|
||||
FROM messages
|
||||
WHERE msg_to = ? AND id < ?
|
||||
AND command = 'PRIVMSG'
|
||||
ORDER BY id DESC LIMIT ?`,
|
||||
target, beforeID, limit)
|
||||
}
|
||||
|
||||
return s.db.QueryContext(ctx,
|
||||
`SELECT id, uuid, command, msg_from,
|
||||
msg_to, body, meta, created_at
|
||||
FROM messages
|
||||
WHERE msg_to = ?
|
||||
AND command = 'PRIVMSG'
|
||||
ORDER BY id DESC LIMIT ?`,
|
||||
target, limit)
|
||||
}
|
||||
|
||||
func scanMessages(
|
||||
rows *sql.Rows,
|
||||
fallbackQID int64,
|
||||
) ([]IRCMessage, int64, error) {
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var msgs []IRCMessage
|
||||
var lastQID int64
|
||||
|
||||
lastQID := fallbackQID
|
||||
|
||||
for rows.Next() {
|
||||
var m IRCMessage
|
||||
var qID int64
|
||||
var body, meta string
|
||||
var ts time.Time
|
||||
if err := rows.Scan(&qID, &m.ID, &m.Command, &m.From, &m.To, &body, &meta, &ts); err != nil {
|
||||
return nil, afterQueueID, err
|
||||
var (
|
||||
m IRCMessage
|
||||
qID int64
|
||||
body, meta string
|
||||
ts time.Time
|
||||
)
|
||||
|
||||
err := rows.Scan(
|
||||
&qID, &m.ID, &m.Command,
|
||||
&m.From, &m.To,
|
||||
&body, &meta, &ts,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fallbackQID, err
|
||||
}
|
||||
|
||||
m.Body = json.RawMessage(body)
|
||||
m.Meta = json.RawMessage(meta)
|
||||
m.TS = ts.Format(time.RFC3339Nano)
|
||||
m.DBID = qID
|
||||
lastQID = qID
|
||||
|
||||
msgs = append(msgs, m)
|
||||
}
|
||||
|
||||
err := rows.Err()
|
||||
if err != nil {
|
||||
return nil, fallbackQID, err
|
||||
}
|
||||
|
||||
if msgs == nil {
|
||||
msgs = []IRCMessage{}
|
||||
}
|
||||
if lastQID == 0 {
|
||||
lastQID = afterQueueID
|
||||
}
|
||||
|
||||
return msgs, lastQID, nil
|
||||
}
|
||||
|
||||
// GetHistory returns message history for a target (channel or DM nick pair).
|
||||
func (s *Database) GetHistory(ctx context.Context, target string, beforeID int64, limit int) ([]IRCMessage, error) {
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
var query string
|
||||
var args []any
|
||||
if beforeID > 0 {
|
||||
query = `SELECT id, uuid, command, msg_from, msg_to, body, meta, created_at
|
||||
FROM messages WHERE msg_to = ? AND id < ? AND command = 'PRIVMSG'
|
||||
ORDER BY id DESC LIMIT ?`
|
||||
args = []any{target, beforeID, limit}
|
||||
} else {
|
||||
query = `SELECT id, uuid, command, msg_from, msg_to, body, meta, created_at
|
||||
FROM messages WHERE msg_to = ? AND command = 'PRIVMSG'
|
||||
ORDER BY id DESC LIMIT ?`
|
||||
args = []any{target, limit}
|
||||
}
|
||||
rows, err := s.db.QueryContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var msgs []IRCMessage
|
||||
for rows.Next() {
|
||||
var m IRCMessage
|
||||
var dbID int64
|
||||
var body, meta string
|
||||
var ts time.Time
|
||||
if err := rows.Scan(&dbID, &m.ID, &m.Command, &m.From, &m.To, &body, &meta, &ts); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m.Body = json.RawMessage(body)
|
||||
m.Meta = json.RawMessage(meta)
|
||||
m.TS = ts.Format(time.RFC3339Nano)
|
||||
m.DBID = dbID
|
||||
msgs = append(msgs, m)
|
||||
}
|
||||
if msgs == nil {
|
||||
msgs = []IRCMessage{}
|
||||
}
|
||||
// Reverse to ascending order
|
||||
func reverseMessages(msgs []IRCMessage) {
|
||||
for i, j := 0, len(msgs)-1; i < j; i, j = i+1, j-1 {
|
||||
msgs[i], msgs[j] = msgs[j], msgs[i]
|
||||
}
|
||||
return msgs, nil
|
||||
}
|
||||
|
||||
// ChangeNick updates a user's nickname.
|
||||
func (s *Database) ChangeNick(ctx context.Context, userID int64, newNick string) error {
|
||||
func (s *Database) ChangeNick(
|
||||
ctx context.Context,
|
||||
userID int64,
|
||||
newNick string,
|
||||
) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
"UPDATE users SET nick = ? WHERE id = ?", newNick, userID)
|
||||
"UPDATE users SET nick = ? WHERE id = ?",
|
||||
newNick, userID)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// SetTopic sets the topic for a channel.
|
||||
func (s *Database) SetTopic(ctx context.Context, channelName string, topic string) error {
|
||||
func (s *Database) SetTopic(
|
||||
ctx context.Context,
|
||||
channelName, topic string,
|
||||
) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
"UPDATE channels SET topic = ?, updated_at = ? WHERE name = ?", topic, time.Now(), channelName)
|
||||
`UPDATE channels SET topic = ?,
|
||||
updated_at = ? WHERE name = ?`,
|
||||
topic, time.Now(), channelName)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteUser removes a user and all their data.
|
||||
func (s *Database) DeleteUser(ctx context.Context, userID int64) error {
|
||||
_, err := s.db.ExecContext(ctx, "DELETE FROM users WHERE id = ?", userID)
|
||||
func (s *Database) DeleteUser(
|
||||
ctx context.Context,
|
||||
userID int64,
|
||||
) error {
|
||||
_, err := s.db.ExecContext(
|
||||
ctx,
|
||||
"DELETE FROM users WHERE id = ?",
|
||||
userID,
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// GetAllChannelMembershipsForUser returns (channelID, channelName) for all channels a user is in.
|
||||
func (s *Database) GetAllChannelMembershipsForUser(ctx context.Context, userID int64) ([]ChannelInfo, error) {
|
||||
// GetAllChannelMembershipsForUser returns channels
|
||||
// a user belongs to.
|
||||
func (s *Database) GetAllChannelMembershipsForUser(
|
||||
ctx context.Context,
|
||||
userID int64,
|
||||
) ([]ChannelInfo, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT c.id, c.name, c.topic FROM channels c
|
||||
INNER JOIN channel_members cm ON cm.channel_id = c.id
|
||||
`SELECT c.id, c.name, c.topic
|
||||
FROM channels c
|
||||
INNER JOIN channel_members cm
|
||||
ON cm.channel_id = c.id
|
||||
WHERE cm.user_id = ?`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var channels []ChannelInfo
|
||||
for rows.Next() {
|
||||
var ch ChannelInfo
|
||||
if err := rows.Scan(&ch.ID, &ch.Name, &ch.Topic); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channels = append(channels, ch)
|
||||
}
|
||||
return channels, nil
|
||||
|
||||
return scanChannels(rows)
|
||||
}
|
||||
|
||||
@@ -1,338 +1,550 @@
|
||||
package db
|
||||
package db_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"git.eeqj.de/sneak/chat/internal/db"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
func setupTestDB(t *testing.T) *Database {
|
||||
func setupTestDB(t *testing.T) *db.Database {
|
||||
t.Helper()
|
||||
d, err := sql.Open("sqlite", "file::memory:?cache=shared&_pragma=foreign_keys(1)")
|
||||
|
||||
d, err := db.NewTestDatabase()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { d.Close() })
|
||||
|
||||
db := &Database{db: d, log: slog.Default()}
|
||||
if err := db.runMigrations(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return db
|
||||
t.Cleanup(func() {
|
||||
closeErr := d.Close()
|
||||
if closeErr != nil {
|
||||
t.Logf("close db: %v", closeErr)
|
||||
}
|
||||
})
|
||||
|
||||
return d
|
||||
}
|
||||
|
||||
func TestCreateUser(t *testing.T) {
|
||||
db := setupTestDB(t)
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
id, token, err := db.CreateUser(ctx, "alice")
|
||||
id, token, err := database.CreateUser(ctx, "alice")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if id == 0 || token == "" {
|
||||
t.Fatal("expected valid id and token")
|
||||
}
|
||||
|
||||
// Duplicate nick
|
||||
_, _, err = db.CreateUser(ctx, "alice")
|
||||
_, _, err = database.CreateUser(ctx, "alice")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for duplicate nick")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetUserByToken(t *testing.T) {
|
||||
db := setupTestDB(t)
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, token, _ := db.CreateUser(ctx, "bob")
|
||||
id, nick, err := db.GetUserByToken(ctx, token)
|
||||
_, token, err := database.CreateUser(ctx, "bob")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
id, nick, err := database.GetUserByToken(ctx, token)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if nick != "bob" || id == 0 {
|
||||
t.Fatalf("expected bob, got %s", nick)
|
||||
}
|
||||
|
||||
// Invalid token
|
||||
_, _, err = db.GetUserByToken(ctx, "badtoken")
|
||||
_, _, err = database.GetUserByToken(ctx, "badtoken")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for bad token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetUserByNick(t *testing.T) {
|
||||
db := setupTestDB(t)
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
db.CreateUser(ctx, "charlie")
|
||||
id, err := db.GetUserByNick(ctx, "charlie")
|
||||
_, _, err := database.CreateUser(ctx, "charlie")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
id, err := database.GetUserByNick(ctx, "charlie")
|
||||
if err != nil || id == 0 {
|
||||
t.Fatal("expected to find charlie")
|
||||
}
|
||||
|
||||
_, err = db.GetUserByNick(ctx, "nobody")
|
||||
_, err = database.GetUserByNick(ctx, "nobody")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for unknown nick")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelOperations(t *testing.T) {
|
||||
db := setupTestDB(t)
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// Create channel
|
||||
chID, err := db.GetOrCreateChannel(ctx, "#test")
|
||||
chID, err := database.GetOrCreateChannel(ctx, "#test")
|
||||
if err != nil || chID == 0 {
|
||||
t.Fatal("expected channel id")
|
||||
}
|
||||
|
||||
// Get same channel
|
||||
chID2, err := db.GetOrCreateChannel(ctx, "#test")
|
||||
chID2, err := database.GetOrCreateChannel(ctx, "#test")
|
||||
if err != nil || chID2 != chID {
|
||||
t.Fatal("expected same channel id")
|
||||
}
|
||||
|
||||
// GetChannelByName
|
||||
chID3, err := db.GetChannelByName(ctx, "#test")
|
||||
chID3, err := database.GetChannelByName(ctx, "#test")
|
||||
if err != nil || chID3 != chID {
|
||||
t.Fatal("expected same channel id from GetChannelByName")
|
||||
t.Fatal("expected same channel id")
|
||||
}
|
||||
|
||||
// Nonexistent channel
|
||||
_, err = db.GetChannelByName(ctx, "#nope")
|
||||
_, err = database.GetChannelByName(ctx, "#nope")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for nonexistent channel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJoinAndPart(t *testing.T) {
|
||||
db := setupTestDB(t)
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
uid, _, _ := db.CreateUser(ctx, "user1")
|
||||
chID, _ := db.GetOrCreateChannel(ctx, "#chan")
|
||||
|
||||
// Join
|
||||
if err := db.JoinChannel(ctx, chID, uid); err != nil {
|
||||
uid, _, err := database.CreateUser(ctx, "user1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Verify membership
|
||||
ids, err := db.GetChannelMemberIDs(ctx, chID)
|
||||
chID, err := database.GetOrCreateChannel(ctx, "#chan")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = database.JoinChannel(ctx, chID, uid)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ids, err := database.GetChannelMemberIDs(ctx, chID)
|
||||
if err != nil || len(ids) != 1 || ids[0] != uid {
|
||||
t.Fatal("expected user in channel")
|
||||
}
|
||||
|
||||
// Double join (should be ignored)
|
||||
if err := db.JoinChannel(ctx, chID, uid); err != nil {
|
||||
err = database.JoinChannel(ctx, chID, uid)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Part
|
||||
if err := db.PartChannel(ctx, chID, uid); err != nil {
|
||||
err = database.PartChannel(ctx, chID, uid)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ids, _ = db.GetChannelMemberIDs(ctx, chID)
|
||||
ids, _ = database.GetChannelMemberIDs(ctx, chID)
|
||||
if len(ids) != 0 {
|
||||
t.Fatal("expected empty channel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteChannelIfEmpty(t *testing.T) {
|
||||
db := setupTestDB(t)
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
chID, _ := db.GetOrCreateChannel(ctx, "#empty")
|
||||
uid, _, _ := db.CreateUser(ctx, "temp")
|
||||
db.JoinChannel(ctx, chID, uid)
|
||||
db.PartChannel(ctx, chID, uid)
|
||||
|
||||
if err := db.DeleteChannelIfEmpty(ctx, chID); err != nil {
|
||||
chID, err := database.GetOrCreateChannel(
|
||||
ctx, "#empty",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err := db.GetChannelByName(ctx, "#empty")
|
||||
uid, _, err := database.CreateUser(ctx, "temp")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = database.JoinChannel(ctx, chID, uid)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = database.PartChannel(ctx, chID, uid)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = database.DeleteChannelIfEmpty(ctx, chID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err = database.GetChannelByName(ctx, "#empty")
|
||||
if err == nil {
|
||||
t.Fatal("expected channel to be deleted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestListChannels(t *testing.T) {
|
||||
db := setupTestDB(t)
|
||||
func createUserWithChannels(
|
||||
t *testing.T,
|
||||
database *db.Database,
|
||||
nick, ch1Name, ch2Name string,
|
||||
) (int64, int64, int64) {
|
||||
t.Helper()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
uid, _, _ := db.CreateUser(ctx, "lister")
|
||||
ch1, _ := db.GetOrCreateChannel(ctx, "#a")
|
||||
ch2, _ := db.GetOrCreateChannel(ctx, "#b")
|
||||
db.JoinChannel(ctx, ch1, uid)
|
||||
db.JoinChannel(ctx, ch2, uid)
|
||||
uid, _, err := database.CreateUser(ctx, nick)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
channels, err := db.ListChannels(ctx, uid)
|
||||
ch1, err := database.GetOrCreateChannel(
|
||||
ctx, ch1Name,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ch2, err := database.GetOrCreateChannel(
|
||||
ctx, ch2Name,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = database.JoinChannel(ctx, ch1, uid)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = database.JoinChannel(ctx, ch2, uid)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
return uid, ch1, ch2
|
||||
}
|
||||
|
||||
func TestListChannels(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
uid, _, _ := createUserWithChannels(
|
||||
t, database, "lister", "#a", "#b",
|
||||
)
|
||||
|
||||
channels, err := database.ListChannels(
|
||||
context.Background(), uid,
|
||||
)
|
||||
if err != nil || len(channels) != 2 {
|
||||
t.Fatalf("expected 2 channels, got %d", len(channels))
|
||||
t.Fatalf(
|
||||
"expected 2 channels, got %d",
|
||||
len(channels),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListAllChannels(t *testing.T) {
|
||||
db := setupTestDB(t)
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
db.GetOrCreateChannel(ctx, "#x")
|
||||
db.GetOrCreateChannel(ctx, "#y")
|
||||
_, err := database.GetOrCreateChannel(ctx, "#x")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
channels, err := db.ListAllChannels(ctx)
|
||||
_, err = database.GetOrCreateChannel(ctx, "#y")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
channels, err := database.ListAllChannels(ctx)
|
||||
if err != nil || len(channels) < 2 {
|
||||
t.Fatalf("expected >= 2 channels, got %d", len(channels))
|
||||
t.Fatalf(
|
||||
"expected >= 2 channels, got %d",
|
||||
len(channels),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangeNick(t *testing.T) {
|
||||
db := setupTestDB(t)
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
uid, token, _ := db.CreateUser(ctx, "old")
|
||||
if err := db.ChangeNick(ctx, uid, "new"); err != nil {
|
||||
uid, token, err := database.CreateUser(ctx, "old")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = database.ChangeNick(ctx, uid, "new")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, nick, err := database.GetUserByToken(ctx, token)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, nick, _ := db.GetUserByToken(ctx, token)
|
||||
if nick != "new" {
|
||||
t.Fatalf("expected new, got %s", nick)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetTopic(t *testing.T) {
|
||||
db := setupTestDB(t)
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
db.GetOrCreateChannel(ctx, "#topictest")
|
||||
if err := db.SetTopic(ctx, "#topictest", "Hello"); err != nil {
|
||||
_, err := database.GetOrCreateChannel(
|
||||
ctx, "#topictest",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = database.SetTopic(ctx, "#topictest", "Hello")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
channels, err := database.ListAllChannels(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
channels, _ := db.ListAllChannels(ctx)
|
||||
for _, ch := range channels {
|
||||
if ch.Name == "#topictest" && ch.Topic != "Hello" {
|
||||
t.Fatalf("expected topic Hello, got %s", ch.Topic)
|
||||
if ch.Name == "#topictest" &&
|
||||
ch.Topic != "Hello" {
|
||||
t.Fatalf(
|
||||
"expected topic Hello, got %s",
|
||||
ch.Topic,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInsertAndPollMessages(t *testing.T) {
|
||||
db := setupTestDB(t)
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
uid, _, _ := db.CreateUser(ctx, "poller")
|
||||
body := json.RawMessage(`["hello"]`)
|
||||
|
||||
dbID, uuid, err := db.InsertMessage(ctx, "PRIVMSG", "poller", "#test", body, nil)
|
||||
if err != nil || dbID == 0 || uuid == "" {
|
||||
t.Fatal("insert failed")
|
||||
}
|
||||
|
||||
if err := db.EnqueueMessage(ctx, uid, dbID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
msgs, lastQID, err := db.PollMessages(ctx, uid, 0, 10)
|
||||
uid, _, err := database.CreateUser(ctx, "poller")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
body := json.RawMessage(`["hello"]`)
|
||||
|
||||
dbID, msgUUID, err := database.InsertMessage(
|
||||
ctx, "PRIVMSG", "poller", "#test", body, nil,
|
||||
)
|
||||
if err != nil || dbID == 0 || msgUUID == "" {
|
||||
t.Fatal("insert failed")
|
||||
}
|
||||
|
||||
err = database.EnqueueMessage(ctx, uid, dbID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
const batchSize = 10
|
||||
|
||||
msgs, lastQID, err := database.PollMessages(
|
||||
ctx, uid, 0, batchSize,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(msgs) != 1 {
|
||||
t.Fatalf("expected 1 message, got %d", len(msgs))
|
||||
t.Fatalf(
|
||||
"expected 1 message, got %d", len(msgs),
|
||||
)
|
||||
}
|
||||
|
||||
if msgs[0].Command != "PRIVMSG" {
|
||||
t.Fatalf("expected PRIVMSG, got %s", msgs[0].Command)
|
||||
t.Fatalf(
|
||||
"expected PRIVMSG, got %s", msgs[0].Command,
|
||||
)
|
||||
}
|
||||
|
||||
if lastQID == 0 {
|
||||
t.Fatal("expected nonzero lastQID")
|
||||
}
|
||||
|
||||
// Poll again with lastQID - should be empty
|
||||
msgs, _, _ = db.PollMessages(ctx, uid, lastQID, 10)
|
||||
msgs, _, _ = database.PollMessages(
|
||||
ctx, uid, lastQID, batchSize,
|
||||
)
|
||||
|
||||
if len(msgs) != 0 {
|
||||
t.Fatalf("expected 0 messages, got %d", len(msgs))
|
||||
t.Fatalf(
|
||||
"expected 0 messages, got %d", len(msgs),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetHistory(t *testing.T) {
|
||||
db := setupTestDB(t)
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
db.InsertMessage(ctx, "PRIVMSG", "user", "#hist", json.RawMessage(`["msg"]`), nil)
|
||||
const msgCount = 10
|
||||
|
||||
for range msgCount {
|
||||
_, _, err := database.InsertMessage(
|
||||
ctx, "PRIVMSG", "user", "#hist",
|
||||
json.RawMessage(`["msg"]`), nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
msgs, err := db.GetHistory(ctx, "#hist", 0, 5)
|
||||
const histLimit = 5
|
||||
|
||||
msgs, err := database.GetHistory(
|
||||
ctx, "#hist", 0, histLimit,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(msgs) != 5 {
|
||||
t.Fatalf("expected 5, got %d", len(msgs))
|
||||
|
||||
if len(msgs) != histLimit {
|
||||
t.Fatalf("expected %d, got %d",
|
||||
histLimit, len(msgs))
|
||||
}
|
||||
// Should be ascending order
|
||||
if msgs[0].DBID > msgs[4].DBID {
|
||||
|
||||
if msgs[0].DBID > msgs[histLimit-1].DBID {
|
||||
t.Fatal("expected ascending order")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteUser(t *testing.T) {
|
||||
db := setupTestDB(t)
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
uid, _, _ := db.CreateUser(ctx, "deleteme")
|
||||
chID, _ := db.GetOrCreateChannel(ctx, "#delchan")
|
||||
db.JoinChannel(ctx, chID, uid)
|
||||
|
||||
if err := db.DeleteUser(ctx, uid); err != nil {
|
||||
uid, _, err := database.CreateUser(ctx, "deleteme")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err := db.GetUserByNick(ctx, "deleteme")
|
||||
chID, err := database.GetOrCreateChannel(
|
||||
ctx, "#delchan",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = database.JoinChannel(ctx, chID, uid)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = database.DeleteUser(ctx, uid)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err = database.GetUserByNick(ctx, "deleteme")
|
||||
if err == nil {
|
||||
t.Fatal("user should be deleted")
|
||||
}
|
||||
|
||||
// Channel membership should be cleaned up via CASCADE
|
||||
ids, _ := db.GetChannelMemberIDs(ctx, chID)
|
||||
ids, _ := database.GetChannelMemberIDs(ctx, chID)
|
||||
if len(ids) != 0 {
|
||||
t.Fatal("expected no members after user deletion")
|
||||
t.Fatal("expected no members after deletion")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelMembers(t *testing.T) {
|
||||
db := setupTestDB(t)
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
uid1, _, _ := db.CreateUser(ctx, "m1")
|
||||
uid2, _, _ := db.CreateUser(ctx, "m2")
|
||||
chID, _ := db.GetOrCreateChannel(ctx, "#members")
|
||||
db.JoinChannel(ctx, chID, uid1)
|
||||
db.JoinChannel(ctx, chID, uid2)
|
||||
uid1, _, err := database.CreateUser(ctx, "m1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
members, err := db.ChannelMembers(ctx, chID)
|
||||
uid2, _, err := database.CreateUser(ctx, "m2")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
chID, err := database.GetOrCreateChannel(
|
||||
ctx, "#members",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = database.JoinChannel(ctx, chID, uid1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = database.JoinChannel(ctx, chID, uid2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
members, err := database.ChannelMembers(ctx, chID)
|
||||
if err != nil || len(members) != 2 {
|
||||
t.Fatalf("expected 2 members, got %d", len(members))
|
||||
t.Fatalf(
|
||||
"expected 2 members, got %d",
|
||||
len(members),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAllChannelMembershipsForUser(t *testing.T) {
|
||||
db := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
t.Parallel()
|
||||
|
||||
uid, _, _ := db.CreateUser(ctx, "multi")
|
||||
ch1, _ := db.GetOrCreateChannel(ctx, "#m1")
|
||||
ch2, _ := db.GetOrCreateChannel(ctx, "#m2")
|
||||
db.JoinChannel(ctx, ch1, uid)
|
||||
db.JoinChannel(ctx, ch2, uid)
|
||||
database := setupTestDB(t)
|
||||
uid, _, _ := createUserWithChannels(
|
||||
t, database, "multi", "#m1", "#m2",
|
||||
)
|
||||
|
||||
channels, err := db.GetAllChannelMembershipsForUser(ctx, uid)
|
||||
channels, err :=
|
||||
database.GetAllChannelMembershipsForUser(
|
||||
context.Background(), uid,
|
||||
)
|
||||
if err != nil || len(channels) != 2 {
|
||||
t.Fatalf("expected 2 channels, got %d", len(channels))
|
||||
t.Fatalf(
|
||||
"expected 2 channels, got %d",
|
||||
len(channels),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user