Table.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. <?php
  2. /*
  3. * $Id$
  4. *
  5. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  9. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  10. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  11. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  12. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  13. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  14. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  15. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  16. *
  17. * This software consists of voluntary contributions made by many individuals
  18. * and is licensed under the MIT license. For more information, see
  19. * <http://www.doctrine-project.org>.
  20. */
  21. namespace Doctrine\DBAL\Schema;
  22. use Doctrine\DBAL\Types\Type;
  23. use Doctrine\DBAL\Schema\Visitor\Visitor;
  24. use Doctrine\DBAL\DBALException;
  25. /**
  26. * Object Representation of a table
  27. *
  28. *
  29. * @link www.doctrine-project.org
  30. * @since 2.0
  31. * @version $Revision$
  32. * @author Benjamin Eberlei <kontakt@beberlei.de>
  33. */
  34. class Table extends AbstractAsset
  35. {
  36. /**
  37. * @var string
  38. */
  39. protected $_name = null;
  40. /**
  41. * @var array
  42. */
  43. protected $_columns = array();
  44. /**
  45. * @var array
  46. */
  47. protected $_indexes = array();
  48. /**
  49. * @var string
  50. */
  51. protected $_primaryKeyName = false;
  52. /**
  53. * @var array
  54. */
  55. protected $_fkConstraints = array();
  56. /**
  57. * @var array
  58. */
  59. protected $_options = array();
  60. /**
  61. * @var SchemaConfig
  62. */
  63. protected $_schemaConfig = null;
  64. /**
  65. *
  66. * @param string $tableName
  67. * @param array $columns
  68. * @param array $indexes
  69. * @param array $fkConstraints
  70. * @param int $idGeneratorType
  71. * @param array $options
  72. */
  73. public function __construct($tableName, array $columns=array(), array $indexes=array(), array $fkConstraints=array(), $idGeneratorType = 0, array $options=array())
  74. {
  75. if (strlen($tableName) == 0) {
  76. throw DBALException::invalidTableName($tableName);
  77. }
  78. $this->_setName($tableName);
  79. $this->_idGeneratorType = $idGeneratorType;
  80. foreach ($columns as $column) {
  81. $this->_addColumn($column);
  82. }
  83. foreach ($indexes as $idx) {
  84. $this->_addIndex($idx);
  85. }
  86. foreach ($fkConstraints as $constraint) {
  87. $this->_addForeignKeyConstraint($constraint);
  88. }
  89. $this->_options = $options;
  90. }
  91. /**
  92. * @param SchemaConfig $schemaConfig
  93. */
  94. public function setSchemaConfig(SchemaConfig $schemaConfig)
  95. {
  96. $this->_schemaConfig = $schemaConfig;
  97. }
  98. /**
  99. * @return int
  100. */
  101. protected function _getMaxIdentifierLength()
  102. {
  103. if ($this->_schemaConfig instanceof SchemaConfig) {
  104. return $this->_schemaConfig->getMaxIdentifierLength();
  105. } else {
  106. return 63;
  107. }
  108. }
  109. /**
  110. * Set Primary Key
  111. *
  112. * @param array $columns
  113. * @param string $indexName
  114. * @return Table
  115. */
  116. public function setPrimaryKey(array $columns, $indexName = false)
  117. {
  118. $primaryKey = $this->_createIndex($columns, $indexName ?: "primary", true, true);
  119. foreach ($columns as $columnName) {
  120. $column = $this->getColumn($columnName);
  121. $column->setNotnull(true);
  122. }
  123. return $primaryKey;
  124. }
  125. /**
  126. * @param array $columnNames
  127. * @param string $indexName
  128. * @return Table
  129. */
  130. public function addIndex(array $columnNames, $indexName = null)
  131. {
  132. if($indexName == null) {
  133. $indexName = $this->_generateIdentifierName(
  134. array_merge(array($this->getName()), $columnNames), "idx", $this->_getMaxIdentifierLength()
  135. );
  136. }
  137. return $this->_createIndex($columnNames, $indexName, false, false);
  138. }
  139. /**
  140. * Drop an index from this table.
  141. *
  142. * @param string $indexName
  143. * @return void
  144. */
  145. public function dropPrimaryKey()
  146. {
  147. $this->dropIndex($this->_primaryKeyName);
  148. $this->_primaryKeyName = false;
  149. }
  150. /**
  151. * Drop an index from this table.
  152. *
  153. * @param string $indexName
  154. * @return void
  155. */
  156. public function dropIndex($indexName)
  157. {
  158. $indexName = strtolower($indexName);
  159. if ( ! $this->hasIndex($indexName)) {
  160. throw SchemaException::indexDoesNotExist($indexName, $this->_name);
  161. }
  162. unset($this->_indexes[$indexName]);
  163. }
  164. /**
  165. *
  166. * @param array $columnNames
  167. * @param string $indexName
  168. * @return Table
  169. */
  170. public function addUniqueIndex(array $columnNames, $indexName = null)
  171. {
  172. if ($indexName === null) {
  173. $indexName = $this->_generateIdentifierName(
  174. array_merge(array($this->getName()), $columnNames), "uniq", $this->_getMaxIdentifierLength()
  175. );
  176. }
  177. return $this->_createIndex($columnNames, $indexName, true, false);
  178. }
  179. /**
  180. * Check if an index begins in the order of the given columns.
  181. *
  182. * @param array $columnsNames
  183. * @return bool
  184. */
  185. public function columnsAreIndexed(array $columnsNames)
  186. {
  187. foreach ($this->getIndexes() as $index) {
  188. /* @var $index Index */
  189. if ($index->spansColumns($columnsNames)) {
  190. return true;
  191. }
  192. }
  193. return false;
  194. }
  195. /**
  196. *
  197. * @param array $columnNames
  198. * @param string $indexName
  199. * @param bool $isUnique
  200. * @param bool $isPrimary
  201. * @return Table
  202. */
  203. private function _createIndex(array $columnNames, $indexName, $isUnique, $isPrimary)
  204. {
  205. if (preg_match('(([^a-zA-Z0-9_]+))', $indexName)) {
  206. throw SchemaException::indexNameInvalid($indexName);
  207. }
  208. foreach ($columnNames as $columnName => $indexColOptions) {
  209. if (is_numeric($columnName) && is_string($indexColOptions)) {
  210. $columnName = $indexColOptions;
  211. }
  212. if ( ! $this->hasColumn($columnName)) {
  213. throw SchemaException::columnDoesNotExist($columnName, $this->_name);
  214. }
  215. }
  216. $this->_addIndex(new Index($indexName, $columnNames, $isUnique, $isPrimary));
  217. return $this;
  218. }
  219. /**
  220. * @param string $columnName
  221. * @param string $columnType
  222. * @param array $options
  223. * @return Column
  224. */
  225. public function addColumn($columnName, $typeName, array $options=array())
  226. {
  227. $column = new Column($columnName, Type::getType($typeName), $options);
  228. $this->_addColumn($column);
  229. return $column;
  230. }
  231. /**
  232. * Rename Column
  233. *
  234. * @param string $oldColumnName
  235. * @param string $newColumnName
  236. * @return Table
  237. */
  238. public function renameColumn($oldColumnName, $newColumnName)
  239. {
  240. throw new DBALException("Table#renameColumn() was removed, because it drops and recreates " .
  241. "the column instead. There is no fix available, because a schema diff cannot reliably detect if a " .
  242. "column was renamed or one column was created and another one dropped.");
  243. }
  244. /**
  245. * Change Column Details
  246. *
  247. * @param string $columnName
  248. * @param array $options
  249. * @return Table
  250. */
  251. public function changeColumn($columnName, array $options)
  252. {
  253. $column = $this->getColumn($columnName);
  254. $column->setOptions($options);
  255. return $this;
  256. }
  257. /**
  258. * Drop Column from Table
  259. *
  260. * @param string $columnName
  261. * @return Table
  262. */
  263. public function dropColumn($columnName)
  264. {
  265. $columnName = strtolower($columnName);
  266. $column = $this->getColumn($columnName);
  267. unset($this->_columns[$columnName]);
  268. return $this;
  269. }
  270. /**
  271. * Add a foreign key constraint
  272. *
  273. * Name is inferred from the local columns
  274. *
  275. * @param Table $foreignTable
  276. * @param array $localColumns
  277. * @param array $foreignColumns
  278. * @param array $options
  279. * @param string $constraintName
  280. * @return Table
  281. */
  282. public function addForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=array(), $constraintName = null)
  283. {
  284. $constraintName = $constraintName ?: $this->_generateIdentifierName(array_merge((array)$this->getName(), $localColumnNames), "fk", $this->_getMaxIdentifierLength());
  285. return $this->addNamedForeignKeyConstraint($constraintName, $foreignTable, $localColumnNames, $foreignColumnNames, $options);
  286. }
  287. /**
  288. * Add a foreign key constraint
  289. *
  290. * Name is to be generated by the database itsself.
  291. *
  292. * @deprecated Use {@link addForeignKeyConstraint}
  293. * @param Table $foreignTable
  294. * @param array $localColumns
  295. * @param array $foreignColumns
  296. * @param array $options
  297. * @return Table
  298. */
  299. public function addUnnamedForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=array())
  300. {
  301. return $this->addForeignKeyConstraint($foreignTable, $localColumnNames, $foreignColumnNames, $options);
  302. }
  303. /**
  304. * Add a foreign key constraint with a given name
  305. *
  306. * @deprecated Use {@link addForeignKeyConstraint}
  307. * @param string $name
  308. * @param Table $foreignTable
  309. * @param array $localColumns
  310. * @param array $foreignColumns
  311. * @param array $options
  312. * @return Table
  313. */
  314. public function addNamedForeignKeyConstraint($name, $foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=array())
  315. {
  316. if ($foreignTable instanceof Table) {
  317. $foreignTableName = $foreignTable->getName();
  318. foreach ($foreignColumnNames as $columnName) {
  319. if ( ! $foreignTable->hasColumn($columnName)) {
  320. throw SchemaException::columnDoesNotExist($columnName, $foreignTable->getName());
  321. }
  322. }
  323. } else {
  324. $foreignTableName = $foreignTable;
  325. }
  326. foreach ($localColumnNames as $columnName) {
  327. if ( ! $this->hasColumn($columnName)) {
  328. throw SchemaException::columnDoesNotExist($columnName, $this->_name);
  329. }
  330. }
  331. $constraint = new ForeignKeyConstraint(
  332. $localColumnNames, $foreignTableName, $foreignColumnNames, $name, $options
  333. );
  334. $this->_addForeignKeyConstraint($constraint);
  335. return $this;
  336. }
  337. /**
  338. * @param string $name
  339. * @param string $value
  340. * @return Table
  341. */
  342. public function addOption($name, $value)
  343. {
  344. $this->_options[$name] = $value;
  345. return $this;
  346. }
  347. /**
  348. * @param Column $column
  349. */
  350. protected function _addColumn(Column $column)
  351. {
  352. $columnName = $column->getName();
  353. $columnName = strtolower($columnName);
  354. if (isset($this->_columns[$columnName])) {
  355. throw SchemaException::columnAlreadyExists($this->getName(), $columnName);
  356. }
  357. $this->_columns[$columnName] = $column;
  358. }
  359. /**
  360. * Add index to table
  361. *
  362. * @param Index $indexCandidate
  363. * @return Table
  364. */
  365. protected function _addIndex(Index $indexCandidate)
  366. {
  367. // check for duplicates
  368. foreach ($this->_indexes as $existingIndex) {
  369. if ($indexCandidate->isFullfilledBy($existingIndex)) {
  370. return $this;
  371. }
  372. }
  373. $indexName = $indexCandidate->getName();
  374. $indexName = strtolower($indexName);
  375. if (isset($this->_indexes[$indexName]) || ($this->_primaryKeyName != false && $indexCandidate->isPrimary())) {
  376. throw SchemaException::indexAlreadyExists($indexName, $this->_name);
  377. }
  378. // remove overruled indexes
  379. foreach ($this->_indexes as $idxKey => $existingIndex) {
  380. if ($indexCandidate->overrules($existingIndex)) {
  381. unset($this->_indexes[$idxKey]);
  382. }
  383. }
  384. if ($indexCandidate->isPrimary()) {
  385. $this->_primaryKeyName = $indexName;
  386. }
  387. $this->_indexes[$indexName] = $indexCandidate;
  388. return $this;
  389. }
  390. /**
  391. * @param ForeignKeyConstraint $constraint
  392. */
  393. protected function _addForeignKeyConstraint(ForeignKeyConstraint $constraint)
  394. {
  395. $constraint->setLocalTable($this);
  396. if(strlen($constraint->getName())) {
  397. $name = $constraint->getName();
  398. } else {
  399. $name = $this->_generateIdentifierName(
  400. array_merge((array)$this->getName(), $constraint->getLocalColumns()), "fk", $this->_getMaxIdentifierLength()
  401. );
  402. }
  403. $name = strtolower($name);
  404. $this->_fkConstraints[$name] = $constraint;
  405. // add an explicit index on the foreign key columns. If there is already an index that fullfils this requirements drop the request.
  406. // In the case of __construct calling this method during hydration from schema-details all the explicitly added indexes
  407. // lead to duplicates. This creates compuation overhead in this case, however no duplicate indexes are ever added (based on columns).
  408. $this->addIndex($constraint->getColumns());
  409. }
  410. /**
  411. * Does Table have a foreign key constraint with the given name?
  412. * *
  413. * @param string $constraintName
  414. * @return bool
  415. */
  416. public function hasForeignKey($constraintName)
  417. {
  418. $constraintName = strtolower($constraintName);
  419. return isset($this->_fkConstraints[$constraintName]);
  420. }
  421. /**
  422. * @param string $constraintName
  423. * @return ForeignKeyConstraint
  424. */
  425. public function getForeignKey($constraintName)
  426. {
  427. $constraintName = strtolower($constraintName);
  428. if(!$this->hasForeignKey($constraintName)) {
  429. throw SchemaException::foreignKeyDoesNotExist($constraintName, $this->_name);
  430. }
  431. return $this->_fkConstraints[$constraintName];
  432. }
  433. public function removeForeignKey($constraintName)
  434. {
  435. $constraintName = strtolower($constraintName);
  436. if(!$this->hasForeignKey($constraintName)) {
  437. throw SchemaException::foreignKeyDoesNotExist($constraintName, $this->_name);
  438. }
  439. unset($this->_fkConstraints[$constraintName]);
  440. }
  441. /**
  442. * @return Column[]
  443. */
  444. public function getColumns()
  445. {
  446. $columns = $this->_columns;
  447. $pkCols = array();
  448. $fkCols = array();
  449. if ($this->hasPrimaryKey()) {
  450. $pkCols = $this->getPrimaryKey()->getColumns();
  451. }
  452. foreach ($this->getForeignKeys() as $fk) {
  453. /* @var $fk ForeignKeyConstraint */
  454. $fkCols = array_merge($fkCols, $fk->getColumns());
  455. }
  456. $colNames = array_unique(array_merge($pkCols, $fkCols, array_keys($columns)));
  457. uksort($columns, function($a, $b) use($colNames) {
  458. return (array_search($a, $colNames) >= array_search($b, $colNames));
  459. });
  460. return $columns;
  461. }
  462. /**
  463. * Does this table have a column with the given name?
  464. *
  465. * @param string $columnName
  466. * @return bool
  467. */
  468. public function hasColumn($columnName)
  469. {
  470. $columnName = $this->trimQuotes(strtolower($columnName));
  471. return isset($this->_columns[$columnName]);
  472. }
  473. /**
  474. * Get a column instance
  475. *
  476. * @param string $columnName
  477. * @return Column
  478. */
  479. public function getColumn($columnName)
  480. {
  481. $columnName = strtolower($this->trimQuotes($columnName));
  482. if ( ! $this->hasColumn($columnName)) {
  483. throw SchemaException::columnDoesNotExist($columnName, $this->_name);
  484. }
  485. return $this->_columns[$columnName];
  486. }
  487. /**
  488. * @return Index|null
  489. */
  490. public function getPrimaryKey()
  491. {
  492. if ( ! $this->hasPrimaryKey()) {
  493. return null;
  494. }
  495. return $this->getIndex($this->_primaryKeyName);
  496. }
  497. public function getPrimaryKeyColumns()
  498. {
  499. if ( ! $this->hasPrimaryKey()) {
  500. throw new DBALException("Table " . $this->getName() . " has no primary key.");
  501. }
  502. return $this->getPrimaryKey()->getColumns();
  503. }
  504. /**
  505. * Check if this table has a primary key.
  506. *
  507. * @return bool
  508. */
  509. public function hasPrimaryKey()
  510. {
  511. return ($this->_primaryKeyName && $this->hasIndex($this->_primaryKeyName));
  512. }
  513. /**
  514. * @param string $indexName
  515. * @return bool
  516. */
  517. public function hasIndex($indexName)
  518. {
  519. $indexName = strtolower($indexName);
  520. return (isset($this->_indexes[$indexName]));
  521. }
  522. /**
  523. * @param string $indexName
  524. * @return Index
  525. */
  526. public function getIndex($indexName)
  527. {
  528. $indexName = strtolower($indexName);
  529. if ( ! $this->hasIndex($indexName)) {
  530. throw SchemaException::indexDoesNotExist($indexName, $this->_name);
  531. }
  532. return $this->_indexes[$indexName];
  533. }
  534. /**
  535. * @return array
  536. */
  537. public function getIndexes()
  538. {
  539. return $this->_indexes;
  540. }
  541. /**
  542. * Get Constraints
  543. *
  544. * @return array
  545. */
  546. public function getForeignKeys()
  547. {
  548. return $this->_fkConstraints;
  549. }
  550. public function hasOption($name)
  551. {
  552. return isset($this->_options[$name]);
  553. }
  554. public function getOption($name)
  555. {
  556. return $this->_options[$name];
  557. }
  558. public function getOptions()
  559. {
  560. return $this->_options;
  561. }
  562. /**
  563. * @param Visitor $visitor
  564. */
  565. public function visit(Visitor $visitor)
  566. {
  567. $visitor->acceptTable($this);
  568. foreach ($this->getColumns() as $column) {
  569. $visitor->acceptColumn($this, $column);
  570. }
  571. foreach ($this->getIndexes() as $index) {
  572. $visitor->acceptIndex($this, $index);
  573. }
  574. foreach ($this->getForeignKeys() as $constraint) {
  575. $visitor->acceptForeignKey($this, $constraint);
  576. }
  577. }
  578. /**
  579. * Clone of a Table triggers a deep clone of all affected assets
  580. */
  581. public function __clone()
  582. {
  583. foreach ($this->_columns as $k => $column) {
  584. $this->_columns[$k] = clone $column;
  585. }
  586. foreach ($this->_indexes as $k => $index) {
  587. $this->_indexes[$k] = clone $index;
  588. }
  589. foreach ($this->_fkConstraints as $k => $fk) {
  590. $this->_fkConstraints[$k] = clone $fk;
  591. $this->_fkConstraints[$k]->setLocalTable($this);
  592. }
  593. }
  594. }