Show:

Db_Query_Mysql Class

Extends Db_Query
Module: Db

This class lets you create and use Db queries

Constructor

Db_Query_Mysql

(
  • $db
  • $type
  • [$clauses=array()]
  • [$parameters=array()]
  • [$tables=null]
)

Parameters:

  • $db Db_Interface

    An instance of a Db adapter

  • $type Integer

    The type of the query. See class constants beginning with TYPE_ .

  • [$clauses=array()] Array optional

    The clauses to add to the query right away

  • [$parameters=array()] Array optional

    The parameters to add to the query right away (to be bound when executing). Values corresponding to numeric keys replace question marks, while values corresponding to string keys replace ":key" placeholders, in the SQL.

  • [$tables=null] Array optional

    The tables operated with query

Methods

__toString

() String

Convert Db_Query_Mysql to it's representation

Returns:

String:

after

(
  • $after
  • $clause
)
chainable

Inserts a custom clause after a particular clause

Parameters:

  • $after String

    The name of the standard clause to add after, such as FROM or UPDATE

  • $clause String

    The text of the clause to add

andWhere

(
  • $criteria
  • [$or_criteria=null]
)
Db_Query_Mysql chainable

Adds to the WHERE clause, like this: "... AND (x OR y OR z)", where x, y and z are the arguments to this function.

Parameters:

  • $criteria Db_Expression | String

    An associative array of expression => value pairs. The values are automatically escaped using the database server, or turned into PDO placeholders for prepared statements They can also be arrays, in which case they are placed into an expression of the form "key IN ('val1', 'val2')" Or, this could be a Db_Expression object.

  • [$or_criteria=null] Db_Expression | String optional

Returns:

Db_Query_Mysql:

The resulting object implementing Db_Query_Interface

applyHash

(
  • $value
  • [$hash='normalize']
  • [$len=self::HASH_LEN]
)
String private

Calculates hash of the value

Parameters:

  • $value String
  • [$hash='normalize'] String optional
  • [$len=self::HASH_LEN] Integer optional

Returns:

String:

begin

(
  • [$lock_type='FOR
)
chainable

Begins a transaction right before executing this query. The reason this method is part of the query class is because you often need the "where" clauses to figure out which database to send it to, if sharding is being used.

Parameters:

  • [$lock_type='FOR String

    UPDATE'] Defaults to 'FOR UPDATE', but can also be 'LOCK IN SHARE MODE' or set it to null to avoid adding a "LOCK" clause

bind

(
  • [$parameters=array()]
)
Db_Query_Mysql chainable

You can bind more parameters to the query manually using this method. These parameters are bound in the order they are passed to the query. Here is an example:

Parameters:

  • [$parameters=array()] Array optional

    An associative array of parameters. The query should contain :name, where :name is a placeholder for the parameter under the key "name". The parameters will be properly escaped. You can also have the query contain question marks (the binding is done using PDO), but then the order of the parameters matters.

Returns:

Db_Query_Mysql:

The resulting object implementing Db_Query_Interface.

Example:

$result = $db->select('*', 'foo')
    ->where(array('a' => $a))
    ->andWhere('a = :moo')
    ->bind(array('moo' => $moo))
    ->execute();

build

() String

Builds the query from the clauses

Returns:

String:

The SQL query built according to defined clauses

caching

(
  • [$mode=null]
)
Db_Query_Mysql

Turn off automatic caching on fetchAll and fetchDbRows.

Parameters:

  • [$mode=null] Boolean optional

    Pass false to suppress all caching. Pass true to cache everything. The default is null, which caches everything except empty results.

Returns:

commit

() chainable

Commits a transaction right after executing this query. The reason this method is part of the query class is because you often need the "where" clauses to figure out which database to send it to, if sharding is being used.

criteria

(
  • $criteria
)

This function is specifically for adding criteria to query for sharding purposes. It doesn't affect the SQL generated for the query.

Parameters:

  • $criteria Db_Expression | Array

    An associative array of expression => value pairs.

criteria_internal

(
  • $criteria
)
String private

Calculates criteria

Parameters:

Returns:

String:

excecute

(
  • [$prepareStatement=false]
  • [$shards]
)
Db_Result

Executes a query against the database and returns the result set.

Parameters:

  • [$prepareStatement=false] Boolean optional

    If true, a PDO statement will be prepared from the query before it is executed. It is also saved for future invocations to use. Do this only if the statement will be executed many times with different parameters. Basically you would use ->bind(...) between invocations of ->execute().

  • [$shards] Array | String optional

    You can pass a shard name here, or a numerically indexed array of shard names, or an associative array where the keys are shard names and the values are the query to execute. This will bypass the usual sharding algorithm.

Returns:

Db_Result:

The Db_Result object containing the PDO statement that resulted from the query.

fetchAll

(
  • $fetch_style=PDO::FETCH_BOTH
  • $column_index=null
  • $ctor_args=null
)
Array

Fetches an array of database rows matching the query. If this exact query has already been executed and fetchAll() has been called on the Db_Query, and the return value was cached by the Db_Query class, then that cached value is returned, unless $this->ignoreCache is true. Otherwise, the query is executed and fetchAll() is called on the result.

See PDO documentation

Parameters:

  • $fetch_style=PDO::FETCH_BOTH Enum
  • $column_index=null Enum
  • $ctor_args=null Array

Returns:

Array:

fetchDbRow

(
  • [$class_name=null]
  • [$fields_prefix='']
)
DbRow | Boolean

Fetches one Db_Row object (possibly extended). You can pass a prefix to strip from the field names. It will also filter the result.

Parameters:

  • [$class_name=null] String optional

    The name of the class to instantiate and fill objects from. Must extend Db_Row. Defaults to $this->query->className

  • [$fields_prefix=''] String optional

    This is the prefix, if any, to strip out when fetching the rows.

Returns:

DbRow | Boolean:

Returns false if no row, otherwise returns an object of type $class_name

fetchDbRows

(
  • [$class_name=null]
  • [$fields_prefix='']
  • [$by_field=null]
)
Array

Fetches an array of Db_Row objects (possibly extended). If this exact query has already been executed and fetchAll() has been called on the Db_Query, and the return value was cached by the Db_Query class, then that cached value is returned. Otherwise, the query is executed and fetchDbRows() is called on the result.

Parameters:

  • [$class_name=null] String optional

    The name of the class to instantiate and fill objects from. Must extend Db_Row. Defaults to $this->className

  • [$fields_prefix=''] String optional

    This is the prefix, if any, to strip out when fetching the rows.

  • [$by_field=null] String optional

    A field name to index the array by. If the field's value is NULL in a given row, that row is just appended in the usual way to the array.

Returns:

Array:

getClause

(
  • $clauseName
  • [$withAfter=false]
)
Mixed

Gets a clause from the query

Parameters:

  • $clauseName String
  • [$withAfter=false] Boolean optional

Returns:

Mixed:

If $withAfter is true, returns array($clause, $after) otherwise just returns $clause

getSQL

(
  • [$callback=null]
  • [$template=false]
)
String | Db_Query

Gets the SQL that would be executed with the execute() method. See build.

Parameters:

  • [$callback=null] Callable optional

    If not set, this function returns the generated SQL string. If it is set, this function calls $callback, passing it the SQL string, and then returns $this, for chainable interface.

  • [$template=false] Boolean optional

Returns:

String | Db_Query:

Depends on whether $callback is set or not.

groupBy

(
  • $expression
)
Db_Query_Mysql chainable

Adds a GROUP BY clause to a query

Parameters:

Returns:

Db_Query_Mysql:

The resulting object implementing Db_Query_Interface

hashed

(
  • $value
  • [$hash=null]
)
String

Calculate hash of the value

Parameters:

  • $value String
  • [$hash=null] String optional

    Hash is one of 'md5' or 'normalize' optionally followed by '%' and number

Returns:

String:

having

(
  • $criteria
)
Db_Query_Mysql chainable

Adds a HAVING clause to a query

Parameters:

  • $criteria Db_Expression | Array

    An associative array of expression => value pairs. The values are automatically escaped using PDO placeholders. Or, this could be a Db_Expression object.

Returns:

Db_Query_Mysql:

The resulting object implementing Db_Query_Interface

ignoreCache

() chainable

Turn off automatic caching on fetchAll and fetchDbRows.

join

(
  • $table
  • $condition
  • [$join_type='INNER']
)
Db_Query_Mysql chainable

Joins another table to use in the query

Parameters:

  • $table String

    The name of the table. May also be "name alias".

  • $condition Db_Expression | Array | String

    The condition to join on. Thus, JOIN table ON ($condition)

  • [$join_type='INNER'] String optional

    The string to prepend to JOIN, such as 'INNER' (default), 'LEFT OUTER', etc.

Returns:

Db_Query_Mysql:

The resulting object implementing Db_Query_Interface

limit

(
  • $limit
  • [$offset=null]
)
Db_Query_Mysql chainable

Adds optional LIMIT and OFFSET clauses to the query

Parameters:

  • $limit Integer

    A non-negative integer showing how many rows to return

  • [$offset=null] Integer optional

    A non-negative integer showing what row to start the result set with.

Returns:

Db_Query_Mysql:

The resulting object implementing Db_Query_Interface

lock

(
  • [$type='FOR
)
chainable

Works with SELECT queries to lock the selected rows. Use only with MySQL.

Parameters:

  • [$type='FOR String

    UPDATE'] Defaults to 'FOR UPDATE', but can also be 'LOCK IN SHARE MODE'

map_shard

(
  • $a
)
String private

Make partition from array of points

Parameters:

  • $a Array

Returns:

String:

onDuplicateKeyUpdate

(
  • $updates
)
Db_Query_Mysql

Adds an ON DUPLICATE KEY UPDATE clause to an INSERT statement. Use only with MySQL.

Parameters:

  • $updates Array

    An associative array of column => value pairs. The values are automatically escaped using PDO placeholders.

Returns:

Db_Query_Mysql:

The resulting object implementing Db_Query_Interface $chainable

onDuplicateKeyUpdate_internal

(
  • $updates
)
String private

Calculates an ON DUPLICATE KEY UPDATE clause

Parameters:

  • $updates Array

    An associative array of column => value pairs. The values are automatically escaped using PDO placeholders.

Returns:

String:

options

(
  • $options
)
chainable

This function provides an easy way to provide additional clauses to the query.

Parameters:

  • $options Array

    An associative array of key => value pairs, where the key is the name of the method to call, and the value is the array of arguments. If the value is not an array, it is wrapped in one.

orderBy

(
  • $expression
  • $ascending=true
)
Db_Query_Mysql chainable

Adds an ORDER BY clause to the query

Parameters:

  • $expression Db_Expression | String

    A string or Db_Expression with the expression to order the results by.

  • $ascending=true Boolean

    If false, sorts results as descending, otherwise ascending.

Returns:

Db_Query_Mysql:

The resulting object implementing Db_Query_Interface

orWhere

(
  • $criteria
  • [$and_criteria=null]
)
Db_Query_Mysql chainable

Adds to the WHERE clause, like this: "... OR (x AND y AND z)", where x, y and z are the arguments to this function.

Parameters:

  • $criteria Db_Expression | String

    An associative array of expression => value pairs. The values are automatically escaped using the database server, or turned into PDO placeholders for prepared statements They can also be arrays, in which case they are placed into an expression of the form key IN ('val1', 'val2') Or, this could be a Db_Expression object.

  • [$and_criteria=null] Db_Expression | String optional

Returns:

Db_Query_Mysql:

The resulting object implementing Db_Query_Interface

reallyConnect

(
  • [$shard_name=null]
)
PDO private

Connects to database

Parameters:

  • [$shard_name=null] String optional

Returns:

PDO:

The PDO object for connection

replace

(
  • [$replacements=array()]
)

Merges additional replacements over the default replacement array, which is currently just

Parameters:

  • [$replacements=array()] Array optional

    This must be an array.

Example:

 array (
    '{$prefix}' => $conn['prefix']
 )

The replacements array is used to replace strings in the SQL before using it. Watch out, because it may replace more than you want!

replaceKeysCompare

() Integer private

Returns:

Integer:

resume

()

Can only be called if this is a query returned from a function that was supposed to execute it, but the user requested a chance to modify it. For example, Db_Row->getRelated and Db_Row->retrieve. After calling a chain of methods, call the resume() method to complete the original function and return the result.

reuseStatement

(
  • $query
)

Re-use an existing (prepared) statement. Rarely used except internally.

Parameters:

rollback

(
  • [$criteria=null]
)
chainable

Roll back a transaction right after executing this query. The reason this method is part of the query class is because you often need the "where" clauses to figure out which database to send it to, if sharding is being used.

Parameters:

  • [$criteria=null] String optional

    Pass this to target the rollback to the right shard.

select

(
  • $fields
  • [$tables='']
  • [$repeat=false]
)
Db_Query_Mysql chainable

Creates a query to select fields from one or more tables.

Parameters:

  • $fields String | Array

    The fields as strings, or array of alias=>field

  • [$tables=''] String | Array optional

    The tables as strings, or array of alias=>field

  • [$repeat=false] Boolean optional

    If $tables is an array, and select() has already been called with the exact table name and alias as one of the tables in that array, then this table is not appended to the tables list if $repeat is false. Otherwise it is. This is really just for using in your hooks.

Returns:

Db_Query_Mysql:

The resulting object implementing Db_Query_Interface. You can use it to chain the calls together.

set

(
  • $updates
)
Db_Query_Mysql chainable

Adds a SET clause to an UPDATE statement

Parameters:

  • $updates Array

    An associative array of column => value pairs. The values are automatically escaped using PDO placeholders.

Returns:

Db_Query_Mysql:

The resulting object implementing Db_Query_Interface

set_internal

(
  • $updates
)
String private

Calculates SET clause

Parameters:

  • $updates Array

    An associative array of column => value pairs. The values are automatically escaped using PDO placeholders.

Returns:

String:

setContext

(
  • $callback
  • [$args=array()]
)

Sets context

Parameters:

  • $callback Callable
  • [$args=array()] Array optional

shard

(
  • [$upcoming=null]
  • [$criteria=null]
)
Array

Analyzes the query's criteria and decides where to execute the query. Here is sample shards config:

NOTE: "fields" shall be an object with keys as fields names and values containing hash definition in the format "type%length" where type is one of 'md5' or 'normalize' and length is hash length hash definition can be empty string or false. In such case 'md5%7' is used

NOTE: "partition" can be an array. In such case shards shall be named after partition points

"Streams": {
    "prefix": "streams_",
    "dsn": "mysql:host=127.0.0.1;dbname=DBNAME",
    "username": "USER",
    "password": "PASSWORD",
    "driver_options": {
        "3": 2
    },
    "shards": {
        "alpha": {
            "prefix": "alpha_",
            "dsn": "mysql:host=127.0.0.1;dbname=SHARDDBNAME",
            "username": "USER",
            "password": "PASSWORD",
            "driver_options": {
                "3": 2
            }
        },
        "betta": {
            "prefix": "betta_",
            "dsn": "mysql:host=127.0.0.1;dbname=SHARDDBNAME",
            "username": "USER",
            "password": "PASSWORD",
            "driver_options": {
                "3": 2
            }
        },
        "gamma": {
            "prefix": "gamma_",
            "dsn": "mysql:host=127.0.0.1;dbname=SHARDDBNAME",
            "username": "USER",
            "password": "PASSWORD",
            "driver_options": {
                "3": 2
            }
        },
        "delta": {
            "prefix": "delta_",
            "dsn": "mysql:host=127.0.0.1;dbname=SHARDDBNAME",
            "username": "USER",
            "password": "PASSWORD",
            "driver_options": {
                "3": 2
            }
        }
    },
    "indexes": {
        "Stream": {
            "fields": {"publisherId": "md5", "name": "normalize"},
            "partition": {
                "0000000.       ": "alpha",
                "0000000.sample_": "betta",
                "4000000.       ": "gamma",
                "4000000.sample_": "delta",
                "8000000.       ": "alpha",
                "8000000.sample_": "betta",
                "c000000.       ": "gamma",
                "c000000.sample_": "delta"
            }
        }
    }
}

Parameters:

  • [$upcoming=null] Array optional

    Temporary config to use in sharding. Used during shard split process only

  • [$criteria=null] Array optional

    Overrides the sharding criteria for the query. Rarely used unless testing what shards the query would be executed on.

Returns:

Array:

Returns an array of ($shardName => $query) pairs, where $shardName can be the name of a shard, '' for just the main shard, or "*" to have the query run on all the shards.

shard_internal

(
  • $index
  • $hashed
)
Array private

does a depth first search and returns the array of shardname => $query pairs corresponding to which shards are affected

Parameters:

  • $index Array
  • $hashed String

Returns:

Array:

slice_partitions

(
  • $partition
  • $j
  • $hashed
  • [$adjust=false]
)
Array private

Narrows the partition list according to hashes

Parameters:

  • $partition Array
  • $j Integer

    Currently processed hashed array member

  • $hashed Array
  • [$adjust=false] Boolean optional

Returns:

Array:

where

(
  • $criteria
)
Db_Query_Mysql chainable

Adds a WHERE clause to a query

Parameters:

  • $criteria Db_Expression | Array

    An associative array of expression => value pairs. The values are automatically escaped using the database server, or turned into PDO placeholders for prepared statements They can also be arrays, in which case they are placed into an expression of the form key IN ('val1', 'val2') Or, this could be a Db_Expression object.

Returns:

Db_Query_Mysql:

The resulting object implementing Db_Query_Interface

Properties

$after

Array

Any additional text that comes after a clause

Default: array()

$cache

Array

Class cache

$caching

Boolean

Whether to cache or not

Default: false

$chain

Db_Query

The query that was run to produce this result

$className

String

The name of the class to instantiate when fetching database rows.

$clauses

Array

Clauses that this query has (WHERE, ORDER BY, etc.)

Default: array()

$context

Array

The context of the query. Contains the following keys:

  • 'callback' => the function or method to call back
  • 'args' => the arguments to pass to that function or method

Default: null

$criteria

Array

Criteria used for sharding the query

Default: array()

$db

Db_Mysql

The object implementing Db_Interface that this query uses

$expression

String

The expression as a string

$ignoreCache

Boolean

Whether to use the cache or not

Default: false

$mapping

Array private

Actual points mapping depending if partition is plain or associative array

$parameters

Array

The parameters passed to this query

Default: array()

$replacements

Array

Strings to replace in the query, if getSQL() or execute() is called

Default: array()

$statement

PDOStatement

If this query is prepared, this would point to the PDOStatement object

Default: null

$table

String

The tables operated with query

$type

Integer

The type of query this is (select, insert, etc.)

HASH_LEN

Integer final

Default length of the hash used for sharding

Default: 7

TYPE_DELETE

Integer final

Delete query

TYPE_INSERT

Integer final

Insert query

TYPE_RAW

Integer final

Raw query

TYPE_ROLLBACK

Integer final

Rollback query

TYPE_SELECT

Integer final

Select query

TYPE_UPDATE

Integer final

Update query

Events

Db/query/exception

After

Event Payload:

Db/query/execute

Before

Event Payload:

Db/query/execute

After

Event Payload:

Db/reallyConnect

Before

Event Payload: