SqlServerAdapter.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  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\Adapter
  28. */
  29. namespace BBDDL\Db\Adapter;
  30. use BBDDL\Db\Table;
  31. use BBDDL\Db\Table\Column;
  32. use BBDDL\Db\Table\Index;
  33. use BBDDL\Db\Table\ForeignKey;
  34. /**
  35. * Phinx SqlServer Adapter.
  36. *
  37. * @author Rob Morgan <robbym@gmail.com>
  38. */
  39. class SqlServerAdapter extends PdoAdapter implements AdapterInterface
  40. {
  41. protected $schema = 'dbo';
  42. protected $signedColumnTypes = array('integer' => true, 'biginteger' => true, 'float' => true, 'decimal' => true);
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function connect()
  47. {
  48. if (null === $this->connection) {
  49. if (!class_exists('PDO') || !in_array('sqlsrv', \PDO::getAvailableDrivers(), true)) {
  50. // try our connection via freetds (Mac/Linux)
  51. return $this->connectDblib();
  52. }
  53. $db = null;
  54. $options = $this->getOptions();
  55. // if port is specified use it, otherwise use the SqlServer default
  56. if (empty($options['port'])) {
  57. $dsn = 'sqlsrv:server=' . $options['host'] . ';database=' . $options['name'];
  58. } else {
  59. $dsn = 'sqlsrv:server=' . $options['host'] . ',' . $options['port'] . ';database=' . $options['name'];
  60. }
  61. $dsn .= ';MultipleActiveResultSets=false';
  62. $driverOptions = array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION);
  63. // charset support
  64. if (isset($options['charset'])) {
  65. $driverOptions[\PDO::SQLSRV_ATTR_ENCODING] = $options['charset'];
  66. }
  67. // support arbitrary \PDO::SQLSRV_ATTR_* driver options and pass them to PDO
  68. // http://php.net/manual/en/ref.pdo-sqlsrv.php#pdo-sqlsrv.constants
  69. foreach ($options as $key => $option) {
  70. if (strpos($key, 'sqlsrv_attr_') === 0) {
  71. $driverOptions[constant('\PDO::' . strtoupper($key))] = $option;
  72. }
  73. }
  74. try {
  75. $db = new \PDO($dsn, $options['user'], $options['pass'], $driverOptions);
  76. } catch (\PDOException $exception) {
  77. throw new \InvalidArgumentException(sprintf(
  78. 'There was a problem connecting to the database: %s',
  79. $exception->getMessage()
  80. ));
  81. }
  82. $this->setConnection($db);
  83. }
  84. }
  85. /**
  86. * Connect to MSSQL using dblib/freetds.
  87. *
  88. * The "sqlsrv" driver is not available on Unix machines.
  89. *
  90. * @throws \InvalidArgumentException
  91. */
  92. protected function connectDblib()
  93. {
  94. if (!class_exists('PDO') || !in_array('dblib', \PDO::getAvailableDrivers(), true)) {
  95. // @codeCoverageIgnoreStart
  96. throw new \RuntimeException('You need to enable the PDO_Dblib extension for Phinx to run properly.');
  97. // @codeCoverageIgnoreEnd
  98. }
  99. $options = $this->getOptions();
  100. // if port is specified use it, otherwise use the SqlServer default
  101. if (empty($options['port'])) {
  102. $dsn = 'dblib:host=' . $options['host'] . ';dbname=' . $options['name'];
  103. } else {
  104. $dsn = 'dblib:host=' . $options['host'] . ':' . $options['port'] . ';dbname=' . $options['name'];
  105. }
  106. $driverOptions = array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION);
  107. try {
  108. $db = new \PDO($dsn, $options['user'], $options['pass'], $driverOptions);
  109. } catch (\PDOException $exception) {
  110. throw new \InvalidArgumentException(sprintf(
  111. 'There was a problem connecting to the database: %s',
  112. $exception->getMessage()
  113. ));
  114. }
  115. $this->setConnection($db);
  116. }
  117. /**
  118. * {@inheritdoc}
  119. */
  120. public function disconnect()
  121. {
  122. $this->connection = null;
  123. }
  124. /**
  125. * {@inheritdoc}
  126. */
  127. public function hasTransactions()
  128. {
  129. return true;
  130. }
  131. /**
  132. * {@inheritdoc}
  133. */
  134. public function beginTransaction()
  135. {
  136. $this->execute('BEGIN TRANSACTION');
  137. }
  138. /**
  139. * {@inheritdoc}
  140. */
  141. public function commitTransaction()
  142. {
  143. $this->execute('COMMIT TRANSACTION');
  144. }
  145. /**
  146. * {@inheritdoc}
  147. */
  148. public function rollbackTransaction()
  149. {
  150. $this->execute('ROLLBACK TRANSACTION');
  151. }
  152. /**
  153. * {@inheritdoc}
  154. */
  155. public function quoteTableName($tableName)
  156. {
  157. return str_replace('.', '].[', $this->quoteColumnName($tableName));
  158. }
  159. /**
  160. * {@inheritdoc}
  161. */
  162. public function quoteColumnName($columnName)
  163. {
  164. return '[' . str_replace(']', '\]', $columnName) . ']';
  165. }
  166. /**
  167. * {@inheritdoc}
  168. */
  169. public function hasTable($tableName)
  170. {
  171. $result = $this->fetchRow(sprintf('SELECT count(*) as [count] FROM information_schema.tables WHERE table_name = \'%s\';', $tableName));
  172. return $result['count'] > 0;
  173. }
  174. /**
  175. * {@inheritdoc}
  176. */
  177. public function createTable(Table $table)
  178. {
  179. $this->startCommandTimer();
  180. $options = $table->getOptions();
  181. // Add the default primary key
  182. $columns = $table->getPendingColumns();
  183. if (!isset($options['id']) || (isset($options['id']) && $options['id'] === true)) {
  184. $column = new Column();
  185. $column->setName('id')
  186. ->setType('integer')
  187. ->setIdentity(true);
  188. array_unshift($columns, $column);
  189. $options['primary_key'] = 'id';
  190. } elseif (isset($options['id']) && is_string($options['id'])) {
  191. // Handle id => "field_name" to support AUTO_INCREMENT
  192. $column = new Column();
  193. $column->setName($options['id'])
  194. ->setType('integer')
  195. ->setIdentity(true);
  196. array_unshift($columns, $column);
  197. $options['primary_key'] = $options['id'];
  198. }
  199. $sql = 'CREATE TABLE ';
  200. $sql .= $this->quoteTableName($table->getName()) . ' (';
  201. $sqlBuffer = array();
  202. $columnsWithComments = array();
  203. foreach ($columns as $column) {
  204. $sqlBuffer[] = $this->quoteColumnName($column->getName()) . ' ' . $this->getColumnSqlDefinition($column);
  205. // set column comments, if needed
  206. if ($column->getComment()) {
  207. $columnsWithComments[] = $column;
  208. }
  209. }
  210. // set the primary key(s)
  211. if (isset($options['primary_key'])) {
  212. $pkSql = sprintf('CONSTRAINT PK_%s PRIMARY KEY (', $table->getName());
  213. if (is_string($options['primary_key'])) { // handle primary_key => 'id'
  214. $pkSql .= $this->quoteColumnName($options['primary_key']);
  215. } elseif (is_array($options['primary_key'])) { // handle primary_key => array('tag_id', 'resource_id')
  216. // PHP 5.4 will allow access of $this, so we can call quoteColumnName() directly in the anonymous function,
  217. // but for now just hard-code the adapter quotes
  218. $pkSql .= implode(
  219. ',',
  220. array_map(
  221. function ($v) {
  222. return '[' . $v . ']';
  223. },
  224. $options['primary_key']
  225. )
  226. );
  227. }
  228. $pkSql .= ')';
  229. $sqlBuffer[] = $pkSql;
  230. }
  231. // set the foreign keys
  232. $foreignKeys = $table->getForeignKeys();
  233. if (!empty($foreignKeys)) {
  234. foreach ($foreignKeys as $foreignKey) {
  235. $sqlBuffer[] = $this->getForeignKeySqlDefinition($foreignKey, $table->getName());
  236. }
  237. }
  238. $sql .= implode(', ', $sqlBuffer);
  239. $sql .= ');';
  240. // process column comments
  241. if (!empty($columnsWithComments)) {
  242. foreach ($columnsWithComments as $column) {
  243. $sql .= $this->getColumnCommentSqlDefinition($column, $table->getName());
  244. }
  245. }
  246. // set the indexes
  247. $indexes = $table->getIndexes();
  248. if (!empty($indexes)) {
  249. foreach ($indexes as $index) {
  250. $sql .= $this->getIndexSqlDefinition($index, $table->getName());
  251. }
  252. }
  253. // execute the sql
  254. $this->writeCommand('createTable', array($table->getName()));
  255. $this->execute($sql);
  256. $this->endCommandTimer();
  257. }
  258. /**
  259. * Gets the SqlServer Column Comment Defininition for a column object.
  260. *
  261. * @param Column $column Column
  262. * @param string $tableName Table name
  263. *
  264. * @return string
  265. */
  266. protected function getColumnCommentSqlDefinition(Column $column, $tableName)
  267. {
  268. // passing 'null' is to remove column comment
  269. $currentComment = $this->getColumnComment($tableName, $column->getName());
  270. $comment = (strcasecmp($column->getComment(), 'NULL') !== 0) ? $this->getConnection()->quote($column->getComment()) : '\'\'';
  271. $command = $currentComment === false ? 'sp_addextendedproperty' : 'sp_updateextendedproperty';
  272. return sprintf(
  273. "EXECUTE %s N'MS_Description', N%s, N'SCHEMA', N'%s', N'TABLE', N'%s', N'COLUMN', N'%s';",
  274. $command,
  275. $comment,
  276. $this->schema,
  277. $tableName,
  278. $column->getName()
  279. );
  280. }
  281. /**
  282. * {@inheritdoc}
  283. */
  284. public function renameTable($tableName, $newTableName)
  285. {
  286. $this->startCommandTimer();
  287. $this->writeCommand('renameTable', array($tableName, $newTableName));
  288. $this->execute(sprintf('EXEC sp_rename \'%s\', \'%s\'', $tableName, $newTableName));
  289. $this->endCommandTimer();
  290. }
  291. /**
  292. * {@inheritdoc}
  293. */
  294. public function dropTable($tableName)
  295. {
  296. $this->startCommandTimer();
  297. $this->writeCommand('dropTable', array($tableName));
  298. $this->execute(sprintf('DROP TABLE %s', $this->quoteTableName($tableName)));
  299. $this->endCommandTimer();
  300. }
  301. public function getColumnComment($tableName, $columnName)
  302. {
  303. $sql = sprintf("SELECT cast(extended_properties.[value] as nvarchar(4000)) comment
  304. FROM sys.schemas
  305. INNER JOIN sys.tables
  306. ON schemas.schema_id = tables.schema_id
  307. INNER JOIN sys.columns
  308. ON tables.object_id = columns.object_id
  309. INNER JOIN sys.extended_properties
  310. ON tables.object_id = extended_properties.major_id
  311. AND columns.column_id = extended_properties.minor_id
  312. AND extended_properties.name = 'MS_Description'
  313. WHERE schemas.[name] = '%s' AND tables.[name] = '%s' AND columns.[name] = '%s'", $this->schema, $tableName, $columnName);
  314. $row = $this->fetchRow($sql);
  315. if ($row) {
  316. return $row['comment'];
  317. }
  318. return false;
  319. }
  320. /**
  321. * {@inheritdoc}
  322. */
  323. public function getColumns($tableName)
  324. {
  325. $columns = array();
  326. $sql = sprintf(
  327. "SELECT DISTINCT TABLE_SCHEMA AS [schema], TABLE_NAME as [table_name], COLUMN_NAME AS [name], DATA_TYPE AS [type],
  328. IS_NULLABLE AS [null], COLUMN_DEFAULT AS [default],
  329. CHARACTER_MAXIMUM_LENGTH AS [char_length],
  330. NUMERIC_PRECISION AS [precision],
  331. NUMERIC_SCALE AS [scale], ORDINAL_POSITION AS [ordinal_position],
  332. COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') as [identity]
  333. FROM INFORMATION_SCHEMA.COLUMNS
  334. WHERE TABLE_NAME = '%s'
  335. ORDER BY ordinal_position",
  336. $tableName
  337. );
  338. $rows = $this->fetchAll($sql);
  339. foreach ($rows as $columnInfo) {
  340. $column = new Column();
  341. $column->setName($columnInfo['name'])
  342. ->setType($this->getPhinxType($columnInfo['type']))
  343. ->setNull($columnInfo['null'] !== 'NO')
  344. ->setDefault($this->parseDefault($columnInfo['default']))
  345. ->setIdentity($columnInfo['identity'] === '1')
  346. ->setComment($this->getColumnComment($columnInfo['table_name'], $columnInfo['name']));
  347. if (!empty($columnInfo['char_length'])) {
  348. $column->setLimit($columnInfo['char_length']);
  349. }
  350. $columns[$columnInfo['name']] = $column;
  351. }
  352. return $columns;
  353. }
  354. protected function parseDefault($default)
  355. {
  356. $default = preg_replace(array("/\('(.*)'\)/", "/\(\((.*)\)\)/", "/\((.*)\)/"), '$1', $default);
  357. if (strtoupper($default) === 'NULL') {
  358. $default = null;
  359. } elseif (is_numeric($default)) {
  360. $default = (int) $default;
  361. }
  362. return $default;
  363. }
  364. /**
  365. * {@inheritdoc}
  366. */
  367. public function hasColumn($tableName, $columnName, $options = array())
  368. {
  369. $sql = sprintf(
  370. "SELECT count(*) as [count]
  371. FROM information_schema.columns
  372. WHERE table_name = '%s' AND column_name = '%s'",
  373. $tableName,
  374. $columnName
  375. );
  376. $result = $this->fetchRow($sql);
  377. return $result['count'] > 0;
  378. }
  379. /**
  380. * {@inheritdoc}
  381. */
  382. public function addColumn(Table $table, Column $column)
  383. {
  384. $this->startCommandTimer();
  385. $sql = sprintf(
  386. 'ALTER TABLE %s ADD %s %s',
  387. $this->quoteTableName($table->getName()),
  388. $this->quoteColumnName($column->getName()),
  389. $this->getColumnSqlDefinition($column)
  390. );
  391. $this->writeCommand('addColumn', array($table->getName(), $column->getName(), $column->getType()));
  392. $this->execute($sql);
  393. $this->endCommandTimer();
  394. }
  395. /**
  396. * {@inheritdoc}
  397. */
  398. public function renameColumn($tableName, $columnName, $newColumnName)
  399. {
  400. $this->startCommandTimer();
  401. if (!$this->hasColumn($tableName, $columnName)) {
  402. throw new \InvalidArgumentException("The specified column does not exist: $columnName");
  403. }
  404. $this->writeCommand('renameColumn', array($tableName, $columnName, $newColumnName));
  405. $this->renameDefault($tableName, $columnName, $newColumnName);
  406. $this->execute(
  407. sprintf(
  408. "EXECUTE sp_rename N'%s.%s', N'%s', 'COLUMN' ",
  409. $tableName,
  410. $columnName,
  411. $newColumnName
  412. )
  413. );
  414. $this->endCommandTimer();
  415. }
  416. protected function renameDefault($tableName, $columnName, $newColumnName)
  417. {
  418. $oldConstraintName = "DF_{$tableName}_{$columnName}";
  419. $newConstraintName = "DF_{$tableName}_{$newColumnName}";
  420. $sql = <<<SQL
  421. IF (OBJECT_ID('$oldConstraintName', 'D') IS NOT NULL)
  422. BEGIN
  423. EXECUTE sp_rename N'%s', N'%s', N'OBJECT'
  424. END
  425. SQL;
  426. $this->execute(sprintf(
  427. $sql,
  428. $oldConstraintName,
  429. $newConstraintName
  430. ));
  431. }
  432. public function changeDefault($tableName, Column $newColumn)
  433. {
  434. $constraintName = "DF_{$tableName}_{$newColumn->getName()}";
  435. $default = $newColumn->getDefault();
  436. if ($default === null) {
  437. $default = 'DEFAULT NULL';
  438. } else {
  439. $default = $this->getDefaultValueDefinition($default);
  440. }
  441. if (empty($default)) {
  442. return;
  443. }
  444. $this->execute(sprintf(
  445. 'ALTER TABLE %s ADD CONSTRAINT %s %s FOR %s',
  446. $this->quoteTableName($tableName),
  447. $constraintName,
  448. $default,
  449. $this->quoteColumnName($newColumn->getName())
  450. ));
  451. }
  452. /**
  453. * {@inheritdoc}
  454. */
  455. public function changeColumn($tableName, $columnName, Column $newColumn)
  456. {
  457. $this->startCommandTimer();
  458. $this->writeCommand('changeColumn', array($tableName, $columnName, $newColumn->getType()));
  459. $columns = $this->getColumns($tableName);
  460. $changeDefault = $newColumn->getDefault() !== $columns[$columnName]->getDefault() || $newColumn->getType() !== $columns[$columnName]->getType();
  461. if ($columnName !== $newColumn->getName()) {
  462. $this->renameColumn($tableName, $columnName, $newColumn->getName());
  463. }
  464. if ($changeDefault) {
  465. $this->dropDefaultConstraint($tableName, $newColumn->getName());
  466. }
  467. $this->execute(
  468. sprintf(
  469. 'ALTER TABLE %s ALTER COLUMN %s %s',
  470. $this->quoteTableName($tableName),
  471. $this->quoteColumnName($newColumn->getName()),
  472. $this->getColumnSqlDefinition($newColumn, false)
  473. )
  474. );
  475. // change column comment if needed
  476. if ($newColumn->getComment()) {
  477. $sql = $this->getColumnCommentSqlDefinition($newColumn, $tableName);
  478. $this->execute($sql);
  479. }
  480. if ($changeDefault) {
  481. $this->changeDefault($tableName, $newColumn);
  482. }
  483. $this->endCommandTimer();
  484. }
  485. /**
  486. * {@inheritdoc}
  487. */
  488. public function dropColumn($tableName, $columnName)
  489. {
  490. $this->startCommandTimer();
  491. $this->writeCommand('dropColumn', array($tableName, $columnName));
  492. $this->dropDefaultConstraint($tableName, $columnName);
  493. $this->execute(
  494. sprintf(
  495. 'ALTER TABLE %s DROP COLUMN %s',
  496. $this->quoteTableName($tableName),
  497. $this->quoteColumnName($columnName)
  498. )
  499. );
  500. $this->endCommandTimer();
  501. }
  502. protected function dropDefaultConstraint($tableName, $columnName)
  503. {
  504. $defaultConstraint = $this->getDefaultConstraint($tableName, $columnName);
  505. if (!$defaultConstraint) {
  506. return;
  507. }
  508. $this->dropForeignKey($tableName, $columnName, $defaultConstraint);
  509. }
  510. protected function getDefaultConstraint($tableName, $columnName)
  511. {
  512. $sql = "SELECT
  513. default_constraints.name
  514. FROM
  515. sys.all_columns
  516. INNER JOIN
  517. sys.tables
  518. ON all_columns.object_id = tables.object_id
  519. INNER JOIN
  520. sys.schemas
  521. ON tables.schema_id = schemas.schema_id
  522. INNER JOIN
  523. sys.default_constraints
  524. ON all_columns.default_object_id = default_constraints.object_id
  525. WHERE
  526. schemas.name = 'dbo'
  527. AND tables.name = '{$tableName}'
  528. AND all_columns.name = '{$columnName}'";
  529. $rows = $this->fetchAll($sql);
  530. return empty($rows) ? false : $rows[0]['name'];
  531. }
  532. protected function getIndexColums($tableId, $indexId)
  533. {
  534. $sql = "SELECT AC.[name] AS [column_name]
  535. FROM sys.[index_columns] IC
  536. INNER JOIN sys.[all_columns] AC ON IC.[column_id] = AC.[column_id]
  537. WHERE AC.[object_id] = {$tableId} AND IC.[index_id] = {$indexId} AND IC.[object_id] = {$tableId}
  538. ORDER BY IC.[key_ordinal];";
  539. $rows = $this->fetchAll($sql);
  540. $columns = array();
  541. foreach($rows as $row) {
  542. $columns[] = strtolower($row['column_name']);
  543. }
  544. return $columns;
  545. }
  546. /**
  547. * Get an array of indexes from a particular table.
  548. *
  549. * @param string $tableName Table Name
  550. * @return array
  551. */
  552. public function getIndexes($tableName)
  553. {
  554. $indexes = array();
  555. $sql = "SELECT I.[name] AS [index_name], I.[index_id] as [index_id], T.[object_id] as [table_id]
  556. FROM sys.[tables] AS T
  557. INNER JOIN sys.[indexes] I ON T.[object_id] = I.[object_id]
  558. WHERE T.[is_ms_shipped] = 0 AND I.[type_desc] <> 'HEAP' AND T.[name] = '{$tableName}'
  559. ORDER BY T.[name], I.[index_id];";
  560. $rows = $this->fetchAll($sql);
  561. foreach ($rows as $row) {
  562. $columns = $this->getIndexColums($row['table_id'], $row['index_id']);
  563. $indexes[$row['index_name']] = array('columns' => $columns);
  564. }
  565. return $indexes;
  566. }
  567. /**
  568. * {@inheritdoc}
  569. */
  570. public function hasIndex($tableName, $columns)
  571. {
  572. if (is_string($columns)) {
  573. $columns = array($columns); // str to array
  574. }
  575. $columns = array_map('strtolower', $columns);
  576. $indexes = $this->getIndexes($tableName);
  577. foreach ($indexes as $index) {
  578. $a = array_diff($columns, $index['columns']);
  579. if (empty($a)) {
  580. return true;
  581. }
  582. }
  583. return false;
  584. }
  585. /**
  586. * {@inheritdoc}
  587. */
  588. public function hasIndexByName($tableName, $indexName)
  589. {
  590. $indexes = $this->getIndexes($tableName);
  591. foreach ($indexes as $name => $index) {
  592. if ($name === $indexName) {
  593. return true;
  594. }
  595. }
  596. return false;
  597. }
  598. /**
  599. * {@inheritdoc}
  600. */
  601. public function addIndex(Table $table, Index $index)
  602. {
  603. $this->startCommandTimer();
  604. $this->writeCommand('addIndex', array($table->getName(), $index->getColumns()));
  605. $sql = $this->getIndexSqlDefinition($index, $table->getName());
  606. $this->execute($sql);
  607. $this->endCommandTimer();
  608. }
  609. /**
  610. * {@inheritdoc}
  611. */
  612. public function dropIndex($tableName, $columns)
  613. {
  614. $this->startCommandTimer();
  615. if (is_string($columns)) {
  616. $columns = array($columns); // str to array
  617. }
  618. $this->writeCommand('dropIndex', array($tableName, $columns));
  619. $indexes = $this->getIndexes($tableName);
  620. $columns = array_map('strtolower', $columns);
  621. foreach ($indexes as $indexName => $index) {
  622. $a = array_diff($columns, $index['columns']);
  623. if (empty($a)) {
  624. $this->execute(
  625. sprintf(
  626. 'DROP INDEX %s ON %s',
  627. $this->quoteColumnName($indexName),
  628. $this->quoteTableName($tableName)
  629. )
  630. );
  631. $this->endCommandTimer();
  632. return;
  633. }
  634. }
  635. }
  636. /**
  637. * {@inheritdoc}
  638. */
  639. public function dropIndexByName($tableName, $indexName)
  640. {
  641. $this->startCommandTimer();
  642. $this->writeCommand('dropIndexByName', array($tableName, $indexName));
  643. $indexes = $this->getIndexes($tableName);
  644. foreach ($indexes as $name => $index) {
  645. if ($name === $indexName) {
  646. $this->execute(
  647. sprintf(
  648. 'DROP INDEX %s ON %s',
  649. $this->quoteColumnName($indexName),
  650. $this->quoteTableName($tableName)
  651. )
  652. );
  653. $this->endCommandTimer();
  654. return;
  655. }
  656. }
  657. }
  658. /**
  659. * {@inheritdoc}
  660. */
  661. public function hasForeignKey($tableName, $columns, $constraint = null)
  662. {
  663. if (is_string($columns)) {
  664. $columns = array($columns); // str to array
  665. }
  666. $foreignKeys = $this->getForeignKeys($tableName);
  667. if ($constraint) {
  668. if (isset($foreignKeys[$constraint])) {
  669. return !empty($foreignKeys[$constraint]);
  670. }
  671. return false;
  672. } else {
  673. foreach ($foreignKeys as $key) {
  674. $a = array_diff($columns, $key['columns']);
  675. if (empty($a)) {
  676. return true;
  677. }
  678. }
  679. return false;
  680. }
  681. }
  682. /**
  683. * Get an array of foreign keys from a particular table.
  684. *
  685. * @param string $tableName Table Name
  686. * @return array
  687. */
  688. protected function getForeignKeys($tableName)
  689. {
  690. $foreignKeys = array();
  691. $rows = $this->fetchAll(sprintf(
  692. "SELECT
  693. tc.constraint_name,
  694. tc.table_name, kcu.column_name,
  695. ccu.table_name AS referenced_table_name,
  696. ccu.column_name AS referenced_column_name
  697. FROM
  698. information_schema.table_constraints AS tc
  699. JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name
  700. JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name
  701. WHERE constraint_type = 'FOREIGN KEY' AND tc.table_name = '%s'
  702. ORDER BY kcu.ordinal_position",
  703. $tableName
  704. ));
  705. foreach ($rows as $row) {
  706. $foreignKeys[$row['constraint_name']]['table'] = $row['table_name'];
  707. $foreignKeys[$row['constraint_name']]['columns'][] = $row['column_name'];
  708. $foreignKeys[$row['constraint_name']]['referenced_table'] = $row['referenced_table_name'];
  709. $foreignKeys[$row['constraint_name']]['referenced_columns'][] = $row['referenced_column_name'];
  710. }
  711. return $foreignKeys;
  712. }
  713. /**
  714. * {@inheritdoc}
  715. */
  716. public function addForeignKey(Table $table, ForeignKey $foreignKey)
  717. {
  718. $this->startCommandTimer();
  719. $this->writeCommand('addForeignKey', array($table->getName(), $foreignKey->getColumns()));
  720. $this->execute(
  721. sprintf(
  722. 'ALTER TABLE %s ADD %s',
  723. $this->quoteTableName($table->getName()),
  724. $this->getForeignKeySqlDefinition($foreignKey, $table->getName())
  725. )
  726. );
  727. $this->endCommandTimer();
  728. }
  729. /**
  730. * {@inheritdoc}
  731. */
  732. public function dropForeignKey($tableName, $columns, $constraint = null)
  733. {
  734. $this->startCommandTimer();
  735. if (is_string($columns)) {
  736. $columns = array($columns); // str to array
  737. }
  738. $this->writeCommand('dropForeignKey', array($tableName, $columns));
  739. if ($constraint) {
  740. $this->execute(
  741. sprintf(
  742. 'ALTER TABLE %s DROP CONSTRAINT %s',
  743. $this->quoteTableName($tableName),
  744. $constraint
  745. )
  746. );
  747. $this->endCommandTimer();
  748. return;
  749. } else {
  750. foreach ($columns as $column) {
  751. $rows = $this->fetchAll(sprintf(
  752. "SELECT
  753. tc.constraint_name,
  754. tc.table_name, kcu.column_name,
  755. ccu.table_name AS referenced_table_name,
  756. ccu.column_name AS referenced_column_name
  757. FROM
  758. information_schema.table_constraints AS tc
  759. JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name
  760. JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name
  761. WHERE constraint_type = 'FOREIGN KEY' AND tc.table_name = '%s' and ccu.column_name='%s'
  762. ORDER BY kcu.ordinal_position",
  763. $tableName,
  764. $column
  765. ));
  766. foreach ($rows as $row) {
  767. $this->dropForeignKey($tableName, $columns, $row['constraint_name']);
  768. }
  769. }
  770. }
  771. $this->endCommandTimer();
  772. }
  773. /**
  774. * {@inheritdoc}
  775. */
  776. public function getSqlType($type, $limit = null)
  777. {
  778. switch ($type) {
  779. case static::PHINX_TYPE_STRING:
  780. return array('name' => 'nvarchar', 'limit' => 255);
  781. break;
  782. case static::PHINX_TYPE_CHAR:
  783. return array('name' => 'nchar', 'limit' => 255);
  784. break;
  785. case static::PHINX_TYPE_TEXT:
  786. return array('name' => 'ntext');
  787. break;
  788. case static::PHINX_TYPE_INTEGER:
  789. return array('name' => 'int');
  790. break;
  791. case static::PHINX_TYPE_BIG_INTEGER:
  792. return array('name' => 'bigint');
  793. break;
  794. case static::PHINX_TYPE_FLOAT:
  795. return array('name' => 'float');
  796. break;
  797. case static::PHINX_TYPE_DECIMAL:
  798. return array('name' => 'decimal');
  799. break;
  800. case static::PHINX_TYPE_DATETIME:
  801. case static::PHINX_TYPE_TIMESTAMP:
  802. return array('name' => 'datetime');
  803. break;
  804. case static::PHINX_TYPE_TIME:
  805. return array('name' => 'time');
  806. break;
  807. case static::PHINX_TYPE_DATE:
  808. return array('name' => 'date');
  809. break;
  810. case static::PHINX_TYPE_BLOB:
  811. case static::PHINX_TYPE_BINARY:
  812. return array('name' => 'varbinary');
  813. break;
  814. case static::PHINX_TYPE_BOOLEAN:
  815. return array('name' => 'bit');
  816. break;
  817. case static::PHINX_TYPE_UUID:
  818. return array('name' => 'uniqueidentifier');
  819. case static::PHINX_TYPE_FILESTREAM:
  820. return array('name' => 'varbinary', 'limit' => 'max');
  821. // Geospatial database types
  822. case static::PHINX_TYPE_GEOMETRY:
  823. case static::PHINX_TYPE_POINT:
  824. case static::PHINX_TYPE_LINESTRING:
  825. case static::PHINX_TYPE_POLYGON:
  826. // SQL Server stores all spatial data using a single data type.
  827. // Specific types (point, polygon, etc) are set at insert time.
  828. return array('name' => 'geography');
  829. break;
  830. default:
  831. throw new \RuntimeException('The type: "' . $type . '" is not supported.');
  832. }
  833. }
  834. /**
  835. * Returns Phinx type by SQL type
  836. *
  837. * @param $sqlTypeDef
  838. * @throws \RuntimeException
  839. * @internal param string $sqlType SQL type
  840. * @returns string Phinx type
  841. */
  842. public function getPhinxType($sqlType)
  843. {
  844. switch ($sqlType) {
  845. case 'nvarchar':
  846. case 'varchar':
  847. return static::PHINX_TYPE_STRING;
  848. case 'char':
  849. case 'nchar':
  850. return static::PHINX_TYPE_CHAR;
  851. case 'text':
  852. case 'ntext':
  853. return static::PHINX_TYPE_TEXT;
  854. case 'int':
  855. case 'integer':
  856. return static::PHINX_TYPE_INTEGER;
  857. case 'decimal':
  858. case 'numeric':
  859. case 'money':
  860. return static::PHINX_TYPE_DECIMAL;
  861. case 'bigint':
  862. return static::PHINX_TYPE_BIG_INTEGER;
  863. case 'real':
  864. case 'float':
  865. return static::PHINX_TYPE_FLOAT;
  866. case 'binary':
  867. case 'image':
  868. case 'varbinary':
  869. return static::PHINX_TYPE_BINARY;
  870. break;
  871. case 'time':
  872. return static::PHINX_TYPE_TIME;
  873. case 'date':
  874. return static::PHINX_TYPE_DATE;
  875. case 'datetime':
  876. case 'timestamp':
  877. return static::PHINX_TYPE_DATETIME;
  878. case 'bit':
  879. return static::PHINX_TYPE_BOOLEAN;
  880. case 'uniqueidentifier':
  881. return static::PHINX_TYPE_UUID;
  882. case 'filestream':
  883. return static::PHINX_TYPE_FILESTREAM;
  884. default:
  885. throw new \RuntimeException('The SqlServer type: "' . $sqlType . '" is not supported');
  886. }
  887. }
  888. /**
  889. * {@inheritdoc}
  890. */
  891. public function createDatabase($name, $options = array())
  892. {
  893. $this->startCommandTimer();
  894. $this->writeCommand('createDatabase', array($name));
  895. if (isset($options['collation'])) {
  896. $this->execute(sprintf('CREATE DATABASE [%s] COLLATE [%s]', $name, $options['collation']));
  897. } else {
  898. $this->execute(sprintf('CREATE DATABASE [%s]', $name));
  899. }
  900. $this->execute(sprintf('USE [%s]', $name));
  901. $this->endCommandTimer();
  902. }
  903. /**
  904. * {@inheritdoc}
  905. */
  906. public function hasDatabase($name)
  907. {
  908. $result = $this->fetchRow(
  909. sprintf(
  910. 'SELECT count(*) as [count] FROM master.dbo.sysdatabases WHERE [name] = \'%s\'',
  911. $name
  912. )
  913. );
  914. return $result['count'] > 0;
  915. }
  916. /**
  917. * {@inheritdoc}
  918. */
  919. public function dropDatabase($name)
  920. {
  921. $this->startCommandTimer();
  922. $this->writeCommand('dropDatabase', array($name));
  923. $sql = <<<SQL
  924. USE master;
  925. IF EXISTS(select * from sys.databases where name=N'$name')
  926. ALTER DATABASE [$name] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  927. DROP DATABASE [$name];
  928. SQL;
  929. $this->execute($sql);
  930. $this->endCommandTimer();
  931. }
  932. /**
  933. * Get the defintion for a `DEFAULT` statement.
  934. *
  935. * @param mixed $default
  936. * @return string
  937. */
  938. protected function getDefaultValueDefinition($default)
  939. {
  940. if (is_string($default) && 'CURRENT_TIMESTAMP' !== $default) {
  941. $default = $this->getConnection()->quote($default);
  942. } elseif (is_bool($default)) {
  943. $default = $this->castToBool($default);
  944. }
  945. return isset($default) ? ' DEFAULT ' . $default : '';
  946. }
  947. /**
  948. * Gets the SqlServer Column Definition for a Column object.
  949. *
  950. * @param Column $column Column
  951. * @return string
  952. */
  953. protected function getColumnSqlDefinition(Column $column, $create = true)
  954. {
  955. $buffer = array();
  956. $sqlType = $this->getSqlType($column->getType());
  957. $buffer[] = strtoupper($sqlType['name']);
  958. // integers cant have limits in SQlServer
  959. $noLimits = array(
  960. 'bigint',
  961. 'int',
  962. 'tinyint'
  963. );
  964. if (!in_array($sqlType['name'], $noLimits) && ($column->getLimit() || isset($sqlType['limit']))) {
  965. $buffer[] = sprintf('(%s)', $column->getLimit() ? $column->getLimit() : $sqlType['limit']);
  966. }
  967. if ($column->getPrecision() && $column->getScale()) {
  968. $buffer[] = '(' . $column->getPrecision() . ',' . $column->getScale() . ')';
  969. }
  970. $properties = $column->getProperties();
  971. $buffer[] = $column->getType() === 'filestream' ? 'FILESTREAM' : '';
  972. $buffer[] = isset($properties['rowguidcol']) ? 'ROWGUIDCOL' : '';
  973. $buffer[] = $column->isNull() ? 'NULL' : 'NOT NULL';
  974. if ($create === true) {
  975. if ($column->getDefault() === null && $column->isNull()) {
  976. $buffer[] = ' DEFAULT NULL';
  977. } else {
  978. $buffer[] = $this->getDefaultValueDefinition($column->getDefault());
  979. }
  980. }
  981. if ($column->isIdentity()) {
  982. $buffer[] = 'IDENTITY(1, 1)';
  983. }
  984. return implode(' ', $buffer);
  985. }
  986. /**
  987. * Gets the SqlServer Index Definition for an Index object.
  988. *
  989. * @param Index $index Index
  990. * @return string
  991. */
  992. protected function getIndexSqlDefinition(Index $index, $tableName)
  993. {
  994. if (is_string($index->getName())) {
  995. $indexName = $index->getName();
  996. } else {
  997. $columnNames = $index->getColumns();
  998. if (is_string($columnNames)) {
  999. $columnNames = array($columnNames);
  1000. }
  1001. $indexName = sprintf('%s_%s', $tableName, implode('_', $columnNames));
  1002. }
  1003. $def = sprintf(
  1004. "CREATE %s INDEX %s ON %s (%s);",
  1005. ($index->getType() === Index::UNIQUE ? 'UNIQUE' : ''),
  1006. $indexName,
  1007. $this->quoteTableName($tableName),
  1008. '[' . implode('],[', $index->getColumns()) . ']'
  1009. );
  1010. return $def;
  1011. }
  1012. /**
  1013. * Gets the SqlServer Foreign Key Definition for an ForeignKey object.
  1014. *
  1015. * @param ForeignKey $foreignKey
  1016. * @return string
  1017. */
  1018. protected function getForeignKeySqlDefinition(ForeignKey $foreignKey, $tableName)
  1019. {
  1020. $def = ' CONSTRAINT "';
  1021. $def .= $tableName . '_' . implode('_', $foreignKey->getColumns());
  1022. $def .= '" FOREIGN KEY ("' . implode('", "', $foreignKey->getColumns()) . '")';
  1023. $def .= " REFERENCES {$this->quoteTableName($foreignKey->getReferencedTable()->getName())} (\"" . implode('", "', $foreignKey->getReferencedColumns()) . '")';
  1024. if ($foreignKey->getOnDelete()) {
  1025. $def .= " ON DELETE {$foreignKey->getOnDelete()}";
  1026. }
  1027. if ($foreignKey->getOnUpdate()) {
  1028. $def .= " ON UPDATE {$foreignKey->getOnUpdate()}";
  1029. }
  1030. return $def;
  1031. }
  1032. /**
  1033. * {@inheritdoc}
  1034. */
  1035. public function getColumnTypes()
  1036. {
  1037. return array_merge(parent::getColumnTypes(), array('filestream'));
  1038. }
  1039. }