forked from doctrine/orm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BasicEntityPersister.php
2062 lines (1672 loc) · 73.2 KB
/
BasicEntityPersister.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace Doctrine\ORM\Persisters\Entity;
use BackedEnum;
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\Expr\Comparison;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\LockMode;
use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Result;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\MappingException;
use Doctrine\ORM\Mapping\QuoteStrategy;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\PersistentCollection;
use Doctrine\ORM\Persisters\Exception\CantUseInOperatorOnCompositeKeys;
use Doctrine\ORM\Persisters\Exception\InvalidOrientation;
use Doctrine\ORM\Persisters\Exception\UnrecognizedField;
use Doctrine\ORM\Persisters\SqlExpressionVisitor;
use Doctrine\ORM\Persisters\SqlValueVisitor;
use Doctrine\ORM\Query;
use Doctrine\ORM\Query\QueryException;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\ORM\Repository\Exception\InvalidFindByCall;
use Doctrine\ORM\UnitOfWork;
use Doctrine\ORM\Utility\IdentifierFlattener;
use Doctrine\ORM\Utility\PersisterHelper;
use LengthException;
use function array_combine;
use function array_keys;
use function array_map;
use function array_merge;
use function array_search;
use function array_unique;
use function array_values;
use function assert;
use function count;
use function implode;
use function is_array;
use function is_object;
use function reset;
use function spl_object_id;
use function sprintf;
use function str_contains;
use function strtoupper;
use function trim;
/**
* A BasicEntityPersister maps an entity to a single table in a relational database.
*
* A persister is always responsible for a single entity type.
*
* EntityPersisters are used during a UnitOfWork to apply any changes to the persistent
* state of entities onto a relational database when the UnitOfWork is committed,
* as well as for basic querying of entities and their associations (not DQL).
*
* The persisting operations that are invoked during a commit of a UnitOfWork to
* persist the persistent entity state are:
*
* - {@link addInsert} : To schedule an entity for insertion.
* - {@link executeInserts} : To execute all scheduled insertions.
* - {@link update} : To update the persistent state of an entity.
* - {@link delete} : To delete the persistent state of an entity.
*
* As can be seen from the above list, insertions are batched and executed all at once
* for increased efficiency.
*
* The querying operations invoked during a UnitOfWork, either through direct find
* requests or lazy-loading, are the following:
*
* - {@link load} : Loads (the state of) a single, managed entity.
* - {@link loadAll} : Loads multiple, managed entities.
* - {@link loadOneToOneEntity} : Loads a one/many-to-one entity association (lazy-loading).
* - {@link loadOneToManyCollection} : Loads a one-to-many entity association (lazy-loading).
* - {@link loadManyToManyCollection} : Loads a many-to-many entity association (lazy-loading).
*
* The BasicEntityPersister implementation provides the default behavior for
* persisting and querying entities that are mapped to a single database table.
*
* Subclasses can be created to provide custom persisting and querying strategies,
* i.e. spanning multiple tables.
*/
class BasicEntityPersister implements EntityPersister
{
/** @var array<string,string> */
private static array $comparisonMap = [
Comparison::EQ => '= %s',
Comparison::NEQ => '!= %s',
Comparison::GT => '> %s',
Comparison::GTE => '>= %s',
Comparison::LT => '< %s',
Comparison::LTE => '<= %s',
Comparison::IN => 'IN (%s)',
Comparison::NIN => 'NOT IN (%s)',
Comparison::CONTAINS => 'LIKE %s',
Comparison::STARTS_WITH => 'LIKE %s',
Comparison::ENDS_WITH => 'LIKE %s',
];
/**
* The underlying DBAL Connection of the used EntityManager.
*/
protected Connection $conn;
/**
* The database platform.
*/
protected AbstractPlatform $platform;
/**
* Queued inserts.
*
* @psalm-var array<int, object>
*/
protected array $queuedInserts = [];
/**
* The map of column names to DBAL mapping types of all prepared columns used
* when INSERTing or UPDATEing an entity.
*
* @see prepareInsertData($entity)
* @see prepareUpdateData($entity)
*
* @var mixed[]
*/
protected array $columnTypes = [];
/**
* The map of quoted column names.
*
* @see prepareInsertData($entity)
* @see prepareUpdateData($entity)
*
* @var mixed[]
*/
protected array $quotedColumns = [];
/**
* The INSERT SQL statement used for entities handled by this persister.
* This SQL is only generated once per request, if at all.
*/
private ?string $insertSql = null;
/**
* The quote strategy.
*/
protected QuoteStrategy $quoteStrategy;
/**
* The IdentifierFlattener used for manipulating identifiers
*/
private IdentifierFlattener $identifierFlattener;
protected CachedPersisterContext $currentPersisterContext;
private CachedPersisterContext $limitsHandlingContext;
private CachedPersisterContext $noLimitsContext;
/**
* Initializes a new <tt>BasicEntityPersister</tt> that uses the given EntityManager
* and persists instances of the class described by the given ClassMetadata descriptor.
*
* @param ClassMetadata $class Metadata object that describes the mapping of the mapped entity class.
*/
public function __construct(
protected EntityManagerInterface $em,
protected ClassMetadata $class,
) {
$this->conn = $em->getConnection();
$this->platform = $this->conn->getDatabasePlatform();
$this->quoteStrategy = $em->getConfiguration()->getQuoteStrategy();
$this->identifierFlattener = new IdentifierFlattener($em->getUnitOfWork(), $em->getMetadataFactory());
$this->noLimitsContext = $this->currentPersisterContext = new CachedPersisterContext(
$class,
new Query\ResultSetMapping(),
false
);
$this->limitsHandlingContext = new CachedPersisterContext(
$class,
new Query\ResultSetMapping(),
true
);
}
public function getClassMetadata(): ClassMetadata
{
return $this->class;
}
public function getResultSetMapping(): ResultSetMapping
{
return $this->currentPersisterContext->rsm;
}
public function addInsert(object $entity): void
{
$this->queuedInserts[spl_object_id($entity)] = $entity;
}
/**
* {@inheritdoc}
*/
public function getInserts(): array
{
return $this->queuedInserts;
}
/**
* {@inheritdoc}
*/
public function executeInserts(): array
{
if (! $this->queuedInserts) {
return [];
}
$postInsertIds = [];
$idGenerator = $this->class->idGenerator;
$isPostInsertId = $idGenerator->isPostInsertGenerator();
$stmt = $this->conn->prepare($this->getInsertSQL());
$tableName = $this->class->getTableName();
foreach ($this->queuedInserts as $entity) {
$insertData = $this->prepareInsertData($entity);
if (isset($insertData[$tableName])) {
$paramIndex = 1;
foreach ($insertData[$tableName] as $column => $value) {
$stmt->bindValue($paramIndex++, $value, $this->columnTypes[$column]);
}
}
$stmt->executeStatement();
if ($isPostInsertId) {
$generatedId = $idGenerator->generateId($this->em, $entity);
$id = [$this->class->identifier[0] => $generatedId];
$postInsertIds[] = [
'generatedId' => $generatedId,
'entity' => $entity,
];
} else {
$id = $this->class->getIdentifierValues($entity);
}
if ($this->class->requiresFetchAfterChange) {
$this->assignDefaultVersionAndUpsertableValues($entity, $id);
}
}
$this->queuedInserts = [];
return $postInsertIds;
}
/**
* Retrieves the default version value which was created
* by the preceding INSERT statement and assigns it back in to the
* entities version field if the given entity is versioned.
* Also retrieves values of columns marked as 'non insertable' and / or
* 'not updatable' and assigns them back to the entities corresponding fields.
*
* @param mixed[] $id
*/
protected function assignDefaultVersionAndUpsertableValues(object $entity, array $id): void
{
$values = $this->fetchVersionAndNotUpsertableValues($this->class, $id);
foreach ($values as $field => $value) {
$value = Type::getType($this->class->fieldMappings[$field]['type'])->convertToPHPValue($value, $this->platform);
$this->class->setFieldValue($entity, $field, $value);
}
}
/**
* Fetches the current version value of a versioned entity and / or the values of fields
* marked as 'not insertable' and / or 'not updatable'.
*
* @param mixed[] $id
*/
protected function fetchVersionAndNotUpsertableValues(ClassMetadata $versionedClass, array $id): mixed
{
$columnNames = [];
foreach ($this->class->fieldMappings as $key => $column) {
if (isset($column['generated']) || ($this->class->isVersioned && $key === $versionedClass->versionField)) {
$columnNames[$key] = $this->quoteStrategy->getColumnName($key, $versionedClass, $this->platform);
}
}
$tableName = $this->quoteStrategy->getTableName($versionedClass, $this->platform);
$identifier = $this->quoteStrategy->getIdentifierColumnNames($versionedClass, $this->platform);
// FIXME: Order with composite keys might not be correct
$sql = 'SELECT ' . implode(', ', $columnNames)
. ' FROM ' . $tableName
. ' WHERE ' . implode(' = ? AND ', $identifier) . ' = ?';
$flatId = $this->identifierFlattener->flattenIdentifier($versionedClass, $id);
$values = $this->conn->fetchNumeric(
$sql,
array_values($flatId),
$this->extractIdentifierTypes($id, $versionedClass)
);
if ($values === false) {
throw new LengthException('Unexpected empty result for database query.');
}
$values = array_combine(array_keys($columnNames), $values);
if (! $values) {
throw new LengthException('Unexpected number of database columns.');
}
return $values;
}
/**
* @param mixed[] $id
*
* @return list<ParameterType|int|string>
* @psalm-return list<ParameterType::*|int|string>
*/
private function extractIdentifierTypes(array $id, ClassMetadata $versionedClass): array
{
$types = [];
foreach ($id as $field => $value) {
$types = array_merge($types, $this->getTypes($field, $value, $versionedClass));
}
return $types;
}
public function update(object $entity): void
{
$tableName = $this->class->getTableName();
$updateData = $this->prepareUpdateData($entity);
if (! isset($updateData[$tableName])) {
return;
}
$data = $updateData[$tableName];
if (! $data) {
return;
}
$isVersioned = $this->class->isVersioned;
$quotedTableName = $this->quoteStrategy->getTableName($this->class, $this->platform);
$this->updateTable($entity, $quotedTableName, $data, $isVersioned);
if ($this->class->requiresFetchAfterChange) {
$id = $this->class->getIdentifierValues($entity);
$this->assignDefaultVersionAndUpsertableValues($entity, $id);
}
}
/**
* Performs an UPDATE statement for an entity on a specific table.
* The UPDATE can optionally be versioned, which requires the entity to have a version field.
*
* @param object $entity The entity object being updated.
* @param string $quotedTableName The quoted name of the table to apply the UPDATE on.
* @param mixed[] $updateData The map of columns to update (column => value).
* @param bool $versioned Whether the UPDATE should be versioned.
*
* @throws UnrecognizedField
* @throws OptimisticLockException
*/
final protected function updateTable(
object $entity,
string $quotedTableName,
array $updateData,
bool $versioned = false
): void {
$set = [];
$types = [];
$params = [];
foreach ($updateData as $columnName => $value) {
$placeholder = '?';
$column = $columnName;
switch (true) {
case isset($this->class->fieldNames[$columnName]):
$fieldName = $this->class->fieldNames[$columnName];
$column = $this->quoteStrategy->getColumnName($fieldName, $this->class, $this->platform);
if (isset($this->class->fieldMappings[$fieldName])) {
$type = Type::getType($this->columnTypes[$columnName]);
$placeholder = $type->convertToDatabaseValueSQL('?', $this->platform);
}
break;
case isset($this->quotedColumns[$columnName]):
$column = $this->quotedColumns[$columnName];
break;
}
$params[] = $value;
$set[] = $column . ' = ' . $placeholder;
$types[] = $this->columnTypes[$columnName];
}
$where = [];
$identifier = $this->em->getUnitOfWork()->getEntityIdentifier($entity);
foreach ($this->class->identifier as $idField) {
if (! isset($this->class->associationMappings[$idField])) {
$params[] = $identifier[$idField];
$types[] = $this->class->fieldMappings[$idField]['type'];
$where[] = $this->quoteStrategy->getColumnName($idField, $this->class, $this->platform);
continue;
}
$params[] = $identifier[$idField];
$where[] = $this->quoteStrategy->getJoinColumnName(
$this->class->associationMappings[$idField]['joinColumns'][0],
$this->class,
$this->platform
);
$targetMapping = $this->em->getClassMetadata($this->class->associationMappings[$idField]['targetEntity']);
$targetType = PersisterHelper::getTypeOfField($targetMapping->identifier[0], $targetMapping, $this->em);
if ($targetType === []) {
throw UnrecognizedField::byName($targetMapping->identifier[0]);
}
$types[] = reset($targetType);
}
if ($versioned) {
$versionField = $this->class->versionField;
assert($versionField !== null);
$versionFieldType = $this->class->fieldMappings[$versionField]['type'];
$versionColumn = $this->quoteStrategy->getColumnName($versionField, $this->class, $this->platform);
$where[] = $versionColumn;
$types[] = $this->class->fieldMappings[$versionField]['type'];
$params[] = $this->class->reflFields[$versionField]->getValue($entity);
switch ($versionFieldType) {
case Types::SMALLINT:
case Types::INTEGER:
case Types::BIGINT:
$set[] = $versionColumn . ' = ' . $versionColumn . ' + 1';
break;
case Types::DATETIME_MUTABLE:
$set[] = $versionColumn . ' = CURRENT_TIMESTAMP';
break;
}
}
$sql = 'UPDATE ' . $quotedTableName
. ' SET ' . implode(', ', $set)
. ' WHERE ' . implode(' = ? AND ', $where) . ' = ?';
$result = $this->conn->executeStatement($sql, $params, $types);
if ($versioned && ! $result) {
throw OptimisticLockException::lockFailed($entity);
}
}
/**
* @param array<mixed> $identifier
* @param string[] $types
*
* @todo Add check for platform if it supports foreign keys/cascading.
*/
protected function deleteJoinTableRecords(array $identifier, array $types): void
{
foreach ($this->class->associationMappings as $mapping) {
if ($mapping['type'] !== ClassMetadata::MANY_TO_MANY) {
continue;
}
// @Todo this only covers scenarios with no inheritance or of the same level. Is there something
// like self-referential relationship between different levels of an inheritance hierarchy? I hope not!
$selfReferential = ($mapping['targetEntity'] === $mapping['sourceEntity']);
$class = $this->class;
$association = $mapping;
$otherColumns = [];
$otherKeys = [];
$keys = [];
if (! $mapping['isOwningSide']) {
$class = $this->em->getClassMetadata($mapping['targetEntity']);
$association = $class->associationMappings[$mapping['mappedBy']];
}
$joinColumns = $mapping['isOwningSide']
? $association['joinTable']['joinColumns']
: $association['joinTable']['inverseJoinColumns'];
if ($selfReferential) {
$otherColumns = ! $mapping['isOwningSide']
? $association['joinTable']['joinColumns']
: $association['joinTable']['inverseJoinColumns'];
}
foreach ($joinColumns as $joinColumn) {
$keys[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
}
foreach ($otherColumns as $joinColumn) {
$otherKeys[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
}
if (isset($mapping['isOnDeleteCascade'])) {
continue;
}
$joinTableName = $this->quoteStrategy->getJoinTableName($association, $this->class, $this->platform);
$this->conn->delete($joinTableName, array_combine($keys, $identifier), $types);
if ($selfReferential) {
$this->conn->delete($joinTableName, array_combine($otherKeys, $identifier), $types);
}
}
}
public function delete(object $entity): bool
{
$class = $this->class;
$identifier = $this->em->getUnitOfWork()->getEntityIdentifier($entity);
$tableName = $this->quoteStrategy->getTableName($class, $this->platform);
$idColumns = $this->quoteStrategy->getIdentifierColumnNames($class, $this->platform);
$id = array_combine($idColumns, $identifier);
$types = $this->getClassIdentifiersTypes($class);
$this->deleteJoinTableRecords($identifier, $types);
return (bool) $this->conn->delete($tableName, $id, $types);
}
/**
* Prepares the changeset of an entity for database insertion (UPDATE).
*
* The changeset is obtained from the currently running UnitOfWork.
*
* During this preparation the array that is passed as the second parameter is filled with
* <columnName> => <value> pairs, grouped by table name.
*
* Example:
* <code>
* array(
* 'foo_table' => array('column1' => 'value1', 'column2' => 'value2', ...),
* 'bar_table' => array('columnX' => 'valueX', 'columnY' => 'valueY', ...),
* ...
* )
* </code>
*
* @param object $entity The entity for which to prepare the data.
* @param bool $isInsert Whether the data to be prepared refers to an insert statement.
*
* @return mixed[][] The prepared data.
* @psalm-return array<string, array<array-key, mixed|null>>
*/
protected function prepareUpdateData(object $entity, bool $isInsert = false): array
{
$versionField = null;
$result = [];
$uow = $this->em->getUnitOfWork();
$versioned = $this->class->isVersioned;
if ($versioned !== false) {
$versionField = $this->class->versionField;
}
foreach ($uow->getEntityChangeSet($entity) as $field => $change) {
if (isset($versionField) && $versionField === $field) {
continue;
}
if (isset($this->class->embeddedClasses[$field])) {
continue;
}
$newVal = $change[1];
if (! isset($this->class->associationMappings[$field])) {
$fieldMapping = $this->class->fieldMappings[$field];
$columnName = $fieldMapping['columnName'];
if (! $isInsert && isset($fieldMapping['notUpdatable'])) {
continue;
}
if ($isInsert && isset($fieldMapping['notInsertable'])) {
continue;
}
$this->columnTypes[$columnName] = $fieldMapping['type'];
$result[$this->getOwningTable($field)][$columnName] = $newVal;
continue;
}
$assoc = $this->class->associationMappings[$field];
// Only owning side of x-1 associations can have a FK column.
if (! $assoc['isOwningSide'] || ! ($assoc['type'] & ClassMetadata::TO_ONE)) {
continue;
}
if ($newVal !== null) {
$oid = spl_object_id($newVal);
if (isset($this->queuedInserts[$oid]) || $uow->isScheduledForInsert($newVal)) {
// The associated entity $newVal is not yet persisted, so we must
// set $newVal = null, in order to insert a null value and schedule an
// extra update on the UnitOfWork.
$uow->scheduleExtraUpdate($entity, [$field => [null, $newVal]]);
$newVal = null;
}
}
$newValId = null;
if ($newVal !== null) {
$newValId = $uow->getEntityIdentifier($newVal);
}
$targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
$owningTable = $this->getOwningTable($field);
foreach ($assoc['joinColumns'] as $joinColumn) {
$sourceColumn = $joinColumn['name'];
$targetColumn = $joinColumn['referencedColumnName'];
$quotedColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform);
$this->quotedColumns[$sourceColumn] = $quotedColumn;
$this->columnTypes[$sourceColumn] = PersisterHelper::getTypeOfColumn($targetColumn, $targetClass, $this->em);
$result[$owningTable][$sourceColumn] = $newValId
? $newValId[$targetClass->getFieldForColumn($targetColumn)]
: null;
}
}
return $result;
}
/**
* Prepares the data changeset of a managed entity for database insertion (initial INSERT).
* The changeset of the entity is obtained from the currently running UnitOfWork.
*
* The default insert data preparation is the same as for updates.
*
* @see prepareUpdateData
*
* @param object $entity The entity for which to prepare the data.
*
* @return mixed[][] The prepared data for the tables to update.
* @psalm-return array<string, mixed[]>
*/
protected function prepareInsertData(object $entity): array
{
return $this->prepareUpdateData($entity, true);
}
public function getOwningTable(string $fieldName): string
{
return $this->class->getTableName();
}
/**
* {@inheritdoc}
*/
public function load(
array $criteria,
?object $entity = null,
?array $assoc = null,
array $hints = [],
LockMode|int|null $lockMode = null,
?int $limit = null,
?array $orderBy = null
): ?object {
$this->switchPersisterContext(null, $limit);
$sql = $this->getSelectSQL($criteria, $assoc, $lockMode, $limit, null, $orderBy);
[$params, $types] = $this->expandParameters($criteria);
$stmt = $this->conn->executeQuery($sql, $params, $types);
if ($entity !== null) {
$hints[Query::HINT_REFRESH] = true;
$hints[Query::HINT_REFRESH_ENTITY] = $entity;
}
$hydrator = $this->em->newHydrator($this->currentPersisterContext->selectJoinSql ? Query::HYDRATE_OBJECT : Query::HYDRATE_SIMPLEOBJECT);
$entities = $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, $hints);
return $entities ? $entities[0] : null;
}
/**
* {@inheritdoc}
*/
public function loadById(array $identifier, ?object $entity = null): ?object
{
return $this->load($identifier, $entity);
}
/**
* {@inheritdoc}
*/
public function loadOneToOneEntity(array $assoc, object $sourceEntity, array $identifier = []): ?object
{
$foundEntity = $this->em->getUnitOfWork()->tryGetById($identifier, $assoc['targetEntity']);
if ($foundEntity !== false) {
return $foundEntity;
}
$targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
if ($assoc['isOwningSide']) {
$isInverseSingleValued = $assoc['inversedBy'] && ! $targetClass->isCollectionValuedAssociation($assoc['inversedBy']);
// Mark inverse side as fetched in the hints, otherwise the UoW would
// try to load it in a separate query (remember: to-one inverse sides can not be lazy).
$hints = [];
if ($isInverseSingleValued) {
$hints['fetched']['r'][$assoc['inversedBy']] = true;
}
$targetEntity = $this->load($identifier, null, $assoc, $hints);
// Complete bidirectional association, if necessary
if ($targetEntity !== null && $isInverseSingleValued) {
$targetClass->reflFields[$assoc['inversedBy']]->setValue($targetEntity, $sourceEntity);
}
return $targetEntity;
}
$sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']);
$owningAssoc = $targetClass->getAssociationMapping($assoc['mappedBy']);
$computedIdentifier = [];
// TRICKY: since the association is specular source and target are flipped
foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) {
if (! isset($sourceClass->fieldNames[$sourceKeyColumn])) {
throw MappingException::joinColumnMustPointToMappedField(
$sourceClass->name,
$sourceKeyColumn
);
}
$computedIdentifier[$targetClass->getFieldForColumn($targetKeyColumn)] =
$sourceClass->reflFields[$sourceClass->fieldNames[$sourceKeyColumn]]->getValue($sourceEntity);
}
$targetEntity = $this->load($computedIdentifier, null, $assoc);
if ($targetEntity !== null) {
$targetClass->setFieldValue($targetEntity, $assoc['mappedBy'], $sourceEntity);
}
return $targetEntity;
}
/**
* {@inheritdoc}
*/
public function refresh(array $id, object $entity, LockMode|int|null $lockMode = null): void
{
$sql = $this->getSelectSQL($id, null, $lockMode);
[$params, $types] = $this->expandParameters($id);
$stmt = $this->conn->executeQuery($sql, $params, $types);
$hydrator = $this->em->newHydrator(Query::HYDRATE_OBJECT);
$hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, [Query::HINT_REFRESH => true]);
}
public function count(array|Criteria $criteria = []): int
{
$sql = $this->getCountSQL($criteria);
[$params, $types] = $criteria instanceof Criteria
? $this->expandCriteriaParameters($criteria)
: $this->expandParameters($criteria);
return (int) $this->conn->executeQuery($sql, $params, $types)->fetchOne();
}
/**
* {@inheritdoc}
*/
public function loadCriteria(Criteria $criteria): array
{
$orderBy = $criteria->getOrderings();
$limit = $criteria->getMaxResults();
$offset = $criteria->getFirstResult();
$query = $this->getSelectSQL($criteria, null, null, $limit, $offset, $orderBy);
[$params, $types] = $this->expandCriteriaParameters($criteria);
$stmt = $this->conn->executeQuery($query, $params, $types);
$hydrator = $this->em->newHydrator($this->currentPersisterContext->selectJoinSql ? Query::HYDRATE_OBJECT : Query::HYDRATE_SIMPLEOBJECT);
return $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true]);
}
/**
* {@inheritdoc}
*/
public function expandCriteriaParameters(Criteria $criteria): array
{
$expression = $criteria->getWhereExpression();
$sqlParams = [];
$sqlTypes = [];
if ($expression === null) {
return [$sqlParams, $sqlTypes];
}
$valueVisitor = new SqlValueVisitor();
$valueVisitor->dispatch($expression);
[$params, $types] = $valueVisitor->getParamsAndTypes();
foreach ($params as $param) {
$sqlParams = array_merge($sqlParams, $this->getValues($param));
}
foreach ($types as $type) {
[$field, $value] = $type;
$sqlTypes = array_merge($sqlTypes, $this->getTypes($field, $value, $this->class));
}
return [$sqlParams, $sqlTypes];
}
/**
* {@inheritdoc}
*/
public function loadAll(
array $criteria = [],
?array $orderBy = null,
?int $limit = null,
?int $offset = null
): array {
$this->switchPersisterContext($offset, $limit);
$sql = $this->getSelectSQL($criteria, null, null, $limit, $offset, $orderBy);
[$params, $types] = $this->expandParameters($criteria);
$stmt = $this->conn->executeQuery($sql, $params, $types);
$hydrator = $this->em->newHydrator($this->currentPersisterContext->selectJoinSql ? Query::HYDRATE_OBJECT : Query::HYDRATE_SIMPLEOBJECT);
return $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true]);
}
/**
* {@inheritdoc}
*/
public function getManyToManyCollection(
array $assoc,
object $sourceEntity,
?int $offset = null,
?int $limit = null
): array {
$this->switchPersisterContext($offset, $limit);
$stmt = $this->getManyToManyStatement($assoc, $sourceEntity, $offset, $limit);
return $this->loadArrayFromResult($assoc, $stmt);
}
/**
* Loads an array of entities from a given DBAL statement.
*
* @param mixed[] $assoc
*
* @return mixed[]
*/
private function loadArrayFromResult(array $assoc, Result $stmt): array
{
$rsm = $this->currentPersisterContext->rsm;
$hints = [UnitOfWork::HINT_DEFEREAGERLOAD => true];
if (isset($assoc['indexBy'])) {
$rsm = clone $this->currentPersisterContext->rsm; // this is necessary because the "default rsm" should be changed.
$rsm->addIndexBy('r', $assoc['indexBy']);
}
return $this->em->newHydrator(Query::HYDRATE_OBJECT)->hydrateAll($stmt, $rsm, $hints);
}
/**
* Hydrates a collection from a given DBAL statement.
*
* @param mixed[] $assoc
*
* @return mixed[]
*/
private function loadCollectionFromStatement(
array $assoc,
Result $stmt,
PersistentCollection $coll
): array {
$rsm = $this->currentPersisterContext->rsm;
$hints = [
UnitOfWork::HINT_DEFEREAGERLOAD => true,
'collection' => $coll,
];
if (isset($assoc['indexBy'])) {
$rsm = clone $this->currentPersisterContext->rsm; // this is necessary because the "default rsm" should be changed.
$rsm->addIndexBy('r', $assoc['indexBy']);
}
return $this->em->newHydrator(Query::HYDRATE_OBJECT)->hydrateAll($stmt, $rsm, $hints);
}
/**
* {@inheritdoc}
*/
public function loadManyToManyCollection(array $assoc, object $sourceEntity, PersistentCollection $collection): array
{
$stmt = $this->getManyToManyStatement($assoc, $sourceEntity);
return $this->loadCollectionFromStatement($assoc, $stmt, $collection);
}
/**
* @psalm-param array<string, mixed> $assoc
*
* @throws MappingException
*/
private function getManyToManyStatement(
array $assoc,
object $sourceEntity,
?int $offset = null,
?int $limit = null
): Result {
$this->switchPersisterContext($offset, $limit);
$sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']);
$class = $sourceClass;
$association = $assoc;
$criteria = [];
$parameters = [];
if (! $assoc['isOwningSide']) {
$class = $this->em->getClassMetadata($assoc['targetEntity']);
$association = $class->associationMappings[$assoc['mappedBy']];
}
$joinColumns = $assoc['isOwningSide']
? $association['joinTable']['joinColumns']
: $association['joinTable']['inverseJoinColumns'];
$quotedJoinTable = $this->quoteStrategy->getJoinTableName($association, $class, $this->platform);
foreach ($joinColumns as $joinColumn) {
$sourceKeyColumn = $joinColumn['referencedColumnName'];
$quotedKeyColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
switch (true) {
case $sourceClass->containsForeignIdentifier:
$field = $sourceClass->getFieldForColumn($sourceKeyColumn);
$value = $sourceClass->reflFields[$field]->getValue($sourceEntity);
if (isset($sourceClass->associationMappings[$field])) {
$value = $this->em->getUnitOfWork()->getEntityIdentifier($value);
$value = $value[$this->em->getClassMetadata($sourceClass->associationMappings[$field]['targetEntity'])->identifier[0]];
}
break;
case isset($sourceClass->fieldNames[$sourceKeyColumn]):
$field = $sourceClass->fieldNames[$sourceKeyColumn];