<?php
/**
 * @file
 * Install hooks for Data module.
 */

/**
 * Implements hook_schema().
 */
function data_schema() {
  $schema['data_tables'] = array(
    'description' => 'Tables managed by Data module.',
    'export' => array(
      'key' => 'name',
      'identifier' => 'data_table',
      'default hook' => 'data_default', // Function hook name.
      'api' => array(
        'owner' => 'data',
        'api' => 'data_default', // Base name for api include files.
        'minimum_version' => 1,
        'current_version' => 1,
      ),
    ),
    'fields' => array(
      'title' => array(
        'type' => 'varchar',
        'length' => '255',
        'not null' => TRUE,
        'default' => '',
        'description' => 'Natural name of the table.',
      ),
      'name' => array(
        'type' => 'varchar',
        'length' => '128',
        'not null' => TRUE,
        'default' => '',
        'description' => 'Table name.',
      ),
      'table_schema' => array(
        'type' => 'text',
        'not null' => FALSE,
        'description' => 'Table schema.',
        'serialize' => TRUE,
      ),
      'meta' => array(
        'type' => 'text',
        'not null' => FALSE,
        'description' => 'Meta information about the table and its fields.',
        'serialize' => TRUE,
      ),
    ),
    'primary key' => array('name'),
  );
  return $schema;
}

/**
 * Implements hook_schema_alter().
 *
 * This is a central piece of data module:
 * Here we tack schema information that has been defined through the API in data_tables
 * or by hook_data_default onto the $schema array.
 *
 * We do not use hook_schema() for exposing schema information as this would cause a race
 * condition: ctools/exports looks for data module's data_tables at the same time when
 * we are actually rebuilding it - follow path through
 * data_get_all_tables() ... _data_load_table() ... ctools_export_load_object().
 *
 * TODO: This is still rather hairy, and needs more work.
 * In the meantime, it's probably best to enable CTools first, and then Data
 * rather than both together.
 */
function data_schema_alter(&$schema) {
  // Sidestep this during installation, as otherwise this is circular:
  // data_get_all_tables() calls ctools stuff, which calls the schema, and
  // gets us right back here.
  if (drupal_get_installed_schema_version('data') != SCHEMA_UNINSTALLED) {
    $tables = data_get_all_tables(TRUE);
    foreach ($tables as $table) {
      // Only add table if not yet present or the table at hand is defined in DB.
      // This allows other modules to "own" data managed tables which in turn makes Drupal
      // track schema versions - the prerequisit for using hook_update_N() on data tables.
      if (!isset($schema[$table->get('name')]) || (EXPORT_IN_DATABASE & $table->get('export_type'))) {
        $table_schema = $table->get('table_schema');
        // @todo: figure out why we need this check here and why for WTF
        // reasons, we sometimes get here and get nada for $table_schema.
        if (isset($table_schema)) {
          $table_schema += array(
            'module' => 'data',
          );
          $schema[$table->get('name')] = $table_schema;
        }
      }
    }
  }
}

/**
 * Implements hook_install().
 */
function data_install() {
  // Refresh the schema to include it.
  // This ensures we include all our schema tables once our initial
  // installation is done, as data_schema_alter() sidesteps our schema tables
  // during installation.
  drupal_get_schema(NULL, TRUE);
}

/**
 * Implements hook_uninstall().
 */
function data_uninstall() {
  // Remove tables.
  // TODO The drupal_(un)install_schema functions are called automatically in D7.
  // drupal_uninstall_schema('data')
}

/**
 * Move join information into meta fields.
 */
function data_update_6001() {
  $ret = array();
  $result = db_query('SELECT * FROM {data_join}');
  while ($row = db_fetch_object($result)) {
    if ($table = data_get_table($row->right_table)) {
      $table->link($row->left_table, $row->left_field, $row->right_field, $row->inner_join ? TRUE : FALSE);
    }
  }
  db_drop_table('data_join');
  // hook_update_N() no longer returns a $ret array. Instead, return
  // nothing or a translated string indicating the update ran successfully.
  // See http://drupal.org/node/224333#update_sql.
  return t('TODO Add a descriptive string here to show in the UI.') /* $ret */;
}

/**
 * Add a primary key, required by CTools. Shorten name key to 128 char max.
 */
function data_update_6002() {
  $ret = array();
  db_drop_index('data_tables', 'name');
  $spec = array(
    'type' => 'varchar',
    'length' => '128',
    'not null' => TRUE,
    'default' => '',
    'description' => 'Table name.',
  );
  db_change_field('data_tables', 'name', 'name', $spec);
  db_add_primary_key('data_tables', array('name'));
  // reset cTools static cache of this table; otherwise it throws an error about
  // lacking a primary key, which just adds insult to injury as we're trying to fix that!
  drupal_get_schema('data_tables', TRUE);
  if (function_exists('drupal_static_reset')) {
    drupal_static_reset('ctools_export_get_schema');
  }
  // hook_update_N() no longer returns a $ret array. Instead, return
  // nothing or a translated string indicating the update ran successfully.
  // See http://drupal.org/node/224333#update_sql.
  return t('TODO Add a descriptive string here to show in the UI.') /* $ret */;
}
