Table.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Database\Schema;
  16. use Cake\Database\Connection;
  17. use Cake\Database\Exception;
  18. /**
  19. * Represents a single table in a database schema.
  20. *
  21. * Can either be populated using the reflection API's
  22. * or by incrementally building an instance using
  23. * methods.
  24. *
  25. * Once created Table instances can be added to
  26. * Schema\Collection objects. They can also be converted into SQL using the
  27. * createSql(), dropSql() and truncateSql() methods.
  28. */
  29. class Table {
  30. /**
  31. * The name of the table
  32. *
  33. * @var string
  34. */
  35. protected $_table;
  36. /**
  37. * Columns in the table.
  38. *
  39. * @var array
  40. */
  41. protected $_columns = [];
  42. /**
  43. * Indexes in the table.
  44. *
  45. * @var array
  46. */
  47. protected $_indexes = [];
  48. /**
  49. * Constraints in the table.
  50. *
  51. * @var array
  52. */
  53. protected $_constraints = [];
  54. /**
  55. * Options for the table.
  56. *
  57. * @var array
  58. */
  59. protected $_options = [];
  60. /**
  61. * Whether or not the table is temporary
  62. *
  63. * @var bool
  64. */
  65. protected $_temporary = false;
  66. /**
  67. * The valid keys that can be used in a column
  68. * definition.
  69. *
  70. * @var array
  71. */
  72. protected static $_columnKeys = [
  73. 'type' => null,
  74. 'length' => null,
  75. 'precision' => null,
  76. 'null' => null,
  77. 'default' => null,
  78. 'comment' => null,
  79. ];
  80. /**
  81. * Additional type specific properties.
  82. *
  83. * @var array
  84. */
  85. protected static $_columnExtras = [
  86. 'string' => [
  87. 'fixed' => null,
  88. ],
  89. 'integer' => [
  90. 'unsigned' => null,
  91. 'autoIncrement' => null,
  92. ],
  93. 'biginteger' => [
  94. 'unsigned' => null,
  95. 'autoIncrement' => null,
  96. ],
  97. 'decimal' => [
  98. 'unsigned' => null,
  99. ],
  100. 'float' => [
  101. 'unsigned' => null,
  102. ],
  103. ];
  104. /**
  105. * The valid keys that can be used in an index
  106. * definition.
  107. *
  108. * @var array
  109. */
  110. protected static $_indexKeys = [
  111. 'type' => null,
  112. 'columns' => [],
  113. 'length' => [],
  114. 'references' => [],
  115. 'update' => 'restrict',
  116. 'delete' => 'restrict',
  117. ];
  118. /**
  119. * Names of the valid index types.
  120. *
  121. * @var array
  122. */
  123. protected static $_validIndexTypes = [
  124. self::INDEX_INDEX,
  125. self::INDEX_FULLTEXT,
  126. ];
  127. /**
  128. * Names of the valid constraint types.
  129. *
  130. * @var array
  131. */
  132. protected static $_validConstraintTypes = [
  133. self::CONSTRAINT_PRIMARY,
  134. self::CONSTRAINT_UNIQUE,
  135. self::CONSTRAINT_FOREIGN,
  136. ];
  137. /**
  138. * Names of the valid foreign key actions.
  139. *
  140. * @var array
  141. */
  142. protected static $_validForeignKeyActions = [
  143. self::ACTION_CASCADE,
  144. self::ACTION_SET_NULL,
  145. self::ACTION_SET_DEFAULT,
  146. self::ACTION_NO_ACTION,
  147. self::ACTION_RESTRICT,
  148. ];
  149. /**
  150. * Primary constraint type
  151. *
  152. * @var string
  153. */
  154. const CONSTRAINT_PRIMARY = 'primary';
  155. /**
  156. * Unique constraint type
  157. *
  158. * @var string
  159. */
  160. const CONSTRAINT_UNIQUE = 'unique';
  161. /**
  162. * Foreign constraint type
  163. *
  164. * @var string
  165. */
  166. const CONSTRAINT_FOREIGN = 'foreign';
  167. /**
  168. * Index - index type
  169. *
  170. * @var string
  171. */
  172. const INDEX_INDEX = 'index';
  173. /**
  174. * Fulltext index type
  175. *
  176. * @var string
  177. */
  178. const INDEX_FULLTEXT = 'fulltext';
  179. /**
  180. * Foreign key cascade action
  181. *
  182. * @var string
  183. */
  184. const ACTION_CASCADE = 'cascade';
  185. /**
  186. * Foreign key set null action
  187. *
  188. * @var string
  189. */
  190. const ACTION_SET_NULL = 'setNull';
  191. /**
  192. * Foreign key no action
  193. *
  194. * @var string
  195. */
  196. const ACTION_NO_ACTION = 'noAction';
  197. /**
  198. * Foreign key restrict action
  199. *
  200. * @var string
  201. */
  202. const ACTION_RESTRICT = 'restrict';
  203. /**
  204. * Foreign key restrict default
  205. *
  206. * @var string
  207. */
  208. const ACTION_SET_DEFAULT = 'setDefault';
  209. /**
  210. * Constructor.
  211. *
  212. * @param string $table The table name.
  213. * @param array $columns The list of columns for the schema.
  214. */
  215. public function __construct($table, array $columns = array()) {
  216. $this->_table = $table;
  217. foreach ($columns as $field => $definition) {
  218. $this->addColumn($field, $definition);
  219. }
  220. }
  221. /**
  222. * Get the name of the table.
  223. *
  224. * @return string
  225. */
  226. public function name() {
  227. return $this->_table;
  228. }
  229. /**
  230. * Add a column to the table.
  231. *
  232. * ### Attributes
  233. *
  234. * Columns can have several attributes:
  235. *
  236. * - `type` The type of the column. This should be
  237. * one of CakePHP's abstract types.
  238. * - `length` The length of the column.
  239. * - `precision` The number of decimal places to store
  240. * for float and decimal types.
  241. * - `default` The default value of the column.
  242. * - `null` Whether or not the column can hold nulls.
  243. * - `fixed` Whether or not the column is a fixed length column.
  244. * This is only present/valid with string columns.
  245. * - `unsigned` Whether or not the column is an unsigned column.
  246. * This is only present/valid for integer, decimal, float columns.
  247. *
  248. * In addition to the above keys, the following keys are
  249. * implemented in some database dialects, but not all:
  250. *
  251. * - `comment` The comment for the column.
  252. *
  253. * @param string $name The name of the column
  254. * @param array $attrs The attributes for the column.
  255. * @return $this
  256. */
  257. public function addColumn($name, $attrs) {
  258. if (is_string($attrs)) {
  259. $attrs = ['type' => $attrs];
  260. }
  261. $valid = static::$_columnKeys;
  262. if (isset(static::$_columnExtras[$attrs['type']])) {
  263. $valid += static::$_columnExtras[$attrs['type']];
  264. }
  265. $attrs = array_intersect_key($attrs, $valid);
  266. $this->_columns[$name] = $attrs + $valid;
  267. return $this;
  268. }
  269. /**
  270. * Get the column names in the table.
  271. *
  272. * @return array
  273. */
  274. public function columns() {
  275. return array_keys($this->_columns);
  276. }
  277. /**
  278. * Get column data in the table.
  279. *
  280. * @param string $name The column name.
  281. * @return array|null Column data or null.
  282. */
  283. public function column($name) {
  284. if (!isset($this->_columns[$name])) {
  285. return null;
  286. }
  287. return $this->_columns[$name];
  288. }
  289. /**
  290. * Sets the type of a column, or returns its current type
  291. * if none is passed.
  292. *
  293. * @param string $name The column to get the type of.
  294. * @param string $type The type to set the column to.
  295. * @return string|null Either the column type or null.
  296. */
  297. public function columnType($name, $type = null) {
  298. if (!isset($this->_columns[$name])) {
  299. return null;
  300. }
  301. if ($type !== null) {
  302. $this->_columns[$name]['type'] = $type;
  303. }
  304. return $this->_columns[$name]['type'];
  305. }
  306. /**
  307. * Get a hash of columns and their default values.
  308. *
  309. * @return array
  310. */
  311. public function defaultValues() {
  312. $defaults = [];
  313. foreach ($this->_columns as $name => $data) {
  314. if (!array_key_exists('default', $data)) {
  315. continue;
  316. }
  317. if ($data['default'] === null && $data['null'] !== true) {
  318. continue;
  319. }
  320. $defaults[$name] = $data['default'];
  321. }
  322. return $defaults;
  323. }
  324. /**
  325. * Add an index.
  326. *
  327. * Used to add indexes, and full text indexes in platforms that support
  328. * them.
  329. *
  330. * ### Attributes
  331. *
  332. * - `type` The type of index being added.
  333. * - `columns` The columns in the index.
  334. *
  335. * @param string $name The name of the index.
  336. * @param array $attrs The attributes for the index.
  337. * @return $this
  338. * @throws \Cake\Database\Exception
  339. */
  340. public function addIndex($name, $attrs) {
  341. if (is_string($attrs)) {
  342. $attrs = ['type' => $attrs];
  343. }
  344. $attrs = array_intersect_key($attrs, static::$_indexKeys);
  345. $attrs = $attrs + static::$_indexKeys;
  346. unset($attrs['references'], $attrs['update'], $attrs['delete']);
  347. if (!in_array($attrs['type'], static::$_validIndexTypes, true)) {
  348. throw new Exception(sprintf('Invalid index type "%s"', $attrs['type']));
  349. }
  350. if (empty($attrs['columns'])) {
  351. throw new Exception('Indexes must have at least one column.');
  352. }
  353. $attrs['columns'] = (array)$attrs['columns'];
  354. foreach ($attrs['columns'] as $field) {
  355. if (empty($this->_columns[$field])) {
  356. $msg = sprintf(
  357. 'Columns used in indexes must be added to the Table schema first. ' .
  358. 'The column "%s" was not found.',
  359. $field
  360. );
  361. throw new Exception($msg);
  362. }
  363. }
  364. $this->_indexes[$name] = $attrs;
  365. return $this;
  366. }
  367. /**
  368. * Get the names of all the indexes in the table.
  369. *
  370. * @return array
  371. */
  372. public function indexes() {
  373. return array_keys($this->_indexes);
  374. }
  375. /**
  376. * Read information about an index based on name.
  377. *
  378. * @param string $name The name of the index.
  379. * @return array|null Array of index data, or null
  380. */
  381. public function index($name) {
  382. if (!isset($this->_indexes[$name])) {
  383. return null;
  384. }
  385. return $this->_indexes[$name];
  386. }
  387. /**
  388. * Get the column(s) used for the primary key.
  389. *
  390. * @return array Column name(s) for the primary key. An
  391. * empty list will be returned when the table has no primary key.
  392. */
  393. public function primaryKey() {
  394. foreach ($this->_constraints as $name => $data) {
  395. if ($data['type'] === static::CONSTRAINT_PRIMARY) {
  396. return $data['columns'];
  397. }
  398. }
  399. return [];
  400. }
  401. /**
  402. * Add a constraint.
  403. *
  404. * Used to add constraints to a table. For example primary keys, unique
  405. * keys and foreign keys.
  406. *
  407. * ### Attributes
  408. *
  409. * - `type` The type of constraint being added.
  410. * - `columns` The columns in the index.
  411. * - `references` The table, column a foreign key references.
  412. * - `update` The behavior on update. Options are 'restrict', 'setNull', 'cascade', 'noAction'.
  413. * - `delete` The behavior on delete. Options are 'restrict', 'setNull', 'cascade', 'noAction'.
  414. *
  415. * The default for 'update' & 'delete' is 'cascade'.
  416. *
  417. * @param string $name The name of the constraint.
  418. * @param array $attrs The attributes for the constraint.
  419. * @return $this
  420. * @throws \Cake\Database\Exception
  421. */
  422. public function addConstraint($name, $attrs) {
  423. if (is_string($attrs)) {
  424. $attrs = ['type' => $attrs];
  425. }
  426. $attrs = array_intersect_key($attrs, static::$_indexKeys);
  427. $attrs = $attrs + static::$_indexKeys;
  428. if (!in_array($attrs['type'], static::$_validConstraintTypes, true)) {
  429. throw new Exception(sprintf('Invalid constraint type "%s"', $attrs['type']));
  430. }
  431. if (empty($attrs['columns'])) {
  432. throw new Exception('Constraints must have at least one column.');
  433. }
  434. $attrs['columns'] = (array)$attrs['columns'];
  435. foreach ($attrs['columns'] as $field) {
  436. if (empty($this->_columns[$field])) {
  437. $msg = sprintf(
  438. 'Columns used in constraints must be added to the Table schema first. ' .
  439. 'The column "%s" was not found.',
  440. $field
  441. );
  442. throw new Exception($msg);
  443. }
  444. }
  445. if ($attrs['type'] === static::CONSTRAINT_FOREIGN) {
  446. $attrs = $this->_checkForeignKey($attrs);
  447. } else {
  448. unset($attrs['references'], $attrs['update'], $attrs['delete']);
  449. }
  450. $this->_constraints[$name] = $attrs;
  451. return $this;
  452. }
  453. /**
  454. * Helper method to check/validate foreign keys.
  455. *
  456. * @param array $attrs Attributes to set.
  457. * @return array
  458. * @throws \Cake\Database\Exception When foreign key definition is not valid.
  459. */
  460. protected function _checkForeignKey($attrs) {
  461. if (count($attrs['references']) < 2) {
  462. throw new Exception('References must contain a table and column.');
  463. }
  464. if (!in_array($attrs['update'], static::$_validForeignKeyActions)) {
  465. throw new Exception(sprintf('Update action is invalid. Must be one of %s', implode(',', static::$_validForeignKeyActions)));
  466. }
  467. if (!in_array($attrs['delete'], static::$_validForeignKeyActions)) {
  468. throw new Exception(sprintf('Delete action is invalid. Must be one of %s', implode(',', static::$_validForeignKeyActions)));
  469. }
  470. return $attrs;
  471. }
  472. /**
  473. * Get the names of all the constraints in the table.
  474. *
  475. * @return array
  476. */
  477. public function constraints() {
  478. return array_keys($this->_constraints);
  479. }
  480. /**
  481. * Read information about a constraint based on name.
  482. *
  483. * @param string $name The name of the constraint.
  484. * @return array|null Array of constraint data, or null
  485. */
  486. public function constraint($name) {
  487. if (!isset($this->_constraints[$name])) {
  488. return null;
  489. }
  490. return $this->_constraints[$name];
  491. }
  492. /**
  493. * Get/set the options for a table.
  494. *
  495. * Table options allow you to set platform specific table level options.
  496. * For example the engine type in MySQL.
  497. *
  498. * @param array|null $options The options to set, or null to read options.
  499. * @return $this|array Either the table instance, or an array of options when reading.
  500. */
  501. public function options($options = null) {
  502. if ($options === null) {
  503. return $this->_options;
  504. }
  505. $this->_options = array_merge($this->_options, $options);
  506. return $this;
  507. }
  508. /**
  509. * Get/Set whether the table is temporary in the database
  510. *
  511. * @param bool|null $set whether or not the table is to be temporary
  512. * @return $this|bool Either the table instance, the current temporary setting
  513. */
  514. public function temporary($set = null) {
  515. if ($set === null) {
  516. return $this->_temporary;
  517. }
  518. $this->_temporary = (bool)$set;
  519. return $this;
  520. }
  521. /**
  522. * Generate the SQL to create the Table.
  523. *
  524. * Uses the connection to access the schema dialect
  525. * to generate platform specific SQL.
  526. *
  527. * @param Connection $connection The connection to generate SQL for
  528. * @return array List of SQL statements to create the table and the
  529. * required indexes.
  530. */
  531. public function createSql(Connection $connection) {
  532. $dialect = $connection->driver()->schemaDialect();
  533. $columns = $constraints = $indexes = [];
  534. foreach (array_keys($this->_columns) as $name) {
  535. $columns[] = $dialect->columnSql($this, $name);
  536. }
  537. foreach (array_keys($this->_constraints) as $name) {
  538. $constraints[] = $dialect->constraintSql($this, $name);
  539. }
  540. foreach (array_keys($this->_indexes) as $name) {
  541. $indexes[] = $dialect->indexSql($this, $name);
  542. }
  543. return $dialect->createTableSql($this, $columns, $constraints, $indexes);
  544. }
  545. /**
  546. * Generate the SQL to drop a table.
  547. *
  548. * Uses the connection to access the schema dialect to generate platform
  549. * specific SQL.
  550. *
  551. * @param Connection $connection The connection to generate SQL for.
  552. * @return array SQL to drop a table.
  553. */
  554. public function dropSql(Connection $connection) {
  555. $dialect = $connection->driver()->schemaDialect();
  556. return $dialect->dropTableSql($this);
  557. }
  558. /**
  559. * Generate the SQL statements to truncate a table
  560. *
  561. * @param Connection $connection The connection to generate SQL for.
  562. * @return array SQL to drop a table.
  563. */
  564. public function truncateSql(Connection $connection) {
  565. $dialect = $connection->driver()->schemaDialect();
  566. return $dialect->truncateTableSql($this);
  567. }
  568. }