vendor/doctrine/orm/src/Persisters/Entity/BasicEntityPersister.php line 1126

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\ORM\Persisters\Entity;
  4. use BackedEnum;
  5. use Doctrine\Common\Collections\Criteria;
  6. use Doctrine\Common\Collections\Expr\Comparison;
  7. use Doctrine\DBAL\Connection;
  8. use Doctrine\DBAL\LockMode;
  9. use Doctrine\DBAL\Platforms\AbstractPlatform;
  10. use Doctrine\DBAL\Result;
  11. use Doctrine\DBAL\Types\Type;
  12. use Doctrine\DBAL\Types\Types;
  13. use Doctrine\Deprecations\Deprecation;
  14. use Doctrine\ORM\EntityManagerInterface;
  15. use Doctrine\ORM\Internal\CriteriaOrderings;
  16. use Doctrine\ORM\Mapping\ClassMetadata;
  17. use Doctrine\ORM\Mapping\MappingException;
  18. use Doctrine\ORM\Mapping\QuoteStrategy;
  19. use Doctrine\ORM\OptimisticLockException;
  20. use Doctrine\ORM\PersistentCollection;
  21. use Doctrine\ORM\Persisters\Exception\CantUseInOperatorOnCompositeKeys;
  22. use Doctrine\ORM\Persisters\Exception\InvalidOrientation;
  23. use Doctrine\ORM\Persisters\Exception\UnrecognizedField;
  24. use Doctrine\ORM\Persisters\SqlExpressionVisitor;
  25. use Doctrine\ORM\Persisters\SqlValueVisitor;
  26. use Doctrine\ORM\Proxy\DefaultProxyClassNameResolver;
  27. use Doctrine\ORM\Query;
  28. use Doctrine\ORM\Query\QueryException;
  29. use Doctrine\ORM\Repository\Exception\InvalidFindByCall;
  30. use Doctrine\ORM\UnitOfWork;
  31. use Doctrine\ORM\Utility\IdentifierFlattener;
  32. use Doctrine\ORM\Utility\LockSqlHelper;
  33. use Doctrine\ORM\Utility\PersisterHelper;
  34. use LengthException;
  35. use function array_combine;
  36. use function array_keys;
  37. use function array_map;
  38. use function array_merge;
  39. use function array_search;
  40. use function array_unique;
  41. use function array_values;
  42. use function assert;
  43. use function count;
  44. use function implode;
  45. use function is_array;
  46. use function is_object;
  47. use function reset;
  48. use function spl_object_id;
  49. use function sprintf;
  50. use function str_contains;
  51. use function strtoupper;
  52. use function trim;
  53. /**
  54. * A BasicEntityPersister maps an entity to a single table in a relational database.
  55. *
  56. * A persister is always responsible for a single entity type.
  57. *
  58. * EntityPersisters are used during a UnitOfWork to apply any changes to the persistent
  59. * state of entities onto a relational database when the UnitOfWork is committed,
  60. * as well as for basic querying of entities and their associations (not DQL).
  61. *
  62. * The persisting operations that are invoked during a commit of a UnitOfWork to
  63. * persist the persistent entity state are:
  64. *
  65. * - {@link addInsert} : To schedule an entity for insertion.
  66. * - {@link executeInserts} : To execute all scheduled insertions.
  67. * - {@link update} : To update the persistent state of an entity.
  68. * - {@link delete} : To delete the persistent state of an entity.
  69. *
  70. * As can be seen from the above list, insertions are batched and executed all at once
  71. * for increased efficiency.
  72. *
  73. * The querying operations invoked during a UnitOfWork, either through direct find
  74. * requests or lazy-loading, are the following:
  75. *
  76. * - {@link load} : Loads (the state of) a single, managed entity.
  77. * - {@link loadAll} : Loads multiple, managed entities.
  78. * - {@link loadOneToOneEntity} : Loads a one/many-to-one entity association (lazy-loading).
  79. * - {@link loadOneToManyCollection} : Loads a one-to-many entity association (lazy-loading).
  80. * - {@link loadManyToManyCollection} : Loads a many-to-many entity association (lazy-loading).
  81. *
  82. * The BasicEntityPersister implementation provides the default behavior for
  83. * persisting and querying entities that are mapped to a single database table.
  84. *
  85. * Subclasses can be created to provide custom persisting and querying strategies,
  86. * i.e. spanning multiple tables.
  87. *
  88. * @phpstan-import-type AssociationMapping from ClassMetadata
  89. */
  90. class BasicEntityPersister implements EntityPersister
  91. {
  92. use CriteriaOrderings;
  93. use LockSqlHelper;
  94. /** @var array<string,string> */
  95. private static $comparisonMap = [
  96. Comparison::EQ => '= %s',
  97. Comparison::NEQ => '!= %s',
  98. Comparison::GT => '> %s',
  99. Comparison::GTE => '>= %s',
  100. Comparison::LT => '< %s',
  101. Comparison::LTE => '<= %s',
  102. Comparison::IN => 'IN (%s)',
  103. Comparison::NIN => 'NOT IN (%s)',
  104. Comparison::CONTAINS => 'LIKE %s',
  105. Comparison::STARTS_WITH => 'LIKE %s',
  106. Comparison::ENDS_WITH => 'LIKE %s',
  107. ];
  108. /**
  109. * Metadata object that describes the mapping of the mapped entity class.
  110. *
  111. * @var ClassMetadata
  112. */
  113. protected $class;
  114. /**
  115. * The underlying DBAL Connection of the used EntityManager.
  116. *
  117. * @var Connection $conn
  118. */
  119. protected $conn;
  120. /**
  121. * The database platform.
  122. *
  123. * @var AbstractPlatform
  124. */
  125. protected $platform;
  126. /**
  127. * The EntityManager instance.
  128. *
  129. * @var EntityManagerInterface
  130. */
  131. protected $em;
  132. /**
  133. * Queued inserts.
  134. *
  135. * @phpstan-var array<int, object>
  136. */
  137. protected $queuedInserts = [];
  138. /**
  139. * The map of column names to DBAL mapping types of all prepared columns used
  140. * when INSERTing or UPDATEing an entity.
  141. *
  142. * @see prepareInsertData($entity)
  143. * @see prepareUpdateData($entity)
  144. *
  145. * @var mixed[]
  146. */
  147. protected $columnTypes = [];
  148. /**
  149. * The map of quoted column names.
  150. *
  151. * @see prepareInsertData($entity)
  152. * @see prepareUpdateData($entity)
  153. *
  154. * @var mixed[]
  155. */
  156. protected $quotedColumns = [];
  157. /**
  158. * The INSERT SQL statement used for entities handled by this persister.
  159. * This SQL is only generated once per request, if at all.
  160. *
  161. * @var string|null
  162. */
  163. private $insertSql;
  164. /**
  165. * The quote strategy.
  166. *
  167. * @var QuoteStrategy
  168. */
  169. protected $quoteStrategy;
  170. /**
  171. * The IdentifierFlattener used for manipulating identifiers
  172. *
  173. * @var IdentifierFlattener
  174. */
  175. protected $identifierFlattener;
  176. /** @var CachedPersisterContext */
  177. protected $currentPersisterContext;
  178. /** @var CachedPersisterContext */
  179. private $limitsHandlingContext;
  180. /** @var CachedPersisterContext */
  181. private $noLimitsContext;
  182. /** @var ?string */
  183. private $filterHash = null;
  184. /**
  185. * Initializes a new <tt>BasicEntityPersister</tt> that uses the given EntityManager
  186. * and persists instances of the class described by the given ClassMetadata descriptor.
  187. */
  188. public function __construct(EntityManagerInterface $em, ClassMetadata $class)
  189. {
  190. $this->em = $em;
  191. $this->class = $class;
  192. $this->conn = $em->getConnection();
  193. $this->platform = $this->conn->getDatabasePlatform();
  194. $this->quoteStrategy = $em->getConfiguration()->getQuoteStrategy();
  195. $this->identifierFlattener = new IdentifierFlattener($em->getUnitOfWork(), $em->getMetadataFactory());
  196. $this->noLimitsContext = $this->currentPersisterContext = new CachedPersisterContext(
  197. $class,
  198. new Query\ResultSetMapping(),
  199. false
  200. );
  201. $this->limitsHandlingContext = new CachedPersisterContext(
  202. $class,
  203. new Query\ResultSetMapping(),
  204. true
  205. );
  206. }
  207. /**
  208. * {@inheritDoc}
  209. */
  210. public function getClassMetadata()
  211. {
  212. return $this->class;
  213. }
  214. /**
  215. * {@inheritDoc}
  216. */
  217. public function getResultSetMapping()
  218. {
  219. return $this->currentPersisterContext->rsm;
  220. }
  221. /**
  222. * {@inheritDoc}
  223. */
  224. public function addInsert($entity)
  225. {
  226. $this->queuedInserts[spl_object_id($entity)] = $entity;
  227. }
  228. /**
  229. * {@inheritDoc}
  230. */
  231. public function getInserts()
  232. {
  233. return $this->queuedInserts;
  234. }
  235. /**
  236. * {@inheritDoc}
  237. */
  238. public function executeInserts()
  239. {
  240. if (! $this->queuedInserts) {
  241. return;
  242. }
  243. $uow = $this->em->getUnitOfWork();
  244. $idGenerator = $this->class->idGenerator;
  245. $isPostInsertId = $idGenerator->isPostInsertGenerator();
  246. $stmt = $this->conn->prepare($this->getInsertSQL());
  247. $tableName = $this->class->getTableName();
  248. foreach ($this->queuedInserts as $key => $entity) {
  249. $insertData = $this->prepareInsertData($entity);
  250. if (isset($insertData[$tableName])) {
  251. $paramIndex = 1;
  252. foreach ($insertData[$tableName] as $column => $value) {
  253. $stmt->bindValue($paramIndex++, $value, $this->columnTypes[$column]);
  254. }
  255. }
  256. $stmt->executeStatement();
  257. if ($isPostInsertId) {
  258. $generatedId = $idGenerator->generateId($this->em, $entity);
  259. $id = [$this->class->identifier[0] => $generatedId];
  260. $uow->assignPostInsertId($entity, $generatedId);
  261. } else {
  262. $id = $this->class->getIdentifierValues($entity);
  263. }
  264. if ($this->class->requiresFetchAfterChange) {
  265. $this->assignDefaultVersionAndUpsertableValues($entity, $id);
  266. }
  267. // Unset this queued insert, so that the prepareUpdateData() method knows right away
  268. // (for the next entity already) that the current entity has been written to the database
  269. // and no extra updates need to be scheduled to refer to it.
  270. //
  271. // In \Doctrine\ORM\UnitOfWork::executeInserts(), the UoW already removed entities
  272. // from its own list (\Doctrine\ORM\UnitOfWork::$entityInsertions) right after they
  273. // were given to our addInsert() method.
  274. unset($this->queuedInserts[$key]);
  275. }
  276. }
  277. /**
  278. * Retrieves the default version value which was created
  279. * by the preceding INSERT statement and assigns it back in to the
  280. * entities version field if the given entity is versioned.
  281. * Also retrieves values of columns marked as 'non insertable' and / or
  282. * 'not updatable' and assigns them back to the entities corresponding fields.
  283. *
  284. * @param object $entity
  285. * @param mixed[] $id
  286. *
  287. * @return void
  288. */
  289. protected function assignDefaultVersionAndUpsertableValues($entity, array $id)
  290. {
  291. $values = $this->fetchVersionAndNotUpsertableValues($this->class, $id);
  292. foreach ($values as $field => $value) {
  293. $value = Type::getType($this->class->fieldMappings[$field]['type'])->convertToPHPValue($value, $this->platform);
  294. $this->class->setFieldValue($entity, $field, $value);
  295. }
  296. }
  297. /**
  298. * Fetches the current version value of a versioned entity and / or the values of fields
  299. * marked as 'not insertable' and / or 'not updatable'.
  300. *
  301. * @param ClassMetadata $versionedClass
  302. * @param mixed[] $id
  303. *
  304. * @return mixed
  305. */
  306. protected function fetchVersionAndNotUpsertableValues($versionedClass, array $id)
  307. {
  308. $columnNames = [];
  309. foreach ($this->class->fieldMappings as $key => $column) {
  310. if (isset($column['generated']) || ($this->class->isVersioned && $key === $versionedClass->versionField)) {
  311. $columnNames[$key] = $this->quoteStrategy->getColumnName($key, $versionedClass, $this->platform);
  312. }
  313. }
  314. $tableName = $this->quoteStrategy->getTableName($versionedClass, $this->platform);
  315. $identifier = $this->quoteStrategy->getIdentifierColumnNames($versionedClass, $this->platform);
  316. // FIXME: Order with composite keys might not be correct
  317. $sql = 'SELECT ' . implode(', ', $columnNames)
  318. . ' FROM ' . $tableName
  319. . ' WHERE ' . implode(' = ? AND ', $identifier) . ' = ?';
  320. $flatId = $this->identifierFlattener->flattenIdentifier($versionedClass, $id);
  321. $values = $this->conn->fetchNumeric(
  322. $sql,
  323. array_values($flatId),
  324. $this->extractIdentifierTypes($id, $versionedClass)
  325. );
  326. if ($values === false) {
  327. throw new LengthException('Unexpected empty result for database query.');
  328. }
  329. $values = array_combine(array_keys($columnNames), $values);
  330. if (! $values) {
  331. throw new LengthException('Unexpected number of database columns.');
  332. }
  333. return $values;
  334. }
  335. /**
  336. * @param mixed[] $id
  337. *
  338. * @return int[]|null[]|string[]
  339. * @phpstan-return list<int|string|null>
  340. */
  341. final protected function extractIdentifierTypes(array $id, ClassMetadata $versionedClass): array
  342. {
  343. $types = [];
  344. foreach ($id as $field => $value) {
  345. $types = array_merge($types, $this->getTypes($field, $value, $versionedClass));
  346. }
  347. return $types;
  348. }
  349. /**
  350. * {@inheritDoc}
  351. */
  352. public function update($entity)
  353. {
  354. $tableName = $this->class->getTableName();
  355. $updateData = $this->prepareUpdateData($entity);
  356. if (! isset($updateData[$tableName])) {
  357. return;
  358. }
  359. $data = $updateData[$tableName];
  360. if (! $data) {
  361. return;
  362. }
  363. $isVersioned = $this->class->isVersioned;
  364. $quotedTableName = $this->quoteStrategy->getTableName($this->class, $this->platform);
  365. $this->updateTable($entity, $quotedTableName, $data, $isVersioned);
  366. if ($this->class->requiresFetchAfterChange) {
  367. $id = $this->class->getIdentifierValues($entity);
  368. $this->assignDefaultVersionAndUpsertableValues($entity, $id);
  369. }
  370. }
  371. /**
  372. * Performs an UPDATE statement for an entity on a specific table.
  373. * The UPDATE can optionally be versioned, which requires the entity to have a version field.
  374. *
  375. * @param object $entity The entity object being updated.
  376. * @param string $quotedTableName The quoted name of the table to apply the UPDATE on.
  377. * @param mixed[] $updateData The map of columns to update (column => value).
  378. * @param bool $versioned Whether the UPDATE should be versioned.
  379. *
  380. * @throws UnrecognizedField
  381. * @throws OptimisticLockException
  382. */
  383. final protected function updateTable(
  384. $entity,
  385. $quotedTableName,
  386. array $updateData,
  387. $versioned = false
  388. ): void {
  389. $set = [];
  390. $types = [];
  391. $params = [];
  392. foreach ($updateData as $columnName => $value) {
  393. $placeholder = '?';
  394. $column = $columnName;
  395. switch (true) {
  396. case isset($this->class->fieldNames[$columnName]):
  397. $fieldName = $this->class->fieldNames[$columnName];
  398. $column = $this->quoteStrategy->getColumnName($fieldName, $this->class, $this->platform);
  399. if (isset($this->class->fieldMappings[$fieldName]['requireSQLConversion'])) {
  400. $type = Type::getType($this->columnTypes[$columnName]);
  401. $placeholder = $type->convertToDatabaseValueSQL('?', $this->platform);
  402. }
  403. break;
  404. case isset($this->quotedColumns[$columnName]):
  405. $column = $this->quotedColumns[$columnName];
  406. break;
  407. }
  408. $params[] = $value;
  409. $set[] = $column . ' = ' . $placeholder;
  410. $types[] = $this->columnTypes[$columnName];
  411. }
  412. $where = [];
  413. $identifier = $this->em->getUnitOfWork()->getEntityIdentifier($entity);
  414. foreach ($this->class->identifier as $idField) {
  415. if (! isset($this->class->associationMappings[$idField])) {
  416. $params[] = $identifier[$idField];
  417. $types[] = $this->class->fieldMappings[$idField]['type'];
  418. $where[] = $this->quoteStrategy->getColumnName($idField, $this->class, $this->platform);
  419. continue;
  420. }
  421. $params[] = $identifier[$idField];
  422. $where[] = $this->quoteStrategy->getJoinColumnName(
  423. $this->class->associationMappings[$idField]['joinColumns'][0],
  424. $this->class,
  425. $this->platform
  426. );
  427. $targetMapping = $this->em->getClassMetadata($this->class->associationMappings[$idField]['targetEntity']);
  428. $targetType = PersisterHelper::getTypeOfField($targetMapping->identifier[0], $targetMapping, $this->em);
  429. if ($targetType === []) {
  430. throw UnrecognizedField::byFullyQualifiedName($this->class->name, $targetMapping->identifier[0]);
  431. }
  432. $types[] = reset($targetType);
  433. }
  434. if ($versioned) {
  435. $versionField = $this->class->versionField;
  436. assert($versionField !== null);
  437. $versionFieldType = $this->class->fieldMappings[$versionField]['type'];
  438. $versionColumn = $this->quoteStrategy->getColumnName($versionField, $this->class, $this->platform);
  439. $where[] = $versionColumn;
  440. $types[] = $this->class->fieldMappings[$versionField]['type'];
  441. $params[] = $this->class->reflFields[$versionField]->getValue($entity);
  442. switch ($versionFieldType) {
  443. case Types::SMALLINT:
  444. case Types::INTEGER:
  445. case Types::BIGINT:
  446. $set[] = $versionColumn . ' = ' . $versionColumn . ' + 1';
  447. break;
  448. case Types::DATETIME_MUTABLE:
  449. $set[] = $versionColumn . ' = CURRENT_TIMESTAMP';
  450. break;
  451. }
  452. }
  453. $sql = 'UPDATE ' . $quotedTableName
  454. . ' SET ' . implode(', ', $set)
  455. . ' WHERE ' . implode(' = ? AND ', $where) . ' = ?';
  456. $result = $this->conn->executeStatement($sql, $params, $types);
  457. if ($versioned && ! $result) {
  458. throw OptimisticLockException::lockFailed($entity);
  459. }
  460. }
  461. /**
  462. * @param array<mixed> $identifier
  463. * @param string[] $types
  464. *
  465. * @todo Add check for platform if it supports foreign keys/cascading.
  466. */
  467. protected function deleteJoinTableRecords(array $identifier, array $types): void
  468. {
  469. foreach ($this->class->associationMappings as $mapping) {
  470. if ($mapping['type'] !== ClassMetadata::MANY_TO_MANY || isset($mapping['isOnDeleteCascade'])) {
  471. continue;
  472. }
  473. // @Todo this only covers scenarios with no inheritance or of the same level. Is there something
  474. // like self-referential relationship between different levels of an inheritance hierarchy? I hope not!
  475. $selfReferential = ($mapping['targetEntity'] === $mapping['sourceEntity']);
  476. $class = $this->class;
  477. $association = $mapping;
  478. $otherColumns = [];
  479. $otherKeys = [];
  480. $keys = [];
  481. if (! $mapping['isOwningSide']) {
  482. $class = $this->em->getClassMetadata($mapping['targetEntity']);
  483. $association = $class->associationMappings[$mapping['mappedBy']];
  484. }
  485. $joinColumns = $mapping['isOwningSide']
  486. ? $association['joinTable']['joinColumns']
  487. : $association['joinTable']['inverseJoinColumns'];
  488. if ($selfReferential) {
  489. $otherColumns = ! $mapping['isOwningSide']
  490. ? $association['joinTable']['joinColumns']
  491. : $association['joinTable']['inverseJoinColumns'];
  492. }
  493. foreach ($joinColumns as $joinColumn) {
  494. $keys[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
  495. }
  496. foreach ($otherColumns as $joinColumn) {
  497. $otherKeys[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
  498. }
  499. $joinTableName = $this->quoteStrategy->getJoinTableName($association, $this->class, $this->platform);
  500. $this->conn->delete($joinTableName, array_combine($keys, $identifier), $types);
  501. if ($selfReferential) {
  502. $this->conn->delete($joinTableName, array_combine($otherKeys, $identifier), $types);
  503. }
  504. }
  505. }
  506. /**
  507. * {@inheritDoc}
  508. */
  509. public function delete($entity)
  510. {
  511. $class = $this->class;
  512. $identifier = $this->em->getUnitOfWork()->getEntityIdentifier($entity);
  513. $tableName = $this->quoteStrategy->getTableName($class, $this->platform);
  514. $idColumns = $this->quoteStrategy->getIdentifierColumnNames($class, $this->platform);
  515. $id = array_combine($idColumns, $identifier);
  516. $types = $this->getClassIdentifiersTypes($class);
  517. $this->deleteJoinTableRecords($identifier, $types);
  518. return (bool) $this->conn->delete($tableName, $id, $types);
  519. }
  520. /**
  521. * Prepares the changeset of an entity for database insertion (UPDATE).
  522. *
  523. * The changeset is obtained from the currently running UnitOfWork.
  524. *
  525. * During this preparation the array that is passed as the second parameter is filled with
  526. * <columnName> => <value> pairs, grouped by table name.
  527. *
  528. * Example:
  529. * <code>
  530. * array(
  531. * 'foo_table' => array('column1' => 'value1', 'column2' => 'value2', ...),
  532. * 'bar_table' => array('columnX' => 'valueX', 'columnY' => 'valueY', ...),
  533. * ...
  534. * )
  535. * </code>
  536. *
  537. * @param object $entity The entity for which to prepare the data.
  538. * @param bool $isInsert Whether the data to be prepared refers to an insert statement.
  539. *
  540. * @return mixed[][] The prepared data.
  541. * @phpstan-return array<string, array<array-key, mixed|null>>
  542. */
  543. protected function prepareUpdateData($entity, bool $isInsert = false)
  544. {
  545. $versionField = null;
  546. $result = [];
  547. $uow = $this->em->getUnitOfWork();
  548. $versioned = $this->class->isVersioned;
  549. if ($versioned !== false) {
  550. $versionField = $this->class->versionField;
  551. }
  552. foreach ($uow->getEntityChangeSet($entity) as $field => $change) {
  553. if (isset($versionField) && $versionField === $field) {
  554. continue;
  555. }
  556. if (isset($this->class->embeddedClasses[$field])) {
  557. continue;
  558. }
  559. $newVal = $change[1];
  560. if (! isset($this->class->associationMappings[$field])) {
  561. $fieldMapping = $this->class->fieldMappings[$field];
  562. $columnName = $fieldMapping['columnName'];
  563. if (! $isInsert && isset($fieldMapping['notUpdatable'])) {
  564. continue;
  565. }
  566. if ($isInsert && isset($fieldMapping['notInsertable'])) {
  567. continue;
  568. }
  569. $this->columnTypes[$columnName] = $fieldMapping['type'];
  570. $result[$this->getOwningTable($field)][$columnName] = $newVal;
  571. continue;
  572. }
  573. $assoc = $this->class->associationMappings[$field];
  574. // Only owning side of x-1 associations can have a FK column.
  575. if (! $assoc['isOwningSide'] || ! ($assoc['type'] & ClassMetadata::TO_ONE)) {
  576. continue;
  577. }
  578. if ($newVal !== null) {
  579. $oid = spl_object_id($newVal);
  580. // If the associated entity $newVal is not yet persisted and/or does not yet have
  581. // an ID assigned, we must set $newVal = null. This will insert a null value and
  582. // schedule an extra update on the UnitOfWork.
  583. //
  584. // This gives us extra time to a) possibly obtain a database-generated identifier
  585. // value for $newVal, and b) insert $newVal into the database before the foreign
  586. // key reference is being made.
  587. //
  588. // When looking at $this->queuedInserts and $uow->isScheduledForInsert, be aware
  589. // of the implementation details that our own executeInserts() method will remove
  590. // entities from the former as soon as the insert statement has been executed and
  591. // a post-insert ID has been assigned (if necessary), and that the UnitOfWork has
  592. // already removed entities from its own list at the time they were passed to our
  593. // addInsert() method.
  594. //
  595. // Then, there is one extra exception we can make: An entity that references back to itself
  596. // _and_ uses an application-provided ID (the "NONE" generator strategy) also does not
  597. // need the extra update, although it is still in the list of insertions itself.
  598. // This looks like a minor optimization at first, but is the capstone for being able to
  599. // use non-NULLable, self-referencing associations in applications that provide IDs (like UUIDs).
  600. if (
  601. (isset($this->queuedInserts[$oid]) || $uow->isScheduledForInsert($newVal))
  602. && ! ($newVal === $entity && $this->class->isIdentifierNatural())
  603. ) {
  604. $uow->scheduleExtraUpdate($entity, [$field => [null, $newVal]]);
  605. $newVal = null;
  606. }
  607. }
  608. $newValId = null;
  609. if ($newVal !== null) {
  610. $newValId = $uow->getEntityIdentifier($newVal);
  611. }
  612. $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
  613. $owningTable = $this->getOwningTable($field);
  614. foreach ($assoc['joinColumns'] as $joinColumn) {
  615. $sourceColumn = $joinColumn['name'];
  616. $targetColumn = $joinColumn['referencedColumnName'];
  617. $quotedColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform);
  618. $this->quotedColumns[$sourceColumn] = $quotedColumn;
  619. $this->columnTypes[$sourceColumn] = PersisterHelper::getTypeOfColumn($targetColumn, $targetClass, $this->em);
  620. $result[$owningTable][$sourceColumn] = $newValId
  621. ? $newValId[$targetClass->getFieldForColumn($targetColumn)]
  622. : null;
  623. }
  624. }
  625. return $result;
  626. }
  627. /**
  628. * Prepares the data changeset of a managed entity for database insertion (initial INSERT).
  629. * The changeset of the entity is obtained from the currently running UnitOfWork.
  630. *
  631. * The default insert data preparation is the same as for updates.
  632. *
  633. * @see prepareUpdateData
  634. *
  635. * @param object $entity The entity for which to prepare the data.
  636. *
  637. * @return mixed[][] The prepared data for the tables to update.
  638. * @phpstan-return array<string, mixed[]>
  639. */
  640. protected function prepareInsertData($entity)
  641. {
  642. return $this->prepareUpdateData($entity, true);
  643. }
  644. /**
  645. * {@inheritDoc}
  646. */
  647. public function getOwningTable($fieldName)
  648. {
  649. return $this->class->getTableName();
  650. }
  651. /**
  652. * {@inheritDoc}
  653. */
  654. public function load(array $criteria, $entity = null, $assoc = null, array $hints = [], $lockMode = null, $limit = null, ?array $orderBy = null)
  655. {
  656. $this->switchPersisterContext(null, $limit);
  657. $sql = $this->getSelectSQL($criteria, $assoc, $lockMode, $limit, null, $orderBy);
  658. [$params, $types] = $this->expandParameters($criteria);
  659. $stmt = $this->conn->executeQuery($sql, $params, $types);
  660. if ($entity !== null) {
  661. $hints[Query::HINT_REFRESH] = true;
  662. $hints[Query::HINT_REFRESH_ENTITY] = $entity;
  663. }
  664. $hydrator = $this->em->newHydrator($this->currentPersisterContext->selectJoinSql ? Query::HYDRATE_OBJECT : Query::HYDRATE_SIMPLEOBJECT);
  665. $entities = $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, $hints);
  666. return $entities ? $entities[0] : null;
  667. }
  668. /**
  669. * {@inheritDoc}
  670. */
  671. public function loadById(array $identifier, $entity = null)
  672. {
  673. return $this->load($identifier, $entity);
  674. }
  675. /**
  676. * {@inheritDoc}
  677. */
  678. public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifier = [])
  679. {
  680. $foundEntity = $this->em->getUnitOfWork()->tryGetById($identifier, $assoc['targetEntity']);
  681. if ($foundEntity !== false) {
  682. return $foundEntity;
  683. }
  684. $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
  685. if ($assoc['isOwningSide']) {
  686. $isInverseSingleValued = $assoc['inversedBy'] && ! $targetClass->isCollectionValuedAssociation($assoc['inversedBy']);
  687. // Mark inverse side as fetched in the hints, otherwise the UoW would
  688. // try to load it in a separate query (remember: to-one inverse sides can not be lazy).
  689. $hints = [];
  690. if ($isInverseSingleValued) {
  691. $hints['fetched']['r'][$assoc['inversedBy']] = true;
  692. }
  693. $targetEntity = $this->load($identifier, null, $assoc, $hints);
  694. // Complete bidirectional association, if necessary
  695. if ($targetEntity !== null && $isInverseSingleValued) {
  696. $targetClass->reflFields[$assoc['inversedBy']]->setValue($targetEntity, $sourceEntity);
  697. }
  698. return $targetEntity;
  699. }
  700. $sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']);
  701. $owningAssoc = $targetClass->getAssociationMapping($assoc['mappedBy']);
  702. $computedIdentifier = [];
  703. /** @var array<string,mixed>|null $sourceEntityData */
  704. $sourceEntityData = null;
  705. // TRICKY: since the association is specular source and target are flipped
  706. foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) {
  707. if (! isset($sourceClass->fieldNames[$sourceKeyColumn])) {
  708. // The likely case here is that the column is a join column
  709. // in an association mapping. However, there is no guarantee
  710. // at this point that a corresponding (generally identifying)
  711. // association has been mapped in the source entity. To handle
  712. // this case we directly reference the column-keyed data used
  713. // to initialize the source entity before throwing an exception.
  714. $resolvedSourceData = false;
  715. if (! isset($sourceEntityData)) {
  716. $sourceEntityData = $this->em->getUnitOfWork()->getOriginalEntityData($sourceEntity);
  717. }
  718. if (isset($sourceEntityData[$sourceKeyColumn])) {
  719. $dataValue = $sourceEntityData[$sourceKeyColumn];
  720. if ($dataValue !== null) {
  721. $resolvedSourceData = true;
  722. $computedIdentifier[$targetClass->getFieldForColumn($targetKeyColumn)] =
  723. $dataValue;
  724. }
  725. }
  726. if (! $resolvedSourceData) {
  727. throw MappingException::joinColumnMustPointToMappedField(
  728. $sourceClass->name,
  729. $sourceKeyColumn
  730. );
  731. }
  732. } else {
  733. $computedIdentifier[$targetClass->getFieldForColumn($targetKeyColumn)] =
  734. $sourceClass->reflFields[$sourceClass->fieldNames[$sourceKeyColumn]]->getValue($sourceEntity);
  735. }
  736. }
  737. $targetEntity = $this->load($computedIdentifier, null, $assoc);
  738. if ($targetEntity !== null) {
  739. $targetClass->setFieldValue($targetEntity, $assoc['mappedBy'], $sourceEntity);
  740. }
  741. return $targetEntity;
  742. }
  743. /**
  744. * {@inheritDoc}
  745. */
  746. public function refresh(array $id, $entity, $lockMode = null)
  747. {
  748. $sql = $this->getSelectSQL($id, null, $lockMode);
  749. [$params, $types] = $this->expandParameters($id);
  750. $stmt = $this->conn->executeQuery($sql, $params, $types);
  751. $hydrator = $this->em->newHydrator(Query::HYDRATE_OBJECT);
  752. $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, [Query::HINT_REFRESH => true]);
  753. }
  754. /**
  755. * {@inheritDoc}
  756. */
  757. public function count($criteria = [])
  758. {
  759. $sql = $this->getCountSQL($criteria);
  760. [$params, $types] = $criteria instanceof Criteria
  761. ? $this->expandCriteriaParameters($criteria)
  762. : $this->expandParameters($criteria);
  763. return (int) $this->conn->executeQuery($sql, $params, $types)->fetchOne();
  764. }
  765. /**
  766. * {@inheritDoc}
  767. */
  768. public function loadCriteria(Criteria $criteria)
  769. {
  770. $orderBy = self::getCriteriaOrderings($criteria);
  771. $limit = $criteria->getMaxResults();
  772. $offset = $criteria->getFirstResult();
  773. $query = $this->getSelectSQL($criteria, null, null, $limit, $offset, $orderBy);
  774. [$params, $types] = $this->expandCriteriaParameters($criteria);
  775. $stmt = $this->conn->executeQuery($query, $params, $types);
  776. $hydrator = $this->em->newHydrator($this->currentPersisterContext->selectJoinSql ? Query::HYDRATE_OBJECT : Query::HYDRATE_SIMPLEOBJECT);
  777. return $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true]);
  778. }
  779. /**
  780. * {@inheritDoc}
  781. */
  782. public function expandCriteriaParameters(Criteria $criteria)
  783. {
  784. $expression = $criteria->getWhereExpression();
  785. $sqlParams = [];
  786. $sqlTypes = [];
  787. if ($expression === null) {
  788. return [$sqlParams, $sqlTypes];
  789. }
  790. $valueVisitor = new SqlValueVisitor();
  791. $valueVisitor->dispatch($expression);
  792. [, $types] = $valueVisitor->getParamsAndTypes();
  793. foreach ($types as $type) {
  794. [$field, $value, $operator] = $type;
  795. if ($value === null && ($operator === Comparison::EQ || $operator === Comparison::NEQ)) {
  796. continue;
  797. }
  798. $sqlParams = array_merge($sqlParams, $this->getValues($value));
  799. $sqlTypes = array_merge($sqlTypes, $this->getTypes($field, $value, $this->class));
  800. }
  801. return [$sqlParams, $sqlTypes];
  802. }
  803. /**
  804. * {@inheritDoc}
  805. */
  806. public function loadAll(array $criteria = [], ?array $orderBy = null, $limit = null, $offset = null)
  807. {
  808. $this->switchPersisterContext($offset, $limit);
  809. $sql = $this->getSelectSQL($criteria, null, null, $limit, $offset, $orderBy);
  810. [$params, $types] = $this->expandParameters($criteria);
  811. $stmt = $this->conn->executeQuery($sql, $params, $types);
  812. $hydrator = $this->em->newHydrator($this->currentPersisterContext->selectJoinSql ? Query::HYDRATE_OBJECT : Query::HYDRATE_SIMPLEOBJECT);
  813. return $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true]);
  814. }
  815. /**
  816. * {@inheritDoc}
  817. */
  818. public function getManyToManyCollection(array $assoc, $sourceEntity, $offset = null, $limit = null)
  819. {
  820. $this->switchPersisterContext($offset, $limit);
  821. $stmt = $this->getManyToManyStatement($assoc, $sourceEntity, $offset, $limit);
  822. return $this->loadArrayFromResult($assoc, $stmt);
  823. }
  824. /**
  825. * Loads an array of entities from a given DBAL statement.
  826. *
  827. * @param mixed[] $assoc
  828. *
  829. * @return mixed[]
  830. */
  831. private function loadArrayFromResult(array $assoc, Result $stmt): array
  832. {
  833. $rsm = $this->currentPersisterContext->rsm;
  834. $hints = [UnitOfWork::HINT_DEFEREAGERLOAD => true];
  835. if (isset($assoc['indexBy'])) {
  836. $rsm = clone $this->currentPersisterContext->rsm; // this is necessary because the "default rsm" should be changed.
  837. $rsm->addIndexBy('r', $assoc['indexBy']);
  838. }
  839. return $this->em->newHydrator(Query::HYDRATE_OBJECT)->hydrateAll($stmt, $rsm, $hints);
  840. }
  841. /**
  842. * Hydrates a collection from a given DBAL statement.
  843. *
  844. * @param mixed[] $assoc
  845. *
  846. * @return mixed[]
  847. */
  848. private function loadCollectionFromStatement(
  849. array $assoc,
  850. Result $stmt,
  851. PersistentCollection $coll
  852. ): array {
  853. $rsm = $this->currentPersisterContext->rsm;
  854. $hints = [
  855. UnitOfWork::HINT_DEFEREAGERLOAD => true,
  856. 'collection' => $coll,
  857. ];
  858. if (isset($assoc['indexBy'])) {
  859. $rsm = clone $this->currentPersisterContext->rsm; // this is necessary because the "default rsm" should be changed.
  860. $rsm->addIndexBy('r', $assoc['indexBy']);
  861. }
  862. return $this->em->newHydrator(Query::HYDRATE_OBJECT)->hydrateAll($stmt, $rsm, $hints);
  863. }
  864. /**
  865. * {@inheritDoc}
  866. */
  867. public function loadManyToManyCollection(array $assoc, $sourceEntity, PersistentCollection $collection)
  868. {
  869. $stmt = $this->getManyToManyStatement($assoc, $sourceEntity);
  870. return $this->loadCollectionFromStatement($assoc, $stmt, $collection);
  871. }
  872. /**
  873. * @param object $sourceEntity
  874. * @phpstan-param array<string, mixed> $assoc
  875. *
  876. * @return Result
  877. *
  878. * @throws MappingException
  879. */
  880. private function getManyToManyStatement(
  881. array $assoc,
  882. $sourceEntity,
  883. ?int $offset = null,
  884. ?int $limit = null
  885. ) {
  886. $this->switchPersisterContext($offset, $limit);
  887. $sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']);
  888. $class = $sourceClass;
  889. $association = $assoc;
  890. $criteria = [];
  891. $parameters = [];
  892. if (! $assoc['isOwningSide']) {
  893. $class = $this->em->getClassMetadata($assoc['targetEntity']);
  894. $association = $class->associationMappings[$assoc['mappedBy']];
  895. }
  896. $joinColumns = $assoc['isOwningSide']
  897. ? $association['joinTable']['joinColumns']
  898. : $association['joinTable']['inverseJoinColumns'];
  899. $quotedJoinTable = $this->quoteStrategy->getJoinTableName($association, $class, $this->platform);
  900. foreach ($joinColumns as $joinColumn) {
  901. $sourceKeyColumn = $joinColumn['referencedColumnName'];
  902. $quotedKeyColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
  903. switch (true) {
  904. case $sourceClass->containsForeignIdentifier:
  905. $field = $sourceClass->getFieldForColumn($sourceKeyColumn);
  906. $value = $sourceClass->reflFields[$field]->getValue($sourceEntity);
  907. if (isset($sourceClass->associationMappings[$field])) {
  908. $value = $this->em->getUnitOfWork()->getEntityIdentifier($value);
  909. $value = $value[$this->em->getClassMetadata($sourceClass->associationMappings[$field]['targetEntity'])->identifier[0]];
  910. }
  911. break;
  912. case isset($sourceClass->fieldNames[$sourceKeyColumn]):
  913. $field = $sourceClass->fieldNames[$sourceKeyColumn];
  914. $value = $sourceClass->reflFields[$field]->getValue($sourceEntity);
  915. break;
  916. default:
  917. throw MappingException::joinColumnMustPointToMappedField(
  918. $sourceClass->name,
  919. $sourceKeyColumn
  920. );
  921. }
  922. $criteria[$quotedJoinTable . '.' . $quotedKeyColumn] = $value;
  923. $parameters[] = [
  924. 'value' => $value,
  925. 'field' => $field,
  926. 'class' => $sourceClass,
  927. ];
  928. }
  929. $sql = $this->getSelectSQL($criteria, $assoc, null, $limit, $offset);
  930. [$params, $types] = $this->expandToManyParameters($parameters);
  931. return $this->conn->executeQuery($sql, $params, $types);
  932. }
  933. /**
  934. * {@inheritDoc}
  935. */
  936. public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit = null, $offset = null, ?array $orderBy = null)
  937. {
  938. $this->switchPersisterContext($offset, $limit);
  939. $lockSql = '';
  940. $joinSql = '';
  941. $orderBySql = '';
  942. if ($assoc !== null && $assoc['type'] === ClassMetadata::MANY_TO_MANY) {
  943. $joinSql = $this->getSelectManyToManyJoinSQL($assoc);
  944. }
  945. if (isset($assoc['orderBy'])) {
  946. $orderBy = $assoc['orderBy'];
  947. }
  948. if ($orderBy) {
  949. $orderBySql = $this->getOrderBySQL($orderBy, $this->getSQLTableAlias($this->class->name));
  950. }
  951. $conditionSql = $criteria instanceof Criteria
  952. ? $this->getSelectConditionCriteriaSQL($criteria)
  953. : $this->getSelectConditionSQL($criteria, $assoc);
  954. switch ($lockMode) {
  955. case LockMode::PESSIMISTIC_READ:
  956. $lockSql = ' ' . $this->getReadLockSQL($this->platform);
  957. break;
  958. case LockMode::PESSIMISTIC_WRITE:
  959. $lockSql = ' ' . $this->getWriteLockSQL($this->platform);
  960. break;
  961. }
  962. $columnList = $this->getSelectColumnsSQL();
  963. $tableAlias = $this->getSQLTableAlias($this->class->name);
  964. $filterSql = $this->generateFilterConditionSQL($this->class, $tableAlias);
  965. $tableName = $this->quoteStrategy->getTableName($this->class, $this->platform);
  966. if ($filterSql !== '') {
  967. $conditionSql = $conditionSql
  968. ? $conditionSql . ' AND ' . $filterSql
  969. : $filterSql;
  970. }
  971. $select = 'SELECT ' . $columnList;
  972. $from = ' FROM ' . $tableName . ' ' . $tableAlias;
  973. $join = $this->currentPersisterContext->selectJoinSql . $joinSql;
  974. $where = ($conditionSql ? ' WHERE ' . $conditionSql : '');
  975. $lock = $this->platform->appendLockHint($from, $lockMode ?? LockMode::NONE);
  976. $query = $select
  977. . $lock
  978. . $join
  979. . $where
  980. . $orderBySql;
  981. return $this->platform->modifyLimitQuery($query, $limit, $offset ?? 0) . $lockSql;
  982. }
  983. /**
  984. * {@inheritDoc}
  985. */
  986. public function getCountSQL($criteria = [])
  987. {
  988. $tableName = $this->quoteStrategy->getTableName($this->class, $this->platform);
  989. $tableAlias = $this->getSQLTableAlias($this->class->name);
  990. $conditionSql = $criteria instanceof Criteria
  991. ? $this->getSelectConditionCriteriaSQL($criteria)
  992. : $this->getSelectConditionSQL($criteria);
  993. $filterSql = $this->generateFilterConditionSQL($this->class, $tableAlias);
  994. if ($filterSql !== '') {
  995. $conditionSql = $conditionSql
  996. ? $conditionSql . ' AND ' . $filterSql
  997. : $filterSql;
  998. }
  999. return 'SELECT COUNT(*) '
  1000. . 'FROM ' . $tableName . ' ' . $tableAlias
  1001. . (empty($conditionSql) ? '' : ' WHERE ' . $conditionSql);
  1002. }
  1003. /**
  1004. * Gets the ORDER BY SQL snippet for ordered collections.
  1005. *
  1006. * @phpstan-param array<string, string> $orderBy
  1007. *
  1008. * @throws InvalidOrientation
  1009. * @throws InvalidFindByCall
  1010. * @throws UnrecognizedField
  1011. */
  1012. final protected function getOrderBySQL(array $orderBy, string $baseTableAlias): string
  1013. {
  1014. $orderByList = [];
  1015. foreach ($orderBy as $fieldName => $orientation) {
  1016. $orientation = strtoupper(trim($orientation));
  1017. if ($orientation !== 'ASC' && $orientation !== 'DESC') {
  1018. throw InvalidOrientation::fromClassNameAndField($this->class->name, $fieldName);
  1019. }
  1020. if (isset($this->class->fieldMappings[$fieldName])) {
  1021. $tableAlias = isset($this->class->fieldMappings[$fieldName]['inherited'])
  1022. ? $this->getSQLTableAlias($this->class->fieldMappings[$fieldName]['inherited'])
  1023. : $baseTableAlias;
  1024. $columnName = $this->quoteStrategy->getColumnName($fieldName, $this->class, $this->platform);
  1025. $orderByList[] = $tableAlias . '.' . $columnName . ' ' . $orientation;
  1026. continue;
  1027. }
  1028. if (isset($this->class->associationMappings[$fieldName])) {
  1029. if (! $this->class->associationMappings[$fieldName]['isOwningSide']) {
  1030. throw InvalidFindByCall::fromInverseSideUsage($this->class->name, $fieldName);
  1031. }
  1032. $tableAlias = isset($this->class->associationMappings[$fieldName]['inherited'])
  1033. ? $this->getSQLTableAlias($this->class->associationMappings[$fieldName]['inherited'])
  1034. : $baseTableAlias;
  1035. foreach ($this->class->associationMappings[$fieldName]['joinColumns'] as $joinColumn) {
  1036. $columnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform);
  1037. $orderByList[] = $tableAlias . '.' . $columnName . ' ' . $orientation;
  1038. }
  1039. continue;
  1040. }
  1041. throw UnrecognizedField::byFullyQualifiedName($this->class->name, $fieldName);
  1042. }
  1043. return ' ORDER BY ' . implode(', ', $orderByList);
  1044. }
  1045. /**
  1046. * Gets the SQL fragment with the list of columns to select when querying for
  1047. * an entity in this persister.
  1048. *
  1049. * Subclasses should override this method to alter or change the select column
  1050. * list SQL fragment. Note that in the implementation of BasicEntityPersister
  1051. * the resulting SQL fragment is generated only once and cached in {@link selectColumnListSql}.
  1052. * Subclasses may or may not do the same.
  1053. *
  1054. * @return string The SQL fragment.
  1055. */
  1056. protected function getSelectColumnsSQL()
  1057. {
  1058. if ($this->currentPersisterContext->selectColumnListSql !== null && $this->filterHash === $this->em->getFilters()->getHash()) {
  1059. return $this->currentPersisterContext->selectColumnListSql;
  1060. }
  1061. $columnList = [];
  1062. $this->currentPersisterContext->rsm->addEntityResult($this->class->name, 'r'); // r for root
  1063. // Add regular columns to select list
  1064. foreach ($this->class->fieldNames as $field) {
  1065. $columnList[] = $this->getSelectColumnSQL($field, $this->class);
  1066. }
  1067. $this->currentPersisterContext->selectJoinSql = '';
  1068. $eagerAliasCounter = 0;
  1069. foreach ($this->class->associationMappings as $assocField => $assoc) {
  1070. $assocColumnSQL = $this->getSelectColumnAssociationSQL($assocField, $assoc, $this->class);
  1071. if ($assocColumnSQL) {
  1072. $columnList[] = $assocColumnSQL;
  1073. }
  1074. $isAssocToOneInverseSide = $assoc['type'] & ClassMetadata::TO_ONE && ! $assoc['isOwningSide'];
  1075. $isAssocFromOneEager = $assoc['type'] & ClassMetadata::TO_ONE && $assoc['fetch'] === ClassMetadata::FETCH_EAGER;
  1076. if (! ($isAssocFromOneEager || $isAssocToOneInverseSide)) {
  1077. continue;
  1078. }
  1079. if ((($assoc['type'] & ClassMetadata::TO_MANY) > 0) && $this->currentPersisterContext->handlesLimits) {
  1080. continue;
  1081. }
  1082. $eagerEntity = $this->em->getClassMetadata($assoc['targetEntity']);
  1083. if ($eagerEntity->inheritanceType !== ClassMetadata::INHERITANCE_TYPE_NONE) {
  1084. continue; // now this is why you shouldn't use inheritance
  1085. }
  1086. $assocAlias = 'e' . ($eagerAliasCounter++);
  1087. $this->currentPersisterContext->rsm->addJoinedEntityResult($assoc['targetEntity'], $assocAlias, 'r', $assocField);
  1088. foreach ($eagerEntity->fieldNames as $field) {
  1089. $columnList[] = $this->getSelectColumnSQL($field, $eagerEntity, $assocAlias);
  1090. }
  1091. foreach ($eagerEntity->associationMappings as $eagerAssocField => $eagerAssoc) {
  1092. $eagerAssocColumnSQL = $this->getSelectColumnAssociationSQL(
  1093. $eagerAssocField,
  1094. $eagerAssoc,
  1095. $eagerEntity,
  1096. $assocAlias
  1097. );
  1098. if ($eagerAssocColumnSQL) {
  1099. $columnList[] = $eagerAssocColumnSQL;
  1100. }
  1101. }
  1102. $association = $assoc;
  1103. $joinCondition = [];
  1104. if (isset($assoc['indexBy'])) {
  1105. $this->currentPersisterContext->rsm->addIndexBy($assocAlias, $assoc['indexBy']);
  1106. }
  1107. if (! $assoc['isOwningSide']) {
  1108. $eagerEntity = $this->em->getClassMetadata($assoc['targetEntity']);
  1109. $association = $eagerEntity->getAssociationMapping($assoc['mappedBy']);
  1110. }
  1111. $joinTableAlias = $this->getSQLTableAlias($eagerEntity->name, $assocAlias);
  1112. $joinTableName = $this->quoteStrategy->getTableName($eagerEntity, $this->platform);
  1113. if ($assoc['isOwningSide']) {
  1114. $tableAlias = $this->getSQLTableAlias($association['targetEntity'], $assocAlias);
  1115. $this->currentPersisterContext->selectJoinSql .= ' ' . $this->getJoinSQLForJoinColumns($association['joinColumns']);
  1116. foreach ($association['joinColumns'] as $joinColumn) {
  1117. $sourceCol = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform);
  1118. $targetCol = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $this->class, $this->platform);
  1119. $joinCondition[] = $this->getSQLTableAlias($association['sourceEntity'])
  1120. . '.' . $sourceCol . ' = ' . $tableAlias . '.' . $targetCol;
  1121. }
  1122. // Add filter SQL
  1123. $filterSql = $this->generateFilterConditionSQL($eagerEntity, $tableAlias);
  1124. if ($filterSql) {
  1125. $joinCondition[] = $filterSql;
  1126. }
  1127. } else {
  1128. $this->currentPersisterContext->selectJoinSql .= ' LEFT JOIN';
  1129. foreach ($association['joinColumns'] as $joinColumn) {
  1130. $sourceCol = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform);
  1131. $targetCol = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $this->class, $this->platform);
  1132. $joinCondition[] = $this->getSQLTableAlias($association['sourceEntity'], $assocAlias) . '.' . $sourceCol . ' = '
  1133. . $this->getSQLTableAlias($association['targetEntity']) . '.' . $targetCol;
  1134. }
  1135. }
  1136. $this->currentPersisterContext->selectJoinSql .= ' ' . $joinTableName . ' ' . $joinTableAlias . ' ON ';
  1137. $this->currentPersisterContext->selectJoinSql .= implode(' AND ', $joinCondition);
  1138. }
  1139. $this->currentPersisterContext->selectColumnListSql = implode(', ', $columnList);
  1140. $this->filterHash = $this->em->getFilters()->getHash();
  1141. return $this->currentPersisterContext->selectColumnListSql;
  1142. }
  1143. /**
  1144. * Gets the SQL join fragment used when selecting entities from an association.
  1145. *
  1146. * @param string $field
  1147. * @param AssociationMapping $assoc
  1148. * @param string $alias
  1149. *
  1150. * @return string
  1151. */
  1152. protected function getSelectColumnAssociationSQL($field, $assoc, ClassMetadata $class, $alias = 'r')
  1153. {
  1154. if (! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) {
  1155. return '';
  1156. }
  1157. $columnList = [];
  1158. $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
  1159. $isIdentifier = isset($assoc['id']) && $assoc['id'] === true;
  1160. $sqlTableAlias = $this->getSQLTableAlias($class->name, ($alias === 'r' ? '' : $alias));
  1161. foreach ($assoc['joinColumns'] as $joinColumn) {
  1162. $quotedColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform);
  1163. $resultColumnName = $this->getSQLColumnAlias($joinColumn['name']);
  1164. $type = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em);
  1165. $this->currentPersisterContext->rsm->addMetaResult($alias, $resultColumnName, $joinColumn['name'], $isIdentifier, $type);
  1166. $columnList[] = sprintf('%s.%s AS %s', $sqlTableAlias, $quotedColumn, $resultColumnName);
  1167. }
  1168. return implode(', ', $columnList);
  1169. }
  1170. /**
  1171. * Gets the SQL join fragment used when selecting entities from a
  1172. * many-to-many association.
  1173. *
  1174. * @phpstan-param AssociationMapping $manyToMany
  1175. *
  1176. * @return string
  1177. */
  1178. protected function getSelectManyToManyJoinSQL(array $manyToMany)
  1179. {
  1180. $conditions = [];
  1181. $association = $manyToMany;
  1182. $sourceTableAlias = $this->getSQLTableAlias($this->class->name);
  1183. if (! $manyToMany['isOwningSide']) {
  1184. $targetEntity = $this->em->getClassMetadata($manyToMany['targetEntity']);
  1185. $association = $targetEntity->associationMappings[$manyToMany['mappedBy']];
  1186. }
  1187. $joinTableName = $this->quoteStrategy->getJoinTableName($association, $this->class, $this->platform);
  1188. $joinColumns = $manyToMany['isOwningSide']
  1189. ? $association['joinTable']['inverseJoinColumns']
  1190. : $association['joinTable']['joinColumns'];
  1191. foreach ($joinColumns as $joinColumn) {
  1192. $quotedSourceColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform);
  1193. $quotedTargetColumn = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $this->class, $this->platform);
  1194. $conditions[] = $sourceTableAlias . '.' . $quotedTargetColumn . ' = ' . $joinTableName . '.' . $quotedSourceColumn;
  1195. }
  1196. return ' INNER JOIN ' . $joinTableName . ' ON ' . implode(' AND ', $conditions);
  1197. }
  1198. /**
  1199. * {@inheritDoc}
  1200. */
  1201. public function getInsertSQL()
  1202. {
  1203. if ($this->insertSql !== null) {
  1204. return $this->insertSql;
  1205. }
  1206. $columns = $this->getInsertColumnList();
  1207. $tableName = $this->quoteStrategy->getTableName($this->class, $this->platform);
  1208. if (empty($columns)) {
  1209. $identityColumn = $this->quoteStrategy->getColumnName($this->class->identifier[0], $this->class, $this->platform);
  1210. $this->insertSql = $this->platform->getEmptyIdentityInsertSQL($tableName, $identityColumn);
  1211. return $this->insertSql;
  1212. }
  1213. $values = [];
  1214. $columns = array_unique($columns);
  1215. foreach ($columns as $column) {
  1216. $placeholder = '?';
  1217. if (
  1218. isset($this->class->fieldNames[$column])
  1219. && isset($this->columnTypes[$this->class->fieldNames[$column]])
  1220. && isset($this->class->fieldMappings[$this->class->fieldNames[$column]]['requireSQLConversion'])
  1221. ) {
  1222. $type = Type::getType($this->columnTypes[$this->class->fieldNames[$column]]);
  1223. $placeholder = $type->convertToDatabaseValueSQL('?', $this->platform);
  1224. }
  1225. $values[] = $placeholder;
  1226. }
  1227. $columns = implode(', ', $columns);
  1228. $values = implode(', ', $values);
  1229. $this->insertSql = sprintf('INSERT INTO %s (%s) VALUES (%s)', $tableName, $columns, $values);
  1230. return $this->insertSql;
  1231. }
  1232. /**
  1233. * Gets the list of columns to put in the INSERT SQL statement.
  1234. *
  1235. * Subclasses should override this method to alter or change the list of
  1236. * columns placed in the INSERT statements used by the persister.
  1237. *
  1238. * @return string[] The list of columns.
  1239. * @phpstan-return list<string>
  1240. */
  1241. protected function getInsertColumnList()
  1242. {
  1243. $columns = [];
  1244. foreach ($this->class->reflFields as $name => $field) {
  1245. if ($this->class->isVersioned && $this->class->versionField === $name) {
  1246. continue;
  1247. }
  1248. if (isset($this->class->embeddedClasses[$name])) {
  1249. continue;
  1250. }
  1251. if (isset($this->class->associationMappings[$name])) {
  1252. $assoc = $this->class->associationMappings[$name];
  1253. if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) {
  1254. foreach ($assoc['joinColumns'] as $joinColumn) {
  1255. $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform);
  1256. }
  1257. }
  1258. continue;
  1259. }
  1260. if (! $this->class->isIdGeneratorIdentity() || $this->class->identifier[0] !== $name) {
  1261. if (isset($this->class->fieldMappings[$name]['notInsertable'])) {
  1262. continue;
  1263. }
  1264. $columns[] = $this->quoteStrategy->getColumnName($name, $this->class, $this->platform);
  1265. $this->columnTypes[$name] = $this->class->fieldMappings[$name]['type'];
  1266. }
  1267. }
  1268. return $columns;
  1269. }
  1270. /**
  1271. * Gets the SQL snippet of a qualified column name for the given field name.
  1272. *
  1273. * @param string $field The field name.
  1274. * @param ClassMetadata $class The class that declares this field. The table this class is
  1275. * mapped to must own the column for the given field.
  1276. * @param string $alias
  1277. *
  1278. * @return string
  1279. */
  1280. protected function getSelectColumnSQL($field, ClassMetadata $class, $alias = 'r')
  1281. {
  1282. $root = $alias === 'r' ? '' : $alias;
  1283. $tableAlias = $this->getSQLTableAlias($class->name, $root);
  1284. $fieldMapping = $class->fieldMappings[$field];
  1285. $sql = sprintf('%s.%s', $tableAlias, $this->quoteStrategy->getColumnName($field, $class, $this->platform));
  1286. $columnAlias = null;
  1287. if ($this->currentPersisterContext->rsm->hasColumnAliasByField($alias, $field)) {
  1288. $columnAlias = $this->currentPersisterContext->rsm->getColumnAliasByField($alias, $field);
  1289. }
  1290. if ($columnAlias === null) {
  1291. $columnAlias = $this->getSQLColumnAlias($fieldMapping['columnName']);
  1292. }
  1293. $this->currentPersisterContext->rsm->addFieldResult($alias, $columnAlias, $field);
  1294. if (! empty($fieldMapping['enumType'])) {
  1295. $this->currentPersisterContext->rsm->addEnumResult($columnAlias, $fieldMapping['enumType']);
  1296. }
  1297. if (isset($fieldMapping['requireSQLConversion'])) {
  1298. $type = Type::getType($fieldMapping['type']);
  1299. $sql = $type->convertToPHPValueSQL($sql, $this->platform);
  1300. }
  1301. return $sql . ' AS ' . $columnAlias;
  1302. }
  1303. /**
  1304. * Gets the SQL table alias for the given class name.
  1305. *
  1306. * @param string $className
  1307. * @param string $assocName
  1308. *
  1309. * @return string The SQL table alias.
  1310. *
  1311. * @todo Reconsider. Binding table aliases to class names is not such a good idea.
  1312. */
  1313. protected function getSQLTableAlias($className, $assocName = '')
  1314. {
  1315. if ($assocName) {
  1316. $className .= '#' . $assocName;
  1317. }
  1318. if (isset($this->currentPersisterContext->sqlTableAliases[$className])) {
  1319. return $this->currentPersisterContext->sqlTableAliases[$className];
  1320. }
  1321. $tableAlias = 't' . $this->currentPersisterContext->sqlAliasCounter++;
  1322. $this->currentPersisterContext->sqlTableAliases[$className] = $tableAlias;
  1323. return $tableAlias;
  1324. }
  1325. /**
  1326. * {@inheritDoc}
  1327. */
  1328. public function lock(array $criteria, $lockMode)
  1329. {
  1330. $lockSql = '';
  1331. $conditionSql = $this->getSelectConditionSQL($criteria);
  1332. switch ($lockMode) {
  1333. case LockMode::PESSIMISTIC_READ:
  1334. $lockSql = $this->getReadLockSQL($this->platform);
  1335. break;
  1336. case LockMode::PESSIMISTIC_WRITE:
  1337. $lockSql = $this->getWriteLockSQL($this->platform);
  1338. break;
  1339. }
  1340. $lock = $this->getLockTablesSql($lockMode);
  1341. $where = ($conditionSql ? ' WHERE ' . $conditionSql : '') . ' ';
  1342. $sql = 'SELECT 1 '
  1343. . $lock
  1344. . $where
  1345. . $lockSql;
  1346. [$params, $types] = $this->expandParameters($criteria);
  1347. $this->conn->executeQuery($sql, $params, $types);
  1348. }
  1349. /**
  1350. * Gets the FROM and optionally JOIN conditions to lock the entity managed by this persister.
  1351. *
  1352. * @param int|null $lockMode One of the Doctrine\DBAL\LockMode::* constants.
  1353. * @phpstan-param LockMode::*|null $lockMode
  1354. *
  1355. * @return string
  1356. */
  1357. protected function getLockTablesSql($lockMode)
  1358. {
  1359. if ($lockMode === null) {
  1360. Deprecation::trigger(
  1361. 'doctrine/orm',
  1362. 'https://github.com/doctrine/orm/pull/9466',
  1363. 'Passing null as argument to %s is deprecated, pass LockMode::NONE instead.',
  1364. __METHOD__
  1365. );
  1366. $lockMode = LockMode::NONE;
  1367. }
  1368. return $this->platform->appendLockHint(
  1369. 'FROM '
  1370. . $this->quoteStrategy->getTableName($this->class, $this->platform) . ' '
  1371. . $this->getSQLTableAlias($this->class->name),
  1372. $lockMode
  1373. );
  1374. }
  1375. /**
  1376. * Gets the Select Where Condition from a Criteria object.
  1377. *
  1378. * @return string
  1379. */
  1380. protected function getSelectConditionCriteriaSQL(Criteria $criteria)
  1381. {
  1382. $expression = $criteria->getWhereExpression();
  1383. if ($expression === null) {
  1384. return '';
  1385. }
  1386. $visitor = new SqlExpressionVisitor($this, $this->class);
  1387. return $visitor->dispatch($expression);
  1388. }
  1389. /**
  1390. * {@inheritDoc}
  1391. */
  1392. public function getSelectConditionStatementSQL($field, $value, $assoc = null, $comparison = null)
  1393. {
  1394. $selectedColumns = [];
  1395. $columns = $this->getSelectConditionStatementColumnSQL($field, $assoc);
  1396. if (count($columns) > 1 && $comparison === Comparison::IN) {
  1397. /*
  1398. * @todo try to support multi-column IN expressions.
  1399. * Example: (col1, col2) IN (('val1A', 'val2A'), ('val1B', 'val2B'))
  1400. */
  1401. throw CantUseInOperatorOnCompositeKeys::create();
  1402. }
  1403. foreach ($columns as $column) {
  1404. $placeholder = '?';
  1405. if (isset($this->class->fieldMappings[$field]['requireSQLConversion'])) {
  1406. $type = Type::getType($this->class->fieldMappings[$field]['type']);
  1407. $placeholder = $type->convertToDatabaseValueSQL($placeholder, $this->platform);
  1408. }
  1409. if ($comparison !== null) {
  1410. // special case null value handling
  1411. if (($comparison === Comparison::EQ || $comparison === Comparison::IS) && $value === null) {
  1412. $selectedColumns[] = $column . ' IS NULL';
  1413. continue;
  1414. }
  1415. if ($comparison === Comparison::NEQ && $value === null) {
  1416. $selectedColumns[] = $column . ' IS NOT NULL';
  1417. continue;
  1418. }
  1419. $selectedColumns[] = $column . ' ' . sprintf(self::$comparisonMap[$comparison], $placeholder);
  1420. continue;
  1421. }
  1422. if (is_array($value)) {
  1423. $in = sprintf('%s IN (%s)', $column, $placeholder);
  1424. if (array_search(null, $value, true) !== false) {
  1425. $selectedColumns[] = sprintf('(%s OR %s IS NULL)', $in, $column);
  1426. continue;
  1427. }
  1428. $selectedColumns[] = $in;
  1429. continue;
  1430. }
  1431. if ($value === null) {
  1432. $selectedColumns[] = sprintf('%s IS NULL', $column);
  1433. continue;
  1434. }
  1435. $selectedColumns[] = sprintf('%s = %s', $column, $placeholder);
  1436. }
  1437. return implode(' AND ', $selectedColumns);
  1438. }
  1439. /**
  1440. * Builds the left-hand-side of a where condition statement.
  1441. *
  1442. * @phpstan-param AssociationMapping|null $assoc
  1443. *
  1444. * @return string[]
  1445. * @phpstan-return list<string>
  1446. *
  1447. * @throws InvalidFindByCall
  1448. * @throws UnrecognizedField
  1449. */
  1450. private function getSelectConditionStatementColumnSQL(
  1451. string $field,
  1452. ?array $assoc = null
  1453. ): array {
  1454. if (isset($this->class->fieldMappings[$field])) {
  1455. $className = $this->class->fieldMappings[$field]['inherited'] ?? $this->class->name;
  1456. return [$this->getSQLTableAlias($className) . '.' . $this->quoteStrategy->getColumnName($field, $this->class, $this->platform)];
  1457. }
  1458. if (isset($this->class->associationMappings[$field])) {
  1459. $association = $this->class->associationMappings[$field];
  1460. // Many-To-Many requires join table check for joinColumn
  1461. $columns = [];
  1462. $class = $this->class;
  1463. if ($association['type'] === ClassMetadata::MANY_TO_MANY) {
  1464. if (! $association['isOwningSide']) {
  1465. $association = $assoc;
  1466. }
  1467. $joinTableName = $this->quoteStrategy->getJoinTableName($association, $class, $this->platform);
  1468. $joinColumns = $assoc['isOwningSide']
  1469. ? $association['joinTable']['joinColumns']
  1470. : $association['joinTable']['inverseJoinColumns'];
  1471. foreach ($joinColumns as $joinColumn) {
  1472. $columns[] = $joinTableName . '.' . $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
  1473. }
  1474. } else {
  1475. if (! $association['isOwningSide']) {
  1476. throw InvalidFindByCall::fromInverseSideUsage(
  1477. $this->class->name,
  1478. $field
  1479. );
  1480. }
  1481. $className = $association['inherited'] ?? $this->class->name;
  1482. foreach ($association['joinColumns'] as $joinColumn) {
  1483. $columns[] = $this->getSQLTableAlias($className) . '.' . $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform);
  1484. }
  1485. }
  1486. return $columns;
  1487. }
  1488. if ($assoc !== null && ! str_contains($field, ' ') && ! str_contains($field, '(')) {
  1489. // very careless developers could potentially open up this normally hidden api for userland attacks,
  1490. // therefore checking for spaces and function calls which are not allowed.
  1491. // found a join column condition, not really a "field"
  1492. return [$field];
  1493. }
  1494. throw UnrecognizedField::byFullyQualifiedName($this->class->name, $field);
  1495. }
  1496. /**
  1497. * Gets the conditional SQL fragment used in the WHERE clause when selecting
  1498. * entities in this persister.
  1499. *
  1500. * Subclasses are supposed to override this method if they intend to change
  1501. * or alter the criteria by which entities are selected.
  1502. *
  1503. * @param AssociationMapping|null $assoc
  1504. * @phpstan-param array<string, mixed> $criteria
  1505. * @phpstan-param array<string, mixed>|null $assoc
  1506. *
  1507. * @return string
  1508. */
  1509. protected function getSelectConditionSQL(array $criteria, $assoc = null)
  1510. {
  1511. $conditions = [];
  1512. foreach ($criteria as $field => $value) {
  1513. $conditions[] = $this->getSelectConditionStatementSQL($field, $value, $assoc);
  1514. }
  1515. return implode(' AND ', $conditions);
  1516. }
  1517. /**
  1518. * {@inheritDoc}
  1519. */
  1520. public function getOneToManyCollection(array $assoc, $sourceEntity, $offset = null, $limit = null)
  1521. {
  1522. $this->switchPersisterContext($offset, $limit);
  1523. $stmt = $this->getOneToManyStatement($assoc, $sourceEntity, $offset, $limit);
  1524. return $this->loadArrayFromResult($assoc, $stmt);
  1525. }
  1526. /**
  1527. * {@inheritDoc}
  1528. */
  1529. public function loadOneToManyCollection(array $assoc, $sourceEntity, PersistentCollection $collection)
  1530. {
  1531. $stmt = $this->getOneToManyStatement($assoc, $sourceEntity);
  1532. return $this->loadCollectionFromStatement($assoc, $stmt, $collection);
  1533. }
  1534. /**
  1535. * Builds criteria and execute SQL statement to fetch the one to many entities from.
  1536. *
  1537. * @param object $sourceEntity
  1538. * @phpstan-param AssociationMapping $assoc
  1539. */
  1540. private function getOneToManyStatement(
  1541. array $assoc,
  1542. $sourceEntity,
  1543. ?int $offset = null,
  1544. ?int $limit = null
  1545. ): Result {
  1546. $this->switchPersisterContext($offset, $limit);
  1547. $criteria = [];
  1548. $parameters = [];
  1549. $owningAssoc = $this->class->associationMappings[$assoc['mappedBy']];
  1550. $sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']);
  1551. $tableAlias = $this->getSQLTableAlias($owningAssoc['inherited'] ?? $this->class->name);
  1552. foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) {
  1553. if ($sourceClass->containsForeignIdentifier) {
  1554. $field = $sourceClass->getFieldForColumn($sourceKeyColumn);
  1555. $value = $sourceClass->reflFields[$field]->getValue($sourceEntity);
  1556. if (isset($sourceClass->associationMappings[$field])) {
  1557. $value = $this->em->getUnitOfWork()->getEntityIdentifier($value);
  1558. $value = $value[$this->em->getClassMetadata($sourceClass->associationMappings[$field]['targetEntity'])->identifier[0]];
  1559. }
  1560. $criteria[$tableAlias . '.' . $targetKeyColumn] = $value;
  1561. $parameters[] = [
  1562. 'value' => $value,
  1563. 'field' => $field,
  1564. 'class' => $sourceClass,
  1565. ];
  1566. continue;
  1567. }
  1568. $field = $sourceClass->fieldNames[$sourceKeyColumn];
  1569. $value = $sourceClass->reflFields[$field]->getValue($sourceEntity);
  1570. $criteria[$tableAlias . '.' . $targetKeyColumn] = $value;
  1571. $parameters[] = [
  1572. 'value' => $value,
  1573. 'field' => $field,
  1574. 'class' => $sourceClass,
  1575. ];
  1576. }
  1577. $sql = $this->getSelectSQL($criteria, $assoc, null, $limit, $offset);
  1578. [$params, $types] = $this->expandToManyParameters($parameters);
  1579. return $this->conn->executeQuery($sql, $params, $types);
  1580. }
  1581. /**
  1582. * {@inheritDoc}
  1583. */
  1584. public function expandParameters($criteria)
  1585. {
  1586. $params = [];
  1587. $types = [];
  1588. foreach ($criteria as $field => $value) {
  1589. if ($value === null) {
  1590. continue; // skip null values.
  1591. }
  1592. $types = array_merge($types, $this->getTypes($field, $value, $this->class));
  1593. $params = array_merge($params, $this->getValues($value));
  1594. }
  1595. return [$params, $types];
  1596. }
  1597. /**
  1598. * Expands the parameters from the given criteria and use the correct binding types if found,
  1599. * specialized for OneToMany or ManyToMany associations.
  1600. *
  1601. * @param mixed[][] $criteria an array of arrays containing following:
  1602. * - field to which each criterion will be bound
  1603. * - value to be bound
  1604. * - class to which the field belongs to
  1605. *
  1606. * @return mixed[][]
  1607. * @phpstan-return array{0: array, 1: list<int|string|null>}
  1608. */
  1609. private function expandToManyParameters(array $criteria): array
  1610. {
  1611. $params = [];
  1612. $types = [];
  1613. foreach ($criteria as $criterion) {
  1614. if ($criterion['value'] === null) {
  1615. continue; // skip null values.
  1616. }
  1617. $types = array_merge($types, $this->getTypes($criterion['field'], $criterion['value'], $criterion['class']));
  1618. $params = array_merge($params, $this->getValues($criterion['value']));
  1619. }
  1620. return [$params, $types];
  1621. }
  1622. /**
  1623. * Infers field types to be used by parameter type casting.
  1624. *
  1625. * @param mixed $value
  1626. *
  1627. * @return int[]|null[]|string[]
  1628. * @phpstan-return list<int|string|null>
  1629. *
  1630. * @throws QueryException
  1631. */
  1632. private function getTypes(string $field, $value, ClassMetadata $class): array
  1633. {
  1634. $types = [];
  1635. switch (true) {
  1636. case isset($class->fieldMappings[$field]):
  1637. $types = array_merge($types, [$class->fieldMappings[$field]['type']]);
  1638. break;
  1639. case isset($class->associationMappings[$field]):
  1640. $assoc = $class->associationMappings[$field];
  1641. $class = $this->em->getClassMetadata($assoc['targetEntity']);
  1642. if (! $assoc['isOwningSide']) {
  1643. $assoc = $class->associationMappings[$assoc['mappedBy']];
  1644. $class = $this->em->getClassMetadata($assoc['targetEntity']);
  1645. }
  1646. $columns = $assoc['type'] === ClassMetadata::MANY_TO_MANY
  1647. ? $assoc['relationToTargetKeyColumns']
  1648. : $assoc['sourceToTargetKeyColumns'];
  1649. foreach ($columns as $column) {
  1650. $types[] = PersisterHelper::getTypeOfColumn($column, $class, $this->em);
  1651. }
  1652. break;
  1653. default:
  1654. $types[] = null;
  1655. break;
  1656. }
  1657. if (is_array($value)) {
  1658. return array_map(static function ($type) {
  1659. $type = Type::getType($type);
  1660. return $type->getBindingType() + Connection::ARRAY_PARAM_OFFSET;
  1661. }, $types);
  1662. }
  1663. return $types;
  1664. }
  1665. /**
  1666. * Retrieves the parameters that identifies a value.
  1667. *
  1668. * @param mixed $value
  1669. *
  1670. * @return mixed[]
  1671. */
  1672. private function getValues($value): array
  1673. {
  1674. if (is_array($value)) {
  1675. $newValue = [];
  1676. foreach ($value as $itemValue) {
  1677. $newValue = array_merge($newValue, $this->getValues($itemValue));
  1678. }
  1679. return [$newValue];
  1680. }
  1681. return $this->getIndividualValue($value);
  1682. }
  1683. /**
  1684. * Retrieves an individual parameter value.
  1685. *
  1686. * @param mixed $value
  1687. *
  1688. * @phpstan-return list<mixed>
  1689. */
  1690. private function getIndividualValue($value): array
  1691. {
  1692. if (! is_object($value)) {
  1693. return [$value];
  1694. }
  1695. if ($value instanceof BackedEnum) {
  1696. return [$value->value];
  1697. }
  1698. $valueClass = DefaultProxyClassNameResolver::getClass($value);
  1699. if ($this->em->getMetadataFactory()->isTransient($valueClass)) {
  1700. return [$value];
  1701. }
  1702. $class = $this->em->getClassMetadata($valueClass);
  1703. if ($class->isIdentifierComposite) {
  1704. $newValue = [];
  1705. foreach ($class->getIdentifierValues($value) as $innerValue) {
  1706. $newValue = array_merge($newValue, $this->getValues($innerValue));
  1707. }
  1708. return $newValue;
  1709. }
  1710. return [$this->em->getUnitOfWork()->getSingleIdentifierValue($value)];
  1711. }
  1712. /**
  1713. * {@inheritDoc}
  1714. */
  1715. public function exists($entity, ?Criteria $extraConditions = null)
  1716. {
  1717. $criteria = $this->class->getIdentifierValues($entity);
  1718. if (! $criteria) {
  1719. return false;
  1720. }
  1721. $alias = $this->getSQLTableAlias($this->class->name);
  1722. $sql = 'SELECT 1 '
  1723. . $this->getLockTablesSql(LockMode::NONE)
  1724. . ' WHERE ' . $this->getSelectConditionSQL($criteria);
  1725. [$params, $types] = $this->expandParameters($criteria);
  1726. if ($extraConditions !== null) {
  1727. $sql .= ' AND ' . $this->getSelectConditionCriteriaSQL($extraConditions);
  1728. [$criteriaParams, $criteriaTypes] = $this->expandCriteriaParameters($extraConditions);
  1729. $params = array_merge($params, $criteriaParams);
  1730. $types = array_merge($types, $criteriaTypes);
  1731. }
  1732. $filterSql = $this->generateFilterConditionSQL($this->class, $alias);
  1733. if ($filterSql) {
  1734. $sql .= ' AND ' . $filterSql;
  1735. }
  1736. return (bool) $this->conn->fetchOne($sql, $params, $types);
  1737. }
  1738. /**
  1739. * Generates the appropriate join SQL for the given join column.
  1740. *
  1741. * @param array[] $joinColumns The join columns definition of an association.
  1742. * @phpstan-param array<array<string, mixed>> $joinColumns
  1743. *
  1744. * @return string LEFT JOIN if one of the columns is nullable, INNER JOIN otherwise.
  1745. */
  1746. protected function getJoinSQLForJoinColumns($joinColumns)
  1747. {
  1748. // if one of the join columns is nullable, return left join
  1749. foreach ($joinColumns as $joinColumn) {
  1750. if (! isset($joinColumn['nullable']) || $joinColumn['nullable']) {
  1751. return 'LEFT JOIN';
  1752. }
  1753. }
  1754. return 'INNER JOIN';
  1755. }
  1756. /**
  1757. * @param string $columnName
  1758. *
  1759. * @return string
  1760. */
  1761. public function getSQLColumnAlias($columnName)
  1762. {
  1763. return $this->quoteStrategy->getColumnAlias($columnName, $this->currentPersisterContext->sqlAliasCounter++, $this->platform);
  1764. }
  1765. /**
  1766. * Generates the filter SQL for a given entity and table alias.
  1767. *
  1768. * @param ClassMetadata $targetEntity Metadata of the target entity.
  1769. * @param string $targetTableAlias The table alias of the joined/selected table.
  1770. *
  1771. * @return string The SQL query part to add to a query.
  1772. */
  1773. protected function generateFilterConditionSQL(ClassMetadata $targetEntity, $targetTableAlias)
  1774. {
  1775. $filterClauses = [];
  1776. foreach ($this->em->getFilters()->getEnabledFilters() as $filter) {
  1777. $filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias);
  1778. if ($filterExpr !== '') {
  1779. $filterClauses[] = '(' . $filterExpr . ')';
  1780. }
  1781. }
  1782. $sql = implode(' AND ', $filterClauses);
  1783. return $sql ? '(' . $sql . ')' : ''; // Wrap again to avoid "X or Y and FilterConditionSQL"
  1784. }
  1785. /**
  1786. * Switches persister context according to current query offset/limits
  1787. *
  1788. * This is due to the fact that to-many associations cannot be fetch-joined when a limit is involved
  1789. *
  1790. * @param int|null $offset
  1791. * @param int|null $limit
  1792. *
  1793. * @return void
  1794. */
  1795. protected function switchPersisterContext($offset, $limit)
  1796. {
  1797. if ($offset === null && $limit === null) {
  1798. $this->currentPersisterContext = $this->noLimitsContext;
  1799. return;
  1800. }
  1801. $this->currentPersisterContext = $this->limitsHandlingContext;
  1802. }
  1803. /**
  1804. * @return string[]
  1805. * @phpstan-return list<string>
  1806. */
  1807. protected function getClassIdentifiersTypes(ClassMetadata $class): array
  1808. {
  1809. $entityManager = $this->em;
  1810. return array_map(
  1811. static function ($fieldName) use ($class, $entityManager): string {
  1812. $types = PersisterHelper::getTypeOfField($fieldName, $class, $entityManager);
  1813. assert(isset($types[0]));
  1814. return $types[0];
  1815. },
  1816. $class->identifier
  1817. );
  1818. }
  1819. }