- 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
58 lines
1.3 KiB
Go
58 lines
1.3 KiB
Go
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{},
|
|
)
|
|
}
|