vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php line 769

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