package storage import ( "context" "database/sql" "embed" "errors" "go.unistack.org/unistack-org/pkgdash/models" pb "go.unistack.org/unistack-org/pkgdash/proto" "go.unistack.org/unistack-org/pkgdash/storage/postgres" "go.unistack.org/unistack-org/pkgdash/storage/sqlite" ) //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 ListPackage(ctx context.Context) (models.ListPackage, error) UpdatePackage(ctx context.Context, req *pb.UpdatePackageReq) error AddComment(ctx context.Context, req *pb.AddCommentReq) (uint64, error) AddPackage(ctx context.Context, req *pb.AddPackageReq) error InsertButchModules(ctx context.Context, req []models.Module) ([]uint64, error) GetModule(ctx context.Context, req *pb.GetModuleReq) (models.ListModule, 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 } }