Table.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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 MIT License (http://www.opensource.org/licenses/mit-license.php)
  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 boolean
  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_NO_ACTION,
  146. self::ACTION_RESTRICT,
  147. ];
  148. /**
  149. * Primary constraint type
  150. *
  151. * @var string
  152. */
  153. const CONSTRAINT_PRIMARY = 'primary';
  154. /**
  155. * Unique constraint type
  156. *
  157. * @var string
  158. */
  159. const CONSTRAINT_UNIQUE = 'unique';
  160. /**
  161. * Foreign constraint type
  162. *
  163. * @var string
  164. */
  165. const CONSTRAINT_FOREIGN = 'foreign';
  166. /**
  167. * Index - index type
  168. *
  169. * @var string
  170. */
  171. const INDEX_INDEX = 'index';
  172. /**
  173. * Fulltext index type
  174. *
  175. * @var string
  176. */
  177. const INDEX_FULLTEXT = 'fulltext';
  178. /**
  179. * Foreign key cascade action
  180. *
  181. * @var string
  182. */
  183. const ACTION_CASCADE = 'cascade';
  184. /**
  185. * Foreign key set null action
  186. *
  187. * @var string
  188. */
  189. const ACTION_SET_NULL = 'setNull';
  190. /**
  191. * Foreign key no action
  192. *
  193. * @var string
  194. */
  195. const ACTION_NO_ACTION = 'noAction';
  196. /**
  197. * Foreign key restrict action
  198. *
  199. * @var string
  200. */
  201. const ACTION_RESTRICT = 'restrict';
  202. /**
  203. * Constructor.
  204. *
  205. * @param string $table The table name.
  206. * @param array $columns The list of columns for the schema.
  207. */
  208. public function __construct($table, $columns = array()) {
  209. $this->_table = $table;
  210. foreach ($columns as $field => $definition) {
  211. $this->addColumn($field, $definition);
  212. }
  213. }
  214. /**
  215. * Get the name of the table.
  216. *
  217. * @return string
  218. */
  219. public function name() {
  220. return $this->_table;
  221. }
  222. /**
  223. * Add a column to the table.
  224. *
  225. * ### Attributes
  226. *
  227. * Columns can have several attributes:
  228. *
  229. * - `type` The type of the column. This should be
  230. * one of CakePHP's abstract types.
  231. * - `length` The length of the column.
  232. * - `precision` The number of decimal places to store
  233. * for float and decimal types.
  234. * - `default` The default value of the column.
  235. * - `null` Whether or not the column can hold nulls.
  236. * - `fixed` Whether or not the column is a fixed length column.
  237. * This is only present/valid with string columns.
  238. * - `unsigned` Whether or not the column is an unsigned column.
  239. * This is only present/valid for integer, decimal, float columns.
  240. *
  241. * In addition to the above keys, the following keys are
  242. * implemented in some database dialects, but not all:
  243. *
  244. * - `comment` The comment for the column.
  245. *
  246. * @param string $name The name of the column
  247. * @param array $attrs The attributes for the column.
  248. * @return Table $this
  249. */
  250. public function addColumn($name, $attrs) {
  251. if (is_string($attrs)) {
  252. $attrs = ['type' => $attrs];
  253. }
  254. $valid = static::$_columnKeys;
  255. if (isset(static::$_columnExtras[$attrs['type']])) {
  256. $valid += static::$_columnExtras[$attrs['type']];
  257. }
  258. $attrs = array_intersect_key($attrs, $valid);
  259. $this->_columns[$name] = $attrs + $valid;
  260. return $this;
  261. }
  262. /**
  263. * Get the column names in the table.
  264. *
  265. * @return array
  266. */
  267. public function columns() {
  268. return array_keys($this->_columns);
  269. }
  270. /**
  271. * Get column data in the table.
  272. *
  273. * @param string $name The column name.
  274. * @return array|null Column data or null.
  275. */
  276. public function column($name) {
  277. if (!isset($this->_columns[$name])) {
  278. return null;
  279. }
  280. return $this->_columns[$name];
  281. }
  282. /**
  283. * Convenience method for getting the type of a given column.
  284. *
  285. * @param string $name The column to get the type of.
  286. * @return string|null Either the column type or null.
  287. */
  288. public function columnType($name) {
  289. if (!isset($this->_columns[$name])) {
  290. return null;
  291. }
  292. return $this->_columns[$name]['type'];
  293. }
  294. /**
  295. * Add an index.
  296. *
  297. * Used to add indexes, and full text indexes in platforms that support
  298. * them.
  299. *
  300. * ### Attributes
  301. *
  302. * - `type` The type of index being added.
  303. * - `columns` The columns in the index.
  304. *
  305. * @param string $name The name of the index.
  306. * @param array $attrs The attributes for the index.
  307. * @return Table $this
  308. * @throws \Cake\Database\Exception
  309. */
  310. public function addIndex($name, $attrs) {
  311. if (is_string($attrs)) {
  312. $attrs = ['type' => $attrs];
  313. }
  314. $attrs = array_intersect_key($attrs, static::$_indexKeys);
  315. $attrs = $attrs + static::$_indexKeys;
  316. unset($attrs['references'], $attrs['update'], $attrs['delete']);
  317. if (!in_array($attrs['type'], static::$_validIndexTypes, true)) {
  318. throw new Exception(sprintf('Invalid index type "%s"', $attrs['type']));
  319. }
  320. if (empty($attrs['columns'])) {
  321. throw new Exception('Indexes must define columns.');
  322. }
  323. $attrs['columns'] = (array)$attrs['columns'];
  324. foreach ($attrs['columns'] as $field) {
  325. if (empty($this->_columns[$field])) {
  326. throw new Exception('Columns used in indexes must already exist.');
  327. }
  328. }
  329. $this->_indexes[$name] = $attrs;
  330. return $this;
  331. }
  332. /**
  333. * Get the names of all the indexes in the table.
  334. *
  335. * @return array
  336. */
  337. public function indexes() {
  338. return array_keys($this->_indexes);
  339. }
  340. /**
  341. * Read information about an index based on name.
  342. *
  343. * @param string $name The name of the index.
  344. * @return array|null Array of index data, or null
  345. */
  346. public function index($name) {
  347. if (!isset($this->_indexes[$name])) {
  348. return null;
  349. }
  350. return $this->_indexes[$name];
  351. }
  352. /**
  353. * Get the column(s) used for the primary key.
  354. *
  355. * @return array|null Column name(s) for the primary key.
  356. * Null will be returned if a table has no primary key.
  357. */
  358. public function primaryKey() {
  359. foreach ($this->_constraints as $name => $data) {
  360. if ($data['type'] === static::CONSTRAINT_PRIMARY) {
  361. return $data['columns'];
  362. }
  363. }
  364. return null;
  365. }
  366. /**
  367. * Add a constraint.
  368. *
  369. * Used to add constraints to a table. For example primary keys, unique
  370. * keys and foriegn keys.
  371. *
  372. * ### Attributes
  373. *
  374. * - `type` The type of constraint being added.
  375. * - `columns` The columns in the index.
  376. * - `references` The table, column a foreign key references.
  377. * - `update` The behavior on update. Options are 'restrict', 'setNull', 'cascade', 'noAction'.
  378. * - `delete` The behavior on delete. Options are 'restrict', 'setNull', 'cascade', 'noAction'.
  379. *
  380. * The default for 'update' & 'delete' is 'cascade'.
  381. *
  382. * @param string $name The name of the constraint.
  383. * @param array $attrs The attributes for the constraint.
  384. * @return Table $this
  385. * @throws \Cake\Database\Exception
  386. */
  387. public function addConstraint($name, $attrs) {
  388. if (is_string($attrs)) {
  389. $attrs = ['type' => $attrs];
  390. }
  391. $attrs = array_intersect_key($attrs, static::$_indexKeys);
  392. $attrs = $attrs + static::$_indexKeys;
  393. if (!in_array($attrs['type'], static::$_validConstraintTypes, true)) {
  394. throw new Exception(sprintf('Invalid constraint type "%s"', $attrs['type']));
  395. }
  396. if (empty($attrs['columns'])) {
  397. throw new Exception('Constraints must define columns.');
  398. }
  399. $attrs['columns'] = (array)$attrs['columns'];
  400. foreach ($attrs['columns'] as $field) {
  401. if (empty($this->_columns[$field])) {
  402. throw new Exception('Columns used in constraints must already exist.');
  403. }
  404. }
  405. if ($attrs['type'] === static::CONSTRAINT_FOREIGN) {
  406. $attrs = $this->_checkForeignKey($attrs);
  407. } else {
  408. unset($attrs['references'], $attrs['update'], $attrs['delete']);
  409. }
  410. $this->_constraints[$name] = $attrs;
  411. return $this;
  412. }
  413. /**
  414. * Helper method to check/validate foreign keys.
  415. *
  416. * @param array $attrs Attributes to set.
  417. * @return array
  418. * @throws \Cake\Database\Exception When foreign key definition is not valid.
  419. */
  420. protected function _checkForeignKey($attrs) {
  421. if (count($attrs['references']) < 2) {
  422. throw new Exception('References must contain a table and column.');
  423. }
  424. if (!in_array($attrs['update'], static::$_validForeignKeyActions)) {
  425. throw new Exception(sprintf('Update action is invalid. Must be one of %s', implode(',', static::$_validForeignKeyActions)));
  426. }
  427. if (!in_array($attrs['delete'], static::$_validForeignKeyActions)) {
  428. throw new Exception(sprintf('Delete action is invalid. Must be one of %s', implode(',', static::$_validForeignKeyActions)));
  429. }
  430. return $attrs;
  431. }
  432. /**
  433. * Get the names of all the constraints in the table.
  434. *
  435. * @return array
  436. */
  437. public function constraints() {
  438. return array_keys($this->_constraints);
  439. }
  440. /**
  441. * Read information about an constraint based on name.
  442. *
  443. * @param string $name The name of the constraint.
  444. * @return array|null Array of constraint data, or null
  445. */
  446. public function constraint($name) {
  447. if (!isset($this->_constraints[$name])) {
  448. return null;
  449. }
  450. return $this->_constraints[$name];
  451. }
  452. /**
  453. * Get/set the options for a table.
  454. *
  455. * Table options allow you to set platform specific table level options.
  456. * For example the engine type in MySQL.
  457. *
  458. * @param array|null $options The options to set, or null to read options.
  459. * @return this|array Either the table instance, or an array of options when reading.
  460. */
  461. public function options($options = null) {
  462. if ($options === null) {
  463. return $this->_options;
  464. }
  465. $this->_options = array_merge($this->_options, $options);
  466. return $this;
  467. }
  468. /**
  469. * Get/Set whether the table is temporary in the database
  470. *
  471. * @param boolean|null $set whether or not the table is to be temporary
  472. * @return this|boolean Either the table instance, the current temporary setting
  473. */
  474. public function temporary($set = null) {
  475. if ($set === null) {
  476. return $this->_temporary;
  477. }
  478. $this->_temporary = (bool)$set;
  479. return $this;
  480. }
  481. /**
  482. * Generate the SQL to create the Table.
  483. *
  484. * Uses the connection to access the schema dialect
  485. * to generate platform specific SQL.
  486. *
  487. * @param Connection $connection The connection to generate SQL for
  488. * @return array List of SQL statements to create the table and the
  489. * required indexes.
  490. */
  491. public function createSql(Connection $connection) {
  492. $dialect = $connection->driver()->schemaDialect();
  493. $columns = $constraints = $indexes = [];
  494. foreach (array_keys($this->_columns) as $name) {
  495. $columns[] = $dialect->columnSql($this, $name);
  496. }
  497. foreach (array_keys($this->_constraints) as $name) {
  498. $constraints[] = $dialect->constraintSql($this, $name);
  499. }
  500. foreach (array_keys($this->_indexes) as $name) {
  501. $indexes[] = $dialect->indexSql($this, $name);
  502. }
  503. return $dialect->createTableSql($this, $columns, $constraints, $indexes);
  504. }
  505. /**
  506. * Generate the SQL to drop a table.
  507. *
  508. * Uses the connection to access the schema dialect to generate platform
  509. * specific SQL.
  510. *
  511. * @param Connection $connection The connection to generate SQL for.
  512. * @return array SQL to drop a table.
  513. */
  514. public function dropSql(Connection $connection) {
  515. $dialect = $connection->driver()->schemaDialect();
  516. return $dialect->dropTableSql($this);
  517. }
  518. /**
  519. * Generate the SQL statements to truncate a table
  520. *
  521. * @param Connection $connection The connection to generate SQL for.
  522. * @return array SQL to drop a table.
  523. */
  524. public function truncateSql(Connection $connection) {
  525. $dialect = $connection->driver()->schemaDialect();
  526. return $dialect->truncateTableSql($this);
  527. }
  528. }