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

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 $emClassMetadata $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 $idClassMetadata $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($joinTableNamearray_combine($keys$identifier), $types);
  499.             if ($selfReferential) {
  500.                 $this->conn->delete($joinTableNamearray_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($entitybool $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($entitytrue);
  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$limitnull$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($identifiernull$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.         // TRICKY: since the association is specular source and target are flipped
  702.         foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) {
  703.             if (! isset($sourceClass->fieldNames[$sourceKeyColumn])) {
  704.                 throw MappingException::joinColumnMustPointToMappedField(
  705.                     $sourceClass->name,
  706.                     $sourceKeyColumn
  707.                 );
  708.             }
  709.             $computedIdentifier[$targetClass->getFieldForColumn($targetKeyColumn)] =
  710.                 $sourceClass->reflFields[$sourceClass->fieldNames[$sourceKeyColumn]]->getValue($sourceEntity);
  711.         }
  712.         $targetEntity $this->load($computedIdentifiernull$assoc);
  713.         if ($targetEntity !== null) {
  714.             $targetClass->setFieldValue($targetEntity$assoc['mappedBy'], $sourceEntity);
  715.         }
  716.         return $targetEntity;
  717.     }
  718.     /**
  719.      * {@inheritDoc}
  720.      */
  721.     public function refresh(array $id$entity$lockMode null)
  722.     {
  723.         $sql              $this->getSelectSQL($idnull$lockMode);
  724.         [$params$types] = $this->expandParameters($id);
  725.         $stmt             $this->conn->executeQuery($sql$params$types);
  726.         $hydrator $this->em->newHydrator(Query::HYDRATE_OBJECT);
  727.         $hydrator->hydrateAll($stmt$this->currentPersisterContext->rsm, [Query::HINT_REFRESH => true]);
  728.     }
  729.     /**
  730.      * {@inheritDoc}
  731.      */
  732.     public function count($criteria = [])
  733.     {
  734.         $sql $this->getCountSQL($criteria);
  735.         [$params$types] = $criteria instanceof Criteria
  736.             $this->expandCriteriaParameters($criteria)
  737.             : $this->expandParameters($criteria);
  738.         return (int) $this->conn->executeQuery($sql$params$types)->fetchOne();
  739.     }
  740.     /**
  741.      * {@inheritDoc}
  742.      */
  743.     public function loadCriteria(Criteria $criteria)
  744.     {
  745.         $orderBy self::getCriteriaOrderings($criteria);
  746.         $limit   $criteria->getMaxResults();
  747.         $offset  $criteria->getFirstResult();
  748.         $query   $this->getSelectSQL($criterianullnull$limit$offset$orderBy);
  749.         [$params$types] = $this->expandCriteriaParameters($criteria);
  750.         $stmt     $this->conn->executeQuery($query$params$types);
  751.         $hydrator $this->em->newHydrator($this->currentPersisterContext->selectJoinSql Query::HYDRATE_OBJECT Query::HYDRATE_SIMPLEOBJECT);
  752.         return $hydrator->hydrateAll($stmt$this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true]);
  753.     }
  754.     /**
  755.      * {@inheritDoc}
  756.      */
  757.     public function expandCriteriaParameters(Criteria $criteria)
  758.     {
  759.         $expression $criteria->getWhereExpression();
  760.         $sqlParams  = [];
  761.         $sqlTypes   = [];
  762.         if ($expression === null) {
  763.             return [$sqlParams$sqlTypes];
  764.         }
  765.         $valueVisitor = new SqlValueVisitor();
  766.         $valueVisitor->dispatch($expression);
  767.         [, $types] = $valueVisitor->getParamsAndTypes();
  768.         foreach ($types as $type) {
  769.             [$field$value$operator] = $type;
  770.             if ($value === null && ($operator === Comparison::EQ || $operator === Comparison::NEQ)) {
  771.                 continue;
  772.             }
  773.             $sqlParams array_merge($sqlParams$this->getValues($value));
  774.             $sqlTypes  array_merge($sqlTypes$this->getTypes($field$value$this->class));
  775.         }
  776.         return [$sqlParams$sqlTypes];
  777.     }
  778.     /**
  779.      * {@inheritDoc}
  780.      */
  781.     public function loadAll(array $criteria = [], ?array $orderBy null$limit null$offset null)
  782.     {
  783.         $this->switchPersisterContext($offset$limit);
  784.         $sql              $this->getSelectSQL($criterianullnull$limit$offset$orderBy);
  785.         [$params$types] = $this->expandParameters($criteria);
  786.         $stmt             $this->conn->executeQuery($sql$params$types);
  787.         $hydrator $this->em->newHydrator($this->currentPersisterContext->selectJoinSql Query::HYDRATE_OBJECT Query::HYDRATE_SIMPLEOBJECT);
  788.         return $hydrator->hydrateAll($stmt$this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true]);
  789.     }
  790.     /**
  791.      * {@inheritDoc}
  792.      */
  793.     public function getManyToManyCollection(array $assoc$sourceEntity$offset null$limit null)
  794.     {
  795.         $this->switchPersisterContext($offset$limit);
  796.         $stmt $this->getManyToManyStatement($assoc$sourceEntity$offset$limit);
  797.         return $this->loadArrayFromResult($assoc$stmt);
  798.     }
  799.     /**
  800.      * Loads an array of entities from a given DBAL statement.
  801.      *
  802.      * @param mixed[] $assoc
  803.      *
  804.      * @return mixed[]
  805.      */
  806.     private function loadArrayFromResult(array $assocResult $stmt): array
  807.     {
  808.         $rsm   $this->currentPersisterContext->rsm;
  809.         $hints = [UnitOfWork::HINT_DEFEREAGERLOAD => true];
  810.         if (isset($assoc['indexBy'])) {
  811.             $rsm = clone $this->currentPersisterContext->rsm// this is necessary because the "default rsm" should be changed.
  812.             $rsm->addIndexBy('r'$assoc['indexBy']);
  813.         }
  814.         return $this->em->newHydrator(Query::HYDRATE_OBJECT)->hydrateAll($stmt$rsm$hints);
  815.     }
  816.     /**
  817.      * Hydrates a collection from a given DBAL statement.
  818.      *
  819.      * @param mixed[] $assoc
  820.      *
  821.      * @return mixed[]
  822.      */
  823.     private function loadCollectionFromStatement(
  824.         array $assoc,
  825.         Result $stmt,
  826.         PersistentCollection $coll
  827.     ): array {
  828.         $rsm   $this->currentPersisterContext->rsm;
  829.         $hints = [
  830.             UnitOfWork::HINT_DEFEREAGERLOAD => true,
  831.             'collection' => $coll,
  832.         ];
  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.      * {@inheritDoc}
  841.      */
  842.     public function loadManyToManyCollection(array $assoc$sourceEntityPersistentCollection $collection)
  843.     {
  844.         $stmt $this->getManyToManyStatement($assoc$sourceEntity);
  845.         return $this->loadCollectionFromStatement($assoc$stmt$collection);
  846.     }
  847.     /**
  848.      * @param object $sourceEntity
  849.      * @psalm-param array<string, mixed> $assoc
  850.      *
  851.      * @return Result
  852.      *
  853.      * @throws MappingException
  854.      */
  855.     private function getManyToManyStatement(
  856.         array $assoc,
  857.         $sourceEntity,
  858.         ?int $offset null,
  859.         ?int $limit null
  860.     ) {
  861.         $this->switchPersisterContext($offset$limit);
  862.         $sourceClass $this->em->getClassMetadata($assoc['sourceEntity']);
  863.         $class       $sourceClass;
  864.         $association $assoc;
  865.         $criteria    = [];
  866.         $parameters  = [];
  867.         if (! $assoc['isOwningSide']) {
  868.             $class       $this->em->getClassMetadata($assoc['targetEntity']);
  869.             $association $class->associationMappings[$assoc['mappedBy']];
  870.         }
  871.         $joinColumns $assoc['isOwningSide']
  872.             ? $association['joinTable']['joinColumns']
  873.             : $association['joinTable']['inverseJoinColumns'];
  874.         $quotedJoinTable $this->quoteStrategy->getJoinTableName($association$class$this->platform);
  875.         foreach ($joinColumns as $joinColumn) {
  876.             $sourceKeyColumn $joinColumn['referencedColumnName'];
  877.             $quotedKeyColumn $this->quoteStrategy->getJoinColumnName($joinColumn$class$this->platform);
  878.             switch (true) {
  879.                 case $sourceClass->containsForeignIdentifier:
  880.                     $field $sourceClass->getFieldForColumn($sourceKeyColumn);
  881.                     $value $sourceClass->reflFields[$field]->getValue($sourceEntity);
  882.                     if (isset($sourceClass->associationMappings[$field])) {
  883.                         $value $this->em->getUnitOfWork()->getEntityIdentifier($value);
  884.                         $value $value[$this->em->getClassMetadata($sourceClass->associationMappings[$field]['targetEntity'])->identifier[0]];
  885.                     }
  886.                     break;
  887.                 case isset($sourceClass->fieldNames[$sourceKeyColumn]):
  888.                     $field $sourceClass->fieldNames[$sourceKeyColumn];
  889.                     $value $sourceClass->reflFields[$field]->getValue($sourceEntity);
  890.                     break;
  891.                 default:
  892.                     throw MappingException::joinColumnMustPointToMappedField(
  893.                         $sourceClass->name,
  894.                         $sourceKeyColumn
  895.                     );
  896.             }
  897.             $criteria[$quotedJoinTable '.' $quotedKeyColumn] = $value;
  898.             $parameters[]                                        = [
  899.                 'value' => $value,
  900.                 'field' => $field,
  901.                 'class' => $sourceClass,
  902.             ];
  903.         }
  904.         $sql              $this->getSelectSQL($criteria$assocnull$limit$offset);
  905.         [$params$types] = $this->expandToManyParameters($parameters);
  906.         return $this->conn->executeQuery($sql$params$types);
  907.     }
  908.     /**
  909.      * {@inheritDoc}
  910.      */
  911.     public function getSelectSQL($criteria$assoc null$lockMode null$limit null$offset null, ?array $orderBy null)
  912.     {
  913.         $this->switchPersisterContext($offset$limit);
  914.         $lockSql    '';
  915.         $joinSql    '';
  916.         $orderBySql '';
  917.         if ($assoc !== null && $assoc['type'] === ClassMetadata::MANY_TO_MANY) {
  918.             $joinSql $this->getSelectManyToManyJoinSQL($assoc);
  919.         }
  920.         if (isset($assoc['orderBy'])) {
  921.             $orderBy $assoc['orderBy'];
  922.         }
  923.         if ($orderBy) {
  924.             $orderBySql $this->getOrderBySQL($orderBy$this->getSQLTableAlias($this->class->name));
  925.         }
  926.         $conditionSql $criteria instanceof Criteria
  927.             $this->getSelectConditionCriteriaSQL($criteria)
  928.             : $this->getSelectConditionSQL($criteria$assoc);
  929.         switch ($lockMode) {
  930.             case LockMode::PESSIMISTIC_READ:
  931.                 $lockSql ' ' $this->getReadLockSQL($this->platform);
  932.                 break;
  933.             case LockMode::PESSIMISTIC_WRITE:
  934.                 $lockSql ' ' $this->getWriteLockSQL($this->platform);
  935.                 break;
  936.         }
  937.         $columnList $this->getSelectColumnsSQL();
  938.         $tableAlias $this->getSQLTableAlias($this->class->name);
  939.         $filterSql  $this->generateFilterConditionSQL($this->class$tableAlias);
  940.         $tableName  $this->quoteStrategy->getTableName($this->class$this->platform);
  941.         if ($filterSql !== '') {
  942.             $conditionSql $conditionSql
  943.                 $conditionSql ' AND ' $filterSql
  944.                 $filterSql;
  945.         }
  946.         $select 'SELECT ' $columnList;
  947.         $from   ' FROM ' $tableName ' ' $tableAlias;
  948.         $join   $this->currentPersisterContext->selectJoinSql $joinSql;
  949.         $where  = ($conditionSql ' WHERE ' $conditionSql '');
  950.         $lock   $this->platform->appendLockHint($from$lockMode ?? LockMode::NONE);
  951.         $query  $select
  952.             $lock
  953.             $join
  954.             $where
  955.             $orderBySql;
  956.         return $this->platform->modifyLimitQuery($query$limit$offset ?? 0) . $lockSql;
  957.     }
  958.     /**
  959.      * {@inheritDoc}
  960.      */
  961.     public function getCountSQL($criteria = [])
  962.     {
  963.         $tableName  $this->quoteStrategy->getTableName($this->class$this->platform);
  964.         $tableAlias $this->getSQLTableAlias($this->class->name);
  965.         $conditionSql $criteria instanceof Criteria
  966.             $this->getSelectConditionCriteriaSQL($criteria)
  967.             : $this->getSelectConditionSQL($criteria);
  968.         $filterSql $this->generateFilterConditionSQL($this->class$tableAlias);
  969.         if ($filterSql !== '') {
  970.             $conditionSql $conditionSql
  971.                 $conditionSql ' AND ' $filterSql
  972.                 $filterSql;
  973.         }
  974.         return 'SELECT COUNT(*) '
  975.             'FROM ' $tableName ' ' $tableAlias
  976.             . (empty($conditionSql) ? '' ' WHERE ' $conditionSql);
  977.     }
  978.     /**
  979.      * Gets the ORDER BY SQL snippet for ordered collections.
  980.      *
  981.      * @psalm-param array<string, string> $orderBy
  982.      *
  983.      * @throws InvalidOrientation
  984.      * @throws InvalidFindByCall
  985.      * @throws UnrecognizedField
  986.      */
  987.     final protected function getOrderBySQL(array $orderBystring $baseTableAlias): string
  988.     {
  989.         $orderByList = [];
  990.         foreach ($orderBy as $fieldName => $orientation) {
  991.             $orientation strtoupper(trim($orientation));
  992.             if ($orientation !== 'ASC' && $orientation !== 'DESC') {
  993.                 throw InvalidOrientation::fromClassNameAndField($this->class->name$fieldName);
  994.             }
  995.             if (isset($this->class->fieldMappings[$fieldName])) {
  996.                 $tableAlias = isset($this->class->fieldMappings[$fieldName]['inherited'])
  997.                     ? $this->getSQLTableAlias($this->class->fieldMappings[$fieldName]['inherited'])
  998.                     : $baseTableAlias;
  999.                 $columnName    $this->quoteStrategy->getColumnName($fieldName$this->class$this->platform);
  1000.                 $orderByList[] = $tableAlias '.' $columnName ' ' $orientation;
  1001.                 continue;
  1002.             }
  1003.             if (isset($this->class->associationMappings[$fieldName])) {
  1004.                 if (! $this->class->associationMappings[$fieldName]['isOwningSide']) {
  1005.                     throw InvalidFindByCall::fromInverseSideUsage($this->class->name$fieldName);
  1006.                 }
  1007.                 $tableAlias = isset($this->class->associationMappings[$fieldName]['inherited'])
  1008.                     ? $this->getSQLTableAlias($this->class->associationMappings[$fieldName]['inherited'])
  1009.                     : $baseTableAlias;
  1010.                 foreach ($this->class->associationMappings[$fieldName]['joinColumns'] as $joinColumn) {
  1011.                     $columnName    $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1012.                     $orderByList[] = $tableAlias '.' $columnName ' ' $orientation;
  1013.                 }
  1014.                 continue;
  1015.             }
  1016.             throw UnrecognizedField::byFullyQualifiedName($this->class->name$fieldName);
  1017.         }
  1018.         return ' ORDER BY ' implode(', '$orderByList);
  1019.     }
  1020.     /**
  1021.      * Gets the SQL fragment with the list of columns to select when querying for
  1022.      * an entity in this persister.
  1023.      *
  1024.      * Subclasses should override this method to alter or change the select column
  1025.      * list SQL fragment. Note that in the implementation of BasicEntityPersister
  1026.      * the resulting SQL fragment is generated only once and cached in {@link selectColumnListSql}.
  1027.      * Subclasses may or may not do the same.
  1028.      *
  1029.      * @return string The SQL fragment.
  1030.      */
  1031.     protected function getSelectColumnsSQL()
  1032.     {
  1033.         if ($this->currentPersisterContext->selectColumnListSql !== null) {
  1034.             return $this->currentPersisterContext->selectColumnListSql;
  1035.         }
  1036.         $columnList = [];
  1037.         $this->currentPersisterContext->rsm->addEntityResult($this->class->name'r'); // r for root
  1038.         // Add regular columns to select list
  1039.         foreach ($this->class->fieldNames as $field) {
  1040.             $columnList[] = $this->getSelectColumnSQL($field$this->class);
  1041.         }
  1042.         $this->currentPersisterContext->selectJoinSql '';
  1043.         $eagerAliasCounter                            0;
  1044.         foreach ($this->class->associationMappings as $assocField => $assoc) {
  1045.             $assocColumnSQL $this->getSelectColumnAssociationSQL($assocField$assoc$this->class);
  1046.             if ($assocColumnSQL) {
  1047.                 $columnList[] = $assocColumnSQL;
  1048.             }
  1049.             $isAssocToOneInverseSide $assoc['type'] & ClassMetadata::TO_ONE && ! $assoc['isOwningSide'];
  1050.             $isAssocFromOneEager     $assoc['type'] & ClassMetadata::TO_ONE && $assoc['fetch'] === ClassMetadata::FETCH_EAGER;
  1051.             if (! ($isAssocFromOneEager || $isAssocToOneInverseSide)) {
  1052.                 continue;
  1053.             }
  1054.             if ((($assoc['type'] & ClassMetadata::TO_MANY) > 0) && $this->currentPersisterContext->handlesLimits) {
  1055.                 continue;
  1056.             }
  1057.             $eagerEntity $this->em->getClassMetadata($assoc['targetEntity']);
  1058.             if ($eagerEntity->inheritanceType !== ClassMetadata::INHERITANCE_TYPE_NONE) {
  1059.                 continue; // now this is why you shouldn't use inheritance
  1060.             }
  1061.             $assocAlias 'e' . ($eagerAliasCounter++);
  1062.             $this->currentPersisterContext->rsm->addJoinedEntityResult($assoc['targetEntity'], $assocAlias'r'$assocField);
  1063.             foreach ($eagerEntity->fieldNames as $field) {
  1064.                 $columnList[] = $this->getSelectColumnSQL($field$eagerEntity$assocAlias);
  1065.             }
  1066.             foreach ($eagerEntity->associationMappings as $eagerAssocField => $eagerAssoc) {
  1067.                 $eagerAssocColumnSQL $this->getSelectColumnAssociationSQL(
  1068.                     $eagerAssocField,
  1069.                     $eagerAssoc,
  1070.                     $eagerEntity,
  1071.                     $assocAlias
  1072.                 );
  1073.                 if ($eagerAssocColumnSQL) {
  1074.                     $columnList[] = $eagerAssocColumnSQL;
  1075.                 }
  1076.             }
  1077.             $association   $assoc;
  1078.             $joinCondition = [];
  1079.             if (isset($assoc['indexBy'])) {
  1080.                 $this->currentPersisterContext->rsm->addIndexBy($assocAlias$assoc['indexBy']);
  1081.             }
  1082.             if (! $assoc['isOwningSide']) {
  1083.                 $eagerEntity $this->em->getClassMetadata($assoc['targetEntity']);
  1084.                 $association $eagerEntity->getAssociationMapping($assoc['mappedBy']);
  1085.             }
  1086.             $joinTableAlias $this->getSQLTableAlias($eagerEntity->name$assocAlias);
  1087.             $joinTableName  $this->quoteStrategy->getTableName($eagerEntity$this->platform);
  1088.             if ($assoc['isOwningSide']) {
  1089.                 $tableAlias                                    $this->getSQLTableAlias($association['targetEntity'], $assocAlias);
  1090.                 $this->currentPersisterContext->selectJoinSql .= ' ' $this->getJoinSQLForJoinColumns($association['joinColumns']);
  1091.                 foreach ($association['joinColumns'] as $joinColumn) {
  1092.                     $sourceCol       $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1093.                     $targetCol       $this->quoteStrategy->getReferencedJoinColumnName($joinColumn$this->class$this->platform);
  1094.                     $joinCondition[] = $this->getSQLTableAlias($association['sourceEntity'])
  1095.                                         . '.' $sourceCol ' = ' $tableAlias '.' $targetCol;
  1096.                 }
  1097.                 // Add filter SQL
  1098.                 $filterSql $this->generateFilterConditionSQL($eagerEntity$tableAlias);
  1099.                 if ($filterSql) {
  1100.                     $joinCondition[] = $filterSql;
  1101.                 }
  1102.             } else {
  1103.                 $this->currentPersisterContext->selectJoinSql .= ' LEFT JOIN';
  1104.                 foreach ($association['joinColumns'] as $joinColumn) {
  1105.                     $sourceCol $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1106.                     $targetCol $this->quoteStrategy->getReferencedJoinColumnName($joinColumn$this->class$this->platform);
  1107.                     $joinCondition[] = $this->getSQLTableAlias($association['sourceEntity'], $assocAlias) . '.' $sourceCol ' = '
  1108.                         $this->getSQLTableAlias($association['targetEntity']) . '.' $targetCol;
  1109.                 }
  1110.             }
  1111.             $this->currentPersisterContext->selectJoinSql .= ' ' $joinTableName ' ' $joinTableAlias ' ON ';
  1112.             $this->currentPersisterContext->selectJoinSql .= implode(' AND '$joinCondition);
  1113.         }
  1114.         $this->currentPersisterContext->selectColumnListSql implode(', '$columnList);
  1115.         return $this->currentPersisterContext->selectColumnListSql;
  1116.     }
  1117.     /**
  1118.      * Gets the SQL join fragment used when selecting entities from an association.
  1119.      *
  1120.      * @param string             $field
  1121.      * @param AssociationMapping $assoc
  1122.      * @param string             $alias
  1123.      *
  1124.      * @return string
  1125.      */
  1126.     protected function getSelectColumnAssociationSQL($field$assocClassMetadata $class$alias 'r')
  1127.     {
  1128.         if (! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) {
  1129.             return '';
  1130.         }
  1131.         $columnList    = [];
  1132.         $targetClass   $this->em->getClassMetadata($assoc['targetEntity']);
  1133.         $isIdentifier  = isset($assoc['id']) && $assoc['id'] === true;
  1134.         $sqlTableAlias $this->getSQLTableAlias($class->name, ($alias === 'r' '' $alias));
  1135.         foreach ($assoc['joinColumns'] as $joinColumn) {
  1136.             $quotedColumn     $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1137.             $resultColumnName $this->getSQLColumnAlias($joinColumn['name']);
  1138.             $type             PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass$this->em);
  1139.             $this->currentPersisterContext->rsm->addMetaResult($alias$resultColumnName$joinColumn['name'], $isIdentifier$type);
  1140.             $columnList[] = sprintf('%s.%s AS %s'$sqlTableAlias$quotedColumn$resultColumnName);
  1141.         }
  1142.         return implode(', '$columnList);
  1143.     }
  1144.     /**
  1145.      * Gets the SQL join fragment used when selecting entities from a
  1146.      * many-to-many association.
  1147.      *
  1148.      * @psalm-param AssociationMapping $manyToMany
  1149.      *
  1150.      * @return string
  1151.      */
  1152.     protected function getSelectManyToManyJoinSQL(array $manyToMany)
  1153.     {
  1154.         $conditions       = [];
  1155.         $association      $manyToMany;
  1156.         $sourceTableAlias $this->getSQLTableAlias($this->class->name);
  1157.         if (! $manyToMany['isOwningSide']) {
  1158.             $targetEntity $this->em->getClassMetadata($manyToMany['targetEntity']);
  1159.             $association  $targetEntity->associationMappings[$manyToMany['mappedBy']];
  1160.         }
  1161.         $joinTableName $this->quoteStrategy->getJoinTableName($association$this->class$this->platform);
  1162.         $joinColumns   $manyToMany['isOwningSide']
  1163.             ? $association['joinTable']['inverseJoinColumns']
  1164.             : $association['joinTable']['joinColumns'];
  1165.         foreach ($joinColumns as $joinColumn) {
  1166.             $quotedSourceColumn $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1167.             $quotedTargetColumn $this->quoteStrategy->getReferencedJoinColumnName($joinColumn$this->class$this->platform);
  1168.             $conditions[]       = $sourceTableAlias '.' $quotedTargetColumn ' = ' $joinTableName '.' $quotedSourceColumn;
  1169.         }
  1170.         return ' INNER JOIN ' $joinTableName ' ON ' implode(' AND '$conditions);
  1171.     }
  1172.     /**
  1173.      * {@inheritDoc}
  1174.      */
  1175.     public function getInsertSQL()
  1176.     {
  1177.         if ($this->insertSql !== null) {
  1178.             return $this->insertSql;
  1179.         }
  1180.         $columns   $this->getInsertColumnList();
  1181.         $tableName $this->quoteStrategy->getTableName($this->class$this->platform);
  1182.         if (empty($columns)) {
  1183.             $identityColumn  $this->quoteStrategy->getColumnName($this->class->identifier[0], $this->class$this->platform);
  1184.             $this->insertSql $this->platform->getEmptyIdentityInsertSQL($tableName$identityColumn);
  1185.             return $this->insertSql;
  1186.         }
  1187.         $values  = [];
  1188.         $columns array_unique($columns);
  1189.         foreach ($columns as $column) {
  1190.             $placeholder '?';
  1191.             if (
  1192.                 isset($this->class->fieldNames[$column])
  1193.                 && isset($this->columnTypes[$this->class->fieldNames[$column]])
  1194.                 && isset($this->class->fieldMappings[$this->class->fieldNames[$column]]['requireSQLConversion'])
  1195.             ) {
  1196.                 $type        Type::getType($this->columnTypes[$this->class->fieldNames[$column]]);
  1197.                 $placeholder $type->convertToDatabaseValueSQL('?'$this->platform);
  1198.             }
  1199.             $values[] = $placeholder;
  1200.         }
  1201.         $columns implode(', '$columns);
  1202.         $values  implode(', '$values);
  1203.         $this->insertSql sprintf('INSERT INTO %s (%s) VALUES (%s)'$tableName$columns$values);
  1204.         return $this->insertSql;
  1205.     }
  1206.     /**
  1207.      * Gets the list of columns to put in the INSERT SQL statement.
  1208.      *
  1209.      * Subclasses should override this method to alter or change the list of
  1210.      * columns placed in the INSERT statements used by the persister.
  1211.      *
  1212.      * @return string[] The list of columns.
  1213.      * @psalm-return list<string>
  1214.      */
  1215.     protected function getInsertColumnList()
  1216.     {
  1217.         $columns = [];
  1218.         foreach ($this->class->reflFields as $name => $field) {
  1219.             if ($this->class->isVersioned && $this->class->versionField === $name) {
  1220.                 continue;
  1221.             }
  1222.             if (isset($this->class->embeddedClasses[$name])) {
  1223.                 continue;
  1224.             }
  1225.             if (isset($this->class->associationMappings[$name])) {
  1226.                 $assoc $this->class->associationMappings[$name];
  1227.                 if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) {
  1228.                     foreach ($assoc['joinColumns'] as $joinColumn) {
  1229.                         $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1230.                     }
  1231.                 }
  1232.                 continue;
  1233.             }
  1234.             if (! $this->class->isIdGeneratorIdentity() || $this->class->identifier[0] !== $name) {
  1235.                 if (isset($this->class->fieldMappings[$name]['notInsertable'])) {
  1236.                     continue;
  1237.                 }
  1238.                 $columns[]                = $this->quoteStrategy->getColumnName($name$this->class$this->platform);
  1239.                 $this->columnTypes[$name] = $this->class->fieldMappings[$name]['type'];
  1240.             }
  1241.         }
  1242.         return $columns;
  1243.     }
  1244.     /**
  1245.      * Gets the SQL snippet of a qualified column name for the given field name.
  1246.      *
  1247.      * @param string        $field The field name.
  1248.      * @param ClassMetadata $class The class that declares this field. The table this class is
  1249.      *                             mapped to must own the column for the given field.
  1250.      * @param string        $alias
  1251.      *
  1252.      * @return string
  1253.      */
  1254.     protected function getSelectColumnSQL($fieldClassMetadata $class$alias 'r')
  1255.     {
  1256.         $root         $alias === 'r' '' $alias;
  1257.         $tableAlias   $this->getSQLTableAlias($class->name$root);
  1258.         $fieldMapping $class->fieldMappings[$field];
  1259.         $sql          sprintf('%s.%s'$tableAlias$this->quoteStrategy->getColumnName($field$class$this->platform));
  1260.         $columnAlias  $this->getSQLColumnAlias($fieldMapping['columnName']);
  1261.         $this->currentPersisterContext->rsm->addFieldResult($alias$columnAlias$field);
  1262.         if (! empty($fieldMapping['enumType'])) {
  1263.             $this->currentPersisterContext->rsm->addEnumResult($columnAlias$fieldMapping['enumType']);
  1264.         }
  1265.         if (isset($fieldMapping['requireSQLConversion'])) {
  1266.             $type Type::getType($fieldMapping['type']);
  1267.             $sql  $type->convertToPHPValueSQL($sql$this->platform);
  1268.         }
  1269.         return $sql ' AS ' $columnAlias;
  1270.     }
  1271.     /**
  1272.      * Gets the SQL table alias for the given class name.
  1273.      *
  1274.      * @param string $className
  1275.      * @param string $assocName
  1276.      *
  1277.      * @return string The SQL table alias.
  1278.      *
  1279.      * @todo Reconsider. Binding table aliases to class names is not such a good idea.
  1280.      */
  1281.     protected function getSQLTableAlias($className$assocName '')
  1282.     {
  1283.         if ($assocName) {
  1284.             $className .= '#' $assocName;
  1285.         }
  1286.         if (isset($this->currentPersisterContext->sqlTableAliases[$className])) {
  1287.             return $this->currentPersisterContext->sqlTableAliases[$className];
  1288.         }
  1289.         $tableAlias 't' $this->currentPersisterContext->sqlAliasCounter++;
  1290.         $this->currentPersisterContext->sqlTableAliases[$className] = $tableAlias;
  1291.         return $tableAlias;
  1292.     }
  1293.     /**
  1294.      * {@inheritDoc}
  1295.      */
  1296.     public function lock(array $criteria$lockMode)
  1297.     {
  1298.         $lockSql      '';
  1299.         $conditionSql $this->getSelectConditionSQL($criteria);
  1300.         switch ($lockMode) {
  1301.             case LockMode::PESSIMISTIC_READ:
  1302.                 $lockSql $this->getReadLockSQL($this->platform);
  1303.                 break;
  1304.             case LockMode::PESSIMISTIC_WRITE:
  1305.                 $lockSql $this->getWriteLockSQL($this->platform);
  1306.                 break;
  1307.         }
  1308.         $lock  $this->getLockTablesSql($lockMode);
  1309.         $where = ($conditionSql ' WHERE ' $conditionSql '') . ' ';
  1310.         $sql   'SELECT 1 '
  1311.              $lock
  1312.              $where
  1313.              $lockSql;
  1314.         [$params$types] = $this->expandParameters($criteria);
  1315.         $this->conn->executeQuery($sql$params$types);
  1316.     }
  1317.     /**
  1318.      * Gets the FROM and optionally JOIN conditions to lock the entity managed by this persister.
  1319.      *
  1320.      * @param int|null $lockMode One of the Doctrine\DBAL\LockMode::* constants.
  1321.      * @psalm-param LockMode::*|null $lockMode
  1322.      *
  1323.      * @return string
  1324.      */
  1325.     protected function getLockTablesSql($lockMode)
  1326.     {
  1327.         if ($lockMode === null) {
  1328.             Deprecation::trigger(
  1329.                 'doctrine/orm',
  1330.                 'https://github.com/doctrine/orm/pull/9466',
  1331.                 'Passing null as argument to %s is deprecated, pass LockMode::NONE instead.',
  1332.                 __METHOD__
  1333.             );
  1334.             $lockMode LockMode::NONE;
  1335.         }
  1336.         return $this->platform->appendLockHint(
  1337.             'FROM '
  1338.             $this->quoteStrategy->getTableName($this->class$this->platform) . ' '
  1339.             $this->getSQLTableAlias($this->class->name),
  1340.             $lockMode
  1341.         );
  1342.     }
  1343.     /**
  1344.      * Gets the Select Where Condition from a Criteria object.
  1345.      *
  1346.      * @return string
  1347.      */
  1348.     protected function getSelectConditionCriteriaSQL(Criteria $criteria)
  1349.     {
  1350.         $expression $criteria->getWhereExpression();
  1351.         if ($expression === null) {
  1352.             return '';
  1353.         }
  1354.         $visitor = new SqlExpressionVisitor($this$this->class);
  1355.         return $visitor->dispatch($expression);
  1356.     }
  1357.     /**
  1358.      * {@inheritDoc}
  1359.      */
  1360.     public function getSelectConditionStatementSQL($field$value$assoc null$comparison null)
  1361.     {
  1362.         $selectedColumns = [];
  1363.         $columns         $this->getSelectConditionStatementColumnSQL($field$assoc);
  1364.         if (count($columns) > && $comparison === Comparison::IN) {
  1365.             /*
  1366.              *  @todo try to support multi-column IN expressions.
  1367.              *  Example: (col1, col2) IN (('val1A', 'val2A'), ('val1B', 'val2B'))
  1368.              */
  1369.             throw CantUseInOperatorOnCompositeKeys::create();
  1370.         }
  1371.         foreach ($columns as $column) {
  1372.             $placeholder '?';
  1373.             if (isset($this->class->fieldMappings[$field]['requireSQLConversion'])) {
  1374.                 $type        Type::getType($this->class->fieldMappings[$field]['type']);
  1375.                 $placeholder $type->convertToDatabaseValueSQL($placeholder$this->platform);
  1376.             }
  1377.             if ($comparison !== null) {
  1378.                 // special case null value handling
  1379.                 if (($comparison === Comparison::EQ || $comparison === Comparison::IS) && $value === null) {
  1380.                     $selectedColumns[] = $column ' IS NULL';
  1381.                     continue;
  1382.                 }
  1383.                 if ($comparison === Comparison::NEQ && $value === null) {
  1384.                     $selectedColumns[] = $column ' IS NOT NULL';
  1385.                     continue;
  1386.                 }
  1387.                 $selectedColumns[] = $column ' ' sprintf(self::$comparisonMap[$comparison], $placeholder);
  1388.                 continue;
  1389.             }
  1390.             if (is_array($value)) {
  1391.                 $in sprintf('%s IN (%s)'$column$placeholder);
  1392.                 if (array_search(null$valuetrue) !== false) {
  1393.                     $selectedColumns[] = sprintf('(%s OR %s IS NULL)'$in$column);
  1394.                     continue;
  1395.                 }
  1396.                 $selectedColumns[] = $in;
  1397.                 continue;
  1398.             }
  1399.             if ($value === null) {
  1400.                 $selectedColumns[] = sprintf('%s IS NULL'$column);
  1401.                 continue;
  1402.             }
  1403.             $selectedColumns[] = sprintf('%s = %s'$column$placeholder);
  1404.         }
  1405.         return implode(' AND '$selectedColumns);
  1406.     }
  1407.     /**
  1408.      * Builds the left-hand-side of a where condition statement.
  1409.      *
  1410.      * @psalm-param AssociationMapping|null $assoc
  1411.      *
  1412.      * @return string[]
  1413.      * @psalm-return list<string>
  1414.      *
  1415.      * @throws InvalidFindByCall
  1416.      * @throws UnrecognizedField
  1417.      */
  1418.     private function getSelectConditionStatementColumnSQL(
  1419.         string $field,
  1420.         ?array $assoc null
  1421.     ): array {
  1422.         if (isset($this->class->fieldMappings[$field])) {
  1423.             $className $this->class->fieldMappings[$field]['inherited'] ?? $this->class->name;
  1424.             return [$this->getSQLTableAlias($className) . '.' $this->quoteStrategy->getColumnName($field$this->class$this->platform)];
  1425.         }
  1426.         if (isset($this->class->associationMappings[$field])) {
  1427.             $association $this->class->associationMappings[$field];
  1428.             // Many-To-Many requires join table check for joinColumn
  1429.             $columns = [];
  1430.             $class   $this->class;
  1431.             if ($association['type'] === ClassMetadata::MANY_TO_MANY) {
  1432.                 if (! $association['isOwningSide']) {
  1433.                     $association $assoc;
  1434.                 }
  1435.                 $joinTableName $this->quoteStrategy->getJoinTableName($association$class$this->platform);
  1436.                 $joinColumns   $assoc['isOwningSide']
  1437.                     ? $association['joinTable']['joinColumns']
  1438.                     : $association['joinTable']['inverseJoinColumns'];
  1439.                 foreach ($joinColumns as $joinColumn) {
  1440.                     $columns[] = $joinTableName '.' $this->quoteStrategy->getJoinColumnName($joinColumn$class$this->platform);
  1441.                 }
  1442.             } else {
  1443.                 if (! $association['isOwningSide']) {
  1444.                     throw InvalidFindByCall::fromInverseSideUsage(
  1445.                         $this->class->name,
  1446.                         $field
  1447.                     );
  1448.                 }
  1449.                 $className $association['inherited'] ?? $this->class->name;
  1450.                 foreach ($association['joinColumns'] as $joinColumn) {
  1451.                     $columns[] = $this->getSQLTableAlias($className) . '.' $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1452.                 }
  1453.             }
  1454.             return $columns;
  1455.         }
  1456.         if ($assoc !== null && ! str_contains($field' ') && ! str_contains($field'(')) {
  1457.             // very careless developers could potentially open up this normally hidden api for userland attacks,
  1458.             // therefore checking for spaces and function calls which are not allowed.
  1459.             // found a join column condition, not really a "field"
  1460.             return [$field];
  1461.         }
  1462.         throw UnrecognizedField::byFullyQualifiedName($this->class->name$field);
  1463.     }
  1464.     /**
  1465.      * Gets the conditional SQL fragment used in the WHERE clause when selecting
  1466.      * entities in this persister.
  1467.      *
  1468.      * Subclasses are supposed to override this method if they intend to change
  1469.      * or alter the criteria by which entities are selected.
  1470.      *
  1471.      * @param AssociationMapping|null $assoc
  1472.      * @psalm-param array<string, mixed> $criteria
  1473.      * @psalm-param array<string, mixed>|null $assoc
  1474.      *
  1475.      * @return string
  1476.      */
  1477.     protected function getSelectConditionSQL(array $criteria$assoc null)
  1478.     {
  1479.         $conditions = [];
  1480.         foreach ($criteria as $field => $value) {
  1481.             $conditions[] = $this->getSelectConditionStatementSQL($field$value$assoc);
  1482.         }
  1483.         return implode(' AND '$conditions);
  1484.     }
  1485.     /**
  1486.      * {@inheritDoc}
  1487.      */
  1488.     public function getOneToManyCollection(array $assoc$sourceEntity$offset null$limit null)
  1489.     {
  1490.         $this->switchPersisterContext($offset$limit);
  1491.         $stmt $this->getOneToManyStatement($assoc$sourceEntity$offset$limit);
  1492.         return $this->loadArrayFromResult($assoc$stmt);
  1493.     }
  1494.     /**
  1495.      * {@inheritDoc}
  1496.      */
  1497.     public function loadOneToManyCollection(array $assoc$sourceEntityPersistentCollection $collection)
  1498.     {
  1499.         $stmt $this->getOneToManyStatement($assoc$sourceEntity);
  1500.         return $this->loadCollectionFromStatement($assoc$stmt$collection);
  1501.     }
  1502.     /**
  1503.      * Builds criteria and execute SQL statement to fetch the one to many entities from.
  1504.      *
  1505.      * @param object $sourceEntity
  1506.      * @psalm-param AssociationMapping $assoc
  1507.      */
  1508.     private function getOneToManyStatement(
  1509.         array $assoc,
  1510.         $sourceEntity,
  1511.         ?int $offset null,
  1512.         ?int $limit null
  1513.     ): Result {
  1514.         $this->switchPersisterContext($offset$limit);
  1515.         $criteria    = [];
  1516.         $parameters  = [];
  1517.         $owningAssoc $this->class->associationMappings[$assoc['mappedBy']];
  1518.         $sourceClass $this->em->getClassMetadata($assoc['sourceEntity']);
  1519.         $tableAlias  $this->getSQLTableAlias($owningAssoc['inherited'] ?? $this->class->name);
  1520.         foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) {
  1521.             if ($sourceClass->containsForeignIdentifier) {
  1522.                 $field $sourceClass->getFieldForColumn($sourceKeyColumn);
  1523.                 $value $sourceClass->reflFields[$field]->getValue($sourceEntity);
  1524.                 if (isset($sourceClass->associationMappings[$field])) {
  1525.                     $value $this->em->getUnitOfWork()->getEntityIdentifier($value);
  1526.                     $value $value[$this->em->getClassMetadata($sourceClass->associationMappings[$field]['targetEntity'])->identifier[0]];
  1527.                 }
  1528.                 $criteria[$tableAlias '.' $targetKeyColumn] = $value;
  1529.                 $parameters[]                                   = [
  1530.                     'value' => $value,
  1531.                     'field' => $field,
  1532.                     'class' => $sourceClass,
  1533.                 ];
  1534.                 continue;
  1535.             }
  1536.             $field $sourceClass->fieldNames[$sourceKeyColumn];
  1537.             $value $sourceClass->reflFields[$field]->getValue($sourceEntity);
  1538.             $criteria[$tableAlias '.' $targetKeyColumn] = $value;
  1539.             $parameters[]                                   = [
  1540.                 'value' => $value,
  1541.                 'field' => $field,
  1542.                 'class' => $sourceClass,
  1543.             ];
  1544.         }
  1545.         $sql              $this->getSelectSQL($criteria$assocnull$limit$offset);
  1546.         [$params$types] = $this->expandToManyParameters($parameters);
  1547.         return $this->conn->executeQuery($sql$params$types);
  1548.     }
  1549.     /**
  1550.      * {@inheritDoc}
  1551.      */
  1552.     public function expandParameters($criteria)
  1553.     {
  1554.         $params = [];
  1555.         $types  = [];
  1556.         foreach ($criteria as $field => $value) {
  1557.             if ($value === null) {
  1558.                 continue; // skip null values.
  1559.             }
  1560.             $types  array_merge($types$this->getTypes($field$value$this->class));
  1561.             $params array_merge($params$this->getValues($value));
  1562.         }
  1563.         return [$params$types];
  1564.     }
  1565.     /**
  1566.      * Expands the parameters from the given criteria and use the correct binding types if found,
  1567.      * specialized for OneToMany or ManyToMany associations.
  1568.      *
  1569.      * @param mixed[][] $criteria an array of arrays containing following:
  1570.      *                             - field to which each criterion will be bound
  1571.      *                             - value to be bound
  1572.      *                             - class to which the field belongs to
  1573.      *
  1574.      * @return mixed[][]
  1575.      * @psalm-return array{0: array, 1: list<int|string|null>}
  1576.      */
  1577.     private function expandToManyParameters(array $criteria): array
  1578.     {
  1579.         $params = [];
  1580.         $types  = [];
  1581.         foreach ($criteria as $criterion) {
  1582.             if ($criterion['value'] === null) {
  1583.                 continue; // skip null values.
  1584.             }
  1585.             $types  array_merge($types$this->getTypes($criterion['field'], $criterion['value'], $criterion['class']));
  1586.             $params array_merge($params$this->getValues($criterion['value']));
  1587.         }
  1588.         return [$params$types];
  1589.     }
  1590.     /**
  1591.      * Infers field types to be used by parameter type casting.
  1592.      *
  1593.      * @param mixed $value
  1594.      *
  1595.      * @return int[]|null[]|string[]
  1596.      * @psalm-return list<int|string|null>
  1597.      *
  1598.      * @throws QueryException
  1599.      */
  1600.     private function getTypes(string $field$valueClassMetadata $class): array
  1601.     {
  1602.         $types = [];
  1603.         switch (true) {
  1604.             case isset($class->fieldMappings[$field]):
  1605.                 $types array_merge($types, [$class->fieldMappings[$field]['type']]);
  1606.                 break;
  1607.             case isset($class->associationMappings[$field]):
  1608.                 $assoc $class->associationMappings[$field];
  1609.                 $class $this->em->getClassMetadata($assoc['targetEntity']);
  1610.                 if (! $assoc['isOwningSide']) {
  1611.                     $assoc $class->associationMappings[$assoc['mappedBy']];
  1612.                     $class $this->em->getClassMetadata($assoc['targetEntity']);
  1613.                 }
  1614.                 $columns $assoc['type'] === ClassMetadata::MANY_TO_MANY
  1615.                     $assoc['relationToTargetKeyColumns']
  1616.                     : $assoc['sourceToTargetKeyColumns'];
  1617.                 foreach ($columns as $column) {
  1618.                     $types[] = PersisterHelper::getTypeOfColumn($column$class$this->em);
  1619.                 }
  1620.                 break;
  1621.             default:
  1622.                 $types[] = null;
  1623.                 break;
  1624.         }
  1625.         if (is_array($value)) {
  1626.             return array_map(static function ($type) {
  1627.                 $type Type::getType($type);
  1628.                 return $type->getBindingType() + Connection::ARRAY_PARAM_OFFSET;
  1629.             }, $types);
  1630.         }
  1631.         return $types;
  1632.     }
  1633.     /**
  1634.      * Retrieves the parameters that identifies a value.
  1635.      *
  1636.      * @param mixed $value
  1637.      *
  1638.      * @return mixed[]
  1639.      */
  1640.     private function getValues($value): array
  1641.     {
  1642.         if (is_array($value)) {
  1643.             $newValue = [];
  1644.             foreach ($value as $itemValue) {
  1645.                 $newValue array_merge($newValue$this->getValues($itemValue));
  1646.             }
  1647.             return [$newValue];
  1648.         }
  1649.         return $this->getIndividualValue($value);
  1650.     }
  1651.     /**
  1652.      * Retrieves an individual parameter value.
  1653.      *
  1654.      * @param mixed $value
  1655.      *
  1656.      * @psalm-return list<mixed>
  1657.      */
  1658.     private function getIndividualValue($value): array
  1659.     {
  1660.         if (! is_object($value)) {
  1661.             return [$value];
  1662.         }
  1663.         if ($value instanceof BackedEnum) {
  1664.             return [$value->value];
  1665.         }
  1666.         $valueClass DefaultProxyClassNameResolver::getClass($value);
  1667.         if ($this->em->getMetadataFactory()->isTransient($valueClass)) {
  1668.             return [$value];
  1669.         }
  1670.         $class $this->em->getClassMetadata($valueClass);
  1671.         if ($class->isIdentifierComposite) {
  1672.             $newValue = [];
  1673.             foreach ($class->getIdentifierValues($value) as $innerValue) {
  1674.                 $newValue array_merge($newValue$this->getValues($innerValue));
  1675.             }
  1676.             return $newValue;
  1677.         }
  1678.         return [$this->em->getUnitOfWork()->getSingleIdentifierValue($value)];
  1679.     }
  1680.     /**
  1681.      * {@inheritDoc}
  1682.      */
  1683.     public function exists($entity, ?Criteria $extraConditions null)
  1684.     {
  1685.         $criteria $this->class->getIdentifierValues($entity);
  1686.         if (! $criteria) {
  1687.             return false;
  1688.         }
  1689.         $alias $this->getSQLTableAlias($this->class->name);
  1690.         $sql 'SELECT 1 '
  1691.              $this->getLockTablesSql(LockMode::NONE)
  1692.              . ' WHERE ' $this->getSelectConditionSQL($criteria);
  1693.         [$params$types] = $this->expandParameters($criteria);
  1694.         if ($extraConditions !== null) {
  1695.             $sql                             .= ' AND ' $this->getSelectConditionCriteriaSQL($extraConditions);
  1696.             [$criteriaParams$criteriaTypes] = $this->expandCriteriaParameters($extraConditions);
  1697.             $params array_merge($params$criteriaParams);
  1698.             $types  array_merge($types$criteriaTypes);
  1699.         }
  1700.         $filterSql $this->generateFilterConditionSQL($this->class$alias);
  1701.         if ($filterSql) {
  1702.             $sql .= ' AND ' $filterSql;
  1703.         }
  1704.         return (bool) $this->conn->fetchOne($sql$params$types);
  1705.     }
  1706.     /**
  1707.      * Generates the appropriate join SQL for the given join column.
  1708.      *
  1709.      * @param array[] $joinColumns The join columns definition of an association.
  1710.      * @psalm-param array<array<string, mixed>> $joinColumns
  1711.      *
  1712.      * @return string LEFT JOIN if one of the columns is nullable, INNER JOIN otherwise.
  1713.      */
  1714.     protected function getJoinSQLForJoinColumns($joinColumns)
  1715.     {
  1716.         // if one of the join columns is nullable, return left join
  1717.         foreach ($joinColumns as $joinColumn) {
  1718.             if (! isset($joinColumn['nullable']) || $joinColumn['nullable']) {
  1719.                 return 'LEFT JOIN';
  1720.             }
  1721.         }
  1722.         return 'INNER JOIN';
  1723.     }
  1724.     /**
  1725.      * @param string $columnName
  1726.      *
  1727.      * @return string
  1728.      */
  1729.     public function getSQLColumnAlias($columnName)
  1730.     {
  1731.         return $this->quoteStrategy->getColumnAlias($columnName$this->currentPersisterContext->sqlAliasCounter++, $this->platform);
  1732.     }
  1733.     /**
  1734.      * Generates the filter SQL for a given entity and table alias.
  1735.      *
  1736.      * @param ClassMetadata $targetEntity     Metadata of the target entity.
  1737.      * @param string        $targetTableAlias The table alias of the joined/selected table.
  1738.      *
  1739.      * @return string The SQL query part to add to a query.
  1740.      */
  1741.     protected function generateFilterConditionSQL(ClassMetadata $targetEntity$targetTableAlias)
  1742.     {
  1743.         $filterClauses = [];
  1744.         foreach ($this->em->getFilters()->getEnabledFilters() as $filter) {
  1745.             $filterExpr $filter->addFilterConstraint($targetEntity$targetTableAlias);
  1746.             if ($filterExpr !== '') {
  1747.                 $filterClauses[] = '(' $filterExpr ')';
  1748.             }
  1749.         }
  1750.         $sql implode(' AND '$filterClauses);
  1751.         return $sql '(' $sql ')' ''// Wrap again to avoid "X or Y and FilterConditionSQL"
  1752.     }
  1753.     /**
  1754.      * Switches persister context according to current query offset/limits
  1755.      *
  1756.      * This is due to the fact that to-many associations cannot be fetch-joined when a limit is involved
  1757.      *
  1758.      * @param int|null $offset
  1759.      * @param int|null $limit
  1760.      *
  1761.      * @return void
  1762.      */
  1763.     protected function switchPersisterContext($offset$limit)
  1764.     {
  1765.         if ($offset === null && $limit === null) {
  1766.             $this->currentPersisterContext $this->noLimitsContext;
  1767.             return;
  1768.         }
  1769.         $this->currentPersisterContext $this->limitsHandlingContext;
  1770.     }
  1771.     /**
  1772.      * @return string[]
  1773.      * @psalm-return list<string>
  1774.      */
  1775.     protected function getClassIdentifiersTypes(ClassMetadata $class): array
  1776.     {
  1777.         $entityManager $this->em;
  1778.         return array_map(
  1779.             static function ($fieldName) use ($class$entityManager): string {
  1780.                 $types PersisterHelper::getTypeOfField($fieldName$class$entityManager);
  1781.                 assert(isset($types[0]));
  1782.                 return $types[0];
  1783.             },
  1784.             $class->identifier
  1785.         );
  1786.     }
  1787. }