You are here

function domain_prefix_insert_data in Domain Access 6.2

Insert data from one table into another.

We need a function here to prevent accidental errors when copying or updating serial fields that have a 0 element, like {users}.

Parameters

$schema: The table definition provided by hook_schema.

$newtable: The name of the table being created or updated.

$sourcetable: The name of the source data table.

1 call to domain_prefix_insert_data()
domain_prefix_form_submit in domain_prefix/domain_prefix.admin.inc
FormsAPI for domain_prefix_form.

File

domain_prefix/domain_prefix.admin.inc, line 488
Admin page functions for selective table prefixing for use with Domain Access.

Code

function domain_prefix_insert_data($schema, $newtable, $sourcetable) {
  $zero_row = FALSE;

  // Check the source table for serial fields that include a zero row.
  foreach ($schema['fields'] as $field => $info) {
    if ($info['type'] == 'serial') {
      $zero_row = db_fetch_array(db_query("SELECT * FROM {%s} WHERE %s = 0", $sourcetable, $field));
    }
    break;
  }

  // If no zero row, then we are done.
  if (empty($zero_row)) {

    // Insert the records.
    db_query("INSERT INTO {%s} SELECT * FROM {%s}", $newtable, $sourcetable);
    return;
  }

  // Run the query, but treat row zero with care.
  db_query("INSERT INTO {%s} SELECT * FROM {%s} WHERE %s > 0", $newtable, $sourcetable, $field);
  db_query("INSERT INTO {%s} SELECT * FROM {%s} WHERE %s = 0", $newtable, $sourcetable, $field);
  $id = db_last_insert_id($newtable, $field);
  db_query("UPDATE {%s} SET %s = 0 WHERE %s = %d", $newtable, $field, $field, $id);

  // On MySQL at least, we can safely modify the autoincrement sequence.
  if ($GLOBALS['db_type'] == 'mysqli') {
    db_query("ALTER TABLE %s AUTO_INCREMENT = %d", $newtable, $id);
  }
}