Skip to content

Commit 58c5009

Browse files
committed
Time scanner.
1 parent 8d0c654 commit 58c5009

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

tests/time_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"time"
77

88
"github.com/ncruces/go-sqlite3"
9+
"github.com/ncruces/go-sqlite3/driver"
910
)
1011

1112
func TestTimeFormat_Encode(t *testing.T) {
@@ -119,6 +120,38 @@ func TestTimeFormat_Decode(t *testing.T) {
119120
}
120121
}
121122

123+
func TestTimeFormat_Scanner(t *testing.T) {
124+
t.Parallel()
125+
126+
db, err := driver.Open(":memory:", nil)
127+
if err != nil {
128+
t.Fatal(err)
129+
}
130+
defer db.Close()
131+
132+
_, err = db.Exec(
133+
`CREATE TABLE IF NOT EXISTS test (col)`)
134+
if err != nil {
135+
t.Fatal(err)
136+
}
137+
138+
reference := time.Date(2013, 10, 7, 4, 23, 19, 120_000_000, time.FixedZone("", -4*3600))
139+
140+
_, err = db.Exec(`INSERT INTO test VALUES (?)`, sqlite3.TimeFormat7TZ.Encode(reference))
141+
if err != nil {
142+
t.Fatal(err)
143+
}
144+
145+
var got time.Time
146+
err = db.QueryRow("SELECT * FROM test").Scan(sqlite3.TimeFormatAuto.Scanner(&got))
147+
if err != nil {
148+
t.Fatal(err)
149+
}
150+
if !got.Equal(reference) {
151+
t.Errorf("got %v, want %v", got, reference)
152+
}
153+
}
154+
122155
func TestDB_timeCollation(t *testing.T) {
123156
t.Parallel()
124157

time.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,3 +338,19 @@ func (f TimeFormat) parseRelaxed(s string) (time.Time, error) {
338338
}
339339
return t, nil
340340
}
341+
342+
// Scanner returns a [database/sql.Scanner] that
343+
// decodes a time value into dest using this format.
344+
func (f TimeFormat) Scanner(dest *time.Time) interface{ Scan(any) error } {
345+
return timeScanner{dest, f}
346+
}
347+
348+
type timeScanner struct {
349+
*time.Time
350+
TimeFormat
351+
}
352+
353+
func (s timeScanner) Scan(src any) (err error) {
354+
*s.Time, err = s.Decode(src)
355+
return
356+
}

wiki

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Subproject commit 9f062e2a6d06bf984807cdc5e21659ed7e56df5b

0 commit comments

Comments
 (0)