pkgdash/internal/storage/storage.go
Vasiliy Tolstov 78f0ae14d7 rewrite
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2023-08-16 13:17:42 +03:00

70 lines
1.9 KiB
Go

package storage
import (
"context"
"database/sql"
"embed"
"errors"
"git.unistack.org/unistack-org/pkgdash/internal/models"
// "git.unistack.org/unistack-org/pkgdash/internal/storage/postgres"
"git.unistack.org/unistack-org/pkgdash/internal/storage/sqlite"
pb "git.unistack.org/unistack-org/pkgdash/proto"
)
//go:embed migrations
var fs embed.FS
var storages = map[string]func(*sql.DB, embed.FS) interface{}{
//"postgres": postgres.NewStorage(),
"sqlite": sqlite.NewStorage(),
}
type contextKey string
var storeIdent = contextKey("store")
type Migrate interface {
MigrateUp() error
MigrateDown() error
}
type Storage interface {
Migrate
PackagesCreate(ctx context.Context, req *pb.PackagesCreateReq) error
PackagesList(ctx context.Context, req *pb.PackagesListReq) ([]*models.Package, error)
PackagesUpdate(ctx context.Context, req *pb.PackagesUpdateReq) error
PackagesDelete(ctx context.Context, req *pb.PackagesDeleteReq) error
CommentsCreate(ctx context.Context, req *pb.CommentsCreateReq) (*models.Comment, error)
CommentsDelete(ctx context.Context, req *pb.CommentsDeleteReq) error
CommentsList(ctx context.Context, req *pb.CommentsListReq) ([]*models.Comment, error)
InsertButchModules(ctx context.Context, req []models.Module) ([]uint64, error)
ModulesList(ctx context.Context, req *pb.ModulesListReq) ([]*models.Module, error)
}
func NewStorage(name string, db *sql.DB) (Storage, error) {
function, ok := storages[name]
if !ok {
return nil, errors.New("incorrect name store")
}
store := function(db, fs)
database, ok := store.(Storage)
if !ok {
return nil, errors.New("dont implements interface Storage")
}
return database, nil
}
func InContext(ctx context.Context, val Storage) context.Context {
return context.WithValue(ctx, storeIdent, val)
}
func FromContext(ctx context.Context) (Storage, error) {
if store, ok := ctx.Value(storeIdent).(Storage); !ok {
return nil, errors.New("empty store")
} else {
return store, nil
}
}