function __schools_add_school_id_to_fp5_tables

7.x schools.module __schools_add_school_id_to_fp5_tables()
6.x schools.module __schools_add_school_id_to_fp5_tables()

File

modules/schools/schools.module, line 14
Schools module.

Code

function __schools_add_school_id_to_fp5_tables() {

  set_time_limit(999); // might take a while

  $tables = array(
    'courses', 'draft_courses', 'degrees', 'draft_degrees', 'groups', 'draft_groups',
    'colleges *',
    'degree_college',
    'degree_tracks', 'draft_degree_tracks',
    'draft_instructions',
    'standardized_tests',
    'student_tests',
    'subjects *',
    'transfer_courses',
    'transfer_institutions',
    'users',
    'watchdog',
  );

  $needs_primary = array();
  $show_create = array();
  foreach ($tables as $table) {
    $bool_primary = FALSE;


    if (strstr($table, "*")) {
      $table = trim(str_replace("*", "", $table));
      $bool_primary = TRUE;
    }

    $show_create [] = $table;

    // If we were supposed to ALSO add as a primary key, then we should output a message to the user, so they know to do that.
    if ($bool_primary) {
      $needs_primary [] = $table;
    }



    // Does this table already have school_id field?
    $res = db_query("show columns from `$table` WHERE `Field` = 'school_id'");
    $cur = db_fetch_array($res);
    $test = @trim($cur ['Field']);
    if ($test == 'school_id') {
      continue;
    }

    // Otherwise, we need to add the column to the table, and a key!
    fpm("Adding to $table...");

    $q = "ALTER TABLE `$table` ADD COLUMN `school_id` INT NOT NULL DEFAULT 0";
    db_query($q);

    // Add regular key    
    $q = "ALTER TABLE `$table` ADD KEY `school_id` (`school_id`)";
    db_query($q);


  } // foreach

  fpm($needs_primary);

  //////////////////////////////////////
  // Set our new primary keys
  foreach ($needs_primary as $table) {
    $res = db_query("SHOW KEYS FROM `$table` WHERE Key_name = 'PRIMARY'");
    $keys = array();
    while ($cur = db_fetch_array($res)) {
      $cn = $cur ['Column_name'];
      if ($cn == 'school_id') {
        continue; // already in there.
      }
      $keys [] = $cn;
    }

    $keys [] = 'school_id';

    $kline = join(", ", $keys);

    db_query("ALTER TABLE `$table` 
              DROP PRIMARY KEY, 
              ADD PRIMARY KEY ($kline)");

  }







  $rtn = "";

  foreach ($show_create as $table) {

    $res = db_query("SHOW CREATE TABLE `$table`");
    $cur = db_fetch_array($res);
    $create = $cur ['Create Table'];

    $create = str_ireplace("USING BTREE", "", $create);
    $create = str_ireplace("CHARACTER SET latin1", "", $create);
    $create = str_ireplace("COLLATE utf8mb4_unicode_ci", "", $create);

    $temp = explode("ENGINE=", $create);
    $create = trim($temp [0]);


    $rtn .= $create . "; \n\n\n\n";

  }

  fpm("<textarea>$rtn</textarea>");



}