go-sql-driver / go-sql-driver/mysql

add support for time.Duration

Open
#1,217 9 comments 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
15.3k
Forks
2.3k
Avg merge
2h 23m
Merged PRs (30d)
10

Description

Today I learned two fun facts:
1. in MySQL, although `now()` is a datetime, `now() + 0` is an integer formed from all of the decimal digits in the date. e.g. 2021-05-27 17:00:26 vs 20210527170026. (I'm not sure why one would ever want that.)
2. in Go's `database/sql` API for prepared statements, "?" applied to a duration value treats the duration (thanks to reflection on the underlying type) as an integer number of nanoseconds, not an interval. I don't know why one would ever want that either, since nanoseconds are not really useful in SQL.

The combination of these two facts means that the behavior of `query("now() + ?", 1*time.Hour)` isn't remotely close to what one might expect:
```
mysql> select now(), now() + interval 1 hour, now() + 60*60*1e9;
+---------------------+-------------------------+-------------------+
| now() | now() + interval 1 hour | now() + 60*60*1e9 |
+---------------------+-------------------------+-------------------+
| 2021-05-27 17:13:53 | 2021-05-27 18:13:53 | 23810527171353 |
+---------------------+-------------------------+-------------------+
1 row in set (0.00 sec)
```
Perhaps go-sql-driver could support time.Duration by mapping it to `interval 1 hour`, thereby avoiding this pitfall.
Alternatively, simply rejecting it with a clear error ("you cannot possibly have wanted this behavior") would be an improvement.

(See also https://github.com/golang/go/issues/46427: I reported this initially against database/sql, and it was closed as a driver-specific issue.)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.