【问题标题】:Ruby PG gem use array as param with exec_paramsRuby PG gem 使用数组作为参数和 exec_params
【发布时间】:2015-08-05 05:22:24
【问题描述】:

我想像这样传递一个 ruby​​ 数组值:

sql = "SELECT $1"
User.connection.raw_connection.exec_params(sql, [[1,2]])

这会返回

PG::IndeterminateDatatype: ERROR:  could not determine data type of parameter $1

如果我将sql 更改为"SELECT $1::int[]",我会得到PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: "[1, 2]"。

有没有办法将 ruby​​ 数组传递给 exec_params 并将其转换为 PostgreSQL 数组?

【问题讨论】:

    标签: ruby-on-rails arrays ruby postgresql pg


    【解决方案1】:

    pg_exec_array_params gem 允许这样做:

    # Instead of:
    # PG::Connection.exec_params(
    #   'SELECT ARRAY[$1, $2]'
    #   [1, 2]
    # )
    PgExecArrayParams.exec_array_params(conn, 'select $1', [[1, 2]])
    => [{"array"=>"{1,2}"}]
    

    【讨论】:

      【解决方案2】:

      您可以使用编码器来做到这一点:

      raw_connection.exec(
        "select $1::int[]",
        [PG::TextEncoder::Array.new.encode([1, 2])]
      )
      

      【讨论】:

        【解决方案3】:

        您需要按照以下方式进行:

        params = [1, 2]
        sql = params.size.times.map { |n| "$#{n+1}::INT" }.join(",")
        User.connection.raw_connection.exec_params("SELECT #{sql}", params)
        

        【讨论】:

          猜你喜欢
          • 2017-01-03
          • 2019-06-27
          • 2018-12-10
          • 2014-07-13
          • 2019-12-27
          • 2015-12-02
          • 2021-10-27
          • 2020-03-24
          相关资源
          最近更新 更多