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

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{},
)
}