Using the PG Gem for Postgresql in Ruby, how would you check to see if a prepared statement already exists?
Asked
Active
Viewed 3,568 times
2
-
What do you mean as "prepared statements in Ruby" ? Ruby statements do not need any preparation. – Sergey Bolgov May 29 '13 at 01:00
-
1@SergeyBolgov: *prepared statements* is database terminology: http://rubydoc.info/gems/pg/PG/Connection#prepare-instance_method and http://www.postgresql.org/docs/current/static/sql-prepare.html – mu is too short May 29 '13 at 01:05
-
Correct. "prepared statement" is a database terminology. So the question "check if prepared statement already exists in Ruby" makes no sense. Probably, the OP wanted to ask about "prepared statement in Rails+Postgres". The question needs clarification. – Sergey Bolgov May 29 '13 at 01:19
-
1@SergeyBolgov: They're using accessing PostgreSQL using Ruby's `pg` gem and they want to know how to check if a particular prepared statement already exists. Seems pretty clear to me. – mu is too short May 29 '13 at 01:58
-
4is this what you are looking for: http://stackoverflow.com/questions/13967333/prepared-statements-already-exists, or you can use http://www.postgresql.org/docs/9.2/interactive/view-pg-prepared-statements.html – akonsu May 29 '13 at 02:01
-
I restated the question for clarification. I'm not able to find the answer for this anywhere. Thank you akonsu, although I didn't ask how to deallocate a prepared statement using the PG Gem in ruby, that was a problem I ran into yesterday. Up vote for helpfulness :) – newUserNameHere May 29 '13 at 12:13
-
Actually here they asked the same question: http://stackoverflow.com/questions/13967333/prepared-statements-already-exists But only got an answer showing how to deallocate the statement that already exists, not to check if it's already there. – newUserNameHere May 29 '13 at 12:15
2 Answers
2
You can query the pg_prepared_statements view to see if the name is used: http://www.postgresql.org/docs/9.2/interactive/view-pg-prepared-statements.html
Credit goes to akonsu who answered in comments.

newUserNameHere
- 17,348
- 18
- 49
- 79
0
You can also do it by catching the error that you get when you call describe_prepared
statement_exists = true
begin
connection.describe_prepared(statement_name)
rescue PG::InvalidSqlStatementName
statement_exists = false
end

bob
- 126
- 9