PHP Class lithium\data\source\Database

Inheritance: extends lithium\data\Source
显示文件 Open project: unionofrad/lithium Class Usage Examples

Public Properties

Property Type Description
$connection PD\PDO Holds the current connection.

Protected Properties

Property Type Description
$_cachedNames array Holds cached names.
$_classes array Classes used by Database.
$_columns array The supported column types and their default values
$_constraintTypes
$_operators array List of SQL operators, paired with handling options.
$_quotes array A pair of opening/closing quote characters used for quoting identifiers in SQL queries.
$_strategies array Array of named callable objects representing different strategies for performing specific types of queries.
$_strings array Strings used to render the given statement

Public Methods

Method Description
__construct ( array $config = [] ) : void Constructor.
alias ( $alias, $context )
applyStrategy ( array $options, object $context ) Applying a strategy to a lithium\data\model\Query object
calculation ( string $type, mixed $query, array $options = [] ) : integer | null Executes calculation-related queries, such as those required for count and other aggregates.
cast ( $entity, array $data, array $options = [] )
column ( $field ) : string Generate a database-native column schema string
comment ( string $comment ) : string Adds formatting to SQL comments before they're embedded in queries.
conditions ( string | array $conditions, object $context, array $options = [] ) : string Returns a string of formatted conditions to be inserted into the query statement. If the query conditions are defined as an array, key pairs are converted to SQL strings.
connect ( ) : boolean Connects to the database by creating a PDO intance using the constructed DSN string.
constraints ( string | array $constraints, Query $context, array $options = [] ) : string Returns a string of formatted constraints to be inserted into the query statement.
create ( object $query, array $options = [] ) : boolean Inserts a new record into the database based on a the Query. The record is updated with the id of the insert.
createSchema ( string $source, object $schema ) : boolean Create a database-native schema
delete ( object $query, array $options = [] ) : boolean Deletes a record in the database based on the given Query.
disconnect ( ) : boolean Disconnects the adapter from the database.
dropSchema ( string $source, boolean $soft = true ) : boolean Drops a table.
encoding ( mixed $encoding = null ) : mixed. Getter/Setter for the connection's encoding Abstract. Must be defined by child class.
error ( ) Return the last errors produced by a the execution of a query.
fields ( array $fields, object $context ) : string Returns a string of formatted fields to be inserted into the query statement.
group ( string | array $group, object $context ) : string | null Return formatted clause for GROUP BY with known fields escaped.
having ( string | array $conditions, object $context, array $options = [] ) : string Returns a string of formatted havings to be inserted into the query statement. If the query havings are defined as an array, key pairs are converted to SQL strings.
join ( object $context, object $rel, string $fromAlias = null, string $toAlias = null, mixed $constraints = [] ) Set a query's join according a Relationship.
joins ( array $joins, Query $context ) : string Returns a join statement for given array of query objects
limit ( integer $limit, Query $context ) : string Returns a LIMIT statement from the given limit and the offset of the context object.
methods ( ) : array Determines the set of methods to be used when exporting query values.
name ( string $name ) : string Field name handler to ensure proper escaping.
on ( object $rel, $aliasFrom = null, $aliasTo = null, array $constraints = [] ) : array Build the ON constraints from a Relationship instance
order ( string | array $order, object $context ) : string | null Return formatted clause for ORDER BY with known fields escaped and directions normalized to uppercase. When order direction is missing or unrecognized defaults to ASC.
read ( string | object $query, array $options = [] ) : mixed Reads records from a database using a lithium\data\model\Query object or raw SQL string.
relationship ( string $class, string $type, string $name, array $config = [] ) : array Defines or modifies the default settings of a relationship between two models.
renderCommand ( string $type, string $data = null, string $context = null ) : string Returns a given type statement for the given data, rendered from Database::$_strings.
schema ( Query $query, Result | null $resource = null, object | null $context = null ) : array Builds an array of keyed on the fully-namespaced Model with array of fields as values for the given Query
update ( object $query, array $options = [] ) : boolean Updates a record in the database based on the given Query.
value ( mixed $value, array $schema = [] ) : mixed Converts a given value into the proper type based on a given schema definition.

Protected Methods

Method Description
_aliasing ( string $name, string $alias, array $map = [] ) : string Helper which add an alias basename to a field name if necessary
_buildConstraints ( array $constraints, type $schema = null, type $joiner = ' ', $primary = false ) : string Helper for building columns constraints
_buildMetas ( $type, array $metas, array $names = null, type $joiner = ' ' ) : string Helper for building columns metas
_cast ( string $type, string $value, array $column, array $schema = [] ) : mixed Cast a value according to a column type, used by Database::value().
_conditions ( string | array $conditions, object $context, array $options = [] ) : string Returns a string of formatted conditions to be inserted into the query statement.
_constraint ( string $name, mixed $value, object $schema = null ) : string Build a SQL column constraint
_constraints ( array $constraints ) : array Auto escape string value to a field name value
_createFields ( array $data, array $schema, object $context ) : array Renders the fields part for _create_ queries.
_entityName ( string $entity, array $options = [] ) : string Returns a fully-qualified table name (i.e. with prefix), quoted.
_error ( string $sql ) Throw a QueryException error
_execute ( string $sql ) : Result Execute a given query Abstract. Must be defined by child class.
_fieldName ( string $field ) : string Return the field name from a conditions key.
_fields ( array $fields, object $context ) : array Reformats fields to be alias based.
_fieldsQuote ( string $alias, string $field ) : string Quotes fields, also handles aliased fields.
_fieldsReturn ( string $type, object $context, array $fields, array $schema ) : string | array Renders the fields SQL fragment for queries.
_formatters ( ) : array Provide an associative array of Closures to be used as the 'formatter' key inside of the Database::$_columns specification. Each Closure should return the appropriately quoted or unquoted value and accept one or two parameters: $format, the format to apply to value and $value, the value to be formatted.
_init ( ) Initializer. Initializes properties like Database::$_strategies because closures cannot be created within the class definition.
_insertId ( $query ) : void Get the last insert id from the database.
_introspectType ( mixed $value ) : string Attempts to automatically determine the column type of a value. Used by the value() method of various database adapters to determine how to prepare a value if the schema is not specified.
_meta ( string $type, string $name, mixed $value ) : string Build a SQL column/table meta.
_on ( array $constraints, $aliasFrom, $aliasTo, $mapAlias = [] )
_operator ( string $key, mixed $value, array $schema = [], array $options = [] ) : string Handles conversion of SQL operator keys to SQL statements.
_processConditions ( $key, $value, $context, $schema = null, $glue = 'AND' )
_processOperator ( $key, $value, $fieldMeta, $glue ) : mixed Helper method used by _processConditions.
_queryExport ( object $query ) : array Helper method for Database::read() to export query while handling additional joins when using relationships and limited result sets. Filters conditions on subsequent queries to just the ones applying to the relation.
_schema ( Query $query, array | null $fields = null ) : array Helper method for data\model\Database::shema()
_splitFieldname ( string $field ) : array Return the alias and the field name from an identifier name.
_toBoolean ( mixed $value ) : boolean Casts a value which is being written or compared to a boolean-type database column.
_updateFields ( array $data, array $schema, object $context ) : string Renders the fields part for _update_ queries.

Method Details

__construct() public method

Constructor.
public __construct ( array $config = [] ) : void
$config array array Available configuration options are: - `'database'` _string_: Name of the database to use. Defaults to `null`. - `'host'` _string_: Name/address of server to connect to. Defaults to `'localhost'`. - `'login'` _string_: Username to use when connecting to server. Defaults to `'root'`. - `'password'` _string_: Password to use when connecting to server. Defaults to `''`. - `'persistent'` _boolean_: If true a persistent connection will be attempted, provided the adapter supports it. Defaults to `true`.
return void

_aliasing() protected method

Helper which add an alias basename to a field name if necessary
protected _aliasing ( string $name, string $alias, array $map = [] ) : string
$name string The field name.
$alias string The alias name
$map array An array of `'modelname' => 'aliasname'` mapping
return string

_buildConstraints() protected method

Helper for building columns constraints
See also: lithium\data\soure\Database::createSchema()
protected _buildConstraints ( array $constraints, type $schema = null, type $joiner = ' ', $primary = false ) : string
$constraints array The array of constraints
$schema type The schema of the table
$joiner type The join character
return string The SQL constraints

_buildMetas() protected method

Helper for building columns metas
See also: lithium\data\soure\Database::createSchema()
See also: lithium\data\soure\Database::column()
protected _buildMetas ( $type, array $metas, array $names = null, type $joiner = ' ' ) : string
$metas array The array of column metas.
$names array If `$names` is not `null` only build meta present in `$names`
$joiner type The join character
return string The SQL constraints

_cast() protected method

Cast a value according to a column type, used by Database::value().
See also: lithium\data\source\Database::value()
protected _cast ( string $type, string $value, array $column, array $schema = [] ) : mixed
$type string Name of the column type.
$value string Value to cast.
$column array The column definition.
$schema array Formatted array from `lithium\data\source\Database::schema()`.
return mixed Casted value.

_conditions() protected method

If the query conditions are defined as an array, key pairs are converted to SQL strings. If $key is numeric and $value is a string, $value is treated as a literal SQL fragment and returned.
protected _conditions ( string | array $conditions, object $context, array $options = [] ) : string
$conditions string | array The conditions for this query.
$context object The current `lithium\data\model\Query` instance.
$options array Available options are: - `'prepend'` _boolean|string_: The string to prepend or `false` for no prepending. Defaults to `false`.
return string Returns an SQL conditions clause.

_constraint() protected method

Build a SQL column constraint
protected _constraint ( string $name, mixed $value, object $schema = null ) : string
$name string The name of the meta to build
$value mixed The value used for building the meta
$schema object A `Schema` instance.
return string The SQL meta string

_constraints() protected method

Auto escape string value to a field name value
protected _constraints ( array $constraints ) : array
$constraints array The constraints array
return array The escaped constraints array

_createFields() protected method

Renders the fields part for _create_ queries.
See also: lithium\data\source\Database::_fieldsReturn()
protected _createFields ( array $data, array $schema, object $context ) : array
$data array
$schema array An array defining the schema of the fields used in the criteria.
$context object Generally a `data\model\Query` instance.
return array Array with `fields` and `values` keys which hold SQL fragments of fields an values separated by comma.

_entityName() protected method

Returns a fully-qualified table name (i.e. with prefix), quoted.
protected _entityName ( string $entity, array $options = [] ) : string
$entity string A table name or fully-namespaced model class name.
$options array Available options: - `'quoted'` _boolean_: Indicates whether the name should be quoted.
return string Returns a quoted table name.

_error() protected method

Throw a QueryException error
protected _error ( string $sql )
$sql string The offending SQL string

_execute() abstract protected method

Execute a given query Abstract. Must be defined by child class.
See also: lithium\data\source\Database::renderCommand()
abstract protected _execute ( string $sql ) : Result
$sql string The sql string to execute
return Result Returns a result object if the query was successful.

_fieldName() protected method

Return the field name from a conditions key.
protected _fieldName ( string $field ) : string
$field string Field or identifier name.
return string Returns the field name without the table alias, if applicable.

_fields() protected method

Reformats fields to be alias based.
See also: lithium\data\source\Database::fields()
See also: lithium\data\source\Database::schema()
protected _fields ( array $fields, object $context ) : array
$fields array Array of fields.
$context object Generally a `data\model\Query` instance.
return array Reformatted fields

_fieldsQuote() protected method

Quotes fields, also handles aliased fields.
See also: lithium\data\source\Database::fields()
protected _fieldsQuote ( string $alias, string $field ) : string
$alias string
$field string
return string The quoted field.

_fieldsReturn() protected method

Renders the fields SQL fragment for queries.
See also: lithium\data\source\Database::fields()
protected _fieldsReturn ( string $type, object $context, array $fields, array $schema ) : string | array
$type string Type of query i.e. `'create'` or `'update'`.
$context object Generally a `data\model\Query` instance.
$fields array
$schema array An array defining the schema of the fields used in the criteria.
return string | array

_formatters() protected method

Example formatter function: function($format, $value) { return is_numeric($value) ? (integer) $value : false; }
See also: lithium\data\source\Database::$_columns
See also: lithium\data\source\Database::_init()
protected _formatters ( ) : array
return array of column types to Closure formatter

_init() protected method

Initializer. Initializes properties like Database::$_strategies because closures cannot be created within the class definition.
See also: lithium\data\source\Database::$_columns
See also: lithium\data\source\Database::$_strings
See also: lithium\data\source\Database::$_strategies
protected _init ( )

_insertId() abstract protected method

Abstract. Must be defined by child class.
abstract protected _insertId ( $query ) : void
$query lithium\data\model\Query $context The given query.
return void

_introspectType() protected method

Attempts to automatically determine the column type of a value. Used by the value() method of various database adapters to determine how to prepare a value if the schema is not specified.
protected _introspectType ( mixed $value ) : string
$value mixed The value to be prepared for an SQL query.
return string Returns the name of the column type which `$value` most likely belongs to.

_meta() protected method

Build a SQL column/table meta.
protected _meta ( string $type, string $name, mixed $value ) : string
$type string The type of the meta to build (possible values: `'table'` or `'column'`).
$name string The name of the meta to build.
$value mixed The value used for building the meta.
return string The SQL meta string.

_on() protected method

protected _on ( array $constraints, $aliasFrom, $aliasTo, $mapAlias = [] )
$constraints array

_operator() protected method

Handles conversion of SQL operator keys to SQL statements.
protected _operator ( string $key, mixed $value, array $schema = [], array $options = [] ) : string
$key string Key in a conditions array. Usually a field name.
$value mixed An SQL operator or comparison value.
$schema array An array defining the schema of the field used in the criteria.
$options array
return string Returns an SQL string representing part of a `WHERE` clause of a query.

_processConditions() protected method

protected _processConditions ( $key, $value, $context, $schema = null, $glue = 'AND' )

_processOperator() protected method

Helper method used by _processConditions.
protected _processOperator ( $key, $value, $fieldMeta, $glue ) : mixed
return mixed Returns the operator expression string or `false` if no operator is applicable.

_queryExport() protected method

Helper method for Database::read() to export query while handling additional joins when using relationships and limited result sets. Filters conditions on subsequent queries to just the ones applying to the relation.
See also: lithium\data\source\Database::read()
protected _queryExport ( object $query ) : array
$query object The query object.
return array The exported query returned by reference.

_schema() protected method

Helper method for data\model\Database::shema()
protected _schema ( Query $query, array | null $fields = null ) : array
$query lithium\data\model\Query A Query instance.
$fields array | null Array of formatted fields.
return array

_splitFieldname() protected method

Return the alias and the field name from an identifier name.
protected _splitFieldname ( string $field ) : array
$field string Field name or identifier name.
return array Returns an array with the alias (or `null` if not applicable) as first value and the field name as second value.

_toBoolean() protected method

Casts a value which is being written or compared to a boolean-type database column.
protected _toBoolean ( mixed $value ) : boolean
$value mixed A value of unknown type to be cast to boolean. Numeric values not equal to zero evaluate to `true`, otherwise `false`. String values equal to `'true'`, `'t'` or `'T'` evaluate to `true`, all others to `false`. In all other cases, uses PHP's default casting.
return boolean Returns a boolean representation of `$value`, based on the comparison rules specified above. Database adapters may override this method if boolean type coercion is required and falls outside the rules defined.

_updateFields() protected method

Also handles correct incremented/decremented fields.
See also: lithium\data\Entity::increment()
See also: lithium\data\source\Database::_fieldsReturn()
protected _updateFields ( array $data, array $schema, object $context ) : string
$data array
$schema array An array defining the schema of the fields used in the criteria.
$context object Generally a `data\model\Query` instance.
return string SQL fragment, with fields separated by comma.

alias() public method

public alias ( $alias, $context )

applyStrategy() public method

Applying a strategy to a lithium\data\model\Query object
public applyStrategy ( array $options, object $context )
$options array The option array
$context object A find query object to configure

calculation() public method

Executes calculation-related queries, such as those required for count and other aggregates.
public calculation ( string $type, mixed $query, array $options = [] ) : integer | null
$type string Only accepts `count`.
$query mixed The query to be executed.
$options array Optional arguments for the `read()` query that will be executed to obtain the calculation result.
return integer | null Result of the calculation or `null` if the calculation failed.

cast() public method

public cast ( $entity, array $data, array $options = [] )
$data array
$options array

column() public method

Generate a database-native column schema string
public column ( $field ) : string
return string SQL string

comment() public method

Adds formatting to SQL comments before they're embedded in queries.
public comment ( string $comment ) : string
$comment string
return string

conditions() public method

Conversion rules are as follows: - If $key is numeric and $value is a string, $value is treated as a literal SQL fragment and returned.
public conditions ( string | array $conditions, object $context, array $options = [] ) : string
$conditions string | array The conditions for this query.
$context object The current `lithium\data\model\Query` instance.
$options array Available options are: - `'prepend'` _boolean|string_: The string to prepend or `false` for no prepending. Defaults to `'WHERE'`.
return string Returns the `WHERE` clause of an SQL query.

connect() public method

Will set general options on the connection as provided (persistence, encoding).
See also: lithium\data\source\Database::encoding()
public connect ( ) : boolean
return boolean Returns `true` if a database connection could be established, otherwise `false`.

constraints() public method

If the query constraints are defined as an array, key pairs are converted to SQL strings. If $key is numeric and $value is a string, $value is treated as a literal SQL fragment and returned.
public constraints ( string | array $constraints, Query $context, array $options = [] ) : string
$constraints string | array The constraints for a `ON` clause.
$context lithium\data\model\Query
$options array Available options are: - `'prepend'` _boolean|string_: The string to prepend or `false` for no prepending. Defaults to `'ON'`.
return string Returns the `ON` clause of an SQL query.

create() public method

Inserts a new record into the database based on a the Query. The record is updated with the id of the insert.
See also: lithium\util\String::insert()
public create ( object $query, array $options = [] ) : boolean
$query object An SQL query string, or `lithium\data\model\Query` object instance.
$options array If $query is a string, $options contains an array of bind values to be escaped, quoted, and inserted into `$query` using `String::insert()`.
return boolean Returns `true` if the query succeeded, otherwise `false`.

createSchema() public method

Create a database-native schema
public createSchema ( string $source, object $schema ) : boolean
$source string A table name.
$schema object A `Schema` instance.
return boolean `true` on success, `true` otherwise

delete() public method

Deletes a record in the database based on the given Query.
public delete ( object $query, array $options = [] ) : boolean
$query object An SQL string, or `lithium\data\model\Query` object instance.
$options array If `$query` is a string, `$options` is the array of quoted/escaped parameter values to be inserted into the query.
return boolean Returns `true` on successful query execution (not necessarily if records are deleted), otherwise `false`.

disconnect() public method

Disconnects the adapter from the database.
public disconnect ( ) : boolean
return boolean Returns `true` on success, else `false`.

dropSchema() public method

Drops a table.
public dropSchema ( string $source, boolean $soft = true ) : boolean
$source string The table name to drop.
$soft boolean With "soft dropping", the function will retrun `true` even if the table doesn't exists.
return boolean `true` on success, `false` otherwise

encoding() abstract public method

Getter/Setter for the connection's encoding Abstract. Must be defined by child class.
abstract public encoding ( mixed $encoding = null ) : mixed.
$encoding mixed
return mixed.

error() abstract public method

Abstract. Must be defined by child class.
abstract public error ( )

fields() public method

Returns a string of formatted fields to be inserted into the query statement.
public fields ( array $fields, object $context ) : string
$fields array Array of fields.
$context object Generally a `data\model\Query` instance.
return string A SQL formatted string

group() public method

Return formatted clause for GROUP BY with known fields escaped.
public group ( string | array $group, object $context ) : string | null
$group string | array The clause to be formatted.
$context object
return string | null Formatted clause, `null` if there is nothing to format.

having() public method

Conversion rules are as follows: - If $key is numeric and $value is a string, $value is treated as a literal SQL fragment and returned.
public having ( string | array $conditions, object $context, array $options = [] ) : string
$conditions string | array The havings for this query.
$context object The current `lithium\data\model\Query` instance.
$options array Available options are: - `'prepend'` _boolean|string_: The string to prepend or `false` for no prepending. Defaults to `'HAVING'`.
return string Returns the `HAVING` clause of an SQL query.

join() public method

Set a query's join according a Relationship.
public join ( object $context, object $rel, string $fromAlias = null, string $toAlias = null, mixed $constraints = [] )
$context object A Query instance
$rel object A Relationship instance
$fromAlias string Set a specific alias for the `'from'` `Model`.
$toAlias string Set a specific alias for `'to'` `Model`.
$constraints mixed If `$constraints` is an array, it will be merged to defaults constraints. If `$constraints` is an object, defaults won't be merged.

joins() public method

Returns a join statement for given array of query objects
public joins ( array $joins, Query $context ) : string
$joins array A single or array of `lithium\data\model\Query` objects
$context lithium\data\model\Query
return string

limit() public method

Returns a LIMIT statement from the given limit and the offset of the context object.
public limit ( integer $limit, Query $context ) : string
$limit integer
$context lithium\data\model\Query
return string

methods() public method

Determines the set of methods to be used when exporting query values.
public methods ( ) : array
return array

name() public method

Field name handler to ensure proper escaping.
public name ( string $name ) : string
$name string Field or identifier name.
return string Returns `$name` quoted according to the rules and quote characters of the database adapter subclass.

on() public method

Build the ON constraints from a Relationship instance
public on ( object $rel, $aliasFrom = null, $aliasTo = null, array $constraints = [] ) : array
$rel object A Relationship instance
$constraints array Array of additionnal $constraints.
return array A constraints array.

order() public method

Return formatted clause for ORDER BY with known fields escaped and directions normalized to uppercase. When order direction is missing or unrecognized defaults to ASC.
public order ( string | array $order, object $context ) : string | null
$order string | array The clause to be formatted.
$context object
return string | null Formatted clause, `null` if there is nothing to format.

read() public method

Reads records from a database using a lithium\data\model\Query object or raw SQL string.
public read ( string | object $query, array $options = [] ) : mixed
$query string | object `lithium\data\model\Query` object or SQL string.
$options array If `$query` is a raw string, contains the values that will be escaped and quoted. Other options: - `'return'` _string_: switch return between `'array'`, `'item'`, or `'resource'` _string_: Defaults to `'item'`.
return mixed Determined by `$options['return']`.

relationship() public method

Defines or modifies the default settings of a relationship between two models.
public relationship ( string $class, string $type, string $name, array $config = [] ) : array
$class string the primary model of the relationship
$type string the type of the relationship (hasMany, hasOne, belongsTo)
$name string the name of the relationship
$config array relationship options
return array Returns an array containing the configuration for a model relationship.

renderCommand() public method

Returns a given type statement for the given data, rendered from Database::$_strings.
public renderCommand ( string $type, string $data = null, string $context = null ) : string
$type string One of `'create'`, `'read'`, `'update'`, `'delete'` or `'join'`.
$data string The data to replace in the string.
$context string
return string

schema() public method

Builds an array of keyed on the fully-namespaced Model with array of fields as values for the given Query
public schema ( Query $query, Result | null $resource = null, object | null $context = null ) : array
$query lithium\data\model\Query A Query instance.
$resource Result | null An optional a result resource.
$context object | null
return array

update() public method

Updates a record in the database based on the given Query.
public update ( object $query, array $options = [] ) : boolean
$query object A `lithium\data\model\Query` object
$options array none
return boolean

value() public method

Will bypass any formatters and casting - effectively forcing the engine "to keep its hands off" - when $value is an object with the property scalar (created by casting a scalar value to an object i.e. (object) 'foo'). This feature allows to construct values or queries that are not (yet) supported by the engine.
See also: lithium\data\source\Database::schema()
public value ( mixed $value, array $schema = [] ) : mixed
$value mixed The value to be converted. Arrays will be recursively converted.
$schema array Formatted array from `lithium\data\source\Database::schema()`
return mixed value with converted type

Property Details

$_cachedNames protected_oe property

Holds cached names.
protected array $_cachedNames
return array

$_classes protected_oe property

Classes used by Database.
protected array $_classes
return array

$_columns protected_oe property

The supported column types and their default values
protected array $_columns
return array

$_constraintTypes protected_oe property

protected $_constraintTypes

$_operators protected_oe property

List of SQL operators, paired with handling options.
protected array $_operators
return array

$_quotes protected_oe property

A pair of opening/closing quote characters used for quoting identifiers in SQL queries.
protected array $_quotes
return array

$_strategies protected_oe property

Array of named callable objects representing different strategies for performing specific types of queries.
protected array $_strategies
return array

$_strings protected_oe property

Strings used to render the given statement
See also: lithium\data\source\Database::renderCommand()
protected array $_strings
return array

$connection public_oe property

Holds the current connection.
public PDO,PD $connection
return PD\PDO