SQL so close I can paste it (YAPC::NA::2011 lightning talk)
Jun. 29, 2011•0 likes•366 views
Download to read offline
Report
Technology
Entertainment & Humor
My lightning talk from YAPC 2011 in Asheville, NC
I wanted to log prepared sql statements with their bind variables included in-line. This hack gets me there. It may be useful to you too.
8. assemble the larger query
my $sql = qq/SELECT
COUNT(DISTINCT(civ.contact_info_id)) AS
volunteers
FROM contact_info_volunteer civ
JOIN contact_info ci ON (ci.contact_info_id
= civ.contact_info_id)
$joins $where
/;
9. prepare_cached
my $sth = $dbh->prepare_cached($sql);
$sth->execute(@binds);
my $data = $sth->fetchrow_hashref();
$sth->finish();
10. log the query
my $sth = $dbh->prepare_cached($sql);
my $sql_fmt = $sql;
$sql_fmt =~ s/?/'%s'/g;
warn sprintf $sql_fmt, @binds;
11. output in your logs (before)
SELECT
COUNT(DISTINCT(civ.contact_info_id)) AS volunteers
FROM contact_info_volunteer civ
JOIN contact_info ci ON (ci.contact_info_id = civ.contact_info_id)
JOIN volunteer_form vf ON(civ.volunteer_form_id = vf.volunteer_form_id)
WHERE vf.story_uuid IN ( ?, ?)
$VAR1 = ['1234','5678'];
12. output in your logs (after)
SELECT
COUNT(DISTINCT(civ.contact_info_id)) AS volunteers
FROM contact_info_volunteer civ
JOIN contact_info ci ON (ci.contact_info_id = civ.contact_info_id)
JOIN volunteer_form vf ON(civ.volunteer_form_id = vf.volunteer_form_id)
WHERE vf.story_uuid IN ( '1234', '5678')
13. log the query
my $sth = $dbh->prepare_cached($sql);
my $sql_fmt = $sql;
$sql_fmt =~ s/?/'%s'/g;
warn sprintf $sql_fmt, @binds;