简体   繁体   English

Hasql:“ SET”语句中的变量替换错误

[英]Hasql: Error from variable substitution in 'SET' statement

I'm trying to write a parameterized statement with Hasql to set a variable in PostgreSQL. 我正在尝试使用Hasql编写参数化语句以在PostgreSQL中设置变量。

import qualified Hasql.Encoders as E
import qualified Hasql.Decoders as D

setOrganization :: Query Int64 ()
setOrganization = statement sql (E.value E.int8) D.unit False
  where
    sql = "set my_session.organization_id = $1"

The result from the above is: 上面的结果是:

ResultError (ServerError "42601" "syntax error at or near \"$1\"" Nothing Nothing)

Adding single quotes eg 添加单引号,例如

    sql = "set my_session.organization_id = '$1'"

Gives this result when I run a query using the variable: 使用变量运行查询时给出以下结果:

ResultError (ServerError "22P02" "invalid input syntax for integer: \"$1\"" Nothing Nothing)

Which does make sense since the organization_id is a bigint / int8 . 确实有意义,因为organization_idbigint / int8

Hard-coding the $1 value in either format works. 以任何一种格式对$1值进行硬编码均可。 I've tried different Hasql types eg E.text and E.unknown and that does not work. 我尝试了不同的Hasql类型,例如E.textE.unknown ,但是这不起作用。


Update: Using the more primitive execParams function from postgresql-libpq . 更新:使用来自postgresql-libpq的更原始的execParams函数。

execParams c "SET my_session.organization_id = '$1'" [Just (Oid 20, "1",Text)] Text

Unquoted variable gives FatalError result. 未加引号的变量给出FatalError结果。 Single-quoted variable gives CommandOk , but is wrong type (not bigint ) for later queries. 单引号变量提供CommandOk ,但用于以后的查询的类型错误(不是bigint )。

The SET command cannot be used with a prepared statement. SET命令不能与预处理语句一起使用。 This is a limitation of PostgreSQL. 这是PostgreSQL的限制。 A prepared statement is a statement with optional parameters that can be executed several times with varying parameter values. 准备语句是带有可选参数的语句,可以使用不同的参数值多次执行该语句。 All statements with parameters are prepared statements in PostgreSQL, regardless if you execute them only once or if you give them a name for reuse. 所有带有参数的语句都是PostgreSQL中的预备语句,无论您仅执行一次还是给它们命名以供重用。

You'll have to construct a query string with a constant value and execute that. 您将必须构造一个具有恒定值的查询字符串并执行它。

Alternatively, you could write a function in PostgreSQL that runs the set command for you with dynamic SQL and call that function in a prepared SELECT statement with a parameter. 另外,您可以在PostgreSQL中编写一个函数,该函数通过动态SQL为您运行set命令,并在准备好的带有参数的SELECT语句中调用该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM