vendor/doctrine/dbal/src/Connection.php line 936

Open in your IDE?
  1. <?php
  2. namespace Doctrine\DBAL;
  3. use Closure;
  4. use Doctrine\Common\EventManager;
  5. use Doctrine\DBAL\Cache\ArrayResult;
  6. use Doctrine\DBAL\Cache\CacheException;
  7. use Doctrine\DBAL\Cache\QueryCacheProfile;
  8. use Doctrine\DBAL\Driver\API\ExceptionConverter;
  9. use Doctrine\DBAL\Driver\Connection as DriverConnection;
  10. use Doctrine\DBAL\Driver\ServerInfoAwareConnection;
  11. use Doctrine\DBAL\Driver\Statement as DriverStatement;
  12. use Doctrine\DBAL\Event\TransactionBeginEventArgs;
  13. use Doctrine\DBAL\Event\TransactionCommitEventArgs;
  14. use Doctrine\DBAL\Event\TransactionRollBackEventArgs;
  15. use Doctrine\DBAL\Exception\ConnectionLost;
  16. use Doctrine\DBAL\Exception\DriverException;
  17. use Doctrine\DBAL\Exception\InvalidArgumentException;
  18. use Doctrine\DBAL\Platforms\AbstractPlatform;
  19. use Doctrine\DBAL\Query\Expression\ExpressionBuilder;
  20. use Doctrine\DBAL\Query\QueryBuilder;
  21. use Doctrine\DBAL\Schema\AbstractSchemaManager;
  22. use Doctrine\DBAL\Schema\DefaultSchemaManagerFactory;
  23. use Doctrine\DBAL\Schema\LegacySchemaManagerFactory;
  24. use Doctrine\DBAL\Schema\SchemaManagerFactory;
  25. use Doctrine\DBAL\SQL\Parser;
  26. use Doctrine\DBAL\Types\Type;
  27. use Doctrine\Deprecations\Deprecation;
  28. use LogicException;
  29. use SensitiveParameter;
  30. use Throwable;
  31. use Traversable;
  32. use function array_key_exists;
  33. use function assert;
  34. use function count;
  35. use function get_class;
  36. use function implode;
  37. use function is_int;
  38. use function is_string;
  39. use function key;
  40. use function method_exists;
  41. use function sprintf;
  42. /**
  43.  * A database abstraction-level connection that implements features like events, transaction isolation levels,
  44.  * configuration, emulated transaction nesting, lazy connecting and more.
  45.  *
  46.  * @psalm-import-type Params from DriverManager
  47.  * @psalm-consistent-constructor
  48.  */
  49. class Connection
  50. {
  51.     /**
  52.      * Represents an array of ints to be expanded by Doctrine SQL parsing.
  53.      *
  54.      * @deprecated Use {@see ArrayParameterType::INTEGER} instead.
  55.      */
  56.     public const PARAM_INT_ARRAY ArrayParameterType::INTEGER;
  57.     /**
  58.      * Represents an array of strings to be expanded by Doctrine SQL parsing.
  59.      *
  60.      * @deprecated Use {@see ArrayParameterType::STRING} instead.
  61.      */
  62.     public const PARAM_STR_ARRAY ArrayParameterType::STRING;
  63.     /**
  64.      * Represents an array of ascii strings to be expanded by Doctrine SQL parsing.
  65.      *
  66.      * @deprecated Use {@see ArrayParameterType::ASCII} instead.
  67.      */
  68.     public const PARAM_ASCII_STR_ARRAY ArrayParameterType::ASCII;
  69.     /**
  70.      * Offset by which PARAM_* constants are detected as arrays of the param type.
  71.      *
  72.      * @internal Should be used only within the wrapper layer.
  73.      */
  74.     public const ARRAY_PARAM_OFFSET 100;
  75.     /**
  76.      * The wrapped driver connection.
  77.      *
  78.      * @var DriverConnection|null
  79.      */
  80.     protected $_conn;
  81.     /** @var Configuration */
  82.     protected $_config;
  83.     /**
  84.      * @deprecated
  85.      *
  86.      * @var EventManager
  87.      */
  88.     protected $_eventManager;
  89.     /**
  90.      * @deprecated Use {@see createExpressionBuilder()} instead.
  91.      *
  92.      * @var ExpressionBuilder
  93.      */
  94.     protected $_expr;
  95.     /**
  96.      * The current auto-commit mode of this connection.
  97.      */
  98.     private bool $autoCommit true;
  99.     /**
  100.      * The transaction nesting level.
  101.      */
  102.     private int $transactionNestingLevel 0;
  103.     /**
  104.      * The currently active transaction isolation level or NULL before it has been determined.
  105.      *
  106.      * @var TransactionIsolationLevel::*|null
  107.      */
  108.     private $transactionIsolationLevel;
  109.     /**
  110.      * If nested transactions should use savepoints.
  111.      */
  112.     private bool $nestTransactionsWithSavepoints false;
  113.     /**
  114.      * The parameters used during creation of the Connection instance.
  115.      *
  116.      * @var array<string,mixed>
  117.      * @psalm-var Params
  118.      */
  119.     private array $params;
  120.     /**
  121.      * The database platform object used by the connection or NULL before it's initialized.
  122.      */
  123.     private ?AbstractPlatform $platform null;
  124.     private ?ExceptionConverter $exceptionConverter null;
  125.     private ?Parser $parser                         null;
  126.     /**
  127.      * The schema manager.
  128.      *
  129.      * @deprecated Use {@see createSchemaManager()} instead.
  130.      *
  131.      * @var AbstractSchemaManager|null
  132.      */
  133.     protected $_schemaManager;
  134.     /**
  135.      * The used DBAL driver.
  136.      *
  137.      * @var Driver
  138.      */
  139.     protected $_driver;
  140.     /**
  141.      * Flag that indicates whether the current transaction is marked for rollback only.
  142.      */
  143.     private bool $isRollbackOnly false;
  144.     private SchemaManagerFactory $schemaManagerFactory;
  145.     /**
  146.      * Initializes a new instance of the Connection class.
  147.      *
  148.      * @internal The connection can be only instantiated by the driver manager.
  149.      *
  150.      * @param array<string,mixed> $params       The connection parameters.
  151.      * @param Driver              $driver       The driver to use.
  152.      * @param Configuration|null  $config       The configuration, optional.
  153.      * @param EventManager|null   $eventManager The event manager, optional.
  154.      * @psalm-param Params $params
  155.      *
  156.      * @throws Exception
  157.      */
  158.     public function __construct(
  159.         #[SensitiveParameter]
  160.         array $params,
  161.         Driver $driver,
  162.         ?Configuration $config null,
  163.         ?EventManager $eventManager null
  164.     ) {
  165.         $this->_driver $driver;
  166.         $this->params  $params;
  167.         // Create default config and event manager if none given
  168.         $config       ??= new Configuration();
  169.         $eventManager ??= new EventManager();
  170.         $this->_config       $config;
  171.         $this->_eventManager $eventManager;
  172.         if (isset($params['platform'])) {
  173.             if (! $params['platform'] instanceof Platforms\AbstractPlatform) {
  174.                 throw Exception::invalidPlatformType($params['platform']);
  175.             }
  176.             Deprecation::trigger(
  177.                 'doctrine/dbal',
  178.                 'https://github.com/doctrine/dbal/pull/5699',
  179.                 'The "platform" connection parameter is deprecated.'
  180.                     ' Use a driver middleware that would instantiate the platform instead.',
  181.             );
  182.             $this->platform $params['platform'];
  183.             $this->platform->setEventManager($this->_eventManager);
  184.             $this->platform->setDisableTypeComments($config->getDisableTypeComments());
  185.         }
  186.         $this->_expr $this->createExpressionBuilder();
  187.         $this->autoCommit $config->getAutoCommit();
  188.         $schemaManagerFactory $config->getSchemaManagerFactory();
  189.         if ($schemaManagerFactory === null) {
  190.             Deprecation::trigger(
  191.                 'doctrine/dbal',
  192.                 'https://github.com/doctrine/dbal/issues/5812',
  193.                 'Not configuring a schema manager factory is deprecated.'
  194.                     ' Use %s which is going to be the default in DBAL 4.',
  195.                 DefaultSchemaManagerFactory::class,
  196.             );
  197.             $schemaManagerFactory = new LegacySchemaManagerFactory();
  198.         }
  199.         $this->schemaManagerFactory $schemaManagerFactory;
  200.     }
  201.     /**
  202.      * Gets the parameters used during instantiation.
  203.      *
  204.      * @internal
  205.      *
  206.      * @return array<string,mixed>
  207.      * @psalm-return Params
  208.      */
  209.     public function getParams()
  210.     {
  211.         return $this->params;
  212.     }
  213.     /**
  214.      * Gets the name of the currently selected database.
  215.      *
  216.      * @return string|null The name of the database or NULL if a database is not selected.
  217.      *                     The platforms which don't support the concept of a database (e.g. embedded databases)
  218.      *                     must always return a string as an indicator of an implicitly selected database.
  219.      *
  220.      * @throws Exception
  221.      */
  222.     public function getDatabase()
  223.     {
  224.         $platform $this->getDatabasePlatform();
  225.         $query    $platform->getDummySelectSQL($platform->getCurrentDatabaseExpression());
  226.         $database $this->fetchOne($query);
  227.         assert(is_string($database) || $database === null);
  228.         return $database;
  229.     }
  230.     /**
  231.      * Gets the DBAL driver instance.
  232.      *
  233.      * @return Driver
  234.      */
  235.     public function getDriver()
  236.     {
  237.         return $this->_driver;
  238.     }
  239.     /**
  240.      * Gets the Configuration used by the Connection.
  241.      *
  242.      * @return Configuration
  243.      */
  244.     public function getConfiguration()
  245.     {
  246.         return $this->_config;
  247.     }
  248.     /**
  249.      * Gets the EventManager used by the Connection.
  250.      *
  251.      * @deprecated
  252.      *
  253.      * @return EventManager
  254.      */
  255.     public function getEventManager()
  256.     {
  257.         Deprecation::triggerIfCalledFromOutside(
  258.             'doctrine/dbal',
  259.             'https://github.com/doctrine/dbal/issues/5784',
  260.             '%s is deprecated.',
  261.             __METHOD__,
  262.         );
  263.         return $this->_eventManager;
  264.     }
  265.     /**
  266.      * Gets the DatabasePlatform for the connection.
  267.      *
  268.      * @return AbstractPlatform
  269.      *
  270.      * @throws Exception
  271.      */
  272.     public function getDatabasePlatform()
  273.     {
  274.         if ($this->platform === null) {
  275.             $this->platform $this->detectDatabasePlatform();
  276.             $this->platform->setEventManager($this->_eventManager);
  277.             $this->platform->setDisableTypeComments($this->_config->getDisableTypeComments());
  278.         }
  279.         return $this->platform;
  280.     }
  281.     /**
  282.      * Creates an expression builder for the connection.
  283.      */
  284.     public function createExpressionBuilder(): ExpressionBuilder
  285.     {
  286.         return new ExpressionBuilder($this);
  287.     }
  288.     /**
  289.      * Gets the ExpressionBuilder for the connection.
  290.      *
  291.      * @deprecated Use {@see createExpressionBuilder()} instead.
  292.      *
  293.      * @return ExpressionBuilder
  294.      */
  295.     public function getExpressionBuilder()
  296.     {
  297.         Deprecation::triggerIfCalledFromOutside(
  298.             'doctrine/dbal',
  299.             'https://github.com/doctrine/dbal/issues/4515',
  300.             'Connection::getExpressionBuilder() is deprecated,'
  301.                 ' use Connection::createExpressionBuilder() instead.',
  302.         );
  303.         return $this->_expr;
  304.     }
  305.     /**
  306.      * Establishes the connection with the database.
  307.      *
  308.      * @internal This method will be made protected in DBAL 4.0.
  309.      *
  310.      * @return bool TRUE if the connection was successfully established, FALSE if
  311.      *              the connection is already open.
  312.      *
  313.      * @throws Exception
  314.      *
  315.      * @psalm-assert !null $this->_conn
  316.      */
  317.     public function connect()
  318.     {
  319.         Deprecation::triggerIfCalledFromOutside(
  320.             'doctrine/dbal',
  321.             'https://github.com/doctrine/dbal/issues/4966',
  322.             'Public access to Connection::connect() is deprecated.',
  323.         );
  324.         if ($this->_conn !== null) {
  325.             return false;
  326.         }
  327.         try {
  328.             $this->_conn $this->_driver->connect($this->params);
  329.         } catch (Driver\Exception $e) {
  330.             throw $this->convertException($e);
  331.         }
  332.         if ($this->autoCommit === false) {
  333.             $this->beginTransaction();
  334.         }
  335.         if ($this->_eventManager->hasListeners(Events::postConnect)) {
  336.             Deprecation::trigger(
  337.                 'doctrine/dbal',
  338.                 'https://github.com/doctrine/dbal/issues/5784',
  339.                 'Subscribing to %s events is deprecated. Implement a middleware instead.',
  340.                 Events::postConnect,
  341.             );
  342.             $eventArgs = new Event\ConnectionEventArgs($this);
  343.             $this->_eventManager->dispatchEvent(Events::postConnect$eventArgs);
  344.         }
  345.         return true;
  346.     }
  347.     /**
  348.      * Detects and sets the database platform.
  349.      *
  350.      * Evaluates custom platform class and version in order to set the correct platform.
  351.      *
  352.      * @throws Exception If an invalid platform was specified for this connection.
  353.      */
  354.     private function detectDatabasePlatform(): AbstractPlatform
  355.     {
  356.         $version $this->getDatabasePlatformVersion();
  357.         if ($version !== null) {
  358.             assert($this->_driver instanceof VersionAwarePlatformDriver);
  359.             return $this->_driver->createDatabasePlatformForVersion($version);
  360.         }
  361.         return $this->_driver->getDatabasePlatform();
  362.     }
  363.     /**
  364.      * Returns the version of the related platform if applicable.
  365.      *
  366.      * Returns null if either the driver is not capable to create version
  367.      * specific platform instances, no explicit server version was specified
  368.      * or the underlying driver connection cannot determine the platform
  369.      * version without having to query it (performance reasons).
  370.      *
  371.      * @return string|null
  372.      *
  373.      * @throws Throwable
  374.      */
  375.     private function getDatabasePlatformVersion()
  376.     {
  377.         // Driver does not support version specific platforms.
  378.         if (! $this->_driver instanceof VersionAwarePlatformDriver) {
  379.             return null;
  380.         }
  381.         // Explicit platform version requested (supersedes auto-detection).
  382.         if (isset($this->params['serverVersion'])) {
  383.             return $this->params['serverVersion'];
  384.         }
  385.         if (isset($this->params['primary']) && isset($this->params['primary']['serverVersion'])) {
  386.             return $this->params['primary']['serverVersion'];
  387.         }
  388.         // If not connected, we need to connect now to determine the platform version.
  389.         if ($this->_conn === null) {
  390.             try {
  391.                 $this->connect();
  392.             } catch (Exception $originalException) {
  393.                 if (! isset($this->params['dbname'])) {
  394.                     throw $originalException;
  395.                 }
  396.                 Deprecation::trigger(
  397.                     'doctrine/dbal',
  398.                     'https://github.com/doctrine/dbal/pull/5707',
  399.                     'Relying on a fallback connection used to determine the database platform while connecting'
  400.                         ' to a non-existing database is deprecated. Either use an existing database name in'
  401.                         ' connection parameters or omit the database name if the platform'
  402.                         ' and the server configuration allow that.',
  403.                 );
  404.                 // The database to connect to might not yet exist.
  405.                 // Retry detection without database name connection parameter.
  406.                 $params $this->params;
  407.                 unset($this->params['dbname']);
  408.                 try {
  409.                     $this->connect();
  410.                 } catch (Exception $fallbackException) {
  411.                     // Either the platform does not support database-less connections
  412.                     // or something else went wrong.
  413.                     throw $originalException;
  414.                 } finally {
  415.                     $this->params $params;
  416.                 }
  417.                 $serverVersion $this->getServerVersion();
  418.                 // Close "temporary" connection to allow connecting to the real database again.
  419.                 $this->close();
  420.                 return $serverVersion;
  421.             }
  422.         }
  423.         return $this->getServerVersion();
  424.     }
  425.     /**
  426.      * Returns the database server version if the underlying driver supports it.
  427.      *
  428.      * @return string|null
  429.      *
  430.      * @throws Exception
  431.      */
  432.     private function getServerVersion()
  433.     {
  434.         $connection $this->getWrappedConnection();
  435.         // Automatic platform version detection.
  436.         if ($connection instanceof ServerInfoAwareConnection) {
  437.             try {
  438.                 return $connection->getServerVersion();
  439.             } catch (Driver\Exception $e) {
  440.                 throw $this->convertException($e);
  441.             }
  442.         }
  443.         Deprecation::trigger(
  444.             'doctrine/dbal',
  445.             'https://github.com/doctrine/dbal/pull/4750',
  446.             'Not implementing the ServerInfoAwareConnection interface in %s is deprecated',
  447.             get_class($connection),
  448.         );
  449.         // Unable to detect platform version.
  450.         return null;
  451.     }
  452.     /**
  453.      * Returns the current auto-commit mode for this connection.
  454.      *
  455.      * @see    setAutoCommit
  456.      *
  457.      * @return bool True if auto-commit mode is currently enabled for this connection, false otherwise.
  458.      */
  459.     public function isAutoCommit()
  460.     {
  461.         return $this->autoCommit === true;
  462.     }
  463.     /**
  464.      * Sets auto-commit mode for this connection.
  465.      *
  466.      * If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual
  467.      * transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either
  468.      * the method commit or the method rollback. By default, new connections are in auto-commit mode.
  469.      *
  470.      * NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is
  471.      * committed. If this method is called and the auto-commit mode is not changed, the call is a no-op.
  472.      *
  473.      * @see   isAutoCommit
  474.      *
  475.      * @param bool $autoCommit True to enable auto-commit mode; false to disable it.
  476.      *
  477.      * @return void
  478.      */
  479.     public function setAutoCommit($autoCommit)
  480.     {
  481.         $autoCommit = (bool) $autoCommit;
  482.         // Mode not changed, no-op.
  483.         if ($autoCommit === $this->autoCommit) {
  484.             return;
  485.         }
  486.         $this->autoCommit $autoCommit;
  487.         // Commit all currently active transactions if any when switching auto-commit mode.
  488.         if ($this->_conn === null || $this->transactionNestingLevel === 0) {
  489.             return;
  490.         }
  491.         $this->commitAll();
  492.     }
  493.     /**
  494.      * Prepares and executes an SQL query and returns the first row of the result
  495.      * as an associative array.
  496.      *
  497.      * @param string                                                               $query  SQL query
  498.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  499.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  500.      *
  501.      * @return array<string, mixed>|false False is returned if no rows are found.
  502.      *
  503.      * @throws Exception
  504.      */
  505.     public function fetchAssociative(string $query, array $params = [], array $types = [])
  506.     {
  507.         return $this->executeQuery($query$params$types)->fetchAssociative();
  508.     }
  509.     /**
  510.      * Prepares and executes an SQL query and returns the first row of the result
  511.      * as a numerically indexed array.
  512.      *
  513.      * @param string                                                               $query  SQL query
  514.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  515.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  516.      *
  517.      * @return list<mixed>|false False is returned if no rows are found.
  518.      *
  519.      * @throws Exception
  520.      */
  521.     public function fetchNumeric(string $query, array $params = [], array $types = [])
  522.     {
  523.         return $this->executeQuery($query$params$types)->fetchNumeric();
  524.     }
  525.     /**
  526.      * Prepares and executes an SQL query and returns the value of a single column
  527.      * of the first row of the result.
  528.      *
  529.      * @param string                                                               $query  SQL query
  530.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  531.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  532.      *
  533.      * @return mixed|false False is returned if no rows are found.
  534.      *
  535.      * @throws Exception
  536.      */
  537.     public function fetchOne(string $query, array $params = [], array $types = [])
  538.     {
  539.         return $this->executeQuery($query$params$types)->fetchOne();
  540.     }
  541.     /**
  542.      * Whether an actual connection to the database is established.
  543.      *
  544.      * @return bool
  545.      */
  546.     public function isConnected()
  547.     {
  548.         return $this->_conn !== null;
  549.     }
  550.     /**
  551.      * Checks whether a transaction is currently active.
  552.      *
  553.      * @return bool TRUE if a transaction is currently active, FALSE otherwise.
  554.      */
  555.     public function isTransactionActive()
  556.     {
  557.         return $this->transactionNestingLevel 0;
  558.     }
  559.     /**
  560.      * Adds condition based on the criteria to the query components
  561.      *
  562.      * @param array<string,mixed> $criteria   Map of key columns to their values
  563.      * @param string[]            $columns    Column names
  564.      * @param mixed[]             $values     Column values
  565.      * @param string[]            $conditions Key conditions
  566.      *
  567.      * @throws Exception
  568.      */
  569.     private function addCriteriaCondition(
  570.         array $criteria,
  571.         array &$columns,
  572.         array &$values,
  573.         array &$conditions
  574.     ): void {
  575.         $platform $this->getDatabasePlatform();
  576.         foreach ($criteria as $columnName => $value) {
  577.             if ($value === null) {
  578.                 $conditions[] = $platform->getIsNullExpression($columnName);
  579.                 continue;
  580.             }
  581.             $columns[]    = $columnName;
  582.             $values[]     = $value;
  583.             $conditions[] = $columnName ' = ?';
  584.         }
  585.     }
  586.     /**
  587.      * Executes an SQL DELETE statement on a table.
  588.      *
  589.      * Table expression and columns are not escaped and are not safe for user-input.
  590.      *
  591.      * @param string                                                               $table    Table name
  592.      * @param array<string, mixed>                                                 $criteria Deletion criteria
  593.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types    Parameter types
  594.      *
  595.      * @return int|string The number of affected rows.
  596.      *
  597.      * @throws Exception
  598.      */
  599.     public function delete($table, array $criteria, array $types = [])
  600.     {
  601.         if (count($criteria) === 0) {
  602.             throw InvalidArgumentException::fromEmptyCriteria();
  603.         }
  604.         $columns $values $conditions = [];
  605.         $this->addCriteriaCondition($criteria$columns$values$conditions);
  606.         return $this->executeStatement(
  607.             'DELETE FROM ' $table ' WHERE ' implode(' AND '$conditions),
  608.             $values,
  609.             is_string(key($types)) ? $this->extractTypeValues($columns$types) : $types,
  610.         );
  611.     }
  612.     /**
  613.      * Closes the connection.
  614.      *
  615.      * @return void
  616.      */
  617.     public function close()
  618.     {
  619.         $this->_conn                   null;
  620.         $this->transactionNestingLevel 0;
  621.     }
  622.     /**
  623.      * Sets the transaction isolation level.
  624.      *
  625.      * @param TransactionIsolationLevel::* $level The level to set.
  626.      *
  627.      * @return int|string
  628.      *
  629.      * @throws Exception
  630.      */
  631.     public function setTransactionIsolation($level)
  632.     {
  633.         $this->transactionIsolationLevel $level;
  634.         return $this->executeStatement($this->getDatabasePlatform()->getSetTransactionIsolationSQL($level));
  635.     }
  636.     /**
  637.      * Gets the currently active transaction isolation level.
  638.      *
  639.      * @return TransactionIsolationLevel::* The current transaction isolation level.
  640.      *
  641.      * @throws Exception
  642.      */
  643.     public function getTransactionIsolation()
  644.     {
  645.         return $this->transactionIsolationLevel ??= $this->getDatabasePlatform()->getDefaultTransactionIsolationLevel();
  646.     }
  647.     /**
  648.      * Executes an SQL UPDATE statement on a table.
  649.      *
  650.      * Table expression and columns are not escaped and are not safe for user-input.
  651.      *
  652.      * @param string                                                               $table    Table name
  653.      * @param array<string, mixed>                                                 $data     Column-value pairs
  654.      * @param array<string, mixed>                                                 $criteria Update criteria
  655.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types    Parameter types
  656.      *
  657.      * @return int|string The number of affected rows.
  658.      *
  659.      * @throws Exception
  660.      */
  661.     public function update($table, array $data, array $criteria, array $types = [])
  662.     {
  663.         $columns $values $conditions $set = [];
  664.         foreach ($data as $columnName => $value) {
  665.             $columns[] = $columnName;
  666.             $values[]  = $value;
  667.             $set[]     = $columnName ' = ?';
  668.         }
  669.         $this->addCriteriaCondition($criteria$columns$values$conditions);
  670.         if (is_string(key($types))) {
  671.             $types $this->extractTypeValues($columns$types);
  672.         }
  673.         $sql 'UPDATE ' $table ' SET ' implode(', '$set)
  674.                 . ' WHERE ' implode(' AND '$conditions);
  675.         return $this->executeStatement($sql$values$types);
  676.     }
  677.     /**
  678.      * Inserts a table row with specified data.
  679.      *
  680.      * Table expression and columns are not escaped and are not safe for user-input.
  681.      *
  682.      * @param string                                                               $table Table name
  683.      * @param array<string, mixed>                                                 $data  Column-value pairs
  684.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types Parameter types
  685.      *
  686.      * @return int|string The number of affected rows.
  687.      *
  688.      * @throws Exception
  689.      */
  690.     public function insert($table, array $data, array $types = [])
  691.     {
  692.         if (count($data) === 0) {
  693.             return $this->executeStatement('INSERT INTO ' $table ' () VALUES ()');
  694.         }
  695.         $columns = [];
  696.         $values  = [];
  697.         $set     = [];
  698.         foreach ($data as $columnName => $value) {
  699.             $columns[] = $columnName;
  700.             $values[]  = $value;
  701.             $set[]     = '?';
  702.         }
  703.         return $this->executeStatement(
  704.             'INSERT INTO ' $table ' (' implode(', '$columns) . ')' .
  705.             ' VALUES (' implode(', '$set) . ')',
  706.             $values,
  707.             is_string(key($types)) ? $this->extractTypeValues($columns$types) : $types,
  708.         );
  709.     }
  710.     /**
  711.      * Extract ordered type list from an ordered column list and type map.
  712.      *
  713.      * @param array<int, string>                                                   $columnList
  714.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types
  715.      *
  716.      * @return array<int, int|string|Type|null>|array<string, int|string|Type|null>
  717.      */
  718.     private function extractTypeValues(array $columnList, array $types): array
  719.     {
  720.         $typeValues = [];
  721.         foreach ($columnList as $columnName) {
  722.             $typeValues[] = $types[$columnName] ?? ParameterType::STRING;
  723.         }
  724.         return $typeValues;
  725.     }
  726.     /**
  727.      * Quotes a string so it can be safely used as a table or column name, even if
  728.      * it is a reserved name.
  729.      *
  730.      * Delimiting style depends on the underlying database platform that is being used.
  731.      *
  732.      * NOTE: Just because you CAN use quoted identifiers does not mean
  733.      * you SHOULD use them. In general, they end up causing way more
  734.      * problems than they solve.
  735.      *
  736.      * @param string $str The name to be quoted.
  737.      *
  738.      * @return string The quoted name.
  739.      */
  740.     public function quoteIdentifier($str)
  741.     {
  742.         return $this->getDatabasePlatform()->quoteIdentifier($str);
  743.     }
  744.     /**
  745.      * The usage of this method is discouraged. Use prepared statements
  746.      * or {@see AbstractPlatform::quoteStringLiteral()} instead.
  747.      *
  748.      * @param mixed                $value
  749.      * @param int|string|Type|null $type
  750.      *
  751.      * @return mixed
  752.      */
  753.     public function quote($value$type ParameterType::STRING)
  754.     {
  755.         $connection $this->getWrappedConnection();
  756.         [$value$bindingType] = $this->getBindingInfo($value$type);
  757.         return $connection->quote($value$bindingType);
  758.     }
  759.     /**
  760.      * Prepares and executes an SQL query and returns the result as an array of numeric arrays.
  761.      *
  762.      * @param string                                                               $query  SQL query
  763.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  764.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  765.      *
  766.      * @return list<list<mixed>>
  767.      *
  768.      * @throws Exception
  769.      */
  770.     public function fetchAllNumeric(string $query, array $params = [], array $types = []): array
  771.     {
  772.         return $this->executeQuery($query$params$types)->fetchAllNumeric();
  773.     }
  774.     /**
  775.      * Prepares and executes an SQL query and returns the result as an array of associative arrays.
  776.      *
  777.      * @param string                                                               $query  SQL query
  778.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  779.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  780.      *
  781.      * @return list<array<string,mixed>>
  782.      *
  783.      * @throws Exception
  784.      */
  785.     public function fetchAllAssociative(string $query, array $params = [], array $types = []): array
  786.     {
  787.         return $this->executeQuery($query$params$types)->fetchAllAssociative();
  788.     }
  789.     /**
  790.      * Prepares and executes an SQL query and returns the result as an associative array with the keys
  791.      * mapped to the first column and the values mapped to the second column.
  792.      *
  793.      * @param string                                                               $query  SQL query
  794.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  795.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  796.      *
  797.      * @return array<mixed,mixed>
  798.      *
  799.      * @throws Exception
  800.      */
  801.     public function fetchAllKeyValue(string $query, array $params = [], array $types = []): array
  802.     {
  803.         return $this->executeQuery($query$params$types)->fetchAllKeyValue();
  804.     }
  805.     /**
  806.      * Prepares and executes an SQL query and returns the result as an associative array with the keys mapped
  807.      * to the first column and the values being an associative array representing the rest of the columns
  808.      * and their values.
  809.      *
  810.      * @param string                                                               $query  SQL query
  811.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  812.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  813.      *
  814.      * @return array<mixed,array<string,mixed>>
  815.      *
  816.      * @throws Exception
  817.      */
  818.     public function fetchAllAssociativeIndexed(string $query, array $params = [], array $types = []): array
  819.     {
  820.         return $this->executeQuery($query$params$types)->fetchAllAssociativeIndexed();
  821.     }
  822.     /**
  823.      * Prepares and executes an SQL query and returns the result as an array of the first column values.
  824.      *
  825.      * @param string                                                               $query  SQL query
  826.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  827.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  828.      *
  829.      * @return list<mixed>
  830.      *
  831.      * @throws Exception
  832.      */
  833.     public function fetchFirstColumn(string $query, array $params = [], array $types = []): array
  834.     {
  835.         return $this->executeQuery($query$params$types)->fetchFirstColumn();
  836.     }
  837.     /**
  838.      * Prepares and executes an SQL query and returns the result as an iterator over rows represented as numeric arrays.
  839.      *
  840.      * @param string                                                               $query  SQL query
  841.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  842.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  843.      *
  844.      * @return Traversable<int,list<mixed>>
  845.      *
  846.      * @throws Exception
  847.      */
  848.     public function iterateNumeric(string $query, array $params = [], array $types = []): Traversable
  849.     {
  850.         return $this->executeQuery($query$params$types)->iterateNumeric();
  851.     }
  852.     /**
  853.      * Prepares and executes an SQL query and returns the result as an iterator over rows represented
  854.      * as associative arrays.
  855.      *
  856.      * @param string                                                               $query  SQL query
  857.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  858.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  859.      *
  860.      * @return Traversable<int,array<string,mixed>>
  861.      *
  862.      * @throws Exception
  863.      */
  864.     public function iterateAssociative(string $query, array $params = [], array $types = []): Traversable
  865.     {
  866.         return $this->executeQuery($query$params$types)->iterateAssociative();
  867.     }
  868.     /**
  869.      * Prepares and executes an SQL query and returns the result as an iterator with the keys
  870.      * mapped to the first column and the values mapped to the second column.
  871.      *
  872.      * @param string                                                               $query  SQL query
  873.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  874.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  875.      *
  876.      * @return Traversable<mixed,mixed>
  877.      *
  878.      * @throws Exception
  879.      */
  880.     public function iterateKeyValue(string $query, array $params = [], array $types = []): Traversable
  881.     {
  882.         return $this->executeQuery($query$params$types)->iterateKeyValue();
  883.     }
  884.     /**
  885.      * Prepares and executes an SQL query and returns the result as an iterator with the keys mapped
  886.      * to the first column and the values being an associative array representing the rest of the columns
  887.      * and their values.
  888.      *
  889.      * @param string                                           $query  SQL query
  890.      * @param list<mixed>|array<string, mixed>                 $params Query parameters
  891.      * @param array<int, int|string>|array<string, int|string> $types  Parameter types
  892.      *
  893.      * @return Traversable<mixed,array<string,mixed>>
  894.      *
  895.      * @throws Exception
  896.      */
  897.     public function iterateAssociativeIndexed(string $query, array $params = [], array $types = []): Traversable
  898.     {
  899.         return $this->executeQuery($query$params$types)->iterateAssociativeIndexed();
  900.     }
  901.     /**
  902.      * Prepares and executes an SQL query and returns the result as an iterator over the first column values.
  903.      *
  904.      * @param string                                                               $query  SQL query
  905.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  906.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  907.      *
  908.      * @return Traversable<int,mixed>
  909.      *
  910.      * @throws Exception
  911.      */
  912.     public function iterateColumn(string $query, array $params = [], array $types = []): Traversable
  913.     {
  914.         return $this->executeQuery($query$params$types)->iterateColumn();
  915.     }
  916.     /**
  917.      * Prepares an SQL statement.
  918.      *
  919.      * @param string $sql The SQL statement to prepare.
  920.      *
  921.      * @throws Exception
  922.      */
  923.     public function prepare(string $sql): Statement
  924.     {
  925.         $connection $this->getWrappedConnection();
  926.         try {
  927.             $statement $connection->prepare($sql);
  928.         } catch (Driver\Exception $e) {
  929.             throw $this->convertExceptionDuringQuery($e$sql);
  930.         }
  931.         return new Statement($this$statement$sql);
  932.     }
  933.     /**
  934.      * Executes an, optionally parameterized, SQL query.
  935.      *
  936.      * If the query is parametrized, a prepared statement is used.
  937.      * If an SQLLogger is configured, the execution is logged.
  938.      *
  939.      * @param string                                                               $sql    SQL query
  940.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  941.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  942.      *
  943.      * @throws Exception
  944.      */
  945.     public function executeQuery(
  946.         string $sql,
  947.         array $params = [],
  948.         $types = [],
  949.         ?QueryCacheProfile $qcp null
  950.     ): Result {
  951.         if ($qcp !== null) {
  952.             return $this->executeCacheQuery($sql$params$types$qcp);
  953.         }
  954.         $connection $this->getWrappedConnection();
  955.         $logger $this->_config->getSQLLogger();
  956.         if ($logger !== null) {
  957.             $logger->startQuery($sql$params$types);
  958.         }
  959.         try {
  960.             if (count($params) > 0) {
  961.                 if ($this->needsArrayParameterConversion($params$types)) {
  962.                     [$sql$params$types] = $this->expandArrayParameters($sql$params$types);
  963.                 }
  964.                 $stmt $connection->prepare($sql);
  965.                 $this->bindParameters($stmt$params$types);
  966.                 $result $stmt->execute();
  967.             } else {
  968.                 $result $connection->query($sql);
  969.             }
  970.             return new Result($result$this);
  971.         } catch (Driver\Exception $e) {
  972.             throw $this->convertExceptionDuringQuery($e$sql$params$types);
  973.         } finally {
  974.             if ($logger !== null) {
  975.                 $logger->stopQuery();
  976.             }
  977.         }
  978.     }
  979.     /**
  980.      * Executes a caching query.
  981.      *
  982.      * @param string                                                               $sql    SQL query
  983.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  984.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  985.      *
  986.      * @throws CacheException
  987.      * @throws Exception
  988.      */
  989.     public function executeCacheQuery($sql$params$typesQueryCacheProfile $qcp): Result
  990.     {
  991.         $resultCache $qcp->getResultCache() ?? $this->_config->getResultCache();
  992.         if ($resultCache === null) {
  993.             throw CacheException::noResultDriverConfigured();
  994.         }
  995.         $connectionParams $this->params;
  996.         unset($connectionParams['platform'], $connectionParams['password'], $connectionParams['url']);
  997.         [$cacheKey$realKey] = $qcp->generateCacheKeys($sql$params$types$connectionParams);
  998.         $item $resultCache->getItem($cacheKey);
  999.         if ($item->isHit()) {
  1000.             $value $item->get();
  1001.             if (isset($value[$realKey])) {
  1002.                 return new Result(new ArrayResult($value[$realKey]), $this);
  1003.             }
  1004.         } else {
  1005.             $value = [];
  1006.         }
  1007.         $data $this->fetchAllAssociative($sql$params$types);
  1008.         $value[$realKey] = $data;
  1009.         $item->set($value);
  1010.         $lifetime $qcp->getLifetime();
  1011.         if ($lifetime 0) {
  1012.             $item->expiresAfter($lifetime);
  1013.         }
  1014.         $resultCache->save($item);
  1015.         return new Result(new ArrayResult($data), $this);
  1016.     }
  1017.     /**
  1018.      * Executes an SQL statement with the given parameters and returns the number of affected rows.
  1019.      *
  1020.      * Could be used for:
  1021.      *  - DML statements: INSERT, UPDATE, DELETE, etc.
  1022.      *  - DDL statements: CREATE, DROP, ALTER, etc.
  1023.      *  - DCL statements: GRANT, REVOKE, etc.
  1024.      *  - Session control statements: ALTER SESSION, SET, DECLARE, etc.
  1025.      *  - Other statements that don't yield a row set.
  1026.      *
  1027.      * This method supports PDO binding types as well as DBAL mapping types.
  1028.      *
  1029.      * @param string                                                               $sql    SQL statement
  1030.      * @param list<mixed>|array<string, mixed>                                     $params Statement parameters
  1031.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  1032.      *
  1033.      * @return int|string The number of affected rows.
  1034.      *
  1035.      * @throws Exception
  1036.      */
  1037.     public function executeStatement($sql, array $params = [], array $types = [])
  1038.     {
  1039.         $connection $this->getWrappedConnection();
  1040.         $logger $this->_config->getSQLLogger();
  1041.         if ($logger !== null) {
  1042.             $logger->startQuery($sql$params$types);
  1043.         }
  1044.         try {
  1045.             if (count($params) > 0) {
  1046.                 if ($this->needsArrayParameterConversion($params$types)) {
  1047.                     [$sql$params$types] = $this->expandArrayParameters($sql$params$types);
  1048.                 }
  1049.                 $stmt $connection->prepare($sql);
  1050.                 $this->bindParameters($stmt$params$types);
  1051.                 return $stmt->execute()
  1052.                     ->rowCount();
  1053.             }
  1054.             return $connection->exec($sql);
  1055.         } catch (Driver\Exception $e) {
  1056.             throw $this->convertExceptionDuringQuery($e$sql$params$types);
  1057.         } finally {
  1058.             if ($logger !== null) {
  1059.                 $logger->stopQuery();
  1060.             }
  1061.         }
  1062.     }
  1063.     /**
  1064.      * Returns the current transaction nesting level.
  1065.      *
  1066.      * @return int The nesting level. A value of 0 means there's no active transaction.
  1067.      */
  1068.     public function getTransactionNestingLevel()
  1069.     {
  1070.         return $this->transactionNestingLevel;
  1071.     }
  1072.     /**
  1073.      * Returns the ID of the last inserted row, or the last value from a sequence object,
  1074.      * depending on the underlying driver.
  1075.      *
  1076.      * Note: This method may not return a meaningful or consistent result across different drivers,
  1077.      * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
  1078.      * columns or sequences.
  1079.      *
  1080.      * @param string|null $name Name of the sequence object from which the ID should be returned.
  1081.      *
  1082.      * @return string|int|false A string representation of the last inserted ID.
  1083.      *
  1084.      * @throws Exception
  1085.      */
  1086.     public function lastInsertId($name null)
  1087.     {
  1088.         if ($name !== null) {
  1089.             Deprecation::trigger(
  1090.                 'doctrine/dbal',
  1091.                 'https://github.com/doctrine/dbal/issues/4687',
  1092.                 'The usage of Connection::lastInsertId() with a sequence name is deprecated.',
  1093.             );
  1094.         }
  1095.         try {
  1096.             return $this->getWrappedConnection()->lastInsertId($name);
  1097.         } catch (Driver\Exception $e) {
  1098.             throw $this->convertException($e);
  1099.         }
  1100.     }
  1101.     /**
  1102.      * Executes a function in a transaction.
  1103.      *
  1104.      * The function gets passed this Connection instance as an (optional) parameter.
  1105.      *
  1106.      * If an exception occurs during execution of the function or transaction commit,
  1107.      * the transaction is rolled back and the exception re-thrown.
  1108.      *
  1109.      * @param Closure(self):T $func The function to execute transactionally.
  1110.      *
  1111.      * @return T The value returned by $func
  1112.      *
  1113.      * @throws Throwable
  1114.      *
  1115.      * @template T
  1116.      */
  1117.     public function transactional(Closure $func)
  1118.     {
  1119.         $this->beginTransaction();
  1120.         try {
  1121.             $res $func($this);
  1122.             $this->commit();
  1123.             return $res;
  1124.         } catch (Throwable $e) {
  1125.             $this->rollBack();
  1126.             throw $e;
  1127.         }
  1128.     }
  1129.     /**
  1130.      * Sets if nested transactions should use savepoints.
  1131.      *
  1132.      * @param bool $nestTransactionsWithSavepoints
  1133.      *
  1134.      * @return void
  1135.      *
  1136.      * @throws Exception
  1137.      */
  1138.     public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints)
  1139.     {
  1140.         if (! $nestTransactionsWithSavepoints) {
  1141.             Deprecation::trigger(
  1142.                 'doctrine/dbal',
  1143.                 'https://github.com/doctrine/dbal/pull/5383',
  1144.                 <<<'DEPRECATION'
  1145.                 Nesting transactions without enabling savepoints is deprecated.
  1146.                 Call %s::setNestTransactionsWithSavepoints(true) to enable savepoints.
  1147.                 DEPRECATION,
  1148.                 self::class,
  1149.             );
  1150.         }
  1151.         if ($this->transactionNestingLevel 0) {
  1152.             throw ConnectionException::mayNotAlterNestedTransactionWithSavepointsInTransaction();
  1153.         }
  1154.         if (! $this->getDatabasePlatform()->supportsSavepoints()) {
  1155.             throw ConnectionException::savepointsNotSupported();
  1156.         }
  1157.         $this->nestTransactionsWithSavepoints = (bool) $nestTransactionsWithSavepoints;
  1158.     }
  1159.     /**
  1160.      * Gets if nested transactions should use savepoints.
  1161.      *
  1162.      * @return bool
  1163.      */
  1164.     public function getNestTransactionsWithSavepoints()
  1165.     {
  1166.         return $this->nestTransactionsWithSavepoints;
  1167.     }
  1168.     /**
  1169.      * Returns the savepoint name to use for nested transactions.
  1170.      *
  1171.      * @return string
  1172.      */
  1173.     protected function _getNestedTransactionSavePointName()
  1174.     {
  1175.         return 'DOCTRINE2_SAVEPOINT_' $this->transactionNestingLevel;
  1176.     }
  1177.     /**
  1178.      * @return bool
  1179.      *
  1180.      * @throws Exception
  1181.      */
  1182.     public function beginTransaction()
  1183.     {
  1184.         $connection $this->getWrappedConnection();
  1185.         ++$this->transactionNestingLevel;
  1186.         $logger $this->_config->getSQLLogger();
  1187.         if ($this->transactionNestingLevel === 1) {
  1188.             if ($logger !== null) {
  1189.                 $logger->startQuery('"START TRANSACTION"');
  1190.             }
  1191.             $connection->beginTransaction();
  1192.             if ($logger !== null) {
  1193.                 $logger->stopQuery();
  1194.             }
  1195.         } elseif ($this->nestTransactionsWithSavepoints) {
  1196.             if ($logger !== null) {
  1197.                 $logger->startQuery('"SAVEPOINT"');
  1198.             }
  1199.             $this->createSavepoint($this->_getNestedTransactionSavePointName());
  1200.             if ($logger !== null) {
  1201.                 $logger->stopQuery();
  1202.             }
  1203.         } else {
  1204.             Deprecation::trigger(
  1205.                 'doctrine/dbal',
  1206.                 'https://github.com/doctrine/dbal/pull/5383',
  1207.                 <<<'DEPRECATION'
  1208.                 Nesting transactions without enabling savepoints is deprecated.
  1209.                 Call %s::setNestTransactionsWithSavepoints(true) to enable savepoints.
  1210.                 DEPRECATION,
  1211.                 self::class,
  1212.             );
  1213.         }
  1214.         $eventManager $this->getEventManager();
  1215.         if ($eventManager->hasListeners(Events::onTransactionBegin)) {
  1216.             Deprecation::trigger(
  1217.                 'doctrine/dbal',
  1218.                 'https://github.com/doctrine/dbal/issues/5784',
  1219.                 'Subscribing to %s events is deprecated.',
  1220.                 Events::onTransactionBegin,
  1221.             );
  1222.             $eventManager->dispatchEvent(Events::onTransactionBegin, new TransactionBeginEventArgs($this));
  1223.         }
  1224.         return true;
  1225.     }
  1226.     /**
  1227.      * @return bool
  1228.      *
  1229.      * @throws Exception
  1230.      */
  1231.     public function commit()
  1232.     {
  1233.         if ($this->transactionNestingLevel === 0) {
  1234.             throw ConnectionException::noActiveTransaction();
  1235.         }
  1236.         if ($this->isRollbackOnly) {
  1237.             throw ConnectionException::commitFailedRollbackOnly();
  1238.         }
  1239.         $result true;
  1240.         $connection $this->getWrappedConnection();
  1241.         if ($this->transactionNestingLevel === 1) {
  1242.             $result $this->doCommit($connection);
  1243.         } elseif ($this->nestTransactionsWithSavepoints) {
  1244.             $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
  1245.         }
  1246.         --$this->transactionNestingLevel;
  1247.         $eventManager $this->getEventManager();
  1248.         if ($eventManager->hasListeners(Events::onTransactionCommit)) {
  1249.             Deprecation::trigger(
  1250.                 'doctrine/dbal',
  1251.                 'https://github.com/doctrine/dbal/issues/5784',
  1252.                 'Subscribing to %s events is deprecated.',
  1253.                 Events::onTransactionCommit,
  1254.             );
  1255.             $eventManager->dispatchEvent(Events::onTransactionCommit, new TransactionCommitEventArgs($this));
  1256.         }
  1257.         if ($this->autoCommit !== false || $this->transactionNestingLevel !== 0) {
  1258.             return $result;
  1259.         }
  1260.         $this->beginTransaction();
  1261.         return $result;
  1262.     }
  1263.     /**
  1264.      * @return bool
  1265.      *
  1266.      * @throws DriverException
  1267.      */
  1268.     private function doCommit(DriverConnection $connection)
  1269.     {
  1270.         $logger $this->_config->getSQLLogger();
  1271.         if ($logger !== null) {
  1272.             $logger->startQuery('"COMMIT"');
  1273.         }
  1274.         $result $connection->commit();
  1275.         if ($logger !== null) {
  1276.             $logger->stopQuery();
  1277.         }
  1278.         return $result;
  1279.     }
  1280.     /**
  1281.      * Commits all current nesting transactions.
  1282.      *
  1283.      * @throws Exception
  1284.      */
  1285.     private function commitAll(): void
  1286.     {
  1287.         while ($this->transactionNestingLevel !== 0) {
  1288.             if ($this->autoCommit === false && $this->transactionNestingLevel === 1) {
  1289.                 // When in no auto-commit mode, the last nesting commit immediately starts a new transaction.
  1290.                 // Therefore we need to do the final commit here and then leave to avoid an infinite loop.
  1291.                 $this->commit();
  1292.                 return;
  1293.             }
  1294.             $this->commit();
  1295.         }
  1296.     }
  1297.     /**
  1298.      * Cancels any database changes done during the current transaction.
  1299.      *
  1300.      * @return bool
  1301.      *
  1302.      * @throws Exception
  1303.      */
  1304.     public function rollBack()
  1305.     {
  1306.         if ($this->transactionNestingLevel === 0) {
  1307.             throw ConnectionException::noActiveTransaction();
  1308.         }
  1309.         $connection $this->getWrappedConnection();
  1310.         $logger $this->_config->getSQLLogger();
  1311.         if ($this->transactionNestingLevel === 1) {
  1312.             if ($logger !== null) {
  1313.                 $logger->startQuery('"ROLLBACK"');
  1314.             }
  1315.             $this->transactionNestingLevel 0;
  1316.             $connection->rollBack();
  1317.             $this->isRollbackOnly false;
  1318.             if ($logger !== null) {
  1319.                 $logger->stopQuery();
  1320.             }
  1321.             if ($this->autoCommit === false) {
  1322.                 $this->beginTransaction();
  1323.             }
  1324.         } elseif ($this->nestTransactionsWithSavepoints) {
  1325.             if ($logger !== null) {
  1326.                 $logger->startQuery('"ROLLBACK TO SAVEPOINT"');
  1327.             }
  1328.             $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
  1329.             --$this->transactionNestingLevel;
  1330.             if ($logger !== null) {
  1331.                 $logger->stopQuery();
  1332.             }
  1333.         } else {
  1334.             $this->isRollbackOnly true;
  1335.             --$this->transactionNestingLevel;
  1336.         }
  1337.         $eventManager $this->getEventManager();
  1338.         if ($eventManager->hasListeners(Events::onTransactionRollBack)) {
  1339.             Deprecation::trigger(
  1340.                 'doctrine/dbal',
  1341.                 'https://github.com/doctrine/dbal/issues/5784',
  1342.                 'Subscribing to %s events is deprecated.',
  1343.                 Events::onTransactionRollBack,
  1344.             );
  1345.             $eventManager->dispatchEvent(Events::onTransactionRollBack, new TransactionRollBackEventArgs($this));
  1346.         }
  1347.         return true;
  1348.     }
  1349.     /**
  1350.      * Creates a new savepoint.
  1351.      *
  1352.      * @param string $savepoint The name of the savepoint to create.
  1353.      *
  1354.      * @return void
  1355.      *
  1356.      * @throws Exception
  1357.      */
  1358.     public function createSavepoint($savepoint)
  1359.     {
  1360.         $platform $this->getDatabasePlatform();
  1361.         if (! $platform->supportsSavepoints()) {
  1362.             throw ConnectionException::savepointsNotSupported();
  1363.         }
  1364.         $this->executeStatement($platform->createSavePoint($savepoint));
  1365.     }
  1366.     /**
  1367.      * Releases the given savepoint.
  1368.      *
  1369.      * @param string $savepoint The name of the savepoint to release.
  1370.      *
  1371.      * @return void
  1372.      *
  1373.      * @throws Exception
  1374.      */
  1375.     public function releaseSavepoint($savepoint)
  1376.     {
  1377.         $logger $this->_config->getSQLLogger();
  1378.         $platform $this->getDatabasePlatform();
  1379.         if (! $platform->supportsSavepoints()) {
  1380.             throw ConnectionException::savepointsNotSupported();
  1381.         }
  1382.         if (! $platform->supportsReleaseSavepoints()) {
  1383.             if ($logger !== null) {
  1384.                 $logger->stopQuery();
  1385.             }
  1386.             return;
  1387.         }
  1388.         if ($logger !== null) {
  1389.             $logger->startQuery('"RELEASE SAVEPOINT"');
  1390.         }
  1391.         $this->executeStatement($platform->releaseSavePoint($savepoint));
  1392.         if ($logger === null) {
  1393.             return;
  1394.         }
  1395.         $logger->stopQuery();
  1396.     }
  1397.     /**
  1398.      * Rolls back to the given savepoint.
  1399.      *
  1400.      * @param string $savepoint The name of the savepoint to rollback to.
  1401.      *
  1402.      * @return void
  1403.      *
  1404.      * @throws Exception
  1405.      */
  1406.     public function rollbackSavepoint($savepoint)
  1407.     {
  1408.         $platform $this->getDatabasePlatform();
  1409.         if (! $platform->supportsSavepoints()) {
  1410.             throw ConnectionException::savepointsNotSupported();
  1411.         }
  1412.         $this->executeStatement($platform->rollbackSavePoint($savepoint));
  1413.     }
  1414.     /**
  1415.      * Gets the wrapped driver connection.
  1416.      *
  1417.      * @deprecated Use {@link getNativeConnection()} to access the native connection.
  1418.      *
  1419.      * @return DriverConnection
  1420.      *
  1421.      * @throws Exception
  1422.      */
  1423.     public function getWrappedConnection()
  1424.     {
  1425.         Deprecation::triggerIfCalledFromOutside(
  1426.             'doctrine/dbal',
  1427.             'https://github.com/doctrine/dbal/issues/4966',
  1428.             'Connection::getWrappedConnection() is deprecated.'
  1429.                 ' Use Connection::getNativeConnection() to access the native connection.',
  1430.         );
  1431.         $this->connect();
  1432.         return $this->_conn;
  1433.     }
  1434.     /** @return resource|object */
  1435.     public function getNativeConnection()
  1436.     {
  1437.         $this->connect();
  1438.         if (! method_exists($this->_conn'getNativeConnection')) {
  1439.             throw new LogicException(sprintf(
  1440.                 'The driver connection %s does not support accessing the native connection.',
  1441.                 get_class($this->_conn),
  1442.             ));
  1443.         }
  1444.         return $this->_conn->getNativeConnection();
  1445.     }
  1446.     /**
  1447.      * Creates a SchemaManager that can be used to inspect or change the
  1448.      * database schema through the connection.
  1449.      *
  1450.      * @throws Exception
  1451.      */
  1452.     public function createSchemaManager(): AbstractSchemaManager
  1453.     {
  1454.         return $this->schemaManagerFactory->createSchemaManager($this);
  1455.     }
  1456.     /**
  1457.      * Gets the SchemaManager that can be used to inspect or change the
  1458.      * database schema through the connection.
  1459.      *
  1460.      * @deprecated Use {@see createSchemaManager()} instead.
  1461.      *
  1462.      * @return AbstractSchemaManager
  1463.      *
  1464.      * @throws Exception
  1465.      */
  1466.     public function getSchemaManager()
  1467.     {
  1468.         Deprecation::triggerIfCalledFromOutside(
  1469.             'doctrine/dbal',
  1470.             'https://github.com/doctrine/dbal/issues/4515',
  1471.             'Connection::getSchemaManager() is deprecated, use Connection::createSchemaManager() instead.',
  1472.         );
  1473.         return $this->_schemaManager ??= $this->createSchemaManager();
  1474.     }
  1475.     /**
  1476.      * Marks the current transaction so that the only possible
  1477.      * outcome for the transaction to be rolled back.
  1478.      *
  1479.      * @return void
  1480.      *
  1481.      * @throws ConnectionException If no transaction is active.
  1482.      */
  1483.     public function setRollbackOnly()
  1484.     {
  1485.         if ($this->transactionNestingLevel === 0) {
  1486.             throw ConnectionException::noActiveTransaction();
  1487.         }
  1488.         $this->isRollbackOnly true;
  1489.     }
  1490.     /**
  1491.      * Checks whether the current transaction is marked for rollback only.
  1492.      *
  1493.      * @return bool
  1494.      *
  1495.      * @throws ConnectionException If no transaction is active.
  1496.      */
  1497.     public function isRollbackOnly()
  1498.     {
  1499.         if ($this->transactionNestingLevel === 0) {
  1500.             throw ConnectionException::noActiveTransaction();
  1501.         }
  1502.         return $this->isRollbackOnly;
  1503.     }
  1504.     /**
  1505.      * Converts a given value to its database representation according to the conversion
  1506.      * rules of a specific DBAL mapping type.
  1507.      *
  1508.      * @param mixed  $value The value to convert.
  1509.      * @param string $type  The name of the DBAL mapping type.
  1510.      *
  1511.      * @return mixed The converted value.
  1512.      *
  1513.      * @throws Exception
  1514.      */
  1515.     public function convertToDatabaseValue($value$type)
  1516.     {
  1517.         return Type::getType($type)->convertToDatabaseValue($value$this->getDatabasePlatform());
  1518.     }
  1519.     /**
  1520.      * Converts a given value to its PHP representation according to the conversion
  1521.      * rules of a specific DBAL mapping type.
  1522.      *
  1523.      * @param mixed  $value The value to convert.
  1524.      * @param string $type  The name of the DBAL mapping type.
  1525.      *
  1526.      * @return mixed The converted type.
  1527.      *
  1528.      * @throws Exception
  1529.      */
  1530.     public function convertToPHPValue($value$type)
  1531.     {
  1532.         return Type::getType($type)->convertToPHPValue($value$this->getDatabasePlatform());
  1533.     }
  1534.     /**
  1535.      * Binds a set of parameters, some or all of which are typed with a PDO binding type
  1536.      * or DBAL mapping type, to a given statement.
  1537.      *
  1538.      * @param DriverStatement                                                      $stmt   Prepared statement
  1539.      * @param list<mixed>|array<string, mixed>                                     $params Statement parameters
  1540.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  1541.      *
  1542.      * @throws Exception
  1543.      */
  1544.     private function bindParameters(DriverStatement $stmt, array $params, array $types): void
  1545.     {
  1546.         // Check whether parameters are positional or named. Mixing is not allowed.
  1547.         if (is_int(key($params))) {
  1548.             $bindIndex 1;
  1549.             foreach ($params as $key => $value) {
  1550.                 if (isset($types[$key])) {
  1551.                     $type                  $types[$key];
  1552.                     [$value$bindingType] = $this->getBindingInfo($value$type);
  1553.                 } else {
  1554.                     if (array_key_exists($key$types)) {
  1555.                         Deprecation::trigger(
  1556.                             'doctrine/dbal',
  1557.                             'https://github.com/doctrine/dbal/pull/5550',
  1558.                             'Using NULL as prepared statement parameter type is deprecated.'
  1559.                                 'Omit or use Parameter::STRING instead',
  1560.                         );
  1561.                     }
  1562.                     $bindingType ParameterType::STRING;
  1563.                 }
  1564.                 $stmt->bindValue($bindIndex$value$bindingType);
  1565.                 ++$bindIndex;
  1566.             }
  1567.         } else {
  1568.             // Named parameters
  1569.             foreach ($params as $name => $value) {
  1570.                 if (isset($types[$name])) {
  1571.                     $type                  $types[$name];
  1572.                     [$value$bindingType] = $this->getBindingInfo($value$type);
  1573.                 } else {
  1574.                     if (array_key_exists($name$types)) {
  1575.                         Deprecation::trigger(
  1576.                             'doctrine/dbal',
  1577.                             'https://github.com/doctrine/dbal/pull/5550',
  1578.                             'Using NULL as prepared statement parameter type is deprecated.'
  1579.                                 'Omit or use Parameter::STRING instead',
  1580.                         );
  1581.                     }
  1582.                     $bindingType ParameterType::STRING;
  1583.                 }
  1584.                 $stmt->bindValue($name$value$bindingType);
  1585.             }
  1586.         }
  1587.     }
  1588.     /**
  1589.      * Gets the binding type of a given type.
  1590.      *
  1591.      * @param mixed                $value The value to bind.
  1592.      * @param int|string|Type|null $type  The type to bind (PDO or DBAL).
  1593.      *
  1594.      * @return array{mixed, int} [0] => the (escaped) value, [1] => the binding type.
  1595.      *
  1596.      * @throws Exception
  1597.      */
  1598.     private function getBindingInfo($value$type): array
  1599.     {
  1600.         if (is_string($type)) {
  1601.             $type Type::getType($type);
  1602.         }
  1603.         if ($type instanceof Type) {
  1604.             $value       $type->convertToDatabaseValue($value$this->getDatabasePlatform());
  1605.             $bindingType $type->getBindingType();
  1606.         } else {
  1607.             $bindingType $type ?? ParameterType::STRING;
  1608.         }
  1609.         return [$value$bindingType];
  1610.     }
  1611.     /**
  1612.      * Creates a new instance of a SQL query builder.
  1613.      *
  1614.      * @return QueryBuilder
  1615.      */
  1616.     public function createQueryBuilder()
  1617.     {
  1618.         return new Query\QueryBuilder($this);
  1619.     }
  1620.     /**
  1621.      * @internal
  1622.      *
  1623.      * @param list<mixed>|array<string, mixed>                                     $params
  1624.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types
  1625.      */
  1626.     final public function convertExceptionDuringQuery(
  1627.         Driver\Exception $e,
  1628.         string $sql,
  1629.         array $params = [],
  1630.         array $types = []
  1631.     ): DriverException {
  1632.         return $this->handleDriverException($e, new Query($sql$params$types));
  1633.     }
  1634.     /** @internal */
  1635.     final public function convertException(Driver\Exception $e): DriverException
  1636.     {
  1637.         return $this->handleDriverException($enull);
  1638.     }
  1639.     /**
  1640.      * @param array<int, mixed>|array<string, mixed>                               $params
  1641.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types
  1642.      *
  1643.      * @return array{string, list<mixed>, array<int,Type|int|string|null>}
  1644.      */
  1645.     private function expandArrayParameters(string $sql, array $params, array $types): array
  1646.     {
  1647.         $this->parser ??= $this->getDatabasePlatform()->createSQLParser();
  1648.         $visitor        = new ExpandArrayParameters($params$types);
  1649.         $this->parser->parse($sql$visitor);
  1650.         return [
  1651.             $visitor->getSQL(),
  1652.             $visitor->getParameters(),
  1653.             $visitor->getTypes(),
  1654.         ];
  1655.     }
  1656.     /**
  1657.      * @param array<int, mixed>|array<string, mixed>                               $params
  1658.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types
  1659.      */
  1660.     private function needsArrayParameterConversion(array $params, array $types): bool
  1661.     {
  1662.         if (is_string(key($params))) {
  1663.             return true;
  1664.         }
  1665.         foreach ($types as $type) {
  1666.             if (
  1667.                 $type === ArrayParameterType::INTEGER
  1668.                 || $type === ArrayParameterType::STRING
  1669.                 || $type === ArrayParameterType::ASCII
  1670.                 || $type === ArrayParameterType::BINARY
  1671.             ) {
  1672.                 return true;
  1673.             }
  1674.         }
  1675.         return false;
  1676.     }
  1677.     private function handleDriverException(
  1678.         Driver\Exception $driverException,
  1679.         ?Query $query
  1680.     ): DriverException {
  1681.         $this->exceptionConverter ??= $this->_driver->getExceptionConverter();
  1682.         $exception                  $this->exceptionConverter->convert($driverException$query);
  1683.         if ($exception instanceof ConnectionLost) {
  1684.             $this->close();
  1685.         }
  1686.         return $exception;
  1687.     }
  1688.     /**
  1689.      * BC layer for a wide-spread use-case of old DBAL APIs
  1690.      *
  1691.      * @deprecated Use {@see executeStatement()} instead
  1692.      *
  1693.      * @param array<mixed>           $params The query parameters
  1694.      * @param array<int|string|null> $types  The parameter types
  1695.      */
  1696.     public function executeUpdate(string $sql, array $params = [], array $types = []): int
  1697.     {
  1698.         Deprecation::trigger(
  1699.             'doctrine/dbal',
  1700.             'https://github.com/doctrine/dbal/pull/4163',
  1701.             '%s is deprecated, please use executeStatement() instead.',
  1702.             __METHOD__,
  1703.         );
  1704.         return $this->executeStatement($sql$params$types);
  1705.     }
  1706.     /**
  1707.      * BC layer for a wide-spread use-case of old DBAL APIs
  1708.      *
  1709.      * @deprecated Use {@see executeQuery()} instead
  1710.      */
  1711.     public function query(string $sql): Result
  1712.     {
  1713.         Deprecation::trigger(
  1714.             'doctrine/dbal',
  1715.             'https://github.com/doctrine/dbal/pull/4163',
  1716.             '%s is deprecated, please use executeQuery() instead.',
  1717.             __METHOD__,
  1718.         );
  1719.         return $this->executeQuery($sql);
  1720.     }
  1721.     /**
  1722.      * BC layer for a wide-spread use-case of old DBAL APIs
  1723.      *
  1724.      * @deprecated please use {@see executeStatement()} instead
  1725.      */
  1726.     public function exec(string $sql): int
  1727.     {
  1728.         Deprecation::trigger(
  1729.             'doctrine/dbal',
  1730.             'https://github.com/doctrine/dbal/pull/4163',
  1731.             '%s is deprecated, please use executeStatement() instead.',
  1732.             __METHOD__,
  1733.         );
  1734.         return $this->executeStatement($sql);
  1735.     }
  1736. }