SlideShare a Scribd company logo
Drupal 8 Database Api
Presented By: Polaki Viswanath & Pankaj Singh
Company: Kellton Tech
General Concepts
Built over PDO library provided by php.
Different databases require different sorts of interaction, the Drupal database
layer requires a driver for each database type. A driver consists of a series of
files located in includes/database/driver, where driver is a string representing
the unique key for that driver.
What are connections?
A connection is an object of class DatabaseConnection, which inherits from the
PDO class.
To create new connection
$conn = Database::getConnection($target, $key);
To get current connection:
$conn = Database::getConnection();
Database configuration
Connection key is a unique identifier for a given database connection.
Target is a database that is used if available. A target of default must be
defined for each and every connection key.
Connection syntax
$databases['default']['default'] = array(
'driver' => 'mysql',
'database' => 'drupaldb',
'username' => 'username',
'password' => 'secret',
'host' => 'localhost',
);
For a master/slave configuration
$databases['default']['default'] = array(
'driver' => 'mysql',
'database' => 'drupaldb1',
'username' => 'username',
'password' => 'secret',
'host' => 'dbserver1',
);
$databases['default']['slave'][] = array(
'driver' => 'mysql',
'database' => 'drupaldb2',
'username' => 'username',
'password' => 'secret',
'host' => 'dbserver2',
);
$databases['default']['slave'][] = array(
'driver' => 'mysql',
'database' => 'drupaldb3',
'username' => 'username',
'password' => 'secret',
'host' => 'dbserver3',
);
For connecting mysql as well as sqlite
$databases['default']['default'] = array(
'driver' => 'mysql',
'database' => 'drupaldb1',
'username' => 'username',
'password' => 'secret',
'host' => 'dbserver1',
);
$databases['extra']['default'] = array(
'driver' => 'sqlite',
'database' => 'files/extradb.sqlite',
);
How to specify pdo options
$databases['default']['default'] = array(
'driver' => 'mysql',
'database' => 'drupaldb',
'username' => 'username',
'password' => 'secret',
'host' => 'dbserver1',
'pdo' => array(ATTR_TIMEOUT => 2.0),
);
Static queries
Only select queries can be static.
For example:
$result = db_query("SELECT nid, title FROM {node}");
$result = db_query("SELECT nid, title FROM {node} WHERE created > :created", array(
':created' => REQUEST_TIME - 3600,
));
$result = db_query("SELECT * FROM {node} WHERE nid IN (:nids[])", array(':nids[]' => array(13, 42, 144)));
Passing options and using the results
$result = db_query("SELECT nid, title FROM {node}", array(), array(
'target' => 'slave',
'fetch' => PDO::FETCH_ASSOC, // Passing Option
));
if ($result) {
while ($row = $result->fetchAssoc()) {
// Do something with:
// $row['nid']
// $row['title']
}
}
Fetching into a custom class
class ExampleClass {
function __construct() {
// Do something
}
}
$result = db_query("SELECT id, title FROM {example_table}", array(), array(
'fetch' => 'ExampleClass',
));
-----------------------------------------To execute constructor before properties are added-------------------------
$result = db_query("SELECT id, title FROM {example_table}");
foreach ($result->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'ExampleClass') as $record) {
// Do something
}
Dynamic queries
All Insert, Update, Delete, and Merge queries must be dynamic. Select queries
may be either static or dynamic.
$query = db_select('users', 'u')
->condition('u.uid', 0, '<>')
->fields('u', array('uid', 'name', 'status', 'created', 'access'))
->range(0, 50);
$result = $query->execute();
foreach ($result as $record) {
// Do something with each $record
}
$query->fields('n', array('nid', 'title', 'created', 'uid')); // Adding fields
$query->condition($field, $value = NULL, $operator = '=') // Adding Condition structure
$query->condition('myfield', array(1, 2, 3), 'IN'); // Using IN operator
$query->condition('myfield', array(5, 10), 'BETWEEN'); // Using BETWEEN
$query
->condition('field1', array(1, 2), 'IN')
->condition(db_or()->condition('field2', 5)->condition('field3', 6))
// Results in:
// (field1 IN (:db_placeholder_1, :db_placeholder_2) AND (field2 = :db_placeholder3 OR field3 = :db_placeholder_4))
Dynamic queries (cont)
Dynamic queries (cont)
$query = db_select('node', 'n');
$query->join('field_data_body', 'b', 'n.nid = b.entity_id'); // Using Joins
$query
->fields('n', array('nid', 'title'))
->condition('n.type', 'page')
->condition('n.status', '1')
->orderBy('n.created', 'DESC')
->addTag('node_access');
There are join(), innerJoin(), leftJoin(), or rightJoin() methods also.
$count_alias = $query->addExpression('created - :offset', 'uid_count', array(':offset' => 3600)); // Adding Expression
$query->groupBy('uid'); // Adding Group by clause.
$query->having('COUNT(uid) >= :matches', array(':matches' => $limit)); // Using Having
Dynamic queries (cont)
$query->orderBy('title', 'DESC')
->orderBy('node.created', 'ASC'); // Adding Order By clause.
$query->orderRandom(); // Random Ordering.
$query->range(5, 10); // Adding Range.
$table1 = db_select('table1', 't1')
->fields('t1', array('column1', 'column2'));
$table2 = db_select('table2', 't2')
->fields('t2', array('column3', 'column4'));
$query = Database::getConnection()
->select($table1->union($table2)) // Adding Union
->fields(NULL, array('column1', 'column2'))
->orderBy('column1')
->orderBy('column2');
Tagging
$query->addTag('node_access'); // Add Tag
// TRUE if this query object has this tag.
$query->hasTag('example');
// TRUE if this query object has every single one of the specified tags.
$query->hasAllTags('example1', 'example2');
// TRUE if this query object has at least one of the specified tags.
$query->hasAnyTag('example1', 'example2');
These tags serve to identify the type of query it is, which in turn allows alter hooks to determine if they need to take action.
Result Sets
$record = $result->fetch(); // Use the default fetch mode.
$record = $result->fetchObject(); // Fetch as a stdClass object.
$record = $result->fetchAssoc(); // Fetch as an associative array.
$record = $result->fetchField($column_index);
$number_of_rows = $result->rowCount();
// Retrieve all records into an indexed array of stdClass objects.
$result->fetchAll();
// Retrieve all records into an associative array keyed by the field in the result specified.
$result->fetchAllAssoc($field);
// Retrieve a 2-column result set as an associative array of field 0 => field 1
$result->fetchAllKeyed();
// You can also specify which two fields to use by specifying the column numbers for each field
$result->fetchAllKeyed(0,2); // would be field 0 => field 2
$result->fetchAllKeyed(1,0); // would be field 1 => field 0
// If you need an array where keys and values contain the same field (e.g. for creating a 'checkboxes' form element), the following is
a perfectly valid method:
$result->fetchAllKeyed(0,0); // would be field 0 => field 0, e.g. [article] => [article]
Insert queries
$nid = db_insert('node')
->fields(array(
'title' => 'Example',
'uid' => 1,
'created' => REQUEST_TIME,
))
->execute();
Update Queries
$num_updated = db_update('node')
->fields(array(
'uid' => 5,
'status' => 1,
))
->condition('created', REQUEST_TIME - 3600, '>=')
->execute();
Delete Queries
$num_deleted = db_delete('node')
->condition('nid', 5)
->execute();
Merge Queries
In the general sense, a Merge query is a combination of an Insert query and an Update query. If a given condition is met,
such as a row with a given primary key already existing, then an Update query is run. If not, an Insert query is run.
db_merge('example')
->key(array('name' => $name))
->fields(array(
'field1' => $value1,
'field2' => $value2,
))
->execute();
Transactions
$transaction = db_transaction();
try {
$id = db_insert('example')
->fields(array(
'field1' => 'mystring',
'field2' => 5,
))
->execute();
return $id;
}
catch (Exception $e) {
$transaction->rollback();
watchdog_exception('my_type', $e);
}
Some interesting points...
Whenever querying the node table you should make use of the "node_access"
tag.
$query = db_select('node', 'n')
->addTag('node_access');
You should use db_query() and friends instead of db_select() for performance
reasons.
echo $query;
print_r($query->arguments());// Debugging
Any Questions?

More Related Content

What's hot

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 2011Masahiro Nagano
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)Night Sailer
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
Nate Abele
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
Nate Abele
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7chuvainc
 
Dependency Injection in Laravel
Dependency Injection in LaravelDependency Injection in Laravel
Dependency Injection in Laravel
HAO-WEN ZHANG
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Nate Abele
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
Nate Abele
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201Fabien Potencier
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aidawaraiotoko
 
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
G Woo
 
Node js mongodriver
Node js mongodriverNode js mongodriver
Node js mongodriver
christkv
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
Rifat Nabi
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHPTaras Kalapun
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and Hobgoblins
Ross Tuck
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
ddiers
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
ddiers
 

What's hot (20)

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
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
 
Dependency Injection in Laravel
Dependency Injection in LaravelDependency Injection in Laravel
Dependency Injection in Laravel
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
Php 101: PDO
Php 101: PDOPhp 101: PDO
Php 101: PDO
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aida
 
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
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Node js mongodriver
Node js mongodriverNode js mongodriver
Node js mongodriver
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHP
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and Hobgoblins
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 

Similar to Drupal 8 database 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óvilesLuis Curo Salvatierra
 
php2.pptx
php2.pptxphp2.pptx
php2.pptx
ElieNGOMSEU
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
Leonardo Proietti
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128PrinceGuru MS
 
Everything About PowerShell
Everything About PowerShellEverything About PowerShell
Everything About PowerShell
Gaetano Causio
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPDifference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Vineet Kumar Saini
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering CollegeDatabase Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
DrDhivyaaCRAssistant
 
CodeIgniter Class Reference
CodeIgniter Class ReferenceCodeIgniter Class Reference
CodeIgniter Class Reference
Jamshid Hashimi
 
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
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
Barang CK
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
Nate Abele
 
Digital Mayflower - Data Pilgrimage with the Drupal Migrate Module
Digital Mayflower - Data Pilgrimage with the Drupal Migrate ModuleDigital Mayflower - Data Pilgrimage with the Drupal Migrate Module
Digital Mayflower - Data Pilgrimage with the Drupal Migrate Module
Erich Beyrent
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceMeet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Ivan Chepurnyi
 
Aura Project for PHP
Aura Project for PHPAura Project for PHP
Aura Project for PHPHari K T
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
Shinya Ohyanagi
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
Michelangelo van Dam
 
Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014
Evgeny Nikitin
 

Similar to Drupal 8 database api (20)

Database api
Database apiDatabase api
Database 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
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
php2.pptx
php2.pptxphp2.pptx
php2.pptx
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
Everything About PowerShell
Everything About PowerShellEverything About PowerShell
Everything About PowerShell
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPDifference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering CollegeDatabase Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
 
CodeIgniter Class Reference
CodeIgniter Class ReferenceCodeIgniter Class Reference
CodeIgniter Class Reference
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Digital Mayflower - Data Pilgrimage with the Drupal Migrate Module
Digital Mayflower - Data Pilgrimage with the Drupal Migrate ModuleDigital Mayflower - Data Pilgrimage with the Drupal Migrate Module
Digital Mayflower - Data Pilgrimage with the Drupal Migrate Module
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceMeet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
 
Aura Project for PHP
Aura Project for PHPAura Project for PHP
Aura Project for PHP
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014
 

Recently uploaded

Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
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
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
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
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 

Recently uploaded (20)

Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
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
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
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 -...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 

Drupal 8 database api

  • 1. Drupal 8 Database Api Presented By: Polaki Viswanath & Pankaj Singh Company: Kellton Tech
  • 2. General Concepts Built over PDO library provided by php. Different databases require different sorts of interaction, the Drupal database layer requires a driver for each database type. A driver consists of a series of files located in includes/database/driver, where driver is a string representing the unique key for that driver.
  • 3. What are connections? A connection is an object of class DatabaseConnection, which inherits from the PDO class. To create new connection $conn = Database::getConnection($target, $key); To get current connection: $conn = Database::getConnection();
  • 4. Database configuration Connection key is a unique identifier for a given database connection. Target is a database that is used if available. A target of default must be defined for each and every connection key.
  • 5. Connection syntax $databases['default']['default'] = array( 'driver' => 'mysql', 'database' => 'drupaldb', 'username' => 'username', 'password' => 'secret', 'host' => 'localhost', );
  • 6. For a master/slave configuration $databases['default']['default'] = array( 'driver' => 'mysql', 'database' => 'drupaldb1', 'username' => 'username', 'password' => 'secret', 'host' => 'dbserver1', ); $databases['default']['slave'][] = array( 'driver' => 'mysql', 'database' => 'drupaldb2', 'username' => 'username', 'password' => 'secret', 'host' => 'dbserver2', ); $databases['default']['slave'][] = array( 'driver' => 'mysql', 'database' => 'drupaldb3', 'username' => 'username', 'password' => 'secret', 'host' => 'dbserver3', );
  • 7. For connecting mysql as well as sqlite $databases['default']['default'] = array( 'driver' => 'mysql', 'database' => 'drupaldb1', 'username' => 'username', 'password' => 'secret', 'host' => 'dbserver1', ); $databases['extra']['default'] = array( 'driver' => 'sqlite', 'database' => 'files/extradb.sqlite', );
  • 8. How to specify pdo options $databases['default']['default'] = array( 'driver' => 'mysql', 'database' => 'drupaldb', 'username' => 'username', 'password' => 'secret', 'host' => 'dbserver1', 'pdo' => array(ATTR_TIMEOUT => 2.0), );
  • 9. Static queries Only select queries can be static. For example: $result = db_query("SELECT nid, title FROM {node}"); $result = db_query("SELECT nid, title FROM {node} WHERE created > :created", array( ':created' => REQUEST_TIME - 3600, )); $result = db_query("SELECT * FROM {node} WHERE nid IN (:nids[])", array(':nids[]' => array(13, 42, 144)));
  • 10. Passing options and using the results $result = db_query("SELECT nid, title FROM {node}", array(), array( 'target' => 'slave', 'fetch' => PDO::FETCH_ASSOC, // Passing Option )); if ($result) { while ($row = $result->fetchAssoc()) { // Do something with: // $row['nid'] // $row['title'] } }
  • 11. Fetching into a custom class class ExampleClass { function __construct() { // Do something } } $result = db_query("SELECT id, title FROM {example_table}", array(), array( 'fetch' => 'ExampleClass', )); -----------------------------------------To execute constructor before properties are added------------------------- $result = db_query("SELECT id, title FROM {example_table}"); foreach ($result->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'ExampleClass') as $record) { // Do something }
  • 12. Dynamic queries All Insert, Update, Delete, and Merge queries must be dynamic. Select queries may be either static or dynamic. $query = db_select('users', 'u') ->condition('u.uid', 0, '<>') ->fields('u', array('uid', 'name', 'status', 'created', 'access')) ->range(0, 50); $result = $query->execute(); foreach ($result as $record) { // Do something with each $record }
  • 13. $query->fields('n', array('nid', 'title', 'created', 'uid')); // Adding fields $query->condition($field, $value = NULL, $operator = '=') // Adding Condition structure $query->condition('myfield', array(1, 2, 3), 'IN'); // Using IN operator $query->condition('myfield', array(5, 10), 'BETWEEN'); // Using BETWEEN $query ->condition('field1', array(1, 2), 'IN') ->condition(db_or()->condition('field2', 5)->condition('field3', 6)) // Results in: // (field1 IN (:db_placeholder_1, :db_placeholder_2) AND (field2 = :db_placeholder3 OR field3 = :db_placeholder_4)) Dynamic queries (cont)
  • 14. Dynamic queries (cont) $query = db_select('node', 'n'); $query->join('field_data_body', 'b', 'n.nid = b.entity_id'); // Using Joins $query ->fields('n', array('nid', 'title')) ->condition('n.type', 'page') ->condition('n.status', '1') ->orderBy('n.created', 'DESC') ->addTag('node_access'); There are join(), innerJoin(), leftJoin(), or rightJoin() methods also. $count_alias = $query->addExpression('created - :offset', 'uid_count', array(':offset' => 3600)); // Adding Expression $query->groupBy('uid'); // Adding Group by clause. $query->having('COUNT(uid) >= :matches', array(':matches' => $limit)); // Using Having
  • 15. Dynamic queries (cont) $query->orderBy('title', 'DESC') ->orderBy('node.created', 'ASC'); // Adding Order By clause. $query->orderRandom(); // Random Ordering. $query->range(5, 10); // Adding Range. $table1 = db_select('table1', 't1') ->fields('t1', array('column1', 'column2')); $table2 = db_select('table2', 't2') ->fields('t2', array('column3', 'column4')); $query = Database::getConnection() ->select($table1->union($table2)) // Adding Union ->fields(NULL, array('column1', 'column2')) ->orderBy('column1') ->orderBy('column2');
  • 16. Tagging $query->addTag('node_access'); // Add Tag // TRUE if this query object has this tag. $query->hasTag('example'); // TRUE if this query object has every single one of the specified tags. $query->hasAllTags('example1', 'example2'); // TRUE if this query object has at least one of the specified tags. $query->hasAnyTag('example1', 'example2'); These tags serve to identify the type of query it is, which in turn allows alter hooks to determine if they need to take action.
  • 17. Result Sets $record = $result->fetch(); // Use the default fetch mode. $record = $result->fetchObject(); // Fetch as a stdClass object. $record = $result->fetchAssoc(); // Fetch as an associative array. $record = $result->fetchField($column_index); $number_of_rows = $result->rowCount(); // Retrieve all records into an indexed array of stdClass objects. $result->fetchAll(); // Retrieve all records into an associative array keyed by the field in the result specified. $result->fetchAllAssoc($field); // Retrieve a 2-column result set as an associative array of field 0 => field 1 $result->fetchAllKeyed(); // You can also specify which two fields to use by specifying the column numbers for each field $result->fetchAllKeyed(0,2); // would be field 0 => field 2 $result->fetchAllKeyed(1,0); // would be field 1 => field 0 // If you need an array where keys and values contain the same field (e.g. for creating a 'checkboxes' form element), the following is a perfectly valid method: $result->fetchAllKeyed(0,0); // would be field 0 => field 0, e.g. [article] => [article]
  • 18. Insert queries $nid = db_insert('node') ->fields(array( 'title' => 'Example', 'uid' => 1, 'created' => REQUEST_TIME, )) ->execute();
  • 19. Update Queries $num_updated = db_update('node') ->fields(array( 'uid' => 5, 'status' => 1, )) ->condition('created', REQUEST_TIME - 3600, '>=') ->execute();
  • 20. Delete Queries $num_deleted = db_delete('node') ->condition('nid', 5) ->execute();
  • 21. Merge Queries In the general sense, a Merge query is a combination of an Insert query and an Update query. If a given condition is met, such as a row with a given primary key already existing, then an Update query is run. If not, an Insert query is run. db_merge('example') ->key(array('name' => $name)) ->fields(array( 'field1' => $value1, 'field2' => $value2, )) ->execute();
  • 22. Transactions $transaction = db_transaction(); try { $id = db_insert('example') ->fields(array( 'field1' => 'mystring', 'field2' => 5, )) ->execute(); return $id; } catch (Exception $e) { $transaction->rollback(); watchdog_exception('my_type', $e); }
  • 23. Some interesting points... Whenever querying the node table you should make use of the "node_access" tag. $query = db_select('node', 'n') ->addTag('node_access'); You should use db_query() and friends instead of db_select() for performance reasons. echo $query; print_r($query->arguments());// Debugging