schema.inc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. <?php
  2. /**
  3. * @file
  4. * Generic Database schema code.
  5. */
  6. require_once dirname(__FILE__) . '/query.inc';
  7. /**
  8. * @defgroup schemaapi Schema API
  9. * @{
  10. * API to handle database schemas.
  11. *
  12. * A Drupal schema definition is an array structure representing one or
  13. * more tables and their related keys and indexes. A schema is defined by
  14. * hook_schema(), which usually lives in a modulename.install file.
  15. *
  16. * By implementing hook_schema() and specifying the tables your module
  17. * declares, you can easily create and drop these tables on all
  18. * supported database engines. You don't have to deal with the
  19. * different SQL dialects for table creation and alteration of the
  20. * supported database engines.
  21. *
  22. * hook_schema() should return an array with a key for each table that
  23. * the module defines.
  24. *
  25. * The following keys are defined:
  26. * - 'description': A string in non-markup plain text describing this table
  27. * and its purpose. References to other tables should be enclosed in
  28. * curly-brackets. For example, the node_revisions table
  29. * description field might contain "Stores per-revision title and
  30. * body data for each {node}."
  31. * - 'fields': An associative array ('fieldname' => specification)
  32. * that describes the table's database columns. The specification
  33. * is also an array. The following specification parameters are defined:
  34. * - 'description': A string in non-markup plain text describing this field
  35. * and its purpose. References to other tables should be enclosed in
  36. * curly-brackets. For example, the node table vid field
  37. * description might contain "Always holds the largest (most
  38. * recent) {node_revision}.vid value for this nid."
  39. * - 'type': The generic datatype: 'char', 'varchar', 'text', 'blob', 'int',
  40. * 'float', 'numeric', or 'serial'. Most types just map to the according
  41. * database engine specific datatypes. Use 'serial' for auto incrementing
  42. * fields. This will expand to 'INT auto_increment' on MySQL.
  43. * - 'mysql_type', 'pgsql_type', 'sqlite_type', etc.: If you need to
  44. * use a record type not included in the officially supported list
  45. * of types above, you can specify a type for each database
  46. * backend. In this case, you can leave out the type parameter,
  47. * but be advised that your schema will fail to load on backends that
  48. * do not have a type specified. A possible solution can be to
  49. * use the "text" type as a fallback.
  50. * - 'serialize': A boolean indicating whether the field will be stored as
  51. * a serialized string.
  52. * - 'size': The data size: 'tiny', 'small', 'medium', 'normal',
  53. * 'big'. This is a hint about the largest value the field will
  54. * store and determines which of the database engine specific
  55. * datatypes will be used (e.g. on MySQL, TINYINT vs. INT vs. BIGINT).
  56. * 'normal', the default, selects the base type (e.g. on MySQL,
  57. * INT, VARCHAR, BLOB, etc.).
  58. * Not all sizes are available for all data types. See
  59. * DatabaseSchema::getFieldTypeMap() for possible combinations.
  60. * - 'not null': If true, no NULL values will be allowed in this
  61. * database column. Defaults to false.
  62. * - 'default': The field's default value. The PHP type of the
  63. * value matters: '', '0', and 0 are all different. If you
  64. * specify '0' as the default value for a type 'int' field it
  65. * will not work because '0' is a string containing the
  66. * character "zero", not an integer.
  67. * - 'length': The maximal length of a type 'char', 'varchar' or 'text'
  68. * field. Ignored for other field types.
  69. * - 'unsigned': A boolean indicating whether a type 'int', 'float'
  70. * and 'numeric' only is signed or unsigned. Defaults to
  71. * FALSE. Ignored for other field types.
  72. * - 'precision', 'scale': For type 'numeric' fields, indicates
  73. * the precision (total number of significant digits) and scale
  74. * (decimal digits right of the decimal point). Both values are
  75. * mandatory. Ignored for other field types.
  76. * - 'binary': A boolean indicating that MySQL should force 'char',
  77. * 'varchar' or 'text' fields to use case-sensitive binary collation.
  78. * This has no effect on other database types for which case sensitivity
  79. * is already the default behavior.
  80. * All parameters apart from 'type' are optional except that type
  81. * 'numeric' columns must specify 'precision' and 'scale', and type
  82. * 'varchar' must specify the 'length' parameter.
  83. * - 'primary key': An array of one or more key column specifiers (see below)
  84. * that form the primary key.
  85. * - 'unique keys': An associative array of unique keys ('keyname' =>
  86. * specification). Each specification is an array of one or more
  87. * key column specifiers (see below) that form a unique key on the table.
  88. * - 'foreign keys': An associative array of relations ('my_relation' =>
  89. * specification). Each specification is an array containing the name of
  90. * the referenced table ('table'), and an array of column mappings
  91. * ('columns'). Column mappings are defined by key pairs ('source_column' =>
  92. * 'referenced_column'). This key is for documentation purposes only; foreign
  93. * keys are not created in the database, nor are they enforced by Drupal.
  94. * - 'indexes': An associative array of indexes ('indexname' =>
  95. * specification). Each specification is an array of one or more
  96. * key column specifiers (see below) that form an index on the
  97. * table.
  98. *
  99. * A key column specifier is either a string naming a column or an
  100. * array of two elements, column name and length, specifying a prefix
  101. * of the named column.
  102. *
  103. * As an example, here is a SUBSET of the schema definition for
  104. * Drupal's 'node' table. It show four fields (nid, vid, type, and
  105. * title), the primary key on field 'nid', a unique key named 'vid' on
  106. * field 'vid', and two indexes, one named 'nid' on field 'nid' and
  107. * one named 'node_title_type' on the field 'title' and the first four
  108. * bytes of the field 'type':
  109. *
  110. * @code
  111. * $schema['node'] = array(
  112. * 'description' => 'The base table for nodes.',
  113. * 'fields' => array(
  114. * 'nid' => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
  115. * 'vid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE,'default' => 0),
  116. * 'type' => array('type' => 'varchar','length' => 32,'not null' => TRUE, 'default' => ''),
  117. * 'language' => array('type' => 'varchar','length' => 12,'not null' => TRUE,'default' => ''),
  118. * 'title' => array('type' => 'varchar','length' => 255,'not null' => TRUE, 'default' => ''),
  119. * 'uid' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
  120. * 'status' => array('type' => 'int', 'not null' => TRUE, 'default' => 1),
  121. * 'created' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
  122. * 'changed' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
  123. * 'comment' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
  124. * 'promote' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
  125. * 'moderate' => array('type' => 'int', 'not null' => TRUE,'default' => 0),
  126. * 'sticky' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
  127. * 'tnid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
  128. * 'translate' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
  129. * ),
  130. * 'indexes' => array(
  131. * 'node_changed' => array('changed'),
  132. * 'node_created' => array('created'),
  133. * 'node_moderate' => array('moderate'),
  134. * 'node_frontpage' => array('promote', 'status', 'sticky', 'created'),
  135. * 'node_status_type' => array('status', 'type', 'nid'),
  136. * 'node_title_type' => array('title', array('type', 4)),
  137. * 'node_type' => array(array('type', 4)),
  138. * 'uid' => array('uid'),
  139. * 'tnid' => array('tnid'),
  140. * 'translate' => array('translate'),
  141. * ),
  142. * 'unique keys' => array(
  143. * 'vid' => array('vid'),
  144. * ),
  145. * // For documentation purposes only; foreign keys are not created in the
  146. * // database.
  147. * 'foreign keys' => array(
  148. * 'node_revision' => array(
  149. * 'table' => 'node_revision',
  150. * 'columns' => array('vid' => 'vid'),
  151. * ),
  152. * 'node_author' => array(
  153. * 'table' => 'users',
  154. * 'columns' => array('uid' => 'uid'),
  155. * ),
  156. * ),
  157. * 'primary key' => array('nid'),
  158. * );
  159. * @endcode
  160. *
  161. * @see drupal_install_schema()
  162. */
  163. /**
  164. * Base class for database schema definitions.
  165. */
  166. abstract class DatabaseSchema implements QueryPlaceholderInterface {
  167. /**
  168. * The database connection.
  169. *
  170. * @var DatabaseConnection
  171. */
  172. protected $connection;
  173. /**
  174. * The placeholder counter.
  175. */
  176. protected $placeholder = 0;
  177. /**
  178. * Definition of prefixInfo array structure.
  179. *
  180. * Rather than redefining DatabaseSchema::getPrefixInfo() for each driver,
  181. * by defining the defaultSchema variable only MySQL has to re-write the
  182. * method.
  183. *
  184. * @see DatabaseSchema::getPrefixInfo()
  185. */
  186. protected $defaultSchema = 'public';
  187. /**
  188. * A unique identifier for this query object.
  189. */
  190. protected $uniqueIdentifier;
  191. public function __construct($connection) {
  192. $this->uniqueIdentifier = uniqid('', TRUE);
  193. $this->connection = $connection;
  194. }
  195. /**
  196. * Implements the magic __clone function.
  197. */
  198. public function __clone() {
  199. $this->uniqueIdentifier = uniqid('', TRUE);
  200. }
  201. /**
  202. * Implements QueryPlaceHolderInterface::uniqueIdentifier().
  203. */
  204. public function uniqueIdentifier() {
  205. return $this->uniqueIdentifier;
  206. }
  207. /**
  208. * Implements QueryPlaceHolderInterface::nextPlaceholder().
  209. */
  210. public function nextPlaceholder() {
  211. return $this->placeholder++;
  212. }
  213. /**
  214. * Get information about the table name and schema from the prefix.
  215. *
  216. * @param
  217. * Name of table to look prefix up for. Defaults to 'default' because thats
  218. * default key for prefix.
  219. * @param $add_prefix
  220. * Boolean that indicates whether the given table name should be prefixed.
  221. *
  222. * @return
  223. * A keyed array with information about the schema, table name and prefix.
  224. */
  225. protected function getPrefixInfo($table = 'default', $add_prefix = TRUE) {
  226. $info = array(
  227. 'schema' => $this->defaultSchema,
  228. 'prefix' => $this->connection->tablePrefix($table),
  229. );
  230. if ($add_prefix) {
  231. $table = $info['prefix'] . $table;
  232. }
  233. // If the prefix contains a period in it, then that means the prefix also
  234. // contains a schema reference in which case we will change the schema key
  235. // to the value before the period in the prefix. Everything after the dot
  236. // will be prefixed onto the front of the table.
  237. if (($pos = strpos($table, '.')) !== FALSE) {
  238. // Grab everything before the period.
  239. $info['schema'] = substr($table, 0, $pos);
  240. // Grab everything after the dot.
  241. $info['table'] = substr($table, ++$pos);
  242. }
  243. else {
  244. $info['table'] = $table;
  245. }
  246. return $info;
  247. }
  248. /**
  249. * Create names for indexes, primary keys and constraints.
  250. *
  251. * This prevents using {} around non-table names like indexes and keys.
  252. */
  253. function prefixNonTable($table) {
  254. $args = func_get_args();
  255. $info = $this->getPrefixInfo($table);
  256. $args[0] = $info['table'];
  257. return implode('_', $args);
  258. }
  259. /**
  260. * Build a condition to match a table name against a standard information_schema.
  261. *
  262. * The information_schema is a SQL standard that provides information about the
  263. * database server and the databases, schemas, tables, columns and users within
  264. * it. This makes information_schema a useful tool to use across the drupal
  265. * database drivers and is used by a few different functions. The function below
  266. * describes the conditions to be meet when querying information_schema.tables
  267. * for drupal tables or information associated with drupal tables. Even though
  268. * this is the standard method, not all databases follow standards and so this
  269. * method should be overwritten by a database driver if the database provider
  270. * uses alternate methods. Because information_schema.tables is used in a few
  271. * different functions, a database driver will only need to override this function
  272. * to make all the others work. For example see includes/databases/mysql/schema.inc.
  273. *
  274. * @param $table_name
  275. * The name of the table in question.
  276. * @param $operator
  277. * The operator to apply on the 'table' part of the condition.
  278. * @param $add_prefix
  279. * Boolean to indicate whether the table name needs to be prefixed.
  280. *
  281. * @return QueryConditionInterface
  282. * A DatabaseCondition object.
  283. */
  284. protected function buildTableNameCondition($table_name, $operator = '=', $add_prefix = TRUE) {
  285. $info = $this->connection->getConnectionOptions();
  286. // Retrieve the table name and schema
  287. $table_info = $this->getPrefixInfo($table_name, $add_prefix);
  288. $condition = new DatabaseCondition('AND');
  289. $condition->condition('table_catalog', $info['database']);
  290. $condition->condition('table_schema', $table_info['schema']);
  291. $condition->condition('table_name', $table_info['table'], $operator);
  292. return $condition;
  293. }
  294. /**
  295. * Check if a table exists.
  296. *
  297. * @param $table
  298. * The name of the table in drupal (no prefixing).
  299. *
  300. * @return
  301. * TRUE if the given table exists, otherwise FALSE.
  302. */
  303. public function tableExists($table) {
  304. $condition = $this->buildTableNameCondition($table);
  305. $condition->compile($this->connection, $this);
  306. // Normally, we would heartily discourage the use of string
  307. // concatenation for conditionals like this however, we
  308. // couldn't use db_select() here because it would prefix
  309. // information_schema.tables and the query would fail.
  310. // Don't use {} around information_schema.tables table.
  311. return (bool) $this->connection->query("SELECT 1 FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchField();
  312. }
  313. /**
  314. * Find all tables that are like the specified base table name.
  315. *
  316. * @param $table_expression
  317. * An SQL expression, for example "simpletest%" (without the quotes).
  318. * BEWARE: this is not prefixed, the caller should take care of that.
  319. *
  320. * @return
  321. * Array, both the keys and the values are the matching tables.
  322. */
  323. public function findTables($table_expression) {
  324. $condition = $this->buildTableNameCondition($table_expression, 'LIKE', FALSE);
  325. $condition->compile($this->connection, $this);
  326. // Normally, we would heartily discourage the use of string
  327. // concatenation for conditionals like this however, we
  328. // couldn't use db_select() here because it would prefix
  329. // information_schema.tables and the query would fail.
  330. // Don't use {} around information_schema.tables table.
  331. return $this->connection->query("SELECT table_name AS table_name FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchAllKeyed(0, 0);
  332. }
  333. /**
  334. * Finds all tables that are like the specified base table name. This is a
  335. * backport of the change made to findTables in Drupal 8 to work with virtual,
  336. * un-prefixed table names. The original function is retained for Backwards
  337. * Compatibility.
  338. * @see https://www.drupal.org/node/2552435
  339. *
  340. * @param string $table_expression
  341. * An SQL expression, for example "cache_%" (without the quotes).
  342. *
  343. * @return array
  344. * Both the keys and the values are the matching tables.
  345. */
  346. public function findTablesD8($table_expression) {
  347. // Load all the tables up front in order to take into account per-table
  348. // prefixes. The actual matching is done at the bottom of the method.
  349. $condition = $this->buildTableNameCondition('%', 'LIKE');
  350. $condition->compile($this->connection, $this);
  351. $individually_prefixed_tables = $this->connection->getUnprefixedTablesMap();
  352. $default_prefix = $this->connection->tablePrefix();
  353. $default_prefix_length = strlen($default_prefix);
  354. $tables = array();
  355. // Normally, we would heartily discourage the use of string
  356. // concatenation for conditionals like this however, we
  357. // couldn't use db_select() here because it would prefix
  358. // information_schema.tables and the query would fail.
  359. // Don't use {} around information_schema.tables table.
  360. $results = $this->connection->query("SELECT table_name AS table_name FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments());
  361. foreach ($results as $table) {
  362. // Take into account tables that have an individual prefix.
  363. if (isset($individually_prefixed_tables[$table->table_name])) {
  364. $prefix_length = strlen($this->connection->tablePrefix($individually_prefixed_tables[$table->table_name]));
  365. }
  366. elseif ($default_prefix && substr($table->table_name, 0, $default_prefix_length) !== $default_prefix) {
  367. // This table name does not start the default prefix, which means that
  368. // it is not managed by Drupal so it should be excluded from the result.
  369. continue;
  370. }
  371. else {
  372. $prefix_length = $default_prefix_length;
  373. }
  374. // Remove the prefix from the returned tables.
  375. $unprefixed_table_name = substr($table->table_name, $prefix_length);
  376. // The pattern can match a table which is the same as the prefix. That
  377. // will become an empty string when we remove the prefix, which will
  378. // probably surprise the caller, besides not being a prefixed table. So
  379. // remove it.
  380. if (!empty($unprefixed_table_name)) {
  381. $tables[$unprefixed_table_name] = $unprefixed_table_name;
  382. }
  383. }
  384. // Convert the table expression from its SQL LIKE syntax to a regular
  385. // expression and escape the delimiter that will be used for matching.
  386. $table_expression = str_replace(array('%', '_'), array('.*?', '.'), preg_quote($table_expression, '/'));
  387. $tables = preg_grep('/^' . $table_expression . '$/i', $tables);
  388. return $tables;
  389. }
  390. /**
  391. * Check if a column exists in the given table.
  392. *
  393. * @param $table
  394. * The name of the table in drupal (no prefixing).
  395. * @param $name
  396. * The name of the column.
  397. *
  398. * @return
  399. * TRUE if the given column exists, otherwise FALSE.
  400. */
  401. public function fieldExists($table, $column) {
  402. $condition = $this->buildTableNameCondition($table);
  403. $condition->condition('column_name', $column);
  404. $condition->compile($this->connection, $this);
  405. // Normally, we would heartily discourage the use of string
  406. // concatenation for conditionals like this however, we
  407. // couldn't use db_select() here because it would prefix
  408. // information_schema.tables and the query would fail.
  409. // Don't use {} around information_schema.columns table.
  410. return (bool) $this->connection->query("SELECT 1 FROM information_schema.columns WHERE " . (string) $condition, $condition->arguments())->fetchField();
  411. }
  412. /**
  413. * Returns a mapping of Drupal schema field names to DB-native field types.
  414. *
  415. * Because different field types do not map 1:1 between databases, Drupal has
  416. * its own normalized field type names. This function returns a driver-specific
  417. * mapping table from Drupal names to the native names for each database.
  418. *
  419. * @return array
  420. * An array of Schema API field types to driver-specific field types.
  421. */
  422. abstract public function getFieldTypeMap();
  423. /**
  424. * Rename a table.
  425. *
  426. * @param $table
  427. * The table to be renamed.
  428. * @param $new_name
  429. * The new name for the table.
  430. *
  431. * @throws DatabaseSchemaObjectDoesNotExistException
  432. * If the specified table doesn't exist.
  433. * @throws DatabaseSchemaObjectExistsException
  434. * If a table with the specified new name already exists.
  435. */
  436. abstract public function renameTable($table, $new_name);
  437. /**
  438. * Drop a table.
  439. *
  440. * @param $table
  441. * The table to be dropped.
  442. *
  443. * @return
  444. * TRUE if the table was successfully dropped, FALSE if there was no table
  445. * by that name to begin with.
  446. */
  447. abstract public function dropTable($table);
  448. /**
  449. * Add a new field to a table.
  450. *
  451. * @param $table
  452. * Name of the table to be altered.
  453. * @param $field
  454. * Name of the field to be added.
  455. * @param $spec
  456. * The field specification array, as taken from a schema definition.
  457. * The specification may also contain the key 'initial', the newly
  458. * created field will be set to the value of the key in all rows.
  459. * This is most useful for creating NOT NULL columns with no default
  460. * value in existing tables.
  461. * @param $keys_new
  462. * (optional) Keys and indexes specification to be created on the
  463. * table along with adding the field. The format is the same as a
  464. * table specification but without the 'fields' element. If you are
  465. * adding a type 'serial' field, you MUST specify at least one key
  466. * or index including it in this array. See db_change_field() for more
  467. * explanation why.
  468. *
  469. * @throws DatabaseSchemaObjectDoesNotExistException
  470. * If the specified table doesn't exist.
  471. * @throws DatabaseSchemaObjectExistsException
  472. * If the specified table already has a field by that name.
  473. */
  474. abstract public function addField($table, $field, $spec, $keys_new = array());
  475. /**
  476. * Drop a field.
  477. *
  478. * @param $table
  479. * The table to be altered.
  480. * @param $field
  481. * The field to be dropped.
  482. *
  483. * @return
  484. * TRUE if the field was successfully dropped, FALSE if there was no field
  485. * by that name to begin with.
  486. */
  487. abstract public function dropField($table, $field);
  488. /**
  489. * Set the default value for a field.
  490. *
  491. * @param $table
  492. * The table to be altered.
  493. * @param $field
  494. * The field to be altered.
  495. * @param $default
  496. * Default value to be set. NULL for 'default NULL'.
  497. *
  498. * @throws DatabaseSchemaObjectDoesNotExistException
  499. * If the specified table or field doesn't exist.
  500. */
  501. abstract public function fieldSetDefault($table, $field, $default);
  502. /**
  503. * Set a field to have no default value.
  504. *
  505. * @param $table
  506. * The table to be altered.
  507. * @param $field
  508. * The field to be altered.
  509. *
  510. * @throws DatabaseSchemaObjectDoesNotExistException
  511. * If the specified table or field doesn't exist.
  512. */
  513. abstract public function fieldSetNoDefault($table, $field);
  514. /**
  515. * Checks if an index exists in the given table.
  516. *
  517. * @param $table
  518. * The name of the table in drupal (no prefixing).
  519. * @param $name
  520. * The name of the index in drupal (no prefixing).
  521. *
  522. * @return
  523. * TRUE if the given index exists, otherwise FALSE.
  524. */
  525. abstract public function indexExists($table, $name);
  526. /**
  527. * Add a primary key.
  528. *
  529. * @param $table
  530. * The table to be altered.
  531. * @param $fields
  532. * Fields for the primary key.
  533. *
  534. * @throws DatabaseSchemaObjectDoesNotExistException
  535. * If the specified table doesn't exist.
  536. * @throws DatabaseSchemaObjectExistsException
  537. * If the specified table already has a primary key.
  538. */
  539. abstract public function addPrimaryKey($table, $fields);
  540. /**
  541. * Drop the primary key.
  542. *
  543. * @param $table
  544. * The table to be altered.
  545. *
  546. * @return
  547. * TRUE if the primary key was successfully dropped, FALSE if there was no
  548. * primary key on this table to begin with.
  549. */
  550. abstract public function dropPrimaryKey($table);
  551. /**
  552. * Add a unique key.
  553. *
  554. * @param $table
  555. * The table to be altered.
  556. * @param $name
  557. * The name of the key.
  558. * @param $fields
  559. * An array of field names.
  560. *
  561. * @throws DatabaseSchemaObjectDoesNotExistException
  562. * If the specified table doesn't exist.
  563. * @throws DatabaseSchemaObjectExistsException
  564. * If the specified table already has a key by that name.
  565. */
  566. abstract public function addUniqueKey($table, $name, $fields);
  567. /**
  568. * Drop a unique key.
  569. *
  570. * @param $table
  571. * The table to be altered.
  572. * @param $name
  573. * The name of the key.
  574. *
  575. * @return
  576. * TRUE if the key was successfully dropped, FALSE if there was no key by
  577. * that name to begin with.
  578. */
  579. abstract public function dropUniqueKey($table, $name);
  580. /**
  581. * Add an index.
  582. *
  583. * @param $table
  584. * The table to be altered.
  585. * @param $name
  586. * The name of the index.
  587. * @param $fields
  588. * An array of field names.
  589. *
  590. * @throws DatabaseSchemaObjectDoesNotExistException
  591. * If the specified table doesn't exist.
  592. * @throws DatabaseSchemaObjectExistsException
  593. * If the specified table already has an index by that name.
  594. */
  595. abstract public function addIndex($table, $name, $fields);
  596. /**
  597. * Drop an index.
  598. *
  599. * @param $table
  600. * The table to be altered.
  601. * @param $name
  602. * The name of the index.
  603. *
  604. * @return
  605. * TRUE if the index was successfully dropped, FALSE if there was no index
  606. * by that name to begin with.
  607. */
  608. abstract public function dropIndex($table, $name);
  609. /**
  610. * Change a field definition.
  611. *
  612. * IMPORTANT NOTE: To maintain database portability, you have to explicitly
  613. * recreate all indices and primary keys that are using the changed field.
  614. *
  615. * That means that you have to drop all affected keys and indexes with
  616. * db_drop_{primary_key,unique_key,index}() before calling db_change_field().
  617. * To recreate the keys and indices, pass the key definitions as the
  618. * optional $keys_new argument directly to db_change_field().
  619. *
  620. * For example, suppose you have:
  621. * @code
  622. * $schema['foo'] = array(
  623. * 'fields' => array(
  624. * 'bar' => array('type' => 'int', 'not null' => TRUE)
  625. * ),
  626. * 'primary key' => array('bar')
  627. * );
  628. * @endcode
  629. * and you want to change foo.bar to be type serial, leaving it as the
  630. * primary key. The correct sequence is:
  631. * @code
  632. * db_drop_primary_key('foo');
  633. * db_change_field('foo', 'bar', 'bar',
  634. * array('type' => 'serial', 'not null' => TRUE),
  635. * array('primary key' => array('bar')));
  636. * @endcode
  637. *
  638. * The reasons for this are due to the different database engines:
  639. *
  640. * On PostgreSQL, changing a field definition involves adding a new field
  641. * and dropping an old one which* causes any indices, primary keys and
  642. * sequences (from serial-type fields) that use the changed field to be dropped.
  643. *
  644. * On MySQL, all type 'serial' fields must be part of at least one key
  645. * or index as soon as they are created. You cannot use
  646. * db_add_{primary_key,unique_key,index}() for this purpose because
  647. * the ALTER TABLE command will fail to add the column without a key
  648. * or index specification. The solution is to use the optional
  649. * $keys_new argument to create the key or index at the same time as
  650. * field.
  651. *
  652. * You could use db_add_{primary_key,unique_key,index}() in all cases
  653. * unless you are converting a field to be type serial. You can use
  654. * the $keys_new argument in all cases.
  655. *
  656. * @param $table
  657. * Name of the table.
  658. * @param $field
  659. * Name of the field to change.
  660. * @param $field_new
  661. * New name for the field (set to the same as $field if you don't want to change the name).
  662. * @param $spec
  663. * The field specification for the new field.
  664. * @param $keys_new
  665. * (optional) Keys and indexes specification to be created on the
  666. * table along with changing the field. The format is the same as a
  667. * table specification but without the 'fields' element.
  668. *
  669. * @throws DatabaseSchemaObjectDoesNotExistException
  670. * If the specified table or source field doesn't exist.
  671. * @throws DatabaseSchemaObjectExistsException
  672. * If the specified destination field already exists.
  673. */
  674. abstract public function changeField($table, $field, $field_new, $spec, $keys_new = array());
  675. /**
  676. * Create a new table from a Drupal table definition.
  677. *
  678. * @param $name
  679. * The name of the table to create.
  680. * @param $table
  681. * A Schema API table definition array.
  682. *
  683. * @throws DatabaseSchemaObjectExistsException
  684. * If the specified table already exists.
  685. */
  686. public function createTable($name, $table) {
  687. if ($this->tableExists($name)) {
  688. throw new DatabaseSchemaObjectExistsException(t('Table @name already exists.', array('@name' => $name)));
  689. }
  690. $statements = $this->createTableSql($name, $table);
  691. foreach ($statements as $statement) {
  692. $this->connection->query($statement);
  693. }
  694. }
  695. /**
  696. * Return an array of field names from an array of key/index column specifiers.
  697. *
  698. * This is usually an identity function but if a key/index uses a column prefix
  699. * specification, this function extracts just the name.
  700. *
  701. * @param $fields
  702. * An array of key/index column specifiers.
  703. *
  704. * @return
  705. * An array of field names.
  706. */
  707. public function fieldNames($fields) {
  708. $return = array();
  709. foreach ($fields as $field) {
  710. if (is_array($field)) {
  711. $return[] = $field[0];
  712. }
  713. else {
  714. $return[] = $field;
  715. }
  716. }
  717. return $return;
  718. }
  719. /**
  720. * Prepare a table or column comment for database query.
  721. *
  722. * @param $comment
  723. * The comment string to prepare.
  724. * @param $length
  725. * Optional upper limit on the returned string length.
  726. *
  727. * @return
  728. * The prepared comment.
  729. */
  730. public function prepareComment($comment, $length = NULL) {
  731. return $this->connection->quote($comment);
  732. }
  733. }
  734. /**
  735. * Exception thrown if an object being created already exists.
  736. *
  737. * For example, this exception should be thrown whenever there is an attempt to
  738. * create a new database table, field, or index that already exists in the
  739. * database schema.
  740. */
  741. class DatabaseSchemaObjectExistsException extends Exception {}
  742. /**
  743. * Exception thrown if an object being modified doesn't exist yet.
  744. *
  745. * For example, this exception should be thrown whenever there is an attempt to
  746. * modify a database table, field, or index that does not currently exist in
  747. * the database schema.
  748. */
  749. class DatabaseSchemaObjectDoesNotExistException extends Exception {}
  750. /**
  751. * @} End of "defgroup schemaapi".
  752. */