SlideShare a Scribd company logo
SQL so close I can paste it



       YAPC::NA::2011
          Asheville

          Brad Oaks
        Plus Three, LP
printf

printf
  'person_id %d name: %s',
  $person_id,
  $person->name;
printf with format as a variable

my $fmt = 'person_id %d name: %s';
printf
  $fmt,
  $person_id,
  $person->name;
dynamically building a query

my (@conds, @binds);
my $joins = '';
my @uuids         = $self->get_story_uuids;
add to your JOINs

if( @uuids ) {
   $joins .= ' JOIN volunteer_form vf
ON(civ.volunteer_form_id =
vf.volunteer_form_id)';
}
add to your conditions

if( @uuids ) {
    push(@conds, 'vf.story_uuid IN ( '
    . join(', ', ('?') x scalar(@uuids)) . ')');
    push(@binds, @uuids);
}
assemble WHERE clause

my $where = @conds
  ? ' WHERE ' . join(' AND ', @conds)
  : '';
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
  /;
prepare_cached

my $sth = $dbh->prepare_cached($sql);
$sth->execute(@binds);
my $data = $sth->fetchrow_hashref();
$sth->finish();
log the query

my $sth = $dbh->prepare_cached($sql);
my $sql_fmt = $sql;
$sql_fmt =~ s/?/'%s'/g;
warn sprintf $sql_fmt, @binds;
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'];
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')
log the query

my $sth = $dbh->prepare_cached($sql);
my $sql_fmt = $sql;
$sql_fmt =~ s/?/'%s'/g;
warn sprintf $sql_fmt, @binds;

More Related Content

What's hot

20. CodeIgniter edit images
20. CodeIgniter edit images20. CodeIgniter edit images
20. CodeIgniter edit images
Razvan Raducanu, PhD
 
Erik mogensen stowe
Erik mogensen stoweErik mogensen stowe
Erik mogensen stowe
Erik Mogensen
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-london
Kris Wallsmith
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
elliando dias
 
Migrare da symfony 1 a Symfony2
 Migrare da symfony 1 a Symfony2  Migrare da symfony 1 a Symfony2
Migrare da symfony 1 a Symfony2
Massimiliano Arione
 
Kasdorf, EPUB 3: Not Your Father’s EPUB
Kasdorf, EPUB 3: Not Your Father’s EPUBKasdorf, EPUB 3: Not Your Father’s EPUB
Kasdorf, EPUB 3: Not Your Father’s EPUB
National Information Standards Organization (NISO)
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
Kris Wallsmith
 
8. vederea inregistrarilor
8. vederea inregistrarilor8. vederea inregistrarilor
8. vederea inregistrarilor
Razvan Raducanu, PhD
 
Borrados
BorradosBorrados
London XQuery Meetup: Querying the World (Web Scraping)
London XQuery Meetup: Querying the World (Web Scraping)London XQuery Meetup: Querying the World (Web Scraping)
London XQuery Meetup: Querying the World (Web Scraping)
Dennis Knochenwefel
 
Solarclave
SolarclaveSolarclave
Solarclave
Rebecca Obounou
 
12. edit record
12. edit record12. edit record
12. edit record
Razvan Raducanu, PhD
 
Threading
ThreadingThreading
Threading
b290572
 
Latihan form login
Latihan form loginLatihan form login
Latihan form login
Edy Sinaga
 
20180921 #24 we_are_javascripters
20180921 #24 we_are_javascripters20180921 #24 we_are_javascripters
20180921 #24 we_are_javascripters
将一 深見
 
Subtração
SubtraçãoSubtração
Subtração
Albertina Pereira
 
Keeping It Simple
Keeping It SimpleKeeping It Simple
Keeping It Simple
Stephanie Leary
 
6. hello popescu 2
6. hello popescu 26. hello popescu 2
6. hello popescu 2
Razvan Raducanu, PhD
 
Les exceptions, oui, mais pas n'importe comment
Les exceptions, oui, mais pas n'importe commentLes exceptions, oui, mais pas n'importe comment
Les exceptions, oui, mais pas n'importe comment
Charles Desneuf
 
Information Science Blog Aggregation
Information Science Blog AggregationInformation Science Blog Aggregation
Information Science Blog Aggregation
Franny Gaede
 

What's hot (20)

20. CodeIgniter edit images
20. CodeIgniter edit images20. CodeIgniter edit images
20. CodeIgniter edit images
 
Erik mogensen stowe
Erik mogensen stoweErik mogensen stowe
Erik mogensen stowe
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-london
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
Migrare da symfony 1 a Symfony2
 Migrare da symfony 1 a Symfony2  Migrare da symfony 1 a Symfony2
Migrare da symfony 1 a Symfony2
 
Kasdorf, EPUB 3: Not Your Father’s EPUB
Kasdorf, EPUB 3: Not Your Father’s EPUBKasdorf, EPUB 3: Not Your Father’s EPUB
Kasdorf, EPUB 3: Not Your Father’s EPUB
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
8. vederea inregistrarilor
8. vederea inregistrarilor8. vederea inregistrarilor
8. vederea inregistrarilor
 
Borrados
BorradosBorrados
Borrados
 
London XQuery Meetup: Querying the World (Web Scraping)
London XQuery Meetup: Querying the World (Web Scraping)London XQuery Meetup: Querying the World (Web Scraping)
London XQuery Meetup: Querying the World (Web Scraping)
 
Solarclave
SolarclaveSolarclave
Solarclave
 
12. edit record
12. edit record12. edit record
12. edit record
 
Threading
ThreadingThreading
Threading
 
Latihan form login
Latihan form loginLatihan form login
Latihan form login
 
20180921 #24 we_are_javascripters
20180921 #24 we_are_javascripters20180921 #24 we_are_javascripters
20180921 #24 we_are_javascripters
 
Subtração
SubtraçãoSubtração
Subtração
 
Keeping It Simple
Keeping It SimpleKeeping It Simple
Keeping It Simple
 
6. hello popescu 2
6. hello popescu 26. hello popescu 2
6. hello popescu 2
 
Les exceptions, oui, mais pas n'importe comment
Les exceptions, oui, mais pas n'importe commentLes exceptions, oui, mais pas n'importe comment
Les exceptions, oui, mais pas n'importe comment
 
Information Science Blog Aggregation
Information Science Blog AggregationInformation Science Blog Aggregation
Information Science Blog Aggregation
 

Similar to SQL so close I can paste it (YAPC::NA::2011 lightning talk)

Daily notes
Daily notesDaily notes
Daily notes
meghendra168
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
Marcus Ramberg
 
Miniproject on Employee Management using Perl/Database.
Miniproject on Employee Management using Perl/Database.Miniproject on Employee Management using Perl/Database.
Miniproject on Employee Management using Perl/Database.
Sanchit Raut
 
WPSessions - Thinking Outside The Box With BuddyPress
WPSessions - Thinking Outside The Box With BuddyPressWPSessions - Thinking Outside The Box With BuddyPress
WPSessions - Thinking Outside The Box With BuddyPress
David Bisset
 
Taking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsTaking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order Functions
David Golden
 
Tidy Up Your Code
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your Code
Abbas Ali
 
Coding website
Coding websiteCoding website
Coding website
PutuMahendra Wijaya
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Masahiro Nagano
 
20 modules i haven't yet talked about
20 modules i haven't yet talked about20 modules i haven't yet talked about
20 modules i haven't yet talked about
Tatsuhiko Miyagawa
 
Php
PhpPhp
Laravel
LaravelLaravel
Laravel
Sayed Ahmed
 
Session8
Session8Session8
06 Php Mysql Connect Query
06 Php Mysql Connect Query06 Php Mysql Connect Query
06 Php Mysql Connect Query
Geshan Manandhar
 
Why Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary ThingWhy Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary Thing
Chris Reynolds
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
jhchabran
 
Who Needs Ruby When You've Got CodeIgniter
Who Needs Ruby When You've Got CodeIgniterWho Needs Ruby When You've Got CodeIgniter
Who Needs Ruby When You've Got CodeIgniter
ciconf
 
CakePHP workshop
CakePHP workshopCakePHP workshop
CakePHP workshop
Walther Lalk
 
Php functions
Php functionsPhp functions
Php functions
JIGAR MAKHIJA
 
Bacbkone js
Bacbkone jsBacbkone js
php Mailer
php Mailerphp Mailer
php Mailer
Randy Arios
 

Similar to SQL so close I can paste it (YAPC::NA::2011 lightning talk) (20)

Daily notes
Daily notesDaily notes
Daily notes
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
Miniproject on Employee Management using Perl/Database.
Miniproject on Employee Management using Perl/Database.Miniproject on Employee Management using Perl/Database.
Miniproject on Employee Management using Perl/Database.
 
WPSessions - Thinking Outside The Box With BuddyPress
WPSessions - Thinking Outside The Box With BuddyPressWPSessions - Thinking Outside The Box With BuddyPress
WPSessions - Thinking Outside The Box With BuddyPress
 
Taking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsTaking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order Functions
 
Tidy Up Your Code
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your Code
 
Coding website
Coding websiteCoding website
Coding website
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
 
20 modules i haven't yet talked about
20 modules i haven't yet talked about20 modules i haven't yet talked about
20 modules i haven't yet talked about
 
Php
PhpPhp
Php
 
Laravel
LaravelLaravel
Laravel
 
Session8
Session8Session8
Session8
 
06 Php Mysql Connect Query
06 Php Mysql Connect Query06 Php Mysql Connect Query
06 Php Mysql Connect Query
 
Why Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary ThingWhy Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary Thing
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
 
Who Needs Ruby When You've Got CodeIgniter
Who Needs Ruby When You've Got CodeIgniterWho Needs Ruby When You've Got CodeIgniter
Who Needs Ruby When You've Got CodeIgniter
 
CakePHP workshop
CakePHP workshopCakePHP workshop
CakePHP workshop
 
Php functions
Php functionsPhp functions
Php functions
 
Bacbkone js
Bacbkone jsBacbkone js
Bacbkone js
 
php Mailer
php Mailerphp Mailer
php Mailer
 

Recently uploaded

inQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
inQuba Webinar Mastering Customer Journey Management with Dr Graham HillinQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
inQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
LizaNolte
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
DanBrown980551
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
Mydbops
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
Safe Software
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
christinelarrosa
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
DianaGray10
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
Fwdays
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 

Recently uploaded (20)

inQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
inQuba Webinar Mastering Customer Journey Management with Dr Graham HillinQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
inQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 

SQL so close I can paste it (YAPC::NA::2011 lightning talk)

  • 1. SQL so close I can paste it YAPC::NA::2011 Asheville Brad Oaks Plus Three, LP
  • 2. printf printf 'person_id %d name: %s', $person_id, $person->name;
  • 3. printf with format as a variable my $fmt = 'person_id %d name: %s'; printf $fmt, $person_id, $person->name;
  • 4. dynamically building a query my (@conds, @binds); my $joins = ''; my @uuids = $self->get_story_uuids;
  • 5. add to your JOINs if( @uuids ) { $joins .= ' JOIN volunteer_form vf ON(civ.volunteer_form_id = vf.volunteer_form_id)'; }
  • 6. add to your conditions if( @uuids ) { push(@conds, 'vf.story_uuid IN ( ' . join(', ', ('?') x scalar(@uuids)) . ')'); push(@binds, @uuids); }
  • 7. assemble WHERE clause my $where = @conds ? ' WHERE ' . join(' AND ', @conds) : '';
  • 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;