Completed
Pull Request — 2.10 (#3876)
by Grégoire
65:18 queued 01:42
created

testGetDropTableSqlDispatchEvent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 15
rs 9.9332
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Doctrine\Tests\DBAL\Platforms;
4
5
use Doctrine\Common\EventManager;
6
use Doctrine\DBAL\DBALException;
7
use Doctrine\DBAL\Events;
8
use Doctrine\DBAL\Platforms\AbstractPlatform;
9
use Doctrine\DBAL\Platforms\Keywords\KeywordList;
10
use Doctrine\DBAL\Schema\Column;
11
use Doctrine\DBAL\Schema\ColumnDiff;
12
use Doctrine\DBAL\Schema\Comparator;
13
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
14
use Doctrine\DBAL\Schema\Index;
15
use Doctrine\DBAL\Schema\Table;
16
use Doctrine\DBAL\Schema\TableDiff;
17
use Doctrine\DBAL\Types\Type;
18
use Doctrine\Tests\DbalTestCase;
19
use Doctrine\Tests\Types\CommentedType;
20
use function get_class;
21
use function implode;
22
use function sprintf;
23
use function str_repeat;
24
25
abstract class AbstractPlatformTestCase extends DbalTestCase
26
{
27
    /** @var AbstractPlatform */
28
    protected $platform;
29
30
    abstract public function createPlatform() : AbstractPlatform;
31
32
    protected function setUp() : void
33
    {
34
        $this->platform = $this->createPlatform();
35
    }
36
37
    /**
38
     * @group DDC-1360
39
     */
40
    public function testQuoteIdentifier() : void
41
    {
42
        if ($this->platform->getName() === 'mssql') {
43
            $this->markTestSkipped('Not working this way on mssql.');
44
        }
45
46
        $c = $this->platform->getIdentifierQuoteCharacter();
47
        self::assertEquals($c . 'test' . $c, $this->platform->quoteIdentifier('test'));
48
        self::assertEquals($c . 'test' . $c . '.' . $c . 'test' . $c, $this->platform->quoteIdentifier('test.test'));
49
        self::assertEquals(str_repeat($c, 4), $this->platform->quoteIdentifier($c));
50
    }
51
52
    /**
53
     * @group DDC-1360
54
     */
55
    public function testQuoteSingleIdentifier() : void
56
    {
57
        if ($this->platform->getName() === 'mssql') {
58
            $this->markTestSkipped('Not working this way on mssql.');
59
        }
60
61
        $c = $this->platform->getIdentifierQuoteCharacter();
62
        self::assertEquals($c . 'test' . $c, $this->platform->quoteSingleIdentifier('test'));
63
        self::assertEquals($c . 'test.test' . $c, $this->platform->quoteSingleIdentifier('test.test'));
64
        self::assertEquals(str_repeat($c, 4), $this->platform->quoteSingleIdentifier($c));
65
    }
66
67
    /**
68
     * @group DBAL-1029
69
     * @dataProvider getReturnsForeignKeyReferentialActionSQL
70
     */
71
    public function testReturnsForeignKeyReferentialActionSQL(string $action, string $expectedSQL) : void
72
    {
73
        self::assertSame($expectedSQL, $this->platform->getForeignKeyReferentialActionSQL($action));
74
    }
75
76
    /**
77
     * @return mixed[][]
78
     */
79
    public static function getReturnsForeignKeyReferentialActionSQL() : iterable
80
    {
81
        return [
82
            ['CASCADE', 'CASCADE'],
83
            ['SET NULL', 'SET NULL'],
84
            ['NO ACTION', 'NO ACTION'],
85
            ['RESTRICT', 'RESTRICT'],
86
            ['SET DEFAULT', 'SET DEFAULT'],
87
            ['CaScAdE', 'CASCADE'],
88
        ];
89
    }
90
91
    public function testGetInvalidForeignKeyReferentialActionSQL() : void
92
    {
93
        $this->expectException('InvalidArgumentException');
94
        $this->platform->getForeignKeyReferentialActionSQL('unknown');
95
    }
96
97
    public function testGetUnknownDoctrineMappingType() : void
98
    {
99
        $this->expectException(DBALException::class);
100
        $this->platform->getDoctrineTypeMapping('foobar');
101
    }
102
103
    public function testRegisterDoctrineMappingType() : void
104
    {
105
        $this->platform->registerDoctrineTypeMapping('foo', 'integer');
106
        self::assertEquals('integer', $this->platform->getDoctrineTypeMapping('foo'));
107
    }
108
109
    public function testRegisterUnknownDoctrineMappingType() : void
110
    {
111
        $this->expectException(DBALException::class);
112
        $this->platform->registerDoctrineTypeMapping('foo', 'bar');
113
    }
114
115
    /**
116
     * @group DBAL-2594
117
     */
118
    public function testRegistersCommentedDoctrineMappingTypeImplicitly() : void
119
    {
120
        if (! Type::hasType('my_commented')) {
121
            Type::addType('my_commented', CommentedType::class);
122
        }
123
124
        $type = Type::getType('my_commented');
125
        $this->platform->registerDoctrineTypeMapping('foo', 'my_commented');
126
127
        self::assertTrue($this->platform->isCommentedDoctrineType($type));
128
    }
129
130
    /**
131
     * @group DBAL-939
132
     * @dataProvider getIsCommentedDoctrineType
133
     */
134
    public function testIsCommentedDoctrineType(Type $type, bool $commented) : void
135
    {
136
        self::assertSame($commented, $this->platform->isCommentedDoctrineType($type));
137
    }
138
139
    /**
140
     * @return mixed[]
141
     */
142
    public function getIsCommentedDoctrineType() : iterable
143
    {
144
        $this->setUp();
145
146
        $data = [];
147
148
        foreach (Type::getTypesMap() as $typeName => $className) {
149
            $type = Type::getType($typeName);
150
151
            $data[$typeName] = [
152
                $type,
153
                $type->requiresSQLCommentHint($this->platform),
154
            ];
155
        }
156
157
        return $data;
158
    }
159
160
    public function testCreateWithNoColumns() : void
161
    {
162
        $table = new Table('test');
163
164
        $this->expectException(DBALException::class);
165
        $sql = $this->platform->getCreateTableSQL($table);
0 ignored issues
show
Unused Code introduced by
The assignment to $sql is dead and can be removed.
Loading history...
166
    }
167
168
    public function testGeneratesTableCreationSql() : void
169
    {
170
        $table = new Table('test');
171
        $table->addColumn('id', 'integer', ['notnull' => true, 'autoincrement' => true]);
172
        $table->addColumn('test', 'string', ['notnull' => false, 'length' => 255]);
173
        $table->setPrimaryKey(['id']);
174
175
        $sql = $this->platform->getCreateTableSQL($table);
176
        self::assertEquals($this->getGenerateTableSql(), $sql[0]);
177
    }
178
179
    abstract public function getGenerateTableSql() : string;
180
181
    public function testGenerateTableWithMultiColumnUniqueIndex() : void
182
    {
183
        $table = new Table('test');
184
        $table->addColumn('foo', 'string', ['notnull' => false, 'length' => 255]);
185
        $table->addColumn('bar', 'string', ['notnull' => false, 'length' => 255]);
186
        $table->addUniqueIndex(['foo', 'bar']);
187
188
        $sql = $this->platform->getCreateTableSQL($table);
189
        self::assertEquals($this->getGenerateTableWithMultiColumnUniqueIndexSql(), $sql);
190
    }
191
192
    /**
193
     * @return string[]
194
     */
195
    abstract public function getGenerateTableWithMultiColumnUniqueIndexSql() : array;
196
197
    public function testGeneratesIndexCreationSql() : void
198
    {
199
        $indexDef = new Index('my_idx', ['user_name', 'last_login']);
200
201
        self::assertEquals(
202
            $this->getGenerateIndexSql(),
203
            $this->platform->getCreateIndexSQL($indexDef, 'mytable')
204
        );
205
    }
206
207
    abstract public function getGenerateIndexSql() : string;
208
209
    public function testGeneratesUniqueIndexCreationSql() : void
210
    {
211
        $indexDef = new Index('index_name', ['test', 'test2'], true);
212
213
        $sql = $this->platform->getCreateIndexSQL($indexDef, 'test');
214
        self::assertEquals($this->getGenerateUniqueIndexSql(), $sql);
215
    }
216
217
    abstract public function getGenerateUniqueIndexSql() : string;
218
219
    public function testGeneratesPartialIndexesSqlOnlyWhenSupportingPartialIndexes() : void
220
    {
221
        $where       = 'test IS NULL AND test2 IS NOT NULL';
222
        $indexDef    = new Index('name', ['test', 'test2'], false, false, [], ['where' => $where]);
223
        $uniqueIndex = new Index('name', ['test', 'test2'], true, false, [], ['where' => $where]);
224
225
        $expected = ' WHERE ' . $where;
226
227
        $actuals = [];
228
229
        if ($this->supportsInlineIndexDeclaration()) {
230
            $actuals[] = $this->platform->getIndexDeclarationSQL('name', $indexDef);
231
        }
232
233
        $actuals[] = $this->platform->getUniqueConstraintDeclarationSQL('name', $uniqueIndex);
234
        $actuals[] = $this->platform->getCreateIndexSQL($indexDef, 'table');
235
236
        foreach ($actuals as $actual) {
237
            if ($this->platform->supportsPartialIndexes()) {
238
                self::assertStringEndsWith($expected, $actual, 'WHERE clause should be present');
239
            } else {
240
                self::assertStringEndsNotWith($expected, $actual, 'WHERE clause should NOT be present');
241
            }
242
        }
243
    }
244
245
    public function testGeneratesForeignKeyCreationSql() : void
246
    {
247
        $fk = new ForeignKeyConstraint(['fk_name_id'], 'other_table', ['id'], '');
248
249
        $sql = $this->platform->getCreateForeignKeySQL($fk, 'test');
250
        self::assertEquals($sql, $this->getGenerateForeignKeySql());
251
    }
252
253
    abstract public function getGenerateForeignKeySql() : string;
254
255
    public function testGeneratesConstraintCreationSql() : void
256
    {
257
        $idx = new Index('constraint_name', ['test'], true, false);
258
        $sql = $this->platform->getCreateConstraintSQL($idx, 'test');
259
        self::assertEquals($this->getGenerateConstraintUniqueIndexSql(), $sql);
260
261
        $pk  = new Index('constraint_name', ['test'], true, true);
262
        $sql = $this->platform->getCreateConstraintSQL($pk, 'test');
263
        self::assertEquals($this->getGenerateConstraintPrimaryIndexSql(), $sql);
264
265
        $fk  = new ForeignKeyConstraint(['fk_name'], 'foreign', ['id'], 'constraint_fk');
266
        $sql = $this->platform->getCreateConstraintSQL($fk, 'test');
267
        self::assertEquals($this->getGenerateConstraintForeignKeySql($fk), $sql);
268
    }
269
270
    public function testGeneratesForeignKeySqlOnlyWhenSupportingForeignKeys() : void
271
    {
272
        $fk = new ForeignKeyConstraint(['fk_name'], 'foreign', ['id'], 'constraint_fk');
273
274
        if ($this->platform->supportsForeignKeyConstraints()) {
275
            self::assertIsString($this->platform->getCreateForeignKeySQL($fk, 'test'));
276
        } else {
277
            $this->expectException(DBALException::class);
278
            $this->platform->getCreateForeignKeySQL($fk, 'test');
279
        }
280
    }
281
282
    protected function getBitAndComparisonExpressionSql(string $value1, string $value2) : string
283
    {
284
        return '(' . $value1 . ' & ' . $value2 . ')';
285
    }
286
287
    /**
288
     * @group DDC-1213
289
     */
290
    public function testGeneratesBitAndComparisonExpressionSql() : void
291
    {
292
        $sql = $this->platform->getBitAndComparisonExpression(2, 4);
293
        self::assertEquals($this->getBitAndComparisonExpressionSql(2, 4), $sql);
294
    }
295
296
    protected function getBitOrComparisonExpressionSql(string $value1, string $value2) : string
297
    {
298
        return '(' . $value1 . ' | ' . $value2 . ')';
299
    }
300
301
    /**
302
     * @group DDC-1213
303
     */
304
    public function testGeneratesBitOrComparisonExpressionSql() : void
305
    {
306
        $sql = $this->platform->getBitOrComparisonExpression(2, 4);
307
        self::assertEquals($this->getBitOrComparisonExpressionSql(2, 4), $sql);
308
    }
309
310
    public function getGenerateConstraintUniqueIndexSql() : string
311
    {
312
        return 'ALTER TABLE test ADD CONSTRAINT constraint_name UNIQUE (test)';
313
    }
314
315
    public function getGenerateConstraintPrimaryIndexSql() : string
316
    {
317
        return 'ALTER TABLE test ADD CONSTRAINT constraint_name PRIMARY KEY (test)';
318
    }
319
320
    public function getGenerateConstraintForeignKeySql(ForeignKeyConstraint $fk) : string
321
    {
322
        $quotedForeignTable = $fk->getQuotedForeignTableName($this->platform);
323
324
        return sprintf(
325
            'ALTER TABLE test ADD CONSTRAINT constraint_fk FOREIGN KEY (fk_name) REFERENCES %s (id)',
326
            $quotedForeignTable
327
        );
328
    }
329
330
    /**
331
     * @return string[]
332
     */
333
    abstract public function getGenerateAlterTableSql() : array;
334
335
    public function testGeneratesTableAlterationSql() : void
336
    {
337
        $expectedSql = $this->getGenerateAlterTableSql();
338
339
        $table = new Table('mytable');
340
        $table->addColumn('id', 'integer', ['autoincrement' => true]);
341
        $table->addColumn('foo', 'integer');
342
        $table->addColumn('bar', 'string');
343
        $table->addColumn('bloo', 'boolean');
344
        $table->setPrimaryKey(['id']);
345
346
        $tableDiff                         = new TableDiff('mytable');
347
        $tableDiff->fromTable              = $table;
348
        $tableDiff->newName                = 'userlist';
349
        $tableDiff->addedColumns['quota']  = new Column('quota', Type::getType('integer'), ['notnull' => false]);
350
        $tableDiff->removedColumns['foo']  = new Column('foo', Type::getType('integer'));
351
        $tableDiff->changedColumns['bar']  = new ColumnDiff(
352
            'bar',
353
            new Column(
354
                'baz',
355
                Type::getType('string'),
356
                ['default' => 'def']
357
            ),
358
            ['type', 'notnull', 'default']
359
        );
360
        $tableDiff->changedColumns['bloo'] = new ColumnDiff(
361
            'bloo',
362
            new Column(
363
                'bloo',
364
                Type::getType('boolean'),
365
                ['default' => false]
366
            ),
367
            ['type', 'notnull', 'default']
368
        );
369
370
        $sql = $this->platform->getAlterTableSQL($tableDiff);
371
372
        self::assertEquals($expectedSql, $sql);
373
    }
374
375
    public function testGetCustomColumnDeclarationSql() : void
376
    {
377
        $field = ['columnDefinition' => 'MEDIUMINT(6) UNSIGNED'];
378
        self::assertEquals('foo MEDIUMINT(6) UNSIGNED', $this->platform->getColumnDeclarationSQL('foo', $field));
379
    }
380
381
    public function testGetCreateTableSqlDispatchEvent() : void
382
    {
383
        $listenerMock = $this->getMockBuilder($this->getMockClass('GetCreateTableSqlDispatchEvenListener'))
384
            ->addMethods(['onSchemaCreateTable', 'onSchemaCreateTableColumn'])
385
            ->getMock();
386
        $listenerMock
387
            ->expects($this->once())
388
            ->method('onSchemaCreateTable');
389
        $listenerMock
390
            ->expects($this->exactly(2))
391
            ->method('onSchemaCreateTableColumn');
392
393
        $eventManager = new EventManager();
394
        $eventManager->addEventListener([Events::onSchemaCreateTable, Events::onSchemaCreateTableColumn], $listenerMock);
395
396
        $this->platform->setEventManager($eventManager);
397
398
        $table = new Table('test');
399
        $table->addColumn('foo', 'string', ['notnull' => false, 'length' => 255]);
400
        $table->addColumn('bar', 'string', ['notnull' => false, 'length' => 255]);
401
402
        $this->platform->getCreateTableSQL($table);
403
    }
404
405
    public function testGetDropTableSqlDispatchEvent() : void
406
    {
407
        $listenerMock = $this->getMockBuilder($this->getMockClass('GetDropTableSqlDispatchEventListener'))
408
            ->addMethods(['onSchemaDropTable'])
409
            ->getMock();
410
        $listenerMock
411
            ->expects($this->once())
412
            ->method('onSchemaDropTable');
413
414
        $eventManager = new EventManager();
415
        $eventManager->addEventListener([Events::onSchemaDropTable], $listenerMock);
416
417
        $this->platform->setEventManager($eventManager);
418
419
        $this->platform->getDropTableSQL('TABLE');
420
    }
421
422
    public function testGetAlterTableSqlDispatchEvent() : void
423
    {
424
        $events = [
425
            'onSchemaAlterTable',
426
            'onSchemaAlterTableAddColumn',
427
            'onSchemaAlterTableRemoveColumn',
428
            'onSchemaAlterTableChangeColumn',
429
            'onSchemaAlterTableRenameColumn',
430
        ];
431
432
        $listenerMock = $this->getMockBuilder($this->getMockClass('GetAlterTableSqlDispatchEvenListener'))
433
            ->addMethods($events)
434
            ->getMock();
435
        $listenerMock
436
            ->expects($this->once())
437
            ->method('onSchemaAlterTable');
438
        $listenerMock
439
            ->expects($this->once())
440
            ->method('onSchemaAlterTableAddColumn');
441
        $listenerMock
442
            ->expects($this->once())
443
            ->method('onSchemaAlterTableRemoveColumn');
444
        $listenerMock
445
            ->expects($this->once())
446
            ->method('onSchemaAlterTableChangeColumn');
447
        $listenerMock
448
            ->expects($this->once())
449
            ->method('onSchemaAlterTableRenameColumn');
450
451
        $eventManager = new EventManager();
452
        $events       = [
453
            Events::onSchemaAlterTable,
454
            Events::onSchemaAlterTableAddColumn,
455
            Events::onSchemaAlterTableRemoveColumn,
456
            Events::onSchemaAlterTableChangeColumn,
457
            Events::onSchemaAlterTableRenameColumn,
458
        ];
459
        $eventManager->addEventListener($events, $listenerMock);
460
461
        $this->platform->setEventManager($eventManager);
462
463
        $table = new Table('mytable');
464
        $table->addColumn('removed', 'integer');
465
        $table->addColumn('changed', 'integer');
466
        $table->addColumn('renamed', 'integer');
467
468
        $tableDiff                            = new TableDiff('mytable');
469
        $tableDiff->fromTable                 = $table;
470
        $tableDiff->addedColumns['added']     = new Column('added', Type::getType('integer'), []);
471
        $tableDiff->removedColumns['removed'] = new Column('removed', Type::getType('integer'), []);
472
        $tableDiff->changedColumns['changed'] = new ColumnDiff(
473
            'changed',
474
            new Column(
475
                'changed2',
476
                Type::getType('string'),
477
                []
478
            ),
479
            []
480
        );
481
        $tableDiff->renamedColumns['renamed'] = new Column('renamed2', Type::getType('integer'), []);
482
483
        $this->platform->getAlterTableSQL($tableDiff);
484
    }
485
486
    /**
487
     * @group DBAL-42
488
     */
489
    public function testCreateTableColumnComments() : void
490
    {
491
        $table = new Table('test');
492
        $table->addColumn('id', 'integer', ['comment' => 'This is a comment']);
493
        $table->setPrimaryKey(['id']);
494
495
        self::assertEquals($this->getCreateTableColumnCommentsSQL(), $this->platform->getCreateTableSQL($table));
496
    }
497
498
    /**
499
     * @group DBAL-42
500
     */
501
    public function testAlterTableColumnComments() : void
502
    {
503
        $tableDiff                        = new TableDiff('mytable');
504
        $tableDiff->addedColumns['quota'] = new Column('quota', Type::getType('integer'), ['comment' => 'A comment']);
505
        $tableDiff->changedColumns['foo'] = new ColumnDiff(
506
            'foo',
507
            new Column(
508
                'foo',
509
                Type::getType('string')
510
            ),
511
            ['comment']
512
        );
513
        $tableDiff->changedColumns['bar'] = new ColumnDiff(
514
            'bar',
515
            new Column(
516
                'baz',
517
                Type::getType('string'),
518
                ['comment' => 'B comment']
519
            ),
520
            ['comment']
521
        );
522
523
        self::assertEquals($this->getAlterTableColumnCommentsSQL(), $this->platform->getAlterTableSQL($tableDiff));
524
    }
525
526
    public function testCreateTableColumnTypeComments() : void
527
    {
528
        $table = new Table('test');
529
        $table->addColumn('id', 'integer');
530
        $table->addColumn('data', 'array');
531
        $table->setPrimaryKey(['id']);
532
533
        self::assertEquals($this->getCreateTableColumnTypeCommentsSQL(), $this->platform->getCreateTableSQL($table));
534
    }
535
536
    /**
537
     * @return string[]
538
     */
539
    public function getCreateTableColumnCommentsSQL() : array
540
    {
541
        $this->markTestSkipped('Platform does not support Column comments.');
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...
542
    }
543
544
    /**
545
     * @return string[]
546
     */
547
    public function getAlterTableColumnCommentsSQL() : array
548
    {
549
        $this->markTestSkipped('Platform does not support Column comments.');
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...
550
    }
551
552
    /**
553
     * @return string[]
554
     */
555
    public function getCreateTableColumnTypeCommentsSQL() : array
556
    {
557
        $this->markTestSkipped('Platform does not support Column comments.');
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...
558
    }
559
560
    public function testGetDefaultValueDeclarationSQL() : void
561
    {
562
        // non-timestamp value will get single quotes
563
        $field = [
564
            'type' => Type::getType('string'),
565
            'default' => 'non_timestamp',
566
        ];
567
568
        self::assertEquals(" DEFAULT 'non_timestamp'", $this->platform->getDefaultValueDeclarationSQL($field));
569
    }
570
571
    /**
572
     * @group 2859
573
     */
574
    public function testGetDefaultValueDeclarationSQLDateTime() : void
575
    {
576
        // timestamps on datetime types should not be quoted
577
        foreach (['datetime', 'datetimetz', 'datetime_immutable', 'datetimetz_immutable'] as $type) {
578
            $field = [
579
                'type'    => Type::getType($type),
580
                'default' => $this->platform->getCurrentTimestampSQL(),
581
            ];
582
583
            self::assertSame(
584
                ' DEFAULT ' . $this->platform->getCurrentTimestampSQL(),
585
                $this->platform->getDefaultValueDeclarationSQL($field)
586
            );
587
        }
588
    }
589
590
    public function testGetDefaultValueDeclarationSQLForIntegerTypes() : void
591
    {
592
        foreach (['bigint', 'integer', 'smallint'] as $type) {
593
            $field = [
594
                'type'    => Type::getType($type),
595
                'default' => 1,
596
            ];
597
598
            self::assertEquals(
599
                ' DEFAULT 1',
600
                $this->platform->getDefaultValueDeclarationSQL($field)
601
            );
602
        }
603
    }
604
605
    /**
606
     * @group 2859
607
     */
608
    public function testGetDefaultValueDeclarationSQLForDateType() : void
609
    {
610
        $currentDateSql = $this->platform->getCurrentDateSQL();
611
        foreach (['date', 'date_immutable'] as $type) {
612
            $field = [
613
                'type'    => Type::getType($type),
614
                'default' => $currentDateSql,
615
            ];
616
617
            self::assertSame(
618
                ' DEFAULT ' . $currentDateSql,
619
                $this->platform->getDefaultValueDeclarationSQL($field)
620
            );
621
        }
622
    }
623
624
    /**
625
     * @group DBAL-45
626
     */
627
    public function testKeywordList() : void
628
    {
629
        $keywordList = $this->platform->getReservedKeywordsList();
630
        self::assertInstanceOf(KeywordList::class, $keywordList);
631
632
        self::assertTrue($keywordList->isKeyword('table'));
633
    }
634
635
    /**
636
     * @return string[][]
637
     */
638
    public function getAutoQuotedIdentifiers() : array
639
    {
640
        return [
641
            ['create'],
642
            ['select'],
643
            ['a name with spaces'],
644
            ['a name with/slash'],
645
            ['name-with-dash'],
646
        ];
647
    }
648
649
    /**
650
     * @group DBAL-374
651
     * @group DBAL-2979
652
     * @dataProvider getAutoQuotedIdentifiers
653
     */
654
    public function testAutoQuotedColumnInPrimaryKeyPropagation(string $columnName) : void
655
    {
656
        $table = new Table('`quoted`');
657
        $table->addColumn($columnName, 'string');
658
        $table->setPrimaryKey([$columnName]);
659
660
        $sql = $this->platform->getCreateTableSQL($table);
661
        self::assertEquals($this->getQuotedColumnInPrimaryKeySQL($columnName), $sql);
662
    }
663
664
    /**
665
     * @return string[]
666
     */
667
    abstract protected function getQuotedColumnInPrimaryKeySQL(string $columnName = 'create') : array;
668
669
    /**
670
     * @return string[]
671
     */
672
    abstract protected function getQuotedColumnInIndexSQL() : array;
673
674
    /**
675
     * @return string[]
676
     */
677
    abstract protected function getQuotedNameInIndexSQL() : array;
678
679
    /**
680
     * @return string[]
681
     */
682
    abstract protected function getQuotedColumnInForeignKeySQL(string $columnName = 'create') : array;
683
684
    /**
685
     * @group DBAL-374
686
     */
687
    public function testQuotedColumnInIndexPropagation() : void
688
    {
689
        $table = new Table('`quoted`');
690
        $table->addColumn('create', 'string');
691
        $table->addIndex(['create']);
692
693
        $sql = $this->platform->getCreateTableSQL($table);
694
        self::assertEquals($this->getQuotedColumnInIndexSQL(), $sql);
695
    }
696
697
    public function testQuotedNameInIndexSQL() : void
698
    {
699
        $table = new Table('test');
700
        $table->addColumn('column1', 'string');
701
        $table->addIndex(['column1'], '`key`');
702
703
        $sql = $this->platform->getCreateTableSQL($table);
704
        self::assertEquals($this->getQuotedNameInIndexSQL(), $sql);
705
    }
706
707
    /**
708
     * @group DBAL-374
709
     * @group DBAL-2979
710
     * @dataProvider getAutoQuotedIdentifiers
711
     */
712
    public function testQuotedColumnInForeignKeyPropagation(string $columnName) : void
713
    {
714
        $table = new Table('`quoted`');
715
        $table->addColumn($columnName, 'string');
716
        $table->addColumn('foo', 'string');
717
        $table->addColumn('`bar`', 'string');
718
719
        // Foreign table with reserved keyword as name (needs quotation).
720
        $foreignTable = new Table('foreign');
721
        $foreignTable->addColumn($columnName, 'string');    // Foreign column with reserved keyword as name (needs quotation).
722
        $foreignTable->addColumn('bar', 'string');       // Foreign column with non-reserved keyword as name (does not need quotation).
723
        $foreignTable->addColumn('`foo-bar`', 'string'); // Foreign table with special character in name (needs quotation on some platforms, e.g. Sqlite).
724
725
        $table->addForeignKeyConstraint($foreignTable, [$columnName, 'foo', '`bar`'], [$columnName, 'bar', '`foo-bar`'], [], 'FK_WITH_RESERVED_KEYWORD');
726
727
        // Foreign table with non-reserved keyword as name (does not need quotation).
728
        $foreignTable = new Table('foo');
729
        $foreignTable->addColumn($columnName, 'string');    // Foreign column with reserved keyword as name (needs quotation).
730
        $foreignTable->addColumn('bar', 'string');       // Foreign column with non-reserved keyword as name (does not need quotation).
731
        $foreignTable->addColumn('`foo-bar`', 'string'); // Foreign table with special character in name (needs quotation on some platforms, e.g. Sqlite).
732
733
        $table->addForeignKeyConstraint($foreignTable, [$columnName, 'foo', '`bar`'], [$columnName, 'bar', '`foo-bar`'], [], 'FK_WITH_NON_RESERVED_KEYWORD');
734
735
        // Foreign table with special character in name (needs quotation on some platforms, e.g. Sqlite).
736
        $foreignTable = new Table('`foo-bar`');
737
        $foreignTable->addColumn($columnName, 'string');    // Foreign column with reserved keyword as name (needs quotation).
738
        $foreignTable->addColumn('bar', 'string');       // Foreign column with non-reserved keyword as name (does not need quotation).
739
        $foreignTable->addColumn('`foo-bar`', 'string'); // Foreign table with special character in name (needs quotation on some platforms, e.g. Sqlite).
740
741
        $table->addForeignKeyConstraint($foreignTable, [$columnName, 'foo', '`bar`'], [$columnName, 'bar', '`foo-bar`'], [], 'FK_WITH_INTENDED_QUOTATION');
742
743
        $sql = $this->platform->getCreateTableSQL($table, AbstractPlatform::CREATE_FOREIGNKEYS);
744
        self::assertEquals($this->getQuotedColumnInForeignKeySQL($columnName), $sql);
745
    }
746
747
    /**
748
     * @group DBAL-1051
749
     * @group DBAL-2979
750
     * @dataProvider getAutoQuotedIdentifiers
751
     */
752
    public function testQuotesReservedKeywordInUniqueConstraintDeclarationSQL(string $constraintName) : void
753
    {
754
        $index = new Index($constraintName, ['foo'], true);
755
756
        self::assertSame(
757
            $this->getQuotesReservedKeywordInUniqueConstraintDeclarationSQL($constraintName),
758
            $this->platform->getUniqueConstraintDeclarationSQL($constraintName, $index)
759
        );
760
    }
761
762
    abstract protected function getQuotesReservedKeywordInUniqueConstraintDeclarationSQL(string $constraintName = 'select') : string;
763
764
    /**
765
     * @group DBAL-2270
766
     * @group DBAL-2979
767
     * @dataProvider getAutoQuotedIdentifiers
768
     */
769
    public function testQuotesReservedKeywordInTruncateTableSQL(string $tableName) : void
770
    {
771
        self::assertSame(
772
            $this->getQuotesReservedKeywordInTruncateTableSQL($tableName),
773
            $this->platform->getTruncateTableSQL($tableName)
774
        );
775
    }
776
777
    abstract protected function getQuotesReservedKeywordInTruncateTableSQL(string $tableName = 'select') : string;
778
779
    /**
780
     * @group DBAL-1051
781
     * @group DBAL-2979
782
     * @dataProvider getAutoQuotedIdentifiers
783
     */
784
    public function testQuotesReservedKeywordInIndexDeclarationSQL(string $indexName) : void
785
    {
786
        $index = new Index($indexName, ['foo']);
787
788
        if (! $this->supportsInlineIndexDeclaration()) {
789
            $this->expectException(DBALException::class);
790
        }
791
792
        self::assertSame(
793
            $this->getQuotesReservedKeywordInIndexDeclarationSQL($indexName),
794
            $this->platform->getIndexDeclarationSQL($indexName, $index)
795
        );
796
    }
797
798
    abstract protected function getQuotesReservedKeywordInIndexDeclarationSQL(string $indexName = 'select') : string;
799
800
    protected function supportsInlineIndexDeclaration() : bool
801
    {
802
        return true;
803
    }
804
805
    public function testSupportsCommentOnStatement() : void
806
    {
807
        self::assertSame($this->supportsCommentOnStatement(), $this->platform->supportsCommentOnStatement());
808
    }
809
810
    protected function supportsCommentOnStatement() : bool
811
    {
812
        return false;
813
    }
814
815
    public function testGetCreateSchemaSQL() : void
816
    {
817
        $this->expectException(DBALException::class);
818
819
        $this->platform->getCreateSchemaSQL('schema');
820
    }
821
822
    /**
823
     * @group DBAL-585
824
     */
825
    public function testAlterTableChangeQuotedColumn() : void
826
    {
827
        $tableDiff                        = new TableDiff('mytable');
828
        $tableDiff->fromTable             = new Table('mytable');
829
        $tableDiff->changedColumns['foo'] = new ColumnDiff(
830
            'select',
831
            new Column(
832
                'select',
833
                Type::getType('string')
834
            ),
835
            ['type']
836
        );
837
838
        self::assertStringContainsString(
839
            $this->platform->quoteIdentifier('select'),
840
            implode(';', $this->platform->getAlterTableSQL($tableDiff))
841
        );
842
    }
843
844
    /**
845
     * @group DBAL-563
846
     */
847
    public function testUsesSequenceEmulatedIdentityColumns() : void
848
    {
849
        self::assertFalse($this->platform->usesSequenceEmulatedIdentityColumns());
850
    }
851
852
    /**
853
     * @group DBAL-563
854
     */
855
    public function testReturnsIdentitySequenceName() : void
856
    {
857
        $this->expectException(DBALException::class);
858
859
        $this->platform->getIdentitySequenceName('mytable', 'mycolumn');
860
    }
861
862
    public function testReturnsBinaryDefaultLength() : void
863
    {
864
        self::assertSame($this->getBinaryDefaultLength(), $this->platform->getBinaryDefaultLength());
865
    }
866
867
    protected function getBinaryDefaultLength() : int
868
    {
869
        return 255;
870
    }
871
872
    public function testReturnsBinaryMaxLength() : void
873
    {
874
        self::assertSame($this->getBinaryMaxLength(), $this->platform->getBinaryMaxLength());
875
    }
876
877
    protected function getBinaryMaxLength() : int
878
    {
879
        return 4000;
880
    }
881
882
    public function testReturnsBinaryTypeDeclarationSQL() : void
883
    {
884
        $this->expectException(DBALException::class);
885
886
        $this->platform->getBinaryTypeDeclarationSQL([]);
887
    }
888
889
    public function testReturnsBinaryTypeLongerThanMaxDeclarationSQL() : void
890
    {
891
        $this->markTestSkipped('Not applicable to the platform');
892
    }
893
894
    /**
895
     * @group DBAL-553
896
     */
897
    public function hasNativeJsonType() : void
898
    {
899
        self::assertFalse($this->platform->hasNativeJsonType());
900
    }
901
902
    /**
903
     * @group DBAL-553
904
     */
905
    public function testReturnsJsonTypeDeclarationSQL() : void
906
    {
907
        $column = [
908
            'length'  => 666,
909
            'notnull' => true,
910
            'type'    => Type::getType('json_array'),
911
        ];
912
913
        self::assertSame(
914
            $this->platform->getClobTypeDeclarationSQL($column),
915
            $this->platform->getJsonTypeDeclarationSQL($column)
916
        );
917
    }
918
919
    /**
920
     * @group DBAL-234
921
     */
922
    public function testAlterTableRenameIndex() : void
923
    {
924
        $tableDiff            = new TableDiff('mytable');
925
        $tableDiff->fromTable = new Table('mytable');
926
        $tableDiff->fromTable->addColumn('id', 'integer');
927
        $tableDiff->fromTable->setPrimaryKey(['id']);
928
        $tableDiff->renamedIndexes = [
929
            'idx_foo' => new Index('idx_bar', ['id']),
930
        ];
931
932
        self::assertSame(
933
            $this->getAlterTableRenameIndexSQL(),
934
            $this->platform->getAlterTableSQL($tableDiff)
935
        );
936
    }
937
938
    /**
939
     * @return string[]
940
     *
941
     * @group DBAL-234
942
     */
943
    protected function getAlterTableRenameIndexSQL() : array
944
    {
945
        return [
946
            'DROP INDEX idx_foo',
947
            'CREATE INDEX idx_bar ON mytable (id)',
948
        ];
949
    }
950
951
    /**
952
     * @group DBAL-234
953
     */
954
    public function testQuotesAlterTableRenameIndex() : void
955
    {
956
        $tableDiff            = new TableDiff('table');
957
        $tableDiff->fromTable = new Table('table');
958
        $tableDiff->fromTable->addColumn('id', 'integer');
959
        $tableDiff->fromTable->setPrimaryKey(['id']);
960
        $tableDiff->renamedIndexes = [
961
            'create' => new Index('select', ['id']),
962
            '`foo`'  => new Index('`bar`', ['id']),
963
        ];
964
965
        self::assertSame(
966
            $this->getQuotedAlterTableRenameIndexSQL(),
967
            $this->platform->getAlterTableSQL($tableDiff)
968
        );
969
    }
970
971
    /**
972
     * @return string[]
973
     *
974
     * @group DBAL-234
975
     */
976
    protected function getQuotedAlterTableRenameIndexSQL() : array
977
    {
978
        return [
979
            'DROP INDEX "create"',
980
            'CREATE INDEX "select" ON "table" (id)',
981
            'DROP INDEX "foo"',
982
            'CREATE INDEX "bar" ON "table" (id)',
983
        ];
984
    }
985
986
    /**
987
     * @group DBAL-835
988
     */
989
    public function testQuotesAlterTableRenameColumn() : void
990
    {
991
        $fromTable = new Table('mytable');
992
993
        $fromTable->addColumn('unquoted1', 'integer', ['comment' => 'Unquoted 1']);
994
        $fromTable->addColumn('unquoted2', 'integer', ['comment' => 'Unquoted 2']);
995
        $fromTable->addColumn('unquoted3', 'integer', ['comment' => 'Unquoted 3']);
996
997
        $fromTable->addColumn('create', 'integer', ['comment' => 'Reserved keyword 1']);
998
        $fromTable->addColumn('table', 'integer', ['comment' => 'Reserved keyword 2']);
999
        $fromTable->addColumn('select', 'integer', ['comment' => 'Reserved keyword 3']);
1000
1001
        $fromTable->addColumn('`quoted1`', 'integer', ['comment' => 'Quoted 1']);
1002
        $fromTable->addColumn('`quoted2`', 'integer', ['comment' => 'Quoted 2']);
1003
        $fromTable->addColumn('`quoted3`', 'integer', ['comment' => 'Quoted 3']);
1004
1005
        $toTable = new Table('mytable');
1006
1007
        $toTable->addColumn('unquoted', 'integer', ['comment' => 'Unquoted 1']); // unquoted -> unquoted
1008
        $toTable->addColumn('where', 'integer', ['comment' => 'Unquoted 2']); // unquoted -> reserved keyword
1009
        $toTable->addColumn('`foo`', 'integer', ['comment' => 'Unquoted 3']); // unquoted -> quoted
1010
1011
        $toTable->addColumn('reserved_keyword', 'integer', ['comment' => 'Reserved keyword 1']); // reserved keyword -> unquoted
1012
        $toTable->addColumn('from', 'integer', ['comment' => 'Reserved keyword 2']); // reserved keyword -> reserved keyword
1013
        $toTable->addColumn('`bar`', 'integer', ['comment' => 'Reserved keyword 3']); // reserved keyword -> quoted
1014
1015
        $toTable->addColumn('quoted', 'integer', ['comment' => 'Quoted 1']); // quoted -> unquoted
1016
        $toTable->addColumn('and', 'integer', ['comment' => 'Quoted 2']); // quoted -> reserved keyword
1017
        $toTable->addColumn('`baz`', 'integer', ['comment' => 'Quoted 3']); // quoted -> quoted
1018
1019
        $comparator = new Comparator();
1020
1021
        self::assertEquals(
1022
            $this->getQuotedAlterTableRenameColumnSQL(),
1023
            $this->platform->getAlterTableSQL($comparator->diffTable($fromTable, $toTable))
0 ignored issues
show
Bug introduced by
It seems like $comparator->diffTable($fromTable, $toTable) can also be of type false; however, parameter $diff of Doctrine\DBAL\Platforms\...orm::getAlterTableSQL() does only seem to accept Doctrine\DBAL\Schema\TableDiff, maybe add an additional type check? ( Ignorable by Annotation )

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

1023
            $this->platform->getAlterTableSQL(/** @scrutinizer ignore-type */ $comparator->diffTable($fromTable, $toTable))
Loading history...
1024
        );
1025
    }
1026
1027
    /**
1028
     * Returns SQL statements for {@link testQuotesAlterTableRenameColumn}.
1029
     *
1030
     * @return string[]
1031
     *
1032
     * @group DBAL-835
1033
     */
1034
    abstract protected function getQuotedAlterTableRenameColumnSQL() : array;
1035
1036
    /**
1037
     * @group DBAL-835
1038
     */
1039
    public function testQuotesAlterTableChangeColumnLength() : void
1040
    {
1041
        $fromTable = new Table('mytable');
1042
1043
        $fromTable->addColumn('unquoted1', 'string', ['comment' => 'Unquoted 1', 'length' => 10]);
1044
        $fromTable->addColumn('unquoted2', 'string', ['comment' => 'Unquoted 2', 'length' => 10]);
1045
        $fromTable->addColumn('unquoted3', 'string', ['comment' => 'Unquoted 3', 'length' => 10]);
1046
1047
        $fromTable->addColumn('create', 'string', ['comment' => 'Reserved keyword 1', 'length' => 10]);
1048
        $fromTable->addColumn('table', 'string', ['comment' => 'Reserved keyword 2', 'length' => 10]);
1049
        $fromTable->addColumn('select', 'string', ['comment' => 'Reserved keyword 3', 'length' => 10]);
1050
1051
        $toTable = new Table('mytable');
1052
1053
        $toTable->addColumn('unquoted1', 'string', ['comment' => 'Unquoted 1', 'length' => 255]);
1054
        $toTable->addColumn('unquoted2', 'string', ['comment' => 'Unquoted 2', 'length' => 255]);
1055
        $toTable->addColumn('unquoted3', 'string', ['comment' => 'Unquoted 3', 'length' => 255]);
1056
1057
        $toTable->addColumn('create', 'string', ['comment' => 'Reserved keyword 1', 'length' => 255]);
1058
        $toTable->addColumn('table', 'string', ['comment' => 'Reserved keyword 2', 'length' => 255]);
1059
        $toTable->addColumn('select', 'string', ['comment' => 'Reserved keyword 3', 'length' => 255]);
1060
1061
        $comparator = new Comparator();
1062
1063
        self::assertEquals(
1064
            $this->getQuotedAlterTableChangeColumnLengthSQL(),
1065
            $this->platform->getAlterTableSQL($comparator->diffTable($fromTable, $toTable))
0 ignored issues
show
Bug introduced by
It seems like $comparator->diffTable($fromTable, $toTable) can also be of type false; however, parameter $diff of Doctrine\DBAL\Platforms\...orm::getAlterTableSQL() does only seem to accept Doctrine\DBAL\Schema\TableDiff, maybe add an additional type check? ( Ignorable by Annotation )

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

1065
            $this->platform->getAlterTableSQL(/** @scrutinizer ignore-type */ $comparator->diffTable($fromTable, $toTable))
Loading history...
1066
        );
1067
    }
1068
1069
    /**
1070
     * Returns SQL statements for {@link testQuotesAlterTableChangeColumnLength}.
1071
     *
1072
     * @return string[]
1073
     *
1074
     * @group DBAL-835
1075
     */
1076
    abstract protected function getQuotedAlterTableChangeColumnLengthSQL() : array;
1077
1078
    /**
1079
     * @group DBAL-807
1080
     */
1081
    public function testAlterTableRenameIndexInSchema() : void
1082
    {
1083
        $tableDiff            = new TableDiff('myschema.mytable');
1084
        $tableDiff->fromTable = new Table('myschema.mytable');
1085
        $tableDiff->fromTable->addColumn('id', 'integer');
1086
        $tableDiff->fromTable->setPrimaryKey(['id']);
1087
        $tableDiff->renamedIndexes = [
1088
            'idx_foo' => new Index('idx_bar', ['id']),
1089
        ];
1090
1091
        self::assertSame(
1092
            $this->getAlterTableRenameIndexInSchemaSQL(),
1093
            $this->platform->getAlterTableSQL($tableDiff)
1094
        );
1095
    }
1096
1097
    /**
1098
     * @return string[]
1099
     *
1100
     * @group DBAL-807
1101
     */
1102
    protected function getAlterTableRenameIndexInSchemaSQL() : array
1103
    {
1104
        return [
1105
            'DROP INDEX idx_foo',
1106
            'CREATE INDEX idx_bar ON myschema.mytable (id)',
1107
        ];
1108
    }
1109
1110
    /**
1111
     * @group DBAL-807
1112
     */
1113
    public function testQuotesAlterTableRenameIndexInSchema() : void
1114
    {
1115
        $tableDiff            = new TableDiff('`schema`.table');
1116
        $tableDiff->fromTable = new Table('`schema`.table');
1117
        $tableDiff->fromTable->addColumn('id', 'integer');
1118
        $tableDiff->fromTable->setPrimaryKey(['id']);
1119
        $tableDiff->renamedIndexes = [
1120
            'create' => new Index('select', ['id']),
1121
            '`foo`'  => new Index('`bar`', ['id']),
1122
        ];
1123
1124
        self::assertSame(
1125
            $this->getQuotedAlterTableRenameIndexInSchemaSQL(),
1126
            $this->platform->getAlterTableSQL($tableDiff)
1127
        );
1128
    }
1129
1130
    /**
1131
     * @return string[]
1132
     *
1133
     * @group DBAL-234
1134
     */
1135
    protected function getQuotedAlterTableRenameIndexInSchemaSQL() : array
1136
    {
1137
        return [
1138
            'DROP INDEX "schema"."create"',
1139
            'CREATE INDEX "select" ON "schema"."table" (id)',
1140
            'DROP INDEX "schema"."foo"',
1141
            'CREATE INDEX "bar" ON "schema"."table" (id)',
1142
        ];
1143
    }
1144
1145
    /**
1146
     * @group DBAL-1237
1147
     */
1148
    public function testQuotesDropForeignKeySQL() : void
1149
    {
1150
        if (! $this->platform->supportsForeignKeyConstraints()) {
1151
            $this->markTestSkipped(
1152
                sprintf('%s does not support foreign key constraints.', get_class($this->platform))
1153
            );
1154
        }
1155
1156
        $tableName      = 'table';
1157
        $table          = new Table($tableName);
1158
        $foreignKeyName = 'select';
1159
        $foreignKey     = new ForeignKeyConstraint([], 'foo', [], 'select');
1160
        $expectedSql    = $this->getQuotesDropForeignKeySQL();
1161
1162
        self::assertSame($expectedSql, $this->platform->getDropForeignKeySQL($foreignKeyName, $tableName));
1163
        self::assertSame($expectedSql, $this->platform->getDropForeignKeySQL($foreignKey, $table));
1164
    }
1165
1166
    protected function getQuotesDropForeignKeySQL() : string
1167
    {
1168
        return 'ALTER TABLE "table" DROP FOREIGN KEY "select"';
1169
    }
1170
1171
    /**
1172
     * @group DBAL-1237
1173
     */
1174
    public function testQuotesDropConstraintSQL() : void
1175
    {
1176
        $tableName      = 'table';
1177
        $table          = new Table($tableName);
1178
        $constraintName = 'select';
1179
        $constraint     = new ForeignKeyConstraint([], 'foo', [], 'select');
1180
        $expectedSql    = $this->getQuotesDropConstraintSQL();
1181
1182
        self::assertSame($expectedSql, $this->platform->getDropConstraintSQL($constraintName, $tableName));
1183
        self::assertSame($expectedSql, $this->platform->getDropConstraintSQL($constraint, $table));
1184
    }
1185
1186
    protected function getQuotesDropConstraintSQL() : string
1187
    {
1188
        return 'ALTER TABLE "table" DROP CONSTRAINT "select"';
1189
    }
1190
1191
    protected function getStringLiteralQuoteCharacter() : string
1192
    {
1193
        return "'";
1194
    }
1195
1196
    public function testGetStringLiteralQuoteCharacter() : void
1197
    {
1198
        self::assertSame($this->getStringLiteralQuoteCharacter(), $this->platform->getStringLiteralQuoteCharacter());
1199
    }
1200
1201
    protected function getQuotedCommentOnColumnSQLWithoutQuoteCharacter() : string
1202
    {
1203
        return "COMMENT ON COLUMN mytable.id IS 'This is a comment'";
1204
    }
1205
1206
    public function testGetCommentOnColumnSQLWithoutQuoteCharacter() : void
1207
    {
1208
        self::assertEquals(
1209
            $this->getQuotedCommentOnColumnSQLWithoutQuoteCharacter(),
1210
            $this->platform->getCommentOnColumnSQL('mytable', 'id', 'This is a comment')
1211
        );
1212
    }
1213
1214
    protected function getQuotedCommentOnColumnSQLWithQuoteCharacter() : string
1215
    {
1216
        return "COMMENT ON COLUMN mytable.id IS 'It''s a quote !'";
1217
    }
1218
1219
    public function testGetCommentOnColumnSQLWithQuoteCharacter() : void
1220
    {
1221
        $c = $this->getStringLiteralQuoteCharacter();
1222
1223
        self::assertEquals(
1224
            $this->getQuotedCommentOnColumnSQLWithQuoteCharacter(),
1225
            $this->platform->getCommentOnColumnSQL('mytable', 'id', 'It' . $c . 's a quote !')
1226
        );
1227
    }
1228
1229
    /**
1230
     * @see testGetCommentOnColumnSQL
1231
     *
1232
     * @return string[]
1233
     */
1234
    abstract protected function getCommentOnColumnSQL() : array;
1235
1236
    /**
1237
     * @group DBAL-1004
1238
     */
1239
    public function testGetCommentOnColumnSQL() : void
1240
    {
1241
        self::assertSame(
1242
            $this->getCommentOnColumnSQL(),
1243
            [
1244
                $this->platform->getCommentOnColumnSQL('foo', 'bar', 'comment'), // regular identifiers
1245
                $this->platform->getCommentOnColumnSQL('`Foo`', '`BAR`', 'comment'), // explicitly quoted identifiers
1246
                $this->platform->getCommentOnColumnSQL('select', 'from', 'comment'), // reserved keyword identifiers
1247
            ]
1248
        );
1249
    }
1250
1251
    /**
1252
     * @group DBAL-1176
1253
     * @dataProvider getGeneratesInlineColumnCommentSQL
1254
     */
1255
    public function testGeneratesInlineColumnCommentSQL(?string $comment, string $expectedSql) : void
1256
    {
1257
        if (! $this->platform->supportsInlineColumnComments()) {
1258
            $this->markTestSkipped(sprintf('%s does not support inline column comments.', get_class($this->platform)));
1259
        }
1260
1261
        self::assertSame($expectedSql, $this->platform->getInlineColumnCommentSQL($comment));
1262
    }
1263
1264
    /**
1265
     * @return mixed[][]
1266
     */
1267
    public static function getGeneratesInlineColumnCommentSQL() : iterable
1268
    {
1269
        return [
1270
            'regular comment' => ['Regular comment', static::getInlineColumnRegularCommentSQL()],
1271
            'comment requiring escaping' => [
1272
                sprintf(
1273
                    'Using inline comment delimiter %s works',
1274
                    static::getInlineColumnCommentDelimiter()
1275
                ),
1276
                static::getInlineColumnCommentRequiringEscapingSQL(),
1277
            ],
1278
            'empty comment' => ['', static::getInlineColumnEmptyCommentSQL()],
1279
        ];
1280
    }
1281
1282
    protected static function getInlineColumnCommentDelimiter() : string
1283
    {
1284
        return "'";
1285
    }
1286
1287
    protected static function getInlineColumnRegularCommentSQL() : string
1288
    {
1289
        return "COMMENT 'Regular comment'";
1290
    }
1291
1292
    protected static function getInlineColumnCommentRequiringEscapingSQL() : string
1293
    {
1294
        return "COMMENT 'Using inline comment delimiter '' works'";
1295
    }
1296
1297
    protected static function getInlineColumnEmptyCommentSQL() : string
1298
    {
1299
        return "COMMENT ''";
1300
    }
1301
1302
    protected function getQuotedStringLiteralWithoutQuoteCharacter() : string
1303
    {
1304
        return "'No quote'";
1305
    }
1306
1307
    protected function getQuotedStringLiteralWithQuoteCharacter() : string
1308
    {
1309
        return "'It''s a quote'";
1310
    }
1311
1312
    protected function getQuotedStringLiteralQuoteCharacter() : string
1313
    {
1314
        return "''''";
1315
    }
1316
1317
    /**
1318
     * @group DBAL-1176
1319
     */
1320
    public function testThrowsExceptionOnGeneratingInlineColumnCommentSQLIfUnsupported() : void
1321
    {
1322
        if ($this->platform->supportsInlineColumnComments()) {
1323
            $this->markTestSkipped(sprintf('%s supports inline column comments.', get_class($this->platform)));
1324
        }
1325
1326
        $this->expectException(DBALException::class);
1327
        $this->expectExceptionMessage("Operation 'Doctrine\\DBAL\\Platforms\\AbstractPlatform::getInlineColumnCommentSQL' is not supported by platform.");
1328
        $this->expectExceptionCode(0);
1329
1330
        $this->platform->getInlineColumnCommentSQL('unsupported');
1331
    }
1332
1333
    public function testQuoteStringLiteral() : void
1334
    {
1335
        $c = $this->getStringLiteralQuoteCharacter();
1336
1337
        self::assertEquals(
1338
            $this->getQuotedStringLiteralWithoutQuoteCharacter(),
1339
            $this->platform->quoteStringLiteral('No quote')
1340
        );
1341
        self::assertEquals(
1342
            $this->getQuotedStringLiteralWithQuoteCharacter(),
1343
            $this->platform->quoteStringLiteral('It' . $c . 's a quote')
1344
        );
1345
        self::assertEquals(
1346
            $this->getQuotedStringLiteralQuoteCharacter(),
1347
            $this->platform->quoteStringLiteral($c)
1348
        );
1349
    }
1350
1351
    /**
1352
     * @group DBAL-423
1353
     */
1354
    public function testReturnsGuidTypeDeclarationSQL() : void
1355
    {
1356
        $this->expectException(DBALException::class);
1357
1358
        $this->platform->getGuidTypeDeclarationSQL([]);
1359
    }
1360
1361
    /**
1362
     * @group DBAL-1010
1363
     */
1364
    public function testGeneratesAlterTableRenameColumnSQL() : void
1365
    {
1366
        $table = new Table('foo');
1367
        $table->addColumn(
1368
            'bar',
1369
            'integer',
1370
            ['notnull' => true, 'default' => 666, 'comment' => 'rename test']
1371
        );
1372
1373
        $tableDiff                        = new TableDiff('foo');
1374
        $tableDiff->fromTable             = $table;
1375
        $tableDiff->renamedColumns['bar'] = new Column(
1376
            'baz',
1377
            Type::getType('integer'),
1378
            ['notnull' => true, 'default' => 666, 'comment' => 'rename test']
1379
        );
1380
1381
        self::assertSame($this->getAlterTableRenameColumnSQL(), $this->platform->getAlterTableSQL($tableDiff));
1382
    }
1383
1384
    /**
1385
     * @return string[]
1386
     */
1387
    abstract public function getAlterTableRenameColumnSQL() : array;
1388
1389
    /**
1390
     * @group DBAL-1016
1391
     */
1392
    public function testQuotesTableIdentifiersInAlterTableSQL() : void
1393
    {
1394
        $table = new Table('"foo"');
1395
        $table->addColumn('id', 'integer');
1396
        $table->addColumn('fk', 'integer');
1397
        $table->addColumn('fk2', 'integer');
1398
        $table->addColumn('fk3', 'integer');
1399
        $table->addColumn('bar', 'integer');
1400
        $table->addColumn('baz', 'integer');
1401
        $table->addForeignKeyConstraint('fk_table', ['fk'], ['id'], [], 'fk1');
1402
        $table->addForeignKeyConstraint('fk_table', ['fk2'], ['id'], [], 'fk2');
1403
1404
        $tableDiff                        = new TableDiff('"foo"');
1405
        $tableDiff->fromTable             = $table;
1406
        $tableDiff->newName               = 'table';
1407
        $tableDiff->addedColumns['bloo']  = new Column('bloo', Type::getType('integer'));
1408
        $tableDiff->changedColumns['bar'] = new ColumnDiff(
1409
            'bar',
1410
            new Column('bar', Type::getType('integer'), ['notnull' => false]),
1411
            ['notnull'],
1412
            $table->getColumn('bar')
1413
        );
1414
        $tableDiff->renamedColumns['id']  = new Column('war', Type::getType('integer'));
1415
        $tableDiff->removedColumns['baz'] = new Column('baz', Type::getType('integer'));
1416
        $tableDiff->addedForeignKeys[]    = new ForeignKeyConstraint(['fk3'], 'fk_table', ['id'], 'fk_add');
1417
        $tableDiff->changedForeignKeys[]  = new ForeignKeyConstraint(['fk2'], 'fk_table2', ['id'], 'fk2');
1418
        $tableDiff->removedForeignKeys[]  = new ForeignKeyConstraint(['fk'], 'fk_table', ['id'], 'fk1');
1419
1420
        self::assertSame(
1421
            $this->getQuotesTableIdentifiersInAlterTableSQL(),
1422
            $this->platform->getAlterTableSQL($tableDiff)
1423
        );
1424
    }
1425
1426
    /**
1427
     * @return string[]
1428
     */
1429
    abstract protected function getQuotesTableIdentifiersInAlterTableSQL() : array;
1430
1431
    /**
1432
     * @group DBAL-1090
1433
     */
1434
    public function testAlterStringToFixedString() : void
1435
    {
1436
        $table = new Table('mytable');
1437
        $table->addColumn('name', 'string', ['length' => 2]);
1438
1439
        $tableDiff            = new TableDiff('mytable');
1440
        $tableDiff->fromTable = $table;
1441
1442
        $tableDiff->changedColumns['name'] = new ColumnDiff(
1443
            'name',
1444
            new Column(
1445
                'name',
1446
                Type::getType('string'),
1447
                ['fixed' => true, 'length' => 2]
1448
            ),
1449
            ['fixed']
1450
        );
1451
1452
        $sql = $this->platform->getAlterTableSQL($tableDiff);
1453
1454
        $expectedSql = $this->getAlterStringToFixedStringSQL();
1455
1456
        self::assertEquals($expectedSql, $sql);
1457
    }
1458
1459
    /**
1460
     * @return string[]
1461
     */
1462
    abstract protected function getAlterStringToFixedStringSQL() : array;
1463
1464
    /**
1465
     * @group DBAL-1062
1466
     */
1467
    public function testGeneratesAlterTableRenameIndexUsedByForeignKeySQL() : void
1468
    {
1469
        $foreignTable = new Table('foreign_table');
1470
        $foreignTable->addColumn('id', 'integer');
1471
        $foreignTable->setPrimaryKey(['id']);
1472
1473
        $primaryTable = new Table('mytable');
1474
        $primaryTable->addColumn('foo', 'integer');
1475
        $primaryTable->addColumn('bar', 'integer');
1476
        $primaryTable->addColumn('baz', 'integer');
1477
        $primaryTable->addIndex(['foo'], 'idx_foo');
1478
        $primaryTable->addIndex(['bar'], 'idx_bar');
1479
        $primaryTable->addForeignKeyConstraint($foreignTable, ['foo'], ['id'], [], 'fk_foo');
1480
        $primaryTable->addForeignKeyConstraint($foreignTable, ['bar'], ['id'], [], 'fk_bar');
1481
1482
        $tableDiff                            = new TableDiff('mytable');
1483
        $tableDiff->fromTable                 = $primaryTable;
1484
        $tableDiff->renamedIndexes['idx_foo'] = new Index('idx_foo_renamed', ['foo']);
1485
1486
        self::assertSame(
1487
            $this->getGeneratesAlterTableRenameIndexUsedByForeignKeySQL(),
1488
            $this->platform->getAlterTableSQL($tableDiff)
1489
        );
1490
    }
1491
1492
    /**
1493
     * @return string[]
1494
     */
1495
    abstract protected function getGeneratesAlterTableRenameIndexUsedByForeignKeySQL() : array;
1496
1497
    /**
1498
     * @param mixed[] $column
1499
     *
1500
     * @group DBAL-1082
1501
     * @dataProvider getGeneratesDecimalTypeDeclarationSQL
1502
     */
1503
    public function testGeneratesDecimalTypeDeclarationSQL(array $column, string $expectedSql) : void
1504
    {
1505
        self::assertSame($expectedSql, $this->platform->getDecimalTypeDeclarationSQL($column));
1506
    }
1507
1508
    /**
1509
     * @return mixed[][]
1510
     */
1511
    public static function getGeneratesDecimalTypeDeclarationSQL() : iterable
1512
    {
1513
        return [
1514
            [[], 'NUMERIC(10, 0)'],
1515
            [['unsigned' => true], 'NUMERIC(10, 0)'],
1516
            [['unsigned' => false], 'NUMERIC(10, 0)'],
1517
            [['precision' => 5], 'NUMERIC(5, 0)'],
1518
            [['scale' => 5], 'NUMERIC(10, 5)'],
1519
            [['precision' => 8, 'scale' => 2], 'NUMERIC(8, 2)'],
1520
        ];
1521
    }
1522
1523
    /**
1524
     * @param mixed[] $column
1525
     *
1526
     * @group DBAL-1082
1527
     * @dataProvider getGeneratesFloatDeclarationSQL
1528
     */
1529
    public function testGeneratesFloatDeclarationSQL(array $column, string $expectedSql) : void
1530
    {
1531
        self::assertSame($expectedSql, $this->platform->getFloatDeclarationSQL($column));
1532
    }
1533
1534
    /**
1535
     * @return mixed[][]
1536
     */
1537
    public static function getGeneratesFloatDeclarationSQL() : iterable
1538
    {
1539
        return [
1540
            [[], 'DOUBLE PRECISION'],
1541
            [['unsigned' => true], 'DOUBLE PRECISION'],
1542
            [['unsigned' => false], 'DOUBLE PRECISION'],
1543
            [['precision' => 5], 'DOUBLE PRECISION'],
1544
            [['scale' => 5], 'DOUBLE PRECISION'],
1545
            [['precision' => 8, 'scale' => 2], 'DOUBLE PRECISION'],
1546
        ];
1547
    }
1548
1549
    public function testItEscapesStringsForLike() : void
1550
    {
1551
        self::assertSame(
1552
            '\_25\% off\_ your next purchase \\\\o/',
1553
            $this->platform->escapeStringForLike('_25% off_ your next purchase \o/', '\\')
1554
        );
1555
    }
1556
1557
    public function testZeroOffsetWithoutLimitIsIgnored() : void
1558
    {
1559
        $query = 'SELECT * FROM user';
1560
1561
        self::assertSame(
1562
            $query,
1563
            $this->platform->modifyLimitQuery($query, null, 0)
1564
        );
1565
    }
1566
}
1567