KEMBAR78
Drupal 8 database api | PPTX
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?

Drupal 8 database api

  • 1.
    Drupal 8 DatabaseApi Presented By: Polaki Viswanath & Pankaj Singh Company: Kellton Tech
  • 2.
    General Concepts Built overPDO 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? Aconnection 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 keyis 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/slaveconfiguration $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 mysqlas 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 specifypdo 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 selectqueries 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 andusing 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 acustom 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'); // AddTag // 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 thegeneral 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... Wheneverquerying 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
  • 24.