TableSchema.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  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. use Cake\Database\Type;
  19. /**
  20. * Represents a single table in a database schema.
  21. *
  22. * Can either be populated using the reflection API's
  23. * or by incrementally building an instance using
  24. * methods.
  25. *
  26. * Once created TableSchema instances can be added to
  27. * Schema\Collection objects. They can also be converted into SQL using the
  28. * createSql(), dropSql() and truncateSql() methods.
  29. */
  30. class TableSchema implements TableSchemaInterface, SqlGeneratorInterface
  31. {
  32. /**
  33. * The name of the table
  34. *
  35. * @var string
  36. */
  37. protected $_table;
  38. /**
  39. * Columns in the table.
  40. *
  41. * @var array
  42. */
  43. protected $_columns = [];
  44. /**
  45. * A map with columns to types
  46. *
  47. * @var array
  48. */
  49. protected $_typeMap = [];
  50. /**
  51. * Indexes in the table.
  52. *
  53. * @var array
  54. */
  55. protected $_indexes = [];
  56. /**
  57. * Constraints in the table.
  58. *
  59. * @var array
  60. */
  61. protected $_constraints = [];
  62. /**
  63. * Options for the table.
  64. *
  65. * @var array
  66. */
  67. protected $_options = [];
  68. /**
  69. * Whether or not the table is temporary
  70. *
  71. * @var bool
  72. */
  73. protected $_temporary = false;
  74. /**
  75. * Column length when using a `tiny` column type
  76. *
  77. * @var int
  78. */
  79. const LENGTH_TINY = 255;
  80. /**
  81. * Column length when using a `medium` column type
  82. *
  83. * @var int
  84. */
  85. const LENGTH_MEDIUM = 16777215;
  86. /**
  87. * Column length when using a `long` column type
  88. *
  89. * @var int
  90. */
  91. const LENGTH_LONG = 4294967295;
  92. /**
  93. * Valid column length that can be used with text type columns
  94. *
  95. * @var array
  96. */
  97. public static $columnLengths = [
  98. 'tiny' => self::LENGTH_TINY,
  99. 'medium' => self::LENGTH_MEDIUM,
  100. 'long' => self::LENGTH_LONG
  101. ];
  102. /**
  103. * The valid keys that can be used in a column
  104. * definition.
  105. *
  106. * @var array
  107. */
  108. protected static $_columnKeys = [
  109. 'type' => null,
  110. 'baseType' => null,
  111. 'length' => null,
  112. 'precision' => null,
  113. 'null' => null,
  114. 'default' => null,
  115. 'comment' => null,
  116. ];
  117. /**
  118. * Additional type specific properties.
  119. *
  120. * @var array
  121. */
  122. protected static $_columnExtras = [
  123. 'string' => [
  124. 'fixed' => null,
  125. 'collate' => null,
  126. ],
  127. 'text' => [
  128. 'collate' => null,
  129. ],
  130. 'tinyinteger' => [
  131. 'unsigned' => null,
  132. ],
  133. 'smallinteger' => [
  134. 'unsigned' => null,
  135. ],
  136. 'integer' => [
  137. 'unsigned' => null,
  138. 'autoIncrement' => null,
  139. ],
  140. 'biginteger' => [
  141. 'unsigned' => null,
  142. 'autoIncrement' => null,
  143. ],
  144. 'decimal' => [
  145. 'unsigned' => null,
  146. ],
  147. 'float' => [
  148. 'unsigned' => null,
  149. ],
  150. ];
  151. /**
  152. * The valid keys that can be used in an index
  153. * definition.
  154. *
  155. * @var array
  156. */
  157. protected static $_indexKeys = [
  158. 'type' => null,
  159. 'columns' => [],
  160. 'length' => [],
  161. 'references' => [],
  162. 'update' => 'restrict',
  163. 'delete' => 'restrict',
  164. ];
  165. /**
  166. * Names of the valid index types.
  167. *
  168. * @var array
  169. */
  170. protected static $_validIndexTypes = [
  171. self::INDEX_INDEX,
  172. self::INDEX_FULLTEXT,
  173. ];
  174. /**
  175. * Names of the valid constraint types.
  176. *
  177. * @var array
  178. */
  179. protected static $_validConstraintTypes = [
  180. self::CONSTRAINT_PRIMARY,
  181. self::CONSTRAINT_UNIQUE,
  182. self::CONSTRAINT_FOREIGN,
  183. ];
  184. /**
  185. * Names of the valid foreign key actions.
  186. *
  187. * @var array
  188. */
  189. protected static $_validForeignKeyActions = [
  190. self::ACTION_CASCADE,
  191. self::ACTION_SET_NULL,
  192. self::ACTION_SET_DEFAULT,
  193. self::ACTION_NO_ACTION,
  194. self::ACTION_RESTRICT,
  195. ];
  196. /**
  197. * Primary constraint type
  198. *
  199. * @var string
  200. */
  201. const CONSTRAINT_PRIMARY = 'primary';
  202. /**
  203. * Unique constraint type
  204. *
  205. * @var string
  206. */
  207. const CONSTRAINT_UNIQUE = 'unique';
  208. /**
  209. * Foreign constraint type
  210. *
  211. * @var string
  212. */
  213. const CONSTRAINT_FOREIGN = 'foreign';
  214. /**
  215. * Index - index type
  216. *
  217. * @var string
  218. */
  219. const INDEX_INDEX = 'index';
  220. /**
  221. * Fulltext index type
  222. *
  223. * @var string
  224. */
  225. const INDEX_FULLTEXT = 'fulltext';
  226. /**
  227. * Foreign key cascade action
  228. *
  229. * @var string
  230. */
  231. const ACTION_CASCADE = 'cascade';
  232. /**
  233. * Foreign key set null action
  234. *
  235. * @var string
  236. */
  237. const ACTION_SET_NULL = 'setNull';
  238. /**
  239. * Foreign key no action
  240. *
  241. * @var string
  242. */
  243. const ACTION_NO_ACTION = 'noAction';
  244. /**
  245. * Foreign key restrict action
  246. *
  247. * @var string
  248. */
  249. const ACTION_RESTRICT = 'restrict';
  250. /**
  251. * Foreign key restrict default
  252. *
  253. * @var string
  254. */
  255. const ACTION_SET_DEFAULT = 'setDefault';
  256. /**
  257. * Constructor.
  258. *
  259. * @param string $table The table name.
  260. * @param array $columns The list of columns for the schema.
  261. */
  262. public function __construct($table, array $columns = [])
  263. {
  264. $this->_table = $table;
  265. foreach ($columns as $field => $definition) {
  266. $this->addColumn($field, $definition);
  267. }
  268. }
  269. /**
  270. * {@inheritDoc}
  271. */
  272. public function name()
  273. {
  274. return $this->_table;
  275. }
  276. /**
  277. * {@inheritDoc}
  278. */
  279. public function addColumn($name, $attrs)
  280. {
  281. if (is_string($attrs)) {
  282. $attrs = ['type' => $attrs];
  283. }
  284. $valid = static::$_columnKeys;
  285. if (isset(static::$_columnExtras[$attrs['type']])) {
  286. $valid += static::$_columnExtras[$attrs['type']];
  287. }
  288. $attrs = array_intersect_key($attrs, $valid);
  289. $this->_columns[$name] = $attrs + $valid;
  290. $this->_typeMap[$name] = $this->_columns[$name]['type'];
  291. return $this;
  292. }
  293. /**
  294. * {@inheritDoc}
  295. */
  296. public function removeColumn($name)
  297. {
  298. unset($this->_columns[$name], $this->_typeMap[$name]);
  299. return $this;
  300. }
  301. /**
  302. * {@inheritDoc}
  303. */
  304. public function columns()
  305. {
  306. return array_keys($this->_columns);
  307. }
  308. /**
  309. * Get column data in the table.
  310. *
  311. * @param string $name The column name.
  312. * @return array|null Column data or null.
  313. * @deprecated 3.5.0 Use getColumn() instead.
  314. */
  315. public function column($name)
  316. {
  317. return $this->getColumn($name);
  318. }
  319. /**
  320. * {@inheritDoc}
  321. */
  322. public function getColumn($name)
  323. {
  324. if (!isset($this->_columns[$name])) {
  325. return null;
  326. }
  327. $column = $this->_columns[$name];
  328. unset($column['baseType']);
  329. return $column;
  330. }
  331. /**
  332. * Sets the type of a column, or returns its current type
  333. * if none is passed.
  334. *
  335. * @param string $name The column to get the type of.
  336. * @param string|null $type The type to set the column to.
  337. * @return string|null Either the column type or null.
  338. * @deprecated 3.5.0 Use setColumnType()/getColumnType() instead.
  339. */
  340. public function columnType($name, $type = null)
  341. {
  342. if ($type !== null) {
  343. $this->setColumnType($name, $type);
  344. }
  345. return $this->getColumnType($name);
  346. }
  347. /**
  348. * {@inheritDoc}
  349. */
  350. public function getColumnType($name)
  351. {
  352. if (!isset($this->_columns[$name])) {
  353. return null;
  354. }
  355. return $this->_columns[$name]['type'];
  356. }
  357. /**
  358. * {@inheritDoc}
  359. */
  360. public function setColumnType($name, $type)
  361. {
  362. if (!isset($this->_columns[$name])) {
  363. return $this;
  364. }
  365. $this->_columns[$name]['type'] = $type;
  366. $this->_typeMap[$name] = $type;
  367. return $this;
  368. }
  369. /**
  370. * {@inheritDoc}
  371. */
  372. public function hasColumn($name)
  373. {
  374. return isset($this->_columns[$name]);
  375. }
  376. /**
  377. * {@inheritDoc}
  378. */
  379. public function baseColumnType($column)
  380. {
  381. if (isset($this->_columns[$column]['baseType'])) {
  382. return $this->_columns[$column]['baseType'];
  383. }
  384. $type = $this->columnType($column);
  385. if ($type === null) {
  386. return null;
  387. }
  388. if (Type::map($type)) {
  389. $type = Type::build($type)->getBaseType();
  390. }
  391. return $this->_columns[$column]['baseType'] = $type;
  392. }
  393. /**
  394. * {@inheritDoc}
  395. */
  396. public function typeMap()
  397. {
  398. return $this->_typeMap;
  399. }
  400. /**
  401. * {@inheritDoc}
  402. */
  403. public function isNullable($name)
  404. {
  405. if (!isset($this->_columns[$name])) {
  406. return true;
  407. }
  408. return ($this->_columns[$name]['null'] === true);
  409. }
  410. /**
  411. * {@inheritDoc}
  412. */
  413. public function defaultValues()
  414. {
  415. $defaults = [];
  416. foreach ($this->_columns as $name => $data) {
  417. if (!array_key_exists('default', $data)) {
  418. continue;
  419. }
  420. if ($data['default'] === null && $data['null'] !== true) {
  421. continue;
  422. }
  423. $defaults[$name] = $data['default'];
  424. }
  425. return $defaults;
  426. }
  427. /**
  428. * {@inheritDoc}
  429. * @throws \Cake\Database\Exception
  430. */
  431. public function addIndex($name, $attrs)
  432. {
  433. if (is_string($attrs)) {
  434. $attrs = ['type' => $attrs];
  435. }
  436. $attrs = array_intersect_key($attrs, static::$_indexKeys);
  437. $attrs += static::$_indexKeys;
  438. unset($attrs['references'], $attrs['update'], $attrs['delete']);
  439. if (!in_array($attrs['type'], static::$_validIndexTypes, true)) {
  440. throw new Exception(sprintf('Invalid index type "%s" in index "%s" in table "%s".', $attrs['type'], $name, $this->_table));
  441. }
  442. if (empty($attrs['columns'])) {
  443. throw new Exception(sprintf('Index "%s" in table "%s" must have at least one column.', $name, $this->_table));
  444. }
  445. $attrs['columns'] = (array)$attrs['columns'];
  446. foreach ($attrs['columns'] as $field) {
  447. if (empty($this->_columns[$field])) {
  448. $msg = sprintf(
  449. 'Columns used in index "%s" in table "%s" must be added to the Table schema first. ' .
  450. 'The column "%s" was not found.',
  451. $name,
  452. $this->_table,
  453. $field
  454. );
  455. throw new Exception($msg);
  456. }
  457. }
  458. $this->_indexes[$name] = $attrs;
  459. return $this;
  460. }
  461. /**
  462. * {@inheritDoc}
  463. */
  464. public function indexes()
  465. {
  466. return array_keys($this->_indexes);
  467. }
  468. /**
  469. * Read information about an index based on name.
  470. *
  471. * @param string $name The name of the index.
  472. * @return array|null Array of index data, or null
  473. * @deprecated 3.5.0 Use getIndex() instead.
  474. */
  475. public function index($name)
  476. {
  477. return $this->getIndex($name);
  478. }
  479. /**
  480. * {@inheritDoc}
  481. */
  482. public function getIndex($name)
  483. {
  484. if (!isset($this->_indexes[$name])) {
  485. return null;
  486. }
  487. return $this->_indexes[$name];
  488. }
  489. /**
  490. * {@inheritDoc}
  491. */
  492. public function primaryKey()
  493. {
  494. foreach ($this->_constraints as $name => $data) {
  495. if ($data['type'] === static::CONSTRAINT_PRIMARY) {
  496. return $data['columns'];
  497. }
  498. }
  499. return [];
  500. }
  501. /**
  502. * {@inheritDoc}
  503. * @throws \Cake\Database\Exception
  504. */
  505. public function addConstraint($name, $attrs)
  506. {
  507. if (is_string($attrs)) {
  508. $attrs = ['type' => $attrs];
  509. }
  510. $attrs = array_intersect_key($attrs, static::$_indexKeys);
  511. $attrs += static::$_indexKeys;
  512. if (!in_array($attrs['type'], static::$_validConstraintTypes, true)) {
  513. throw new Exception(sprintf('Invalid constraint type "%s" in table "%s".', $attrs['type'], $this->_table));
  514. }
  515. if (empty($attrs['columns'])) {
  516. throw new Exception(sprintf('Constraints in table "%s" must have at least one column.', $this->_table));
  517. }
  518. $attrs['columns'] = (array)$attrs['columns'];
  519. foreach ($attrs['columns'] as $field) {
  520. if (empty($this->_columns[$field])) {
  521. $msg = sprintf(
  522. 'Columns used in constraints must be added to the Table schema first. ' .
  523. 'The column "%s" was not found in table "%s".',
  524. $field,
  525. $this->_table
  526. );
  527. throw new Exception($msg);
  528. }
  529. }
  530. if ($attrs['type'] === static::CONSTRAINT_FOREIGN) {
  531. $attrs = $this->_checkForeignKey($attrs);
  532. if (isset($this->_constraints[$name])) {
  533. $this->_constraints[$name]['columns'] = array_unique(array_merge(
  534. $this->_constraints[$name]['columns'],
  535. $attrs['columns']
  536. ));
  537. if (isset($this->_constraints[$name]['references'])) {
  538. $this->_constraints[$name]['references'][1] = array_unique(array_merge(
  539. (array)$this->_constraints[$name]['references'][1],
  540. [$attrs['references'][1]]
  541. ));
  542. }
  543. return $this;
  544. }
  545. } else {
  546. unset($attrs['references'], $attrs['update'], $attrs['delete']);
  547. }
  548. $this->_constraints[$name] = $attrs;
  549. return $this;
  550. }
  551. /**
  552. * {@inheritDoc}
  553. */
  554. public function dropConstraint($name)
  555. {
  556. if (isset($this->_constraints[$name])) {
  557. unset($this->_constraints[$name]);
  558. }
  559. return $this;
  560. }
  561. /**
  562. * Check whether or not a table has an autoIncrement column defined.
  563. *
  564. * @return bool
  565. */
  566. public function hasAutoincrement()
  567. {
  568. foreach ($this->_columns as $column) {
  569. if (isset($column['autoIncrement']) && $column['autoIncrement']) {
  570. return true;
  571. }
  572. }
  573. return false;
  574. }
  575. /**
  576. * Helper method to check/validate foreign keys.
  577. *
  578. * @param array $attrs Attributes to set.
  579. * @return array
  580. * @throws \Cake\Database\Exception When foreign key definition is not valid.
  581. */
  582. protected function _checkForeignKey($attrs)
  583. {
  584. if (count($attrs['references']) < 2) {
  585. throw new Exception('References must contain a table and column.');
  586. }
  587. if (!in_array($attrs['update'], static::$_validForeignKeyActions)) {
  588. throw new Exception(sprintf('Update action is invalid. Must be one of %s', implode(',', static::$_validForeignKeyActions)));
  589. }
  590. if (!in_array($attrs['delete'], static::$_validForeignKeyActions)) {
  591. throw new Exception(sprintf('Delete action is invalid. Must be one of %s', implode(',', static::$_validForeignKeyActions)));
  592. }
  593. return $attrs;
  594. }
  595. /**
  596. * {@inheritDoc}
  597. */
  598. public function constraints()
  599. {
  600. return array_keys($this->_constraints);
  601. }
  602. /**
  603. * Read information about a constraint based on name.
  604. *
  605. * @param string $name The name of the constraint.
  606. * @return array|null Array of constraint data, or null
  607. * @deprecated 3.5.0 Use getConstraint() instead.
  608. */
  609. public function constraint($name)
  610. {
  611. return $this->getConstraint($name);
  612. }
  613. /**
  614. * {@inheritDoc}
  615. */
  616. public function getConstraint($name)
  617. {
  618. if (!isset($this->_constraints[$name])) {
  619. return null;
  620. }
  621. return $this->_constraints[$name];
  622. }
  623. /**
  624. * {@inheritDoc}
  625. */
  626. public function setOptions($options)
  627. {
  628. $this->_options = array_merge($this->_options, $options);
  629. return $this;
  630. }
  631. /**
  632. * {@inheritDoc}
  633. */
  634. public function getOptions()
  635. {
  636. return $this->_options;
  637. }
  638. /**
  639. * Get/set the options for a table.
  640. *
  641. * Table options allow you to set platform specific table level options.
  642. * For example the engine type in MySQL.
  643. *
  644. * @deprecated 3.4.0 Use setOptions()/getOptions() instead.
  645. * @param array|null $options The options to set, or null to read options.
  646. * @return $this|array Either the TableSchema instance, or an array of options when reading.
  647. */
  648. public function options($options = null)
  649. {
  650. if ($options !== null) {
  651. return $this->setOptions($options);
  652. }
  653. return $this->getOptions();
  654. }
  655. /**
  656. * {@inheritDoc}
  657. */
  658. public function setTemporary($temporary)
  659. {
  660. $this->_temporary = (bool)$temporary;
  661. return $this;
  662. }
  663. /**
  664. * {@inheritDoc}
  665. */
  666. public function isTemporary()
  667. {
  668. return $this->_temporary;
  669. }
  670. /**
  671. * Get/Set whether the table is temporary in the database
  672. *
  673. * @deprecated 3.4.0 Use setTemporary()/isTemporary() instead.
  674. * @param bool|null $temporary whether or not the table is to be temporary
  675. * @return $this|bool Either the TableSchema instance, the current temporary setting
  676. */
  677. public function temporary($temporary = null)
  678. {
  679. if ($temporary !== null) {
  680. return $this->setTemporary($temporary);
  681. }
  682. return $this->isTemporary();
  683. }
  684. /**
  685. * {@inheritDoc}
  686. */
  687. public function createSql(Connection $connection)
  688. {
  689. $dialect = $connection->driver()->schemaDialect();
  690. $columns = $constraints = $indexes = [];
  691. foreach (array_keys($this->_columns) as $name) {
  692. $columns[] = $dialect->columnSql($this, $name);
  693. }
  694. foreach (array_keys($this->_constraints) as $name) {
  695. $constraints[] = $dialect->constraintSql($this, $name);
  696. }
  697. foreach (array_keys($this->_indexes) as $name) {
  698. $indexes[] = $dialect->indexSql($this, $name);
  699. }
  700. return $dialect->createTableSql($this, $columns, $constraints, $indexes);
  701. }
  702. /**
  703. * {@inheritDoc}
  704. */
  705. public function dropSql(Connection $connection)
  706. {
  707. $dialect = $connection->driver()->schemaDialect();
  708. return $dialect->dropTableSql($this);
  709. }
  710. /**
  711. * {@inheritDoc}
  712. */
  713. public function truncateSql(Connection $connection)
  714. {
  715. $dialect = $connection->driver()->schemaDialect();
  716. return $dialect->truncateTableSql($this);
  717. }
  718. /**
  719. * {@inheritDoc}
  720. */
  721. public function addConstraintSql(Connection $connection)
  722. {
  723. $dialect = $connection->driver()->schemaDialect();
  724. return $dialect->addConstraintSql($this);
  725. }
  726. /**
  727. * {@inheritDoc}
  728. */
  729. public function dropConstraintSql(Connection $connection)
  730. {
  731. $dialect = $connection->driver()->schemaDialect();
  732. return $dialect->dropConstraintSql($this);
  733. }
  734. }
  735. // @deprecated Add backwards compat alias.
  736. class_alias('Cake\Database\Schema\TableSchema', 'Cake\Database\Schema\Table');