Skip to content

Commit

Permalink
Added experimental support for type maps
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Jul 14, 2024
1 parent 2ac7c3a commit d206c2a
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
30 changes: 30 additions & 0 deletions lib/pgvector/pg.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,21 @@ def decode(string, tuple = nil, field = nil)
end
end

module BinaryEncoder
# experimental
def self.type_map
tm = ::PG::TypeMapByClass.new
tm[::Pgvector::Vector] = Vector.new
tm
end

class Vector < ::PG::SimpleEncoder
def encode(value)
value.to_binary
end
end
end

module TextDecoder
class Vector < ::PG::SimpleDecoder
def decode(string, tuple = nil, field = nil)
Expand All @@ -61,5 +76,20 @@ def decode(string, tuple = nil, field = nil)
end
end
end

module TextEncoder
# experimental
def self.type_map
tm = ::PG::TypeMapByClass.new
tm[::Pgvector::Vector] = Vector.new
tm
end

class Vector < ::PG::SimpleEncoder
def encode(value)
value.to_s
end
end
end
end
end
11 changes: 11 additions & 0 deletions test/pg_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,17 @@ def test_sparsevec_binary
assert_nil res[1]["sparse_embedding"]
end

def test_type_map_binary
vec = Pgvector::Vector.new([1, 2, 3])
coder = PG::BinaryEncoder::CopyRow.new(type_map: Pgvector::PG::BinaryEncoder.type_map)
assert_include vec.to_binary, coder.encode([vec])
end

def test_type_map_binary
coder = PG::TextEncoder::CopyRow.new(type_map: Pgvector::PG::TextEncoder.type_map)
assert_equal "[1.0,2.0,3.0]\n", coder.encode([Pgvector::Vector.new([1, 2, 3])])
end

def conn
@@conn ||= begin
conn = PG.connect(dbname: "pgvector_ruby_test")
Expand Down

0 comments on commit d206c2a

Please sign in to comment.