Techradar
Techradar

Reputation: 4154

Golang DB de-/serialization method (sqlx on top ofdatabase/sql)

I have a Timestamp column in the database and a struct with a type int64 that should load the column as a integer timestamp.

Query:

select date from table;

Error:

sql: Scan error on column index 1, name "date": converting driver.Value type time.Time ("2019-04-14 21:49:59.159317 +0000 +0000") to a int64: invalid syntax

Is there a way to define a serialization method on the struct instead of casting the timestamp to int64 at the query level (extract epoch...).

Upvotes: 0

Views: 763

Answers (1)

mkopriva
mkopriva

Reputation: 38313

You need a custom int64 type so that you can then have it implement the sql.Scanner interface.

type Timestamp int64

func (ts *Timestamp) Scan(src interface{}) error {
    switch v := src.(type) {
    case time.Time:
        *ts = Timestamp(v.Unix())
    case []byte:
        // ...
    case string:
        // ...
    }
    return nil
}

With this you can either use conversion when scanning the result:

type Record struct {
    Date int64
}

var r Record
if err := db.QueryRow("select data from table").Scan((*Timestamp)(&r.Date)); err != nil {
    panic(err)
}

Or you can change the field's type in the struct definition and then you can scan directly into the field:

type Record struct {
    Date Timestamp
}

var r Record
if err := db.QueryRow("select data from table").Scan(&r.Date); err != nil {
    panic(err)
}

Upvotes: 1

Related Questions