title: Can I execute a raw sql query, leverage prepared statements, and not use ActiveRecord::Relation::QueryAttribute?
body: <p>I want to do an <a href="https://www.postgresql.org/docs/10/static/sql-insert.html#SQL-ON-CONFLICT" rel="noreferrer">upsert</a>. Rails doesn't support this yet. The query is something like this:</p>
  
  <pre class="lang-sql prettyprint-override"><code>INSERT INTO foos (thing_id, bar_id) VALUES (1, 2)
  ON CONFLICT (thing_id, bar_id) DO NOTHING
  </code></pre>
  
  <p>I can easily do this with <code>self.class.connection.execute</code> or <code>exec_insert</code>. But I want to also leverage prepared statements. I thought I can do this like so:</p>
  
  <pre class="lang-rb prettyprint-override"><code>thing_id = ActiveRecord::Relation::QueryAttribute.new("thing_id", thing.id, ActiveRecord::Type::Integer.new)
  bar_id = ActiveRecord::Relation::QueryAttribute.new("bar_id", id, ActiveRecord::Type::Integer.new)
  
  self.class.connection.exec_insert(&lt;&lt;-SQL, nil, [thing_id, bar_id])
    INSERT INTO foos (thing_id, bar_id) VALUES ($1, $2)
    ON CONFLICT (thing_id, bar_id) DO NOTHING
  SQL
  </code></pre>
  
  <p>But when I experimented with this it seems that a prepared statement is not created.</p>
  
  <p>I tried this style:</p>
  
  <pre class="lang-rb prettyprint-override"><code>query = &lt;&lt;-SQL
    INSERT INTO foos (thing_id, bar_id) VALUES ($1, $2)
    ON CONFLICT (thing_id, bar_id) DO NOTHING
  SQL
  
  connection = ActiveRecord::Base.connection.raw_connection
  connection.prepare('some_name', query)
  st = connection.exec_prepared('some_name', [ thing.id, id ])
  </code></pre>
  
  <p>And it does create a prepared statement. BUT, the second time it is run, postgres complains about creating a prepared statement with the same name. So, rails' prepared statement management happens at a level above this, and I'm unable to leverage it here. I would have to manually manage it here. I'm not confident I could do this properly, and even if I could it would be verbose.</p>
  
  <p><code>execute</code> and friends do not accept the <code>("foo=?", 1)</code> api that <code>where</code> accepts.</p>
  
  <p>Is there any way to leverage rails' automagic prepared statement management for raw SQL?</p>