summaryrefslogtreecommitdiff
path: root/kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage
diff options
context:
space:
mode:
Diffstat (limited to 'kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage')
-rw-r--r--kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage/field_sql_storage.info14
-rw-r--r--kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage/field_sql_storage.install215
-rw-r--r--kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage/field_sql_storage.module758
-rw-r--r--kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage/field_sql_storage.test441
4 files changed, 1428 insertions, 0 deletions
diff --git a/kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage/field_sql_storage.info b/kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage/field_sql_storage.info
new file mode 100644
index 0000000..a5a8eaf
--- /dev/null
+++ b/kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage/field_sql_storage.info
@@ -0,0 +1,14 @@
+name = Field SQL storage
+description = Stores field data in an SQL database.
+package = Core
+version = VERSION
+core = 7.x
+dependencies[] = field
+files[] = field_sql_storage.test
+required = TRUE
+
+; Information added by Drupal.org packaging script on 2014-01-15
+version = "7.26"
+project = "drupal"
+datestamp = "1389815930"
+
diff --git a/kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage/field_sql_storage.install b/kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage/field_sql_storage.install
new file mode 100644
index 0000000..24973ab
--- /dev/null
+++ b/kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage/field_sql_storage.install
@@ -0,0 +1,215 @@
+<?php
+
+/**
+ * @file
+ * Install, update and uninstall functions for the field_sql_storage module.
+ */
+
+/**
+ * Implements hook_schema().
+ */
+function field_sql_storage_schema() {
+ $schema = array();
+
+ // Dynamic (data) tables.
+ if (db_table_exists('field_config')) {
+ $fields = field_read_fields(array(), array('include_deleted' => TRUE, 'include_inactive' => TRUE));
+ drupal_load('module', 'field_sql_storage');
+ foreach ($fields as $field) {
+ if ($field['storage']['type'] == 'field_sql_storage') {
+ $schema += _field_sql_storage_schema($field);
+ }
+ }
+ }
+ return $schema;
+}
+
+/**
+ * Utility function: write field data directly to SQL storage.
+ *
+ * This function can be used for databases whose schema is at field module
+ * version 7000 or higher.
+ *
+ * @ingroup update_api
+ */
+function _update_7000_field_sql_storage_write($entity_type, $bundle, $entity_id, $revision_id, $field_name, $data) {
+ $table_name = "field_data_{$field_name}";
+ $revision_name = "field_revision_{$field_name}";
+
+ db_delete($table_name)
+ ->condition('entity_type', $entity_type)
+ ->condition('entity_id', $entity_id)
+ ->execute();
+ db_delete($revision_name)
+ ->condition('entity_type', $entity_type)
+ ->condition('entity_id', $entity_id)
+ ->condition('revision_id', $revision_id)
+ ->execute();
+
+ $columns = array();
+ foreach ($data as $langcode => $items) {
+ foreach ($items as $delta => $item) {
+ $record = array(
+ 'entity_type' => $entity_type,
+ 'entity_id' => $entity_id,
+ 'revision_id' => $revision_id,
+ 'bundle' => $bundle,
+ 'delta' => $delta,
+ 'language' => $langcode,
+ );
+ foreach ($item as $column => $value) {
+ $record[_field_sql_storage_columnname($field_name, $column)] = $value;
+ }
+
+ $records[] = $record;
+ // Record the columns used.
+ $columns += $record;
+ }
+ }
+
+ if ($columns) {
+ $query = db_insert($table_name)->fields(array_keys($columns));
+ $revision_query = db_insert($revision_name)->fields(array_keys($columns));
+ foreach ($records as $record) {
+ $query->values($record);
+ if ($revision_id) {
+ $revision_query->values($record);
+ }
+ }
+ $query->execute();
+ $revision_query->execute();
+ }
+}
+
+/**
+ * @addtogroup updates-6.x-to-7.x
+ * @{
+ */
+
+/**
+ * Field SQL storage update version placeholder.
+ */
+function field_sql_storage_update_7000() {
+ // Some update helper functions (such as
+ // _update_7000_field_sql_storage_write()) modify the database directly. They
+ // can be used safely only if the database schema matches the field module
+ // schema established for Drupal 7.0 (i.e. version 7000). This function exists
+ // solely to set the schema version to 7000, so that update functions calling
+ // those helpers can do so safely by declaring a dependency on
+ // field_sql_storage_update_7000().
+}
+
+/**
+ * Remove the field_config_entity_type table and store 'entity_type' strings.
+ */
+function field_sql_storage_update_7001(&$sandbox) {
+ if (!isset($sandbox['progress'])) {
+ // Collect current etids.
+ $sandbox['etids'] = db_query('SELECT etid, type FROM {field_config_entity_type}')->fetchAllKeyed();
+
+ // Collect affected tables: field data, field revision data, 'deleted'
+ // tables.
+ $sandbox['tables'] = array();
+ $results = db_select('field_config', 'fc', array('fetch' => PDO::FETCH_ASSOC))
+ ->fields('fc')
+ ->condition('storage_module', 'field_sql_storage')
+ ->execute();
+ foreach ($results as $field) {
+ if ($field['deleted']) {
+ $sandbox['tables']["field_deleted_data_{$field['id']}"] = 'data';
+ $sandbox['tables']["field_deleted_revision_{$field['id']}"] = 'revision';
+ }
+ else {
+ $sandbox['tables']["field_data_{$field['field_name']}"] = 'data';
+ $sandbox['tables']["field_revision_{$field['field_name']}"] = 'revision';
+ }
+ }
+ reset($sandbox['tables']);
+
+ $sandbox['total'] = count($sandbox['tables']);
+ $sandbox['progress'] = 0;
+ }
+
+ if ($sandbox['tables']) {
+ // Grab the next table to process.
+ $table = key($sandbox['tables']);
+ $type = array_shift($sandbox['tables']);
+
+ if (db_table_exists($table)) {
+ // Add the 'entity_type' column.
+ if (!db_field_exists($table, 'entity_type')) {
+ $column = array(
+ 'type' => 'varchar',
+ 'length' => 128,
+ 'not null' => TRUE,
+ 'default' => '',
+ 'description' => 'The entity type this data is attached to.',
+ );
+ db_add_field($table, 'entity_type', $column);
+
+ // Populate the 'entity_type' column based on the 'etid' column.
+ foreach ($sandbox['etids'] as $etid => $entity_type) {
+ db_update($table)
+ ->fields(array('entity_type' => $entity_type))
+ ->condition('etid', $etid)
+ ->execute();
+ }
+
+ // Index the new column.
+ db_add_index($table, 'entity_type', array('entity_type'));
+ }
+
+ // Use the 'entity_type' column in the primary key.
+ db_drop_primary_key($table);
+ $primary_keys = array(
+ 'data' => array('entity_type', 'entity_id', 'deleted', 'delta', 'language'),
+ 'revision' => array('entity_type', 'entity_id', 'revision_id', 'deleted', 'delta', 'language'),
+ );
+ db_add_primary_key($table, $primary_keys[$type]);
+
+ // Drop the 'etid' column.
+ if (db_field_exists($table, 'etid')) {
+ db_drop_field($table, 'etid');
+ }
+ }
+
+ // Report progress.
+ $sandbox['progress']++;
+ $sandbox['#finished'] = min(0.99, $sandbox['progress'] / $sandbox['total']);
+ }
+ else {
+ // No more tables left: drop the field_config_entity_type table.
+ db_drop_table('field_config_entity_type');
+
+ // Drop the previous 'field_sql_storage_ENTITYTYPE_etid' system variables.
+ foreach ($sandbox['etids'] as $etid => $entity_type) {
+ variable_del('field_sql_storage_' . $entity_type . '_etid');
+ }
+
+ // We're done.
+ $sandbox['#finished'] = 1;
+ }
+}
+
+/**
+ * Fix primary keys in field revision data tables.
+ */
+function field_sql_storage_update_7002() {
+ $results = db_select('field_config', 'fc', array('fetch' => PDO::FETCH_ASSOC))
+ ->fields('fc')
+ ->condition('storage_module', 'field_sql_storage')
+ ->execute();
+ foreach ($results as $field) {
+ // Revision tables of deleted fields do not need to be fixed, since no new
+ // data is written to them.
+ if (!$field['deleted']) {
+ $table = "field_revision_{$field['field_name']}";
+ db_drop_primary_key($table);
+ db_add_primary_key($table, array('entity_type', 'entity_id', 'revision_id', 'deleted', 'delta', 'language'));
+ }
+ }
+}
+
+/**
+ * @} End of "addtogroup updates-6.x-to-7.x".
+ */
diff --git a/kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage/field_sql_storage.module b/kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage/field_sql_storage.module
new file mode 100644
index 0000000..93f2077
--- /dev/null
+++ b/kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage/field_sql_storage.module
@@ -0,0 +1,758 @@
+<?php
+
+/**
+ * @file
+ * Default implementation of the field storage API.
+ */
+
+/**
+ * Implements hook_help().
+ */
+function field_sql_storage_help($path, $arg) {
+ switch ($path) {
+ case 'admin/help#field_sql_storage':
+ $output = '';
+ $output .= '<h3>' . t('About') . '</h3>';
+ $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>';
+ return $output;
+ }
+}
+
+/**
+ * Implements hook_field_storage_info().
+ */
+function field_sql_storage_field_storage_info() {
+ return array(
+ 'field_sql_storage' => array(
+ 'label' => t('Default SQL storage'),
+ 'description' => t('Stores fields in the local SQL database, using per-field tables.'),
+ ),
+ );
+}
+
+/**
+ * Generate a table name for a field data table.
+ *
+ * @param $field
+ * The field structure.
+ * @return
+ * A string containing the generated name for the database table
+ */
+function _field_sql_storage_tablename($field) {
+ if ($field['deleted']) {
+ return "field_deleted_data_{$field['id']}";
+ }
+ else {
+ return "field_data_{$field['field_name']}";
+ }
+}
+
+/**
+ * Generate a table name for a field revision archive table.
+ *
+ * @param $name
+ * The field structure.
+ * @return
+ * A string containing the generated name for the database table
+ */
+function _field_sql_storage_revision_tablename($field) {
+ if ($field['deleted']) {
+ return "field_deleted_revision_{$field['id']}";
+ }
+ else {
+ return "field_revision_{$field['field_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;
+}
+
+/**
+ * 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) {
+ $deleted = $field['deleted'] ? 'deleted ' : '';
+ $current = array(
+ 'description' => "Data storage for {$deleted}field {$field['id']} ({$field['field_name']})",
+ 'fields' => array(
+ 'entity_type' => array(
+ 'type' => 'varchar',
+ 'length' => 128,
+ 'not null' => TRUE,
+ 'default' => '',
+ 'description' => 'The entity type this data is attached to',
+ ),
+ 'bundle' => array(
+ 'type' => 'varchar',
+ 'length' => 128,
+ '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',
+ ),
+ // @todo Consider storing language as integer.
+ 'language' => array(
+ 'type' => 'varchar',
+ 'length' => 32,
+ 'not null' => TRUE,
+ 'default' => '',
+ 'description' => 'The language for this data item.',
+ ),
+ '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('entity_type', 'entity_id', 'deleted', 'delta', 'language'),
+ 'indexes' => array(
+ 'entity_type' => array('entity_type'),
+ 'bundle' => array('bundle'),
+ 'deleted' => array('deleted'),
+ 'entity_id' => array('entity_id'),
+ 'revision_id' => array('revision_id'),
+ 'language' => array('language'),
+ ),
+ );
+
+ $field += array('columns' => array(), 'indexes' => array(), 'foreign keys' => array());
+ // Add field columns.
+ foreach ($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 ($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);
+ }
+ }
+
+ // Add foreign keys.
+ foreach ($field['foreign keys'] as $specifier => $specification) {
+ $real_name = _field_sql_storage_indexname($field['field_name'], $specifier);
+ $current['foreign keys'][$real_name]['table'] = $specification['table'];
+ foreach ($specification['columns'] as $column_name => $referenced) {
+ $sql_storage_column = _field_sql_storage_columnname($field['field_name'], $column_name);
+ $current['foreign keys'][$real_name]['columns'][$sql_storage_column] = $referenced;
+ }
+ }
+
+ // Construct the revision table.
+ $revision = $current;
+ $revision['description'] = "Revision archive storage for {$deleted}field {$field['id']} ({$field['field_name']})";
+ $revision['primary key'] = array('entity_type', 'entity_id', 'revision_id', 'deleted', 'delta', 'language');
+ $revision['fields']['revision_id']['not null'] = TRUE;
+ $revision['fields']['revision_id']['description'] = 'The entity revision id this data is attached to';
+
+ return array(
+ _field_sql_storage_tablename($field) => $current,
+ _field_sql_storage_revision_tablename($field) => $revision,
+ );
+}
+
+/**
+ * Implements 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($name, $table);
+ }
+ drupal_get_schema(NULL, TRUE);
+}
+
+/**
+ * Implements hook_field_update_forbid().
+ *
+ * Forbid any field update that changes column definitions if there is
+ * any data.
+ */
+function field_sql_storage_field_update_forbid($field, $prior_field, $has_data) {
+ if ($has_data && $field['columns'] != $prior_field['columns']) {
+ throw new FieldUpdateForbiddenException("field_sql_storage cannot change the schema for an existing field with data.");
+ }
+}
+
+/**
+ * Implements hook_field_storage_update_field().
+ */
+function field_sql_storage_field_storage_update_field($field, $prior_field, $has_data) {
+ if (! $has_data) {
+ // There is no data. Re-create the tables completely.
+
+ if (Database::getConnection()->supportsTransactionalDDL()) {
+ // If the database supports transactional DDL, we can go ahead and rely
+ // on it. If not, we will have to rollback manually if something fails.
+ $transaction = db_transaction();
+ }
+
+ try {
+ $prior_schema = _field_sql_storage_schema($prior_field);
+ foreach ($prior_schema as $name => $table) {
+ db_drop_table($name, $table);
+ }
+ $schema = _field_sql_storage_schema($field);
+ foreach ($schema as $name => $table) {
+ db_create_table($name, $table);
+ }
+ }
+ catch (Exception $e) {
+ if (Database::getConnection()->supportsTransactionalDDL()) {
+ $transaction->rollback();
+ }
+ else {
+ // Recreate tables.
+ $prior_schema = _field_sql_storage_schema($prior_field);
+ foreach ($prior_schema as $name => $table) {
+ if (!db_table_exists($name)) {
+ db_create_table($name, $table);
+ }
+ }
+ }
+ throw $e;
+ }
+ }
+ else {
+ // There is data, so there are no column changes. Drop all the
+ // prior indexes and create all the new ones, except for all the
+ // priors that exist unchanged.
+ $table = _field_sql_storage_tablename($prior_field);
+ $revision_table = _field_sql_storage_revision_tablename($prior_field);
+ foreach ($prior_field['indexes'] as $name => $columns) {
+ if (!isset($field['indexes'][$name]) || $columns != $field['indexes'][$name]) {
+ $real_name = _field_sql_storage_indexname($field['field_name'], $name);
+ db_drop_index($table, $real_name);
+ db_drop_index($revision_table, $real_name);
+ }
+ }
+ $table = _field_sql_storage_tablename($field);
+ $revision_table = _field_sql_storage_revision_tablename($field);
+ foreach ($field['indexes'] as $name => $columns) {
+ if (!isset($prior_field['indexes'][$name]) || $columns != $prior_field['indexes'][$name]) {
+ $real_name = _field_sql_storage_indexname($field['field_name'], $name);
+ $real_columns = array();
+ foreach ($columns as $column_name) {
+ $real_columns[] = _field_sql_storage_columnname($field['field_name'], $column_name);
+ }
+ db_add_index($table, $real_name, $real_columns);
+ db_add_index($revision_table, $real_name, $real_columns);
+ }
+ }
+ }
+ drupal_get_schema(NULL, TRUE);
+}
+
+/**
+ * Implements hook_field_storage_delete_field().
+ */
+function field_sql_storage_field_storage_delete_field($field) {
+ // Mark all data associated with the field for deletion.
+ $field['deleted'] = 0;
+ $table = _field_sql_storage_tablename($field);
+ $revision_table = _field_sql_storage_revision_tablename($field);
+ db_update($table)
+ ->fields(array('deleted' => 1))
+ ->execute();
+
+ // Move the table to a unique name while the table contents are being deleted.
+ $field['deleted'] = 1;
+ $new_table = _field_sql_storage_tablename($field);
+ $revision_new_table = _field_sql_storage_revision_tablename($field);
+ db_rename_table($table, $new_table);
+ db_rename_table($revision_table, $revision_new_table);
+ drupal_get_schema(NULL, TRUE);
+}
+
+/**
+ * Implements hook_field_storage_load().
+ */
+function field_sql_storage_field_storage_load($entity_type, $entities, $age, $fields, $options) {
+ $load_current = $age == FIELD_LOAD_CURRENT;
+
+ foreach ($fields as $field_id => $ids) {
+ // By the time this hook runs, the relevant field definitions have been
+ // populated and cached in FieldInfo, so calling field_info_field_by_id()
+ // on each field individually is more efficient than loading all fields in
+ // memory upfront with field_info_field_by_ids().
+ $field = field_info_field_by_id($field_id);
+ $field_name = $field['field_name'];
+ $table = $load_current ? _field_sql_storage_tablename($field) : _field_sql_storage_revision_tablename($field);
+
+ $query = db_select($table, 't')
+ ->fields('t')
+ ->condition('entity_type', $entity_type)
+ ->condition($load_current ? 'entity_id' : 'revision_id', $ids, 'IN')
+ ->condition('language', field_available_languages($entity_type, $field), 'IN')
+ ->orderBy('delta');
+
+ if (empty($options['deleted'])) {
+ $query->condition('deleted', 0);
+ }
+
+ $results = $query->execute();
+
+ $delta_count = array();
+ foreach ($results as $row) {
+ if (!isset($delta_count[$row->entity_id][$row->language])) {
+ $delta_count[$row->entity_id][$row->language] = 0;
+ }
+
+ if ($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || $delta_count[$row->entity_id][$row->language] < $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) {
+ $column_name = _field_sql_storage_columnname($field_name, $column);
+ $item[$column] = $row->$column_name;
+ }
+
+ // Add the item to the field values for the entity.
+ $entities[$row->entity_id]->{$field_name}[$row->language][] = $item;
+ $delta_count[$row->entity_id][$row->language]++;
+ }
+ }
+ }
+}
+
+/**
+ * Implements hook_field_storage_write().
+ */
+function field_sql_storage_field_storage_write($entity_type, $entity, $op, $fields) {
+ list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
+ if (!isset($vid)) {
+ $vid = $id;
+ }
+
+ foreach ($fields as $field_id) {
+ $field = field_info_field_by_id($field_id);
+ $field_name = $field['field_name'];
+ $table_name = _field_sql_storage_tablename($field);
+ $revision_name = _field_sql_storage_revision_tablename($field);
+
+ $all_languages = field_available_languages($entity_type, $field);
+ $field_languages = array_intersect($all_languages, array_keys((array) $entity->$field_name));
+
+ // Delete and insert, rather than update, in case a value was added.
+ if ($op == FIELD_STORAGE_UPDATE) {
+ // Delete languages present in the incoming $entity->$field_name.
+ // Delete all languages if $entity->$field_name is empty.
+ $languages = !empty($entity->$field_name) ? $field_languages : $all_languages;
+ if ($languages) {
+ db_delete($table_name)
+ ->condition('entity_type', $entity_type)
+ ->condition('entity_id', $id)
+ ->condition('language', $languages, 'IN')
+ ->execute();
+ db_delete($revision_name)
+ ->condition('entity_type', $entity_type)
+ ->condition('entity_id', $id)
+ ->condition('revision_id', $vid)
+ ->condition('language', $languages, 'IN')
+ ->execute();
+ }
+ }
+
+ // Prepare the multi-insert query.
+ $do_insert = FALSE;
+ $columns = array('entity_type', 'entity_id', 'revision_id', 'bundle', 'delta', 'language');
+ foreach ($field['columns'] as $column => $attributes) {
+ $columns[] = _field_sql_storage_columnname($field_name, $column);
+ }
+ $query = db_insert($table_name)->fields($columns);
+ $revision_query = db_insert($revision_name)->fields($columns);
+
+ foreach ($field_languages as $langcode) {
+ $items = (array) $entity->{$field_name}[$langcode];
+ $delta_count = 0;
+ foreach ($items as $delta => $item) {
+ // We now know we have someting to insert.
+ $do_insert = TRUE;
+ $record = array(
+ 'entity_type' => $entity_type,
+ 'entity_id' => $id,
+ 'revision_id' => $vid,
+ 'bundle' => $bundle,
+ 'delta' => $delta,
+ 'language' => $langcode,
+ );
+ 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 query if we have values to insert.
+ if ($do_insert) {
+ $query->execute();
+ $revision_query->execute();
+ }
+ }
+}
+
+/**
+ * Implements hook_field_storage_delete().
+ *
+ * This function deletes data for all fields for an entity from the database.
+ */
+function field_sql_storage_field_storage_delete($entity_type, $entity, $fields) {
+ list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
+
+ foreach (field_info_instances($entity_type, $bundle) as $instance) {
+ if (isset($fields[$instance['field_id']])) {
+ $field = field_info_field_by_id($instance['field_id']);
+ field_sql_storage_field_storage_purge($entity_type, $entity, $field, $instance);
+ }
+ }
+}
+
+/**
+ * Implements hook_field_storage_purge().
+ *
+ * This function deletes data from the database for a single field on
+ * an entity.
+ */
+function field_sql_storage_field_storage_purge($entity_type, $entity, $field, $instance) {
+ list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
+
+ $table_name = _field_sql_storage_tablename($field);
+ $revision_name = _field_sql_storage_revision_tablename($field);
+ db_delete($table_name)
+ ->condition('entity_type', $entity_type)
+ ->condition('entity_id', $id)
+ ->execute();
+ db_delete($revision_name)
+ ->condition('entity_type', $entity_type)
+ ->condition('entity_id', $id)
+ ->execute();
+}
+
+/**
+ * Implements hook_field_storage_query().
+ */
+function field_sql_storage_field_storage_query(EntityFieldQuery $query) {
+ if ($query->age == FIELD_LOAD_CURRENT) {
+ $tablename_function = '_field_sql_storage_tablename';
+ $id_key = 'entity_id';
+ }
+ else {
+ $tablename_function = '_field_sql_storage_revision_tablename';
+ $id_key = 'revision_id';
+ }
+ $table_aliases = array();
+ // Add tables for the fields used.
+ foreach ($query->fields as $key => $field) {
+ $tablename = $tablename_function($field);
+ // Every field needs a new table.
+ $table_alias = $tablename . $key;
+ $table_aliases[$key] = $table_alias;
+ if ($key) {
+ $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");
+ }
+ else {
+ $select_query = db_select($tablename, $table_alias);
+ // Allow queries internal to the Field API to opt out of the access
+ // check, for situations where the query's results should not depend on
+ // the access grants for the current user.
+ if (!isset($query->tags['DANGEROUS_ACCESS_CHECK_OPT_OUT'])) {
+ $select_query->addTag('entity_field_access');
+ }
+ $select_query->addMetaData('base_table', $tablename);
+ $select_query->fields($table_alias, array('entity_type', 'entity_id', 'revision_id', 'bundle'));
+ $field_base_table = $table_alias;
+ }
+ if ($field['cardinality'] != 1 || $field['translatable']) {
+ $select_query->distinct();
+ }
+ }
+
+ // Add field conditions. We need a fresh grouping cache.
+ drupal_static_reset('_field_sql_storage_query_field_conditions');
+ _field_sql_storage_query_field_conditions($query, $select_query, $query->fieldConditions, $table_aliases, '_field_sql_storage_columnname');
+
+ // Add field meta conditions.
+ _field_sql_storage_query_field_conditions($query, $select_query, $query->fieldMetaConditions, $table_aliases, '_field_sql_storage_query_columnname');
+
+ if (isset($query->deleted)) {
+ $select_query->condition("$field_base_table.deleted", (int) $query->deleted);
+ }
+
+ // Is there a need to sort the query by property?
+ $has_property_order = FALSE;
+ foreach ($query->order as $order) {
+ if ($order['type'] == 'property') {
+ $has_property_order = TRUE;
+ }
+ }
+
+ if ($query->propertyConditions || $has_property_order) {
+ if (empty($query->entityConditions['entity_type']['value'])) {
+ throw new EntityFieldQueryException('Property conditions and orders must have an entity type defined.');
+ }
+ $entity_type = $query->entityConditions['entity_type']['value'];
+ $entity_base_table = _field_sql_storage_query_join_entity($select_query, $entity_type, $field_base_table);
+ $query->entityConditions['entity_type']['operator'] = '=';
+ foreach ($query->propertyConditions as $property_condition) {
+ $query->addCondition($select_query, "$entity_base_table." . $property_condition['column'], $property_condition);
+ }
+ }
+ foreach ($query->entityConditions as $key => $condition) {
+ $query->addCondition($select_query, "$field_base_table.$key", $condition);
+ }
+
+ // Order the query.
+ foreach ($query->order as $order) {
+ if ($order['type'] == 'entity') {
+ $key = $order['specifier'];
+ $select_query->orderBy("$field_base_table.$key", $order['direction']);
+ }
+ elseif ($order['type'] == 'field') {
+ $specifier = $order['specifier'];
+ $field = $specifier['field'];
+ $table_alias = $table_aliases[$specifier['index']];
+ $sql_field = "$table_alias." . _field_sql_storage_columnname($field['field_name'], $specifier['column']);
+ $select_query->orderBy($sql_field, $order['direction']);
+ }
+ elseif ($order['type'] == 'property') {
+ $select_query->orderBy("$entity_base_table." . $order['specifier'], $order['direction']);
+ }
+ }
+
+ return $query->finishQuery($select_query, $id_key);
+}
+
+/**
+ * Adds the base entity table to a field query object.
+ *
+ * @param SelectQuery $select_query
+ * A SelectQuery containing at least one table as specified by
+ * _field_sql_storage_tablename().
+ * @param $entity_type
+ * The entity type for which the base table should be joined.
+ * @param $field_base_table
+ * Name of a table in $select_query. As only INNER JOINs are used, it does
+ * not matter which.
+ *
+ * @return
+ * The name of the entity base table joined in.
+ */
+function _field_sql_storage_query_join_entity(SelectQuery $select_query, $entity_type, $field_base_table) {
+ $entity_info = entity_get_info($entity_type);
+ $entity_base_table = $entity_info['base table'];
+ $entity_field = $entity_info['entity keys']['id'];
+ $select_query->join($entity_base_table, $entity_base_table, "$entity_base_table.$entity_field = $field_base_table.entity_id");
+ return $entity_base_table;
+}
+
+/**
+ * Adds field (meta) conditions to the given query objects respecting groupings.
+ *
+ * @param EntityFieldQuery $query
+ * The field query object to be processed.
+ * @param SelectQuery $select_query
+ * The SelectQuery that should get grouping conditions.
+ * @param condtions
+ * The conditions to be added.
+ * @param $table_aliases
+ * An associative array of table aliases keyed by field index.
+ * @param $column_callback
+ * A callback that should return the column name to be used for the field
+ * conditions. Accepts a field name and a field column name as parameters.
+ */
+function _field_sql_storage_query_field_conditions(EntityFieldQuery $query, SelectQuery $select_query, $conditions, $table_aliases, $column_callback) {
+ $groups = &drupal_static(__FUNCTION__, array());
+ foreach ($conditions as $key => $condition) {
+ $table_alias = $table_aliases[$key];
+ $field = $condition['field'];
+ // Add the specified condition.
+ $sql_field = "$table_alias." . $column_callback($field['field_name'], $condition['column']);
+ $query->addCondition($select_query, $sql_field, $condition);
+ // Add delta / language group conditions.
+ foreach (array('delta', 'language') as $column) {
+ if (isset($condition[$column . '_group'])) {
+ $group_name = $condition[$column . '_group'];
+ if (!isset($groups[$column][$group_name])) {
+ $groups[$column][$group_name] = $table_alias;
+ }
+ else {
+ $select_query->where("$table_alias.$column = " . $groups[$column][$group_name] . ".$column");
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Field meta condition column callback.
+ */
+function _field_sql_storage_query_columnname($field_name, $column) {
+ return $column;
+}
+
+/**
+ * Implements hook_field_storage_delete_revision().
+ *
+ * This function actually deletes the data from the database.
+ */
+function field_sql_storage_field_storage_delete_revision($entity_type, $entity, $fields) {
+ list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
+
+ if (isset($vid)) {
+ foreach ($fields as $field_id) {
+ $field = field_info_field_by_id($field_id);
+ $revision_name = _field_sql_storage_revision_tablename($field);
+ db_delete($revision_name)
+ ->condition('entity_type', $entity_type)
+ ->condition('entity_id', $id)
+ ->condition('revision_id', $vid)
+ ->execute();
+ }
+ }
+}
+
+/**
+ * Implements 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($instance) {
+ $field = field_info_field($instance['field_name']);
+ $table_name = _field_sql_storage_tablename($field);
+ $revision_name = _field_sql_storage_revision_tablename($field);
+ db_update($table_name)
+ ->fields(array('deleted' => 1))
+ ->condition('entity_type', $instance['entity_type'])
+ ->condition('bundle', $instance['bundle'])
+ ->execute();
+ db_update($revision_name)
+ ->fields(array('deleted' => 1))
+ ->condition('entity_type', $instance['entity_type'])
+ ->condition('bundle', $instance['bundle'])
+ ->execute();
+}
+
+/**
+ * Implements hook_field_attach_rename_bundle().
+ */
+function field_sql_storage_field_attach_rename_bundle($entity_type, $bundle_old, $bundle_new) {
+ // We need to account for deleted or inactive fields and instances.
+ $instances = field_read_instances(array('entity_type' => $entity_type, 'bundle' => $bundle_new), array('include_deleted' => TRUE, 'include_inactive' => TRUE));
+ foreach ($instances as $instance) {
+ $field = field_info_field_by_id($instance['field_id']);
+ if ($field['storage']['type'] == 'field_sql_storage') {
+ $table_name = _field_sql_storage_tablename($field);
+ $revision_name = _field_sql_storage_revision_tablename($field);
+ db_update($table_name)
+ ->fields(array('bundle' => $bundle_new))
+ ->condition('entity_type', $entity_type)
+ ->condition('bundle', $bundle_old)
+ ->execute();
+ db_update($revision_name)
+ ->fields(array('bundle' => $bundle_new))
+ ->condition('entity_type', $entity_type)
+ ->condition('bundle', $bundle_old)
+ ->execute();
+ }
+ }
+}
+
+/**
+ * Implements hook_field_storage_purge_field().
+ *
+ * All field data items and instances have already been purged, so all
+ * that is left is to delete the table.
+ */
+function field_sql_storage_field_storage_purge_field($field) {
+ $table_name = _field_sql_storage_tablename($field);
+ $revision_name = _field_sql_storage_revision_tablename($field);
+ db_drop_table($table_name);
+ db_drop_table($revision_name);
+}
+
+/**
+ * Implements hook_field_storage_details().
+ */
+function field_sql_storage_field_storage_details($field) {
+ $details = array();
+ if (!empty($field['columns'])) {
+ // Add field columns.
+ foreach ($field['columns'] as $column_name => $attributes) {
+ $real_name = _field_sql_storage_columnname($field['field_name'], $column_name);
+ $columns[$column_name] = $real_name;
+ }
+ return array(
+ 'sql' => array(
+ FIELD_LOAD_CURRENT => array(
+ _field_sql_storage_tablename($field) => $columns,
+ ),
+ FIELD_LOAD_REVISION => array(
+ _field_sql_storage_revision_tablename($field) => $columns,
+ ),
+ ),
+ );
+ }
+}
diff --git a/kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage/field_sql_storage.test b/kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage/field_sql_storage.test
new file mode 100644
index 0000000..12c54ba
--- /dev/null
+++ b/kolab.org/www/drupal-7.26/modules/field/modules/field_sql_storage/field_sql_storage.test
@@ -0,0 +1,441 @@
+<?php
+
+/**
+ * @file
+ * Tests for field_sql_storage.module.
+ *
+ * Field_sql_storage.module implements the default back-end storage plugin
+ * for the Field Strage API.
+ */
+
+/**
+ * Tests field storage.
+ */
+class FieldSqlStorageTestCase extends DrupalWebTestCase {
+ public static function getInfo() {
+ return array(
+ 'name' => 'Field SQL storage tests',
+ 'description' => "Test field SQL storage module.",
+ 'group' => 'Field API'
+ );
+ }
+
+ function setUp() {
+ parent::setUp('field_sql_storage', 'field', 'field_test', 'text');
+ $this->field_name = strtolower($this->randomName());
+ $this->field = array('field_name' => $this->field_name, 'type' => 'test_field', 'cardinality' => 4);
+ $this->field = field_create_field($this->field);
+ $this->instance = array(
+ 'field_name' => $this->field_name,
+ 'entity_type' => 'test_entity',
+ 'bundle' => 'test_bundle'
+ );
+ $this->instance = field_create_instance($this->instance);
+ $this->table = _field_sql_storage_tablename($this->field);
+ $this->revision_table = _field_sql_storage_revision_tablename($this->field);
+
+ }
+
+ /**
+ * Uses the mysql tables and records to verify
+ * field_load_revision works correctly.
+ */
+ function testFieldAttachLoad() {
+ $entity_type = 'test_entity';
+ $eid = 0;
+ $langcode = LANGUAGE_NONE;
+
+ $columns = array('entity_type', 'entity_id', 'revision_id', 'delta', 'language', $this->field_name . '_value');
+
+ // Insert data for four revisions to the field revisions table
+ $query = db_insert($this->revision_table)->fields($columns);
+ for ($evid = 0; $evid < 4; ++$evid) {
+ $values[$evid] = array();
+ // Note: we insert one extra value ('<=' instead of '<').
+ for ($delta = 0; $delta <= $this->field['cardinality']; $delta++) {
+ $value = mt_rand(1, 127);
+ $values[$evid][] = $value;
+ $query->values(array($entity_type, $eid, $evid, $delta, $langcode, $value));
+ }
+ }
+ $query->execute();
+
+ // Insert data for the "most current revision" into the field table
+ $query = db_insert($this->table)->fields($columns);
+ foreach ($values[0] as $delta => $value) {
+ $query->values(array($entity_type, $eid, 0, $delta, $langcode, $value));
+ }
+ $query->execute();
+
+ // Load the "most current revision"
+ $entity = field_test_create_stub_entity($eid, 0, $this->instance['bundle']);
+ field_attach_load($entity_type, array($eid => $entity));
+ foreach ($values[0] as $delta => $value) {
+ if ($delta < $this->field['cardinality']) {
+ $this->assertEqual($entity->{$this->field_name}[$langcode][$delta]['value'], $value, "Value $delta is loaded correctly for current revision");
+ }
+ else {
+ $this->assertFalse(array_key_exists($delta, $entity->{$this->field_name}[$langcode]), "No extraneous value gets loaded for current revision.");
+ }
+ }
+
+ // Load every revision
+ for ($evid = 0; $evid < 4; ++$evid) {
+ $entity = field_test_create_stub_entity($eid, $evid, $this->instance['bundle']);
+ field_attach_load_revision($entity_type, array($eid => $entity));
+ foreach ($values[$evid] as $delta => $value) {
+ if ($delta < $this->field['cardinality']) {
+ $this->assertEqual($entity->{$this->field_name}[$langcode][$delta]['value'], $value, "Value $delta for revision $evid is loaded correctly");
+ }
+ else {
+ $this->assertFalse(array_key_exists($delta, $entity->{$this->field_name}[$langcode]), "No extraneous value gets loaded for revision $evid.");
+ }
+ }
+ }
+
+ // Add a translation in an unavailable language and verify it is not loaded.
+ $eid = $evid = 1;
+ $unavailable_language = 'xx';
+ $entity = field_test_create_stub_entity($eid, $evid, $this->instance['bundle']);
+ $values = array($entity_type, $eid, $evid, 0, $unavailable_language, mt_rand(1, 127));
+ db_insert($this->table)->fields($columns)->values($values)->execute();
+ db_insert($this->revision_table)->fields($columns)->values($values)->execute();
+ field_attach_load($entity_type, array($eid => $entity));
+ $this->assertFalse(array_key_exists($unavailable_language, $entity->{$this->field_name}), 'Field translation in an unavailable language ignored');
+ }
+
+ /**
+ * Reads mysql to verify correct data is
+ * written when using insert and update.
+ */
+ function testFieldAttachInsertAndUpdate() {
+ $entity_type = 'test_entity';
+ $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
+ $langcode = LANGUAGE_NONE;
+
+ // Test insert.
+ $values = array();
+ // Note: we try to insert one extra value ('<=' instead of '<').
+ // TODO : test empty values filtering and "compression" (store consecutive deltas).
+ for ($delta = 0; $delta <= $this->field['cardinality']; $delta++) {
+ $values[$delta]['value'] = mt_rand(1, 127);
+ }
+ $entity->{$this->field_name}[$langcode] = $rev_values[0] = $values;
+ field_attach_insert($entity_type, $entity);
+
+ $rows = db_select($this->table, 't')->fields('t')->execute()->fetchAllAssoc('delta', PDO::FETCH_ASSOC);
+ foreach ($values as $delta => $value) {
+ if ($delta < $this->field['cardinality']) {
+ $this->assertEqual($rows[$delta][$this->field_name . '_value'], $value['value'], format_string("Value %delta is inserted correctly", array('%delta' => $delta)));
+ }
+ else {
+ $this->assertFalse(array_key_exists($delta, $rows), "No extraneous value gets inserted.");
+ }
+ }
+
+ // Test update.
+ $entity = field_test_create_stub_entity(0, 1, $this->instance['bundle']);
+ $values = array();
+ // Note: we try to update one extra value ('<=' instead of '<').
+ for ($delta = 0; $delta <= $this->field['cardinality']; $delta++) {
+ $values[$delta]['value'] = mt_rand(1, 127);
+ }
+ $entity->{$this->field_name}[$langcode] = $rev_values[1] = $values;
+ field_attach_update($entity_type, $entity);
+ $rows = db_select($this->table, 't')->fields('t')->execute()->fetchAllAssoc('delta', PDO::FETCH_ASSOC);
+ foreach ($values as $delta => $value) {
+ if ($delta < $this->field['cardinality']) {
+ $this->assertEqual($rows[$delta][$this->field_name . '_value'], $value['value'], format_string("Value %delta is updated correctly", array('%delta' => $delta)));
+ }
+ else {
+ $this->assertFalse(array_key_exists($delta, $rows), "No extraneous value gets updated.");
+ }
+ }
+
+ // Check that data for both revisions are in the revision table.
+ // We make sure each value is stored correctly, then unset it.
+ // When an entire revision's values are unset (remembering that we
+ // put one extra value in $values per revision), unset the entire
+ // revision. Then, if $rev_values is empty at the end, all
+ // revision data was found.
+ $results = db_select($this->revision_table, 't')->fields('t')->execute();
+ foreach ($results as $row) {
+ $this->assertEqual($row->{$this->field_name . '_value'}, $rev_values[$row->revision_id][$row->delta]['value'], "Value {$row->delta} for revision {$row->revision_id} stored correctly");
+ unset($rev_values[$row->revision_id][$row->delta]);
+ if (count($rev_values[$row->revision_id]) == 1) {
+ unset($rev_values[$row->revision_id]);
+ }
+ }
+ $this->assertTrue(empty($rev_values), "All values for all revisions are stored in revision table {$this->revision_table}");
+
+ // Check that update leaves the field data untouched if
+ // $entity->{$field_name} is absent.
+ unset($entity->{$this->field_name});
+ field_attach_update($entity_type, $entity);
+ $rows = db_select($this->table, 't')->fields('t')->execute()->fetchAllAssoc('delta', PDO::FETCH_ASSOC);
+ foreach ($values as $delta => $value) {
+ if ($delta < $this->field['cardinality']) {
+ $this->assertEqual($rows[$delta][$this->field_name . '_value'], $value['value'], format_string("Update with no field_name entry leaves value %delta untouched", array('%delta' => $delta)));
+ }
+ }
+
+ // Check that update with an empty $entity->$field_name empties the field.
+ $entity->{$this->field_name} = NULL;
+ field_attach_update($entity_type, $entity);
+ $rows = db_select($this->table, 't')->fields('t')->execute()->fetchAllAssoc('delta', PDO::FETCH_ASSOC);
+ $this->assertEqual(count($rows), 0, "Update with an empty field_name entry empties the field.");
+ }
+
+ /**
+ * Tests insert and update with missing or NULL fields.
+ */
+ function testFieldAttachSaveMissingData() {
+ $entity_type = 'test_entity';
+ $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
+ $langcode = LANGUAGE_NONE;
+
+ // Insert: Field is missing
+ field_attach_insert($entity_type, $entity);
+ $count = db_select($this->table)
+ ->countQuery()
+ ->execute()
+ ->fetchField();
+ $this->assertEqual($count, 0, 'Missing field results in no inserts');
+
+ // Insert: Field is NULL
+ $entity->{$this->field_name} = NULL;
+ field_attach_insert($entity_type, $entity);
+ $count = db_select($this->table)
+ ->countQuery()
+ ->execute()
+ ->fetchField();
+ $this->assertEqual($count, 0, 'NULL field results in no inserts');
+
+ // Add some real data
+ $entity->{$this->field_name}[$langcode] = array(0 => array('value' => 1));
+ field_attach_insert($entity_type, $entity);
+ $count = db_select($this->table)
+ ->countQuery()
+ ->execute()
+ ->fetchField();
+ $this->assertEqual($count, 1, 'Field data saved');
+
+ // Update: Field is missing. Data should survive.
+ unset($entity->{$this->field_name});
+ field_attach_update($entity_type, $entity);
+ $count = db_select($this->table)
+ ->countQuery()
+ ->execute()
+ ->fetchField();
+ $this->assertEqual($count, 1, 'Missing field leaves data in table');
+
+ // Update: Field is NULL. Data should be wiped.
+ $entity->{$this->field_name} = NULL;
+ field_attach_update($entity_type, $entity);
+ $count = db_select($this->table)
+ ->countQuery()
+ ->execute()
+ ->fetchField();
+ $this->assertEqual($count, 0, 'NULL field leaves no data in table');
+
+ // Add a translation in an unavailable language.
+ $unavailable_language = 'xx';
+ db_insert($this->table)
+ ->fields(array('entity_type', 'bundle', 'deleted', 'entity_id', 'revision_id', 'delta', 'language'))
+ ->values(array($entity_type, $this->instance['bundle'], 0, 0, 0, 0, $unavailable_language))
+ ->execute();
+ $count = db_select($this->table)
+ ->countQuery()
+ ->execute()
+ ->fetchField();
+ $this->assertEqual($count, 1, 'Field translation in an unavailable language saved.');
+
+ // Again add some real data.
+ $entity->{$this->field_name}[$langcode] = array(0 => array('value' => 1));
+ field_attach_insert($entity_type, $entity);
+ $count = db_select($this->table)
+ ->countQuery()
+ ->execute()
+ ->fetchField();
+ $this->assertEqual($count, 2, 'Field data saved.');
+
+ // Update: Field translation is missing but field is not empty. Translation
+ // data should survive.
+ $entity->{$this->field_name}[$unavailable_language] = array(mt_rand(1, 127));
+ unset($entity->{$this->field_name}[$langcode]);
+ field_attach_update($entity_type, $entity);
+ $count = db_select($this->table)
+ ->countQuery()
+ ->execute()
+ ->fetchField();
+ $this->assertEqual($count, 2, 'Missing field translation leaves data in table.');
+
+ // Update: Field translation is NULL but field is not empty. Translation
+ // data should be wiped.
+ $entity->{$this->field_name}[$langcode] = NULL;
+ field_attach_update($entity_type, $entity);
+ $count = db_select($this->table)
+ ->countQuery()
+ ->execute()
+ ->fetchField();
+ $this->assertEqual($count, 1, 'NULL field translation is wiped.');
+ }
+
+ /**
+ * Test trying to update a field with data.
+ */
+ function testUpdateFieldSchemaWithData() {
+ // Create a decimal 5.2 field and add some data.
+ $field = array('field_name' => 'decimal52', 'type' => 'number_decimal', 'settings' => array('precision' => 5, 'scale' => 2));
+ $field = field_create_field($field);
+ $instance = array('field_name' => 'decimal52', 'entity_type' => 'test_entity', 'bundle' => 'test_bundle');
+ $instance = field_create_instance($instance);
+ $entity = field_test_create_stub_entity(0, 0, $instance['bundle']);
+ $entity->decimal52[LANGUAGE_NONE][0]['value'] = '1.235';
+ field_attach_insert('test_entity', $entity);
+
+ // Attempt to update the field in a way that would work without data.
+ $field['settings']['scale'] = 3;
+ try {
+ field_update_field($field);
+ $this->fail(t('Cannot update field schema with data.'));
+ }
+ catch (FieldException $e) {
+ $this->pass(t('Cannot update field schema with data.'));
+ }
+ }
+
+ /**
+ * Test that failure to create fields is handled gracefully.
+ */
+ function testFieldUpdateFailure() {
+ // Create a text field.
+ $field = array('field_name' => 'test_text', 'type' => 'text', 'settings' => array('max_length' => 255));
+ $field = field_create_field($field);
+
+ // Attempt to update the field in a way that would break the storage.
+ $prior_field = $field;
+ $field['settings']['max_length'] = -1;
+ try {
+ field_update_field($field);
+ $this->fail(t('Update succeeded.'));
+ }
+ catch (Exception $e) {
+ $this->pass(t('Update properly failed.'));
+ }
+
+ // Ensure that the field tables are still there.
+ foreach (_field_sql_storage_schema($prior_field) as $table_name => $table_info) {
+ $this->assertTrue(db_table_exists($table_name), format_string('Table %table exists.', array('%table' => $table_name)));
+ }
+ }
+
+ /**
+ * Test adding and removing indexes while data is present.
+ */
+ function testFieldUpdateIndexesWithData() {
+
+ // Create a decimal field.
+ $field_name = 'testfield';
+ $field = array('field_name' => $field_name, 'type' => 'text');
+ $field = field_create_field($field);
+ $instance = array('field_name' => $field_name, 'entity_type' => 'test_entity', 'bundle' => 'test_bundle');
+ $instance = field_create_instance($instance);
+ $tables = array(_field_sql_storage_tablename($field), _field_sql_storage_revision_tablename($field));
+
+ // Verify the indexes we will create do not exist yet.
+ foreach ($tables as $table) {
+ $this->assertFalse(Database::getConnection()->schema()->indexExists($table, 'value'), format_string("No index named value exists in %table", array('%table' => $table)));
+ $this->assertFalse(Database::getConnection()->schema()->indexExists($table, 'value_format'), format_string("No index named value_format exists in %table", array('%table' => $table)));
+ }
+
+ // Add data so the table cannot be dropped.
+ $entity = field_test_create_stub_entity(0, 0, $instance['bundle']);
+ $entity->{$field_name}[LANGUAGE_NONE][0]['value'] = 'field data';
+ field_attach_insert('test_entity', $entity);
+
+ // Add an index
+ $field = array('field_name' => $field_name, 'indexes' => array('value' => array('value')));
+ field_update_field($field);
+ foreach ($tables as $table) {
+ $this->assertTrue(Database::getConnection()->schema()->indexExists($table, "{$field_name}_value"), format_string("Index on value created in %table", array('%table' => $table)));
+ }
+
+ // Add a different index, removing the existing custom one.
+ $field = array('field_name' => $field_name, 'indexes' => array('value_format' => array('value', 'format')));
+ field_update_field($field);
+ foreach ($tables as $table) {
+ $this->assertTrue(Database::getConnection()->schema()->indexExists($table, "{$field_name}_value_format"), format_string("Index on value_format created in %table", array('%table' => $table)));
+ $this->assertFalse(Database::getConnection()->schema()->indexExists($table, "{$field_name}_value"), format_string("Index on value removed in %table", array('%table' => $table)));
+ }
+
+ // Verify that the tables were not dropped.
+ $entity = field_test_create_stub_entity(0, 0, $instance['bundle']);
+ field_attach_load('test_entity', array(0 => $entity));
+ $this->assertEqual($entity->{$field_name}[LANGUAGE_NONE][0]['value'], 'field data', "Index changes performed without dropping the tables");
+ }
+
+ /**
+ * Test the storage details.
+ */
+ function testFieldStorageDetails() {
+ $current = _field_sql_storage_tablename($this->field);
+ $revision = _field_sql_storage_revision_tablename($this->field);
+
+ // Retrieve the field and instance with field_info so the storage details are attached.
+ $field = field_info_field($this->field['field_name']);
+ $instance = field_info_instance($this->instance['entity_type'], $this->instance['field_name'], $this->instance['bundle']);
+
+ // The storage details are indexed by a storage engine type.
+ $this->assertTrue(array_key_exists('sql', $field['storage']['details']), 'The storage type is SQL.');
+
+ // The SQL details are indexed by table name.
+ $details = $field['storage']['details']['sql'];
+ $this->assertTrue(array_key_exists($current, $details[FIELD_LOAD_CURRENT]), 'Table name is available in the instance array.');
+ $this->assertTrue(array_key_exists($revision, $details[FIELD_LOAD_REVISION]), 'Revision table name is available in the instance array.');
+
+ // Test current and revision storage details together because the columns
+ // are the same.
+ foreach ((array) $this->field['columns'] as $column_name => $attributes) {
+ $storage_column_name = _field_sql_storage_columnname($this->field['field_name'], $column_name);
+ $this->assertEqual($details[FIELD_LOAD_CURRENT][$current][$column_name], $storage_column_name, format_string('Column name %value matches the definition in %bin.', array('%value' => $column_name, '%bin' => $current)));
+ $this->assertEqual($details[FIELD_LOAD_REVISION][$revision][$column_name], $storage_column_name, format_string('Column name %value matches the definition in %bin.', array('%value' => $column_name, '%bin' => $revision)));
+ }
+ }
+
+ /**
+ * Test foreign key support.
+ */
+ function testFieldSqlStorageForeignKeys() {
+ // Create a 'shape' field, with a configurable foreign key (see
+ // field_test_field_schema()).
+ $field_name = 'testfield';
+ $foreign_key_name = 'shape';
+ $field = array('field_name' => $field_name, 'type' => 'shape', 'settings' => array('foreign_key_name' => $foreign_key_name));
+ field_create_field($field);
+
+ // Retrieve the field definition and check that the foreign key is in place.
+ $field = field_info_field($field_name);
+ $this->assertEqual($field['foreign keys'][$foreign_key_name]['table'], $foreign_key_name, 'Foreign key table name preserved through CRUD');
+ $this->assertEqual($field['foreign keys'][$foreign_key_name]['columns'][$foreign_key_name], 'id', 'Foreign key column name preserved through CRUD');
+
+ // Update the field settings, it should update the foreign key definition
+ // too.
+ $foreign_key_name = 'color';
+ $field['settings']['foreign_key_name'] = $foreign_key_name;
+ field_update_field($field);
+
+ // Retrieve the field definition and check that the foreign key is in place.
+ $field = field_info_field($field_name);
+ $this->assertEqual($field['foreign keys'][$foreign_key_name]['table'], $foreign_key_name, 'Foreign key table name modified after update');
+ $this->assertEqual($field['foreign keys'][$foreign_key_name]['columns'][$foreign_key_name], 'id', 'Foreign key column name modified after update');
+
+ // Now grab the SQL schema and verify that too.
+ $schema = drupal_get_schema(_field_sql_storage_tablename($field), TRUE);
+ $this->assertEqual(count($schema['foreign keys']), 1, 'There is 1 foreign key in the schema');
+ $foreign_key = reset($schema['foreign keys']);
+ $foreign_key_column = _field_sql_storage_columnname($field['field_name'], $foreign_key_name);
+ $this->assertEqual($foreign_key['table'], $foreign_key_name, 'Foreign key table name preserved in the schema');
+ $this->assertEqual($foreign_key['columns'][$foreign_key_column], 'id', 'Foreign key column name preserved in the schema');
+ }
+}