Connection.php 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the LGPL. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\DBAL;
  20. use PDO, Closure, Exception,
  21. Doctrine\DBAL\Types\Type,
  22. Doctrine\DBAL\Driver\Connection as DriverConnection,
  23. Doctrine\Common\EventManager,
  24. Doctrine\DBAL\DBALException,
  25. Doctrine\DBAL\Cache\ResultCacheStatement,
  26. Doctrine\DBAL\Cache\QueryCacheProfile,
  27. Doctrine\DBAL\Cache\ArrayStatement,
  28. Doctrine\DBAL\Cache\CacheException;
  29. /**
  30. * A wrapper around a Doctrine\DBAL\Driver\Connection that adds features like
  31. * events, transaction isolation levels, configuration, emulated transaction nesting,
  32. * lazy connecting and more.
  33. *
  34. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  35. * @link www.doctrine-project.org
  36. * @since 2.0
  37. * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
  38. * @author Jonathan Wage <jonwage@gmail.com>
  39. * @author Roman Borschel <roman@code-factory.org>
  40. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
  41. * @author Lukas Smith <smith@pooteeweet.org> (MDB2 library)
  42. * @author Benjamin Eberlei <kontakt@beberlei.de>
  43. */
  44. class Connection implements DriverConnection
  45. {
  46. /**
  47. * Constant for transaction isolation level READ UNCOMMITTED.
  48. */
  49. const TRANSACTION_READ_UNCOMMITTED = 1;
  50. /**
  51. * Constant for transaction isolation level READ COMMITTED.
  52. */
  53. const TRANSACTION_READ_COMMITTED = 2;
  54. /**
  55. * Constant for transaction isolation level REPEATABLE READ.
  56. */
  57. const TRANSACTION_REPEATABLE_READ = 3;
  58. /**
  59. * Constant for transaction isolation level SERIALIZABLE.
  60. */
  61. const TRANSACTION_SERIALIZABLE = 4;
  62. /**
  63. * Represents an array of ints to be expanded by Doctrine SQL parsing.
  64. *
  65. * @var int
  66. */
  67. const PARAM_INT_ARRAY = 101;
  68. /**
  69. * Represents an array of strings to be expanded by Doctrine SQL parsing.
  70. *
  71. * @var int
  72. */
  73. const PARAM_STR_ARRAY = 102;
  74. /**
  75. * Offset by which PARAM_* constants are detected as arrays of the param type.
  76. *
  77. * @var int
  78. */
  79. const ARRAY_PARAM_OFFSET = 100;
  80. /**
  81. * The wrapped driver connection.
  82. *
  83. * @var Doctrine\DBAL\Driver\Connection
  84. */
  85. protected $_conn;
  86. /**
  87. * @var Doctrine\DBAL\Configuration
  88. */
  89. protected $_config;
  90. /**
  91. * @var Doctrine\Common\EventManager
  92. */
  93. protected $_eventManager;
  94. /**
  95. * @var Doctrine\DBAL\Query\ExpressionBuilder
  96. */
  97. protected $_expr;
  98. /**
  99. * Whether or not a connection has been established.
  100. *
  101. * @var boolean
  102. */
  103. private $_isConnected = false;
  104. /**
  105. * The transaction nesting level.
  106. *
  107. * @var integer
  108. */
  109. private $_transactionNestingLevel = 0;
  110. /**
  111. * The currently active transaction isolation level.
  112. *
  113. * @var integer
  114. */
  115. private $_transactionIsolationLevel;
  116. /**
  117. * If nested transations should use savepoints
  118. *
  119. * @var integer
  120. */
  121. private $_nestTransactionsWithSavepoints;
  122. /**
  123. * The parameters used during creation of the Connection instance.
  124. *
  125. * @var array
  126. */
  127. private $_params = array();
  128. /**
  129. * The DatabasePlatform object that provides information about the
  130. * database platform used by the connection.
  131. *
  132. * @var Doctrine\DBAL\Platforms\AbstractPlatform
  133. */
  134. protected $_platform;
  135. /**
  136. * The schema manager.
  137. *
  138. * @var Doctrine\DBAL\Schema\SchemaManager
  139. */
  140. protected $_schemaManager;
  141. /**
  142. * The used DBAL driver.
  143. *
  144. * @var Doctrine\DBAL\Driver
  145. */
  146. protected $_driver;
  147. /**
  148. * Flag that indicates whether the current transaction is marked for rollback only.
  149. *
  150. * @var boolean
  151. */
  152. private $_isRollbackOnly = false;
  153. /**
  154. * Initializes a new instance of the Connection class.
  155. *
  156. * @param array $params The connection parameters.
  157. * @param Driver $driver
  158. * @param Configuration $config
  159. * @param EventManager $eventManager
  160. */
  161. public function __construct(array $params, Driver $driver, Configuration $config = null,
  162. EventManager $eventManager = null)
  163. {
  164. $this->_driver = $driver;
  165. $this->_params = $params;
  166. if (isset($params['pdo'])) {
  167. $this->_conn = $params['pdo'];
  168. $this->_isConnected = true;
  169. }
  170. // Create default config and event manager if none given
  171. if ( ! $config) {
  172. $config = new Configuration();
  173. }
  174. if ( ! $eventManager) {
  175. $eventManager = new EventManager();
  176. }
  177. $this->_config = $config;
  178. $this->_eventManager = $eventManager;
  179. $this->_expr = new Query\Expression\ExpressionBuilder($this);
  180. if ( ! isset($params['platform'])) {
  181. $this->_platform = $driver->getDatabasePlatform();
  182. } else if ($params['platform'] instanceof Platforms\AbstractPlatform) {
  183. $this->_platform = $params['platform'];
  184. } else {
  185. throw DBALException::invalidPlatformSpecified();
  186. }
  187. $this->_platform->setEventManager($eventManager);
  188. $this->_transactionIsolationLevel = $this->_platform->getDefaultTransactionIsolationLevel();
  189. }
  190. /**
  191. * Gets the parameters used during instantiation.
  192. *
  193. * @return array $params
  194. */
  195. public function getParams()
  196. {
  197. return $this->_params;
  198. }
  199. /**
  200. * Gets the name of the database this Connection is connected to.
  201. *
  202. * @return string $database
  203. */
  204. public function getDatabase()
  205. {
  206. return $this->_driver->getDatabase($this);
  207. }
  208. /**
  209. * Gets the hostname of the currently connected database.
  210. *
  211. * @return string
  212. */
  213. public function getHost()
  214. {
  215. return isset($this->_params['host']) ? $this->_params['host'] : null;
  216. }
  217. /**
  218. * Gets the port of the currently connected database.
  219. *
  220. * @return mixed
  221. */
  222. public function getPort()
  223. {
  224. return isset($this->_params['port']) ? $this->_params['port'] : null;
  225. }
  226. /**
  227. * Gets the username used by this connection.
  228. *
  229. * @return string
  230. */
  231. public function getUsername()
  232. {
  233. return isset($this->_params['user']) ? $this->_params['user'] : null;
  234. }
  235. /**
  236. * Gets the password used by this connection.
  237. *
  238. * @return string
  239. */
  240. public function getPassword()
  241. {
  242. return isset($this->_params['password']) ? $this->_params['password'] : null;
  243. }
  244. /**
  245. * Gets the DBAL driver instance.
  246. *
  247. * @return \Doctrine\DBAL\Driver
  248. */
  249. public function getDriver()
  250. {
  251. return $this->_driver;
  252. }
  253. /**
  254. * Gets the Configuration used by the Connection.
  255. *
  256. * @return \Doctrine\DBAL\Configuration
  257. */
  258. public function getConfiguration()
  259. {
  260. return $this->_config;
  261. }
  262. /**
  263. * Gets the EventManager used by the Connection.
  264. *
  265. * @return \Doctrine\Common\EventManager
  266. */
  267. public function getEventManager()
  268. {
  269. return $this->_eventManager;
  270. }
  271. /**
  272. * Gets the DatabasePlatform for the connection.
  273. *
  274. * @return \Doctrine\DBAL\Platforms\AbstractPlatform
  275. */
  276. public function getDatabasePlatform()
  277. {
  278. return $this->_platform;
  279. }
  280. /**
  281. * Gets the ExpressionBuilder for the connection.
  282. *
  283. * @return \Doctrine\DBAL\Query\ExpressionBuilder
  284. */
  285. public function getExpressionBuilder()
  286. {
  287. return $this->_expr;
  288. }
  289. /**
  290. * Establishes the connection with the database.
  291. *
  292. * @return boolean TRUE if the connection was successfully established, FALSE if
  293. * the connection is already open.
  294. */
  295. public function connect()
  296. {
  297. if ($this->_isConnected) return false;
  298. $driverOptions = isset($this->_params['driverOptions']) ?
  299. $this->_params['driverOptions'] : array();
  300. $user = isset($this->_params['user']) ? $this->_params['user'] : null;
  301. $password = isset($this->_params['password']) ?
  302. $this->_params['password'] : null;
  303. $this->_conn = $this->_driver->connect($this->_params, $user, $password, $driverOptions);
  304. $this->_isConnected = true;
  305. if ($this->_eventManager->hasListeners(Events::postConnect)) {
  306. $eventArgs = new Event\ConnectionEventArgs($this);
  307. $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
  308. }
  309. return true;
  310. }
  311. /**
  312. * Prepares and executes an SQL query and returns the first row of the result
  313. * as an associative array.
  314. *
  315. * @param string $statement The SQL query.
  316. * @param array $params The query parameters.
  317. * @return array
  318. */
  319. public function fetchAssoc($statement, array $params = array())
  320. {
  321. return $this->executeQuery($statement, $params)->fetch(PDO::FETCH_ASSOC);
  322. }
  323. /**
  324. * Prepares and executes an SQL query and returns the first row of the result
  325. * as a numerically indexed array.
  326. *
  327. * @param string $statement sql query to be executed
  328. * @param array $params prepared statement params
  329. * @return array
  330. */
  331. public function fetchArray($statement, array $params = array())
  332. {
  333. return $this->executeQuery($statement, $params)->fetch(PDO::FETCH_NUM);
  334. }
  335. /**
  336. * Prepares and executes an SQL query and returns the value of a single column
  337. * of the first row of the result.
  338. *
  339. * @param string $statement sql query to be executed
  340. * @param array $params prepared statement params
  341. * @param int $colnum 0-indexed column number to retrieve
  342. * @return mixed
  343. */
  344. public function fetchColumn($statement, array $params = array(), $colnum = 0)
  345. {
  346. return $this->executeQuery($statement, $params)->fetchColumn($colnum);
  347. }
  348. /**
  349. * Whether an actual connection to the database is established.
  350. *
  351. * @return boolean
  352. */
  353. public function isConnected()
  354. {
  355. return $this->_isConnected;
  356. }
  357. /**
  358. * Checks whether a transaction is currently active.
  359. *
  360. * @return boolean TRUE if a transaction is currently active, FALSE otherwise.
  361. */
  362. public function isTransactionActive()
  363. {
  364. return $this->_transactionNestingLevel > 0;
  365. }
  366. /**
  367. * Executes an SQL DELETE statement on a table.
  368. *
  369. * @param string $table The name of the table on which to delete.
  370. * @param array $identifier The deletion criteria. An associateve array containing column-value pairs.
  371. * @return integer The number of affected rows.
  372. */
  373. public function delete($tableName, array $identifier)
  374. {
  375. $this->connect();
  376. $criteria = array();
  377. foreach (array_keys($identifier) as $columnName) {
  378. $criteria[] = $columnName . ' = ?';
  379. }
  380. $query = 'DELETE FROM ' . $tableName . ' WHERE ' . implode(' AND ', $criteria);
  381. return $this->executeUpdate($query, array_values($identifier));
  382. }
  383. /**
  384. * Closes the connection.
  385. *
  386. * @return void
  387. */
  388. public function close()
  389. {
  390. unset($this->_conn);
  391. $this->_isConnected = false;
  392. }
  393. /**
  394. * Sets the transaction isolation level.
  395. *
  396. * @param integer $level The level to set.
  397. */
  398. public function setTransactionIsolation($level)
  399. {
  400. $this->_transactionIsolationLevel = $level;
  401. return $this->executeUpdate($this->_platform->getSetTransactionIsolationSQL($level));
  402. }
  403. /**
  404. * Gets the currently active transaction isolation level.
  405. *
  406. * @return integer The current transaction isolation level.
  407. */
  408. public function getTransactionIsolation()
  409. {
  410. return $this->_transactionIsolationLevel;
  411. }
  412. /**
  413. * Executes an SQL UPDATE statement on a table.
  414. *
  415. * @param string $table The name of the table to update.
  416. * @param array $identifier The update criteria. An associative array containing column-value pairs.
  417. * @param array $types Types of the merged $data and $identifier arrays in that order.
  418. * @return integer The number of affected rows.
  419. */
  420. public function update($tableName, array $data, array $identifier, array $types = array())
  421. {
  422. $this->connect();
  423. $set = array();
  424. foreach ($data as $columnName => $value) {
  425. $set[] = $columnName . ' = ?';
  426. }
  427. $params = array_merge(array_values($data), array_values($identifier));
  428. $sql = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $set)
  429. . ' WHERE ' . implode(' = ? AND ', array_keys($identifier))
  430. . ' = ?';
  431. return $this->executeUpdate($sql, $params, $types);
  432. }
  433. /**
  434. * Inserts a table row with specified data.
  435. *
  436. * @param string $table The name of the table to insert data into.
  437. * @param array $data An associative array containing column-value pairs.
  438. * @param array $types Types of the inserted data.
  439. * @return integer The number of affected rows.
  440. */
  441. public function insert($tableName, array $data, array $types = array())
  442. {
  443. $this->connect();
  444. // column names are specified as array keys
  445. $cols = array();
  446. $placeholders = array();
  447. foreach ($data as $columnName => $value) {
  448. $cols[] = $columnName;
  449. $placeholders[] = '?';
  450. }
  451. $query = 'INSERT INTO ' . $tableName
  452. . ' (' . implode(', ', $cols) . ')'
  453. . ' VALUES (' . implode(', ', $placeholders) . ')';
  454. return $this->executeUpdate($query, array_values($data), $types);
  455. }
  456. /**
  457. * Sets the given charset on the current connection.
  458. *
  459. * @param string $charset The charset to set.
  460. */
  461. public function setCharset($charset)
  462. {
  463. $this->executeUpdate($this->_platform->getSetCharsetSQL($charset));
  464. }
  465. /**
  466. * Quote a string so it can be safely used as a table or column name, even if
  467. * it is a reserved name.
  468. *
  469. * Delimiting style depends on the underlying database platform that is being used.
  470. *
  471. * NOTE: Just because you CAN use quoted identifiers does not mean
  472. * you SHOULD use them. In general, they end up causing way more
  473. * problems than they solve.
  474. *
  475. * @param string $str The name to be quoted.
  476. * @return string The quoted name.
  477. */
  478. public function quoteIdentifier($str)
  479. {
  480. return $this->_platform->quoteIdentifier($str);
  481. }
  482. /**
  483. * Quotes a given input parameter.
  484. *
  485. * @param mixed $input Parameter to be quoted.
  486. * @param string $type Type of the parameter.
  487. * @return string The quoted parameter.
  488. */
  489. public function quote($input, $type = null)
  490. {
  491. $this->connect();
  492. list($value, $bindingType) = $this->getBindingInfo($input, $type);
  493. return $this->_conn->quote($value, $bindingType);
  494. }
  495. /**
  496. * Prepares and executes an SQL query and returns the result as an associative array.
  497. *
  498. * @param string $sql The SQL query.
  499. * @param array $params The query parameters.
  500. * @return array
  501. */
  502. public function fetchAll($sql, array $params = array())
  503. {
  504. return $this->executeQuery($sql, $params)->fetchAll(PDO::FETCH_ASSOC);
  505. }
  506. /**
  507. * Prepares an SQL statement.
  508. *
  509. * @param string $statement The SQL statement to prepare.
  510. * @return Doctrine\DBAL\Driver\Statement The prepared statement.
  511. */
  512. public function prepare($statement)
  513. {
  514. $this->connect();
  515. return new Statement($statement, $this);
  516. }
  517. /**
  518. * Executes an, optionally parameterized, SQL query.
  519. *
  520. * If the query is parameterized, a prepared statement is used.
  521. * If an SQLLogger is configured, the execution is logged.
  522. *
  523. * @param string $query The SQL query to execute.
  524. * @param array $params The parameters to bind to the query, if any.
  525. * @param array $types The types the previous parameters are in.
  526. * @param QueryCacheProfile $qcp
  527. * @return Doctrine\DBAL\Driver\Statement The executed statement.
  528. * @internal PERF: Directly prepares a driver statement, not a wrapper.
  529. */
  530. public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
  531. {
  532. if ($qcp !== null) {
  533. return $this->executeCacheQuery($query, $params, $types, $qcp);
  534. }
  535. $this->connect();
  536. $hasLogger = $this->_config->getSQLLogger() !== null;
  537. if ($hasLogger) {
  538. $this->_config->getSQLLogger()->startQuery($query, $params, $types);
  539. }
  540. if ($params) {
  541. list($query, $params, $types) = SQLParserUtils::expandListParameters($query, $params, $types);
  542. $stmt = $this->_conn->prepare($query);
  543. if ($types) {
  544. $this->_bindTypedValues($stmt, $params, $types);
  545. $stmt->execute();
  546. } else {
  547. $stmt->execute($params);
  548. }
  549. } else {
  550. $stmt = $this->_conn->query($query);
  551. }
  552. if ($hasLogger) {
  553. $this->_config->getSQLLogger()->stopQuery();
  554. }
  555. return $stmt;
  556. }
  557. /**
  558. * Execute a caching query and
  559. *
  560. * @param string $query
  561. * @param array $params
  562. * @param array $types
  563. * @param QueryCacheProfile $qcp
  564. * @return \Doctrine\DBAL\Driver\ResultStatement
  565. */
  566. public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qcp)
  567. {
  568. $resultCache = $qcp->getResultCacheDriver() ?: $this->_config->getResultCacheImpl();
  569. if (!$resultCache) {
  570. throw CacheException::noResultDriverConfigured();
  571. }
  572. list($cacheKey, $realKey) = $qcp->generateCacheKeys($query, $params, $types);
  573. // fetch the row pointers entry
  574. if ($data = $resultCache->fetch($cacheKey)) {
  575. // is the real key part of this row pointers map or is the cache only pointing to other cache keys?
  576. if (isset($data[$realKey])) {
  577. return new ArrayStatement($data[$realKey]);
  578. } else if (array_key_exists($realKey, $data)) {
  579. return new ArrayStatement(array());
  580. }
  581. }
  582. return new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime());
  583. }
  584. /**
  585. * Executes an, optionally parameterized, SQL query and returns the result,
  586. * applying a given projection/transformation function on each row of the result.
  587. *
  588. * @param string $query The SQL query to execute.
  589. * @param array $params The parameters, if any.
  590. * @param Closure $mapper The transformation function that is applied on each row.
  591. * The function receives a single paramater, an array, that
  592. * represents a row of the result set.
  593. * @return mixed The projected result of the query.
  594. */
  595. public function project($query, array $params, Closure $function)
  596. {
  597. $result = array();
  598. $stmt = $this->executeQuery($query, $params ?: array());
  599. while ($row = $stmt->fetch()) {
  600. $result[] = $function($row);
  601. }
  602. $stmt->closeCursor();
  603. return $result;
  604. }
  605. /**
  606. * Executes an SQL statement, returning a result set as a Statement object.
  607. *
  608. * @param string $statement
  609. * @param integer $fetchType
  610. * @return Doctrine\DBAL\Driver\Statement
  611. */
  612. public function query()
  613. {
  614. $this->connect();
  615. $args = func_get_args();
  616. $logger = $this->getConfiguration()->getSQLLogger();
  617. if ($logger) {
  618. $logger->startQuery($args[0]);
  619. }
  620. $statement = call_user_func_array(array($this->_conn, 'query'), $args);
  621. if ($logger) {
  622. $logger->stopQuery();
  623. }
  624. return $statement;
  625. }
  626. /**
  627. * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
  628. * and returns the number of affected rows.
  629. *
  630. * This method supports PDO binding types as well as DBAL mapping types.
  631. *
  632. * @param string $query The SQL query.
  633. * @param array $params The query parameters.
  634. * @param array $types The parameter types.
  635. * @return integer The number of affected rows.
  636. * @internal PERF: Directly prepares a driver statement, not a wrapper.
  637. */
  638. public function executeUpdate($query, array $params = array(), array $types = array())
  639. {
  640. $this->connect();
  641. $hasLogger = $this->_config->getSQLLogger() !== null;
  642. if ($hasLogger) {
  643. $this->_config->getSQLLogger()->startQuery($query, $params, $types);
  644. }
  645. if ($params) {
  646. list($query, $params, $types) = SQLParserUtils::expandListParameters($query, $params, $types);
  647. $stmt = $this->_conn->prepare($query);
  648. if ($types) {
  649. $this->_bindTypedValues($stmt, $params, $types);
  650. $stmt->execute();
  651. } else {
  652. $stmt->execute($params);
  653. }
  654. $result = $stmt->rowCount();
  655. } else {
  656. $result = $this->_conn->exec($query);
  657. }
  658. if ($hasLogger) {
  659. $this->_config->getSQLLogger()->stopQuery();
  660. }
  661. return $result;
  662. }
  663. /**
  664. * Execute an SQL statement and return the number of affected rows.
  665. *
  666. * @param string $statement
  667. * @return integer The number of affected rows.
  668. */
  669. public function exec($statement)
  670. {
  671. $this->connect();
  672. return $this->_conn->exec($statement);
  673. }
  674. /**
  675. * Returns the current transaction nesting level.
  676. *
  677. * @return integer The nesting level. A value of 0 means there's no active transaction.
  678. */
  679. public function getTransactionNestingLevel()
  680. {
  681. return $this->_transactionNestingLevel;
  682. }
  683. /**
  684. * Fetch the SQLSTATE associated with the last database operation.
  685. *
  686. * @return integer The last error code.
  687. */
  688. public function errorCode()
  689. {
  690. $this->connect();
  691. return $this->_conn->errorCode();
  692. }
  693. /**
  694. * Fetch extended error information associated with the last database operation.
  695. *
  696. * @return array The last error information.
  697. */
  698. public function errorInfo()
  699. {
  700. $this->connect();
  701. return $this->_conn->errorInfo();
  702. }
  703. /**
  704. * Returns the ID of the last inserted row, or the last value from a sequence object,
  705. * depending on the underlying driver.
  706. *
  707. * Note: This method may not return a meaningful or consistent result across different drivers,
  708. * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
  709. * columns or sequences.
  710. *
  711. * @param string $seqName Name of the sequence object from which the ID should be returned.
  712. * @return string A string representation of the last inserted ID.
  713. */
  714. public function lastInsertId($seqName = null)
  715. {
  716. $this->connect();
  717. return $this->_conn->lastInsertId($seqName);
  718. }
  719. /**
  720. * Executes a function in a transaction.
  721. *
  722. * The function gets passed this Connection instance as an (optional) parameter.
  723. *
  724. * If an exception occurs during execution of the function or transaction commit,
  725. * the transaction is rolled back and the exception re-thrown.
  726. *
  727. * @param Closure $func The function to execute transactionally.
  728. */
  729. public function transactional(Closure $func)
  730. {
  731. $this->beginTransaction();
  732. try {
  733. $func($this);
  734. $this->commit();
  735. } catch (Exception $e) {
  736. $this->rollback();
  737. throw $e;
  738. }
  739. }
  740. /**
  741. * Set if nested transactions should use savepoints
  742. *
  743. * @param boolean
  744. * @return void
  745. */
  746. public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints)
  747. {
  748. if ($this->_transactionNestingLevel > 0) {
  749. throw ConnectionException::mayNotAlterNestedTransactionWithSavepointsInTransaction();
  750. }
  751. if (!$this->_platform->supportsSavepoints()) {
  752. throw ConnectionException::savepointsNotSupported();
  753. }
  754. $this->_nestTransactionsWithSavepoints = $nestTransactionsWithSavepoints;
  755. }
  756. /**
  757. * Get if nested transactions should use savepoints
  758. *
  759. * @return boolean
  760. */
  761. public function getNestTransactionsWithSavepoints()
  762. {
  763. return $this->_nestTransactionsWithSavepoints;
  764. }
  765. /**
  766. * Returns the savepoint name to use for nested transactions are false if they are not supported
  767. * "savepointFormat" parameter is not set
  768. *
  769. * @return mixed a string with the savepoint name or false
  770. */
  771. protected function _getNestedTransactionSavePointName()
  772. {
  773. return 'DOCTRINE2_SAVEPOINT_'.$this->_transactionNestingLevel;
  774. }
  775. /**
  776. * Starts a transaction by suspending auto-commit mode.
  777. *
  778. * @return void
  779. */
  780. public function beginTransaction()
  781. {
  782. $this->connect();
  783. ++$this->_transactionNestingLevel;
  784. if ($this->_transactionNestingLevel == 1) {
  785. $this->_conn->beginTransaction();
  786. } else if ($this->_nestTransactionsWithSavepoints) {
  787. $this->createSavepoint($this->_getNestedTransactionSavePointName());
  788. }
  789. }
  790. /**
  791. * Commits the current transaction.
  792. *
  793. * @return void
  794. * @throws ConnectionException If the commit failed due to no active transaction or
  795. * because the transaction was marked for rollback only.
  796. */
  797. public function commit()
  798. {
  799. if ($this->_transactionNestingLevel == 0) {
  800. throw ConnectionException::noActiveTransaction();
  801. }
  802. if ($this->_isRollbackOnly) {
  803. throw ConnectionException::commitFailedRollbackOnly();
  804. }
  805. $this->connect();
  806. if ($this->_transactionNestingLevel == 1) {
  807. $this->_conn->commit();
  808. } else if ($this->_nestTransactionsWithSavepoints) {
  809. $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
  810. }
  811. --$this->_transactionNestingLevel;
  812. }
  813. /**
  814. * Cancel any database changes done during the current transaction.
  815. *
  816. * this method can be listened with onPreTransactionRollback and onTransactionRollback
  817. * eventlistener methods
  818. *
  819. * @throws ConnectionException If the rollback operation failed.
  820. */
  821. public function rollback()
  822. {
  823. if ($this->_transactionNestingLevel == 0) {
  824. throw ConnectionException::noActiveTransaction();
  825. }
  826. $this->connect();
  827. if ($this->_transactionNestingLevel == 1) {
  828. $this->_transactionNestingLevel = 0;
  829. $this->_conn->rollback();
  830. $this->_isRollbackOnly = false;
  831. } else if ($this->_nestTransactionsWithSavepoints) {
  832. $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
  833. --$this->_transactionNestingLevel;
  834. } else {
  835. $this->_isRollbackOnly = true;
  836. --$this->_transactionNestingLevel;
  837. }
  838. }
  839. /**
  840. * createSavepoint
  841. * creates a new savepoint
  842. *
  843. * @param string $savepoint name of a savepoint to set
  844. * @return void
  845. */
  846. public function createSavepoint($savepoint)
  847. {
  848. if (!$this->_platform->supportsSavepoints()) {
  849. throw ConnectionException::savepointsNotSupported();
  850. }
  851. $this->_conn->exec($this->_platform->createSavePoint($savepoint));
  852. }
  853. /**
  854. * releaseSavePoint
  855. * releases given savepoint
  856. *
  857. * @param string $savepoint name of a savepoint to release
  858. * @return void
  859. */
  860. public function releaseSavepoint($savepoint)
  861. {
  862. if (!$this->_platform->supportsSavepoints()) {
  863. throw ConnectionException::savepointsNotSupported();
  864. }
  865. if ($this->_platform->supportsReleaseSavepoints()) {
  866. $this->_conn->exec($this->_platform->releaseSavePoint($savepoint));
  867. }
  868. }
  869. /**
  870. * rollbackSavePoint
  871. * releases given savepoint
  872. *
  873. * @param string $savepoint name of a savepoint to rollback to
  874. * @return void
  875. */
  876. public function rollbackSavepoint($savepoint)
  877. {
  878. if (!$this->_platform->supportsSavepoints()) {
  879. throw ConnectionException::savepointsNotSupported();
  880. }
  881. $this->_conn->exec($this->_platform->rollbackSavePoint($savepoint));
  882. }
  883. /**
  884. * Gets the wrapped driver connection.
  885. *
  886. * @return Doctrine\DBAL\Driver\Connection
  887. */
  888. public function getWrappedConnection()
  889. {
  890. $this->connect();
  891. return $this->_conn;
  892. }
  893. /**
  894. * Gets the SchemaManager that can be used to inspect or change the
  895. * database schema through the connection.
  896. *
  897. * @return Doctrine\DBAL\Schema\AbstractSchemaManager
  898. */
  899. public function getSchemaManager()
  900. {
  901. if ( ! $this->_schemaManager) {
  902. $this->_schemaManager = $this->_driver->getSchemaManager($this);
  903. }
  904. return $this->_schemaManager;
  905. }
  906. /**
  907. * Marks the current transaction so that the only possible
  908. * outcome for the transaction to be rolled back.
  909. *
  910. * @throws ConnectionException If no transaction is active.
  911. */
  912. public function setRollbackOnly()
  913. {
  914. if ($this->_transactionNestingLevel == 0) {
  915. throw ConnectionException::noActiveTransaction();
  916. }
  917. $this->_isRollbackOnly = true;
  918. }
  919. /**
  920. * Check whether the current transaction is marked for rollback only.
  921. *
  922. * @return boolean
  923. * @throws ConnectionException If no transaction is active.
  924. */
  925. public function isRollbackOnly()
  926. {
  927. if ($this->_transactionNestingLevel == 0) {
  928. throw ConnectionException::noActiveTransaction();
  929. }
  930. return $this->_isRollbackOnly;
  931. }
  932. /**
  933. * Converts a given value to its database representation according to the conversion
  934. * rules of a specific DBAL mapping type.
  935. *
  936. * @param mixed $value The value to convert.
  937. * @param string $type The name of the DBAL mapping type.
  938. * @return mixed The converted value.
  939. */
  940. public function convertToDatabaseValue($value, $type)
  941. {
  942. return Type::getType($type)->convertToDatabaseValue($value, $this->_platform);
  943. }
  944. /**
  945. * Converts a given value to its PHP representation according to the conversion
  946. * rules of a specific DBAL mapping type.
  947. *
  948. * @param mixed $value The value to convert.
  949. * @param string $type The name of the DBAL mapping type.
  950. * @return mixed The converted type.
  951. */
  952. public function convertToPHPValue($value, $type)
  953. {
  954. return Type::getType($type)->convertToPHPValue($value, $this->_platform);
  955. }
  956. /**
  957. * Binds a set of parameters, some or all of which are typed with a PDO binding type
  958. * or DBAL mapping type, to a given statement.
  959. *
  960. * @param $stmt The statement to bind the values to.
  961. * @param array $params The map/list of named/positional parameters.
  962. * @param array $types The parameter types (PDO binding types or DBAL mapping types).
  963. * @internal Duck-typing used on the $stmt parameter to support driver statements as well as
  964. * raw PDOStatement instances.
  965. */
  966. private function _bindTypedValues($stmt, array $params, array $types)
  967. {
  968. // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
  969. if (is_int(key($params))) {
  970. // Positional parameters
  971. $typeOffset = array_key_exists(0, $types) ? -1 : 0;
  972. $bindIndex = 1;
  973. foreach ($params as $position => $value) {
  974. $typeIndex = $bindIndex + $typeOffset;
  975. if (isset($types[$typeIndex])) {
  976. $type = $types[$typeIndex];
  977. list($value, $bindingType) = $this->getBindingInfo($value, $type);
  978. $stmt->bindValue($bindIndex, $value, $bindingType);
  979. } else {
  980. $stmt->bindValue($bindIndex, $value);
  981. }
  982. ++$bindIndex;
  983. }
  984. } else {
  985. // Named parameters
  986. foreach ($params as $name => $value) {
  987. if (isset($types[$name])) {
  988. $type = $types[$name];
  989. list($value, $bindingType) = $this->getBindingInfo($value, $type);
  990. $stmt->bindValue($name, $value, $bindingType);
  991. } else {
  992. $stmt->bindValue($name, $value);
  993. }
  994. }
  995. }
  996. }
  997. /**
  998. * Gets the binding type of a given type. The given type can be a PDO or DBAL mapping type.
  999. *
  1000. * @param mixed $value The value to bind
  1001. * @param mixed $type The type to bind (PDO or DBAL)
  1002. * @return array [0] => the (escaped) value, [1] => the binding type
  1003. */
  1004. private function getBindingInfo($value, $type)
  1005. {
  1006. if (is_string($type)) {
  1007. $type = Type::getType($type);
  1008. }
  1009. if ($type instanceof Type) {
  1010. $value = $type->convertToDatabaseValue($value, $this->_platform);
  1011. $bindingType = $type->getBindingType();
  1012. } else {
  1013. $bindingType = $type; // PDO::PARAM_* constants
  1014. }
  1015. return array($value, $bindingType);
  1016. }
  1017. /**
  1018. * Create a new instance of a SQL query builder.
  1019. *
  1020. * @return Query\QueryBuilder
  1021. */
  1022. public function createQueryBuilder()
  1023. {
  1024. return new Query\QueryBuilder($this);
  1025. }
  1026. }