class MySQLDatabase extends SS_Database (View source)

MySQL connector class.

Supported indexes for {@link requireTable()}:

Properties

static private string $connection_charset

Default connection charset (may be overridden in $databaseConfig)

Methods

getConnector()

Get the current connector

setConnector(DBConnector $connector)

Injector injection point for connector dependency

getSchemaManager()

Returns the current schema manager

setSchemaManager(DBSchemaManager $schemaManager)

Injector injection point for schema manager

getQueryBuilder()

Returns the current query builder

setQueryBuilder(DBQueryBuilder $queryBuilder)

Injector injection point for schema manager

query(string $sql, int $errorLevel = E_USER_ERROR)

Execute the given SQL query.

preparedQuery(string $sql, array $parameters, int $errorLevel = E_USER_ERROR)

Execute the given SQL parameterised query with the specified arguments

int
getGeneratedID(string $table)

Get the autogenerated ID from the previous INSERT query.

bool
isActive()

Determines if we are connected to a server AND have a valid database selected.

string
escapeString(mixed $value)

Returns an escaped string. This string won't be quoted, so would be suitable for appending to other quoted strings.

string
quoteString(mixed $value)

Wrap a string into DB-specific quotes.

escapeIdentifier(string $value, string $separator = '.')

Escapes an identifier (table / database name). Typically the value is simply double quoted. Don't pass in already escaped identifiers in, as this will double escape the value!

manipulate(array $manipulation)

Execute a complex manipulation on the database.

quiet()

Enable supression of database messages.

clearAllData()

Clear all data out of the database

clearTable(string $table)

Clear all data in a given table

string
comparisonClause(string $field, string $value, bool $exact = false, bool $negate = false, bool $caseSensitive = null, bool $parameterised = false)

Generate a WHERE clause for text matching.

string
formattedDatetimeClause(string $date, string $format)

function to return an SQL datetime expression that can be used with the adapter in use used for querying a datetime in a certain format

string
datetimeIntervalClause($date, string $interval)

function to return an SQL datetime expression that can be used with the adapter in use used for querying a datetime addition

string
datetimeDifferenceClause($date1, string $date2)

function to return an SQL datetime expression that can be used with the adapter in use used for querying a datetime substraction

bool
supportsCollations()

Returns true if this database supports collations

bool
supportsTimezoneOverride()

Can the database override timezone as a connection setting, or does it use the system timezone exclusively?

string
getVersion()

Query for the version of the currently connected database

string
getDatabaseServer()

Get the database server type (e.g. mysql, postgresql).

int
affectedRows()

Return the number of rows affected by the previous operation.

searchEngine(array $classesToSearch, string $keywords, int $start, int $pageLength, string $sortBy = "Relevance DESC", string $extraFilter = "", bool $booleanSearch = false, string $alternativeFileFilter = "", bool $invertedMatch = false)

The core search engine, used by this class and its subclasses to do fun stuff.

bool
supportsTransactions()

Determines if this database supports transactions

transactionStart(string|bool $transactionMode = false, string|bool $sessionCharacteristics = false)

Start a prepared transaction See http://developer.postgresql.org/pgdocs/postgres/sql-set-transaction.html for details on transaction isolation options

transactionSavepoint(string $savepoint)

Create a savepoint that you can jump back to if you encounter problems

transactionRollback(string|bool $savepoint = false)

Rollback or revert to a savepoint if your queries encounter problems If you encounter a problem at any point during a transaction, you may need to rollback that particular query, or return to a savepoint

transactionEnd(bool $chain = false)

Commit everything inside this transaction so far

bool
supportsLocks()

Determines if the used database supports application-level locks, which is different from table- or row-level locking.

bool
canLock(string $name)

Returns if the lock is available.

bool
getLock(string $name, int $timeout = 5)

Sets an application-level lock so that no two processes can run at the same time, also called a "cooperative advisory lock".

bool
releaseLock(string $name)

Remove an application-level lock file to allow another process to run (if the execution aborts (e.g. due to an error) all locks are automatically released).

connect(array $parameters)

Instruct the database to generate a live connection

bool
databaseExists(string $name)

Determine if the database with the specified name exists

array
databaseList()

Retrieves the list of all databases the user has access to

bool
selectDatabase(string $name, bool $create = false, int|bool $errorLevel = E_USER_ERROR)

Change the connection to the specified database, optionally creating the database if it doesn't exist in the current schema.

dropSelectedDatabase()

Drop the database that this object is currently connected to.

string|null
getSelectedDatabase()

Returns the name of the currently selected database

string
now()

Return SQL expression used to represent the current date/time

string
random()

Returns the database-specific version of the random() function

dbDataType($type) deprecated

No description

createDatabase() deprecated

No description

getConnect($parameters) deprecated

No description

prepStringForDB($string) deprecated

No description

dropDatabase() deprecated

No description

allDatabaseNames() deprecated

No description

createTable($table, $fields = null, $indexes = null, $options = null, $advancedOptions = null) deprecated

No description

alterTable($table, $newFields = null, $newIndexes = null, $alteredFields = null, $alteredIndexes = null, $alteredOptions = null, $advancedOptions = null) deprecated

No description

renameTable($oldTableName, $newTableName) deprecated

No description

createField($table, $field, $spec) deprecated

No description

renameField($tableName, $oldName, $newName) deprecated

No description

currentDatabase() deprecated

No description

fieldList($table) deprecated

No description

tableList() deprecated

No description

hasTable($tableName) deprecated

No description

enumValuesForField($tableName, $fieldName) deprecated

No description

addslashes($value) deprecated

No description

beginSchemaUpdate() deprecated

No description

endSchemaUpdate() deprecated

No description

cancelSchemaUpdate() deprecated

No description

isSchemaUpdating() deprecated

No description

doesSchemaNeedUpdating() deprecated

No description

transCreateTable($table, $options = null, $advanced_options = null) deprecated

No description

transAlterTable($table, $options, $advanced_options) deprecated

No description

transCreateField($table, $field, $schema) deprecated

No description

transCreateIndex($table, $index, $schema) deprecated

No description

transAlterField($table, $field, $schema) deprecated

No description

transAlterIndex($table, $index, $schema) deprecated

No description

requireTable($table, $fieldSchema = null, $indexSchema = null, $hasAutoIncPK = true, $options = array(), $extensions = false) deprecated

No description

dontRequireTable($table) deprecated

No description

requireIndex($table, $index, $spec) deprecated

No description

hasField($tableName, $fieldName) deprecated

No description

requireField($table, $field, $spec) deprecated

No description

dontRequireField($table, $fieldName) deprecated

No description

sqlQueryToString(SQLExpression $query, $parameters = array()) deprecated

No description

static 
set_connection_charset($charset = 'utf8') deprecated

No description

setSQLMode(string $mode)

Sets the SQL mode

selectTimezone(string $timezone)

Sets the system timezone for the database connection

Details

DBConnector getConnector()

Get the current connector

Return Value

DBConnector

setConnector(DBConnector $connector)

Injector injection point for connector dependency

Parameters

DBConnector $connector

DBSchemaManager getSchemaManager()

Returns the current schema manager

Return Value

DBSchemaManager

setSchemaManager(DBSchemaManager $schemaManager)

Injector injection point for schema manager

Parameters

DBSchemaManager $schemaManager

DBQueryBuilder getQueryBuilder()

Returns the current query builder

Return Value

DBQueryBuilder

setQueryBuilder(DBQueryBuilder $queryBuilder)

Injector injection point for schema manager

Parameters

DBQueryBuilder $queryBuilder

SS_Query query(string $sql, int $errorLevel = E_USER_ERROR)

Execute the given SQL query.

Parameters

string $sql

The SQL query to execute

int $errorLevel

The level of error reporting to enable for the query

Return Value

SS_Query

SS_Query preparedQuery(string $sql, array $parameters, int $errorLevel = E_USER_ERROR)

Execute the given SQL parameterised query with the specified arguments

Parameters

string $sql

The SQL query to execute. The ? character will denote parameters.

array $parameters

An ordered list of arguments.

int $errorLevel

The level of error reporting to enable for the query

Return Value

SS_Query

int getGeneratedID(string $table)

Get the autogenerated ID from the previous INSERT query.

Parameters

string $table

The name of the table to get the generated ID for

Return Value

int

the most recently generated ID for the specified table

bool isActive()

Determines if we are connected to a server AND have a valid database selected.

Return Value

bool

Flag indicating that a valid database is connected

string escapeString(mixed $value)

Returns an escaped string. This string won't be quoted, so would be suitable for appending to other quoted strings.

Parameters

mixed $value

Value to be prepared for database query

Return Value

string

Prepared string

string quoteString(mixed $value)

Wrap a string into DB-specific quotes.

Parameters

mixed $value

Value to be prepared for database query

Return Value

string

Prepared string

escapeIdentifier(string $value, string $separator = '.')

Escapes an identifier (table / database name). Typically the value is simply double quoted. Don't pass in already escaped identifiers in, as this will double escape the value!

Parameters

string $value

The identifier to escape

string $separator

optional identifier splitter

manipulate(array $manipulation)

Execute a complex manipulation on the database.

A manipulation is an array of insert / or update sequences. The keys of the array are table names, and the values are map containing 'command' and 'fields'. Command should be 'insert' or 'update', and fields should be a map of field names to field values, NOT including quotes.

The field values could also be in paramaterised format, such as array('MAX(?,?)' => array(42, 69)), allowing the use of raw SQL values such as array('NOW()' => array()).

Parameters

array $manipulation

See also

SQLWriteExpression::addAssignments for syntax examples

quiet()

Enable supression of database messages.

clearAllData()

Clear all data out of the database

clearTable(string $table)

Clear all data in a given table

Parameters

string $table

Name of table

string comparisonClause(string $field, string $value, bool $exact = false, bool $negate = false, bool $caseSensitive = null, bool $parameterised = false)

Generate a WHERE clause for text matching.

Parameters

string $field

Quoted field name

string $value

Escaped search. Can include percentage wildcards. Ignored if $parameterised is true.

bool $exact

Exact matches or wildcard support.

bool $negate

Negate the clause.

bool $caseSensitive

Enforce case sensitivity if TRUE or FALSE. Fallback to default collation if set to NULL.

bool $parameterised

Insert the ? placeholder rather than the given value. If this is true then $value is ignored.

Return Value

string

SQL

string formattedDatetimeClause(string $date, string $format)

function to return an SQL datetime expression that can be used with the adapter in use used for querying a datetime in a certain format

Parameters

string $date

to be formated, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"'

string $format

to be used, supported specifiers: %Y = Year (four digits) %m = Month (01..12) %d = Day (01..31) %H = Hour (00..23) %i = Minutes (00..59) %s = Seconds (00..59) %U = unix timestamp, can only be used on it's own

Return Value

string

SQL datetime expression to query for a formatted datetime

string datetimeIntervalClause($date, string $interval)

function to return an SQL datetime expression that can be used with the adapter in use used for querying a datetime addition

Parameters

$date
string $interval

to be added, use the format [sign][integer] [qualifier], e.g. -1 Day, +15 minutes, +1 YEAR supported qualifiers:

  • years
  • months
  • days
  • hours
  • minutes
  • seconds This includes the singular forms as well

Return Value

string

SQL datetime expression to query for a datetime (YYYY-MM-DD hh:mm:ss) which is the result of the addition

string datetimeDifferenceClause($date1, string $date2)

function to return an SQL datetime expression that can be used with the adapter in use used for querying a datetime substraction

Parameters

$date1
string $date2

to be substracted of $date1, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"'

Return Value

string

SQL datetime expression to query for the interval between $date1 and $date2 in seconds which is the result of the substraction

bool supportsCollations()

Returns true if this database supports collations

Return Value

bool

bool supportsTimezoneOverride()

Can the database override timezone as a connection setting, or does it use the system timezone exclusively?

Return Value

bool

string getVersion()

Query for the version of the currently connected database

Return Value

string

Version of this database

string getDatabaseServer()

Get the database server type (e.g. mysql, postgresql).

This value is passed to the connector as the 'driver' argument when initiating a database connection

Return Value

string

int affectedRows()

Return the number of rows affected by the previous operation.

Return Value

int

PaginatedList searchEngine(array $classesToSearch, string $keywords, int $start, int $pageLength, string $sortBy = "Relevance DESC", string $extraFilter = "", bool $booleanSearch = false, string $alternativeFileFilter = "", bool $invertedMatch = false)

The core search engine, used by this class and its subclasses to do fun stuff.

Searches both SiteTree and File.

Parameters

array $classesToSearch

List of classes to search

string $keywords

Keywords as a string.

int $start

Item to start returning results from

int $pageLength

Number of items per page

string $sortBy

Sort order expression

string $extraFilter

Additional filter

bool $booleanSearch

Flag for boolean search mode

string $alternativeFileFilter
bool $invertedMatch

Return Value

PaginatedList

Search results

bool supportsTransactions()

Determines if this database supports transactions

Return Value

bool

Flag indicating support for transactions

transactionStart(string|bool $transactionMode = false, string|bool $sessionCharacteristics = false)

Start a prepared transaction See http://developer.postgresql.org/pgdocs/postgres/sql-set-transaction.html for details on transaction isolation options

Parameters

string|bool $transactionMode

Transaction mode, or false to ignore

string|bool $sessionCharacteristics

Session characteristics, or false to ignore

transactionSavepoint(string $savepoint)

Create a savepoint that you can jump back to if you encounter problems

Parameters

string $savepoint

Name of savepoint

transactionRollback(string|bool $savepoint = false)

Rollback or revert to a savepoint if your queries encounter problems If you encounter a problem at any point during a transaction, you may need to rollback that particular query, or return to a savepoint

Parameters

string|bool $savepoint

Name of savepoint, or leave empty to rollback to last savepoint

transactionEnd(bool $chain = false)

Commit everything inside this transaction so far

Parameters

bool $chain

bool supportsLocks()

Determines if the used database supports application-level locks, which is different from table- or row-level locking.

See {@link getLock()} for details.

Return Value

bool

Flag indicating that locking is available

bool canLock(string $name)

Returns if the lock is available.

See {@link supportsLocks()} to check if locking is generally supported.

Parameters

string $name

Name of the lock

Return Value

bool

bool getLock(string $name, int $timeout = 5)

Sets an application-level lock so that no two processes can run at the same time, also called a "cooperative advisory lock".

Return FALSE if acquiring the lock fails; otherwise return TRUE, if lock was acquired successfully. Lock is automatically released if connection to the database is broken (either normally or abnormally), making it less prone to deadlocks than session- or file-based locks. Should be accompanied by a {@link releaseLock()} call after the logic requiring the lock has completed. Can be called multiple times, in which case locks "stack" (PostgreSQL, SQL Server), or auto-releases the previous lock (MySQL).

Note that this might trigger the database to wait for the lock to be released, delaying further execution.

Parameters

string $name

Name of lock

int $timeout

Timeout in seconds

Return Value

bool

bool releaseLock(string $name)

Remove an application-level lock file to allow another process to run (if the execution aborts (e.g. due to an error) all locks are automatically released).

Parameters

string $name

Name of the lock

Return Value

bool

Flag indicating whether the lock was successfully released

connect(array $parameters)

Instruct the database to generate a live connection

Parameters

array $parameters

An map of parameters, which should include:

  • server: The server, eg, localhost
  • username: The username to log on with
  • password: The password to log on with
  • database: The database to connect to
  • charset: The character set to use. Defaults to utf8
  • timezone: (optional) The timezone offset. For example: +12:00, "Pacific/Auckland", or "SYSTEM"
  • driver: (optional) Driver name

bool databaseExists(string $name)

Determine if the database with the specified name exists

Parameters

string $name

Name of the database to check for

Return Value

bool

Flag indicating whether this database exists

array databaseList()

Retrieves the list of all databases the user has access to

Return Value

array

List of database names

bool selectDatabase(string $name, bool $create = false, int|bool $errorLevel = E_USER_ERROR)

Change the connection to the specified database, optionally creating the database if it doesn't exist in the current schema.

Parameters

string $name

Name of the database

bool $create

Flag indicating whether the database should be created if it doesn't exist. If $create is false and the database doesn't exist then an error will be raised

int|bool $errorLevel

The level of error reporting to enable for the query, or false if no error should be raised

Return Value

bool

Flag indicating success

dropSelectedDatabase()

Drop the database that this object is currently connected to.

Use with caution.

string|null getSelectedDatabase()

Returns the name of the currently selected database

Return Value

string|null

Name of the selected database, or null if none selected

string now()

Return SQL expression used to represent the current date/time

Return Value

string

Expression for the current date/time

string random()

Returns the database-specific version of the random() function

Return Value

string

Expression for a random value

dbDataType($type) deprecated

deprecated since version 4.0 Use DB::get_schema()->dbDataType($type) instead

Parameters

$type

createDatabase() deprecated

deprecated since version 4.0 Use selectDatabase('dbname', true) instead

getConnect($parameters) deprecated

deprecated since version 4.0 SS_Database::getConnect was never implemented and is obsolete

Parameters

$parameters

prepStringForDB($string) deprecated

deprecated since version 4.0 Use Convert::raw2sql($string, true) instead

Parameters

$string

dropDatabase() deprecated

deprecated since version 4.0 Use dropSelectedDatabase instead

allDatabaseNames() deprecated

deprecated since version 4.0 Use databaseList instead

createTable($table, $fields = null, $indexes = null, $options = null, $advancedOptions = null) deprecated

deprecated since version 4.0 Use DB::create_table instead

Parameters

$table
$fields
$indexes
$options
$advancedOptions

alterTable($table, $newFields = null, $newIndexes = null, $alteredFields = null, $alteredIndexes = null, $alteredOptions = null, $advancedOptions = null) deprecated

deprecated since version 4.0 Use DB::get_schema()->alterTable() instead

Parameters

$table
$newFields
$newIndexes
$alteredFields
$alteredIndexes
$alteredOptions
$advancedOptions

renameTable($oldTableName, $newTableName) deprecated

deprecated since version 4.0 Use DB::get_schema()->renameTable() instead

Parameters

$oldTableName
$newTableName

createField($table, $field, $spec) deprecated

deprecated since version 4.0 Use DB::create_field() instead

Parameters

$table
$field
$spec

renameField($tableName, $oldName, $newName) deprecated

deprecated since version 4.0 Use DB::get_schema()->renameField() instead

Parameters

$tableName
$oldName
$newName

currentDatabase() deprecated

deprecated since version 4.0 Use getSelectedDatabase instead

fieldList($table) deprecated

deprecated since version 4.0 Use DB::field_list instead

Parameters

$table

tableList() deprecated

deprecated since version 4.0 Use DB::table_list instead

hasTable($tableName) deprecated

deprecated since version 4.0 Use DB::get_schema()->hasTable() instead

Parameters

$tableName

enumValuesForField($tableName, $fieldName) deprecated

deprecated since version 4.0 Use DB::get_schema()->enumValuesForField() instead

Parameters

$tableName
$fieldName

addslashes($value) deprecated

deprecated since version 4.0 Use Convert::raw2sql instead

Parameters

$value

beginSchemaUpdate() deprecated

deprecated since version 3.2 Use DB::get_schema()->schemaUpdate with a callback instead

endSchemaUpdate() deprecated

deprecated since version 3.2 Use DB::get_schema()->schemaUpdate with a callback instead

cancelSchemaUpdate() deprecated

deprecated since version 4.0 Use DB::get_schema()->cancelSchemaUpdate instead

isSchemaUpdating() deprecated

deprecated since version 4.0 Use DB::get_schema()->isSchemaUpdating() instead

doesSchemaNeedUpdating() deprecated

deprecated since version 4.0 Use DB::get_schema()->doesSchemaNeedUpdating() instead

transCreateTable($table, $options = null, $advanced_options = null) deprecated

deprecated since version 4.0 Use DB::get_schema()->transCreateTable() instead

Parameters

$table
$options
$advanced_options

transAlterTable($table, $options, $advanced_options) deprecated

deprecated since version 4.0 Use DB::get_schema()->transAlterTable() instead

Parameters

$table
$options
$advanced_options

transCreateField($table, $field, $schema) deprecated

deprecated since version 4.0 Use DB::get_schema()->transCreateField() instead

Parameters

$table
$field
$schema

transCreateIndex($table, $index, $schema) deprecated

deprecated since version 4.0 Use DB::get_schema()->transCreateIndex() instead

Parameters

$table
$index
$schema

transAlterField($table, $field, $schema) deprecated

deprecated since version 4.0 Use DB::get_schema()->transAlterField() instead

Parameters

$table
$field
$schema

transAlterIndex($table, $index, $schema) deprecated

deprecated since version 4.0 Use DB::get_schema()->transAlterIndex() instead

Parameters

$table
$index
$schema

requireTable($table, $fieldSchema = null, $indexSchema = null, $hasAutoIncPK = true, $options = array(), $extensions = false) deprecated

deprecated since version 4.0 Use DB::require_table() instead

Parameters

$table
$fieldSchema
$indexSchema
$hasAutoIncPK
$options
$extensions

dontRequireTable($table) deprecated

deprecated since version 4.0 Use DB::dont_require_table() instead

Parameters

$table

requireIndex($table, $index, $spec) deprecated

deprecated since version 4.0 Use DB::require_index() instead

Parameters

$table
$index
$spec

hasField($tableName, $fieldName) deprecated

deprecated since version 4.0 Use DB::get_schema()->hasField() instead

Parameters

$tableName
$fieldName

requireField($table, $field, $spec) deprecated

deprecated since version 4.0 Use DB::require_field() instead

Parameters

$table
$field
$spec

dontRequireField($table, $fieldName) deprecated

deprecated since version 4.0 Use DB::dont_require_field() instead

Parameters

$table
$fieldName

sqlQueryToString(SQLExpression $query, $parameters = array()) deprecated

deprecated since version 4.0 Use DB::build_sql() instead

Parameters

SQLExpression $query
$parameters

static set_connection_charset($charset = 'utf8') deprecated

deprecated 4.0 Use "MySQLDatabase.connection_charset" config setting instead

Parameters

$charset

setSQLMode(string $mode)

Sets the SQL mode

Parameters

string $mode

Connection mode

selectTimezone(string $timezone)

Sets the system timezone for the database connection

Parameters

string $timezone