Add comprehensive model and relation test suite
This commit is contained in:
@@ -45,16 +45,6 @@ type Database struct {
|
||||
params *Params
|
||||
}
|
||||
|
||||
// GetDB returns the underlying sql.DB connection.
|
||||
func (s *Database) GetDB() *sql.DB {
|
||||
return s.db
|
||||
}
|
||||
|
||||
// Hydrate injects the database reference into any model that embeds Base.
|
||||
func (s *Database) Hydrate(m interface{ SetDB(d models.DB) }) {
|
||||
m.SetDB(s)
|
||||
}
|
||||
|
||||
// New creates a new Database instance and registers lifecycle hooks.
|
||||
func New(lc fx.Lifecycle, params Params) (*Database, error) {
|
||||
s := new(Database)
|
||||
@@ -83,6 +73,238 @@ func New(lc fx.Lifecycle, params Params) (*Database, error) {
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// NewTest creates a Database for testing, bypassing fx lifecycle.
|
||||
// It connects to the given DSN and runs all migrations.
|
||||
func NewTest(dsn string) (*Database, error) {
|
||||
d, err := sql.Open("sqlite", dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s := &Database{
|
||||
db: d,
|
||||
log: slog.Default(),
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
err = s.runMigrations(ctx)
|
||||
if err != nil {
|
||||
_ = d.Close()
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// GetDB returns the underlying sql.DB connection.
|
||||
func (s *Database) GetDB() *sql.DB {
|
||||
return s.db
|
||||
}
|
||||
|
||||
// Hydrate injects the database reference into any model that
|
||||
// embeds Base.
|
||||
func (s *Database) Hydrate(m interface{ SetDB(d models.DB) }) {
|
||||
m.SetDB(s)
|
||||
}
|
||||
|
||||
// CreateUser inserts a new user into the database.
|
||||
func (s *Database) CreateUser(
|
||||
ctx context.Context,
|
||||
id, nick, passwordHash string,
|
||||
) (*models.User, error) {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO users (id, nick, password_hash)
|
||||
VALUES (?, ?, ?)`,
|
||||
id, nick, passwordHash,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
u := &models.User{
|
||||
ID: id, Nick: nick, PasswordHash: passwordHash,
|
||||
}
|
||||
s.Hydrate(u)
|
||||
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// CreateChannel inserts a new channel into the database.
|
||||
func (s *Database) CreateChannel(
|
||||
ctx context.Context,
|
||||
id, name, topic, modes string,
|
||||
) (*models.Channel, error) {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO channels (id, name, topic, modes)
|
||||
VALUES (?, ?, ?, ?)`,
|
||||
id, name, topic, modes,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c := &models.Channel{
|
||||
ID: id, Name: name, Topic: topic, Modes: modes,
|
||||
}
|
||||
s.Hydrate(c)
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// AddChannelMember adds a user to a channel with the given modes.
|
||||
func (s *Database) AddChannelMember(
|
||||
ctx context.Context,
|
||||
channelID, userID, modes string,
|
||||
) (*models.ChannelMember, error) {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO channel_members
|
||||
(channel_id, user_id, modes)
|
||||
VALUES (?, ?, ?)`,
|
||||
channelID, userID, modes,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cm := &models.ChannelMember{
|
||||
ChannelID: channelID,
|
||||
UserID: userID,
|
||||
Modes: modes,
|
||||
}
|
||||
s.Hydrate(cm)
|
||||
|
||||
return cm, nil
|
||||
}
|
||||
|
||||
// CreateMessage inserts a new message into the database.
|
||||
func (s *Database) CreateMessage(
|
||||
ctx context.Context,
|
||||
id, fromUserID, fromNick, target, msgType, body string,
|
||||
) (*models.Message, error) {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO messages
|
||||
(id, from_user_id, from_nick, target, type, body)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
id, fromUserID, fromNick, target, msgType, body,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
m := &models.Message{
|
||||
ID: id,
|
||||
FromUserID: fromUserID,
|
||||
FromNick: fromNick,
|
||||
Target: target,
|
||||
Type: msgType,
|
||||
Body: body,
|
||||
}
|
||||
s.Hydrate(m)
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// QueueMessage adds a message to a user's delivery queue.
|
||||
func (s *Database) QueueMessage(
|
||||
ctx context.Context,
|
||||
userID, messageID string,
|
||||
) (*models.MessageQueueEntry, error) {
|
||||
res, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO message_queue (user_id, message_id)
|
||||
VALUES (?, ?)`,
|
||||
userID, messageID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entryID, _ := res.LastInsertId()
|
||||
|
||||
mq := &models.MessageQueueEntry{
|
||||
ID: entryID,
|
||||
UserID: userID,
|
||||
MessageID: messageID,
|
||||
}
|
||||
s.Hydrate(mq)
|
||||
|
||||
return mq, nil
|
||||
}
|
||||
|
||||
// CreateAuthToken inserts a new auth token for a user.
|
||||
func (s *Database) CreateAuthToken(
|
||||
ctx context.Context,
|
||||
token, userID string,
|
||||
) (*models.AuthToken, error) {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO auth_tokens (token, user_id)
|
||||
VALUES (?, ?)`,
|
||||
token, userID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
at := &models.AuthToken{Token: token, UserID: userID}
|
||||
s.Hydrate(at)
|
||||
|
||||
return at, nil
|
||||
}
|
||||
|
||||
// CreateSession inserts a new session for a user.
|
||||
func (s *Database) CreateSession(
|
||||
ctx context.Context,
|
||||
id, userID string,
|
||||
) (*models.Session, error) {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO sessions (id, user_id)
|
||||
VALUES (?, ?)`,
|
||||
id, userID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sess := &models.Session{ID: id, UserID: userID}
|
||||
s.Hydrate(sess)
|
||||
|
||||
return sess, nil
|
||||
}
|
||||
|
||||
// CreateServerLink inserts a new server link.
|
||||
func (s *Database) CreateServerLink(
|
||||
ctx context.Context,
|
||||
id, name, url, sharedKeyHash string,
|
||||
isActive bool,
|
||||
) (*models.ServerLink, error) {
|
||||
active := 0
|
||||
if isActive {
|
||||
active = 1
|
||||
}
|
||||
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO server_links
|
||||
(id, name, url, shared_key_hash, is_active)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
id, name, url, sharedKeyHash, active,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sl := &models.ServerLink{
|
||||
ID: id,
|
||||
Name: name,
|
||||
URL: url,
|
||||
SharedKeyHash: sharedKeyHash,
|
||||
IsActive: isActive,
|
||||
}
|
||||
s.Hydrate(sl)
|
||||
|
||||
return sl, nil
|
||||
}
|
||||
|
||||
func (s *Database) connect(ctx context.Context) error {
|
||||
dbURL := s.params.Config.DBURL
|
||||
if dbURL == "" {
|
||||
@@ -138,13 +360,18 @@ func (s *Database) runMigrations(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Database) bootstrapMigrationsTable(ctx context.Context) error {
|
||||
_, err := s.db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
func (s *Database) bootstrapMigrationsTable(
|
||||
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
|
||||
)`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create schema_migrations table: %w", err)
|
||||
return fmt.Errorf(
|
||||
"create schema_migrations table: %w", err,
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -153,17 +380,20 @@ func (s *Database) bootstrapMigrationsTable(ctx context.Context) error {
|
||||
func (s *Database) loadMigrations() ([]migration, error) {
|
||||
entries, err := fs.ReadDir(SchemaFiles, "schema")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to 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
|
||||
}
|
||||
@@ -173,9 +403,13 @@ func (s *Database) loadMigrations() ([]migration, error) {
|
||||
continue
|
||||
}
|
||||
|
||||
content, err := SchemaFiles.ReadFile("schema/" + entry.Name())
|
||||
content, err := SchemaFiles.ReadFile(
|
||||
"schema/" + entry.Name(),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read migration %s: %w", entry.Name(), err)
|
||||
return nil, fmt.Errorf(
|
||||
"read migration %s: %w", entry.Name(), err,
|
||||
)
|
||||
}
|
||||
|
||||
migrations = append(migrations, migration{
|
||||
@@ -192,29 +426,48 @@ func (s *Database) loadMigrations() ([]migration, error) {
|
||||
return migrations, nil
|
||||
}
|
||||
|
||||
func (s *Database) applyMigrations(ctx context.Context, migrations []migration) error {
|
||||
func (s *Database) applyMigrations(
|
||||
ctx context.Context,
|
||||
migrations []migration,
|
||||
) 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.db.QueryRowContext(ctx,
|
||||
"SELECT COUNT(*) FROM schema_migrations WHERE version = ?",
|
||||
m.version,
|
||||
).Scan(&exists)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check migration %d: %w", m.version, err)
|
||||
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)
|
||||
s.log.Info(
|
||||
"applying migration",
|
||||
"version", m.version, "name", m.name,
|
||||
)
|
||||
|
||||
_, err = s.db.ExecContext(ctx, m.sql)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to apply migration %d (%s): %w", m.version, m.name, err)
|
||||
return fmt.Errorf(
|
||||
"apply migration %d (%s): %w",
|
||||
m.version, m.name, err,
|
||||
)
|
||||
}
|
||||
|
||||
_, err = s.db.ExecContext(ctx, "INSERT INTO schema_migrations (version) VALUES (?)", m.version)
|
||||
_, err = s.db.ExecContext(ctx,
|
||||
"INSERT INTO schema_migrations (version) VALUES (?)",
|
||||
m.version,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to record migration %d: %w", m.version, err)
|
||||
return fmt.Errorf(
|
||||
"record migration %d: %w", m.version, err,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user