summaryrefslogtreecommitdiff
path: root/modules/field/modules/field_sql_storage/field_sql_storage.module
blob: 51a82308a74ebf28eef0cdf4a07fc1bf845ab1a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
<?php
// $Id$

/**
 * @file
 * Default implementation of the field storage API.
 */

/**
 * Implementation of hook_help().
 */
function field_sql_storage_help($path, $arg) {
  switch ($path) {
    case 'admin/help#field_sql_storage':
      $output = '<p>' . t('The Field SQL Storage module stores Field API data in the database.  It is the default field storage module, but other field storage modules may be available in the contributions repository.') . '</p>';
      return $output;
  }
}

/**
 * Generate a table name for a field data table.
 *
 * @param $name
 *   The name of the field
 * @return
 *   A string containing the generated name for the database table
 */
function _field_sql_storage_tablename($name) {
  return 'field_data_' . $name;
}

/**
 * Generate a table name for a field revision archive table.
 *
 * @param $name
 *   The name of the field
 * @return
 *   A string containing the generated name for the database table
 */
function _field_sql_storage_revision_tablename($name) {
  return 'field_data_revision_' . $name;
}

/**
 * Generate a column name for a field data table.
 *
 * @param $name
 *   The name of the field
 * @param $column
 *   The name of the column
 * @return
 *   A string containing a generated column name for a field data
 *   table that is unique among all other fields.
 */
function _field_sql_storage_columnname($name, $column) {
  return $name . '_' . $column;
}

/**
 * Generate an index name for a field data table.
 *
 * @param $name
 *   The name of the field
 * @param $column
 *   The name of the index
 * @return
 *   A string containing a generated index name for a field data
 *   table that is unique among all other fields.
 */
function _field_sql_storage_indexname($name, $index) {
  return $name . '_' . $index;
}

/**
 * Retrieve or assign an entity type id for an object type.
 *
 * @param $obj_type
 *   The object type, such as 'node' or 'user'.
 * @return
 *   The entity type id.
 *
 * TODO: We need to decide on 'entity' or 'object'.
 */
function _field_sql_storage_etid($obj_type) {
  $etid = variable_get('field_sql_storage_' . $obj_type . '_etid', NULL);
  if (is_null($etid)) {
    $etid = db_insert('field_config_entity_type')->fields(array('type' => $obj_type))->execute();
    variable_set('field_sql_storage_' . $obj_type . '_etid', $etid);
  }
  return $etid;
}

/**
 * Return the database schema for a field. This may contain one or
 * more tables. Each table will contain the columns relevant for the
 * specified field. Leave the $field's 'columns' and 'indexes' keys
 * empty to get only the base schema.
 *
 * @param $field
 *   The field structure for which to generate a database schema.
 * @return
 *   One or more tables representing the schema for the field.
 */
function _field_sql_storage_schema($field) {
  $current = array(
    'description' => 'Data storage for field ' . $field['field_name'],
    'fields' => array(
      'etid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'The entity type id this data is attached to',
      ),
      'bundle' => array(
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => '',
        'description' => 'The field instance bundle to which this row belongs, used when deleting a field instance',
      ),
      'deleted' => array(
        'type' => 'int',
        'size' => 'tiny',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'A boolean indicating whether this data item has been deleted'
      ),
      'entity_id' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'The entity id this data is attached to',
      ),
      'revision_id' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => FALSE,
        'description' => 'The entity revision id this data is attached to, or NULL if the entity type is not versioned',
      ),
      'delta' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'The sequence number for this data item, used for multi-value fields',
      ),
    ),
    'primary key' => array('etid', 'entity_id', 'deleted', 'delta'),
    // TODO : index on 'bundle'
  );

  // Add field columns.
  foreach ((array) $field['columns'] as $column_name => $attributes) {
    $real_name = _field_sql_storage_columnname($field['field_name'], $column_name);
    $current['fields'][$real_name] = $attributes;
  }

  // Add indexes.
  foreach ((array) $field['indexes'] as $index_name => $columns) {
    $real_name = _field_sql_storage_indexname($field['field_name'], $index_name);
    foreach ($columns as $column_name) {
      $current['indexes'][$real_name][] = _field_sql_storage_columnname($field['field_name'], $column_name);
    }
  }

  // Construct the revision table. The primary key includes
  // revision_id but not entity_id so that multiple revision loads can
  // use the IN operator.
  $revision = $current;
  $revision['description'] = 'Revision archive storage for field ' . $field['field_name'];
  $revision['revision_id']['description'] = 'The entity revision id this data is attached to';
  $revision['primary key'] = array('etid', 'revision_id', 'deleted', 'delta');

  return array(
    _field_sql_storage_tablename($field['field_name']) => $current,
    _field_sql_storage_revision_tablename($field['field_name']) => $revision,
  );
}

/**
 * Implementation of hook_field_storage_create_field().
 */
function field_sql_storage_field_storage_create_field($field) {
  $schema = _field_sql_storage_schema($field);
  foreach ($schema as $name => $table) {
    db_create_table($ret, $name, $table);
  }
}

/**
 * Implementation of hook_field_storage_delete_field().
 */
function field_sql_storage_field_storage_delete_field($field_name) {
  // Mark all data associated with the field for deletion.
  $table = _field_sql_storage_tablename($field_name);
  db_update($table)
    ->fields(array('deleted' => 1))
    ->execute();
}

/**
 * Implementation of hook_field_storage_load().
 */
function field_sql_storage_field_storage_load($obj_type, &$objects, $age, $skip_fields = array()) {
  $etid = _field_sql_storage_etid($obj_type);
  $load_current = $age == FIELD_LOAD_CURRENT;

  // Gather ids needed for each field.
  $field_ids = array();
  $delta_count = array();
  foreach ($objects as $obj) {
    list($id, $vid, $bundle) = field_attach_extract_ids($obj_type, $obj);
    foreach (field_info_instances($bundle) as $field_name => $instance) {
      if (!isset($skip_fields[$field_name])) {
        $objects[$id]->{$field_name} = array();
        $field_ids[$field_name][] = $load_current ? $id : $vid;
        $delta_count[$id][$field_name] = 0;
      }
    }
  }

  foreach ($field_ids as $field_name => $ids) {
    $field = field_info_field($field_name);
    $table = $load_current ? _field_sql_storage_tablename($field_name) : _field_sql_storage_revision_tablename($field_name);

    $results = db_select($table, 't')
      ->fields('t')
      ->condition('etid', $etid)
      ->condition($load_current ? 'entity_id' : 'revision_id', $ids, 'IN')
      ->condition('deleted', 0)
      ->orderBy('delta')
      ->execute();

    foreach ($results as $row) {
      if ($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || $delta_count[$row->entity_id][$field_name] < $field['cardinality']) {
        $item = array();
        // For each column declared by the field, populate the item
        // from the prefixed database column.
        foreach ($field['columns'] as $column => $attributes) {
          $item[$column] = $row->{_field_sql_storage_columnname($field_name, $column)};
        }

        // Add the item to the field values for the entity.
        $objects[$row->entity_id]->{$field_name}[] = $item;
        $delta_count[$row->entity_id][$field_name]++;
      }
    }
  }
}

/**
 * Implementation of hook_field_storage_write().
 */
function field_sql_storage_field_storage_write($obj_type, $object, $op, $skip_fields) {
  list($id, $vid, $bundle) = field_attach_extract_ids($obj_type, $object);
  $etid = _field_sql_storage_etid($obj_type);

  $instances = field_info_instances($bundle);
  foreach ($instances as $instance) {
    $field_name = $instance['field_name'];
    if (isset($skip_fields[$field_name])) {
      continue;
    }

    $table_name = _field_sql_storage_tablename($field_name);
    $revision_name = _field_sql_storage_revision_tablename($field_name);
    $field = field_info_field($field_name);

    // Leave the field untouched if $object comes with no $field_name property.
    // Empty the field if $object->$field_name is NULL or an empty array.

    // Function property_exists() is slower, so we catch the more frequent cases
    // where it's an empty array with the faster isset().
    if (isset($object->$field_name) || property_exists($object, $field_name)) {
      // Delete and insert, rather than update, in case a value was added.
      if ($op == FIELD_STORAGE_UPDATE) {
        db_delete($table_name)->condition('etid', $etid)->condition('entity_id', $id)->execute();
        if (isset($vid)) {
          db_delete($revision_name)->condition('etid', $etid)->condition('entity_id', $id)->condition('revision_id', $vid)->execute();
        }
      }

      if ($object->$field_name) {
        // Prepare the multi-insert query.
        $columns = array('etid', 'entity_id', 'revision_id', 'bundle', 'delta');
        foreach ($field['columns'] as $column => $attributes) {
          $columns[] = _field_sql_storage_columnname($field_name, $column);
        }
        $query = db_insert($table_name)->fields($columns);
        if (isset($vid)) {
          $revision_query = db_insert($revision_name)->fields($columns);
        }

        $delta_count = 0;
        foreach ($object->$field_name as $delta => $item) {
          $record = array(
            'etid' => $etid,
            'entity_id' => $id,
            'revision_id' => $vid,
            'bundle' => $bundle,
            'delta' => $delta,
          );
          foreach ($field['columns'] as $column => $attributes) {
            $record[_field_sql_storage_columnname($field_name, $column)] = isset($item[$column]) ? $item[$column] : NULL;
          }
          $query->values($record);
          if (isset($vid)) {
            $revision_query->values($record);
          }

          if ($field['cardinality'] != FIELD_CARDINALITY_UNLIMITED && ++$delta_count == $field['cardinality']) {
            break;
          }
        }

        // Execute the insert.
        $query->execute();
        if (isset($vid)) {
          $revision_query->execute();
        }
      }
    }
  }
}

/**
 * Implementation of hook_field_storage_delete().
 *
 * This function actually deletes the data from the database.
 */
function field_sql_storage_field_storage_delete($obj_type, $object) {
  list($id, $vid, $bundle) = field_attach_extract_ids($obj_type, $object);
  $etid = _field_sql_storage_etid($obj_type);

  $instances = field_info_instances($bundle);
  foreach ($instances as $instance) {
    $field_name = $instance['field_name'];
    $table_name = _field_sql_storage_tablename($field_name);
    $revision_name = _field_sql_storage_revision_tablename($field_name);
    db_delete($table_name)
      ->condition('etid', $etid)
      ->condition('entity_id', $id)
      ->execute();
    db_delete($revision_name)
      ->condition('etid', $etid)
      ->condition('entity_id', $id)
      ->execute();
  }
}

/**
 * Implementation of hook_field_storage_delete_revision().
 *
 * This function actually deletes the data from the database.
 */
function field_sql_storage_field_storage_delete_revision($obj_type, $object) {
  list($id, $vid, $bundle) = field_attach_extract_ids($obj_type, $object);
  $etid = _field_sql_storage_etid($obj_type);

  if (isset($vid)) {
    $instances = field_info_instances($bundle);
    foreach ($instances as $instance) {
      $field_name = $instance['field_name'];
      $revision_name = _field_sql_storage_revision_tablename($field_name);
      db_delete($revision_name)
        ->condition('etid', $etid)
        ->condition('entity_id', $id)
        ->condition('revision_id', $vid)
        ->execute();
    }
  }
}

/**
 * Implementation of hook_field_storage_delete_instance().
 *
 * This function simply marks for deletion all data associated with the field.
 */
function field_sql_storage_field_storage_delete_instance($field_name, $bundle) {
  $table_name = _field_sql_storage_tablename($field_name);
  $revision_name = _field_sql_storage_revision_tablename($field_name);
  db_update($table_name)
    ->fields(array('deleted' => 1))
    ->condition('bundle', $bundle)
    ->execute();
  db_update($revision_name)
    ->fields(array('deleted' => 1))
    ->condition('bundle', $bundle)
    ->execute();
}

/**
 * Implementation of hook_field_storage_rename_bundle().
 */
function field_sql_storage_field_storage_rename_bundle($bundle_old, $bundle_new) {
  $instances = field_info_instances($bundle_old);
  foreach ($instances as $instance) {
    $table_name = _field_sql_storage_tablename($instance['field_name']);
    $revision_name = _field_sql_storage_revision_tablename($instance['field_name']);
    db_update($table_name)
      ->fields(array('bundle' => $bundle_new))
      ->condition('bundle', $bundle_old)
      ->execute();
    db_update($revision_name)
      ->fields(array('bundle' => $bundle_new))
      ->condition('bundle', $bundle_old)
      ->execute();
  }
}