SqlserverSchema.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Database\Schema;
  16. /**
  17. * Schema management/reflection features for SQLServer.
  18. */
  19. class SqlserverSchema extends BaseSchema
  20. {
  21. const DEFAULT_SCHEMA_NAME = 'dbo';
  22. /**
  23. * {@inheritDoc}
  24. */
  25. public function listTablesSql($config)
  26. {
  27. $sql = "SELECT TABLE_NAME
  28. FROM INFORMATION_SCHEMA.TABLES
  29. WHERE TABLE_SCHEMA = ?
  30. AND (TABLE_TYPE = 'BASE TABLE' OR TABLE_TYPE = 'VIEW')
  31. ORDER BY TABLE_NAME";
  32. $schema = empty($config['schema']) ? static::DEFAULT_SCHEMA_NAME : $config['schema'];
  33. return [$sql, [$schema]];
  34. }
  35. /**
  36. * {@inheritDoc}
  37. */
  38. public function describeColumnSql($tableName, $config)
  39. {
  40. $sql = "SELECT DISTINCT
  41. AC.column_id AS [column_id],
  42. AC.name AS [name],
  43. TY.name AS [type],
  44. AC.max_length AS [char_length],
  45. AC.precision AS [precision],
  46. AC.scale AS [scale],
  47. AC.is_identity AS [autoincrement],
  48. AC.is_nullable AS [null],
  49. OBJECT_DEFINITION(AC.default_object_id) AS [default],
  50. AC.collation_name AS [collation_name]
  51. FROM sys.[objects] T
  52. INNER JOIN sys.[schemas] S ON S.[schema_id] = T.[schema_id]
  53. INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id]
  54. INNER JOIN sys.[types] TY ON TY.[user_type_id] = AC.[user_type_id]
  55. WHERE T.[name] = ? AND S.[name] = ?
  56. ORDER BY column_id";
  57. $schema = empty($config['schema']) ? static::DEFAULT_SCHEMA_NAME : $config['schema'];
  58. return [$sql, [$tableName, $schema]];
  59. }
  60. /**
  61. * Convert a column definition to the abstract types.
  62. *
  63. * The returned type will be a type that
  64. * Cake\Database\Type can handle.
  65. *
  66. * @param string $col The column type
  67. * @param int|null $length the column length
  68. * @param int|null $precision The column precision
  69. * @param int|null $scale The column scale
  70. * @return array Array of column information.
  71. * @link http://technet.microsoft.com/en-us/library/ms187752.aspx
  72. */
  73. protected function _convertColumn($col, $length = null, $precision = null, $scale = null)
  74. {
  75. $col = strtolower($col);
  76. if (in_array($col, ['date', 'time'])) {
  77. return ['type' => $col, 'length' => null];
  78. }
  79. if (strpos($col, 'datetime') !== false) {
  80. return ['type' => 'timestamp', 'length' => null];
  81. }
  82. if ($col === 'int' || $col === 'integer') {
  83. return ['type' => 'integer', 'length' => $precision ?: 10];
  84. }
  85. if ($col === 'bigint') {
  86. return ['type' => 'biginteger', 'length' => $precision ?: 20];
  87. }
  88. if ($col === 'smallint') {
  89. return ['type' => 'integer', 'length' => $precision ?: 5];
  90. }
  91. if ($col === 'tinyint') {
  92. return ['type' => 'integer', 'length' => $precision ?: 3];
  93. }
  94. if ($col === 'bit') {
  95. return ['type' => 'boolean', 'length' => null];
  96. }
  97. if (strpos($col, 'numeric') !== false ||
  98. strpos($col, 'money') !== false ||
  99. strpos($col, 'decimal') !== false
  100. ) {
  101. return ['type' => 'decimal', 'length' => $precision, 'precision' => $scale];
  102. }
  103. if ($col === 'real' || $col === 'float') {
  104. return ['type' => 'float', 'length' => null];
  105. }
  106. if (strpos($col, 'varchar') !== false && $length < 0) {
  107. return ['type' => 'text', 'length' => null];
  108. }
  109. if (strpos($col, 'varchar') !== false) {
  110. return ['type' => 'string', 'length' => $length ?: 255];
  111. }
  112. if (strpos($col, 'char') !== false) {
  113. return ['type' => 'string', 'fixed' => true, 'length' => $length];
  114. }
  115. if (strpos($col, 'text') !== false) {
  116. return ['type' => 'text', 'length' => null];
  117. }
  118. if ($col === 'image' || strpos($col, 'binary')) {
  119. return ['type' => 'binary', 'length' => null];
  120. }
  121. if ($col === 'uniqueidentifier') {
  122. return ['type' => 'uuid'];
  123. }
  124. return ['type' => 'text', 'length' => null];
  125. }
  126. /**
  127. * {@inheritDoc}
  128. */
  129. public function convertColumnDescription(Table $table, $row)
  130. {
  131. $field = $this->_convertColumn(
  132. $row['type'],
  133. $row['char_length'],
  134. $row['precision'],
  135. $row['scale']
  136. );
  137. if (!empty($row['default'])) {
  138. $row['default'] = trim($row['default'], '()');
  139. }
  140. if (!empty($row['autoincrement'])) {
  141. $field['autoIncrement'] = true;
  142. }
  143. if ($field['type'] === 'boolean') {
  144. $row['default'] = (int)$row['default'];
  145. }
  146. $field += [
  147. 'null' => $row['null'] === '1' ? true : false,
  148. 'default' => $this->_defaultValue($row['default']),
  149. 'collate' => $row['collation_name'],
  150. ];
  151. $table->addColumn($row['name'], $field);
  152. }
  153. /**
  154. * Manipulate the default value.
  155. *
  156. * Sqlite includes quotes and bared NULLs in default values.
  157. * We need to remove those.
  158. *
  159. * @param string|null $default The default value.
  160. * @return string|null
  161. */
  162. protected function _defaultValue($default)
  163. {
  164. if ($default === 'NULL') {
  165. return null;
  166. }
  167. // Remove quotes
  168. if (preg_match("/^N?'(.*)'/", $default, $matches)) {
  169. return str_replace("''", "'", $matches[1]);
  170. }
  171. return $default;
  172. }
  173. /**
  174. * {@inheritDoc}
  175. */
  176. public function describeIndexSql($tableName, $config)
  177. {
  178. $sql = "SELECT
  179. I.[name] AS [index_name],
  180. IC.[index_column_id] AS [index_order],
  181. AC.[name] AS [column_name],
  182. I.[is_unique], I.[is_primary_key],
  183. I.[is_unique_constraint]
  184. FROM sys.[tables] AS T
  185. INNER JOIN sys.[schemas] S ON S.[schema_id] = T.[schema_id]
  186. INNER JOIN sys.[indexes] I ON T.[object_id] = I.[object_id]
  187. INNER JOIN sys.[index_columns] IC ON I.[object_id] = IC.[object_id] AND I.[index_id] = IC.[index_id]
  188. INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id] AND IC.[column_id] = AC.[column_id]
  189. WHERE T.[is_ms_shipped] = 0 AND I.[type_desc] <> 'HEAP' AND T.[name] = ? AND S.[name] = ?
  190. ORDER BY I.[index_id], IC.[index_column_id]";
  191. $schema = empty($config['schema']) ? static::DEFAULT_SCHEMA_NAME : $config['schema'];
  192. return [$sql, [$tableName, $schema]];
  193. }
  194. /**
  195. * {@inheritDoc}
  196. */
  197. public function convertIndexDescription(Table $table, $row)
  198. {
  199. $type = Table::INDEX_INDEX;
  200. $name = $row['index_name'];
  201. if ($row['is_primary_key']) {
  202. $name = $type = Table::CONSTRAINT_PRIMARY;
  203. }
  204. if ($row['is_unique_constraint'] && $type === Table::INDEX_INDEX) {
  205. $type = Table::CONSTRAINT_UNIQUE;
  206. }
  207. if ($type === Table::INDEX_INDEX) {
  208. $existing = $table->index($name);
  209. } else {
  210. $existing = $table->constraint($name);
  211. }
  212. $columns = [$row['column_name']];
  213. if (!empty($existing)) {
  214. $columns = array_merge($existing['columns'], $columns);
  215. }
  216. if ($type === Table::CONSTRAINT_PRIMARY || $type === Table::CONSTRAINT_UNIQUE) {
  217. $table->addConstraint($name, [
  218. 'type' => $type,
  219. 'columns' => $columns
  220. ]);
  221. return;
  222. }
  223. $table->addIndex($name, [
  224. 'type' => $type,
  225. 'columns' => $columns
  226. ]);
  227. }
  228. /**
  229. * {@inheritDoc}
  230. */
  231. public function describeForeignKeySql($tableName, $config)
  232. {
  233. $sql = "SELECT FK.[name] AS [foreign_key_name], FK.[delete_referential_action_desc] AS [delete_type],
  234. FK.[update_referential_action_desc] AS [update_type], C.name AS [column], RT.name AS [reference_table],
  235. RC.name AS [reference_column]
  236. FROM sys.foreign_keys FK
  237. INNER JOIN sys.foreign_key_columns FKC ON FKC.constraint_object_id = FK.object_id
  238. INNER JOIN sys.tables T ON T.object_id = FKC.parent_object_id
  239. INNER JOIN sys.tables RT ON RT.object_id = FKC.referenced_object_id
  240. INNER JOIN sys.schemas S ON S.schema_id = T.schema_id AND S.schema_id = RT.schema_id
  241. INNER JOIN sys.columns C ON C.column_id = FKC.parent_column_id AND C.object_id = FKC.parent_object_id
  242. INNER JOIN sys.columns RC ON RC.column_id = FKC.referenced_column_id AND RC.object_id = FKC.referenced_object_id
  243. WHERE FK.is_ms_shipped = 0 AND T.name = ? AND S.name = ?";
  244. $schema = empty($config['schema']) ? static::DEFAULT_SCHEMA_NAME : $config['schema'];
  245. return [$sql, [$tableName, $schema]];
  246. }
  247. /**
  248. * {@inheritDoc}
  249. */
  250. public function convertForeignKeyDescription(Table $table, $row)
  251. {
  252. $data = [
  253. 'type' => Table::CONSTRAINT_FOREIGN,
  254. 'columns' => [$row['column']],
  255. 'references' => [$row['reference_table'], $row['reference_column']],
  256. 'update' => $this->_convertOnClause($row['update_type']),
  257. 'delete' => $this->_convertOnClause($row['delete_type']),
  258. ];
  259. $name = $row['foreign_key_name'];
  260. $table->addConstraint($name, $data);
  261. }
  262. /**
  263. * {@inheritDoc}
  264. */
  265. protected function _foreignOnClause($on)
  266. {
  267. $parent = parent::_foreignOnClause($on);
  268. return $parent === 'RESTRICT' ? parent::_foreignOnClause(Table::ACTION_SET_NULL) : $parent;
  269. }
  270. /**
  271. * {@inheritDoc}
  272. */
  273. protected function _convertOnClause($clause)
  274. {
  275. switch ($clause) {
  276. case 'NO_ACTION':
  277. return Table::ACTION_NO_ACTION;
  278. case 'CASCADE':
  279. return Table::ACTION_CASCADE;
  280. case 'SET_NULL':
  281. return Table::ACTION_SET_NULL;
  282. case 'SET_DEFAULT':
  283. return Table::ACTION_SET_DEFAULT;
  284. }
  285. return Table::ACTION_SET_NULL;
  286. }
  287. /**
  288. * {@inheritDoc}
  289. */
  290. public function columnSql(Table $table, $name)
  291. {
  292. $data = $table->column($name);
  293. $out = $this->_driver->quoteIdentifier($name);
  294. $typeMap = [
  295. 'integer' => ' INTEGER',
  296. 'biginteger' => ' BIGINT',
  297. 'boolean' => ' BIT',
  298. 'float' => ' FLOAT',
  299. 'decimal' => ' DECIMAL',
  300. 'date' => ' DATE',
  301. 'time' => ' TIME',
  302. 'datetime' => ' DATETIME',
  303. 'timestamp' => ' DATETIME',
  304. 'uuid' => ' UNIQUEIDENTIFIER',
  305. 'json' => ' NVARCHAR(MAX)',
  306. ];
  307. if (isset($typeMap[$data['type']])) {
  308. $out .= $typeMap[$data['type']];
  309. }
  310. if ($data['type'] === 'integer' || $data['type'] === 'biginteger') {
  311. if ([$name] === $table->primaryKey() || $data['autoIncrement'] === true) {
  312. unset($data['null'], $data['default']);
  313. $out .= ' IDENTITY(1, 1)';
  314. }
  315. }
  316. if ($data['type'] === 'text' && $data['length'] !== Table::LENGTH_TINY) {
  317. $out .= ' NVARCHAR(MAX)';
  318. }
  319. if ($data['type'] === 'binary') {
  320. $out .= ' VARBINARY';
  321. if ($data['length'] !== Table::LENGTH_TINY) {
  322. $out .= '(MAX)';
  323. } else {
  324. $out .= sprintf('(%s)', Table::LENGTH_TINY);
  325. }
  326. }
  327. if ($data['type'] === 'string' || ($data['type'] === 'text' && $data['length'] === Table::LENGTH_TINY)) {
  328. $type = ' NVARCHAR';
  329. if (!empty($data['fixed'])) {
  330. $type = ' NCHAR';
  331. }
  332. if (!isset($data['length'])) {
  333. $data['length'] = 255;
  334. }
  335. $out .= sprintf('%s(%d)', $type, $data['length']);
  336. }
  337. $hasCollate = ['text', 'string'];
  338. if (in_array($data['type'], $hasCollate, true) && isset($data['collate']) && $data['collate'] !== '') {
  339. $out .= ' COLLATE ' . $data['collate'];
  340. }
  341. if ($data['type'] === 'float' && isset($data['precision'])) {
  342. $out .= '(' . (int)$data['precision'] . ')';
  343. }
  344. if ($data['type'] === 'decimal' &&
  345. (isset($data['length']) || isset($data['precision']))
  346. ) {
  347. $out .= '(' . (int)$data['length'] . ',' . (int)$data['precision'] . ')';
  348. }
  349. if (isset($data['null']) && $data['null'] === false) {
  350. $out .= ' NOT NULL';
  351. } elseif (isset($data['null']) && $data['null'] === true) {
  352. $out .= ' NULL';
  353. }
  354. if (isset($data['default']) &&
  355. in_array($data['type'], ['timestamp', 'datetime']) &&
  356. strtolower($data['default']) === 'current_timestamp') {
  357. $out .= ' DEFAULT CURRENT_TIMESTAMP';
  358. } elseif (isset($data['default'])) {
  359. $default = is_bool($data['default']) ? (int)$data['default'] : $this->_driver->schemaValue($data['default']);
  360. $out .= ' DEFAULT ' . $default;
  361. } elseif (isset($data['null']) && $data['null'] === true) {
  362. $out .= ' DEFAULT NULL';
  363. }
  364. return $out;
  365. }
  366. /**
  367. * {@inheritDoc}
  368. */
  369. public function addConstraintSql(Table $table)
  370. {
  371. $sqlPattern = 'ALTER TABLE %s ADD %s;';
  372. $sql = [];
  373. foreach ($table->constraints() as $name) {
  374. $constraint = $table->constraint($name);
  375. if ($constraint['type'] === Table::CONSTRAINT_FOREIGN) {
  376. $tableName = $this->_driver->quoteIdentifier($table->name());
  377. $sql[] = sprintf($sqlPattern, $tableName, $this->constraintSql($table, $name));
  378. }
  379. }
  380. return $sql;
  381. }
  382. /**
  383. * {@inheritDoc}
  384. */
  385. public function dropConstraintSql(Table $table)
  386. {
  387. $sqlPattern = 'ALTER TABLE %s DROP CONSTRAINT %s;';
  388. $sql = [];
  389. foreach ($table->constraints() as $name) {
  390. $constraint = $table->constraint($name);
  391. if ($constraint['type'] === Table::CONSTRAINT_FOREIGN) {
  392. $tableName = $this->_driver->quoteIdentifier($table->name());
  393. $constraintName = $this->_driver->quoteIdentifier($name);
  394. $sql[] = sprintf($sqlPattern, $tableName, $constraintName);
  395. }
  396. }
  397. return $sql;
  398. }
  399. /**
  400. * {@inheritDoc}
  401. */
  402. public function indexSql(Table $table, $name)
  403. {
  404. $data = $table->index($name);
  405. $columns = array_map(
  406. [$this->_driver, 'quoteIdentifier'],
  407. $data['columns']
  408. );
  409. return sprintf(
  410. 'CREATE INDEX %s ON %s (%s)',
  411. $this->_driver->quoteIdentifier($name),
  412. $this->_driver->quoteIdentifier($table->name()),
  413. implode(', ', $columns)
  414. );
  415. }
  416. /**
  417. * {@inheritDoc}
  418. */
  419. public function constraintSql(Table $table, $name)
  420. {
  421. $data = $table->constraint($name);
  422. $out = 'CONSTRAINT ' . $this->_driver->quoteIdentifier($name);
  423. if ($data['type'] === Table::CONSTRAINT_PRIMARY) {
  424. $out = 'PRIMARY KEY';
  425. }
  426. if ($data['type'] === Table::CONSTRAINT_UNIQUE) {
  427. $out .= ' UNIQUE';
  428. }
  429. return $this->_keySql($out, $data);
  430. }
  431. /**
  432. * Helper method for generating key SQL snippets.
  433. *
  434. * @param string $prefix The key prefix
  435. * @param array $data Key data.
  436. * @return string
  437. */
  438. protected function _keySql($prefix, $data)
  439. {
  440. $columns = array_map(
  441. [$this->_driver, 'quoteIdentifier'],
  442. $data['columns']
  443. );
  444. if ($data['type'] === Table::CONSTRAINT_FOREIGN) {
  445. return $prefix . sprintf(
  446. ' FOREIGN KEY (%s) REFERENCES %s (%s) ON UPDATE %s ON DELETE %s',
  447. implode(', ', $columns),
  448. $this->_driver->quoteIdentifier($data['references'][0]),
  449. $this->_convertConstraintColumns($data['references'][1]),
  450. $this->_foreignOnClause($data['update']),
  451. $this->_foreignOnClause($data['delete'])
  452. );
  453. }
  454. return $prefix . ' (' . implode(', ', $columns) . ')';
  455. }
  456. /**
  457. * {@inheritDoc}
  458. */
  459. public function createTableSql(Table $table, $columns, $constraints, $indexes)
  460. {
  461. $content = array_merge($columns, $constraints);
  462. $content = implode(",\n", array_filter($content));
  463. $tableName = $this->_driver->quoteIdentifier($table->name());
  464. $out = [];
  465. $out[] = sprintf("CREATE TABLE %s (\n%s\n)", $tableName, $content);
  466. foreach ($indexes as $index) {
  467. $out[] = $index;
  468. }
  469. return $out;
  470. }
  471. /**
  472. * {@inheritDoc}
  473. */
  474. public function truncateTableSql(Table $table)
  475. {
  476. $name = $this->_driver->quoteIdentifier($table->name());
  477. $queries = [
  478. sprintf('DELETE FROM %s', $name)
  479. ];
  480. // Restart identity sequences
  481. $pk = $table->primaryKey();
  482. if (count($pk) === 1) {
  483. $column = $table->column($pk[0]);
  484. if (in_array($column['type'], ['integer', 'biginteger'])) {
  485. $queries[] = sprintf(
  486. "DBCC CHECKIDENT('%s', RESEED, 0)",
  487. $table->name()
  488. );
  489. }
  490. }
  491. return $queries;
  492. }
  493. }