From d4abb0c64701d3c97e9ea09ec6b6d1810f50664d Mon Sep 17 00:00:00 2001 From: Matthew McGarvey Date: Sat, 9 Jan 2021 11:46:19 -0500 Subject: [PATCH] Refactor and support asking for String? --- spec/pg/driver_spec.cr | 4 ++++ src/pg/result_set.cr | 19 +++++++++++++++---- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/spec/pg/driver_spec.cr b/spec/pg/driver_spec.cr index b304a6ce..252a3c71 100644 --- a/spec/pg/driver_spec.cr +++ b/spec/pg/driver_spec.cr @@ -105,6 +105,10 @@ describe PG::Driver do db.query "select email from users limit 1" do |rs| assert_single_read rs, String, "foo@example.com" end + + db.query "select email from users limit 1" do |rs| + assert_single_read rs, String?, "foo@example.com" + end end end diff --git a/src/pg/result_set.cr b/src/pg/result_set.cr index 1479a216..578cc060 100644 --- a/src/pg/result_set.cr +++ b/src/pg/result_set.cr @@ -93,13 +93,24 @@ class PG::ResultSet < ::DB::ResultSet end def read(t : String.class) : String - value = read - if value.is_a?(String) + value = read(String | Slice(UInt8)) + + case value + when Slice(UInt8) + String.new(value) + else value - elsif value.is_a?(Slice(UInt8)) + end + end + + def read(t : String?.class) : String? + value = read(String | Slice(UInt8) | Nil) + + case value + when Slice(UInt8) String.new(value) else - raise "#{self.class}#read returned a #{value.class}. A String was expected." + value end end