fix transaction already commited error

I encountered with the following error:

> 2023/02/05 07:33:00 /app/scanner/face_detection/face_detector.go:92 sql: transaction has already been committed or rolled back
> [0.042ms] [rows:0] SELECT * FROM `media` WHERE `media`.`id` = 823 ORDER BY `media`.`id` LIMIT 1
> 2023/02/05 07:33:00 ERROR: Error detecting faces in image (/photos/Borzsony2017/DSC_0028.NEF): sql: transaction has already been committed or rolled back

It turned out it comes from the api/routes/photos.go

I found a very similar code in album_scanner.go.
The difference I saw was that while in the single photo request the
transaction passed to the `scanner_tasks.Tasks.BeforeProcessMedia` call,
in the album_scann.go the transaction created after this call and
created from the context which returned by `BeforeProcessMedia`.

Another difference was that in the `ProcessSingleMedia` call the
`AfterProcessMedia` call was called with the same - db transaction -
context, in the album_scanner it was called outside of the transaction.

I changed the logic by merging the two behavior:
Create the transaction from the context of `BeforeProcessMedia` and also
use the transaction context in the `AfterProcessMedia`.
After the change the error disappeared.

So to have it in a common place I extracted that logic into a function
and use for both the single photo request and in the album scanner.

I did not go more deeper to find out what's going on with the context
under the hood.
This commit is contained in:
Lajos Koszti
2023-02-03 09:14:30 +01:00
parent 92bcba0334
commit 1f8664d7f8
5 changed files with 61 additions and 76 deletions

View File

@@ -86,7 +86,6 @@ func ValidRootPath(rootPath string) bool {
}
func ScanAlbum(ctx scanner_task.TaskContext) error {
newCtx, err := scanner_tasks.Tasks.BeforeScanAlbum(ctx)
if err != nil {
return errors.Wrapf(err, "before scan album (%s)", ctx.GetAlbum().Path)
@@ -101,35 +100,10 @@ func ScanAlbum(ctx scanner_task.TaskContext) error {
changedMedia := make([]*models.Media, 0)
for i, media := range albumMedia {
updatedURLs := []*models.MediaURL{}
mediaData := media_encoding.NewEncodeMediaData(media)
// define new ctx for scope of for-loop
ctx, err := scanner_tasks.Tasks.BeforeProcessMedia(ctx, &mediaData)
if err != nil {
return err
}
transactionError := ctx.DatabaseTransaction(func(ctx scanner_task.TaskContext) error {
updatedURLs, err = processMedia(ctx, &mediaData)
if err != nil {
return errors.Wrapf(err, "process media (%s)", media.Path)
}
if len(updatedURLs) > 0 {
changedMedia = append(changedMedia, media)
}
return nil
})
if transactionError != nil {
return errors.Wrap(err, "process media database transaction")
}
if err = scanner_tasks.Tasks.AfterProcessMedia(ctx, &mediaData, updatedURLs, i, len(albumMedia)); err != nil {
return errors.Wrap(err, "after process media")
if err := scanMedia(ctx, media, &mediaData, i, len(albumMedia)); err != nil {
return errors.Wrap(err, "album scan")
}
}