Completed
Push — develop ( fa42c1...0ef7d4 )
by Sergei
22:52
created

getTableConstraintDeclarationSQL()   B

Complexity

Conditions 9
Paths 12

Size

Total Lines 40
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 9.0086

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 40
ccs 20
cts 21
cp 0.9524
rs 8.0555
c 0
b 0
f 0
cc 9
nc 12
nop 2
crap 9.0086
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\Sequence;
14
use Doctrine\DBAL\Schema\Table;
15
use Doctrine\DBAL\Schema\TableDiff;
16
use Doctrine\DBAL\TransactionIsolationLevel;
17
use InvalidArgumentException;
18
use UnexpectedValueException;
19
use function array_merge;
20
use function array_unique;
21
use function array_values;
22
use function count;
23
use function explode;
24
use function func_get_args;
25
use function get_class;
26
use function implode;
27
use function is_string;
28
use function preg_replace;
29
use function sprintf;
30
use function strlen;
31
use function strpos;
32
use function strtoupper;
33
use function substr;
34
35
/**
36
 * The SQLAnywherePlatform provides the behavior, features and SQL dialect of the
37
 * SAP Sybase SQL Anywhere 12 database platform.
38
 */
39
class SQLAnywherePlatform extends AbstractPlatform
40
{
41
    public const FOREIGN_KEY_MATCH_SIMPLE        = 1;
42
    public const FOREIGN_KEY_MATCH_FULL          = 2;
43
    public const FOREIGN_KEY_MATCH_SIMPLE_UNIQUE = 129;
44
    public const FOREIGN_KEY_MATCH_FULL_UNIQUE   = 130;
45
46
    /**
47
     * {@inheritdoc}
48
     */
49 161
    public function appendLockHint($fromClause, $lockMode)
50
    {
51 161
        switch (true) {
52
            case $lockMode === LockMode::NONE:
53 23
                return $fromClause . ' WITH (NOLOCK)';
54
55 138
            case $lockMode === LockMode::PESSIMISTIC_READ:
56 23
                return $fromClause . ' WITH (UPDLOCK)';
57
58 115
            case $lockMode === LockMode::PESSIMISTIC_WRITE:
59 23
                return $fromClause . ' WITH (XLOCK)';
60
61
            default:
62 92
                return $fromClause;
63
        }
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     *
69
     * SQL Anywhere supports a maximum length of 128 bytes for identifiers.
70
     */
71 23
    public function fixSchemaElementName($schemaElementName)
72
    {
73 23
        $maxIdentifierLength = $this->getMaxIdentifierLength();
74
75 23
        if (strlen($schemaElementName) > $maxIdentifierLength) {
76 23
            return substr($schemaElementName, 0, $maxIdentifierLength);
77
        }
78
79 23
        return $schemaElementName;
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     */
85 161
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
86
    {
87 161
        $query = '';
88
89 161
        if ($foreignKey->hasOption('match')) {
90 23
            $query = ' MATCH ' . $this->getForeignKeyMatchClauseSQL($foreignKey->getOption('match'));
91
        }
92
93 161
        $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
94
95 161
        if ($foreignKey->hasOption('check_on_commit') && (bool) $foreignKey->getOption('check_on_commit')) {
96 23
            $query .= ' CHECK ON COMMIT';
97
        }
98
99 161
        if ($foreignKey->hasOption('clustered') && (bool) $foreignKey->getOption('clustered')) {
100 23
            $query .= ' CLUSTERED';
101
        }
102
103 161
        if ($foreignKey->hasOption('for_olap_workload') && (bool) $foreignKey->getOption('for_olap_workload')) {
104 23
            $query .= ' FOR OLAP WORKLOAD';
105
        }
106
107 161
        return $query;
108
    }
109
110
    /**
111
     * {@inheritdoc}
112
     */
113 345
    public function getAlterTableSQL(TableDiff $diff)
114
    {
115 345
        $sql          = [];
116 345
        $columnSql    = [];
117 345
        $commentsSQL  = [];
118 345
        $tableSql     = [];
119 345
        $alterClauses = [];
120
121
        /** @var Column $column */
122 345
        foreach ($diff->addedColumns as $column) {
123 92
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
124
                continue;
125
            }
126
127 92
            $alterClauses[] = $this->getAlterTableAddColumnClause($column);
128
129 92
            $comment = $this->getColumnComment($column);
130
131 92
            if ($comment === null || $comment === '') {
132 69
                continue;
133
            }
134
135 23
            $commentsSQL[] = $this->getCommentOnColumnSQL(
136 23
                $diff->getName($this)->getQuotedName($this),
137 23
                $column->getQuotedName($this),
138 23
                $comment
139
            );
140
        }
141
142
        /** @var Column $column */
143 345
        foreach ($diff->removedColumns as $column) {
144 69
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
145
                continue;
146
            }
147
148 69
            $alterClauses[] = $this->getAlterTableRemoveColumnClause($column);
149
        }
150
151
        /** @var ColumnDiff $columnDiff */
152 345
        foreach ($diff->changedColumns as $columnDiff) {
153 184
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
154
                continue;
155
            }
156
157 184
            $alterClause = $this->getAlterTableChangeColumnClause($columnDiff);
158
159 184
            if ($alterClause !== null) {
160 115
                $alterClauses[] = $alterClause;
161
            }
162
163 184
            if (! $columnDiff->hasChanged('comment')) {
164 115
                continue;
165
            }
166
167 69
            $column = $columnDiff->column;
168
169 69
            $commentsSQL[] = $this->getCommentOnColumnSQL(
170 69
                $diff->getName($this)->getQuotedName($this),
171 69
                $column->getQuotedName($this),
172 69
                $this->getColumnComment($column)
173
            );
174
        }
175
176 345
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
177 92
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
178
                continue;
179
            }
180
181 92
            $sql[] = $this->getAlterTableClause($diff->getName($this)) . ' ' .
182 92
                $this->getAlterTableRenameColumnClause($oldColumnName, $column);
183
        }
184
185 345
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
186 345
            if (! empty($alterClauses)) {
187 138
                $sql[] = $this->getAlterTableClause($diff->getName($this)) . ' ' . implode(', ', $alterClauses);
188
            }
189
190 345
            $sql = array_merge($sql, $commentsSQL);
191
192 345
            if ($diff->newName !== false) {
193 46
                $sql[] = $this->getAlterTableClause($diff->getName($this)) . ' ' .
194 46
                    $this->getAlterTableRenameTableClause($diff->getNewName());
0 ignored issues
show
Bug introduced by
It seems like $diff->getNewName() can also be of type string; however, parameter $newTableName of Doctrine\DBAL\Platforms\...ableRenameTableClause() does only seem to accept Doctrine\DBAL\Schema\Identifier, 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

194
                    $this->getAlterTableRenameTableClause(/** @scrutinizer ignore-type */ $diff->getNewName());
Loading history...
195
            }
196
197 345
            $sql = array_merge(
198 345
                $this->getPreAlterTableIndexForeignKeySQL($diff),
199 345
                $sql,
200 345
                $this->getPostAlterTableIndexForeignKeySQL($diff)
201
            );
202
        }
203
204 345
        return array_merge($sql, $tableSql, $columnSql);
205
    }
206
207
    /**
208
     * Returns the SQL clause for creating a column in a table alteration.
209
     *
210
     * @param Column $column The column to add.
211
     *
212
     * @return string
213
     */
214 92
    protected function getAlterTableAddColumnClause(Column $column)
215
    {
216 92
        return 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
217
    }
218
219
    /**
220
     * Returns the SQL clause for altering a table.
221
     *
222
     * @param Identifier $tableName The quoted name of the table to alter.
223
     *
224
     * @return string
225
     */
226 184
    protected function getAlterTableClause(Identifier $tableName)
227
    {
228 184
        return 'ALTER TABLE ' . $tableName->getQuotedName($this);
229
    }
230
231
    /**
232
     * Returns the SQL clause for dropping a column in a table alteration.
233
     *
234
     * @param Column $column The column to drop.
235
     *
236
     * @return string
237
     */
238 69
    protected function getAlterTableRemoveColumnClause(Column $column)
239
    {
240 69
        return 'DROP ' . $column->getQuotedName($this);
241
    }
242
243
    /**
244
     * Returns the SQL clause for renaming a column in a table alteration.
245
     *
246
     * @param string $oldColumnName The quoted name of the column to rename.
247
     * @param Column $column        The column to rename to.
248
     *
249
     * @return string
250
     */
251 92
    protected function getAlterTableRenameColumnClause($oldColumnName, Column $column)
252
    {
253 92
        $oldColumnName = new Identifier($oldColumnName);
254
255 92
        return 'RENAME ' . $oldColumnName->getQuotedName($this) . ' TO ' . $column->getQuotedName($this);
256
    }
257
258
    /**
259
     * Returns the SQL clause for renaming a table in a table alteration.
260
     *
261
     * @param Identifier $newTableName The quoted name of the table to rename to.
262
     *
263
     * @return string
264
     */
265 46
    protected function getAlterTableRenameTableClause(Identifier $newTableName)
266
    {
267 46
        return 'RENAME ' . $newTableName->getQuotedName($this);
268
    }
269
270
    /**
271
     * Returns the SQL clause for altering a column in a table alteration.
272
     *
273
     * This method returns null in case that only the column comment has changed.
274
     * Changes in column comments have to be handled differently.
275
     *
276
     * @param ColumnDiff $columnDiff The diff of the column to alter.
277
     *
278
     * @return string|null
279
     */
280 184
    protected function getAlterTableChangeColumnClause(ColumnDiff $columnDiff)
281
    {
282 184
        $column = $columnDiff->column;
283
284
        // Do not return alter clause if only comment has changed.
285 184
        if (! ($columnDiff->hasChanged('comment') && count($columnDiff->changedProperties) === 1)) {
286
            $columnAlterationClause = 'ALTER ' .
287 115
                $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
288
289 115
            if ($columnDiff->hasChanged('default') && $column->getDefault() === null) {
290
                $columnAlterationClause .= ', ALTER ' . $column->getQuotedName($this) . ' DROP DEFAULT';
291
            }
292
293 115
            return $columnAlterationClause;
294
        }
295
296 69
        return null;
297
    }
298
299
    /**
300
     * {@inheritdoc}
301
     */
302 23
    public function getBigIntTypeDeclarationSQL(array $columnDef)
303
    {
304 23
        $columnDef['integer_type'] = 'BIGINT';
305
306 23
        return $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
307
    }
308
309
    /**
310
     * {@inheritdoc}
311
     */
312 46
    public function getBinaryDefaultLength()
313
    {
314 46
        return 1;
315
    }
316
317
    /**
318
     * {@inheritdoc}
319
     */
320 23
    public function getBinaryMaxLength()
321
    {
322 23
        return 32767;
323
    }
324
325
    /**
326
     * {@inheritdoc}
327
     */
328 23
    public function getBlobTypeDeclarationSQL(array $field)
329
    {
330 23
        return 'LONG BINARY';
331
    }
332
333
    /**
334
     * {@inheritdoc}
335
     *
336
     * BIT type columns require an explicit NULL declaration
337
     * in SQL Anywhere if they shall be nullable.
338
     * Otherwise by just omitting the NOT NULL clause,
339
     * SQL Anywhere will declare them NOT NULL nonetheless.
340
     */
341 46
    public function getBooleanTypeDeclarationSQL(array $columnDef)
342
    {
343 46
        $nullClause = isset($columnDef['notnull']) && (bool) $columnDef['notnull'] === false ? ' NULL' : '';
344
345 46
        return 'BIT' . $nullClause;
346
    }
347
348
    /**
349
     * {@inheritdoc}
350
     */
351 69
    public function getClobTypeDeclarationSQL(array $field)
352
    {
353 69
        return 'TEXT';
354
    }
355
356
    /**
357
     * {@inheritdoc}
358
     */
359 184
    public function getCommentOnColumnSQL($tableName, $columnName, $comment)
360
    {
361 184
        $tableName  = new Identifier($tableName);
362 184
        $columnName = new Identifier($columnName);
363 184
        $comment    = $comment === null ? 'NULL' : $this->quoteStringLiteral($comment);
364
365 184
        return sprintf(
366 184
            'COMMENT ON COLUMN %s.%s IS %s',
367 184
            $tableName->getQuotedName($this),
368 184
            $columnName->getQuotedName($this),
369 184
            $comment
370
        );
371
    }
372
373
    /**
374
     * {@inheritdoc}
375
     */
376 23
    public function getConcatExpression()
377
    {
378 23
        return 'STRING(' . implode(', ', (array) func_get_args()) . ')';
379
    }
380
381
    /**
382
     * {@inheritdoc}
383
     */
384 69
    public function getCreateConstraintSQL(Constraint $constraint, $table)
385
    {
386 69
        if ($constraint instanceof ForeignKeyConstraint) {
387 23
            return $this->getCreateForeignKeySQL($constraint, $table);
388
        }
389
390 69
        if ($table instanceof Table) {
391 23
            $table = $table->getQuotedName($this);
392
        }
393
394 69
        return 'ALTER TABLE ' . $table .
395 69
               ' ADD ' . $this->getTableConstraintDeclarationSQL($constraint, $constraint->getQuotedName($this));
396
    }
397
398
    /**
399
     * {@inheritdoc}
400
     */
401 23
    public function getCreateDatabaseSQL($database)
402
    {
403 23
        $database = new Identifier($database);
404
405 23
        return "CREATE DATABASE '" . $database->getName() . "'";
406
    }
407
408
    /**
409
     * {@inheritdoc}
410
     *
411
     * Appends SQL Anywhere specific flags if given.
412
     */
413 207
    public function getCreateIndexSQL(Index $index, $table)
414
    {
415 207
        return parent::getCreateIndexSQL($index, $table) . $this->getAdvancedIndexOptionsSQL($index);
416
    }
417
418
    /**
419
     * {@inheritdoc}
420
     */
421 46
    public function getCreatePrimaryKeySQL(Index $index, $table)
422
    {
423 46
        if ($table instanceof Table) {
424 23
            $table = $table->getQuotedName($this);
425
        }
426
427 46
        return 'ALTER TABLE ' . $table . ' ADD ' . $this->getPrimaryKeyDeclarationSQL($index);
428
    }
429
430
    /**
431
     * {@inheritdoc}
432
     */
433 23
    public function getCreateTemporaryTableSnippetSQL()
434
    {
435 23
        return 'CREATE ' . $this->getTemporaryTableSQL() . ' TABLE';
436
    }
437
438
    /**
439
     * {@inheritdoc}
440
     */
441 23
    public function getCreateViewSQL($name, $sql)
442
    {
443 23
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
444
    }
445
446
    /**
447
     * {@inheritdoc}
448
     */
449 46
    public function getCurrentDateSQL()
450
    {
451 46
        return 'CURRENT DATE';
452
    }
453
454
    /**
455
     * {@inheritdoc}
456
     */
457 23
    public function getCurrentTimeSQL()
458
    {
459 23
        return 'CURRENT TIME';
460
    }
461
462
    /**
463
     * {@inheritdoc}
464
     */
465 46
    public function getCurrentTimestampSQL()
466
    {
467 46
        return 'CURRENT TIMESTAMP';
468
    }
469
470
    /**
471
     * {@inheritdoc}
472
     */
473 23
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
474
    {
475 23
        $factorClause = '';
476
477 23
        if ($operator === '-') {
478 23
            $factorClause = '-1 * ';
479
        }
480
481 23
        return 'DATEADD(' . $unit . ', ' . $factorClause . $interval . ', ' . $date . ')';
482
    }
483
484
    /**
485
     * {@inheritdoc}
486
     */
487 23
    public function getDateDiffExpression($date1, $date2)
488
    {
489 23
        return 'DATEDIFF(day, ' . $date2 . ', ' . $date1 . ')';
490
    }
491
492
    /**
493
     * {@inheritdoc}
494
     */
495 23
    public function getDateTimeFormatString()
496
    {
497 23
        return 'Y-m-d H:i:s.u';
498
    }
499
500
    /**
501
     * {@inheritdoc}
502
     */
503 23
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
504
    {
505 23
        return 'DATETIME';
506
    }
507
508
    /**
509
     * {@inheritdoc}
510
     */
511 23
    public function getDateTimeTzFormatString()
512
    {
513 23
        return 'Y-m-d H:i:s.uP';
514
    }
515
516
    /**
517
     * {@inheritdoc}
518
     */
519 23
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
520
    {
521 23
        return 'DATE';
522
    }
523
524
    /**
525
     * {@inheritdoc}
526
     */
527 23
    public function getDefaultTransactionIsolationLevel()
528
    {
529 23
        return TransactionIsolationLevel::READ_UNCOMMITTED;
530
    }
531
532
    /**
533
     * {@inheritdoc}
534
     */
535 23
    public function getDropDatabaseSQL($database)
536
    {
537 23
        $database = new Identifier($database);
538
539 23
        return "DROP DATABASE '" . $database->getName() . "'";
540
    }
541
542
    /**
543
     * {@inheritdoc}
544
     */
545 69
    public function getDropIndexSQL($index, $table = null)
546
    {
547 69
        if ($index instanceof Index) {
548 23
            $index = $index->getQuotedName($this);
549
        }
550
551 69
        if (! is_string($index)) {
552 23
            throw new InvalidArgumentException(
553 23
                'SQLAnywherePlatform::getDropIndexSQL() expects $index parameter to be string or ' . Index::class . '.'
554
            );
555
        }
556
557 46
        if (! isset($table)) {
558 23
            return 'DROP INDEX ' . $index;
559
        }
560
561 46
        if ($table instanceof Table) {
562 23
            $table = $table->getQuotedName($this);
563
        }
564
565 46
        if (! is_string($table)) {
566 23
            throw new InvalidArgumentException(
567 23
                'SQLAnywherePlatform::getDropIndexSQL() expects $table parameter to be string or ' . Index::class . '.'
568
            );
569
        }
570
571 23
        return 'DROP INDEX ' . $table . '.' . $index;
572
    }
573
574
    /**
575
     * {@inheritdoc}
576
     */
577 23
    public function getDropViewSQL($name)
578
    {
579 23
        return 'DROP VIEW ' . $name;
580
    }
581
582
    /**
583
     * {@inheritdoc}
584
     */
585 230
    public function getForeignKeyBaseDeclarationSQL(ForeignKeyConstraint $foreignKey)
586
    {
587 230
        $sql              = '';
588 230
        $foreignKeyName   = $foreignKey->getName();
589 230
        $localColumns     = $foreignKey->getQuotedLocalColumns($this);
590 230
        $foreignColumns   = $foreignKey->getQuotedForeignColumns($this);
591 230
        $foreignTableName = $foreignKey->getQuotedForeignTableName($this);
592
593 230
        if (! empty($foreignKeyName)) {
594 138
            $sql .= 'CONSTRAINT ' . $foreignKey->getQuotedName($this) . ' ';
595
        }
596
597 230
        if (empty($localColumns)) {
598 23
            throw new InvalidArgumentException("Incomplete definition. 'local' required.");
599
        }
600
601 207
        if (empty($foreignColumns)) {
602 23
            throw new InvalidArgumentException("Incomplete definition. 'foreign' required.");
603
        }
604
605 184
        if (empty($foreignTableName)) {
606 23
            throw new InvalidArgumentException("Incomplete definition. 'foreignTable' required.");
607
        }
608
609 161
        if ($foreignKey->hasOption('notnull') && (bool) $foreignKey->getOption('notnull')) {
610 23
            $sql .= 'NOT NULL ';
611
        }
612
613
        return $sql .
614 161
            'FOREIGN KEY (' . $this->getIndexFieldDeclarationListSQL($localColumns) . ') ' .
615 161
            'REFERENCES ' . $foreignKey->getQuotedForeignTableName($this) .
616 161
            ' (' . $this->getIndexFieldDeclarationListSQL($foreignColumns) . ')';
617
    }
618
619
    /**
620
     * Returns foreign key MATCH clause for given type.
621
     *
622
     * @param int $type The foreign key match type
623
     *
624
     * @return string
625
     *
626
     * @throws InvalidArgumentException If unknown match type given.
627
     */
628 69
    public function getForeignKeyMatchClauseSQL($type)
629
    {
630 69
        switch ((int) $type) {
631 69
            case self::FOREIGN_KEY_MATCH_SIMPLE:
632 23
                return 'SIMPLE';
633
                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...
634 69
            case self::FOREIGN_KEY_MATCH_FULL:
635 23
                return 'FULL';
636
                break;
637 69
            case self::FOREIGN_KEY_MATCH_SIMPLE_UNIQUE:
638 46
                return 'UNIQUE SIMPLE';
639
                break;
640 46
            case self::FOREIGN_KEY_MATCH_FULL_UNIQUE:
641 23
                return 'UNIQUE FULL';
642
            default:
643 23
                throw new InvalidArgumentException('Invalid foreign key match type: ' . $type);
644
        }
645
    }
646
647
    /**
648
     * {@inheritdoc}
649
     */
650 184
    public function getForeignKeyReferentialActionSQL($action)
651
    {
652
        // NO ACTION is not supported, therefore falling back to RESTRICT.
653 184
        if (strtoupper($action) === 'NO ACTION') {
654 23
            return 'RESTRICT';
655
        }
656
657 161
        return parent::getForeignKeyReferentialActionSQL($action);
658
    }
659
660
    /**
661
     * {@inheritdoc}
662
     */
663 23
    public function getForUpdateSQL()
664
    {
665 23
        return '';
666
    }
667
668
    /**
669
     * {@inheritdoc}
670
     */
671 46
    public function getGuidTypeDeclarationSQL(array $field)
672
    {
673 46
        return 'UNIQUEIDENTIFIER';
674
    }
675
676
    /**
677
     * {@inheritdoc}
678
     */
679 46
    public function getIndexDeclarationSQL($name, Index $index)
680
    {
681
        // Index declaration in statements like CREATE TABLE is not supported.
682 46
        throw DBALException::notSupported(__METHOD__);
683
    }
684
685
    /**
686
     * {@inheritdoc}
687
     */
688 253
    public function getIntegerTypeDeclarationSQL(array $columnDef)
689
    {
690 253
        $columnDef['integer_type'] = 'INT';
691
692 253
        return $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
693
    }
694
695
    /**
696
     * {@inheritdoc}
697
     */
698
    public function getListDatabasesSQL()
699
    {
700
        return 'SELECT db_name(number) AS name FROM sa_db_list()';
701
    }
702
703
    /**
704
     * {@inheritdoc}
705
     */
706 23
    public function getListTableColumnsSQL($table, $database = null)
707
    {
708 23
        $user = 'USER_NAME()';
709
710 23
        if (strpos($table, '.') !== false) {
711 23
            [$user, $table] = explode('.', $table);
712 23
            $user           = $this->quoteStringLiteral($user);
713
        }
714
715 23
        return sprintf(
716
            <<<'SQL'
717 23
SELECT    col.column_name,
718
          COALESCE(def.user_type_name, def.domain_name) AS 'type',
719
          def.declared_width AS 'length',
720
          def.scale,
721
          CHARINDEX('unsigned', def.domain_name) AS 'unsigned',
722
          IF col.nulls = 'Y' THEN 0 ELSE 1 ENDIF AS 'notnull',
723
          col."default",
724
          def.is_autoincrement AS 'autoincrement',
725
          rem.remarks AS 'comment'
726
FROM      sa_describe_query('SELECT * FROM "%s"') AS def
727
JOIN      SYS.SYSTABCOL AS col
728
ON        col.table_id = def.base_table_id AND col.column_id = def.base_column_id
729
LEFT JOIN SYS.SYSREMARK AS rem
730
ON        col.object_id = rem.object_id
731
WHERE     def.base_owner_name = %s
732
ORDER BY  def.base_column_id ASC
733
SQL
734
            ,
735 23
            $table,
736 23
            $user
737
        );
738
    }
739
740
    /**
741
     * {@inheritdoc}
742
     *
743
     * @todo Where is this used? Which information should be retrieved?
744
     */
745 46
    public function getListTableConstraintsSQL($table)
746
    {
747 46
        $user = '';
748
749 46
        if (strpos($table, '.') !== false) {
750 23
            [$user, $table] = explode('.', $table);
751 23
            $user           = $this->quoteStringLiteral($user);
752 23
            $table          = $this->quoteStringLiteral($table);
753
        } else {
754 23
            $table = $this->quoteStringLiteral($table);
755
        }
756
757 46
        return sprintf(
758
            <<<'SQL'
759 46
SELECT con.*
760
FROM   SYS.SYSCONSTRAINT AS con
761
JOIN   SYS.SYSTAB AS tab ON con.table_object_id = tab.object_id
762
WHERE  tab.table_name = %s
763
AND    tab.creator = USER_ID(%s)
764
SQL
765
            ,
766 46
            $table,
767 46
            $user
768
        );
769
    }
770
771
    /**
772
     * {@inheritdoc}
773
     */
774 46
    public function getListTableForeignKeysSQL($table)
775
    {
776 46
        $user = '';
777
778 46
        if (strpos($table, '.') !== false) {
779 23
            [$user, $table] = explode('.', $table);
780 23
            $user           = $this->quoteStringLiteral($user);
781 23
            $table          = $this->quoteStringLiteral($table);
782
        } else {
783 23
            $table = $this->quoteStringLiteral($table);
784
        }
785
786 46
        return sprintf(
787
            <<<'SQL'
788 46
SELECT    fcol.column_name AS local_column,
789
          ptbl.table_name AS foreign_table,
790
          pcol.column_name AS foreign_column,
791
          idx.index_name,
792
          IF fk.nulls = 'N'
793
              THEN 1
794
              ELSE NULL
795
          ENDIF AS notnull,
796
          CASE ut.referential_action
797
              WHEN 'C' THEN 'CASCADE'
798
              WHEN 'D' THEN 'SET DEFAULT'
799
              WHEN 'N' THEN 'SET NULL'
800
              WHEN 'R' THEN 'RESTRICT'
801
              ELSE NULL
802
          END AS  on_update,
803
          CASE dt.referential_action
804
              WHEN 'C' THEN 'CASCADE'
805
              WHEN 'D' THEN 'SET DEFAULT'
806
              WHEN 'N' THEN 'SET NULL'
807
              WHEN 'R' THEN 'RESTRICT'
808
              ELSE NULL
809
          END AS on_delete,
810
          IF fk.check_on_commit = 'Y'
811
              THEN 1
812
              ELSE NULL
813
          ENDIF AS check_on_commit, -- check_on_commit flag
814
          IF ftbl.clustered_index_id = idx.index_id
815
              THEN 1
816
              ELSE NULL
817
          ENDIF AS 'clustered', -- clustered flag
818
          IF fk.match_type = 0
819
              THEN NULL
820
              ELSE fk.match_type
821
          ENDIF AS 'match', -- match option
822
          IF pidx.max_key_distance = 1
823
              THEN 1
824
              ELSE NULL
825
          ENDIF AS for_olap_workload -- for_olap_workload flag
826
FROM      SYS.SYSFKEY AS fk
827
JOIN      SYS.SYSIDX AS idx
828
ON        fk.foreign_table_id = idx.table_id
829
AND       fk.foreign_index_id = idx.index_id
830
JOIN      SYS.SYSPHYSIDX pidx
831
ON        idx.table_id = pidx.table_id
832
AND       idx.phys_index_id = pidx.phys_index_id
833
JOIN      SYS.SYSTAB AS ptbl
834
ON        fk.primary_table_id = ptbl.table_id
835
JOIN      SYS.SYSTAB AS ftbl
836
ON        fk.foreign_table_id = ftbl.table_id
837
JOIN      SYS.SYSIDXCOL AS idxcol
838
ON        idx.table_id = idxcol.table_id
839
AND       idx.index_id = idxcol.index_id
840
JOIN      SYS.SYSTABCOL AS pcol
841
ON        ptbl.table_id = pcol.table_id
842
AND       idxcol.primary_column_id = pcol.column_id
843
JOIN      SYS.SYSTABCOL AS fcol
844
ON        ftbl.table_id = fcol.table_id
845
AND       idxcol.column_id = fcol.column_id
846
LEFT JOIN SYS.SYSTRIGGER ut
847
ON        fk.foreign_table_id = ut.foreign_table_id
848
AND       fk.foreign_index_id = ut.foreign_key_id
849
AND       ut.event = 'C'
850
LEFT JOIN SYS.SYSTRIGGER dt
851
ON        fk.foreign_table_id = dt.foreign_table_id
852
AND       fk.foreign_index_id = dt.foreign_key_id
853
AND       dt.event = 'D'
854
WHERE     ftbl.table_name = %s
855
AND       ftbl.creator = USER_ID(%s)
856
ORDER BY  fk.foreign_index_id ASC, idxcol.sequence ASC
857
SQL
858
            ,
859 46
            $table,
860 46
            $user
861
        );
862
    }
863
864
    /**
865
     * {@inheritdoc}
866
     */
867 46
    public function getListTableIndexesSQL($table, $currentDatabase = null)
868
    {
869 46
        $user = '';
870
871 46
        if (strpos($table, '.') !== false) {
872 23
            [$user, $table] = explode('.', $table);
873 23
            $user           = $this->quoteStringLiteral($user);
874 23
            $table          = $this->quoteStringLiteral($table);
875
        } else {
876 23
            $table = $this->quoteStringLiteral($table);
877
        }
878
879 46
        return sprintf(
880
            <<<'SQL'
881 46
SELECT   idx.index_name AS key_name,
882
         IF idx.index_category = 1
883
             THEN 1
884
             ELSE 0
885
         ENDIF AS 'primary',
886
         col.column_name,
887
         IF idx."unique" IN(1, 2, 5)
888
             THEN 0
889
             ELSE 1
890
         ENDIF AS non_unique,
891
         IF tbl.clustered_index_id = idx.index_id
892
             THEN 1
893
             ELSE NULL
894
         ENDIF AS 'clustered', -- clustered flag
895
         IF idx."unique" = 5
896
             THEN 1
897
             ELSE NULL
898
         ENDIF AS with_nulls_not_distinct, -- with_nulls_not_distinct flag
899
         IF pidx.max_key_distance = 1
900
              THEN 1
901
              ELSE NULL
902
          ENDIF AS for_olap_workload -- for_olap_workload flag
903
FROM     SYS.SYSIDX AS idx
904
JOIN     SYS.SYSPHYSIDX pidx
905
ON       idx.table_id = pidx.table_id
906
AND      idx.phys_index_id = pidx.phys_index_id
907
JOIN     SYS.SYSIDXCOL AS idxcol
908
ON       idx.table_id = idxcol.table_id AND idx.index_id = idxcol.index_id
909
JOIN     SYS.SYSTABCOL AS col
910
ON       idxcol.table_id = col.table_id AND idxcol.column_id = col.column_id
911
JOIN     SYS.SYSTAB AS tbl
912
ON       idx.table_id = tbl.table_id
913
WHERE    tbl.table_name = %s
914
AND      tbl.creator = USER_ID(%s)
915
AND      idx.index_category != 2 -- exclude indexes implicitly created by foreign key constraints
916
ORDER BY idx.index_id ASC, idxcol.sequence ASC
917
SQL
918
            ,
919 46
            $table,
920 46
            $user
921
        );
922
    }
923
924
    /**
925
     * {@inheritdoc}
926
     */
927
    public function getListTablesSQL()
928
    {
929
        return "SELECT   tbl.table_name
930
                FROM     SYS.SYSTAB AS tbl
931
                JOIN     SYS.SYSUSER AS usr ON tbl.creator = usr.user_id
932
                JOIN     dbo.SYSOBJECTS AS obj ON tbl.object_id = obj.id
933
                WHERE    tbl.table_type IN(1, 3) -- 'BASE', 'GBL TEMP'
934
                AND      usr.user_name NOT IN('SYS', 'dbo', 'rs_systabgroup') -- exclude system users
935
                AND      obj.type = 'U' -- user created tables only
936
                ORDER BY tbl.table_name ASC";
937
    }
938
939
    /**
940
     * {@inheritdoc}
941
     *
942
     * @todo Where is this used? Which information should be retrieved?
943
     */
944
    public function getListUsersSQL()
945
    {
946
        return 'SELECT * FROM SYS.SYSUSER ORDER BY user_name ASC';
947
    }
948
949
    /**
950
     * {@inheritdoc}
951
     */
952
    public function getListViewsSQL($database)
953
    {
954
        return "SELECT   tbl.table_name, v.view_def
955
                FROM     SYS.SYSVIEW v
956
                JOIN     SYS.SYSTAB tbl ON v.view_object_id = tbl.object_id
957
                JOIN     SYS.SYSUSER usr ON tbl.creator = usr.user_id
958
                JOIN     dbo.SYSOBJECTS obj ON tbl.object_id = obj.id
959
                WHERE    usr.user_name NOT IN('SYS', 'dbo', 'rs_systabgroup') -- exclude system users
960
                ORDER BY tbl.table_name ASC";
961
    }
962
963
    /**
964
     * {@inheritdoc}
965
     */
966 23
    public function getLocateExpression($str, $substr, $startPos = false)
967
    {
968 23
        if ($startPos === false) {
969 23
            return 'LOCATE(' . $str . ', ' . $substr . ')';
970
        }
971
972 23
        return 'LOCATE(' . $str . ', ' . $substr . ', ' . $startPos . ')';
973
    }
974
975
    /**
976
     * {@inheritdoc}
977
     */
978 46
    public function getMaxIdentifierLength()
979
    {
980 46
        return 128;
981
    }
982
983
    /**
984
     * {@inheritdoc}
985
     */
986 23
    public function getMd5Expression($column)
987
    {
988 23
        return 'HASH(' . $column . ", 'MD5')";
989
    }
990
991
    /**
992
     * {@inheritdoc}
993
     */
994
    public function getRegexpExpression()
995
    {
996
        return 'REGEXP';
997
    }
998
999
    /**
1000
     * {@inheritdoc}
1001
     */
1002 69
    public function getName()
1003
    {
1004 69
        return 'sqlanywhere';
1005
    }
1006
1007
    /**
1008
     * Obtain DBMS specific SQL code portion needed to set a primary key
1009
     * declaration to be used in statements like ALTER TABLE.
1010
     *
1011
     * @param Index  $index Index definition
1012
     * @param string $name  Name of the primary key
1013
     *
1014
     * @return string DBMS specific SQL code portion needed to set a primary key
1015
     *
1016
     * @throws InvalidArgumentException If the given index is not a primary key.
1017
     */
1018 92
    public function getPrimaryKeyDeclarationSQL(Index $index, $name = null)
1019
    {
1020 92
        if (! $index->isPrimary()) {
1021
            throw new InvalidArgumentException(
1022
                'Can only create primary key declarations with getPrimaryKeyDeclarationSQL()'
1023
            );
1024
        }
1025
1026 92
        return $this->getTableConstraintDeclarationSQL($index, $name);
1027
    }
1028
1029
    /**
1030
     * {@inheritdoc}
1031
     */
1032 46
    public function getSetTransactionIsolationSQL($level)
1033
    {
1034 46
        return 'SET TEMPORARY OPTION isolation_level = ' . $this->_getTransactionIsolationLevelSQL($level);
1035
    }
1036
1037
    /**
1038
     * {@inheritdoc}
1039
     */
1040 23
    public function getSmallIntTypeDeclarationSQL(array $columnDef)
1041
    {
1042 23
        $columnDef['integer_type'] = 'SMALLINT';
1043
1044 23
        return $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
1045
    }
1046
1047
    /**
1048
     * Returns the SQL statement for starting an existing database.
1049
     *
1050
     * In SQL Anywhere you can start and stop databases on a
1051
     * database server instance.
1052
     * This is a required statement after having created a new database
1053
     * as it has to be explicitly started to be usable.
1054
     * SQL Anywhere does not automatically start a database after creation!
1055
     *
1056
     * @param string $database Name of the database to start.
1057
     *
1058
     * @return string
1059
     */
1060 23
    public function getStartDatabaseSQL($database)
1061
    {
1062 23
        $database = new Identifier($database);
1063
1064 23
        return "START DATABASE '" . $database->getName() . "' AUTOSTOP OFF";
1065
    }
1066
1067
    /**
1068
     * Returns the SQL statement for stopping a running database.
1069
     *
1070
     * In SQL Anywhere you can start and stop databases on a
1071
     * database server instance.
1072
     * This is a required statement before dropping an existing database
1073
     * as it has to be explicitly stopped before it can be dropped.
1074
     *
1075
     * @param string $database Name of the database to stop.
1076
     *
1077
     * @return string
1078
     */
1079 23
    public function getStopDatabaseSQL($database)
1080
    {
1081 23
        $database = new Identifier($database);
1082
1083 23
        return 'STOP DATABASE "' . $database->getName() . '" UNCONDITIONALLY';
1084
    }
1085
1086
    /**
1087
     * {@inheritdoc}
1088
     */
1089 23
    public function getSubstringExpression($value, $from, $length = null)
1090
    {
1091 23
        if ($length === null) {
1092 23
            return 'SUBSTRING(' . $value . ', ' . $from . ')';
1093
        }
1094
1095 23
        return 'SUBSTRING(' . $value . ', ' . $from . ', ' . $length . ')';
1096
    }
1097
1098
    /**
1099
     * {@inheritdoc}
1100
     */
1101 46
    public function getTemporaryTableSQL()
1102
    {
1103 46
        return 'GLOBAL TEMPORARY';
1104
    }
1105
1106
    /**
1107
     * {@inheritdoc}
1108
     */
1109 23
    public function getTimeFormatString()
1110
    {
1111 23
        return 'H:i:s.u';
1112
    }
1113
1114
    /**
1115
     * {@inheritdoc}
1116
     */
1117 23
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
1118
    {
1119 23
        return 'TIME';
1120
    }
1121
1122
    /**
1123
     * {@inheritdoc}
1124
     */
1125 23
    public function getTrimExpression($str, $pos = TrimMode::UNSPECIFIED, $char = false)
1126
    {
1127 23
        if (! $char) {
1128 23
            switch ($pos) {
1129
                case TrimMode::LEADING:
1130 23
                    return $this->getLtrimExpression($str);
1131
                case TrimMode::TRAILING:
1132 23
                    return $this->getRtrimExpression($str);
1133
                default:
1134 23
                    return 'TRIM(' . $str . ')';
1135
            }
1136
        }
1137
1138 23
        $pattern = "'%[^' + " . $char . " + ']%'";
1139
1140 23
        switch ($pos) {
1141
            case TrimMode::LEADING:
1142 23
                return 'SUBSTR(' . $str . ', PATINDEX(' . $pattern . ', ' . $str . '))';
1143
            case TrimMode::TRAILING:
1144 23
                return 'REVERSE(SUBSTR(REVERSE(' . $str . '), PATINDEX(' . $pattern . ', REVERSE(' . $str . '))))';
1145
            default:
1146 23
                return 'REVERSE(SUBSTR(REVERSE(SUBSTR(' . $str . ', PATINDEX(' . $pattern . ', ' . $str . '))), ' .
1147 23
                    'PATINDEX(' . $pattern . ', REVERSE(SUBSTR(' . $str . ', PATINDEX(' . $pattern . ', ' . $str . '))))))';
1148
        }
1149
    }
1150
1151
    /**
1152
     * {@inheritdoc}
1153
     */
1154 46
    public function getTruncateTableSQL($tableName, $cascade = false)
1155
    {
1156 46
        $tableIdentifier = new Identifier($tableName);
1157
1158 46
        return 'TRUNCATE TABLE ' . $tableIdentifier->getQuotedName($this);
1159
    }
1160
1161
    /**
1162
     * {@inheritdoc}
1163
     */
1164 23
    public function getCreateSequenceSQL(Sequence $sequence)
1165
    {
1166 23
        return 'CREATE SEQUENCE ' . $sequence->getQuotedName($this) .
1167 23
            ' INCREMENT BY ' . $sequence->getAllocationSize() .
1168 23
            ' START WITH ' . $sequence->getInitialValue() .
1169 23
            ' MINVALUE ' . $sequence->getInitialValue();
1170
    }
1171
1172
    /**
1173
     * {@inheritdoc}
1174
     */
1175 23
    public function getAlterSequenceSQL(Sequence $sequence)
1176
    {
1177 23
        return 'ALTER SEQUENCE ' . $sequence->getQuotedName($this) .
1178 23
            ' INCREMENT BY ' . $sequence->getAllocationSize();
1179
    }
1180
1181
    /**
1182
     * {@inheritdoc}
1183
     */
1184 23
    public function getDropSequenceSQL($sequence)
1185
    {
1186 23
        if ($sequence instanceof Sequence) {
1187 23
            $sequence = $sequence->getQuotedName($this);
1188
        }
1189
1190 23
        return 'DROP SEQUENCE ' . $sequence;
1191
    }
1192
1193
    /**
1194
     * {@inheritdoc}
1195
     */
1196 23
    public function getListSequencesSQL($database)
1197
    {
1198 23
        return 'SELECT sequence_name, increment_by, start_with, min_value FROM SYS.SYSSEQUENCE';
1199
    }
1200
1201
    /**
1202
     * {@inheritdoc}
1203
     */
1204 23
    public function getSequenceNextValSQL($sequenceName)
1205
    {
1206 23
        return 'SELECT ' . $sequenceName . '.NEXTVAL';
1207
    }
1208
1209
    /**
1210
     * {@inheritdoc}
1211
     */
1212 23
    public function supportsSequences()
1213
    {
1214 23
        return true;
1215
    }
1216
1217
    /**
1218
     * {@inheritdoc}
1219
     */
1220 23
    public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
1221
    {
1222 23
        return 'TIMESTAMP WITH TIME ZONE';
1223
    }
1224
1225
    /**
1226
     * {@inheritdoc}
1227
     */
1228 92
    public function getVarcharDefaultLength()
1229
    {
1230 92
        return 1;
1231
    }
1232
1233
    /**
1234
     * {@inheritdoc}
1235
     */
1236 299
    public function getVarcharMaxLength()
1237
    {
1238 299
        return 32767;
1239
    }
1240
1241
    /**
1242
     * {@inheritdoc}
1243
     */
1244 1035
    public function hasNativeGuidType()
1245
    {
1246 1035
        return true;
1247
    }
1248
1249
    /**
1250
     * {@inheritdoc}
1251
     */
1252 23
    public function prefersIdentityColumns()
1253
    {
1254 23
        return true;
1255
    }
1256
1257
    /**
1258
     * {@inheritdoc}
1259
     */
1260 299
    public function supportsCommentOnStatement()
1261
    {
1262 299
        return true;
1263
    }
1264
1265
    /**
1266
     * {@inheritdoc}
1267
     */
1268 23
    public function supportsIdentityColumns()
1269
    {
1270 23
        return true;
1271
    }
1272
1273
    /**
1274
     * {@inheritdoc}
1275
     */
1276 253
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
1277
    {
1278 253
        $unsigned      = ! empty($columnDef['unsigned']) ? 'UNSIGNED ' : '';
1279 253
        $autoincrement = ! empty($columnDef['autoincrement']) ? ' IDENTITY' : '';
1280
1281 253
        return $unsigned . $columnDef['integer_type'] . $autoincrement;
1282
    }
1283
1284
    /**
1285
     * {@inheritdoc}
1286
     */
1287 276
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
1288
    {
1289 276
        $columnListSql = $this->getColumnDeclarationListSQL($columns);
1290 276
        $indexSql      = [];
1291
1292 276
        if (! empty($options['uniqueConstraints'])) {
1293
            foreach ((array) $options['uniqueConstraints'] as $name => $definition) {
1294
                $columnListSql .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
1295
            }
1296
        }
1297
1298 276
        if (! empty($options['indexes'])) {
1299
            /** @var Index $index */
1300 92
            foreach ((array) $options['indexes'] as $index) {
1301 92
                $indexSql[] = $this->getCreateIndexSQL($index, $tableName);
1302
            }
1303
        }
1304
1305 276
        if (! empty($options['primary'])) {
1306 138
            $flags = '';
1307
1308 138
            if (isset($options['primary_index']) && $options['primary_index']->hasFlag('clustered')) {
1309
                $flags = ' CLUSTERED ';
1310
            }
1311
1312 138
            $columnListSql .= ', PRIMARY KEY' . $flags . ' (' . implode(', ', array_unique(array_values((array) $options['primary']))) . ')';
1313
        }
1314
1315 276
        if (! empty($options['foreignKeys'])) {
1316 46
            foreach ((array) $options['foreignKeys'] as $definition) {
1317 46
                $columnListSql .= ', ' . $this->getForeignKeyDeclarationSQL($definition);
1318
            }
1319
        }
1320
1321 276
        $query = 'CREATE TABLE ' . $tableName . ' (' . $columnListSql;
1322 276
        $check = $this->getCheckDeclarationSQL($columns);
1323
1324 276
        if (! empty($check)) {
1325 23
            $query .= ', ' . $check;
1326
        }
1327
1328 276
        $query .= ')';
1329
1330 276
        return array_merge([$query], $indexSql);
1331
    }
1332
1333
    /**
1334
     * {@inheritdoc}
1335
     */
1336 46
    protected function _getTransactionIsolationLevelSQL($level)
1337
    {
1338 46
        switch ($level) {
1339
            case TransactionIsolationLevel::READ_UNCOMMITTED:
1340 23
                return 0;
1341
            case TransactionIsolationLevel::READ_COMMITTED:
1342 23
                return 1;
1343
            case TransactionIsolationLevel::REPEATABLE_READ:
1344 23
                return 2;
1345
            case TransactionIsolationLevel::SERIALIZABLE:
1346 23
                return 3;
1347
            default:
1348 23
                throw new InvalidArgumentException('Invalid isolation level:' . $level);
1349
        }
1350
    }
1351
1352
    /**
1353
     * {@inheritdoc}
1354
     */
1355 115
    protected function doModifyLimitQuery(string $query, ?int $limit, int $offset) : string
1356
    {
1357 115
        $limitOffsetClause = '';
1358
1359 115
        if ($limit !== null) {
1360 92
            $limitOffsetClause = 'TOP ' . $limit . ' ';
1361
        }
1362
1363 115
        if ($offset > 0) {
1364 23
            if ($limit === null) {
1365 23
                $limitOffsetClause = 'TOP ALL ';
1366
            }
1367
1368 23
            $limitOffsetClause .= 'START AT ' . ($offset + 1) . ' ';
1369
        }
1370
1371 115
        if ($limitOffsetClause) {
1372 92
            return preg_replace('/^\s*(SELECT\s+(DISTINCT\s+)?)/i', '\1' . $limitOffsetClause, $query);
1373
        }
1374
1375 23
        return $query;
1376
    }
1377
1378
    /**
1379
     * Return the INDEX query section dealing with non-standard
1380
     * SQL Anywhere options.
1381
     *
1382
     * @param Index $index Index definition
1383
     *
1384
     * @return string
1385
     */
1386 207
    protected function getAdvancedIndexOptionsSQL(Index $index)
1387
    {
1388 207
        if ($index->hasFlag('with_nulls_distinct') && $index->hasFlag('with_nulls_not_distinct')) {
1389 23
            throw new UnexpectedValueException(
1390 23
                'An Index can either have a "with_nulls_distinct" or "with_nulls_not_distinct" flag but not both.'
1391
            );
1392
        }
1393
1394 184
        $sql = '';
1395
1396 184
        if (! $index->isPrimary() && $index->hasFlag('for_olap_workload')) {
1397 23
            $sql .= ' FOR OLAP WORKLOAD';
1398
        }
1399
1400 184
        if (! $index->isPrimary() && $index->isUnique() && $index->hasFlag('with_nulls_not_distinct')) {
1401 23
            return ' WITH NULLS NOT DISTINCT' . $sql;
1402
        }
1403
1404 184
        if (! $index->isPrimary() && $index->isUnique() && $index->hasFlag('with_nulls_distinct')) {
1405 23
            return ' WITH NULLS DISTINCT' . $sql;
1406
        }
1407
1408 184
        return $sql;
1409
    }
1410
1411
    /**
1412
     * {@inheritdoc}
1413
     */
1414 23
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
1415
    {
1416 23
        return $fixed
1417 23
            ? 'BINARY(' . ($length ?: $this->getBinaryDefaultLength()) . ')'
1418 23
            : 'VARBINARY(' . ($length ?: $this->getBinaryDefaultLength()) . ')';
1419
    }
1420
1421
    /**
1422
     * Returns the SQL snippet for creating a table constraint.
1423
     *
1424
     * @param Constraint  $constraint The table constraint to create the SQL snippet for.
1425
     * @param string|null $name       The table constraint name to use if any.
1426
     *
1427
     * @return string
1428
     *
1429
     * @throws InvalidArgumentException If the given table constraint type is not supported by this method.
1430
     */
1431 161
    protected function getTableConstraintDeclarationSQL(Constraint $constraint, $name = null)
1432
    {
1433 161
        if ($constraint instanceof ForeignKeyConstraint) {
1434
            return $this->getForeignKeyDeclarationSQL($constraint);
1435
        }
1436
1437 161
        if (! $constraint instanceof Index) {
1438 23
            throw new InvalidArgumentException('Unsupported constraint type: ' . get_class($constraint));
1439
        }
1440
1441 138
        if (! $constraint->isPrimary() && ! $constraint->isUnique()) {
1442 23
            throw new InvalidArgumentException(
1443
                'Can only create primary, unique or foreign key constraint declarations, no common index declarations ' .
1444 23
                'with getTableConstraintDeclarationSQL().'
1445
            );
1446
        }
1447
1448 115
        $constraintColumns = $constraint->getQuotedColumns($this);
1449
1450 115
        if (empty($constraintColumns)) {
1451 23
            throw new InvalidArgumentException("Incomplete definition. 'columns' required.");
1452
        }
1453
1454 92
        $sql   = '';
1455 92
        $flags = '';
1456
1457 92
        if (! empty($name)) {
1458 46
            $name = new Identifier($name);
1459 46
            $sql .= 'CONSTRAINT ' . $name->getQuotedName($this) . ' ';
1460
        }
1461
1462 92
        if ($constraint->hasFlag('clustered')) {
1463 46
            $flags = 'CLUSTERED ';
1464
        }
1465
1466 92
        if ($constraint->isPrimary()) {
1467 92
            return $sql . 'PRIMARY KEY ' . $flags . '(' . $this->getIndexFieldDeclarationListSQL($constraintColumns) . ')';
1468
        }
1469
1470 23
        return $sql . 'UNIQUE ' . $flags . '(' . $this->getIndexFieldDeclarationListSQL($constraintColumns) . ')';
1471
    }
1472
1473
    /**
1474
     * {@inheritdoc}
1475
     */
1476 207
    protected function getCreateIndexSQLFlags(Index $index)
1477
    {
1478 207
        $type = '';
1479 207
        if ($index->hasFlag('virtual')) {
1480 23
            $type .= 'VIRTUAL ';
1481
        }
1482
1483 207
        if ($index->isUnique()) {
1484 69
            $type .= 'UNIQUE ';
1485
        }
1486
1487 207
        if ($index->hasFlag('clustered')) {
1488 23
            $type .= 'CLUSTERED ';
1489
        }
1490
1491 207
        return $type;
1492
    }
1493
1494
    /**
1495
     * {@inheritdoc}
1496
     */
1497 115
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
1498
    {
1499 115
        return ['ALTER INDEX ' . $oldIndexName . ' ON ' . $tableName . ' RENAME TO ' . $index->getQuotedName($this)];
1500
    }
1501
1502
    /**
1503
     * {@inheritdoc}
1504
     */
1505 1242
    protected function getReservedKeywordsClass()
1506
    {
1507 1242
        return Keywords\SQLAnywhereKeywords::class;
1508
    }
1509
1510
    /**
1511
     * {@inheritdoc}
1512
     */
1513 276
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
1514
    {
1515 276
        return $fixed
1516 23
            ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(' . $this->getVarcharDefaultLength() . ')')
1517 276
            : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(' . $this->getVarcharDefaultLength() . ')');
1518
    }
1519
1520
    /**
1521
     * {@inheritdoc}
1522
     */
1523 138
    protected function initializeDoctrineTypeMappings()
1524
    {
1525 138
        $this->doctrineTypeMapping = [
1526
            'bigint'                   => 'bigint',
1527
            'binary'                   => 'binary',
1528
            'bit'                      => 'boolean',
1529
            'char'                     => 'string',
1530
            'decimal'                  => 'decimal',
1531
            'date'                     => 'date',
1532
            'datetime'                 => 'datetime',
1533
            'double'                   => 'float',
1534
            'float'                    => 'float',
1535
            'image'                    => 'blob',
1536
            'int'                      => 'integer',
1537
            'integer'                  => 'integer',
1538
            'long binary'              => 'blob',
1539
            'long nvarchar'            => 'text',
1540
            'long varbit'              => 'text',
1541
            'long varchar'             => 'text',
1542
            'money'                    => 'decimal',
1543
            'nchar'                    => 'string',
1544
            'ntext'                    => 'text',
1545
            'numeric'                  => 'decimal',
1546
            'nvarchar'                 => 'string',
1547
            'smalldatetime'            => 'datetime',
1548
            'smallint'                 => 'smallint',
1549
            'smallmoney'               => 'decimal',
1550
            'text'                     => 'text',
1551
            'time'                     => 'time',
1552
            'timestamp'                => 'datetime',
1553
            'timestamp with time zone' => 'datetime',
1554
            'tinyint'                  => 'smallint',
1555
            'uniqueidentifier'         => 'guid',
1556
            'uniqueidentifierstr'      => 'guid',
1557
            'unsigned bigint'          => 'bigint',
1558
            'unsigned int'             => 'integer',
1559
            'unsigned smallint'        => 'smallint',
1560
            'unsigned tinyint'         => 'smallint',
1561
            'varbinary'                => 'binary',
1562
            'varbit'                   => 'string',
1563
            'varchar'                  => 'string',
1564
            'xml'                      => 'text',
1565
        ];
1566 138
    }
1567
}
1568