PHP Класс DboSource

Creates DBO-descendant objects from a given db connection configuration
Наследование: extends DataSource
Показать файл Открыть проект Примеры использования класса

Открытые свойства

Свойство Тип Описание
$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)

Свойство Тип Описание
$_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

Открытые методы

Метод Описание
__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 モデル名を指定してスキーマファイルを生成する

Защищенные методы

Метод Описание
_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

Описание методов

__construct() публичный Метод

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() публичный Метод

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

_beginNested() защищенный Метод

Begin a nested transaction
protected _beginNested ( ) : boolean
Результат boolean

_buildFieldParameters() защищенный Метод

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
Результат string a built column with the field parameters added.

_commitNested() защищенный Метод

Commit a nested transaction
protected _commitNested ( ) : boolean
Результат boolean

_constructVirtualFields() защищенный Метод

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
Результат array

_convertFieldToCsv() защищенный Метод

CSV用のフィールドデータに変換する
protected _convertFieldToCsv ( string $value, boolean $dc = true ) : string
$value string
$dc boolean ( " を "" に変換するか)
Результат string

_convertRecordToCsv() защищенный Метод

CSV用のレコードデータに変換する
protected _convertRecordToCsv ( array $record ) : array
$record array
Результат array

_dbEncToPhp() защищенный Метод

DB用エンコーディング名称をPHP用エンコーディング名称に変換する
protected _dbEncToPhp ( string $enc ) : string
$enc string
Результат string

_dropTable() защищенный Метод

Generate a "drop table" statement for a single table
protected _dropTable ( type $table ) : string
$table type Name of the table to drop
Результат string Drop table SQL statement

_execute() защищенный Метод

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
Результат 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() защищенный Метод

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.
Результат array Association results.

_fetchHasMany() защищенный Метод

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.
Результат array Association results.

_filterResults() защищенный Метод

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.
Результат array Array of results that have been filtered through $Model->afterFind.

_getJoins() защищенный Метод

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
Результат array

_matchRecords() защищенный Метод

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.
Результат array List of record IDs

_mergeAssociation() защищенный Метод

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.
Результат void

_mergeConditions() защищенный Метод

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.
Результат array

_mergeHasMany() защищенный Метод

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.
Результат void

_parseKey() защищенный Метод

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
Результат string

_phpEncToDb() защищенный Метод

PHP用エンコーディング名称をDB用のエンコーディング名称に変換する
protected _phpEncToDb ( string $enc ) : string
$enc string
Результат string

_prepareUpdateFields() защищенный Метод

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
Результат array Fields and values, quoted and prepared

_quoteFields() защищенный Метод

Quotes Model.fields
protected _quoteFields ( string $conditions ) : string
$conditions string The conditions to quote.
Результат string or false if no match

_quoteMatchedField() защищенный Метод

Auxiliary function to quote matches Model.fields from a preg_replace_callback call
protected _quoteMatchedField ( string $match ) : string
$match string matched string
Результат string quoted string

_rollbackNested() защищенный Метод

Rollback a nested transaction
protected _rollbackNested ( ) : boolean
Результат boolean

_scrubQueryData() защищенный Метод

Private helper method to remove query metadata in given data array.
protected _scrubQueryData ( array $data ) : array
$data array The data to scrub.
Результат array

_writeQueryCache() защищенный Метод

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
Результат void

addColumn() публичный Метод

カラムを追加する
public addColumn ( array $options ) : boolean
$options array [ table / column ]
Результат boolean

alterSchema() публичный Метод

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.
Результат boolean

alterTable() публичный Метод

テーブル構造を変更する
public alterTable ( array $options ) : boolean
$options array [ new / old ]
Результат boolean

alterTableBySchema() публичный Метод

スキーマファイルからテーブル構造を変更する
public alterTableBySchema ( array $options ) : boolean
$options array [ oldPath / newPath ]
Результат boolean

begin() публичный Метод

Begin a transaction
public begin ( ) : boolean
Результат boolean True on success, false on fail (i.e. if the database/model does not support transactions, or a transaction has not started).

boolean() публичный Метод

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.
Результат string | boolean Converted boolean value

buildAssociationQuery() публичный Метод

This is merely a convenient wrapper to DboSource::buildStatement().
См. также: 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().
Результат string String containing an SQL statement.

buildColumn() публичный Метод

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'.
Результат string

buildIndex() публичный Метод

Format indexes for create table.
public buildIndex ( array $indexes, string $table = null ) : array
$indexes array The indexes to build
$table string The table name.
Результат array

buildJoinStatement() публичный Метод

Builds and generates a JOIN condition from an array. Handles final clean-up before conversion.
См. также: DboSource::renderJoinStatement()
См. также: DboSource::buildStatement()
public buildJoinStatement ( array $join ) : string
$join array An array defining a JOIN condition in a query.
Результат string An SQL JOIN condition to be used in a query.

buildRenameTable() публичный Метод

テーブル名のリネームステートメントを生成
public buildRenameTable ( string $sourceName, string $targetName ) : string
$sourceName string
$targetName string
Результат string

buildStatement() публичный Метод

Builds and generates an SQL statement from an array. Handles final clean-up before conversion.
См. также: 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.
Результат string An executable SQL statement.

buildTableParameters() публичный Метод

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.
Результат array

cacheMethod() публичный Метод

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.
Результат mixed Either null on failure, or the value if its set.

calculate() публичный Метод

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)
Результат string An SQL calculation function

changeColumn() публичный Метод

カラムを変更する
public changeColumn ( array $options ) : boolean
$options array [ table / column / field ]
Результат boolean

close() публичный Метод

Disconnects database, kills the connection and says the connection is closed.
public close ( ) : void
Результат void

commit() публичный Метод

Commit a transaction
public commit ( ) : boolean
Результат boolean True on success, false on fail (i.e. if the database/model does not support transactions, or a transaction has not started).

conditionKeysToString() публичный Метод

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
Результат string SQL fragment

conditions() публичный Метод

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
Результат string SQL fragment

create() публичный Метод

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.
Результат boolean Success

createSchema() публичный Метод

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.
Результат string

createTable() публичный Метод

テーブルを作成する
public createTable ( array $options ) : boolean
$options array [ schema / table ]
Результат boolean

createTableBySchema() публичный Метод

スキーマファイルからテーブルを生成する
public createTableBySchema ( array $options ) : boolean
$options array [ path ]
Результат boolean

defaultConditions() публичный Метод

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.
См. также: DboSource::update()
См. также: 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
Результат mixed Either null, false, $conditions or an array of default conditions to use.

delete() публичный Метод

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.
Результат boolean Success

disconnect() публичный Метод

Disconnects from database.
public disconnect ( ) : boolean
Результат boolean Always true

dropColumn() публичный Метод

カラムを削除する
public dropColumn ( array $options ) : boolean
$options array [ table / field ]
Результат boolean

dropSchema() публичный Метод

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.
Результат string

dropTable() публичный Метод

テーブルを削除する
public dropTable ( array $options ) : boolean
$options array [ schema / table ]
Результат boolean

dropTableBySchema() публичный Метод

スキーマファイルからテーブルを削除する
public dropTableBySchema ( $options ) : boolean
Результат boolean

execute() публичный Метод

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.
Результат mixed Resource or object representing the result set, or false on failure

expression() публичный Метод

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.
Результат stdClass An object representing a database expression to be used in a query

fetchAll() публичный Метод

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.
Результат boolean | array Array of resultset rows, or false if no rows matched

fetchAssociated() публичный Метод

This is just a proxy to maintain BC.
См. также: 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.
Результат array Association results.

fetchResult() публичный Метод

Fetches the next row from the current result set
public fetchResult ( ) : boolean
Результат boolean

fetchRow() публичный Метод

Returns a row from current resultset as an array
public fetchRow ( string $sql = null ) : array
$sql string Some SQL to be executed.
Результат array The fetched row as an array

fetchVirtualField() публичный Метод

Modifies $result array to place virtual fields in model entry where they belongs to
public fetchVirtualField ( &$result ) : void
Результат void

field() публичный Метод

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
Результат mixed Value of field read.

fields() публичный Метод

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
Результат array

flushMethodCache() публичный Метод

These caches are used by DboSource::name() and DboSource::conditions()
public flushMethodCache ( ) : void
Результат void

fullTableName() публичный Метод

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.
Результат string Full quoted table name

generateAssociationQuery() публичный Метод

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.
Результат mixed String representing a query. True, when $external is false and association $type is 'hasOne' or 'belongsTo'.

getConnection() публичный Метод

Get the underlying connection object.
public getConnection ( ) : PDO
Результат PDO

getConstraint() публичный Метод

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.
Результат array Conditions array defining the constraint between $Model and $LinkModel.

getLog() публичный Метод

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.
Результат array Array of queries run as an array

getQueryCache() публичный Метод

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
Результат mixed results for query if it is cached, false otherwise

getVersion() публичный Метод

Gets the version string of the database server
public getVersion ( ) : string
Результат string The database version

group() публичный Метод

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.
Результат string Group By clause or null.

hasAny() публичный Метод

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)
Результат boolean True if the table has a matching record, else false

hasResult() публичный Метод

Checks if the result is valid
public hasResult ( ) : boolean
Результат boolean True if the result is valid else false

identifier() публичный Метод

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
Результат stdClass An object representing a database identifier to be used in a query

index() публичный Метод

Returns an array of the indexes in given datasource name.
public index ( string $model ) : array
$model string Name of model to inspect
Результат array Fields in table. Keys are column and unique

insertMulti() публичный Метод

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.
Результат boolean

introspectType() публичный Метод

Guesses the data type of an array
public introspectType ( string $value ) : string
$value string The value to introspect for type data.
Результат string

isConnected() публичный Метод

Checks if the source is connected to the database.
public isConnected ( ) : boolean
Результат boolean True if the database is connected, else false

lastAffected() публичный Метод

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.
Результат integer Number of affected rows

lastError() публичный Метод

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
Результат string Error message with error number

lastInsertId() публичный Метод

Returns the ID generated from the previous INSERT operation.
public lastInsertId ( mixed $source = null ) : mixed
$source mixed The source to get an id for.
Результат mixed

lastNumRows() публичный Метод

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
Результат integer Number of rows in resultset

length() публичный Метод

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)")
Результат mixed An integer or string representing the length of the column, or null for unknown length.

limit() публичный Метод

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
Результат string SQL limit/offset statement

loadCsv() публичный Метод

CSVファイルをDBに読み込む
public loadCsv ( array $options ) : boolean
$options array [ path / encoding ]
Результат boolean

loadCsvToArray() публичный Метод

CSVよりデータを配列として読み込む
public loadCsvToArray ( string $path, $encoding ) : mixed
$path string
Результат mixed boolean Or array

loadSchema() публичный Метод

スキーマファイルを利用してテーブルを生成する
public loadSchema ( array $options ) : boolean
$options array path は必須
Результат boolean

logQuery() публичный Метод

Log given SQL query.
public logQuery ( string $sql, array $params = [] ) : void
$sql string SQL statement
$params array Values binded to the query (prepared statements)
Результат void

name() публичный Метод

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()
Результат string SQL field

nestedTransactionSupported() публичный Метод

Check if the server support nested transactions
public nestedTransactionSupported ( ) : boolean
Результат boolean

order() публичный Метод

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)
Результат string ORDER BY clause

prepareFields() публичный Метод

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().
Результат array Array containing SQL fields.

query() публичный Метод

DataSource Query abstraction
public query ( ) : resource
Результат resource Result resource identifier.

queryAssociation() публичный Метод

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.
Результат mixed

rawQuery() публичный Метод

Executes given SQL statement.
public rawQuery ( string $sql, array $params = [] ) : boolean
$sql string SQL statement
$params array Additional options for the query.
Результат boolean

read() публичный Метод

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
Результат mixed boolean false on error/failure. An array of results on success.

readSchema() публичный Метод

データベースよりスキーマ情報を読み込む
public readSchema ( string $table, $options = [] ) : array
$table string
Результат array $schema

readTableParameters() публичный Метод

Read additional table parameters
public readTableParameters ( string $name ) : array
$name string The table name to read.
Результат array

reconnect() публичный Метод

Reconnects to database server with optional new settings
public reconnect ( array $config = [] ) : boolean
$config array An array defining the new configuration settings
Результат boolean True on success, false on failure

renameColumn() публичный Метод

カラム名を変更する
public renameColumn ( array $options ) : boolean
$options array [ table / new / old ]
Результат boolean

renameTable() публичный Метод

テーブル名をリネームする
public renameTable ( array $options ) : boolean
$options array [ old / new ]
Результат boolean

renderJoinStatement() публичный Метод

Renders a final SQL JOIN statement
public renderJoinStatement ( array $data ) : string
$data array The data to generate a join statement for.
Результат string

renderStatement() публичный Метод

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.
Результат string Rendered SQL expression to be run.

resetSequence() публичный Метод

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.
Результат boolean | void success.

resolveKey() публичный Метод

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.
Результат string

rollback() публичный Метод

Rollback a transaction
public rollback ( ) : boolean
Результат boolean True on success, false on fail (i.e. if the database/model does not support transactions, or a transaction has not started).

showLog() публичный Метод

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.
Результат void

truncate() публичный Метод

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
Результат boolean SQL TRUNCATE TABLE statement, false if not applicable.

update() публичный Метод

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.
Результат boolean Success

value() публичный Метод

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.
Результат string Quoted and escaped data

writeCsv() публичный Метод

DBのデータをCSVファイルとして書きだす
public writeCsv ( array $options ) : boolean
$options array [ path / table / encoding ]
Результат boolean

writeCurrentSchema() публичный Метод

現在の接続のスキーマを生成する
public writeCurrentSchema ( string $filename ) : boolean
$filename string 保存先のフルパス
Результат boolean

writeSchema() публичный Метод

モデル名を指定してスキーマファイルを生成する
public writeSchema ( $options ) : mixed
Результат mixed スキーマファイルの内容 Or false

Описание свойств

$_connection защищенное свойство

A reference to the physical connection of this DataSource
protected array $_connection
Результат array

$_encodingMaps защищенное свойство

PHP←→DBエンコーディングマップ
protected array $_encodingMaps
Результат array

$_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
protected bool $_methodCacheChange
Результат boolean

$_queriesCnt защищенное свойство

Queries count.
protected int $_queriesCnt
Результат integer

$_queriesLog защищенное свойство

Log of queries executed by this DataSource
protected array $_queriesLog
Результат array

$_queriesLogMax защищенное свойство

This is to prevent query log taking over too much memory.
protected int $_queriesLogMax
Результат integer

$_queriesTime защищенное свойство

Total duration of all queries.
protected int $_queriesTime
Результат integer

$_queryCache защищенное свойство

Caches serialized results of executed queries
protected array $_queryCache
Результат array

$_queryDefaults защищенное свойство

Default fields that are used by the DBO
protected array $_queryDefaults
Результат array

$_result защищенное свойство

Result
protected array $_result
Результат array

$_sqlOps защищенное свойство

The set of valid SQL operations usable in a WHERE statement
protected array $_sqlOps
Результат array

$_transactionNesting защищенное свойство

Indicates the level of nested transactions
protected int $_transactionNesting
Результат integer

$affected публичное свойство

String to hold how many rows were affected by the last SQL operation.
public string $affected
Результат string

$alias публичное свойство

Database keyword used to assign aliases to identifiers.
public string $alias
Результат string

$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.
public bool $cacheMethods
Результат boolean

$configKeyName публичное свойство

The DataSource configuration key name
public string $configKeyName
Результат string

$description публичное свойство

Description string for this Database Data Source.
public string $description
Результат string

$endQuote публичное свойство

The ending character that this DataSource uses for quoted identifiers.
public string $endQuote
Результат string

$fieldParameters публичное свойство

List of engine specific additional field parameters used on table creating
public array $fieldParameters
Результат array

$fullDebug публичное свойство

Print full query debug info?
public bool $fullDebug
Результат boolean

$index публичное свойство

index definition, standard cake, primary, index, unique
public array $index
Результат array

$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.
public static array $methodCache
Результат array

$numRows публичное свойство

Number of rows in current resultset
public int $numRows
Результат integer

$startQuote публичное свойство

The starting character that this DataSource uses for quoted identifiers.
public string $startQuote
Результат string

$tableParameters публичное свойство

List of table engine specific parameters used on table creating
public array $tableParameters
Результат array

$took публичное свойство

Time the last query took
public int $took
Результат integer

$useNestedTransactions публичное свойство

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
Результат boolean

$virtualFieldSeparator публичное свойство

Separator string for virtualField composition
public string $virtualFieldSeparator
Результат string