PHP Class DboSource

Creates DBO-descendant objects from a given db connection configuration
Inheritance: extends DataSource
Afficher le fichier Open project: baserproject/basercms Class Usage Examples

Méthodes publiques

Свойство Type Description
$affected string String to hold how many rows were affected by the last SQL operation.
$alias string Database keyword used to assign aliases to identifiers.
$cacheMethods boolean Whether or not to cache the results of DboSource::name() and DboSource::conditions() into the memory cache. Set to false to disable the use of the memory cache.
$configKeyName string The DataSource configuration key name
$description string Description string for this Database Data Source.
$endQuote string The ending character that this DataSource uses for quoted identifiers.
$fieldParameters array List of engine specific additional field parameters used on table creating
$fullDebug boolean Print full query debug info?
$index array index definition, standard cake, primary, index, unique
$methodCache array Caches result from query parsing operations. Cached results for both DboSource::name() and DboSource::conditions() will be stored here. Method caching uses md5(). If you have problems with collisions, set DboSource::$cacheMethods to false.
$numRows integer Number of rows in current resultset
$startQuote string The starting character that this DataSource uses for quoted identifiers.
$tableParameters array List of table engine specific parameters used on table creating
$took integer Time the last query took
$useNestedTransactions 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.
$virtualFieldSeparator string Separator string for virtualField composition

Protected Properties

Свойство Type Description
$_connection array A reference to the physical connection of this DataSource
$_encodingMaps array PHP←→DBエンコーディングマップ
$_methodCacheChange 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
$_queriesCnt integer Queries count.
$_queriesLog array Log of queries executed by this DataSource
$_queriesLogMax integer This is to prevent query log taking over too much memory.
$_queriesTime integer Total duration of all queries.
$_queryCache array Caches serialized results of executed queries
$_queryDefaults array Default fields that are used by the DBO
$_result array Result
$_sqlOps array The set of valid SQL operations usable in a WHERE statement
$_transactionNesting integer Indicates the level of nested transactions

Méthodes publiques

Méthode Description
__construct ( array $config = null, boolean $autoConnect = true ) Constructor
__destruct ( ) Used for storing in cache the results of the in-memory methodCache
addColumn ( array $options ) : boolean カラムを追加する
alterSchema ( mixed $compare, string $table = null ) : boolean Generate a alter syntax from CakeSchema::compare()
alterTable ( array $options ) : boolean テーブル構造を変更する
alterTableBySchema ( array $options ) : boolean スキーマファイルからテーブル構造を変更する
begin ( ) : boolean Begin a transaction
boolean ( mixed $data, boolean $quote = false ) : string | boolean Translates between PHP boolean values and Database (faked) boolean values
buildAssociationQuery ( Model $Model, array $queryData ) : string Builds an SQL statement.
buildColumn ( array $column ) : string Generate a database-native column schema string
buildIndex ( array $indexes, string $table = null ) : array Format indexes for create table.
buildJoinStatement ( array $join ) : string Builds and generates a JOIN condition from an array. Handles final clean-up before conversion.
buildRenameTable ( string $sourceName, string $targetName ) : string テーブル名のリネームステートメントを生成
buildStatement ( array $query, Model $Model ) : string Builds and generates an SQL statement from an array. Handles final clean-up before conversion.
buildTableParameters ( array $parameters, string $table = null ) : array Format parameters for create table
cacheMethod ( string $method, string $key, mixed $value = null ) : mixed Cache a value into the methodCaches. Will respect the value of DboSource::$cacheMethods.
calculate ( Model $Model, string $func, array $params = [] ) : string Returns an SQL calculation, i.e. COUNT() or MAX()
changeColumn ( array $options ) : boolean カラムを変更する
close ( ) : void Disconnects database, kills the connection and says the connection is closed.
commit ( ) : boolean Commit a transaction
conditionKeysToString ( array $conditions, boolean $quoteValues = true, Model $Model = null ) : string Creates a WHERE clause by parsing given conditions array. Used by DboSource::conditions().
conditions ( mixed $conditions, boolean $quoteValues = true, boolean $where = true, Model $Model = null ) : string 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 ( Model $Model, array $fields = null, array $values = null ) : boolean The "C" in CRUD
createSchema ( CakeSchema $schema, string $tableName = null ) : string Generate a database-native schema for the given Schema object
createTable ( array $options ) : boolean テーブルを作成する
createTableBySchema ( array $options ) : boolean スキーマファイルからテーブルを生成する
defaultConditions ( Model $Model, string | array | boolean $conditions, boolean $useAlias = true ) : mixed Creates a default set of conditions from the model if $conditions is null/empty.
delete ( Model $Model, mixed $conditions = null ) : boolean Generates and executes an SQL DELETE statement.
disconnect ( ) : boolean Disconnects from database.
dropColumn ( array $options ) : boolean カラムを削除する
dropSchema ( CakeSchema $schema, string $table = null ) : string Generate a "drop table" statement for the given Schema object
dropTable ( array $options ) : boolean テーブルを削除する
dropTableBySchema ( $options ) : boolean スキーマファイルからテーブルを削除する
execute ( string $sql, array $options = [], array $params = [] ) : mixed 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.
expression ( string $expression ) : stdClass Returns an object to represent a database expression in a query. Expression objects are not sanitized or escaped.
fetchAll ( string $sql, array | boolean $params = [], array $options = [] ) : boolean | array Returns an array of all result rows for a given SQL query.
fetchAssociated ( Model $Model, string $query, array $ids ) : array Fetch 'hasMany' associations.
fetchResult ( ) : boolean Fetches the next row from the current result set
fetchRow ( string $sql = null ) : array Returns a row from current resultset as an array
fetchVirtualField ( &$result ) : void Modifies $result array to place virtual fields in model entry where they belongs to
field ( string $name, string $sql ) : mixed Returns a single field of the first of query results for a given SQL query, or false if empty.
fields ( Model $Model, string $alias = null, mixed $fields = [], boolean $quote = true ) : array Generates the fields list of an SQL query.
flushMethodCache ( ) : void Empties the method caches.
fullTableName ( Model | string $model, boolean $quote = true, boolean $schema = true ) : string Gets full table name including prefix
generateAssociationQuery ( Model $Model, Model | null $LinkModel, string $type, string $association, array $assocData, &$queryData, boolean $external ) : mixed Generates a query or part of a query from a single model or two associated models.
getConnection ( ) : PDO Get the underlying connection object.
getConstraint ( string $type, Model $Model, Model $LinkModel, string $association, array $assocData, string $association2 = null ) : array Returns a conditions array for the constraint between two models.
getLog ( boolean $sorted = false, boolean $clear = true ) : array Get the query log as an array.
getQueryCache ( string $sql, array $params = [] ) : mixed Returns the result for a sql query if it is already cached
getVersion ( ) : string Gets the version string of the database server
group ( string | array $fields, Model $Model = null ) : string Create a GROUP BY SQL clause.
hasAny ( Model $Model, string $sql ) : boolean Checks if the specified table contains any record matching specified SQL
hasResult ( ) : boolean Checks if the result is valid
identifier ( string $identifier ) : stdClass Returns an object to represent a database identifier in a query. Expression objects are not sanitized or escaped.
index ( string $model ) : array Returns an array of the indexes in given datasource name.
insertMulti ( string $table, array $fields, array $values ) : boolean Inserts multiple values into a table
introspectType ( string $value ) : string Guesses the data type of an array
isConnected ( ) : boolean Checks if the source is connected to the database.
lastAffected ( mixed $source = null ) : integer Returns number of affected rows in previous database operation. If no previous operation exists, this returns false.
lastError ( PDOStatement $query = null ) : string Returns a formatted error message from previous database operation.
lastInsertId ( mixed $source = null ) : mixed Returns the ID generated from the previous INSERT operation.
lastNumRows ( mixed $source = null ) : integer Returns number of rows in previous resultset. If no previous resultset exists, this returns false.
length ( string $real ) : mixed Gets the length of a database-native column description, or null if no length
limit ( integer $limit, integer $offset = null ) : string Returns a limit statement in the correct format for the particular database.
loadCsv ( array $options ) : boolean CSVファイルをDBに読み込む
loadCsvToArray ( string $path, $encoding ) : mixed CSVよりデータを配列として読み込む
loadSchema ( array $options ) : boolean スキーマファイルを利用してテーブルを生成する
logQuery ( string $sql, array $params = [] ) : void Log given SQL query.
name ( mixed $data ) : string Returns a quoted name of $data for use in an SQL statement.
nestedTransactionSupported ( ) : boolean Check if the server support nested transactions
order ( array | string $keys, string $direction = 'ASC', Model $Model = null ) : string Returns an ORDER BY clause as a string.
prepareFields ( Model $Model, array $queryData ) : array Prepares fields required by an SQL statement.
query ( ) : resource DataSource Query abstraction
queryAssociation ( Model $Model, Model $LinkModel, string $type, string $association, array $assocData, &$queryData, boolean $external, &$resultSet, integer $recursive, array $stack ) : mixed Queries associations.
rawQuery ( string $sql, array $params = [] ) : boolean Executes given SQL statement.
read ( Model $Model, array $queryData = [], integer $recursive = null ) : mixed The "R" in CRUD
readSchema ( string $table, $options = [] ) : array データベースよりスキーマ情報を読み込む
readTableParameters ( string $name ) : array Read additional table parameters
reconnect ( array $config = [] ) : boolean Reconnects to database server with optional new settings
renameColumn ( array $options ) : boolean カラム名を変更する
renameTable ( array $options ) : boolean テーブル名をリネームする
renderJoinStatement ( array $data ) : string Renders a final SQL JOIN statement
renderStatement ( string $type, array $data ) : string Renders a final SQL statement by putting together the component parts in the correct order
resetSequence ( string $table, string $column ) : boolean | void Reset a sequence based on the MAX() value of $column. Useful for resetting sequences after using insertMulti().
resolveKey ( Model $Model, string $key, string $assoc = null ) : string Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name)
rollback ( ) : boolean Rollback a transaction
showLog ( boolean $sorted = false ) : void 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 ( Model | string $table ) : boolean Deletes all the records in a table and resets the count of the auto-incrementing primary key, where applicable.
update ( Model $Model, array $fields = [], array $values = null, mixed $conditions = null ) : boolean Generates and executes an SQL UPDATE statement for given model, fields, and values.
value ( string $data, string $column = null ) : string Returns a quoted and escaped string of $data for use in an SQL statement.
writeCsv ( array $options ) : boolean DBのデータをCSVファイルとして書きだす
writeCurrentSchema ( string $filename ) : boolean 現在の接続のスキーマを生成する
writeSchema ( $options ) : mixed モデル名を指定してスキーマファイルを生成する

Méthodes protégées

Méthode Description
_beginNested ( ) : boolean Begin a nested transaction
_buildFieldParameters ( string $columnString, array $columnData, string $position ) : string Build the field parameters, in a position
_commitNested ( ) : boolean Commit a nested transaction
_constructVirtualFields ( Model $Model, string $alias, array $fields ) : array Converts model virtual fields into sql expressions to be fetched later
_convertFieldToCsv ( string $value, boolean $dc = true ) : string CSV用のフィールドデータに変換する
_convertRecordToCsv ( array $record ) : array CSV用のレコードデータに変換する
_dbEncToPhp ( string $enc ) : string DB用エンコーディング名称をPHP用エンコーディング名称に変換する
_dropTable ( type $table ) : string Generate a "drop table" statement for a single table
_execute ( string $sql, array $params = [], array $prepareOptions = [] ) : mixed Executes given SQL statement.
_fetchHasAndBelongsToMany ( Model $Model, string $query, array $ids, string $association ) : array Fetch 'hasAndBelongsToMany' associations.
_fetchHasMany ( Model $Model, string $query, array $ids ) : array Fetch 'hasMany' associations.
_filterResults ( &$resultSet, Model $Model, array $filtered = [] ) : array Passes association results through afterFind filters of the corresponding model.
_getJoins ( Model $Model ) : array Returns an array of SQL JOIN conditions from a model's associations.
_matchRecords ( Model $Model, mixed $conditions = null ) : array 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 ( &$data, &$merge, string $association, string $type, boolean $selfJoin = false ) : void Merge association of merge into data
_mergeConditions ( mixed $query, mixed $assoc ) : array Merges a mixed set of string/array conditions.
_mergeHasMany ( &$resultSet, array $assocResultSet, string $association, Model $Model ) : void Merge the results of 'hasMany' associations.
_parseKey ( string $key, mixed $value, Model $Model = null ) : string Extracts a Model.field identifier and an SQL condition operator from a string, formats and inserts values, and composes them into an SQL snippet.
_phpEncToDb ( string $enc ) : string PHP用エンコーディング名称をDB用のエンコーディング名称に変換する
_prepareUpdateFields ( Model $Model, array $fields, boolean $quoteValues = true, boolean $alias = false ) : array Quotes and prepares fields and values for an SQL UPDATE statement
_quoteFields ( string $conditions ) : string Quotes Model.fields
_quoteMatchedField ( string $match ) : string Auxiliary function to quote matches Model.fields from a preg_replace_callback call
_rollbackNested ( ) : boolean Rollback a nested transaction
_scrubQueryData ( array $data ) : array Private helper method to remove query metadata in given data array.
_writeQueryCache ( string $sql, mixed $data, array $params = [] ) : void Writes a new key for the in memory sql query cache

Method Details

__construct() public méthode

Constructor
public __construct ( array $config = null, boolean $autoConnect = true )
$config array Array of configuration information for the Datasource.
$autoConnect boolean Whether or not the datasource should automatically connect.

__destruct() public méthode

Used for storing in cache the results of the in-memory methodCache
public __destruct ( )

_beginNested() protected méthode

Begin a nested transaction
protected _beginNested ( ) : boolean
Résultat boolean

_buildFieldParameters() protected méthode

Build the field parameters, in a position
protected _buildFieldParameters ( string $columnString, array $columnData, string $position ) : string
$columnString string The partially built column string
$columnData array The array of column data.
$position string The position type to use. 'beforeDefault' or 'afterDefault' are common
Résultat string a built column with the field parameters added.

_commitNested() protected méthode

Commit a nested transaction
protected _commitNested ( ) : boolean
Résultat boolean

_constructVirtualFields() protected méthode

Converts model virtual fields into sql expressions to be fetched later
protected _constructVirtualFields ( Model $Model, string $alias, array $fields ) : array
$Model Model The model to get virtual fields for.
$alias string Alias table name
$fields array virtual fields to be used on query
Résultat array

_convertFieldToCsv() protected méthode

CSV用のフィールドデータに変換する
protected _convertFieldToCsv ( string $value, boolean $dc = true ) : string
$value string
$dc boolean ( " を "" に変換するか)
Résultat string

_convertRecordToCsv() protected méthode

CSV用のレコードデータに変換する
protected _convertRecordToCsv ( array $record ) : array
$record array
Résultat array

_dbEncToPhp() protected méthode

DB用エンコーディング名称をPHP用エンコーディング名称に変換する
protected _dbEncToPhp ( string $enc ) : string
$enc string
Résultat string

_dropTable() protected méthode

Generate a "drop table" statement for a single table
protected _dropTable ( type $table ) : string
$table type Name of the table to drop
Résultat string Drop table SQL statement

_execute() protected méthode

Executes given SQL statement.
protected _execute ( string $sql, array $params = [], array $prepareOptions = [] ) : mixed
$sql string SQL statement
$params array list of params to be bound to query
$prepareOptions array Options to be used in the prepare statement
Résultat mixed PDOStatement if query executes with no problem, true as the result of a successful, false on error query returning no rows, such as a CREATE statement, false otherwise

_fetchHasAndBelongsToMany() protected méthode

Fetch 'hasAndBelongsToMany' associations.
protected _fetchHasAndBelongsToMany ( Model $Model, string $query, array $ids, string $association ) : array
$Model Model Primary model object.
$query string Association query.
$ids array Array of IDs of associated records.
$association string Association name.
Résultat array Association results.

_fetchHasMany() protected méthode

Fetch 'hasMany' associations.
protected _fetchHasMany ( Model $Model, string $query, array $ids ) : array
$Model Model Primary model object.
$query string Association query template.
$ids array Array of IDs of associated records.
Résultat array Association results.

_filterResults() protected méthode

The primary model is always excluded, because the filtering is later done by Model::_filterResults().
protected _filterResults ( &$resultSet, Model $Model, array $filtered = [] ) : array
$Model Model Instance of model to operate against.
$filtered array List of classes already filtered, to be skipped.
Résultat array Array of results that have been filtered through $Model->afterFind.

_getJoins() protected méthode

Returns an array of SQL JOIN conditions from a model's associations.
protected _getJoins ( Model $Model ) : array
$Model Model The model to get joins for.2
Résultat array

_matchRecords() protected méthode

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.
protected _matchRecords ( Model $Model, mixed $conditions = null ) : array
$Model Model The model to find matching records for.
$conditions mixed The conditions to match against.
Résultat array List of record IDs

_mergeAssociation() protected méthode

Merge association of merge into data
protected _mergeAssociation ( &$data, &$merge, string $association, string $type, boolean $selfJoin = false ) : void
$association string The association name to merge.
$type string The type of association
$selfJoin boolean Whether or not this is a self join.
Résultat void

_mergeConditions() protected méthode

Merges a mixed set of string/array conditions.
protected _mergeConditions ( mixed $query, mixed $assoc ) : array
$query mixed The query to merge conditions for.
$assoc mixed The association names.
Résultat array

_mergeHasMany() protected méthode

Note: this function also deals with the formatting of the data.
protected _mergeHasMany ( &$resultSet, array $assocResultSet, string $association, Model $Model ) : void
$assocResultSet array Data to merge.
$association string Name of Model being merged.
$Model Model Model being merged onto.
Résultat void

_parseKey() protected méthode

Extracts a Model.field identifier and an SQL condition operator from a string, formats and inserts values, and composes them into an SQL snippet.
protected _parseKey ( string $key, mixed $value, Model $Model = null ) : string
$key string An SQL key snippet containing a field and optional SQL operator
$value mixed The value(s) to be inserted in the string
$Model Model Model object initiating the query
Résultat string

_phpEncToDb() protected méthode

PHP用エンコーディング名称をDB用のエンコーディング名称に変換する
protected _phpEncToDb ( string $enc ) : string
$enc string
Résultat string

_prepareUpdateFields() protected méthode

Quotes and prepares fields and values for an SQL UPDATE statement
protected _prepareUpdateFields ( Model $Model, array $fields, boolean $quoteValues = true, boolean $alias = false ) : array
$Model Model The model to prepare fields for.
$fields array The fields to update.
$quoteValues boolean If values should be quoted, or treated as SQL snippets
$alias boolean Include the model alias in the field name
Résultat array Fields and values, quoted and prepared

_quoteFields() protected méthode

Quotes Model.fields
protected _quoteFields ( string $conditions ) : string
$conditions string The conditions to quote.
Résultat string or false if no match

_quoteMatchedField() protected méthode

Auxiliary function to quote matches Model.fields from a preg_replace_callback call
protected _quoteMatchedField ( string $match ) : string
$match string matched string
Résultat string quoted string

_rollbackNested() protected méthode

Rollback a nested transaction
protected _rollbackNested ( ) : boolean
Résultat boolean

_scrubQueryData() protected méthode

Private helper method to remove query metadata in given data array.
protected _scrubQueryData ( array $data ) : array
$data array The data to scrub.
Résultat array

_writeQueryCache() protected méthode

Writes a new key for the in memory sql query cache
protected _writeQueryCache ( string $sql, mixed $data, array $params = [] ) : void
$sql string SQL query
$data mixed result of $sql query
$params array query params bound as values
Résultat void

addColumn() public méthode

カラムを追加する
public addColumn ( array $options ) : boolean
$options array [ table / column ]
Résultat boolean

alterSchema() public méthode

Generate a alter syntax from CakeSchema::compare()
public alterSchema ( mixed $compare, string $table = null ) : boolean
$compare mixed The comparison data.
$table string The table name.
Résultat boolean

alterTable() public méthode

テーブル構造を変更する
public alterTable ( array $options ) : boolean
$options array [ new / old ]
Résultat boolean

alterTableBySchema() public méthode

スキーマファイルからテーブル構造を変更する
public alterTableBySchema ( array $options ) : boolean
$options array [ oldPath / newPath ]
Résultat boolean

begin() public méthode

Begin a transaction
public begin ( ) : boolean
Résultat boolean True on success, false on fail (i.e. if the database/model does not support transactions, or a transaction has not started).

boolean() public méthode

Translates between PHP boolean values and Database (faked) boolean values
public boolean ( mixed $data, boolean $quote = false ) : string | boolean
$data mixed Value to be translated
$quote boolean Whether or not the field should be cast to a string.
Résultat string | boolean Converted boolean value

buildAssociationQuery() public méthode

This is merely a convenient wrapper to DboSource::buildStatement().
See also: DboSource::buildStatement()
public buildAssociationQuery ( Model $Model, array $queryData ) : string
$Model Model The model to build an association query for.
$queryData array An array of queryData information containing keys similar to Model::find().
Résultat string String containing an SQL statement.

buildColumn() public méthode

Generate a database-native column schema string
public buildColumn ( array $column ) : string
$column array An array structured like the following: array('name' => 'value', 'type' => 'value'[, options]), where options can be 'default', 'length', or 'key'.
Résultat string

buildIndex() public méthode

Format indexes for create table.
public buildIndex ( array $indexes, string $table = null ) : array
$indexes array The indexes to build
$table string The table name.
Résultat array

buildJoinStatement() public méthode

Builds and generates a JOIN condition from an array. Handles final clean-up before conversion.
See also: DboSource::renderJoinStatement()
See also: DboSource::buildStatement()
public buildJoinStatement ( array $join ) : string
$join array An array defining a JOIN condition in a query.
Résultat string An SQL JOIN condition to be used in a query.

buildRenameTable() public méthode

テーブル名のリネームステートメントを生成
public buildRenameTable ( string $sourceName, string $targetName ) : string
$sourceName string
$targetName string
Résultat string

buildStatement() public méthode

Builds and generates an SQL statement from an array. Handles final clean-up before conversion.
See also: DboSource::renderStatement()
public buildStatement ( array $query, Model $Model ) : string
$query array An array defining an SQL query.
$Model Model The model object which initiated the query.
Résultat string An executable SQL statement.

buildTableParameters() public méthode

Format parameters for create table
public buildTableParameters ( array $parameters, string $table = null ) : array
$parameters array The parameters to create SQL for.
$table string The table name.
Résultat array

cacheMethod() public méthode

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.
public cacheMethod ( string $method, string $key, mixed $value = null ) : mixed
$method string Name of the method being cached.
$key string The key name for the cache operation.
$value mixed The value to cache into memory.
Résultat mixed Either null on failure, or the value if its set.

calculate() public méthode

Returns an SQL calculation, i.e. COUNT() or MAX()
public calculate ( Model $Model, string $func, array $params = [] ) : string
$Model Model The model to get a calculated field for.
$func string Lowercase name of SQL function, i.e. 'count' or 'max'
$params array Function parameters (any values must be quoted manually)
Résultat string An SQL calculation function

changeColumn() public méthode

カラムを変更する
public changeColumn ( array $options ) : boolean
$options array [ table / column / field ]
Résultat boolean

close() public méthode

Disconnects database, kills the connection and says the connection is closed.
public close ( ) : void
Résultat void

commit() public méthode

Commit a transaction
public commit ( ) : boolean
Résultat boolean True on success, false on fail (i.e. if the database/model does not support transactions, or a transaction has not started).

conditionKeysToString() public méthode

Creates a WHERE clause by parsing given conditions array. Used by DboSource::conditions().
public conditionKeysToString ( array $conditions, boolean $quoteValues = true, Model $Model = null ) : string
$conditions array Array or string of conditions
$quoteValues boolean If true, values should be quoted
$Model Model A reference to the Model instance making the query
Résultat string SQL fragment

conditions() public méthode

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.
public conditions ( mixed $conditions, boolean $quoteValues = true, boolean $where = true, Model $Model = null ) : string
$conditions mixed Array or string of conditions, or any value.
$quoteValues boolean If true, values should be quoted
$where boolean If true, "WHERE " will be prepended to the return value
$Model Model A reference to the Model instance making the query
Résultat string SQL fragment

create() public méthode

Creates new records in the database.
public create ( Model $Model, array $fields = null, array $values = null ) : boolean
$Model Model Model object that the record is for.
$fields array An array of field names to insert. If null, $Model->data will be used to generate field names.
$values array An array of values with keys matching the fields. If null, $Model->data will be used to generate values.
Résultat boolean Success

createSchema() public méthode

Generate a database-native schema for the given Schema object
public createSchema ( CakeSchema $schema, string $tableName = null ) : string
$schema CakeSchema An instance of a subclass of CakeSchema
$tableName string Optional. If specified only the table name given will be generated. Otherwise, all tables defined in the schema are generated.
Résultat string

createTable() public méthode

テーブルを作成する
public createTable ( array $options ) : boolean
$options array [ schema / table ]
Résultat boolean

createTableBySchema() public méthode

スキーマファイルからテーブルを生成する
public createTableBySchema ( array $options ) : boolean
$options array [ path ]
Résultat boolean

defaultConditions() public méthode

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.
See also: DboSource::update()
See also: DboSource::conditions()
public defaultConditions ( Model $Model, string | array | boolean $conditions, boolean $useAlias = true ) : mixed
$Model Model The model to get conditions for.
$conditions string | array | boolean Array of conditions, conditions string, null or false. If an array of conditions, or string conditions those conditions will be returned. With other values the model's existence will be checked. If the model doesn't exist a null or false will be returned depending on the input value.
$useAlias boolean Use model aliases rather than table names when generating conditions
Résultat mixed Either null, false, $conditions or an array of default conditions to use.

delete() public méthode

For databases that do not support aliases in UPDATE queries.
public delete ( Model $Model, mixed $conditions = null ) : boolean
$Model Model The model to delete from
$conditions mixed The conditions to use. If empty the model's primary key will be used.
Résultat boolean Success

disconnect() public méthode

Disconnects from database.
public disconnect ( ) : boolean
Résultat boolean Always true

dropColumn() public méthode

カラムを削除する
public dropColumn ( array $options ) : boolean
$options array [ table / field ]
Résultat boolean

dropSchema() public méthode

Generate a "drop table" statement for the given Schema object
public dropSchema ( CakeSchema $schema, string $table = null ) : string
$schema CakeSchema An instance of a subclass of CakeSchema
$table string Optional. If specified only the table name given will be generated. Otherwise, all tables defined in the schema are generated.
Résultat string

dropTable() public méthode

テーブルを削除する
public dropTable ( array $options ) : boolean
$options array [ schema / table ]
Résultat boolean

dropTableBySchema() public méthode

スキーマファイルからテーブルを削除する
public dropTableBySchema ( $options ) : boolean
Résultat boolean

execute() public méthode

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.
public execute ( string $sql, array $options = [], array $params = [] ) : mixed
$sql string SQL statement
$options array The options for executing the query.
$params array values to be bound to the query.
Résultat mixed Resource or object representing the result set, or false on failure

expression() public méthode

Returns an object to represent a database expression in a query. Expression objects are not sanitized or escaped.
public expression ( string $expression ) : stdClass
$expression string An arbitrary SQL expression to be inserted into a query.
Résultat stdClass An object representing a database expression to be used in a query

fetchAll() public méthode

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 to false
public fetchAll ( string $sql, array | boolean $params = [], array $options = [] ) : boolean | array
$sql string SQL statement
$params array | boolean Either parameters to be bound as values for the SQL statement, or a boolean to control query caching.
$options array additional options for the query.
Résultat boolean | array Array of resultset rows, or false if no rows matched

fetchAssociated() public méthode

This is just a proxy to maintain BC.
See also: DboSource::_fetchHasMany()
public fetchAssociated ( Model $Model, string $query, array $ids ) : array
$Model Model Primary model object.
$query string Association query template.
$ids array Array of IDs of associated records.
Résultat array Association results.

fetchResult() public méthode

Fetches the next row from the current result set
public fetchResult ( ) : boolean
Résultat boolean

fetchRow() public méthode

Returns a row from current resultset as an array
public fetchRow ( string $sql = null ) : array
$sql string Some SQL to be executed.
Résultat array The fetched row as an array

fetchVirtualField() public méthode

Modifies $result array to place virtual fields in model entry where they belongs to
public fetchVirtualField ( &$result ) : void
Résultat void

field() public méthode

Returns a single field of the first of query results for a given SQL query, or false if empty.
public field ( string $name, string $sql ) : mixed
$name string Name of the field
$sql string SQL query
Résultat mixed Value of field read.

fields() public méthode

Generates the fields list of an SQL query.
public fields ( Model $Model, string $alias = null, mixed $fields = [], boolean $quote = true ) : array
$Model Model The model to get fields for.
$alias string Alias table name
$fields mixed The provided list of fields.
$quote boolean If false, returns fields array unquoted
Résultat array

flushMethodCache() public méthode

These caches are used by DboSource::name() and DboSource::conditions()
public flushMethodCache ( ) : void
Résultat void

fullTableName() public méthode

Gets full table name including prefix
public fullTableName ( Model | string $model, boolean $quote = true, boolean $schema = true ) : string
$model Model | string Either a Model object or a string table name.
$quote boolean Whether you want the table name quoted.
$schema boolean Whether you want the schema name included.
Résultat string Full quoted table name

generateAssociationQuery() public méthode

Builds a string containing an SQL statement template.
public generateAssociationQuery ( Model $Model, Model | null $LinkModel, string $type, string $association, array $assocData, &$queryData, boolean $external ) : mixed
$Model Model Primary Model object.
$LinkModel Model | null Linked model object.
$type string Association type, one of the model association types ie. hasMany.
$association string Association name.
$assocData array Association data.
$external boolean Whether or not the association query is on an external datasource.
Résultat mixed String representing a query. True, when $external is false and association $type is 'hasOne' or 'belongsTo'.

getConnection() public méthode

Get the underlying connection object.
public getConnection ( ) : PDO
Résultat PDO

getConstraint() public méthode

Returns a conditions array for the constraint between two models.
public getConstraint ( string $type, Model $Model, Model $LinkModel, string $association, array $assocData, string $association2 = null ) : array
$type string Association type.
$Model Model Primary Model object.
$LinkModel Model Linked model object.
$association string Association name.
$assocData array Association data.
$association2 string HABTM association name.
Résultat array Conditions array defining the constraint between $Model and $LinkModel.

getLog() public méthode

Get the query log as an array.
public getLog ( boolean $sorted = false, boolean $clear = true ) : array
$sorted boolean Get the queries sorted by time taken, defaults to false.
$clear boolean If True the existing log will cleared.
Résultat array Array of queries run as an array

getQueryCache() public méthode

Returns the result for a sql query if it is already cached
public getQueryCache ( string $sql, array $params = [] ) : mixed
$sql string SQL query
$params array query params bound as values
Résultat mixed results for query if it is cached, false otherwise

getVersion() public méthode

Gets the version string of the database server
public getVersion ( ) : string
Résultat string The database version

group() public méthode

Create a GROUP BY SQL clause.
public group ( string | array $fields, Model $Model = null ) : string
$fields string | array Group By fields
$Model Model The model to get group by fields for.
Résultat string Group By clause or null.

hasAny() public méthode

Checks if the specified table contains any record matching specified SQL
public hasAny ( Model $Model, string $sql ) : boolean
$Model Model Model to search
$sql string SQL WHERE clause (condition only, not the "WHERE" part)
Résultat boolean True if the table has a matching record, else false

hasResult() public méthode

Checks if the result is valid
public hasResult ( ) : boolean
Résultat boolean True if the result is valid else false

identifier() public méthode

Returns an object to represent a database identifier in a query. Expression objects are not sanitized or escaped.
public identifier ( string $identifier ) : stdClass
$identifier string A SQL expression to be used as an identifier
Résultat stdClass An object representing a database identifier to be used in a query

index() public méthode

Returns an array of the indexes in given datasource name.
public index ( string $model ) : array
$model string Name of model to inspect
Résultat array Fields in table. Keys are column and unique

insertMulti() public méthode

Inserts multiple values into a table
public insertMulti ( string $table, array $fields, array $values ) : boolean
$table string The table being inserted into.
$fields array The array of field/column names being inserted.
$values array 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.
Résultat boolean

introspectType() public méthode

Guesses the data type of an array
public introspectType ( string $value ) : string
$value string The value to introspect for type data.
Résultat string

isConnected() public méthode

Checks if the source is connected to the database.
public isConnected ( ) : boolean
Résultat boolean True if the database is connected, else false

lastAffected() public méthode

Returns number of affected rows in previous database operation. If no previous operation exists, this returns false.
public lastAffected ( mixed $source = null ) : integer
$source mixed The source to check.
Résultat integer Number of affected rows

lastError() public méthode

Returns a formatted error message from previous database operation.
public lastError ( PDOStatement $query = null ) : string
$query PDOStatement the query to extract the error from if any
Résultat string Error message with error number

lastInsertId() public méthode

Returns the ID generated from the previous INSERT operation.
public lastInsertId ( mixed $source = null ) : mixed
$source mixed The source to get an id for.
Résultat mixed

lastNumRows() public méthode

Returns number of rows in previous resultset. If no previous resultset exists, this returns false.
public lastNumRows ( mixed $source = null ) : integer
$source mixed Not used
Résultat integer Number of rows in resultset

length() public méthode

Gets the length of a database-native column description, or null if no length
public length ( string $real ) : mixed
$real string Real database-layer column type (i.e. "varchar(255)")
Résultat mixed An integer or string representing the length of the column, or null for unknown length.

limit() public méthode

Returns a limit statement in the correct format for the particular database.
public limit ( integer $limit, integer $offset = null ) : string
$limit integer Limit of results returned
$offset integer Offset from which to start results
Résultat string SQL limit/offset statement

loadCsv() public méthode

CSVファイルをDBに読み込む
public loadCsv ( array $options ) : boolean
$options array [ path / encoding ]
Résultat boolean

loadCsvToArray() public méthode

CSVよりデータを配列として読み込む
public loadCsvToArray ( string $path, $encoding ) : mixed
$path string
Résultat mixed boolean Or array

loadSchema() public méthode

スキーマファイルを利用してテーブルを生成する
public loadSchema ( array $options ) : boolean
$options array path は必須
Résultat boolean

logQuery() public méthode

Log given SQL query.
public logQuery ( string $sql, array $params = [] ) : void
$sql string SQL statement
$params array Values binded to the query (prepared statements)
Résultat void

name() public méthode

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.
public name ( mixed $data ) : string
$data mixed Either a string with a column to quote. An array of columns to quote or an object from DboSource::expression() or DboSource::identifier()
Résultat string SQL field

nestedTransactionSupported() public méthode

Check if the server support nested transactions
public nestedTransactionSupported ( ) : boolean
Résultat boolean

order() public méthode

Returns an ORDER BY clause as a string.
public order ( array | string $keys, string $direction = 'ASC', Model $Model = null ) : string
$keys array | string Field reference, as a key (i.e. Post.title)
$direction string Direction (ASC or DESC)
$Model Model Model reference (used to look for virtual field)
Résultat string ORDER BY clause

prepareFields() public méthode

When no fields are set, all the $Model fields are returned.
public prepareFields ( Model $Model, array $queryData ) : array
$Model Model The model to prepare.
$queryData array An array of queryData information containing keys similar to Model::find().
Résultat array Array containing SQL fields.

query() public méthode

DataSource Query abstraction
public query ( ) : resource
Résultat resource Result resource identifier.

queryAssociation() public méthode

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.
public queryAssociation ( Model $Model, Model $LinkModel, string $type, string $association, array $assocData, &$queryData, boolean $external, &$resultSet, integer $recursive, array $stack ) : mixed
$Model Model Primary Model object.
$LinkModel Model Linked model object.
$type string Association type, one of the model association types ie. hasMany.
$association string Association name.
$assocData array Association data.
$external boolean Whether or not the association query is on an external datasource.
$recursive integer Number of levels of association.
$stack array A list with joined models.
Résultat mixed

rawQuery() public méthode

Executes given SQL statement.
public rawQuery ( string $sql, array $params = [] ) : boolean
$sql string SQL statement
$params array Additional options for the query.
Résultat boolean

read() public méthode

Reads record(s) from the database.
public read ( Model $Model, array $queryData = [], integer $recursive = null ) : mixed
$Model Model A Model object that the query is for.
$queryData array An array of queryData information containing keys similar to Model::find().
$recursive integer Number of levels of association
Résultat mixed boolean false on error/failure. An array of results on success.

readSchema() public méthode

データベースよりスキーマ情報を読み込む
public readSchema ( string $table, $options = [] ) : array
$table string
Résultat array $schema

readTableParameters() public méthode

Read additional table parameters
public readTableParameters ( string $name ) : array
$name string The table name to read.
Résultat array

reconnect() public méthode

Reconnects to database server with optional new settings
public reconnect ( array $config = [] ) : boolean
$config array An array defining the new configuration settings
Résultat boolean True on success, false on failure

renameColumn() public méthode

カラム名を変更する
public renameColumn ( array $options ) : boolean
$options array [ table / new / old ]
Résultat boolean

renameTable() public méthode

テーブル名をリネームする
public renameTable ( array $options ) : boolean
$options array [ old / new ]
Résultat boolean

renderJoinStatement() public méthode

Renders a final SQL JOIN statement
public renderJoinStatement ( array $data ) : string
$data array The data to generate a join statement for.
Résultat string

renderStatement() public méthode

Renders a final SQL statement by putting together the component parts in the correct order
public renderStatement ( string $type, array $data ) : string
$type string type of query being run. e.g select, create, update, delete, schema, alter.
$data array Array of data to insert into the query.
Résultat string Rendered SQL expression to be run.

resetSequence() public méthode

This method should be implemented by datasources that require sequences to be used.
public resetSequence ( string $table, string $column ) : boolean | void
$table string The name of the table to update.
$column string The column to use when resetting the sequence value.
Résultat boolean | void success.

resolveKey() public méthode

Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name)
public resolveKey ( Model $Model, string $key, string $assoc = null ) : string
$Model Model The model to get a key for.
$key string The key field.
$assoc string The association name.
Résultat string

rollback() public méthode

Rollback a transaction
public rollback ( ) : boolean
Résultat boolean True on success, false on fail (i.e. if the database/model does not support transactions, or a transaction has not started).

showLog() public méthode

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.
public showLog ( boolean $sorted = false ) : void
$sorted boolean Get the queries sorted by time taken, defaults to false.
Résultat void

truncate() public méthode

Deletes all the records in a table and resets the count of the auto-incrementing primary key, where applicable.
public truncate ( Model | string $table ) : boolean
$table Model | string A string or model class representing the table to be truncated
Résultat boolean SQL TRUNCATE TABLE statement, false if not applicable.

update() public méthode

For databases that do not support aliases in UPDATE queries.
public update ( Model $Model, array $fields = [], array $values = null, mixed $conditions = null ) : boolean
$Model Model The model to update.
$fields array The fields to update
$values array The values fo the fields.
$conditions mixed The conditions for the update. When non-empty $values will not be quoted.
Résultat boolean Success

value() public méthode

Returns a quoted and escaped string of $data for use in an SQL statement.
public value ( string $data, string $column = null ) : string
$data string String to be prepared for use in an SQL statement
$column string The column datatype into which this data will be inserted.
Résultat string Quoted and escaped data

writeCsv() public méthode

DBのデータをCSVファイルとして書きだす
public writeCsv ( array $options ) : boolean
$options array [ path / table / encoding ]
Résultat boolean

writeCurrentSchema() public méthode

現在の接続のスキーマを生成する
public writeCurrentSchema ( string $filename ) : boolean
$filename string 保存先のフルパス
Résultat boolean

writeSchema() public méthode

モデル名を指定してスキーマファイルを生成する
public writeSchema ( $options ) : mixed
Résultat mixed スキーマファイルの内容 Or false

Property Details

$_connection protected_oe property

A reference to the physical connection of this DataSource
protected array $_connection
Résultat array

$_encodingMaps protected_oe property

PHP←→DBエンコーディングマップ
protected array $_encodingMaps
Résultat array

$_methodCacheChange protected_oe property

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
protected bool $_methodCacheChange
Résultat boolean

$_queriesCnt protected_oe property

Queries count.
protected int $_queriesCnt
Résultat integer

$_queriesLog protected_oe property

Log of queries executed by this DataSource
protected array $_queriesLog
Résultat array

$_queriesLogMax protected_oe property

This is to prevent query log taking over too much memory.
protected int $_queriesLogMax
Résultat integer

$_queriesTime protected_oe property

Total duration of all queries.
protected int $_queriesTime
Résultat integer

$_queryCache protected_oe property

Caches serialized results of executed queries
protected array $_queryCache
Résultat array

$_queryDefaults protected_oe property

Default fields that are used by the DBO
protected array $_queryDefaults
Résultat array

$_result protected_oe property

Result
protected array $_result
Résultat array

$_sqlOps protected_oe property

The set of valid SQL operations usable in a WHERE statement
protected array $_sqlOps
Résultat array

$_transactionNesting protected_oe property

Indicates the level of nested transactions
protected int $_transactionNesting
Résultat integer

$affected public_oe property

String to hold how many rows were affected by the last SQL operation.
public string $affected
Résultat string

$alias public_oe property

Database keyword used to assign aliases to identifiers.
public string $alias
Résultat string

$cacheMethods public_oe property

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.
public bool $cacheMethods
Résultat boolean

$configKeyName public_oe property

The DataSource configuration key name
public string $configKeyName
Résultat string

$description public_oe property

Description string for this Database Data Source.
public string $description
Résultat string

$endQuote public_oe property

The ending character that this DataSource uses for quoted identifiers.
public string $endQuote
Résultat string

$fieldParameters public_oe property

List of engine specific additional field parameters used on table creating
public array $fieldParameters
Résultat array

$fullDebug public_oe property

Print full query debug info?
public bool $fullDebug
Résultat boolean

$index public_oe property

index definition, standard cake, primary, index, unique
public array $index
Résultat array

$methodCache public_oe static_oe property

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.
public static array $methodCache
Résultat array

$numRows public_oe property

Number of rows in current resultset
public int $numRows
Résultat integer

$startQuote public_oe property

The starting character that this DataSource uses for quoted identifiers.
public string $startQuote
Résultat string

$tableParameters public_oe property

List of table engine specific parameters used on table creating
public array $tableParameters
Résultat array

$took public_oe property

Time the last query took
public int $took
Résultat integer

$useNestedTransactions public_oe property

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.
public bool $useNestedTransactions
Résultat boolean

$virtualFieldSeparator public_oe property

Separator string for virtualField composition
public string $virtualFieldSeparator
Résultat string