From 88636f7195fc936421392740f980d17ebe77d701 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 21 Mar 2011 14:48:43 -0700 Subject: [PATCH] escaping binary data encoding when inserting to sqlite3. Thanks Naruse! [#6559 state:resolved] --- .../connection_adapters/sqlite3_adapter.rb | 8 ++++++++ .../adapters/sqlite/sqlite_adapter_test.rb | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb index c2cd9e8d5e..c3a7b039ff 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb @@ -34,6 +34,14 @@ module ActiveRecord module ConnectionAdapters #:nodoc: class SQLite3Adapter < SQLiteAdapter # :nodoc: + def quote(value, column = nil) + if value.kind_of?(String) && column && column.type == :binary && column.class.respond_to?(:string_to_binary) + s = column.class.string_to_binary(value).unpack("H*")[0] + "x'#{s}'" + else + super + end + end # Returns the current database encoding format as a string, eg: 'UTF-8' def encoding diff --git a/activerecord/test/cases/adapters/sqlite/sqlite_adapter_test.rb b/activerecord/test/cases/adapters/sqlite/sqlite_adapter_test.rb index ce0b2f5f5b..d1fc470907 100644 --- a/activerecord/test/cases/adapters/sqlite/sqlite_adapter_test.rb +++ b/activerecord/test/cases/adapters/sqlite/sqlite_adapter_test.rb @@ -1,8 +1,13 @@ +# encoding: utf-8 require "cases/helper" +require 'models/binary' module ActiveRecord module ConnectionAdapters class SQLiteAdapterTest < ActiveRecord::TestCase + class DualEncoding < ActiveRecord::Base + end + def setup @ctx = Base.sqlite3_connection :database => ':memory:', :adapter => 'sqlite3', @@ -15,6 +20,20 @@ module ActiveRecord eosql end + def test_quote_binary_column_escapes_it + DualEncoding.connection.execute(<<-eosql) + CREATE TABLE dual_encodings ( + id integer PRIMARY KEY AUTOINCREMENT, + name string, + data binary + ) + eosql + str = "\x80".force_encoding("ASCII-8BIT") + binary = DualEncoding.new :name => 'いただきます!', :data => str + binary.save! + assert_equal str, binary.data + end + def test_execute @ctx.execute "INSERT INTO items (number) VALUES (10)" records = @ctx.execute "SELECT * FROM items"