Class DboSource
DboSource
Creates DBO-descendant objects from a given db connection configuration
- CakeObject
- DataSource
- DboSource
Direct Subclasses
Copyright: Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
License: MIT License
Location: Cake/Model/Datasource/DboSource.php
Properties summary
-
$_connection
protectedA reference to the physical connection of this DataSourcearray
-
$_methodCacheChange
protectedboolean
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
-
$_queriesCnt
protectedQueries count.integer
-
$_queriesLog
protectedLog of queries executed by this DataSourcearray
-
$_queriesLogMax
protectedMaximum number of items in query loginteger
-
$_queriesTime
protectedTotal duration of all queries.integer
-
$_queryCache
protectedCaches serialized results of executed queriesarray
-
$_queryDefaults
protectedDefault fields that are used by the DBOarray
-
$_result
protectedResultarray
-
$_sqlBoolOps
protectedThe set of valid SQL boolean operations usable in a WHERE statementarray
-
$_sqlOps
protectedThe set of valid SQL operations usable in a WHERE statementarray
-
$_transactionNesting
protectedIndicates the level of nested transactionsinteger
-
$affected
publicString to hold how many rows were affected by the last SQL operation.string
-
$alias
publicDatabase keyword used to assign aliases to identifiers.string
-
$cacheMethods
publicboolean
Whether or not to cache the results of DboSource::name() and DboSource::fields() into the memory cache. Set to false to disable the use of the memory cache.
-
$configKeyName
publicThe DataSource configuration key namestring
-
$description
publicDescription string for this Database Data Source.string
-
$endQuote
publicThe ending character that this DataSource uses for quoted identifiers.string
-
$fieldParameters
publicList of engine specific additional field parameters used on table creatingarray
-
$fullDebug
publicPrint full query debug info?boolean
-
$index
publicindex definition, standard cake, primary, index, uniquearray
-
array
Caches result from query parsing operations. Cached results for both DboSource::name() and DboSource::fields() will be stored here.
-
$numRows
publicNumber of rows in current resultsetinteger
-
$startQuote
publicThe starting character that this DataSource uses for quoted identifiers.string
-
$tableParameters
publicList of table engine specific parameters used on table creatingarray
-
$took
publicTime the last query tookinteger
-
$useNestedTransactions
publicboolean
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.
-
$virtualFieldSeparator
publicSeparator string for virtualField compositionstring
Inherited Properties
Method Summary
- __construct() publicConstructor
- __destruct() publicUsed for storing in cache the results of the in-memory methodCache
- _beginNested() protectedBegin a nested transaction
- _buildFieldParameters() protectedBuild the field parameters, in a position
- _commitNested() protectedCommit a nested transaction
- _constructVirtualFields() protectedConverts model virtual fields into sql expressions to be fetched later
- _dropTable() protectedGenerate a "drop table" statement for a single table
- _execute() protectedExecutes given SQL statement.
- _fetchHasAndBelongsToMany() protectedFetch 'hasAndBelongsToMany' associations.
- _fetchHasMany() protectedFetch 'hasMany' associations.
- _filterResults() protectedPasses association results through afterFind filters of the corresponding model.
- _filterResultsInclusive() protectedPasses association results through afterFind filters of the corresponding model.
- _getJoins() protectedReturns an array of SQL JOIN conditions from a model's associations.
- _matchRecords() protected
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.
- _mergeAssociation() protectedMerge association of merge into data
- _mergeConditions() protectedMerges a mixed set of string/array conditions.
- _mergeHasMany() protectedMerge the results of 'hasMany' associations.
- _parseKey() protected
Extracts a Model.field identifier and an SQL condition operator from a string, formats and inserts values, and composes them into an SQL snippet.
- _prepareUpdateFields() protectedQuotes and prepares fields and values for an SQL UPDATE statement
- _quoteFields() protectedQuotes Model.fields
- _quoteMatchedField() protectedAuxiliary function to quote matches
Model.fields
from a preg_replace_callback call - _rollbackNested() protectedRollback a nested transaction
- _scrubQueryData() protectedPrivate helper method to remove query metadata in given data array.
- _writeQueryCache() protectedWrites a new key for the in memory sql query cache
- alterSchema() publicGenerate an alter syntax from CakeSchema::compare()
- begin() publicBegin a transaction
- boolean() publicTranslates between PHP boolean values and Database (faked) boolean values
- buildAssociationQuery() publicBuilds an SQL statement.
- buildColumn() publicGenerate a database-native column schema string
- buildIndex() publicFormat indexes for create table.
- buildJoinStatement() publicBuilds and generates a JOIN condition from an array. Handles final clean-up before conversion.
- buildStatement() publicBuilds and generates an SQL statement from an array. Handles final clean-up before conversion.
- buildTableParameters() publicFormat parameters for create table
- cacheMethod() public
Cache a value into the methodCaches. Will respect the value of DboSource::$cacheMethods. Will retrieve a value from the cache if $value is null.
- cacheMethodFilter() public
Filters to apply to the results of
name
andfields
. When the filter for a given method does not returntrue
then the result is not added to the memory cache. - cacheMethodHasher() publicHashes a given value.
- calculate() publicReturns an SQL calculation, i.e. COUNT() or MAX()
- close() publicDisconnects database, kills the connection and says the connection is closed.
- commit() publicCommit a transaction
- conditionKeysToString() publicCreates a WHERE clause by parsing given conditions array. Used by DboSource::conditions().
- conditions() public
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.
- create() publicThe "C" in CRUD
- createSchema() publicGenerate a database-native schema for the given Schema object
- defaultConditions() public
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.
- delete() public
Generates and executes an SQL DELETE statement. For databases that do not support aliases in UPDATE queries.
- disconnect() publicDisconnects from database.
- dropSchema() publicGenerate a "drop table" statement for the given Schema object
- execute() public
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.
- expression() public
Returns an object to represent a database expression in a query. Expression objects are not sanitized or escaped.
- fetchAll() publicReturns an array of all result rows for a given SQL query.
- fetchAssociated() publicFetch 'hasMany' associations.
- fetchResult() publicFetches the next row from the current result set
- fetchRow() publicReturns a row from current resultset as an array
- fetchVirtualField() publicModifies $result array to place virtual fields in model entry where they belongs to
- field() publicReturns a single field of the first of query results for a given SQL query, or false if empty.
- fields() publicGenerates the fields list of an SQL query.
- flushMethodCache() public
Empties the method caches. These caches are used by DboSource::name() and DboSource::conditions()
- flushQueryCache() publicEmpties the query caches.
- fullTableName() publicGets full table name including prefix
- generateAssociationQuery() publicGenerates a query or part of a query from a single model or two associated models.
- getConnection() publicGet the underlying connection object.
- getConstraint() publicReturns a conditions array for the constraint between two models.
- getLockingHint() publicReturns a locking hint for the given mode.
- getLog() publicGet the query log as an array.
- getQueryCache() publicReturns the result for a sql query if it is already cached
- getVersion() publicGets the version string of the database server
- group() publicCreate a GROUP BY SQL clause.
- hasAny() publicChecks if the specified table contains any record matching specified SQL
- hasResult() publicChecks if the result is valid
- having() publicCreate a HAVING SQL clause.
- identifier() public
Returns an object to represent a database identifier in a query. Expression objects are not sanitized or escaped.
- index() publicReturns an array of the indexes in given datasource name.
- insertMulti() publicInserts multiple values into a table
- introspectType() publicGuesses the data type of an array
- isConnected() publicChecks if the source is connected to the database.
- lastAffected() public
Returns number of affected rows in previous database operation. If no previous operation exists, this returns false.
- lastError() publicReturns a formatted error message from previous database operation.
- lastInsertId() publicReturns the ID generated from the previous INSERT operation.
- lastNumRows() public
Returns number of rows in previous resultset. If no previous resultset exists, this returns false.
- length() publicGets the length of a database-native column description, or null if no length
- limit() publicReturns a limit statement in the correct format for the particular database.
- logQuery() publicLog given SQL query.
- name() public
Returns a quoted name of $data for use in an SQL statement. Strips fields out of SQL functions before quoting.
- nestedTransactionSupported() publicCheck if the server support nested transactions
- order() publicReturns an ORDER BY clause as a string.
- prepareFields() publicPrepares fields required by an SQL statement.
- query() publicDataSource Query abstraction
- queryAssociation() publicQueries associations.
- rawQuery() publicExecutes given SQL statement.
- read() publicThe "R" in CRUD
- readTableParameters() publicRead additional table parameters
- reconnect() publicReconnects to database server with optional new settings
- renderJoinStatement() publicRenders a final SQL JOIN statement
- renderStatement() publicRenders a final SQL statement by putting together the component parts in the correct order
- resetSequence() public
Reset a sequence based on the MAX() value of $column. Useful for resetting sequences after using insertMulti().
- resolveKey() publicReturns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name)
- rollback() publicRollback a transaction
- showLog() public
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.
- truncate() public
Deletes all the records in a table and resets the count of the auto-incrementing primary key, where applicable.
- update() public
Generates and executes an SQL UPDATE statement for given model, fields, and values. For databases that do not support aliases in UPDATE queries.
- value() publicReturns a quoted and escaped string of $data for use in an SQL statement.
Method Detail
__construct()source public
__construct( array $config null , boolean $autoConnect true )
Constructor
Parameters
- array
$config
optional null - Array of configuration information for the Datasource.
- boolean
$autoConnect
optional true - Whether or not the datasource should automatically connect.
Throws
MissingConnectionException
when a connection cannot be made.
Overrides
DataSource::__construct()
__destruct()source public
__destruct( )
Used for storing in cache the results of the in-memory methodCache
Overrides
DataSource::__destruct()
_buildFieldParameters()source protected
_buildFieldParameters( string $columnString , array $columnData , string $position )
Build the field parameters, in a position
Parameters
- string
$columnString
- The partially built column string
- array
$columnData
- The array of column data.
- string
$position
- The position type to use. 'beforeDefault' or 'afterDefault' are common
Returns
stringa built column with the field parameters added.
_constructVirtualFields()source protected
_constructVirtualFields( Model $Model , string $alias , array $fields )
Converts model virtual fields into sql expressions to be fetched later
Parameters
-
Model
$Model
- The model to get virtual fields for.
- string
$alias
- Alias table name
- array
$fields
- virtual fields to be used on query
Returns
array_dropTable()source protected
_dropTable( type $table )
Generate a "drop table" statement for a single table
Parameters
- type
$table
- Name of the table to drop
Returns
stringDrop table SQL statement
_execute()source protected
_execute( string $sql , array $params array() , array $prepareOptions array() )
Executes given SQL statement.
Parameters
- string
$sql
- SQL statement
- array
$params
optional array() - list of params to be bound to query
- array
$prepareOptions
optional array() - Options to be used in the prepare statement
Returns
mixedPDOStatement 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
Throws
PDOException_fetchHasAndBelongsToMany()source protected
_fetchHasAndBelongsToMany( Model $Model , string $query , array $ids , string $association )
Fetch 'hasAndBelongsToMany' associations.
Parameters
-
Model
$Model
- Primary model object.
- string
$query
- Association query.
- array
$ids
- Array of IDs of associated records.
- string
$association
- Association name.
Returns
arrayAssociation results.
_fetchHasMany()source protected
_fetchHasMany( Model $Model , string $query , array $ids )
Fetch 'hasMany' associations.
Parameters
-
Model
$Model
- Primary model object.
- string
$query
- Association query template.
- array
$ids
- Array of IDs of associated records.
Returns
arrayAssociation results.
_filterResults()source protected
_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().
Parameters
- array
$resultSet
- $resultSet Reference of resultset to be filtered.
-
Model
$Model
- Instance of model to operate against.
- array
$filtered
optional array() - List of classes already filtered, to be skipped.
Returns
arrayArray of results that have been filtered through $Model->afterFind.
_filterResultsInclusive()source protected
_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.
Parameters
- array
$resultSet
- $resultSet Reference of resultset to be filtered.
-
Model
$Model
- Instance of model to operate against.
- array
$toBeFiltered
optional array() - List of classes to be filtered.
Returns
arrayArray of results that have been filtered through $Model->afterFind.
_getJoins()source protected
_getJoins( Model $Model )
Returns an array of SQL JOIN conditions from a model's associations.
Parameters
-
Model
$Model
- The model to get joins for.2
Returns
array_matchRecords()source protected
_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.
Parameters
-
Model
$Model
- The model to find matching records for.
- mixed
$conditions
optional null - The conditions to match against.
Returns
arrayList of record IDs
_mergeAssociation()source protected
_mergeAssociation( array $data , array $merge , string $association , string $type , boolean $selfJoin false )
Merge association of merge into data
Parameters
- array
$data
- $data The data to merge.
- array
$merge
- $merge The data to merge.
- string
$association
- The association name to merge.
- string
$type
- The type of association
- boolean
$selfJoin
optional false - Whether or not this is a self join.
_mergeConditions()source protected
_mergeConditions( mixed $query , mixed $assoc )
Merges a mixed set of string/array conditions.
Parameters
- mixed
$query
- The query to merge conditions for.
- mixed
$assoc
- The association names.
Returns
array_mergeHasMany()source protected
_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.
Parameters
- array
$resultSet
- $resultSet Data to merge into.
- array
$assocResultSet
- Data to merge.
- string
$association
- Name of Model being merged.
-
Model
$Model
- Model being merged onto.
_parseKey()source protected
_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.
Parameters
- string
$key
- An SQL key snippet containing a field and optional SQL operator
- mixed
$value
- The value(s) to be inserted in the string
-
Model
$Model
optional null - Model object initiating the query
Returns
string_prepareUpdateFields()source protected
_prepareUpdateFields( Model $Model , array $fields , boolean $quoteValues true , boolean $alias false )
Quotes and prepares fields and values for an SQL UPDATE statement
Parameters
-
Model
$Model
- The model to prepare fields for.
- array
$fields
- The fields to update.
- boolean
$quoteValues
optional true - If values should be quoted, or treated as SQL snippets
- boolean
$alias
optional false - Include the model alias in the field name
Returns
arrayFields and values, quoted and prepared
_quoteFields()source protected
_quoteFields( string $conditions )
Quotes Model.fields
Parameters
- string
$conditions
- The conditions to quote.
Returns
stringor false if no match
_quoteMatchedField()source protected
_quoteMatchedField( string $match )
Auxiliary function to quote matches Model.fields
from a preg_replace_callback call
Parameters
- string
$match
- matched string
Returns
stringquoted string
_scrubQueryData()source protected
_scrubQueryData( array $data )
Private helper method to remove query metadata in given data array.
Parameters
- array
$data
- The data to scrub.
Returns
array_writeQueryCache()source protected
_writeQueryCache( string $sql , mixed $data , array $params array() )
Writes a new key for the in memory sql query cache
Parameters
- string
$sql
- SQL query
- mixed
$data
- result of $sql query
- array
$params
optional array() - query params bound as values
alterSchema()source public
alterSchema( mixed $compare , string $table null )
Generate an alter syntax from CakeSchema::compare()
Parameters
- mixed
$compare
- The comparison data.
- string
$table
optional null - The table name.
Returns
booleanbegin()source public
begin( )
Begin a transaction
Returns
booleanTrue on success, false on fail (i.e. if the database/model does not support transactions, or a transaction has not started).
Overrides
DataSource::begin()
boolean()source public
boolean( mixed $data , boolean $quote false )
Translates between PHP boolean values and Database (faked) boolean values
Parameters
- mixed
$data
- Value to be translated
- boolean
$quote
optional false - Whether or not the field should be cast to a string.
Returns
string|booleanConverted boolean value
buildAssociationQuery()source public
buildAssociationQuery( Model $Model , array $queryData )
Builds an SQL statement.
This is merely a convenient wrapper to DboSource::buildStatement().
Parameters
-
Model
$Model
- The model to build an association query for.
- array
$queryData
- An array of queryData information containing keys similar to Model::find().
Returns
stringString containing an SQL statement.
See
DboSource::buildStatement()buildColumn()source public
buildColumn( array $column )
Generate a database-native column schema string
Parameters
- array
$column
An array structured like the following: array('name' => 'value', 'type' => 'value'[, options]), where options can be 'default', 'length', or 'key'.
Returns
stringbuildIndex()source public
buildIndex( array $indexes , string $table null )
Format indexes for create table.
Parameters
- array
$indexes
- The indexes to build
- string
$table
optional null - The table name.
Returns
arraybuildJoinStatement()source public
buildJoinStatement( array $join )
Builds and generates a JOIN condition from an array. Handles final clean-up before conversion.
Parameters
- array
$join
- An array defining a JOIN condition in a query.
Returns
stringAn SQL JOIN condition to be used in a query.
See
DboSource::renderJoinStatement()DboSource::buildStatement()
buildStatement()source public
buildStatement( array $query , Model $Model )
Builds and generates an SQL statement from an array. Handles final clean-up before conversion.
Parameters
- array
$query
- An array defining an SQL query.
-
Model
$Model
- The model object which initiated the query.
Returns
stringAn executable SQL statement.
See
DboSource::renderStatement()buildTableParameters()source public
buildTableParameters( array $parameters , string $table null )
Format parameters for create table
Parameters
- array
$parameters
- The parameters to create SQL for.
- string
$table
optional null - The table name.
Returns
arraycacheMethod()source public
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.
Parameters
- string
$method
- Name of the method being cached.
- string
$key
- The key name for the cache operation.
- mixed
$value
optional null - The value to cache into memory.
Returns
mixedEither null on failure, or the value if its set.
cacheMethodFilter()source public
cacheMethodFilter( string $method , string $key , mixed $value )
Filters to apply to the results of name
and fields
. When the filter for a given method does not return true
then the result is not added to the memory cache.
Some examples:
// For method fields, do not cache values that contain floats if ($method === 'fields') { $hasFloat = preg_grep('/(\d+)?\.\d+/', $value); return count($hasFloat) === 0; } return true;
// For method name, do not cache values that have the name created if ($method === 'name') { return preg_match('/^`created`$/', $value) !== 1; } return true;
// For method name, do not cache values that have the key 472551d38e1f8bbc78d7dfd28106166f if ($key === '472551d38e1f8bbc78d7dfd28106166f') { return false; } return true;
Parameters
- string
$method
- Name of the method being cached.
- string
$key
- The key name for the cache operation.
- mixed
$value
- The value to cache into memory.
Returns
booleanWhether or not to cache
cacheMethodHasher()source public
cacheMethodHasher( string $value )
Hashes a given value.
Method caching uses md5
(by default) to construct cache keys. If you have problems with collisions, try a different hashing algorithm or set DboSource::$cacheMethods to false.
Parameters
- string
$value
- Value to hash
Returns
stringHashed value
See
http://php.net/manual/en/function.hash-algos.phphttp://softwareengineering.stackexchange.com/questions/49550/which-hashing-algorithm-is-best-for-uniqueness-and-speed
calculate()source public
calculate( Model $Model , string $func , array $params array() )
Returns an SQL calculation, i.e. COUNT() or MAX()
Parameters
-
Model
$Model
- The model to get a calculated field for.
- string
$func
- Lowercase name of SQL function, i.e. 'count' or 'max'
- array
$params
optional array() - Function parameters (any values must be quoted manually)
Returns
stringAn SQL calculation function
close()source public
close( )
Disconnects database, kills the connection and says the connection is closed.
Overrides
DataSource::close()
commit()source public
commit( )
Commit a transaction
Returns
booleanTrue on success, false on fail (i.e. if the database/model does not support transactions, or a transaction has not started).
Overrides
DataSource::commit()
conditionKeysToString()source public
conditionKeysToString( array $conditions , boolean $quoteValues true , Model $Model null )
Creates a WHERE clause by parsing given conditions array. Used by DboSource::conditions().
Parameters
- array
$conditions
- Array or string of conditions
- boolean
$quoteValues
optional true - If true, values should be quoted
-
Model
$Model
optional null - A reference to the Model instance making the query
Returns
stringSQL fragment
conditions()source public
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.
Parameters
- mixed
$conditions
- Array or string of conditions, or any value.
- boolean
$quoteValues
optional true - If true, values should be quoted
- boolean
$where
optional true - If true, "WHERE " will be prepended to the return value
-
Model
$Model
optional null - A reference to the Model instance making the query
Returns
stringSQL fragment
create()source public
create( Model $Model , array $fields null , array $values null )
The "C" in CRUD
Creates new records in the database.
Parameters
-
Model
$Model
- Model object that the record is for.
- array
$fields
optional null An array of field names to insert. If null, $Model->data will be used to generate field names.
- array
$values
optional null An array of values with keys matching the fields. If null, $Model->data will be used to generate values.
Returns
booleanSuccess
Overrides
DataSource::create()
createSchema()source public
createSchema( CakeSchema $schema , string $tableName null )
Generate a database-native schema for the given Schema object
Parameters
-
CakeSchema
$schema
- An instance of a subclass of CakeSchema
- string
$tableName
optional null Optional. If specified only the table name given will be generated. Otherwise, all tables defined in the schema are generated.
Returns
stringdefaultConditions()source public
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.
Parameters
-
Model
$Model
- The model to get conditions for.
- string|array|boolean
$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.
- boolean
$useAlias
optional true - Use model aliases rather than table names when generating conditions
Returns
mixedEither null, false, $conditions or an array of default conditions to use.
See
DboSource::update()DboSource::conditions()
delete()source public
delete( Model $Model , mixed $conditions null )
Generates and executes an SQL DELETE statement. For databases that do not support aliases in UPDATE queries.
Parameters
-
Model
$Model
- The model to delete from
- mixed
$conditions
optional null - The conditions to use. If empty the model's primary key will be used.
Returns
booleanSuccess
Overrides
DataSource::delete()
dropSchema()source public
dropSchema( CakeSchema $schema , string $table null )
Generate a "drop table" statement for the given Schema object
Parameters
-
CakeSchema
$schema
- An instance of a subclass of CakeSchema
- string
$table
optional null Optional. If specified only the table name given will be generated. Otherwise, all tables defined in the schema are generated.
Returns
stringexecute()source public
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.
Options
- log - Whether or not the query should be logged to the memory log.
Parameters
- string
$sql
- SQL statement
- array
$options
optional array() - The options for executing the query.
- array
$params
optional array() - values to be bound to the query.
Returns
mixedResource or object representing the result set, or false on failure
expression()source public
expression( string $expression )
Returns an object to represent a database expression in a query. Expression objects are not sanitized or escaped.
Parameters
- string
$expression
- An arbitrary SQL expression to be inserted into a query.
Returns
stdClassAn object representing a database expression to be used in a query
fetchAll()source public
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.
Options
-
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 tofalse
Parameters
- string
$sql
- SQL statement
- array|boolean
$params
optional array() Either parameters to be bound as values for the SQL statement, or a boolean to control query caching.
- array
$options
optional array() - additional options for the query.
Returns
boolean|arrayArray of resultset rows, or false if no rows matched
fetchAssociated()source public
fetchAssociated( Model $Model , string $query , array $ids )
Fetch 'hasMany' associations.
This is just a proxy to maintain BC.
Parameters
-
Model
$Model
- Primary model object.
- string
$query
- Association query template.
- array
$ids
- Array of IDs of associated records.
Returns
arrayAssociation results.
See
DboSource::_fetchHasMany()fetchResult()source public
fetchResult( )
Fetches the next row from the current result set
Returns
booleanfetchRow()source public
fetchRow( string $sql null )
Returns a row from current resultset as an array
Parameters
- string
$sql
optional null - Some SQL to be executed.
Returns
arrayThe fetched row as an array
fetchVirtualField()source public
fetchVirtualField( array $result )
Modifies $result array to place virtual fields in model entry where they belongs to
Parameters
- array
$result
- $result Reference to the fetched row
field()source public
field( string $name , string $sql )
Returns a single field of the first of query results for a given SQL query, or false if empty.
Parameters
- string
$name
- The name of the field to get.
- string
$sql
- The SQL query.
Returns
mixedValue of field read, or false if not found.
fields()source public
fields( Model $Model , string $alias null , mixed $fields array() , boolean $quote true )
Generates the fields list of an SQL query.
Parameters
-
Model
$Model
- The model to get fields for.
- string
$alias
optional null - Alias table name
- mixed
$fields
optional array() - The provided list of fields.
- boolean
$quote
optional true - If false, returns fields array unquoted
Returns
arrayflushMethodCache()source public
flushMethodCache( )
Empties the method caches. These caches are used by DboSource::name() and DboSource::conditions()
fullTableName()source public
fullTableName( Model|string $model , boolean $quote true , boolean $schema true )
Gets full table name including prefix
Parameters
-
Model
|string$model
- Either a Model object or a string table name.
- boolean
$quote
optional true - Whether you want the table name quoted.
- boolean
$schema
optional true - Whether you want the schema name included.
Returns
stringFull quoted table name
generateAssociationQuery()source public
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.
Parameters
-
Model
$Model
- Primary Model object.
-
Model
|null$LinkModel
- Linked model object.
- string
$type
- Association type, one of the model association types ie. hasMany.
- string
$association
- Association name.
- array
$assocData
- Association data.
- array
$queryData
- $queryData An array of queryData information containing keys similar to Model::find().
- boolean
$external
- Whether or not the association query is on an external datasource.
Returns
mixedString representing a query. True, when $external is false and association $type is 'hasOne' or 'belongsTo'.
getConstraint()source public
getConstraint( string $type , Model $Model , Model $LinkModel , string $association , array $assocData , string $association2 null )
Returns a conditions array for the constraint between two models.
Parameters
- string
$type
- Association type.
-
Model
$Model
- Primary Model object.
-
Model
$LinkModel
- Linked model object.
- string
$association
- Association name.
- array
$assocData
- Association data.
- string
$association2
optional null - HABTM association name.
Returns
arrayConditions array defining the constraint between $Model and $LinkModel.
getLockingHint()source public
getLockingHint( mixed $mode )
Returns a locking hint for the given mode.
Currently, this method only returns FOR UPDATE when the mode is set to true.
Parameters
- mixed
$mode
- Lock mode
Returns
string|nullFOR UPDATE clause or null
getLog()source public
getLog( boolean $sorted false , boolean $clear true )
Get the query log as an array.
Parameters
- boolean
$sorted
optional false - Get the queries sorted by time taken, defaults to false.
- boolean
$clear
optional true - If True the existing log will cleared.
Returns
arrayArray of queries run as an array
getQueryCache()source public
getQueryCache( string $sql , array $params array() )
Returns the result for a sql query if it is already cached
Parameters
- string
$sql
- SQL query
- array
$params
optional array() - query params bound as values
Returns
mixedresults for query if it is cached, false otherwise
getVersion()source public
getVersion( )
Gets the version string of the database server
Returns
stringThe database version
group()source public
group( string|array $fields , Model $Model null )
Create a GROUP BY SQL clause.
Parameters
- string|array
$fields
- Group By fields
-
Model
$Model
optional null - The model to get group by fields for.
Returns
stringGroup By clause or null.
hasAny()source public
hasAny( Model $Model , string $sql )
Checks if the specified table contains any record matching specified SQL
Parameters
-
Model
$Model
- Model to search
- string
$sql
- SQL WHERE clause (condition only, not the "WHERE" part)
Returns
booleanTrue if the table has a matching record, else false
hasResult()source public
hasResult( )
Checks if the result is valid
Returns
booleanTrue if the result is valid else false
having()source public
having( mixed $fields , boolean $quoteValues true , Model $Model null )
Create a HAVING SQL clause.
Parameters
- mixed
$fields
- Array or string of conditions
- boolean
$quoteValues
optional true - If true, values should be quoted
-
Model
$Model
optional null - A reference to the Model instance making the query
Returns
string|nullHAVING clause or null
identifier()source public
identifier( string $identifier )
Returns an object to represent a database identifier in a query. Expression objects are not sanitized or escaped.
Parameters
- string
$identifier
- A SQL expression to be used as an identifier
Returns
stdClassAn object representing a database identifier to be used in a query
index()source public
index( string $model )
Returns an array of the indexes in given datasource name.
Parameters
- string
$model
- Name of model to inspect
Returns
arrayFields in table. Keys are column and unique
insertMulti()source public
insertMulti( string $table , array $fields , array $values )
Inserts multiple values into a table
Parameters
- string
$table
- The table being inserted into.
- array
$fields
- The array of field/column names being inserted.
- array
$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.
Returns
booleanintrospectType()source public
introspectType( string $value )
Guesses the data type of an array
Parameters
- string
$value
- The value to introspect for type data.
Returns
stringisConnected()source public
isConnected( )
Checks if the source is connected to the database.
Returns
booleanTrue if the database is connected, else false
lastAffected()source public
lastAffected( mixed $source null )
Returns number of affected rows in previous database operation. If no previous operation exists, this returns false.
Parameters
- mixed
$source
optional null - The source to check.
Returns
integerNumber of affected rows
Overrides
DataSource::lastAffected()
lastError()source public
lastError( PDOStatement $query null )
Returns a formatted error message from previous database operation.
Parameters
- PDOStatement
$query
optional null - the query to extract the error from if any
Returns
stringError message with error number
lastInsertId()source public
lastInsertId( mixed $source null )
Returns the ID generated from the previous INSERT operation.
Parameters
- mixed
$source
optional null - The source to get an id for.
Returns
mixedOverrides
DataSource::lastInsertId()
lastNumRows()source public
lastNumRows( mixed $source null )
Returns number of rows in previous resultset. If no previous resultset exists, this returns false.
Parameters
- mixed
$source
optional null - Not used
Returns
integerNumber of rows in resultset
Overrides
DataSource::lastNumRows()
length()source public
length( string $real )
Gets the length of a database-native column description, or null if no length
Parameters
- string
$real
- Real database-layer column type (i.e. "varchar(255)")
Returns
mixedAn integer or string representing the length of the column, or null for unknown length.
limit()source public
limit( integer $limit , integer $offset null )
Returns a limit statement in the correct format for the particular database.
Parameters
- integer
$limit
- Limit of results returned
- integer
$offset
optional null - Offset from which to start results
Returns
stringSQL limit/offset statement
logQuery()source public
logQuery( string $sql , array $params array() )
Log given SQL query.
Parameters
- string
$sql
- SQL statement
- array
$params
optional array() - Values binded to the query (prepared statements)
name()source public
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.
Parameters
- mixed
$data
Either a string with a column to quote. An array of columns to quote or an object from DboSource::expression() or DboSource::identifier()
Returns
stringSQL field
nestedTransactionSupported()source public
nestedTransactionSupported( )
Check if the server support nested transactions
Returns
booleanorder()source public
order( array|string $keys , string $direction 'ASC' , Model $Model null )
Returns an ORDER BY clause as a string.
Parameters
- array|string
$keys
- Field reference, as a key (i.e. Post.title)
- string
$direction
optional 'ASC' - Direction (ASC or DESC)
-
Model
$Model
optional null - Model reference (used to look for virtual field)
Returns
stringORDER BY clause
prepareFields()source public
prepareFields( Model $Model , array $queryData )
Prepares fields required by an SQL statement.
When no fields are set, all the $Model fields are returned.
Parameters
-
Model
$Model
- The model to prepare.
- array
$queryData
- An array of queryData information containing keys similar to Model::find().
Returns
arrayArray containing SQL fields.
query()source public
query( )
DataSource Query abstraction
Returns
resourceResult resource identifier.
queryAssociation()source public
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.
Parameters
-
Model
$Model
- Primary Model object.
-
Model
$LinkModel
- Linked model object.
- string
$type
- Association type, one of the model association types ie. hasMany.
- string
$association
- Association name.
- array
$assocData
- Association data.
- array
$queryData
- $queryData An array of queryData information containing keys similar to Model::find().
- boolean
$external
- Whether or not the association query is on an external datasource.
- array
$resultSet
- $resultSet Existing results.
- integer
$recursive
- Number of levels of association.
- array
$stack
- A list with joined models.
Returns
mixedThrows
CakeException
when results cannot be created.
rawQuery()source public
rawQuery( string $sql , array $params array() )
Executes given SQL statement.
Parameters
- string
$sql
- SQL statement
- array
$params
optional array() - Additional options for the query.
Returns
mixedResource or object representing the result set, or false on failure
read()source public
read( Model $Model , array $queryData array() , integer $recursive null )
The "R" in CRUD
Reads record(s) from the database.
Parameters
-
Model
$Model
- A Model object that the query is for.
- array
$queryData
optional array() - An array of queryData information containing keys similar to Model::find().
- integer
$recursive
optional null - Number of levels of association
Returns
mixedboolean false on error/failure. An array of results on success.
Overrides
DataSource::read()
readTableParameters()source public
readTableParameters( string $name )
Read additional table parameters
Parameters
- string
$name
- The table name to read.
Returns
arrayreconnect()source public
reconnect( array $config array() )
Reconnects to database server with optional new settings
Parameters
- array
$config
optional array() - An array defining the new configuration settings
Returns
booleanTrue on success, false on failure
renderJoinStatement()source public
renderJoinStatement( array $data )
Renders a final SQL JOIN statement
Parameters
- array
$data
- The data to generate a join statement for.
Returns
stringrenderStatement()source public
renderStatement( string $type , array $data )
Renders a final SQL statement by putting together the component parts in the correct order
Parameters
- string
$type
- type of query being run. e.g select, create, update, delete, schema, alter.
- array
$data
- Array of data to insert into the query.
Returns
string|nullRendered SQL expression to be run, otherwise null.
resetSequence()source public
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.
Parameters
- string
$table
- The name of the table to update.
- string
$column
- The column to use when resetting the sequence value.
Returns
booleanSuccess.
resolveKey()source public
resolveKey( Model $Model , string $key , string $assoc null )
Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name)
Parameters
-
Model
$Model
- The model to get a key for.
- string
$key
- The key field.
- string
$assoc
optional null - The association name.
Returns
stringOverrides
DataSource::resolveKey()
rollback()source public
rollback( )
Rollback a transaction
Returns
booleanTrue on success, false on fail (i.e. if the database/model does not support transactions, or a transaction has not started).
Overrides
DataSource::rollback()
showLog()source public
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.
Parameters
- boolean
$sorted
optional false - Get the queries sorted by time taken, defaults to false.
truncate()source public
truncate( Model|string $table )
Deletes all the records in a table and resets the count of the auto-incrementing primary key, where applicable.
Parameters
-
Model
|string$table
- A string or model class representing the table to be truncated
Returns
booleanSQL TRUNCATE TABLE statement, false if not applicable.
update()source public
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.
Parameters
-
Model
$Model
- The model to update.
- array
$fields
optional array() - The fields to update
- array
$values
optional null - The values fo the fields.
- mixed
$conditions
optional null - The conditions for the update. When non-empty $values will not be quoted.
Returns
booleanSuccess
Overrides
DataSource::update()
value()source public
value( string $data , string $column null , boolean $null true )
Returns a quoted and escaped string of $data for use in an SQL statement.
Parameters
- string
$data
- String to be prepared for use in an SQL statement
- string
$column
optional null - The column datatype into which this data will be inserted.
- boolean
$null
optional true - Column allows NULL values
Returns
stringQuoted and escaped data
Methods inherited from DataSource
_cacheDescription()source protected
_cacheDescription( string $object , mixed $data null )
Cache the DataSource description
Parameters
- string
$object
- The name of the object (model) to cache
- mixed
$data
optional null - The description of the model, usually a string or array
Returns
mixedcolumn()source public
column( string $real )
Converts column types to basic types
Parameters
- string
$real
- Real column type (i.e. "varchar(255)")
Returns
stringAbstract column type (i.e. "string")
describe()source public
describe( Model|string $model )
Returns a Model description (metadata) or null if none found.
Parameters
-
Model
|string$model
- The model to describe.
Returns
array|nullArray of Metadata for the $model
enabled()source public
enabled( )
Check whether the conditions for the Datasource being available are satisfied. Often used from connect() to check for support before establishing a connection.
Returns
booleanWhether or not the Datasources conditions for use are met.
getSchemaName()source public
getSchemaName( )
Returns the schema name. Override this in subclasses.
Returns
string|nullThe schema name
insertQueryData()source public
insertQueryData( string $query , array $data , string $association , Model $Model , array $stack )
Replaces {$__cakeID__$}
and {$__cakeForeignKey__$}
placeholders in query data.
Parameters
- string
$query
- Query string needing replacements done.
- array
$data
- Array of data with values that will be inserted in placeholders.
- string
$association
- Name of association model being replaced.
-
Model
$Model
- Model instance.
- array
$stack
- The context stack.
Returns
mixedString of query data with placeholders replaced, or false on failure.
listSources()source public
listSources( mixed $data null )
Caches/returns cached results for child instances
Parameters
- mixed
$data
optional null - Unused in this class.
Returns
array|nullArray of sources available in this datasource.
setConfig()source public
setConfig( array $config array() )
Sets the configuration for the DataSource. Merges the $config information with the _baseConfig and the existing $config property.
Parameters
- array
$config
optional array() - The configuration array
Methods inherited from CakeObject
_mergeVars()source protected
_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.
Parameters
- array
$properties
- The name of the properties to merge.
- string
$class
- The class to merge the property with.
- boolean
$normalize
optional true - Set to true to run the properties through Hash::normalize() before merging.
_set()source protected
_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.
Parameters
- array
$properties
optional array() - An associative array containing properties and corresponding values.
_stop()source protected
_stop( integer|string $status 0 )
Stop execution of the current script. Wraps exit() making testing easier.
Parameters
- integer|string
$status
optional 0 - see http://php.net/exit for values
dispatchMethod()source public
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
Parameters
- string
$method
- Name of the method to call
- array
$params
optional array() - Parameter list to use when calling $method
Returns
mixedReturns the result of the method call
log()source public
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.
Parameters
- string
$msg
- Log message
- integer
$type
optional LOG_ERR - Error type constant. Defined in app/Config/core.php.
- null|string|array
$scope
optional null The scope(s) a log message is being created in. See CakeLog::config() for more information on logging scopes.
Returns
booleanSuccess of log write
requestAction()source public
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()
Passing POST and GET data
POST and GET data can be simulated in requestAction. Use $extra['url']
for GET data. The $extra['data']
parameter allows POST data simulation.
Parameters
- string|array
$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.
- array
$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.
Returns
mixedBoolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.
toString()source public
toString( )
CakeObject-to-string conversion. Each class can override this method as necessary.
Returns
stringThe name of this class
Properties detail
$_methodCacheChangesource
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
$_queriesLogMaxsource
protected integer
Maximum number of items in query log
This is to prevent query log taking over too much memory.
200
$_queryDefaultssource
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, 'having' => null, 'lock' => null, )
$_sqlBoolOpssource
protected array
The set of valid SQL boolean operations usable in a WHERE statement
array('and', 'or', 'not', 'and not', 'or not', 'xor', '||', '&&')
$_sqlOpssource
protected array
The set of valid SQL operations usable in a WHERE statement
array('like', 'ilike', 'rlike', 'or', 'not', 'in', 'between', 'regexp', 'similar to')
$affectedsource
public string
String to hold how many rows were affected by the last SQL operation.
null
$cacheMethodssource
public boolean
Whether or not to cache the results of DboSource::name() and DboSource::fields() into the memory cache. Set to false to disable the use of the memory cache.
true
$descriptionsource
public string
Description string for this Database Data Source.
"Database Data Source"
$endQuotesource
public string
The ending character that this DataSource uses for quoted identifiers.
null
$fieldParameterssource
public array
List of engine specific additional field parameters used on table creating
array()
$indexsource
public array
index definition, standard cake, primary, index, unique
array('PRI' => 'primary', 'MUL' => 'index', 'UNI' => 'unique')
$methodCachesource
public static array
Caches result from query parsing operations. Cached results for both DboSource::name() and DboSource::fields() will be stored here.
Method caching uses md5
(by default) to construct cache keys. If you have problems with collisions, try a different hashing algorithm by overriding DboSource::cacheMethodHasher or set DboSource::$cacheMethods to false.
array()
$startQuotesource
public string
The starting character that this DataSource uses for quoted identifiers.
null
$tableParameterssource
public array
List of table engine specific parameters used on table creating
array()
$useNestedTransactionssource
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–2017 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.
https://api.cakephp.org/2.10/class-DboSource.html