Table.php 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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 LGPL. 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. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  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. *
  141. * @param array $columnNames
  142. * @param string $indexName
  143. * @return Table
  144. */
  145. public function addUniqueIndex(array $columnNames, $indexName = null)
  146. {
  147. if ($indexName == null) {
  148. $indexName = $this->_generateIdentifierName(
  149. array_merge(array($this->getName()), $columnNames), "uniq", $this->_getMaxIdentifierLength()
  150. );
  151. }
  152. return $this->_createIndex($columnNames, $indexName, true, false);
  153. }
  154. /**
  155. * Check if an index begins in the order of the given columns.
  156. *
  157. * @param array $columnsNames
  158. * @return bool
  159. */
  160. public function columnsAreIndexed(array $columnsNames)
  161. {
  162. foreach ($this->getIndexes() AS $index) {
  163. /* @var $index Index */
  164. if ($index->spansColumns($columnsNames)) {
  165. return true;
  166. }
  167. }
  168. return false;
  169. }
  170. /**
  171. *
  172. * @param array $columnNames
  173. * @param string $indexName
  174. * @param bool $isUnique
  175. * @param bool $isPrimary
  176. * @return Table
  177. */
  178. private function _createIndex(array $columnNames, $indexName, $isUnique, $isPrimary)
  179. {
  180. if (preg_match('(([^a-zA-Z0-9_]+))', $indexName)) {
  181. throw SchemaException::indexNameInvalid($indexName);
  182. }
  183. foreach ($columnNames AS $columnName => $indexColOptions) {
  184. if (is_numeric($columnName) && is_string($indexColOptions)) {
  185. $columnName = $indexColOptions;
  186. }
  187. if ( ! $this->hasColumn($columnName)) {
  188. throw SchemaException::columnDoesNotExist($columnName, $this->_name);
  189. }
  190. }
  191. $this->_addIndex(new Index($indexName, $columnNames, $isUnique, $isPrimary));
  192. return $this;
  193. }
  194. /**
  195. * @param string $columnName
  196. * @param string $columnType
  197. * @param array $options
  198. * @return Column
  199. */
  200. public function addColumn($columnName, $typeName, array $options=array())
  201. {
  202. $column = new Column($columnName, Type::getType($typeName), $options);
  203. $this->_addColumn($column);
  204. return $column;
  205. }
  206. /**
  207. * Rename Column
  208. *
  209. * @param string $oldColumnName
  210. * @param string $newColumnName
  211. * @return Table
  212. */
  213. public function renameColumn($oldColumnName, $newColumnName)
  214. {
  215. $column = $this->getColumn($oldColumnName);
  216. $this->dropColumn($oldColumnName);
  217. $column->_setName($newColumnName);
  218. return $this;
  219. }
  220. /**
  221. * Change Column Details
  222. *
  223. * @param string $columnName
  224. * @param array $options
  225. * @return Table
  226. */
  227. public function changeColumn($columnName, array $options)
  228. {
  229. $column = $this->getColumn($columnName);
  230. $column->setOptions($options);
  231. return $this;
  232. }
  233. /**
  234. * Drop Column from Table
  235. *
  236. * @param string $columnName
  237. * @return Table
  238. */
  239. public function dropColumn($columnName)
  240. {
  241. $columnName = strtolower($columnName);
  242. $column = $this->getColumn($columnName);
  243. unset($this->_columns[$columnName]);
  244. return $this;
  245. }
  246. /**
  247. * Add a foreign key constraint
  248. *
  249. * Name is inferred from the local columns
  250. *
  251. * @param Table $foreignTable
  252. * @param array $localColumns
  253. * @param array $foreignColumns
  254. * @param array $options
  255. * @param string $constraintName
  256. * @return Table
  257. */
  258. public function addForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=array(), $constraintName = null)
  259. {
  260. $constraintName = $constraintName ?: $this->_generateIdentifierName(array_merge((array)$this->getName(), $localColumnNames), "fk", $this->_getMaxIdentifierLength());
  261. return $this->addNamedForeignKeyConstraint($constraintName, $foreignTable, $localColumnNames, $foreignColumnNames, $options);
  262. }
  263. /**
  264. * Add a foreign key constraint
  265. *
  266. * Name is to be generated by the database itsself.
  267. *
  268. * @deprecated Use {@link addForeignKeyConstraint}
  269. * @param Table $foreignTable
  270. * @param array $localColumns
  271. * @param array $foreignColumns
  272. * @param array $options
  273. * @return Table
  274. */
  275. public function addUnnamedForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=array())
  276. {
  277. return $this->addForeignKeyConstraint($foreignTable, $localColumnNames, $foreignColumnNames, $options);
  278. }
  279. /**
  280. * Add a foreign key constraint with a given name
  281. *
  282. * @deprecated Use {@link addForeignKeyConstraint}
  283. * @param string $name
  284. * @param Table $foreignTable
  285. * @param array $localColumns
  286. * @param array $foreignColumns
  287. * @param array $options
  288. * @return Table
  289. */
  290. public function addNamedForeignKeyConstraint($name, $foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=array())
  291. {
  292. if ($foreignTable instanceof Table) {
  293. $foreignTableName = $foreignTable->getName();
  294. foreach ($foreignColumnNames AS $columnName) {
  295. if ( ! $foreignTable->hasColumn($columnName)) {
  296. throw SchemaException::columnDoesNotExist($columnName, $foreignTable->getName());
  297. }
  298. }
  299. } else {
  300. $foreignTableName = $foreignTable;
  301. }
  302. foreach ($localColumnNames AS $columnName) {
  303. if ( ! $this->hasColumn($columnName)) {
  304. throw SchemaException::columnDoesNotExist($columnName, $this->_name);
  305. }
  306. }
  307. $constraint = new ForeignKeyConstraint(
  308. $localColumnNames, $foreignTableName, $foreignColumnNames, $name, $options
  309. );
  310. $this->_addForeignKeyConstraint($constraint);
  311. return $this;
  312. }
  313. /**
  314. * @param string $name
  315. * @param string $value
  316. * @return Table
  317. */
  318. public function addOption($name, $value)
  319. {
  320. $this->_options[$name] = $value;
  321. return $this;
  322. }
  323. /**
  324. * @param Column $column
  325. */
  326. protected function _addColumn(Column $column)
  327. {
  328. $columnName = $column->getName();
  329. $columnName = strtolower($columnName);
  330. if (isset($this->_columns[$columnName])) {
  331. throw SchemaException::columnAlreadyExists($this->getName(), $columnName);
  332. }
  333. $this->_columns[$columnName] = $column;
  334. }
  335. /**
  336. * Add index to table
  337. *
  338. * @param Index $indexCandidate
  339. * @return Table
  340. */
  341. protected function _addIndex(Index $indexCandidate)
  342. {
  343. // check for duplicates
  344. foreach ($this->_indexes AS $existingIndex) {
  345. if ($indexCandidate->isFullfilledBy($existingIndex)) {
  346. return $this;
  347. }
  348. }
  349. $indexName = $indexCandidate->getName();
  350. $indexName = strtolower($indexName);
  351. if (isset($this->_indexes[$indexName]) || ($this->_primaryKeyName != false && $indexCandidate->isPrimary())) {
  352. throw SchemaException::indexAlreadyExists($indexName, $this->_name);
  353. }
  354. // remove overruled indexes
  355. foreach ($this->_indexes AS $idxKey => $existingIndex) {
  356. if ($indexCandidate->overrules($existingIndex)) {
  357. unset($this->_indexes[$idxKey]);
  358. }
  359. }
  360. if ($indexCandidate->isPrimary()) {
  361. $this->_primaryKeyName = $indexName;
  362. }
  363. $this->_indexes[$indexName] = $indexCandidate;
  364. return $this;
  365. }
  366. /**
  367. * @param ForeignKeyConstraint $constraint
  368. */
  369. protected function _addForeignKeyConstraint(ForeignKeyConstraint $constraint)
  370. {
  371. $constraint->setLocalTable($this);
  372. if(strlen($constraint->getName())) {
  373. $name = $constraint->getName();
  374. } else {
  375. $name = $this->_generateIdentifierName(
  376. array_merge((array)$this->getName(), $constraint->getLocalColumns()), "fk", $this->_getMaxIdentifierLength()
  377. );
  378. }
  379. $name = strtolower($name);
  380. $this->_fkConstraints[$name] = $constraint;
  381. // add an explicit index on the foreign key columns. If there is already an index that fullfils this requirements drop the request.
  382. // In the case of __construct calling this method during hydration from schema-details all the explicitly added indexes
  383. // lead to duplicates. This creates compuation overhead in this case, however no duplicate indexes are ever added (based on columns).
  384. $this->addIndex($constraint->getColumns());
  385. }
  386. /**
  387. * Does Table have a foreign key constraint with the given name?
  388. * *
  389. * @param string $constraintName
  390. * @return bool
  391. */
  392. public function hasForeignKey($constraintName)
  393. {
  394. $constraintName = strtolower($constraintName);
  395. return isset($this->_fkConstraints[$constraintName]);
  396. }
  397. /**
  398. * @param string $constraintName
  399. * @return ForeignKeyConstraint
  400. */
  401. public function getForeignKey($constraintName)
  402. {
  403. $constraintName = strtolower($constraintName);
  404. if(!$this->hasForeignKey($constraintName)) {
  405. throw SchemaException::foreignKeyDoesNotExist($constraintName, $this->_name);
  406. }
  407. return $this->_fkConstraints[$constraintName];
  408. }
  409. /**
  410. * @return Column[]
  411. */
  412. public function getColumns()
  413. {
  414. $columns = $this->_columns;
  415. $pkCols = array();
  416. $fkCols = array();
  417. if ($this->hasIndex($this->_primaryKeyName)) {
  418. $pkCols = $this->getPrimaryKey()->getColumns();
  419. }
  420. foreach ($this->getForeignKeys() AS $fk) {
  421. /* @var $fk ForeignKeyConstraint */
  422. $fkCols = array_merge($fkCols, $fk->getColumns());
  423. }
  424. $colNames = array_unique(array_merge($pkCols, $fkCols, array_keys($columns)));
  425. uksort($columns, function($a, $b) use($colNames) {
  426. return (array_search($a, $colNames) >= array_search($b, $colNames));
  427. });
  428. return $columns;
  429. }
  430. /**
  431. * Does this table have a column with the given name?
  432. *
  433. * @param string $columnName
  434. * @return bool
  435. */
  436. public function hasColumn($columnName)
  437. {
  438. $columnName = $this->trimQuotes(strtolower($columnName));
  439. return isset($this->_columns[$columnName]);
  440. }
  441. /**
  442. * Get a column instance
  443. *
  444. * @param string $columnName
  445. * @return Column
  446. */
  447. public function getColumn($columnName)
  448. {
  449. $columnName = strtolower($this->trimQuotes($columnName));
  450. if (!$this->hasColumn($columnName)) {
  451. throw SchemaException::columnDoesNotExist($columnName, $this->_name);
  452. }
  453. return $this->_columns[$columnName];
  454. }
  455. /**
  456. * @return Index
  457. */
  458. public function getPrimaryKey()
  459. {
  460. return $this->getIndex($this->_primaryKeyName);
  461. }
  462. /**
  463. * Check if this table has a primary key.
  464. *
  465. * @return bool
  466. */
  467. public function hasPrimaryKey()
  468. {
  469. return ($this->_primaryKeyName && $this->hasIndex($this->_primaryKeyName));
  470. }
  471. /**
  472. * @param string $indexName
  473. * @return bool
  474. */
  475. public function hasIndex($indexName)
  476. {
  477. $indexName = strtolower($indexName);
  478. return (isset($this->_indexes[$indexName]));
  479. }
  480. /**
  481. * @param string $indexName
  482. * @return Index
  483. */
  484. public function getIndex($indexName)
  485. {
  486. $indexName = strtolower($indexName);
  487. if (!$this->hasIndex($indexName)) {
  488. throw SchemaException::indexDoesNotExist($indexName, $this->_name);
  489. }
  490. return $this->_indexes[$indexName];
  491. }
  492. /**
  493. * @return array
  494. */
  495. public function getIndexes()
  496. {
  497. return $this->_indexes;
  498. }
  499. /**
  500. * Get Constraints
  501. *
  502. * @return array
  503. */
  504. public function getForeignKeys()
  505. {
  506. return $this->_fkConstraints;
  507. }
  508. public function hasOption($name)
  509. {
  510. return isset($this->_options[$name]);
  511. }
  512. public function getOption($name)
  513. {
  514. return $this->_options[$name];
  515. }
  516. public function getOptions()
  517. {
  518. return $this->_options;
  519. }
  520. /**
  521. * @param Visitor $visitor
  522. */
  523. public function visit(Visitor $visitor)
  524. {
  525. $visitor->acceptTable($this);
  526. foreach ($this->getColumns() AS $column) {
  527. $visitor->acceptColumn($this, $column);
  528. }
  529. foreach ($this->getIndexes() AS $index) {
  530. $visitor->acceptIndex($this, $index);
  531. }
  532. foreach ($this->getForeignKeys() AS $constraint) {
  533. $visitor->acceptForeignKey($this, $constraint);
  534. }
  535. }
  536. /**
  537. * Clone of a Table triggers a deep clone of all affected assets
  538. */
  539. public function __clone()
  540. {
  541. foreach ($this->_columns AS $k => $column) {
  542. $this->_columns[$k] = clone $column;
  543. }
  544. foreach ($this->_indexes AS $k => $index) {
  545. $this->_indexes[$k] = clone $index;
  546. }
  547. foreach ($this->_fkConstraints AS $k => $fk) {
  548. $this->_fkConstraints[$k] = clone $fk;
  549. $this->_fkConstraints[$k]->setLocalTable($this);
  550. }
  551. }
  552. }