Sequelはいつの間にか良くなっていた
以前、SequelからJDBC経由でデータベースに接続する場合は注意すべきだと書きました。
- SequelはJDBC以外ならいい (2008-07-10)
Sequelはまだまだ使い物にならないと思っていましたが、いつの間にか良くなっていました。
かつては、sequel_core/sql.rbに以下のような記述がありました。
# This method quotes the given name with the SQL standard double quote. # It uppercases the name given to conform with the SQL standard. This # should be overridden by subclasses to provide quoting not matching the # SQL standard, such as backtick (used by MySQL and SQLite), or where # lowercase is the default for unquoted identifiers (PostgreSQL). # # If you are using a database such as Oracle that defaults to uppercase # but you are using lower case identifiers, you should override this # method to not upcase the name for those identifiers. def quoted_identifier(name) "\"#{name.to_s.upcase}\"" end
おせっかいにも、quoted_identifierメソッドは名前を大文字に変換していたのです。
このため、PostgreSQLのように大文字と小文字を区別し、デフォルトでは小文字を使うデータベースの場合、DB[:user_data].allといったシンボルによる表指定ができませんでした。
この問題の回避策として、JDBC経由でPostgreSQLに接続するときは、以下のような小細工をしていました。
module Sequel module JDBC class Dataset < Sequel::Dataset def quoted_identifier(name) "\"#{name.to_s}\"" end end end end
Sequel 2.8.0では、sequel_core/sql.rbは以下のようになっています。
# This method quotes the given name with the SQL standard double quote. # should be overridden by subclasses to provide quoting not matching the # SQL standard, such as backtick (used by MySQL and SQLite). def quoted_identifier(name) "\"#{name}\"" end
quoted_identifierは余計なことをしなくなりました。
というわけで、改めてSequelからJDBC経由でPostgreSQLに接続するサンプルを書くと、以下の通りになります。
require 'rubygems' require 'sequel' DB = Sequel.connect('jdbc:postgresql://localhost/postgres?' + 'user=postgres&password=postgres') DB["SELECT * FROM user_data"].all # 成功 DB[:user_data].all # 成功(従来は失敗) DB[:user_data].all.each do |user_data| puts "#{user_data[:user_id]} #{user_data[:user_account]}" end; nil
JDBCドライバの登録も自動化され、すっきりしました。