PHP Class DboSource

Creates DBO-descendant objects from a given db connection configuration
Inheritance: extends DataSource
ファイルを表示 Open project: baserproject/basercms Class Usage Examples

Public Properties

Property 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

Property 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

Public Methods

Method 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 モデル名を指定してスキーマファイルを生成する

Protected Methods

Method 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 method

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 method

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

_beginNested() protected method

Begin a nested transaction
protected _beginNested ( ) : boolean
return boolean

_buildFieldParameters() protected method

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
return string a built column with the field parameters added.

_commitNested() protected method

Commit a nested transaction
protected _commitNested ( ) : boolean
return boolean

_constructVirtualFields() protected method

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
return array

_convertFieldToCsv() protected method

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

_convertRecordToCsv() protected method

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

_dbEncToPhp() protected method

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

_dropTable() protected method

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

_execute() protected method

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
return 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 method

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.
return array Association results.

_fetchHasMany() protected method

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.
return array Association results.

_filterResults() protected method

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.
return array Array of results that have been filtered through $Model->afterFind.

_getJoins() protected method

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
return array

_matchRecords() protected method

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.
return array List of record IDs

_mergeAssociation() protected method

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.
return void

_mergeConditions() protected method

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.
return array

_mergeHasMany() protected method

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.
return void

_parseKey() protected method

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
return string

_phpEncToDb() protected method

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

_prepareUpdateFields() protected method

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
return array Fields and values, quoted and prepared

_quoteFields() protected method

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

_quoteMatchedField() protected method

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

_rollbackNested() protected method

Rollback a nested transaction
protected _rollbackNested ( ) : boolean
return boolean

_scrubQueryData() protected method

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

_writeQueryCache() protected method

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
return void

addColumn() public method

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

alterSchema() public method

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.
return boolean

alterTable() public method

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

alterTableBySchema() public method

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

begin() public method

Begin a transaction
public begin ( ) : boolean
return 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 method

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.
return string | boolean Converted boolean value

buildAssociationQuery() public method

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().
return string String containing an SQL statement.

buildColumn() public method

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'.
return string

buildIndex() public method

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

buildJoinStatement() public method

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.
return string An SQL JOIN condition to be used in a query.

buildRenameTable() public method

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

buildStatement() public method

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.
return string An executable SQL statement.

buildTableParameters() public method

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.
return array

cacheMethod() public method

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.
return mixed Either null on failure, or the value if its set.

calculate() public method

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)
return string An SQL calculation function

changeColumn() public method

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

close() public method

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

commit() public method

Commit a transaction
public commit ( ) : boolean
return 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 method

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
return string SQL fragment

conditions() public method

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
return string SQL fragment

create() public method

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.
return boolean Success

createSchema() public method

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.
return string

createTable() public method

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

createTableBySchema() public method

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

defaultConditions() public method

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
return mixed Either null, false, $conditions or an array of default conditions to use.

delete() public method

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.
return boolean Success

disconnect() public method

Disconnects from database.
public disconnect ( ) : boolean
return boolean Always true

dropColumn() public method

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

dropSchema() public method

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.
return string

dropTable() public method

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

dropTableBySchema() public method

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

execute() public method

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.
return mixed Resource or object representing the result set, or false on failure

expression() public method

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.
return stdClass An object representing a database expression to be used in a query

fetchAll() public method

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.
return boolean | array Array of resultset rows, or false if no rows matched

fetchAssociated() public method

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.
return array Association results.

fetchResult() public method

Fetches the next row from the current result set
public fetchResult ( ) : boolean
return boolean

fetchRow() public method

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

fetchVirtualField() public method

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

field() public method

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
return mixed Value of field read.

fields() public method

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
return array

flushMethodCache() public method

These caches are used by DboSource::name() and DboSource::conditions()
public flushMethodCache ( ) : void
return void

fullTableName() public method

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.
return string Full quoted table name

generateAssociationQuery() public method

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.
return mixed String representing a query. True, when $external is false and association $type is 'hasOne' or 'belongsTo'.

getConnection() public method

Get the underlying connection object.
public getConnection ( ) : PDO
return PDO

getConstraint() public method

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.
return array Conditions array defining the constraint between $Model and $LinkModel.

getLog() public method

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.
return array Array of queries run as an array

getQueryCache() public method

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
return mixed results for query if it is cached, false otherwise

getVersion() public method

Gets the version string of the database server
public getVersion ( ) : string
return string The database version

group() public method

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.
return string Group By clause or null.

hasAny() public method

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)
return boolean True if the table has a matching record, else false

hasResult() public method

Checks if the result is valid
public hasResult ( ) : boolean
return boolean True if the result is valid else false

identifier() public method

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
return stdClass An object representing a database identifier to be used in a query

index() public method

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

insertMulti() public method

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.
return boolean

introspectType() public method

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

isConnected() public method

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

lastAffected() public method

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.
return integer Number of affected rows

lastError() public method

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
return string Error message with error number

lastInsertId() public method

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

lastNumRows() public method

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
return integer Number of rows in resultset

length() public method

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)")
return mixed An integer or string representing the length of the column, or null for unknown length.

limit() public method

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
return string SQL limit/offset statement

loadCsv() public method

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

loadCsvToArray() public method

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

loadSchema() public method

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

logQuery() public method

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

name() public method

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()
return string SQL field

nestedTransactionSupported() public method

Check if the server support nested transactions

order() public method

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)
return string ORDER BY clause

prepareFields() public method

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().
return array Array containing SQL fields.

query() public method

DataSource Query abstraction
public query ( ) : resource
return resource Result resource identifier.

queryAssociation() public method

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.
return mixed

rawQuery() public method

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

read() public method

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
return mixed boolean false on error/failure. An array of results on success.

readSchema() public method

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

readTableParameters() public method

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

reconnect() public method

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

renameColumn() public method

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

renameTable() public method

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

renderJoinStatement() public method

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

renderStatement() public method

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.
return string Rendered SQL expression to be run.

resetSequence() public method

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.
return boolean | void success.

resolveKey() public method

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.
return string

rollback() public method

Rollback a transaction
public rollback ( ) : boolean
return 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 method

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.
return void

truncate() public method

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
return boolean SQL TRUNCATE TABLE statement, false if not applicable.

update() public method

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.
return boolean Success

value() public method

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.
return string Quoted and escaped data

writeCsv() public method

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

writeCurrentSchema() public method

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

writeSchema() public method

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

Property Details

$_connection protected_oe property

A reference to the physical connection of this DataSource
protected array $_connection
return array

$_encodingMaps protected_oe property

PHP←→DBエンコーディングマップ
protected array $_encodingMaps
return 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
return boolean

$_queriesCnt protected_oe property

Queries count.
protected int $_queriesCnt
return integer

$_queriesLog protected_oe property

Log of queries executed by this DataSource
protected array $_queriesLog
return array

$_queriesLogMax protected_oe property

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

$_queriesTime protected_oe property

Total duration of all queries.
protected int $_queriesTime
return integer

$_queryCache protected_oe property

Caches serialized results of executed queries
protected array $_queryCache
return array

$_queryDefaults protected_oe property

Default fields that are used by the DBO
protected array $_queryDefaults
return array

$_result protected_oe property

Result
protected array $_result
return array

$_sqlOps protected_oe property

The set of valid SQL operations usable in a WHERE statement
protected array $_sqlOps
return array

$_transactionNesting protected_oe property

Indicates the level of nested transactions
protected int $_transactionNesting
return integer

$affected public_oe property

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

$alias public_oe property

Database keyword used to assign aliases to identifiers.
public string $alias
return 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
return boolean

$configKeyName public_oe property

The DataSource configuration key name
public string $configKeyName
return string

$description public_oe property

Description string for this Database Data Source.
public string $description
return string

$endQuote public_oe property

The ending character that this DataSource uses for quoted identifiers.
public string $endQuote
return string

$fieldParameters public_oe property

List of engine specific additional field parameters used on table creating
public array $fieldParameters
return array

$fullDebug public_oe property

Print full query debug info?
public bool $fullDebug
return boolean

$index public_oe property

index definition, standard cake, primary, index, unique
public array $index
return 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
return array

$numRows public_oe property

Number of rows in current resultset
public int $numRows
return integer

$startQuote public_oe property

The starting character that this DataSource uses for quoted identifiers.
public string $startQuote
return string

$tableParameters public_oe property

List of table engine specific parameters used on table creating
public array $tableParameters
return array

$took public_oe property

Time the last query took
public int $took
return 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
return boolean

$virtualFieldSeparator public_oe property

Separator string for virtualField composition
public string $virtualFieldSeparator
return string