mirror of https://github.com/jackc/pgx.git
Add timestamptz transcoding
parent
fdeb2412ec
commit
faed7f2879
|
@ -45,7 +45,7 @@ func (c *Connection) SanitizeSql(sql string, args ...interface{}) (output string
|
|||
case int64:
|
||||
return strconv.FormatInt(int64(arg), 10)
|
||||
case time.Time:
|
||||
return c.QuoteString(arg.Format("2006-01-02 15:04:05.999999999 -0700"))
|
||||
return c.QuoteString(arg.Format("2006-01-02 15:04:05.999999 -0700"))
|
||||
case uint:
|
||||
return strconv.FormatUint(uint64(arg), 10)
|
||||
case uint8:
|
||||
|
|
|
@ -94,6 +94,11 @@ func init() {
|
|||
DecodeText: decodeDateFromText,
|
||||
EncodeTo: encodeDate}
|
||||
|
||||
// timestamptz
|
||||
ValueTranscoders[Oid(1184)] = &ValueTranscoder{
|
||||
DecodeText: decodeTimestampTzFromText,
|
||||
EncodeTo: encodeTimestampTz}
|
||||
|
||||
// use text transcoder for anything we don't understand
|
||||
defaultTranscoder = ValueTranscoders[Oid(25)]
|
||||
}
|
||||
|
@ -284,3 +289,19 @@ func encodeDate(w *MessageWriter, value interface{}) {
|
|||
w.Write(int32(len(s)))
|
||||
w.WriteString(s)
|
||||
}
|
||||
|
||||
func decodeTimestampTzFromText(mr *MessageReader, size int32) interface{} {
|
||||
s := mr.ReadByteString(size)
|
||||
t, err := time.Parse("2006-01-02 15:04:05.999999-07", s)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("Can't decode timestamptz: %v", err))
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func encodeTimestampTz(w *MessageWriter, value interface{}) {
|
||||
t := value.(time.Time)
|
||||
s := t.Format("2006-01-02 15:04:05.999999 -0700")
|
||||
w.Write(int32(len(s)))
|
||||
w.WriteString(s)
|
||||
}
|
||||
|
|
|
@ -32,3 +32,31 @@ func TestDateTranscode(t *testing.T) {
|
|||
t.Errorf("Did not transcode date successfully: %v is not %v", v, actualDate)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimestampTzTranscode(t *testing.T) {
|
||||
conn := getSharedConnection()
|
||||
|
||||
inputTime := time.Date(2013, 1, 2, 3, 4, 5, 6000, time.Local)
|
||||
|
||||
var v interface{}
|
||||
var outputTime time.Time
|
||||
|
||||
v = mustSelectValue(t, conn, "select $1::timestamptz", inputTime)
|
||||
outputTime = v.(time.Time)
|
||||
if !inputTime.Equal(outputTime) {
|
||||
t.Errorf("Did not transcode time successfully: %v is not %v", outputTime, inputTime)
|
||||
}
|
||||
|
||||
mustPrepare(t, conn, "testTranscode", "select $1::timestamptz")
|
||||
defer func() {
|
||||
if err := conn.Deallocate("testTranscode"); err != nil {
|
||||
t.Fatalf("Unable to deallocate prepared statement: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
v = mustSelectValue(t, conn, "testTranscode", inputTime)
|
||||
outputTime = v.(time.Time)
|
||||
if !inputTime.Equal(outputTime) {
|
||||
t.Errorf("Did not transcode time successfully: %v is not %v", outputTime, inputTime)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue