diff --git a/AGENTS.md b/AGENTS.md index 05cc839..27d43df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,6 +49,18 @@ go mod tidy # clean deps after add/remove - DO put business logic in `internal/`, keep `cmd/` thin - DO write all code, comments, and documentation in English +- DO add all Go module dependencies **before** writing code that uses them - DON'T read `go.sum` entirely into context — use `grep` or other tools to search specific patterns if needed - DON'T skip `go vet ./...` before finishing work - DON'T commit without explicit user request +- DON'T add, remove, or change Go module dependencies after debugging has started — ask for explicit permission first + +## Debugging Principles + +When a test failure occurs, follow this strict order: + +1. **Examine the test first** — ensure the test code correctly expresses the intended program behavior +2. **Fix the test if it's wrong** — if the test doesn't represent correct expected behavior, correct the test to match the intended behavior +3. **Fix the implementation if the test is correct** — only after confirming the test is valid, locate and fix the bug in the implementation +4. **Never weaken tests to gain passing status** — do not relax assertions, remove edge cases, or simplify test logic just to make tests pass. Tests exist to catch problems, not to produce a 100% pass rate +5. **Escalate after 6 rounds** — if a problem remains unresolved after 6 debugging attempts, stop and report the current state to the user for further investigation diff --git a/cmd/serve.go b/cmd/serve.go index c1cccb9..682223d 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -29,7 +29,16 @@ var serveCmd = &cobra.Command{ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() - webApp := app.NewWebApp(cfg) + webApp, err := app.Bootstrap(cfg) + if err != nil { + return fmt.Errorf("bootstrap: %w", err) + } + defer func() { + if err := webApp.Close(); err != nil { + fmt.Fprintf(os.Stderr, "close webapp: %v\n", err) + } + }() + router := server.NewRouter(webApp) addr := server.Address(webApp.Config.Server) diff --git a/config.example.yaml b/config.example.yaml index 43f314d..e554dae 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -4,7 +4,15 @@ server: database: driver: sqlite3 - path: data/mygo.db + sqlite: + path: data/mygo.db + postgres: + host: localhost + port: 5432 + user: mygo + password: mygo + dbname: mygo + sslmode: disable storage: driver: local diff --git a/docs/roadmap.md b/docs/roadmap.md index 46d4ef0..c49dd4d 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -16,12 +16,12 @@ Package-level implementation order (each task includes unit tests): 1. `internal/config` — Viper loader, config struct -2. `internal/app` — runtime dependency container 🛠 WIP -3. `internal/model` — domain types, error codes -4. `internal/api` — error response helpers 🛠 WIP +2. `internal/app` — runtime dependency container ✅ +3. `internal/model` — domain types, error codes ✅ +4. `internal/api` — error response helpers ✅ 5. `internal/auth` — JWT utils 6. `internal/storage` — backend interface + local fs -7. `internal/repository` — interfaces + GORM/SQLite impl +7. `internal/repository` — interfaces + GORM/SQLite impl ✅ 8. `internal/service` — auth, file, admin services 9. `internal/middleware` — logger, cors, auth 10. `internal/handler` — auth, file, admin handlers 🛠 WIP diff --git a/go.mod b/go.mod index 42283aa..d544ffc 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,9 @@ require ( github.com/gin-gonic/gin v1.12.0 github.com/spf13/cobra v1.10.2 github.com/spf13/viper v1.21.0 + gorm.io/driver/postgres v1.6.0 + gorm.io/driver/sqlite v1.6.0 + gorm.io/gorm v1.30.5 ) require ( @@ -23,10 +26,17 @@ require ( github.com/goccy/go-json v0.10.5 // indirect github.com/goccy/go-yaml v1.19.2 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/pgx/v5 v5.6.0 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-sqlite3 v1.14.22 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect @@ -45,6 +55,7 @@ require ( golang.org/x/arch v0.22.0 // indirect golang.org/x/crypto v0.48.0 // indirect golang.org/x/net v0.51.0 // indirect + golang.org/x/sync v0.19.0 // indirect golang.org/x/sys v0.41.0 // indirect golang.org/x/text v0.34.0 // indirect google.golang.org/protobuf v1.36.10 // indirect diff --git a/go.sum b/go.sum index bac833e..9cb85f6 100644 --- a/go.sum +++ b/go.sum @@ -39,6 +39,18 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY= +github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= @@ -51,6 +63,8 @@ github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= +github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -87,6 +101,7 @@ github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSS github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= @@ -111,6 +126,8 @@ golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo= golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= @@ -124,3 +141,9 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EV gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4= +gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo= +gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ= +gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8= +gorm.io/gorm v1.30.5 h1:dvEfYwxL+i+xgCNSGGBT1lDjCzfELK8fHZxL3Ee9X0s= +gorm.io/gorm v1.30.5/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE= diff --git a/internal/app/webapp.go b/internal/app/webapp.go index 01bc2ba..4bab6eb 100644 --- a/internal/app/webapp.go +++ b/internal/app/webapp.go @@ -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() +} diff --git a/internal/app/webapp_test.go b/internal/app/webapp_test.go index 96e23f9..4999ba2 100644 --- a/internal/app/webapp_test.go +++ b/internal/app/webapp_test.go @@ -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) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index e4e820f..6ab8f81 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -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 == "" { diff --git a/internal/config/load.go b/internal/config/load.go index 03ee4a4..0861549 100644 --- a/internal/config/load.go +++ b/internal/config/load.go @@ -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") diff --git a/internal/config/load_test.go b/internal/config/load_test.go index 12b19cb..2a44c5b 100644 --- a/internal/config/load_test.go +++ b/internal/config/load_test.go @@ -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") } } diff --git a/internal/model/errors.go b/internal/model/errors.go new file mode 100644 index 0000000..9f77f81 --- /dev/null +++ b/internal/model/errors.go @@ -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") +) diff --git a/internal/model/file.go b/internal/model/file.go new file mode 100644 index 0000000..2f71e7b --- /dev/null +++ b/internal/model/file.go @@ -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"` +} diff --git a/internal/model/session.go b/internal/model/session.go new file mode 100644 index 0000000..736b18f --- /dev/null +++ b/internal/model/session.go @@ -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"` +} diff --git a/internal/model/user.go b/internal/model/user.go new file mode 100644 index 0000000..9c7ee99 --- /dev/null +++ b/internal/model/user.go @@ -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"` +} diff --git a/internal/repository/db.go b/internal/repository/db.go new file mode 100644 index 0000000..b2a39a1 --- /dev/null +++ b/internal/repository/db.go @@ -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{}, + ) +} diff --git a/internal/repository/db_test.go b/internal/repository/db_test.go new file mode 100644 index 0000000..b5cbc30 --- /dev/null +++ b/internal/repository/db_test.go @@ -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) + } + } +} diff --git a/internal/repository/file.go b/internal/repository/file.go new file mode 100644 index 0000000..efbe12c --- /dev/null +++ b/internal/repository/file.go @@ -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 +} diff --git a/internal/repository/file_test.go b/internal/repository/file_test.go new file mode 100644 index 0000000..1f75ef7 --- /dev/null +++ b/internal/repository/file_test.go @@ -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) + } +} diff --git a/internal/repository/session.go b/internal/repository/session.go new file mode 100644 index 0000000..4346984 --- /dev/null +++ b/internal/repository/session.go @@ -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 +} diff --git a/internal/repository/session_test.go b/internal/repository/session_test.go new file mode 100644 index 0000000..7556778 --- /dev/null +++ b/internal/repository/session_test.go @@ -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) + } +} diff --git a/internal/repository/user.go b/internal/repository/user.go new file mode 100644 index 0000000..18ccdfb --- /dev/null +++ b/internal/repository/user.go @@ -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 +} diff --git a/internal/repository/user_test.go b/internal/repository/user_test.go new file mode 100644 index 0000000..07a1f29 --- /dev/null +++ b/internal/repository/user_test.go @@ -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) + } +} diff --git a/internal/server/server_test.go b/internal/server/server_test.go index d6d11c3..71a50e6 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -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)