SqlserverSchema.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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' => TableSchema::TYPE_TIMESTAMP, 'length' => null];
  81. }
  82. if ($col === 'tinyint') {
  83. return ['type' => TableSchema::TYPE_TINYINTEGER, 'length' => $precision ?: 3];
  84. }
  85. if ($col === 'smallint') {
  86. return ['type' => TableSchema::TYPE_SMALLINTEGER, 'length' => $precision ?: 5];
  87. }
  88. if ($col === 'int' || $col === 'integer') {
  89. return ['type' => TableSchema::TYPE_INTEGER, 'length' => $precision ?: 10];
  90. }
  91. if ($col === 'bigint') {
  92. return ['type' => TableSchema::TYPE_BIGINTEGER, 'length' => $precision ?: 20];
  93. }
  94. if ($col === 'bit') {
  95. return ['type' => TableSchema::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' => TableSchema::TYPE_DECIMAL, 'length' => $precision, 'precision' => $scale];
  102. }
  103. if ($col === 'real' || $col === 'float') {
  104. return ['type' => TableSchema::TYPE_FLOAT, 'length' => null];
  105. }
  106. if (strpos($col, 'varchar') !== false && $length < 0) {
  107. return ['type' => TableSchema::TYPE_TEXT, 'length' => null];
  108. }
  109. if (strpos($col, 'varchar') !== false) {
  110. return ['type' => TableSchema::TYPE_STRING, 'length' => $length ?: 255];
  111. }
  112. if (strpos($col, 'char') !== false) {
  113. return ['type' => TableSchema::TYPE_STRING, 'fixed' => true, 'length' => $length];
  114. }
  115. if (strpos($col, 'text') !== false) {
  116. return ['type' => TableSchema::TYPE_TEXT, 'length' => null];
  117. }
  118. if ($col === 'image' || strpos($col, 'binary')) {
  119. return ['type' => TableSchema::TYPE_BINARY, 'length' => null];
  120. }
  121. if ($col === 'uniqueidentifier') {
  122. return ['type' => TableSchema::TYPE_UUID];
  123. }
  124. return ['type' => TableSchema::TYPE_STRING, 'length' => null];
  125. }
  126. /**
  127. * {@inheritDoc}
  128. */
  129. public function convertColumnDescription(TableSchema $schema, $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'] === TableSchema::TYPE_BOOLEAN) {
  144. $row['default'] = (int)$row['default'];
  145. }
  146. $field += [
  147. 'null' => $row['null'] === '1',
  148. 'default' => $this->_defaultValue($row['default']),
  149. 'collate' => $row['collation_name'],
  150. ];
  151. $schema->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(TableSchema $schema, $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 = $schema->index($name);
  209. } else {
  210. $existing = $schema->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. $schema->addConstraint($name, [
  218. 'type' => $type,
  219. 'columns' => $columns
  220. ]);
  221. return;
  222. }
  223. $schema->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(TableSchema $schema, $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. $schema->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(TableSchema $schema, $name)
  291. {
  292. $data = $schema->column($name);
  293. $out = $this->_driver->quoteIdentifier($name);
  294. $typeMap = [
  295. TableSchema::TYPE_TINYINTEGER => ' TINYINT',
  296. TableSchema::TYPE_SMALLINTEGER => ' SMALLINT',
  297. TableSchema::TYPE_INTEGER => ' INTEGER',
  298. TableSchema::TYPE_BIGINTEGER => ' BIGINT',
  299. TableSchema::TYPE_BOOLEAN => ' BIT',
  300. TableSchema::TYPE_FLOAT => ' FLOAT',
  301. TableSchema::TYPE_DECIMAL => ' DECIMAL',
  302. TableSchema::TYPE_DATE => ' DATE',
  303. TableSchema::TYPE_TIME => ' TIME',
  304. TableSchema::TYPE_DATETIME => ' DATETIME',
  305. TableSchema::TYPE_TIMESTAMP => ' DATETIME',
  306. TableSchema::TYPE_UUID => ' UNIQUEIDENTIFIER',
  307. TableSchema::TYPE_JSON => ' NVARCHAR(MAX)',
  308. ];
  309. if (isset($typeMap[$data['type']])) {
  310. $out .= $typeMap[$data['type']];
  311. }
  312. if ($data['type'] === TableSchema::TYPE_INTEGER || $data['type'] === TableSchema::TYPE_BIGINTEGER) {
  313. if ([$name] === $schema->primaryKey() || $data['autoIncrement'] === true) {
  314. unset($data['null'], $data['default']);
  315. $out .= ' IDENTITY(1, 1)';
  316. }
  317. }
  318. if ($data['type'] === TableSchema::TYPE_TEXT && $data['length'] !== Table::LENGTH_TINY) {
  319. $out .= ' NVARCHAR(MAX)';
  320. }
  321. if ($data['type'] === TableSchema::TYPE_BINARY) {
  322. $out .= ' VARBINARY';
  323. if ($data['length'] !== Table::LENGTH_TINY) {
  324. $out .= '(MAX)';
  325. } else {
  326. $out .= sprintf('(%s)', Table::LENGTH_TINY);
  327. }
  328. }
  329. if ($data['type'] === TableSchema::TYPE_STRING ||
  330. ($data['type'] === TableSchema::TYPE_TEXT && $data['length'] === Table::LENGTH_TINY)
  331. ) {
  332. $type = ' NVARCHAR';
  333. if (!empty($data['fixed'])) {
  334. $type = ' NCHAR';
  335. }
  336. if (!isset($data['length'])) {
  337. $data['length'] = 255;
  338. }
  339. $out .= sprintf('%s(%d)', $type, $data['length']);
  340. }
  341. $hasCollate = [TableSchema::TYPE_TEXT, TableSchema::TYPE_STRING];
  342. if (in_array($data['type'], $hasCollate, true) && isset($data['collate']) && $data['collate'] !== '') {
  343. $out .= ' COLLATE ' . $data['collate'];
  344. }
  345. if ($data['type'] === TableSchema::TYPE_FLOAT && isset($data['precision'])) {
  346. $out .= '(' . (int)$data['precision'] . ')';
  347. }
  348. if ($data['type'] === TableSchema::TYPE_DECIMAL &&
  349. (isset($data['length']) || isset($data['precision']))
  350. ) {
  351. $out .= '(' . (int)$data['length'] . ',' . (int)$data['precision'] . ')';
  352. }
  353. if (isset($data['null']) && $data['null'] === false) {
  354. $out .= ' NOT NULL';
  355. }
  356. if (isset($data['default']) &&
  357. in_array($data['type'], [TableSchema::TYPE_TIMESTAMP, TableSchema::TYPE_DATETIME]) &&
  358. strtolower($data['default']) === 'current_timestamp'
  359. ) {
  360. $out .= ' DEFAULT CURRENT_TIMESTAMP';
  361. } elseif (isset($data['default'])) {
  362. $default = is_bool($data['default']) ? (int)$data['default'] : $this->_driver->schemaValue($data['default']);
  363. $out .= ' DEFAULT ' . $default;
  364. } elseif (isset($data['null']) && $data['null'] !== false) {
  365. $out .= ' DEFAULT NULL';
  366. }
  367. return $out;
  368. }
  369. /**
  370. * {@inheritDoc}
  371. */
  372. public function addConstraintSql(TableSchema $schema)
  373. {
  374. $sqlPattern = 'ALTER TABLE %s ADD %s;';
  375. $sql = [];
  376. foreach ($schema->constraints() as $name) {
  377. $constraint = $schema->constraint($name);
  378. if ($constraint['type'] === Table::CONSTRAINT_FOREIGN) {
  379. $tableName = $this->_driver->quoteIdentifier($schema->name());
  380. $sql[] = sprintf($sqlPattern, $tableName, $this->constraintSql($schema, $name));
  381. }
  382. }
  383. return $sql;
  384. }
  385. /**
  386. * {@inheritDoc}
  387. */
  388. public function dropConstraintSql(TableSchema $schema)
  389. {
  390. $sqlPattern = 'ALTER TABLE %s DROP CONSTRAINT %s;';
  391. $sql = [];
  392. foreach ($schema->constraints() as $name) {
  393. $constraint = $schema->constraint($name);
  394. if ($constraint['type'] === Table::CONSTRAINT_FOREIGN) {
  395. $tableName = $this->_driver->quoteIdentifier($schema->name());
  396. $constraintName = $this->_driver->quoteIdentifier($name);
  397. $sql[] = sprintf($sqlPattern, $tableName, $constraintName);
  398. }
  399. }
  400. return $sql;
  401. }
  402. /**
  403. * {@inheritDoc}
  404. */
  405. public function indexSql(TableSchema $schema, $name)
  406. {
  407. $data = $schema->index($name);
  408. $columns = array_map(
  409. [$this->_driver, 'quoteIdentifier'],
  410. $data['columns']
  411. );
  412. return sprintf(
  413. 'CREATE INDEX %s ON %s (%s)',
  414. $this->_driver->quoteIdentifier($name),
  415. $this->_driver->quoteIdentifier($schema->name()),
  416. implode(', ', $columns)
  417. );
  418. }
  419. /**
  420. * {@inheritDoc}
  421. */
  422. public function constraintSql(TableSchema $schema, $name)
  423. {
  424. $data = $schema->constraint($name);
  425. $out = 'CONSTRAINT ' . $this->_driver->quoteIdentifier($name);
  426. if ($data['type'] === Table::CONSTRAINT_PRIMARY) {
  427. $out = 'PRIMARY KEY';
  428. }
  429. if ($data['type'] === Table::CONSTRAINT_UNIQUE) {
  430. $out .= ' UNIQUE';
  431. }
  432. return $this->_keySql($out, $data);
  433. }
  434. /**
  435. * Helper method for generating key SQL snippets.
  436. *
  437. * @param string $prefix The key prefix
  438. * @param array $data Key data.
  439. * @return string
  440. */
  441. protected function _keySql($prefix, $data)
  442. {
  443. $columns = array_map(
  444. [$this->_driver, 'quoteIdentifier'],
  445. $data['columns']
  446. );
  447. if ($data['type'] === Table::CONSTRAINT_FOREIGN) {
  448. return $prefix . sprintf(
  449. ' FOREIGN KEY (%s) REFERENCES %s (%s) ON UPDATE %s ON DELETE %s',
  450. implode(', ', $columns),
  451. $this->_driver->quoteIdentifier($data['references'][0]),
  452. $this->_convertConstraintColumns($data['references'][1]),
  453. $this->_foreignOnClause($data['update']),
  454. $this->_foreignOnClause($data['delete'])
  455. );
  456. }
  457. return $prefix . ' (' . implode(', ', $columns) . ')';
  458. }
  459. /**
  460. * {@inheritDoc}
  461. */
  462. public function createTableSql(TableSchema $schema, $columns, $constraints, $indexes)
  463. {
  464. $content = array_merge($columns, $constraints);
  465. $content = implode(",\n", array_filter($content));
  466. $tableName = $this->_driver->quoteIdentifier($schema->name());
  467. $out = [];
  468. $out[] = sprintf("CREATE TABLE %s (\n%s\n)", $tableName, $content);
  469. foreach ($indexes as $index) {
  470. $out[] = $index;
  471. }
  472. return $out;
  473. }
  474. /**
  475. * {@inheritDoc}
  476. */
  477. public function truncateTableSql(TableSchema $schema)
  478. {
  479. $name = $this->_driver->quoteIdentifier($schema->name());
  480. $queries = [
  481. sprintf('DELETE FROM %s', $name)
  482. ];
  483. // Restart identity sequences
  484. $pk = $schema->primaryKey();
  485. if (count($pk) === 1) {
  486. $column = $schema->column($pk[0]);
  487. if (in_array($column['type'], ['integer', 'biginteger'])) {
  488. $queries[] = sprintf(
  489. "DBCC CHECKIDENT('%s', RESEED, 0)",
  490. $schema->name()
  491. );
  492. }
  493. }
  494. return $queries;
  495. }
  496. }