Completed
Pull Request — master (#3675)
by
unknown
64:43
created

testSupportsIdentityColumns()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
1
<?php
2
3
namespace Doctrine\Tests\DBAL\Platforms;
4
5
use Doctrine\DBAL\DBALException;
6
use Doctrine\DBAL\Schema\Column;
7
use Doctrine\DBAL\Schema\ColumnDiff;
8
use Doctrine\DBAL\Schema\Index;
9
use Doctrine\DBAL\Schema\Schema;
10
use Doctrine\DBAL\Schema\Table;
11
use Doctrine\DBAL\Schema\TableDiff;
12
use Doctrine\DBAL\TransactionIsolationLevel;
13
use Doctrine\DBAL\Types\Type;
14
use function sprintf;
15
16
abstract class AbstractSQLServerPlatformTestCase extends AbstractPlatformTestCase
17
{
18
    public function getGenerateTableSql() : string
19
    {
20
        return 'CREATE TABLE test (id INT IDENTITY NOT NULL, test NVARCHAR(255), PRIMARY KEY (id))';
21
    }
22
23
    /**
24
     * {@inheritDoc}
25
     */
26
    public function getGenerateTableWithMultiColumnUniqueIndexSql() : array
27
    {
28
        return [
29
            'CREATE TABLE test (foo NVARCHAR(255), bar NVARCHAR(255))',
30
            'CREATE UNIQUE INDEX UNIQ_D87F7E0C8C73652176FF8CAA ON test (foo, bar) WHERE foo IS NOT NULL AND bar IS NOT NULL',
31
        ];
32
    }
33
34
    /**
35
     * {@inheritDoc}
36
     */
37
    public function getGenerateAlterTableSql() : array
38
    {
39
        return [
40
            'ALTER TABLE mytable ADD quota INT',
41
            'ALTER TABLE mytable DROP COLUMN foo',
42
            'ALTER TABLE mytable ALTER COLUMN baz NVARCHAR(255) NOT NULL',
43
            "ALTER TABLE mytable ADD CONSTRAINT DF_6B2BD609_78240498 DEFAULT 'def' FOR baz",
44
            'ALTER TABLE mytable ALTER COLUMN bloo BIT NOT NULL',
45
            "ALTER TABLE mytable ADD CONSTRAINT DF_6B2BD609_CECED971 DEFAULT '0' FOR bloo",
46
            "sp_RENAME 'mytable', 'userlist'",
47
            "DECLARE @sql NVARCHAR(MAX) = N''; " .
48
            "SELECT @sql += N'EXEC sp_rename N''' + dc.name + ''', N''' " .
49
            "+ REPLACE(dc.name, '6B2BD609', 'E2B58069') + ''', ''OBJECT'';' " .
50
            'FROM sys.default_constraints dc ' .
51
            'JOIN sys.tables tbl ON dc.parent_object_id = tbl.object_id ' .
52
            "WHERE tbl.name = 'userlist';" .
53
            'EXEC sp_executesql @sql',
54
        ];
55
    }
56
57
    public function testDoesNotSupportRegexp() : void
58
    {
59
        $this->expectException(DBALException::class);
60
61
        $this->platform->getRegexpExpression();
62
    }
63
64
    public function testGeneratesSqlSnippets() : void
65
    {
66
        self::assertEquals('CONVERT(date, GETDATE())', $this->platform->getCurrentDateSQL());
67
        self::assertEquals('CONVERT(time, GETDATE())', $this->platform->getCurrentTimeSQL());
68
        self::assertEquals('CURRENT_TIMESTAMP', $this->platform->getCurrentTimestampSQL());
69
        self::assertEquals('"', $this->platform->getIdentifierQuoteCharacter(), 'Identifier quote character is not correct');
70
        self::assertEquals('(column1 + column2 + column3)', $this->platform->getConcatExpression('column1', 'column2', 'column3'), 'Concatenation expression is not correct');
71
    }
72
73
    public function testGeneratesTransactionsCommands() : void
74
    {
75
        self::assertEquals(
76
            'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED',
77
            $this->platform->getSetTransactionIsolationSQL(TransactionIsolationLevel::READ_UNCOMMITTED)
78
        );
79
        self::assertEquals(
80
            'SET TRANSACTION ISOLATION LEVEL READ COMMITTED',
81
            $this->platform->getSetTransactionIsolationSQL(TransactionIsolationLevel::READ_COMMITTED)
82
        );
83
        self::assertEquals(
84
            'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ',
85
            $this->platform->getSetTransactionIsolationSQL(TransactionIsolationLevel::REPEATABLE_READ)
86
        );
87
        self::assertEquals(
88
            'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE',
89
            $this->platform->getSetTransactionIsolationSQL(TransactionIsolationLevel::SERIALIZABLE)
90
        );
91
    }
92
93
    public function testGeneratesDDLSnippets() : void
94
    {
95
        $dropDatabaseExpectation = 'DROP DATABASE foobar';
96
97
        self::assertEquals('SELECT * FROM sys.databases', $this->platform->getListDatabasesSQL());
98
        self::assertEquals('CREATE DATABASE foobar', $this->platform->getCreateDatabaseSQL('foobar'));
99
        self::assertEquals($dropDatabaseExpectation, $this->platform->getDropDatabaseSQL('foobar'));
100
        self::assertEquals('DROP TABLE foobar', $this->platform->getDropTableSQL('foobar'));
101
    }
102
103
    public function testGeneratesTypeDeclarationForIntegers() : void
104
    {
105
        self::assertEquals(
106
            'INT',
107
            $this->platform->getIntegerTypeDeclarationSQL([])
108
        );
109
        self::assertEquals(
110
            'INT IDENTITY',
111
            $this->platform->getIntegerTypeDeclarationSQL(['autoincrement' => true])
112
        );
113
        self::assertEquals(
114
            'INT IDENTITY',
115
            $this->platform->getIntegerTypeDeclarationSQL(
116
                ['autoincrement' => true, 'primary' => true]
117
            )
118
        );
119
    }
120
121
    public function testGeneratesTypeDeclarationsForStrings() : void
122
    {
123
        self::assertEquals(
124
            'NCHAR(10)',
125
            $this->platform->getVarcharTypeDeclarationSQL(
126
                ['length' => 10, 'fixed' => true]
127
            )
128
        );
129
        self::assertEquals(
130
            'NVARCHAR(50)',
131
            $this->platform->getVarcharTypeDeclarationSQL(['length' => 50]),
132
            'Variable string declaration is not correct'
133
        );
134
        self::assertEquals(
135
            'NVARCHAR(255)',
136
            $this->platform->getVarcharTypeDeclarationSQL([]),
137
            'Long string declaration is not correct'
138
        );
139
        self::assertSame('VARCHAR(MAX)', $this->platform->getClobTypeDeclarationSQL([]));
140
        self::assertSame(
141
            'VARCHAR(MAX)',
142
            $this->platform->getClobTypeDeclarationSQL(['length' => 5, 'fixed' => true])
143
        );
144
    }
145
146
    public function testPrefersIdentityColumns() : void
147
    {
148
        self::assertTrue($this->platform->prefersIdentityColumns());
149
    }
150
151
    public function testSupportsIdentityColumns() : void
152
    {
153
        self::assertTrue($this->platform->supportsIdentityColumns());
154
    }
155
156
    public function testSupportsCreateDropDatabase() : void
157
    {
158
        self::assertTrue($this->platform->supportsCreateDropDatabase());
159
    }
160
161
    public function testSupportsSchemas() : void
162
    {
163
        self::assertTrue($this->platform->supportsSchemas());
164
    }
165
166
    public function testDoesNotSupportSavePoints() : void
167
    {
168
        self::assertTrue($this->platform->supportsSavepoints());
169
    }
170
171
    public function getGenerateIndexSql() : string
172
    {
173
        return 'CREATE INDEX my_idx ON mytable (user_name, last_login)';
174
    }
175
176
    public function getGenerateUniqueIndexSql() : string
177
    {
178
        return 'CREATE UNIQUE INDEX index_name ON test (test, test2) WHERE test IS NOT NULL AND test2 IS NOT NULL';
179
    }
180
181
    public function getGenerateForeignKeySql() : string
182
    {
183
        return 'ALTER TABLE test ADD FOREIGN KEY (fk_name_id) REFERENCES other_table (id)';
184
    }
185
186
    public function testModifyLimitQuery() : void
187
    {
188
        $querySql   = 'SELECT * FROM user';
189
        $alteredSql = 'SELECT TOP 10 * FROM user';
190
        $sql        = $this->platform->modifyLimitQuery($querySql, 10, 0);
191
        $this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
192
    }
193
194
    public function testModifyLimitQueryWithEmptyOffset() : void
195
    {
196
        $querySql   = 'SELECT * FROM user';
197
        $alteredSql = 'SELECT TOP 10 * FROM user';
198
        $sql        = $this->platform->modifyLimitQuery($querySql, 10);
199
        $this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
200
    }
201
202
    public function testModifyLimitQueryWithOffset() : void
203
    {
204
        if (! $this->platform->supportsLimitOffset()) {
205
            $this->markTestSkipped(sprintf('Platform "%s" does not support offsets in result limiting.', $this->platform->getName()));
206
        }
207
208
        $querySql   = 'SELECT * FROM user ORDER BY username DESC';
209
        $alteredSql = 'SELECT TOP 15 * FROM user ORDER BY username DESC';
210
        $sql        = $this->platform->modifyLimitQuery($querySql, 10, 5);
211
212
        $this->expectCteWithMinAndMaxRowNums($alteredSql, 6, 15, $sql);
213
    }
214
215
    public function testModifyLimitQueryWithAscOrderBy() : void
216
    {
217
        $querySql   = 'SELECT * FROM user ORDER BY username ASC';
218
        $alteredSql = 'SELECT TOP 10 * FROM user ORDER BY username ASC';
219
        $sql        = $this->platform->modifyLimitQuery($querySql, 10);
220
221
        $this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
222
    }
223
224
    public function testModifyLimitQueryWithLowercaseOrderBy() : void
225
    {
226
        $querySql   = 'SELECT * FROM user order by username';
227
        $alteredSql = 'SELECT TOP 10 * FROM user order by username';
228
        $sql        = $this->platform->modifyLimitQuery($querySql, 10);
229
        $this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
230
    }
231
232
    public function testModifyLimitQueryWithDescOrderBy() : void
233
    {
234
        $querySql   = 'SELECT * FROM user ORDER BY username DESC';
235
        $alteredSql = 'SELECT TOP 10 * FROM user ORDER BY username DESC';
236
        $sql        = $this->platform->modifyLimitQuery($querySql, 10);
237
        $this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
238
    }
239
240
    public function testModifyLimitQueryWithMultipleOrderBy() : void
241
    {
242
        $querySql   = 'SELECT * FROM user ORDER BY username DESC, usereamil ASC';
243
        $alteredSql = 'SELECT TOP 10 * FROM user ORDER BY username DESC, usereamil ASC';
244
        $sql        = $this->platform->modifyLimitQuery($querySql, 10);
245
        $this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
246
    }
247
248
    public function testModifyLimitQueryWithSubSelect() : void
249
    {
250
        $querySql   = 'SELECT * FROM (SELECT u.id as uid, u.name as uname) dctrn_result';
251
        $alteredSql = 'SELECT TOP 10 * FROM (SELECT u.id as uid, u.name as uname) dctrn_result';
252
        $sql        = $this->platform->modifyLimitQuery($querySql, 10);
253
        $this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
254
    }
255
256
    public function testModifyLimitQueryWithSubSelectAndOrder() : void
257
    {
258
        $querySql   = 'SELECT * FROM (SELECT u.id as uid, u.name as uname ORDER BY u.name DESC) dctrn_result';
259
        $alteredSql = 'SELECT TOP 10 * FROM (SELECT u.id as uid, u.name as uname) dctrn_result';
260
        $sql        = $this->platform->modifyLimitQuery($querySql, 10);
261
        $this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
262
263
        $querySql   = 'SELECT * FROM (SELECT u.id, u.name ORDER BY u.name DESC) dctrn_result';
264
        $alteredSql = 'SELECT TOP 10 * FROM (SELECT u.id, u.name) dctrn_result';
265
        $sql        = $this->platform->modifyLimitQuery($querySql, 10);
266
        $this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
267
    }
268
269
    public function testModifyLimitQueryWithSubSelectAndMultipleOrder() : void
270
    {
271
        if (! $this->platform->supportsLimitOffset()) {
272
            $this->markTestSkipped(sprintf('Platform "%s" does not support offsets in result limiting.', $this->platform->getName()));
273
        }
274
275
        $querySql   = 'SELECT * FROM (SELECT u.id as uid, u.name as uname ORDER BY u.name DESC, id ASC) dctrn_result';
276
        $alteredSql = 'SELECT TOP 15 * FROM (SELECT u.id as uid, u.name as uname) dctrn_result';
277
        $sql        = $this->platform->modifyLimitQuery($querySql, 10, 5);
278
        $this->expectCteWithMinAndMaxRowNums($alteredSql, 6, 15, $sql);
279
280
        $querySql   = 'SELECT * FROM (SELECT u.id uid, u.name uname ORDER BY u.name DESC, id ASC) dctrn_result';
281
        $alteredSql = 'SELECT TOP 15 * FROM (SELECT u.id uid, u.name uname) dctrn_result';
282
        $sql        = $this->platform->modifyLimitQuery($querySql, 10, 5);
283
        $this->expectCteWithMinAndMaxRowNums($alteredSql, 6, 15, $sql);
284
285
        $querySql   = 'SELECT * FROM (SELECT u.id, u.name ORDER BY u.name DESC, id ASC) dctrn_result';
286
        $alteredSql = 'SELECT TOP 15 * FROM (SELECT u.id, u.name) dctrn_result';
287
        $sql        = $this->platform->modifyLimitQuery($querySql, 10, 5);
288
        $this->expectCteWithMinAndMaxRowNums($alteredSql, 6, 15, $sql);
289
    }
290
291
    public function testModifyLimitQueryWithFromColumnNames() : void
292
    {
293
        $querySql   = 'SELECT a.fromFoo, fromBar FROM foo';
294
        $alteredSql = 'SELECT TOP 10 a.fromFoo, fromBar FROM foo';
295
        $sql        = $this->platform->modifyLimitQuery($querySql, 10);
296
        $this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
297
    }
298
299
    /**
300
     * @group DBAL-927
301
     */
302
    public function testModifyLimitQueryWithExtraLongQuery() : void
303
    {
304
        $query  = 'SELECT table1.column1, table2.column2, table3.column3, table4.column4, table5.column5, table6.column6, table7.column7, table8.column8 FROM table1, table2, table3, table4, table5, table6, table7, table8 ';
305
        $query .= 'WHERE (table1.column1 = table2.column2) AND (table1.column1 = table3.column3) AND (table1.column1 = table4.column4) AND (table1.column1 = table5.column5) AND (table1.column1 = table6.column6) AND (table1.column1 = table7.column7) AND (table1.column1 = table8.column8) AND (table2.column2 = table3.column3) AND (table2.column2 = table4.column4) AND (table2.column2 = table5.column5) AND (table2.column2 = table6.column6) ';
306
        $query .= 'AND (table2.column2 = table7.column7) AND (table2.column2 = table8.column8) AND (table3.column3 = table4.column4) AND (table3.column3 = table5.column5) AND (table3.column3 = table6.column6) AND (table3.column3 = table7.column7) AND (table3.column3 = table8.column8) AND (table4.column4 = table5.column5) AND (table4.column4 = table6.column6) AND (table4.column4 = table7.column7) AND (table4.column4 = table8.column8) ';
307
        $query .= 'AND (table5.column5 = table6.column6) AND (table5.column5 = table7.column7) AND (table5.column5 = table8.column8) AND (table6.column6 = table7.column7) AND (table6.column6 = table8.column8) AND (table7.column7 = table8.column8)';
308
309
        $alteredSql  = 'SELECT TOP 10 table1.column1, table2.column2, table3.column3, table4.column4, table5.column5, table6.column6, table7.column7, table8.column8 FROM table1, table2, table3, table4, table5, table6, table7, table8 ';
310
        $alteredSql .= 'WHERE (table1.column1 = table2.column2) AND (table1.column1 = table3.column3) AND (table1.column1 = table4.column4) AND (table1.column1 = table5.column5) AND (table1.column1 = table6.column6) AND (table1.column1 = table7.column7) AND (table1.column1 = table8.column8) AND (table2.column2 = table3.column3) AND (table2.column2 = table4.column4) AND (table2.column2 = table5.column5) AND (table2.column2 = table6.column6) ';
311
        $alteredSql .= 'AND (table2.column2 = table7.column7) AND (table2.column2 = table8.column8) AND (table3.column3 = table4.column4) AND (table3.column3 = table5.column5) AND (table3.column3 = table6.column6) AND (table3.column3 = table7.column7) AND (table3.column3 = table8.column8) AND (table4.column4 = table5.column5) AND (table4.column4 = table6.column6) AND (table4.column4 = table7.column7) AND (table4.column4 = table8.column8) ';
312
        $alteredSql .= 'AND (table5.column5 = table6.column6) AND (table5.column5 = table7.column7) AND (table5.column5 = table8.column8) AND (table6.column6 = table7.column7) AND (table6.column6 = table8.column8) AND (table7.column7 = table8.column8)';
313
314
        $sql = $this->platform->modifyLimitQuery($query, 10);
315
        $this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
316
    }
317
318
    /**
319
     * @group DDC-2470
320
     */
321
    public function testModifyLimitQueryWithOrderByClause() : void
322
    {
323
        if (! $this->platform->supportsLimitOffset()) {
324
            $this->markTestSkipped(sprintf('Platform "%s" does not support offsets in result limiting.', $this->platform->getName()));
325
        }
326
327
        $sql        = 'SELECT m0_.NOMBRE AS NOMBRE0, m0_.FECHAINICIO AS FECHAINICIO1, m0_.FECHAFIN AS FECHAFIN2 FROM MEDICION m0_ WITH (NOLOCK) INNER JOIN ESTUDIO e1_ ON m0_.ESTUDIO_ID = e1_.ID INNER JOIN CLIENTE c2_ ON e1_.CLIENTE_ID = c2_.ID INNER JOIN USUARIO u3_ ON c2_.ID = u3_.CLIENTE_ID WHERE u3_.ID = ? ORDER BY m0_.FECHAINICIO DESC';
328
        $alteredSql = 'SELECT TOP 15 m0_.NOMBRE AS NOMBRE0, m0_.FECHAINICIO AS FECHAINICIO1, m0_.FECHAFIN AS FECHAFIN2 FROM MEDICION m0_ WITH (NOLOCK) INNER JOIN ESTUDIO e1_ ON m0_.ESTUDIO_ID = e1_.ID INNER JOIN CLIENTE c2_ ON e1_.CLIENTE_ID = c2_.ID INNER JOIN USUARIO u3_ ON c2_.ID = u3_.CLIENTE_ID WHERE u3_.ID = ? ORDER BY m0_.FECHAINICIO DESC';
329
        $actual     = $this->platform->modifyLimitQuery($sql, 10, 5);
330
331
        $this->expectCteWithMinAndMaxRowNums($alteredSql, 6, 15, $actual);
332
    }
333
334
    /**
335
     * @group DBAL-713
336
     */
337
    public function testModifyLimitQueryWithSubSelectInSelectList() : void
338
    {
339
        $querySql   = 'SELECT ' .
340
            'u.id, ' .
341
            '(u.foo/2) foodiv, ' .
342
            'CONCAT(u.bar, u.baz) barbaz, ' .
343
            '(SELECT (SELECT COUNT(*) FROM login l WHERE l.profile_id = p.id) FROM profile p WHERE p.user_id = u.id) login_count ' .
344
            'FROM user u ' .
345
            "WHERE u.status = 'disabled'";
346
        $alteredSql = 'SELECT TOP 10 ' .
347
            'u.id, ' .
348
            '(u.foo/2) foodiv, ' .
349
            'CONCAT(u.bar, u.baz) barbaz, ' .
350
            '(SELECT (SELECT COUNT(*) FROM login l WHERE l.profile_id = p.id) FROM profile p WHERE p.user_id = u.id) login_count ' .
351
            'FROM user u ' .
352
            "WHERE u.status = 'disabled'";
353
        $sql        = $this->platform->modifyLimitQuery($querySql, 10);
354
355
        $this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
356
    }
357
358
    /**
359
     * @group DBAL-713
360
     */
361
    public function testModifyLimitQueryWithSubSelectInSelectListAndOrderByClause() : void
362
    {
363
        if (! $this->platform->supportsLimitOffset()) {
364
            $this->markTestSkipped(sprintf('Platform "%s" does not support offsets in result limiting.', $this->platform->getName()));
365
        }
366
367
        $querySql   = 'SELECT ' .
368
            'u.id, ' .
369
            '(u.foo/2) foodiv, ' .
370
            'CONCAT(u.bar, u.baz) barbaz, ' .
371
            '(SELECT (SELECT COUNT(*) FROM login l WHERE l.profile_id = p.id) FROM profile p WHERE p.user_id = u.id) login_count ' .
372
            'FROM user u ' .
373
            "WHERE u.status = 'disabled' " .
374
            'ORDER BY u.username DESC';
375
        $alteredSql = 'SELECT TOP 15 ' .
376
            'u.id, ' .
377
            '(u.foo/2) foodiv, ' .
378
            'CONCAT(u.bar, u.baz) barbaz, ' .
379
            '(SELECT (SELECT COUNT(*) FROM login l WHERE l.profile_id = p.id) FROM profile p WHERE p.user_id = u.id) login_count ' .
380
            'FROM user u ' .
381
            "WHERE u.status = 'disabled' " .
382
            'ORDER BY u.username DESC';
383
        $sql        = $this->platform->modifyLimitQuery($querySql, 10, 5);
384
        $this->expectCteWithMinAndMaxRowNums($alteredSql, 6, 15, $sql);
385
    }
386
387
    /**
388
     * @group DBAL-834
389
     */
390
    public function testModifyLimitQueryWithAggregateFunctionInOrderByClause() : void
391
    {
392
        $querySql   = 'SELECT ' .
393
            'MAX(heading_id) aliased, ' .
394
            'code ' .
395
            'FROM operator_model_operator ' .
396
            'GROUP BY code ' .
397
            'ORDER BY MAX(heading_id) DESC';
398
        $alteredSql = 'SELECT TOP 1 ' .
399
            'MAX(heading_id) aliased, ' .
400
            'code ' .
401
            'FROM operator_model_operator ' .
402
            'GROUP BY code ' .
403
            'ORDER BY MAX(heading_id) DESC';
404
        $sql        = $this->platform->modifyLimitQuery($querySql, 1, 0);
405
        $this->expectCteWithMaxRowNum($alteredSql, 1, $sql);
406
    }
407
408
    /**
409
     * @throws DBALException
410
     */
411
    public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnFromBaseTable() : void
412
    {
413
        $querySql   = 'SELECT DISTINCT id_0, name_1 '
414
            . 'FROM ('
415
            . 'SELECT t1.id AS id_0, t2.name AS name_1 '
416
            . 'FROM table_parent t1 '
417
            . 'LEFT JOIN join_table t2 ON t1.id = t2.table_id '
418
            . 'ORDER BY t1.id ASC'
419
            . ') dctrn_result '
420
            . 'ORDER BY id_0 ASC';
421
        $alteredSql = 'SELECT DISTINCT TOP 5 id_0, name_1 '
422
            . 'FROM ('
423
            . 'SELECT t1.id AS id_0, t2.name AS name_1 '
424
            . 'FROM table_parent t1 '
425
            . 'LEFT JOIN join_table t2 ON t1.id = t2.table_id'
426
            . ') dctrn_result '
427
            . 'ORDER BY id_0 ASC';
428
        $sql        = $this->platform->modifyLimitQuery($querySql, 5);
429
        $this->expectCteWithMaxRowNum($alteredSql, 5, $sql);
430
    }
431
432
    /**
433
     * @throws DBALException
434
     */
435
    public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnFromJoinTable() : void
436
    {
437
        $querySql   = 'SELECT DISTINCT id_0, name_1 '
438
            . 'FROM ('
439
            . 'SELECT t1.id AS id_0, t2.name AS name_1 '
440
            . 'FROM table_parent t1 '
441
            . 'LEFT JOIN join_table t2 ON t1.id = t2.table_id '
442
            . 'ORDER BY t2.name ASC'
443
            . ') dctrn_result '
444
            . 'ORDER BY name_1 ASC';
445
        $alteredSql = 'SELECT DISTINCT TOP 5 id_0, name_1 '
446
            . 'FROM ('
447
            . 'SELECT t1.id AS id_0, t2.name AS name_1 '
448
            . 'FROM table_parent t1 '
449
            . 'LEFT JOIN join_table t2 ON t1.id = t2.table_id'
450
            . ') dctrn_result '
451
            . 'ORDER BY name_1 ASC';
452
        $sql        = $this->platform->modifyLimitQuery($querySql, 5);
453
        $this->expectCteWithMaxRowNum($alteredSql, 5, $sql);
454
    }
455
456
    /**
457
     * @throws DBALException
458
     */
459
    public function testModifyLimitSubqueryWithJoinAndSubqueryOrderedByColumnsFromBothTables() : void
460
    {
461
        $querySql   = 'SELECT DISTINCT id_0, name_1, foo_2 '
462
            . 'FROM ('
463
            . 'SELECT t1.id AS id_0, t2.name AS name_1, t2.foo AS foo_2 '
464
            . 'FROM table_parent t1 '
465
            . 'LEFT JOIN join_table t2 ON t1.id = t2.table_id '
466
            . 'ORDER BY t2.name ASC, t2.foo DESC'
467
            . ') dctrn_result '
468
            . 'ORDER BY name_1 ASC, foo_2 DESC';
469
        $alteredSql = 'SELECT DISTINCT TOP 5 id_0, name_1, foo_2 '
470
            . 'FROM ('
471
            . 'SELECT t1.id AS id_0, t2.name AS name_1, t2.foo AS foo_2 '
472
            . 'FROM table_parent t1 '
473
            . 'LEFT JOIN join_table t2 ON t1.id = t2.table_id'
474
            . ') dctrn_result '
475
            . 'ORDER BY name_1 ASC, foo_2 DESC';
476
        $sql        = $this->platform->modifyLimitQuery($querySql, 5);
477
        $this->expectCteWithMaxRowNum($alteredSql, 5, $sql);
478
    }
479
480
    public function testModifyLimitSubquerySimple() : void
481
    {
482
        $querySql   = 'SELECT DISTINCT id_0 FROM '
483
            . '(SELECT k0_.id AS id_0, k0_.field AS field_1 '
484
            . 'FROM key_table k0_ WHERE (k0_.where_field IN (1))) dctrn_result';
485
        $alteredSql = 'SELECT DISTINCT TOP 20 id_0 FROM (SELECT k0_.id AS id_0, k0_.field AS field_1 '
486
            . 'FROM key_table k0_ WHERE (k0_.where_field IN (1))) dctrn_result';
487
        $sql        = $this->platform->modifyLimitQuery($querySql, 20);
488
        $this->expectCteWithMaxRowNum($alteredSql, 20, $sql);
489
    }
490
491
    /**
492
     * @group DDC-1360
493
     */
494
    public function testQuoteIdentifier() : void
495
    {
496
        self::assertEquals('[fo][o]', $this->platform->quoteIdentifier('fo]o'));
497
        self::assertEquals('[test]', $this->platform->quoteIdentifier('test'));
498
        self::assertEquals('[test].[test]', $this->platform->quoteIdentifier('test.test'));
499
    }
500
501
    /**
502
     * @group DDC-1360
503
     */
504
    public function testQuoteSingleIdentifier() : void
505
    {
506
        self::assertEquals('[fo][o]', $this->platform->quoteSingleIdentifier('fo]o'));
507
        self::assertEquals('[test]', $this->platform->quoteSingleIdentifier('test'));
508
        self::assertEquals('[test.test]', $this->platform->quoteSingleIdentifier('test.test'));
509
    }
510
511
    /**
512
     * @group DBAL-220
513
     */
514
    public function testCreateClusteredIndex() : void
515
    {
516
        $idx = new Index('idx', ['id']);
517
        $idx->addFlag('clustered');
518
        self::assertEquals('CREATE CLUSTERED INDEX idx ON tbl (id)', $this->platform->getCreateIndexSQL($idx, 'tbl'));
519
    }
520
521
    /**
522
     * @group DBAL-220
523
     */
524
    public function testCreateNonClusteredPrimaryKeyInTable() : void
525
    {
526
        $table = new Table('tbl');
527
        $table->addColumn('id', 'integer');
528
        $table->setPrimaryKey(['id']);
529
        $table->getIndex('primary')->addFlag('nonclustered');
530
531
        self::assertEquals(['CREATE TABLE tbl (id INT NOT NULL, PRIMARY KEY NONCLUSTERED (id))'], $this->platform->getCreateTableSQL($table));
532
    }
533
534
    /**
535
     * @group DBAL-220
536
     */
537
    public function testCreateNonClusteredPrimaryKey() : void
538
    {
539
        $idx = new Index('idx', ['id'], false, true);
540
        $idx->addFlag('nonclustered');
541
        self::assertEquals('ALTER TABLE tbl ADD PRIMARY KEY NONCLUSTERED (id)', $this->platform->getCreatePrimaryKeySQL($idx, 'tbl'));
542
    }
543
544
    public function testAlterAddPrimaryKey() : void
545
    {
546
        $idx = new Index('idx', ['id'], false, true);
547
        self::assertEquals('ALTER TABLE tbl ADD PRIMARY KEY (id)', $this->platform->getCreateIndexSQL($idx, 'tbl'));
548
    }
549
550
    /**
551
     * {@inheritDoc}
552
     */
553
    protected function getQuotedColumnInPrimaryKeySQL() : array
554
    {
555
        return ['CREATE TABLE [quoted] ([create] NVARCHAR(255) NOT NULL, PRIMARY KEY ([create]))'];
556
    }
557
558
    /**
559
     * {@inheritDoc}
560
     */
561
    protected function getQuotedColumnInIndexSQL() : array
562
    {
563
        return [
564
            'CREATE TABLE [quoted] ([create] NVARCHAR(255) NOT NULL)',
565
            'CREATE INDEX IDX_22660D028FD6E0FB ON [quoted] ([create])',
566
        ];
567
    }
568
569
    /**
570
     * {@inheritDoc}
571
     */
572
    protected function getQuotedNameInIndexSQL() : array
573
    {
574
        return [
575
            'CREATE TABLE test (column1 NVARCHAR(255) NOT NULL)',
576
            'CREATE INDEX [key] ON test (column1)',
577
        ];
578
    }
579
580
    /**
581
     * {@inheritDoc}
582
     */
583
    protected function getQuotedColumnInForeignKeySQL() : array
584
    {
585
        return [
586
            'CREATE TABLE [quoted] ([create] NVARCHAR(255) NOT NULL, foo NVARCHAR(255) NOT NULL, [bar] NVARCHAR(255) NOT NULL)',
587
            'ALTER TABLE [quoted] ADD CONSTRAINT FK_WITH_RESERVED_KEYWORD FOREIGN KEY ([create], foo, [bar]) REFERENCES [foreign] ([create], bar, [foo-bar])',
588
            'ALTER TABLE [quoted] ADD CONSTRAINT FK_WITH_NON_RESERVED_KEYWORD FOREIGN KEY ([create], foo, [bar]) REFERENCES foo ([create], bar, [foo-bar])',
589
            'ALTER TABLE [quoted] ADD CONSTRAINT FK_WITH_INTENDED_QUOTATION FOREIGN KEY ([create], foo, [bar]) REFERENCES [foo-bar] ([create], bar, [foo-bar])',
590
        ];
591
    }
592
593
    public function testGetCreateSchemaSQL() : void
594
    {
595
        $schemaName = 'schema';
596
        $sql        = $this->platform->getCreateSchemaSQL($schemaName);
597
        self::assertEquals('CREATE SCHEMA ' . $schemaName, $sql);
598
    }
599
600
    public function testCreateTableWithSchemaColumnComments() : void
601
    {
602
        $table = new Table('testschema.test');
603
        $table->addColumn('id', 'integer', ['comment' => 'This is a comment']);
604
        $table->setPrimaryKey(['id']);
605
606
        $expectedSql = [
607
            'CREATE TABLE testschema.test (id INT NOT NULL, PRIMARY KEY (id))',
608
            "EXEC sp_addextendedproperty N'MS_Description', N'This is a comment', N'SCHEMA', 'testschema', N'TABLE', 'test', N'COLUMN', id",
609
        ];
610
611
        self::assertEquals($expectedSql, $this->platform->getCreateTableSQL($table));
612
    }
613
614
    public function testAlterTableWithSchemaColumnComments() : void
615
    {
616
        $tableDiff                        = new TableDiff('testschema.mytable');
617
        $tableDiff->addedColumns['quota'] = new Column('quota', Type::getType('integer'), ['comment' => 'A comment']);
618
619
        $expectedSql = [
620
            'ALTER TABLE testschema.mytable ADD quota INT NOT NULL',
621
            "EXEC sp_addextendedproperty N'MS_Description', N'A comment', N'SCHEMA', 'testschema', N'TABLE', 'mytable', N'COLUMN', quota",
622
        ];
623
624
        self::assertEquals($expectedSql, $this->platform->getAlterTableSQL($tableDiff));
625
    }
626
627
    public function testAlterTableWithSchemaDropColumnComments() : void
628
    {
629
        $tableDiff                          = new TableDiff('testschema.mytable');
630
        $tableDiff->changedColumns['quota'] = new ColumnDiff(
631
            'quota',
632
            new Column('quota', Type::getType('integer'), []),
633
            ['comment'],
634
            new Column('quota', Type::getType('integer'), ['comment' => 'A comment'])
635
        );
636
637
        $expectedSql = ["EXEC sp_dropextendedproperty N'MS_Description', N'SCHEMA', 'testschema', N'TABLE', 'mytable', N'COLUMN', quota"];
638
639
        self::assertEquals($expectedSql, $this->platform->getAlterTableSQL($tableDiff));
640
    }
641
642
    public function testAlterTableWithSchemaUpdateColumnComments() : void
643
    {
644
        $tableDiff                          = new TableDiff('testschema.mytable');
645
        $tableDiff->changedColumns['quota'] = new ColumnDiff(
646
            'quota',
647
            new Column('quota', Type::getType('integer'), ['comment' => 'B comment']),
648
            ['comment'],
649
            new Column('quota', Type::getType('integer'), ['comment' => 'A comment'])
650
        );
651
652
        $expectedSql = ["EXEC sp_updateextendedproperty N'MS_Description', N'B comment', N'SCHEMA', 'testschema', N'TABLE', 'mytable', N'COLUMN', quota"];
653
654
        self::assertEquals($expectedSql, $this->platform->getAlterTableSQL($tableDiff));
655
    }
656
657
    /**
658
     * {@inheritDoc}
659
     *
660
     * @group DBAL-543
661
     */
662
    public function getCreateTableColumnCommentsSQL() : array
663
    {
664
        return [
665
            'CREATE TABLE test (id INT NOT NULL, PRIMARY KEY (id))',
666
            "EXEC sp_addextendedproperty N'MS_Description', N'This is a comment', N'SCHEMA', 'dbo', N'TABLE', 'test', N'COLUMN', id",
667
        ];
668
    }
669
670
    /**
671
     * {@inheritDoc}
672
     *
673
     * @group DBAL-543
674
     */
675
    public function getAlterTableColumnCommentsSQL() : array
676
    {
677
        return [
678
            'ALTER TABLE mytable ADD quota INT NOT NULL',
679
            "EXEC sp_addextendedproperty N'MS_Description', N'A comment', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', quota",
680
            // todo
681
            //"EXEC sp_addextendedproperty N'MS_Description', N'B comment', N'SCHEMA', dbo, N'TABLE', mytable, N'COLUMN', baz",
682
        ];
683
    }
684
685
    /**
686
     * {@inheritDoc}
687
     *
688
     * @group DBAL-543
689
     */
690
    public function getCreateTableColumnTypeCommentsSQL() : array
691
    {
692
        return [
693
            'CREATE TABLE test (id INT NOT NULL, data VARCHAR(MAX) NOT NULL, PRIMARY KEY (id))',
694
            "EXEC sp_addextendedproperty N'MS_Description', N'(DC2Type:array)', N'SCHEMA', 'dbo', N'TABLE', 'test', N'COLUMN', data",
695
        ];
696
    }
697
698
    /**
699
     * @group DBAL-543
700
     */
701
    public function testGeneratesCreateTableSQLWithColumnComments() : void
702
    {
703
        $table = new Table('mytable');
704
        $table->addColumn('id', 'integer', ['autoincrement' => true]);
705
        $table->addColumn('comment_null', 'integer', ['comment' => null]);
706
        $table->addColumn('comment_false', 'integer', ['comment' => false]);
707
        $table->addColumn('comment_empty_string', 'integer', ['comment' => '']);
708
        $table->addColumn('comment_integer_0', 'integer', ['comment' => 0]);
709
        $table->addColumn('comment_float_0', 'integer', ['comment' => 0.0]);
710
        $table->addColumn('comment_string_0', 'integer', ['comment' => '0']);
711
        $table->addColumn('comment', 'integer', ['comment' => 'Doctrine 0wnz you!']);
712
        $table->addColumn('`comment_quoted`', 'integer', ['comment' => 'Doctrine 0wnz comments for explicitly quoted columns!']);
713
        $table->addColumn('create', 'integer', ['comment' => 'Doctrine 0wnz comments for reserved keyword columns!']);
714
        $table->addColumn('commented_type', 'object');
715
        $table->addColumn('commented_type_with_comment', 'array', ['comment' => 'Doctrine array type.']);
716
        $table->addColumn('comment_with_string_literal_char', 'string', ['comment' => "O'Reilly"]);
717
        $table->setPrimaryKey(['id']);
718
719
        self::assertEquals(
720
            [
721
                'CREATE TABLE mytable (id INT IDENTITY NOT NULL, comment_null INT NOT NULL, comment_false INT NOT NULL, comment_empty_string INT NOT NULL, comment_integer_0 INT NOT NULL, comment_float_0 INT NOT NULL, comment_string_0 INT NOT NULL, comment INT NOT NULL, [comment_quoted] INT NOT NULL, [create] INT NOT NULL, commented_type VARCHAR(MAX) NOT NULL, commented_type_with_comment VARCHAR(MAX) NOT NULL, comment_with_string_literal_char NVARCHAR(255) NOT NULL, PRIMARY KEY (id))',
722
                "EXEC sp_addextendedproperty N'MS_Description', N'0', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', comment_integer_0",
723
                "EXEC sp_addextendedproperty N'MS_Description', N'0', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', comment_float_0",
724
                "EXEC sp_addextendedproperty N'MS_Description', N'0', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', comment_string_0",
725
                "EXEC sp_addextendedproperty N'MS_Description', N'Doctrine 0wnz you!', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', comment",
726
                "EXEC sp_addextendedproperty N'MS_Description', N'Doctrine 0wnz comments for explicitly quoted columns!', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', [comment_quoted]",
727
                "EXEC sp_addextendedproperty N'MS_Description', N'Doctrine 0wnz comments for reserved keyword columns!', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', [create]",
728
                "EXEC sp_addextendedproperty N'MS_Description', N'(DC2Type:object)', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', commented_type",
729
                "EXEC sp_addextendedproperty N'MS_Description', N'Doctrine array type.(DC2Type:array)', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', commented_type_with_comment",
730
                "EXEC sp_addextendedproperty N'MS_Description', N'O''Reilly', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', comment_with_string_literal_char",
731
            ],
732
            $this->platform->getCreateTableSQL($table)
733
        );
734
    }
735
736
    /**
737
     * @group DBAL-543
738
     * @group DBAL-1011
739
     */
740
    public function testGeneratesAlterTableSQLWithColumnComments() : void
741
    {
742
        $table = new Table('mytable');
743
        $table->addColumn('id', 'integer', ['autoincrement' => true]);
744
        $table->addColumn('comment_null', 'integer', ['comment' => null]);
745
        $table->addColumn('comment_false', 'integer', ['comment' => false]);
746
        $table->addColumn('comment_empty_string', 'integer', ['comment' => '']);
747
        $table->addColumn('comment_integer_0', 'integer', ['comment' => 0]);
748
        $table->addColumn('comment_float_0', 'integer', ['comment' => 0.0]);
749
        $table->addColumn('comment_string_0', 'integer', ['comment' => '0']);
750
        $table->addColumn('comment', 'integer', ['comment' => 'Doctrine 0wnz you!']);
751
        $table->addColumn('`comment_quoted`', 'integer', ['comment' => 'Doctrine 0wnz comments for explicitly quoted columns!']);
752
        $table->addColumn('create', 'integer', ['comment' => 'Doctrine 0wnz comments for reserved keyword columns!']);
753
        $table->addColumn('commented_type', 'object');
754
        $table->addColumn('commented_type_with_comment', 'array', ['comment' => 'Doctrine array type.']);
755
        $table->addColumn('comment_with_string_literal_quote_char', 'array', ['comment' => "O'Reilly"]);
756
        $table->setPrimaryKey(['id']);
757
758
        $tableDiff                                                         = new TableDiff('mytable');
759
        $tableDiff->fromTable                                              = $table;
760
        $tableDiff->addedColumns['added_comment_none']                     = new Column('added_comment_none', Type::getType('integer'));
761
        $tableDiff->addedColumns['added_comment_null']                     = new Column('added_comment_null', Type::getType('integer'), ['comment' => null]);
762
        $tableDiff->addedColumns['added_comment_false']                    = new Column('added_comment_false', Type::getType('integer'), ['comment' => false]);
763
        $tableDiff->addedColumns['added_comment_empty_string']             = new Column('added_comment_empty_string', Type::getType('integer'), ['comment' => '']);
764
        $tableDiff->addedColumns['added_comment_integer_0']                = new Column('added_comment_integer_0', Type::getType('integer'), ['comment' => 0]);
765
        $tableDiff->addedColumns['added_comment_float_0']                  = new Column('added_comment_float_0', Type::getType('integer'), ['comment' => 0.0]);
766
        $tableDiff->addedColumns['added_comment_string_0']                 = new Column('added_comment_string_0', Type::getType('integer'), ['comment' => '0']);
767
        $tableDiff->addedColumns['added_comment']                          = new Column('added_comment', Type::getType('integer'), ['comment' => 'Doctrine']);
768
        $tableDiff->addedColumns['`added_comment_quoted`']                 = new Column('`added_comment_quoted`', Type::getType('integer'), ['comment' => 'rulez']);
769
        $tableDiff->addedColumns['select']                                 = new Column('select', Type::getType('integer'), ['comment' => '666']);
770
        $tableDiff->addedColumns['added_commented_type']                   = new Column('added_commented_type', Type::getType('object'));
771
        $tableDiff->addedColumns['added_commented_type_with_comment']      = new Column('added_commented_type_with_comment', Type::getType('array'), ['comment' => '666']);
772
        $tableDiff->addedColumns['added_comment_with_string_literal_char'] = new Column('added_comment_with_string_literal_char', Type::getType('string'), ['comment' => "''"]);
773
774
        $tableDiff->renamedColumns['comment_float_0'] = new Column('comment_double_0', Type::getType('decimal'), ['comment' => 'Double for real!']);
775
776
        // Add comment to non-commented column.
777
        $tableDiff->changedColumns['id'] = new ColumnDiff(
778
            'id',
779
            new Column('id', Type::getType('integer'), ['autoincrement' => true, 'comment' => 'primary']),
780
            ['comment'],
781
            new Column('id', Type::getType('integer'), ['autoincrement' => true])
782
        );
783
784
        // Remove comment from null-commented column.
785
        $tableDiff->changedColumns['comment_null'] = new ColumnDiff(
786
            'comment_null',
787
            new Column('comment_null', Type::getType('string')),
788
            ['type'],
789
            new Column('comment_null', Type::getType('integer'), ['comment' => null])
790
        );
791
792
        // Add comment to false-commented column.
793
        $tableDiff->changedColumns['comment_false'] = new ColumnDiff(
794
            'comment_false',
795
            new Column('comment_false', Type::getType('integer'), ['comment' => 'false']),
796
            ['comment'],
797
            new Column('comment_false', Type::getType('integer'), ['comment' => false])
798
        );
799
800
        // Change type to custom type from empty string commented column.
801
        $tableDiff->changedColumns['comment_empty_string'] = new ColumnDiff(
802
            'comment_empty_string',
803
            new Column('comment_empty_string', Type::getType('object')),
804
            ['type'],
805
            new Column('comment_empty_string', Type::getType('integer'), ['comment' => ''])
806
        );
807
808
        // Change comment to false-comment from zero-string commented column.
809
        $tableDiff->changedColumns['comment_string_0'] = new ColumnDiff(
810
            'comment_string_0',
811
            new Column('comment_string_0', Type::getType('integer'), ['comment' => false]),
812
            ['comment'],
813
            new Column('comment_string_0', Type::getType('integer'), ['comment' => '0'])
814
        );
815
816
        // Remove comment from regular commented column.
817
        $tableDiff->changedColumns['comment'] = new ColumnDiff(
818
            'comment',
819
            new Column('comment', Type::getType('integer')),
820
            ['comment'],
821
            new Column('comment', Type::getType('integer'), ['comment' => 'Doctrine 0wnz you!'])
822
        );
823
824
        // Change comment and change type to custom type from regular commented column.
825
        $tableDiff->changedColumns['`comment_quoted`'] = new ColumnDiff(
826
            '`comment_quoted`',
827
            new Column('`comment_quoted`', Type::getType('array'), ['comment' => 'Doctrine array.']),
828
            ['comment', 'type'],
829
            new Column('`comment_quoted`', Type::getType('integer'), ['comment' => 'Doctrine 0wnz you!'])
830
        );
831
832
        // Remove comment and change type to custom type from regular commented column.
833
        $tableDiff->changedColumns['create'] = new ColumnDiff(
834
            'create',
835
            new Column('create', Type::getType('object')),
836
            ['comment', 'type'],
837
            new Column('create', Type::getType('integer'), ['comment' => 'Doctrine 0wnz comments for reserved keyword columns!'])
838
        );
839
840
        // Add comment and change custom type to regular type from non-commented column.
841
        $tableDiff->changedColumns['commented_type'] = new ColumnDiff(
842
            'commented_type',
843
            new Column('commented_type', Type::getType('integer'), ['comment' => 'foo']),
844
            ['comment', 'type'],
845
            new Column('commented_type', Type::getType('object'))
846
        );
847
848
        // Remove comment from commented custom type column.
849
        $tableDiff->changedColumns['commented_type_with_comment'] = new ColumnDiff(
850
            'commented_type_with_comment',
851
            new Column('commented_type_with_comment', Type::getType('array')),
852
            ['comment'],
853
            new Column('commented_type_with_comment', Type::getType('array'), ['comment' => 'Doctrine array type.'])
854
        );
855
856
        // Change comment from comment with string literal char column.
857
        $tableDiff->changedColumns['comment_with_string_literal_char'] = new ColumnDiff(
858
            'comment_with_string_literal_char',
859
            new Column('comment_with_string_literal_char', Type::getType('string'), ['comment' => "'"]),
860
            ['comment'],
861
            new Column('comment_with_string_literal_char', Type::getType('array'), ['comment' => "O'Reilly"])
862
        );
863
864
        $tableDiff->removedColumns['comment_integer_0'] = new Column('comment_integer_0', Type::getType('integer'), ['comment' => 0]);
865
866
        self::assertEquals(
867
            [
868
                // Renamed columns.
869
                "sp_RENAME 'mytable.comment_float_0', 'comment_double_0', 'COLUMN'",
870
871
                // Added columns.
872
                'ALTER TABLE mytable ADD added_comment_none INT NOT NULL',
873
                'ALTER TABLE mytable ADD added_comment_null INT NOT NULL',
874
                'ALTER TABLE mytable ADD added_comment_false INT NOT NULL',
875
                'ALTER TABLE mytable ADD added_comment_empty_string INT NOT NULL',
876
                'ALTER TABLE mytable ADD added_comment_integer_0 INT NOT NULL',
877
                'ALTER TABLE mytable ADD added_comment_float_0 INT NOT NULL',
878
                'ALTER TABLE mytable ADD added_comment_string_0 INT NOT NULL',
879
                'ALTER TABLE mytable ADD added_comment INT NOT NULL',
880
                'ALTER TABLE mytable ADD [added_comment_quoted] INT NOT NULL',
881
                'ALTER TABLE mytable ADD [select] INT NOT NULL',
882
                'ALTER TABLE mytable ADD added_commented_type VARCHAR(MAX) NOT NULL',
883
                'ALTER TABLE mytable ADD added_commented_type_with_comment VARCHAR(MAX) NOT NULL',
884
                'ALTER TABLE mytable ADD added_comment_with_string_literal_char NVARCHAR(255) NOT NULL',
885
                'ALTER TABLE mytable DROP COLUMN comment_integer_0',
886
                'ALTER TABLE mytable ALTER COLUMN comment_null NVARCHAR(255) NOT NULL',
887
                'ALTER TABLE mytable ALTER COLUMN comment_empty_string VARCHAR(MAX) NOT NULL',
888
                'ALTER TABLE mytable ALTER COLUMN [comment_quoted] VARCHAR(MAX) NOT NULL',
889
                'ALTER TABLE mytable ALTER COLUMN [create] VARCHAR(MAX) NOT NULL',
890
                'ALTER TABLE mytable ALTER COLUMN commented_type INT NOT NULL',
891
892
                // Added columns.
893
                "EXEC sp_addextendedproperty N'MS_Description', N'0', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', added_comment_integer_0",
894
                "EXEC sp_addextendedproperty N'MS_Description', N'0', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', added_comment_float_0",
895
                "EXEC sp_addextendedproperty N'MS_Description', N'0', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', added_comment_string_0",
896
                "EXEC sp_addextendedproperty N'MS_Description', N'Doctrine', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', added_comment",
897
                "EXEC sp_addextendedproperty N'MS_Description', N'rulez', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', [added_comment_quoted]",
898
                "EXEC sp_addextendedproperty N'MS_Description', N'666', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', [select]",
899
                "EXEC sp_addextendedproperty N'MS_Description', N'(DC2Type:object)', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', added_commented_type",
900
                "EXEC sp_addextendedproperty N'MS_Description', N'666(DC2Type:array)', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', added_commented_type_with_comment",
901
                "EXEC sp_addextendedproperty N'MS_Description', N'''''', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', added_comment_with_string_literal_char",
902
903
                // Changed columns.
904
                "EXEC sp_addextendedproperty N'MS_Description', N'primary', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', id",
905
                "EXEC sp_addextendedproperty N'MS_Description', N'false', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', comment_false",
906
                "EXEC sp_addextendedproperty N'MS_Description', N'(DC2Type:object)', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', comment_empty_string",
907
                "EXEC sp_dropextendedproperty N'MS_Description', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', comment_string_0",
908
                "EXEC sp_dropextendedproperty N'MS_Description', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', comment",
909
                "EXEC sp_updateextendedproperty N'MS_Description', N'Doctrine array.(DC2Type:array)', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', [comment_quoted]",
910
                "EXEC sp_updateextendedproperty N'MS_Description', N'(DC2Type:object)', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', [create]",
911
                "EXEC sp_updateextendedproperty N'MS_Description', N'foo', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', commented_type",
912
                "EXEC sp_updateextendedproperty N'MS_Description', N'(DC2Type:array)', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', commented_type_with_comment",
913
                "EXEC sp_updateextendedproperty N'MS_Description', N'''', N'SCHEMA', 'dbo', N'TABLE', 'mytable', N'COLUMN', comment_with_string_literal_char",
914
            ],
915
            $this->platform->getAlterTableSQL($tableDiff)
916
        );
917
    }
918
919
    /**
920
     * @group DBAL-122
921
     */
922
    public function testInitializesDoctrineTypeMappings() : void
923
    {
924
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('bigint'));
925
        self::assertSame('bigint', $this->platform->getDoctrineTypeMapping('bigint'));
926
927
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('numeric'));
928
        self::assertSame('decimal', $this->platform->getDoctrineTypeMapping('numeric'));
929
930
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('bit'));
931
        self::assertSame('boolean', $this->platform->getDoctrineTypeMapping('bit'));
932
933
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('smallint'));
934
        self::assertSame('smallint', $this->platform->getDoctrineTypeMapping('smallint'));
935
936
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('decimal'));
937
        self::assertSame('decimal', $this->platform->getDoctrineTypeMapping('decimal'));
938
939
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('smallmoney'));
940
        self::assertSame('integer', $this->platform->getDoctrineTypeMapping('smallmoney'));
941
942
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('int'));
943
        self::assertSame('integer', $this->platform->getDoctrineTypeMapping('int'));
944
945
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('tinyint'));
946
        self::assertSame('smallint', $this->platform->getDoctrineTypeMapping('tinyint'));
947
948
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('money'));
949
        self::assertSame('integer', $this->platform->getDoctrineTypeMapping('money'));
950
951
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('float'));
952
        self::assertSame('float', $this->platform->getDoctrineTypeMapping('float'));
953
954
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('real'));
955
        self::assertSame('float', $this->platform->getDoctrineTypeMapping('real'));
956
957
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('double'));
958
        self::assertSame('float', $this->platform->getDoctrineTypeMapping('double'));
959
960
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('double precision'));
961
        self::assertSame('float', $this->platform->getDoctrineTypeMapping('double precision'));
962
963
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('smalldatetime'));
964
        self::assertSame('datetime', $this->platform->getDoctrineTypeMapping('smalldatetime'));
965
966
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('datetime'));
967
        self::assertSame('datetime', $this->platform->getDoctrineTypeMapping('datetime'));
968
969
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('char'));
970
        self::assertSame('string', $this->platform->getDoctrineTypeMapping('char'));
971
972
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('varchar'));
973
        self::assertSame('string', $this->platform->getDoctrineTypeMapping('varchar'));
974
975
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('text'));
976
        self::assertSame('text', $this->platform->getDoctrineTypeMapping('text'));
977
978
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('nchar'));
979
        self::assertSame('string', $this->platform->getDoctrineTypeMapping('nchar'));
980
981
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('nvarchar'));
982
        self::assertSame('string', $this->platform->getDoctrineTypeMapping('nvarchar'));
983
984
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('ntext'));
985
        self::assertSame('text', $this->platform->getDoctrineTypeMapping('ntext'));
986
987
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('binary'));
988
        self::assertSame('binary', $this->platform->getDoctrineTypeMapping('binary'));
989
990
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('varbinary'));
991
        self::assertSame('binary', $this->platform->getDoctrineTypeMapping('varbinary'));
992
993
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('image'));
994
        self::assertSame('blob', $this->platform->getDoctrineTypeMapping('image'));
995
996
        self::assertTrue($this->platform->hasDoctrineTypeMappingFor('uniqueidentifier'));
997
        self::assertSame('guid', $this->platform->getDoctrineTypeMapping('uniqueidentifier'));
998
    }
999
1000
    protected function getBinaryMaxLength() : int
1001
    {
1002
        return 8000;
1003
    }
1004
1005
    public function testReturnsBinaryTypeDeclarationSQL() : void
1006
    {
1007
        self::assertSame('VARBINARY(255)', $this->platform->getBinaryTypeDeclarationSQL([]));
1008
        self::assertSame('VARBINARY(255)', $this->platform->getBinaryTypeDeclarationSQL(['length' => 0]));
1009
        self::assertSame('VARBINARY(8000)', $this->platform->getBinaryTypeDeclarationSQL(['length' => 8000]));
1010
1011
        self::assertSame('BINARY(255)', $this->platform->getBinaryTypeDeclarationSQL(['fixed' => true]));
1012
        self::assertSame('BINARY(255)', $this->platform->getBinaryTypeDeclarationSQL(['fixed' => true, 'length' => 0]));
1013
        self::assertSame('BINARY(8000)', $this->platform->getBinaryTypeDeclarationSQL(['fixed' => true, 'length' => 8000]));
1014
    }
1015
1016
    /**
1017
     * @group legacy
1018
     * @expectedDeprecation Binary field length 8001 is greater than supported by the platform (8000). Reduce the field length or use a BLOB field instead.
1019
     */
1020
    public function testReturnsBinaryTypeLongerThanMaxDeclarationSQL() : void
1021
    {
1022
        self::assertSame('VARBINARY(MAX)', $this->platform->getBinaryTypeDeclarationSQL(['length' => 8001]));
1023
        self::assertSame('VARBINARY(MAX)', $this->platform->getBinaryTypeDeclarationSQL(['fixed' => true, 'length' => 8001]));
1024
    }
1025
1026
    /**
1027
     * {@inheritDoc}
1028
     *
1029
     * @group DBAL-234
1030
     */
1031
    protected function getAlterTableRenameIndexSQL() : array
1032
    {
1033
        return ["EXEC sp_RENAME N'mytable.idx_foo', N'idx_bar', N'INDEX'"];
1034
    }
1035
1036
    /**
1037
     * {@inheritDoc}
1038
     *
1039
     * @group DBAL-234
1040
     */
1041
    protected function getQuotedAlterTableRenameIndexSQL() : array
1042
    {
1043
        return [
1044
            "EXEC sp_RENAME N'[table].[create]', N'[select]', N'INDEX'",
1045
            "EXEC sp_RENAME N'[table].[foo]', N'[bar]', N'INDEX'",
1046
        ];
1047
    }
1048
1049
    /**
1050
     * @group DBAL-825
1051
     */
1052
    public function testChangeColumnsTypeWithDefaultValue() : void
1053
    {
1054
        $tableName = 'column_def_change_type';
1055
        $table     = new Table($tableName);
1056
1057
        $table->addColumn('col_int', 'smallint', ['default' => 666]);
1058
        $table->addColumn('col_string', 'string', ['default' => 'foo']);
1059
1060
        $tableDiff                            = new TableDiff($tableName);
1061
        $tableDiff->fromTable                 = $table;
1062
        $tableDiff->changedColumns['col_int'] = new ColumnDiff(
1063
            'col_int',
1064
            new Column('col_int', Type::getType('integer'), ['default' => 666]),
1065
            ['type'],
1066
            new Column('col_int', Type::getType('smallint'), ['default' => 666])
1067
        );
1068
1069
        $tableDiff->changedColumns['col_string'] = new ColumnDiff(
1070
            'col_string',
1071
            new Column('col_string', Type::getType('string'), ['default' => 666, 'fixed' => true]),
1072
            ['fixed'],
1073
            new Column('col_string', Type::getType('string'), ['default' => 666])
1074
        );
1075
1076
        $expected = $this->platform->getAlterTableSQL($tableDiff);
1077
1078
        self::assertSame(
1079
            $expected,
1080
            [
1081
                'ALTER TABLE column_def_change_type DROP CONSTRAINT DF_829302E0_FA2CB292',
1082
                'ALTER TABLE column_def_change_type ALTER COLUMN col_int INT NOT NULL',
1083
                'ALTER TABLE column_def_change_type ADD CONSTRAINT DF_829302E0_FA2CB292 DEFAULT 666 FOR col_int',
1084
                'ALTER TABLE column_def_change_type DROP CONSTRAINT DF_829302E0_2725A6D0',
1085
                'ALTER TABLE column_def_change_type ALTER COLUMN col_string NCHAR(255) NOT NULL',
1086
                "ALTER TABLE column_def_change_type ADD CONSTRAINT DF_829302E0_2725A6D0 DEFAULT '666' FOR col_string",
1087
            ]
1088
        );
1089
    }
1090
1091
    /**
1092
     * {@inheritdoc}
1093
     */
1094
    protected function getQuotedAlterTableRenameColumnSQL() : array
1095
    {
1096
        return [
1097
            "sp_RENAME 'mytable.unquoted1', 'unquoted', 'COLUMN'",
1098
            "sp_RENAME 'mytable.unquoted2', '[where]', 'COLUMN'",
1099
            "sp_RENAME 'mytable.unquoted3', '[foo]', 'COLUMN'",
1100
            "sp_RENAME 'mytable.[create]', 'reserved_keyword', 'COLUMN'",
1101
            "sp_RENAME 'mytable.[table]', '[from]', 'COLUMN'",
1102
            "sp_RENAME 'mytable.[select]', '[bar]', 'COLUMN'",
1103
            "sp_RENAME 'mytable.quoted1', 'quoted', 'COLUMN'",
1104
            "sp_RENAME 'mytable.quoted2', '[and]', 'COLUMN'",
1105
            "sp_RENAME 'mytable.quoted3', '[baz]', 'COLUMN'",
1106
        ];
1107
    }
1108
1109
    /**
1110
     * {@inheritdoc}
1111
     */
1112
    protected function getQuotedAlterTableChangeColumnLengthSQL() : array
1113
    {
1114
        $this->markTestIncomplete('Not implemented yet');
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return array. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
1115
    }
1116
1117
    /**
1118
     * {@inheritDoc}
1119
     *
1120
     * @group DBAL-807
1121
     */
1122
    protected function getAlterTableRenameIndexInSchemaSQL() : array
1123
    {
1124
        return ["EXEC sp_RENAME N'myschema.mytable.idx_foo', N'idx_bar', N'INDEX'"];
1125
    }
1126
1127
    /**
1128
     * {@inheritDoc}
1129
     *
1130
     * @group DBAL-807
1131
     */
1132
    protected function getQuotedAlterTableRenameIndexInSchemaSQL() : array
1133
    {
1134
        return [
1135
            "EXEC sp_RENAME N'[schema].[table].[create]', N'[select]', N'INDEX'",
1136
            "EXEC sp_RENAME N'[schema].[table].[foo]', N'[bar]', N'INDEX'",
1137
        ];
1138
    }
1139
1140
    protected function getQuotesDropForeignKeySQL() : string
1141
    {
1142
        return 'ALTER TABLE [table] DROP CONSTRAINT [select]';
1143
    }
1144
1145
    protected function getQuotesDropConstraintSQL() : string
1146
    {
1147
        return 'ALTER TABLE [table] DROP CONSTRAINT [select]';
1148
    }
1149
1150
    /**
1151
     * @param mixed[] $column
1152
     *
1153
     * @dataProvider getGeneratesIdentifierNamesInDefaultConstraintDeclarationSQL
1154
     * @group DBAL-830
1155
     */
1156
    public function testGeneratesIdentifierNamesInDefaultConstraintDeclarationSQL(string $table, array $column, string $expectedSql) : void
1157
    {
1158
        self::assertSame($expectedSql, $this->platform->getDefaultConstraintDeclarationSQL($table, $column));
0 ignored issues
show
Bug introduced by
The method getDefaultConstraintDeclarationSQL() does not exist on Doctrine\DBAL\Platforms\AbstractPlatform. It seems like you code against a sub-type of Doctrine\DBAL\Platforms\AbstractPlatform such as Doctrine\DBAL\Platforms\SQLServerPlatform. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1158
        self::assertSame($expectedSql, $this->platform->/** @scrutinizer ignore-call */ getDefaultConstraintDeclarationSQL($table, $column));
Loading history...
1159
    }
1160
1161
    /**
1162
     * @return mixed[][]
1163
     */
1164
    public static function getGeneratesIdentifierNamesInDefaultConstraintDeclarationSQL() : iterable
1165
    {
1166
        return [
1167
            // Unquoted identifiers non-reserved keywords.
1168
            ['mytable', ['name' => 'mycolumn', 'default' => 'foo'], " CONSTRAINT DF_6B2BD609_9BADD926 DEFAULT 'foo' FOR mycolumn"],
1169
            // Quoted identifiers non-reserved keywords.
1170
            ['`mytable`', ['name' => '`mycolumn`', 'default' => 'foo'], " CONSTRAINT DF_6B2BD609_9BADD926 DEFAULT 'foo' FOR [mycolumn]"],
1171
            // Unquoted identifiers reserved keywords.
1172
            ['table', ['name' => 'select', 'default' => 'foo'], " CONSTRAINT DF_F6298F46_4BF2EAC0 DEFAULT 'foo' FOR [select]"],
1173
            // Quoted identifiers reserved keywords.
1174
            ['`table`', ['name' => '`select`', 'default' => 'foo'], " CONSTRAINT DF_F6298F46_4BF2EAC0 DEFAULT 'foo' FOR [select]"],
1175
        ];
1176
    }
1177
1178
    /**
1179
     * @param string[] $expectedSql
1180
     *
1181
     * @dataProvider getGeneratesIdentifierNamesInCreateTableSQL
1182
     * @group DBAL-830
1183
     */
1184
    public function testGeneratesIdentifierNamesInCreateTableSQL(Table $table, array $expectedSql) : void
1185
    {
1186
        self::assertSame($expectedSql, $this->platform->getCreateTableSQL($table));
1187
    }
1188
1189
    /**
1190
     * @return mixed[][]
1191
     */
1192
    public static function getGeneratesIdentifierNamesInCreateTableSQL() : iterable
1193
    {
1194
        return [
1195
            // Unquoted identifiers non-reserved keywords.
1196
            [
1197
                new Table('mytable', [new Column('mycolumn', Type::getType('string'), ['default' => 'foo'])]),
1198
                [
1199
                    'CREATE TABLE mytable (mycolumn NVARCHAR(255) NOT NULL)',
1200
                    "ALTER TABLE mytable ADD CONSTRAINT DF_6B2BD609_9BADD926 DEFAULT 'foo' FOR mycolumn",
1201
                ],
1202
            ],
1203
            // Quoted identifiers reserved keywords.
1204
            [
1205
                new Table('`mytable`', [new Column('`mycolumn`', Type::getType('string'), ['default' => 'foo'])]),
1206
                [
1207
                    'CREATE TABLE [mytable] ([mycolumn] NVARCHAR(255) NOT NULL)',
1208
                    "ALTER TABLE [mytable] ADD CONSTRAINT DF_6B2BD609_9BADD926 DEFAULT 'foo' FOR [mycolumn]",
1209
                ],
1210
            ],
1211
            // Unquoted identifiers reserved keywords.
1212
            [
1213
                new Table('table', [new Column('select', Type::getType('string'), ['default' => 'foo'])]),
1214
                [
1215
                    'CREATE TABLE [table] ([select] NVARCHAR(255) NOT NULL)',
1216
                    "ALTER TABLE [table] ADD CONSTRAINT DF_F6298F46_4BF2EAC0 DEFAULT 'foo' FOR [select]",
1217
                ],
1218
            ],
1219
            // Quoted identifiers reserved keywords.
1220
            [
1221
                new Table('`table`', [new Column('`select`', Type::getType('string'), ['default' => 'foo'])]),
1222
                [
1223
                    'CREATE TABLE [table] ([select] NVARCHAR(255) NOT NULL)',
1224
                    "ALTER TABLE [table] ADD CONSTRAINT DF_F6298F46_4BF2EAC0 DEFAULT 'foo' FOR [select]",
1225
                ],
1226
            ],
1227
        ];
1228
    }
1229
1230
    /**
1231
     * @param string[] $expectedSql
1232
     *
1233
     * @dataProvider getGeneratesIdentifierNamesInAlterTableSQL
1234
     * @group DBAL-830
1235
     */
1236
    public function testGeneratesIdentifierNamesInAlterTableSQL(TableDiff $tableDiff, array $expectedSql) : void
1237
    {
1238
        self::assertSame($expectedSql, $this->platform->getAlterTableSQL($tableDiff));
1239
    }
1240
1241
    /**
1242
     * @return mixed[][]
1243
     */
1244
    public static function getGeneratesIdentifierNamesInAlterTableSQL() : iterable
1245
    {
1246
        return [
1247
            // Unquoted identifiers non-reserved keywords.
1248
            [
1249
                new TableDiff(
1250
                    'mytable',
1251
                    [new Column('addcolumn', Type::getType('string'), ['default' => 'foo'])],
1252
                    [
1253
                        'mycolumn' => new ColumnDiff(
1254
                            'mycolumn',
1255
                            new Column('mycolumn', Type::getType('string'), ['default' => 'bar']),
1256
                            ['default'],
1257
                            new Column('mycolumn', Type::getType('string'), ['default' => 'foo'])
1258
                        ),
1259
                    ],
1260
                    [new Column('removecolumn', Type::getType('string'), ['default' => 'foo'])]
1261
                ),
1262
                [
1263
                    'ALTER TABLE mytable ADD addcolumn NVARCHAR(255) NOT NULL',
1264
                    "ALTER TABLE mytable ADD CONSTRAINT DF_6B2BD609_4AD86123 DEFAULT 'foo' FOR addcolumn",
1265
                    'ALTER TABLE mytable DROP COLUMN removecolumn',
1266
                    'ALTER TABLE mytable DROP CONSTRAINT DF_6B2BD609_9BADD926',
1267
                    'ALTER TABLE mytable ALTER COLUMN mycolumn NVARCHAR(255) NOT NULL',
1268
                    "ALTER TABLE mytable ADD CONSTRAINT DF_6B2BD609_9BADD926 DEFAULT 'bar' FOR mycolumn",
1269
                ],
1270
            ],
1271
            // Quoted identifiers non-reserved keywords.
1272
            [
1273
                new TableDiff(
1274
                    '`mytable`',
1275
                    [new Column('`addcolumn`', Type::getType('string'), ['default' => 'foo'])],
1276
                    [
1277
                        'mycolumn' => new ColumnDiff(
1278
                            '`mycolumn`',
1279
                            new Column('`mycolumn`', Type::getType('string'), ['default' => 'bar']),
1280
                            ['default'],
1281
                            new Column('`mycolumn`', Type::getType('string'), ['default' => 'foo'])
1282
                        ),
1283
                    ],
1284
                    [new Column('`removecolumn`', Type::getType('string'), ['default' => 'foo'])]
1285
                ),
1286
                [
1287
                    'ALTER TABLE [mytable] ADD [addcolumn] NVARCHAR(255) NOT NULL',
1288
                    "ALTER TABLE [mytable] ADD CONSTRAINT DF_6B2BD609_4AD86123 DEFAULT 'foo' FOR [addcolumn]",
1289
                    'ALTER TABLE [mytable] DROP COLUMN [removecolumn]',
1290
                    'ALTER TABLE [mytable] DROP CONSTRAINT DF_6B2BD609_9BADD926',
1291
                    'ALTER TABLE [mytable] ALTER COLUMN [mycolumn] NVARCHAR(255) NOT NULL',
1292
                    "ALTER TABLE [mytable] ADD CONSTRAINT DF_6B2BD609_9BADD926 DEFAULT 'bar' FOR [mycolumn]",
1293
                ],
1294
            ],
1295
            // Unquoted identifiers reserved keywords.
1296
            [
1297
                new TableDiff(
1298
                    'table',
1299
                    [new Column('add', Type::getType('string'), ['default' => 'foo'])],
1300
                    [
1301
                        'select' => new ColumnDiff(
1302
                            'select',
1303
                            new Column('select', Type::getType('string'), ['default' => 'bar']),
1304
                            ['default'],
1305
                            new Column('select', Type::getType('string'), ['default' => 'foo'])
1306
                        ),
1307
                    ],
1308
                    [new Column('drop', Type::getType('string'), ['default' => 'foo'])]
1309
                ),
1310
                [
1311
                    'ALTER TABLE [table] ADD [add] NVARCHAR(255) NOT NULL',
1312
                    "ALTER TABLE [table] ADD CONSTRAINT DF_F6298F46_FD1A73E7 DEFAULT 'foo' FOR [add]",
1313
                    'ALTER TABLE [table] DROP COLUMN [drop]',
1314
                    'ALTER TABLE [table] DROP CONSTRAINT DF_F6298F46_4BF2EAC0',
1315
                    'ALTER TABLE [table] ALTER COLUMN [select] NVARCHAR(255) NOT NULL',
1316
                    "ALTER TABLE [table] ADD CONSTRAINT DF_F6298F46_4BF2EAC0 DEFAULT 'bar' FOR [select]",
1317
                ],
1318
            ],
1319
            // Quoted identifiers reserved keywords.
1320
            [
1321
                new TableDiff(
1322
                    '`table`',
1323
                    [new Column('`add`', Type::getType('string'), ['default' => 'foo'])],
1324
                    [
1325
                        'select' => new ColumnDiff(
1326
                            '`select`',
1327
                            new Column('`select`', Type::getType('string'), ['default' => 'bar']),
1328
                            ['default'],
1329
                            new Column('`select`', Type::getType('string'), ['default' => 'foo'])
1330
                        ),
1331
                    ],
1332
                    [new Column('`drop`', Type::getType('string'), ['default' => 'foo'])]
1333
                ),
1334
                [
1335
                    'ALTER TABLE [table] ADD [add] NVARCHAR(255) NOT NULL',
1336
                    "ALTER TABLE [table] ADD CONSTRAINT DF_F6298F46_FD1A73E7 DEFAULT 'foo' FOR [add]",
1337
                    'ALTER TABLE [table] DROP COLUMN [drop]',
1338
                    'ALTER TABLE [table] DROP CONSTRAINT DF_F6298F46_4BF2EAC0',
1339
                    'ALTER TABLE [table] ALTER COLUMN [select] NVARCHAR(255) NOT NULL',
1340
                    "ALTER TABLE [table] ADD CONSTRAINT DF_F6298F46_4BF2EAC0 DEFAULT 'bar' FOR [select]",
1341
                ],
1342
            ],
1343
        ];
1344
    }
1345
1346
    /**
1347
     * @group DBAL-423
1348
     */
1349
    public function testReturnsGuidTypeDeclarationSQL() : void
1350
    {
1351
        self::assertSame('UNIQUEIDENTIFIER', $this->platform->getGuidTypeDeclarationSQL([]));
1352
    }
1353
1354
    /**
1355
     * {@inheritdoc}
1356
     */
1357
    public function getAlterTableRenameColumnSQL() : array
1358
    {
1359
        return [
1360
            "sp_RENAME 'foo.bar', 'baz', 'COLUMN'",
1361
            'ALTER TABLE foo DROP CONSTRAINT DF_8C736521_76FF8CAA',
1362
            'ALTER TABLE foo ADD CONSTRAINT DF_8C736521_78240498 DEFAULT 666 FOR baz',
1363
        ];
1364
    }
1365
1366
    /**
1367
     * {@inheritdoc}
1368
     */
1369
    protected function getQuotesTableIdentifiersInAlterTableSQL() : array
1370
    {
1371
        return [
1372
            'ALTER TABLE [foo] DROP CONSTRAINT fk1',
1373
            'ALTER TABLE [foo] DROP CONSTRAINT fk2',
1374
            "sp_RENAME '[foo].id', 'war', 'COLUMN'",
1375
            'ALTER TABLE [foo] ADD bloo INT NOT NULL',
1376
            'ALTER TABLE [foo] DROP COLUMN baz',
1377
            'ALTER TABLE [foo] ALTER COLUMN bar INT',
1378
            "sp_RENAME '[foo]', 'table'",
1379
            "DECLARE @sql NVARCHAR(MAX) = N''; " .
1380
            "SELECT @sql += N'EXEC sp_rename N''' + dc.name + ''', N''' + REPLACE(dc.name, '8C736521', 'F6298F46') + ''', " .
1381
            "''OBJECT'';' FROM sys.default_constraints dc JOIN sys.tables tbl ON dc.parent_object_id = tbl.object_id " .
1382
            "WHERE tbl.name = 'table';EXEC sp_executesql @sql",
1383
            'ALTER TABLE [table] ADD CONSTRAINT fk_add FOREIGN KEY (fk3) REFERENCES fk_table (id)',
1384
            'ALTER TABLE [table] ADD CONSTRAINT fk2 FOREIGN KEY (fk2) REFERENCES fk_table2 (id)',
1385
        ];
1386
    }
1387
1388
    /**
1389
     * {@inheritdoc}
1390
     */
1391
    protected function getCommentOnColumnSQL() : array
1392
    {
1393
        return [
1394
            "COMMENT ON COLUMN foo.bar IS 'comment'",
1395
            "COMMENT ON COLUMN [Foo].[BAR] IS 'comment'",
1396
            "COMMENT ON COLUMN [select].[from] IS 'comment'",
1397
        ];
1398
    }
1399
1400
    /**
1401
     * {@inheritdoc}
1402
     */
1403
    public static function getReturnsForeignKeyReferentialActionSQL() : iterable
1404
    {
1405
        return [
1406
            ['CASCADE', 'CASCADE'],
1407
            ['SET NULL', 'SET NULL'],
1408
            ['NO ACTION', 'NO ACTION'],
1409
            ['RESTRICT', 'NO ACTION'],
1410
            ['SET DEFAULT', 'SET DEFAULT'],
1411
            ['CaScAdE', 'CASCADE'],
1412
        ];
1413
    }
1414
1415
    /**
1416
     * {@inheritdoc}
1417
     */
1418
    protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL() : string
1419
    {
1420
        return 'CONSTRAINT [select] UNIQUE (foo) WHERE foo IS NOT NULL';
1421
    }
1422
1423
    /**
1424
     * {@inheritdoc}
1425
     */
1426
    protected function getQuotesReservedKeywordInIndexDeclarationSQL() : string
1427
    {
1428
        return 'INDEX [select] (foo)';
1429
    }
1430
1431
    /**
1432
     * {@inheritdoc}
1433
     */
1434
    protected function getQuotesReservedKeywordInTruncateTableSQL() : string
1435
    {
1436
        return 'TRUNCATE TABLE [select]';
1437
    }
1438
1439
    /**
1440
     * {@inheritdoc}
1441
     */
1442
    protected function getAlterStringToFixedStringSQL() : array
1443
    {
1444
        return ['ALTER TABLE mytable ALTER COLUMN name NCHAR(2) NOT NULL'];
1445
    }
1446
1447
    /**
1448
     * {@inheritdoc}
1449
     */
1450
    protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL() : array
1451
    {
1452
        return ["EXEC sp_RENAME N'mytable.idx_foo', N'idx_foo_renamed', N'INDEX'"];
1453
    }
1454
1455
    public function testModifyLimitQueryWithTopNSubQueryWithOrderBy() : void
1456
    {
1457
        $querySql   = 'SELECT * FROM test t WHERE t.id = (SELECT TOP 1 t2.id FROM test t2 ORDER BY t2.data DESC)';
1458
        $alteredSql = 'SELECT TOP 10 * FROM test t WHERE t.id = (SELECT TOP 1 t2.id FROM test t2 ORDER BY t2.data DESC)';
1459
        $sql        = $this->platform->modifyLimitQuery($querySql, 10);
1460
        $this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
1461
1462
        $querySql   = 'SELECT * FROM test t WHERE t.id = (SELECT TOP 1 t2.id FROM test t2 ORDER BY t2.data DESC) ORDER BY t.data2 DESC';
1463
        $alteredSql = 'SELECT TOP 10 * FROM test t WHERE t.id = (SELECT TOP 1 t2.id FROM test t2 ORDER BY t2.data DESC) ORDER BY t.data2 DESC';
1464
        $sql        = $this->platform->modifyLimitQuery($querySql, 10);
1465
        $this->expectCteWithMaxRowNum($alteredSql, 10, $sql);
1466
    }
1467
1468
    /**
1469
     * @group DBAL-2436
1470
     */
1471
    public function testQuotesTableNameInListTableColumnsSQL() : void
1472
    {
1473
        self::assertStringContainsStringIgnoringCase(
1474
            "'Foo''Bar\\'",
1475
            $this->platform->getListTableColumnsSQL("Foo'Bar\\")
1476
        );
1477
    }
1478
1479
    /**
1480
     * @group DBAL-2436
1481
     */
1482
    public function testQuotesSchemaNameInListTableColumnsSQL() : void
1483
    {
1484
        self::assertStringContainsStringIgnoringCase(
1485
            "'Foo''Bar\\'",
1486
            $this->platform->getListTableColumnsSQL("Foo'Bar\\.baz_table")
1487
        );
1488
    }
1489
1490
    /**
1491
     * @group DBAL-2436
1492
     */
1493
    public function testQuotesTableNameInListTableForeignKeysSQL() : void
1494
    {
1495
        self::assertStringContainsStringIgnoringCase(
1496
            "'Foo''Bar\\'",
1497
            $this->platform->getListTableForeignKeysSQL("Foo'Bar\\")
1498
        );
1499
    }
1500
1501
    /**
1502
     * @group DBAL-2436
1503
     */
1504
    public function testQuotesSchemaNameInListTableForeignKeysSQL() : void
1505
    {
1506
        self::assertStringContainsStringIgnoringCase(
1507
            "'Foo''Bar\\'",
1508
            $this->platform->getListTableForeignKeysSQL("Foo'Bar\\.baz_table")
1509
        );
1510
    }
1511
1512
    /**
1513
     * @group DBAL-2436
1514
     */
1515
    public function testQuotesTableNameInListTableIndexesSQL() : void
1516
    {
1517
        self::assertStringContainsStringIgnoringCase(
1518
            "'Foo''Bar\\'",
1519
            $this->platform->getListTableIndexesSQL("Foo'Bar\\")
1520
        );
1521
    }
1522
1523
    /**
1524
     * @group DBAL-2436
1525
     */
1526
    public function testQuotesSchemaNameInListTableIndexesSQL() : void
1527
    {
1528
        self::assertStringContainsStringIgnoringCase(
1529
            "'Foo''Bar\\'",
1530
            $this->platform->getListTableIndexesSQL("Foo'Bar\\.baz_table")
1531
        );
1532
    }
1533
1534
    /**
1535
     * @group 2859
1536
     */
1537
    public function testGetDefaultValueDeclarationSQLForDateType() : void
1538
    {
1539
        $currentDateSql = $this->platform->getCurrentDateSQL();
1540
        foreach (['date', 'date_immutable'] as $type) {
1541
            $field = [
1542
                'type' => Type::getType($type),
1543
                'default' => $currentDateSql,
1544
            ];
1545
1546
            self::assertSame(
1547
                ' DEFAULT CONVERT(date, GETDATE())',
1548
                $this->platform->getDefaultValueDeclarationSQL($field)
1549
            );
1550
        }
1551
    }
1552
1553
    public function testSupportsColumnCollation() : void
1554
    {
1555
        self::assertTrue($this->platform->supportsColumnCollation());
1556
    }
1557
1558
    public function testColumnCollationDeclarationSQL() : void
1559
    {
1560
        self::assertSame(
1561
            'COLLATE Latin1_General_CS_AS_KS_WS',
1562
            $this->platform->getColumnCollationDeclarationSQL('Latin1_General_CS_AS_KS_WS')
1563
        );
1564
    }
1565
1566
    public function testGetCreateTableSQLWithColumnCollation() : void
1567
    {
1568
        $table = new Table('foo');
1569
        $table->addColumn('no_collation', 'string');
1570
        $table->addColumn('column_collation', 'string')->setPlatformOption('collation', 'Latin1_General_CS_AS_KS_WS');
1571
1572
        self::assertSame(
1573
            ['CREATE TABLE foo (no_collation NVARCHAR(255) NOT NULL, column_collation NVARCHAR(255) COLLATE Latin1_General_CS_AS_KS_WS NOT NULL)'],
1574
            $this->platform->getCreateTableSQL($table),
1575
            'Column "no_collation" will use the default collation from the table/database and "column_collation" overwrites the collation on this column'
1576
        );
1577
    }
1578
1579
    private function expectCteWithMaxRowNum(string $expectedSql, int $expectedMax, string $sql) : void
1580
    {
1581
        $pattern = 'WITH dctrn_cte AS (%s) SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS doctrine_rownum FROM dctrn_cte) AS doctrine_tbl WHERE doctrine_rownum <= %d ORDER BY doctrine_rownum ASC';
1582
        self::assertEquals(sprintf($pattern, $expectedSql, $expectedMax), $sql);
1583
    }
1584
1585
    private function expectCteWithMinAndMaxRowNums(string $expectedSql, int $expectedMin, int $expectedMax, string $sql) : void
1586
    {
1587
        $pattern = 'WITH dctrn_cte AS (%s) SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS doctrine_rownum FROM dctrn_cte) AS doctrine_tbl WHERE doctrine_rownum >= %d AND doctrine_rownum <= %d ORDER BY doctrine_rownum ASC';
1588
        self::assertEquals(sprintf($pattern, $expectedSql, $expectedMin, $expectedMax), $sql);
1589
    }
1590
1591
    public function testIndexCreationSyntax(): void {
1592
        $table = new Table(
1593
            'foo',
1594
            [
1595
                'id' => new Column(
1596
                    'id',
1597
                    Type::getType(Type::INTEGER),
0 ignored issues
show
Deprecated Code introduced by
The constant Doctrine\DBAL\Types\Type::INTEGER has been deprecated: Use {@see DefaultTypes::INTEGER} instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1597
                    Type::getType(/** @scrutinizer ignore-deprecated */ Type::INTEGER),

This class constant has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the constant will be removed from the class and what other constant to use instead.

Loading history...
1598
                    ['autoincrement' => true, 'notNull' => true]
1599
                ),
1600
                'idA' => new Column(
1601
                    'workspace_id',
1602
                    Type::getType(Type::INTEGER),
0 ignored issues
show
Deprecated Code introduced by
The constant Doctrine\DBAL\Types\Type::INTEGER has been deprecated: Use {@see DefaultTypes::INTEGER} instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1602
                    Type::getType(/** @scrutinizer ignore-deprecated */ Type::INTEGER),

This class constant has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the constant will be removed from the class and what other constant to use instead.

Loading history...
1603
                    ['default' => null, 'notNull' => false]
1604
                ),
1605
                'idB' => new Column(
1606
                    'search_engine_id',
1607
                    Type::getType(Type::INTEGER),
0 ignored issues
show
Deprecated Code introduced by
The constant Doctrine\DBAL\Types\Type::INTEGER has been deprecated: Use {@see DefaultTypes::INTEGER} instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1607
                    Type::getType(/** @scrutinizer ignore-deprecated */ Type::INTEGER),

This class constant has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the constant will be removed from the class and what other constant to use instead.

Loading history...
1608
                    ['default' => null, 'notNull' => false]
1609
                ),
1610
            ],
1611
            [
1612
                new Index(
1613
                    'key_COMPOUND',
1614
                    [
1615
                        'idA',
1616
                        'idB'
1617
                    ],
1618
                    true
1619
                ),
1620
                new Index(
1621
                    'PRIMARY',
1622
                    ['id'],
1623
                    true,
1624
                    true
1625
                )
1626
            ]
1627
        );
1628
        $schema = new Schema([$table]);
1629
        $queries = $schema->toSql($this->platform);
1630
1631
        self::assertSame(
1632
            [
1633
                'CREATE TABLE foo (id INT IDENTITY NOT NULL, workspace_id INT, search_engine_id INT, PRIMARY KEY (id))',
1634
                'CREATE UNIQUE INDEX key_COMPOUND ON foo (idA, idB)'
1635
            ],
1636
            $queries
1637
        );
1638
    }
1639
}
1640