#!/usr/bin/env perl
# @(#) escape a file as PostgreSQL string literal.
#
# Copyright (c) 2008 Dirk Jagdmann <doj@cubic.org>
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
#     1. The origin of this software must not be misrepresented; you
#        must not claim that you wrote the original software. If you use
#        this software in a product, an acknowledgment in the product
#        documentation would be appreciated but is not required.
#
#     2. Altered source versions must be plainly marked as such, and
#        must not be misrepresented as being the original software.
#
#     3. This notice may not be removed or altered from any source
#        distribution. */

=head1 NAME

B<pg_file2str.pl> - escape a file as PostgreSQL string literal.

=head1 SYNOPSIS

B<pg_file2str.pl> < I<inputfile>

B<pg_file2str.pl> I<inputfile>

=head1 DESCRIPTION

B<pg_file2str.pl> reads a file from STDIN or the filename given as its
first command line argument and prints the file properly escaped as a
PostgreSQL string literal to STDOUT.

=cut

# slurp input into $_
$/=undef;
$_=<>;

# escape quotes and backslashes
s/\\/\\\\/gs;
s/'/''/gs;
# escape common stuff
s/\a/\\a/gs;
s/\e/\\e/gs;
s/\f/\\f/gs;
s/\n/\\n/gs;
s/\r/\\r/gs;
s/\t/\\t/gs;
s/\v/\\v/gs;

# escape any non-printable characters
s/([\x00-\x1F\x7F-\xFF])/sprintf('\\x%02X', ord($1))/gse;

print "E'$_'\n";

=head1 SEE ALSO

L<http://www.postgresql.org/docs/8.3/interactive/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS>

=head1 AUTHOR

Dirk Jagdmann <doj@cubic.org>
L<http://pgfoundry.org/projects/pg-toolbox/>

=head1 LICENSE

zlib/libpng license: L<http://en.wikipedia.org/wiki/Zlib_License>

=cut
