class Database

Abstract database connectivity class.

Sub-classes of this implement the actual database connection libraries

Constants

PARTIAL_QUERY

FULL_QUERY

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

static 
setWhitelistQueryArray(array $whitelistArray)

Add the sql queries that need to be partially or fully matched

static array
getWhitelistQueryArray()

Get the sql queries that need to be partially or fully matched

integer
getGeneratedID(string $table)

Get the autogenerated ID from the previous INSERT query.

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

string
escapeIdentifier(string|array $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
nullCheckClause(string $field, bool $isNull)

Generates a WHERE clause for null comparison check

String
comparisonClause(String $field, String $value, boolean $exact = false, boolean $negate = false, boolean $caseSensitive = null, boolean $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, $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, $date2)

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

string
concatOperator()

String operator for concatenation of strings

boolean
supportsCollations()

Returns true if this database supports collations

Boolean
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, integer $start, integer $pageLength, string $sortBy = "Relevance DESC", string $extraFilter = "", boolean $booleanSearch = false, string $alternativeFileFilter = "", boolean $invertedMatch = false)

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

boolean
supportsTransactions()

Determines if this database supports transactions

boolean
supportsSavepoints()

Does this database support savepoints in transactions By default it is assumed that they don't unless they are explicitly enabled.

withTransaction(callable $callback, callable $errorCallback = null, bool|string $transactionMode = false, bool $errorIfTransactionsUnsupported = false)

Invoke $callback within a transaction

supportsExtensions($extensions)

No description

transactionStart(string|boolean $transactionMode = false, string|boolean $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

bool|null
transactionRollback(string|boolean $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

bool|null
transactionEnd(bool $chain = false)

Commit everything inside this transaction so far

int
transactionDepth()

Return depth of current transaction

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, integer $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

Details

at line 67
DBConnector getConnector()

Get the current connector

Return Value

DBConnector

at line 77
setConnector(DBConnector $connector)

Injector injection point for connector dependency

Parameters

DBConnector $connector

at line 94
DBSchemaManager getSchemaManager()

Returns the current schema manager

Return Value

DBSchemaManager

at line 104
setSchemaManager(DBSchemaManager $schemaManager)

Injector injection point for schema manager

Parameters

DBSchemaManager $schemaManager

at line 125
DBQueryBuilder getQueryBuilder()

Returns the current query builder

Return Value

DBQueryBuilder

at line 135
setQueryBuilder(DBQueryBuilder $queryBuilder)

Injector injection point for schema manager

Parameters

DBQueryBuilder $queryBuilder

at line 147
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

Query

at line 173
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

Query

at line 279
static setWhitelistQueryArray(array $whitelistArray)

Add the sql queries that need to be partially or fully matched

Parameters

array $whitelistArray

at line 289
static array getWhitelistQueryArray()

Get the sql queries that need to be partially or fully matched

Return Value

array

at line 300
integer 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

integer the most recently generated ID for the specified table

at line 311
boolean isActive()

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

Return Value

boolean Flag indicating that a valid database is connected

at line 323
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

at line 334
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

at line 348
string escapeIdentifier(string|array $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|array $value The identifier to escape or list of split components
string $separator Splitter for each component

Return Value

string

at line 388
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

at line 445
quiet()

Enable supression of database messages.

at line 453
clearAllData()

Clear all data out of the database

at line 466
clearTable(string $table)

Clear all data in a given table

Parameters

string $table Name of table

at line 478
string nullCheckClause(string $field, bool $isNull)

Generates a WHERE clause for null comparison check

Parameters

string $field Quoted field name
bool $isNull Whether to check for NULL or NOT NULL

Return Value

string Non-parameterised null comparison clause

at line 500
abstract String comparisonClause(String $field, String $value, boolean $exact = false, boolean $negate = false, boolean $caseSensitive = null, boolean $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.
boolean $exact Exact matches or wildcard support.
boolean $negate Negate the clause.
boolean $caseSensitive Enforce case sensitivity if TRUE or FALSE. Fallback to default collation if set to NULL.
boolean $parameterised Insert the ? placeholder rather than the given value. If this is true then $value is ignored.

Return Value

String SQL

at line 525
abstract 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

at line 546
abstract string datetimeIntervalClause($date, $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
$interval

Return Value

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

at line 559
abstract string datetimeDifferenceClause($date1, $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
$date2

Return Value

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

at line 566
string concatOperator()

String operator for concatenation of strings

Return Value

string

at line 577
abstract boolean supportsCollations()

Returns true if this database supports collations

Return Value

boolean

at line 585
abstract Boolean supportsTimezoneOverride()

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

Return Value

Boolean

at line 591
string getVersion()

Query for the version of the currently connected database

Return Value

string Version of this database

at line 603
abstract 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

at line 609
int affectedRows()

Return the number of rows affected by the previous operation.

Return Value

int

at line 629
abstract PaginatedList searchEngine(array $classesToSearch, string $keywords, integer $start, integer $pageLength, string $sortBy = "Relevance DESC", string $extraFilter = "", boolean $booleanSearch = false, string $alternativeFileFilter = "", boolean $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.
integer $start Item to start returning results from
integer $pageLength Number of items per page
string $sortBy Sort order expression
string $extraFilter Additional filter
boolean $booleanSearch Flag for boolean search mode
string $alternativeFileFilter
boolean $invertedMatch

Return Value

PaginatedList Search results

at line 646
abstract boolean supportsTransactions()

Determines if this database supports transactions

Return Value

boolean Flag indicating support for transactions

at line 654
boolean supportsSavepoints()

Does this database support savepoints in transactions By default it is assumed that they don't unless they are explicitly enabled.

Return Value

boolean Flag indicating support for savepoints in transactions

at line 669
withTransaction(callable $callback, callable $errorCallback = null, bool|string $transactionMode = false, bool $errorIfTransactionsUnsupported = false)

Invoke $callback within a transaction

Parameters

callable $callback Callback to run
callable $errorCallback Optional callback to run after rolling back transaction.
bool|string $transactionMode Optional transaction mode to use
bool $errorIfTransactionsUnsupported If true, this method will fail if transactions are unsupported. Otherwise, the $callback will potentially be invoked outside of a transaction.

Exceptions

Exception

at line 707
supportsExtensions($extensions)

Parameters

$extensions

at line 720
abstract transactionStart(string|boolean $transactionMode = false, string|boolean $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|boolean $transactionMode Transaction mode, or false to ignore
string|boolean $sessionCharacteristics Session characteristics, or false to ignore

at line 727
abstract transactionSavepoint(string $savepoint)

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

Parameters

string $savepoint Name of savepoint

at line 739
abstract bool|null transactionRollback(string|boolean $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|boolean $savepoint Name of savepoint, or leave empty to rollback to last savepoint

Return Value

bool|null Boolean is returned if success state is known, or null if unknown. Note: For error checking purposes null should not be treated as error.

at line 748
abstract bool|null transactionEnd(bool $chain = false)

Commit everything inside this transaction so far

Parameters

bool $chain

Return Value

bool|null Boolean is returned if success state is known, or null if unknown. Note: For error checking purposes null should not be treated as error.

at line 755
int transactionDepth()

Return depth of current transaction

Return Value

int Nesting level, or 0 if not in a transaction

at line 771
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

at line 783
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

at line 805
bool getLock(string $name, integer $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
integer $timeout Timeout in seconds

Return Value

bool

at line 817
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

at line 834
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

at line 858
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

at line 868
array databaseList()

Retrieves the list of all databases the user has access to

Return Value

array List of database names

at line 885
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

at line 911
dropSelectedDatabase()

Drop the database that this object is currently connected to.

Use with caution.

at line 925
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

at line 935
abstract string now()

Return SQL expression used to represent the current date/time

Return Value

string Expression for the current date/time

at line 942
abstract string random()

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

Return Value

string Expression for a random value