SQLAnywhere16Platform.php 44.8 KB
Newer Older
1 2 3 4 5 6
<?php

namespace Doctrine\DBAL\Platforms;

use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\LockMode;
Steve Müller's avatar
Steve Müller committed
7 8
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\ColumnDiff;
9 10
use Doctrine\DBAL\Schema\Constraint;
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
11
use Doctrine\DBAL\Schema\Identifier;
12
use Doctrine\DBAL\Schema\Index;
13
use Doctrine\DBAL\Schema\Sequence;
14 15
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Schema\TableDiff;
16
use Doctrine\DBAL\TransactionIsolationLevel;
17
use InvalidArgumentException;
18
use UnexpectedValueException;
19 20 21 22 23 24 25 26 27
use function array_merge;
use function array_unique;
use function array_values;
use function count;
use function explode;
use function func_get_args;
use function get_class;
use function implode;
use function is_string;
Sergei Morozov's avatar
Sergei Morozov committed
28
use function preg_match;
29
use function sprintf;
30 31 32 33
use function strlen;
use function strpos;
use function strtoupper;
use function substr;
34 35

/**
36
 * Provides the behavior, features and SQL dialect of the SAP Sybase SQL Anywhere 16 database platform.
37
 */
38
class SQLAnywhere16Platform extends AbstractPlatform
39
{
40 41 42 43
    public const FOREIGN_KEY_MATCH_SIMPLE        = 1;
    public const FOREIGN_KEY_MATCH_FULL          = 2;
    public const FOREIGN_KEY_MATCH_SIMPLE_UNIQUE = 129;
    public const FOREIGN_KEY_MATCH_FULL_UNIQUE   = 130;
44 45 46 47 48 49 50 51

    /**
     * {@inheritdoc}
     */
    public function appendLockHint($fromClause, $lockMode)
    {
        switch (true) {
            case $lockMode === LockMode::NONE:
52
                return $fromClause . ' WITH (NOLOCK)';
53

54
            case $lockMode === LockMode::PESSIMISTIC_READ:
55
                return $fromClause . ' WITH (UPDLOCK)';
56

57
            case $lockMode === LockMode::PESSIMISTIC_WRITE:
58
                return $fromClause . ' WITH (XLOCK)';
59

60
            default:
61
                return $fromClause;
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
        }
    }

    /**
     * {@inheritdoc}
     *
     * SQL Anywhere supports a maximum length of 128 bytes for identifiers.
     */
    public function fixSchemaElementName($schemaElementName)
    {
        $maxIdentifierLength = $this->getMaxIdentifierLength();

        if (strlen($schemaElementName) > $maxIdentifierLength) {
            return substr($schemaElementName, 0, $maxIdentifierLength);
        }

        return $schemaElementName;
    }

    /**
     * {@inheritdoc}
     */
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
    {
        $query = '';

        if ($foreignKey->hasOption('match')) {
            $query = ' MATCH ' . $this->getForeignKeyMatchClauseSQL($foreignKey->getOption('match'));
        }

        $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);

94
        if ($foreignKey->hasOption('check_on_commit') && (bool) $foreignKey->getOption('check_on_commit')) {
95 96 97
            $query .= ' CHECK ON COMMIT';
        }

98
        if ($foreignKey->hasOption('clustered') && (bool) $foreignKey->getOption('clustered')) {
99 100 101
            $query .= ' CLUSTERED';
        }

102
        if ($foreignKey->hasOption('for_olap_workload') && (bool) $foreignKey->getOption('for_olap_workload')) {
103 104 105 106 107 108 109 110 111 112 113
            $query .= ' FOR OLAP WORKLOAD';
        }

        return $query;
    }

    /**
     * {@inheritdoc}
     */
    public function getAlterTableSQL(TableDiff $diff)
    {
114 115 116 117 118
        $sql          = [];
        $columnSql    = [];
        $commentsSQL  = [];
        $tableSql     = [];
        $alterClauses = [];
119 120 121 122 123 124

        foreach ($diff->addedColumns as $column) {
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
            }

Steve Müller's avatar
Steve Müller committed
125
            $alterClauses[] = $this->getAlterTableAddColumnClause($column);
126

Steve Müller's avatar
Steve Müller committed
127 128
            $comment = $this->getColumnComment($column);

129 130
            if ($comment === null || $comment === '') {
                continue;
131
            }
132 133 134 135 136 137

            $commentsSQL[] = $this->getCommentOnColumnSQL(
                $diff->getName($this)->getQuotedName($this),
                $column->getQuotedName($this),
                $comment
            );
138 139 140 141 142 143 144
        }

        foreach ($diff->removedColumns as $column) {
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
            }

Steve Müller's avatar
Steve Müller committed
145
            $alterClauses[] = $this->getAlterTableRemoveColumnClause($column);
146 147 148 149 150 151 152
        }

        foreach ($diff->changedColumns as $columnDiff) {
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
            }

Steve Müller's avatar
Steve Müller committed
153
            $alterClause = $this->getAlterTableChangeColumnClause($columnDiff);
154

155
            if ($alterClause !== null) {
Steve Müller's avatar
Steve Müller committed
156
                $alterClauses[] = $alterClause;
157 158
            }

159 160
            if (! $columnDiff->hasChanged('comment')) {
                continue;
161
            }
162 163 164 165 166 167 168 169

            $column = $columnDiff->column;

            $commentsSQL[] = $this->getCommentOnColumnSQL(
                $diff->getName($this)->getQuotedName($this),
                $column->getQuotedName($this),
                $this->getColumnComment($column)
            );
170 171 172 173 174 175 176
        }

        foreach ($diff->renamedColumns as $oldColumnName => $column) {
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
            }

177
            $sql[] = $this->getAlterTableClause($diff->getName($this)) . ' ' .
Steve Müller's avatar
Steve Müller committed
178
                $this->getAlterTableRenameColumnClause($oldColumnName, $column);
179 180
        }

181 182 183
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
            if (! empty($alterClauses)) {
                $sql[] = $this->getAlterTableClause($diff->getName($this)) . ' ' . implode(', ', $alterClauses);
184 185
            }

186 187
            $sql = array_merge($sql, $commentsSQL);

Sergei Morozov's avatar
Sergei Morozov committed
188 189 190
            $newName = $diff->getNewName();

            if ($newName !== false) {
191
                $sql[] = $this->getAlterTableClause($diff->getName($this)) . ' ' .
Sergei Morozov's avatar
Sergei Morozov committed
192
                    $this->getAlterTableRenameTableClause($newName);
193 194
            }

195 196 197 198 199
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
200 201 202 203 204
        }

        return array_merge($sql, $tableSql, $columnSql);
    }

Steve Müller's avatar
Steve Müller committed
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    /**
     * Returns the SQL clause for creating a column in a table alteration.
     *
     * @param Column $column The column to add.
     *
     * @return string
     */
    protected function getAlterTableAddColumnClause(Column $column)
    {
        return 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
    }

    /**
     * Returns the SQL clause for altering a table.
     *
220
     * @param Identifier $tableName The quoted name of the table to alter.
Steve Müller's avatar
Steve Müller committed
221 222 223
     *
     * @return string
     */
224
    protected function getAlterTableClause(Identifier $tableName)
Steve Müller's avatar
Steve Müller committed
225
    {
226
        return 'ALTER TABLE ' . $tableName->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    }

    /**
     * Returns the SQL clause for dropping a column in a table alteration.
     *
     * @param Column $column The column to drop.
     *
     * @return string
     */
    protected function getAlterTableRemoveColumnClause(Column $column)
    {
        return 'DROP ' . $column->getQuotedName($this);
    }

    /**
     * Returns the SQL clause for renaming a column in a table alteration.
     *
     * @param string $oldColumnName The quoted name of the column to rename.
     * @param Column $column        The column to rename to.
     *
     * @return string
     */
    protected function getAlterTableRenameColumnClause($oldColumnName, Column $column)
    {
251 252
        $oldColumnName = new Identifier($oldColumnName);

253
        return 'RENAME ' . $oldColumnName->getQuotedName($this) . ' TO ' . $column->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
254 255 256 257 258
    }

    /**
     * Returns the SQL clause for renaming a table in a table alteration.
     *
259
     * @param Identifier $newTableName The quoted name of the table to rename to.
Steve Müller's avatar
Steve Müller committed
260 261 262
     *
     * @return string
     */
263
    protected function getAlterTableRenameTableClause(Identifier $newTableName)
Steve Müller's avatar
Steve Müller committed
264
    {
265
        return 'RENAME ' . $newTableName->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
    }

    /**
     * Returns the SQL clause for altering a column in a table alteration.
     *
     * This method returns null in case that only the column comment has changed.
     * Changes in column comments have to be handled differently.
     *
     * @param ColumnDiff $columnDiff The diff of the column to alter.
     *
     * @return string|null
     */
    protected function getAlterTableChangeColumnClause(ColumnDiff $columnDiff)
    {
        $column = $columnDiff->column;

        // Do not return alter clause if only comment has changed.
283
        if (! ($columnDiff->hasChanged('comment') && count($columnDiff->changedProperties) === 1)) {
284 285 286
            $columnAlterationClause = 'ALTER ' .
                $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());

287
            if ($columnDiff->hasChanged('default') && $column->getDefault() === null) {
288 289 290 291
                $columnAlterationClause .= ', ALTER ' . $column->getQuotedName($this) . ' DROP DEFAULT';
            }

            return $columnAlterationClause;
Steve Müller's avatar
Steve Müller committed
292
        }
293 294

        return null;
Steve Müller's avatar
Steve Müller committed
295 296
    }

297 298 299 300 301 302 303 304 305 306
    /**
     * {@inheritdoc}
     */
    public function getBigIntTypeDeclarationSQL(array $columnDef)
    {
        $columnDef['integer_type'] = 'BIGINT';

        return $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
    }

Steve Müller's avatar
Steve Müller committed
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
    /**
     * {@inheritdoc}
     */
    public function getBinaryDefaultLength()
    {
        return 1;
    }

    /**
     * {@inheritdoc}
     */
    public function getBinaryMaxLength()
    {
        return 32767;
    }

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    /**
     * {@inheritdoc}
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'LONG BINARY';
    }

    /**
     * {@inheritdoc}
     *
     * BIT type columns require an explicit NULL declaration
     * in SQL Anywhere if they shall be nullable.
     * Otherwise by just omitting the NOT NULL clause,
     * SQL Anywhere will declare them NOT NULL nonetheless.
     */
    public function getBooleanTypeDeclarationSQL(array $columnDef)
    {
341
        $nullClause = isset($columnDef['notnull']) && (bool) $columnDef['notnull'] === false ? ' NULL' : '';
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358

        return 'BIT' . $nullClause;
    }

    /**
     * {@inheritdoc}
     */
    public function getClobTypeDeclarationSQL(array $field)
    {
        return 'TEXT';
    }

    /**
     * {@inheritdoc}
     */
    public function getCommentOnColumnSQL($tableName, $columnName, $comment)
    {
359
        $tableName  = new Identifier($tableName);
360
        $columnName = new Identifier($columnName);
361
        $comment    = $comment === null ? 'NULL' : $this->quoteStringLiteral($comment);
362

363 364 365 366 367 368
        return sprintf(
            'COMMENT ON COLUMN %s.%s IS %s',
            $tableName->getQuotedName($this),
            $columnName->getQuotedName($this),
            $comment
        );
369 370 371 372 373 374 375
    }

    /**
     * {@inheritdoc}
     */
    public function getConcatExpression()
    {
376
        return 'STRING(' . implode(', ', func_get_args()) . ')';
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
    }

    /**
     * {@inheritdoc}
     */
    public function getCreateConstraintSQL(Constraint $constraint, $table)
    {
        if ($constraint instanceof ForeignKeyConstraint) {
            return $this->getCreateForeignKeySQL($constraint, $table);
        }

        if ($table instanceof Table) {
            $table = $table->getQuotedName($this);
        }

Steve Müller's avatar
Steve Müller committed
392 393
        return 'ALTER TABLE ' . $table .
               ' ADD ' . $this->getTableConstraintDeclarationSQL($constraint, $constraint->getQuotedName($this));
394 395 396 397 398 399 400
    }

    /**
     * {@inheritdoc}
     */
    public function getCreateDatabaseSQL($database)
    {
401 402 403
        $database = new Identifier($database);

        return "CREATE DATABASE '" . $database->getName() . "'";
404 405 406 407 408 409 410 411 412
    }

    /**
     * {@inheritdoc}
     *
     * Appends SQL Anywhere specific flags if given.
     */
    public function getCreateIndexSQL(Index $index, $table)
    {
413
        return parent::getCreateIndexSQL($index, $table) . $this->getAdvancedIndexOptionsSQL($index);
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
    }

    /**
     * {@inheritdoc}
     */
    public function getCreatePrimaryKeySQL(Index $index, $table)
    {
        if ($table instanceof Table) {
            $table = $table->getQuotedName($this);
        }

        return 'ALTER TABLE ' . $table . ' ADD ' . $this->getPrimaryKeyDeclarationSQL($index);
    }

    /**
     * {@inheritdoc}
     */
    public function getCreateTemporaryTableSnippetSQL()
    {
        return 'CREATE ' . $this->getTemporaryTableSQL() . ' TABLE';
    }

    /**
     * {@inheritdoc}
     */
    public function getCreateViewSQL($name, $sql)
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }

    /**
     * {@inheritdoc}
     */
    public function getCurrentDateSQL()
    {
        return 'CURRENT DATE';
    }

    /**
     * {@inheritdoc}
     */
    public function getCurrentTimeSQL()
    {
        return 'CURRENT TIME';
    }

    /**
     * {@inheritdoc}
     */
    public function getCurrentTimestampSQL()
    {
        return 'CURRENT TIMESTAMP';
    }

    /**
     * {@inheritdoc}
     */
471
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
472
    {
473
        $factorClause = '';
474

475
        if ($operator === '-') {
476 477
            $factorClause = '-1 * ';
        }
478

479
        return 'DATEADD(' . $unit . ', ' . $factorClause . $interval . ', ' . $date . ')';
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
    }

    /**
     * {@inheritdoc}
     */
    public function getDateDiffExpression($date1, $date2)
    {
        return 'DATEDIFF(day, ' . $date2 . ', ' . $date1 . ')';
    }

    /**
     * {@inheritdoc}
     */
    public function getDateTimeFormatString()
    {
        return 'Y-m-d H:i:s.u';
    }

    /**
     * {@inheritdoc}
     */
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
    {
        return 'DATETIME';
    }

506 507 508 509 510
    /**
     * {@inheritdoc}
     */
    public function getDateTimeTzFormatString()
    {
511
        return 'Y-m-d H:i:s.uP';
512 513
    }

514 515 516 517 518 519 520 521 522 523 524 525 526
    /**
     * {@inheritdoc}
     */
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
    {
        return 'DATE';
    }

    /**
     * {@inheritdoc}
     */
    public function getDefaultTransactionIsolationLevel()
    {
527
        return TransactionIsolationLevel::READ_UNCOMMITTED;
528 529 530 531 532 533 534
    }

    /**
     * {@inheritdoc}
     */
    public function getDropDatabaseSQL($database)
    {
535 536 537
        $database = new Identifier($database);

        return "DROP DATABASE '" . $database->getName() . "'";
538 539 540 541 542 543 544 545 546
    }

    /**
     * {@inheritdoc}
     */
    public function getDropIndexSQL($index, $table = null)
    {
        if ($index instanceof Index) {
            $index = $index->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
547 548
        }

549 550
        if (! is_string($index)) {
            throw new InvalidArgumentException(
551
                'AbstractPlatform::getDropIndexSQL() expects $index parameter to be string or ' . Index::class . '.'
552 553 554
            );
        }

555
        if (! isset($table)) {
556 557 558 559 560
            return 'DROP INDEX ' . $index;
        }

        if ($table instanceof Table) {
            $table = $table->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
561 562
        }

563 564
        if (! is_string($table)) {
            throw new InvalidArgumentException(
565
                'AbstractPlatform::getDropIndexSQL() expects $table parameter to be string or ' . Index::class . '.'
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
            );
        }

        return 'DROP INDEX ' . $table . '.' . $index;
    }

    /**
     * {@inheritdoc}
     */
    public function getDropViewSQL($name)
    {
        return 'DROP VIEW ' . $name;
    }

    /**
     * {@inheritdoc}
     */
    public function getForeignKeyBaseDeclarationSQL(ForeignKeyConstraint $foreignKey)
    {
Steve Müller's avatar
Steve Müller committed
585 586 587 588
        $sql              = '';
        $foreignKeyName   = $foreignKey->getName();
        $localColumns     = $foreignKey->getQuotedLocalColumns($this);
        $foreignColumns   = $foreignKey->getQuotedForeignColumns($this);
589
        $foreignTableName = $foreignKey->getQuotedForeignTableName($this);
590

591
        if (! empty($foreignKeyName)) {
592 593 594 595
            $sql .= 'CONSTRAINT ' . $foreignKey->getQuotedName($this) . ' ';
        }

        if (empty($localColumns)) {
596
            throw new InvalidArgumentException("Incomplete definition. 'local' required.");
597 598 599
        }

        if (empty($foreignColumns)) {
600
            throw new InvalidArgumentException("Incomplete definition. 'foreign' required.");
601 602 603
        }

        if (empty($foreignTableName)) {
604
            throw new InvalidArgumentException("Incomplete definition. 'foreignTable' required.");
605 606
        }

607
        if ($foreignKey->hasOption('notnull') && (bool) $foreignKey->getOption('notnull')) {
608 609 610 611 612 613 614 615 616 617 618 619
            $sql .= 'NOT NULL ';
        }

        return $sql .
            'FOREIGN KEY (' . $this->getIndexFieldDeclarationListSQL($localColumns) . ') ' .
            'REFERENCES ' . $foreignKey->getQuotedForeignTableName($this) .
            ' (' . $this->getIndexFieldDeclarationListSQL($foreignColumns) . ')';
    }

    /**
     * Returns foreign key MATCH clause for given type.
     *
620
     * @param int $type The foreign key match type
621 622 623
     *
     * @return string
     *
624
     * @throws InvalidArgumentException If unknown match type given.
625 626 627 628 629 630
     */
    public function getForeignKeyMatchClauseSQL($type)
    {
        switch ((int) $type) {
            case self::FOREIGN_KEY_MATCH_SIMPLE:
                return 'SIMPLE';
631

632 633
            case self::FOREIGN_KEY_MATCH_FULL:
                return 'FULL';
634

635 636
            case self::FOREIGN_KEY_MATCH_SIMPLE_UNIQUE:
                return 'UNIQUE SIMPLE';
637

638 639 640
            case self::FOREIGN_KEY_MATCH_FULL_UNIQUE:
                return 'UNIQUE FULL';
            default:
641
                throw new InvalidArgumentException('Invalid foreign key match type: ' . $type);
642 643 644 645 646 647 648 649
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getForeignKeyReferentialActionSQL($action)
    {
650 651 652
        // NO ACTION is not supported, therefore falling back to RESTRICT.
        if (strtoupper($action) === 'NO ACTION') {
            return 'RESTRICT';
653
        }
654 655

        return parent::getForeignKeyReferentialActionSQL($action);
656 657 658 659 660 661 662
    }

    /**
     * {@inheritdoc}
     */
    public function getForUpdateSQL()
    {
663
        return '';
664 665 666 667
    }

    /**
     * {@inheritdoc}
668 669
     *
     * @deprecated Use application-generated UUIDs instead
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
     */
    public function getGuidExpression()
    {
        return 'NEWID()';
    }

    /**
     * {@inheritdoc}
     */
    public function getGuidTypeDeclarationSQL(array $field)
    {
        return 'UNIQUEIDENTIFIER';
    }

    /**
     * {@inheritdoc}
     */
    public function getIndexDeclarationSQL($name, Index $index)
    {
Steve Müller's avatar
Steve Müller committed
689
        // Index declaration in statements like CREATE TABLE is not supported.
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
        throw DBALException::notSupported(__METHOD__);
    }

    /**
     * {@inheritdoc}
     */
    public function getIntegerTypeDeclarationSQL(array $columnDef)
    {
        $columnDef['integer_type'] = 'INT';

        return $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
    }

    /**
     * {@inheritdoc}
     */
    public function getListDatabasesSQL()
    {
        return 'SELECT db_name(number) AS name FROM sa_db_list()';
    }

    /**
     * {@inheritdoc}
     */
    public function getListTableColumnsSQL($table, $database = null)
    {
716 717 718
        $user = 'USER_NAME()';

        if (strpos($table, '.') !== false) {
719 720
            [$user, $table] = explode('.', $table);
            $user           = $this->quoteStringLiteral($user);
721 722
        }

723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
        return sprintf(
            <<<'SQL'
SELECT    col.column_name,
          COALESCE(def.user_type_name, def.domain_name) AS 'type',
          def.declared_width AS 'length',
          def.scale,
          CHARINDEX('unsigned', def.domain_name) AS 'unsigned',
          IF col.nulls = 'Y' THEN 0 ELSE 1 ENDIF AS 'notnull',
          col."default",
          def.is_autoincrement AS 'autoincrement',
          rem.remarks AS 'comment'
FROM      sa_describe_query('SELECT * FROM "%s"') AS def
JOIN      SYS.SYSTABCOL AS col
ON        col.table_id = def.base_table_id AND col.column_id = def.base_column_id
LEFT JOIN SYS.SYSREMARK AS rem
ON        col.object_id = rem.object_id
WHERE     def.base_owner_name = %s
ORDER BY  def.base_column_id ASC
SQL
            ,
            $table,
            $user
        );
746 747 748 749 750 751 752 753 754
    }

    /**
     * {@inheritdoc}
     *
     * @todo Where is this used? Which information should be retrieved?
     */
    public function getListTableConstraintsSQL($table)
    {
755 756 757
        $user = '';

        if (strpos($table, '.') !== false) {
758 759 760
            [$user, $table] = explode('.', $table);
            $user           = $this->quoteStringLiteral($user);
            $table          = $this->quoteStringLiteral($table);
761 762
        } else {
            $table = $this->quoteStringLiteral($table);
763 764
        }

765 766 767 768 769 770 771 772 773 774 775 776
        return sprintf(
            <<<'SQL'
SELECT con.*
FROM   SYS.SYSCONSTRAINT AS con
JOIN   SYS.SYSTAB AS tab ON con.table_object_id = tab.object_id
WHERE  tab.table_name = %s
AND    tab.creator = USER_ID(%s)
SQL
            ,
            $table,
            $user
        );
777 778 779 780 781 782 783
    }

    /**
     * {@inheritdoc}
     */
    public function getListTableForeignKeysSQL($table)
    {
784 785 786
        $user = '';

        if (strpos($table, '.') !== false) {
787 788 789
            [$user, $table] = explode('.', $table);
            $user           = $this->quoteStringLiteral($user);
            $table          = $this->quoteStringLiteral($table);
790 791
        } else {
            $table = $this->quoteStringLiteral($table);
792 793
        }

794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
        return sprintf(
            <<<'SQL'
SELECT    fcol.column_name AS local_column,
          ptbl.table_name AS foreign_table,
          pcol.column_name AS foreign_column,
          idx.index_name,
          IF fk.nulls = 'N'
              THEN 1
              ELSE NULL
          ENDIF AS notnull,
          CASE ut.referential_action
              WHEN 'C' THEN 'CASCADE'
              WHEN 'D' THEN 'SET DEFAULT'
              WHEN 'N' THEN 'SET NULL'
              WHEN 'R' THEN 'RESTRICT'
              ELSE NULL
          END AS  on_update,
          CASE dt.referential_action
              WHEN 'C' THEN 'CASCADE'
              WHEN 'D' THEN 'SET DEFAULT'
              WHEN 'N' THEN 'SET NULL'
              WHEN 'R' THEN 'RESTRICT'
              ELSE NULL
          END AS on_delete,
          IF fk.check_on_commit = 'Y'
              THEN 1
              ELSE NULL
          ENDIF AS check_on_commit, -- check_on_commit flag
          IF ftbl.clustered_index_id = idx.index_id
              THEN 1
              ELSE NULL
          ENDIF AS 'clustered', -- clustered flag
          IF fk.match_type = 0
              THEN NULL
              ELSE fk.match_type
          ENDIF AS 'match', -- match option
          IF pidx.max_key_distance = 1
              THEN 1
              ELSE NULL
          ENDIF AS for_olap_workload -- for_olap_workload flag
FROM      SYS.SYSFKEY AS fk
JOIN      SYS.SYSIDX AS idx
ON        fk.foreign_table_id = idx.table_id
AND       fk.foreign_index_id = idx.index_id
JOIN      SYS.SYSPHYSIDX pidx
ON        idx.table_id = pidx.table_id
AND       idx.phys_index_id = pidx.phys_index_id
JOIN      SYS.SYSTAB AS ptbl
ON        fk.primary_table_id = ptbl.table_id
JOIN      SYS.SYSTAB AS ftbl
ON        fk.foreign_table_id = ftbl.table_id
JOIN      SYS.SYSIDXCOL AS idxcol
ON        idx.table_id = idxcol.table_id
AND       idx.index_id = idxcol.index_id
JOIN      SYS.SYSTABCOL AS pcol
ON        ptbl.table_id = pcol.table_id
AND       idxcol.primary_column_id = pcol.column_id
JOIN      SYS.SYSTABCOL AS fcol
ON        ftbl.table_id = fcol.table_id
AND       idxcol.column_id = fcol.column_id
LEFT JOIN SYS.SYSTRIGGER ut
ON        fk.foreign_table_id = ut.foreign_table_id
AND       fk.foreign_index_id = ut.foreign_key_id
AND       ut.event = 'C'
LEFT JOIN SYS.SYSTRIGGER dt
ON        fk.foreign_table_id = dt.foreign_table_id
AND       fk.foreign_index_id = dt.foreign_key_id
AND       dt.event = 'D'
WHERE     ftbl.table_name = %s
AND       ftbl.creator = USER_ID(%s)
ORDER BY  fk.foreign_index_id ASC, idxcol.sequence ASC
SQL
            ,
            $table,
            $user
        );
870 871 872 873 874 875 876
    }

    /**
     * {@inheritdoc}
     */
    public function getListTableIndexesSQL($table, $currentDatabase = null)
    {
877 878 879
        $user = '';

        if (strpos($table, '.') !== false) {
880 881 882
            [$user, $table] = explode('.', $table);
            $user           = $this->quoteStringLiteral($user);
            $table          = $this->quoteStringLiteral($table);
883 884
        } else {
            $table = $this->quoteStringLiteral($table);
885 886
        }

887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
        return sprintf(
            <<<'SQL'
SELECT   idx.index_name AS key_name,
         IF idx.index_category = 1
             THEN 1
             ELSE 0
         ENDIF AS 'primary',
         col.column_name,
         IF idx."unique" IN(1, 2, 5)
             THEN 0
             ELSE 1
         ENDIF AS non_unique,
         IF tbl.clustered_index_id = idx.index_id
             THEN 1
             ELSE NULL
         ENDIF AS 'clustered', -- clustered flag
         IF idx."unique" = 5
             THEN 1
             ELSE NULL
         ENDIF AS with_nulls_not_distinct, -- with_nulls_not_distinct flag
         IF pidx.max_key_distance = 1
              THEN 1
              ELSE NULL
          ENDIF AS for_olap_workload -- for_olap_workload flag
FROM     SYS.SYSIDX AS idx
JOIN     SYS.SYSPHYSIDX pidx
ON       idx.table_id = pidx.table_id
AND      idx.phys_index_id = pidx.phys_index_id
JOIN     SYS.SYSIDXCOL AS idxcol
ON       idx.table_id = idxcol.table_id AND idx.index_id = idxcol.index_id
JOIN     SYS.SYSTABCOL AS col
ON       idxcol.table_id = col.table_id AND idxcol.column_id = col.column_id
JOIN     SYS.SYSTAB AS tbl
ON       idx.table_id = tbl.table_id
WHERE    tbl.table_name = %s
AND      tbl.creator = USER_ID(%s)
AND      idx.index_category != 2 -- exclude indexes implicitly created by foreign key constraints
ORDER BY idx.index_id ASC, idxcol.sequence ASC
SQL
            ,
            $table,
            $user
        );
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
    }

    /**
     * {@inheritdoc}
     */
    public function getListTablesSQL()
    {
        return "SELECT   tbl.table_name
                FROM     SYS.SYSTAB AS tbl
                JOIN     SYS.SYSUSER AS usr ON tbl.creator = usr.user_id
                JOIN     dbo.SYSOBJECTS AS obj ON tbl.object_id = obj.id
                WHERE    tbl.table_type IN(1, 3) -- 'BASE', 'GBL TEMP'
                AND      usr.user_name NOT IN('SYS', 'dbo', 'rs_systabgroup') -- exclude system users
                AND      obj.type = 'U' -- user created tables only
                ORDER BY tbl.table_name ASC";
    }

    /**
     * {@inheritdoc}
     *
     * @todo Where is this used? Which information should be retrieved?
     */
    public function getListUsersSQL()
    {
        return 'SELECT * FROM SYS.SYSUSER ORDER BY user_name ASC';
    }

    /**
     * {@inheritdoc}
     */
    public function getListViewsSQL($database)
    {
        return "SELECT   tbl.table_name, v.view_def
                FROM     SYS.SYSVIEW v
                JOIN     SYS.SYSTAB tbl ON v.view_object_id = tbl.object_id
                JOIN     SYS.SYSUSER usr ON tbl.creator = usr.user_id
                JOIN     dbo.SYSOBJECTS obj ON tbl.object_id = obj.id
                WHERE    usr.user_name NOT IN('SYS', 'dbo', 'rs_systabgroup') -- exclude system users
                ORDER BY tbl.table_name ASC";
    }

    /**
     * {@inheritdoc}
     */
    public function getLocateExpression($str, $substr, $startPos = false)
    {
976
        if ($startPos === false) {
977
            return 'LOCATE(' . $str . ', ' . $substr . ')';
978 979
        }

980
        return 'LOCATE(' . $str . ', ' . $substr . ', ' . $startPos . ')';
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
    }

    /**
     * {@inheritdoc}
     */
    public function getMaxIdentifierLength()
    {
        return 128;
    }

    /**
     * {@inheritdoc}
     */
    public function getMd5Expression($column)
    {
996
        return 'HASH(' . $column . ", 'MD5')";
997 998
    }

999 1000 1001 1002 1003 1004 1005 1006
    /**
     * {@inheritdoc}
     */
    public function getRegexpExpression()
    {
        return 'REGEXP';
    }

1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'sqlanywhere';
    }

    /**
     * Obtain DBMS specific SQL code portion needed to set a primary key
     * declaration to be used in statements like ALTER TABLE.
     *
     * @param Index  $index Index definition
     * @param string $name  Name of the primary key
     *
     * @return string DBMS specific SQL code portion needed to set a primary key
     *
1024
     * @throws InvalidArgumentException If the given index is not a primary key.
1025 1026 1027
     */
    public function getPrimaryKeyDeclarationSQL(Index $index, $name = null)
    {
1028 1029
        if (! $index->isPrimary()) {
            throw new InvalidArgumentException(
Steve Müller's avatar
Steve Müller committed
1030 1031
                'Can only create primary key declarations with getPrimaryKeyDeclarationSQL()'
            );
1032 1033
        }

Steve Müller's avatar
Steve Müller committed
1034
        return $this->getTableConstraintDeclarationSQL($index, $name);
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
    }

    /**
     * {@inheritdoc}
     */
    public function getSetTransactionIsolationSQL($level)
    {
        return 'SET TEMPORARY OPTION isolation_level = ' . $this->_getTransactionIsolationLevelSQL($level);
    }

    /**
     * {@inheritdoc}
     */
    public function getSmallIntTypeDeclarationSQL(array $columnDef)
    {
        $columnDef['integer_type'] = 'SMALLINT';

        return $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
    }

    /**
     * Returns the SQL statement for starting an existing database.
     *
     * In SQL Anywhere you can start and stop databases on a
     * database server instance.
     * This is a required statement after having created a new database
     * as it has to be explicitly started to be usable.
     * SQL Anywhere does not automatically start a database after creation!
     *
     * @param string $database Name of the database to start.
     *
     * @return string
     */
    public function getStartDatabaseSQL($database)
    {
1070 1071 1072
        $database = new Identifier($database);

        return "START DATABASE '" . $database->getName() . "' AUTOSTOP OFF";
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
    }

    /**
     * Returns the SQL statement for stopping a running database.
     *
     * In SQL Anywhere you can start and stop databases on a
     * database server instance.
     * This is a required statement before dropping an existing database
     * as it has to be explicitly stopped before it can be dropped.
     *
     * @param string $database Name of the database to stop.
     *
     * @return string
     */
    public function getStopDatabaseSQL($database)
    {
1089 1090 1091
        $database = new Identifier($database);

        return 'STOP DATABASE "' . $database->getName() . '" UNCONDITIONALLY';
1092 1093 1094 1095 1096 1097 1098
    }

    /**
     * {@inheritdoc}
     */
    public function getSubstringExpression($value, $from, $length = null)
    {
1099
        if ($length === null) {
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
            return 'SUBSTRING(' . $value . ', ' . $from . ')';
        }

        return 'SUBSTRING(' . $value . ', ' . $from . ', ' . $length . ')';
    }

    /**
     * {@inheritdoc}
     */
    public function getTemporaryTableSQL()
    {
        return 'GLOBAL TEMPORARY';
    }

    /**
     * {@inheritdoc}
     */
    public function getTimeFormatString()
    {
        return 'H:i:s.u';
    }

    /**
     * {@inheritdoc}
     */
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
    {
        return 'TIME';
    }

    /**
     * {@inheritdoc}
     */
1133
    public function getTrimExpression($str, $pos = TrimMode::UNSPECIFIED, $char = false)
1134
    {
1135
        if ($char === false) {
1136
            switch ($pos) {
1137
                case TrimMode::LEADING:
1138
                    return $this->getLtrimExpression($str);
1139
                case TrimMode::TRAILING:
1140 1141 1142 1143 1144 1145
                    return $this->getRtrimExpression($str);
                default:
                    return 'TRIM(' . $str . ')';
            }
        }

1146
        $pattern = "'%[^' + " . $char . " + ']%'";
1147 1148

        switch ($pos) {
1149
            case TrimMode::LEADING:
1150
                return 'SUBSTR(' . $str . ', PATINDEX(' . $pattern . ', ' . $str . '))';
1151
            case TrimMode::TRAILING:
1152 1153
                return 'REVERSE(SUBSTR(REVERSE(' . $str . '), PATINDEX(' . $pattern . ', REVERSE(' . $str . '))))';
            default:
1154
                return 'REVERSE(SUBSTR(REVERSE(SUBSTR(' . $str . ', PATINDEX(' . $pattern . ', ' . $str . '))), ' .
1155 1156 1157 1158 1159 1160 1161 1162 1163
                    'PATINDEX(' . $pattern . ', REVERSE(SUBSTR(' . $str . ', PATINDEX(' . $pattern . ', ' . $str . '))))))';
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getTruncateTableSQL($tableName, $cascade = false)
    {
1164 1165 1166
        $tableIdentifier = new Identifier($tableName);

        return 'TRUNCATE TABLE ' . $tableIdentifier->getQuotedName($this);
1167 1168 1169 1170 1171 1172 1173
    }

    /**
     * {@inheritdoc}
     */
    public function getUniqueConstraintDeclarationSQL($name, Index $index)
    {
Steve Müller's avatar
Steve Müller committed
1174
        if ($index->isPrimary()) {
1175
            throw new InvalidArgumentException(
Steve Müller's avatar
Steve Müller committed
1176 1177
                'Cannot create primary key constraint declarations with getUniqueConstraintDeclarationSQL().'
            );
1178 1179
        }

1180 1181
        if (! $index->isUnique()) {
            throw new InvalidArgumentException(
Steve Müller's avatar
Steve Müller committed
1182 1183 1184
                'Can only create unique constraint declarations, no common index declarations with ' .
                'getUniqueConstraintDeclarationSQL().'
            );
1185 1186
        }

Steve Müller's avatar
Steve Müller committed
1187
        return $this->getTableConstraintDeclarationSQL($index, $name);
1188 1189
    }

1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
    /**
     * {@inheritdoc}
     */
    public function getCreateSequenceSQL(Sequence $sequence)
    {
        return 'CREATE SEQUENCE ' . $sequence->getQuotedName($this) .
            ' INCREMENT BY ' . $sequence->getAllocationSize() .
            ' START WITH ' . $sequence->getInitialValue() .
            ' MINVALUE ' . $sequence->getInitialValue();
    }

    /**
     * {@inheritdoc}
     */
    public function getAlterSequenceSQL(Sequence $sequence)
    {
        return 'ALTER SEQUENCE ' . $sequence->getQuotedName($this) .
            ' INCREMENT BY ' . $sequence->getAllocationSize();
    }

    /**
     * {@inheritdoc}
     */
    public function getDropSequenceSQL($sequence)
    {
        if ($sequence instanceof Sequence) {
            $sequence = $sequence->getQuotedName($this);
        }

        return 'DROP SEQUENCE ' . $sequence;
    }

    /**
     * {@inheritdoc}
     */
    public function getListSequencesSQL($database)
    {
        return 'SELECT sequence_name, increment_by, start_with, min_value FROM SYS.SYSSEQUENCE';
    }

    /**
     * {@inheritdoc}
     */
    public function getSequenceNextValSQL($sequenceName)
    {
        return 'SELECT ' . $sequenceName . '.NEXTVAL';
    }

    /**
     * {@inheritdoc}
     */
    public function supportsSequences()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
    {
        return 'TIMESTAMP WITH TIME ZONE';
    }

1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
    /**
     * {@inheritdoc}
     */
    public function getVarcharDefaultLength()
    {
        return 1;
    }

    /**
     * {@inheritdoc}
     */
    public function getVarcharMaxLength()
    {
        return 32767;
    }

    /**
     * {@inheritdoc}
     */
    public function hasNativeGuidType()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function prefersIdentityColumns()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function supportsCommentOnStatement()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function supportsIdentityColumns()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
    {
Steve Müller's avatar
Steve Müller committed
1307
        $unsigned      = ! empty($columnDef['unsigned']) ? 'UNSIGNED ' : '';
1308 1309 1310 1311 1312 1313 1314 1315
        $autoincrement = ! empty($columnDef['autoincrement']) ? ' IDENTITY' : '';

        return $unsigned . $columnDef['integer_type'] . $autoincrement;
    }

    /**
     * {@inheritdoc}
     */
1316
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
1317 1318
    {
        $columnListSql = $this->getColumnDeclarationListSQL($columns);
1319
        $indexSql      = [];
1320

1321
        if (! empty($options['uniqueConstraints'])) {
1322 1323 1324 1325 1326
            foreach ((array) $options['uniqueConstraints'] as $name => $definition) {
                $columnListSql .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
            }
        }

1327 1328
        if (! empty($options['indexes'])) {
            /** @var Index $index */
1329 1330
            foreach ((array) $options['indexes'] as $index) {
                $indexSql[] = $this->getCreateIndexSQL($index, $tableName);
1331 1332 1333
            }
        }

1334
        if (! empty($options['primary'])) {
1335 1336 1337 1338 1339 1340 1341 1342 1343
            $flags = '';

            if (isset($options['primary_index']) && $options['primary_index']->hasFlag('clustered')) {
                $flags = ' CLUSTERED ';
            }

            $columnListSql .= ', PRIMARY KEY' . $flags . ' (' . implode(', ', array_unique(array_values((array) $options['primary']))) . ')';
        }

1344
        if (! empty($options['foreignKeys'])) {
1345 1346 1347 1348 1349 1350 1351 1352
            foreach ((array) $options['foreignKeys'] as $definition) {
                $columnListSql .= ', ' . $this->getForeignKeyDeclarationSQL($definition);
            }
        }

        $query = 'CREATE TABLE ' . $tableName . ' (' . $columnListSql;
        $check = $this->getCheckDeclarationSQL($columns);

1353
        if (! empty($check)) {
1354 1355 1356 1357 1358
            $query .= ', ' . $check;
        }

        $query .= ')';

1359
        return array_merge([$query], $indexSql);
1360 1361 1362 1363 1364 1365 1366 1367
    }

    /**
     * {@inheritdoc}
     */
    protected function _getTransactionIsolationLevelSQL($level)
    {
        switch ($level) {
1368
            case TransactionIsolationLevel::READ_UNCOMMITTED:
1369
                return '0';
1370
            case TransactionIsolationLevel::READ_COMMITTED:
1371
                return '1';
1372
            case TransactionIsolationLevel::REPEATABLE_READ:
1373
                return '2';
1374
            case TransactionIsolationLevel::SERIALIZABLE:
1375
                return '3';
1376
            default:
1377
                throw new InvalidArgumentException('Invalid isolation level:' . $level);
1378 1379 1380 1381 1382 1383 1384 1385
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function doModifyLimitQuery($query, $limit, $offset)
    {
1386
        $limitOffsetClause = $this->getTopClauseSQL($limit, $offset);
1387

Sergei Morozov's avatar
Sergei Morozov committed
1388 1389 1390 1391
        if ($limitOffsetClause === '') {
            return $query;
        }

1392
        if (preg_match('/^\s*(SELECT\s+(DISTINCT\s+)?)(.*)/i', $query, $matches) === 0) {
Sergei Morozov's avatar
Sergei Morozov committed
1393 1394 1395 1396
            return $query;
        }

        return $matches[1] . $limitOffsetClause . ' ' . $matches[3];
1397
    }
1398

1399 1400
    private function getTopClauseSQL(?int $limit, ?int $offset) : string
    {
1401
        if ($offset > 0) {
1402
            return sprintf('TOP %s START AT %d', $limit ?? 'ALL', $offset + 1);
1403 1404
        }

1405
        return $limit === null ? '' : 'TOP ' . $limit;
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
    }

    /**
     * Return the INDEX query section dealing with non-standard
     * SQL Anywhere options.
     *
     * @param Index $index Index definition
     *
     * @return string
     */
    protected function getAdvancedIndexOptionsSQL(Index $index)
    {
1418 1419 1420 1421 1422 1423
        if ($index->hasFlag('with_nulls_distinct') && $index->hasFlag('with_nulls_not_distinct')) {
            throw new UnexpectedValueException(
                'An Index can either have a "with_nulls_distinct" or "with_nulls_not_distinct" flag but not both.'
            );
        }

1424 1425
        $sql = '';

1426
        if (! $index->isPrimary() && $index->hasFlag('for_olap_workload')) {
1427 1428 1429
            $sql .= ' FOR OLAP WORKLOAD';
        }

1430 1431 1432 1433 1434 1435 1436 1437
        if (! $index->isPrimary() && $index->isUnique() && $index->hasFlag('with_nulls_not_distinct')) {
            return ' WITH NULLS NOT DISTINCT' . $sql;
        }

        if (! $index->isPrimary() && $index->isUnique() && $index->hasFlag('with_nulls_distinct')) {
            return ' WITH NULLS DISTINCT' . $sql;
        }

1438 1439 1440
        return $sql;
    }

Steve Müller's avatar
Steve Müller committed
1441 1442 1443 1444 1445 1446
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        return $fixed
1447 1448
            ? 'BINARY(' . ($length > 0 ? $length : $this->getBinaryDefaultLength()) . ')'
            : 'VARBINARY(' . ($length > 0 ? $length : $this->getBinaryDefaultLength()) . ')';
Steve Müller's avatar
Steve Müller committed
1449 1450
    }

Steve Müller's avatar
Steve Müller committed
1451 1452 1453 1454 1455 1456 1457 1458
    /**
     * Returns the SQL snippet for creating a table constraint.
     *
     * @param Constraint  $constraint The table constraint to create the SQL snippet for.
     * @param string|null $name       The table constraint name to use if any.
     *
     * @return string
     *
1459
     * @throws InvalidArgumentException If the given table constraint type is not supported by this method.
Steve Müller's avatar
Steve Müller committed
1460 1461 1462 1463 1464 1465 1466
     */
    protected function getTableConstraintDeclarationSQL(Constraint $constraint, $name = null)
    {
        if ($constraint instanceof ForeignKeyConstraint) {
            return $this->getForeignKeyDeclarationSQL($constraint);
        }

1467 1468
        if (! $constraint instanceof Index) {
            throw new InvalidArgumentException('Unsupported constraint type: ' . get_class($constraint));
Steve Müller's avatar
Steve Müller committed
1469 1470
        }

1471 1472
        if (! $constraint->isPrimary() && ! $constraint->isUnique()) {
            throw new InvalidArgumentException(
Steve Müller's avatar
Steve Müller committed
1473 1474 1475 1476 1477 1478 1479 1480
                'Can only create primary, unique or foreign key constraint declarations, no common index declarations ' .
                'with getTableConstraintDeclarationSQL().'
            );
        }

        $constraintColumns = $constraint->getQuotedColumns($this);

        if (empty($constraintColumns)) {
1481
            throw new InvalidArgumentException("Incomplete definition. 'columns' required.");
Steve Müller's avatar
Steve Müller committed
1482 1483 1484 1485 1486
        }

        $sql   = '';
        $flags = '';

1487
        if (! empty($name)) {
1488 1489
            $name = new Identifier($name);
            $sql .= 'CONSTRAINT ' . $name->getQuotedName($this) . ' ';
Steve Müller's avatar
Steve Müller committed
1490 1491 1492 1493 1494 1495 1496
        }

        if ($constraint->hasFlag('clustered')) {
            $flags = 'CLUSTERED ';
        }

        if ($constraint->isPrimary()) {
1497
            return $sql . 'PRIMARY KEY ' . $flags . '(' . $this->getIndexFieldDeclarationListSQL($constraintColumns) . ')';
Steve Müller's avatar
Steve Müller committed
1498 1499
        }

1500
        return $sql . 'UNIQUE ' . $flags . '(' . $this->getIndexFieldDeclarationListSQL($constraintColumns) . ')';
Steve Müller's avatar
Steve Müller committed
1501 1502
    }

1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
    /**
     * {@inheritdoc}
     */
    protected function getCreateIndexSQLFlags(Index $index)
    {
        $type = '';
        if ($index->hasFlag('virtual')) {
            $type .= 'VIRTUAL ';
        }

        if ($index->isUnique()) {
            $type .= 'UNIQUE ';
        }

        if ($index->hasFlag('clustered')) {
            $type .= 'CLUSTERED ';
        }

        return $type;
    }

1524 1525 1526 1527 1528
    /**
     * {@inheritdoc}
     */
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
    {
1529
        return ['ALTER INDEX ' . $oldIndexName . ' ON ' . $tableName . ' RENAME TO ' . $index->getQuotedName($this)];
1530 1531
    }

1532 1533 1534 1535 1536
    /**
     * {@inheritdoc}
     */
    protected function getReservedKeywordsClass()
    {
1537
        return Keywords\SQLAnywhereKeywords::class;
1538 1539 1540 1541 1542 1543 1544 1545
    }

    /**
     * {@inheritdoc}
     */
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
    {
        return $fixed
1546 1547
            ? ($length > 0 ? 'CHAR(' . $length . ')' : 'CHAR(' . $this->getVarcharDefaultLength() . ')')
            : ($length > 0 ? 'VARCHAR(' . $length . ')' : 'VARCHAR(' . $this->getVarcharDefaultLength() . ')');
1548 1549 1550 1551 1552 1553 1554
    }

    /**
     * {@inheritdoc}
     */
    protected function initializeDoctrineTypeMappings()
    {
1555
        $this->doctrineTypeMapping = [
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
            'bigint'                   => 'bigint',
            'binary'                   => 'binary',
            'bit'                      => 'boolean',
            'char'                     => 'string',
            'decimal'                  => 'decimal',
            'date'                     => 'date',
            'datetime'                 => 'datetime',
            'double'                   => 'float',
            'float'                    => 'float',
            'image'                    => 'blob',
            'int'                      => 'integer',
            'integer'                  => 'integer',
            'long binary'              => 'blob',
            'long nvarchar'            => 'text',
            'long varbit'              => 'text',
            'long varchar'             => 'text',
            'money'                    => 'decimal',
            'nchar'                    => 'string',
            'ntext'                    => 'text',
            'numeric'                  => 'decimal',
            'nvarchar'                 => 'string',
            'smalldatetime'            => 'datetime',
            'smallint'                 => 'smallint',
            'smallmoney'               => 'decimal',
            'text'                     => 'text',
            'time'                     => 'time',
            'timestamp'                => 'datetime',
1583
            'timestamp with time zone' => 'datetime',
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
            'tinyint'                  => 'smallint',
            'uniqueidentifier'         => 'guid',
            'uniqueidentifierstr'      => 'guid',
            'unsigned bigint'          => 'bigint',
            'unsigned int'             => 'integer',
            'unsigned smallint'        => 'smallint',
            'unsigned tinyint'         => 'smallint',
            'varbinary'                => 'binary',
            'varbit'                   => 'string',
            'varchar'                  => 'string',
            'xml'                      => 'text',
1595
        ];
1596 1597
    }
}