使用 postgresql-simple 的查询字符串类型错误

Type error for Query string with postgresql-simple

this question, I have a query template that I've constructed using the interpolate package, which I'm then trying to pass to the query_/execute_ functions from postgresql-simple 相关。但编译器拒绝,错误

    • Couldn't match type ‘[Char]’ with ‘Query’
      Expected type: Query
      Actual type: String

postgresql-simple 的文档页面中值得注意的段落是,"To most easily construct a query, enable GHC's OverloadedStrings language extension and write your query as a normal literal string."因此,看起来以下内容应该有效:

{-# LANGUAGE QuasiQuotes       #-}
{-# LANGUAGE OverloadedStrings #-}

import Control.Monad (void)
import Database.PostgreSQL.Simple
import Data.String.Interpolate (i)

-- schema_name.table_name
type Table = String

dropTableIfExistsQuery :: Table -> String
dropTableIfExistsQuery tbl = [i| DROP TABLE IF EXISTS #{tbl} |]

dropTableIfExists :: Connection -> Table -> IO ()
dropTableIfExists conn tbl = void $ execute_ conn $ dropTableIfExistsQuery tbl

但这不会编译,如上所示:

    • Couldn't match type ‘[Char]’ with ‘Query’
  Expected type: Query
    Actual type: String
• In the second argument of ‘($)’, namely
    ‘dropTableIfExistsQuery tbl’
  In the second argument of ‘($)’, namely
    ‘execute_ conn $ dropTableIfExistsQuery tbl’
  In the expression:
    void $ execute_ conn $ dropTableIfExistsQuery tbl

什么给了?为什么 OverloadedStrings 不在这里工作?

OverloadedStrings 只影响字符串字面量,而不是所有 String 类型的术语。如果你有一个 String 不是文字,你可以明确地将它转换为 IsString 的任何实例(例如 Query),使用:

fromString :: IsString a => String -> a

N.B。我对 Query 和您使用的其他库的了解还不够,无法判断 fromString 是否具有您需要的行为;我只声称它有你需要的类型。