Projet

Général

Profil

Paste
Télécharger (28,1 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / field / modules / field_sql_storage / field_sql_storage.module @ 6ff32cea

1
<?php
2

    
3
/**
4
 * @file
5
 * Default implementation of the field storage API.
6
 */
7

    
8
/**
9
 * Implements hook_help().
10
 */
11
function field_sql_storage_help($path, $arg) {
12
  switch ($path) {
13
    case 'admin/help#field_sql_storage':
14
      $output = '';
15
      $output .= '<h3>' . t('About') . '</h3>';
16
      $output .= '<p>' . t('The Field SQL storage module stores field data in the database. It is the default field storage module; other field storage mechanisms may be available as contributed modules. See the <a href="@field-help">Field module help page</a> for more information about fields.', array('@field-help' => url('admin/help/field'))) . '</p>';
17
      return $output;
18
  }
19
}
20

    
21
/**
22
 * Implements hook_field_storage_info().
23
 */
24
function field_sql_storage_field_storage_info() {
25
  return array(
26
    'field_sql_storage' => array(
27
      'label' => t('Default SQL storage'),
28
      'description' => t('Stores fields in the local SQL database, using per-field tables.'),
29
    ),
30
  );
31
}
32

    
33
/**
34
 * Generate a table name for a field data table.
35
 *
36
 * @param $field
37
 *   The field structure.
38
 * @return
39
 *   A string containing the generated name for the database table
40
 */
41
function _field_sql_storage_tablename($field) {
42
  if ($field['deleted']) {
43
    return "field_deleted_data_{$field['id']}";
44
  }
45
  else {
46
    return "field_data_{$field['field_name']}";
47
  }
48
}
49

    
50
/**
51
 * Generate a table name for a field revision archive table.
52
 *
53
 * @param $name
54
 *   The field structure.
55
 * @return
56
 *   A string containing the generated name for the database table
57
 */
58
function _field_sql_storage_revision_tablename($field) {
59
  if ($field['deleted']) {
60
    return "field_deleted_revision_{$field['id']}";
61
  }
62
  else {
63
    return "field_revision_{$field['field_name']}";
64
  }
65
}
66

    
67
/**
68
 * Generates a table alias for a field data table.
69
 *
70
 * The table alias is unique for each unique combination of field name
71
 * (represented by $tablename), delta_group and language_group.
72
 *
73
 * @param $tablename
74
 *   The name of the data table for this field.
75
 * @param $field_key
76
 *   The numeric key of this field in this query.
77
 * @param $query
78
 *   The EntityFieldQuery that is executed.
79
 *
80
 * @return
81
 *   A string containing the generated table alias.
82
 */
83
function _field_sql_storage_tablealias($tablename, $field_key, EntityFieldQuery $query) {
84
  // No conditions present: use a unique alias.
85
  if (empty($query->fieldConditions[$field_key])) {
86
    return $tablename . $field_key;
87
  }
88

    
89
  // Find the delta and language condition values and append them to the alias.
90
  $condition = $query->fieldConditions[$field_key];
91
  $alias = $tablename;
92
  $has_group_conditions = FALSE;
93

    
94
  foreach (array('delta', 'language') as $column) {
95
    if (isset($condition[$column . '_group'])) {
96
      $alias .= '_' . $column . '_' . $condition[$column . '_group'];
97
      $has_group_conditions = TRUE;
98
    }
99
  }
100

    
101
  // Return the alias when it has delta/language group conditions.
102
  if ($has_group_conditions) {
103
    return $alias;
104
  }
105

    
106
  // Return a unique alias in other cases.
107
  return $tablename . $field_key;
108
}
109

    
110
/**
111
 * Generate a column name for a field data table.
112
 *
113
 * @param $name
114
 *   The name of the field
115
 * @param $column
116
 *   The name of the column
117
 * @return
118
 *   A string containing a generated column name for a field data
119
 *   table that is unique among all other fields.
120
 */
121
function _field_sql_storage_columnname($name, $column) {
122
  return $name . '_' . $column;
123
}
124

    
125
/**
126
 * Generate an index name for a field data table.
127
 *
128
 * @param $name
129
 *   The name of the field
130
 * @param $column
131
 *   The name of the index
132
 * @return
133
 *   A string containing a generated index name for a field data
134
 *   table that is unique among all other fields.
135
 */
136
function _field_sql_storage_indexname($name, $index) {
137
  return $name . '_' . $index;
138
}
139

    
140
/**
141
 * Return the database schema for a field. This may contain one or
142
 * more tables. Each table will contain the columns relevant for the
143
 * specified field. Leave the $field's 'columns' and 'indexes' keys
144
 * empty to get only the base schema.
145
 *
146
 * @param $field
147
 *   The field structure for which to generate a database schema.
148
 * @return
149
 *   One or more tables representing the schema for the field.
150
 */
151
function _field_sql_storage_schema($field) {
152
  $deleted = $field['deleted'] ? 'deleted ' : '';
153
  $current = array(
154
    'description' => "Data storage for {$deleted}field {$field['id']} ({$field['field_name']})",
155
    'fields' => array(
156
      'entity_type' => array(
157
        'type' => 'varchar',
158
        'length' => 128,
159
        'not null' => TRUE,
160
        'default' => '',
161
        'description' => 'The entity type this data is attached to',
162
      ),
163
      'bundle' => array(
164
        'type' => 'varchar',
165
        'length' => 128,
166
        'not null' => TRUE,
167
        'default' => '',
168
        'description' => 'The field instance bundle to which this row belongs, used when deleting a field instance',
169
      ),
170
      'deleted' => array(
171
        'type' => 'int',
172
        'size' => 'tiny',
173
        'not null' => TRUE,
174
        'default' => 0,
175
        'description' => 'A boolean indicating whether this data item has been deleted'
176
      ),
177
      'entity_id' => array(
178
        'type' => 'int',
179
        'unsigned' => TRUE,
180
        'not null' => TRUE,
181
        'description' => 'The entity id this data is attached to',
182
      ),
183
      'revision_id' => array(
184
        'type' => 'int',
185
        'unsigned' => TRUE,
186
        'not null' => FALSE,
187
        'description' => 'The entity revision id this data is attached to, or NULL if the entity type is not versioned',
188
      ),
189
      // @todo Consider storing language as integer.
190
      'language' => array(
191
        'type' => 'varchar',
192
        'length' => 32,
193
        'not null' => TRUE,
194
        'default' => '',
195
        'description' => 'The language for this data item.',
196
      ),
197
      'delta' => array(
198
        'type' => 'int',
199
        'unsigned' => TRUE,
200
        'not null' => TRUE,
201
        'description' => 'The sequence number for this data item, used for multi-value fields',
202
      ),
203
    ),
204
    'primary key' => array('entity_type', 'entity_id', 'deleted', 'delta', 'language'),
205
    'indexes' => array(
206
      'entity_type' => array('entity_type'),
207
      'bundle' => array('bundle'),
208
      'deleted' => array('deleted'),
209
      'entity_id' => array('entity_id'),
210
      'revision_id' => array('revision_id'),
211
      'language' => array('language'),
212
    ),
213
  );
214

    
215
  $field += array('columns' => array(), 'indexes' => array(), 'foreign keys' => array());
216
  // Add field columns.
217
  foreach ($field['columns'] as $column_name => $attributes) {
218
    $real_name = _field_sql_storage_columnname($field['field_name'], $column_name);
219
    $current['fields'][$real_name] = $attributes;
220
  }
221

    
222
  // Add indexes.
223
  foreach ($field['indexes'] as $index_name => $columns) {
224
    $real_name = _field_sql_storage_indexname($field['field_name'], $index_name);
225
    foreach ($columns as $column_name) {
226
      $current['indexes'][$real_name][] = _field_sql_storage_columnname($field['field_name'], $column_name);
227
    }
228
  }
229

    
230
  // Add foreign keys.
231
  foreach ($field['foreign keys'] as $specifier => $specification) {
232
    $real_name = _field_sql_storage_indexname($field['field_name'], $specifier);
233
    $current['foreign keys'][$real_name]['table'] = $specification['table'];
234
    foreach ($specification['columns'] as $column_name => $referenced) {
235
      $sql_storage_column = _field_sql_storage_columnname($field['field_name'], $column_name);
236
      $current['foreign keys'][$real_name]['columns'][$sql_storage_column] = $referenced;
237
    }
238
  }
239

    
240
  // Construct the revision table.
241
  $revision = $current;
242
  $revision['description'] = "Revision archive storage for {$deleted}field {$field['id']} ({$field['field_name']})";
243
  $revision['primary key'] = array('entity_type', 'entity_id', 'revision_id', 'deleted', 'delta', 'language');
244
  $revision['fields']['revision_id']['not null'] = TRUE;
245
  $revision['fields']['revision_id']['description'] = 'The entity revision id this data is attached to';
246

    
247
  return array(
248
    _field_sql_storage_tablename($field) => $current,
249
    _field_sql_storage_revision_tablename($field) => $revision,
250
  );
251
}
252

    
253
/**
254
 * Implements hook_field_storage_create_field().
255
 */
256
function field_sql_storage_field_storage_create_field($field) {
257
  $schema = _field_sql_storage_schema($field);
258
  foreach ($schema as $name => $table) {
259
    db_create_table($name, $table);
260
  }
261
  drupal_get_schema(NULL, TRUE);
262
}
263

    
264
/**
265
 * Implements hook_field_update_forbid().
266
 *
267
 * Forbid any field update that changes column definitions if there is
268
 * any data.
269
 */
270
function field_sql_storage_field_update_forbid($field, $prior_field, $has_data) {
271
  if ($has_data && $field['columns'] != $prior_field['columns']) {
272
    throw new FieldUpdateForbiddenException("field_sql_storage cannot change the schema for an existing field with data.");
273
  }
274
}
275

    
276
/**
277
 * Implements hook_field_storage_update_field().
278
 */
279
function field_sql_storage_field_storage_update_field($field, $prior_field, $has_data) {
280
  if (! $has_data) {
281
    // There is no data. Re-create the tables completely.
282

    
283
    if (Database::getConnection()->supportsTransactionalDDL()) {
284
      // If the database supports transactional DDL, we can go ahead and rely
285
      // on it. If not, we will have to rollback manually if something fails.
286
      $transaction = db_transaction();
287
    }
288

    
289
    try {
290
      $prior_schema = _field_sql_storage_schema($prior_field);
291
      foreach ($prior_schema as $name => $table) {
292
        db_drop_table($name, $table);
293
      }
294
      $schema = _field_sql_storage_schema($field);
295
      foreach ($schema as $name => $table) {
296
        db_create_table($name, $table);
297
      }
298
    }
299
    catch (Exception $e) {
300
      if (Database::getConnection()->supportsTransactionalDDL()) {
301
        $transaction->rollback();
302
      }
303
      else {
304
        // Recreate tables.
305
        $prior_schema = _field_sql_storage_schema($prior_field);
306
        foreach ($prior_schema as $name => $table) {
307
          if (!db_table_exists($name)) {
308
            db_create_table($name, $table);
309
          }
310
        }
311
      }
312
      throw $e;
313
    }
314
  }
315
  else {
316
    // There is data, so there are no column changes. Drop all the
317
    // prior indexes and create all the new ones, except for all the
318
    // priors that exist unchanged.
319
    $table = _field_sql_storage_tablename($prior_field);
320
    $revision_table = _field_sql_storage_revision_tablename($prior_field);
321
    foreach ($prior_field['indexes'] as $name => $columns) {
322
      if (!isset($field['indexes'][$name]) || $columns != $field['indexes'][$name]) {
323
        $real_name = _field_sql_storage_indexname($field['field_name'], $name);
324
        db_drop_index($table, $real_name);
325
        db_drop_index($revision_table, $real_name);
326
      }
327
    }
328
    $table = _field_sql_storage_tablename($field);
329
    $revision_table = _field_sql_storage_revision_tablename($field);
330
    foreach ($field['indexes'] as $name => $columns) {
331
      if (!isset($prior_field['indexes'][$name]) || $columns != $prior_field['indexes'][$name]) {
332
        $real_name = _field_sql_storage_indexname($field['field_name'], $name);
333
        $real_columns = array();
334
        foreach ($columns as $column_name) {
335
          $real_columns[] = _field_sql_storage_columnname($field['field_name'], $column_name);
336
        }
337
        db_add_index($table, $real_name, $real_columns);
338
        db_add_index($revision_table, $real_name, $real_columns);
339
      }
340
    }
341
  }
342
  drupal_get_schema(NULL, TRUE);
343
}
344

    
345
/**
346
 * Implements hook_field_storage_delete_field().
347
 */
348
function field_sql_storage_field_storage_delete_field($field) {
349
  // Mark all data associated with the field for deletion.
350
  $field['deleted'] = 0;
351
  $table = _field_sql_storage_tablename($field);
352
  $revision_table = _field_sql_storage_revision_tablename($field);
353
  db_update($table)
354
    ->fields(array('deleted' => 1))
355
    ->execute();
356

    
357
  // Move the table to a unique name while the table contents are being deleted.
358
  $field['deleted'] = 1;
359
  $new_table = _field_sql_storage_tablename($field);
360
  $revision_new_table = _field_sql_storage_revision_tablename($field);
361
  db_rename_table($table, $new_table);
362
  db_rename_table($revision_table, $revision_new_table);
363
  drupal_get_schema(NULL, TRUE);
364
}
365

    
366
/**
367
 * Implements hook_field_storage_load().
368
 */
369
function field_sql_storage_field_storage_load($entity_type, $entities, $age, $fields, $options) {
370
  $load_current = $age == FIELD_LOAD_CURRENT;
371

    
372
  foreach ($fields as $field_id => $ids) {
373
    // By the time this hook runs, the relevant field definitions have been
374
    // populated and cached in FieldInfo, so calling field_info_field_by_id()
375
    // on each field individually is more efficient than loading all fields in
376
    // memory upfront with field_info_field_by_ids().
377
    $field = field_info_field_by_id($field_id);
378
    $field_name = $field['field_name'];
379
    $table = $load_current ? _field_sql_storage_tablename($field) : _field_sql_storage_revision_tablename($field);
380

    
381
    $query = db_select($table, 't')
382
      ->fields('t')
383
      ->condition('entity_type', $entity_type)
384
      ->condition($load_current ? 'entity_id' : 'revision_id', $ids, 'IN')
385
      ->condition('language', field_available_languages($entity_type, $field), 'IN')
386
      ->orderBy('delta');
387

    
388
    if (empty($options['deleted'])) {
389
      $query->condition('deleted', 0);
390
    }
391

    
392
    $results = $query->execute();
393

    
394
    $delta_count = array();
395
    foreach ($results as $row) {
396
      if (!isset($delta_count[$row->entity_id][$row->language])) {
397
        $delta_count[$row->entity_id][$row->language] = 0;
398
      }
399

    
400
      if ($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || $delta_count[$row->entity_id][$row->language] < $field['cardinality']) {
401
        $item = array();
402
        // For each column declared by the field, populate the item
403
        // from the prefixed database column.
404
        foreach ($field['columns'] as $column => $attributes) {
405
          $column_name = _field_sql_storage_columnname($field_name, $column);
406
          $item[$column] = $row->$column_name;
407
        }
408

    
409
        // Add the item to the field values for the entity.
410
        $entities[$row->entity_id]->{$field_name}[$row->language][] = $item;
411
        $delta_count[$row->entity_id][$row->language]++;
412
      }
413
    }
414
  }
415
}
416

    
417
/**
418
 * Implements hook_field_storage_write().
419
 */
420
function field_sql_storage_field_storage_write($entity_type, $entity, $op, $fields) {
421
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
422
  if (!isset($vid)) {
423
    $vid = $id;
424
  }
425

    
426
  foreach ($fields as $field_id) {
427
    $field = field_info_field_by_id($field_id);
428
    $field_name = $field['field_name'];
429
    $table_name = _field_sql_storage_tablename($field);
430
    $revision_name = _field_sql_storage_revision_tablename($field);
431

    
432
    $all_languages = field_available_languages($entity_type, $field);
433
    $field_languages = array_intersect($all_languages, array_keys((array) $entity->$field_name));
434

    
435
    // Delete and insert, rather than update, in case a value was added.
436
    if ($op == FIELD_STORAGE_UPDATE) {
437
      // Delete languages present in the incoming $entity->$field_name.
438
      // Delete all languages if $entity->$field_name is empty.
439
      $languages = !empty($entity->$field_name) ? $field_languages : $all_languages;
440
      if ($languages) {
441
        db_delete($table_name)
442
          ->condition('entity_type', $entity_type)
443
          ->condition('entity_id', $id)
444
          ->condition('language', $languages, 'IN')
445
          ->execute();
446
        db_delete($revision_name)
447
          ->condition('entity_type', $entity_type)
448
          ->condition('entity_id', $id)
449
          ->condition('revision_id', $vid)
450
          ->condition('language', $languages, 'IN')
451
          ->execute();
452
      }
453
    }
454

    
455
    // Prepare the multi-insert query.
456
    $do_insert = FALSE;
457
    $columns = array('entity_type', 'entity_id', 'revision_id', 'bundle', 'delta', 'language');
458
    foreach ($field['columns'] as $column => $attributes) {
459
      $columns[] = _field_sql_storage_columnname($field_name, $column);
460
    }
461
    $query = db_insert($table_name)->fields($columns);
462
    $revision_query = db_insert($revision_name)->fields($columns);
463

    
464
    foreach ($field_languages as $langcode) {
465
      $items = (array) $entity->{$field_name}[$langcode];
466
      $delta_count = 0;
467
      foreach ($items as $delta => $item) {
468
        // We now know we have something to insert.
469
        $do_insert = TRUE;
470
        $record = array(
471
          'entity_type' => $entity_type,
472
          'entity_id' => $id,
473
          'revision_id' => $vid,
474
          'bundle' => $bundle,
475
          'delta' => $delta,
476
          'language' => $langcode,
477
        );
478
        foreach ($field['columns'] as $column => $attributes) {
479
          $record[_field_sql_storage_columnname($field_name, $column)] = isset($item[$column]) ? $item[$column] : NULL;
480
        }
481
        $query->values($record);
482
        if (isset($vid)) {
483
          $revision_query->values($record);
484
        }
485

    
486
        if ($field['cardinality'] != FIELD_CARDINALITY_UNLIMITED && ++$delta_count == $field['cardinality']) {
487
          break;
488
        }
489
      }
490
    }
491

    
492
    // Execute the query if we have values to insert.
493
    if ($do_insert) {
494
      $query->execute();
495
      $revision_query->execute();
496
    }
497
  }
498
}
499

    
500
/**
501
 * Implements hook_field_storage_delete().
502
 *
503
 * This function deletes data for all fields for an entity from the database.
504
 */
505
function field_sql_storage_field_storage_delete($entity_type, $entity, $fields) {
506
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
507

    
508
  foreach (field_info_instances($entity_type, $bundle) as $instance) {
509
    if (isset($fields[$instance['field_id']])) {
510
      $field = field_info_field_by_id($instance['field_id']);
511
      field_sql_storage_field_storage_purge($entity_type, $entity, $field, $instance);
512
    }
513
  }
514
}
515

    
516
/**
517
 * Implements hook_field_storage_purge().
518
 *
519
 * This function deletes data from the database for a single field on
520
 * an entity.
521
 */
522
function field_sql_storage_field_storage_purge($entity_type, $entity, $field, $instance) {
523
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
524

    
525
  $table_name = _field_sql_storage_tablename($field);
526
  $revision_name = _field_sql_storage_revision_tablename($field);
527
  db_delete($table_name)
528
    ->condition('entity_type', $entity_type)
529
    ->condition('entity_id', $id)
530
    ->execute();
531
  db_delete($revision_name)
532
    ->condition('entity_type', $entity_type)
533
    ->condition('entity_id', $id)
534
    ->execute();
535
}
536

    
537
/**
538
 * Implements hook_field_storage_query().
539
 */
540
function field_sql_storage_field_storage_query(EntityFieldQuery $query) {
541
  if ($query->age == FIELD_LOAD_CURRENT) {
542
    $tablename_function = '_field_sql_storage_tablename';
543
    $id_key = 'entity_id';
544
  }
545
  else {
546
    $tablename_function = '_field_sql_storage_revision_tablename';
547
    $id_key = 'revision_id';
548
  }
549
  $table_aliases = array();
550
  $query_tables = NULL;
551
  // Add tables for the fields used.
552
  foreach ($query->fields as $key => $field) {
553
    $tablename = $tablename_function($field);
554
    $table_alias = _field_sql_storage_tablealias($tablename, $key, $query);
555
    $table_aliases[$key] = $table_alias;
556
    if ($key) {
557
      if (!isset($query_tables[$table_alias])) {
558
        $select_query->join($tablename, $table_alias, "$table_alias.entity_type = $field_base_table.entity_type AND $table_alias.$id_key = $field_base_table.$id_key");
559
      }
560
    }
561
    else {
562
      $select_query = db_select($tablename, $table_alias);
563
      // Store a reference to the list of joined tables.
564
      $query_tables =& $select_query->getTables();
565
      // Allow queries internal to the Field API to opt out of the access
566
      // check, for situations where the query's results should not depend on
567
      // the access grants for the current user.
568
      if (!isset($query->tags['DANGEROUS_ACCESS_CHECK_OPT_OUT'])) {
569
        $select_query->addTag('entity_field_access');
570
      }
571
      $select_query->addMetaData('base_table', $tablename);
572
      $select_query->fields($table_alias, array('entity_type', 'entity_id', 'revision_id', 'bundle'));
573
      $field_base_table = $table_alias;
574
    }
575
    if ($field['cardinality'] != 1 || $field['translatable']) {
576
      $select_query->distinct();
577
    }
578
  }
579

    
580
  // Add field conditions. We need a fresh grouping cache.
581
  drupal_static_reset('_field_sql_storage_query_field_conditions');
582
  _field_sql_storage_query_field_conditions($query, $select_query, $query->fieldConditions, $table_aliases, '_field_sql_storage_columnname');
583

    
584
  // Add field meta conditions.
585
  _field_sql_storage_query_field_conditions($query, $select_query, $query->fieldMetaConditions, $table_aliases, '_field_sql_storage_query_columnname');
586

    
587
  if (isset($query->deleted)) {
588
    $select_query->condition("$field_base_table.deleted", (int) $query->deleted);
589
  }
590

    
591
  // Is there a need to sort the query by property?
592
  $has_property_order = FALSE;
593
  foreach ($query->order as $order) {
594
    if ($order['type'] == 'property') {
595
      $has_property_order = TRUE;
596
    }
597
  }
598

    
599
  if ($query->propertyConditions || $has_property_order) {
600
    if (empty($query->entityConditions['entity_type']['value'])) {
601
      throw new EntityFieldQueryException('Property conditions and orders must have an entity type defined.');
602
    }
603
    $entity_type = $query->entityConditions['entity_type']['value'];
604
    $entity_base_table = _field_sql_storage_query_join_entity($select_query, $entity_type, $field_base_table);
605
    $query->entityConditions['entity_type']['operator'] = '=';
606
    foreach ($query->propertyConditions as $property_condition) {
607
      $query->addCondition($select_query, "$entity_base_table." . $property_condition['column'], $property_condition);
608
    }
609
  }
610
  foreach ($query->entityConditions as $key => $condition) {
611
    $query->addCondition($select_query, "$field_base_table.$key", $condition);
612
  }
613

    
614
  // Order the query.
615
  foreach ($query->order as $order) {
616
    if ($order['type'] == 'entity') {
617
      $key = $order['specifier'];
618
      $select_query->orderBy("$field_base_table.$key", $order['direction']);
619
    }
620
    elseif ($order['type'] == 'field') {
621
      $specifier = $order['specifier'];
622
      $field = $specifier['field'];
623
      $table_alias = $table_aliases[$specifier['index']];
624
      $sql_field = "$table_alias." . _field_sql_storage_columnname($field['field_name'], $specifier['column']);
625
      $select_query->orderBy($sql_field, $order['direction']);
626
    }
627
    elseif ($order['type'] == 'property') {
628
      $select_query->orderBy("$entity_base_table." . $order['specifier'], $order['direction']);
629
    }
630
  }
631

    
632
  return $query->finishQuery($select_query, $id_key);
633
}
634

    
635
/**
636
 * Adds the base entity table to a field query object.
637
 *
638
 * @param SelectQuery $select_query
639
 *   A SelectQuery containing at least one table as specified by
640
 *   _field_sql_storage_tablename().
641
 * @param $entity_type
642
 *   The entity type for which the base table should be joined.
643
 * @param $field_base_table
644
 *   Name of a table in $select_query. As only INNER JOINs are used, it does
645
 *   not matter which.
646
 *
647
 * @return
648
 *   The name of the entity base table joined in.
649
 */
650
function _field_sql_storage_query_join_entity(SelectQuery $select_query, $entity_type, $field_base_table) {
651
  $entity_info = entity_get_info($entity_type);
652
  $entity_base_table = $entity_info['base table'];
653
  $entity_field = $entity_info['entity keys']['id'];
654
  $select_query->join($entity_base_table, $entity_base_table, "$entity_base_table.$entity_field = $field_base_table.entity_id");
655
  return $entity_base_table;
656
}
657

    
658
/**
659
 * Adds field (meta) conditions to the given query objects respecting groupings.
660
 *
661
 * @param EntityFieldQuery $query
662
 *   The field query object to be processed.
663
 * @param SelectQuery $select_query
664
 *   The SelectQuery that should get grouping conditions.
665
 * @param condtions
666
 *   The conditions to be added.
667
 * @param $table_aliases
668
 *   An associative array of table aliases keyed by field index.
669
 * @param $column_callback
670
 *   A callback that should return the column name to be used for the field
671
 *   conditions. Accepts a field name and a field column name as parameters.
672
 */
673
function _field_sql_storage_query_field_conditions(EntityFieldQuery $query, SelectQuery $select_query, $conditions, $table_aliases, $column_callback) {
674
  $groups = &drupal_static(__FUNCTION__, array());
675
  foreach ($conditions as $key => $condition) {
676
    $table_alias = $table_aliases[$key];
677
    $field = $condition['field'];
678
    // Add the specified condition.
679
    $sql_field = "$table_alias." . $column_callback($field['field_name'], $condition['column']);
680
    $query->addCondition($select_query, $sql_field, $condition);
681
    // Add delta / language group conditions.
682
    foreach (array('delta', 'language') as $column) {
683
      if (isset($condition[$column . '_group'])) {
684
        $group_name = $condition[$column . '_group'];
685
        if (!isset($groups[$column][$group_name])) {
686
          $groups[$column][$group_name] = $table_alias;
687
        }
688
        else {
689
          $select_query->where("$table_alias.$column = " . $groups[$column][$group_name] . ".$column");
690
        }
691
      }
692
    }
693
  }
694
}
695

    
696
/**
697
 * Field meta condition column callback.
698
 */
699
function _field_sql_storage_query_columnname($field_name, $column) {
700
  return $column;
701
}
702

    
703
/**
704
 * Implements hook_field_storage_delete_revision().
705
 *
706
 * This function actually deletes the data from the database.
707
 */
708
function field_sql_storage_field_storage_delete_revision($entity_type, $entity, $fields) {
709
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
710

    
711
  if (isset($vid)) {
712
    foreach ($fields as $field_id) {
713
      $field = field_info_field_by_id($field_id);
714
      $revision_name = _field_sql_storage_revision_tablename($field);
715
      db_delete($revision_name)
716
        ->condition('entity_type', $entity_type)
717
        ->condition('entity_id', $id)
718
        ->condition('revision_id', $vid)
719
        ->execute();
720
    }
721
  }
722
}
723

    
724
/**
725
 * Implements hook_field_storage_delete_instance().
726
 *
727
 * This function simply marks for deletion all data associated with the field.
728
 */
729
function field_sql_storage_field_storage_delete_instance($instance) {
730
  $field = field_info_field($instance['field_name']);
731
  $table_name = _field_sql_storage_tablename($field);
732
  $revision_name = _field_sql_storage_revision_tablename($field);
733
  db_update($table_name)
734
    ->fields(array('deleted' => 1))
735
    ->condition('entity_type', $instance['entity_type'])
736
    ->condition('bundle', $instance['bundle'])
737
    ->execute();
738
  db_update($revision_name)
739
    ->fields(array('deleted' => 1))
740
    ->condition('entity_type', $instance['entity_type'])
741
    ->condition('bundle', $instance['bundle'])
742
    ->execute();
743
}
744

    
745
/**
746
 * Implements hook_field_attach_rename_bundle().
747
 */
748
function field_sql_storage_field_attach_rename_bundle($entity_type, $bundle_old, $bundle_new) {
749
  // We need to account for deleted or inactive fields and instances.
750
  $instances = field_read_instances(array('entity_type' => $entity_type, 'bundle' => $bundle_new), array('include_deleted' => TRUE, 'include_inactive' => TRUE));
751
  foreach ($instances as $instance) {
752
    $field = field_info_field_by_id($instance['field_id']);
753
    if ($field['storage']['type'] == 'field_sql_storage') {
754
      $table_name = _field_sql_storage_tablename($field);
755
      $revision_name = _field_sql_storage_revision_tablename($field);
756
      db_update($table_name)
757
        ->fields(array('bundle' => $bundle_new))
758
        ->condition('entity_type', $entity_type)
759
        ->condition('bundle', $bundle_old)
760
        ->execute();
761
      db_update($revision_name)
762
        ->fields(array('bundle' => $bundle_new))
763
        ->condition('entity_type', $entity_type)
764
        ->condition('bundle', $bundle_old)
765
        ->execute();
766
    }
767
  }
768
}
769

    
770
/**
771
 * Implements hook_field_storage_purge_field().
772
 *
773
 * All field data items and instances have already been purged, so all
774
 * that is left is to delete the table.
775
 */
776
function field_sql_storage_field_storage_purge_field($field) {
777
  $table_name = _field_sql_storage_tablename($field);
778
  $revision_name = _field_sql_storage_revision_tablename($field);
779
  db_drop_table($table_name);
780
  db_drop_table($revision_name);
781
}
782

    
783
/**
784
 * Implements hook_field_storage_details().
785
 */
786
function field_sql_storage_field_storage_details($field) {
787
  $details = array();
788
  if (!empty($field['columns'])) {
789
     // Add field columns.
790
    foreach ($field['columns'] as $column_name => $attributes) {
791
      $real_name = _field_sql_storage_columnname($field['field_name'], $column_name);
792
      $columns[$column_name] = $real_name;
793
    }
794
    return array(
795
      'sql' => array(
796
        FIELD_LOAD_CURRENT => array(
797
          _field_sql_storage_tablename($field) => $columns,
798
        ),
799
        FIELD_LOAD_REVISION => array(
800
          _field_sql_storage_revision_tablename($field) => $columns,
801
        ),
802
      ),
803
    );
804
  }
805
}