Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add PG::BasicTypeMapForQueries::BinaryData for encoding of bytea columns #348

Merged
merged 1 commit into from
Mar 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions lib/pg/basic_type_mapping.rb
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,21 @@ def initialize(connection)
# # The format of the parameter is set to 0 (text) and the OID of this parameter is set to 20 (int8).
# res = conn.exec_params( "SELECT $1", [5] )
class PG::BasicTypeMapForQueries < PG::TypeMapByClass
# Helper class for submission of binary strings into bytea columns.
#
# Since PG::BasicTypeMapForQueries chooses the encoder to be used by the class of the submitted value,
# it's necessary to send binary strings as BinaryData.
# That way they're distinct from text strings.
# Please note however that PG::BasicTypeMapForResults delivers bytea columns as plain String
# with binary encoding.
#
# conn.type_map_for_queries = PG::BasicTypeMapForQueries.new(conn)
# conn.exec("CREATE TEMP TABLE test (data bytea)")
# bd = PG::BasicTypeMapForQueries::BinaryData.new("ab\xff\0cd")
# conn.exec_params("INSERT INTO test (data) VALUES ($1)", [bd])
class BinaryData < String
end

include PG::BasicTypeRegistry

def initialize(connection)
Expand Down Expand Up @@ -506,6 +521,7 @@ def get_array_type(value)
IPAddr => [0, 'inet'],
Hash => [0, 'json'],
Array => :get_array_type,
BinaryData => [1, 'bytea'],
}

DEFAULT_ARRAY_TYPE_MAP = {
Expand Down
7 changes: 7 additions & 0 deletions spec/pg/basic_type_mapping_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,13 @@ def to_s
expect( result_typenames(res) ).to eq( ['text[]'] )
end

it "should take BinaryData for bytea columns" do
@conn.exec("CREATE TEMP TABLE IF NOT EXISTS bytea_test (data bytea)")
bd = PG::BasicTypeMapForQueries::BinaryData.new("ab\xff\0cd")
res = @conn.exec_params("INSERT INTO bytea_test (data) VALUES ($1) RETURNING data", [bd], nil, basic_type_mapping)

expect( res.to_a ).to eq([{"data" => "\\x6162ff006364"}])
end
end


Expand Down