SlideShare une entreprise Scribd logo
1  sur  39
Télécharger pour lire hors ligne
Drupal DataBase
                 The next Generation


 Drupal for the Enterprise.
           Austin Drupal User’s Group

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?
    !  Uniformity
    !  Structure
!   DB Abstraction is nothing new for Drupal
Drupal 7 DB API uses PDO
!   D7 had a facelift for DB Layer
!   Built on PDO
    !  PDO is PHPOOP
    !  Drupal extends PDO classes
    !  PDO used in many projects
It takes some learning. So
why learn the DB API?
!   You may say, with all due
    respect:
     !  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™?
A few reasons:
!   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 exportables (features, views,
    panels) to migrate 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
     !  Dynamic queries
db_query – the basics
!   IN SQL:               !   IN db_query:
                          <?php
                          $type = ‘article’;
SELECT nid, title         $result = db_query("SELECT nid, title
FROM node                 FROM {node}
WHERE type = ‘article’;   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 less orderly
     •  % syntax for placeholders
     •  Lawless, unregulated SQL could be executed like a
        dishonorable Klingon
Dynamic sql – the basics
!   Dynamic Queries
    !  Much more transportable, powerful, but complex
    !  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
                          $type = ‘article’;
SELECT nid, title         $query = db_select(‘node’, ’n’);
FROM node                 $result = $query->fields(‘n’,
WHERE type = ‘article’;   array(‘nid’,’title’)
                           ->condition(‘n.type’,$type)
                           ->execute();




                                 Note: This is an example for comparison, selects are better served by dbquery.
db_select – the basics
                            !   IN db_select:
                            <?php
                            $type = ‘article’;
(‘node’, ‘n’)
                            $query = db_select(‘node’, ’n’);
Name of Table / Alias

(fields(‘n’, array(‘nid’,
                            $result = $query->fields(‘n’,
‘title’))
                            array(‘nid’,’title’)
                             ->condition(‘n.type’,$type)
Alias, array of fields
                             ->execute();

Single quotes are
important for
transferability.
DQ– of special note
$query = db_select(‘node’, ’n’);
$result = $query->fields(‘n’, array(‘nid’,’title’)
 ->condition(‘n.type’,$type)
 ->execute();

!   Fluid Interface
!   ->execute();
!   Returns 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);
But which should I use?

  dbquery or dynamic query
Questions to help decide
!   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.
More with Dynamic Queries
!     How to add fields or select *
!     Conditional Statements
!     AND / OR
!     Sub-selects
!     JOINS
!     SORT
Working with Fields
!   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 contrib…
!   Original d6 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);



                                       …ah, contrib.
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.
     !  Best when:
      •  one value is returned,
      •  A 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 2
! 
    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 - dbtng 25th Anniversary Edition

Contenu connexe

Tendances

50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of LithiumNate Abele
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo Hamon
 
Your code sucks, let's fix it (CakeFest2012)
Your code sucks, let's fix it (CakeFest2012)Your code sucks, let's fix it (CakeFest2012)
Your code sucks, let's fix it (CakeFest2012)Rafael Dohms
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design PatternsHugo Hamon
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aidawaraiotoko
 
Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012Rafael Dohms
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data ObjectsWez Furlong
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Fabien Potencier
 
Apache Solr Search Mastery
Apache Solr Search MasteryApache Solr Search Mastery
Apache Solr Search MasteryAcquia
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Formsdrubb
 
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 PimpleHugo Hamon
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkG Woo
 

Tendances (20)

50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database api
 
DBI
DBIDBI
DBI
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Your code sucks, let's fix it (CakeFest2012)
Your code sucks, let's fix it (CakeFest2012)Your code sucks, let's fix it (CakeFest2012)
Your code sucks, let's fix it (CakeFest2012)
 
Daily notes
Daily notesDaily notes
Daily notes
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aida
 
Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
Php 101: PDO
Php 101: PDOPhp 101: PDO
Php 101: PDO
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
 
Apache Solr Search Mastery
Apache Solr Search MasteryApache Solr Search Mastery
Apache Solr Search Mastery
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Forms
 
Agile database access with CakePHP 3
Agile database access with CakePHP 3Agile database access with CakePHP 3
Agile database access with CakePHP 3
 
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
 
CakeFest 2013 keynote
CakeFest 2013 keynoteCakeFest 2013 keynote
CakeFest 2013 keynote
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
 

En vedette

Comenius Poland
Comenius   PolandComenius   Poland
Comenius Polandagnes1311
 
Comenius Poland
Comenius   PolandComenius   Poland
Comenius Polandagnes1311
 
Comenius rada pedagogiczna
Comenius    rada pedagogicznaComenius    rada pedagogiczna
Comenius rada pedagogicznaagnes1311
 
Autumn market
Autumn marketAutumn market
Autumn marketagnes1311
 
Prezentacja o angielskiej szkole - Mobilność Kadry Edukacyjnej
Prezentacja o angielskiej szkole - Mobilność Kadry EdukacyjnejPrezentacja o angielskiej szkole - Mobilność Kadry Edukacyjnej
Prezentacja o angielskiej szkole - Mobilność Kadry Edukacyjnejagnes1311
 
Wales- Places to Go
Wales- Places to GoWales- Places to Go
Wales- Places to GoLouisatom
 

En vedette (9)

Comenius Poland
Comenius   PolandComenius   Poland
Comenius Poland
 
Comenius Poland
Comenius   PolandComenius   Poland
Comenius Poland
 
Comenius rada pedagogiczna
Comenius    rada pedagogicznaComenius    rada pedagogiczna
Comenius rada pedagogiczna
 
Autumn market
Autumn marketAutumn market
Autumn market
 
Cookies 1
Cookies 1Cookies 1
Cookies 1
 
Prezentacja o angielskiej szkole - Mobilność Kadry Edukacyjnej
Prezentacja o angielskiej szkole - Mobilność Kadry EdukacyjnejPrezentacja o angielskiej szkole - Mobilność Kadry Edukacyjnej
Prezentacja o angielskiej szkole - Mobilność Kadry Edukacyjnej
 
Our school
Our schoolOur school
Our school
 
Hobbit1
Hobbit1Hobbit1
Hobbit1
 
Wales- Places to Go
Wales- Places to GoWales- Places to Go
Wales- Places to Go
 

Similaire à Drupal - dbtng 25th Anniversary Edition

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
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesLuis Curo Salvatierra
 
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
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
CodeIgniter Class Reference
CodeIgniter Class ReferenceCodeIgniter Class Reference
CodeIgniter Class ReferenceJamshid Hashimi
 
PHP Development With MongoDB
PHP Development With MongoDBPHP Development With MongoDB
PHP Development With MongoDBFitz Agard
 
PHP Development with MongoDB (Fitz Agard)
PHP Development with MongoDB (Fitz Agard)PHP Development with MongoDB (Fitz Agard)
PHP Development with MongoDB (Fitz Agard)MongoSF
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)Night Sailer
 
Dirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP ExtensionDirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP ExtensionAdam Trachtenberg
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in PerlLaurent Dami
 
Learning the basics of the Drupal API
Learning the basics of the Drupal APILearning the basics of the Drupal API
Learning the basics of the Drupal APIAlexandru Badiu
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needKacper Gunia
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersKacper Gunia
 
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, GermanyLet's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, GermanyBalázs Tatár
 

Similaire à Drupal - dbtng 25th Anniversary Edition (20)

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?
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
 
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!
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
Database api
Database apiDatabase api
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
 
CodeIgniter Class Reference
CodeIgniter Class ReferenceCodeIgniter Class Reference
CodeIgniter Class Reference
 
PHP Development With MongoDB
PHP Development With MongoDBPHP Development With MongoDB
PHP Development With MongoDB
 
PHP Development with MongoDB (Fitz Agard)
PHP Development with MongoDB (Fitz Agard)PHP Development with MongoDB (Fitz Agard)
PHP Development with MongoDB (Fitz Agard)
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
Dirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP ExtensionDirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP Extension
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in Perl
 
Fatc
FatcFatc
Fatc
 
Learning the basics of the Drupal API
Learning the basics of the Drupal APILearning the basics of the Drupal API
Learning the basics of the Drupal API
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4Developers
 
21. CodeIgniter search
21. CodeIgniter search21. CodeIgniter search
21. CodeIgniter search
 
About Data::ObjectDriver
About Data::ObjectDriverAbout Data::ObjectDriver
About Data::ObjectDriver
 
Working with databases
Working with databasesWorking with databases
Working with databases
 
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, GermanyLet's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
 

Dernier

Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 

Dernier (20)

Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 

Drupal - dbtng 25th Anniversary Edition

  • 1. Drupal DataBase The next Generation Drupal for the Enterprise. Austin Drupal User’s Group 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? !  Uniformity !  Structure !   DB Abstraction is nothing new for Drupal
  • 5. Drupal 7 DB API uses PDO !   D7 had a facelift for DB Layer !   Built on PDO !  PDO is PHPOOP !  Drupal extends PDO classes !  PDO used in many projects
  • 6. It takes some learning. So why learn the DB API? !   You may say, with all due respect: !  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. A few reasons: !   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 exportables (features, views, panels) to migrate 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 !  Dynamic queries
  • 9. db_query – the basics !   IN SQL: !   IN db_query: <?php $type = ‘article’; SELECT nid, title $result = db_query("SELECT nid, title FROM node FROM {node} WHERE type = ‘article’; 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 less orderly •  % syntax for placeholders •  Lawless, unregulated SQL could be executed like a dishonorable Klingon
  • 12. Dynamic sql – the basics !   Dynamic Queries !  Much more transportable, powerful, but complex !  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 $type = ‘article’; SELECT nid, title $query = db_select(‘node’, ’n’); FROM node $result = $query->fields(‘n’, WHERE type = ‘article’; array(‘nid’,’title’) ->condition(‘n.type’,$type) ->execute(); Note: This is an example for comparison, selects are better served by dbquery.
  • 14. db_select – the basics !   IN db_select: <?php $type = ‘article’; (‘node’, ‘n’) $query = db_select(‘node’, ’n’); Name of Table / Alias (fields(‘n’, array(‘nid’, $result = $query->fields(‘n’, ‘title’)) array(‘nid’,’title’) ->condition(‘n.type’,$type) Alias, array of fields ->execute(); Single quotes are important for transferability.
  • 15. DQ– of special note $query = db_select(‘node’, ’n’); $result = $query->fields(‘n’, array(‘nid’,’title’) ->condition(‘n.type’,$type) ->execute(); !   Fluid Interface !   ->execute(); !   Returns 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. But which should I use? dbquery or dynamic query
  • 18. Questions to help decide !   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.
  • 19. More with Dynamic Queries !   How to add fields or select * !   Conditional Statements !   AND / OR !   Sub-selects !   JOINS !   SORT
  • 20. Working with Fields !   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
  • 21. 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');
  • 22. 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');
  • 23. An example from contrib… !   Original d6 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); …ah, contrib.
  • 24. 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();
  • 25. Subselects ! Subselects - form a query using dbtng then instead of executing it - !   use that query variable in a condition. !  Best when: •  one value is returned, •  A column return value is used with an IN clause. !   $query->condition('myfield', $querysubselect, 'IN');
  • 26. 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'); ?>
  • 27. dynamic queries: sorting ! orderBy(‘field’, ‘ASC’/’DESC’) $result = db_select(‘node’, ‘n’) ->fields(‘n’, array(‘title’)) ->orderBy(‘n.created’, ‘DESC’) ->execute();
  • 28. 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)
  • 29. What about the others? ! db_update, db_insert, db_delete !   Similar syntax !   Assemble and execute.
  • 30. 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)
  • 31. 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
  • 32. 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
  • 33. db_select extenders !   Extenders - implements a decorator pattern, currently only 2 !  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
  • 34. TIME FOR BONUS ROUND YUB NUB
  • 35. What is the ? Now that you have Drupal DB Chops You may start to consider… To VIEWS or not to VIEWS
  • 36. 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 )
  • 37. 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
  • 38. Questions and Thank you! David Diers, Developer Four Kitchens david.diers@fourkitchens.com D.O - thebruce @beautyhammer

Notes de l'éditeur

  1. Content – nodes, entities, caches, paths, custom tablesconfig - 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 widelyA way of uniformly interacting and leveraging SQL commands with multiple types of database products.A structured way of dynamically constructing SQL statementsDB Abstraction is nothing new to Drupal – 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) so we leverage all of the work, testing and bug fixes from the PHP community at large.
  4. Don’t I already get a lot of stuff through the built in functions of core and contributed modules?Can’t I just use views for my sql stuff.
  5. 2 Primary ways to interact with data in D7dbquery – performant limited transferability amongst dbs simpler – more like the sql of OLDEDynamic queries – powerful high transferability among dbs less performant. complex
  6. Let’s use this simple query of the node table
  7. 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.
  8. IF YOU ARE DOING TRANSITION WORK FROM D6 to D7Be 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.
  9. Let’s use this simple query of the node table
  10. Let’s use this simple query of the node tableNode table and then ‘n’ as the table alias, we’ll use the table alias throughout the query as we can do in SQL.
  11. $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
  12. Because you have a results set returned – to handle the results and get them out to your php in a meaningful wayYou might find the following helpful.
  13. How to work with fieldsUse table aliasSyntax is fields(‘table’, array(of fields))Looking for your olde select * inefficient query? - use fields(‘table’)
  14. This complicated query says:Give me all columns from the table users where UID is not =1 andeither the access does not equal 0And log in does not equal 0And access is less than the result of Request_time minus the $warn_time variableOR the login is 0And created less than the result of Request time minus the warn_time variable.
  15. Give me all columns from the table users where UID is not =1 andeither the access does not equal 0And log in does not equal 0And access is less than the result of Request_time minus the $warn_time variableOR the login is 0And created less than the result of Request time minus the warn_time variable.
  16. 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.
  17. 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.