NAME

DBIx::Squirrel::Placeholders - find the placeholders in a statement

SYNOPSIS

use DBIx::Squirrel::Placeholders qw(study_sql trim_sql);

my($positions, $normalised, $trimmed)
    = study_sql('SELECT * FROM artist WHERE id = :id');
# ({1 => ':id'}, 'SELECT * FROM artist WHERE id = ?', ...)

DESCRIPTION

The functions DBIx::Squirrel::db's prepare uses to find the placeholders in a statement and rewrite them as ? for the DBI. Neither is exported by default.

FUNCTIONS

study_sql

($positions, $normalised, $trimmed) = study_sql($statement);
($positions, $normalised, $trimmed) = study_sql($statement, \%options);

Returns a hash reference mapping each placeholder's position, from 1, to the placeholder as written (?, ?1, :1, $1 or :name); the statement with each placeholder rewritten as ?; and the statement as "trim_sql" returns it. Returns nothing if the statement is blank.

Croaks if the statement uses more than one style of placeholder: one of ?, ?1, :1, $1, :name or $name, used throughout.

Placeholders are looked for only in the SQL itself, not in quoted strings or identifiers, comments or PostgreSQL's dollar-quoted bodies, and not in casts, such as x::int, or identifiers containing $, such as v$session. A ?, : or $ with a backslash before it isn't a placeholder either, and both are left as they are, for DBD::Pg, which removes the backslash.

%options can hold:

ekorn_dialect

The SQL dialect the statement is written in, named as its DBI driver is, as in $dbh->{Driver}{Name}. For mysql and MariaDB, a backslash escapes a character in a string, "..." is a string, and # starts a comment. For any other dialect, or none, a backslash is an ordinary character in a string, except in PostgreSQL's E'...' strings.

pg_placeholder_dollaronly

With ekorn_dialect Pg, only $1-style placeholders are found, and the statement is returned as it is, for DBD::Pg to read.

pg_placeholder_nocolons

With ekorn_dialect Pg, the :1 and :name styles aren't placeholders.

Anything else in %options is ignored, so the attributes passed to prepare can be given as they are.

trim_sql

$trimmed = trim_sql($statement);

Returns the statement without the blank space around it, or an empty string if it was all blank or undef. Comments are kept.

SEE ALSO

DBIx::Squirrel::db

AUTHOR

Iain Campbell <cpanic@cpan.org>

LICENSE

Copyright (c) 2024-2026 by Iain Campbell.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.