Skip to content
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 25 additions & 17 deletions migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package migrate

import (
"bufio"
"errors"
"fmt"
"io"
"time"
Expand Down Expand Up @@ -118,7 +119,7 @@ func (m *Migration) LogString() string {

// Buffer buffers Body up to BufferSize.
// Calling this function blocks. Call with goroutine.
func (m *Migration) Buffer() error {
func (m *Migration) Buffer() (err error) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rename this so we can continue to use err below

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done. renamed to berr

if m.Body == nil {
return nil
}
Expand All @@ -127,34 +128,41 @@ func (m *Migration) Buffer() error {

b := bufio.NewReaderSize(m.Body, int(m.BufferSize))

// defer closing buffer writer and body.
// defer blocks run in reverse order
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we use a single defer instead to avoid this confusion?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


// close the Body.
defer func() {
if cerr := m.Body.Close(); cerr != nil {
err = errors.Join(err, cerr)
}
}()

// always close bufferWriter, even on error, to prevent deadlocks.
// this lets Buffer know that there is no more data coming.
defer func() {
if cerr := m.bufferWriter.Close(); cerr != nil {
err = errors.Join(err, cerr)
}
}()

// start reading from body, peek won't move the read pointer though
// poor man's solution?
if _, err := b.Peek(int(m.BufferSize)); err != nil && err != io.EOF {
return err
if _, perr := b.Peek(int(m.BufferSize)); perr != nil && perr != io.EOF {
return perr
}

m.FinishedBuffering = time.Now()

// write to bufferWriter, this will block until
// something starts reading from m.Buffer
n, err := b.WriteTo(m.bufferWriter)
if err != nil {
return err
n, werr := b.WriteTo(m.bufferWriter)
if werr != nil {
return werr
}

m.FinishedReading = time.Now()
m.BytesRead = n

// close bufferWriter so Buffer knows that there is no
// more data coming
if err := m.bufferWriter.Close(); err != nil {
return err
}

// it's safe to close the Body too
if err := m.Body.Close(); err != nil {
return err
}

return nil
}