drupal_get_schema

Definition

drupal_get_schema($table = NULL, $rebuild = FALSE)
drupal/includes/bootstrap.inc, line 1336

Description

Get the schema definition of a table, or the whole database schema.

The returned schema will include any modifications made by any module that implements hook_schema_alter().

Parameters

$table The name of the table. If not given, the schema of all tables is returned.

$rebuild If true, the schema will be rebuilt instead of retrieved from the cache.

Related topics

Namesort iconDescription
Input validationFunctions to validate user input.
Schema APIA 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.

Code

function drupal_get_schema($table = NULL, $rebuild = FALSE) {
  static $schema = array();

  if (empty($schema) || $rebuild) {
    // Try to load the schema from cache.
    if (!$rebuild && $cached = cache_get('schema')) {
      $schema = $cached->data;
    }
    // Otherwise, rebuild the schema cache.
    else {
      $schema = array();
      // Load the .install files to get hook_schema.
      // On some databases this function may be called before bootstrap has
      // been completed, so we force the functions we need to load just in case.
      if (drupal_function_exists('module_load_all_includes')) {

        // There is currently a bug in module_list() where it caches what it
        // was last called with, which is not always what you want.
        // module_load_all_includes() calls module_list(), but if this function
        // is called very early in the bootstrap process then it will be
        // uninitialized and therefore return no modules.  Instead, we have to
        // "prime" module_list() here to to values we want, specifically
        // "yes rebuild the list and don't limit to bootstrap".
        // TODO: Remove this call after http://drupal.org/node/222109 is fixed.
        module_list(TRUE, FALSE);
        module_load_all_includes('install');
      }

      // Invoke hook_schema for all modules.
      foreach (module_implements('schema') as $module) {
        $current = module_invoke($module, 'schema');
        require_once DRUPAL_ROOT . '/includes/common.inc';
        if (drupal_function_exists('_drupal_initialize_schema')) {
          _drupal_initialize_schema($module, $current);
        }

        $schema = array_merge($schema, $current);
      }

      if (drupal_function_exists('drupal_alter')) {
        drupal_alter('schema', $schema);
      }

      if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL) {
        cache_set('schema', $schema);
      }
    }
  }

  if (!isset($table)) {
    return $schema;
  }
  elseif (isset($schema[$table])) {
    return $schema[$table];
  }
  else {
    return FALSE;
  }
}