Failed Conditions
Pull Request — master (#3546)
by Sergei
14:16
created

SQLAnywherePlatform::getDropIndexSQL()   A

Complexity

Conditions 6
Paths 12

Size

Total Lines 27
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 27
ccs 14
cts 14
cp 1
rs 9.2222
c 0
b 0
f 0
cc 6
nc 12
nop 2
crap 6
1
<?php
2
3
namespace Doctrine\DBAL\Platforms;
4
5
use Doctrine\DBAL\DBALException;
6
use Doctrine\DBAL\LockMode;
7
use Doctrine\DBAL\Schema\Column;
8
use Doctrine\DBAL\Schema\ColumnDiff;
9
use Doctrine\DBAL\Schema\Constraint;
10
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
11
use Doctrine\DBAL\Schema\Identifier;
12
use Doctrine\DBAL\Schema\Index;
13
use Doctrine\DBAL\Schema\Table;
14
use Doctrine\DBAL\Schema\TableDiff;
15
use Doctrine\DBAL\TransactionIsolationLevel;
16
use InvalidArgumentException;
17
use function array_merge;
18
use function array_unique;
19
use function array_values;
20
use function count;
21
use function explode;
22
use function func_get_args;
23
use function get_class;
24
use function implode;
25
use function is_string;
26
use function preg_match;
27
use function sprintf;
28
use function strlen;
29
use function strpos;
30
use function strtoupper;
31
use function substr;
32
33
/**
34
 * The SQLAnywherePlatform provides the behavior, features and SQL dialect of the
35
 * SAP Sybase SQL Anywhere 10 database platform.
36
 */
37
class SQLAnywherePlatform extends AbstractPlatform
38
{
39
    public const FOREIGN_KEY_MATCH_SIMPLE        = 1;
40
    public const FOREIGN_KEY_MATCH_FULL          = 2;
41
    public const FOREIGN_KEY_MATCH_SIMPLE_UNIQUE = 129;
42
    public const FOREIGN_KEY_MATCH_FULL_UNIQUE   = 130;
43
44
    /**
45
     * {@inheritdoc}
46
     */
47 12431
    public function appendLockHint($fromClause, $lockMode)
48
    {
49 12431
        switch (true) {
50
            case $lockMode === LockMode::NONE:
51 12333
                return $fromClause . ' WITH (NOLOCK)';
52
53 12423
            case $lockMode === LockMode::PESSIMISTIC_READ:
54 12283
                return $fromClause . ' WITH (UPDLOCK)';
55
56 12415
            case $lockMode === LockMode::PESSIMISTIC_WRITE:
57 12258
                return $fromClause . ' WITH (XLOCK)';
58
59
            default:
60 12407
                return $fromClause;
61
        }
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     *
67
     * SQL Anywhere supports a maximum length of 128 bytes for identifiers.
68
     */
69 12208
    public function fixSchemaElementName($schemaElementName)
70
    {
71 12208
        $maxIdentifierLength = $this->getMaxIdentifierLength();
72
73 12208
        if (strlen($schemaElementName) > $maxIdentifierLength) {
74 12208
            return substr($schemaElementName, 0, $maxIdentifierLength);
75
        }
76
77 12208
        return $schemaElementName;
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83 12506
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
84
    {
85 12506
        $query = '';
86
87 12506
        if ($foreignKey->hasOption('match')) {
88 11983
            $query = ' MATCH ' . $this->getForeignKeyMatchClauseSQL($foreignKey->getOption('match'));
89
        }
90
91 12506
        $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
92
93 12506
        if ($foreignKey->hasOption('check_on_commit') && (bool) $foreignKey->getOption('check_on_commit')) {
94 11983
            $query .= ' CHECK ON COMMIT';
95
        }
96
97 12506
        if ($foreignKey->hasOption('clustered') && (bool) $foreignKey->getOption('clustered')) {
98 11983
            $query .= ' CLUSTERED';
99
        }
100
101 12506
        if ($foreignKey->hasOption('for_olap_workload') && (bool) $foreignKey->getOption('for_olap_workload')) {
102 11983
            $query .= ' FOR OLAP WORKLOAD';
103
        }
104
105 12506
        return $query;
106
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111 12520
    public function getAlterTableSQL(TableDiff $diff)
112
    {
113 12520
        $sql          = [];
114 12520
        $columnSql    = [];
115 12520
        $commentsSQL  = [];
116 12520
        $tableSql     = [];
117 12520
        $alterClauses = [];
118
119 12520
        foreach ($diff->addedColumns as $column) {
120 10182
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
121
                continue;
122
            }
123
124 10182
            $alterClauses[] = $this->getAlterTableAddColumnClause($column);
125
126 10182
            $comment = $this->getColumnComment($column);
127
128 10182
            if ($comment === null || $comment === '') {
129 10174
                continue;
130
            }
131
132 10058
            $commentsSQL[] = $this->getCommentOnColumnSQL(
133 10058
                $diff->getName($this)->getQuotedName($this),
134 10058
                $column->getQuotedName($this),
135 8
                $comment
136
            );
137
        }
138
139 12520
        foreach ($diff->removedColumns as $column) {
140 10174
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
141
                continue;
142
            }
143
144 10174
            $alterClauses[] = $this->getAlterTableRemoveColumnClause($column);
145
        }
146
147 12520
        foreach ($diff->changedColumns as $columnDiff) {
148 12464
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
149
                continue;
150
            }
151
152 12464
            $alterClause = $this->getAlterTableChangeColumnClause($columnDiff);
153
154 12464
            if ($alterClause !== null) {
155 10190
                $alterClauses[] = $alterClause;
156
            }
157
158 12464
            if (! $columnDiff->hasChanged('comment')) {
159 10190
                continue;
160
            }
161
162 12424
            $column = $columnDiff->column;
163
164 12424
            $commentsSQL[] = $this->getCommentOnColumnSQL(
165 12424
                $diff->getName($this)->getQuotedName($this),
166 12424
                $column->getQuotedName($this),
167 12424
                $this->getColumnComment($column)
168
            );
169
        }
170
171 12520
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
172 10132
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
173
                continue;
174
            }
175
176 10132
            $sql[] = $this->getAlterTableClause($diff->getName($this)) . ' ' .
177 10132
                $this->getAlterTableRenameColumnClause($oldColumnName, $column);
178
        }
179
180 12520
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
181 12520
            if (! empty($alterClauses)) {
182 10198
                $sql[] = $this->getAlterTableClause($diff->getName($this)) . ' ' . implode(', ', $alterClauses);
183
            }
184
185 12520
            $sql = array_merge($sql, $commentsSQL);
186
187 12520
            $newName = $diff->getNewName();
188
189 12520
            if ($newName !== false) {
190 10166
                $sql[] = $this->getAlterTableClause($diff->getName($this)) . ' ' .
191 10166
                    $this->getAlterTableRenameTableClause($newName);
192
            }
193
194 12520
            $sql = array_merge(
195 12520
                $this->getPreAlterTableIndexForeignKeySQL($diff),
196 12520
                $sql,
197 12520
                $this->getPostAlterTableIndexForeignKeySQL($diff)
198
            );
199
        }
200
201 12520
        return array_merge($sql, $tableSql, $columnSql);
202
    }
203
204
    /**
205
     * Returns the SQL clause for creating a column in a table alteration.
206
     *
207
     * @param Column $column The column to add.
208
     *
209
     * @return string
210
     */
211 10182
    protected function getAlterTableAddColumnClause(Column $column)
212
    {
213 10182
        return 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
214
    }
215
216
    /**
217
     * Returns the SQL clause for altering a table.
218
     *
219
     * @param Identifier $tableName The quoted name of the table to alter.
220
     *
221
     * @return string
222
     */
223 10214
    protected function getAlterTableClause(Identifier $tableName)
224
    {
225 10214
        return 'ALTER TABLE ' . $tableName->getQuotedName($this);
226
    }
227
228
    /**
229
     * Returns the SQL clause for dropping a column in a table alteration.
230
     *
231
     * @param Column $column The column to drop.
232
     *
233
     * @return string
234
     */
235 10174
    protected function getAlterTableRemoveColumnClause(Column $column)
236
    {
237 10174
        return 'DROP ' . $column->getQuotedName($this);
238
    }
239
240
    /**
241
     * Returns the SQL clause for renaming a column in a table alteration.
242
     *
243
     * @param string $oldColumnName The quoted name of the column to rename.
244
     * @param Column $column        The column to rename to.
245
     *
246
     * @return string
247
     */
248 10132
    protected function getAlterTableRenameColumnClause($oldColumnName, Column $column)
249
    {
250 10132
        $oldColumnName = new Identifier($oldColumnName);
251
252 10132
        return 'RENAME ' . $oldColumnName->getQuotedName($this) . ' TO ' . $column->getQuotedName($this);
253
    }
254
255
    /**
256
     * Returns the SQL clause for renaming a table in a table alteration.
257
     *
258
     * @param Identifier $newTableName The quoted name of the table to rename to.
259
     *
260
     * @return string
261
     */
262 10166
    protected function getAlterTableRenameTableClause(Identifier $newTableName)
263
    {
264 10166
        return 'RENAME ' . $newTableName->getQuotedName($this);
265
    }
266
267
    /**
268
     * Returns the SQL clause for altering a column in a table alteration.
269
     *
270
     * This method returns null in case that only the column comment has changed.
271
     * Changes in column comments have to be handled differently.
272
     *
273
     * @param ColumnDiff $columnDiff The diff of the column to alter.
274
     *
275
     * @return string|null
276
     */
277 12464
    protected function getAlterTableChangeColumnClause(ColumnDiff $columnDiff)
278
    {
279 12464
        $column = $columnDiff->column;
280
281
        // Do not return alter clause if only comment has changed.
282 12464
        if (! ($columnDiff->hasChanged('comment') && count($columnDiff->changedProperties) === 1)) {
283
            $columnAlterationClause = 'ALTER ' .
284 10190
                $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
285
286 10190
            if ($columnDiff->hasChanged('default') && $column->getDefault() === null) {
287
                $columnAlterationClause .= ', ALTER ' . $column->getQuotedName($this) . ' DROP DEFAULT';
288
            }
289
290 10190
            return $columnAlterationClause;
291
        }
292
293 12424
        return null;
294
    }
295
296
    /**
297
     * {@inheritdoc}
298
     */
299 12183
    public function getBigIntTypeDeclarationSQL(array $columnDef)
300
    {
301 12183
        $columnDef['integer_type'] = 'BIGINT';
302
303 12183
        return $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
304
    }
305
306
    /**
307
     * {@inheritdoc}
308
     */
309 11316
    public function getBinaryDefaultLength()
310
    {
311 11316
        return 1;
312
    }
313
314
    /**
315
     * {@inheritdoc}
316
     */
317 11324
    public function getBinaryMaxLength()
318
    {
319 11324
        return 32767;
320
    }
321
322
    /**
323
     * {@inheritdoc}
324
     */
325 12191
    public function getBlobTypeDeclarationSQL(array $field)
326
    {
327 12191
        return 'LONG BINARY';
328
    }
329
330
    /**
331
     * {@inheritdoc}
332
     *
333
     * BIT type columns require an explicit NULL declaration
334
     * in SQL Anywhere if they shall be nullable.
335
     * Otherwise by just omitting the NOT NULL clause,
336
     * SQL Anywhere will declare them NOT NULL nonetheless.
337
     */
338 12191
    public function getBooleanTypeDeclarationSQL(array $columnDef)
339
    {
340 12191
        $nullClause = isset($columnDef['notnull']) && (bool) $columnDef['notnull'] === false ? ' NULL' : '';
341
342 12191
        return 'BIT' . $nullClause;
343
    }
344
345
    /**
346
     * {@inheritdoc}
347
     */
348 12199
    public function getClobTypeDeclarationSQL(array $field)
349
    {
350 12199
        return 'TEXT';
351
    }
352
353
    /**
354
     * {@inheritdoc}
355
     */
356 12464
    public function getCommentOnColumnSQL($tableName, $columnName, $comment)
357
    {
358 12464
        $tableName  = new Identifier($tableName);
359 12464
        $columnName = new Identifier($columnName);
360 12464
        $comment    = $comment === null ? 'NULL' : $this->quoteStringLiteral($comment);
361
362 12464
        return sprintf(
363 64
            'COMMENT ON COLUMN %s.%s IS %s',
364 12464
            $tableName->getQuotedName($this),
365 12464
            $columnName->getQuotedName($this),
366 12464
            $comment
367
        );
368
    }
369
370
    /**
371
     * {@inheritdoc}
372
     */
373 11658
    public function getConcatExpression()
374
    {
375 11658
        return 'STRING(' . implode(', ', (array) func_get_args()) . ')';
376
    }
377
378
    /**
379
     * {@inheritdoc}
380
     */
381 11849
    public function getCreateConstraintSQL(Constraint $constraint, $table)
382
    {
383 11849
        if ($constraint instanceof ForeignKeyConstraint) {
384 10208
            return $this->getCreateForeignKeySQL($constraint, $table);
385
        }
386
387 11849
        if ($table instanceof Table) {
388 11833
            $table = $table->getQuotedName($this);
389
        }
390
391 11849
        return 'ALTER TABLE ' . $table .
392 11849
               ' ADD ' . $this->getTableConstraintDeclarationSQL($constraint, $constraint->getQuotedName($this));
393
    }
394
395
    /**
396
     * {@inheritdoc}
397
     */
398 12133
    public function getCreateDatabaseSQL($database)
399
    {
400 12133
        $database = new Identifier($database);
401
402 12133
        return "CREATE DATABASE '" . $database->getName() . "'";
403
    }
404
405
    /**
406
     * {@inheritdoc}
407
     *
408
     * Appends SQL Anywhere specific flags if given.
409
     */
410 12541
    public function getCreateIndexSQL(Index $index, $table)
411
    {
412 12541
        return parent::getCreateIndexSQL($index, $table) . $this->getAdvancedIndexOptionsSQL($index);
413
    }
414
415
    /**
416
     * {@inheritdoc}
417
     */
418 12062
    public function getCreatePrimaryKeySQL(Index $index, $table)
419
    {
420 12062
        if ($table instanceof Table) {
421 12058
            $table = $table->getQuotedName($this);
422
        }
423
424 12062
        return 'ALTER TABLE ' . $table . ' ADD ' . $this->getPrimaryKeyDeclarationSQL($index);
425
    }
426
427
    /**
428
     * {@inheritdoc}
429
     */
430 12133
    public function getCreateTemporaryTableSnippetSQL()
431
    {
432 12133
        return 'CREATE ' . $this->getTemporaryTableSQL() . ' TABLE';
433
    }
434
435
    /**
436
     * {@inheritdoc}
437
     */
438 12133
    public function getCreateViewSQL($name, $sql)
439
    {
440 12133
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
441
    }
442
443
    /**
444
     * {@inheritdoc}
445
     */
446 11666
    public function getCurrentDateSQL()
447
    {
448 11666
        return 'CURRENT DATE';
449
    }
450
451
    /**
452
     * {@inheritdoc}
453
     */
454 11658
    public function getCurrentTimeSQL()
455
    {
456 11658
        return 'CURRENT TIME';
457
    }
458
459
    /**
460
     * {@inheritdoc}
461
     */
462 11666
    public function getCurrentTimestampSQL()
463
    {
464 11666
        return 'CURRENT TIMESTAMP';
465
    }
466
467
    /**
468
     * {@inheritdoc}
469
     */
470 11658
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
471
    {
472 11658
        $factorClause = '';
473
474 11658
        if ($operator === '-') {
475 11658
            $factorClause = '-1 * ';
476
        }
477
478 11658
        return 'DATEADD(' . $unit . ', ' . $factorClause . $interval . ', ' . $date . ')';
479
    }
480
481
    /**
482
     * {@inheritdoc}
483
     */
484 11658
    public function getDateDiffExpression($date1, $date2)
485
    {
486 11658
        return 'DATEDIFF(day, ' . $date2 . ', ' . $date1 . ')';
487
    }
488
489
    /**
490
     * {@inheritdoc}
491
     */
492 11662
    public function getDateTimeFormatString()
493
    {
494 11662
        return 'Y-m-d H:i:s.u';
495
    }
496
497
    /**
498
     * {@inheritdoc}
499
     */
500 12183
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
501
    {
502 12183
        return 'DATETIME';
503
    }
504
505
    /**
506
     * {@inheritdoc}
507
     */
508 11629
    public function getDateTimeTzFormatString()
509
    {
510 11629
        return $this->getDateTimeFormatString();
511
    }
512
513
    /**
514
     * {@inheritdoc}
515
     */
516 12183
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
517
    {
518 12183
        return 'DATE';
519
    }
520
521
    /**
522
     * {@inheritdoc}
523
     */
524 11608
    public function getDefaultTransactionIsolationLevel()
525
    {
526 11608
        return TransactionIsolationLevel::READ_UNCOMMITTED;
527
    }
528
529
    /**
530
     * {@inheritdoc}
531
     */
532 12133
    public function getDropDatabaseSQL($database)
533
    {
534 12133
        $database = new Identifier($database);
535
536 12133
        return "DROP DATABASE '" . $database->getName() . "'";
537
    }
538
539
    /**
540
     * {@inheritdoc}
541
     */
542 11749
    public function getDropIndexSQL($index, $table = null)
543
    {
544 11749
        if ($index instanceof Index) {
545 11733
            $index = $index->getQuotedName($this);
546
        }
547
548 11749
        if (! is_string($index)) {
549 11708
            throw new InvalidArgumentException(
550 11708
                'SQLAnywherePlatform::getDropIndexSQL() expects $index parameter to be string or ' . Index::class . '.'
551
            );
552
        }
553
554 11741
        if (! isset($table)) {
555 11733
            return 'DROP INDEX ' . $index;
556
        }
557
558 11741
        if ($table instanceof Table) {
559 11733
            $table = $table->getQuotedName($this);
560
        }
561
562 11741
        if (! is_string($table)) {
563 11683
            throw new InvalidArgumentException(
564 11683
                'SQLAnywherePlatform::getDropIndexSQL() expects $table parameter to be string or ' . Index::class . '.'
565
            );
566
        }
567
568 11733
        return 'DROP INDEX ' . $table . '.' . $index;
569
    }
570
571
    /**
572
     * {@inheritdoc}
573
     */
574 12133
    public function getDropViewSQL($name)
575
    {
576 12133
        return 'DROP VIEW ' . $name;
577
    }
578
579
    /**
580
     * {@inheritdoc}
581
     */
582 12530
    public function getForeignKeyBaseDeclarationSQL(ForeignKeyConstraint $foreignKey)
583
    {
584 12530
        $sql              = '';
585 12530
        $foreignKeyName   = $foreignKey->getName();
586 12530
        $localColumns     = $foreignKey->getQuotedLocalColumns($this);
587 12530
        $foreignColumns   = $foreignKey->getQuotedForeignColumns($this);
588 12530
        $foreignTableName = $foreignKey->getQuotedForeignTableName($this);
589
590 12530
        if (! empty($foreignKeyName)) {
591 12498
            $sql .= 'CONSTRAINT ' . $foreignKey->getQuotedName($this) . ' ';
592
        }
593
594 12530
        if (empty($localColumns)) {
595 11908
            throw new InvalidArgumentException("Incomplete definition. 'local' required.");
596
        }
597
598 12522
        if (empty($foreignColumns)) {
599 11883
            throw new InvalidArgumentException("Incomplete definition. 'foreign' required.");
600
        }
601
602 12514
        if (empty($foreignTableName)) {
603 11858
            throw new InvalidArgumentException("Incomplete definition. 'foreignTable' required.");
604
        }
605
606 12506
        if ($foreignKey->hasOption('notnull') && (bool) $foreignKey->getOption('notnull')) {
607 11983
            $sql .= 'NOT NULL ';
608
        }
609
610
        return $sql .
611 12506
            'FOREIGN KEY (' . $this->getIndexFieldDeclarationListSQL($localColumns) . ') ' .
612 12506
            'REFERENCES ' . $foreignKey->getQuotedForeignTableName($this) .
613 12506
            ' (' . $this->getIndexFieldDeclarationListSQL($foreignColumns) . ')';
614
    }
615
616
    /**
617
     * Returns foreign key MATCH clause for given type.
618
     *
619
     * @param int $type The foreign key match type
620
     *
621
     * @return string
622
     *
623
     * @throws InvalidArgumentException If unknown match type given.
624
     */
625 11999
    public function getForeignKeyMatchClauseSQL($type)
626
    {
627 11999
        switch ((int) $type) {
628 11999
            case self::FOREIGN_KEY_MATCH_SIMPLE:
629 11958
                return 'SIMPLE';
630
631
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
632 11999
            case self::FOREIGN_KEY_MATCH_FULL:
633 11958
                return 'FULL';
634
635
                break;
636 11999
            case self::FOREIGN_KEY_MATCH_SIMPLE_UNIQUE:
637 11991
                return 'UNIQUE SIMPLE';
638
639
                break;
640 11966
            case self::FOREIGN_KEY_MATCH_FULL_UNIQUE:
641 11958
                return 'UNIQUE FULL';
642
            default:
643 11933
                throw new InvalidArgumentException('Invalid foreign key match type: ' . $type);
644
        }
645
    }
646
647
    /**
648
     * {@inheritdoc}
649
     */
650 12039
    public function getForeignKeyReferentialActionSQL($action)
651
    {
652
        // NO ACTION is not supported, therefore falling back to RESTRICT.
653 12039
        if (strtoupper($action) === 'NO ACTION') {
654 10958
            return 'RESTRICT';
655
        }
656
657 12031
        return parent::getForeignKeyReferentialActionSQL($action);
658
    }
659
660
    /**
661
     * {@inheritdoc}
662
     */
663 11658
    public function getForUpdateSQL()
664
    {
665 11658
        return '';
666
    }
667
668
    /**
669
     * {@inheritdoc}
670
     *
671
     * @deprecated Use application-generated UUIDs instead
672
     */
673 11658
    public function getGuidExpression()
674
    {
675 11658
        return 'NEWID()';
676
    }
677
678
    /**
679
     * {@inheritdoc}
680
     */
681 12191
    public function getGuidTypeDeclarationSQL(array $field)
682
    {
683 12191
        return 'UNIQUEIDENTIFIER';
684
    }
685
686
    /**
687
     * {@inheritdoc}
688
     */
689 11766
    public function getIndexDeclarationSQL($name, Index $index)
690
    {
691
        // Index declaration in statements like CREATE TABLE is not supported.
692 11766
        throw DBALException::notSupported(__METHOD__);
693
    }
694
695
    /**
696
     * {@inheritdoc}
697
     */
698 12563
    public function getIntegerTypeDeclarationSQL(array $columnDef)
699
    {
700 12563
        $columnDef['integer_type'] = 'INT';
701
702 12563
        return $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
703
    }
704
705
    /**
706
     * {@inheritdoc}
707
     */
708
    public function getListDatabasesSQL()
709
    {
710
        return 'SELECT db_name(number) AS name FROM sa_db_list()';
711
    }
712
713
    /**
714
     * {@inheritdoc}
715
     */
716 11208
    public function getListTableColumnsSQL($table, $database = null)
717
    {
718 11208
        $user = 'USER_NAME()';
719
720 11208
        if (strpos($table, '.') !== false) {
721 11208
            [$user, $table] = explode('.', $table);
722 11208
            $user           = $this->quoteStringLiteral($user);
723
        }
724
725 11208
        return sprintf(
726
            <<<'SQL'
727 8
SELECT    col.column_name,
728
          COALESCE(def.user_type_name, def.domain_name) AS 'type',
729
          def.declared_width AS 'length',
730
          def.scale,
731
          CHARINDEX('unsigned', def.domain_name) AS 'unsigned',
732
          IF col.nulls = 'Y' THEN 0 ELSE 1 ENDIF AS 'notnull',
733
          col."default",
734
          def.is_autoincrement AS 'autoincrement',
735
          rem.remarks AS 'comment'
736
FROM      sa_describe_query('SELECT * FROM "%s"') AS def
737
JOIN      SYS.SYSTABCOL AS col
738
ON        col.table_id = def.base_table_id AND col.column_id = def.base_column_id
739
LEFT JOIN SYS.SYSREMARK AS rem
740
ON        col.object_id = rem.object_id
741
WHERE     def.base_owner_name = %s
742
ORDER BY  def.base_column_id ASC
743
SQL
744
            ,
745 11208
            $table,
746 11208
            $user
747
        );
748
    }
749
750
    /**
751
     * {@inheritdoc}
752
     *
753
     * @todo Where is this used? Which information should be retrieved?
754
     */
755 11191
    public function getListTableConstraintsSQL($table)
756
    {
757 11191
        $user = '';
758
759 11191
        if (strpos($table, '.') !== false) {
760 11158
            [$user, $table] = explode('.', $table);
761 11158
            $user           = $this->quoteStringLiteral($user);
762 11158
            $table          = $this->quoteStringLiteral($table);
763
        } else {
764 11183
            $table = $this->quoteStringLiteral($table);
765
        }
766
767 11191
        return sprintf(
768
            <<<'SQL'
769 16
SELECT con.*
770
FROM   SYS.SYSCONSTRAINT AS con
771
JOIN   SYS.SYSTAB AS tab ON con.table_object_id = tab.object_id
772
WHERE  tab.table_name = %s
773
AND    tab.creator = USER_ID(%s)
774
SQL
775
            ,
776 11191
            $table,
777 11191
            $user
778
        );
779
    }
780
781
    /**
782
     * {@inheritdoc}
783
     */
784 11141
    public function getListTableForeignKeysSQL($table)
785
    {
786 11141
        $user = '';
787
788 11141
        if (strpos($table, '.') !== false) {
789 11108
            [$user, $table] = explode('.', $table);
790 11108
            $user           = $this->quoteStringLiteral($user);
791 11108
            $table          = $this->quoteStringLiteral($table);
792
        } else {
793 11133
            $table = $this->quoteStringLiteral($table);
794
        }
795
796 11141
        return sprintf(
797
            <<<'SQL'
798 16
SELECT    fcol.column_name AS local_column,
799
          ptbl.table_name AS foreign_table,
800
          pcol.column_name AS foreign_column,
801
          idx.index_name,
802
          IF fk.nulls = 'N'
803
              THEN 1
804
              ELSE NULL
805
          ENDIF AS notnull,
806
          CASE ut.referential_action
807
              WHEN 'C' THEN 'CASCADE'
808
              WHEN 'D' THEN 'SET DEFAULT'
809
              WHEN 'N' THEN 'SET NULL'
810
              WHEN 'R' THEN 'RESTRICT'
811
              ELSE NULL
812
          END AS  on_update,
813
          CASE dt.referential_action
814
              WHEN 'C' THEN 'CASCADE'
815
              WHEN 'D' THEN 'SET DEFAULT'
816
              WHEN 'N' THEN 'SET NULL'
817
              WHEN 'R' THEN 'RESTRICT'
818
              ELSE NULL
819
          END AS on_delete,
820
          IF fk.check_on_commit = 'Y'
821
              THEN 1
822
              ELSE NULL
823
          ENDIF AS check_on_commit, -- check_on_commit flag
824
          IF ftbl.clustered_index_id = idx.index_id
825
              THEN 1
826
              ELSE NULL
827
          ENDIF AS 'clustered', -- clustered flag
828
          IF fk.match_type = 0
829
              THEN NULL
830
              ELSE fk.match_type
831
          ENDIF AS 'match', -- match option
832
          IF pidx.max_key_distance = 1
833
              THEN 1
834
              ELSE NULL
835
          ENDIF AS for_olap_workload -- for_olap_workload flag
836
FROM      SYS.SYSFKEY AS fk
837
JOIN      SYS.SYSIDX AS idx
838
ON        fk.foreign_table_id = idx.table_id
839
AND       fk.foreign_index_id = idx.index_id
840
JOIN      SYS.SYSPHYSIDX pidx
841
ON        idx.table_id = pidx.table_id
842
AND       idx.phys_index_id = pidx.phys_index_id
843
JOIN      SYS.SYSTAB AS ptbl
844
ON        fk.primary_table_id = ptbl.table_id
845
JOIN      SYS.SYSTAB AS ftbl
846
ON        fk.foreign_table_id = ftbl.table_id
847
JOIN      SYS.SYSIDXCOL AS idxcol
848
ON        idx.table_id = idxcol.table_id
849
AND       idx.index_id = idxcol.index_id
850
JOIN      SYS.SYSTABCOL AS pcol
851
ON        ptbl.table_id = pcol.table_id
852
AND       idxcol.primary_column_id = pcol.column_id
853
JOIN      SYS.SYSTABCOL AS fcol
854
ON        ftbl.table_id = fcol.table_id
855
AND       idxcol.column_id = fcol.column_id
856
LEFT JOIN SYS.SYSTRIGGER ut
857
ON        fk.foreign_table_id = ut.foreign_table_id
858
AND       fk.foreign_index_id = ut.foreign_key_id
859
AND       ut.event = 'C'
860
LEFT JOIN SYS.SYSTRIGGER dt
861
ON        fk.foreign_table_id = dt.foreign_table_id
862
AND       fk.foreign_index_id = dt.foreign_key_id
863
AND       dt.event = 'D'
864
WHERE     ftbl.table_name = %s
865
AND       ftbl.creator = USER_ID(%s)
866
ORDER BY  fk.foreign_index_id ASC, idxcol.sequence ASC
867
SQL
868
            ,
869 11141
            $table,
870 11141
            $user
871
        );
872
    }
873
874
    /**
875
     * {@inheritdoc}
876
     */
877 11091
    public function getListTableIndexesSQL($table, $currentDatabase = null)
878
    {
879 11091
        $user = '';
880
881 11091
        if (strpos($table, '.') !== false) {
882 11058
            [$user, $table] = explode('.', $table);
883 11058
            $user           = $this->quoteStringLiteral($user);
884 11058
            $table          = $this->quoteStringLiteral($table);
885
        } else {
886 11083
            $table = $this->quoteStringLiteral($table);
887
        }
888
889 11091
        return sprintf(
890
            <<<'SQL'
891 16
SELECT   idx.index_name AS key_name,
892
         IF idx.index_category = 1
893
             THEN 1
894
             ELSE 0
895
         ENDIF AS 'primary',
896
         col.column_name,
897
         IF idx."unique" IN(1, 2, 5)
898
             THEN 0
899
             ELSE 1
900
         ENDIF AS non_unique,
901
         IF tbl.clustered_index_id = idx.index_id
902
             THEN 1
903
             ELSE NULL
904
         ENDIF AS 'clustered', -- clustered flag
905
         IF idx."unique" = 5
906
             THEN 1
907
             ELSE NULL
908
         ENDIF AS with_nulls_not_distinct, -- with_nulls_not_distinct flag
909
         IF pidx.max_key_distance = 1
910
              THEN 1
911
              ELSE NULL
912
          ENDIF AS for_olap_workload -- for_olap_workload flag
913
FROM     SYS.SYSIDX AS idx
914
JOIN     SYS.SYSPHYSIDX pidx
915
ON       idx.table_id = pidx.table_id
916
AND      idx.phys_index_id = pidx.phys_index_id
917
JOIN     SYS.SYSIDXCOL AS idxcol
918
ON       idx.table_id = idxcol.table_id AND idx.index_id = idxcol.index_id
919
JOIN     SYS.SYSTABCOL AS col
920
ON       idxcol.table_id = col.table_id AND idxcol.column_id = col.column_id
921
JOIN     SYS.SYSTAB AS tbl
922
ON       idx.table_id = tbl.table_id
923
WHERE    tbl.table_name = %s
924
AND      tbl.creator = USER_ID(%s)
925
AND      idx.index_category != 2 -- exclude indexes implicitly created by foreign key constraints
926
ORDER BY idx.index_id ASC, idxcol.sequence ASC
927
SQL
928
            ,
929 11091
            $table,
930 11091
            $user
931
        );
932
    }
933
934
    /**
935
     * {@inheritdoc}
936
     */
937
    public function getListTablesSQL()
938
    {
939
        return "SELECT   tbl.table_name
940
                FROM     SYS.SYSTAB AS tbl
941
                JOIN     SYS.SYSUSER AS usr ON tbl.creator = usr.user_id
942
                JOIN     dbo.SYSOBJECTS AS obj ON tbl.object_id = obj.id
943
                WHERE    tbl.table_type IN(1, 3) -- 'BASE', 'GBL TEMP'
944
                AND      usr.user_name NOT IN('SYS', 'dbo', 'rs_systabgroup') -- exclude system users
945
                AND      obj.type = 'U' -- user created tables only
946
                ORDER BY tbl.table_name ASC";
947
    }
948
949
    /**
950
     * {@inheritdoc}
951
     *
952
     * @todo Where is this used? Which information should be retrieved?
953
     */
954
    public function getListUsersSQL()
955
    {
956
        return 'SELECT * FROM SYS.SYSUSER ORDER BY user_name ASC';
957
    }
958
959
    /**
960
     * {@inheritdoc}
961
     */
962
    public function getListViewsSQL($database)
963
    {
964
        return "SELECT   tbl.table_name, v.view_def
965
                FROM     SYS.SYSVIEW v
966
                JOIN     SYS.SYSTAB tbl ON v.view_object_id = tbl.object_id
967
                JOIN     SYS.SYSUSER usr ON tbl.creator = usr.user_id
968
                JOIN     dbo.SYSOBJECTS obj ON tbl.object_id = obj.id
969
                WHERE    usr.user_name NOT IN('SYS', 'dbo', 'rs_systabgroup') -- exclude system users
970
                ORDER BY tbl.table_name ASC";
971
    }
972
973
    /**
974
     * {@inheritdoc}
975
     */
976 11658
    public function getLocateExpression($str, $substr, $startPos = false)
977
    {
978 11658
        if ($startPos === false) {
979 11658
            return 'LOCATE(' . $str . ', ' . $substr . ')';
980
        }
981
982 11658
        return 'LOCATE(' . $str . ', ' . $substr . ', ' . $startPos . ')';
983
    }
984
985
    /**
986
     * {@inheritdoc}
987
     */
988 12241
    public function getMaxIdentifierLength()
989
    {
990 12241
        return 128;
991
    }
992
993
    /**
994
     * {@inheritdoc}
995
     */
996 11658
    public function getMd5Expression($column)
997
    {
998 11658
        return 'HASH(' . $column . ", 'MD5')";
999
    }
1000
1001
    /**
1002
     * {@inheritdoc}
1003
     */
1004 12499
    public function getName()
1005
    {
1006 12499
        return 'sqlanywhere';
1007
    }
1008
1009
    /**
1010
     * Obtain DBMS specific SQL code portion needed to set a primary key
1011
     * declaration to be used in statements like ALTER TABLE.
1012
     *
1013
     * @param Index  $index Index definition
1014
     * @param string $name  Name of the primary key
1015
     *
1016
     * @return string DBMS specific SQL code portion needed to set a primary key
1017
     *
1018
     * @throws InvalidArgumentException If the given index is not a primary key.
1019
     */
1020 12128
    public function getPrimaryKeyDeclarationSQL(Index $index, $name = null)
1021
    {
1022 12128
        if (! $index->isPrimary()) {
1023
            throw new InvalidArgumentException(
1024
                'Can only create primary key declarations with getPrimaryKeyDeclarationSQL()'
1025
            );
1026
        }
1027
1028 12128
        return $this->getTableConstraintDeclarationSQL($index, $name);
1029
    }
1030
1031
    /**
1032
     * {@inheritdoc}
1033
     */
1034 11591
    public function getSetTransactionIsolationSQL($level)
1035
    {
1036 11591
        return 'SET TEMPORARY OPTION isolation_level = ' . $this->_getTransactionIsolationLevelSQL($level);
1037
    }
1038
1039
    /**
1040
     * {@inheritdoc}
1041
     */
1042 12183
    public function getSmallIntTypeDeclarationSQL(array $columnDef)
1043
    {
1044 12183
        $columnDef['integer_type'] = 'SMALLINT';
1045
1046 12183
        return $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
1047
    }
1048
1049
    /**
1050
     * Returns the SQL statement for starting an existing database.
1051
     *
1052
     * In SQL Anywhere you can start and stop databases on a
1053
     * database server instance.
1054
     * This is a required statement after having created a new database
1055
     * as it has to be explicitly started to be usable.
1056
     * SQL Anywhere does not automatically start a database after creation!
1057
     *
1058
     * @param string $database Name of the database to start.
1059
     *
1060
     * @return string
1061
     */
1062 12133
    public function getStartDatabaseSQL($database)
1063
    {
1064 12133
        $database = new Identifier($database);
1065
1066 12133
        return "START DATABASE '" . $database->getName() . "' AUTOSTOP OFF";
1067
    }
1068
1069
    /**
1070
     * Returns the SQL statement for stopping a running database.
1071
     *
1072
     * In SQL Anywhere you can start and stop databases on a
1073
     * database server instance.
1074
     * This is a required statement before dropping an existing database
1075
     * as it has to be explicitly stopped before it can be dropped.
1076
     *
1077
     * @param string $database Name of the database to stop.
1078
     *
1079
     * @return string
1080
     */
1081 12133
    public function getStopDatabaseSQL($database)
1082
    {
1083 12133
        $database = new Identifier($database);
1084
1085 12133
        return 'STOP DATABASE "' . $database->getName() . '" UNCONDITIONALLY';
1086
    }
1087
1088
    /**
1089
     * {@inheritdoc}
1090
     */
1091 11658
    public function getSubstringExpression($value, $from, $length = null)
1092
    {
1093 11658
        if ($length === null) {
1094 11658
            return 'SUBSTRING(' . $value . ', ' . $from . ')';
1095
        }
1096
1097 11658
        return 'SUBSTRING(' . $value . ', ' . $from . ', ' . $length . ')';
1098
    }
1099
1100
    /**
1101
     * {@inheritdoc}
1102
     */
1103 12141
    public function getTemporaryTableSQL()
1104
    {
1105 12141
        return 'GLOBAL TEMPORARY';
1106
    }
1107
1108
    /**
1109
     * {@inheritdoc}
1110
     */
1111 11658
    public function getTimeFormatString()
1112
    {
1113 11658
        return 'H:i:s.u';
1114
    }
1115
1116
    /**
1117
     * {@inheritdoc}
1118
     */
1119 12183
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
1120
    {
1121 12183
        return 'TIME';
1122
    }
1123
1124
    /**
1125
     * {@inheritdoc}
1126
     */
1127 11658
    public function getTrimExpression($str, $pos = TrimMode::UNSPECIFIED, $char = false)
1128
    {
1129 11658
        if (! $char) {
1130 11658
            switch ($pos) {
1131
                case TrimMode::LEADING:
1132 11658
                    return $this->getLtrimExpression($str);
1133
                case TrimMode::TRAILING:
1134 11658
                    return $this->getRtrimExpression($str);
1135
                default:
1136 11658
                    return 'TRIM(' . $str . ')';
1137
            }
1138
        }
1139
1140 11658
        $pattern = "'%[^' + " . $char . " + ']%'";
1141
1142 11658
        switch ($pos) {
1143
            case TrimMode::LEADING:
1144 11658
                return 'SUBSTR(' . $str . ', PATINDEX(' . $pattern . ', ' . $str . '))';
1145
            case TrimMode::TRAILING:
1146 11658
                return 'REVERSE(SUBSTR(REVERSE(' . $str . '), PATINDEX(' . $pattern . ', REVERSE(' . $str . '))))';
1147
            default:
1148 11658
                return 'REVERSE(SUBSTR(REVERSE(SUBSTR(' . $str . ', PATINDEX(' . $pattern . ', ' . $str . '))), ' .
1149 11658
                    'PATINDEX(' . $pattern . ', REVERSE(SUBSTR(' . $str . ', PATINDEX(' . $pattern . ', ' . $str . '))))))';
1150
        }
1151
    }
1152
1153
    /**
1154
     * {@inheritdoc}
1155
     */
1156 12141
    public function getTruncateTableSQL($tableName, $cascade = false)
1157
    {
1158 12141
        $tableIdentifier = new Identifier($tableName);
1159
1160 12141
        return 'TRUNCATE TABLE ' . $tableIdentifier->getQuotedName($this);
1161
    }
1162
1163
    /**
1164
     * {@inheritdoc}
1165
     */
1166 12057
    public function getUniqueConstraintDeclarationSQL($name, Index $index)
1167
    {
1168 12057
        if ($index->isPrimary()) {
1169
            throw new InvalidArgumentException(
1170
                'Cannot create primary key constraint declarations with getUniqueConstraintDeclarationSQL().'
1171
            );
1172
        }
1173
1174 12057
        if (! $index->isUnique()) {
1175
            throw new InvalidArgumentException(
1176
                'Can only create unique constraint declarations, no common index declarations with ' .
1177
                'getUniqueConstraintDeclarationSQL().'
1178
            );
1179
        }
1180
1181 12057
        return $this->getTableConstraintDeclarationSQL($index, $name);
1182
    }
1183
1184
    /**
1185
     * {@inheritdoc}
1186
     */
1187 12207
    public function getVarcharDefaultLength()
1188
    {
1189 12207
        return 1;
1190
    }
1191
1192
    /**
1193
     * {@inheritdoc}
1194
     */
1195 12579
    public function getVarcharMaxLength()
1196
    {
1197 12579
        return 32767;
1198
    }
1199
1200
    /**
1201
     * {@inheritdoc}
1202
     */
1203 12835
    public function hasNativeGuidType()
1204
    {
1205 12835
        return true;
1206
    }
1207
1208
    /**
1209
     * {@inheritdoc}
1210
     */
1211 11408
    public function prefersIdentityColumns()
1212
    {
1213 11408
        return true;
1214
    }
1215
1216
    /**
1217
     * {@inheritdoc}
1218
     */
1219 12579
    public function supportsCommentOnStatement()
1220
    {
1221 12579
        return true;
1222
    }
1223
1224
    /**
1225
     * {@inheritdoc}
1226
     */
1227 11383
    public function supportsIdentityColumns()
1228
    {
1229 11383
        return true;
1230
    }
1231
1232
    /**
1233
     * {@inheritdoc}
1234
     */
1235 12563
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
1236
    {
1237 12563
        $unsigned      = ! empty($columnDef['unsigned']) ? 'UNSIGNED ' : '';
1238 12563
        $autoincrement = ! empty($columnDef['autoincrement']) ? ' IDENTITY' : '';
1239
1240 12563
        return $unsigned . $columnDef['integer_type'] . $autoincrement;
1241
    }
1242
1243
    /**
1244
     * {@inheritdoc}
1245
     */
1246 12571
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
1247
    {
1248 12571
        $columnListSql = $this->getColumnDeclarationListSQL($columns);
1249 12571
        $indexSql      = [];
1250
1251 12571
        if (! empty($options['uniqueConstraints'])) {
1252
            foreach ((array) $options['uniqueConstraints'] as $name => $definition) {
1253
                $columnListSql .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
1254
            }
1255
        }
1256
1257 12571
        if (! empty($options['indexes'])) {
1258
            /** @var Index $index */
1259 12507
            foreach ((array) $options['indexes'] as $index) {
1260 12507
                $indexSql[] = $this->getCreateIndexSQL($index, $tableName);
1261
            }
1262
        }
1263
1264 12571
        if (! empty($options['primary'])) {
1265 12523
            $flags = '';
1266
1267 12523
            if (isset($options['primary_index']) && $options['primary_index']->hasFlag('clustered')) {
1268
                $flags = ' CLUSTERED ';
1269
            }
1270
1271 12523
            $columnListSql .= ', PRIMARY KEY' . $flags . ' (' . implode(', ', array_unique(array_values((array) $options['primary']))) . ')';
1272
        }
1273
1274 12571
        if (! empty($options['foreignKeys'])) {
1275 12466
            foreach ((array) $options['foreignKeys'] as $definition) {
1276 12466
                $columnListSql .= ', ' . $this->getForeignKeyDeclarationSQL($definition);
1277
            }
1278
        }
1279
1280 12571
        $query = 'CREATE TABLE ' . $tableName . ' (' . $columnListSql;
1281 12571
        $check = $this->getCheckDeclarationSQL($columns);
1282
1283 12571
        if (! empty($check)) {
1284 12433
            $query .= ', ' . $check;
1285
        }
1286
1287 12571
        $query .= ')';
1288
1289 12571
        return array_merge([$query], $indexSql);
1290
    }
1291
1292
    /**
1293
     * {@inheritdoc}
1294
     */
1295 11591
    protected function _getTransactionIsolationLevelSQL($level)
1296
    {
1297 16
        switch ($level) {
1298 11575
            case TransactionIsolationLevel::READ_UNCOMMITTED:
1299 11583
                return 0;
1300 11575
            case TransactionIsolationLevel::READ_COMMITTED:
1301 11583
                return 1;
1302 11575
            case TransactionIsolationLevel::REPEATABLE_READ:
1303 11583
                return 2;
1304 11575
            case TransactionIsolationLevel::SERIALIZABLE:
1305 11583
                return 3;
1306
            default:
1307 11558
                throw new InvalidArgumentException('Invalid isolation level:' . $level);
1308
        }
1309
    }
1310
1311
    /**
1312
     * {@inheritdoc}
1313
     */
1314 11573
    protected function doModifyLimitQuery($query, $limit, $offset)
1315
    {
1316 11573
        $limitOffsetClause = $this->getTopClauseSQL($limit, $offset);
1317
1318 11573
        if ($limitOffsetClause === '') {
1319 9433
            return $query;
1320
        }
1321
1322 11565
        if (! preg_match('/^\s*(SELECT\s+(DISTINCT\s+)?)(.*)/i', $query, $matches)) {
1323
            return $query;
1324
        }
1325
1326 11565
        return $matches[1] . $limitOffsetClause . ' ' . $matches[3];
1327
    }
1328
1329 11573
    private function getTopClauseSQL(?int $limit, ?int $offset) : string
1330
    {
1331 11573
        if ($offset > 0) {
1332 11491
            return sprintf('TOP %s START AT %d', $limit ?? 'ALL', $offset + 1);
1333
        }
1334
1335 11557
        return $limit === null ? '' : 'TOP ' . $limit;
1336
    }
1337
1338
    /**
1339
     * Return the INDEX query section dealing with non-standard
1340
     * SQL Anywhere options.
1341
     *
1342
     * @param Index $index Index definition
1343
     *
1344
     * @return string
1345
     */
1346 12539
    protected function getAdvancedIndexOptionsSQL(Index $index)
1347
    {
1348 12539
        $sql = '';
1349
1350 12539
        if (! $index->isPrimary() && $index->hasFlag('for_olap_workload')) {
1351 11783
            $sql .= ' FOR OLAP WORKLOAD';
1352
        }
1353
1354 12539
        return $sql;
1355
    }
1356
1357
    /**
1358
     * {@inheritdoc}
1359
     */
1360 11308
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
1361
    {
1362 11308
        return $fixed
1363 11308
            ? 'BINARY(' . ($length ?: $this->getBinaryDefaultLength()) . ')'
1364 11308
            : 'VARBINARY(' . ($length ?: $this->getBinaryDefaultLength()) . ')';
1365
    }
1366
1367
    /**
1368
     * Returns the SQL snippet for creating a table constraint.
1369
     *
1370
     * @param Constraint  $constraint The table constraint to create the SQL snippet for.
1371
     * @param string|null $name       The table constraint name to use if any.
1372
     *
1373
     * @return string
1374
     *
1375
     * @throws InvalidArgumentException If the given table constraint type is not supported by this method.
1376
     */
1377 12184
    protected function getTableConstraintDeclarationSQL(Constraint $constraint, $name = null)
1378
    {
1379 12184
        if ($constraint instanceof ForeignKeyConstraint) {
1380
            return $this->getForeignKeyDeclarationSQL($constraint);
1381
        }
1382
1383 12184
        if (! $constraint instanceof Index) {
1384 11808
            throw new InvalidArgumentException('Unsupported constraint type: ' . get_class($constraint));
1385
        }
1386
1387 12176
        if (! $constraint->isPrimary() && ! $constraint->isUnique()) {
1388 11833
            throw new InvalidArgumentException(
1389
                'Can only create primary, unique or foreign key constraint declarations, no common index declarations ' .
1390 11833
                'with getTableConstraintDeclarationSQL().'
1391
            );
1392
        }
1393
1394 12168
        $constraintColumns = $constraint->getQuotedColumns($this);
1395
1396 12168
        if (empty($constraintColumns)) {
1397 12091
            throw new InvalidArgumentException("Incomplete definition. 'columns' required.");
1398
        }
1399
1400 12152
        $sql   = '';
1401 12152
        $flags = '';
1402
1403 12152
        if (! empty($name)) {
1404 12140
            $name = new Identifier($name);
1405 12140
            $sql .= 'CONSTRAINT ' . $name->getQuotedName($this) . ' ';
1406
        }
1407
1408 12152
        if ($constraint->hasFlag('clustered')) {
1409 12124
            $flags = 'CLUSTERED ';
1410
        }
1411
1412 12152
        if ($constraint->isPrimary()) {
1413 12128
            return $sql . 'PRIMARY KEY ' . $flags . '(' . $this->getIndexFieldDeclarationListSQL($constraintColumns) . ')';
1414
        }
1415
1416 12057
        return $sql . 'UNIQUE ' . $flags . '(' . $this->getIndexFieldDeclarationListSQL($constraintColumns) . ')';
1417
    }
1418
1419
    /**
1420
     * {@inheritdoc}
1421
     */
1422 12541
    protected function getCreateIndexSQLFlags(Index $index)
1423
    {
1424 12541
        $type = '';
1425 12541
        if ($index->hasFlag('virtual')) {
1426 11783
            $type .= 'VIRTUAL ';
1427
        }
1428
1429 12541
        if ($index->isUnique()) {
1430 11799
            $type .= 'UNIQUE ';
1431
        }
1432
1433 12541
        if ($index->hasFlag('clustered')) {
1434 11783
            $type .= 'CLUSTERED ';
1435
        }
1436
1437 12541
        return $type;
1438
    }
1439
1440
    /**
1441
     * {@inheritdoc}
1442
     */
1443 9740
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
1444
    {
1445 9740
        return ['ALTER INDEX ' . $oldIndexName . ' ON ' . $tableName . ' RENAME TO ' . $index->getQuotedName($this)];
1446
    }
1447
1448
    /**
1449
     * {@inheritdoc}
1450
     */
1451 3254
    protected function getReservedKeywordsClass()
1452
    {
1453 3254
        return Keywords\SQLAnywhereKeywords::class;
1454
    }
1455
1456
    /**
1457
     * {@inheritdoc}
1458
     */
1459 12571
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
1460
    {
1461 12571
        return $fixed
1462 9483
            ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(' . $this->getVarcharDefaultLength() . ')')
1463 12571
            : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(' . $this->getVarcharDefaultLength() . ')');
1464
    }
1465
1466
    /**
1467
     * {@inheritdoc}
1468
     */
1469 11369
    protected function initializeDoctrineTypeMappings()
1470
    {
1471 11369
        $this->doctrineTypeMapping = [
1472
            'char' => 'string',
1473
            'long nvarchar' => 'text',
1474
            'long varchar' => 'text',
1475
            'nchar' => 'string',
1476
            'ntext' => 'text',
1477
            'nvarchar' => 'string',
1478
            'text' => 'text',
1479
            'uniqueidentifierstr' => 'guid',
1480
            'varchar' => 'string',
1481
            'xml' => 'text',
1482
            'bigint' => 'bigint',
1483
            'unsigned bigint' => 'bigint',
1484
            'bit' => 'boolean',
1485
            'decimal' => 'decimal',
1486
            'double' => 'float',
1487
            'float' => 'float',
1488
            'int' => 'integer',
1489
            'integer' => 'integer',
1490
            'unsigned int' => 'integer',
1491
            'numeric' => 'decimal',
1492
            'smallint' => 'smallint',
1493
            'unsigned smallint' => 'smallint',
1494
            'tinyint' => 'smallint',
1495
            'unsigned tinyint' => 'smallint',
1496
            'money' => 'decimal',
1497
            'smallmoney' => 'decimal',
1498
            'long varbit' => 'text',
1499
            'varbit' => 'string',
1500
            'date' => 'date',
1501
            'datetime' => 'datetime',
1502
            'smalldatetime' => 'datetime',
1503
            'time' => 'time',
1504
            'timestamp' => 'datetime',
1505
            'binary' => 'binary',
1506
            'image' => 'blob',
1507
            'long binary' => 'blob',
1508
            'uniqueidentifier' => 'guid',
1509
            'varbinary' => 'binary',
1510
        ];
1511 11369
    }
1512
}
1513