Class DboSource
DboSource
Creates DBO-descendant objects from a given db connection configuration
- Object
- DataSource
- DboSource
Copyright: Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
License: License (http://www.opensource.org/licenses/mit-license.php)
Location: Cake/Model/Datasource/DboSource.php
Properties summary
-
$_commands
protectedarray
Index of basic SQL commands -
$_connection
protectedarray
A reference to the physical connection of this DataSource -
$_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
protectedinteger
Queries count. -
$_queriesLog
protectedarray
Log of queries executed by this DataSource -
$_queriesLogMax
protectedinteger
Maximum number of items in query log -
$_queriesTime
protectedinteger
Total duration of all queries. -
$_queryCache
protectedarray
Caches serialized results of executed queries -
$_result
protectedarray
Result -
$_sqlOps
protectedarray
The set of valid SQL operations usable in a WHERE statement -
$_transactionNesting
protectedinteger
Indicates the level of nested transactions -
$affected
publicstring
String to hold how many rows were affected by the last SQL operation. -
$alias
publicstring
Database keyword used to assign aliases to identifiers. -
$cacheMethods
publicboolean.
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.
-
$configKeyName
publicstring
The DataSource configuration key name -
$description
publicstring
Description string for this Database Data Source. -
$endQuote
publicstring
The ending character that this DataSource uses for quoted identifiers. -
$fieldParameters
publicarray
List of engine specific additional field parameters used on table creating -
$fullDebug
publicboolean
Print full query debug info? -
$index
publicarray
index definition, standard cake, primary, index, unique -
$methodCache
public staticarray
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. -
$numRows
publicinteger
Number of rows in current resultset -
$startQuote
publicstring
The starting character that this DataSource uses for quoted identifiers. -
$tableParameters
publicarray
List of table engine specific parameters used on table creating -
$took
publicinteger
Time the last query took -
$virtualFieldSeparator
publicstring
Separator string for virtualField composition
Inherited Properties
Method Summary
-
__construct() public
Constructor -
__destruct() public
Used for storing in cache the results of the in-memory methodCache -
_buildFieldParameters() protected
Build the field parameters, in a position -
_constructVirtualFields() protected
Converts model virtual fields into sql expressions to be fetched later -
_execute() protected
Executes given SQL statement. -
_filterResults() protected
Passes association results thru afterFind filters of corresponding model -
_getJoins() protected
Returns an array of SQL JOIN fragments 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() protected
Merge association of merge into data -
_mergeConditions() protected
Merges a mixed set of string/array conditions -
_mergeHasMany() protected
mergeHasMany - Merge the results of hasMany relations. -
_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() protected
Quotes and prepares fields and values for an SQL UPDATE statement -
_quoteFields() protected
Quotes Model.fields -
_quoteMatchedField() protected
Auxiliary function to quote matchesModel.fields
from a preg_replace_callback call -
_scrubQueryData() protected
Private helper method to remove query metadata in given data array. -
_writeQueryCache() protected
Writes a new key for the in memory sql query cache -
alterSchema() public
Generate a alter syntax from CakeSchema::compare() -
begin() public
Begin a transaction -
boolean() public
Translates between PHP boolean values and Database (faked) boolean values -
buildColumn() public
Generate a database-native column schema string -
buildIndex() public
Format indexes for create table -
buildJoinStatement() public
Builds and generates a JOIN statement from an array. Handles final clean-up before conversion. -
buildStatement() public
Builds and generates an SQL statement from an array. Handles final clean-up before conversion. -
buildTableParameters() public
Format 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.
-
calculate() public
Returns an SQL calculation, i.e. COUNT() or MAX() -
close() public
Disconnects database, kills the connection and says the connection is closed. -
commit() public
Commit a transaction -
conditionKeysToString() public
Creates 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() public
The "C" in CRUD -
createSchema() public
Generate 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() public
Disconnects from database. -
dropSchema() public
Generate 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() public
Returns an array of all result rows for a given SQL query. Returns false if no rows matched.
-
fetchAssociated() public
A more efficient way to fetch associations. Woohoo! -
fetchResult() public
Fetches the next row from the current result set -
fetchRow() public
Returns a row from current resultset as an array -
fetchVirtualField() public
Modifies $result array to place virtual fields in model entry where they belongs to -
field() public
Returns a single field of the first of query results for a given SQL query, or false if empty. -
fields() public
Generates the fields list of an SQL query. -
flushMethodCache() public
Empties the method caches. These caches are used by DboSource::name() and DboSource::conditions()
-
fullTableName() public
Gets full table name including prefix -
generateAssociationQuery() public
Generates an array representing a query or part of a query from a single model or two associated models -
getConnection() public
Get the underlying connection object. -
getConstraint() public
Returns a conditions array for the constraint between two models -
getLog() public
Get the query log as an array. -
getQueryCache() public
Returns the result for a sql query if it is already cached -
group() public
Create a GROUP BY SQL clause -
hasAny() public
Checks if the specified table contains any record matching specified SQL -
hasResult() public
Checks if the result is valid -
identifier() public
Returns an object to represent a database identifier in a query. Expression objects are not sanitized or escaped.
-
index() public
Returns an array of the indexes in given datasource name. -
insertMulti() public
Inserts multiple values into a table -
introspectType() public
Guesses the data type of an array -
isConnected() public
Checks 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() public
Returns a formatted error message from previous database operation. -
lastInsertId() public
Returns 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() public
Gets the length of a database-native column description, or null if no length -
limit() public
Returns a limit statement in the correct format for the particular database. -
logQuery() public
Log 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.
-
order() public
Returns an ORDER BY clause as a string. -
query() public
DataSource Query abstraction -
queryAssociation() public
Queries associations. Used to fetch results on recursive models. -
rawQuery() public
Executes given SQL statement. -
read() public
The "R" in CRUD -
readTableParameters() public
Read additional table parameters -
reconnect() public
Reconnects to database server with optional new settings -
renderJoinStatement() public
Renders a final SQL JOIN statement -
renderStatement() public
Renders a final SQL statement by putting together the component parts in the correct order -
resolveKey() public
Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name) -
rollback() public
Rollback 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() public
Returns a quoted and escaped string of $data for use in an SQL statement.
Method Detail
__construct() 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
Overrides
__destruct() public ¶
__destruct( )
Used for storing in cache the results of the in-memory methodCache
Overrides
_buildFieldParameters() 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
a built column with the field parameters added.
_constructVirtualFields() protected ¶
_constructVirtualFields( Model
$model , string $alias , mixed $fields )
Converts model virtual fields into sql expressions to be fetched later
Parameters
-
Model
$model - string $alias
- Alias table name
- mixed $fields
- virtual fields to be used on query
Returns
_execute() 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
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
Throws
_filterResults() protected ¶
_filterResults( array $results , Model
$model , array $filtered = array() )
Passes association results thru afterFind filters of corresponding model
Parameters
- array $results
- 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
Array of results that have been filtered through $model->afterFind
_getJoins() protected ¶
_getJoins( Model
$model )
Returns an array of SQL JOIN fragments from a model's associations
Parameters
-
Model
$model
Returns
_matchRecords() 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 - mixed $conditions optional null
Returns
List of record IDs
_mergeAssociation() protected ¶
_mergeAssociation( array $data , array $merge , string $association , string $type , boolean $selfJoin = false )
Merge association of merge into data
Parameters
- array $data
- array $merge
- string $association
- string $type
- boolean $selfJoin optional false
_mergeConditions() protected ¶
_mergeConditions( mixed $query , mixed $assoc )
Merges a mixed set of string/array conditions
Parameters
- mixed $query
- mixed $assoc
Returns
_mergeHasMany() protected ¶
_mergeHasMany( array $resultSet , array $merge , string $association , Model
$model , Model
$linkModel )
_parseKey() protected ¶
_parseKey( Model
$model , string $key , mixed $value )
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
-
Model
$model - Model object initiating the query
- string $key
- An SQL key snippet containing a field and optional SQL operator
- mixed $value
- The value(s) to be inserted in the string
Returns
_prepareUpdateFields() 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 - array $fields
- 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
Fields and values, quoted and prepared
_quoteFields() protected ¶
_quoteFields( string $conditions )
Quotes Model.fields
Parameters
- string $conditions
Returns
or false if no match
_quoteMatchedField() protected ¶
_quoteMatchedField( string $match )
Auxiliary function to quote matches Model.fields
from a preg_replace_callback call
Parameters
- string $match
- matched string
Returns
quoted string
_scrubQueryData() protected ¶
_scrubQueryData( array $data )
Private helper method to remove query metadata in given data array.
Parameters
- array $data
Returns
_writeQueryCache() 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() public ¶
alterSchema( mixed $compare , string $table = null )
Generate a alter syntax from CakeSchema::compare()
Parameters
- mixed $compare
- string $table optional null
Returns
begin() public ¶
begin( )
Begin a transaction
Returns
True on success, false on fail (i.e. if the database/model does not support transactions, or a transaction has not started).
Overrides
boolean() 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
Returns
Converted boolean value
buildColumn() 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
buildIndex() public ¶
buildIndex( array $indexes , string $table = null )
Format indexes for create table
Parameters
- array $indexes
- string $table optional null
Returns
buildJoinStatement() public ¶
buildJoinStatement( array $join )
Builds and generates a JOIN statement from an array. Handles final clean-up before conversion.
Parameters
- array $join
- An array defining a JOIN statement in a query
Returns
An SQL JOIN statement to be used in a query
See
DboSource::buildStatement()
buildStatement() 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
An executable SQL statement
See
buildTableParameters() public ¶
buildTableParameters( array $parameters , string $table = null )
Format parameters for create table
Parameters
- array $parameters
- string $table optional null
Returns
cacheMethod() 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
Either null on failure, or the value if its set.
calculate() public ¶
calculate( Model
$model , string $func , array $params = array() )
Returns an SQL calculation, i.e. COUNT() or MAX()
Parameters
-
Model
$model - 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
An SQL calculation function
close() public ¶
close( )
Disconnects database, kills the connection and says the connection is closed.
Overrides
commit() public ¶
commit( )
Commit a transaction
Returns
True on success, false on fail (i.e. if the database/model does not support transactions, or a transaction has not started).
Overrides
conditionKeysToString() 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
SQL fragment
conditions() 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
SQL fragment
create() 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
Success
Overrides
createSchema() public ¶
createSchema( Model
$schema , string $tableName = null )
Generate a database-native schema for the given Schema object
Parameters
-
Model
$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
defaultConditions() public ¶
defaultConditions( Model
$model , mixed $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 - mixed $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
Either null, false, $conditions or an array of default conditions to use.
See
DboSource::conditions()
delete() 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 - mixed $conditions optional null
Returns
Success
Overrides
disconnect() public ¶
disconnect( )
Disconnects from database.
Returns
True if the database could be disconnected, else false
dropSchema() 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
execute() 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()
- array $params optional array()
- values to be bound to the query
Returns
Resource or object representing the result set, or false on failure
expression() 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
An object representing a database expression to be used in a query
fetchAll() public ¶
fetchAll( string $sql , array $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 $params optional array()
- parameters to be bound as values for the SQL statement
- array $options optional array()
- additional options for the query.
Returns
Array of resultset rows, or false if no rows matched
fetchAssociated() public ¶
fetchAssociated( Model
$model , string $query , array $ids )
A more efficient way to fetch associations. Woohoo!
Parameters
-
Model
$model - Primary model object
- string $query
- Association query
- array $ids
- Array of IDs of associated records
Returns
Association results
fetchResult() public ¶
fetchResult( )
Fetches the next row from the current result set
Returns
fetchRow() 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
The fetched row as an array
fetchVirtualField() public ¶
fetchVirtualField( array $result )
Modifies $result array to place virtual fields in model entry where they belongs to
Parameters
- array $result
- Reference to the fetched row
field() 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
- Name of the field
- string $sql
- SQL query
Returns
Value of field read.
fields() public ¶
fields( Model
$model , string $alias = null , mixed $fields = array() , boolean $quote = true )
Generates the fields list of an SQL query.
Parameters
-
Model
$model - string $alias optional null
- Alias table name
- mixed $fields optional array()
- boolean $quote optional true
- If false, returns fields array unquoted
Returns
flushMethodCache() public ¶
flushMethodCache( )
Empties the method caches. These caches are used by DboSource::name() and DboSource::conditions()
fullTableName() public ¶
fullTableName( mixed $model , boolean $quote = true , boolean $schema = true )
Gets full table name including prefix
Parameters
- mixed $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
Full quoted table name
generateAssociationQuery() public ¶
generateAssociationQuery( Model
$model , Model
$linkModel , string $type , string $association , array $assocData , array $queryData , boolean $external , array $resultSet )
getConnection() public ¶
getConnection( )
Get the underlying connection object.
Returns
getConstraint() public ¶
getConstraint( string $type , Model
$model , string $linkModel , string $alias , array $assoc , string $alias2 = null )
Returns a conditions array for the constraint between two models
Parameters
- string $type
- Association type
-
Model
$model - Model object
- string $linkModel
- string $alias
- array $assoc
- string $alias2 optional null
Returns
Conditions array defining the constraint between $model and $association
getLog() 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
Array of queries run as an array
getQueryCache() 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
results for query if it is cached, false otherwise
group() public ¶
group( string $group , Model
$model = null )
Create a GROUP BY SQL clause
Parameters
- string $group
- Group By Condition
-
Model
$model optional null
Returns
string condition or null
hasAny() 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
True if the table has a matching record, else false
hasResult() public ¶
hasResult( )
Checks if the result is valid
Returns
True if the result is valid else false
identifier() 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
An object representing a database identifier to be used in a query
index() public ¶
index( string $model )
Returns an array of the indexes in given datasource name.
Parameters
- string $model
- Name of model to inspect
Returns
Fields in table. Keys are column and unique
insertMulti() 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
introspectType() public ¶
introspectType( string $value )
Guesses the data type of an array
Parameters
- string $value
isConnected() public ¶
isConnected( )
Checks if the source is connected to the database.
Returns
True if the database is connected, else false
lastAffected() 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
Returns
Number of affected rows
Overrides
lastError() 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
Error message with error number
lastInsertId() public ¶
lastInsertId( mixed $source = null )
Returns the ID generated from the previous INSERT operation.
Parameters
- mixed $source optional null
Returns
Overrides
lastNumRows() 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
Number of rows in resultset
Overrides
length() 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
An integer or string representing the length of the column, or null for unknown length.
limit() 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
SQL limit/offset statement
logQuery() 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() 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
SQL field
order() 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
ORDER BY clause
queryAssociation() 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.
Parameters
-
Model
$model - Primary Model object
-
Model
$linkModel - Linked model that
- string $type
- Association type, one of the model association types ie. hasMany
- string $association
- array $assocData
- array $queryData
- boolean $external
- Whether or not the association query is on an external datasource.
- array $resultSet
- Existing results
- integer $recursive
- Number of levels of association
- array $stack
Returns
Throws
rawQuery() 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
read() 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
boolean false on error/failure. An array of results on success.
Overrides
readTableParameters() public ¶
readTableParameters( string $name )
Read additional table parameters
Parameters
- string $name
Returns
reconnect() 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
True on success, false on failure
renderJoinStatement() public ¶
renderJoinStatement( array $data )
Renders a final SQL JOIN statement
Parameters
- array $data
Returns
renderStatement() 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
Rendered SQL expression to be run.
resolveKey() 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 - string $key
- string $assoc optional null
Returns
Overrides
rollback() public ¶
rollback( )
Rollback a transaction
Returns
True on success, false on fail (i.e. if the database/model does not support transactions, or a transaction has not started).
Overrides
showLog() 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() public ¶
truncate( mixed $table )
Deletes all the records in a table and resets the count of the auto-incrementing primary key, where applicable.
Parameters
- mixed $table
- A string or model class representing the table to be truncated
Returns
SQL TRUNCATE TABLE statement, false if not applicable.
update() 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 - array $fields optional array()
- array $values optional null
- mixed $conditions optional null
Returns
Success
Overrides
value() public ¶
value( string $data , string $column = null )
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 into which this data will be inserted
Returns
Quoted and escaped data
Methods inherited from DataSource
_cacheDescription() 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
column() public ¶
column( string $real )
Converts column types to basic types
Parameters
- string $real
- Real column type (i.e. "varchar(255)")
Returns
Abstract column type (i.e. "string")
describe() public ¶
describe( Model
|string $model )
Returns a Model description (metadata) or null if none found.
Parameters
-
Model
|string $model
Returns
Array of Metadata for the $model
enabled() 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
Whether or not the Datasources conditions for use are met.
getSchemaName() public ¶
getSchemaName( )
Returns the schema name. Override this in subclasses.
Returns
schema name
insertQueryData() public ¶
insertQueryData( string $query , array $data , string $association , array $assocData , Model
$model , Model
$linkModel , 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
- array $assocData
-
Model
$model - Instance of the model to replace $cakeID$
-
Model
$linkModel - Instance of model to replace $cakeForeignKey$
- array $stack
Returns
String of query data with placeholders replaced.
listSources() public ¶
listSources( mixed $data = null )
Caches/returns cached results for child instances
Parameters
- mixed $data optional null
Returns
Array of sources available in this datasource.
setConfig() 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 Object
_mergeVars() 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 Set::normalize() before merging.
_set() 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() 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() 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
Returns the result of the method call
log() public ¶
log( string $msg , integer $type = LOG_ERROR )
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_ERROR
- Error type constant. Defined in app/Config/core.php.
Returns
Success of log write
requestAction() public ¶
requestAction( mixed $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
- mixed $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
Boolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.
toString() public ¶
toString( )
Object-to-string conversion. Each class can override this method as necessary.
Returns
The name of this class
Properties detail
$_commands ¶
Index of basic SQL commands
array( 'begin' => 'BEGIN', 'commit' => 'COMMIT', 'rollback' => 'ROLLBACK' )
$_methodCacheChange ¶
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
$_queriesLogMax ¶
Maximum number of items in query log
This is to prevent query log taking over too much memory.
200
$_sqlOps ¶
The set of valid SQL operations usable in a WHERE statement
array('like', 'ilike', 'or', 'not', 'in', 'between', 'regexp', 'similar to')
$affected ¶
String to hold how many rows were affected by the last SQL operation.
null
$cacheMethods ¶
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
$description ¶
Description string for this Database Data Source.
"Database Data Source"
$endQuote ¶
The ending character that this DataSource uses for quoted identifiers.
null
$fieldParameters ¶
List of engine specific additional field parameters used on table creating
array()
$index ¶
index definition, standard cake, primary, index, unique
array('PRI' => 'primary', 'MUL' => 'index', 'UNI' => 'unique')
$methodCache ¶
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()
$startQuote ¶
The starting character that this DataSource uses for quoted identifiers.
null
$tableParameters ¶
List of table engine specific parameters used on table creating
array()