Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm looking for a way to take arbitrary strings, and quote them so that if they were included in an SQL statement for the PostGres database, they couldn't parse as anything other than a single string. I looked at quotemeta, but I don't think that does the right kind of quoting.

Replies are listed 'Best First'.
Re: PostGreSQL Quoting
by diotalevi (Canon) on Aug 12, 2004 at 15:24 UTC
    Use DBI's $dbh->quote or even better, use DBI's placeholders and delegate the job of quoting to the driver.
      DBI seems to want to connect to the database first. Is there any way to avoid that?

      The reason I need this is because the data is actually being formatted for a report, not a database, but some of the users want to be able to copy-and-paste parts of the report directly into their SQL statements. So, I need to be able to do the quoting without actually connection to a DB.

        Ah ok. Then you'll need to write your own filter. For that just go read the driver's source or the documentation on the Pg web site.
        DBI seems to want to connect to the database first. Is there any way to avoid that?

        Maybe:
        You can try this:

        use DBI; my $drh = DBI->install_driver('Pg') or die; my $dbh = DBI::_new_dbh($drh) or die; print $dbh->quote(q{My "" test ' data \\' for quoting'}), "\n";

        Of course you would be violating all sorts of good programming practices and there is no guarantee that 1. it will work consistantly and 2. it won't segfault, but if it works, it works.

Re: PostGreSQL Quoting
by ikegami (Patriarch) on Aug 12, 2004 at 16:12 UTC

    Confirm this with the PostGreSQL docs, but SQL is generally quoted as follows:

    $expr =~ s/'/''/g; $expr = "'$expr'";

    Some DBs will require that you escape backslashes too. I didn't take non-printables into account. You probably won't have those in reports, except maybe a new line. Really, you should check the database's manual. Note: don't expect all databases to quote strings in the same fashion.