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

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