skip empty automigrate templates

This commit is contained in:
Gani Georgiev
2022-12-02 11:36:13 +02:00
parent 6400924d29
commit d2028143df
3 changed files with 56 additions and 15 deletions
+44 -13
View File
@@ -8,8 +8,11 @@ import (
"path/filepath"
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/tools/migrate"
)
const collectionsCacheKey = "migratecmd_collections"
@@ -43,6 +46,9 @@ func (p *plugin) afterCollectionChange() func(*core.ModelEvent) error {
template, templateErr = p.goDiffTemplate(new, old)
}
if templateErr != nil {
if errors.Is(templateErr, emptyTemplateErr) {
return nil // no changes
}
return fmt.Errorf("failed to resolve template: %w", templateErr)
}
@@ -57,23 +63,48 @@ func (p *plugin) afterCollectionChange() func(*core.ModelEvent) error {
}
appliedTime := time.Now().Unix()
fileDest := filepath.Join(p.options.Dir, fmt.Sprintf("%d_%s.%s", appliedTime, action, p.options.TemplateLang))
name := fmt.Sprintf("%d_%s.%s", appliedTime, action, p.options.TemplateLang)
filePath := filepath.Join(p.options.Dir, name)
// ensure that the local migrations dir exist
if err := os.MkdirAll(p.options.Dir, os.ModePerm); err != nil {
return fmt.Errorf("failed to create migration dir: %w", err)
}
return p.app.Dao().RunInTransaction(func(txDao *daos.Dao) error {
// insert the migration entry
_, err := txDao.DB().Insert(migrate.DefaultMigrationsTable, dbx.Params{
"file": name,
"applied": appliedTime,
}).Execute()
if err != nil {
return err
}
if err := os.WriteFile(fileDest, []byte(template), 0644); err != nil {
return fmt.Errorf("failed to save automigrate file: %w", err)
}
// ensure that the local migrations dir exist
if err := os.MkdirAll(p.options.Dir, os.ModePerm); err != nil {
return fmt.Errorf("failed to create migration dir: %w", err)
}
p.refreshCachedCollections()
if err := os.WriteFile(filePath, []byte(template), 0644); err != nil {
return fmt.Errorf("failed to save automigrate file: %w", err)
}
return nil
p.updateSingleCachedCollection(new, old)
return nil
})
}
}
func (p *plugin) updateSingleCachedCollection(new, old *models.Collection) {
cached, _ := p.app.Cache().Get(collectionsCacheKey).(map[string]*models.Collection)
switch {
case new == nil:
delete(cached, old.Id)
default:
cached[new.Id] = new
}
p.app.Cache().Set(collectionsCacheKey, cached)
}
func (p *plugin) refreshCachedCollections() error {
if p.app.Dao() == nil {
return errors.New("app is not initialized yet")
@@ -84,12 +115,12 @@ func (p *plugin) refreshCachedCollections() error {
return err
}
mapped := map[string]*models.Collection{}
cached := map[string]*models.Collection{}
for _, c := range collections {
mapped[c.Id] = c
cached[c.Id] = c
}
p.app.Cache().Set(collectionsCacheKey, mapped)
p.app.Cache().Set(collectionsCacheKey, cached)
return nil
}