From e3185517424c7903d80cb24b789db2b702a736ce Mon Sep 17 00:00:00 2001 From: Joseph Buchma Date: Mon, 27 Nov 2017 21:12:22 +0200 Subject: [PATCH] Flag for disabling milliseconds time resolution support This change allows to restore v1.2 behavior of dealing with time.Time values. When connection is open with `disableMilliseconds=true` time.Time values will be rounded DOWN to second resolution before insert into database. --- connection.go | 5 +++++ driver.go | 1 + dsn.go | 17 +++++++++++++++++ 3 files changed, 23 insertions(+) diff --git a/connection.go b/connection.go index e57061412..eb26af735 100644 --- a/connection.go +++ b/connection.go @@ -41,6 +41,8 @@ type mysqlConn struct { sequence uint8 parseTime bool + disableMilliseconds bool + // for context support (Go 1.8+) watching bool watcher chan<- mysqlContext @@ -231,6 +233,9 @@ func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (strin if v.IsZero() { buf = append(buf, "'0000-00-00'"...) } else { + if mc.disableMilliseconds { + v = v.Round(time.Second) + } v := v.In(mc.cfg.Loc) v = v.Add(time.Nanosecond * 500) // To round under microsecond year := v.Year() diff --git a/driver.go b/driver.go index d42ce7a3d..ba47da09c 100644 --- a/driver.go +++ b/driver.go @@ -64,6 +64,7 @@ func (d MySQLDriver) Open(dsn string) (driver.Conn, error) { return nil, err } mc.parseTime = mc.cfg.ParseTime + mc.disableMilliseconds = mc.cfg.DisableMilliseconds // Connect to Server if dial, ok := dials[mc.cfg.Net]; ok { diff --git a/dsn.go b/dsn.go index f5ea0d470..a7659ffc1 100644 --- a/dsn.go +++ b/dsn.go @@ -56,6 +56,7 @@ type Config struct { InterpolateParams bool // Interpolate placeholders into query string MultiStatements bool // Allow multiple statements in one query ParseTime bool // Parse time values to time.Time + DisableMilliseconds bool // Disable DATETIME sub-second precision and round time.Time down. RejectReadOnly bool // Reject read-only connections } @@ -226,6 +227,15 @@ func (cfg *Config) FormatDSN() string { } } + if cfg.DisableMilliseconds { + if hasParam { + buf.WriteString("&disableMilliseconds=true") + } else { + hasParam = true + buf.WriteString("?disableMilliseconds=true") + } + } + if cfg.ReadTimeout > 0 { if hasParam { buf.WriteString("&readTimeout=") @@ -488,6 +498,13 @@ func parseDSNParams(cfg *Config, params string) (err error) { return errors.New("invalid bool value: " + value) } + case "disableMilliseconds": + var isBool bool + cfg.DisableMilliseconds, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } + // I/O read Timeout case "readTimeout": cfg.ReadTimeout, err = time.ParseDuration(value)