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