SlideShare a Scribd company logo
Drupal II: The SQL
David Diers, Developer
Four Kitchens
Austin, TX

D.O - thebruce
@beautyhammer
What we’ll cover
 Basics of the Drupal DB API
 Using db_query
 Using and building dynamic queries including
   Criteria clauses, joins, sorting, sub-
   selects, extenders, and tagging
 How to work with result sets
Drupal and the DB
Drupal uses the DB to:
   Store content - where
   "content" is thought of very
   broadly.
   Store user or module
   configurations
   Store system values
Drupal retrieves these values
all of the time.
Drupal and DB Abstraction
 What is DB Abstraction?
   A way of uniformly interacting and leveraging
   SQL commands with multiple types of database
   products.
   A structured way of dynamically constructing
   SQL statements
 DB Abstraction is nothing new for Drupal
Drupal 7 DB API uses PDO
 In D7 the DB Abstraction layer got a face-lift
 Built on PDO
    PDO is PHPOOP
    Drupal extends PDO classes
    PDO used in many projects
Why learn the DB API?
 Isn‟t most of this stuff in functions already?
 Doesn‟t views do this for me?
 Can‟t I just use raw SQL like they did in ye olde
 days ™?
Why Learn the DB API?
 Need a result set that you can‟t get or requires custom
 views development?
 Writing or supporting custom modules with their own
 schema?
 Need results from the contrib module‟s schema but there
 isn‟t a function to do so?
 Patching an existing modules‟ database functionality?
 Need additional ways besides features, views, panels to
 transfer configuration via update hooks?
 Need to implement custom sql statements to improve the
 performance of your site?
Using the DB API
 2 Primary ways to interact with data in D7
   dbquery – performant, limited transferability.
   Dynamic queries - more complex, high
   transferability, powerful, less performant.
db_query – the basics
  IN SQL:                    IN db_query:
                          <?php
SELECT nid, title         $type = „article‟;
FROM node                 $result = db_query("SELECT nid, title
WHERE type = „article‟;   FROM {node} WHERE type =
                          :type", array(':type' => $type,));
db_query – the breakdown
$result = db_query("SELECT nid, title FROM {node} WHERE type = :type",
array(':type' => $type,));


   db_query($query, $placeholders, $options)
   enclose tables in { }
   Placeholders start with ":"
      EX: WHERE type = :type", array(':type' => 'page',))
   Options array - 2 common ones are:
      Target (default or slave)
      Fetch (pdo fetch type)

http://druptest7.dev:8888/example_dbq
db_query d6 => d7
transitions
 In transitioning D6 db_query to D7 be aware:
    The syntax signature has changed –
    • D6 parameters were the $query, followed by a
      variable number of arguments or an array of query
      substitutions.
    • % syntax for placeholders
    • Varied sql commands executed via db_query.
Dynamic sql – the basics
 Dynamic Queries
   Much more transportable.
   You MUST use for (
   INSERT, UPDATE, DELETE)
   You may use for (SELECT)
   • http://www.lullabot.com/articles/simplify-your-code-
     with-drupal-7s-database-api ).
db_select – the basics
  IN SQL:                    IN db_select:
                          <?php
SELECT nid, title         $type = „article‟;
FROM node                 $query = db_select(„node‟, ‟n‟);
WHERE type = „article‟;   $result = $query->fields(„n‟,
                          array(„nid‟,‟title‟)
                           ->condition(„n.type‟,$type)
                           ->execute();
db_select – the basics
(„node‟, „n‟)                  IN db_select:
Name of Table / Alias       <?php
                            $type = „article‟;
(fields(„n‟, array(„nid‟,   $query = db_select(„node‟, ‟n‟);
„title‟))
                            $result = $query->fields(„n‟,
                            array(„nid‟,‟title‟)
Alias, array of fields       ->condition(„n.type‟,$type)
                             ->execute();
Single quotes are
important for
transferability.
Dynamic Queries – of note
$query = db_select(„node‟, ‟n‟);
$result = $query->fields(„n‟, array(„nid‟,‟title‟)
 ->condition(„n.type‟,$type)
 ->execute();

  Fluid Interface - allows method chaining
  Query statements are executed by ->execute(); easy
  to forget, but don't.
  You‟ll get back a result set / statement object
Working with Result Sets
 Use - foreach loop or
 or - Specificaly get the next record
    $record = $result->fetch(); // Use the default fetch
    mode.
    $record = $result->fetchObject(); // Fetch as a
    stdClass object.
    $record = $result->fetchAssoc(); // Fetch as an
    associative array.
 or - to get a single field
    $record = $result->fetchField($column_index);
Which should I use?
 Is your query static? Use db_query it is faster.
 Does your query need to be constructed at run
 time? Use dynamic queries
 Do you need to INSERT, UPDATE, or DELETE?
 Use Dynamic queries.
 Are you querying the node table – Use Dynamic
 queries to respect node access.
More with Dynamic Queries
 How to add fields or select *
 Conditional Statements
 AND / OR
 Sub-selects
 JOINS
 SORT
Fields and db_select
 Adding fields to a query:
 $query->fields('n', array('nid', 'title', 'created', 'uid'));

 "select *" is fields with no field array indicated:
 $query->fields('n');




 http://druptest7.dev:8888/example_dyn
Conditional Statements
 Signature: $query->condition($field, $value = NULL,
 $operator = '=')
 Default operator is SQL =
 can take ANSI sql comparators <, >, LIKE, = >=
    EX: $query->condition('nid',1)
    EX: $query->condition('nid',1, '<>')
 In or between:
    EX: $query->condition('myfield', array(1, 2, 3), 'IN');
Conditional Statements
(more)
  Nested Conditionals:
  db_and() / db_or() / db_xor() are used to handle
  nested conditionals such as:
  ->condition(db_or()
    ->condition('field2', 5)
    ->condition('field3', 6))

Testing for NULL:
$query->isNull('myfield');
$query->isNotNull('myfield');
An example from the field…
  Original query:
$result = db_query('SELECT * FROM {users}
WHERE ((access <> 0 AND login <> 0 AND access
< (%d - %d)) OR (login = 0 AND created < (%d -
%d))) AND uid <> 1', REQUEST_TIME, $warn_time,
REQUEST_TIME, $warn_time);
Now In dynamic query format
 $query = db_select('users', 'u');
    $query->fields('u', array('uid', 'name', 'mail', 'created', 'access'))
    ->condition(db_or()
      ->condition(db_and()
       ->condition('u.access', 0, '<>')
       ->condition('u.login', 0, '<>')
       ->condition('u.access', REQUEST_TIME - $warn_time, '<'))
      ->condition(db_and()
       ->condition('u.login', 0)
       ->condition('u.created', REQUEST_TIME - $warn_time, '<'))
    )
    ->condition('u.uid', 1, '<>');

     $results = $query->execute();
Subselects
 Subselects - form a query using dbtng then instead
 of executing it -
 use that query variable in a condition.
    Most successful when one value is returned,
    or a one column return value is used with an IN
    clause.

 $query->condition('myfield', $querysubselect, 'IN');
JOINS & db_select
<?php
$query = db_select('node', 'n');
$query->join('field_data_body', 'b', 'n.nid = b.entity_id');
$query
->fields('n', array('nid', 'title'))
->condition('n.type', 'page')
->condition('n.status', '1')
->orderBy('n.created', 'DESC')
->addTag('node_access');
?>
dynamic queries: sorting
  orderBy(„field‟, „ASC‟/‟DESC‟)

$result = db_select(„node‟, „n‟)
 ->fields(„n‟, array(„title‟))
 ->orderBy(„n.created‟, „DESC‟)
 ->execute();
db_select Tagging
Tagging – lets alter hooks take action

ex: $query->addTag('node_access'); - this should be
implemented on all queries that retrieve nodes.

Node access query alter will then check to see if a
user can see the nodes in the result.

(http://druptest7.dev:8888/example_tag)
What about the others?
 db_update, db_insert, db_delete
 Similar syntax
 Assemble and execute.
db_insert
   Syntax: $query = db_insert('node', $options);
   $nid = db_insert('node')
   ->fields(array(
      'title' => ‟This Example',
      'uid' => 1,
      'created' => REQUEST_TIME,
   ))
   ->execute();
   db_insert returns the auto-increment value defined by
   hook_schema.

(http://druptest7.dev:8888/example_insert)
db_update
$num_updated = db_update('node')
->fields(array(
   'uid' => 1
))
->condition('uid', 2)
->execute();

db_update returns the number of records updated.

  http://druptest7.dev:8888/example_update
db_delete
Signature: $query = db_delete('node', $options);

$num_deleted = db_delete('node')
->condition('nid', 5)
->execute();


db_delete returns the number of rows deleted.

 http://druptest7.dev:8888/example_delete
db_select extenders
 Extenders - implements a decorator pattern, currently only two in core

 TableSort and PagerQuery = adds the methods for these extension to
 query

 example:
 $query = $query
 ->extend('TableSort')
 ->orderByHeader($header);

 Put these near the start.
 Not chainable, if you forget to return it to itself it will have odd results.



 http://druptest7.dev:8888/example_extend
TIME FOR BONUS ROUND
         YUB NUB
What is the ?
Now that you have Drupal DB Chops
You may start to consider…



                    To VIEWS or
                       not to
                       VIEWS
DB API an Alternative to
Views
 Who will maintain the functionality?
 Does it require a lot of custom views code?
 Are you doing a lot of aggregated data work?
 Do you need a highly tuned SQL statement for performance?
 Do you need a lot of user facing, non programmer modifications,
 will site builders be cloning views or modifying displays?
 Are you integrating with other modules (panels, voting, etc)?
 How complex are the changes you need to views default
 queries/output?

   To views or not to views (http://drupal.org/node/242311 )
Quick case study:
• Client wanted private comments
• Client wanted to see a listing of all comments
  made against all nodes
• Views can do this but it is described as “hacky”
• Created a db_select with pager and table
  extenders
Questions and Thank you!
David Diers, Developer
Four Kitchens
david.diers@fourkitchens.com

D.O - thebruce
@beautyhammer
Drupal II: The SQL

More Related Content

What's hot

Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
Hugo Hamon
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
Hugo Hamon
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в MagentoMagecom Ukraine
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
Pavel Makhrinsky
 
Drupal Render API
Drupal Render APIDrupal Render API
Drupal Render API
Pavel Makhrinsky
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
Pavel Makhrinsky
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
Nate Abele
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
Nate Abele
 
CodeIgniter Class Reference
CodeIgniter Class ReferenceCodeIgniter Class Reference
CodeIgniter Class Reference
Jamshid Hashimi
 
Drupal 8: Routing & More
Drupal 8: Routing & MoreDrupal 8: Routing & More
Drupal 8: Routing & More
drubb
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
Rafael Dohms
 
Modularity and Layered Data Model
Modularity and Layered Data ModelModularity and Layered Data Model
Modularity and Layered Data Model
Attila Jenei
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aidawaraiotoko
 
Caching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment CachingCaching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment Caching
Erick Hitter
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
Azim Kurt
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
Hugo Hamon
 
Dependency Injection in Laravel
Dependency Injection in LaravelDependency Injection in Laravel
Dependency Injection in Laravel
HAO-WEN ZHANG
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
Nate Abele
 
Drupal 8 Sample Module
Drupal 8 Sample ModuleDrupal 8 Sample Module
Drupal 8 Sample Module
drubb
 

What's hot (20)

Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
 
Drupal Render API
Drupal Render APIDrupal Render API
Drupal Render API
 
B13 Investigating oracle by Julian Dyke
B13 Investigating oracle by Julian DykeB13 Investigating oracle by Julian Dyke
B13 Investigating oracle by Julian Dyke
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
CodeIgniter Class Reference
CodeIgniter Class ReferenceCodeIgniter Class Reference
CodeIgniter Class Reference
 
Drupal 8: Routing & More
Drupal 8: Routing & MoreDrupal 8: Routing & More
Drupal 8: Routing & More
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 
Modularity and Layered Data Model
Modularity and Layered Data ModelModularity and Layered Data Model
Modularity and Layered Data Model
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aida
 
Caching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment CachingCaching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment Caching
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
Dependency Injection in Laravel
Dependency Injection in LaravelDependency Injection in Laravel
Dependency Injection in Laravel
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Drupal 8 Sample Module
Drupal 8 Sample ModuleDrupal 8 Sample Module
Drupal 8 Sample Module
 

Viewers also liked

Resumen unidad 1 actividad 1
Resumen unidad 1 actividad 1Resumen unidad 1 actividad 1
Resumen unidad 1 actividad 1
maricelaidm
 
Seguridad
SeguridadSeguridad
Seguridad
Yulder Bermeo
 
Marketingclassprojectii 13019382401354-phpapp02
Marketingclassprojectii 13019382401354-phpapp02Marketingclassprojectii 13019382401354-phpapp02
Marketingclassprojectii 13019382401354-phpapp02Shivani Gupta
 
Early northernrenaissance
Early northernrenaissanceEarly northernrenaissance
Early northernrenaissance
Andrea Fuentes
 
Drupal 7 Tutorial: Features Module
Drupal 7 Tutorial: Features ModuleDrupal 7 Tutorial: Features Module
Drupal 7 Tutorial: Features ModuleAcquia
 
Action Mailer
Action MailerAction Mailer
Action Mailer
SHC
 
Presentasi Kelompok 25 PW A+B
Presentasi Kelompok 25 PW A+BPresentasi Kelompok 25 PW A+B
Presentasi Kelompok 25 PW A+B
Hapsoro Permana
 

Viewers also liked (8)

Resumen unidad 1 actividad 1
Resumen unidad 1 actividad 1Resumen unidad 1 actividad 1
Resumen unidad 1 actividad 1
 
Seguridad
SeguridadSeguridad
Seguridad
 
tecnologia voip
tecnologia voiptecnologia voip
tecnologia voip
 
Marketingclassprojectii 13019382401354-phpapp02
Marketingclassprojectii 13019382401354-phpapp02Marketingclassprojectii 13019382401354-phpapp02
Marketingclassprojectii 13019382401354-phpapp02
 
Early northernrenaissance
Early northernrenaissanceEarly northernrenaissance
Early northernrenaissance
 
Drupal 7 Tutorial: Features Module
Drupal 7 Tutorial: Features ModuleDrupal 7 Tutorial: Features Module
Drupal 7 Tutorial: Features Module
 
Action Mailer
Action MailerAction Mailer
Action Mailer
 
Presentasi Kelompok 25 PW A+B
Presentasi Kelompok 25 PW A+BPresentasi Kelompok 25 PW A+B
Presentasi Kelompok 25 PW A+B
 

Similar to Drupal II: The SQL

DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7chuvainc
 
Database API, your new friend
Database API, your new friendDatabase API, your new friend
Database API, your new friendkikoalonsob
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database api
Viswanath Polaki
 
Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09
Michelangelo van Dam
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
Michelangelo van Dam
 
What's new in the Drupal 7 API?
What's new in the Drupal 7 API?What's new in the Drupal 7 API?
What's new in the Drupal 7 API?
Alexandru Badiu
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in Perl
Laurent Dami
 
Working with databases
Working with databasesWorking with databases
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
Jonathan Wage
 
Fatc
FatcFatc
Drupal as a web framework
Drupal as a web frameworkDrupal as a web framework
Drupal as a web framework
Adam Kalsey
 
Sqlite perl
Sqlite perlSqlite perl
Sqlite perl
Ashoka Vanjare
 
Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
Benjamin Eberlei
 
About Data::ObjectDriver
About Data::ObjectDriverAbout Data::ObjectDriver
About Data::ObjectDriver
Yoshiki Kurihara
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
Rifat Nabi
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)Night Sailer
 
Slow Database in your PHP stack? Don't blame the DBA!
Slow Database in your PHP stack? Don't blame the DBA!Slow Database in your PHP stack? Don't blame the DBA!
Slow Database in your PHP stack? Don't blame the DBA!
Harald Zeitlhofer
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redis
jimbojsb
 
2015 02-09 - NoSQL Vorlesung Mosbach
2015 02-09 - NoSQL Vorlesung Mosbach2015 02-09 - NoSQL Vorlesung Mosbach
2015 02-09 - NoSQL Vorlesung Mosbach
Johannes Hoppe
 

Similar to Drupal II: The SQL (20)

DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
 
Database API, your new friend
Database API, your new friendDatabase API, your new friend
Database API, your new friend
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database api
 
Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
What's new in the Drupal 7 API?
What's new in the Drupal 7 API?What's new in the Drupal 7 API?
What's new in the Drupal 7 API?
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in Perl
 
Working with databases
Working with databasesWorking with databases
Working with databases
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
 
Fatc
FatcFatc
Fatc
 
Drupal as a web framework
Drupal as a web frameworkDrupal as a web framework
Drupal as a web framework
 
Sqlite perl
Sqlite perlSqlite perl
Sqlite perl
 
Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
 
About Data::ObjectDriver
About Data::ObjectDriverAbout Data::ObjectDriver
About Data::ObjectDriver
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Php summary
Php summaryPhp summary
Php summary
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
Slow Database in your PHP stack? Don't blame the DBA!
Slow Database in your PHP stack? Don't blame the DBA!Slow Database in your PHP stack? Don't blame the DBA!
Slow Database in your PHP stack? Don't blame the DBA!
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redis
 
2015 02-09 - NoSQL Vorlesung Mosbach
2015 02-09 - NoSQL Vorlesung Mosbach2015 02-09 - NoSQL Vorlesung Mosbach
2015 02-09 - NoSQL Vorlesung Mosbach
 

Recently uploaded

LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 

Recently uploaded (20)

LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 

Drupal II: The SQL

  • 1. Drupal II: The SQL David Diers, Developer Four Kitchens Austin, TX D.O - thebruce @beautyhammer
  • 2. What we’ll cover Basics of the Drupal DB API Using db_query Using and building dynamic queries including Criteria clauses, joins, sorting, sub- selects, extenders, and tagging How to work with result sets
  • 3. Drupal and the DB Drupal uses the DB to: Store content - where "content" is thought of very broadly. Store user or module configurations Store system values Drupal retrieves these values all of the time.
  • 4. Drupal and DB Abstraction What is DB Abstraction? A way of uniformly interacting and leveraging SQL commands with multiple types of database products. A structured way of dynamically constructing SQL statements DB Abstraction is nothing new for Drupal
  • 5. Drupal 7 DB API uses PDO In D7 the DB Abstraction layer got a face-lift Built on PDO PDO is PHPOOP Drupal extends PDO classes PDO used in many projects
  • 6. Why learn the DB API? Isn‟t most of this stuff in functions already? Doesn‟t views do this for me? Can‟t I just use raw SQL like they did in ye olde days ™?
  • 7. Why Learn the DB API? Need a result set that you can‟t get or requires custom views development? Writing or supporting custom modules with their own schema? Need results from the contrib module‟s schema but there isn‟t a function to do so? Patching an existing modules‟ database functionality? Need additional ways besides features, views, panels to transfer configuration via update hooks? Need to implement custom sql statements to improve the performance of your site?
  • 8. Using the DB API 2 Primary ways to interact with data in D7 dbquery – performant, limited transferability. Dynamic queries - more complex, high transferability, powerful, less performant.
  • 9. db_query – the basics IN SQL: IN db_query: <?php SELECT nid, title $type = „article‟; FROM node $result = db_query("SELECT nid, title WHERE type = „article‟; FROM {node} WHERE type = :type", array(':type' => $type,));
  • 10. db_query – the breakdown $result = db_query("SELECT nid, title FROM {node} WHERE type = :type", array(':type' => $type,)); db_query($query, $placeholders, $options) enclose tables in { } Placeholders start with ":" EX: WHERE type = :type", array(':type' => 'page',)) Options array - 2 common ones are: Target (default or slave) Fetch (pdo fetch type) http://druptest7.dev:8888/example_dbq
  • 11. db_query d6 => d7 transitions In transitioning D6 db_query to D7 be aware: The syntax signature has changed – • D6 parameters were the $query, followed by a variable number of arguments or an array of query substitutions. • % syntax for placeholders • Varied sql commands executed via db_query.
  • 12. Dynamic sql – the basics Dynamic Queries Much more transportable. You MUST use for ( INSERT, UPDATE, DELETE) You may use for (SELECT) • http://www.lullabot.com/articles/simplify-your-code- with-drupal-7s-database-api ).
  • 13. db_select – the basics IN SQL: IN db_select: <?php SELECT nid, title $type = „article‟; FROM node $query = db_select(„node‟, ‟n‟); WHERE type = „article‟; $result = $query->fields(„n‟, array(„nid‟,‟title‟) ->condition(„n.type‟,$type) ->execute();
  • 14. db_select – the basics („node‟, „n‟) IN db_select: Name of Table / Alias <?php $type = „article‟; (fields(„n‟, array(„nid‟, $query = db_select(„node‟, ‟n‟); „title‟)) $result = $query->fields(„n‟, array(„nid‟,‟title‟) Alias, array of fields ->condition(„n.type‟,$type) ->execute(); Single quotes are important for transferability.
  • 15. Dynamic Queries – of note $query = db_select(„node‟, ‟n‟); $result = $query->fields(„n‟, array(„nid‟,‟title‟) ->condition(„n.type‟,$type) ->execute(); Fluid Interface - allows method chaining Query statements are executed by ->execute(); easy to forget, but don't. You‟ll get back a result set / statement object
  • 16. Working with Result Sets Use - foreach loop or or - Specificaly get the next record $record = $result->fetch(); // Use the default fetch mode. $record = $result->fetchObject(); // Fetch as a stdClass object. $record = $result->fetchAssoc(); // Fetch as an associative array. or - to get a single field $record = $result->fetchField($column_index);
  • 17. Which should I use? Is your query static? Use db_query it is faster. Does your query need to be constructed at run time? Use dynamic queries Do you need to INSERT, UPDATE, or DELETE? Use Dynamic queries. Are you querying the node table – Use Dynamic queries to respect node access.
  • 18. More with Dynamic Queries How to add fields or select * Conditional Statements AND / OR Sub-selects JOINS SORT
  • 19. Fields and db_select Adding fields to a query: $query->fields('n', array('nid', 'title', 'created', 'uid')); "select *" is fields with no field array indicated: $query->fields('n'); http://druptest7.dev:8888/example_dyn
  • 20. Conditional Statements Signature: $query->condition($field, $value = NULL, $operator = '=') Default operator is SQL = can take ANSI sql comparators <, >, LIKE, = >= EX: $query->condition('nid',1) EX: $query->condition('nid',1, '<>') In or between: EX: $query->condition('myfield', array(1, 2, 3), 'IN');
  • 21. Conditional Statements (more) Nested Conditionals: db_and() / db_or() / db_xor() are used to handle nested conditionals such as: ->condition(db_or() ->condition('field2', 5) ->condition('field3', 6)) Testing for NULL: $query->isNull('myfield'); $query->isNotNull('myfield');
  • 22. An example from the field… Original query: $result = db_query('SELECT * FROM {users} WHERE ((access <> 0 AND login <> 0 AND access < (%d - %d)) OR (login = 0 AND created < (%d - %d))) AND uid <> 1', REQUEST_TIME, $warn_time, REQUEST_TIME, $warn_time);
  • 23. Now In dynamic query format $query = db_select('users', 'u'); $query->fields('u', array('uid', 'name', 'mail', 'created', 'access')) ->condition(db_or() ->condition(db_and() ->condition('u.access', 0, '<>') ->condition('u.login', 0, '<>') ->condition('u.access', REQUEST_TIME - $warn_time, '<')) ->condition(db_and() ->condition('u.login', 0) ->condition('u.created', REQUEST_TIME - $warn_time, '<')) ) ->condition('u.uid', 1, '<>'); $results = $query->execute();
  • 24. Subselects Subselects - form a query using dbtng then instead of executing it - use that query variable in a condition. Most successful when one value is returned, or a one column return value is used with an IN clause. $query->condition('myfield', $querysubselect, 'IN');
  • 25. JOINS & db_select <?php $query = db_select('node', 'n'); $query->join('field_data_body', 'b', 'n.nid = b.entity_id'); $query ->fields('n', array('nid', 'title')) ->condition('n.type', 'page') ->condition('n.status', '1') ->orderBy('n.created', 'DESC') ->addTag('node_access'); ?>
  • 26. dynamic queries: sorting orderBy(„field‟, „ASC‟/‟DESC‟) $result = db_select(„node‟, „n‟) ->fields(„n‟, array(„title‟)) ->orderBy(„n.created‟, „DESC‟) ->execute();
  • 27. db_select Tagging Tagging – lets alter hooks take action ex: $query->addTag('node_access'); - this should be implemented on all queries that retrieve nodes. Node access query alter will then check to see if a user can see the nodes in the result. (http://druptest7.dev:8888/example_tag)
  • 28. What about the others? db_update, db_insert, db_delete Similar syntax Assemble and execute.
  • 29. db_insert Syntax: $query = db_insert('node', $options); $nid = db_insert('node') ->fields(array( 'title' => ‟This Example', 'uid' => 1, 'created' => REQUEST_TIME, )) ->execute(); db_insert returns the auto-increment value defined by hook_schema. (http://druptest7.dev:8888/example_insert)
  • 30. db_update $num_updated = db_update('node') ->fields(array( 'uid' => 1 )) ->condition('uid', 2) ->execute(); db_update returns the number of records updated. http://druptest7.dev:8888/example_update
  • 31. db_delete Signature: $query = db_delete('node', $options); $num_deleted = db_delete('node') ->condition('nid', 5) ->execute(); db_delete returns the number of rows deleted. http://druptest7.dev:8888/example_delete
  • 32. db_select extenders Extenders - implements a decorator pattern, currently only two in core TableSort and PagerQuery = adds the methods for these extension to query example: $query = $query ->extend('TableSort') ->orderByHeader($header); Put these near the start. Not chainable, if you forget to return it to itself it will have odd results. http://druptest7.dev:8888/example_extend
  • 33. TIME FOR BONUS ROUND YUB NUB
  • 34. What is the ? Now that you have Drupal DB Chops You may start to consider… To VIEWS or not to VIEWS
  • 35. DB API an Alternative to Views Who will maintain the functionality? Does it require a lot of custom views code? Are you doing a lot of aggregated data work? Do you need a highly tuned SQL statement for performance? Do you need a lot of user facing, non programmer modifications, will site builders be cloning views or modifying displays? Are you integrating with other modules (panels, voting, etc)? How complex are the changes you need to views default queries/output? To views or not to views (http://drupal.org/node/242311 )
  • 36. Quick case study: • Client wanted private comments • Client wanted to see a listing of all comments made against all nodes • Views can do this but it is described as “hacky” • Created a db_select with pager and table extenders
  • 37. Questions and Thank you! David Diers, Developer Four Kitchens david.diers@fourkitchens.com D.O - thebruce @beautyhammer

Editor's Notes

  1. Content – nodes, entitiesconfig - administrator, moduleconfiguraton, or user based configuration settingssystem – logs (watchdog), sessions, queue to be processed at next cron, class hashes
  2. What is DB Abstraction?-&gt; db implementations vary from product to product, ANSI sql implementations vary widelyDB Abstraction is nothing new – Just the way it is done.
  3. It was built on PDO – PHP Data ObjectsPDO is written in PHPOOPDrupal implements extensions or interfaces of PDO classesPDO is in wide use across many projects (Symfony, Zend Framework, Magento)
  4. 2 Primary ways to interact with data in D7dbquery - performant but limited transferability.Dynamic queries - more complex, high transferability, powerful, less performant.
  5. Let’s use this simple query of the node table
  6. enclose tables in { } for db prefixarg 2 - use placeholders to avoid sql injection, start with &quot;:&quot;EX: WHERE type = :type&quot;, array(&apos;:type&apos; =&gt; &apos;page&apos;,))arg3 – options array - 2 common ones are:target - default or slavefetch - pdo fetch type (the select statement will return into the fetch type specified. Can and should use object(default), assoc array, or a string class name.
  7. In transitioning D6 db_query to D7 be aware:The syntax signature has changed –D6 took a single parameter – the $query, followed by a variable number of arguments or an array of query substitutions.D6 used the % syntax for placeholders instead of the “:” syntax.Functions other than select could be executed via db_query.
  8. Let’s use this simple query of the node table
  9. Let’s use this simple query of the node table
  10. $query = db_select(‘node’, ’n’);$result = $query-&gt;fields(‘n’, array(‘nid’,’title’) -&gt;condition(‘n.type’,$type) -&gt;execute;Fluid Interface - allows chaining (because the results of each chainable method return an instance of the object itself)Not all methods are chainable so consult your documentation.$result = $query-&gt;execute();Query statements are executed by -&gt;execute();  easy to forget, but don&apos;t.You’ll get back a result set / statement objectforeach ($result as $record) { //do something
  11. Tagging - any dynamic select query can be tagged with one or more strings which then allows alter hooks to determine if they need to take action.Via hook_query_alter &amp; hook_query_TAG_alterex: $query-&gt;addTag(&apos;node_access&apos;);  - this should be implemented on all queries that retrieve nodes.Node access query alter will then check to see if a user can see the nodes in the result.
  12. Extenders - implements a decorator pattern, currently only two in coreDecorator pattern – allows the “decoration” of a classes functionality at run time, allowing you to change a single instance of a class with a set of functionalityTableSort and PagerQuery = adds the methods for these extension to queryexample:$query = $query-&gt;extend(&apos;TableSort&apos;)-&gt;orderByHeader($header);Put these near the start.Not chainable, if you forget to return it to itself it will have odd results.