简体   繁体   中英

Is there any way to filter a column using SQL functions in Perl's DBIx::Class?

I am using a PostgreSQL database with PostGIS geometry columns.

I would like to configure the Result classes so that geometry columns are inflated using the ST_AsEWKT function and deflated using the ST_GeomFromEWKT function.

Is there a way to do this so that the "find" method works as normal, and so that the "update" and "create" methods also work as normal. I'd rather not have to write specialized queries for each table, if I can avoid it.

I can use a hack for inflating the column, eg

__PACKAGE__->inflate_column( 'geo', {
  inflate => sub {
    my ($raw_value, $result) = @_;
    my $col = $result->result_source->resultset->get_column("geo")->func("ST_AsEWKT");
  },
});

but I am unsure how to implement deflation.

Thanks in advance.

I've got a working solution using DBIx::Class::InflateColumn. It's not ideal, since it makes a separate query to the database for each geometry column. (Ideally, there should be a way to tell DBIC to just use the appropriate functions for queries to this field, if that can even be done without changing DBIC.)

An answer is below.

__PACKAGE__->load_components("InflateColumn");

__PACKAGE__->inflate_column( 'geo', {

  inflate => sub {
    my ($value, $result) = @_;

    my $dbh = $result->result_source->storage->dbh;
    my $sth = $dbh->prepare( q{SELECT ST_AsEWKT(?)} );
    $sth->execute( $value );
    my @row = $sth->fetchrow;

    return $row[0];
  },

  deflate => sub {
    my ($value, $result) = @_;

    my $dbh = $result->result_source->storage->dbh;
    my $sth = $dbh->prepare( q{SELECT ST_GeomFromEWKT(?)} );
    $sth->execute( $value );
    my @row = $sth->fetchrow;

    return $row[0];
  },

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM