如何在QuasiQuoted Hasql查询代码中将表名作为变量传递?

时间:2015-08-31 10:24:33

标签: postgresql haskell

我正在尝试编写一些通用的Haskell代码,以使用Hasql库将行插入到多个Postgresql表中。

我无法获取替换表名的变量。以下是一些说明错误的示例代码:

.....
> Timeout waiting to lock artifact cache (...). It is currently in use by another Gradle instance.
Owner PID: ...
.....

它编译但存在运行时错误:

{-# LANGUAGE QuasiQuotes, ScopedTypeVariables, OverloadedStrings #-}
module Main where

import           Data.Functor.Identity
import           Control.Exception

import qualified Data.Text             as T

import qualified Hasql.Postgres        as HP
import qualified Hasql                 as H

doit pool = do
  r <- H.session pool $ do
         let kName = "Rob" :: T.Text
             vValue = 34 :: Int
             tName = "t" :: String
         H.tx (Just (H.Serializable, (Just True))) $ do
           H.unitEx $
             [H.stmt| INSERT INTO $tName (name, age) VALUES (?, ?) |] kName vValue
  print r

main = do
  let
    dbConnStr = "dbname=testdb host=pg user=testuser password=password port=5432"
    pgSettings = HP.StringSettings dbConnStr
  poolSettings <- maybe (fail "Improper session settings") return $
                  H.poolSettings 8 30
  bracket (H.acquirePool pgSettings poolSettings :: IO (H.Pool HP.Postgres))
          H.releasePool
          (doit)

在数据库日志中,出现以下错误:

$ cabal exec runghc hasql-exp.hs 
Left (TxError (ErroneousResult "42601" "syntax error at or near \"$1\"" Nothing Nothing))

在该计划中,如果我将pg_1 | ERROR: syntax error at or near "$1" at character 13 pg_1 | STATEMENT: INSERT INTO $1 (name, age) VALUES ($2, $3) 替换为$tName,则查询会很好。这是否意味着无法使用t库从变量加载表名?

0 个答案:

没有答案