Skip to content

Commit

Permalink
Added support for text format to pgx
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Aug 6, 2024
1 parent 8b4d374 commit 1406c17
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
14 changes: 12 additions & 2 deletions pgx/sparsevec.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
type SparseVectorCodec struct{}

func (SparseVectorCodec) FormatSupported(format int16) bool {
return format == pgx.BinaryFormatCode
return format == pgx.BinaryFormatCode || format == pgx.TextFormatCode
}

func (SparseVectorCodec) PreferredFormat() int16 {
Expand All @@ -25,8 +25,11 @@ func (SparseVectorCodec) PlanEncode(m *pgtype.Map, oid uint32, format int16, val
return nil
}

if format == pgx.BinaryFormatCode {
switch format {
case pgx.BinaryFormatCode:
return encodePlanSparseVectorCodecBinary{}
case pgx.TextFormatCode:
return encodePlanSparseVectorCodecText{}
}

return nil
Expand All @@ -39,6 +42,13 @@ func (encodePlanSparseVectorCodecBinary) Encode(value any, buf []byte) (newBuf [
return v.EncodeBinary(buf)
}

type encodePlanSparseVectorCodecText struct{}

func (encodePlanSparseVectorCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) {
v := value.(pgvector.SparseVector)
return append(buf, v.String()...), nil
}

func (SparseVectorCodec) PlanScan(m *pgtype.Map, oid uint32, format int16, target any) pgtype.ScanPlan {
_, ok := target.(*pgvector.SparseVector)
if !ok {
Expand Down
14 changes: 12 additions & 2 deletions pgx/vector.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
type VectorCodec struct{}

func (VectorCodec) FormatSupported(format int16) bool {
return format == pgx.BinaryFormatCode
return format == pgx.BinaryFormatCode || format == pgx.TextFormatCode
}

func (VectorCodec) PreferredFormat() int16 {
Expand All @@ -25,8 +25,11 @@ func (VectorCodec) PlanEncode(m *pgtype.Map, oid uint32, format int16, value any
return nil
}

if format == pgx.BinaryFormatCode {
switch format {
case pgx.BinaryFormatCode:
return encodePlanVectorCodecBinary{}
case pgx.TextFormatCode:
return encodePlanVectorCodecText{}
}

return nil
Expand All @@ -39,6 +42,13 @@ func (encodePlanVectorCodecBinary) Encode(value any, buf []byte) (newBuf []byte,
return v.EncodeBinary(buf)
}

type encodePlanVectorCodecText struct{}

func (encodePlanVectorCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) {
v := value.(pgvector.Vector)
return append(buf, v.String()...), nil
}

func (VectorCodec) PlanScan(m *pgtype.Map, oid uint32, format int16, target any) pgtype.ScanPlan {
_, ok := target.(*pgvector.Vector)
if !ok {
Expand Down

0 comments on commit 1406c17

Please sign in to comment.