Skip to content

Commit

Permalink
Time scanner.
Browse files Browse the repository at this point in the history
  • Loading branch information
ncruces committed Oct 17, 2023
1 parent 8d0c654 commit 58c5009
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
33 changes: 33 additions & 0 deletions tests/time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"time"

"github.com/ncruces/go-sqlite3"
"github.com/ncruces/go-sqlite3/driver"
)

func TestTimeFormat_Encode(t *testing.T) {
Expand Down Expand Up @@ -119,6 +120,38 @@ func TestTimeFormat_Decode(t *testing.T) {
}
}

func TestTimeFormat_Scanner(t *testing.T) {
t.Parallel()

db, err := driver.Open(":memory:", nil)
if err != nil {
t.Fatal(err)
}
defer db.Close()

_, err = db.Exec(
`CREATE TABLE IF NOT EXISTS test (col)`)
if err != nil {
t.Fatal(err)
}

reference := time.Date(2013, 10, 7, 4, 23, 19, 120_000_000, time.FixedZone("", -4*3600))

_, err = db.Exec(`INSERT INTO test VALUES (?)`, sqlite3.TimeFormat7TZ.Encode(reference))
if err != nil {
t.Fatal(err)
}

var got time.Time
err = db.QueryRow("SELECT * FROM test").Scan(sqlite3.TimeFormatAuto.Scanner(&got))
if err != nil {
t.Fatal(err)
}
if !got.Equal(reference) {
t.Errorf("got %v, want %v", got, reference)
}
}

func TestDB_timeCollation(t *testing.T) {
t.Parallel()

Expand Down
16 changes: 16 additions & 0 deletions time.go
Original file line number Diff line number Diff line change
Expand Up @@ -338,3 +338,19 @@ func (f TimeFormat) parseRelaxed(s string) (time.Time, error) {
}
return t, nil
}

// Scanner returns a [database/sql.Scanner] that
// decodes a time value into dest using this format.
func (f TimeFormat) Scanner(dest *time.Time) interface{ Scan(any) error } {
return timeScanner{dest, f}
}

type timeScanner struct {
*time.Time
TimeFormat
}

func (s timeScanner) Scan(src any) (err error) {
*s.Time, err = s.Decode(src)
return
}
1 change: 1 addition & 0 deletions wiki
Submodule wiki added at 9f062e

0 comments on commit 58c5009

Please sign in to comment.