DBIO-PostgreSQL

 view release on metacpan or  search on metacpan

lib/DBIO/PostgreSQL/InflateColumn/Vector.pm  view on Meta::CPAN

  my $inner = $value;
  $inner =~ s/\A\s*\[//;
  $inner =~ s/\]\s*\z//;

  return [] if $inner =~ /\A\s*\z/;

  return [ map { $class->_coerce_number($_) } map { _trim($_) } split /,/, $inner ];
}

sub _deflate_dense {
  my ($class, $value) = @_;

  Carp::croak('a vector/halfvec column expects an arrayref of numbers or a pgvector string')
    unless ref $value eq 'ARRAY';

  return '[' . join(',', @$value) . ']';
}

sub _inflate_sparsevec {
  my ($class, $value) = @_;

  return $value unless $value =~ /\A\s*\{.*\}\s*\/\s*\d+\s*\z/s;

  my ($body, $dims) = $value =~ /\A\s*\{(.*)\}\s*\/\s*(\d+)\s*\z/s;

  my %values;
  for my $pair (split /,/, $body) {
    next unless $pair =~ /\A\s*(\d+)\s*:\s*(.*?)\s*\z/;
    $values{$1} = $class->_coerce_number($2);
  }

  return { dims => 0 + $dims, values => \%values };
}

sub _deflate_sparsevec {
  my ($class, $value, $dims) = @_;

  Carp::croak('a sparsevec column expects a hashref or a pgvector string')
    unless ref $value eq 'HASH';

  my ($d, $values);
  if (exists $value->{dims} && ref $value->{values} eq 'HASH') {
    $d = $value->{dims};
    $values = $value->{values};
  }
  else {
    $values = $value;
    $d = $dims;
  }

  Carp::croak(
    'cannot deflate a sparsevec hashref without dimensions: '
      . 'declare the column as sparsevec(N) or pass { dims => N, values => { idx => val } }'
  ) unless defined $d;

  my $body = join(',', map { "$_:$values->{$_}" } sort { $a <=> $b } keys %$values);
  return "{$body}/$d";
}

# Numeric-looking values come back as numbers (the natural Perl shape for a
# vector); 'NaN'/'Infinity' and anything else stay strings.
sub _coerce_number {
  my ($class, $value) = @_;

  return $value unless $value =~ /\A-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\z/;
  return 0 + $value;
}

sub _trim {
  my ($value) = @_;
  $value =~ s/\A\s+//;
  $value =~ s/\s+\z//;
  return $value;
}


1;

__END__

=pod

=encoding UTF-8

=head1 NAME

DBIO::PostgreSQL::InflateColumn::Vector - Auto-inflate/deflate pgvector columns to/from Perl data structures

=head1 VERSION

version 0.900007

=head1 SYNOPSIS

  package MyApp::DB::Result::Item;
  use base 'DBIO::Core';
  __PACKAGE__->load_components('PostgreSQL::Result');   # loads this component

  __PACKAGE__->add_columns(
    embedding => { data_type => 'vector(3)' },
    sparse    => { data_type => 'sparsevec(3)' },
  );

Then treat the columns as Perl data structures:

  $row->update({ embedding => [0.1, 0.2, 0.3] });   # stored as '[0.1,0.2,0.3]'
  my $v = $row->embedding;                          # [0.1, 0.2, 0.3]

  $row->update({ sparse => { 0 => 0.1, 2 => 0.2 } });  # stored as '{0:0.1,2:0.2}/3'
  my $s = $row->sparse;   # { dims => 3, values => { 0 => 0.1, 2 => 0.2 } }

=head1 DESCRIPTION

This component translates pgvector column data between PostgreSQL's text
input/output format and Perl data structures, following the
L<DBIO::InflateColumn::DateTime> pattern: a C<register_column> hook that calls
L<DBIO::InflateColumn/inflate_column> for the columns it recognises.

It is loaded automatically by L<DBIO::PostgreSQL::Result>, so declaring a
pgvector column is the whole opt-in — no user glue. The mapping:



( run in 2.488 seconds using v1.01-cache-2.11-cpan-60884a8df76 )