Schema.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. <?php
  2. namespace Drupal\Core\Database;
  3. use Drupal\Core\Database\Query\Condition;
  4. use Drupal\Core\Database\Query\PlaceholderInterface;
  5. /**
  6. * Provides a base implementation for Database Schema.
  7. */
  8. abstract class Schema implements PlaceholderInterface {
  9. /**
  10. * The database connection.
  11. *
  12. * @var \Drupal\Core\Database\Connection
  13. */
  14. protected $connection;
  15. /**
  16. * The placeholder counter.
  17. *
  18. * @var int
  19. */
  20. protected $placeholder = 0;
  21. /**
  22. * Definition of prefixInfo array structure.
  23. *
  24. * Rather than redefining DatabaseSchema::getPrefixInfo() for each driver,
  25. * by defining the defaultSchema variable only MySQL has to re-write the
  26. * method.
  27. *
  28. * @see DatabaseSchema::getPrefixInfo()
  29. *
  30. * @var string
  31. */
  32. protected $defaultSchema = 'public';
  33. /**
  34. * A unique identifier for this query object.
  35. */
  36. protected $uniqueIdentifier;
  37. public function __construct($connection) {
  38. $this->uniqueIdentifier = uniqid('', TRUE);
  39. $this->connection = $connection;
  40. }
  41. /**
  42. * Implements the magic __clone function.
  43. */
  44. public function __clone() {
  45. $this->uniqueIdentifier = uniqid('', TRUE);
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public function uniqueIdentifier() {
  51. return $this->uniqueIdentifier;
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function nextPlaceholder() {
  57. return $this->placeholder++;
  58. }
  59. /**
  60. * Get information about the table name and schema from the prefix.
  61. *
  62. * @param
  63. * Name of table to look prefix up for. Defaults to 'default' because that's
  64. * default key for prefix.
  65. * @param $add_prefix
  66. * Boolean that indicates whether the given table name should be prefixed.
  67. *
  68. * @return
  69. * A keyed array with information about the schema, table name and prefix.
  70. */
  71. protected function getPrefixInfo($table = 'default', $add_prefix = TRUE) {
  72. $info = [
  73. 'schema' => $this->defaultSchema,
  74. 'prefix' => $this->connection->tablePrefix($table),
  75. ];
  76. if ($add_prefix) {
  77. $table = $info['prefix'] . $table;
  78. }
  79. // If the prefix contains a period in it, then that means the prefix also
  80. // contains a schema reference in which case we will change the schema key
  81. // to the value before the period in the prefix. Everything after the dot
  82. // will be prefixed onto the front of the table.
  83. if (($pos = strpos($table, '.')) !== FALSE) {
  84. // Grab everything before the period.
  85. $info['schema'] = substr($table, 0, $pos);
  86. // Grab everything after the dot.
  87. $info['table'] = substr($table, ++$pos);
  88. }
  89. else {
  90. $info['table'] = $table;
  91. }
  92. return $info;
  93. }
  94. /**
  95. * Create names for indexes, primary keys and constraints.
  96. *
  97. * This prevents using {} around non-table names like indexes and keys.
  98. */
  99. public function prefixNonTable($table) {
  100. $args = func_get_args();
  101. $info = $this->getPrefixInfo($table);
  102. $args[0] = $info['table'];
  103. return implode('_', $args);
  104. }
  105. /**
  106. * Build a condition to match a table name against a standard information_schema.
  107. *
  108. * The information_schema is a SQL standard that provides information about the
  109. * database server and the databases, schemas, tables, columns and users within
  110. * it. This makes information_schema a useful tool to use across the drupal
  111. * database drivers and is used by a few different functions. The function below
  112. * describes the conditions to be meet when querying information_schema.tables
  113. * for drupal tables or information associated with drupal tables. Even though
  114. * this is the standard method, not all databases follow standards and so this
  115. * method should be overwritten by a database driver if the database provider
  116. * uses alternate methods. Because information_schema.tables is used in a few
  117. * different functions, a database driver will only need to override this function
  118. * to make all the others work. For example see
  119. * core/includes/databases/mysql/schema.inc.
  120. *
  121. * @param $table_name
  122. * The name of the table in question.
  123. * @param $operator
  124. * The operator to apply on the 'table' part of the condition.
  125. * @param $add_prefix
  126. * Boolean to indicate whether the table name needs to be prefixed.
  127. *
  128. * @return \Drupal\Core\Database\Query\Condition
  129. * A Condition object.
  130. */
  131. protected function buildTableNameCondition($table_name, $operator = '=', $add_prefix = TRUE) {
  132. $info = $this->connection->getConnectionOptions();
  133. // Retrieve the table name and schema
  134. $table_info = $this->getPrefixInfo($table_name, $add_prefix);
  135. $condition = new Condition('AND');
  136. $condition->condition('table_catalog', $info['database']);
  137. $condition->condition('table_schema', $table_info['schema']);
  138. $condition->condition('table_name', $table_info['table'], $operator);
  139. return $condition;
  140. }
  141. /**
  142. * Check if a table exists.
  143. *
  144. * @param $table
  145. * The name of the table in drupal (no prefixing).
  146. *
  147. * @return
  148. * TRUE if the given table exists, otherwise FALSE.
  149. */
  150. public function tableExists($table) {
  151. $condition = $this->buildTableNameCondition($table);
  152. $condition->compile($this->connection, $this);
  153. // Normally, we would heartily discourage the use of string
  154. // concatenation for conditionals like this however, we
  155. // couldn't use db_select() here because it would prefix
  156. // information_schema.tables and the query would fail.
  157. // Don't use {} around information_schema.tables table.
  158. return (bool) $this->connection->query("SELECT 1 FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchField();
  159. }
  160. /**
  161. * Finds all tables that are like the specified base table name.
  162. *
  163. * @param string $table_expression
  164. * An SQL expression, for example "cache_%" (without the quotes).
  165. *
  166. * @return array
  167. * Both the keys and the values are the matching tables.
  168. */
  169. public function findTables($table_expression) {
  170. // Load all the tables up front in order to take into account per-table
  171. // prefixes. The actual matching is done at the bottom of the method.
  172. $condition = $this->buildTableNameCondition('%', 'LIKE');
  173. $condition->compile($this->connection, $this);
  174. $individually_prefixed_tables = $this->connection->getUnprefixedTablesMap();
  175. $default_prefix = $this->connection->tablePrefix();
  176. $default_prefix_length = strlen($default_prefix);
  177. $tables = [];
  178. // Normally, we would heartily discourage the use of string
  179. // concatenation for conditionals like this however, we
  180. // couldn't use db_select() here because it would prefix
  181. // information_schema.tables and the query would fail.
  182. // Don't use {} around information_schema.tables table.
  183. $results = $this->connection->query("SELECT table_name FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments());
  184. foreach ($results as $table) {
  185. // Take into account tables that have an individual prefix.
  186. if (isset($individually_prefixed_tables[$table->table_name])) {
  187. $prefix_length = strlen($this->connection->tablePrefix($individually_prefixed_tables[$table->table_name]));
  188. }
  189. elseif ($default_prefix && substr($table->table_name, 0, $default_prefix_length) !== $default_prefix) {
  190. // This table name does not start the default prefix, which means that
  191. // it is not managed by Drupal so it should be excluded from the result.
  192. continue;
  193. }
  194. else {
  195. $prefix_length = $default_prefix_length;
  196. }
  197. // Remove the prefix from the returned tables.
  198. $unprefixed_table_name = substr($table->table_name, $prefix_length);
  199. // The pattern can match a table which is the same as the prefix. That
  200. // will become an empty string when we remove the prefix, which will
  201. // probably surprise the caller, besides not being a prefixed table. So
  202. // remove it.
  203. if (!empty($unprefixed_table_name)) {
  204. $tables[$unprefixed_table_name] = $unprefixed_table_name;
  205. }
  206. }
  207. // Convert the table expression from its SQL LIKE syntax to a regular
  208. // expression and escape the delimiter that will be used for matching.
  209. $table_expression = str_replace(['%', '_'], ['.*?', '.'], preg_quote($table_expression, '/'));
  210. $tables = preg_grep('/^' . $table_expression . '$/i', $tables);
  211. return $tables;
  212. }
  213. /**
  214. * Check if a column exists in the given table.
  215. *
  216. * @param $table
  217. * The name of the table in drupal (no prefixing).
  218. * @param $name
  219. * The name of the column.
  220. *
  221. * @return
  222. * TRUE if the given column exists, otherwise FALSE.
  223. */
  224. public function fieldExists($table, $column) {
  225. $condition = $this->buildTableNameCondition($table);
  226. $condition->condition('column_name', $column);
  227. $condition->compile($this->connection, $this);
  228. // Normally, we would heartily discourage the use of string
  229. // concatenation for conditionals like this however, we
  230. // couldn't use db_select() here because it would prefix
  231. // information_schema.tables and the query would fail.
  232. // Don't use {} around information_schema.columns table.
  233. return (bool) $this->connection->query("SELECT 1 FROM information_schema.columns WHERE " . (string) $condition, $condition->arguments())->fetchField();
  234. }
  235. /**
  236. * Returns a mapping of Drupal schema field names to DB-native field types.
  237. *
  238. * Because different field types do not map 1:1 between databases, Drupal has
  239. * its own normalized field type names. This function returns a driver-specific
  240. * mapping table from Drupal names to the native names for each database.
  241. *
  242. * @return array
  243. * An array of Schema API field types to driver-specific field types.
  244. */
  245. abstract public function getFieldTypeMap();
  246. /**
  247. * Rename a table.
  248. *
  249. * @param $table
  250. * The table to be renamed.
  251. * @param $new_name
  252. * The new name for the table.
  253. *
  254. * @throws \Drupal\Core\Database\SchemaObjectDoesNotExistException
  255. * If the specified table doesn't exist.
  256. * @throws \Drupal\Core\Database\SchemaObjectExistsException
  257. * If a table with the specified new name already exists.
  258. */
  259. abstract public function renameTable($table, $new_name);
  260. /**
  261. * Drop a table.
  262. *
  263. * @param $table
  264. * The table to be dropped.
  265. *
  266. * @return
  267. * TRUE if the table was successfully dropped, FALSE if there was no table
  268. * by that name to begin with.
  269. */
  270. abstract public function dropTable($table);
  271. /**
  272. * Add a new field to a table.
  273. *
  274. * @param $table
  275. * Name of the table to be altered.
  276. * @param $field
  277. * Name of the field to be added.
  278. * @param $spec
  279. * The field specification array, as taken from a schema definition.
  280. * The specification may also contain the key 'initial', the newly
  281. * created field will be set to the value of the key in all rows.
  282. * This is most useful for creating NOT NULL columns with no default
  283. * value in existing tables.
  284. * Alternatively, the 'initial_form_field' key may be used, which will
  285. * auto-populate the new field with values from the specified field.
  286. * @param $keys_new
  287. * (optional) Keys and indexes specification to be created on the
  288. * table along with adding the field. The format is the same as a
  289. * table specification but without the 'fields' element. If you are
  290. * adding a type 'serial' field, you MUST specify at least one key
  291. * or index including it in this array. See db_change_field() for more
  292. * explanation why.
  293. *
  294. * @throws \Drupal\Core\Database\SchemaObjectDoesNotExistException
  295. * If the specified table doesn't exist.
  296. * @throws \Drupal\Core\Database\SchemaObjectExistsException
  297. * If the specified table already has a field by that name.
  298. */
  299. abstract public function addField($table, $field, $spec, $keys_new = []);
  300. /**
  301. * Drop a field.
  302. *
  303. * @param $table
  304. * The table to be altered.
  305. * @param $field
  306. * The field to be dropped.
  307. *
  308. * @return
  309. * TRUE if the field was successfully dropped, FALSE if there was no field
  310. * by that name to begin with.
  311. */
  312. abstract public function dropField($table, $field);
  313. /**
  314. * Set the default value for a field.
  315. *
  316. * @param $table
  317. * The table to be altered.
  318. * @param $field
  319. * The field to be altered.
  320. * @param $default
  321. * Default value to be set. NULL for 'default NULL'.
  322. *
  323. * @throws \Drupal\Core\Database\SchemaObjectDoesNotExistException
  324. * If the specified table or field doesn't exist.
  325. */
  326. abstract public function fieldSetDefault($table, $field, $default);
  327. /**
  328. * Set a field to have no default value.
  329. *
  330. * @param $table
  331. * The table to be altered.
  332. * @param $field
  333. * The field to be altered.
  334. *
  335. * @throws \Drupal\Core\Database\SchemaObjectDoesNotExistException
  336. * If the specified table or field doesn't exist.
  337. */
  338. abstract public function fieldSetNoDefault($table, $field);
  339. /**
  340. * Checks if an index exists in the given table.
  341. *
  342. * @param $table
  343. * The name of the table in drupal (no prefixing).
  344. * @param $name
  345. * The name of the index in drupal (no prefixing).
  346. *
  347. * @return
  348. * TRUE if the given index exists, otherwise FALSE.
  349. */
  350. abstract public function indexExists($table, $name);
  351. /**
  352. * Add a primary key.
  353. *
  354. * @param $table
  355. * The table to be altered.
  356. * @param $fields
  357. * Fields for the primary key.
  358. *
  359. * @throws \Drupal\Core\Database\SchemaObjectDoesNotExistException
  360. * If the specified table doesn't exist.
  361. * @throws \Drupal\Core\Database\SchemaObjectExistsException
  362. * If the specified table already has a primary key.
  363. */
  364. abstract public function addPrimaryKey($table, $fields);
  365. /**
  366. * Drop the primary key.
  367. *
  368. * @param $table
  369. * The table to be altered.
  370. *
  371. * @return
  372. * TRUE if the primary key was successfully dropped, FALSE if there was no
  373. * primary key on this table to begin with.
  374. */
  375. abstract public function dropPrimaryKey($table);
  376. /**
  377. * Add a unique key.
  378. *
  379. * @param $table
  380. * The table to be altered.
  381. * @param $name
  382. * The name of the key.
  383. * @param $fields
  384. * An array of field names.
  385. *
  386. * @throws \Drupal\Core\Database\SchemaObjectDoesNotExistException
  387. * If the specified table doesn't exist.
  388. * @throws \Drupal\Core\Database\SchemaObjectExistsException
  389. * If the specified table already has a key by that name.
  390. */
  391. abstract public function addUniqueKey($table, $name, $fields);
  392. /**
  393. * Drop a unique key.
  394. *
  395. * @param $table
  396. * The table to be altered.
  397. * @param $name
  398. * The name of the key.
  399. *
  400. * @return
  401. * TRUE if the key was successfully dropped, FALSE if there was no key by
  402. * that name to begin with.
  403. */
  404. abstract public function dropUniqueKey($table, $name);
  405. /**
  406. * Add an index.
  407. *
  408. * @param $table
  409. * The table to be altered.
  410. * @param $name
  411. * The name of the index.
  412. * @param $fields
  413. * An array of field names or field information; if field information is
  414. * passed, it's an array whose first element is the field name and whose
  415. * second is the maximum length in the index. For example, the following
  416. * will use the full length of the `foo` field, but limit the `bar` field to
  417. * 4 characters:
  418. * @code
  419. * $fields = ['foo', ['bar', 4]];
  420. * @endcode
  421. * @param array $spec
  422. * The table specification for the table to be altered. This is used in
  423. * order to be able to ensure that the index length is not too long.
  424. * This schema definition can usually be obtained through hook_schema(), or
  425. * in case the table was created by the Entity API, through the schema
  426. * handler listed in the entity class definition. For reference, see
  427. * SqlContentEntityStorageSchema::getDedicatedTableSchema() and
  428. * SqlContentEntityStorageSchema::getSharedTableFieldSchema().
  429. *
  430. * In order to prevent human error, it is recommended to pass in the
  431. * complete table specification. However, in the edge case of the complete
  432. * table specification not being available, we can pass in a partial table
  433. * definition containing only the fields that apply to the index:
  434. * @code
  435. * $spec = [
  436. * // Example partial specification for a table:
  437. * 'fields' => [
  438. * 'example_field' => [
  439. * 'description' => 'An example field',
  440. * 'type' => 'varchar',
  441. * 'length' => 32,
  442. * 'not null' => TRUE,
  443. * 'default' => '',
  444. * ],
  445. * ],
  446. * 'indexes' => [
  447. * 'table_example_field' => ['example_field'],
  448. * ],
  449. * ];
  450. * @endcode
  451. * Note that the above is a partial table definition and that we would
  452. * usually pass a complete table definition as obtained through
  453. * hook_schema() instead.
  454. *
  455. * @see schemaapi
  456. * @see hook_schema()
  457. *
  458. * @throws \Drupal\Core\Database\SchemaObjectDoesNotExistException
  459. * If the specified table doesn't exist.
  460. * @throws \Drupal\Core\Database\SchemaObjectExistsException
  461. * If the specified table already has an index by that name.
  462. *
  463. * @todo remove the $spec argument whenever schema introspection is added.
  464. */
  465. abstract public function addIndex($table, $name, $fields, array $spec);
  466. /**
  467. * Drop an index.
  468. *
  469. * @param $table
  470. * The table to be altered.
  471. * @param $name
  472. * The name of the index.
  473. *
  474. * @return
  475. * TRUE if the index was successfully dropped, FALSE if there was no index
  476. * by that name to begin with.
  477. */
  478. abstract public function dropIndex($table, $name);
  479. /**
  480. * Change a field definition.
  481. *
  482. * IMPORTANT NOTE: To maintain database portability, you have to explicitly
  483. * recreate all indices and primary keys that are using the changed field.
  484. *
  485. * That means that you have to drop all affected keys and indexes with
  486. * db_drop_{primary_key,unique_key,index}() before calling db_change_field().
  487. * To recreate the keys and indices, pass the key definitions as the
  488. * optional $keys_new argument directly to db_change_field().
  489. *
  490. * For example, suppose you have:
  491. * @code
  492. * $schema['foo'] = array(
  493. * 'fields' => array(
  494. * 'bar' => array('type' => 'int', 'not null' => TRUE)
  495. * ),
  496. * 'primary key' => array('bar')
  497. * );
  498. * @endcode
  499. * and you want to change foo.bar to be type serial, leaving it as the
  500. * primary key. The correct sequence is:
  501. * @code
  502. * db_drop_primary_key('foo');
  503. * db_change_field('foo', 'bar', 'bar',
  504. * array('type' => 'serial', 'not null' => TRUE),
  505. * array('primary key' => array('bar')));
  506. * @endcode
  507. *
  508. * The reasons for this are due to the different database engines:
  509. *
  510. * On PostgreSQL, changing a field definition involves adding a new field
  511. * and dropping an old one which* causes any indices, primary keys and
  512. * sequences (from serial-type fields) that use the changed field to be dropped.
  513. *
  514. * On MySQL, all type 'serial' fields must be part of at least one key
  515. * or index as soon as they are created. You cannot use
  516. * db_add_{primary_key,unique_key,index}() for this purpose because
  517. * the ALTER TABLE command will fail to add the column without a key
  518. * or index specification. The solution is to use the optional
  519. * $keys_new argument to create the key or index at the same time as
  520. * field.
  521. *
  522. * You could use db_add_{primary_key,unique_key,index}() in all cases
  523. * unless you are converting a field to be type serial. You can use
  524. * the $keys_new argument in all cases.
  525. *
  526. * @param $table
  527. * Name of the table.
  528. * @param $field
  529. * Name of the field to change.
  530. * @param $field_new
  531. * New name for the field (set to the same as $field if you don't want to change the name).
  532. * @param $spec
  533. * The field specification for the new field.
  534. * @param $keys_new
  535. * (optional) Keys and indexes specification to be created on the
  536. * table along with changing the field. The format is the same as a
  537. * table specification but without the 'fields' element.
  538. *
  539. * @throws \Drupal\Core\Database\SchemaObjectDoesNotExistException
  540. * If the specified table or source field doesn't exist.
  541. * @throws \Drupal\Core\Database\SchemaObjectExistsException
  542. * If the specified destination field already exists.
  543. */
  544. abstract public function changeField($table, $field, $field_new, $spec, $keys_new = []);
  545. /**
  546. * Create a new table from a Drupal table definition.
  547. *
  548. * @param $name
  549. * The name of the table to create.
  550. * @param $table
  551. * A Schema API table definition array.
  552. *
  553. * @throws \Drupal\Core\Database\SchemaObjectExistsException
  554. * If the specified table already exists.
  555. */
  556. public function createTable($name, $table) {
  557. if ($this->tableExists($name)) {
  558. throw new SchemaObjectExistsException(t('Table @name already exists.', ['@name' => $name]));
  559. }
  560. $statements = $this->createTableSql($name, $table);
  561. foreach ($statements as $statement) {
  562. $this->connection->query($statement);
  563. }
  564. }
  565. /**
  566. * Return an array of field names from an array of key/index column specifiers.
  567. *
  568. * This is usually an identity function but if a key/index uses a column prefix
  569. * specification, this function extracts just the name.
  570. *
  571. * @param $fields
  572. * An array of key/index column specifiers.
  573. *
  574. * @return
  575. * An array of field names.
  576. */
  577. public function fieldNames($fields) {
  578. $return = [];
  579. foreach ($fields as $field) {
  580. if (is_array($field)) {
  581. $return[] = $field[0];
  582. }
  583. else {
  584. $return[] = $field;
  585. }
  586. }
  587. return $return;
  588. }
  589. /**
  590. * Prepare a table or column comment for database query.
  591. *
  592. * @param $comment
  593. * The comment string to prepare.
  594. * @param $length
  595. * Optional upper limit on the returned string length.
  596. *
  597. * @return
  598. * The prepared comment.
  599. */
  600. public function prepareComment($comment, $length = NULL) {
  601. // Remove semicolons to avoid triggering multi-statement check.
  602. $comment = strtr($comment, [';' => '.']);
  603. return $this->connection->quote($comment);
  604. }
  605. /**
  606. * Return an escaped version of its parameter to be used as a default value
  607. * on a column.
  608. *
  609. * @param mixed $value
  610. * The value to be escaped (int, float, null or string).
  611. *
  612. * @return string|int|float
  613. * The escaped value.
  614. */
  615. protected function escapeDefaultValue($value) {
  616. if (is_null($value)) {
  617. return 'NULL';
  618. }
  619. return is_string($value) ? $this->connection->quote($value) : $value;
  620. }
  621. }