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

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