schema.inc 27 KB

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