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

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