You are here

function coder_upgrade_parse_insert_query_string in Coder 7.2

Same name and namespace in other branches
  1. 7 coder_upgrade/conversions/db.inc \coder_upgrade_parse_insert_query_string()

Replaces D6 database API call with D7 equivalent.

@todo Fill in this with unhandled items.

Parameters

string $sql: The SQL query string to parse.

array $values: List of replacement values passed to db_query().

1 call to coder_upgrade_parse_insert_query_string()
coder_upgrade_parse_query_string in coder_upgrade/conversions/db.inc
Replaces D6 database API call with D7 equivalent.

File

coder_upgrade/conversions/db.inc, line 349
Provides conversion routines applied to database API function calls and hooks.

Code

function coder_upgrade_parse_insert_query_string($sql, $values) {
  global $_coder_upgrade_replacement_values_is_array;
  $new = array();

  // Look for query with a WHERE clause.
  // INSERT INTO {mytable_longer_name} (intvar, stringvar, floatvar) VALUES (%d, '%s', %f)
  // TODO How does DBTNG handle multiple rows to insert?
  $find = '@INSERT INTO\\s+{(\\w+)}\\s+\\((.*?)\\)\\s+VALUES\\s+\\((.*?)\\)@s';
  preg_match($find, $sql, $matches);
  cdp($matches);
  if (empty($matches)) {
    cdp($sql, '$sql');
    clp('ERROR: could not parse sql INSERT statement.');
    return array(
      'NULL',
    );

    // $new;
  }

  // Parse fields to be updated.
  if (count($matches[2]) != count($matches[3])) {
    clp('ERROR: could not parse field names and replacements on sql INSERT statement.');
    return array(
      'NULL',
    );

    // $new;
  }
  $fields = preg_split("@,\\s*@", $matches[2]);
  $holders = preg_split("@,\\s*@", $matches[3]);
  $fields = array_combine($fields, $holders);
  cdp($fields);
  $replacement_count = coder_upgrade_count_sql_values($holders);
  $_coder_upgrade_replacement_values_is_array = count($values) == 1 && $replacement_count > 1;

  // Build DBTNG syntax string.
  // TODO Values could be literals not placeholders.
  $new[] = "\$id = db_insert('{$matches[1]}')";
  $new[] = "\t->fields(array(";
  foreach ($fields as $field => $value) {
    if (preg_match('/%[sdbf]/', $value)) {

      // Value is a placeholder.
      $value = coder_upgrade_next_replacement_value($values);
    }
    else {

      // Value is a literal (assume so).
    }
    $new[] = "\t\t'{$field}' => {$value},";
  }
  $new[] = "\t))";
  $new[] = "\t->execute();";
  return $new;
}