Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MySQL datetime guardrail #428

Merged
merged 5 commits into from
Jul 3, 2024
Merged
Changes from 2 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
9 changes: 5 additions & 4 deletions lib/mysql/schema/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/binary"
"fmt"
"math"
"strings"
"time"
)

Expand Down Expand Up @@ -82,13 +83,13 @@ func ConvertValue(value any, colType DataType) (any, error) {
return nil, fmt.Errorf("expected []byte got %T for value: %v", value, value)
}

if string(bytesValue) == "0000-00-00 00:00:00" {
// MySQL supports '0000-00-00 00:00:00' for datetime columns.
// We are returning `nil` here because this will fail most Time parsers.
stringValue := string(bytesValue)
if strings.HasSuffix(stringValue, "-00-00 00:00:00") {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Reading the MySQL docs it seems like it's also possible for the date to be non-zero and the month zero, or vice versa, so maybe what we want to do is lop off just the date, split by hyphens, and then check if any of the three segments is only zeros, something like:

func hasNonStrictModeDate(d string) bool {
	if len(d) < 10 {
		return false
	}
	parts := strings.Split(d[:10], "-")
	if len(parts) != 3 {
		return false
	}
	for _, part := range parts {
		value, err := strconv.Atoi(part)
		if err != nil {
			return false
		}
		if value == 0 {
			return true
		}
	}
	return false
}

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

date to be non-zero and the month zero

Oh god.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yeah makes sense

Copy link
Collaborator

Choose a reason for hiding this comment

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

Not to mention whether it's possible to have a zero day/month but a non-zero h/m/s. 😬

// If MySQL strict mode isn't turned on, it can allow invalid dates like 2020-00-00 00:00:00 or 0000-00-00 00:00:00
return nil, nil
}

timeValue, err := time.Parse(DateTimeFormat, string(bytesValue))
timeValue, err := time.Parse(DateTimeFormat, stringValue)
if err != nil {
return nil, err
}
Expand Down