87 lines
2.2 KiB
Go
87 lines
2.2 KiB
Go
package db
|
|
|
|
import (
|
|
"path"
|
|
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/logger"
|
|
"gorm.io/driver/sqlite"
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"reichard.io/imagini/internal/config"
|
|
"reichard.io/imagini/internal/models"
|
|
)
|
|
|
|
type DBManager struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewMgr(c *config.Config) *DBManager {
|
|
gormConfig := &gorm.Config{
|
|
PrepareStmt: true,
|
|
Logger: logger.Default.LogMode(logger.Silent),
|
|
}
|
|
|
|
// Create manager
|
|
dbm := &DBManager{}
|
|
|
|
if c.DBType == "SQLite" {
|
|
dbLocation := path.Join(c.ConfigPath, "imagini.db")
|
|
dbm.db, _ = gorm.Open(sqlite.Open(dbLocation), gormConfig)
|
|
} else {
|
|
log.Fatal("Unsupported Database")
|
|
}
|
|
|
|
// Initialize database
|
|
dbm.db.AutoMigrate(&models.ServerSetting{})
|
|
dbm.db.AutoMigrate(&models.Device{})
|
|
dbm.db.AutoMigrate(&models.User{})
|
|
dbm.db.AutoMigrate(&models.MediaItem{})
|
|
dbm.db.AutoMigrate(&models.Tag{})
|
|
dbm.db.AutoMigrate(&models.Album{})
|
|
|
|
// Determine whether to bootstrap
|
|
var count int64
|
|
dbm.db.Model(&models.User{}).Count(&count)
|
|
if count == 0 {
|
|
dbm.bootstrapDatabase()
|
|
}
|
|
|
|
return dbm
|
|
}
|
|
|
|
func (dbm *DBManager) bootstrapDatabase() {
|
|
log.Info("[query] Bootstrapping database.")
|
|
err := dbm.CreateUser(models.User{
|
|
Username: "admin",
|
|
Password: "admin",
|
|
AuthType: "Local",
|
|
})
|
|
|
|
if err != nil {
|
|
log.Fatal("[query] Unable to bootstrap database.")
|
|
}
|
|
}
|
|
|
|
func (dbm *DBManager) ItemsFromAlbum(user models.User, album models.Album) []models.MediaItem {
|
|
var mediaItems []models.MediaItem
|
|
// db.Table("media_albums").
|
|
// Select("media_item.*").
|
|
// Joins("INNER JOIN media_items ON media_albums.ID = media_items.Albums").
|
|
// Where("media_albums.album_id = ? AND media_items.User = ?", albumID, userID).
|
|
|
|
|
|
dbm.db.
|
|
//Where("album = ? AND user = ?", albumID, userID).
|
|
Find(&mediaItems)
|
|
return mediaItems
|
|
|
|
// db.Raw(`
|
|
// SELECT
|
|
// MediaItems.*
|
|
// FROM
|
|
// MediaAlbums
|
|
// INNER JOIN MediaItems ON MediaAlbums.mediaID = MediaItems.mediaID
|
|
// WHERE MediaAlbums.albumID = ? AND MediaItems.userID = ?`, albumID, userID)
|
|
}
|