This repository has been archived on 2023-11-13. You can view files and clone it, but cannot push or open issues or pull requests.
imagini/internal/db/db.go
2021-02-01 18:24:09 -05:00

110 lines
2.9 KiB
Go

package db
import (
"fmt"
"path"
"errors"
"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) QueryBuilder(dest interface{}, params []byte) (int64, error) {
// TODO:
// - Where Filters
// - Sort Filters
// - Paging Filters
objType := fmt.Sprintf("%T", dest)
if objType == "*[]models.MediaItem" {
// TODO: Validate MediaItem Type
} else {
// Return Error
return 0, errors.New("Invalid type")
}
var count int64
err := dbm.db.Find(dest).Count(&count).Error;
return count, err
// Paging:
// - Regular Pagination:
// - /api/v1/MediaItems?page[limit]=50&page=2
// - Meta Count Only
// - /api/v1/MediaItems?page[limit]=0
// Sorting:
// - Ascending Sort:
// - /api/v1/MediaItems?sort=created_at
// - Descending Sort:
// - /api/v1/MediaItems?sort=-created_at
// Filters:
// - Greater Than / Less Than (created_at, updated_at, exif_date)
// - /api/v1/MediaItems?filter[created_at]>=2020-01-01&filter[created_at]<=2021-01-01
// - Long / Lat Range (latitude, longitude)
// - /api/v1/MediaItems?filter[latitude]>=71.1827&filter[latitude]<=72.0000&filter[longitude]>=100.000&filter[longitude]<=101.0000
// - Image / Video (media_type)
// - /api/v1/MediaItems?filter[media_type]=Image
// - Tags (tags)
// - /api/v1/MediaItems?filter[tags]=id1,id2,id3
// - Albums (albums)
// - /api/v1/MediaItems?filter[albums]=id1
}