45a561872a72a2d15c6b37c1b347634279b9573a
[yaffs-website] / web / core / lib / Drupal / Core / Database / database.api.php
1 <?php
2
3 /**
4  * @file
5  * Hooks related to the Database system and the Schema API.
6  */
7
8 use Drupal\Core\Database\Query\Condition;
9
10 /**
11  * @defgroup database Database abstraction layer
12  * @{
13  * Allow the use of different database servers using the same code base.
14  *
15  * @section sec_intro Overview
16  * Drupal's database abstraction layer provides a unified database query API
17  * that can query different underlying databases. It is built upon PHP's
18  * PDO (PHP Data Objects) database API, and inherits much of its syntax and
19  * semantics. Besides providing a unified API for database queries, the
20  * database abstraction layer also provides a structured way to construct
21  * complex queries, and it protects the database by using good security
22  * practices.
23  *
24  * For more detailed information on the database abstraction layer, see
25  * https://www.drupal.org/developing/api/database.
26  *
27  * @section sec_entity Querying entities
28  * Any query on Drupal entities or fields should use the Entity Query API. See
29  * the @link entity_api entity API topic @endlink for more information.
30  *
31  * @section sec_simple Simple SELECT database queries
32  * For simple SELECT queries that do not involve entities, the Drupal database
33  * abstraction layer provides the functions db_query() and db_query_range(),
34  * which execute SELECT queries (optionally with range limits) and return result
35  * sets that you can iterate over using foreach loops. (The result sets are
36  * objects implementing the \Drupal\Core\Database\StatementInterface interface.)
37  * You can use the simple query functions for query strings that are not
38  * dynamic (except for placeholders, see below), and that you are certain will
39  * work in any database engine. See @ref sec_dynamic below if you have a more
40  * complex query, or a query whose syntax would be different in some databases.
41  *
42  * As a note, db_query() and similar functions are wrappers on connection object
43  * methods. In most classes, you should use dependency injection and the
44  * database connection object instead of these wrappers; See @ref sec_connection
45  * below for details.
46  *
47  * To use the simple database query functions, you will need to make a couple of
48  * modifications to your bare SQL query:
49  * - Enclose your table name in {}. Drupal allows site builders to use
50  *   database table name prefixes, so you cannot be sure what the actual
51  *   name of the table will be. So, use the name that is in the hook_schema(),
52  *   enclosed in {}, and Drupal will calculate the right name.
53  * - Instead of putting values for conditions into the query, use placeholders.
54  *   The placeholders are named and start with :, and they take the place of
55  *   putting variables directly into the query, to protect against SQL
56  *   injection attacks.
57  * - LIMIT syntax differs between databases, so if you have a ranged query,
58  *   use db_query_range() instead of db_query().
59  *
60  * For example, if the query you want to run is:
61  * @code
62  * SELECT e.id, e.title, e.created FROM example e WHERE e.uid = $uid
63  *   ORDER BY e.created DESC LIMIT 0, 10;
64  * @endcode
65  * you would do it like this:
66  * @code
67  * $result = db_query_range('SELECT e.id, e.title, e.created
68  *   FROM {example} e
69  *   WHERE e.uid = :uid
70  *   ORDER BY e.created DESC',
71  *   0, 10, array(':uid' => $uid));
72  * foreach ($result as $record) {
73  *   // Perform operations on $record->title, etc. here.
74  * }
75  * @endcode
76  *
77  * Note that if your query has a string condition, like:
78  * @code
79  * WHERE e.my_field = 'foo'
80  * @endcode
81  * when you convert it to placeholders, omit the quotes:
82  * @code
83  * WHERE e.my_field = :my_field
84  * ... array(':my_field' => 'foo') ...
85  * @endcode
86  *
87  * @section sec_dynamic Dynamic SELECT queries
88  * For SELECT queries where the simple query API described in @ref sec_simple
89  * will not work well, you need to use the dynamic query API. However, you
90  * should still use the Entity Query API if your query involves entities or
91  * fields (see the @link entity_api Entity API topic @endlink for more on
92  * entity queries).
93  *
94  * As a note, db_select() and similar functions are wrappers on connection
95  * object methods. In most classes, you should use dependency injection and the
96  * database connection object instead of these wrappers; See @ref sec_connection
97  * below for details.
98  *
99  * The dynamic query API lets you build up a query dynamically using method
100  * calls. As an illustration, the query example from @ref sec_simple above
101  * would be:
102  * @code
103  * $result = db_select('example', 'e')
104  *   ->fields('e', array('id', 'title', 'created'))
105  *   ->condition('e.uid', $uid)
106  *   ->orderBy('e.created', 'DESC')
107  *   ->range(0, 10)
108  *   ->execute();
109  * @endcode
110  *
111  * There are also methods to join to other tables, add fields with aliases,
112  * isNull() to have a @code WHERE e.foo IS NULL @endcode condition, etc. See
113  * https://www.drupal.org/developing/api/database for many more details.
114  *
115  * One note on chaining: It is common in the dynamic database API to chain
116  * method calls (as illustrated here), because most of the query methods modify
117  * the query object and then return the modified query as their return
118  * value. However, there are some important exceptions; these methods (and some
119  * others) do not support chaining:
120  * - join(), innerJoin(), etc.: These methods return the joined table alias.
121  * - addField(): This method returns the field alias.
122  * Check the documentation for the query method you are using to see if it
123  * returns the query or something else, and only chain methods that return the
124  * query.
125  *
126  * @section_insert INSERT, UPDATE, and DELETE queries
127  * INSERT, UPDATE, and DELETE queries need special care in order to behave
128  * consistently across databases; you should never use db_query() to run
129  * an INSERT, UPDATE, or DELETE query. Instead, use functions db_insert(),
130  * db_update(), and db_delete() to obtain a base query on your table, and then
131  * add dynamic conditions (as illustrated in @ref sec_dynamic above).
132  *
133  * As a note, db_insert() and similar functions are wrappers on connection
134  * object methods. In most classes, you should use dependency injection and the
135  * database connection object instead of these wrappers; See @ref sec_connection
136  * below for details.
137  *
138  * For example, if your query is:
139  * @code
140  * INSERT INTO example (id, uid, path, name) VALUES (1, 2, 'path', 'Name');
141  * @endcode
142  * You can execute it via:
143  * @code
144  * $fields = array('id' => 1, 'uid' => 2, 'path' => 'path', 'name' => 'Name');
145  * db_insert('example')
146  *   ->fields($fields)
147  *   ->execute();
148  * @endcode
149  *
150  * @section sec_transaction Transactions
151  * Drupal supports transactions, including a transparent fallback for
152  * databases that do not support transactions. To start a new transaction,
153  * call @code $txn = db_transaction(); @endcode The transaction will
154  * remain open for as long as the variable $txn remains in scope; when $txn is
155  * destroyed, the transaction will be committed. If your transaction is nested
156  * inside of another then Drupal will track each transaction and only commit
157  * the outer-most transaction when the last transaction object goes out out of
158  * scope (when all relevant queries have completed successfully).
159  *
160  * Example:
161  * @code
162  * function my_transaction_function() {
163  *   // The transaction opens here.
164  *   $txn = db_transaction();
165  *
166  *   try {
167  *     $id = db_insert('example')
168  *       ->fields(array(
169  *         'field1' => 'mystring',
170  *         'field2' => 5,
171  *       ))
172  *       ->execute();
173  *
174  *     my_other_function($id);
175  *
176  *     return $id;
177  *   }
178  *   catch (Exception $e) {
179  *     // Something went wrong somewhere, so roll back now.
180  *     $txn->rollBack();
181  *     // Log the exception to watchdog.
182  *     watchdog_exception('type', $e);
183  *   }
184  *
185  *   // $txn goes out of scope here.  Unless the transaction was rolled back, it
186  *   // gets automatically committed here.
187  * }
188  *
189  * function my_other_function($id) {
190  *   // The transaction is still open here.
191  *
192  *   if ($id % 2 == 0) {
193  *     db_update('example')
194  *       ->condition('id', $id)
195  *       ->fields(array('field2' => 10))
196  *       ->execute();
197  *   }
198  * }
199  * @endcode
200  *
201  * @section sec_connection Database connection objects
202  * The examples here all use functions like db_select() and db_query(), which
203  * can be called from any Drupal method or function code. In some classes, you
204  * may already have a database connection object in a member variable, or it may
205  * be passed into a class constructor via dependency injection. If that is the
206  * case, you can look at the code for db_select() and the other functions to see
207  * how to get a query object from your connection variable. For example:
208  * @code
209  * $query = $connection->select('example', 'e');
210  * @endcode
211  * would be the equivalent of
212  * @code
213  * $query = db_select('example', 'e');
214  * @endcode
215  * if you had a connection object variable $connection available to use. See
216  * also the @link container Services and Dependency Injection topic. @endlink
217  *
218  * @see https://www.drupal.org/developing/api/database
219  * @see entity_api
220  * @see schemaapi
221  *
222  * @}
223  */
224
225 /**
226  * @defgroup schemaapi Schema API
227  * @{
228  * API to handle database schemas.
229  *
230  * A Drupal schema definition is an array structure representing one or
231  * more tables and their related keys and indexes. A schema is defined by
232  * hook_schema(), which usually lives in a modulename.install file.
233  *
234  * By implementing hook_schema() and specifying the tables your module
235  * declares, you can easily create and drop these tables on all
236  * supported database engines. You don't have to deal with the
237  * different SQL dialects for table creation and alteration of the
238  * supported database engines.
239  *
240  * hook_schema() should return an array with a key for each table that
241  * the module defines.
242  *
243  * The following keys are defined:
244  *   - 'description': A string in non-markup plain text describing this table
245  *     and its purpose. References to other tables should be enclosed in
246  *     curly-brackets. For example, the node_field_revision table
247  *     description field might contain "Stores per-revision title and
248  *     body data for each {node}."
249  *   - 'fields': An associative array ('fieldname' => specification)
250  *     that describes the table's database columns. The specification
251  *     is also an array. The following specification parameters are defined:
252  *     - 'description': A string in non-markup plain text describing this field
253  *       and its purpose. References to other tables should be enclosed in
254  *       curly-brackets. For example, the node table vid field
255  *       description might contain "Always holds the largest (most
256  *       recent) {node_field_revision}.vid value for this nid."
257  *     - 'type': The generic datatype: 'char', 'varchar', 'text', 'blob', 'int',
258  *       'float', 'numeric', or 'serial'. Most types just map to the according
259  *       database engine specific datatypes. Use 'serial' for auto incrementing
260  *       fields. This will expand to 'INT auto_increment' on MySQL.
261  *       A special 'varchar_ascii' type is also available for limiting machine
262  *       name field to US ASCII characters.
263  *     - 'mysql_type', 'pgsql_type', 'sqlite_type', etc.: If you need to
264  *       use a record type not included in the officially supported list
265  *       of types above, you can specify a type for each database
266  *       backend. In this case, you can leave out the type parameter,
267  *       but be advised that your schema will fail to load on backends that
268  *       do not have a type specified. A possible solution can be to
269  *       use the "text" type as a fallback.
270  *     - 'serialize': A boolean indicating whether the field will be stored as
271  *       a serialized string.
272  *     - 'size': The data size: 'tiny', 'small', 'medium', 'normal',
273  *       'big'. This is a hint about the largest value the field will
274  *       store and determines which of the database engine specific
275  *       datatypes will be used (e.g. on MySQL, TINYINT vs. INT vs. BIGINT).
276  *       'normal', the default, selects the base type (e.g. on MySQL,
277  *       INT, VARCHAR, BLOB, etc.).
278  *       Not all sizes are available for all data types. See
279  *       DatabaseSchema::getFieldTypeMap() for possible combinations.
280  *     - 'not null': If true, no NULL values will be allowed in this
281  *       database column. Defaults to false.
282  *     - 'default': The field's default value. The PHP type of the
283  *       value matters: '', '0', and 0 are all different. If you
284  *       specify '0' as the default value for a type 'int' field it
285  *       will not work because '0' is a string containing the
286  *       character "zero", not an integer.
287  *     - 'length': The maximal length of a type 'char', 'varchar' or 'text'
288  *       field. Ignored for other field types.
289  *     - 'unsigned': A boolean indicating whether a type 'int', 'float'
290  *       and 'numeric' only is signed or unsigned. Defaults to
291  *       FALSE. Ignored for other field types.
292  *     - 'precision', 'scale': For type 'numeric' fields, indicates
293  *       the precision (total number of significant digits) and scale
294  *       (decimal digits right of the decimal point). Both values are
295  *       mandatory. Ignored for other field types.
296  *     - 'binary': A boolean indicating that MySQL should force 'char',
297  *       'varchar' or 'text' fields to use case-sensitive binary collation.
298  *       This has no effect on other database types for which case sensitivity
299  *       is already the default behavior.
300  *     All parameters apart from 'type' are optional except that type
301  *     'numeric' columns must specify 'precision' and 'scale', and type
302  *     'varchar' must specify the 'length' parameter.
303  *  - 'primary key': An array of one or more key column specifiers (see below)
304  *    that form the primary key.
305  *  - 'unique keys': An associative array of unique keys ('keyname' =>
306  *    specification). Each specification is an array of one or more
307  *    key column specifiers (see below) that form a unique key on the table.
308  *  - 'foreign keys': An associative array of relations ('my_relation' =>
309  *    specification). Each specification is an array containing the name of
310  *    the referenced table ('table'), and an array of column mappings
311  *    ('columns'). Column mappings are defined by key pairs ('source_column' =>
312  *    'referenced_column'). This key is for documentation purposes only; foreign
313  *    keys are not created in the database, nor are they enforced by Drupal.
314  *  - 'indexes':  An associative array of indexes ('indexname' =>
315  *    specification). Each specification is an array of one or more
316  *    key column specifiers (see below) that form an index on the
317  *    table.
318  *
319  * A key column specifier is either a string naming a column or an
320  * array of two elements, column name and length, specifying a prefix
321  * of the named column.
322  *
323  * As an example, here is a SUBSET of the schema definition for
324  * Drupal's 'node' table. It show four fields (nid, vid, type, and
325  * title), the primary key on field 'nid', a unique key named 'vid' on
326  * field 'vid', and two indexes, one named 'nid' on field 'nid' and
327  * one named 'node_title_type' on the field 'title' and the first four
328  * bytes of the field 'type':
329  *
330  * @code
331  * $schema['node'] = array(
332  *   'description' => 'The base table for nodes.',
333  *   'fields' => array(
334  *     'nid'       => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
335  *     'vid'       => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE,'default' => 0),
336  *     'type'      => array('type' => 'varchar','length' => 32,'not null' => TRUE, 'default' => ''),
337  *     'language'  => array('type' => 'varchar','length' => 12,'not null' => TRUE,'default' => ''),
338  *     'title'     => array('type' => 'varchar','length' => 255,'not null' => TRUE, 'default' => ''),
339  *     'uid'       => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
340  *     'status'    => array('type' => 'int', 'not null' => TRUE, 'default' => 1),
341  *     'created'   => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
342  *     'changed'   => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
343  *     'comment'   => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
344  *     'promote'   => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
345  *     'moderate'  => array('type' => 'int', 'not null' => TRUE,'default' => 0),
346  *     'sticky'    => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
347  *     'translate' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
348  *   ),
349  *   'indexes' => array(
350  *     'node_changed'        => array('changed'),
351  *     'node_created'        => array('created'),
352  *     'node_moderate'       => array('moderate'),
353  *     'node_frontpage'      => array('promote', 'status', 'sticky', 'created'),
354  *     'node_status_type'    => array('status', 'type', 'nid'),
355  *     'node_title_type'     => array('title', array('type', 4)),
356  *     'node_type'           => array(array('type', 4)),
357  *     'uid'                 => array('uid'),
358  *     'translate'           => array('translate'),
359  *   ),
360  *   'unique keys' => array(
361  *     'vid' => array('vid'),
362  *   ),
363  *   // For documentation purposes only; foreign keys are not created in the
364  *   // database.
365  *   'foreign keys' => array(
366  *     'node_revision' => array(
367  *       'table' => 'node_field_revision',
368  *       'columns' => array('vid' => 'vid'),
369  *      ),
370  *     'node_author' => array(
371  *       'table' => 'users',
372  *       'columns' => array('uid' => 'uid'),
373  *      ),
374  *    ),
375  *   'primary key' => array('nid'),
376  * );
377  * @endcode
378  *
379  * @see drupal_install_schema()
380  *
381  * @}
382  */
383
384 /**
385  * @addtogroup hooks
386  * @{
387  */
388
389 /**
390  * Perform alterations to a structured query.
391  *
392  * Structured (aka dynamic) queries that have tags associated may be altered by any module
393  * before the query is executed.
394  *
395  * @param $query
396  *   A Query object describing the composite parts of a SQL query.
397  *
398  * @see hook_query_TAG_alter()
399  * @see node_query_node_access_alter()
400  * @see AlterableInterface
401  * @see SelectInterface
402  *
403  * @ingroup database
404  */
405 function hook_query_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
406   if ($query->hasTag('micro_limit')) {
407     $query->range(0, 2);
408   }
409 }
410
411 /**
412  * Perform alterations to a structured query for a given tag.
413  *
414  * @param $query
415  *   An Query object describing the composite parts of a SQL query.
416  *
417  * @see hook_query_alter()
418  * @see node_query_node_access_alter()
419  * @see AlterableInterface
420  * @see SelectInterface
421  *
422  * @ingroup database
423  */
424 function hook_query_TAG_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
425   // Skip the extra expensive alterations if site has no node access control modules.
426   if (!node_access_view_all_nodes()) {
427     // Prevent duplicates records.
428     $query->distinct();
429     // The recognized operations are 'view', 'update', 'delete'.
430     if (!$op = $query->getMetaData('op')) {
431       $op = 'view';
432     }
433     // Skip the extra joins and conditions for node admins.
434     if (!\Drupal::currentUser()->hasPermission('bypass node access')) {
435       // The node_access table has the access grants for any given node.
436       $access_alias = $query->join('node_access', 'na', '%alias.nid = n.nid');
437       $or = new Condition('OR');
438       // If any grant exists for the specified user, then user has access to the node for the specified operation.
439       foreach (node_access_grants($op, $query->getMetaData('account')) as $realm => $gids) {
440         foreach ($gids as $gid) {
441           $or->condition((new Condition('AND'))
442             ->condition($access_alias . '.gid', $gid)
443             ->condition($access_alias . '.realm', $realm)
444           );
445         }
446       }
447
448       if (count($or->conditions())) {
449         $query->condition($or);
450       }
451
452       $query->condition($access_alias . 'grant_' . $op, 1, '>=');
453     }
454   }
455 }
456
457 /**
458  * Define the current version of the database schema.
459  *
460  * A Drupal schema definition is an array structure representing one or more
461  * tables and their related keys and indexes. A schema is defined by
462  * hook_schema() which must live in your module's .install file.
463  *
464  * The tables declared by this hook will be automatically created when the
465  * module is installed, and removed when the module is uninstalled. This happens
466  * before hook_install() is invoked, and after hook_uninstall() is invoked,
467  * respectively.
468  *
469  * By declaring the tables used by your module via an implementation of
470  * hook_schema(), these tables will be available on all supported database
471  * engines. You don't have to deal with the different SQL dialects for table
472  * creation and alteration of the supported database engines.
473  *
474  * See the Schema API Handbook at https://www.drupal.org/node/146843 for details
475  * on schema definition structures. Note that foreign key definitions are for
476  * documentation purposes only; foreign keys are not created in the database,
477  * nor are they enforced by Drupal.
478  *
479  * @return array
480  *   A schema definition structure array. For each element of the
481  *   array, the key is a table name and the value is a table structure
482  *   definition.
483  *
484  * @ingroup schemaapi
485  */
486 function hook_schema() {
487   $schema['node'] = [
488     // Example (partial) specification for table "node".
489     'description' => 'The base table for nodes.',
490     'fields' => [
491       'nid' => [
492         'description' => 'The primary identifier for a node.',
493         'type' => 'serial',
494         'unsigned' => TRUE,
495         'not null' => TRUE,
496       ],
497       'vid' => [
498         'description' => 'The current {node_field_revision}.vid version identifier.',
499         'type' => 'int',
500         'unsigned' => TRUE,
501         'not null' => TRUE,
502         'default' => 0,
503       ],
504       'type' => [
505         'description' => 'The type of this node.',
506         'type' => 'varchar',
507         'length' => 32,
508         'not null' => TRUE,
509         'default' => '',
510       ],
511       'title' => [
512         'description' => 'The node title.',
513         'type' => 'varchar',
514         'length' => 255,
515         'not null' => TRUE,
516         'default' => '',
517       ],
518     ],
519     'indexes' => [
520       'node_changed'        => ['changed'],
521       'node_created'        => ['created'],
522     ],
523     'unique keys' => [
524       'nid_vid' => ['nid', 'vid'],
525       'vid'     => ['vid'],
526     ],
527     // For documentation purposes only; foreign keys are not created in the
528     // database.
529     'foreign keys' => [
530       'node_revision' => [
531         'table' => 'node_field_revision',
532         'columns' => ['vid' => 'vid'],
533       ],
534       'node_author' => [
535         'table' => 'users',
536         'columns' => ['uid' => 'uid'],
537       ],
538     ],
539     'primary key' => ['nid'],
540   ];
541   return $schema;
542 }
543
544 /**
545  * @} End of "addtogroup hooks".
546  */