Complete foundational data layer with repository implementation

- Add GORM dependencies for SQLite and PostgreSQL
- Create domain models (User, Session, File) with common errors
- Implement repository interfaces and database layer with migrations
- Update WebApp to bootstrap with database and repositories
- Add comprehensive unit tests for repository methods
- Update config structure to support multiple database drivers
- Extend AGENTS.md with debugging principles and dependency rules
This commit is contained in:
2026-04-28 13:32:33 +08:00
parent f57f6c8f35
commit 901a769ee7
24 changed files with 1232 additions and 24 deletions

View File

@@ -1,19 +1,67 @@
package app
import (
"fmt"
"gorm.io/gorm"
"github.com/dhao2001/mygo/internal/config"
"github.com/dhao2001/mygo/internal/repository"
)
// WebApp contains application-wide runtime dependencies and metadata.
type WebApp struct {
Config *config.Config
Version string
DB *gorm.DB
UserRepo repository.UserRepository
SessionRepo repository.SessionRepository
FileRepo repository.FileRepository
}
// NewWebApp creates the application dependency container for the HTTP server.
func NewWebApp(cfg *config.Config) *WebApp {
// Bootstrap creates a fully initialized WebApp from config.
// It opens the database, runs migrations, and wires all repositories.
func Bootstrap(cfg *config.Config) (*WebApp, error) {
db, err := repository.Open(cfg.Database)
if err != nil {
return nil, fmt.Errorf("open database: %w", err)
}
if err := repository.AutoMigrate(db); err != nil {
return nil, fmt.Errorf("migrate database: %w", err)
}
return &WebApp{
Config: cfg,
Version: AppVersion,
Config: cfg,
Version: AppVersion,
DB: db,
UserRepo: repository.NewUserRepository(db),
SessionRepo: repository.NewSessionRepository(db),
FileRepo: repository.NewFileRepository(db),
}, nil
}
// NewWebApp creates a WebApp with pre-built dependencies (useful for testing).
func NewWebApp(cfg *config.Config, db *gorm.DB, userRepo repository.UserRepository, sessionRepo repository.SessionRepository, fileRepo repository.FileRepository) *WebApp {
return &WebApp{
Config: cfg,
Version: AppVersion,
DB: db,
UserRepo: userRepo,
SessionRepo: sessionRepo,
FileRepo: fileRepo,
}
}
// Close releases resources held by the application (e.g., database connections).
func (w *WebApp) Close() error {
if w.DB == nil {
return nil
}
sqlDB, err := w.DB.DB()
if err != nil {
return err
}
return sqlDB.Close()
}

View File

@@ -9,7 +9,7 @@ import (
func TestNewWebApp(t *testing.T) {
cfg := &config.Config{}
webApp := NewWebApp(cfg)
webApp := NewWebApp(cfg, nil, nil, nil, nil)
if webApp.Config != cfg {
t.Fatal("Config was not assigned")
@@ -18,3 +18,10 @@ func TestNewWebApp(t *testing.T) {
t.Errorf("Version = %q, want %q", webApp.Version, AppVersion)
}
}
func TestCloseNilDB(t *testing.T) {
webApp := NewWebApp(&config.Config{}, nil, nil, nil, nil)
if err := webApp.Close(); err != nil {
t.Errorf("Close with nil DB should not error: %v", err)
}
}

View File

@@ -20,8 +20,22 @@ type ServerConfig struct {
}
type DatabaseConfig struct {
Driver string `mapstructure:"driver"`
Path string `mapstructure:"path"`
Driver string `mapstructure:"driver"`
SQLite SQLiteConfig `mapstructure:"sqlite"`
Postgres PostgresConfig `mapstructure:"postgres"`
}
type SQLiteConfig struct {
Path string `mapstructure:"path"`
}
type PostgresConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
DBName string `mapstructure:"dbname"`
SSLMode string `mapstructure:"sslmode"`
}
type StorageConfig struct {
@@ -60,8 +74,26 @@ func (c *Config) Validate() error {
errs = append(errs, fmt.Errorf("server.host: %q is not a valid IP address", c.Server.Host))
}
if c.Database.Path == "" {
errs = append(errs, errors.New("database.path: must not be empty"))
switch c.Database.Driver {
case "sqlite3":
if c.Database.SQLite.Path == "" {
errs = append(errs, errors.New("database.sqlite.path: must not be empty"))
}
case "postgres":
if c.Database.Postgres.Host == "" {
errs = append(errs, errors.New("database.postgres.host: must not be empty"))
}
if c.Database.Postgres.Port < 1 || c.Database.Postgres.Port > 65535 {
errs = append(errs, fmt.Errorf("database.postgres.port: %d out of range [1, 65535]", c.Database.Postgres.Port))
}
if c.Database.Postgres.User == "" {
errs = append(errs, errors.New("database.postgres.user: must not be empty"))
}
if c.Database.Postgres.DBName == "" {
errs = append(errs, errors.New("database.postgres.dbname: must not be empty"))
}
default:
errs = append(errs, fmt.Errorf("database.driver: %q is not supported (use sqlite3 or postgres)", c.Database.Driver))
}
if c.Storage.Local.Path == "" {

View File

@@ -13,7 +13,13 @@ func defaults(v *viper.Viper) {
v.SetDefault("server.port", 10086)
v.SetDefault("database.driver", "sqlite3")
v.SetDefault("database.path", "data/mygo.db")
v.SetDefault("database.sqlite.path", "data/mygo.db")
v.SetDefault("database.postgres.host", "localhost")
v.SetDefault("database.postgres.port", 5432)
v.SetDefault("database.postgres.user", "mygo")
v.SetDefault("database.postgres.password", "")
v.SetDefault("database.postgres.dbname", "mygo")
v.SetDefault("database.postgres.sslmode", "disable")
v.SetDefault("storage.driver", "local")
v.SetDefault("storage.local.path", "data/files")

View File

@@ -22,7 +22,7 @@ func TestDefaults(t *testing.T) {
{"server.host", cfg.Server.Host, "0.0.0.0"},
{"server.port", cfg.Server.Port, 10086},
{"database.driver", cfg.Database.Driver, "sqlite3"},
{"database.path", cfg.Database.Path, "data/mygo.db"},
{"database.sqlite.path", cfg.Database.SQLite.Path, "data/mygo.db"},
{"storage.driver", cfg.Storage.Driver, "local"},
{"storage.local.path", cfg.Storage.Local.Path, "data/files"},
{"jwt.access_ttl", cfg.JWT.AccessTTL, "15m"},
@@ -49,7 +49,8 @@ server:
database:
driver: sqlite3
path: /tmp/mygo.db
sqlite:
path: /tmp/mygo.db
storage:
driver: local
@@ -77,8 +78,8 @@ jwt:
if cfg.Server.Port != 9090 {
t.Errorf("server.port = %d, want %d", cfg.Server.Port, 9090)
}
if cfg.Database.Path != "/tmp/mygo.db" {
t.Errorf("database.path = %q, want %q", cfg.Database.Path, "/tmp/mygo.db")
if cfg.Database.SQLite.Path != "/tmp/mygo.db" {
t.Errorf("database.sqlite.path = %q, want %q", cfg.Database.SQLite.Path, "/tmp/mygo.db")
}
if cfg.Storage.Local.Path != "/tmp/mygo-storage" {
t.Errorf("storage.local.path = %q, want %q", cfg.Storage.Local.Path, "/tmp/mygo-storage")
@@ -98,7 +99,7 @@ func TestEnvOverride(t *testing.T) {
t.Setenv("MYGO_SERVER_PORT", "8080")
t.Setenv("MYGO_SERVER_HOST", "192.168.1.1")
t.Setenv("MYGO_JWT_SECRET", "env-secret")
t.Setenv("MYGO_DATABASE_PATH", "/env/path/db.sqlite")
t.Setenv("MYGO_DATABASE_SQLITE_PATH", "/env/path/db.sqlite")
v := New()
cfg, err := Load(v, "")
@@ -115,8 +116,8 @@ func TestEnvOverride(t *testing.T) {
if cfg.JWT.Secret != "env-secret" {
t.Errorf("jwt.secret = %q, want %q", cfg.JWT.Secret, "env-secret")
}
if cfg.Database.Path != "/env/path/db.sqlite" {
t.Errorf("database.path = %q, want %q", cfg.Database.Path, "/env/path/db.sqlite")
if cfg.Database.SQLite.Path != "/env/path/db.sqlite" {
t.Errorf("database.sqlite.path = %q, want %q", cfg.Database.SQLite.Path, "/env/path/db.sqlite")
}
}

10
internal/model/errors.go Normal file
View File

@@ -0,0 +1,10 @@
package model
import "errors"
var (
ErrNotFound = errors.New("resource not found")
ErrDuplicate = errors.New("resource already exists")
ErrUnauthorized = errors.New("unauthorized")
ErrForbidden = errors.New("forbidden")
)

19
internal/model/file.go Normal file
View File

@@ -0,0 +1,19 @@
package model
import (
"time"
)
// File represents a file or directory entry in the virtual filesystem.
type File struct {
ID string `gorm:"primaryKey;type:varchar(36)" json:"id"`
UserID string `gorm:"index;type:varchar(36);not null" json:"user_id"`
ParentID *string `gorm:"index;type:varchar(36)" json:"parent_id"`
Name string `gorm:"type:varchar(255);not null" json:"name"`
Size int64 `gorm:"default:0" json:"size"`
MimeType string `gorm:"type:varchar(127)" json:"mime_type"`
StoragePath string `gorm:"type:varchar(512)" json:"storage_path"`
IsDir bool `gorm:"default:false" json:"is_dir"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}

14
internal/model/session.go Normal file
View File

@@ -0,0 +1,14 @@
package model
import (
"time"
)
// Session stores a refresh token for a user session.
type Session struct {
ID string `gorm:"primaryKey;type:varchar(36)" json:"id"`
UserID string `gorm:"index;type:varchar(36);not null" json:"user_id"`
TokenHash string `gorm:"uniqueIndex;type:varchar(255);not null" json:"-"`
ExpiresAt time.Time `gorm:"not null" json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
}

16
internal/model/user.go Normal file
View File

@@ -0,0 +1,16 @@
package model
import (
"time"
)
// User represents a registered account.
type User struct {
ID string `gorm:"primaryKey;type:varchar(36)" json:"id"`
Username string `gorm:"uniqueIndex;type:varchar(64);not null" json:"username"`
Email string `gorm:"uniqueIndex;type:varchar(255);not null" json:"email"`
PasswordHash string `gorm:"type:varchar(255);not null" json:"-"`
IsAdmin bool `gorm:"default:false" json:"is_admin"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}

57
internal/repository/db.go Normal file
View File

@@ -0,0 +1,57 @@
package repository
import (
"fmt"
"os"
"path/filepath"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"github.com/dhao2001/mygo/internal/config"
"github.com/dhao2001/mygo/internal/model"
)
// Open creates a GORM database connection based on the config driver.
func Open(cfg config.DatabaseConfig) (*gorm.DB, error) {
var dialector gorm.Dialector
switch cfg.Driver {
case "sqlite3":
dir := filepath.Dir(cfg.SQLite.Path)
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, fmt.Errorf("create db directory: %w", err)
}
dialector = sqlite.Open(cfg.SQLite.Path)
case "postgres":
dsn := fmt.Sprintf(
"host=%s user=%s password=%s dbname=%s port=%d sslmode=%s",
cfg.Postgres.Host,
cfg.Postgres.User,
cfg.Postgres.Password,
cfg.Postgres.DBName,
cfg.Postgres.Port,
cfg.Postgres.SSLMode,
)
dialector = postgres.Open(dsn)
default:
return nil, fmt.Errorf("unsupported database driver: %s", cfg.Driver)
}
db, err := gorm.Open(dialector, &gorm.Config{})
if err != nil {
return nil, fmt.Errorf("open database: %w", err)
}
return db, nil
}
// AutoMigrate runs schema migration for all domain models.
func AutoMigrate(db *gorm.DB) error {
return db.AutoMigrate(
&model.User{},
&model.Session{},
&model.File{},
)
}

View File

@@ -0,0 +1,58 @@
package repository
import (
"testing"
"github.com/dhao2001/mygo/internal/config"
)
func TestOpenSQLite(t *testing.T) {
cfg := config.DatabaseConfig{
Driver: "sqlite3",
SQLite: config.SQLiteConfig{Path: ":memory:"},
}
db, err := Open(cfg)
if err != nil {
t.Fatalf("Open(sqlite3) = %v", err)
}
sqlDB, err := db.DB()
if err != nil {
t.Fatalf("db.DB() = %v", err)
}
if err := sqlDB.Ping(); err != nil {
t.Fatalf("ping = %v", err)
}
}
func TestOpenUnsupportedDriver(t *testing.T) {
cfg := config.DatabaseConfig{Driver: "mysql"}
_, err := Open(cfg)
if err == nil {
t.Fatal("expected error for unsupported driver, got nil")
}
}
func TestAutoMigrate(t *testing.T) {
cfg := config.DatabaseConfig{
Driver: "sqlite3",
SQLite: config.SQLiteConfig{Path: ":memory:"},
}
db, err := Open(cfg)
if err != nil {
t.Fatalf("Open = %v", err)
}
if err := AutoMigrate(db); err != nil {
t.Fatalf("AutoMigrate = %v", err)
}
// Verify tables exist
for _, table := range []string{"users", "sessions", "files"} {
if !db.Migrator().HasTable(table) {
t.Errorf("table %q not found after migration", table)
}
}
}

View File

@@ -0,0 +1,93 @@
package repository
import (
"context"
"errors"
"gorm.io/gorm"
"github.com/dhao2001/mygo/internal/model"
)
// FileRepository provides access to file records.
type FileRepository interface {
Create(ctx context.Context, file *model.File) error
FindByID(ctx context.Context, id string) (*model.File, error)
FindByUserID(ctx context.Context, userID string, offset, limit int) ([]model.File, int64, error)
FindByParentID(ctx context.Context, userID string, parentID *string) ([]model.File, error)
Update(ctx context.Context, file *model.File) error
Delete(ctx context.Context, id string) error
}
type fileRepository struct {
db *gorm.DB
}
// NewFileRepository creates a FileRepository backed by GORM.
func NewFileRepository(db *gorm.DB) FileRepository {
return &fileRepository{db: db}
}
func (r *fileRepository) Create(ctx context.Context, file *model.File) error {
result := r.db.WithContext(ctx).Create(file)
if result.Error != nil {
if isDuplicateKeyError(result.Error) {
return model.ErrDuplicate
}
return result.Error
}
return nil
}
func (r *fileRepository) FindByID(ctx context.Context, id string) (*model.File, error) {
var file model.File
result := r.db.WithContext(ctx).First(&file, "id = ?", id)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, model.ErrNotFound
}
if result.Error != nil {
return nil, result.Error
}
return &file, nil
}
func (r *fileRepository) FindByUserID(ctx context.Context, userID string, offset, limit int) ([]model.File, int64, error) {
var files []model.File
var total int64
if err := r.db.WithContext(ctx).Model(&model.File{}).Where("user_id = ?", userID).Count(&total).Error; err != nil {
return nil, 0, err
}
result := r.db.WithContext(ctx).Where("user_id = ?", userID).Offset(offset).Limit(limit).Find(&files)
if result.Error != nil {
return nil, 0, result.Error
}
return files, total, nil
}
func (r *fileRepository) FindByParentID(ctx context.Context, userID string, parentID *string) ([]model.File, error) {
var files []model.File
result := r.db.WithContext(ctx).Where("user_id = ? AND parent_id IS ?", userID, parentID).Find(&files)
if result.Error != nil {
return nil, result.Error
}
return files, nil
}
func (r *fileRepository) Update(ctx context.Context, file *model.File) error {
result := r.db.WithContext(ctx).Save(file)
if result.Error != nil {
return result.Error
}
return nil
}
func (r *fileRepository) Delete(ctx context.Context, id string) error {
result := r.db.WithContext(ctx).Delete(&model.File{}, "id = ?", id)
if result.Error != nil {
return result.Error
}
return nil
}

View File

@@ -0,0 +1,195 @@
package repository
import (
"context"
"testing"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"github.com/dhao2001/mygo/internal/model"
)
func setupFileRepo(t *testing.T) FileRepository {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatalf("open db: %v", err)
}
if err := db.AutoMigrate(&model.File{}); err != nil {
t.Fatalf("migrate: %v", err)
}
return NewFileRepository(db)
}
func TestFileRepository_Create(t *testing.T) {
repo := setupFileRepo(t)
ctx := context.Background()
file := &model.File{
ID: "file-1",
UserID: "user-1",
Name: "test.txt",
Size: 1024,
}
if err := repo.Create(ctx, file); err != nil {
t.Fatalf("Create = %v", err)
}
}
func TestFileRepository_FindByID(t *testing.T) {
repo := setupFileRepo(t)
ctx := context.Background()
file := &model.File{
ID: "file-1",
UserID: "user-1",
Name: "test.txt",
}
if err := repo.Create(ctx, file); err != nil {
t.Fatalf("Create = %v", err)
}
found, err := repo.FindByID(ctx, "file-1")
if err != nil {
t.Fatalf("FindByID = %v", err)
}
if found.Name != "test.txt" {
t.Errorf("name = %q, want %q", found.Name, "test.txt")
}
}
func TestFileRepository_FindByIDNotFound(t *testing.T) {
repo := setupFileRepo(t)
ctx := context.Background()
_, err := repo.FindByID(ctx, "nonexistent")
if err != model.ErrNotFound {
t.Fatalf("expected ErrNotFound, got %v", err)
}
}
func TestFileRepository_FindByUserID(t *testing.T) {
repo := setupFileRepo(t)
ctx := context.Background()
files := []*model.File{
{ID: "f-1", UserID: "user-1", Name: "a.txt"},
{ID: "f-2", UserID: "user-1", Name: "b.txt"},
{ID: "f-3", UserID: "user-2", Name: "c.txt"},
}
for _, f := range files {
if err := repo.Create(ctx, f); err != nil {
t.Fatalf("Create = %v", err)
}
}
result, total, err := repo.FindByUserID(ctx, "user-1", 0, 10)
if err != nil {
t.Fatalf("FindByUserID = %v", err)
}
if len(result) != 2 {
t.Errorf("len(result) = %d, want 2", len(result))
}
if total != 2 {
t.Errorf("total = %d, want 2", total)
}
}
func TestFileRepository_FindByParentID(t *testing.T) {
repo := setupFileRepo(t)
ctx := context.Background()
parentID := "dir-1"
files := []*model.File{
{ID: "f-1", UserID: "user-1", ParentID: &parentID, Name: "a.txt"},
{ID: "f-2", UserID: "user-1", ParentID: &parentID, Name: "b.txt"},
{ID: "f-3", UserID: "user-1", Name: "c.txt"},
}
for _, f := range files {
if err := repo.Create(ctx, f); err != nil {
t.Fatalf("Create = %v", err)
}
}
children, err := repo.FindByParentID(ctx, "user-1", &parentID)
if err != nil {
t.Fatalf("FindByParentID = %v", err)
}
if len(children) != 2 {
t.Errorf("len(children) = %d, want 2", len(children))
}
}
func TestFileRepository_FindByParentIDNull(t *testing.T) {
repo := setupFileRepo(t)
ctx := context.Background()
parentID := "dir-1"
files := []*model.File{
{ID: "f-1", UserID: "user-1", ParentID: &parentID, Name: "a.txt"},
{ID: "f-2", UserID: "user-1", Name: "root.txt"},
}
for _, f := range files {
if err := repo.Create(ctx, f); err != nil {
t.Fatalf("Create = %v", err)
}
}
children, err := repo.FindByParentID(ctx, "user-1", nil)
if err != nil {
t.Fatalf("FindByParentID(nil) = %v", err)
}
if len(children) != 1 {
t.Errorf("len(children) = %d, want 1", len(children))
}
}
func TestFileRepository_Update(t *testing.T) {
repo := setupFileRepo(t)
ctx := context.Background()
file := &model.File{ID: "file-1", UserID: "user-1", Name: "original.txt"}
if err := repo.Create(ctx, file); err != nil {
t.Fatalf("Create = %v", err)
}
file.Name = "renamed.txt"
file.Size = 2048
if err := repo.Update(ctx, file); err != nil {
t.Fatalf("Update = %v", err)
}
found, err := repo.FindByID(ctx, "file-1")
if err != nil {
t.Fatalf("FindByID = %v", err)
}
if found.Name != "renamed.txt" {
t.Errorf("name = %q, want %q", found.Name, "renamed.txt")
}
if found.Size != 2048 {
t.Errorf("size = %d, want %d", found.Size, 2048)
}
}
func TestFileRepository_Delete(t *testing.T) {
repo := setupFileRepo(t)
ctx := context.Background()
file := &model.File{ID: "file-1", UserID: "user-1", Name: "test.txt"}
if err := repo.Create(ctx, file); err != nil {
t.Fatalf("Create = %v", err)
}
if err := repo.Delete(ctx, "file-1"); err != nil {
t.Fatalf("Delete = %v", err)
}
_, err := repo.FindByID(ctx, "file-1")
if err != model.ErrNotFound {
t.Fatalf("expected ErrNotFound after delete, got %v", err)
}
}

View File

@@ -0,0 +1,89 @@
package repository
import (
"context"
"errors"
"time"
"gorm.io/gorm"
"github.com/dhao2001/mygo/internal/model"
)
// SessionRepository provides access to refresh token sessions.
type SessionRepository interface {
Create(ctx context.Context, session *model.Session) error
FindByID(ctx context.Context, id string) (*model.Session, error)
FindByTokenHash(ctx context.Context, tokenHash string) (*model.Session, error)
Delete(ctx context.Context, id string) error
DeleteByUserID(ctx context.Context, userID string) error
DeleteExpired(ctx context.Context) (int64, error)
}
type sessionRepository struct {
db *gorm.DB
}
// NewSessionRepository creates a SessionRepository backed by GORM.
func NewSessionRepository(db *gorm.DB) SessionRepository {
return &sessionRepository{db: db}
}
func (r *sessionRepository) Create(ctx context.Context, session *model.Session) error {
result := r.db.WithContext(ctx).Create(session)
if result.Error != nil {
if isDuplicateKeyError(result.Error) {
return model.ErrDuplicate
}
return result.Error
}
return nil
}
func (r *sessionRepository) FindByID(ctx context.Context, id string) (*model.Session, error) {
var session model.Session
result := r.db.WithContext(ctx).First(&session, "id = ?", id)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, model.ErrNotFound
}
if result.Error != nil {
return nil, result.Error
}
return &session, nil
}
func (r *sessionRepository) FindByTokenHash(ctx context.Context, tokenHash string) (*model.Session, error) {
var session model.Session
result := r.db.WithContext(ctx).First(&session, "token_hash = ?", tokenHash)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, model.ErrNotFound
}
if result.Error != nil {
return nil, result.Error
}
return &session, nil
}
func (r *sessionRepository) Delete(ctx context.Context, id string) error {
result := r.db.WithContext(ctx).Delete(&model.Session{}, "id = ?", id)
if result.Error != nil {
return result.Error
}
return nil
}
func (r *sessionRepository) DeleteByUserID(ctx context.Context, userID string) error {
result := r.db.WithContext(ctx).Delete(&model.Session{}, "user_id = ?", userID)
if result.Error != nil {
return result.Error
}
return nil
}
func (r *sessionRepository) DeleteExpired(ctx context.Context) (int64, error) {
result := r.db.WithContext(ctx).Delete(&model.Session{}, "expires_at < ?", time.Now())
if result.Error != nil {
return 0, result.Error
}
return result.RowsAffected, nil
}

View File

@@ -0,0 +1,190 @@
package repository
import (
"context"
"testing"
"time"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"github.com/dhao2001/mygo/internal/model"
)
func setupSessionRepo(t *testing.T) SessionRepository {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatalf("open db: %v", err)
}
if err := db.AutoMigrate(&model.Session{}); err != nil {
t.Fatalf("migrate: %v", err)
}
return NewSessionRepository(db)
}
func TestSessionRepository_Create(t *testing.T) {
repo := setupSessionRepo(t)
ctx := context.Background()
session := &model.Session{
ID: "session-1",
UserID: "user-1",
TokenHash: "hash-abc",
ExpiresAt: time.Now().Add(24 * time.Hour),
}
if err := repo.Create(ctx, session); err != nil {
t.Fatalf("Create = %v", err)
}
}
func TestSessionRepository_CreateDuplicateHash(t *testing.T) {
repo := setupSessionRepo(t)
ctx := context.Background()
s1 := &model.Session{ID: "session-1", UserID: "user-1", TokenHash: "hash-abc", ExpiresAt: time.Now().Add(24 * time.Hour)}
s2 := &model.Session{ID: "session-2", UserID: "user-2", TokenHash: "hash-abc", ExpiresAt: time.Now().Add(24 * time.Hour)}
if err := repo.Create(ctx, s1); err != nil {
t.Fatalf("Create = %v", err)
}
err := repo.Create(ctx, s2)
if err != model.ErrDuplicate {
t.Fatalf("expected ErrDuplicate, got %v", err)
}
}
func TestSessionRepository_FindByID(t *testing.T) {
repo := setupSessionRepo(t)
ctx := context.Background()
session := &model.Session{ID: "session-1", UserID: "user-1", TokenHash: "hash-abc", ExpiresAt: time.Now().Add(24 * time.Hour)}
if err := repo.Create(ctx, session); err != nil {
t.Fatalf("Create = %v", err)
}
found, err := repo.FindByID(ctx, "session-1")
if err != nil {
t.Fatalf("FindByID = %v", err)
}
if found.UserID != "user-1" {
t.Errorf("user_id = %q, want %q", found.UserID, "user-1")
}
}
func TestSessionRepository_FindByTokenHash(t *testing.T) {
repo := setupSessionRepo(t)
ctx := context.Background()
session := &model.Session{ID: "session-1", UserID: "user-1", TokenHash: "hash-abc", ExpiresAt: time.Now().Add(24 * time.Hour)}
if err := repo.Create(ctx, session); err != nil {
t.Fatalf("Create = %v", err)
}
found, err := repo.FindByTokenHash(ctx, "hash-abc")
if err != nil {
t.Fatalf("FindByTokenHash = %v", err)
}
if found.ID != "session-1" {
t.Errorf("id = %q, want %q", found.ID, "session-1")
}
}
func TestSessionRepository_FindByTokenHashNotFound(t *testing.T) {
repo := setupSessionRepo(t)
ctx := context.Background()
_, err := repo.FindByTokenHash(ctx, "nonexistent")
if err != model.ErrNotFound {
t.Fatalf("expected ErrNotFound, got %v", err)
}
}
func TestSessionRepository_Delete(t *testing.T) {
repo := setupSessionRepo(t)
ctx := context.Background()
session := &model.Session{ID: "session-1", UserID: "user-1", TokenHash: "hash-abc", ExpiresAt: time.Now().Add(24 * time.Hour)}
if err := repo.Create(ctx, session); err != nil {
t.Fatalf("Create = %v", err)
}
if err := repo.Delete(ctx, "session-1"); err != nil {
t.Fatalf("Delete = %v", err)
}
_, err := repo.FindByID(ctx, "session-1")
if err != model.ErrNotFound {
t.Fatalf("expected ErrNotFound after delete, got %v", err)
}
}
func TestSessionRepository_DeleteByUserID(t *testing.T) {
repo := setupSessionRepo(t)
ctx := context.Background()
s1 := &model.Session{ID: "session-1", UserID: "user-1", TokenHash: "hash-1", ExpiresAt: time.Now().Add(24 * time.Hour)}
s2 := &model.Session{ID: "session-2", UserID: "user-1", TokenHash: "hash-2", ExpiresAt: time.Now().Add(24 * time.Hour)}
s3 := &model.Session{ID: "session-3", UserID: "user-2", TokenHash: "hash-3", ExpiresAt: time.Now().Add(24 * time.Hour)}
for _, s := range []*model.Session{s1, s2, s3} {
if err := repo.Create(ctx, s); err != nil {
t.Fatalf("Create = %v", err)
}
}
if err := repo.DeleteByUserID(ctx, "user-1"); err != nil {
t.Fatalf("DeleteByUserID = %v", err)
}
_, err := repo.FindByID(ctx, "session-1")
if err != model.ErrNotFound {
t.Fatalf("session-1 should have been deleted")
}
_, err = repo.FindByID(ctx, "session-2")
if err != model.ErrNotFound {
t.Fatalf("session-2 should have been deleted")
}
if _, err := repo.FindByID(ctx, "session-3"); err != nil {
t.Fatalf("session-3 should still exist: %v", err)
}
}
func TestSessionRepository_DeleteExpired(t *testing.T) {
repo := setupSessionRepo(t)
ctx := context.Background()
expired := &model.Session{
ID: "session-1", UserID: "user-1", TokenHash: "hash-old",
ExpiresAt: time.Now().Add(-1 * time.Hour),
}
valid := &model.Session{
ID: "session-2", UserID: "user-1", TokenHash: "hash-new",
ExpiresAt: time.Now().Add(24 * time.Hour),
}
for _, s := range []*model.Session{expired, valid} {
if err := repo.Create(ctx, s); err != nil {
t.Fatalf("Create = %v", err)
}
}
count, err := repo.DeleteExpired(ctx)
if err != nil {
t.Fatalf("DeleteExpired = %v", err)
}
if count != 1 {
t.Errorf("DeleteExpired count = %d, want 1", count)
}
if _, err := repo.FindByID(ctx, "session-1"); err != model.ErrNotFound {
t.Fatalf("expired session should have been deleted")
}
if _, err := repo.FindByID(ctx, "session-2"); err != nil {
t.Fatalf("valid session should still exist: %v", err)
}
}

118
internal/repository/user.go Normal file
View File

@@ -0,0 +1,118 @@
package repository
import (
"context"
"errors"
"strings"
"gorm.io/gorm"
"github.com/dhao2001/mygo/internal/model"
)
// isDuplicateKeyError checks if the error indicates a unique constraint violation.
func isDuplicateKeyError(err error) bool {
return errors.Is(err, gorm.ErrDuplicatedKey) || strings.Contains(strings.ToLower(err.Error()), "unique constraint failed")
}
// UserRepository provides access to user records.
type UserRepository interface {
Create(ctx context.Context, user *model.User) error
FindByID(ctx context.Context, id string) (*model.User, error)
FindByEmail(ctx context.Context, email string) (*model.User, error)
FindByUsername(ctx context.Context, username string) (*model.User, error)
Update(ctx context.Context, user *model.User) error
Delete(ctx context.Context, id string) error
List(ctx context.Context, offset, limit int) ([]model.User, int64, error)
}
type userRepository struct {
db *gorm.DB
}
// NewUserRepository creates a UserRepository backed by GORM.
func NewUserRepository(db *gorm.DB) UserRepository {
return &userRepository{db: db}
}
func (r *userRepository) Create(ctx context.Context, user *model.User) error {
result := r.db.WithContext(ctx).Create(user)
if result.Error != nil {
if isDuplicateKeyError(result.Error) {
return model.ErrDuplicate
}
return result.Error
}
return nil
}
func (r *userRepository) FindByID(ctx context.Context, id string) (*model.User, error) {
var user model.User
result := r.db.WithContext(ctx).First(&user, "id = ?", id)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, model.ErrNotFound
}
if result.Error != nil {
return nil, result.Error
}
return &user, nil
}
func (r *userRepository) FindByEmail(ctx context.Context, email string) (*model.User, error) {
var user model.User
result := r.db.WithContext(ctx).First(&user, "email = ?", email)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, model.ErrNotFound
}
if result.Error != nil {
return nil, result.Error
}
return &user, nil
}
func (r *userRepository) FindByUsername(ctx context.Context, username string) (*model.User, error) {
var user model.User
result := r.db.WithContext(ctx).First(&user, "username = ?", username)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, model.ErrNotFound
}
if result.Error != nil {
return nil, result.Error
}
return &user, nil
}
func (r *userRepository) Update(ctx context.Context, user *model.User) error {
result := r.db.WithContext(ctx).Save(user)
if result.Error != nil {
if isDuplicateKeyError(result.Error) {
return model.ErrDuplicate
}
return result.Error
}
return nil
}
func (r *userRepository) Delete(ctx context.Context, id string) error {
result := r.db.WithContext(ctx).Delete(&model.User{}, "id = ?", id)
if result.Error != nil {
return result.Error
}
return nil
}
func (r *userRepository) List(ctx context.Context, offset, limit int) ([]model.User, int64, error) {
var users []model.User
var total int64
if err := r.db.WithContext(ctx).Model(&model.User{}).Count(&total).Error; err != nil {
return nil, 0, err
}
result := r.db.WithContext(ctx).Offset(offset).Limit(limit).Find(&users)
if result.Error != nil {
return nil, 0, result.Error
}
return users, total, nil
}

View File

@@ -0,0 +1,192 @@
package repository
import (
"context"
"testing"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"github.com/dhao2001/mygo/internal/model"
)
func setupUserRepo(t *testing.T) UserRepository {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatalf("open db: %v", err)
}
if err := db.AutoMigrate(&model.User{}); err != nil {
t.Fatalf("migrate: %v", err)
}
return NewUserRepository(db)
}
func TestUserRepository_Create(t *testing.T) {
repo := setupUserRepo(t)
ctx := context.Background()
user := &model.User{
ID: "user-1",
Username: "alice",
Email: "alice@example.com",
PasswordHash: "hash",
}
if err := repo.Create(ctx, user); err != nil {
t.Fatalf("Create = %v", err)
}
}
func TestUserRepository_CreateDuplicateUsername(t *testing.T) {
repo := setupUserRepo(t)
ctx := context.Background()
u1 := &model.User{ID: "user-1", Username: "alice", Email: "alice@example.com", PasswordHash: "hash"}
u2 := &model.User{ID: "user-2", Username: "alice", Email: "alice2@example.com", PasswordHash: "hash"}
if err := repo.Create(ctx, u1); err != nil {
t.Fatalf("Create = %v", err)
}
err := repo.Create(ctx, u2)
if err != model.ErrDuplicate {
t.Fatalf("expected ErrDuplicate, got %v", err)
}
}
func TestUserRepository_FindByID(t *testing.T) {
repo := setupUserRepo(t)
ctx := context.Background()
user := &model.User{ID: "user-1", Username: "alice", Email: "alice@example.com", PasswordHash: "hash"}
if err := repo.Create(ctx, user); err != nil {
t.Fatalf("Create = %v", err)
}
found, err := repo.FindByID(ctx, "user-1")
if err != nil {
t.Fatalf("FindByID = %v", err)
}
if found.Username != "alice" {
t.Errorf("username = %q, want %q", found.Username, "alice")
}
}
func TestUserRepository_FindByIDNotFound(t *testing.T) {
repo := setupUserRepo(t)
ctx := context.Background()
_, err := repo.FindByID(ctx, "nonexistent")
if err != model.ErrNotFound {
t.Fatalf("expected ErrNotFound, got %v", err)
}
}
func TestUserRepository_FindByEmail(t *testing.T) {
repo := setupUserRepo(t)
ctx := context.Background()
user := &model.User{ID: "user-1", Username: "alice", Email: "alice@example.com", PasswordHash: "hash"}
if err := repo.Create(ctx, user); err != nil {
t.Fatalf("Create = %v", err)
}
found, err := repo.FindByEmail(ctx, "alice@example.com")
if err != nil {
t.Fatalf("FindByEmail = %v", err)
}
if found.ID != "user-1" {
t.Errorf("id = %q, want %q", found.ID, "user-1")
}
}
func TestUserRepository_FindByUsername(t *testing.T) {
repo := setupUserRepo(t)
ctx := context.Background()
user := &model.User{ID: "user-1", Username: "alice", Email: "alice@example.com", PasswordHash: "hash"}
if err := repo.Create(ctx, user); err != nil {
t.Fatalf("Create = %v", err)
}
found, err := repo.FindByUsername(ctx, "alice")
if err != nil {
t.Fatalf("FindByUsername = %v", err)
}
if found.Email != "alice@example.com" {
t.Errorf("email = %q, want %q", found.Email, "alice@example.com")
}
}
func TestUserRepository_Update(t *testing.T) {
repo := setupUserRepo(t)
ctx := context.Background()
user := &model.User{ID: "user-1", Username: "alice", Email: "alice@example.com", PasswordHash: "hash"}
if err := repo.Create(ctx, user); err != nil {
t.Fatalf("Create = %v", err)
}
user.Username = "alice2"
if err := repo.Update(ctx, user); err != nil {
t.Fatalf("Update = %v", err)
}
found, err := repo.FindByID(ctx, "user-1")
if err != nil {
t.Fatalf("FindByID = %v", err)
}
if found.Username != "alice2" {
t.Errorf("username = %q, want %q", found.Username, "alice2")
}
}
func TestUserRepository_Delete(t *testing.T) {
repo := setupUserRepo(t)
ctx := context.Background()
user := &model.User{ID: "user-1", Username: "alice", Email: "alice@example.com", PasswordHash: "hash"}
if err := repo.Create(ctx, user); err != nil {
t.Fatalf("Create = %v", err)
}
if err := repo.Delete(ctx, "user-1"); err != nil {
t.Fatalf("Delete = %v", err)
}
_, err := repo.FindByID(ctx, "user-1")
if err != model.ErrNotFound {
t.Fatalf("expected ErrNotFound after delete, got %v", err)
}
}
func TestUserRepository_List(t *testing.T) {
repo := setupUserRepo(t)
ctx := context.Background()
for i := range 5 {
user := &model.User{
ID: "user-" + string(rune('0'+i)),
Username: "user" + string(rune('0'+i)),
Email: "user" + string(rune('0'+i)) + "@example.com",
PasswordHash: "hash",
}
if err := repo.Create(ctx, user); err != nil {
t.Fatalf("Create = %v", err)
}
}
users, total, err := repo.List(ctx, 0, 3)
if err != nil {
t.Fatalf("List = %v", err)
}
if len(users) != 3 {
t.Errorf("len(users) = %d, want %d", len(users), 3)
}
if total != 5 {
t.Errorf("total = %d, want %d", total, 5)
}
}

View File

@@ -11,7 +11,7 @@ import (
)
func TestVersionRoute(t *testing.T) {
webApp := app.NewWebApp(&config.Config{})
webApp := app.NewWebApp(&config.Config{}, nil, nil, nil, nil)
router := NewRouter(webApp)
req := httptest.NewRequest(http.MethodGet, "/api/v1/version", nil)