tags:

views:

74

answers:

1

Hello!

How do I find a literal % with the LIKE-operator?

#!/usr/bin/perl
use warnings;
use strict;

use DBI;

my $table = 'formula';
my $dbh = DBI->connect ( "DBI:CSV:", undef, undef, { RaiseError => 1 } );

my $AoA = [ [ qw( id formula ) ], 
        [ 1, 'a + b' ], 
        [ 2, 'c - d' ], 
        [ 3, 'e * f' ], 
        [ 4, 'g / h' ], 
        [ 5, 'i % j' ],     ];

$dbh->do( qq{ CREATE TEMP TABLE $table AS IMPORT ( ? ) }, {}, $AoA ); 

my $sth = $dbh->prepare ( qq{ SELECT * FROM $table WHERE formula LIKE '%[%]%' } );
$sth->execute;
$sth->dump_results;

# Output:
# 3, 'e * f'
# 1 rows
+4  A: 

Looks like you can't do this with current version of DBD::CSV.

You are using DBD::CSVmodule to access data. It uses SQL::Statement module to handle expresions. I've searched its source code and found that following code handles LIKE sql statement condition:

## from SQL::Statement::Operation::Regexp::right method
unless ( defined( $self->{PATTERNS}->{$right} ) )
{
    $self->{PATTERNS}->{$right} = $right;
    ## looks like it doen't check any escape symbols
    $self->{PATTERNS}->{$right} =~ s/%/.*/g; 
    $self->{PATTERNS}->{$right} = $self->regexp( $self->{PATTERNS}->{$right} );
}

Look at $self->{PATTERNS}->{$right} =~ s/%/.*/g; line. It converts LIKE pattern to regexp. And it doesn't do any check of any escape symbols. All % symbols are blindly translated to .* pattern. That's why I think it's not implemented yet.

Well, may be someone'll find time to fix this issue.

Ivan Nevostruev