在Postgresql-simple中检索带时区的时间戳

时间:2016-04-14 21:03:46

标签: haskell

我知道此问题已在past before中提出,现在标记为已解决。

我正在使用postgresql-simple包和Data.Time。如果我进行查询以检索类型为timestamptz的单个列,则会出现模式匹配错误。下面的伪代码:

import Data.Text as T
import Data.Time (UTCTime,LocalTime,ZonedTime)
import Database.PostgreSQL.Simple as Pg
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.ToRow
import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.Time
import qualified Data.Vector as V
...
--- in main this is the code
[Pg.Only (i::UTCTime)] <- Pg.query conn "select lastupdated from constraints where name=?" ( Only ("carrier"::T.Text))
...

执行查询时,我在运行时遇到此错误(请注意以上内容:

*** Exception: user error (Pattern match failure in do expression at ...)

如果我将上面更改为无效类型,如下所示:

[Pg.Only (i::T.Text)] <- Pg.query conn "select lastupdated from constraints where name=?" ( Only ("carrier"::T.Text))

我对类型有异常,表明期望的类型确实是timestamptz

*** Exception: Incompatible {errSQLType = "timestamptz",...,
errSQLField = "lastupdated", errHaskellType = "Text", errMessage = "types incompatible"}

此外,这是上述查询结果在psql控制台中的显示方式:

          lastupdated          
-------------------------------
 2016-04-13 00:08:33.789761+00
 2016-04-13 14:33:38.27739+00
(2 rows)

我的理解是Data.Time.UTCTimeDatabase.PostgreSQL.Simple.Time.UTCTimestamp应该映射到timestamptz类型的PostgreSQL。显然,如果我得到上述错误,那理解是错误的。非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

请改为尝试:

(times :: [Pg.Only UTCTime]) <-
    Pg.query conn "select lastupdated from constraints where name=?" (Only ("carrier" :: T.Text))

您的模式匹配不仅强制执行Only UTCTime的列表,而且列表中只有一个元素。由于您有两条记录,query将返回一个包含两个元素的列表,并且模式匹配失败。