From e0bcae83cbaf5b7665ff5bb3b950b5bad19578a8 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 23 Jan 2024 16:30:40 -0800 Subject: [PATCH] Ensure the `Database#encoding` method works when results are "as hash" This is a regression test for Rails. Rails instantiates SQLite3 with `results_as_hash` set to `true` by default. I broke the encoding method when that value is set to true, so this patch fixes it. --- lib/sqlite3/database.rb | 4 +++- test/test_encoding.rb | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/sqlite3/database.rb b/lib/sqlite3/database.rb index e8977896..1ae1368d 100644 --- a/lib/sqlite3/database.rb +++ b/lib/sqlite3/database.rb @@ -138,7 +138,9 @@ def initialize file, options = {}, zvfs = nil # # Fetch the encoding set on this database def encoding - @encoding ||= Encoding.find(execute("PRAGMA encoding").first.first) + @encoding ||= prepare("PRAGMA encoding") { |stmt| + Encoding.find(stmt.first.first) + } end # Installs (or removes) a block that will be invoked for every access diff --git a/test/test_encoding.rb b/test/test_encoding.rb index 33c72c67..65df5ff7 100644 --- a/test/test_encoding.rb +++ b/test/test_encoding.rb @@ -13,6 +13,11 @@ def teardown @db.close end + def test_encoding_when_results_are_hash + db = SQLite3::Database.new(":memory:", results_as_hash: true) + assert_equal Encoding.find("UTF-8"), db.encoding + end + def test_select_encoding_on_utf_16 str = "foo" utf16 = ([1].pack("I") == [1].pack("N")) ? "UTF-16BE" : "UTF-16LE"