Skip to content

Commit d7e2ac4

Browse files
committed
infile: refactoring
1 parent d503c4b commit d7e2ac4

File tree

1 file changed

+28
-27
lines changed

1 file changed

+28
-27
lines changed

infile.go

Lines changed: 28 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
package mysql
1010

1111
import (
12-
"database/sql/driver"
1312
"fmt"
1413
"io"
1514
"os"
@@ -86,6 +85,16 @@ func (mc *mysqlConn) handleInFileRequest(name string) (err error) {
8685
rdr = handler()
8786
if rdr != nil {
8887
data = make([]byte, 4+mc.maxWriteSize)
88+
89+
if rdc, ok := rdr.(io.ReadCloser); ok {
90+
defer func() {
91+
if err == nil {
92+
err = rdc.Close()
93+
} else {
94+
rdc.Close()
95+
}
96+
}()
97+
}
8998
} else {
9099
err = fmt.Errorf("Reader '%s' is <nil>", name)
91100
}
@@ -99,6 +108,15 @@ func (mc *mysqlConn) handleInFileRequest(name string) (err error) {
99108
var fi os.FileInfo
100109

101110
if file, err = os.Open(name); err == nil {
111+
defer func() {
112+
if err == nil {
113+
err = file.Close()
114+
} else {
115+
file.Close()
116+
}
117+
}()
118+
119+
// get file size
102120
if fi, err = file.Stat(); err == nil {
103121
rdr = file
104122
if fileSize := int(fi.Size()); fileSize <= mc.maxWriteSize {
@@ -115,45 +133,28 @@ func (mc *mysqlConn) handleInFileRequest(name string) (err error) {
115133
}
116134
}
117135

118-
if rdc, ok := rdr.(io.ReadCloser); ok {
119-
defer func() {
120-
if err == nil {
121-
err = rdc.Close()
122-
} else {
123-
rdc.Close()
124-
}
125-
}()
126-
}
127-
128136
// send content packets
129-
var ioErr error
130137
if err == nil {
131138
var n int
132-
for err == nil && ioErr == nil {
139+
for err == nil {
133140
n, err = rdr.Read(data[4:])
134141
if n > 0 {
135-
ioErr = mc.writePacket(data[:4+n])
142+
if ioErr := mc.writePacket(data[:4+n]); ioErr != nil {
143+
return ioErr
144+
}
136145
}
137146
}
138147
if err == io.EOF {
139148
err = nil
140149
}
141-
if ioErr != nil {
142-
errLog.Print(ioErr.Error())
143-
return driver.ErrBadConn
144-
}
145150
}
146151

147152
// send empty packet (termination)
148-
ioErr = mc.writePacket([]byte{
149-
0x00,
150-
0x00,
151-
0x00,
152-
mc.sequence,
153-
})
154-
if ioErr != nil {
155-
errLog.Print(ioErr.Error())
156-
return driver.ErrBadConn
153+
if data == nil {
154+
data = make([]byte, 4)
155+
}
156+
if ioErr := mc.writePacket(data[:4]); ioErr != nil {
157+
return ioErr
157158
}
158159

159160
// read OK packet

0 commit comments

Comments
 (0)