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

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