Skip to content

Commit

Permalink
Introduce RegisterReaderHandlerWithEncoderInfo
Browse files Browse the repository at this point in the history
It is the same as RegisterReaderHandler, but receives some configuration
settings which are needed to correctly encode the TSV. (For now only the
Location).

issue go-sql-driver#1416
  • Loading branch information
Jille committed Apr 26, 2023
1 parent 8503110 commit 6f7eca0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ Jeffrey Charles <jeffreycharles at gmail.com>
Jerome Meyer <jxmeyer at gmail.com>
Jiajia Zhong <zhong2plus at gmail.com>
Jian Zhen <zhenjl at gmail.com>
Jille Timmermans <jille at quis.cx>
Joshua Prunier <joshua.prunier at gmail.com>
Julien Lefevre <julien.lefevr at gmail.com>
Julien Schmidt <go-sql-driver at julienschmidt.com>
Expand Down
26 changes: 23 additions & 3 deletions infile.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,27 @@ import (
"os"
"strings"
"sync"
"time"
)

var (
fileRegister map[string]bool
fileRegisterLock sync.RWMutex
readerRegister map[string]func() io.Reader
readerRegister map[string]func(EncoderInfo) io.Reader
readerRegisterLock sync.RWMutex
)

// EncoderInfo contains the settings needed to encode a TSV file for LOAD DATA INFILE.
type EncoderInfo struct {
Location *time.Location
}

func (c *Config) encoderInfo() EncoderInfo {
return EncoderInfo{
Location: c.Loc,
}
}

// RegisterLocalFile adds the given file to the file allowlist,
// so that it can be used by "LOAD DATA LOCAL INFILE <filepath>".
// Alternatively you can allow the use of all local files with
Expand Down Expand Up @@ -66,10 +78,18 @@ func DeregisterLocalFile(filePath string) {
// if err != nil {
// ...
func RegisterReaderHandler(name string, handler func() io.Reader) {
RegisterReaderHandlerWithEncoderInfo(name, func(EncoderInfo) io.Reader {
return handler()
})
}

// RegisterReaderHandlerWithEncoderInfo is like RegisterReaderHandler but the
// callback receives the information needed to correctly encode a TSV file.
func RegisterReaderHandlerWithEncoderInfo(name string, handler func(EncoderInfo) io.Reader) {
readerRegisterLock.Lock()
// lazy map init
if readerRegister == nil {
readerRegister = make(map[string]func() io.Reader)
readerRegister = make(map[string]func(EncoderInfo) io.Reader)
}

readerRegister[name] = handler
Expand Down Expand Up @@ -110,7 +130,7 @@ func (mc *mysqlConn) handleInFileRequest(name string) (err error) {
readerRegisterLock.RUnlock()

if inMap {
rdr = handler()
rdr = handler(mc.cfg.encoderInfo())
if rdr != nil {
if cl, ok := rdr.(io.Closer); ok {
defer deferredClose(&err, cl)
Expand Down

0 comments on commit 6f7eca0

Please sign in to comment.