Version: current

# Class SS_Database

Abstract database connectivity class. Sub-classes of this implement the actual database connection libraries

### Direct known subclasses

`MySQLDatabase`

Abstract
Package: sapphire\model
Located at sapphire/core/model/Database.php

## Methods summary

`abstract public `SS_Query`` | # `query( string $sql, integer $errorLevel = E_USER_ERROR )` Execute the given SQL query. This abstract function must be defined by subclasses as part of the actual implementation. It should return a subclass of SS_Query as the result. Execute the given SQL query. This abstract function must be defined by subclasses as part of the actual implementation. It should return a subclass of SS_Query as the result. #### Parameters $sql string $sql The SQL query to execute $errorLevel int $errorLevel The level of error reporting to enable for the query #### Returns ``SS_Query`` SS_Query
`abstract public integer` | # `getGeneratedID( mixed $table )` Get the autogenerated ID from the previous INSERT query. Get the autogenerated ID from the previous INSERT query. #### Returns `integer` int
`abstract public boolean` | # `isActive( )` Check if the connection to the database is active. Check if the connection to the database is active. #### Returns `boolean` boolean
`abstract public boolean` | # `createDatabase( )` Create the database and connect to it. This can be called if the initial database connection is not successful because the database does not exist. Create the database and connect to it. This can be called if the initial database connection is not successful because the database does not exist. It takes no parameters, and should create the database from the information specified in the constructor. #### Returns `boolean` Returns true if successful
`abstract public string` | # `getConnect( array $parameters )` Build the connection string from input Build the connection string from input #### Parameters $parameters array $parameters The connection details #### Returns `string` $connect The connection string
`abstract public The` | # `createTable( mixed $table, mixed $fields = null, mixed $indexes = null, mixed $options = null, mixed $advancedOptions = null )` Create a new table. Create a new table. #### Parameters $table $tableName The name of the table $fields $fields A map of field names to field types $indexes $indexes A map of indexes $options $options An map of additional options. The available keys are as follows: - 'MSSQLDatabase'/'MySQLDatabase'/'PostgreSQLDatabase' - database-specific options such as "engine" for MySQL. - 'temporary' - If true, then a temporary table will be created $advancedOptions #### Returns `The` table name generated. This may be different from the table name, for example with temporary tables.
`abstract public` | # `alterTable( mixed $table, mixed $newFields = null, mixed $newIndexes = null, mixed $alteredFields = null, mixed $alteredIndexes = null, mixed $alteredOptions = null, mixed $advancedOptions = null )` Alter a table's schema. Alter a table's schema.
`abstract public` | # `renameTable( string $oldTableName, string $newTableName )` Rename a table. Rename a table. #### Parameters $oldTableName string $oldTableName The old table name. $newTableName string $newTableName The new table name.
`abstract public` | # `createField( string $table, string $field, string $spec )` Create a new field on a table. Create a new field on a table. #### Parameters $table string $table Name of the table. $field string $field Name of the field to add. $spec string $spec The field specification, eg 'INTEGER NOT NULL'
`abstract public` | # `renameField( string $tableName, string $oldName, string $newName )` Change the database column name of the given field. Change the database column name of the given field. #### Parameters $tableName string $tableName The name of the tbale the field is in. $oldName string $oldName The name of the field to change. $newName string $newName The new name of the field
`abstract protected array` | # `fieldList( string $table )` Get a list of all the fields for the given table. Returns a map of field name => field spec. Get a list of all the fields for the given table. Returns a map of field name => field spec. #### Parameters $table string $table The table name. #### Returns `array` array
`abstract protected array` | # `tableList( )` Returns a list of all tables in the database. Keys are table names in lower case, values are table names in case that database expects. Returns a list of all tables in the database. Keys are table names in lower case, values are table names in case that database expects. #### Returns `array` array
`abstract public` | # `hasTable( mixed $tableName )` Returns true if the given table exists in the database Returns true if the given table exists in the database
`abstract public` | # `enumValuesForField( mixed $tableName, mixed $fieldName )` Returns the enum values available on the given field Returns the enum values available on the given field
`public` | # `beginSchemaUpdate( )` Start a schema-updating transaction. All calls to requireTable/Field/Index will keep track of the changes requested, but not actually do anything. Once Start a schema-updating transaction. All calls to requireTable/Field/Index will keep track of the changes requested, but not actually do anything. Once
`public` | # `endSchemaUpdate( )` Completes a schema-updated transaction, executing all the schema chagnes. Completes a schema-updated transaction, executing all the schema chagnes.
`public` | # `cancelSchemaUpdate( )` Cancels the schema updates requested after a beginSchemaUpdate() call. Cancels the schema updates requested after a beginSchemaUpdate() call.
`public` | # `doesSchemaNeedUpdating( )` Returns true if schema modifications were requested after a beginSchemaUpdate() call. Returns true if schema modifications were requested after a beginSchemaUpdate() call.
`public` | # `transCreateTable( string $table, string $options = null, mixed $advanced_options = null )` #### Parameters $table string $table $options string $options $advanced_options
`public` | # `transAlterTable( string $table, array $options, mixed $advanced_options )` #### Parameters $table string $table $options array $options $advanced_options
`public` | # `transCreateField( mixed $table, mixed $field, mixed $schema )`
`public` | # `transCreateIndex( mixed $table, mixed $index, mixed $schema )`
`public` | # `transAlterField( mixed $table, mixed $field, mixed $schema )`
`public` | # `transAlterIndex( mixed $table, mixed $index, mixed $schema )`
`protected` | # `transInitTable( mixed $table )` Handler for the other transXXX methods - mark the given table as being altered if it doesn't already exist Handler for the other transXXX methods - mark the given table as being altered if it doesn't already exist
`public` | # `requireTable( string $table, string $fieldSchema = null, string $indexSchema = null, array $hasAutoIncPK = true, mixed $options = Array(), mixed $extensions = false )` Generate the following table in the database, modifying whatever already exists as necessary. Generate the following table in the database, modifying whatever already exists as necessary. #### Parameters $table string $table The name of the table $fieldSchema string $fieldSchema A list of the fields to create, in the same form as DataObject::$db $indexSchema string $indexSchema A list of indexes to create. See `SS_Database::requireIndex()` $hasAutoIncPK array $options $options $extensions
`public` | # `dontRequireTable( string $table )` If the given table exists, move it out of the way by renaming it to _obsolete_(tablename). If the given table exists, move it out of the way by renaming it to _obsolete_(tablename). #### Parameters $table string $table The table name.
`public` | # `requireIndex( string $table, string $index, string|boolean $spec )` Generate the given index in the database, modifying whatever already exists as necessary. Generate the given index in the database, modifying whatever already exists as necessary. The keys of the array are the names of the index. The values of the array can be one of: - true: Create a single column index on the field named the same as the index. - array('type' => 'index|unique|fulltext', 'value' => 'FieldA, FieldB'): This gives you full control over the index. #### Parameters $table string $table The table name. $index string $index The index name. $spec string|boolean $spec The specification of the index. See requireTable() for more information.
`public` | # `requireField( string $table, string $field, array|string $spec )` Generate the given field on the table, modifying whatever already exists as necessary. Generate the given field on the table, modifying whatever already exists as necessary. #### Parameters $table string $table The table name. $field string $field The field name. $spec array|string $spec The field specification. If passed in array syntax, the specific database driver takes care of the ALTER TABLE syntax. If passed as a string, its assumed to be prepared as a direct SQL framgment ready for insertion into ALTER TABLE. In this case you'll need to take care of database abstraction in your DBField subclass.
`public` | # `dontRequireField( string $table, string $fieldName )` If the given field exists, move it out of the way by renaming it to _obsolete_(fieldname). If the given field exists, move it out of the way by renaming it to _obsolete_(fieldname). #### Parameters $table string $table $fieldName string $fieldName
`public` | # `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, including quotes. The field value can also be a SQL function or similar. 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, including quotes. The field value can also be a SQL function or similar. #### Parameters $manipulation array $manipulation
`public static` | # `replace_with_null( string & $array )` Replaces "\'\'" with "null", recursively walks through the given array. Replaces "\'\'" with "null", recursively walks through the given array. #### Parameters $array string $array Array where the replacement should happen
`public` | # `databaseError( string $msg, integer $errorLevel = E_USER_ERROR )` Error handler for database errors. All database errors will call this function to report the error. It isn't a static function; it will be called on the object itself and as such can be overridden in a subclass. Error handler for database errors. All database errors will call this function to report the error. It isn't a static function; it will be called on the object itself and as such can be overridden in a subclass. #### Parameters $msg string $msg The error message. $errorLevel int $errorLevel The level of the error to throw.
`public` | # `quiet( )` Enable supression of database messages. Enable supression of database messages.
`public` | # `alterationMessage( mixed $message, mixed $type = "" )` Show a message about database alteration Show a message about database alteration
`public` | # `sqlQueryToString( `SQLQuery` $sqlQuery )` Convert a SQLQuery object into a SQL statement Convert a SQLQuery object into a SQL statement
`abstract public 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 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 $date 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"' $format 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 #### Returns `string` SQL datetime expression to query for a formatted datetime
`abstract public string` | # `datetimeIntervalClause( string $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 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 $date, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"' $interval 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 #### Returns `string` SQL datetime expression to query for a datetime (YYYY-MM-DD hh:mm:ss) which is the result of the addition
`abstract public string` | # `datetimeDifferenceClause( string $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 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 $date1, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"' $date2 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"' #### Returns `string` SQL datetime expression to query for the interval between $date1 and $date2 in seconds which is the result of the substraction

### Magic methods summary

## Properties summary

`public static mixed` | $globalConn | # Connection object to the database. Connection object to the database. #### Param resource
`protected boolean` | $supressOutput | # If this is false, then information about database operations will be displayed, eg creation of tables. If this is false, then information about database operations will be displayed, eg creation of tables. #### Param boolean
`protected array` | $tableList | # The table list, generated by the tableList() function. Used by the requireTable() function. The table list, generated by the tableList() function. Used by the requireTable() function.
`protected array` | $fieldList | # The field list, generated by the fieldList() function. An array of maps of field name => field spec, indexed by table name. The field list, generated by the fieldList() function. An array of maps of field name => field spec, indexed by table name.
`protected array` | $indexList | # The index list for each table, generated by the indexList() function. An map from table name to an array of index names. The index list for each table, generated by the indexList() function. An map from table name to an array of index names.
`protected mixed` | $schemaUpdateTransaction | # Large array structure that represents a schema update transaction Large array structure that represents a schema update transaction

[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the Silverstripe Forums to ask development related questions. -