Connection.php 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696
  1. <?php
  2. namespace Drupal\Core\Database;
  3. use Drupal\Core\Database\Query\Condition;
  4. /**
  5. * Base Database API class.
  6. *
  7. * This class provides a Drupal-specific extension of the PDO database
  8. * abstraction class in PHP. Every database driver implementation must provide a
  9. * concrete implementation of it to support special handling required by that
  10. * database.
  11. *
  12. * @see http://php.net/manual/book.pdo.php
  13. */
  14. abstract class Connection {
  15. /**
  16. * The database target this connection is for.
  17. *
  18. * We need this information for later auditing and logging.
  19. *
  20. * @var string|null
  21. */
  22. protected $target = NULL;
  23. /**
  24. * The key representing this connection.
  25. *
  26. * The key is a unique string which identifies a database connection. A
  27. * connection can be a single server or a cluster of primary and replicas
  28. * (use target to pick between primary and replica).
  29. *
  30. * @var string|null
  31. */
  32. protected $key = NULL;
  33. /**
  34. * The current database logging object for this connection.
  35. *
  36. * @var \Drupal\Core\Database\Log|null
  37. */
  38. protected $logger = NULL;
  39. /**
  40. * Tracks the number of "layers" of transactions currently active.
  41. *
  42. * On many databases transactions cannot nest. Instead, we track
  43. * nested calls to transactions and collapse them into a single
  44. * transaction.
  45. *
  46. * @var array
  47. */
  48. protected $transactionLayers = [];
  49. /**
  50. * Index of what driver-specific class to use for various operations.
  51. *
  52. * @var array
  53. */
  54. protected $driverClasses = [];
  55. /**
  56. * The name of the Statement class for this connection.
  57. *
  58. * @var string
  59. */
  60. protected $statementClass = 'Drupal\Core\Database\Statement';
  61. /**
  62. * Whether this database connection supports transactions.
  63. *
  64. * @var bool
  65. */
  66. protected $transactionSupport = TRUE;
  67. /**
  68. * Whether this database connection supports transactional DDL.
  69. *
  70. * Set to FALSE by default because few databases support this feature.
  71. *
  72. * @var bool
  73. */
  74. protected $transactionalDDLSupport = FALSE;
  75. /**
  76. * An index used to generate unique temporary table names.
  77. *
  78. * @var int
  79. */
  80. protected $temporaryNameIndex = 0;
  81. /**
  82. * The actual PDO connection.
  83. *
  84. * @var \PDO
  85. */
  86. protected $connection;
  87. /**
  88. * The connection information for this connection object.
  89. *
  90. * @var array
  91. */
  92. protected $connectionOptions = [];
  93. /**
  94. * The schema object for this connection.
  95. *
  96. * Set to NULL when the schema is destroyed.
  97. *
  98. * @var \Drupal\Core\Database\Schema|null
  99. */
  100. protected $schema = NULL;
  101. /**
  102. * The prefixes used by this database connection.
  103. *
  104. * @var array
  105. */
  106. protected $prefixes = [];
  107. /**
  108. * List of search values for use in prefixTables().
  109. *
  110. * @var array
  111. */
  112. protected $prefixSearch = [];
  113. /**
  114. * List of replacement values for use in prefixTables().
  115. *
  116. * @var array
  117. */
  118. protected $prefixReplace = [];
  119. /**
  120. * List of un-prefixed table names, keyed by prefixed table names.
  121. *
  122. * @var array
  123. */
  124. protected $unprefixedTablesMap = [];
  125. /**
  126. * List of escaped database, table, and field names, keyed by unescaped names.
  127. *
  128. * @var array
  129. */
  130. protected $escapedNames = [];
  131. /**
  132. * List of escaped aliases names, keyed by unescaped aliases.
  133. *
  134. * @var array
  135. */
  136. protected $escapedAliases = [];
  137. /**
  138. * Post-root (non-nested) transaction commit callbacks.
  139. *
  140. * @var callable[]
  141. */
  142. protected $rootTransactionEndCallbacks = [];
  143. /**
  144. * Constructs a Connection object.
  145. *
  146. * @param \PDO $connection
  147. * An object of the PDO class representing a database connection.
  148. * @param array $connection_options
  149. * An array of options for the connection. May include the following:
  150. * - prefix
  151. * - namespace
  152. * - Other driver-specific options.
  153. */
  154. public function __construct(\PDO $connection, array $connection_options) {
  155. // Initialize and prepare the connection prefix.
  156. $this->setPrefix(isset($connection_options['prefix']) ? $connection_options['prefix'] : '');
  157. // Set a Statement class, unless the driver opted out.
  158. if (!empty($this->statementClass)) {
  159. $connection->setAttribute(\PDO::ATTR_STATEMENT_CLASS, [$this->statementClass, [$this]]);
  160. }
  161. $this->connection = $connection;
  162. $this->connectionOptions = $connection_options;
  163. }
  164. /**
  165. * Opens a PDO connection.
  166. *
  167. * @param array $connection_options
  168. * The database connection settings array.
  169. *
  170. * @return \PDO
  171. * A \PDO object.
  172. */
  173. public static function open(array &$connection_options = []) {}
  174. /**
  175. * Destroys this Connection object.
  176. *
  177. * PHP does not destruct an object if it is still referenced in other
  178. * variables. In case of PDO database connection objects, PHP only closes the
  179. * connection when the PDO object is destructed, so any references to this
  180. * object may cause the number of maximum allowed connections to be exceeded.
  181. */
  182. public function destroy() {
  183. // Destroy all references to this connection by setting them to NULL.
  184. // The Statement class attribute only accepts a new value that presents a
  185. // proper callable, so we reset it to PDOStatement.
  186. if (!empty($this->statementClass)) {
  187. $this->connection->setAttribute(\PDO::ATTR_STATEMENT_CLASS, ['PDOStatement', []]);
  188. }
  189. $this->schema = NULL;
  190. }
  191. /**
  192. * Returns the default query options for any given query.
  193. *
  194. * A given query can be customized with a number of option flags in an
  195. * associative array:
  196. * - fetch: This element controls how rows from a result set will be
  197. * returned. Legal values include PDO::FETCH_ASSOC, PDO::FETCH_BOTH,
  198. * PDO::FETCH_OBJ, PDO::FETCH_NUM, or a string representing the name of a
  199. * class. If a string is specified, each record will be fetched into a new
  200. * object of that class. The behavior of all other values is defined by PDO.
  201. * See http://php.net/manual/pdostatement.fetch.php
  202. * - return: Depending on the type of query, different return values may be
  203. * meaningful. This directive instructs the system which type of return
  204. * value is desired. The system will generally set the correct value
  205. * automatically, so it is extremely rare that a module developer will ever
  206. * need to specify this value. Setting it incorrectly will likely lead to
  207. * unpredictable results or fatal errors. Legal values include:
  208. * - Database::RETURN_STATEMENT: Return the prepared statement object for
  209. * the query. This is usually only meaningful for SELECT queries, where
  210. * the statement object is how one accesses the result set returned by the
  211. * query.
  212. * - Database::RETURN_AFFECTED: Return the number of rows affected by an
  213. * UPDATE or DELETE query. Be aware that means the number of rows actually
  214. * changed, not the number of rows matched by the WHERE clause.
  215. * - Database::RETURN_INSERT_ID: Return the sequence ID (primary key)
  216. * created by an INSERT statement on a table that contains a serial
  217. * column.
  218. * - Database::RETURN_NULL: Do not return anything, as there is no
  219. * meaningful value to return. That is the case for INSERT queries on
  220. * tables that do not contain a serial column.
  221. * - throw_exception: By default, the database system will catch any errors
  222. * on a query as an Exception, log it, and then rethrow it so that code
  223. * further up the call chain can take an appropriate action. To suppress
  224. * that behavior and simply return NULL on failure, set this option to
  225. * FALSE.
  226. * - allow_delimiter_in_query: By default, queries which have the ; delimiter
  227. * any place in them will cause an exception. This reduces the chance of SQL
  228. * injection attacks that terminate the original query and add one or more
  229. * additional queries (such as inserting new user accounts). In rare cases,
  230. * such as creating an SQL function, a ; is needed and can be allowed by
  231. * changing this option to TRUE.
  232. *
  233. * @return array
  234. * An array of default query options.
  235. */
  236. protected function defaultOptions() {
  237. return [
  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. * Note that if a sequence was generated automatically by the database, its
  440. * name might not match the one returned by this function. Therefore, in those
  441. * cases, it is generally advised to use a database-specific way of retrieving
  442. * the name of an auto-created sequence. For example, PostgreSQL provides a
  443. * dedicated function for this purpose: pg_get_serial_sequence().
  444. *
  445. * @param string $table
  446. * The table name to use for the sequence.
  447. * @param string $field
  448. * The field name to use for the sequence.
  449. *
  450. * @return string
  451. * A table prefix-parsed string for the sequence name.
  452. */
  453. public function makeSequenceName($table, $field) {
  454. return $this->prefixTables('{' . $table . '}_' . $field . '_seq');
  455. }
  456. /**
  457. * Flatten an array of query comments into a single comment string.
  458. *
  459. * The comment string will be sanitized to avoid SQL injection attacks.
  460. *
  461. * @param string[] $comments
  462. * An array of query comment strings.
  463. *
  464. * @return string
  465. * A sanitized comment string.
  466. */
  467. public function makeComment($comments) {
  468. if (empty($comments)) {
  469. return '';
  470. }
  471. // Flatten the array of comments.
  472. $comment = implode('. ', $comments);
  473. // Sanitize the comment string so as to avoid SQL injection attacks.
  474. return '/* ' . $this->filterComment($comment) . ' */ ';
  475. }
  476. /**
  477. * Sanitize a query comment string.
  478. *
  479. * Ensure a query comment does not include strings such as "* /" that might
  480. * terminate the comment early. This avoids SQL injection attacks via the
  481. * query comment. The comment strings in this example are separated by a
  482. * space to avoid PHP parse errors.
  483. *
  484. * For example, the comment:
  485. * @code
  486. * \Drupal::database()->update('example')
  487. * ->condition('id', $id)
  488. * ->fields(array('field2' => 10))
  489. * ->comment('Exploit * / DROP TABLE node; --')
  490. * ->execute()
  491. * @endcode
  492. *
  493. * Would result in the following SQL statement being generated:
  494. * @code
  495. * "/ * Exploit * / DROP TABLE node. -- * / UPDATE example SET field2=..."
  496. * @endcode
  497. *
  498. * Unless the comment is sanitized first, the SQL server would drop the
  499. * node table and ignore the rest of the SQL statement.
  500. *
  501. * @param string $comment
  502. * A query comment string.
  503. *
  504. * @return string
  505. * A sanitized version of the query comment string.
  506. */
  507. protected function filterComment($comment = '') {
  508. // Change semicolons to period to avoid triggering multi-statement check.
  509. return strtr($comment, ['*' => ' * ', ';' => '.']);
  510. }
  511. /**
  512. * Executes a query string against the database.
  513. *
  514. * This method provides a central handler for the actual execution of every
  515. * query. All queries executed by Drupal are executed as PDO prepared
  516. * statements.
  517. *
  518. * @param string|\Drupal\Core\Database\StatementInterface $query
  519. * The query to execute. In most cases this will be a string containing
  520. * an SQL query with placeholders. An already-prepared instance of
  521. * StatementInterface may also be passed in order to allow calling
  522. * code to manually bind variables to a query. If a
  523. * StatementInterface is passed, the $args array will be ignored.
  524. * It is extremely rare that module code will need to pass a statement
  525. * object to this method. It is used primarily for database drivers for
  526. * databases that require special LOB field handling.
  527. * @param array $args
  528. * An array of arguments for the prepared statement. If the prepared
  529. * statement uses ? placeholders, this array must be an indexed array.
  530. * If it contains named placeholders, it must be an associative array.
  531. * @param array $options
  532. * An associative array of options to control how the query is run. The
  533. * given options will be merged with self::defaultOptions(). See the
  534. * documentation for self::defaultOptions() for details.
  535. * Typically, $options['return'] will be set by a default or by a query
  536. * builder, and should not be set by a user.
  537. *
  538. * @return \Drupal\Core\Database\StatementInterface|int|string|null
  539. * This method will return one of the following:
  540. * - If either $options['return'] === self::RETURN_STATEMENT, or
  541. * $options['return'] is not set (due to self::defaultOptions()),
  542. * returns the executed statement.
  543. * - If $options['return'] === self::RETURN_AFFECTED,
  544. * returns the number of rows affected by the query
  545. * (not the number matched).
  546. * - If $options['return'] === self::RETURN_INSERT_ID,
  547. * returns the generated insert ID of the last query as a string.
  548. * - If either $options['return'] === self::RETURN_NULL, or
  549. * an exception occurs and $options['throw_exception'] evaluates to FALSE,
  550. * returns NULL.
  551. *
  552. * @throws \Drupal\Core\Database\DatabaseExceptionWrapper
  553. * @throws \Drupal\Core\Database\IntegrityConstraintViolationException
  554. * @throws \InvalidArgumentException
  555. *
  556. * @see \Drupal\Core\Database\Connection::defaultOptions()
  557. */
  558. public function query($query, array $args = [], $options = []) {
  559. // Use default values if not already set.
  560. $options += $this->defaultOptions();
  561. if (isset($options['target'])) {
  562. @trigger_error('Passing a \'target\' key to \\Drupal\\Core\\Database\\Connection::query $options argument is deprecated in drupal:8.0.x and will be removed before drupal:9.0.0. Instead, use \\Drupal\\Core\\Database\\Database::getConnection($target)->query(). See https://www.drupal.org/node/2993033', E_USER_DEPRECATED);
  563. }
  564. try {
  565. // We allow either a pre-bound statement object or a literal string.
  566. // In either case, we want to end up with an executed statement object,
  567. // which we pass to PDOStatement::execute.
  568. if ($query instanceof StatementInterface) {
  569. $stmt = $query;
  570. $stmt->execute(NULL, $options);
  571. }
  572. else {
  573. $this->expandArguments($query, $args);
  574. // To protect against SQL injection, Drupal only supports executing one
  575. // statement at a time. Thus, the presence of a SQL delimiter (the
  576. // semicolon) is not allowed unless the option is set. Allowing
  577. // semicolons should only be needed for special cases like defining a
  578. // function or stored procedure in SQL. Trim any trailing delimiter to
  579. // minimize false positives.
  580. $trim_chars = " \t\n\r\0\x0B";
  581. if (empty($options['allow_delimiter_in_query'])) {
  582. $trim_chars .= ';';
  583. }
  584. $query = rtrim($query, $trim_chars);
  585. if (strpos($query, ';') !== FALSE && empty($options['allow_delimiter_in_query'])) {
  586. throw new \InvalidArgumentException('; is not supported in SQL strings. Use only one statement at a time.');
  587. }
  588. $stmt = $this->prepareQuery($query);
  589. $stmt->execute($args, $options);
  590. }
  591. // Depending on the type of query we may need to return a different value.
  592. // See DatabaseConnection::defaultOptions() for a description of each
  593. // value.
  594. switch ($options['return']) {
  595. case Database::RETURN_STATEMENT:
  596. return $stmt;
  597. case Database::RETURN_AFFECTED:
  598. $stmt->allowRowCount = TRUE;
  599. return $stmt->rowCount();
  600. case Database::RETURN_INSERT_ID:
  601. $sequence_name = isset($options['sequence_name']) ? $options['sequence_name'] : NULL;
  602. return $this->connection->lastInsertId($sequence_name);
  603. case Database::RETURN_NULL:
  604. return NULL;
  605. default:
  606. throw new \PDOException('Invalid return directive: ' . $options['return']);
  607. }
  608. }
  609. catch (\PDOException $e) {
  610. // Most database drivers will return NULL here, but some of them
  611. // (e.g. the SQLite driver) may need to re-run the query, so the return
  612. // value will be the same as for static::query().
  613. return $this->handleQueryException($e, $query, $args, $options);
  614. }
  615. }
  616. /**
  617. * Wraps and re-throws any PDO exception thrown by static::query().
  618. *
  619. * @param \PDOException $e
  620. * The exception thrown by static::query().
  621. * @param $query
  622. * The query executed by static::query().
  623. * @param array $args
  624. * An array of arguments for the prepared statement.
  625. * @param array $options
  626. * An associative array of options to control how the query is run.
  627. *
  628. * @return \Drupal\Core\Database\StatementInterface|int|null
  629. * Most database drivers will return NULL when a PDO exception is thrown for
  630. * a query, but some of them may need to re-run the query, so they can also
  631. * return a \Drupal\Core\Database\StatementInterface object or an integer.
  632. *
  633. * @throws \Drupal\Core\Database\DatabaseExceptionWrapper
  634. * @throws \Drupal\Core\Database\IntegrityConstraintViolationException
  635. */
  636. protected function handleQueryException(\PDOException $e, $query, array $args = [], $options = []) {
  637. if ($options['throw_exception']) {
  638. // Wrap the exception in another exception, because PHP does not allow
  639. // overriding Exception::getMessage(). Its message is the extra database
  640. // debug information.
  641. $query_string = ($query instanceof StatementInterface) ? $query->getQueryString() : $query;
  642. $message = $e->getMessage() . ": " . $query_string . "; " . print_r($args, TRUE);
  643. // Match all SQLSTATE 23xxx errors.
  644. if (substr($e->getCode(), -6, -3) == '23') {
  645. $exception = new IntegrityConstraintViolationException($message, $e->getCode(), $e);
  646. }
  647. else {
  648. $exception = new DatabaseExceptionWrapper($message, 0, $e);
  649. }
  650. throw $exception;
  651. }
  652. return NULL;
  653. }
  654. /**
  655. * Expands out shorthand placeholders.
  656. *
  657. * Drupal supports an alternate syntax for doing arrays of values. We
  658. * therefore need to expand them out into a full, executable query string.
  659. *
  660. * @param string $query
  661. * The query string to modify.
  662. * @param array $args
  663. * The arguments for the query.
  664. *
  665. * @return bool
  666. * TRUE if the query was modified, FALSE otherwise.
  667. *
  668. * @throws \InvalidArgumentException
  669. * This exception is thrown when:
  670. * - A placeholder that ends in [] is supplied, and the supplied value is
  671. * not an array.
  672. * - A placeholder that does not end in [] is supplied, and the supplied
  673. * value is an array.
  674. */
  675. protected function expandArguments(&$query, &$args) {
  676. $modified = FALSE;
  677. // If the placeholder indicated the value to use is an array, we need to
  678. // expand it out into a comma-delimited set of placeholders.
  679. foreach ($args as $key => $data) {
  680. $is_bracket_placeholder = substr($key, -2) === '[]';
  681. $is_array_data = is_array($data);
  682. if ($is_bracket_placeholder && !$is_array_data) {
  683. throw new \InvalidArgumentException('Placeholders with a trailing [] can only be expanded with an array of values.');
  684. }
  685. elseif (!$is_bracket_placeholder) {
  686. if ($is_array_data) {
  687. throw new \InvalidArgumentException('Placeholders must have a trailing [] if they are to be expanded with an array of values.');
  688. }
  689. // Scalar placeholder - does not need to be expanded.
  690. continue;
  691. }
  692. // Handle expansion of arrays.
  693. $key_name = str_replace('[]', '__', $key);
  694. $new_keys = [];
  695. // We require placeholders to have trailing brackets if the developer
  696. // intends them to be expanded to an array to make the intent explicit.
  697. foreach (array_values($data) as $i => $value) {
  698. // This assumes that there are no other placeholders that use the same
  699. // name. For example, if the array placeholder is defined as :example[]
  700. // and there is already an :example_2 placeholder, this will generate
  701. // a duplicate key. We do not account for that as the calling code
  702. // is already broken if that happens.
  703. $new_keys[$key_name . $i] = $value;
  704. }
  705. // Update the query with the new placeholders.
  706. $query = str_replace($key, implode(', ', array_keys($new_keys)), $query);
  707. // Update the args array with the new placeholders.
  708. unset($args[$key]);
  709. $args += $new_keys;
  710. $modified = TRUE;
  711. }
  712. return $modified;
  713. }
  714. /**
  715. * Gets the driver-specific override class if any for the specified class.
  716. *
  717. * @param string $class
  718. * The class for which we want the potentially driver-specific class.
  719. *
  720. * @return string
  721. * The name of the class that should be used for this driver.
  722. */
  723. public function getDriverClass($class) {
  724. if (empty($this->driverClasses[$class])) {
  725. if (empty($this->connectionOptions['namespace'])) {
  726. // Fallback for Drupal 7 settings.php and the test runner script.
  727. $this->connectionOptions['namespace'] = (new \ReflectionObject($this))->getNamespaceName();
  728. }
  729. $driver_class = $this->connectionOptions['namespace'] . '\\' . $class;
  730. $this->driverClasses[$class] = class_exists($driver_class) ? $driver_class : $class;
  731. if ($this->driverClasses[$class] === 'Condition') {
  732. // @todo Deprecate the fallback for contrib and custom drivers in 9.1.x
  733. // in https://www.drupal.org/project/drupal/issues/3120036.
  734. $this->driverClasses[$class] = Condition::class;
  735. }
  736. }
  737. return $this->driverClasses[$class];
  738. }
  739. /**
  740. * Prepares and returns a SELECT query object.
  741. *
  742. * @param string $table
  743. * The base table for this query, that is, the first table in the FROM
  744. * clause. This table will also be used as the "base" table for query_alter
  745. * hook implementations.
  746. * @param string $alias
  747. * (optional) The alias of the base table of this query.
  748. * @param $options
  749. * An array of options on the query.
  750. *
  751. * @return \Drupal\Core\Database\Query\SelectInterface
  752. * An appropriate SelectQuery object for this database connection. Note that
  753. * it may be a driver-specific subclass of SelectQuery, depending on the
  754. * driver.
  755. *
  756. * @see \Drupal\Core\Database\Query\Select
  757. */
  758. public function select($table, $alias = NULL, array $options = []) {
  759. $class = $this->getDriverClass('Select');
  760. return new $class($table, $alias, $this, $options);
  761. }
  762. /**
  763. * Prepares and returns an INSERT query object.
  764. *
  765. * @param string $table
  766. * The table to use for the insert statement.
  767. * @param array $options
  768. * (optional) An associative array of options to control how the query is
  769. * run. The given options will be merged with
  770. * \Drupal\Core\Database\Connection::defaultOptions().
  771. *
  772. * @return \Drupal\Core\Database\Query\Insert
  773. * A new Insert query object.
  774. *
  775. * @see \Drupal\Core\Database\Query\Insert
  776. * @see \Drupal\Core\Database\Connection::defaultOptions()
  777. */
  778. public function insert($table, array $options = []) {
  779. $class = $this->getDriverClass('Insert');
  780. return new $class($this, $table, $options);
  781. }
  782. /**
  783. * Prepares and returns a MERGE query object.
  784. *
  785. * @param string $table
  786. * The table to use for the merge statement.
  787. * @param array $options
  788. * (optional) An array of options on the query.
  789. *
  790. * @return \Drupal\Core\Database\Query\Merge
  791. * A new Merge query object.
  792. *
  793. * @see \Drupal\Core\Database\Query\Merge
  794. */
  795. public function merge($table, array $options = []) {
  796. $class = $this->getDriverClass('Merge');
  797. return new $class($this, $table, $options);
  798. }
  799. /**
  800. * Prepares and returns an UPSERT query object.
  801. *
  802. * @param string $table
  803. * The table to use for the upsert query.
  804. * @param array $options
  805. * (optional) An array of options on the query.
  806. *
  807. * @return \Drupal\Core\Database\Query\Upsert
  808. * A new Upsert query object.
  809. *
  810. * @see \Drupal\Core\Database\Query\Upsert
  811. */
  812. public function upsert($table, array $options = []) {
  813. $class = $this->getDriverClass('Upsert');
  814. return new $class($this, $table, $options);
  815. }
  816. /**
  817. * Prepares and returns an UPDATE query object.
  818. *
  819. * @param string $table
  820. * The table to use for the update statement.
  821. * @param array $options
  822. * (optional) An associative array of options to control how the query is
  823. * run. The given options will be merged with
  824. * \Drupal\Core\Database\Connection::defaultOptions().
  825. *
  826. * @return \Drupal\Core\Database\Query\Update
  827. * A new Update query object.
  828. *
  829. * @see \Drupal\Core\Database\Query\Update
  830. * @see \Drupal\Core\Database\Connection::defaultOptions()
  831. */
  832. public function update($table, array $options = []) {
  833. $class = $this->getDriverClass('Update');
  834. return new $class($this, $table, $options);
  835. }
  836. /**
  837. * Prepares and returns a DELETE query object.
  838. *
  839. * @param string $table
  840. * The table to use for the delete statement.
  841. * @param array $options
  842. * (optional) An associative array of options to control how the query is
  843. * run. The given options will be merged with
  844. * \Drupal\Core\Database\Connection::defaultOptions().
  845. *
  846. * @return \Drupal\Core\Database\Query\Delete
  847. * A new Delete query object.
  848. *
  849. * @see \Drupal\Core\Database\Query\Delete
  850. * @see \Drupal\Core\Database\Connection::defaultOptions()
  851. */
  852. public function delete($table, array $options = []) {
  853. $class = $this->getDriverClass('Delete');
  854. return new $class($this, $table, $options);
  855. }
  856. /**
  857. * Prepares and returns a TRUNCATE query object.
  858. *
  859. * @param string $table
  860. * The table to use for the truncate statement.
  861. * @param array $options
  862. * (optional) An array of options on the query.
  863. *
  864. * @return \Drupal\Core\Database\Query\Truncate
  865. * A new Truncate query object.
  866. *
  867. * @see \Drupal\Core\Database\Query\Truncate
  868. */
  869. public function truncate($table, array $options = []) {
  870. $class = $this->getDriverClass('Truncate');
  871. return new $class($this, $table, $options);
  872. }
  873. /**
  874. * Returns a DatabaseSchema object for manipulating the schema.
  875. *
  876. * This method will lazy-load the appropriate schema library file.
  877. *
  878. * @return \Drupal\Core\Database\Schema
  879. * The database Schema object for this connection.
  880. */
  881. public function schema() {
  882. if (empty($this->schema)) {
  883. $class = $this->getDriverClass('Schema');
  884. $this->schema = new $class($this);
  885. }
  886. return $this->schema;
  887. }
  888. /**
  889. * Prepares and returns a CONDITION query object.
  890. *
  891. * @param string $conjunction
  892. * The operator to use to combine conditions: 'AND' or 'OR'.
  893. *
  894. * @return \Drupal\Core\Database\Query\Condition
  895. * A new Condition query object.
  896. *
  897. * @see \Drupal\Core\Database\Query\Condition
  898. */
  899. public function condition($conjunction) {
  900. $class = $this->getDriverClass('Condition');
  901. return new $class($conjunction);
  902. }
  903. /**
  904. * Escapes a database name string.
  905. *
  906. * Force all database names to be strictly alphanumeric-plus-underscore.
  907. * For some database drivers, it may also wrap the database name in
  908. * database-specific escape characters.
  909. *
  910. * @param string $database
  911. * An unsanitized database name.
  912. *
  913. * @return string
  914. * The sanitized database name.
  915. */
  916. public function escapeDatabase($database) {
  917. if (!isset($this->escapedNames[$database])) {
  918. $this->escapedNames[$database] = preg_replace('/[^A-Za-z0-9_.]+/', '', $database);
  919. }
  920. return $this->escapedNames[$database];
  921. }
  922. /**
  923. * Escapes a table name string.
  924. *
  925. * Force all table names to be strictly alphanumeric-plus-underscore.
  926. * For some database drivers, it may also wrap the table name in
  927. * database-specific escape characters.
  928. *
  929. * @param string $table
  930. * An unsanitized table name.
  931. *
  932. * @return string
  933. * The sanitized table name.
  934. */
  935. public function escapeTable($table) {
  936. if (!isset($this->escapedNames[$table])) {
  937. $this->escapedNames[$table] = preg_replace('/[^A-Za-z0-9_.]+/', '', $table);
  938. }
  939. return $this->escapedNames[$table];
  940. }
  941. /**
  942. * Escapes a field name string.
  943. *
  944. * Force all field names to be strictly alphanumeric-plus-underscore.
  945. * For some database drivers, it may also wrap the field name in
  946. * database-specific escape characters.
  947. *
  948. * @param string $field
  949. * An unsanitized field name.
  950. *
  951. * @return string
  952. * The sanitized field name.
  953. */
  954. public function escapeField($field) {
  955. if (!isset($this->escapedNames[$field])) {
  956. $this->escapedNames[$field] = preg_replace('/[^A-Za-z0-9_.]+/', '', $field);
  957. }
  958. return $this->escapedNames[$field];
  959. }
  960. /**
  961. * Escapes an alias name string.
  962. *
  963. * Force all alias names to be strictly alphanumeric-plus-underscore. In
  964. * contrast to DatabaseConnection::escapeField() /
  965. * DatabaseConnection::escapeTable(), this doesn't allow the period (".")
  966. * because that is not allowed in aliases.
  967. *
  968. * @param string $field
  969. * An unsanitized alias name.
  970. *
  971. * @return string
  972. * The sanitized alias name.
  973. */
  974. public function escapeAlias($field) {
  975. if (!isset($this->escapedAliases[$field])) {
  976. $this->escapedAliases[$field] = preg_replace('/[^A-Za-z0-9_]+/', '', $field);
  977. }
  978. return $this->escapedAliases[$field];
  979. }
  980. /**
  981. * Escapes characters that work as wildcard characters in a LIKE pattern.
  982. *
  983. * The wildcard characters "%" and "_" as well as backslash are prefixed with
  984. * a backslash. Use this to do a search for a verbatim string without any
  985. * wildcard behavior.
  986. *
  987. * For example, the following does a case-insensitive query for all rows whose
  988. * name starts with $prefix:
  989. * @code
  990. * $result = $injected_connection->query(
  991. * 'SELECT * FROM person WHERE name LIKE :pattern',
  992. * array(':pattern' => $injected_connection->escapeLike($prefix) . '%')
  993. * );
  994. * @endcode
  995. *
  996. * Backslash is defined as escape character for LIKE patterns in
  997. * Drupal\Core\Database\Query\Condition::mapConditionOperator().
  998. *
  999. * @param string $string
  1000. * The string to escape.
  1001. *
  1002. * @return string
  1003. * The escaped string.
  1004. */
  1005. public function escapeLike($string) {
  1006. return addcslashes($string, '\%_');
  1007. }
  1008. /**
  1009. * Determines if there is an active transaction open.
  1010. *
  1011. * @return bool
  1012. * TRUE if we're currently in a transaction, FALSE otherwise.
  1013. */
  1014. public function inTransaction() {
  1015. return ($this->transactionDepth() > 0);
  1016. }
  1017. /**
  1018. * Determines the current transaction depth.
  1019. *
  1020. * @return int
  1021. * The current transaction depth.
  1022. */
  1023. public function transactionDepth() {
  1024. return count($this->transactionLayers);
  1025. }
  1026. /**
  1027. * Returns a new DatabaseTransaction object on this connection.
  1028. *
  1029. * @param string $name
  1030. * (optional) The name of the savepoint.
  1031. *
  1032. * @return \Drupal\Core\Database\Transaction
  1033. * A Transaction object.
  1034. *
  1035. * @see \Drupal\Core\Database\Transaction
  1036. */
  1037. public function startTransaction($name = '') {
  1038. $class = $this->getDriverClass('Transaction');
  1039. return new $class($this, $name);
  1040. }
  1041. /**
  1042. * Rolls back the transaction entirely or to a named savepoint.
  1043. *
  1044. * This method throws an exception if no transaction is active.
  1045. *
  1046. * @param string $savepoint_name
  1047. * (optional) The name of the savepoint. The default, 'drupal_transaction',
  1048. * will roll the entire transaction back.
  1049. *
  1050. * @throws \Drupal\Core\Database\TransactionOutOfOrderException
  1051. * @throws \Drupal\Core\Database\TransactionNoActiveException
  1052. *
  1053. * @see \Drupal\Core\Database\Transaction::rollBack()
  1054. */
  1055. public function rollBack($savepoint_name = 'drupal_transaction') {
  1056. if (!$this->supportsTransactions()) {
  1057. return;
  1058. }
  1059. if (!$this->inTransaction()) {
  1060. throw new TransactionNoActiveException();
  1061. }
  1062. // A previous rollback to an earlier savepoint may mean that the savepoint
  1063. // in question has already been accidentally committed.
  1064. if (!isset($this->transactionLayers[$savepoint_name])) {
  1065. throw new TransactionNoActiveException();
  1066. }
  1067. // We need to find the point we're rolling back to, all other savepoints
  1068. // before are no longer needed. If we rolled back other active savepoints,
  1069. // we need to throw an exception.
  1070. $rolled_back_other_active_savepoints = FALSE;
  1071. while ($savepoint = array_pop($this->transactionLayers)) {
  1072. if ($savepoint == $savepoint_name) {
  1073. // If it is the last the transaction in the stack, then it is not a
  1074. // savepoint, it is the transaction itself so we will need to roll back
  1075. // the transaction rather than a savepoint.
  1076. if (empty($this->transactionLayers)) {
  1077. break;
  1078. }
  1079. $this->query('ROLLBACK TO SAVEPOINT ' . $savepoint);
  1080. $this->popCommittableTransactions();
  1081. if ($rolled_back_other_active_savepoints) {
  1082. throw new TransactionOutOfOrderException();
  1083. }
  1084. return;
  1085. }
  1086. else {
  1087. $rolled_back_other_active_savepoints = TRUE;
  1088. }
  1089. }
  1090. // Notify the callbacks about the rollback.
  1091. $callbacks = $this->rootTransactionEndCallbacks;
  1092. $this->rootTransactionEndCallbacks = [];
  1093. foreach ($callbacks as $callback) {
  1094. call_user_func($callback, FALSE);
  1095. }
  1096. $this->connection->rollBack();
  1097. if ($rolled_back_other_active_savepoints) {
  1098. throw new TransactionOutOfOrderException();
  1099. }
  1100. }
  1101. /**
  1102. * Increases the depth of transaction nesting.
  1103. *
  1104. * If no transaction is already active, we begin a new transaction.
  1105. *
  1106. * @param string $name
  1107. * The name of the transaction.
  1108. *
  1109. * @throws \Drupal\Core\Database\TransactionNameNonUniqueException
  1110. *
  1111. * @see \Drupal\Core\Database\Transaction
  1112. */
  1113. public function pushTransaction($name) {
  1114. if (!$this->supportsTransactions()) {
  1115. return;
  1116. }
  1117. if (isset($this->transactionLayers[$name])) {
  1118. throw new TransactionNameNonUniqueException($name . " is already in use.");
  1119. }
  1120. // If we're already in a transaction then we want to create a savepoint
  1121. // rather than try to create another transaction.
  1122. if ($this->inTransaction()) {
  1123. $this->query('SAVEPOINT ' . $name);
  1124. }
  1125. else {
  1126. $this->connection->beginTransaction();
  1127. }
  1128. $this->transactionLayers[$name] = $name;
  1129. }
  1130. /**
  1131. * Decreases the depth of transaction nesting.
  1132. *
  1133. * If we pop off the last transaction layer, then we either commit or roll
  1134. * back the transaction as necessary. If no transaction is active, we return
  1135. * because the transaction may have manually been rolled back.
  1136. *
  1137. * @param string $name
  1138. * The name of the savepoint.
  1139. *
  1140. * @throws \Drupal\Core\Database\TransactionNoActiveException
  1141. * @throws \Drupal\Core\Database\TransactionCommitFailedException
  1142. *
  1143. * @see \Drupal\Core\Database\Transaction
  1144. */
  1145. public function popTransaction($name) {
  1146. if (!$this->supportsTransactions()) {
  1147. return;
  1148. }
  1149. // The transaction has already been committed earlier. There is nothing we
  1150. // need to do. If this transaction was part of an earlier out-of-order
  1151. // rollback, an exception would already have been thrown by
  1152. // Database::rollBack().
  1153. if (!isset($this->transactionLayers[$name])) {
  1154. return;
  1155. }
  1156. // Mark this layer as committable.
  1157. $this->transactionLayers[$name] = FALSE;
  1158. $this->popCommittableTransactions();
  1159. }
  1160. /**
  1161. * Adds a root transaction end callback.
  1162. *
  1163. * These callbacks are invoked immediately after the transaction has been
  1164. * committed.
  1165. *
  1166. * It can for example be used to avoid deadlocks on write-heavy tables that
  1167. * do not need to be part of the transaction, like cache tag invalidations.
  1168. *
  1169. * Another use case is that services using alternative backends like Redis and
  1170. * Memcache cache implementations can replicate the transaction-behavior of
  1171. * the database cache backend and avoid race conditions.
  1172. *
  1173. * An argument is passed to the callbacks that indicates whether the
  1174. * transaction was successful or not.
  1175. *
  1176. * @param callable $callback
  1177. * The callback to invoke.
  1178. *
  1179. * @see \Drupal\Core\Database\Connection::doCommit()
  1180. */
  1181. public function addRootTransactionEndCallback(callable $callback) {
  1182. if (!$this->transactionLayers) {
  1183. throw new \LogicException('Root transaction end callbacks can only be added when there is an active transaction.');
  1184. }
  1185. $this->rootTransactionEndCallbacks[] = $callback;
  1186. }
  1187. /**
  1188. * Commit all the transaction layers that can commit.
  1189. *
  1190. * @internal
  1191. */
  1192. protected function popCommittableTransactions() {
  1193. // Commit all the committable layers.
  1194. foreach (array_reverse($this->transactionLayers) as $name => $active) {
  1195. // Stop once we found an active transaction.
  1196. if ($active) {
  1197. break;
  1198. }
  1199. // If there are no more layers left then we should commit.
  1200. unset($this->transactionLayers[$name]);
  1201. if (empty($this->transactionLayers)) {
  1202. $this->doCommit();
  1203. }
  1204. else {
  1205. $this->query('RELEASE SAVEPOINT ' . $name);
  1206. }
  1207. }
  1208. }
  1209. /**
  1210. * Do the actual commit, invoke post-commit callbacks.
  1211. *
  1212. * @internal
  1213. */
  1214. protected function doCommit() {
  1215. $success = $this->connection->commit();
  1216. if (!empty($this->rootTransactionEndCallbacks)) {
  1217. $callbacks = $this->rootTransactionEndCallbacks;
  1218. $this->rootTransactionEndCallbacks = [];
  1219. foreach ($callbacks as $callback) {
  1220. call_user_func($callback, $success);
  1221. }
  1222. }
  1223. if (!$success) {
  1224. throw new TransactionCommitFailedException();
  1225. }
  1226. }
  1227. /**
  1228. * Runs a limited-range query on this database object.
  1229. *
  1230. * Use this as a substitute for ->query() when a subset of the query is to be
  1231. * returned. User-supplied arguments to the query should be passed in as
  1232. * separate parameters so that they can be properly escaped to avoid SQL
  1233. * injection attacks.
  1234. *
  1235. * @param string $query
  1236. * A string containing an SQL query.
  1237. * @param int $from
  1238. * The first result row to return.
  1239. * @param int $count
  1240. * The maximum number of result rows to return.
  1241. * @param array $args
  1242. * (optional) An array of values to substitute into the query at placeholder
  1243. * markers.
  1244. * @param array $options
  1245. * (optional) An array of options on the query.
  1246. *
  1247. * @return \Drupal\Core\Database\StatementInterface
  1248. * A database query result resource, or NULL if the query was not executed
  1249. * correctly.
  1250. */
  1251. abstract public function queryRange($query, $from, $count, array $args = [], array $options = []);
  1252. /**
  1253. * Generates a temporary table name.
  1254. *
  1255. * @return string
  1256. * A table name.
  1257. */
  1258. protected function generateTemporaryTableName() {
  1259. return "db_temporary_" . $this->temporaryNameIndex++;
  1260. }
  1261. /**
  1262. * Runs a SELECT query and stores its results in a temporary table.
  1263. *
  1264. * Use this as a substitute for ->query() when the results need to stored
  1265. * in a temporary table. Temporary tables exist for the duration of the page
  1266. * request. User-supplied arguments to the query should be passed in as
  1267. * separate parameters so that they can be properly escaped to avoid SQL
  1268. * injection attacks.
  1269. *
  1270. * Note that if you need to know how many results were returned, you should do
  1271. * a SELECT COUNT(*) on the temporary table afterwards.
  1272. *
  1273. * @param string $query
  1274. * A string containing a normal SELECT SQL query.
  1275. * @param array $args
  1276. * (optional) An array of values to substitute into the query at placeholder
  1277. * markers.
  1278. * @param array $options
  1279. * (optional) An associative array of options to control how the query is
  1280. * run. See the documentation for DatabaseConnection::defaultOptions() for
  1281. * details.
  1282. *
  1283. * @return string
  1284. * The name of the temporary table.
  1285. */
  1286. abstract public function queryTemporary($query, array $args = [], array $options = []);
  1287. /**
  1288. * Returns the type of database driver.
  1289. *
  1290. * This is not necessarily the same as the type of the database itself. For
  1291. * instance, there could be two MySQL drivers, mysql and mysqlMock. This
  1292. * function would return different values for each, but both would return
  1293. * "mysql" for databaseType().
  1294. *
  1295. * @return string
  1296. * The type of database driver.
  1297. */
  1298. abstract public function driver();
  1299. /**
  1300. * Returns the version of the database server.
  1301. */
  1302. public function version() {
  1303. return $this->connection->getAttribute(\PDO::ATTR_SERVER_VERSION);
  1304. }
  1305. /**
  1306. * Returns the version of the database client.
  1307. */
  1308. public function clientVersion() {
  1309. return $this->connection->getAttribute(\PDO::ATTR_CLIENT_VERSION);
  1310. }
  1311. /**
  1312. * Determines if this driver supports transactions.
  1313. *
  1314. * @return bool
  1315. * TRUE if this connection supports transactions, FALSE otherwise.
  1316. */
  1317. public function supportsTransactions() {
  1318. return $this->transactionSupport;
  1319. }
  1320. /**
  1321. * Determines if this driver supports transactional DDL.
  1322. *
  1323. * DDL queries are those that change the schema, such as ALTER queries.
  1324. *
  1325. * @return bool
  1326. * TRUE if this connection supports transactions for DDL queries, FALSE
  1327. * otherwise.
  1328. */
  1329. public function supportsTransactionalDDL() {
  1330. return $this->transactionalDDLSupport;
  1331. }
  1332. /**
  1333. * Returns the name of the PDO driver for this connection.
  1334. */
  1335. abstract public function databaseType();
  1336. /**
  1337. * Creates a database.
  1338. *
  1339. * In order to use this method, you must be connected without a database
  1340. * specified.
  1341. *
  1342. * @param string $database
  1343. * The name of the database to create.
  1344. */
  1345. abstract public function createDatabase($database);
  1346. /**
  1347. * Gets any special processing requirements for the condition operator.
  1348. *
  1349. * Some condition types require special processing, such as IN, because
  1350. * the value data they pass in is not a simple value. This is a simple
  1351. * overridable lookup function. Database connections should define only
  1352. * those operators they wish to be handled differently than the default.
  1353. *
  1354. * @param string $operator
  1355. * The condition operator, such as "IN", "BETWEEN", etc. Case-sensitive.
  1356. *
  1357. * @return
  1358. * The extra handling directives for the specified operator, or NULL.
  1359. *
  1360. * @see \Drupal\Core\Database\Query\Condition::compile()
  1361. */
  1362. abstract public function mapConditionOperator($operator);
  1363. /**
  1364. * Throws an exception to deny direct access to transaction commits.
  1365. *
  1366. * We do not want to allow users to commit transactions at any time, only
  1367. * by destroying the transaction object or allowing it to go out of scope.
  1368. * A direct commit bypasses all of the safety checks we've built on top of
  1369. * PDO's transaction routines.
  1370. *
  1371. * @throws \Drupal\Core\Database\TransactionExplicitCommitNotAllowedException
  1372. *
  1373. * @see \Drupal\Core\Database\Transaction
  1374. */
  1375. public function commit() {
  1376. throw new TransactionExplicitCommitNotAllowedException();
  1377. }
  1378. /**
  1379. * Retrieves an unique ID from a given sequence.
  1380. *
  1381. * Use this function if for some reason you can't use a serial field. For
  1382. * example, MySQL has no ways of reading of the current value of a sequence
  1383. * and PostgreSQL can not advance the sequence to be larger than a given
  1384. * value. Or sometimes you just need a unique integer.
  1385. *
  1386. * @param $existing_id
  1387. * (optional) After a database import, it might be that the sequences table
  1388. * is behind, so by passing in the maximum existing ID, it can be assured
  1389. * that we never issue the same ID.
  1390. *
  1391. * @return
  1392. * An integer number larger than any number returned by earlier calls and
  1393. * also larger than the $existing_id if one was passed in.
  1394. */
  1395. abstract public function nextId($existing_id = 0);
  1396. /**
  1397. * Prepares a statement for execution and returns a statement object
  1398. *
  1399. * Emulated prepared statements do not communicate with the database server so
  1400. * this method does not check the statement.
  1401. *
  1402. * @param string $statement
  1403. * This must be a valid SQL statement for the target database server.
  1404. * @param array $driver_options
  1405. * (optional) This array holds one or more key=>value pairs to set
  1406. * attribute values for the PDOStatement object that this method returns.
  1407. * You would most commonly use this to set the \PDO::ATTR_CURSOR value to
  1408. * \PDO::CURSOR_SCROLL to request a scrollable cursor. Some drivers have
  1409. * driver specific options that may be set at prepare-time. Defaults to an
  1410. * empty array.
  1411. *
  1412. * @return \PDOStatement|false
  1413. * If the database server successfully prepares the statement, returns a
  1414. * \PDOStatement object.
  1415. * If the database server cannot successfully prepare the statement returns
  1416. * FALSE or emits \PDOException (depending on error handling).
  1417. *
  1418. * @throws \PDOException
  1419. *
  1420. * @see \PDO::prepare()
  1421. */
  1422. public function prepare($statement, array $driver_options = []) {
  1423. return $this->connection->prepare($statement, $driver_options);
  1424. }
  1425. /**
  1426. * Quotes a string for use in a query.
  1427. *
  1428. * @param string $string
  1429. * The string to be quoted.
  1430. * @param int $parameter_type
  1431. * (optional) Provides a data type hint for drivers that have alternate
  1432. * quoting styles. Defaults to \PDO::PARAM_STR.
  1433. *
  1434. * @return string|bool
  1435. * A quoted string that is theoretically safe to pass into an SQL statement.
  1436. * Returns FALSE if the driver does not support quoting in this way.
  1437. *
  1438. * @see \PDO::quote()
  1439. */
  1440. public function quote($string, $parameter_type = \PDO::PARAM_STR) {
  1441. return $this->connection->quote($string, $parameter_type);
  1442. }
  1443. /**
  1444. * Extracts the SQLSTATE error from the PDOException.
  1445. *
  1446. * @param \Exception $e
  1447. * The exception
  1448. *
  1449. * @return string
  1450. * The five character error code.
  1451. */
  1452. protected static function getSQLState(\Exception $e) {
  1453. // The PDOException code is not always reliable, try to see whether the
  1454. // message has something usable.
  1455. if (preg_match('/^SQLSTATE\[(\w{5})\]/', $e->getMessage(), $matches)) {
  1456. return $matches[1];
  1457. }
  1458. else {
  1459. return $e->getCode();
  1460. }
  1461. }
  1462. /**
  1463. * Prevents the database connection from being serialized.
  1464. */
  1465. public function __sleep() {
  1466. 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.');
  1467. }
  1468. /**
  1469. * Creates an array of database connection options from a URL.
  1470. *
  1471. * @param string $url
  1472. * The URL.
  1473. * @param string $root
  1474. * The root directory of the Drupal installation. Some database drivers,
  1475. * like for example SQLite, need this information.
  1476. *
  1477. * @return array
  1478. * The connection options.
  1479. *
  1480. * @throws \InvalidArgumentException
  1481. * Exception thrown when the provided URL does not meet the minimum
  1482. * requirements.
  1483. *
  1484. * @internal
  1485. * This method should only be called from
  1486. * \Drupal\Core\Database\Database::convertDbUrlToConnectionInfo().
  1487. *
  1488. * @see \Drupal\Core\Database\Database::convertDbUrlToConnectionInfo()
  1489. */
  1490. public static function createConnectionOptionsFromUrl($url, $root) {
  1491. $url_components = parse_url($url);
  1492. if (!isset($url_components['scheme'], $url_components['host'], $url_components['path'])) {
  1493. throw new \InvalidArgumentException('Minimum requirement: driver://host/database');
  1494. }
  1495. $url_components += [
  1496. 'user' => '',
  1497. 'pass' => '',
  1498. 'fragment' => '',
  1499. ];
  1500. // Remove leading slash from the URL path.
  1501. if ($url_components['path'][0] === '/') {
  1502. $url_components['path'] = substr($url_components['path'], 1);
  1503. }
  1504. // Use reflection to get the namespace of the class being called.
  1505. $reflector = new \ReflectionClass(get_called_class());
  1506. $database = [
  1507. 'driver' => $url_components['scheme'],
  1508. 'username' => $url_components['user'],
  1509. 'password' => $url_components['pass'],
  1510. 'host' => $url_components['host'],
  1511. 'database' => $url_components['path'],
  1512. 'namespace' => $reflector->getNamespaceName(),
  1513. ];
  1514. if (isset($url_components['port'])) {
  1515. $database['port'] = $url_components['port'];
  1516. }
  1517. if (!empty($url_components['fragment'])) {
  1518. $database['prefix']['default'] = $url_components['fragment'];
  1519. }
  1520. return $database;
  1521. }
  1522. /**
  1523. * Creates a URL from an array of database connection options.
  1524. *
  1525. * @param array $connection_options
  1526. * The array of connection options for a database connection. An additional
  1527. * key of 'module' is added by Database::getConnectionInfoAsUrl() for
  1528. * drivers provided my contributed or custom modules for convenience.
  1529. *
  1530. * @return string
  1531. * The connection info as a URL.
  1532. *
  1533. * @throws \InvalidArgumentException
  1534. * Exception thrown when the provided array of connection options does not
  1535. * meet the minimum requirements.
  1536. *
  1537. * @internal
  1538. * This method should only be called from
  1539. * \Drupal\Core\Database\Database::getConnectionInfoAsUrl().
  1540. *
  1541. * @see \Drupal\Core\Database\Database::getConnectionInfoAsUrl()
  1542. */
  1543. public static function createUrlFromConnectionOptions(array $connection_options) {
  1544. if (!isset($connection_options['driver'], $connection_options['database'])) {
  1545. throw new \InvalidArgumentException("As a minimum, the connection options array must contain at least the 'driver' and 'database' keys");
  1546. }
  1547. $user = '';
  1548. if (isset($connection_options['username'])) {
  1549. $user = $connection_options['username'];
  1550. if (isset($connection_options['password'])) {
  1551. $user .= ':' . $connection_options['password'];
  1552. }
  1553. $user .= '@';
  1554. }
  1555. $host = empty($connection_options['host']) ? 'localhost' : $connection_options['host'];
  1556. $db_url = $connection_options['driver'] . '://' . $user . $host;
  1557. if (isset($connection_options['port'])) {
  1558. $db_url .= ':' . $connection_options['port'];
  1559. }
  1560. $db_url .= '/' . $connection_options['database'];
  1561. // Add the module when the driver is provided by a module.
  1562. if (isset($connection_options['module'])) {
  1563. $db_url .= '?module=' . $connection_options['module'];
  1564. }
  1565. if (isset($connection_options['prefix']['default']) && $connection_options['prefix']['default'] !== '') {
  1566. $db_url .= '#' . $connection_options['prefix']['default'];
  1567. }
  1568. return $db_url;
  1569. }
  1570. }