Allow the use of different database servers using the same code base.
Drupal provides a database abstraction layer to provide developers with the ability to support multiple database servers easily. The intent of this layer is to preserve the syntax and power of SQL as much as possible, but also allow developers a way to leverage more complex functionality in a unified way. It also provides a structured interface for dynamically constructing queries when appropriate, and enforcing security checks and similar good practices.
The system is built atop PHP's PDO (PHP Data Objects) database API and inherits much of its syntax and semantics.
Most Drupal database SELECT queries are performed by a call to db_query() or db_query_range(). Module authors should also consider using pager_query() for queries that return results that need to be presented on multiple pages, and tablesort_sql() for generating appropriate queries for sortable tables.
For example, one might wish to return a list of the most recent 10 nodes authored by a given user. Instead of directly issuing the SQL query
<?php
SELECT n.nid, n.title, n.created FROM node n WHERE n.uid = $uid LIMIT 0, 10;
?>one would instead call the Drupal functions:
<?php
$result = db_query_range('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid), 0, 10);
foreach($result as $record) {
// Perform operations on $node->title, etc. here.
}
?>Curly braces are used around "node" to provide table prefixing via DatabaseConnection::prefixTables(). The explicit use of a user ID is pulled out into an argument passed to db_query() so that SQL injection attacks from user input can be caught and nullified. The LIMIT syntax varies between database servers, so that is abstracted into db_query_range() arguments. Finally, note the PDO-based ability to foreach() over the result set.
All queries are passed as a prepared statement string. A prepared statement is a "template" of a query that omits literal or variable values in favor of placeholders. The values to place into those placeholders are passed separately, and the database driver handles inserting the values into the query in a secure fashion. That means you should never quote or string-escape a value to be inserted into the query.
There are two formats for placeholders: named and unnamed. Named placeholders are strongly preferred in all cases as they are more flexible and self-documenting. Named placeholders should start with a colon ":" and can be followed by one or more letters, numbers or underscores.
Named placeholders begin with a colon followed by a unique string. Example:
<?php
SELECT nid, title FROM {node} WHERE uid=:uid
?>":uid" is a placeholder that will be replaced with a literal value when the query is executed. A given placeholder label cannot be repeated in a given query, even if the value should be the same. When using named placeholders, the array of arguments to the query must be an associative array where keys are a placeholder label (e.g., :uid) and the value is the corresponding value to use. The array may be in any order.
Unnamed placeholders are simply a question mark. Example:
<?php
SELECT nid, title FROM {node} WHERE uid=?
?>In this case, the array of arguments must be an indexed array of values to use in the exact same order as the placeholders in the query.
Note that placeholders should be a "complete" value. For example, when running a LIKE query the SQL wildcard character, %, should be part of the value, not the query itself. Thus, the following is incorrect:
<?php
SELECT nid, title FROM {node} WHERE title LIKE :title%
?>It should instead read:
<?php
SELECT nid, title FROM {node} WHERE title LIKE :title
?>and the value for :title should include a % as appropriate. Again, note the lack of quotation marks around :title. Because the value is not inserted into the query as one big string but as an explicitly separate value, the database server knows where the query ends and a value begins. That is considerably more secure against SQL injection than trying to remember which values need quotation marks and string escaping and which don't.
INSERT, UPDATE, and DELETE queries need special care in order to behave consistently across all different databases. Therefore, they use a special object-oriented API for defining a query structurally. For example, rather than
<?php
INSERT INTO node (nid, title, body) VALUES (1, 'my title', 'my body')
?>one would instead write:
<?php
$fields = array('nid' => 1, 'title' => 'my title', 'body' => 'my body');
db_insert('my_table')->fields($fields)->execute();
?>This method allows databases that need special data type handling to do so, while also allowing optimizations such as multi-insert queries. UPDATE and DELETE queries have a similar pattern.
Drupal also supports transactions, including a transparent fallback for databases that do not support transactions. To start a new transaction, simply call $txn = db_transaction(): in your own code. The transaction will remain open for as long as the variable $txn remains in scope. When $txn is destroyed, the transaction will be committed. If your transaction is nested inside of another then Drupal will track each transaction and only commit the outer-most transaction when the last transaction object goes out out of scope, that is, all relevant queries completed successfully.
Example:
<?php
function my_transaction_function() {
// The transaction opens here.
$txn = db_transaction();
try {
$id = db_insert('example')
->fields(array(
'field1' => 'mystring',
'field2' => 5,
))
->execute();
my_other_function($id);
return $id;
}
catch (Exception $e) {
// Something went wrong somewhere, so flag the entire transaction to
// roll back instead of getting committed. It doesn't actually roll back
// yet, just gets flagged to do so.
$txn->rollback();
}
// $txn goes out of scope here. If there was a problem, it rolls back
// automatically. If not, it commits automatically.
}
function my_other_function($id) {
// The transaction is still open here.
if ($id % 2 == 0) {
db_update('example')
->condition('id', $id)
->fields(array('field2' => 10))
->execute();
}
}
?>
| Name | Beschreibung |
|---|---|
| Database | Primary front-controller for the database system. |
| DatabaseCondition | Generic class for a series of conditions in a query. |
| DatabaseConnection | Base Database API class. |
| DatabaseConnection_mysql | |
| DatabaseConnection_pgsql | |
| DatabaseConnection_sqlite | Specific SQLite implementation of DatabaseConnection. |
| DatabaseStatementBase | Default implementation of DatabaseStatementInterface. |
| DatabaseStatementPrefetch | An implementation of DatabaseStatementInterface that prefetches all data. |
| DatabaseStatement_sqlite | Specific SQLite implementation of DatabaseConnection. |
| DatabaseTransaction | A wrapper class for creating and managing database transactions. |
| DeleteQuery | General class for an abstracted DELETE operation. |
| DeleteQuery_sqlite | SQLite specific implementation of DeleteQuery. |
| ExplicitTransactionsNotSupportedException | Exception to deny attempts to explicitly manage transactions. |
| InsertQuery | General class for an abstracted INSERT operation. |
| InsertQuery_mysql | |
| InsertQuery_pgsql | |
| InsertQuery_sqlite | SQLite specific implementation of InsertQuery. |
| InvalidMergeQueryException | Exception thrown for merge queries that do not make semantic sense. |
| MergeQuery | General class for an abstracted MERGE operation. |
| MergeQuery_mysql | |
| NoActiveTransactionException | Exception to throw when popTransaction() is called when no transaction is active. |
| Query | Base class for the query builders. |
| SelectQuery | Query builder for SELECT statements. |
| SelectQueryExtender | The base extender class for Select queries. |
| TransactionsNotSupportedException | Exception to mark databases that do not support transations. |
| TruncateQuery | General class for an abstracted TRUNCATE operation. |
| TruncateQuery_sqlite | SQLite specific implementation of TruncateQuery. |
| UpdateQuery | General class for an abstracted UPDATE operation. |
| UpdateQuery_pgsql | |
| UpdateQuery_sqlite | SQLite specific implementation of UpdateQuery. |
| Name | Beschreibung |
|---|---|
| Flag to indicate a query call should return the "last insert id". |
| Name | Beschreibung |
|---|---|
| addConnectionInfo | Add database connection info for a given key/target. |
| getConnection | Gets the connection object for the specified database key and target. |
| getConnectionInfo | Gets information on the specified database connection. |
| getLog | Retrieve the queries logged on for given logging key. |
| ignoreTarget | Instruct the system to temporarily ignore a given key/target. |
| isActiveConnection | Determine if there is an active connection. |
| openConnection | Open a connection to the server specified by the given key and target. |
| parseConnectionInfo | Process the configuration file for database information. |
| setActiveConnection | Set the active connection to the specified key. |
| startLog | Start logging a given logging key on the specified connection. |
| arguments | |
| compile | |
| condition | |
| conditions | |
| count | Return the size of this conditional. This is part of the Countable interface. |
| isNotNull | |
| isNull | |
| mapConditionOperator | Gets any special processing requirements for the condition operator. |
| where | |
| __construct | |
| __toString | |
| commit | Throws an exception to deny direct access to transaction commits. |
| databaseType | Returns the type of the database being accessed. |
| defaultOptions | Return the default query options for any given query. |
| delete | Prepare and return a DELETE query object with the specified ID. |
| driver | Returns the type of database driver. |
| escapeTable | Escapes a table name string. |
| expandArguments | Expand out shorthand placeholders. |
| generateTemporaryTableName | Generate a temporary table name. |
| getLogger | Get the current logging object for this connection. |
| getTarget | Returns the target this connection is associated with. |
| insert | Prepare and return an INSERT query object with the specified ID. |
| inTransaction | Determine if there is an active transaction open. |
| makeSequenceName | Create the appropriate sequence name for a given table and serial field. |
| mapConditionOperator | Gets any special processing requirements for the condition operator. |
| merge | Prepare and return a MERGE query object with the specified ID. |
| popTransaction | Decreases the depth of transaction nesting, committing or rolling back if necessary. |
| prefixTables | Append a database prefix to all tables in a query. |
| prepareQuery | Prepare a query string and return the prepared statement. |
| pushTransaction | Increases the depth of transaction nesting. |
| query | Executes a query string against the database. |
| queryRange | Runs a limited-range query on this database object. |
| queryTemporary | Runs a SELECT query and stores its results in a temporary table. |
| rollBack | Schedule the current transaction for rollback. |
| schema | Returns a DatabaseSchema object for manipulating the schema of this database. |
| select | Prepare and return a SELECT query object with the specified ID. |
| setLogger | Associate a logging object with this connection. |
| setTarget | Tell this connection object what its target value is. |
| startTransaction | Returns a new DatabaseTransaction object on this connection. |
| supportsTransactionalDDL | Determine if this driver supports transactional DDL. |
| supportsTransactions | Determine if this driver supports transactions. |
| truncate | Prepare and return a TRUNCATE query object. |
| update | Prepare and return an UPDATE query object with the specified ID. |
| willRollBack | Determine if this transaction will roll back. |
| __construct | |
| databaseType | |
| distinctField | @todo Remove this as soon as db_rewrite_sql() has been exterminated. |
| driver | |
| mapConditionOperator | |
| queryRange | |
| queryTemporary | |
| __construct | |
| databaseType | |
| distinctField | @todo Remove this as soon as db_rewrite_sql() has been exterminated. |
| driver | |
| mapConditionOperator | |
| query | |
| queryRange | |
| queryTemporary | |
| __construct | |
| databaseType | |
| distinctField | @todo Remove this as soon as db_rewrite_sql() has been exterminated. |
| driver | |
| mapConditionOperator | |
| PDOPrepare | NEVER CALL THIS FUNCTION: YOU MIGHT DEADLOCK YOUR PHP PROCESS. |
| prepare | SQLite-specific implementation of DatabaseConnection::prepare(). |
| prepareQuery | |
| queryRange | |
| queryTemporary | |
| sqlFunctionConcat | SQLite compatibility implementation for the CONCAT() SQL function. |
| sqlFunctionGreatest | SQLite compatibility implementation for the GREATEST() SQL function. |
| sqlFunctionIf | SQLite compatibility implementation for the IF() SQL function. |
| sqlFunctionRand | SQLite compatibility implementation for the RAND() SQL function. |
| sqlFunctionSubstring | SQLite compatibility implementation for the SUBSTRING() SQL function. |
| __construct | |
| execute | |
| fetchAllAssoc | |
| fetchAllKeyed | |
| fetchAssoc | |
| fetchCol | |
| fetchField | |
| getQueryString | |
| __construct | |
| execute | Executes a prepared statement |
| fetchAllAssoc | Returns an entire result set as an associative array keyed by the named field. |
| fetchAllKeyed | Returns the entire result set as a single associative array. |
| fetchAssoc | Fetches the next row and returns it as an associative array. |
| fetchCol | Returns an entire single column of a result set as an indexed array. |
| fetchField | Return a single field out of the current |
| getQueryString | Get the query string of that statement. |
| rowCount | Returns the number of rows affected by the last SQL statement. |
| current | Return the current row formatted according to the current fetch style. |
| execute | Executes a prepared statement. |
| fetch | |
| fetchAll | |
| fetchAllAssoc | |
| fetchAllKeyed | |
| fetchAssoc | |
| fetchCol | |
| fetchField | |
| fetchObject | |
| getQueryString | Return the object's SQL query string. |
| getStatement | Grab a PDOStatement object from a given query and its arguments. |
| key | Returns the rendered local tasks. The default implementation renders them as tabs. Overridden to split the secondary tasks. |
| next | Returns the rendered local tasks. The default implementation renders them as tabs. Overridden to split the secondary tasks. |
| rewind | Returns the rendered local tasks. The default implementation renders them as tabs. Overridden to split the secondary tasks. |
| rowCount | |
| setFetchMode | |
| throwPDOException | Throw a PDO Exception based on the last PDO error. |
| valid | |
| __construct | |
| execute | |
| getStatement | SQLite specific implementation of getStatement(). |
| __construct | |
| __destruct | |
| db_affected_rows | Determine the number of rows changed by the preceding query. |
| db_and | Returns a new DatabaseCondition, set to "AND" all conditions together. |
| db_condition | Returns a new DatabaseCondition, set to the specified conjunction. |
| db_delete | Returns a new DeleteQuery object for the active database. |
| db_distinct_field | Wraps the given table.field entry with a DISTINCT(). The wrapper is added to the SELECT list entry of the given query and the resulting query is returned. This function only applies the wrapper if a DISTINCT doesn't already exist in the query. |
| db_driver | Retrieve the name of the currently active database driver, such as "mysql" or "pgsql". |
| db_escape_table | Restrict a dynamic table, column or constraint name to safe characters. |
| db_fetch_array | |
| db_fetch_object | |
| db_insert | Returns a new InsertQuery object for the active database. |
| db_is_active | Determine if there is an active connection. |
| db_last_insert_id | Returns the last insert id. |
| db_merge | Returns a new MergeQuery object for the active database. |
| db_or | Returns a new DatabaseCondition, set to "OR" all conditions together. |
| db_placeholders | Generate placeholders for an array of query arguments of a single type. |
| db_query | Execute an arbitrary query string against the active database. |
| db_query_range | Execute an arbitrary query string against the active database, restricted to a specified range. |
| db_query_temporary | Execute a query string against the active database and save the result set to a temp table. |
| db_result | |
| db_rewrite_sql | Rewrites node, taxonomy and comment queries. Use it for listing queries. Do not use FROM table1, table2 syntax, use JOIN instead. |
| db_select | Returns a new SelectQuery object for the active database. |
| db_set_active | Sets a new active database. |
| db_transaction | Returns a new transaction object for the active database. |
| db_truncate | Returns a new TruncateQuery object for the active database. |
| db_update | Returns a new UpdateQuery object for the active database. |
| db_xor | Returns a new DatabaseCondition, set to "XOR" all conditions together. |
| arguments | |
| compile | |
| condition | |
| conditions | |
| execute | |
| isNotNull | |
| isNull | |
| where | |
| __construct | |
| __toString | |
| execute | |
| delay | Flag this query as being delay-safe or not. |
| execute | Executes the insert query. |
| fields | Add a set of field->value pairs to be inserted. |
| useDefaults | Specify fields for which the database-defaults should be used. |
| values | Add another set of values to the query to be inserted. |
| __construct | |
| __toString | |
| execute | |
| __toString | |
| execute | |
| __toString | |
| execute | |
| __toString | |
| execute | |
| expression | Specify fields to be updated as an expression. |
| fields | Set the field->value pairs to be merged into the table. |
| key | Set the key field(s) to be used to insert or update into the table. |
| update | Specify fields to update in case of a duplicate record. |
| updateExcept | Specify fields that should not be updated in case of a duplicate record. |
| __construct | |
| __toString | |
| execute | |
| __toString | |
| pager_query | Perform a paged database query. |
| execute | Run the query against the database. |
| __construct | |
| __toString | __toString() magic method. |
| addMetaData | Adds additional metadata to the query. |
| addTag | Adds a tag to a query. |
| getMetaData | Retrieves a given piece of metadata. |
| hasAllTags | Determines if a given query has all specified tags. |
| hasAnyTag | Determines if a given query has any specified tag. |
| hasTag | Determines if a given query has a given tag. |
| arguments | Gets a complete list of all values to insert into the prepared statement. |
| compile | Compiles the saved conditions for later retrieval. |
| condition | Helper function to build most common conditional clauses. |
| conditions | Gets a complete list of all conditions in this conditional clause. |
| isNotNull | Set a condition that the specified field be NOT NULL. |
| isNull | Set a condition that the specified field be NULL. |
| where | Add an arbitrary WHERE clause to the query. |
| extend | Enhance this object by wrapping it in an extender object. |
| addExpression | |
| addField | |
| addJoin | |
| addMetaData | |
| addTag | |
| arguments | |
| compile | |
| condition | |
| conditions | |
| countQuery | |
| distinct | |
| execute | |
| extend | |
| fields | |
| getArguments | |
| getExpressions | |
| getFields | |
| getMetaData | |
| getOrderBy | |
| getTables | |
| groupBy | |
| hasAllTags | |
| hasAnyTag | |
| hasTag | |
| having | |
| havingArguments | |
| havingCompile | |
| havingCondition | |
| havingConditions | |
| havingIsNotNull | |
| havingIsNull | |
| innerJoin | |
| isNotNull | |
| isNull | |
| join | |
| leftJoin | |
| orderBy | |
| range | |
| rightJoin | |
| where | |
| __clone | |
| __construct | |
| __toString | |
| addExpression | |
| addField | |
| addJoin | |
| addMetaData | |
| addTag | |
| arguments | |
| compile | |
| condition | |
| conditions | |
| countQuery | |
| distinct | |
| execute | |
| extend | |
| fields | |
| getArguments | |
| getExpressions | |
| getFields | |
| getMetaData | |
| getOrderBy | |
| getTables | |
| groupBy | |
| hasAllTags | |
| hasAnyTag | |
| hasTag | |
| having | |
| havingArguments | |
| havingCompile | |
| havingCondition | |
| havingConditions | |
| innerJoin | |
| isNotNull | |
| isNull | |
| join | Default Join against another table in the database. |
| leftJoin | |
| orderBy | |
| range | |
| rightJoin | |
| where | |
| __call | Magic override for undefined methods. |
| __clone | |
| __construct | |
| __toString | |
| addExpression | Adds an expression to the list of "fields" to be SELECTed. |
| addField | Adds a field to the list to be SELECTed. |
| addJoin | Join against another table in the database. |
| countQuery | Get the equivalent COUNT query of this query as a new query object. |
| distinct | Sets this query to be DISTINCT. |
| fields | Add multiple fields from the same table to be SELECTed. |
| getArguments | Compiles and returns an associative array of the arguments for this prepared statement. |
| getExpressions | Returns a reference to the expressions array for this query. |
| getFields | Returns a reference to the fields array for this query. |
| getOrderBy | Returns a reference to the order by array for this query. |
| getTables | Returns a reference to the tables array for this query. |
| groupBy | Groups the result set by the specified field. |
| innerJoin | Inner Join against another table in the database. |
| join | Default Join against another table in the database. |
| leftJoin | Left Outer Join against another table in the database. |
| orderBy | Orders the result set by a given field. |
| range | Restricts a query to a given range in the result set. |
| rightJoin | Right Outer Join against another table in the database. |
| __clone | Clone magic method. |
| tablesort_sql | Create an SQL sort clause. |
| compile | |
| execute | |
| __construct | |
| __toString | |
| __toString | |
| arguments | |
| compile | |
| condition | |
| conditions | |
| execute | |
| expression | Specify fields to be updated as an expression. |
| fields | Add a set of field->value pairs to be updated. |
| isNotNull | |
| isNull | |
| where | |
| __construct | |
| __toString | |
| execute | |
| execute | |
| removeFieldsInCondition | Helper function that removes the fields that are already in a condition. |
| update_sql | Perform an SQL query and return success or failure. |
| _db_check_install_needed | Redirect the user to the installation script if Drupal has not been installed yet (i.e., if no $databases array has been defined in the settings file) and we are not already there. Otherwise, do nothing. |
| _db_query_process_args | Backward-compatibility utility. |
| _db_rewrite_sql | Helper function for db_rewrite_sql. |
| Name | Beschreibung |
|---|---|
| DatabaseStatementInterface | A prepared statement. |
| QueryAlterableInterface | Interface for a query that can be manipulated via an alter hook. |
| QueryConditionInterface | Interface for a conditional clause in a query. |
| QueryExtendableInterface | Interface for extendable query objects. |
| SelectQueryInterface | Interface definition for a Select Query object. |
includes/
Kommentare
Kommentar hinzufügen