Table.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. <?php
  2. /**
  3. * Phinx
  4. *
  5. * (The MIT license)
  6. * Copyright (c) 2015 Rob Morgan
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated * documentation files (the "Software"), to
  10. * deal in the Software without restriction, including without limitation the
  11. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  12. * sell copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  23. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  24. * IN THE SOFTWARE.
  25. *
  26. * @package Phinx
  27. * @subpackage Phinx\Db
  28. */
  29. namespace DDLWrapper\Db;
  30. use DDLWrapper\Db\Table\Column;
  31. use DDLWrapper\Db\Table\Index;
  32. use DDLWrapper\Db\Table\ForeignKey;
  33. use DDLWrapper\Db\Adapter\AdapterInterface;
  34. /**
  35. *
  36. * This object is based loosely on: http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html.
  37. */
  38. class Table
  39. {
  40. /**
  41. * @var string
  42. */
  43. protected $name;
  44. /**
  45. * @var array
  46. */
  47. protected $options = array();
  48. /**
  49. * @var AdapterInterface
  50. */
  51. protected $adapter;
  52. /**
  53. * @var array
  54. */
  55. protected $columns = array();
  56. /**
  57. * @var array
  58. */
  59. protected $indexes = array();
  60. /**
  61. * @var ForeignKey[]
  62. */
  63. protected $foreignKeys = array();
  64. /**
  65. * @var array
  66. */
  67. protected $data = array();
  68. /**
  69. * Class Constuctor.
  70. *
  71. * @param string $name Table Name
  72. * @param array $options Options
  73. * @param AdapterInterface $adapter Database Adapter
  74. */
  75. public function __construct($name, $options = array(), AdapterInterface $adapter = null)
  76. {
  77. $this->setName($name);
  78. $this->setOptions($options);
  79. if (null !== $adapter) {
  80. //echo 'Adapter definido';
  81. $this->setAdapter($adapter);
  82. }
  83. }
  84. /**
  85. * Sets the table name.
  86. *
  87. * @param string $name Table Name
  88. * @return Table
  89. */
  90. public function setName($name)
  91. {
  92. $this->name = $name;
  93. return $this;
  94. }
  95. /**
  96. * Gets the table name.
  97. *
  98. * @return string
  99. */
  100. public function getName()
  101. {
  102. return $this->name;
  103. }
  104. /**
  105. * Sets the table options.
  106. *
  107. * @param array $options
  108. * @return Table
  109. */
  110. public function setOptions($options)
  111. {
  112. $this->options = $options;
  113. return $this;
  114. }
  115. /**
  116. * Gets the table options.
  117. *
  118. * @return array
  119. */
  120. public function getOptions()
  121. {
  122. return $this->options;
  123. }
  124. /**
  125. * Sets the database adapter.
  126. *
  127. * @param AdapterInterface $adapter Database Adapter
  128. * @return Table
  129. */
  130. public function setAdapter(AdapterInterface $adapter)
  131. {
  132. $this->adapter = $adapter;
  133. return $this;
  134. }
  135. /**
  136. * Gets the database adapter.
  137. *
  138. * @return AdapterInterface
  139. */
  140. public function getAdapter()
  141. {
  142. return $this->adapter;
  143. }
  144. /**
  145. * Does the table exist?
  146. *
  147. * @return boolean
  148. */
  149. public function exists()
  150. {
  151. return $this->getAdapter()->hasTable($this->getName());
  152. }
  153. /**
  154. * Drops the database table.
  155. *
  156. * @return void
  157. */
  158. public function drop()
  159. {
  160. $this->getAdapter()->dropTable($this->getName());
  161. }
  162. /**
  163. * Renames the database table.
  164. *
  165. * @param string $newTableName New Table Name
  166. * @return Table
  167. */
  168. public function rename($newTableName)
  169. {
  170. $this->getAdapter()->renameTable($this->getName(), $newTableName);
  171. $this->setName($newTableName);
  172. return $this;
  173. }
  174. /**
  175. * Sets an array of columns waiting to be committed.
  176. * Use setPendingColumns
  177. *
  178. * @deprecated
  179. * @param array $columns Columns
  180. * @return Table
  181. */
  182. public function setColumns($columns)
  183. {
  184. $this->setPendingColumns($columns);
  185. }
  186. /**
  187. * Gets an array of the table columns.
  188. *
  189. * @return Column[]
  190. */
  191. public function getColumns()
  192. {
  193. return $this->getAdapter()->getColumns($this->getName());
  194. }
  195. /**
  196. * Sets an array of columns waiting to be committed.
  197. *
  198. * @param array $columns Columns
  199. * @return Table
  200. */
  201. public function setPendingColumns($columns)
  202. {
  203. $this->columns = $columns;
  204. return $this;
  205. }
  206. /**
  207. * Gets an array of columns waiting to be committed.
  208. *
  209. * @return Column[]
  210. */
  211. public function getPendingColumns()
  212. {
  213. return $this->columns;
  214. }
  215. /**
  216. * Sets an array of columns waiting to be indexed.
  217. *
  218. * @param array $indexes Indexes
  219. * @return Table
  220. */
  221. public function setIndexes($indexes)
  222. {
  223. $this->indexes = $indexes;
  224. return $this;
  225. }
  226. /**
  227. * Gets an array of indexes waiting to be committed.
  228. *
  229. * @return array
  230. */
  231. public function getIndexes()
  232. {
  233. return $this->indexes;
  234. }
  235. /**
  236. * Sets an array of foreign keys waiting to be commited.
  237. *
  238. * @param ForeignKey[] $foreignKeys foreign keys
  239. * @return Table
  240. */
  241. public function setForeignKeys($foreignKeys)
  242. {
  243. $this->foreignKeys = $foreignKeys;
  244. return $this;
  245. }
  246. /**
  247. * Gets an array of foreign keys waiting to be commited.
  248. *
  249. * @return array|ForeignKey[]
  250. */
  251. public function getForeignKeys()
  252. {
  253. return $this->foreignKeys;
  254. }
  255. /**
  256. * Sets an array of data to be inserted.
  257. *
  258. * @param array $data Data
  259. * @return Table
  260. */
  261. public function setData($data)
  262. {
  263. $this->data = $data;
  264. return $this;
  265. }
  266. /**
  267. * Gets the data waiting to be inserted.
  268. *
  269. * @return array
  270. */
  271. public function getData()
  272. {
  273. return $this->data;
  274. }
  275. /**
  276. * Resets all of the pending table changes.
  277. *
  278. * @return void
  279. */
  280. public function reset()
  281. {
  282. $this->setPendingColumns(array());
  283. $this->setIndexes(array());
  284. $this->setForeignKeys(array());
  285. $this->setData(array());
  286. }
  287. /**
  288. * Add a table column.
  289. *
  290. * Type can be: string, text, integer, float, decimal, datetime, timestamp,
  291. * time, date, binary, boolean.
  292. *
  293. * Valid options can be: limit, default, null, precision or scale.
  294. *
  295. * @param string|Column $columnName Column Name
  296. * @param string $type Column Type
  297. * @param array $options Column Options
  298. * @throws \RuntimeException
  299. * @throws \InvalidArgumentException
  300. * @return Table
  301. */
  302. public function addColumn($columnName, $type = null, $options = array())
  303. {
  304. // we need an adapter set to add a column
  305. if (null === $this->getAdapter()) {
  306. throw new \RuntimeException('An adapter must be specified to add a column.');
  307. }
  308. // create a new column object if only strings were supplied
  309. if (!$columnName instanceof Column) {
  310. $column = new Column();
  311. $column->setName($columnName);
  312. $column->setType($type);
  313. $column->setOptions($options); // map options to column methods
  314. } else {
  315. $column = $columnName;
  316. }
  317. // Delegate to Adapters to check column type
  318. if (!$this->getAdapter()->isValidColumnType($column)) {
  319. throw new \InvalidArgumentException(sprintf(
  320. 'An invalid column type "%s" was specified for column "%s".',
  321. $column->getType(),
  322. $column->getName()
  323. ));
  324. }
  325. $this->columns[] = $column;
  326. return $this;
  327. }
  328. /**
  329. * Remove a table column.
  330. *
  331. * @param string $columnName Column Name
  332. * @return Table
  333. */
  334. public function removeColumn($columnName)
  335. {
  336. $this->getAdapter()->dropColumn($this->getName(), $columnName);
  337. return $this;
  338. }
  339. /**
  340. * Rename a table column.
  341. *
  342. * @param string $oldName Old Column Name
  343. * @param string $newName New Column Name
  344. * @return Table
  345. */
  346. public function renameColumn($oldName, $newName)
  347. {
  348. $this->getAdapter()->renameColumn($this->getName(), $oldName, $newName);
  349. return $this;
  350. }
  351. /**
  352. * Change a table column type.
  353. *
  354. * @param string $columnName Column Name
  355. * @param string|Column $newColumnType New Column Type
  356. * @param array $options Options
  357. * @return Table
  358. */
  359. public function changeColumn($columnName, $newColumnType, $options = array())
  360. {
  361. // create a column object if one wasn't supplied
  362. if (!$newColumnType instanceof Column) {
  363. $newColumn = new Column();
  364. $newColumn->setType($newColumnType);
  365. $newColumn->setOptions($options);
  366. } else {
  367. $newColumn = $newColumnType;
  368. }
  369. // if the name was omitted use the existing column name
  370. if (null === $newColumn->getName() || strlen($newColumn->getName()) === 0) {
  371. $newColumn->setName($columnName);
  372. }
  373. $this->getAdapter()->changeColumn($this->getName(), $columnName, $newColumn);
  374. return $this;
  375. }
  376. /**
  377. * Checks to see if a column exists.
  378. *
  379. * @param string $columnName Column Name
  380. * @param array $options Options
  381. * @return boolean
  382. */
  383. public function hasColumn($columnName, $options = array())
  384. {
  385. return $this->getAdapter()->hasColumn($this->getName(), $columnName, $options);
  386. }
  387. /**
  388. * Add an index to a database table.
  389. *
  390. * In $options you can specific unique = true/false or name (index name).
  391. *
  392. * @param string|array|Index $columns Table Column(s)
  393. * @param array $options Index Options
  394. * @return Table
  395. */
  396. public function addIndex($columns, $options = array())
  397. {
  398. // create a new index object if strings or an array of strings were supplied
  399. if (!$columns instanceof Index) {
  400. $index = new Index();
  401. if (is_string($columns)) {
  402. $columns = array($columns); // str to array
  403. }
  404. $index->setColumns($columns);
  405. $index->setOptions($options);
  406. } else {
  407. $index = $columns;
  408. }
  409. $this->indexes[] = $index;
  410. return $this;
  411. }
  412. /**
  413. * Removes the given index from a table.
  414. *
  415. * @param array $columns Columns
  416. * @param array $options Options
  417. * @return Table
  418. */
  419. public function removeIndex($columns, $options = array())
  420. {
  421. $this->getAdapter()->dropIndex($this->getName(), $columns, $options);
  422. return $this;
  423. }
  424. /**
  425. * Removes the given index identified by its name from a table.
  426. *
  427. * @param string $name Index name
  428. * @return Table
  429. */
  430. public function removeIndexByName($name)
  431. {
  432. $this->getAdapter()->dropIndexByName($this->getName(), $name);
  433. return $this;
  434. }
  435. /**
  436. * Checks to see if an index exists.
  437. *
  438. * @param string|array $columns Columns
  439. * @param array $options Options
  440. * @return boolean
  441. */
  442. public function hasIndex($columns, $options = array())
  443. {
  444. return $this->getAdapter()->hasIndex($this->getName(), $columns, $options);
  445. }
  446. /**
  447. * Add a foreign key to a database table.
  448. *
  449. * In $options you can specify on_delete|on_delete = cascade|no_action ..,
  450. * on_update, constraint = constraint name.
  451. *
  452. * @param string|array $columns Columns
  453. * @param string|Table $referencedTable Referenced Table
  454. * @param string|array $referencedColumns Referenced Columns
  455. * @param array $options Options
  456. * @return Table
  457. */
  458. public function addForeignKey($columns, $referencedTable, $referencedColumns = array('id'), $options = array())
  459. {
  460. if (is_string($referencedColumns)) {
  461. $referencedColumns = array($referencedColumns); // str to array
  462. }
  463. $fk = new ForeignKey();
  464. if ($referencedTable instanceof Table) {
  465. $fk->setReferencedTable($referencedTable);
  466. } else {
  467. $fk->setReferencedTable(new Table($referencedTable, array(), $this->adapter));
  468. }
  469. $fk->setColumns($columns)
  470. ->setReferencedColumns($referencedColumns)
  471. ->setOptions($options);
  472. $this->foreignKeys[] = $fk;
  473. return $this;
  474. }
  475. /**
  476. * Removes the given foreign key from the table.
  477. *
  478. * @param string|array $columns Column(s)
  479. * @param null|string $constraint Constraint names
  480. * @return Table
  481. */
  482. public function dropForeignKey($columns, $constraint = null)
  483. {
  484. if (is_string($columns)) {
  485. $columns = array($columns);
  486. }
  487. if ($constraint) {
  488. $this->getAdapter()->dropForeignKey($this->getName(), array(), $constraint);
  489. } else {
  490. $this->getAdapter()->dropForeignKey($this->getName(), $columns);
  491. }
  492. return $this;
  493. }
  494. /**
  495. * Checks to see if a foreign key exists.
  496. *
  497. * @param string|array $columns Column(s)
  498. * @param null|string $constraint Constraint names
  499. * @return boolean
  500. */
  501. public function hasForeignKey($columns, $constraint = null)
  502. {
  503. return $this->getAdapter()->hasForeignKey($this->getName(), $columns, $constraint);
  504. }
  505. /**
  506. * Add timestamp columns created_at and updated_at to the table.
  507. *
  508. * @param string $createdAtColumnName
  509. * @param string $updatedAtColumnName
  510. *
  511. * @return Table
  512. */
  513. public function addTimestamps($createdAtColumnName = 'created_at', $updatedAtColumnName = 'updated_at')
  514. {
  515. $createdAtColumnName = is_null($createdAtColumnName) ? 'created_at' : $createdAtColumnName;
  516. $updatedAtColumnName = is_null($updatedAtColumnName) ? 'updated_at' : $updatedAtColumnName;
  517. $this->addColumn($createdAtColumnName, 'timestamp', array(
  518. 'default' => 'CURRENT_TIMESTAMP',
  519. 'update' => ''
  520. ))
  521. ->addColumn($updatedAtColumnName, 'timestamp', array(
  522. 'null' => true,
  523. 'default' => null
  524. ));
  525. return $this;
  526. }
  527. /**
  528. * Insert data into the table.
  529. *
  530. * @param $data array of data in the form:
  531. * array(
  532. * array("col1" => "value1", "col2" => "anotherValue1"),
  533. * array("col2" => "value2", "col2" => "anotherValue2"),
  534. * )
  535. * or array("col1" => "value1", "col2" => "anotherValue1")
  536. *
  537. * @return Table
  538. */
  539. public function insert($data)
  540. {
  541. // handle array of array situations
  542. if (isset($data[0]) && is_array($data[0])) {
  543. foreach ($data as $row) {
  544. $this->data[] = $row;
  545. }
  546. return $this;
  547. }
  548. $this->data[] = $data;
  549. return $this;
  550. }
  551. /**
  552. * Creates a table from the object instance.
  553. *
  554. * @return void
  555. */
  556. public function create()
  557. {
  558. $this->getAdapter()->createTable($this);
  559. $this->saveData();
  560. $this->reset(); // reset pending changes
  561. }
  562. /**
  563. * Updates a table from the object instance.
  564. *
  565. * @throws \RuntimeException
  566. * @return void
  567. */
  568. public function update()
  569. {
  570. if (!$this->exists()) {
  571. throw new \RuntimeException('Cannot update a table that doesn\'t exist!');
  572. }
  573. // update table
  574. foreach ($this->getPendingColumns() as $column) {
  575. $this->getAdapter()->addColumn($this, $column);
  576. }
  577. foreach ($this->getIndexes() as $index) {
  578. $this->getAdapter()->addIndex($this, $index);
  579. }
  580. foreach ($this->getForeignKeys() as $foreignKey) {
  581. $this->getAdapter()->addForeignKey($this, $foreignKey);
  582. }
  583. $this->saveData();
  584. $this->reset(); // reset pending changes
  585. }
  586. /**
  587. * Commit the pending data waiting for insertion.
  588. *
  589. * @return void
  590. */
  591. public function saveData()
  592. {
  593. foreach ($this->getData() as $row) {
  594. $this->getAdapter()->insert($this, $row);
  595. }
  596. }
  597. /**
  598. * Commits the table changes.
  599. *
  600. * If the table doesn't exist it is created otherwise it is updated.
  601. *
  602. * @return void
  603. */
  604. public function save()
  605. {
  606. if ($this->exists()) {
  607. $this->update(); // update the table
  608. } else {
  609. $this->create(); // create the table
  610. }
  611. $this->reset(); // reset pending changes
  612. }
  613. }