You are here

function search_api_update_7101 in Search API 7

Update function that adds the machine names for servers and indexes.

File

./search_api.install, line 465
Install, update and uninstall functions for the Search API module.

Code

function search_api_update_7101() {
  $tx = db_transaction();
  try {

    // Servers
    $spec = array(
      'description' => 'The machine name for a server.',
      'type' => 'varchar',
      'length' => 50,
      'not null' => TRUE,
      'default' => '',
    );
    db_add_field('search_api_server', 'machine_name', $spec);
    $names = array();
    $servers = db_select('search_api_server', 's')
      ->fields('s')
      ->execute();
    foreach ($servers as $server) {
      $base = $name = drupal_strtolower(preg_replace('/[^a-z0-9]+/i', '_', $server->name));
      $i = 0;
      while (isset($names[$name])) {
        $name = $base . '_' . ++$i;
      }
      $names[$name] = TRUE;
      db_update('search_api_server')
        ->fields(array(
        'machine_name' => $name,
      ))
        ->condition('id', $server->id)
        ->execute();
    }
    db_add_unique_key('search_api_server', 'machine_name', array(
      'machine_name',
    ));

    //Indexes
    $spec = array(
      'description' => 'The machine name of the index.',
      'type' => 'varchar',
      'length' => 50,
      'not null' => TRUE,
      'default' => '',
    );
    db_add_field('search_api_index', 'machine_name', $spec);
    $names = array();
    $indexes = db_select('search_api_index', 'i')
      ->fields('i')
      ->execute();
    foreach ($indexes as $index) {
      $base = $name = drupal_strtolower(preg_replace('/[^a-z0-9]+/i', '_', $index->name));
      $i = 0;
      while (isset($names[$name])) {
        $name = $base . '_' . ++$i;
      }
      $names[$name] = TRUE;
      db_update('search_api_index')
        ->fields(array(
        'machine_name' => $name,
      ))
        ->condition('id', $index->id)
        ->execute();
    }
    db_add_unique_key('search_api_index', 'machine_name', array(
      'machine_name',
    ));
  } catch (Exception $e) {
    $tx
      ->rollback();
    try {
      db_drop_field('search_api_server', 'machine_name');
      db_drop_field('search_api_index', 'machine_name');
    } catch (Exception $e1) {

      // Ignore.
    }
    throw new DrupalUpdateException(t('An exception occurred during the update: @msg.', array(
      '@msg' => $e
        ->getMessage(),
    )));
  }
}