linstrom/storage/storage.go
2024-08-28 17:20:38 +02:00

48 lines
1.1 KiB
Go

package storage
import (
"github.com/glebarez/sqlite"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
// Storage is responsible for all database, cache and media related actions
// and serves as the lowest layer of the cake
type Storage struct {
db *gorm.DB
}
// Build a new storage using sqlite as database backend
func NewStorageSqlite(filePath string) (*Storage, error) {
db, err := gorm.Open(sqlite.Open(filePath))
if err != nil {
return nil, err
}
return storageFromEmptyDb(db)
}
func NewStoragePostgres(dbUrl string) (*Storage, error) {
db, err := gorm.Open(postgres.Open(dbUrl))
if err != nil {
return nil, err
}
return storageFromEmptyDb(db)
}
func storageFromEmptyDb(db *gorm.DB) (*Storage, error) {
// AutoMigrate ensures the db is in a state where all the structs given here
// have their own tables and relations setup. It also updates tables if necessary
db.AutoMigrate(
MediaFile{},
Account{},
RemoteServer{},
Note{},
Role{},
PasskeySession{},
)
// And finally, build the actual storage struct
return &Storage{
db: db,
}, nil
}