Monday, August 6, 2012

InvalidURIError For pg Gem For Certain Passwords

While working on my Sinatra & PostgreSQL-powered web-site (using Sequel 3.37.0 and pg 0.14.0), I encountered an odd URI-related error message.

Let's assume for a moment that this is the connection string that Sequel uses:


The resulting error message looks like this:

Error: URI::InvalidURIError: the scheme postgres does not accept registry part:
user: pass (or bad hostname?)

Because I wasn't actually using that connection string, the actual error message that I received was a little different. The root cause, however, remains the same: the password has a question mark in it. A question mark is used to separate the query string part of a URL from the rest of the URL. In the above connection string example, Ruby's URI-related code seems to treat 'word@localhost/user' as an invalid query string.

The password needs to be separated from the query string, and CGI's escape method needs to be used.

Old Code


New Code

password = CGI.escape('pass?word')


Stack Overflow - In Ruby, how do I replace the question mark character in a string?

This SO question (and the accepted answer by kmkaplan) suggested the use of CGI's escape method.