Prepared Statement on Postgresql in Rails

后端 未结 1 531
醉酒成梦
醉酒成梦 2021-01-27 15:18

Right now I am in the middle of migrating from SQLite to Postgresql and I came across this problem. The following prepared statement works with SQLite:

id = 5
st         


        
1条回答
  •  梦毁少年i
    2021-01-27 15:54

    If you want to use prepare like that then you'll need to make a couple changes:

    1. The PostgreSQL driver wants to see numbered placeholders ($1, $2, ...) not question marks and you need to give your prepared statement a name:

       ActiveRecord::Base.connection.raw_connection.prepare('some_name', "DELETE FROM my_table WHERE id = $1")
      
    2. The calling sequence is prepare followed by exec_prepared:

      connection = ActiveRecord::Base.connection.raw_connection
      connection.prepare('some_name', "DELETE FROM my_table WHERE id = $1")
      st = connection.exec_prepared('some_name', [ id ])
      

    The above approach works for me with ActiveRecord and PostgreSQL, your PG::Connection.open version should work if you're connecting properly.

    Another way is to do the quoting yourself:

    conn = ActiveRecord::Base.connection
    conn.execute(%Q{
        delete from my_table
        where id = #{conn.quote(id)}
    })
    

    That's the sort of thing that ActiveRecord is usually doing behind your back.

    Directly interacting with the database tends to be a bit of a mess with Rails since the Rails people don't think you should ever do it.

    If you really are just trying to delete a row without interference, you could use delete:

    delete()

    [...]

    The row is simply removed with an SQL DELETE statement on the record’s primary key, and no callbacks are executed.

    So you can just say this:

    MyTable.delete(id)
    

    and you'll send a simple delete from my_tables where id = ... into the database.

    0 讨论(0)
提交回复
热议问题