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:
57
internal/repository/db.go
Normal file
57
internal/repository/db.go
Normal 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{},
|
||||
)
|
||||
}
|
||||
58
internal/repository/db_test.go
Normal file
58
internal/repository/db_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
93
internal/repository/file.go
Normal file
93
internal/repository/file.go
Normal 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
|
||||
}
|
||||
195
internal/repository/file_test.go
Normal file
195
internal/repository/file_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
89
internal/repository/session.go
Normal file
89
internal/repository/session.go
Normal 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
|
||||
}
|
||||
190
internal/repository/session_test.go
Normal file
190
internal/repository/session_test.go
Normal 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
118
internal/repository/user.go
Normal 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
|
||||
}
|
||||
192
internal/repository/user_test.go
Normal file
192
internal/repository/user_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user