我怎样才能让 esqueleto 为我生成一个 SQL 字符串?

如何让 esqueleto 从 from语句生成 SQL 字符串?

toRawSql的文档说“您可以打开持久查询日志记录”。我尝试了所有可能的 MonadLogger形式,我可以理解,但它从来没有打印任何 SQL。同样的文档还说“手动使用这个函数... ... 是可能的,但是很繁琐”。但是,没有导出类型的构造函数,也没有返回类型 QueryType值的函数。通过注意到 QueryTypenewtype并使用 unsafeCoerce,我设法绕过了这个问题!

我还被迫提供了一个 Connection(这是我通过 SQLite 得到的) ,即使没有必要连接到数据库来生成 SQL。

我只有这个办法,一定有更好的办法。

withSqliteConn ":memory:" $
\conn -> return $ toRawSql SELECT
(unsafeCoerce ((const mempty)
:: a -> Text.Lazy.Builder.Builder))
(conn, initialIdentState) myFromStatement)

Http://hackage.haskell.org/package/esqueleto-1.3.4.2/docs/database-esqueleto-internal-sql.html

2827 次浏览

In the time since this question was posted, esqueleto has gone through a number of major revisions. As of version 2.1.2, and several earlier versions, the QueryType a parameter that necessitated your unsafeCoerce has been removed from toRawSql; that major wart is no longer necessary.

As currently implemented, a Connection is required. I believe that, as indicated by the type synonym name, IdentInfo, esqueleto uses this to build identifiers in the query. It may, for example, add the database name. I haven't really plumbed the source in enough depth. Suffice it to say, passing a fake connection (i.e. undefined) doesn't work; I don't know if a mock connection could be implemented. Your solution seems workable.

The rest of your solution should work fine. Since toRawSql is explicitly an internal function, the API here seems reasonable. Although others note that it "should" be possible to generate a connection-neutral string, that appears outside the scope of toRawSql.

You mention that you couldn't use MonadLogger as recommended. What did you try, and what happened?