linstrom/storage/storage.go

64 lines
1.6 KiB
Go
Raw Normal View History

2024-09-13 09:58:29 +00:00
// TODO: Unify function names
// Storage is the handler for cache and db access
// It handles storing various data in the database as well as caching that data
// Said data includes notes, accounts, metadata about media files, servers and similar
2024-05-31 09:54:39 +00:00
package storage
import (
2024-09-12 06:56:57 +00:00
"errors"
2024-05-31 09:54:39 +00:00
"github.com/glebarez/sqlite"
2024-09-12 06:56:57 +00:00
"gitlab.com/mstarongitlab/linstrom/storage/cache"
2024-05-31 09:54:39 +00:00
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
2024-05-31 15:21:29 +00:00
// Storage is responsible for all database, cache and media related actions
// and serves as the lowest layer of the cake
2024-05-31 09:54:39 +00:00
type Storage struct {
2024-09-12 06:56:57 +00:00
db *gorm.DB
cache *cache.Cache
2024-05-31 09:54:39 +00:00
}
2024-09-12 06:56:57 +00:00
var ErrInvalidData = errors.New("invalid data")
2024-05-31 15:21:29 +00:00
// Build a new storage using sqlite as database backend
2024-09-12 06:56:57 +00:00
func NewStorageSqlite(filePath string, cache *cache.Cache) (*Storage, error) {
2024-05-31 09:54:39 +00:00
db, err := gorm.Open(sqlite.Open(filePath))
if err != nil {
return nil, err
}
2024-09-12 06:56:57 +00:00
return storageFromEmptyDb(db, cache)
2024-05-31 09:54:39 +00:00
}
2024-09-12 06:56:57 +00:00
func NewStoragePostgres(dbUrl string, cache *cache.Cache) (*Storage, error) {
2024-05-31 09:54:39 +00:00
db, err := gorm.Open(postgres.Open(dbUrl))
if err != nil {
return nil, err
}
2024-09-12 06:56:57 +00:00
return storageFromEmptyDb(db, cache)
2024-05-31 15:21:29 +00:00
}
2024-09-12 06:56:57 +00:00
func storageFromEmptyDb(db *gorm.DB, cache *cache.Cache) (*Storage, error) {
2024-05-31 15:21:29 +00:00
// 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
2024-09-12 06:56:57 +00:00
err := db.AutoMigrate(
2024-09-13 07:18:05 +00:00
MediaMetadata{},
2024-08-28 15:20:38 +00:00
Account{},
RemoteServer{},
Note{},
Role{},
PasskeySession{},
2024-05-31 15:21:29 +00:00
)
2024-09-12 06:56:57 +00:00
if err != nil {
return nil, err
}
2024-05-31 15:21:29 +00:00
// And finally, build the actual storage struct
2024-05-31 09:54:39 +00:00
return &Storage{
2024-09-12 06:56:57 +00:00
db: db,
cache: cache,
2024-05-31 09:54:39 +00:00
}, nil
}