Selecting string literals in Rails 4 using PostgreSQL

I recently ran into an issue with Rails 4 using the PostgreSQL adapter (MRI) where selecting a string literal in a query would return a warning about an unknown OID.

This can be reproduced by running the following in Rails Console:

Rails.logger.level = 2
ActiveRecord::Base.connection.select_all("SELECT 'test'")

=> unknown OID: ?column?(705) (SELECT 'test')

This occurs both with and without column aliases.

705 is PostgreSQL’s code for an unknown type and in order to fix this, what we want to do is register the “unknown” type. Based on this blog post, I put the following code in an postgres_oids.rb initializer:

# Treat any unknown types (e.g. string literals) as text
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::OID.alias_type 'unknown', 'text'