Time handling.

This commit is contained in:
Nuno Cruces
2023-02-17 10:40:43 +00:00
parent 28cb558d10
commit 72e0415184
3 changed files with 35 additions and 1 deletions

View File

@@ -118,6 +118,10 @@ func (s stmt) Query(args []driver.Value) (driver.Rows, error) {
err = s.stmt.BindBlob(i+1, a)
case time.Time:
err = s.stmt.BindText(i+1, a.Format(time.RFC3339Nano))
case nil:
err = s.stmt.BindNull(i + 1)
default:
panic(assertErr)
}
if err != nil {
return nil, err
@@ -167,9 +171,13 @@ func (r rows) Next(dest []driver.Value) error {
case sqlite3.FLOAT:
dest[i] = r.s.ColumnFloat(i)
case sqlite3.TEXT:
dest[i] = r.s.ColumnText(i)
dest[i] = maybeDate(r.s.ColumnText(i))
case sqlite3.BLOB:
dest[i] = r.s.ColumnBlob(i, nil)
case sqlite3.NULL:
dest[i] = nil
default:
panic(assertErr)
}
}

7
driver/error.go Normal file
View File

@@ -0,0 +1,7 @@
package driver
type errorString string
func (e errorString) Error() string { return string(e) }
const assertErr = errorString("sqlite3: assertion failed")

19
driver/time.go Normal file
View File

@@ -0,0 +1,19 @@
package driver
import (
"database/sql/driver"
"time"
)
// Convert a string in [time.RFC3339Nano] format into a [time.Time]
// if it roundtrips back to the same string.
// This way times can be persisted to, and recovered from, the database,
// but if a string is needed, [database.sql] will recover the same string.
// TODO: optimize and fuzz test.
func maybeDate(text string) driver.Value {
date, err := time.Parse(time.RFC3339Nano, text)
if err == nil && date.Format(time.RFC3339Nano) == text {
return date
}
return text
}