DboSource
Creates DBO-descendant objects from a given db connection configuration
DataSource
DboSource $_connection protected array$_methodCacheChange protected booleanIndicates whether there was a change on the cached results on the methods of this class This will be used for storing in a more persistent cache
$_queriesCnt protected integer$_queriesLog protected array$_queriesLogMax protected integer$_queriesTime protected integer$_queryCache protected array$_queryDefaults protected array$_result protected array$_sqlBoolOps protected array$_sqlOps protected array$_transactionNesting protected integer$affected public string$alias public string$cacheMethods public booleanWhether or not to cache the results of DboSource::name() and DboSource::conditions() into the memory cache. Set to false to disable the use of the memory cache.
$configKeyName public string$description public string$endQuote public string$fieldParameters public array$fullDebug public boolean$index public arrayarrayCaches result from query parsing operations. Cached results for both DboSource::name() and DboSource::conditions() will be stored here. Method caching uses md5(). If you have problems with collisions, set DboSource::$cacheMethods to false.
$numRows public integer$startQuote public string$tableParameters public array$took public integer$useNestedTransactions public booleanFlag to support nested transactions. If it is set to false, you will be able to use the transaction methods (begin/commit/rollback), but just the global transaction will be executed.
$virtualFieldSeparator public stringGets a list of record IDs for the given conditions. Used for multi-record updates and deletes in databases that do not support aliases in UPDATE/DELETE queries.
Extracts a Model.field identifier and an SQL condition operator from a string, formats and inserts values, and composes them into an SQL snippet.
Model.fields from a preg_replace_callback call Cache a value into the methodCaches. Will respect the value of DboSource::$cacheMethods. Will retrieve a value from the cache if $value is null.
Creates a WHERE clause by parsing given conditions data. If an array or string conditions are provided those conditions will be parsed and quoted. If a boolean is given it will be integer cast as condition. Null will return 1 = 1.
Creates a default set of conditions from the model if $conditions is null/empty. If conditions are supplied then they will be returned. If a model doesn't exist and no conditions were provided either null or false will be returned based on what was input.
Generates and executes an SQL DELETE statement. For databases that do not support aliases in UPDATE queries.
Queries the database with given SQL statement, and obtains some metadata about the result (rows affected, timing, any errors, number of rows in resultset). The query is also logged. If Configure::read('debug') is set, the log is shown all the time, else it is only shown on errors.
Returns an object to represent a database expression in a query. Expression objects are not sanitized or escaped.
Empties the method caches. These caches are used by DboSource::name() and DboSource::conditions()
Returns an object to represent a database identifier in a query. Expression objects are not sanitized or escaped.
Returns number of affected rows in previous database operation. If no previous operation exists, this returns false.
Returns number of rows in previous resultset. If no previous resultset exists, this returns false.
Returns a quoted name of $data for use in an SQL statement. Strips fields out of SQL functions before quoting.
Reset a sequence based on the MAX() value of $column. Useful for resetting sequences after using insertMulti().
Outputs the contents of the queries log. If in a non-CLI environment the sql_log element will be rendered and output. If in a CLI environment, a plain text log is generated.
Deletes all the records in a table and resets the count of the auto-incrementing primary key, where applicable.
Generates and executes an SQL UPDATE statement for given model, fields, and values. For databases that do not support aliases in UPDATE queries.
__construct( array $config null , boolean $autoConnect true )
Constructor
$config optional null $autoConnect optional true MissingConnectionExceptionDataSource::__construct() __destruct( )
Used for storing in cache the results of the in-memory methodCache
DataSource::__destruct() _buildFieldParameters( string $columnString , array $columnData , string $position )
Build the field parameters, in a position
$columnString $columnData $position _constructVirtualFields( Model $Model , string $alias , array $fields )
Converts model virtual fields into sql expressions to be fetched later
Model $Model $alias $fields _dropTable( type $table )
Generate a "drop table" statement for a single table
$table _execute( string $sql , array $params array() , array $prepareOptions array() )
Executes given SQL statement.
$sql $params optional array() $prepareOptions optional array() PDOStatement if query executes with no problem, true as the result of a successful, false on error query returning no rows, such as a CREATE statement, false otherwise
_fetchHasAndBelongsToMany( Model $Model , string $query , array $ids , string $association )
Fetch 'hasAndBelongsToMany' associations.
Model $Model $query $ids $association _fetchHasMany( Model $Model , string $query , array $ids )
Fetch 'hasMany' associations.
Model $Model $query $ids _filterResults( array $resultSet , Model $Model , array $filtered array() )
Passes association results through afterFind filters of the corresponding model.
The primary model is always excluded, because the filtering is later done by Model::_filterResults().
$resultSet Model $Model $filtered optional array() _filterResultsInclusive( array $resultSet , Model $Model , array $toBeFiltered array() )
Passes association results through afterFind filters of the corresponding model.
Similar to DboSource::_filterResults(), but this filters only specified models. The primary model can not be specified, because this call DboSource::_filterResults() internally.
$resultSet Model $Model $toBeFiltered optional array() _getJoins( Model $Model )
Returns an array of SQL JOIN conditions from a model's associations.
Model $Model _matchRecords( Model $Model , mixed $conditions null )
Gets a list of record IDs for the given conditions. Used for multi-record updates and deletes in databases that do not support aliases in UPDATE/DELETE queries.
Model $Model $conditions optional null _mergeAssociation( array $data , array $merge , string $association , string $type , boolean $selfJoin false )
Merge association of merge into data
$data $merge $association $type $selfJoin optional false _mergeConditions( mixed $query , mixed $assoc )
Merges a mixed set of string/array conditions.
$query $assoc _mergeHasMany( array $resultSet , array $assocResultSet , string $association , Model $Model )
Merge the results of 'hasMany' associations.
Note: this function also deals with the formatting of the data.
$resultSet $assocResultSet $association Model $Model _parseKey( string $key , mixed $value , Model $Model null )
Extracts a Model.field identifier and an SQL condition operator from a string, formats and inserts values, and composes them into an SQL snippet.
$key $value Model $Model optional null _prepareUpdateFields( Model $Model , array $fields , boolean $quoteValues true , boolean $alias false )
Quotes and prepares fields and values for an SQL UPDATE statement
Model $Model $fields $quoteValues optional true $alias optional false _quoteFields( string $conditions )
Quotes Model.fields
$conditions _quoteMatchedField( string $match )
Auxiliary function to quote matches Model.fields from a preg_replace_callback call
$match _scrubQueryData( array $data )
Private helper method to remove query metadata in given data array.
$data _writeQueryCache( string $sql , mixed $data , array $params array() )
Writes a new key for the in memory sql query cache
$sql $data $params optional array() alterSchema( mixed $compare , string $table null )
Generate an alter syntax from CakeSchema::compare()
$compare $table optional null begin( )
Begin a transaction
True on success, false on fail (i.e. if the database/model does not support transactions, or a transaction has not started).
DataSource::begin() boolean( mixed $data , boolean $quote false )
Translates between PHP boolean values and Database (faked) boolean values
$data $quote optional false buildAssociationQuery( Model $Model , array $queryData )
Builds an SQL statement.
This is merely a convenient wrapper to DboSource::buildStatement().
Model $Model $queryData buildColumn( array $column )
Generate a database-native column schema string
$column An array structured like the following: array('name' => 'value', 'type' => 'value'[, options]), where options can be 'default', 'length', or 'key'.
buildIndex( array $indexes , string $table null )
Format indexes for create table.
$indexes $table optional null buildJoinStatement( array $join )
Builds and generates a JOIN condition from an array. Handles final clean-up before conversion.
$join buildStatement( array $query , Model $Model )
Builds and generates an SQL statement from an array. Handles final clean-up before conversion.
$query Model $Model buildTableParameters( array $parameters , string $table null )
Format parameters for create table
$parameters $table optional null cacheMethod( string $method , string $key , mixed $value null )
Cache a value into the methodCaches. Will respect the value of DboSource::$cacheMethods. Will retrieve a value from the cache if $value is null.
If caching is disabled and a write is attempted, the $value will be returned. A read will either return the value or null.
$method $key $value optional null calculate( Model $Model , string $func , array $params array() )
Returns an SQL calculation, i.e. COUNT() or MAX()
Model $Model $func $params optional array() close( )
Disconnects database, kills the connection and says the connection is closed.
DataSource::close() commit( )
Commit a transaction
True on success, false on fail (i.e. if the database/model does not support transactions, or a transaction has not started).
DataSource::commit() conditionKeysToString( array $conditions , boolean $quoteValues true , Model $Model null )
Creates a WHERE clause by parsing given conditions array. Used by DboSource::conditions().
$conditions $quoteValues optional true Model $Model optional null conditions( mixed $conditions , boolean $quoteValues true , boolean $where true , Model $Model null )
Creates a WHERE clause by parsing given conditions data. If an array or string conditions are provided those conditions will be parsed and quoted. If a boolean is given it will be integer cast as condition. Null will return 1 = 1.
Results of this method are stored in a memory cache. This improves performance, but because the method uses a hashing algorithm it can have collisions. Setting DboSource::$cacheMethods to false will disable the memory cache.
$conditions $quoteValues optional true $where optional true Model $Model optional null create( Model $Model , array $fields null , array $values null )
The "C" in CRUD
Creates new records in the database.
Model $Model $fields optional null An array of field names to insert. If null, $Model->data will be used to generate field names.
$values optional null An array of values with keys matching the fields. If null, $Model->data will be used to generate values.
DataSource::create() createSchema( CakeSchema $schema , string $tableName null )
Generate a database-native schema for the given Schema object
CakeSchema $schema $tableName optional null Optional. If specified only the table name given will be generated. Otherwise, all tables defined in the schema are generated.
defaultConditions( Model $Model , string|array|boolean $conditions , boolean $useAlias true )
Creates a default set of conditions from the model if $conditions is null/empty. If conditions are supplied then they will be returned. If a model doesn't exist and no conditions were provided either null or false will be returned based on what was input.
Model $Model $conditions Array of conditions, conditions string, null or false. If an array of conditions, or string conditions those conditions will be returned. With other values the model's existence will be checked. If the model doesn't exist a null or false will be returned depending on the input value.
$useAlias optional true delete( Model $Model , mixed $conditions null )
Generates and executes an SQL DELETE statement. For databases that do not support aliases in UPDATE queries.
Model $Model $conditions optional null DataSource::delete() dropSchema( CakeSchema $schema , string $table null )
Generate a "drop table" statement for the given Schema object
CakeSchema $schema $table optional null Optional. If specified only the table name given will be generated. Otherwise, all tables defined in the schema are generated.
execute( string $sql , array $options array() , array $params array() )
Queries the database with given SQL statement, and obtains some metadata about the result (rows affected, timing, any errors, number of rows in resultset). The query is also logged. If Configure::read('debug') is set, the log is shown all the time, else it is only shown on errors.
$sql $options optional array() $params optional array() expression( string $expression )
Returns an object to represent a database expression in a query. Expression objects are not sanitized or escaped.
$expression fetchAll( string $sql , array|boolean $params array() , array $options array() )
Returns an array of all result rows for a given SQL query.
Returns false if no rows matched.
cache - Returns the cached version of the query, if exists and stores the result in cache. This is a non-persistent cache, and only lasts for a single request. This option defaults to true. If you are directly calling this method, you can disable caching by setting $options to false
$sql $params optional array() Either parameters to be bound as values for the SQL statement, or a boolean to control query caching.
$options optional array() fetchAssociated( Model $Model , string $query , array $ids )
Fetch 'hasMany' associations.
This is just a proxy to maintain BC.
Model $Model $query $ids fetchResult( )
Fetches the next row from the current result set
fetchRow( string $sql null )
Returns a row from current resultset as an array
$sql optional null fetchVirtualField( array $result )
Modifies $result array to place virtual fields in model entry where they belongs to
$result field( string $name , string $sql )
Returns a single field of the first of query results for a given SQL query, or false if empty.
$name $sql fields( Model $Model , string $alias null , mixed $fields array() , boolean $quote true )
Generates the fields list of an SQL query.
Model $Model $alias optional null $fields optional array() $quote optional true flushMethodCache( )
Empties the method caches. These caches are used by DboSource::name() and DboSource::conditions()
fullTableName( Model|string $model , boolean $quote true , boolean $schema true )
Gets full table name including prefix
Model|string $model $quote optional true $schema optional true generateAssociationQuery( Model $Model , Model|null $LinkModel , string $type , string $association , array $assocData , array $queryData , boolean $external )
Generates a query or part of a query from a single model or two associated models.
Builds a string containing an SQL statement template.
Model $Model Model|null $LinkModel $type $association $assocData $queryData $external String representing a query. True, when $external is false and association $type is 'hasOne' or 'belongsTo'.
getConstraint( string $type , Model $Model , Model $LinkModel , string $association , array $assocData , string $association2 null )
Returns a conditions array for the constraint between two models.
$type Model $Model Model $LinkModel $association $assocData $association2 optional null getLog( boolean $sorted false , boolean $clear true )
Get the query log as an array.
$sorted optional false $clear optional true getQueryCache( string $sql , array $params array() )
Returns the result for a sql query if it is already cached
$sql $params optional array() getVersion( )
Gets the version string of the database server
group( string|array $fields , Model $Model null )
Create a GROUP BY SQL clause.
$fields Model $Model optional null hasAny( Model $Model , string $sql )
Checks if the specified table contains any record matching specified SQL
Model $Model $sql hasResult( )
Checks if the result is valid
identifier( string $identifier )
Returns an object to represent a database identifier in a query. Expression objects are not sanitized or escaped.
$identifier index( string $model )
Returns an array of the indexes in given datasource name.
$model insertMulti( string $table , array $fields , array $values )
Inserts multiple values into a table
$table $fields $values The array of values to insert. The values should be an array of rows. Each row should have values keyed by the column name. Each row must have the values in the same order as $fields.
introspectType( string $value )
Guesses the data type of an array
$value isConnected( )
Checks if the source is connected to the database.
lastAffected( mixed $source null )
Returns number of affected rows in previous database operation. If no previous operation exists, this returns false.
$source optional null DataSource::lastAffected() lastError( PDOStatement $query null )
Returns a formatted error message from previous database operation.
$query optional null lastInsertId( mixed $source null )
Returns the ID generated from the previous INSERT operation.
$source optional null DataSource::lastInsertId() lastNumRows( mixed $source null )
Returns number of rows in previous resultset. If no previous resultset exists, this returns false.
$source optional null DataSource::lastNumRows() length( string $real )
Gets the length of a database-native column description, or null if no length
$real limit( integer $limit , integer $offset null )
Returns a limit statement in the correct format for the particular database.
$limit $offset optional null logQuery( string $sql , array $params array() )
Log given SQL query.
$sql $params optional array() name( mixed $data )
Returns a quoted name of $data for use in an SQL statement. Strips fields out of SQL functions before quoting.
Results of this method are stored in a memory cache. This improves performance, but because the method uses a hashing algorithm it can have collisions. Setting DboSource::$cacheMethods to false will disable the memory cache.
$data Either a string with a column to quote. An array of columns to quote or an object from DboSource::expression() or DboSource::identifier()
nestedTransactionSupported( )
Check if the server support nested transactions
order( array|string $keys , string $direction 'ASC' , Model $Model null )
Returns an ORDER BY clause as a string.
$keys $direction optional 'ASC' Model $Model optional null prepareFields( Model $Model , array $queryData )
Prepares fields required by an SQL statement.
When no fields are set, all the $Model fields are returned.
Model $Model $queryData query( )
DataSource Query abstraction
queryAssociation( Model $Model , Model $LinkModel , string $type , string $association , array $assocData , array $queryData , boolean $external , array $resultSet , integer $recursive , array $stack )
Queries associations.
Used to fetch results on recursive models.
'hasMany' associations with no limit set: Fetch, filter and merge is done recursively for every level.
'hasAndBelongsToMany' associations: Fetch and filter is done unaffected by the (recursive) level set.
Model $Model Model $LinkModel $type $association $assocData $queryData $external $resultSet $recursive $stack CakeExceptionrawQuery( string $sql , array $params array() )
Executes given SQL statement.
$sql $params optional array() read( Model $Model , array $queryData array() , integer $recursive null )
The "R" in CRUD
Reads record(s) from the database.
Model $Model $queryData optional array() $recursive optional null DataSource::read() readTableParameters( string $name )
Read additional table parameters
$name reconnect( array $config array() )
Reconnects to database server with optional new settings
$config optional array() renderJoinStatement( array $data )
Renders a final SQL JOIN statement
$data renderStatement( string $type , array $data )
Renders a final SQL statement by putting together the component parts in the correct order
$type $data resetSequence( string $table , string $column )
Reset a sequence based on the MAX() value of $column. Useful for resetting sequences after using insertMulti().
This method should be implemented by datasources that require sequences to be used.
$table $column resolveKey( Model $Model , string $key , string $assoc null )
Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name)
Model $Model $key $assoc optional null DataSource::resolveKey() rollback( )
Rollback a transaction
True on success, false on fail (i.e. if the database/model does not support transactions, or a transaction has not started).
DataSource::rollback() showLog( boolean $sorted false )
Outputs the contents of the queries log. If in a non-CLI environment the sql_log element will be rendered and output. If in a CLI environment, a plain text log is generated.
$sorted optional false truncate( Model|string $table )
Deletes all the records in a table and resets the count of the auto-incrementing primary key, where applicable.
Model|string $table update( Model $Model , array $fields array() , array $values null , mixed $conditions null )
Generates and executes an SQL UPDATE statement for given model, fields, and values. For databases that do not support aliases in UPDATE queries.
Model $Model $fields optional array() $values optional null $conditions optional null DataSource::update() value( string $data , string $column null , boolean $null true )
Returns a quoted and escaped string of $data for use in an SQL statement.
$data $column optional null $null optional true _cacheDescription( string $object , mixed $data null )
Cache the DataSource description
$object $data optional null column( string $real )
Converts column types to basic types
$real describe( Model|string $model )
Returns a Model description (metadata) or null if none found.
Model|string $model enabled( )
Check whether the conditions for the Datasource being available are satisfied. Often used from connect() to check for support before establishing a connection.
getSchemaName( )
Returns the schema name. Override this in subclasses.
insertQueryData( string $query , array $data , string $association , Model $Model , array $stack )
Replaces {$__cakeID__$} and {$__cakeForeignKey__$} placeholders in query data.
$query $data $association Model $Model $stack listSources( mixed $data null )
Caches/returns cached results for child instances
$data optional null setConfig( array $config array() )
Sets the configuration for the DataSource. Merges the $config information with the _baseConfig and the existing $config property.
$config optional array() _mergeVars( array $properties , string $class , boolean $normalize true )
Merges this objects $property with the property in $class' definition. This classes value for the property will be merged on top of $class'
This provides some of the DRY magic CakePHP provides. If you want to shut it off, redefine this method as an empty function.
$properties $class $normalize optional true _set( array $properties array() )
Allows setting of multiple properties of the object in a single line of code. Will only set properties that are part of a class declaration.
$properties optional array() _stop( integer|string $status 0 )
Stop execution of the current script. Wraps exit() making testing easier.
$status optional 0 dispatchMethod( string $method , array $params array() )
Calls a method on this object with the given parameters. Provides an OO wrapper for call_user_func_array
$method $params optional array() log( string $msg , integer $type LOG_ERR , null|string|array $scope null )
Convenience method to write a message to CakeLog. See CakeLog::write() for more information on writing to logs.
$msg $type optional LOG_ERR $scope optional null The scope(s) a log message is being created in. See CakeLog::config() for more information on logging scopes.
requestAction( string|array $url , array $extra array() )
Calls a controller's method from any location. Can be used to connect controllers together or tie plugins into a main application. requestAction can be used to return rendered views or fetch the return value from controller actions.
Under the hood this method uses Router::reverse() to convert the $url parameter into a string URL. You should use URL formats that are compatible with Router::reverse()
POST and GET data can be simulated in requestAction. Use $extra['url'] for GET data. The $extra['data'] parameter allows POST data simulation.
$url String or array-based URL. Unlike other URL arrays in CakePHP, this URL will not automatically handle passed and named arguments in the $url parameter.
$extra optional array() if array includes the key "return" it sets the AutoRender to true. Can also be used to submit GET/POST data, and named/passed arguments.
Boolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.
toString( )
Object-to-string conversion. Each class can override this method as necessary.
protected boolean
Indicates whether there was a change on the cached results on the methods of this class This will be used for storing in a more persistent cache
false
protected integer
Maximum number of items in query log
This is to prevent query log taking over too much memory.
200
protected array
Default fields that are used by the DBO
array(
'conditions' => array(),
'fields' => null,
'table' => null,
'alias' => null,
'order' => null,
'limit' => null,
'joins' => array(),
'group' => null,
'offset' => null
) protected array
The set of valid SQL boolean operations usable in a WHERE statement
array('and', 'or', 'not', 'and not', 'or not', 'xor', '||', '&&') protected array
The set of valid SQL operations usable in a WHERE statement
array('like', 'ilike', 'rlike', 'or', 'not', 'in', 'between', 'regexp', 'similar to') public string
String to hold how many rows were affected by the last SQL operation.
null
public boolean
Whether or not to cache the results of DboSource::name() and DboSource::conditions() into the memory cache. Set to false to disable the use of the memory cache.
true
public string
Description string for this Database Data Source.
"Database Data Source"
public string
The ending character that this DataSource uses for quoted identifiers.
null
public array
List of engine specific additional field parameters used on table creating
array()
public array
index definition, standard cake, primary, index, unique
array('PRI' => 'primary', 'MUL' => 'index', 'UNI' => 'unique') public static array
Caches result from query parsing operations. Cached results for both DboSource::name() and DboSource::conditions() will be stored here. Method caching uses md5(). If you have problems with collisions, set DboSource::$cacheMethods to false.
array()
public string
The starting character that this DataSource uses for quoted identifiers.
null
public array
List of table engine specific parameters used on table creating
array()
public boolean
Flag to support nested transactions. If it is set to false, you will be able to use the transaction methods (begin/commit/rollback), but just the global transaction will be executed.
false
© 2005–2016 The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
http://api.cakephp.org/2.8/class-DboSource.html