Skip to content

Commit

Permalink
Merge pull request #71 from whywaita/feat/mysql-loc
Browse files Browse the repository at this point in the history
fix MySQL timezone to UTC
  • Loading branch information
whywaita authored Jun 24, 2021
2 parents 28f61d7 + 54a5d26 commit 995257c
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion pkg/datastore/mysql/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package mysql

import (
"fmt"
"time"

"github.com/go-sql-driver/mysql"

"github.com/jmoiron/sqlx"

Expand All @@ -16,7 +19,12 @@ type MySQL struct {

// New create mysql connection
func New(dsn string) (*MySQL, error) {
conn, err := sqlx.Open("mysql", dsn+"?parseTime=true&loc=Local")
u, err := getMySQLURL(dsn)
if err != nil {
return nil, fmt.Errorf("failed to get MySQL URL: %w", err)
}

conn, err := sqlx.Open("mysql", u)
if err != nil {
return nil, fmt.Errorf("failed to create mysql connection: %w", err)
}
Expand All @@ -25,3 +33,22 @@ func New(dsn string) (*MySQL, error) {
Conn: conn,
}, nil
}

func getMySQLURL(dsn string) (string, error) {
c, err := mysql.ParseDSN(dsn)
if err != nil {
return "", fmt.Errorf("failed to parse DSN: %w", err)
}

c.Loc = time.UTC
c.ParseTime = true
c.Collation = "utf8mb4_general_ci"
if c.Params == nil {
c.Params = map[string]string{}
}
c.Params["sql_mode"] = "'TRADITIONAL,NO_AUTO_VALUE_ON_ZERO,ONLY_FULL_GROUP_BY'"

c.InterpolateParams = true

return c.FormatDSN(), nil
}

0 comments on commit 995257c

Please sign in to comment.