Table.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. <?php
  2. /**
  3. * PHP Version 5.4
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @since CakePHP(tm) v 3.0.0
  15. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  16. */
  17. namespace Cake\Database\Schema;
  18. use Cake\Database\Connection;
  19. use Cake\Database\Exception;
  20. /**
  21. * Represents a single table in a database schema.
  22. *
  23. * Can either be populated using the reflection API's
  24. * or by incrementally building an instance using
  25. * methods.
  26. *
  27. * Once created Table instances can be added to
  28. * Schema\Collection objects.
  29. */
  30. class Table {
  31. /**
  32. * The name of the table
  33. *
  34. * @var string
  35. */
  36. protected $_table;
  37. /**
  38. * Columns in the table.
  39. *
  40. * @var array
  41. */
  42. protected $_columns = [];
  43. /**
  44. * Indexes in the table.
  45. *
  46. * @var array
  47. */
  48. protected $_indexes = [];
  49. /**
  50. * Constraints in the table.
  51. *
  52. * @var array
  53. */
  54. protected $_constraints = [];
  55. /**
  56. * Options for the table.
  57. *
  58. * @var array
  59. */
  60. protected $_options = [];
  61. /**
  62. * The valid keys that can be used in a column
  63. * definition.
  64. *
  65. * @var array
  66. */
  67. protected $_columnKeys = [
  68. 'type' => null,
  69. 'length' => null,
  70. 'precision' => null,
  71. 'null' => null,
  72. 'default' => null,
  73. 'fixed' => null,
  74. 'comment' => null,
  75. ];
  76. /**
  77. * The valid keys that can be used in an index
  78. * definition.
  79. *
  80. * @var array
  81. */
  82. protected $_indexKeys = [
  83. 'type' => null,
  84. 'columns' => [],
  85. 'length' => [],
  86. 'references' => [],
  87. 'update' => 'restrict',
  88. 'delete' => 'restrict',
  89. ];
  90. /**
  91. * Names of the valid index types.
  92. *
  93. * @var array
  94. */
  95. protected $_validIndexTypes = [
  96. self::INDEX_INDEX,
  97. self::INDEX_FULLTEXT,
  98. ];
  99. /**
  100. * Names of the valid constraint types.
  101. *
  102. * @var array
  103. */
  104. protected $_validConstraintTypes = [
  105. self::CONSTRAINT_PRIMARY,
  106. self::CONSTRAINT_UNIQUE,
  107. self::CONSTRAINT_FOREIGN,
  108. ];
  109. /**
  110. * Names of the valid foreign key actions.
  111. *
  112. * @var array
  113. */
  114. protected $_validForeignKeyActions = [
  115. self::ACTION_CASCADE,
  116. self::ACTION_SET_NULL,
  117. self::ACTION_NO_ACTION,
  118. self::ACTION_RESTRICT,
  119. ];
  120. const CONSTRAINT_PRIMARY = 'primary';
  121. const CONSTRAINT_UNIQUE = 'unique';
  122. const CONSTRAINT_FOREIGN = 'foreign';
  123. const INDEX_INDEX = 'index';
  124. const INDEX_FULLTEXT = 'fulltext';
  125. const ACTION_CASCADE = 'cascade';
  126. const ACTION_SET_NULL = 'setNull';
  127. const ACTION_NO_ACTION = 'noAction';
  128. const ACTION_RESTRICT = 'restrict';
  129. /**
  130. * Constructor.
  131. *
  132. * @param string $table The table name.
  133. * @param array $columns The list of columns for the schema.
  134. */
  135. public function __construct($table, $columns = array()) {
  136. $this->_table = $table;
  137. foreach ($columns as $field => $definition) {
  138. $this->addColumn($field, $definition);
  139. }
  140. }
  141. /**
  142. * Get the name of the table.
  143. *
  144. * @return string
  145. */
  146. public function name() {
  147. return $this->_table;
  148. }
  149. /**
  150. * Add a column to the table.
  151. *
  152. * ### Attributes
  153. *
  154. * Columns can have several attributes:
  155. *
  156. * - `type` The type of the column. This should be
  157. * one of CakePHP's abstract types.
  158. * - `length` The length of the column.
  159. * - `precision` The number of decimal places to store
  160. * for float and decimal types.
  161. * - `default` The default value of the column.
  162. * - `null` Whether or not the column can hold nulls.
  163. * - `fixed` Whether or not the column is a fixed length column.
  164. * this is only useful for string colums.
  165. *
  166. * In addition to the above keys, the following keys are
  167. * implemented in some database dialects, but not all:
  168. *
  169. * - `comment` The comment for the column.
  170. *
  171. * @param string $name The name of the column
  172. * @param array $attrs The attributes for the column.
  173. * @return Table $this
  174. */
  175. public function addColumn($name, $attrs) {
  176. if (is_string($attrs)) {
  177. $attrs = ['type' => $attrs];
  178. }
  179. $attrs = array_intersect_key($attrs, $this->_columnKeys);
  180. $this->_columns[$name] = $attrs + $this->_columnKeys;
  181. return $this;
  182. }
  183. /**
  184. * Get the column names in the table.
  185. *
  186. * @return array
  187. */
  188. public function columns() {
  189. return array_keys($this->_columns);
  190. }
  191. /**
  192. * Get column data in the table.
  193. *
  194. * @param string $name The column name.
  195. * @return array|null Column data or null.
  196. */
  197. public function column($name) {
  198. if (!isset($this->_columns[$name])) {
  199. return null;
  200. }
  201. return $this->_columns[$name];
  202. }
  203. /**
  204. * Convenience method for getting the type of a given column.
  205. *
  206. * @param string $name The column to get the type of.
  207. * @return string|null Either the column type or null.
  208. */
  209. public function columnType($name) {
  210. if (!isset($this->_columns[$name])) {
  211. return null;
  212. }
  213. return $this->_columns[$name]['type'];
  214. }
  215. /**
  216. * Add an index.
  217. *
  218. * Used to add indexes, and full text indexes in platforms that support
  219. * them.
  220. *
  221. * ### Attributes
  222. *
  223. * - `type` The type of index being added.
  224. * - `columns` The columns in the index.
  225. *
  226. * @param string $name The name of the index.
  227. * @param array $attrs The attributes for the index.
  228. * @return Table $this
  229. * @throws Cake\Database\Exception
  230. */
  231. public function addIndex($name, $attrs) {
  232. if (is_string($attrs)) {
  233. $attrs = ['type' => $attrs];
  234. }
  235. $attrs = array_intersect_key($attrs, $this->_indexKeys);
  236. $attrs = $attrs + $this->_indexKeys;
  237. unset($attrs['references'], $attrs['update'], $attrs['delete']);
  238. if (!in_array($attrs['type'], $this->_validIndexTypes, true)) {
  239. throw new Exception(__d('cake_dev', 'Invalid index type "%s"', $attrs['type']));
  240. }
  241. if (empty($attrs['columns'])) {
  242. throw new Exception(__d('cake_dev', 'Indexes must define columns.'));
  243. }
  244. $attrs['columns'] = (array)$attrs['columns'];
  245. foreach ($attrs['columns'] as $field) {
  246. if (empty($this->_columns[$field])) {
  247. throw new Exception(__d('cake_dev', 'Columns used in indexes must already exist.'));
  248. }
  249. }
  250. $this->_indexes[$name] = $attrs;
  251. return $this;
  252. }
  253. /**
  254. * Get the names of all the indexes in the table.
  255. *
  256. * @return array
  257. */
  258. public function indexes() {
  259. return array_keys($this->_indexes);
  260. }
  261. /**
  262. * Read information about an index based on name.
  263. *
  264. * @param string $name The name of the index.
  265. * @return array|null Array of index data, or null
  266. */
  267. public function index($name) {
  268. if (!isset($this->_indexes[$name])) {
  269. return null;
  270. }
  271. return $this->_indexes[$name];
  272. }
  273. /**
  274. * Get the column(s) used for the primary key.
  275. *
  276. * @return array|null Column name(s) for the primary key.
  277. * Null will be returned if a table has no primary key.
  278. */
  279. public function primaryKey() {
  280. foreach ($this->_constraints as $name => $data) {
  281. if ($data['type'] === self::CONSTRAINT_PRIMARY) {
  282. return $data['columns'];
  283. }
  284. }
  285. return null;
  286. }
  287. /**
  288. * Add a constraint.
  289. *
  290. * Used to add constraints to a table. For example primary keys, unique
  291. * keys and foriegn keys.
  292. *
  293. * ### Attributes
  294. *
  295. * - `type` The type of constraint being added.
  296. * - `columns` The columns in the index.
  297. * - `references` The table, column a foreign key references.
  298. * - `update` The behavior on update. Options are 'restrict', 'setNull', 'cascade', 'noAction'.
  299. * - `delete` The behavior on delete. Options are 'restrict', 'setNull', 'cascade', 'noAction'.
  300. *
  301. * The default for 'update' & 'delete' is 'cascade'.
  302. *
  303. * @param string $name The name of the constraint.
  304. * @param array $attrs The attributes for the constraint.
  305. * @return Table $this
  306. * @throws Cake\Database\Exception
  307. */
  308. public function addConstraint($name, $attrs) {
  309. if (is_string($attrs)) {
  310. $attrs = ['type' => $attrs];
  311. }
  312. $attrs = array_intersect_key($attrs, $this->_indexKeys);
  313. $attrs = $attrs + $this->_indexKeys;
  314. if (!in_array($attrs['type'], $this->_validConstraintTypes, true)) {
  315. throw new Exception(__d('cake_dev', 'Invalid constraint type "%s"', $attrs['type']));
  316. }
  317. if (empty($attrs['columns'])) {
  318. throw new Exception(__d('cake_dev', 'Constraints must define columns.'));
  319. }
  320. $attrs['columns'] = (array)$attrs['columns'];
  321. foreach ($attrs['columns'] as $field) {
  322. if (empty($this->_columns[$field])) {
  323. throw new Exception(__d('cake_dev', 'Columns used in constraints must already exist.'));
  324. }
  325. }
  326. if ($attrs['type'] === static::CONSTRAINT_FOREIGN) {
  327. $attrs = $this->_checkForeignKey($attrs);
  328. } else {
  329. unset($attrs['references'], $attrs['update'], $attrs['delete']);
  330. }
  331. $this->_constraints[$name] = $attrs;
  332. return $this;
  333. }
  334. /**
  335. * Helper method to check/validate foreign keys.
  336. *
  337. * @param array $attrs Attributes to set.
  338. * @return array
  339. * @throws Cake\Database\Exception When foreign key definition is not valid.
  340. */
  341. protected function _checkForeignKey($attrs) {
  342. if (count($attrs['references']) < 2) {
  343. throw new Exception(__d('cake_dev', 'References must contain a table and column.'));
  344. }
  345. if (!in_array($attrs['update'], $this->_validForeignKeyActions)) {
  346. throw new Exception(__d('cake_dev', 'Update action is invalid. Must be one of %s', implode(',', $this->_validForeignKeyActions)));
  347. }
  348. if (!in_array($attrs['delete'], $this->_validForeignKeyActions)) {
  349. throw new Exception(__d('cake_dev', 'Delete action is invalid. Must be one of %s', implode(',', $this->_validForeignKeyActions)));
  350. }
  351. return $attrs;
  352. }
  353. /**
  354. * Get the names of all the constraints in the table.
  355. *
  356. * @return array
  357. */
  358. public function constraints() {
  359. return array_keys($this->_constraints);
  360. }
  361. /**
  362. * Read information about an constraint based on name.
  363. *
  364. * @param string $name The name of the constraint.
  365. * @return array|null Array of constraint data, or null
  366. */
  367. public function constraint($name) {
  368. if (!isset($this->_constraints[$name])) {
  369. return null;
  370. }
  371. return $this->_constraints[$name];
  372. }
  373. /**
  374. * Get/set the options for a table.
  375. *
  376. * Table options allow you to set platform specific table level options.
  377. * For example the engine type in MySQL.
  378. *
  379. * @param array|null $options The options to set, or null to read options.
  380. * @return this|array Either the table instance, or an array of options when reading.
  381. */
  382. public function options($options = null) {
  383. if ($options === null) {
  384. return $this->_options;
  385. }
  386. $this->_options = array_merge($this->_options, $options);
  387. return $this;
  388. }
  389. /**
  390. * Generate the SQL to create the Table.
  391. *
  392. * Uses the connection to access the schema dialect
  393. * to generate platform specific SQL.
  394. *
  395. * @param Connection $connection The connection to generate SQL for
  396. * @return array List of SQL statements to create the table and the
  397. * required indexes.
  398. */
  399. public function createSql(Connection $connection) {
  400. $dialect = $connection->driver()->schemaDialect();
  401. $columns = $constraints = $indexes = [];
  402. foreach (array_keys($this->_columns) as $name) {
  403. $columns[] = $dialect->columnSql($this, $name);
  404. }
  405. foreach (array_keys($this->_constraints) as $name) {
  406. $constraints[] = $dialect->constraintSql($this, $name);
  407. }
  408. foreach (array_keys($this->_indexes) as $name) {
  409. $indexes[] = $dialect->indexSql($this, $name);
  410. }
  411. return $dialect->createTableSql($this, $columns, $constraints, $indexes);
  412. }
  413. /**
  414. * Generate the SQL to drop a table.
  415. *
  416. * Uses the connection to access the schema dialect to generate platform
  417. * specific SQL.
  418. *
  419. * @param Connection $connection The connection to generate SQL for.
  420. * @return array SQL to drop a table.
  421. */
  422. public function dropSql(Connection $connection) {
  423. $dialect = $connection->driver()->schemaDialect();
  424. return $dialect->dropTableSql($this);
  425. }
  426. /**
  427. * Generate the SQL statements to truncate a table
  428. *
  429. * @param Connection $connection The connection to generate SQL for.
  430. * @return array SQL to drop a table.
  431. */
  432. public function truncateSql(Connection $connection) {
  433. $dialect = $connection->driver()->schemaDialect();
  434. return $dialect->truncateTableSql($this);
  435. }
  436. }