4

I don't know if this is a bug, but I am using Doctrine 2.3.0 and I found the persist/flush behaviour quite strange. I have a basic table:

------------------
|   test         |
------------------
| id   INT | AI  |
| field1 VARCHAR |
| field2 VARCHAR |
-----------------

When I create an entry by setting only field1:

$test = new Entities\test();
$test->setField1('foo');
$em->persist($test);
$em->flush();

Doctrine\DBAL\Logging\EchoSQLLogger tells me (which is confirmed by looking at the DB) that Doctrine performs the following query:

INSERT INTO test (field1, field2) VALUES (?, ?)
array(2) {
  [1]=>
  string(3) "foo"
  [2]=>
  NULL
}

As you can see, although I haven't set field2, Doctrine does put it in the insert statement with a NULL value.

I have that behaviour for all my entities, which is problematic because when doing inserts, my default DB values for fields I don't set are overwritten by NULL.

Is this the expected default behaviour of Doctrine, is there a way to turn that off (i.e. exclude fields I don't set from the INSERT statements)?

I should probably add that my entities were generated automatically with the reverse engineering, and that the declaration for one of the fields looks like this

/**
 * @var string $field2
 *                                       // removing nullalble makes no diff.
 * @ORM\Column(name="field2", type="string", length=45, nullable=true)
 */
private $field2;

/**
 * Set field2
 *
 * @param string $field2
 * @return Test
 */
public function setField2($field2)
{
    $this->field2 = $field2;
    return $this;
}
Max
  • 12,794
  • 30
  • 90
  • 142

1 Answers1

1

I suppose this is default behaviour, as it could be treated logical to create a full record in one INSERT statement. But I could be mistaking. Having some kind of @ORM\Column(type="boolean", columnDefinition="TINYINT(1) NULL DEFAULT 0") could be treated as a hack, but solution. I advise you to review database record insertion logic.

nefo_x
  • 3,050
  • 4
  • 27
  • 40
  • +1 for the hack, I will try it out. Can you clarify what you mean by "I advise you to review database record insertion logic": AFAIK doing partial `INSERT` (i.e. where not all fields are defined in `VALUES`) is perfectly legit., so is the use of the `DEFAULT` constraint on `MySQL` fields which intended behaviour is to provide a default value for a field when not provided during `INSERT/UPDATE`: http://stackoverflow.com/questions/3357953/default-a-column-with-empty-string. How am I supposed to get the `DEFAULT` constraint value to actually be used? (instead of `NULL` as inserted by `Doctrine`)? – Max Oct 24 '12 at 10:25
  • I was using setting default values for properties in the class. Will check later evening, if won't forget. – nefo_x Oct 24 '12 at 15:38