diff --git a/internal/app/datastore.go b/internal/app/datastore.go index 61b304a..2221adb 100644 --- a/internal/app/datastore.go +++ b/internal/app/datastore.go @@ -31,6 +31,7 @@ type ImageMetadataProvider interface { ImageMetadata(relativePath string) (ImageMetaData, error) ImageMetadataToUpload() ([]*ImageMetaData, error) SaveImageMetadata(m ImageMetaData) error + SavePiwigoIdAndUpdateUploadFlag(md5Sum string, piwigoId int) error } type localDataStore struct { @@ -155,6 +156,42 @@ func (d *localDataStore) SaveImageMetadata(img ImageMetaData) error { return tx.Commit() } +func (d *localDataStore) SavePiwigoIdAndUpdateUploadFlag(md5Sum string, piwigoId int) error { + logrus.Tracef("Saving piwigo id %d for file with md5sum %s", piwigoId, md5Sum) + db, err := d.openDatabase() + if err != nil { + return err + } + defer db.Close() + + tx, err := db.Begin() + if err != nil { + return err + } + + stmt, err := tx.Prepare("UPDATE image SET piwigoId = ? WHERE md5sum = ?") + if err != nil { + return err + } + + _, err = stmt.Exec(piwigoId, md5Sum) + if err != nil { + return err + } + + if err != nil { + logrus.Errorf("Rolling back transaction for piwigo id update of file %s", md5Sum) + errTx := tx.Rollback() + if errTx != nil { + logrus.Errorf("Rollback of transaction for piwigo id update of file %s failed!", md5Sum) + } + return err + } + + logrus.Tracef("Commiting piwigo id %d for file with md5sum %s", piwigoId, md5Sum) + return tx.Commit() +} + func (d *localDataStore) insertImageMetaData(tx *sql.Tx, data ImageMetaData) error { stmt, err := tx.Prepare("INSERT INTO image (piwigoId, relativePath, fileName, md5sum, lastChanged, categoryPath, categoryId, uploadRequired) VALUES (?,?,?,?,?,?,?,?)") if err != nil { diff --git a/internal/app/datastore_test.go b/internal/app/datastore_test.go index 41daa03..0d3f4ab 100644 --- a/internal/app/datastore_test.go +++ b/internal/app/datastore_test.go @@ -110,6 +110,30 @@ func TestUniqueIndexOnRelativeFilePath(t *testing.T) { cleanupDatabase(t) } +func TestUpdatePiwigoIdByChecksum(t *testing.T) { + if !dbinitOk { + t.Skip("Skipping test as TestDataStoreInitialize failed!") + } + dataStore := setupDatabase(t) + + filePath := "blah/foo/bar.jpg" + img := getExampleImageMetadata(filePath) + + saveImageShouldNotFail("insert", dataStore, img, t) + img.ImageId = 1 + img.PiwigoId = 1234 + + err := dataStore.SavePiwigoIdAndUpdateUploadFlag(img.Md5Sum, img.PiwigoId) + if err != nil { + t.Errorf("SavePiwigoId: Could not update piwigo id: %s", err) + } + + imgLoad := loadMetadataShouldNotFail("update", dataStore, filePath, t) + EnsureMetadataAreEqual("update", img, imgLoad, t) + + cleanupDatabase(t) +} + func saveImageShouldNotFail(action string, dataStore *localDataStore, img ImageMetaData, t *testing.T) { err := dataStore.SaveImageMetadata(img) if err != nil {