SlideShare ist ein Scribd-Unternehmen logo
1 von 13
Downloaden Sie, um offline zu lesen
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;

Weitere ähnliche Inhalte

Was ist angesagt?

PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
elliando dias
 
Threading
ThreadingThreading
Threading
b290572
 
Information Science Blog Aggregation
Information Science Blog AggregationInformation Science Blog Aggregation
Information Science Blog Aggregation
Franny Gaede
 

Was ist angesagt? (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
 

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

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
 
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
 
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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

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;