1

I've looked the link

How to fix PG::DuplicatePstatement: ERROR?

but it still did not solve the error message I'm getting

`prepare': ERROR:  prepared statement "should_insert" already exists (PG::DuplicatePstatement)

Where do I put the block of code from the answer in the above link? Do I have to call a method in order for it to execute?

db_connection = PGconn.connect("localhost", 5433, '', '', "dev_ddb", "user", "pass")

db_connection.prepare('should_insert', 'SELECT COUNT(*) from users where user_id = $1')
Community
  • 1
  • 1
user2974739
  • 619
  • 1
  • 7
  • 20
  • I created a new initializer in the config folder called pg_init.rb and put the code from the "How to fix..." link above. But, it still gives me the same error. My code is in a file called app.rb and I'm testing it using ruby app.rb. Not sure if that makes a difference. – user2974739 Sep 24 '15 at 22:27

2 Answers2

2

I was able to get this working by deallocating the prepared statement. I inserted this line right after the exec_prepared statement.

db_connection.exec("DEALLOCATE should_insert")
user2974739
  • 619
  • 1
  • 7
  • 20
0

You can always try with a begin-rescue block to check if the statement is already prepared or not, something like:

begin 
  db_connection.describe_prepared("should_insert")
rescue PG::InvalidSqlStatementName
  db_connection.prepare("should_insert",<<-SQL)
    'SELECT COUNT(*) from users where user_id = $1'
    SQL
end

and then exec it with

db_connection.exec_prepared
the Tin Man
  • 158,662
  • 42
  • 215
  • 303