<?php

/**
 * @file
 * Installation functions for Relation Endpoint field type module.
 */

/**
 * Implements hook_field_schema().
 */
function relation_endpoint_field_schema() {
  $columns = array(
    'entity_type' => array(
      'type' => 'varchar',
      'length' => 255,
      'not null' => TRUE,
      'default' => '',
      'description' => 'Entity_type of this relation end-point.',
    ),
    'entity_id' => array(
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
      'default' => 0,
      'description' => 'Entity_id of this relation end-point.',
    ),
    'r_index' => array(
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
      'default' => 0,
      'description' => 'The index of this row in this relation. The highest index in the relation is stored as "arity" in the relation table.',
    ),
  );
  return array(
    'columns' => $columns,
    'indexes' => array(
      'entity_type' => array('entity_type'),
      'entity_id' => array('entity_id'),
      'r_index' => array('r_index'),
    ),
  );
}

/**
 * Split combined index into separate indexes.
 */
function relation_endpoint_update_7001() {
  // Same index operations are performed to data and revision tables
  foreach (array('field_data_endpoints', 'field_revision_endpoints') as $table) {
    // Do not touch any indexes if field data table doesn't exist. This might
    // happen if there aren't any relation types created yet.
    if (!db_table_exists($table)) {
      continue;
    }
    // If old style index does not exist do not attempt to drop it and create
    // new indexes as these are probably already created by other means.
    // (eg. shared database)
    if (!db_index_exists($table, 'endpoints_relation')) {
      continue;
    }
    db_drop_index($table, 'endpoints_relation');
    db_add_index($table, 'endpoints_entity_type', array('endpoints_entity_type'));
    db_add_index($table, 'endpoints_entity_id', array('endpoints_entity_id'));
    db_add_index($table, 'endpoints_r_index', array('endpoints_r_index'));
  }
}
