You are here

function geolocation_update_7101 in Geolocation Field 7

Increase precision of Geolocation Field data columns: lat_sin, lat_cos, lng_rad

File

./geolocation.install, line 62
Install/Update/Uninstall functions for geolocation_field module

Code

function geolocation_update_7101() {
  $fields = geolocation_get_geolocation_fields();
  foreach ($fields as $field) {
    $tables = array(
      _field_sql_storage_tablename($field),
      _field_sql_storage_revision_tablename($field),
    );
    foreach ($tables as $table) {
      $field_name = $field['field_name'];

      // eg 'field_mygeolocname' ;
      // Convert three db columns from float to double precision
      $columns = array(
        $field_name . '_lat_sin',
        $field_name . '_lat_cos',
        $field_name . '_lng_rad',
      );
      $spec = array(
        'type' => 'float',
        'size' => 'big',
        'not null' => TRUE,
        'default' => 0.0,
      );
      foreach ($columns as $column) {
        db_change_field($table, $column, $column, $spec);
      }

      // Now update these columns by re-calculating and re-storing existing values
      $column_lat = $field_name . '_lat';
      $column_lng = $field_name . '_lng';
      $query = db_select($table, 'g')
        ->fields('g', array(
        'revision_id',
        'delta',
        $column_lat,
        $column_lng,
      ));
      $results = $query
        ->execute();
      foreach ($results as $row) {
        $lat_rad = deg2rad($row->{$column_lat});
        $lat_sin = sin($lat_rad);
        $lat_cos = cos($lat_rad);
        $lng_rad = deg2rad($row->{$column_lng});

        // Cannot use drupal_write_record() within hook_update_N(), as the database
        // schema cannot be relied on when a user is running a series of updates.
        $updated = db_update($table)
          ->fields(array(
          $columns[0] => $lat_sin,
          $columns[1] => $lat_cos,
          $columns[2] => $lng_rad,
        ))
          ->condition('revision_id', $row->revision_id)
          ->condition('delta', $row->delta)
          ->execute();
      }
    }
  }
  return t('Geolocation Field data columns lat_sin, lat_cos, lng_rad converted to double precision.');
}