Connection.php 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475
  1. <?php
  2. namespace Drupal\Core\Database;
  3. /**
  4. * Base Database API class.
  5. *
  6. * This class provides a Drupal-specific extension of the PDO database
  7. * abstraction class in PHP. Every database driver implementation must provide a
  8. * concrete implementation of it to support special handling required by that
  9. * database.
  10. *
  11. * @see http://php.net/manual/book.pdo.php
  12. */
  13. abstract class Connection {
  14. /**
  15. * The database target this connection is for.
  16. *
  17. * We need this information for later auditing and logging.
  18. *
  19. * @var string|null
  20. */
  21. protected $target = NULL;
  22. /**
  23. * The key representing this connection.
  24. *
  25. * The key is a unique string which identifies a database connection. A
  26. * connection can be a single server or a cluster of primary and replicas
  27. * (use target to pick between primary and replica).
  28. *
  29. * @var string|null
  30. */
  31. protected $key = NULL;
  32. /**
  33. * The current database logging object for this connection.
  34. *
  35. * @var \Drupal\Core\Database\Log|null
  36. */
  37. protected $logger = NULL;
  38. /**
  39. * Tracks the number of "layers" of transactions currently active.
  40. *
  41. * On many databases transactions cannot nest. Instead, we track
  42. * nested calls to transactions and collapse them into a single
  43. * transaction.
  44. *
  45. * @var array
  46. */
  47. protected $transactionLayers = [];
  48. /**
  49. * Index of what driver-specific class to use for various operations.
  50. *
  51. * @var array
  52. */
  53. protected $driverClasses = [];
  54. /**
  55. * The name of the Statement class for this connection.
  56. *
  57. * @var string
  58. */
  59. protected $statementClass = 'Drupal\Core\Database\Statement';
  60. /**
  61. * Whether this database connection supports transactions.
  62. *
  63. * @var bool
  64. */
  65. protected $transactionSupport = TRUE;
  66. /**
  67. * Whether this database connection supports transactional DDL.
  68. *
  69. * Set to FALSE by default because few databases support this feature.
  70. *
  71. * @var bool
  72. */
  73. protected $transactionalDDLSupport = FALSE;
  74. /**
  75. * An index used to generate unique temporary table names.
  76. *
  77. * @var int
  78. */
  79. protected $temporaryNameIndex = 0;
  80. /**
  81. * The actual PDO connection.
  82. *
  83. * @var \PDO
  84. */
  85. protected $connection;
  86. /**
  87. * The connection information for this connection object.
  88. *
  89. * @var array
  90. */
  91. protected $connectionOptions = [];
  92. /**
  93. * The schema object for this connection.
  94. *
  95. * Set to NULL when the schema is destroyed.
  96. *
  97. * @var \Drupal\Core\Database\Schema|null
  98. */
  99. protected $schema = NULL;
  100. /**
  101. * The prefixes used by this database connection.
  102. *
  103. * @var array
  104. */
  105. protected $prefixes = [];
  106. /**
  107. * List of search values for use in prefixTables().
  108. *
  109. * @var array
  110. */
  111. protected $prefixSearch = [];
  112. /**
  113. * List of replacement values for use in prefixTables().
  114. *
  115. * @var array
  116. */
  117. protected $prefixReplace = [];
  118. /**
  119. * List of un-prefixed table names, keyed by prefixed table names.
  120. *
  121. * @var array
  122. */
  123. protected $unprefixedTablesMap = [];
  124. /**
  125. * List of escaped database, table, and field names, keyed by unescaped names.
  126. *
  127. * @var array
  128. */
  129. protected $escapedNames = [];
  130. /**
  131. * List of escaped aliases names, keyed by unescaped aliases.
  132. *
  133. * @var array
  134. */
  135. protected $escapedAliases = [];
  136. /**
  137. * Constructs a Connection object.
  138. *
  139. * @param \PDO $connection
  140. * An object of the PDO class representing a database connection.
  141. * @param array $connection_options
  142. * An array of options for the connection. May include the following:
  143. * - prefix
  144. * - namespace
  145. * - Other driver-specific options.
  146. */
  147. public function __construct(\PDO $connection, array $connection_options) {
  148. // Initialize and prepare the connection prefix.
  149. $this->setPrefix(isset($connection_options['prefix']) ? $connection_options['prefix'] : '');
  150. // Set a Statement class, unless the driver opted out.
  151. if (!empty($this->statementClass)) {
  152. $connection->setAttribute(\PDO::ATTR_STATEMENT_CLASS, [$this->statementClass, [$this]]);
  153. }
  154. $this->connection = $connection;
  155. $this->connectionOptions = $connection_options;
  156. }
  157. /**
  158. * Opens a PDO connection.
  159. *
  160. * @param array $connection_options
  161. * The database connection settings array.
  162. *
  163. * @return \PDO
  164. * A \PDO object.
  165. */
  166. public static function open(array &$connection_options = []) {}
  167. /**
  168. * Destroys this Connection object.
  169. *
  170. * PHP does not destruct an object if it is still referenced in other
  171. * variables. In case of PDO database connection objects, PHP only closes the
  172. * connection when the PDO object is destructed, so any references to this
  173. * object may cause the number of maximum allowed connections to be exceeded.
  174. */
  175. public function destroy() {
  176. // Destroy all references to this connection by setting them to NULL.
  177. // The Statement class attribute only accepts a new value that presents a
  178. // proper callable, so we reset it to PDOStatement.
  179. if (!empty($this->statementClass)) {
  180. $this->connection->setAttribute(\PDO::ATTR_STATEMENT_CLASS, ['PDOStatement', []]);
  181. }
  182. $this->schema = NULL;
  183. }
  184. /**
  185. * Returns the default query options for any given query.
  186. *
  187. * A given query can be customized with a number of option flags in an
  188. * associative array:
  189. * - target: The database "target" against which to execute a query. Valid
  190. * values are "default" or "replica". The system will first try to open a
  191. * connection to a database specified with the user-supplied key. If one
  192. * is not available, it will silently fall back to the "default" target.
  193. * If multiple databases connections are specified with the same target,
  194. * one will be selected at random for the duration of the request.
  195. * - fetch: This element controls how rows from a result set will be
  196. * returned. Legal values include PDO::FETCH_ASSOC, PDO::FETCH_BOTH,
  197. * PDO::FETCH_OBJ, PDO::FETCH_NUM, or a string representing the name of a
  198. * class. If a string is specified, each record will be fetched into a new
  199. * object of that class. The behavior of all other values is defined by PDO.
  200. * See http://php.net/manual/pdostatement.fetch.php
  201. * - return: Depending on the type of query, different return values may be
  202. * meaningful. This directive instructs the system which type of return
  203. * value is desired. The system will generally set the correct value
  204. * automatically, so it is extremely rare that a module developer will ever
  205. * need to specify this value. Setting it incorrectly will likely lead to
  206. * unpredictable results or fatal errors. Legal values include:
  207. * - Database::RETURN_STATEMENT: Return the prepared statement object for
  208. * the query. This is usually only meaningful for SELECT queries, where
  209. * the statement object is how one accesses the result set returned by the
  210. * query.
  211. * - Database::RETURN_AFFECTED: Return the number of rows affected by an
  212. * UPDATE or DELETE query. Be aware that means the number of rows actually
  213. * changed, not the number of rows matched by the WHERE clause.
  214. * - Database::RETURN_INSERT_ID: Return the sequence ID (primary key)
  215. * created by an INSERT statement on a table that contains a serial
  216. * column.
  217. * - Database::RETURN_NULL: Do not return anything, as there is no
  218. * meaningful value to return. That is the case for INSERT queries on
  219. * tables that do not contain a serial column.
  220. * - throw_exception: By default, the database system will catch any errors
  221. * on a query as an Exception, log it, and then rethrow it so that code
  222. * further up the call chain can take an appropriate action. To suppress
  223. * that behavior and simply return NULL on failure, set this option to
  224. * FALSE.
  225. * - allow_delimiter_in_query: By default, queries which have the ; delimiter
  226. * any place in them will cause an exception. This reduces the chance of SQL
  227. * injection attacks that terminate the original query and add one or more
  228. * additional queries (such as inserting new user accounts). In rare cases,
  229. * such as creating an SQL function, a ; is needed and can be allowed by
  230. * changing this option to TRUE.
  231. *
  232. * @return array
  233. * An array of default query options.
  234. */
  235. protected function defaultOptions() {
  236. return [
  237. 'target' => 'default',
  238. 'fetch' => \PDO::FETCH_OBJ,
  239. 'return' => Database::RETURN_STATEMENT,
  240. 'throw_exception' => TRUE,
  241. 'allow_delimiter_in_query' => FALSE,
  242. ];
  243. }
  244. /**
  245. * Returns the connection information for this connection object.
  246. *
  247. * Note that Database::getConnectionInfo() is for requesting information
  248. * about an arbitrary database connection that is defined. This method
  249. * is for requesting the connection information of this specific
  250. * open connection object.
  251. *
  252. * @return array
  253. * An array of the connection information. The exact list of
  254. * properties is driver-dependent.
  255. */
  256. public function getConnectionOptions() {
  257. return $this->connectionOptions;
  258. }
  259. /**
  260. * Set the list of prefixes used by this database connection.
  261. *
  262. * @param array|string $prefix
  263. * Either a single prefix, or an array of prefixes, in any of the multiple
  264. * forms documented in default.settings.php.
  265. */
  266. protected function setPrefix($prefix) {
  267. if (is_array($prefix)) {
  268. $this->prefixes = $prefix + ['default' => ''];
  269. }
  270. else {
  271. $this->prefixes = ['default' => $prefix];
  272. }
  273. // Set up variables for use in prefixTables(). Replace table-specific
  274. // prefixes first.
  275. $this->prefixSearch = [];
  276. $this->prefixReplace = [];
  277. foreach ($this->prefixes as $key => $val) {
  278. if ($key != 'default') {
  279. $this->prefixSearch[] = '{' . $key . '}';
  280. $this->prefixReplace[] = $val . $key;
  281. }
  282. }
  283. // Then replace remaining tables with the default prefix.
  284. $this->prefixSearch[] = '{';
  285. $this->prefixReplace[] = $this->prefixes['default'];
  286. $this->prefixSearch[] = '}';
  287. $this->prefixReplace[] = '';
  288. // Set up a map of prefixed => un-prefixed tables.
  289. foreach ($this->prefixes as $table_name => $prefix) {
  290. if ($table_name !== 'default') {
  291. $this->unprefixedTablesMap[$prefix . $table_name] = $table_name;
  292. }
  293. }
  294. }
  295. /**
  296. * Appends a database prefix to all tables in a query.
  297. *
  298. * Queries sent to Drupal should wrap all table names in curly brackets. This
  299. * function searches for this syntax and adds Drupal's table prefix to all
  300. * tables, allowing Drupal to coexist with other systems in the same database
  301. * and/or schema if necessary.
  302. *
  303. * @param string $sql
  304. * A string containing a partial or entire SQL query.
  305. *
  306. * @return string
  307. * The properly-prefixed string.
  308. */
  309. public function prefixTables($sql) {
  310. return str_replace($this->prefixSearch, $this->prefixReplace, $sql);
  311. }
  312. /**
  313. * Find the prefix for a table.
  314. *
  315. * This function is for when you want to know the prefix of a table. This
  316. * is not used in prefixTables due to performance reasons.
  317. *
  318. * @param string $table
  319. * (optional) The table to find the prefix for.
  320. */
  321. public function tablePrefix($table = 'default') {
  322. if (isset($this->prefixes[$table])) {
  323. return $this->prefixes[$table];
  324. }
  325. else {
  326. return $this->prefixes['default'];
  327. }
  328. }
  329. /**
  330. * Gets a list of individually prefixed table names.
  331. *
  332. * @return array
  333. * An array of un-prefixed table names, keyed by their fully qualified table
  334. * names (i.e. prefix + table_name).
  335. */
  336. public function getUnprefixedTablesMap() {
  337. return $this->unprefixedTablesMap;
  338. }
  339. /**
  340. * Get a fully qualified table name.
  341. *
  342. * @param string $table
  343. * The name of the table in question.
  344. *
  345. * @return string
  346. */
  347. public function getFullQualifiedTableName($table) {
  348. $options = $this->getConnectionOptions();
  349. $prefix = $this->tablePrefix($table);
  350. return $options['database'] . '.' . $prefix . $table;
  351. }
  352. /**
  353. * Prepares a query string and returns the prepared statement.
  354. *
  355. * This method caches prepared statements, reusing them when
  356. * possible. It also prefixes tables names enclosed in curly-braces.
  357. *
  358. * @param $query
  359. * The query string as SQL, with curly-braces surrounding the
  360. * table names.
  361. *
  362. * @return \Drupal\Core\Database\StatementInterface
  363. * A PDO prepared statement ready for its execute() method.
  364. */
  365. public function prepareQuery($query) {
  366. $query = $this->prefixTables($query);
  367. return $this->connection->prepare($query);
  368. }
  369. /**
  370. * Tells this connection object what its target value is.
  371. *
  372. * This is needed for logging and auditing. It's sloppy to do in the
  373. * constructor because the constructor for child classes has a different
  374. * signature. We therefore also ensure that this function is only ever
  375. * called once.
  376. *
  377. * @param string $target
  378. * (optional) The target this connection is for.
  379. */
  380. public function setTarget($target = NULL) {
  381. if (!isset($this->target)) {
  382. $this->target = $target;
  383. }
  384. }
  385. /**
  386. * Returns the target this connection is associated with.
  387. *
  388. * @return string|null
  389. * The target string of this connection, or NULL if no target is set.
  390. */
  391. public function getTarget() {
  392. return $this->target;
  393. }
  394. /**
  395. * Tells this connection object what its key is.
  396. *
  397. * @param string $key
  398. * The key this connection is for.
  399. */
  400. public function setKey($key) {
  401. if (!isset($this->key)) {
  402. $this->key = $key;
  403. }
  404. }
  405. /**
  406. * Returns the key this connection is associated with.
  407. *
  408. * @return string|null
  409. * The key of this connection, or NULL if no key is set.
  410. */
  411. public function getKey() {
  412. return $this->key;
  413. }
  414. /**
  415. * Associates a logging object with this connection.
  416. *
  417. * @param \Drupal\Core\Database\Log $logger
  418. * The logging object we want to use.
  419. */
  420. public function setLogger(Log $logger) {
  421. $this->logger = $logger;
  422. }
  423. /**
  424. * Gets the current logging object for this connection.
  425. *
  426. * @return \Drupal\Core\Database\Log|null
  427. * The current logging object for this connection. If there isn't one,
  428. * NULL is returned.
  429. */
  430. public function getLogger() {
  431. return $this->logger;
  432. }
  433. /**
  434. * Creates the appropriate sequence name for a given table and serial field.
  435. *
  436. * This information is exposed to all database drivers, although it is only
  437. * useful on some of them. This method is table prefix-aware.
  438. *
  439. * @param string $table
  440. * The table name to use for the sequence.
  441. * @param string $field
  442. * The field name to use for the sequence.
  443. *
  444. * @return string
  445. * A table prefix-parsed string for the sequence name.
  446. */
  447. public function makeSequenceName($table, $field) {
  448. return $this->prefixTables('{' . $table . '}_' . $field . '_seq');
  449. }
  450. /**
  451. * Flatten an array of query comments into a single comment string.
  452. *
  453. * The comment string will be sanitized to avoid SQL injection attacks.
  454. *
  455. * @param string[] $comments
  456. * An array of query comment strings.
  457. *
  458. * @return string
  459. * A sanitized comment string.
  460. */
  461. public function makeComment($comments) {
  462. if (empty($comments)) {
  463. return '';
  464. }
  465. // Flatten the array of comments.
  466. $comment = implode('. ', $comments);
  467. // Sanitize the comment string so as to avoid SQL injection attacks.
  468. return '/* ' . $this->filterComment($comment) . ' */ ';
  469. }
  470. /**
  471. * Sanitize a query comment string.
  472. *
  473. * Ensure a query comment does not include strings such as "* /" that might
  474. * terminate the comment early. This avoids SQL injection attacks via the
  475. * query comment. The comment strings in this example are separated by a
  476. * space to avoid PHP parse errors.
  477. *
  478. * For example, the comment:
  479. * @code
  480. * db_update('example')
  481. * ->condition('id', $id)
  482. * ->fields(array('field2' => 10))
  483. * ->comment('Exploit * / DROP TABLE node; --')
  484. * ->execute()
  485. * @endcode
  486. *
  487. * Would result in the following SQL statement being generated:
  488. * @code
  489. * "/ * Exploit * / DROP TABLE node. -- * / UPDATE example SET field2=..."
  490. * @endcode
  491. *
  492. * Unless the comment is sanitised first, the SQL server would drop the
  493. * node table and ignore the rest of the SQL statement.
  494. *
  495. * @param string $comment
  496. * A query comment string.
  497. *
  498. * @return string
  499. * A sanitized version of the query comment string.
  500. */
  501. protected function filterComment($comment = '') {
  502. // Change semicolons to period to avoid triggering multi-statement check.
  503. return strtr($comment, ['*' => ' * ', ';' => '.']);
  504. }
  505. /**
  506. * Executes a query string against the database.
  507. *
  508. * This method provides a central handler for the actual execution of every
  509. * query. All queries executed by Drupal are executed as PDO prepared
  510. * statements.
  511. *
  512. * @param string|\Drupal\Core\Database\StatementInterface $query
  513. * The query to execute. In most cases this will be a string containing
  514. * an SQL query with placeholders. An already-prepared instance of
  515. * StatementInterface may also be passed in order to allow calling
  516. * code to manually bind variables to a query. If a
  517. * StatementInterface is passed, the $args array will be ignored.
  518. * It is extremely rare that module code will need to pass a statement
  519. * object to this method. It is used primarily for database drivers for
  520. * databases that require special LOB field handling.
  521. * @param array $args
  522. * An array of arguments for the prepared statement. If the prepared
  523. * statement uses ? placeholders, this array must be an indexed array.
  524. * If it contains named placeholders, it must be an associative array.
  525. * @param array $options
  526. * An associative array of options to control how the query is run. The
  527. * given options will be merged with self::defaultOptions(). See the
  528. * documentation for self::defaultOptions() for details.
  529. * Typically, $options['return'] will be set by a default or by a query
  530. * builder, and should not be set by a user.
  531. *
  532. * @return \Drupal\Core\Database\StatementInterface|int|null
  533. * This method will return one of the following:
  534. * - If either $options['return'] === self::RETURN_STATEMENT, or
  535. * $options['return'] is not set (due to self::defaultOptions()),
  536. * returns the executed statement.
  537. * - If $options['return'] === self::RETURN_AFFECTED,
  538. * returns the number of rows affected by the query
  539. * (not the number matched).
  540. * - If $options['return'] === self::RETURN_INSERT_ID,
  541. * returns the generated insert ID of the last query.
  542. * - If either $options['return'] === self::RETURN_NULL, or
  543. * an exception occurs and $options['throw_exception'] evaluates to FALSE,
  544. * returns NULL.
  545. *
  546. * @throws \Drupal\Core\Database\DatabaseExceptionWrapper
  547. * @throws \Drupal\Core\Database\IntegrityConstraintViolationException
  548. * @throws \InvalidArgumentException
  549. *
  550. * @see \Drupal\Core\Database\Connection::defaultOptions()
  551. */
  552. public function query($query, array $args = [], $options = []) {
  553. // Use default values if not already set.
  554. $options += $this->defaultOptions();
  555. try {
  556. // We allow either a pre-bound statement object or a literal string.
  557. // In either case, we want to end up with an executed statement object,
  558. // which we pass to PDOStatement::execute.
  559. if ($query instanceof StatementInterface) {
  560. $stmt = $query;
  561. $stmt->execute(NULL, $options);
  562. }
  563. else {
  564. $this->expandArguments($query, $args);
  565. // To protect against SQL injection, Drupal only supports executing one
  566. // statement at a time. Thus, the presence of a SQL delimiter (the
  567. // semicolon) is not allowed unless the option is set. Allowing
  568. // semicolons should only be needed for special cases like defining a
  569. // function or stored procedure in SQL. Trim any trailing delimiter to
  570. // minimize false positives.
  571. $query = rtrim($query, "; \t\n\r\0\x0B");
  572. if (strpos($query, ';') !== FALSE && empty($options['allow_delimiter_in_query'])) {
  573. throw new \InvalidArgumentException('; is not supported in SQL strings. Use only one statement at a time.');
  574. }
  575. $stmt = $this->prepareQuery($query);
  576. $stmt->execute($args, $options);
  577. }
  578. // Depending on the type of query we may need to return a different value.
  579. // See DatabaseConnection::defaultOptions() for a description of each
  580. // value.
  581. switch ($options['return']) {
  582. case Database::RETURN_STATEMENT:
  583. return $stmt;
  584. case Database::RETURN_AFFECTED:
  585. $stmt->allowRowCount = TRUE;
  586. return $stmt->rowCount();
  587. case Database::RETURN_INSERT_ID:
  588. $sequence_name = isset($options['sequence_name']) ? $options['sequence_name'] : NULL;
  589. return $this->connection->lastInsertId($sequence_name);
  590. case Database::RETURN_NULL:
  591. return NULL;
  592. default:
  593. throw new \PDOException('Invalid return directive: ' . $options['return']);
  594. }
  595. }
  596. catch (\PDOException $e) {
  597. // Most database drivers will return NULL here, but some of them
  598. // (e.g. the SQLite driver) may need to re-run the query, so the return
  599. // value will be the same as for static::query().
  600. return $this->handleQueryException($e, $query, $args, $options);
  601. }
  602. }
  603. /**
  604. * Wraps and re-throws any PDO exception thrown by static::query().
  605. *
  606. * @param \PDOException $e
  607. * The exception thrown by static::query().
  608. * @param $query
  609. * The query executed by static::query().
  610. * @param array $args
  611. * An array of arguments for the prepared statement.
  612. * @param array $options
  613. * An associative array of options to control how the query is run.
  614. *
  615. * @return \Drupal\Core\Database\StatementInterface|int|null
  616. * Most database drivers will return NULL when a PDO exception is thrown for
  617. * a query, but some of them may need to re-run the query, so they can also
  618. * return a \Drupal\Core\Database\StatementInterface object or an integer.
  619. *
  620. * @throws \Drupal\Core\Database\DatabaseExceptionWrapper
  621. * @throws \Drupal\Core\Database\IntegrityConstraintViolationException
  622. */
  623. protected function handleQueryException(\PDOException $e, $query, array $args = [], $options = []) {
  624. if ($options['throw_exception']) {
  625. // Wrap the exception in another exception, because PHP does not allow
  626. // overriding Exception::getMessage(). Its message is the extra database
  627. // debug information.
  628. $query_string = ($query instanceof StatementInterface) ? $query->getQueryString() : $query;
  629. $message = $e->getMessage() . ": " . $query_string . "; " . print_r($args, TRUE);
  630. // Match all SQLSTATE 23xxx errors.
  631. if (substr($e->getCode(), -6, -3) == '23') {
  632. $exception = new IntegrityConstraintViolationException($message, $e->getCode(), $e);
  633. }
  634. else {
  635. $exception = new DatabaseExceptionWrapper($message, 0, $e);
  636. }
  637. throw $exception;
  638. }
  639. return NULL;
  640. }
  641. /**
  642. * Expands out shorthand placeholders.
  643. *
  644. * Drupal supports an alternate syntax for doing arrays of values. We
  645. * therefore need to expand them out into a full, executable query string.
  646. *
  647. * @param string $query
  648. * The query string to modify.
  649. * @param array $args
  650. * The arguments for the query.
  651. *
  652. * @return bool
  653. * TRUE if the query was modified, FALSE otherwise.
  654. *
  655. * @throws \InvalidArgumentException
  656. * This exception is thrown when:
  657. * - A placeholder that ends in [] is supplied, and the supplied value is
  658. * not an array.
  659. * - A placeholder that does not end in [] is supplied, and the supplied
  660. * value is an array.
  661. */
  662. protected function expandArguments(&$query, &$args) {
  663. $modified = FALSE;
  664. // If the placeholder indicated the value to use is an array, we need to
  665. // expand it out into a comma-delimited set of placeholders.
  666. foreach ($args as $key => $data) {
  667. $is_bracket_placeholder = substr($key, -2) === '[]';
  668. $is_array_data = is_array($data);
  669. if ($is_bracket_placeholder && !$is_array_data) {
  670. throw new \InvalidArgumentException('Placeholders with a trailing [] can only be expanded with an array of values.');
  671. }
  672. elseif (!$is_bracket_placeholder) {
  673. if ($is_array_data) {
  674. throw new \InvalidArgumentException('Placeholders must have a trailing [] if they are to be expanded with an array of values.');
  675. }
  676. // Scalar placeholder - does not need to be expanded.
  677. continue;
  678. }
  679. // Handle expansion of arrays.
  680. $key_name = str_replace('[]', '__', $key);
  681. $new_keys = [];
  682. // We require placeholders to have trailing brackets if the developer
  683. // intends them to be expanded to an array to make the intent explicit.
  684. foreach (array_values($data) as $i => $value) {
  685. // This assumes that there are no other placeholders that use the same
  686. // name. For example, if the array placeholder is defined as :example[]
  687. // and there is already an :example_2 placeholder, this will generate
  688. // a duplicate key. We do not account for that as the calling code
  689. // is already broken if that happens.
  690. $new_keys[$key_name . $i] = $value;
  691. }
  692. // Update the query with the new placeholders.
  693. $query = str_replace($key, implode(', ', array_keys($new_keys)), $query);
  694. // Update the args array with the new placeholders.
  695. unset($args[$key]);
  696. $args += $new_keys;
  697. $modified = TRUE;
  698. }
  699. return $modified;
  700. }
  701. /**
  702. * Gets the driver-specific override class if any for the specified class.
  703. *
  704. * @param string $class
  705. * The class for which we want the potentially driver-specific class.
  706. * @return string
  707. * The name of the class that should be used for this driver.
  708. */
  709. public function getDriverClass($class) {
  710. if (empty($this->driverClasses[$class])) {
  711. if (empty($this->connectionOptions['namespace'])) {
  712. // Fallback for Drupal 7 settings.php and the test runner script.
  713. $this->connectionOptions['namespace'] = (new \ReflectionObject($this))->getNamespaceName();
  714. }
  715. $driver_class = $this->connectionOptions['namespace'] . '\\' . $class;
  716. $this->driverClasses[$class] = class_exists($driver_class) ? $driver_class : $class;
  717. }
  718. return $this->driverClasses[$class];
  719. }
  720. /**
  721. * Prepares and returns a SELECT query object.
  722. *
  723. * @param string $table
  724. * The base table for this query, that is, the first table in the FROM
  725. * clause. This table will also be used as the "base" table for query_alter
  726. * hook implementations.
  727. * @param string $alias
  728. * (optional) The alias of the base table of this query.
  729. * @param $options
  730. * An array of options on the query.
  731. *
  732. * @return \Drupal\Core\Database\Query\SelectInterface
  733. * An appropriate SelectQuery object for this database connection. Note that
  734. * it may be a driver-specific subclass of SelectQuery, depending on the
  735. * driver.
  736. *
  737. * @see \Drupal\Core\Database\Query\Select
  738. */
  739. public function select($table, $alias = NULL, array $options = []) {
  740. $class = $this->getDriverClass('Select');
  741. return new $class($table, $alias, $this, $options);
  742. }
  743. /**
  744. * Prepares and returns an INSERT query object.
  745. *
  746. * @param string $table
  747. * The table to use for the insert statement.
  748. * @param array $options
  749. * (optional) An array of options on the query.
  750. *
  751. * @return \Drupal\Core\Database\Query\Insert
  752. * A new Insert query object.
  753. *
  754. * @see \Drupal\Core\Database\Query\Insert
  755. */
  756. public function insert($table, array $options = []) {
  757. $class = $this->getDriverClass('Insert');
  758. return new $class($this, $table, $options);
  759. }
  760. /**
  761. * Prepares and returns a MERGE query object.
  762. *
  763. * @param string $table
  764. * The table to use for the merge statement.
  765. * @param array $options
  766. * (optional) An array of options on the query.
  767. *
  768. * @return \Drupal\Core\Database\Query\Merge
  769. * A new Merge query object.
  770. *
  771. * @see \Drupal\Core\Database\Query\Merge
  772. */
  773. public function merge($table, array $options = []) {
  774. $class = $this->getDriverClass('Merge');
  775. return new $class($this, $table, $options);
  776. }
  777. /**
  778. * Prepares and returns an UPSERT query object.
  779. *
  780. * @param string $table
  781. * The table to use for the upsert query.
  782. * @param array $options
  783. * (optional) An array of options on the query.
  784. *
  785. * @return \Drupal\Core\Database\Query\Upsert
  786. * A new Upsert query object.
  787. *
  788. * @see \Drupal\Core\Database\Query\Upsert
  789. */
  790. public function upsert($table, array $options = []) {
  791. $class = $this->getDriverClass('Upsert');
  792. return new $class($this, $table, $options);
  793. }
  794. /**
  795. * Prepares and returns an UPDATE query object.
  796. *
  797. * @param string $table
  798. * The table to use for the update statement.
  799. * @param array $options
  800. * (optional) An array of options on the query.
  801. *
  802. * @return \Drupal\Core\Database\Query\Update
  803. * A new Update query object.
  804. *
  805. * @see \Drupal\Core\Database\Query\Update
  806. */
  807. public function update($table, array $options = []) {
  808. $class = $this->getDriverClass('Update');
  809. return new $class($this, $table, $options);
  810. }
  811. /**
  812. * Prepares and returns a DELETE query object.
  813. *
  814. * @param string $table
  815. * The table to use for the delete statement.
  816. * @param array $options
  817. * (optional) An array of options on the query.
  818. *
  819. * @return \Drupal\Core\Database\Query\Delete
  820. * A new Delete query object.
  821. *
  822. * @see \Drupal\Core\Database\Query\Delete
  823. */
  824. public function delete($table, array $options = []) {
  825. $class = $this->getDriverClass('Delete');
  826. return new $class($this, $table, $options);
  827. }
  828. /**
  829. * Prepares and returns a TRUNCATE query object.
  830. *
  831. * @param string $table
  832. * The table to use for the truncate statement.
  833. * @param array $options
  834. * (optional) An array of options on the query.
  835. *
  836. * @return \Drupal\Core\Database\Query\Truncate
  837. * A new Truncate query object.
  838. *
  839. * @see \Drupal\Core\Database\Query\Truncate
  840. */
  841. public function truncate($table, array $options = []) {
  842. $class = $this->getDriverClass('Truncate');
  843. return new $class($this, $table, $options);
  844. }
  845. /**
  846. * Returns a DatabaseSchema object for manipulating the schema.
  847. *
  848. * This method will lazy-load the appropriate schema library file.
  849. *
  850. * @return \Drupal\Core\Database\Schema
  851. * The database Schema object for this connection.
  852. */
  853. public function schema() {
  854. if (empty($this->schema)) {
  855. $class = $this->getDriverClass('Schema');
  856. $this->schema = new $class($this);
  857. }
  858. return $this->schema;
  859. }
  860. /**
  861. * Escapes a database name string.
  862. *
  863. * Force all database names to be strictly alphanumeric-plus-underscore.
  864. * For some database drivers, it may also wrap the database name in
  865. * database-specific escape characters.
  866. *
  867. * @param string $database
  868. * An unsanitized database name.
  869. *
  870. * @return string
  871. * The sanitized database name.
  872. */
  873. public function escapeDatabase($database) {
  874. if (!isset($this->escapedNames[$database])) {
  875. $this->escapedNames[$database] = preg_replace('/[^A-Za-z0-9_.]+/', '', $database);
  876. }
  877. return $this->escapedNames[$database];
  878. }
  879. /**
  880. * Escapes a table name string.
  881. *
  882. * Force all table names to be strictly alphanumeric-plus-underscore.
  883. * For some database drivers, it may also wrap the table name in
  884. * database-specific escape characters.
  885. *
  886. * @param string $table
  887. * An unsanitized table name.
  888. *
  889. * @return string
  890. * The sanitized table name.
  891. */
  892. public function escapeTable($table) {
  893. if (!isset($this->escapedNames[$table])) {
  894. $this->escapedNames[$table] = preg_replace('/[^A-Za-z0-9_.]+/', '', $table);
  895. }
  896. return $this->escapedNames[$table];
  897. }
  898. /**
  899. * Escapes a field name string.
  900. *
  901. * Force all field names to be strictly alphanumeric-plus-underscore.
  902. * For some database drivers, it may also wrap the field name in
  903. * database-specific escape characters.
  904. *
  905. * @param string $field
  906. * An unsanitized field name.
  907. *
  908. * @return string
  909. * The sanitized field name.
  910. */
  911. public function escapeField($field) {
  912. if (!isset($this->escapedNames[$field])) {
  913. $this->escapedNames[$field] = preg_replace('/[^A-Za-z0-9_.]+/', '', $field);
  914. }
  915. return $this->escapedNames[$field];
  916. }
  917. /**
  918. * Escapes an alias name string.
  919. *
  920. * Force all alias names to be strictly alphanumeric-plus-underscore. In
  921. * contrast to DatabaseConnection::escapeField() /
  922. * DatabaseConnection::escapeTable(), this doesn't allow the period (".")
  923. * because that is not allowed in aliases.
  924. *
  925. * @param string $field
  926. * An unsanitized alias name.
  927. *
  928. * @return string
  929. * The sanitized alias name.
  930. */
  931. public function escapeAlias($field) {
  932. if (!isset($this->escapedAliases[$field])) {
  933. $this->escapedAliases[$field] = preg_replace('/[^A-Za-z0-9_]+/', '', $field);
  934. }
  935. return $this->escapedAliases[$field];
  936. }
  937. /**
  938. * Escapes characters that work as wildcard characters in a LIKE pattern.
  939. *
  940. * The wildcard characters "%" and "_" as well as backslash are prefixed with
  941. * a backslash. Use this to do a search for a verbatim string without any
  942. * wildcard behavior.
  943. *
  944. * For example, the following does a case-insensitive query for all rows whose
  945. * name starts with $prefix:
  946. * @code
  947. * $result = db_query(
  948. * 'SELECT * FROM person WHERE name LIKE :pattern',
  949. * array(':pattern' => db_like($prefix) . '%')
  950. * );
  951. * @endcode
  952. *
  953. * Backslash is defined as escape character for LIKE patterns in
  954. * Drupal\Core\Database\Query\Condition::mapConditionOperator().
  955. *
  956. * @param string $string
  957. * The string to escape.
  958. *
  959. * @return string
  960. * The escaped string.
  961. */
  962. public function escapeLike($string) {
  963. return addcslashes($string, '\%_');
  964. }
  965. /**
  966. * Determines if there is an active transaction open.
  967. *
  968. * @return bool
  969. * TRUE if we're currently in a transaction, FALSE otherwise.
  970. */
  971. public function inTransaction() {
  972. return ($this->transactionDepth() > 0);
  973. }
  974. /**
  975. * Determines the current transaction depth.
  976. *
  977. * @return int
  978. * The current transaction depth.
  979. */
  980. public function transactionDepth() {
  981. return count($this->transactionLayers);
  982. }
  983. /**
  984. * Returns a new DatabaseTransaction object on this connection.
  985. *
  986. * @param string $name
  987. * (optional) The name of the savepoint.
  988. *
  989. * @return \Drupal\Core\Database\Transaction
  990. * A Transaction object.
  991. *
  992. * @see \Drupal\Core\Database\Transaction
  993. */
  994. public function startTransaction($name = '') {
  995. $class = $this->getDriverClass('Transaction');
  996. return new $class($this, $name);
  997. }
  998. /**
  999. * Rolls back the transaction entirely or to a named savepoint.
  1000. *
  1001. * This method throws an exception if no transaction is active.
  1002. *
  1003. * @param string $savepoint_name
  1004. * (optional) The name of the savepoint. The default, 'drupal_transaction',
  1005. * will roll the entire transaction back.
  1006. *
  1007. * @throws \Drupal\Core\Database\TransactionOutOfOrderException
  1008. * @throws \Drupal\Core\Database\TransactionNoActiveException
  1009. *
  1010. * @see \Drupal\Core\Database\Transaction::rollBack()
  1011. */
  1012. public function rollBack($savepoint_name = 'drupal_transaction') {
  1013. if (!$this->supportsTransactions()) {
  1014. return;
  1015. }
  1016. if (!$this->inTransaction()) {
  1017. throw new TransactionNoActiveException();
  1018. }
  1019. // A previous rollback to an earlier savepoint may mean that the savepoint
  1020. // in question has already been accidentally committed.
  1021. if (!isset($this->transactionLayers[$savepoint_name])) {
  1022. throw new TransactionNoActiveException();
  1023. }
  1024. // We need to find the point we're rolling back to, all other savepoints
  1025. // before are no longer needed. If we rolled back other active savepoints,
  1026. // we need to throw an exception.
  1027. $rolled_back_other_active_savepoints = FALSE;
  1028. while ($savepoint = array_pop($this->transactionLayers)) {
  1029. if ($savepoint == $savepoint_name) {
  1030. // If it is the last the transaction in the stack, then it is not a
  1031. // savepoint, it is the transaction itself so we will need to roll back
  1032. // the transaction rather than a savepoint.
  1033. if (empty($this->transactionLayers)) {
  1034. break;
  1035. }
  1036. $this->query('ROLLBACK TO SAVEPOINT ' . $savepoint);
  1037. $this->popCommittableTransactions();
  1038. if ($rolled_back_other_active_savepoints) {
  1039. throw new TransactionOutOfOrderException();
  1040. }
  1041. return;
  1042. }
  1043. else {
  1044. $rolled_back_other_active_savepoints = TRUE;
  1045. }
  1046. }
  1047. $this->connection->rollBack();
  1048. if ($rolled_back_other_active_savepoints) {
  1049. throw new TransactionOutOfOrderException();
  1050. }
  1051. }
  1052. /**
  1053. * Increases the depth of transaction nesting.
  1054. *
  1055. * If no transaction is already active, we begin a new transaction.
  1056. *
  1057. * @param string $name
  1058. * The name of the transaction.
  1059. *
  1060. * @throws \Drupal\Core\Database\TransactionNameNonUniqueException
  1061. *
  1062. * @see \Drupal\Core\Database\Transaction
  1063. */
  1064. public function pushTransaction($name) {
  1065. if (!$this->supportsTransactions()) {
  1066. return;
  1067. }
  1068. if (isset($this->transactionLayers[$name])) {
  1069. throw new TransactionNameNonUniqueException($name . " is already in use.");
  1070. }
  1071. // If we're already in a transaction then we want to create a savepoint
  1072. // rather than try to create another transaction.
  1073. if ($this->inTransaction()) {
  1074. $this->query('SAVEPOINT ' . $name);
  1075. }
  1076. else {
  1077. $this->connection->beginTransaction();
  1078. }
  1079. $this->transactionLayers[$name] = $name;
  1080. }
  1081. /**
  1082. * Decreases the depth of transaction nesting.
  1083. *
  1084. * If we pop off the last transaction layer, then we either commit or roll
  1085. * back the transaction as necessary. If no transaction is active, we return
  1086. * because the transaction may have manually been rolled back.
  1087. *
  1088. * @param string $name
  1089. * The name of the savepoint.
  1090. *
  1091. * @throws \Drupal\Core\Database\TransactionNoActiveException
  1092. * @throws \Drupal\Core\Database\TransactionCommitFailedException
  1093. *
  1094. * @see \Drupal\Core\Database\Transaction
  1095. */
  1096. public function popTransaction($name) {
  1097. if (!$this->supportsTransactions()) {
  1098. return;
  1099. }
  1100. // The transaction has already been committed earlier. There is nothing we
  1101. // need to do. If this transaction was part of an earlier out-of-order
  1102. // rollback, an exception would already have been thrown by
  1103. // Database::rollBack().
  1104. if (!isset($this->transactionLayers[$name])) {
  1105. return;
  1106. }
  1107. // Mark this layer as committable.
  1108. $this->transactionLayers[$name] = FALSE;
  1109. $this->popCommittableTransactions();
  1110. }
  1111. /**
  1112. * Internal function: commit all the transaction layers that can commit.
  1113. */
  1114. protected function popCommittableTransactions() {
  1115. // Commit all the committable layers.
  1116. foreach (array_reverse($this->transactionLayers) as $name => $active) {
  1117. // Stop once we found an active transaction.
  1118. if ($active) {
  1119. break;
  1120. }
  1121. // If there are no more layers left then we should commit.
  1122. unset($this->transactionLayers[$name]);
  1123. if (empty($this->transactionLayers)) {
  1124. if (!$this->connection->commit()) {
  1125. throw new TransactionCommitFailedException();
  1126. }
  1127. }
  1128. else {
  1129. $this->query('RELEASE SAVEPOINT ' . $name);
  1130. }
  1131. }
  1132. }
  1133. /**
  1134. * Runs a limited-range query on this database object.
  1135. *
  1136. * Use this as a substitute for ->query() when a subset of the query is to be
  1137. * returned. User-supplied arguments to the query should be passed in as
  1138. * separate parameters so that they can be properly escaped to avoid SQL
  1139. * injection attacks.
  1140. *
  1141. * @param string $query
  1142. * A string containing an SQL query.
  1143. * @param int $from
  1144. * The first result row to return.
  1145. * @param int $count
  1146. * The maximum number of result rows to return.
  1147. * @param array $args
  1148. * (optional) An array of values to substitute into the query at placeholder
  1149. * markers.
  1150. * @param array $options
  1151. * (optional) An array of options on the query.
  1152. *
  1153. * @return \Drupal\Core\Database\StatementInterface
  1154. * A database query result resource, or NULL if the query was not executed
  1155. * correctly.
  1156. */
  1157. abstract public function queryRange($query, $from, $count, array $args = [], array $options = []);
  1158. /**
  1159. * Generates a temporary table name.
  1160. *
  1161. * @return string
  1162. * A table name.
  1163. */
  1164. protected function generateTemporaryTableName() {
  1165. return "db_temporary_" . $this->temporaryNameIndex++;
  1166. }
  1167. /**
  1168. * Runs a SELECT query and stores its results in a temporary table.
  1169. *
  1170. * Use this as a substitute for ->query() when the results need to stored
  1171. * in a temporary table. Temporary tables exist for the duration of the page
  1172. * request. User-supplied arguments to the query should be passed in as
  1173. * separate parameters so that they can be properly escaped to avoid SQL
  1174. * injection attacks.
  1175. *
  1176. * Note that if you need to know how many results were returned, you should do
  1177. * a SELECT COUNT(*) on the temporary table afterwards.
  1178. *
  1179. * @param string $query
  1180. * A string containing a normal SELECT SQL query.
  1181. * @param array $args
  1182. * (optional) An array of values to substitute into the query at placeholder
  1183. * markers.
  1184. * @param array $options
  1185. * (optional) An associative array of options to control how the query is
  1186. * run. See the documentation for DatabaseConnection::defaultOptions() for
  1187. * details.
  1188. *
  1189. * @return string
  1190. * The name of the temporary table.
  1191. */
  1192. abstract public function queryTemporary($query, array $args = [], array $options = []);
  1193. /**
  1194. * Returns the type of database driver.
  1195. *
  1196. * This is not necessarily the same as the type of the database itself. For
  1197. * instance, there could be two MySQL drivers, mysql and mysql_mock. This
  1198. * function would return different values for each, but both would return
  1199. * "mysql" for databaseType().
  1200. *
  1201. * @return string
  1202. * The type of database driver.
  1203. */
  1204. abstract public function driver();
  1205. /**
  1206. * Returns the version of the database server.
  1207. */
  1208. public function version() {
  1209. return $this->connection->getAttribute(\PDO::ATTR_SERVER_VERSION);
  1210. }
  1211. /**
  1212. * Returns the version of the database client.
  1213. */
  1214. public function clientVersion() {
  1215. return $this->connection->getAttribute(\PDO::ATTR_CLIENT_VERSION);
  1216. }
  1217. /**
  1218. * Determines if this driver supports transactions.
  1219. *
  1220. * @return bool
  1221. * TRUE if this connection supports transactions, FALSE otherwise.
  1222. */
  1223. public function supportsTransactions() {
  1224. return $this->transactionSupport;
  1225. }
  1226. /**
  1227. * Determines if this driver supports transactional DDL.
  1228. *
  1229. * DDL queries are those that change the schema, such as ALTER queries.
  1230. *
  1231. * @return bool
  1232. * TRUE if this connection supports transactions for DDL queries, FALSE
  1233. * otherwise.
  1234. */
  1235. public function supportsTransactionalDDL() {
  1236. return $this->transactionalDDLSupport;
  1237. }
  1238. /**
  1239. * Returns the name of the PDO driver for this connection.
  1240. */
  1241. abstract public function databaseType();
  1242. /**
  1243. * Creates a database.
  1244. *
  1245. * In order to use this method, you must be connected without a database
  1246. * specified.
  1247. *
  1248. * @param string $database
  1249. * The name of the database to create.
  1250. */
  1251. abstract public function createDatabase($database);
  1252. /**
  1253. * Gets any special processing requirements for the condition operator.
  1254. *
  1255. * Some condition types require special processing, such as IN, because
  1256. * the value data they pass in is not a simple value. This is a simple
  1257. * overridable lookup function. Database connections should define only
  1258. * those operators they wish to be handled differently than the default.
  1259. *
  1260. * @param string $operator
  1261. * The condition operator, such as "IN", "BETWEEN", etc. Case-sensitive.
  1262. *
  1263. * @return
  1264. * The extra handling directives for the specified operator, or NULL.
  1265. *
  1266. * @see \Drupal\Core\Database\Query\Condition::compile()
  1267. */
  1268. abstract public function mapConditionOperator($operator);
  1269. /**
  1270. * Throws an exception to deny direct access to transaction commits.
  1271. *
  1272. * We do not want to allow users to commit transactions at any time, only
  1273. * by destroying the transaction object or allowing it to go out of scope.
  1274. * A direct commit bypasses all of the safety checks we've built on top of
  1275. * PDO's transaction routines.
  1276. *
  1277. * @throws \Drupal\Core\Database\TransactionExplicitCommitNotAllowedException
  1278. *
  1279. * @see \Drupal\Core\Database\Transaction
  1280. */
  1281. public function commit() {
  1282. throw new TransactionExplicitCommitNotAllowedException();
  1283. }
  1284. /**
  1285. * Retrieves an unique ID from a given sequence.
  1286. *
  1287. * Use this function if for some reason you can't use a serial field. For
  1288. * example, MySQL has no ways of reading of the current value of a sequence
  1289. * and PostgreSQL can not advance the sequence to be larger than a given
  1290. * value. Or sometimes you just need a unique integer.
  1291. *
  1292. * @param $existing_id
  1293. * (optional) After a database import, it might be that the sequences table
  1294. * is behind, so by passing in the maximum existing ID, it can be assured
  1295. * that we never issue the same ID.
  1296. *
  1297. * @return
  1298. * An integer number larger than any number returned by earlier calls and
  1299. * also larger than the $existing_id if one was passed in.
  1300. */
  1301. abstract public function nextId($existing_id = 0);
  1302. /**
  1303. * Prepares a statement for execution and returns a statement object
  1304. *
  1305. * Emulated prepared statements does not communicate with the database server
  1306. * so this method does not check the statement.
  1307. *
  1308. * @param string $statement
  1309. * This must be a valid SQL statement for the target database server.
  1310. * @param array $driver_options
  1311. * (optional) This array holds one or more key=>value pairs to set
  1312. * attribute values for the PDOStatement object that this method returns.
  1313. * You would most commonly use this to set the \PDO::ATTR_CURSOR value to
  1314. * \PDO::CURSOR_SCROLL to request a scrollable cursor. Some drivers have
  1315. * driver specific options that may be set at prepare-time. Defaults to an
  1316. * empty array.
  1317. *
  1318. * @return \PDOStatement|false
  1319. * If the database server successfully prepares the statement, returns a
  1320. * \PDOStatement object.
  1321. * If the database server cannot successfully prepare the statement returns
  1322. * FALSE or emits \PDOException (depending on error handling).
  1323. *
  1324. * @throws \PDOException
  1325. *
  1326. * @see \PDO::prepare()
  1327. */
  1328. public function prepare($statement, array $driver_options = []) {
  1329. return $this->connection->prepare($statement, $driver_options);
  1330. }
  1331. /**
  1332. * Quotes a string for use in a query.
  1333. *
  1334. * @param string $string
  1335. * The string to be quoted.
  1336. * @param int $parameter_type
  1337. * (optional) Provides a data type hint for drivers that have alternate
  1338. * quoting styles. Defaults to \PDO::PARAM_STR.
  1339. *
  1340. * @return string|bool
  1341. * A quoted string that is theoretically safe to pass into an SQL statement.
  1342. * Returns FALSE if the driver does not support quoting in this way.
  1343. *
  1344. * @see \PDO::quote()
  1345. */
  1346. public function quote($string, $parameter_type = \PDO::PARAM_STR) {
  1347. return $this->connection->quote($string, $parameter_type);
  1348. }
  1349. /**
  1350. * Extracts the SQLSTATE error from the PDOException.
  1351. *
  1352. * @param \Exception $e
  1353. * The exception
  1354. *
  1355. * @return string
  1356. * The five character error code.
  1357. */
  1358. protected static function getSQLState(\Exception $e) {
  1359. // The PDOException code is not always reliable, try to see whether the
  1360. // message has something usable.
  1361. if (preg_match('/^SQLSTATE\[(\w{5})\]/', $e->getMessage(), $matches)) {
  1362. return $matches[1];
  1363. }
  1364. else {
  1365. return $e->getCode();
  1366. }
  1367. }
  1368. /**
  1369. * Prevents the database connection from being serialized.
  1370. */
  1371. public function __sleep() {
  1372. throw new \LogicException('The database connection is not serializable. This probably means you are serializing an object that has an indirect reference to the database connection. Adjust your code so that is not necessary. Alternatively, look at DependencySerializationTrait as a temporary solution.');
  1373. }
  1374. }