2

I am using rails 3 and I need to execute raw sql in one of my migration and I need to do it using prepared statement since it is the best way to escape problems which arise due to single, statement or so. Is there a way where in I can execute multiple sql statements in a single prepare statement. I am using PostgreSQL for my database

Here is my code what i tried

  CONN = ActiveRecord::Base.connection.raw_connection  
  sql = %Q[
            INSERT INTO table1 
              (
                name,
                email,
                phone,
                created_at,
                updated_at
               ) 
              VALUES 
              (
                $1, 
                $2, 
                $3,
                current_timestamp, 
                current_timestamp
              );
            UPDATE table2 
              SET column_1 = $1
              WHERE id = $4;
            UPDATE contacts SET 
              column_2 = $2
              WHERE id = $4
          ]

  CONN.prepare('insert_and_update', sql)
  CONN.exe_prepared('insert_and_update', [
      name,
      email,
      phone,
      customer.id
    ])

But I am getting error as

 cannot insert multiple commands into a prepared statement
Ankita.P
  • 442
  • 1
  • 8
  • 17

1 Answers1

5

Turn it into a single command:

with i as (
    insert into table1 (
        name,
        email,
        phone,
        created_at,
        updated_at
    ) values (
        $1, 
        $2, 
        $3,
        current_timestamp, 
        current_timestamp
), u as (
    update table2 
    set column_1 = $1
    where id = $4
)
update contacts 
set column_2 = $2
where id = $4
;
Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260
  • 1
    What if I want something like `set local intervalstyle=postgres_verbose;`? It can't go to CTE. – mlt Dec 19 '17 at 06:10