Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Você atualiza apenas os campos alterados ou todos os campos?


Acho que vale a pena mudar - mas provavelmente não vale a pena fazer um select antes de inserir.

Eu só atualizo os campos que foram alterados, faz parte do funcionamento da minha classe DbEntity que segue um padrão activerecord. Custa pouco mais fazer isso porque eu mantenho o registro atual e os registros originais - simplesmente copiando sempre que um registro é carregado.

As razões são brevidade - não realmente desempenho. Além disso, você pode verificar a modificação simultânea adicionando uma cláusula where no valor antigo dos campos atualizados e lançando o erro apropriado.

No método de gravação/atualização:
$s1 = "";

foreach ($this->record as $key => $value)
{
    // only update fields that have been changed
    if ($value != $this->orig_record[$key])
    {
        $s1 .= $comma."`$key`='".mysql_real_escape_string($value)."'";
        $comma = ", ";
    }
}

$query = "UPDATE ".$this->table." SET $s1 where {$this->id_field}='".$this->get_keyfield()."'";
$query .= $this->extra_sql_update;
mysql_query($query);

$ar = mysql_affected_rows();
//
// the number of affected rows is actually those changed by the update operation, which will 
// either be zero, or 1. If the query affects more than one row then we have a problem.
if ($ar < 0 || $ar > 1)
{
    cbf_error("cbf_dbentity: {$this->table} :: only one row (not $ar) must be affected by an insert operation. $query",
      E_USER_ERROR);
}
else
{
    $new_id = $this->get_keyfield();

    GlobalEventBus::notify_all(new AuditLogSQL($this->table, "update", $query));

}

$this->orig_record = Array();

foreach ($this->record as $key => $value)
    $this->orig_record[$key] = $value;


//
// sanity check - ensure that what we have just written is actually there.

$this->load($new_id);

foreach ($this->orig_record as $key => $value)
    if (trim($this->record[$key]) != trim($value) 
        && (!$this->record[$key] == "0" && $value=""))
        cbf_error("cbf_dbentity: {$this->table} :: record differs during write after reload: field $key was \"$value\", after write it is now \"".
              $this->record[$key]."\"",E_USER_ERROR);

No método de carregamento
$this->orig_record = Array();
foreach ($this->record as $key => $value)
    $this->orig_record[$key] = $value;