Drupal 8  8.0.2
Schema API

Data Structures

class  Schema
 

Functions

 db_create_table ($name, $table)
 
 db_field_names ($fields)
 
 db_index_exists ($table, $name)
 
 db_table_exists ($table)
 
 db_field_exists ($table, $field)
 
 db_find_tables ($table_expression)
 
 db_rename_table ($table, $new_name)
 
 db_drop_table ($table)
 
 db_add_field ($table, $field, $spec, $keys_new=array())
 
 db_drop_field ($table, $field)
 
 db_field_set_default ($table, $field, $default)
 
 db_field_set_no_default ($table, $field)
 
 db_add_primary_key ($table, $fields)
 
 db_drop_primary_key ($table)
 
 db_add_unique_key ($table, $name, $fields)
 
 db_drop_unique_key ($table, $name)
 
 db_add_index ($table, $name, $fields, array $spec)
 
 db_drop_index ($table, $name)
 
 db_change_field ($table, $field, $field_new, $spec, $keys_new=array())
 
 drupal_get_schema_versions ($module)
 
 drupal_get_installed_schema_version ($module, $reset=FALSE, $array=FALSE)
 
 drupal_set_installed_schema_version ($module, $version)
 
 drupal_install_schema ($module)
 
 drupal_uninstall_schema ($module)
 
 drupal_get_module_schema ($module, $table=NULL)
 
 _drupal_schema_initialize (&$schema, $module, $remove_descriptions=TRUE)
 
 drupal_schema_get_field_value (array $info, $value)
 
 hook_schema ()
 

Variables

const SCHEMA_UNINSTALLED = -1
 

Detailed Description

API to handle database schemas.

A Drupal schema definition is an array structure representing one or more tables and their related keys and indexes. A schema is defined by hook_schema(), which usually lives in a modulename.install file.

By implementing hook_schema() and specifying the tables your module declares, you can easily create and drop these tables on all supported database engines. You don't have to deal with the different SQL dialects for table creation and alteration of the supported database engines.

hook_schema() should return an array with a key for each table that the module defines.

The following keys are defined:

'primary key': An array of one or more key column specifiers (see below) that form the primary key.

A key column specifier is either a string naming a column or an array of two elements, column name and length, specifying a prefix of the named column.

As an example, here is a SUBSET of the schema definition for Drupal's 'node' table. It show four fields (nid, vid, type, and title), the primary key on field 'nid', a unique key named 'vid' on field 'vid', and two indexes, one named 'nid' on field 'nid' and one named 'node_title_type' on the field 'title' and the first four bytes of the field 'type':

$schema['node'] = array(
'description' => 'The base table for nodes.',
'fields' => array(
'nid' => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
'vid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE,'default' => 0),
'type' => array('type' => 'varchar','length' => 32,'not null' => TRUE, 'default' => ''),
'language' => array('type' => 'varchar','length' => 12,'not null' => TRUE,'default' => ''),
'title' => array('type' => 'varchar','length' => 255,'not null' => TRUE, 'default' => ''),
'uid' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
'status' => array('type' => 'int', 'not null' => TRUE, 'default' => 1),
'created' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
'changed' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
'comment' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
'promote' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
'moderate' => array('type' => 'int', 'not null' => TRUE,'default' => 0),
'sticky' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
'translate' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
),
'indexes' => array(
'node_changed' => array('changed'),
'node_created' => array('created'),
'node_moderate' => array('moderate'),
'node_frontpage' => array('promote', 'status', 'sticky', 'created'),
'node_status_type' => array('status', 'type', 'nid'),
'node_title_type' => array('title', array('type', 4)),
'node_type' => array(array('type', 4)),
'uid' => array('uid'),
'translate' => array('translate'),
),
'unique keys' => array(
'vid' => array('vid'),
),
// For documentation purposes only; foreign keys are not created in the
// database.
'foreign keys' => array(
'node_revision' => array(
'table' => 'node_field_revision',
'columns' => array('vid' => 'vid'),
),
'node_author' => array(
'table' => 'users',
'columns' => array('uid' => 'uid'),
),
),
'primary key' => array('nid'),
);
See Also
drupal_install_schema()

End of "addtogroup database".

Function Documentation

_drupal_schema_initialize ( $schema,
  $module,
  $remove_descriptions = TRUE 
)

Fills in required default values for table definitions from hook_schema().

Parameters
array$schemaThe schema definition array as it was returned by the module's hook_schema().
string$moduleThe module for which hook_schema() was invoked.
bool$remove_descriptions(optional) Whether to additionally remove 'description' keys of all tables and fields to improve performance of serialize() and unserialize(). Defaults to TRUE.

Referenced by drupal_install_schema(), and drupal_uninstall_schema().

Here is the caller graph for this function:

db_add_field (   $table,
  $field,
  $spec,
  $keys_new = array() 
)

Adds a new field to a table.

Parameters
$tableName of the table to be altered.
$fieldName of the field to be added.
array$specThe field specification array, as taken from a schema definition. The specification may also contain the key 'initial'; the newly-created field will be set to the value of the key in all rows. This is most useful for creating NOT NULL columns with no default value in existing tables.
array$keys_new(optional) Keys and indexes specification to be created on the table along with adding the field. The format is the same as a table specification, but without the 'fields' element. If you are adding a type 'serial' field, you MUST specify at least one key or index including it in this array. See db_change_field() for more explanation why.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call addField() on it. For example, $injected_database->schema()->addField($table, $field, $spec, $keys_new);
See Also
::addField()
db_change_field()

Referenced by SchemaTest\assertFieldAdditionRemoval(), SchemaTest\testSchema(), and SchemaTest\testUnsignedColumns().

Here is the caller graph for this function:

db_add_index (   $table,
  $name,
  $fields,
array  $spec 
)

Adds an index.

Parameters
$tableThe table to be altered.
$nameThe name of the index.
array$fieldsAn array of field names.
array$specThe table specification of the table to be altered, as taken from a schema definition. See ::addIndex() for how to obtain this specification.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call addIndex() on it. For example, $injected_database->schema()->addIndex($table, $name, $fields, $spec);
See Also
hook_schema()
Schema API
::addIndex()

Referenced by SchemaTest\testSchema().

Here is the caller graph for this function:

db_add_primary_key (   $table,
  $fields 
)

Adds a primary key to a database table.

Parameters
$tableName of the table to be altered.
$fieldsArray of fields for the primary key.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call addPrimaryKey() on it. For example, $injected_database->schema()->addPrimaryKey($table, $fields);
See Also
::addPrimaryKey()
db_add_unique_key (   $table,
  $name,
  $fields 
)

Adds a unique key.

Parameters
$tableThe table to be altered.
$nameThe name of the key.
array$fieldsAn array of field names.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call addUniqueKey() on it. For example, $injected_database->schema()->addUniqueKey($table, $name, $fields);
See Also
::addUniqueKey()
db_change_field (   $table,
  $field,
  $field_new,
  $spec,
  $keys_new = array() 
)

Changes a field definition.

IMPORTANT NOTE: To maintain database portability, you have to explicitly recreate all indices and primary keys that are using the changed field.

That means that you have to drop all affected keys and indexes with db_drop_{primary_key,unique_key,index}() before calling db_change_field(). To recreate the keys and indices, pass the key definitions as the optional $keys_new argument directly to db_change_field().

For example, suppose you have:

$schema['foo'] = array(
'fields' => array(
'bar' => array('type' => 'int', 'not null' => TRUE)
),
'primary key' => array('bar')
);

and you want to change foo.bar to be type serial, leaving it as the primary key. The correct sequence is:

db_change_field('foo', 'bar', 'bar',
array('type' => 'serial', 'not null' => TRUE),
array('primary key' => array('bar')));

The reasons for this are due to the different database engines:

On PostgreSQL, changing a field definition involves adding a new field and dropping an old one which causes any indices, primary keys and sequences (from serial-type fields) that use the changed field to be dropped.

On MySQL, all type 'serial' fields must be part of at least one key or index as soon as they are created. You cannot use db_add_{primary_key,unique_key,index}() for this purpose because the ALTER TABLE command will fail to add the column without a key or index specification. The solution is to use the optional $keys_new argument to create the key or index at the same time as field.

You could use db_add_{primary_key,unique_key,index}() in all cases unless you are converting a field to be type serial. You can use the $keys_new argument in all cases.

Parameters
$tableName of the table.
$fieldName of the field to change.
$field_newNew name for the field (set to the same as $field if you don't want to change the name).
$specThe field specification for the new field.
array$keys_new(optional) Keys and indexes specification to be created on the table along with changing the field. The format is the same as a table specification but without the 'fields' element.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call changeField() on it. For example, $injected_database->schema()->changeField($table, $field, $field_new, $spec, $keys_new);
See Also
::changeField()

Referenced by SchemaTest\assertFieldChange(), and SchemaTest\testSchema().

Here is the caller graph for this function:

db_create_table (   $name,
  $table 
)

Creates a new table from a Drupal table definition.

Parameters
string$nameThe name of the table to create.
array$tableA Schema API table definition array.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call createTable() on it. For example, $injected_database->schema()->createTable($name, $table);
See Also
::createTable()

Referenced by SchemaTest\assertFieldAdditionRemoval(), SchemaTest\assertFieldChange(), drupal_install_schema(), TransactionTest\executeDDLStatement(), SchemaTest\testIndexLength(), SchemaTest\testSchema(), SchemaTest\testUnsignedColumns(), and TransactionTest\transactionInnerLayer().

Here is the caller graph for this function:

db_drop_field (   $table,
  $field 
)

Drops a field.

Parameters
$tableThe table to be altered.
$fieldThe field to be dropped.
Returns
bool TRUE if the field was successfully dropped, FALSE if there was no field by that name to begin with.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call dropField() on it. For example, $injected_database->schema()->dropField($table, $field);
See Also
::dropField()

Referenced by SchemaTest\assertFieldAdditionRemoval().

Here is the caller graph for this function:

db_drop_index (   $table,
  $name 
)

Drops an index.

Parameters
$tableThe table to be altered.
$nameThe name of the index.
Returns
bool TRUE if the index was successfully dropped, FALSE if there was no index by that name to begin with.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call dropIndex() on it. For example, $injected_database->schema()->dropIndex($table, $name);
See Also
::dropIndex()
db_drop_primary_key (   $table)

Drops the primary key of a database table.

Parameters
$tableName of the table to be altered.
Returns
bool TRUE if the primary key was successfully dropped, FALSE if there was no primary key on this table to begin with.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call dropPrimaryKey() on it. For example, $injected_database->schema()->dropPrimaryKey($table);
See Also
::dropPrimaryKey()
db_drop_table (   $table)

Drops a table.

Parameters
$tableThe table to be dropped.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call dropTable() on it. For example, $injected_database->schema()->dropTable($table);
See Also
::dropTable()

Referenced by SchemaTest\assertFieldAdditionRemoval(), SchemaTest\assertFieldChange(), drupal_uninstall_schema(), and SchemaTest\testSchema().

Here is the caller graph for this function:

db_drop_unique_key (   $table,
  $name 
)

Drops a unique key.

Parameters
$tableThe table to be altered.
$nameThe name of the key.
Returns
bool TRUE if the key was successfully dropped, FALSE if there was no key by that name to begin with.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call dropUniqueKey() on it. For example, $injected_database->schema()->dropUniqueKey($table, $name);
See Also
::dropUniqueKey()
db_field_exists (   $table,
  $field 
)

Checks if a column exists in the given table.

Parameters
$tableThe name of the table in drupal (no prefixing).
$fieldThe name of the field.
Returns
bool TRUE if the given column exists, otherwise FALSE.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call fieldExists() on it. For example, $injected_database->schema()->fieldExists($table, $field);
See Also
::fieldExists()

Referenced by RegressionTest\testDBFieldExists(), ContentTranslationSettingsApiTest\testSettingsApi(), and SchemaTest\testUnsignedColumns().

Here is the caller graph for this function:

db_field_names (   $fields)

Returns an array of field names from an array of key/index column specifiers.

This is usually an identity function but if a key/index uses a column prefix specification, this function extracts just the name.

Parameters
array$fieldsAn array of key/index column specifiers.
Returns
array An array of field names.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call fieldNames() on it. For example, $injected_database->schema()->fieldNames($fields);
See Also
::fieldNames()
db_field_set_default (   $table,
  $field,
  $default 
)

Sets the default value for a field.

Parameters
$tableThe table to be altered.
$fieldThe field to be altered.
$defaultDefault value to be set. NULL for 'default NULL'.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call fieldSetDefault() on it. For example, $injected_database->schema()->fieldSetDefault($table, $field, $default);
See Also
::fieldSetDefault()

Referenced by SchemaTest\testSchema().

Here is the caller graph for this function:

db_field_set_no_default (   $table,
  $field 
)

Sets a field to have no default value.

Parameters
$tableThe table to be altered.
$fieldThe field to be altered.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call fieldSetNoDefault() on it. For example, $injected_database->schema()->fieldSetNoDefault($table, $field);
See Also
::fieldSetNoDefault()

Referenced by SchemaTest\testSchema().

Here is the caller graph for this function:

db_find_tables (   $table_expression)

Finds all tables that are like the specified base table name.

Parameters
string$table_expressionAn SQL expression, for example "simpletest%" (without the quotes).
Returns
array Array, both the keys and the values are the matching tables.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call findTables() on it. For example, $injected_database->schema()->findTables($table_expression);
See Also
::findTables()

Referenced by ModuleTestBase\assertTableCount().

Here is the caller graph for this function:

db_index_exists (   $table,
  $name 
)

Checks if an index exists in the given table.

Parameters
string$tableThe name of the table in drupal (no prefixing).
string$nameThe name of the index in drupal (no prefixing).
Returns
bool TRUE if the given index exists, otherwise FALSE.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call indexExists() on it. For example, $injected_database->schema()->indexExists($table, $name);
See Also
::indexExists()

Referenced by RegressionTest\testDBIndexExists(), SqlContentEntityStorageSchemaIndexTest\testIndex(), UpdatePathTestBaseTest\testUpdateHookN(), and UpdateSchemaTest\testUpdateHooks().

Here is the caller graph for this function:

db_rename_table (   $table,
  $new_name 
)

Renames a table.

Parameters
$tableThe current name of the table to be renamed.
$new_nameThe new name for the table.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call renameTable() on it. For example, $injected_database->schema()->renameTable($table, $new_name);
See Also
::renameTable()

Referenced by SchemaTest\testSchema().

Here is the caller graph for this function:

db_table_exists (   $table)

Checks if a table exists.

Parameters
string$tableThe name of the table in drupal (no prefixing).
Returns
bool TRUE if the given table exists, otherwise FALSE.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container, get its schema driver, and call tableExists() on it. For example, $injected_database->schema()->tableExists($table);
See Also
::tableExists()

Referenced by ModuleTestBase\assertModuleTablesDoNotExist(), ModuleTestBase\assertModuleTablesExist(), drupal_uninstall_schema(), RegressionTest\testDBTableExists(), KernelTestBaseTest\testEnableModulesInstall(), FieldSqlStorageTest\testFieldUpdateFailure(), KernelTestBaseTest\testInstallEntitySchema(), KernelTestBaseTest\testInstallSchema(), SchemaTest\testSchema(), KernelTestBaseTest\testSetUp(), and TemporaryQueryTest\testTemporaryQuery().

Here is the caller graph for this function:

drupal_get_installed_schema_version (   $module,
  $reset = FALSE,
  $array = FALSE 
)

Returns the currently installed schema version for a module.

Parameters
string$moduleA module name.
bool$resetSet to TRUE after installing or uninstalling an extension.
bool$arraySet to TRUE if you want to get information about all modules in the system.
Returns
string|int The currently installed schema version, or SCHEMA_UNINSTALLED if the module is not installed.

References Drupal\keyValue(), and SCHEMA_UNINSTALLED.

Referenced by ModulesUninstallForm\buildForm(), drupal_set_installed_schema_version(), UpdatePathRC1TestBaseTest\testDatabaseLoaded(), UpdatePathTestBaseTest\testDatabaseLoaded(), ModuleHandlerTest\testDependencyResolution(), InstallTest\testRequiredModuleSchemaVersions(), UpdateScriptTest\testRequirements(), UpdateScriptTest\testSuccessfulUpdateFunctionality(), ModuleHandlerTest\testUninstallContentDependency(), ModuleHandlerTest\testUninstallProfileDependency(), UpdatePathTestBaseTest\testUpdateHookN(), UpdateSchemaTest\testUpdateHooks(), and UpdateScriptTest\updateScriptTest().

Here is the call graph for this function:

Here is the caller graph for this function:

drupal_get_module_schema (   $module,
  $table = NULL 
)

Returns a module's schema.

This function can be used to retrieve a schema specification in hook_schema(), so it allows you to derive your tables from existing specifications.

Parameters
string$moduleThe module to which the table belongs.
string$tableThe name of the table. If not given, the module's complete schema is returned.

References Drupal\moduleHandler().

Referenced by ModuleTestBase\assertModuleTablesDoNotExist(), ModuleTestBase\assertModuleTablesExist(), drupal_install_schema(), drupal_uninstall_schema(), InsertDefaultsTest\testDefaultInsert(), InsertDefaultsTest\testDefaultInsertWithFields(), KernelTestBaseTest\testEnableModulesInstall(), and KernelTestBaseTest\testInstallSchema().

Here is the call graph for this function:

Here is the caller graph for this function:

drupal_get_schema_versions (   $module)

Returns an array of available schema versions for a module.

Parameters
string$moduleA module name.
Returns
array|bool If the module has updates, an array of available updates sorted by version. Otherwise, FALSE.

References Drupal\moduleHandler().

Referenced by Module\getSchemaUpdates().

Here is the call graph for this function:

Here is the caller graph for this function:

drupal_install_schema (   $module)

Creates all tables defined in a module's hook_schema().

Parameters
string$moduleThe module for which the tables will be created.

References _drupal_schema_initialize(), db_create_table(), and drupal_get_module_schema().

Here is the call graph for this function:

drupal_schema_get_field_value ( array  $info,
  $value 
)

Typecasts values to proper datatypes.

MySQL PDO silently casts, e.g. FALSE and '' to 0, when inserting the value into an integer column, but PostgreSQL PDO does not. Look up the schema information and use that to correctly typecast the value.

Parameters
array$infoAn array describing the schema field info.
mixed$valueThe value to be converted.
Returns
mixed The converted value.

Referenced by SqlContentEntityStorage\mapToStorageRecord().

Here is the caller graph for this function:

drupal_set_installed_schema_version (   $module,
  $version 
)

Updates the installed version information for a module.

Parameters
string$moduleA module name.
string$versionThe new schema version.

References drupal_get_installed_schema_version(), and Drupal\keyValue().

Referenced by UpdateScriptTest\testRequirements(), UpdateScriptTest\testSuccessfulUpdateFunctionality(), DbUpdateController\triggerBatch(), and UpdateScriptTest\updateScriptTest().

Here is the call graph for this function:

Here is the caller graph for this function:

drupal_uninstall_schema (   $module)

Removes all tables defined in a module's hook_schema().

Parameters
string$moduleThe module for which the tables will be removed.

References _drupal_schema_initialize(), db_drop_table(), db_table_exists(), and drupal_get_module_schema().

Here is the call graph for this function:

hook_schema ( )

Define the current version of the database schema.

A Drupal schema definition is an array structure representing one or more tables and their related keys and indexes. A schema is defined by hook_schema() which must live in your module's .install file.

The tables declared by this hook will be automatically created when the module is installed, and removed when the module is uninstalled. This happens before hook_install() is invoked, and after hook_uninstall() is invoked, respectively.

By declaring the tables used by your module via an implementation of hook_schema(), these tables will be available on all supported database engines. You don't have to deal with the different SQL dialects for table creation and alteration of the supported database engines.

See the Schema API Handbook at https://www.drupal.org/node/146843 for details on schema definition structures. Note that foreign key definitions are for documentation purposes only; foreign keys are not created in the database, nor are they enforced by Drupal.

Returns
array A schema definition structure array. For each element of the array, the key is a table name and the value is a table structure definition.

Variable Documentation