schema.inc 26 KB

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