taxonomy.install 30.1 KB
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 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
<?php

/**
 * @file
 * Install, update and uninstall functions for the taxonomy module.
 */

/**
 * Implements hook_uninstall().
 */
function taxonomy_uninstall() {
  // Remove variables.
  variable_del('taxonomy_override_selector');
  variable_del('taxonomy_terms_per_page_admin');
  // Remove taxonomy_term bundles.
  $vocabularies = db_query("SELECT machine_name FROM {taxonomy_vocabulary}")->fetchCol();
  foreach ($vocabularies as $vocabulary) {
    field_attach_delete_bundle('taxonomy_term', $vocabulary);
  }
}

/**
 * Implements hook_schema().
 */
function taxonomy_schema() {
  $schema['taxonomy_term_data'] = array(
    'description' => 'Stores term information.',
    'fields' => array(
      'tid' => array(
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'Primary Key: Unique term ID.',
      ),
      'vid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The {taxonomy_vocabulary}.vid of the vocabulary to which the term is assigned.',
      ),
      'name' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'The term name.',
        'translatable' => TRUE,
      ),
      'description' => array(
        'type' => 'text',
        'not null' => FALSE,
        'size' => 'big',
        'description' => 'A description of the term.',
        'translatable' => TRUE,
      ),
      'format' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => FALSE,
        'description' => 'The {filter_format}.format of the description.',
      ),
      'weight' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The weight of this term in relation to other terms.',
      ),
    ),
    'primary key' => array('tid'),
    'foreign keys' => array(
      'vocabulary' => array(
        'table' => 'taxonomy_vocabulary',
        'columns' => array('vid' => 'vid'),
      ),
    ),
    'indexes' => array(
      'taxonomy_tree' => array('vid', 'weight', 'name'),
      'vid_name' => array('vid', 'name'),
      'name' => array('name'),
    ),
  );

  $schema['taxonomy_term_hierarchy'] = array(
    'description' => 'Stores the hierarchical relationship between terms.',
    'fields' => array(
      'tid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'description' => 'Primary Key: The {taxonomy_term_data}.tid of the term.',
      ),
      'parent' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'description' => "Primary Key: The {taxonomy_term_data}.tid of the term's parent. 0 indicates no parent.",
      ),
    ),
    'indexes' => array(
      'parent' => array('parent'),
    ),
    'foreign keys' => array(
      'taxonomy_term_data' => array(
        'table' => 'taxonomy_term_data',
        'columns' => array('tid' => 'tid'),
      ),
    ),
    'primary key' => array('tid', 'parent'),
  );

  $schema['taxonomy_vocabulary'] = array(
    'description' => 'Stores vocabulary information.',
    'fields' => array(
      'vid' => array(
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'Primary Key: Unique vocabulary ID.',
      ),
      'name' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Name of the vocabulary.',
        'translatable' => TRUE,
      ),
      'machine_name' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'The vocabulary machine name.',
      ),
      'description' => array(
        'type' => 'text',
        'not null' => FALSE,
        'size' => 'big',
        'description' => 'Description of the vocabulary.',
        'translatable' => TRUE,
      ),
      'hierarchy' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'size' => 'tiny',
        'description' => 'The type of hierarchy allowed within the vocabulary. (0 = disabled, 1 = single, 2 = multiple)',
      ),
      'module' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'The module which created the vocabulary.',
      ),
      'weight' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The weight of this vocabulary in relation to other vocabularies.',
      ),
    ),
    'primary key' => array('vid'),
    'indexes' => array(
      'list' => array('weight', 'name'),
    ),
    'unique keys' => array(
      'machine_name' => array('machine_name'),
    ),
  );

  $schema['taxonomy_index'] = array(
    'description' => 'Maintains denormalized information about node/term relationships.',
    'fields' => array(
      'nid' => array(
        'description' => 'The {node}.nid this record tracks.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'tid' => array(
         'description' => 'The term ID.',
         'type' => 'int',
         'unsigned' => TRUE,
         'not null' => TRUE,
         'default' => 0,
      ),
      'sticky' => array(
        'description' => 'Boolean indicating whether the node is sticky.',
        'type' => 'int',
        'not null' => FALSE,
        'default' => 0,
        'size' => 'tiny',
      ),
      'created' => array(
        'description' => 'The Unix timestamp when the node was created.',
        'type' => 'int',
        'not null' => TRUE,
        'default'=> 0,
      ),
    ),
    'indexes' => array(
      'term_node' => array('tid', 'sticky', 'created'),
      'nid' => array('nid'),
    ),
    'foreign keys' => array(
      'tracked_node' => array(
        'table' => 'node',
        'columns' => array('nid' => 'nid'),
      ),
      'term' => array(
        'table' => 'taxonomy_term_data',
        'columns' => array('tid' => 'tid'),
      ),
    ),
  );

  return $schema;
}

/**
 * Implements hook_field_schema().
 */
function taxonomy_field_schema($field) {
  return array(
    'columns' => array(
      'tid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => FALSE,
      ),
    ),
    'indexes' => array(
      'tid' => array('tid'),
    ),
    'foreign keys' => array(
      'tid' => array(
        'table' => 'taxonomy_term_data',
        'columns' => array('tid' => 'tid'),
      ),
    ),
  );
}

/**
 * Implements hook_update_dependencies().
 */
function taxonomy_update_dependencies() {
  // taxonomy_update_7004() migrates taxonomy term data to fields and therefore
  // must run after all Field modules have been enabled, which happens in
  // system_update_7027().
  $dependencies['taxonomy'][7004] = array(
    'system' => 7027,
  );

  return $dependencies;
}

/**
 * Utility function: get the list of vocabularies directly from the database.
 *
 * This function is valid for a database schema version 7002.
 *
 * @ingroup update_api
 */
function _update_7002_taxonomy_get_vocabularies() {
  return db_query('SELECT v.* FROM {taxonomy_vocabulary} v ORDER BY v.weight, v.name')->fetchAllAssoc('vid', PDO::FETCH_OBJ);
}

/**
 * Rename taxonomy tables.
 */
function taxonomy_update_7001() {
  db_rename_table('term_data', 'taxonomy_term_data');
  db_rename_table('term_hierarchy', 'taxonomy_term_hierarchy');
  db_rename_table('term_node', 'taxonomy_term_node');
  db_rename_table('term_relation', 'taxonomy_term_relation');
  db_rename_table('term_synonym', 'taxonomy_term_synonym');
  db_rename_table('vocabulary', 'taxonomy_vocabulary');
  db_rename_table('vocabulary_node_types', 'taxonomy_vocabulary_node_type');
}

/**
 * Add {vocabulary}.machine_name column.
 */
function taxonomy_update_7002() {
  $field = array(
    'type' => 'varchar',
    'length' => 255,
    'not null' => TRUE,
    'default' => '',
    'description' => 'The vocabulary machine name.',
  );

  db_add_field('taxonomy_vocabulary', 'machine_name', $field);

  // Do a direct query here, rather than calling taxonomy_get_vocabularies(),
  // in case Taxonomy module is disabled.
  $vids = db_query('SELECT vid FROM {taxonomy_vocabulary}')->fetchCol();
  foreach ($vids as $vid) {
    $machine_name = 'vocabulary_' . $vid;
    db_update('taxonomy_vocabulary')
      ->fields(array('machine_name' => $machine_name))
      ->condition('vid', $vid)
      ->execute();
  }

  // The machine_name unique key can only be added after we ensure the
  // machine_name column contains unique values.
  db_add_unique_key('taxonomy_vocabulary', 'machine_name', array('machine_name'));
}

/**
 * Remove the related terms setting from vocabularies.
 *
 * This setting has not been used since Drupal 6. The {taxonomy_relations} table
 * itself is retained to allow for data to be upgraded.
 */
function taxonomy_update_7003() {
  db_drop_field('taxonomy_vocabulary', 'relations');
}

/**
 * Move taxonomy vocabulary associations for nodes to fields and field instances.
 */
function taxonomy_update_7004() {
  $taxonomy_index = array(
    'description' => 'Maintains denormalized information about node/term relationships.',
    'fields' => array(
      'nid' => array(
        'description' => 'The {node}.nid this record tracks.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'tid' => array(
         'description' => 'The term ID.',
         'type' => 'int',
         'unsigned' => TRUE,
         'not null' => TRUE,
         'default' => 0,
      ),
      'sticky' => array(
        'description' => 'Boolean indicating whether the node is sticky.',
        'type' => 'int',
        'not null' => FALSE,
        'default' => 0,
        'size' => 'tiny',
      ),
      'created' => array(
        'description' => 'The Unix timestamp when the node was created.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default'=> 0,
      ),
    ),
    'indexes' => array(
      'term_node' => array('tid', 'sticky', 'created'),
      'nid' => array('nid'),
    ),
    'foreign keys' => array(
      'tracked_node' => array(
        'table' => 'node',
        'columns' => array('nid' => 'nid'),
      ),
      'term' => array(
        'table' => 'taxonomy_term_data',
        'columns' => array('tid' => 'tid'),
      ),
    ),
  );
  db_create_table('taxonomy_index', $taxonomy_index);

  // Use an inline version of Drupal 6 taxonomy_get_vocabularies() here since
  // we can no longer rely on $vocabulary->nodes from the API function.
  $result = db_query('SELECT v.*, n.type FROM {taxonomy_vocabulary} v LEFT JOIN {taxonomy_vocabulary_node_type} n ON v.vid = n.vid ORDER BY v.weight, v.name');
  $vocabularies = array();
  foreach ($result as $record) {
    // If no node types are associated with a vocabulary, the LEFT JOIN will
    // return a NULL value for type.
    if (isset($record->type)) {
      $node_types[$record->vid][$record->type] = $record->type;
      unset($record->type);
      $record->nodes = $node_types[$record->vid];
    }
    elseif (!isset($record->nodes)) {
      $record->nodes = array();
    }
    $vocabularies[$record->vid] = $record;
  }

  foreach ($vocabularies as $vocabulary) {
    $field_name = 'taxonomy_' . $vocabulary->machine_name;
    $field = array(
      'field_name' => $field_name,
      'module' => 'taxonomy',
      'type' => 'taxonomy_term_reference',
      'cardinality' => $vocabulary->multiple || $vocabulary->tags ? FIELD_CARDINALITY_UNLIMITED : 1,
      'settings' => array(
        'required' => $vocabulary->required ? TRUE : FALSE,
        'allowed_values' => array(
          array(
            'vocabulary' => $vocabulary->machine_name,
            'parent' => 0,
          ),
        ),
      ),
    );
    _update_7000_field_create_field($field);

    foreach ($vocabulary->nodes as $bundle) {
      $instance = array(
        'label' => $vocabulary->name,
        'field_name' => $field_name,
        'bundle' => $bundle,
        'entity_type' => 'node',
        'settings' => array(),
        'description' => $vocabulary->help,
        'required' => $vocabulary->required,
        'widget' => array(),
        'display' => array(
          'default' => array(
            'type' => 'taxonomy_term_reference_link',
            'weight' => 10,
          ),
          'teaser' => array(
            'type' => 'taxonomy_term_reference_link',
            'weight' => 10,
          ),
        ),
      );
      if ($vocabulary->tags) {
        $instance['widget'] = array(
          'type' => 'taxonomy_autocomplete',
          'module' => 'taxonomy',
          'settings' => array(
            'size' => 60,
            'autocomplete_path' => 'taxonomy/autocomplete',
          ),
        );
      }
      else {
        $instance['widget'] = array(
          'type' => 'select',
          'module' => 'options',
          'settings' => array(),
        );
      }
      _update_7000_field_create_instance($field, $instance);
    }
  }

  // Some contrib projects stored term node associations without regard for the
  // selections in the taxonomy_vocabulary_node_types table, or have more terms
  // for a single node than the vocabulary allowed. We construct the
  // taxonomyextra field to store all the extra stuff.

  // Allowed values for this extra vocabs field is every vocabulary.
  $allowed_values = array();
  foreach (_update_7002_taxonomy_get_vocabularies() as $vocabulary) {
    $allowed_values[] = array(
      'vocabulary' => $vocabulary->machine_name,
      'parent' => 0,
    );
  }

  $field_name = 'taxonomyextra';
  $field = array(
    'field_name' => $field_name,
    'module' => 'taxonomy',
    'type' => 'taxonomy_term_reference',
    'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    'settings' => array(
      'required' => FALSE,
      'allowed_values' => $allowed_values,
    ),
  );
  _update_7000_field_create_field($field);

  foreach (_update_7000_node_get_types() as $bundle) {
    $instance = array(
      'label' => 'Taxonomy upgrade extras',
      'field_name' => $field_name,
      'entity_type' => 'node',
      'bundle' => $bundle->type,
      'settings' => array(),
      'description' => 'Debris left over after upgrade from Drupal 6',
      'widget' => array(
        'type' => 'taxonomy_autocomplete',
        'module' => 'taxonomy',
        'settings' => array(),
      ),
      'display' => array(
        'default' => array(
          'type' => 'taxonomy_term_reference_link',
          'weight' => 10,
        ),
        'teaser' => array(
          'type' => 'taxonomy_term_reference_link',
          'weight' => 10,
        ),
      ),
    );
    _update_7000_field_create_instance($field, $instance);
  }

  $fields = array('help', 'multiple', 'required', 'tags');
  foreach ($fields as $field) {
    db_drop_field('taxonomy_vocabulary', $field);
  }
}

/**
 * Migrate {taxonomy_term_node} table to field storage.
 *
 * @todo: This function can possibly be made much faster by wrapping a
 * transaction around all the inserts.
 */
function taxonomy_update_7005(&$sandbox) {
  // $sandbox contents:
  // - total: The total number of term_node relationships to migrate.
  // - count: The number of term_node relationships that have been
  //   migrated so far.
  // - last: The db_query_range() offset to use when querying
  //   term_node; this field is incremented in quantities of $batch
  //   (1000) but at the end of each call to this function, last and
  //   count are the same.
  // - vocabularies: An associative array mapping vocabulary id and node
  //   type to field name. If a voc id/node type pair does not appear
  //   in this array but a term_node relationship exists mapping a
  //   term in voc id to node of that type, the relationship is
  //   assigned to the taxonomymyextra field which allows terms of all
  //   vocabularies.
  // - cursor[values], cursor[deltas]: The contents of $values and
  //   $deltas at the end of the previous call to this function. These
  //   need to be preserved across calls because a single batch of
  //   1000 rows from term_node may end in the middle of the terms for
  //   a single node revision.
  //
  // $values is the array of values about to be/most recently inserted
  // into the SQL data table for the taxonomy_term_reference
  // field. Before $values is constructed for each record, the
  // $values from the previous insert is checked to see if the two
  // records are for the same node revision id; this enables knowing
  // when to reset the delta counters which are incremented across all
  // terms for a single field on a single revision, but reset for each
  // new field and revision.
  //
  // $deltas is an associative array mapping field name to the number
  // of term references stored so far for the current revision, which
  // provides the delta value for each term reference data insert. The
  // deltas are reset for each new revision.
  
  $conditions = array(
    'type' => 'taxonomy_term_reference',
    'deleted' => 0,
  );
  $field_info = _update_7000_field_read_fields($conditions, 'field_name');

  // This is a multi-pass update. On the first call we need to initialize some
  // variables.
  if (!isset($sandbox['total'])) {
    $sandbox['last'] = 0;
    $sandbox['count'] = 0;

    // Run the same joins as the query that is used later to retrieve the
    // term_node data, this ensures that bad records in that table - for
    // tids which aren't in taxonomy_term_data or nids which aren't in {node}
    // are not included in the count.
    $sandbox['total'] = db_query('SELECT COUNT(*) FROM {taxonomy_term_data} td INNER JOIN {taxonomy_term_node} tn ON td.tid = tn.tid INNER JOIN {node} n ON tn.nid = n.nid LEFT JOIN {node} n2 ON tn.vid = n2.vid')->fetchField();

    // Use an inline version of Drupal 6 taxonomy_get_vocabularies() here since
    // we can no longer rely on $vocabulary->nodes from the API function.
    $result = db_query('SELECT v.vid, v.machine_name, n.type FROM {taxonomy_vocabulary} v INNER JOIN {taxonomy_vocabulary_node_type} n ON v.vid = n.vid');
    $vocabularies = array();
    foreach ($result as $record) {

      // If no node types are associated with a vocabulary, the LEFT JOIN will
      // return a NULL value for type.
      if (isset($record->type)) {
        $vocabularies[$record->vid][$record->type] = 'taxonomy_'. $record->machine_name;
      }
    }

    if (!empty($vocabularies)) {
      $sandbox['vocabularies'] = $vocabularies;
    }

    db_create_table('taxonomy_update_7005', array(
      'description' => 'Stores temporary data for taxonomy_update_7005.',
      'fields' => array(
        'n' => array(
          'description' => 'Preserve order.',
          'type' => 'serial',
          'unsigned' => TRUE,
          'not null' => TRUE,
        ),
        'vocab_id' => array(
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
          'default' => 0,
        ),
        'tid' => array(
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
        ),
        'nid' => array(
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
        ),
        'vid' => array(
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => FALSE,
          'default' => NULL,
        ),
        'type' => array(
          'type' => 'varchar',
          'length' => 32,
          'not null' => TRUE,
          'default' => '',
        ),
        'created' => array(
          'type' => 'int',
          'not null' => FALSE,
        ),
        'sticky' => array(
          'type' => 'int',
          'not null' => FALSE,
        ),
        'status' => array(
          'type' => 'int',
          'not null' => FALSE,
        ),
        'is_current' => array(
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => FALSE,
        ),
      ),
      'primary key' => array('n'),
    ));

    // Query selects all revisions at once and processes them in revision and
    // term weight order.
    $query = db_select('taxonomy_term_data', 'td');
    // We are migrating term-node relationships. If there are none for a
    // term, we do not need the term_data row.
    $query->join('taxonomy_term_node', 'tn', 'td.tid = tn.tid');
    // If a term-node relationship exists for a nid that does not exist, we
    // cannot migrate it as we have no node to relate it to; thus we do not
    // need that row from term_node.
    $query->join('node', 'n', 'tn.nid = n.nid');
    // If the current term-node relationship is for the current revision of
    // the node, this left join will match and is_current will be non-NULL
    // (we also get the current sticky and created in this case). This
    // tells us whether to insert into the current data tables in addition
    // to the revision data tables.
    $query->leftJoin('node', 'n2', 'tn.vid = n2.vid');
    $query->addField('td', 'vid', 'vocab_id');
    $query->addField('td', 'tid');
    $query->addField('tn', 'nid');
    $query->addField('tn', 'vid');
    $query->addField('n', 'type');
    $query->addField('n2', 'created');
    $query->addField('n2', 'sticky');
    $query->addField('n2', 'status');
    $query->addField('n2', 'nid', 'is_current');
    // This query must return a consistent ordering across multiple calls.
    // We need them ordered by node vid (since we use that to decide when
    // to reset the delta counters) and by term weight so they appear
    // within each node in weight order. However, tn.vid,td.weight is not
    // guaranteed to be unique, so we add tn.tid as an additional sort key
    // because tn.tid,tn.vid is the primary key of the D6 term_node table
    // and so is guaranteed unique. Unfortunately it also happens to be in
    // the wrong order which is less efficient, but c'est la vie.
    $query->orderBy('tn.vid');
    $query->orderBy('td.weight');
    $query->orderBy('tn.tid');

    // Work around a bug in the PostgreSQL driver that would result in fatal
    // errors when this subquery is used in the insert query below. See
    // https://drupal.org/node/2057693.
    $fields = &$query->getFields();
    unset($fields['td.weight']);
    unset($fields['tn.tid']);

    db_insert('taxonomy_update_7005')
      ->from($query)
      ->execute();
  }
  else {
    // We do each pass in batches of 1000.
    $batch = 1000;

    $result = db_query_range('SELECT vocab_id, tid, nid, vid, type, created, sticky, status, is_current FROM {taxonomy_update_7005} ORDER BY n', $sandbox['last'], $batch);
    if (isset($sandbox['cursor'])) {
      $values = $sandbox['cursor']['values'];
      $deltas = $sandbox['cursor']['deltas'];
    }
    else {
      $deltas = array();
    }
    foreach ($result as $record) {
      $sandbox['count'] += 1;

      // Use the valid field for this vocabulary and node type or use the
      // overflow vocabulary if there is no valid field.
      $field_name = isset($sandbox['vocabularies'][$record->vocab_id][$record->type]) ? $sandbox['vocabularies'][$record->vocab_id][$record->type] : 'taxonomyextra';
      $field = $field_info[$field_name];

      // Start deltas from 0, and increment by one for each term attached to a
      // node.
      if (!isset($deltas[$field_name])) {
        $deltas[$field_name] = 0;
      }

      if (isset($values)) {

        // If the last inserted revision_id is the same as the current record,
        // use the previous deltas to calculate the next delta.
        if ($record->vid == $values[2]) {

          // For limited cardinality fields, the delta must not be allowed to
          // exceed the cardinality during the update. So ensure that the
          // delta about to be inserted is within this limit.
          // @see field_default_validate().
          if ($field['cardinality'] != FIELD_CARDINALITY_UNLIMITED && ($deltas[$field_name] + 1) > $field['cardinality']) {

            // For excess values of a single-term vocabulary, switch over to
            // the overflow field.
            $field_name = 'taxonomyextra';
            $field = $field_info[$field_name];
            if (!isset($deltas[$field_name])) {
              $deltas[$field_name] = 0;
            }
          }
        }
        else {

          // When the record is a new revision, empty the deltas array.
          $deltas = array($field_name => 0);
        }
      }

      // Table and column found in the field's storage details. During upgrades,
      // it's always SQL.
      $table_name = "field_data_{$field_name}";
      $revision_name = "field_revision_{$field_name}";
      $value_column = $field_name . '_tid';

      // Column names and values in field storage are the same for current and
      // revision.
      $columns = array('entity_type', 'entity_id', 'revision_id', 'bundle', 'language', 'delta', $value_column);
      $values = array('node', $record->nid, $record->vid, $record->type, LANGUAGE_NONE, $deltas[$field_name]++, $record->tid);

      // Insert rows into the revision table.
      db_insert($revision_name)->fields($columns)->values($values)->execute();

      // is_current column is a node ID if this revision is also current.
      if ($record->is_current) {
        db_insert($table_name)->fields($columns)->values($values)->execute();
        // Only insert a record in the taxonomy index if the node is published.
        if ($record->status) {
          // Update the {taxonomy_index} table.
          db_insert('taxonomy_index')
            ->fields(array('nid', 'tid', 'sticky', 'created',))
            ->values(array($record->nid, $record->tid, $record->sticky, $record->created))
            ->execute();
        }
      }
    }

    // Store the set of inserted values and the current revision's deltas in the
    // sandbox.
    $sandbox['cursor'] = array(
      'values' => $values,
      'deltas' => $deltas,
    );
    $sandbox['last'] += $batch;
  }

  if ($sandbox['count'] < $sandbox['total']) {
    $sandbox['#finished'] = FALSE;
  }
  else {
    db_drop_table('taxonomy_vocabulary_node_type');
    db_drop_table('taxonomy_term_node');

    // If there are no vocabs, we're done.
    db_drop_table('taxonomy_update_7005');
    $sandbox['#finished'] = TRUE;

    // Determine necessity of taxonomyextras field.
    $field = $field_info['taxonomyextra'];
    $revision_name = 'field_revision_' . $field['field_name'];
    $node_types = db_select($revision_name)->distinct()->fields($revision_name, array('bundle'))
      ->execute()->fetchCol();

    if (empty($node_types)) {
      // Delete the overflow field if there are no rows in the revision table.
      _update_7000_field_delete_field('taxonomyextra');
    }
    else {
      // Remove instances which are not actually used.
      $bundles = db_query('SELECT bundle FROM {field_config_instance} WHERE field_name = :field_name', array(':field_name' => 'taxonomyextra'))->fetchCol();
      $bundles = array_diff($bundles, $node_types);
      foreach ($bundles as $bundle) {
        _update_7000_field_delete_instance('taxonomyextra', 'node', $bundle);
      }
    }
  }
}

/**
 * Add {taxonomy_term_data}.format column.
 */
function taxonomy_update_7006() {
  db_add_field('taxonomy_term_data', 'format', array(
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => FALSE,
    'description' => 'The {filter_format}.format of the description.',
  ));
}

/**
 * Add index on {taxonomy_term_data}.name column to speed up taxonomy_get_term_by_name().
 */
function taxonomy_update_7007() {
  db_add_index('taxonomy_term_data', 'name', array('name'));
}

/**
 * Change the weight columns to normal int.
 */
function taxonomy_update_7008() {
  db_drop_index('taxonomy_term_data', 'taxonomy_tree');
  db_change_field('taxonomy_term_data', 'weight', 'weight', array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'The weight of this term in relation to other terms.',
  ), array(
    'indexes' => array(
       'taxonomy_tree' => array('vid', 'weight', 'name'),
    ),
  ));

  db_drop_index('taxonomy_vocabulary', 'list');
  db_change_field('taxonomy_vocabulary', 'weight', 'weight', array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'The weight of this vocabulary in relation to other vocabularies.',
  ), array(
    'indexes' => array(
      'list' => array('weight', 'name'),
    ),
  ));
}

/**
 * Change {taxonomy_term_data}.format into varchar.
 */
function taxonomy_update_7009() {
  db_change_field('taxonomy_term_data', 'format', 'format', array(
    'type' => 'varchar',
    'length' => 255,
    'not null' => FALSE,
    'description' => 'The {filter_format}.format of the description.',
  ));
}

/**
 * Change {taxonomy_index}.created to support signed int.
*/
function taxonomy_update_7010() {
  db_change_field('taxonomy_index', 'created', 'created', array(
    'description' => 'The Unix timestamp when the node was created.',
    'type' => 'int',
    'unsigned' => FALSE,
    'not null' => TRUE,
    'default'=> 0,
  ));
}

/**
 * @addtogroup updates-7.x-extra
 * @{
 */

/**
 * Drop unpublished nodes from the index.
 */
function taxonomy_update_7011(&$sandbox) {
  // Initialize information needed by the batch update system.
  if (!isset($sandbox['progress'])) {
    $sandbox['progress'] = 0;
    $sandbox['max'] = db_query('SELECT COUNT(DISTINCT n.nid) FROM {node} n INNER JOIN {taxonomy_index} t ON n.nid = t.nid WHERE n.status = :status', array(':status' => NODE_NOT_PUBLISHED))->fetchField();
    // If there's no data, don't bother with the extra work.
    if (empty($sandbox['max'])) {
      return;
    }
  }

  // Process records in groups of 5000.
  $limit = 5000;
  $nids = db_query_range('SELECT DISTINCT n.nid FROM {node} n INNER JOIN {taxonomy_index} t ON n.nid = t.nid WHERE n.status = :status', 0, $limit, array(':status' => NODE_NOT_PUBLISHED))->fetchCol();
  if (!empty($nids)) {
    db_delete('taxonomy_index')
      ->condition('nid', $nids)
      ->execute();
  }

  // Update our progress information for the batch update.
  $sandbox['progress'] += $limit;

  // Indicate our current progress to the batch update system, if the update is
  // not yet complete.
  if ($sandbox['progress'] < $sandbox['max']) {
    $sandbox['#finished'] = $sandbox['progress'] / $sandbox['max'];
  }
}

/**
 * @} End of "addtogroup updates-7.x-extra".
 */