schema.inc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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. abstract class DatabaseSchema implements QueryPlaceholderInterface {
  164. protected $connection;
  165. /**
  166. * The placeholder counter.
  167. */
  168. protected $placeholder = 0;
  169. /**
  170. * Definition of prefixInfo array structure.
  171. *
  172. * Rather than redefining DatabaseSchema::getPrefixInfo() for each driver,
  173. * by defining the defaultSchema variable only MySQL has to re-write the
  174. * method.
  175. *
  176. * @see DatabaseSchema::getPrefixInfo()
  177. */
  178. protected $defaultSchema = 'public';
  179. /**
  180. * A unique identifier for this query object.
  181. */
  182. protected $uniqueIdentifier;
  183. public function __construct($connection) {
  184. $this->uniqueIdentifier = uniqid('', TRUE);
  185. $this->connection = $connection;
  186. }
  187. /**
  188. * Implements the magic __clone function.
  189. */
  190. public function __clone() {
  191. $this->uniqueIdentifier = uniqid('', TRUE);
  192. }
  193. /**
  194. * Implements QueryPlaceHolderInterface::uniqueIdentifier().
  195. */
  196. public function uniqueIdentifier() {
  197. return $this->uniqueIdentifier;
  198. }
  199. /**
  200. * Implements QueryPlaceHolderInterface::nextPlaceholder().
  201. */
  202. public function nextPlaceholder() {
  203. return $this->placeholder++;
  204. }
  205. /**
  206. * Get information about the table name and schema from the prefix.
  207. *
  208. * @param
  209. * Name of table to look prefix up for. Defaults to 'default' because thats
  210. * default key for prefix.
  211. * @param $add_prefix
  212. * Boolean that indicates whether the given table name should be prefixed.
  213. *
  214. * @return
  215. * A keyed array with information about the schema, table name and prefix.
  216. */
  217. protected function getPrefixInfo($table = 'default', $add_prefix = TRUE) {
  218. $info = array(
  219. 'schema' => $this->defaultSchema,
  220. 'prefix' => $this->connection->tablePrefix($table),
  221. );
  222. if ($add_prefix) {
  223. $table = $info['prefix'] . $table;
  224. }
  225. // If the prefix contains a period in it, then that means the prefix also
  226. // contains a schema reference in which case we will change the schema key
  227. // to the value before the period in the prefix. Everything after the dot
  228. // will be prefixed onto the front of the table.
  229. if (($pos = strpos($table, '.')) !== FALSE) {
  230. // Grab everything before the period.
  231. $info['schema'] = substr($table, 0, $pos);
  232. // Grab everything after the dot.
  233. $info['table'] = substr($table, ++$pos);
  234. }
  235. else {
  236. $info['table'] = $table;
  237. }
  238. return $info;
  239. }
  240. /**
  241. * Create names for indexes, primary keys and constraints.
  242. *
  243. * This prevents using {} around non-table names like indexes and keys.
  244. */
  245. function prefixNonTable($table) {
  246. $args = func_get_args();
  247. $info = $this->getPrefixInfo($table);
  248. $args[0] = $info['table'];
  249. return implode('_', $args);
  250. }
  251. /**
  252. * Build a condition to match a table name against a standard information_schema.
  253. *
  254. * The information_schema is a SQL standard that provides information about the
  255. * database server and the databases, schemas, tables, columns and users within
  256. * it. This makes information_schema a useful tool to use across the drupal
  257. * database drivers and is used by a few different functions. The function below
  258. * describes the conditions to be meet when querying information_schema.tables
  259. * for drupal tables or information associated with drupal tables. Even though
  260. * this is the standard method, not all databases follow standards and so this
  261. * method should be overwritten by a database driver if the database provider
  262. * uses alternate methods. Because information_schema.tables is used in a few
  263. * different functions, a database driver will only need to override this function
  264. * to make all the others work. For example see includes/databases/mysql/schema.inc.
  265. *
  266. * @param $table_name
  267. * The name of the table in question.
  268. * @param $operator
  269. * The operator to apply on the 'table' part of the condition.
  270. * @param $add_prefix
  271. * Boolean to indicate whether the table name needs to be prefixed.
  272. *
  273. * @return QueryConditionInterface
  274. * A DatabaseCondition object.
  275. */
  276. protected function buildTableNameCondition($table_name, $operator = '=', $add_prefix = TRUE) {
  277. $info = $this->connection->getConnectionOptions();
  278. // Retrive the table name and schema
  279. $table_info = $this->getPrefixInfo($table_name, $add_prefix);
  280. $condition = new DatabaseCondition('AND');
  281. $condition->condition('table_catalog', $info['database']);
  282. $condition->condition('table_schema', $table_info['schema']);
  283. $condition->condition('table_name', $table_info['table'], $operator);
  284. return $condition;
  285. }
  286. /**
  287. * Check if a table exists.
  288. *
  289. * @param $table
  290. * The name of the table in drupal (no prefixing).
  291. *
  292. * @return
  293. * TRUE if the given table exists, otherwise FALSE.
  294. */
  295. public function tableExists($table) {
  296. $condition = $this->buildTableNameCondition($table);
  297. $condition->compile($this->connection, $this);
  298. // Normally, we would heartily discourage the use of string
  299. // concatenation for conditionals like this however, we
  300. // couldn't use db_select() here because it would prefix
  301. // information_schema.tables and the query would fail.
  302. // Don't use {} around information_schema.tables table.
  303. return (bool) $this->connection->query("SELECT 1 FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchField();
  304. }
  305. /**
  306. * Find all tables that are like the specified base table name.
  307. *
  308. * @param $table_expression
  309. * An SQL expression, for example "simpletest%" (without the quotes).
  310. * BEWARE: this is not prefixed, the caller should take care of that.
  311. *
  312. * @return
  313. * Array, both the keys and the values are the matching tables.
  314. */
  315. public function findTables($table_expression) {
  316. $condition = $this->buildTableNameCondition($table_expression, 'LIKE', FALSE);
  317. $condition->compile($this->connection, $this);
  318. // Normally, we would heartily discourage the use of string
  319. // concatenation for conditionals like this however, we
  320. // couldn't use db_select() here because it would prefix
  321. // information_schema.tables and the query would fail.
  322. // Don't use {} around information_schema.tables table.
  323. return $this->connection->query("SELECT table_name FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchAllKeyed(0, 0);
  324. }
  325. /**
  326. * Check if a column exists in the given table.
  327. *
  328. * @param $table
  329. * The name of the table in drupal (no prefixing).
  330. * @param $name
  331. * The name of the column.
  332. *
  333. * @return
  334. * TRUE if the given column exists, otherwise FALSE.
  335. */
  336. public function fieldExists($table, $column) {
  337. $condition = $this->buildTableNameCondition($table);
  338. $condition->condition('column_name', $column);
  339. $condition->compile($this->connection, $this);
  340. // Normally, we would heartily discourage the use of string
  341. // concatenation for conditionals like this however, we
  342. // couldn't use db_select() here because it would prefix
  343. // information_schema.tables and the query would fail.
  344. // Don't use {} around information_schema.columns table.
  345. return (bool) $this->connection->query("SELECT 1 FROM information_schema.columns WHERE " . (string) $condition, $condition->arguments())->fetchField();
  346. }
  347. /**
  348. * Returns a mapping of Drupal schema field names to DB-native field types.
  349. *
  350. * Because different field types do not map 1:1 between databases, Drupal has
  351. * its own normalized field type names. This function returns a driver-specific
  352. * mapping table from Drupal names to the native names for each database.
  353. *
  354. * @return array
  355. * An array of Schema API field types to driver-specific field types.
  356. */
  357. abstract public function getFieldTypeMap();
  358. /**
  359. * Rename a table.
  360. *
  361. * @param $table
  362. * The table to be renamed.
  363. * @param $new_name
  364. * The new name for the table.
  365. *
  366. * @throws DatabaseSchemaObjectDoesNotExistException
  367. * If the specified table doesn't exist.
  368. * @throws DatabaseSchemaObjectExistsException
  369. * If a table with the specified new name already exists.
  370. */
  371. abstract public function renameTable($table, $new_name);
  372. /**
  373. * Drop a table.
  374. *
  375. * @param $table
  376. * The table to be dropped.
  377. *
  378. * @return
  379. * TRUE if the table was successfully dropped, FALSE if there was no table
  380. * by that name to begin with.
  381. */
  382. abstract public function dropTable($table);
  383. /**
  384. * Add a new field to a table.
  385. *
  386. * @param $table
  387. * Name of the table to be altered.
  388. * @param $field
  389. * Name of the field to be added.
  390. * @param $spec
  391. * The field specification array, as taken from a schema definition.
  392. * The specification may also contain the key 'initial', the newly
  393. * created field will be set to the value of the key in all rows.
  394. * This is most useful for creating NOT NULL columns with no default
  395. * value in existing tables.
  396. * @param $keys_new
  397. * (optional) Keys and indexes specification to be created on the
  398. * table along with adding the field. The format is the same as a
  399. * table specification but without the 'fields' element. If you are
  400. * adding a type 'serial' field, you MUST specify at least one key
  401. * or index including it in this array. See db_change_field() for more
  402. * explanation why.
  403. *
  404. * @throws DatabaseSchemaObjectDoesNotExistException
  405. * If the specified table doesn't exist.
  406. * @throws DatabaseSchemaObjectExistsException
  407. * If the specified table already has a field by that name.
  408. */
  409. abstract public function addField($table, $field, $spec, $keys_new = array());
  410. /**
  411. * Drop a field.
  412. *
  413. * @param $table
  414. * The table to be altered.
  415. * @param $field
  416. * The field to be dropped.
  417. *
  418. * @return
  419. * TRUE if the field was successfully dropped, FALSE if there was no field
  420. * by that name to begin with.
  421. */
  422. abstract public function dropField($table, $field);
  423. /**
  424. * Set the default value for a field.
  425. *
  426. * @param $table
  427. * The table to be altered.
  428. * @param $field
  429. * The field to be altered.
  430. * @param $default
  431. * Default value to be set. NULL for 'default NULL'.
  432. *
  433. * @throws DatabaseSchemaObjectDoesNotExistException
  434. * If the specified table or field doesn't exist.
  435. */
  436. abstract public function fieldSetDefault($table, $field, $default);
  437. /**
  438. * Set a field to have no default value.
  439. *
  440. * @param $table
  441. * The table to be altered.
  442. * @param $field
  443. * The field to be altered.
  444. *
  445. * @throws DatabaseSchemaObjectDoesNotExistException
  446. * If the specified table or field doesn't exist.
  447. */
  448. abstract public function fieldSetNoDefault($table, $field);
  449. /**
  450. * Checks if an index exists in the given table.
  451. *
  452. * @param $table
  453. * The name of the table in drupal (no prefixing).
  454. * @param $name
  455. * The name of the index in drupal (no prefixing).
  456. *
  457. * @return
  458. * TRUE if the given index exists, otherwise FALSE.
  459. */
  460. abstract public function indexExists($table, $name);
  461. /**
  462. * Add a primary key.
  463. *
  464. * @param $table
  465. * The table to be altered.
  466. * @param $fields
  467. * Fields for the primary key.
  468. *
  469. * @throws DatabaseSchemaObjectDoesNotExistException
  470. * If the specified table doesn't exist.
  471. * @throws DatabaseSchemaObjectExistsException
  472. * If the specified table already has a primary key.
  473. */
  474. abstract public function addPrimaryKey($table, $fields);
  475. /**
  476. * Drop the primary key.
  477. *
  478. * @param $table
  479. * The table to be altered.
  480. *
  481. * @return
  482. * TRUE if the primary key was successfully dropped, FALSE if there was no
  483. * primary key on this table to begin with.
  484. */
  485. abstract public function dropPrimaryKey($table);
  486. /**
  487. * Add a unique key.
  488. *
  489. * @param $table
  490. * The table to be altered.
  491. * @param $name
  492. * The name of the key.
  493. * @param $fields
  494. * An array of field names.
  495. *
  496. * @throws DatabaseSchemaObjectDoesNotExistException
  497. * If the specified table doesn't exist.
  498. * @throws DatabaseSchemaObjectExistsException
  499. * If the specified table already has a key by that name.
  500. */
  501. abstract public function addUniqueKey($table, $name, $fields);
  502. /**
  503. * Drop a unique key.
  504. *
  505. * @param $table
  506. * The table to be altered.
  507. * @param $name
  508. * The name of the key.
  509. *
  510. * @return
  511. * TRUE if the key was successfully dropped, FALSE if there was no key by
  512. * that name to begin with.
  513. */
  514. abstract public function dropUniqueKey($table, $name);
  515. /**
  516. * Add an index.
  517. *
  518. * @param $table
  519. * The table to be altered.
  520. * @param $name
  521. * The name of the index.
  522. * @param $fields
  523. * An array of field names.
  524. *
  525. * @throws DatabaseSchemaObjectDoesNotExistException
  526. * If the specified table doesn't exist.
  527. * @throws DatabaseSchemaObjectExistsException
  528. * If the specified table already has an index by that name.
  529. */
  530. abstract public function addIndex($table, $name, $fields);
  531. /**
  532. * Drop an index.
  533. *
  534. * @param $table
  535. * The table to be altered.
  536. * @param $name
  537. * The name of the index.
  538. *
  539. * @return
  540. * TRUE if the index was successfully dropped, FALSE if there was no index
  541. * by that name to begin with.
  542. */
  543. abstract public function dropIndex($table, $name);
  544. /**
  545. * Change a field definition.
  546. *
  547. * IMPORTANT NOTE: To maintain database portability, you have to explicitly
  548. * recreate all indices and primary keys that are using the changed field.
  549. *
  550. * That means that you have to drop all affected keys and indexes with
  551. * db_drop_{primary_key,unique_key,index}() before calling db_change_field().
  552. * To recreate the keys and indices, pass the key definitions as the
  553. * optional $keys_new argument directly to db_change_field().
  554. *
  555. * For example, suppose you have:
  556. * @code
  557. * $schema['foo'] = array(
  558. * 'fields' => array(
  559. * 'bar' => array('type' => 'int', 'not null' => TRUE)
  560. * ),
  561. * 'primary key' => array('bar')
  562. * );
  563. * @endcode
  564. * and you want to change foo.bar to be type serial, leaving it as the
  565. * primary key. The correct sequence is:
  566. * @code
  567. * db_drop_primary_key('foo');
  568. * db_change_field('foo', 'bar', 'bar',
  569. * array('type' => 'serial', 'not null' => TRUE),
  570. * array('primary key' => array('bar')));
  571. * @endcode
  572. *
  573. * The reasons for this are due to the different database engines:
  574. *
  575. * On PostgreSQL, changing a field definition involves adding a new field
  576. * and dropping an old one which* causes any indices, primary keys and
  577. * sequences (from serial-type fields) that use the changed field to be dropped.
  578. *
  579. * On MySQL, all type 'serial' fields must be part of at least one key
  580. * or index as soon as they are created. You cannot use
  581. * db_add_{primary_key,unique_key,index}() for this purpose because
  582. * the ALTER TABLE command will fail to add the column without a key
  583. * or index specification. The solution is to use the optional
  584. * $keys_new argument to create the key or index at the same time as
  585. * field.
  586. *
  587. * You could use db_add_{primary_key,unique_key,index}() in all cases
  588. * unless you are converting a field to be type serial. You can use
  589. * the $keys_new argument in all cases.
  590. *
  591. * @param $table
  592. * Name of the table.
  593. * @param $field
  594. * Name of the field to change.
  595. * @param $field_new
  596. * New name for the field (set to the same as $field if you don't want to change the name).
  597. * @param $spec
  598. * The field specification for the new field.
  599. * @param $keys_new
  600. * (optional) Keys and indexes specification to be created on the
  601. * table along with changing the field. The format is the same as a
  602. * table specification but without the 'fields' element.
  603. *
  604. * @throws DatabaseSchemaObjectDoesNotExistException
  605. * If the specified table or source field doesn't exist.
  606. * @throws DatabaseSchemaObjectExistsException
  607. * If the specified destination field already exists.
  608. */
  609. abstract public function changeField($table, $field, $field_new, $spec, $keys_new = array());
  610. /**
  611. * Create a new table from a Drupal table definition.
  612. *
  613. * @param $name
  614. * The name of the table to create.
  615. * @param $table
  616. * A Schema API table definition array.
  617. *
  618. * @throws DatabaseSchemaObjectExistsException
  619. * If the specified table already exists.
  620. */
  621. public function createTable($name, $table) {
  622. if ($this->tableExists($name)) {
  623. throw new DatabaseSchemaObjectExistsException(t('Table @name already exists.', array('@name' => $name)));
  624. }
  625. $statements = $this->createTableSql($name, $table);
  626. foreach ($statements as $statement) {
  627. $this->connection->query($statement);
  628. }
  629. }
  630. /**
  631. * Return an array of field names from an array of key/index column specifiers.
  632. *
  633. * This is usually an identity function but if a key/index uses a column prefix
  634. * specification, this function extracts just the name.
  635. *
  636. * @param $fields
  637. * An array of key/index column specifiers.
  638. *
  639. * @return
  640. * An array of field names.
  641. */
  642. public function fieldNames($fields) {
  643. $return = array();
  644. foreach ($fields as $field) {
  645. if (is_array($field)) {
  646. $return[] = $field[0];
  647. }
  648. else {
  649. $return[] = $field;
  650. }
  651. }
  652. return $return;
  653. }
  654. /**
  655. * Prepare a table or column comment for database query.
  656. *
  657. * @param $comment
  658. * The comment string to prepare.
  659. * @param $length
  660. * Optional upper limit on the returned string length.
  661. *
  662. * @return
  663. * The prepared comment.
  664. */
  665. public function prepareComment($comment, $length = NULL) {
  666. return $this->connection->quote($comment);
  667. }
  668. }
  669. /**
  670. * Exception thrown if an object being created already exists.
  671. *
  672. * For example, this exception should be thrown whenever there is an attempt to
  673. * create a new database table, field, or index that already exists in the
  674. * database schema.
  675. */
  676. class DatabaseSchemaObjectExistsException extends Exception {}
  677. /**
  678. * Exception thrown if an object being modified doesn't exist yet.
  679. *
  680. * For example, this exception should be thrown whenever there is an attempt to
  681. * modify a database table, field, or index that does not currently exist in
  682. * the database schema.
  683. */
  684. class DatabaseSchemaObjectDoesNotExistException extends Exception {}
  685. /**
  686. * @} End of "defgroup schemaapi".
  687. */