Fix database syncronization
When connecting to the internet for the first time, the proclamations table is empty. If the user navigates to Settings -> Proclamations, then the sync.SyncProclamations function is called. After this function returns, the ProclamationOptions screen queries the database for proclamations which returns an empty list. Even though the database was updated, the ProclamationOptions screen's instance of the database connection was returning empty.
This commit is contained in:
+31
-12
@@ -4,6 +4,7 @@ import (
|
||||
"regexp"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
"rhemawavetech.com/rhemawave/internal/db"
|
||||
"rhemawavetech.com/rhemawave/internal/logger"
|
||||
"rhemawavetech.com/rhemawave/internal/netreq"
|
||||
@@ -43,20 +44,38 @@ func SyncProclamations(database *gorm.DB) ([]db.Proclamation, error) {
|
||||
}
|
||||
|
||||
err = database.Transaction(func(tx *gorm.DB) error {
|
||||
// Clear the database
|
||||
// Where "1 = 1" because batch Delete() requires a condition
|
||||
// 'Where "1 = 1"' is like saying "while true be true" and tricks GORM into deleting everything
|
||||
if err := tx.Where("1 = 1").Delete(db.Proclamation{}).Error; err != nil {
|
||||
ids := make([]string, len(proclamations))
|
||||
for i, p := range proclamations {
|
||||
ids[i] = p.ID
|
||||
}
|
||||
|
||||
if len(ids) == 0 {
|
||||
// API returned nothing → DB should be empty
|
||||
if err := tx.Where("1 = 1").Delete(&db.Proclamation{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
// Remove anything not in API
|
||||
if err := tx.Where("id NOT IN ?", ids).Delete(&db.Proclamation{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Upsert (preserve Selected automatically)
|
||||
if err := tx.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "id"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{
|
||||
"name",
|
||||
"content",
|
||||
"solfeggio_frequency_id",
|
||||
"category_id",
|
||||
"available",
|
||||
"price",
|
||||
}),
|
||||
}).Create(&proclamations).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// Then re-populate the database
|
||||
if err := tx.Save(&proclamations).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// Old sync code
|
||||
// if err := tx.Omit("selected").Save(&proclamations).Error; err != nil {
|
||||
// return err
|
||||
// }
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user