diff --git a/.appveyor.yml b/.appveyor.yml index 546ae92e554..636c269d846 100644 --- a/.appveyor.yml +++ b/.appveyor.yml @@ -68,8 +68,8 @@ install: Add-Content php.ini "`n extension=php_curl.dll" Add-Content php.ini "`n curl.cainfo=C:\tools\cacert\bundle.pem" - # Get and install the MSSQL DLL's - $DLLVersion = "5.2.0" + # Get and install the latest stable sqlsrv DLL's + $DLLVersion = (Invoke-WebRequest "https://pecl.php.net/rest/r/sqlsrv/stable.txt").Content cd c:\tools\php\ext $source = "https://windows.php.net/downloads/pecl/releases/sqlsrv/$($DLLVersion)/php_sqlsrv-$($DLLVersion)-$($env:php)-nts-vc15-x64.zip" $destination = "c:\tools\php\ext\php_sqlsrv-$($DLLVersion)-$($env:php)-nts-vc15-x64.zip" diff --git a/.doctrine-project.json b/.doctrine-project.json new file mode 100644 index 00000000000..9fb3d836c74 --- /dev/null +++ b/.doctrine-project.json @@ -0,0 +1,49 @@ +{ + "active": true, + "name": "Database Abstraction Layer", + "shortName": "DBAL", + "slug": "dbal", + "docsSlug": "doctrine-dbal", + "versions": [ + { + "name": "3.0", + "branchName": "develop", + "slug": "latest", + "upcoming": true + }, + { + "name": "2.9", + "branchName": "master", + "slug": "2.9", + "upcoming": true + }, + { + "name": "2.8", + "branchName": "2.8", + "slug": "2.8", + "current": true, + "aliases": [ + "current", + "stable" + ] + }, + { + "name": "2.7", + "branchName": "2.7", + "slug": "2.7", + "maintained": false + }, + { + "name": "2.6", + "branchName": "2.6", + "slug": "2.6", + "maintained": false + }, + { + "name": "2.5", + "branchName": "2.5", + "slug": "2.5", + "maintained": false + } + ] +} diff --git a/.gitattributes b/.gitattributes index d15eb35f48f..5bbaf359701 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,12 +1,15 @@ -/tests export-ignore +/.appveyor.yml export-ignore +/.gitattributes export-ignore +/.github export-ignore +/.gitignore export-ignore +/.scrutinizer.yml export-ignore +/.travis.yml export-ignore +/build.properties export-ignore +/build.xml export-ignore +/composer.lock export-ignore /docs export-ignore -.gitattributes export-ignore -.gitignore export-ignore -.appveyor.yml export-ignore -.travis.yml export-ignore -build.properties export-ignore -build.xml export-ignore -phpunit.xml.dist export-ignore -run-all.sh export-ignore /phpcs.xml.dist export-ignore -/composer.lock export-ignore +/phpstan.neon.dist export-ignore +/phpunit.xml.dist export-ignore +/run-all.sh export-ignore +/tests export-ignore diff --git a/.github/ISSUE_TEMPLATE/BC_Break.md b/.github/ISSUE_TEMPLATE/BC_Break.md index fe2f6eac490..c372e7fefd5 100644 --- a/.github/ISSUE_TEMPLATE/BC_Break.md +++ b/.github/ISSUE_TEMPLATE/BC_Break.md @@ -1,6 +1,6 @@ --- name: 💥 BC Break -about: Have you encountered an issue during upgrade? 💣 +about: Have you encountered an issue during an upgrade? 💣 --- + -#### Previous behavior +#### Previous behaviour - + #### Current behavior - + #### How to reproduce diff --git a/.github/ISSUE_TEMPLATE/Bug.md b/.github/ISSUE_TEMPLATE/Bug.md index b0767e8c790..2e7d29ca027 100644 --- a/.github/ISSUE_TEMPLATE/Bug.md +++ b/.github/ISSUE_TEMPLATE/Bug.md @@ -14,11 +14,11 @@ about: Something is broken? 🔨 #### Summary - + -#### Current behavior +#### Current behaviour - + #### How to reproduce @@ -28,7 +28,7 @@ If possible, also add a code snippet with relevant configuration, driver/platfor Adding a failing Unit or Functional Test would help us a lot - you can submit one in a Pull Request separately, referencing this bug report. --> -#### Expected behavior +#### Expected behaviour - + diff --git a/.github/ISSUE_TEMPLATE/Support_Question.md b/.github/ISSUE_TEMPLATE/Support_Question.md index 59a63fda112..d5bccbd15fa 100644 --- a/.github/ISSUE_TEMPLATE/Support_Question.md +++ b/.github/ISSUE_TEMPLATE/Support_Question.md @@ -10,7 +10,7 @@ about: Have a problem that you can't figure out? 🤔 | Version | x.y.z diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 332d6db0bb8..d88b155d0a0 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -8,4 +8,4 @@ #### Summary - + diff --git a/.gitignore b/.gitignore index c6aebb3b279..835be8e8487 100644 --- a/.gitignore +++ b/.gitignore @@ -4,7 +4,7 @@ reports/ dist/ download/ vendor/ -*.phpunit.xml +/*.phpunit.xml /phpunit.xml /.phpcs-cache /phpstan.neon diff --git a/.scrutinizer.yml b/.scrutinizer.yml index 125becc5263..68b7f344399 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -21,7 +21,7 @@ before_commands: tools: external_code_coverage: timeout: 3600 - runs: 22 # 18x Travis (jobs with COVERAGE=yes) + 3x AppVeyor (jobs with coverage=yes) + 1x ContinuousPHP + runs: 30 # 25x Travis (jobs with COVERAGE=yes) + 3x AppVeyor (jobs with coverage=yes) + 2x ContinuousPHP filter: excluded_paths: diff --git a/.travis.yml b/.travis.yml index 7bf23c9c0b3..6be26170ae5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,16 +7,6 @@ cache: - vendor - $HOME/.composer/cache -php: - - 7.1 - - 7.2 - - nightly - -env: - - DB=sqlite - - DB=mysql - - DB=mysqli - before_install: - | if [ "x$COVERAGE" != "xyes" ]; then @@ -53,134 +43,149 @@ after_script: jobs: allow_failures: - php: nightly - - stage: Coding standard - - env: DB=pgsql POSTGRESQL_VERSION=11.0 - - exclude: - - php: 7.1 - env: DB=sqlite - - php: 7.1 - env: DB=mysql - - php: 7.1 - env: DB=mysqli include: - stage: Test php: 7.1 - env: DB=sqlite COVERAGE=yes - + env: DB=mysql MYSQL_VERSION=8.0 + dist: xenial + sudo: required + before_script: + - bash ./tests/travis/install-mysql-8.0.sh - stage: Test php: 7.1 - env: DB=mysql COVERAGE=yes - + env: DB=mysqli MYSQL_VERSION=8.0 + dist: xenial + sudo: required + before_script: + - bash ./tests/travis/install-mysql-8.0.sh - stage: Test php: 7.1 - env: DB=mysqli COVERAGE=yes - + env: DB=mariadb MARIADB_VERSION=10.3 + addons: + mariadb: 10.3 - stage: Test php: 7.1 - env: DB=mysql MYSQL_VERSION=5.7 COVERAGE=yes + env: DB=mariadb.mysqli MARIADB_VERSION=10.3 + addons: + mariadb: 10.3 + - stage: Test + php: 7.1 + env: DB=pgsql POSTGRESQL_VERSION=11.0 sudo: required + services: + - docker before_script: - - bash ./tests/travis/install-mysql-5.7.sh + - bash ./tests/travis/install-postgres-11.sh - stage: Test - php: 7.2 - env: DB=mysql MYSQL_VERSION=5.7 + php: 7.1 + env: DB=sqlite + - stage: Test + php: 7.1 + env: DB=sqlsrv sudo: required + services: + - docker before_script: - - bash ./tests/travis/install-mysql-5.7.sh + - bash ./tests/travis/install-mssql-sqlsrv.sh + - bash ./tests/travis/install-mssql.sh - stage: Test - php: nightly - env: DB=mysql MYSQL_VERSION=5.7 + php: 7.1 + env: DB=pdo_sqlsrv sudo: required + services: + - docker before_script: - - bash ./tests/travis/install-mysql-5.7.sh - + - bash ./tests/travis/install-mssql-pdo_sqlsrv.sh + - bash ./tests/travis/install-mssql.sh - stage: Test php: 7.1 - env: DB=mysqli MYSQL_VERSION=5.7 COVERAGE=yes + env: DB=ibm_db2 sudo: required + services: + - docker before_script: - - bash ./tests/travis/install-mysql-5.7.sh + - bash ./tests/travis/install-db2.sh + - bash ./tests/travis/install-db2-ibm_db2.sh + - stage: Test + php: 7.1 + env: DB=sqlite DEPENDENCIES=low + install: + - travis_retry composer update --prefer-dist --prefer-lowest - stage: Test php: 7.2 - env: DB=mysqli MYSQL_VERSION=5.7 + env: DB=mysql COVERAGE=yes + - stage: Test + php: 7.2 + env: DB=mysql MYSQL_VERSION=5.7 COVERAGE=yes sudo: required before_script: - bash ./tests/travis/install-mysql-5.7.sh - stage: Test - php: nightly - env: DB=mysqli MYSQL_VERSION=5.7 + php: 7.2 + env: DB=mysql MYSQL_VERSION=8.0 COVERAGE=yes + dist: xenial sudo: required before_script: - - bash ./tests/travis/install-mysql-5.7.sh - + - bash ./tests/travis/install-mysql-8.0.sh - stage: Test - php: 7.1 - env: DB=mariadb MARIADB_VERSION=10.0 COVERAGE=yes - addons: - mariadb: 10.0 + php: 7.2 + env: DB=mysqli COVERAGE=yes - stage: Test php: 7.2 - env: DB=mariadb MARIADB_VERSION=10.0 - addons: - mariadb: 10.0 + env: DB=mysqli MYSQL_VERSION=5.7 COVERAGE=yes + sudo: required + before_script: + - bash ./tests/travis/install-mysql-5.7.sh - stage: Test - php: nightly - env: DB=mariadb MARIADB_VERSION=10.0 + php: 7.2 + env: DB=mysqli MYSQL_VERSION=8.0 COVERAGE=yes + dist: xenial + sudo: required + before_script: + - bash ./tests/travis/install-mysql-8.0.sh + - stage: Test + php: 7.2 + env: DB=mariadb MARIADB_VERSION=10.0 COVERAGE=yes addons: mariadb: 10.0 - - stage: Test - php: 7.1 + php: 7.2 env: DB=mariadb MARIADB_VERSION=10.1 COVERAGE=yes addons: mariadb: 10.1 - stage: Test php: 7.2 - env: DB=mariadb MARIADB_VERSION=10.1 - addons: - mariadb: 10.1 - - stage: Test - php: nightly - env: DB=mariadb MARIADB_VERSION=10.1 - addons: - mariadb: 10.1 - - - stage: Test - php: 7.1 env: DB=mariadb MARIADB_VERSION=10.2 COVERAGE=yes addons: mariadb: 10.2 - stage: Test php: 7.2 - env: DB=mariadb MARIADB_VERSION=10.2 + env: DB=mariadb MARIADB_VERSION=10.3 COVERAGE=yes addons: - mariadb: 10.2 + mariadb: 10.3 - stage: Test - php: nightly - env: DB=mariadb MARIADB_VERSION=10.2 + php: 7.2 + env: DB=mariadb.mysqli MARIADB_VERSION=10.0 COVERAGE=yes addons: - mariadb: 10.2 - + mariadb: 10.0 - stage: Test - php: 7.1 - env: DB=mariadb.mysqli MARIADB_VERSION=10.2 COVERAGE=yes + php: 7.2 + env: DB=mariadb.mysqli MARIADB_VERSION=10.1 COVERAGE=yes addons: - mariadb: 10.2 + mariadb: 10.1 - stage: Test php: 7.2 - env: DB=mariadb.mysqli MARIADB_VERSION=10.2 + env: DB=mariadb.mysqli MARIADB_VERSION=10.2 COVERAGE=yes addons: mariadb: 10.2 - stage: Test - php: nightly - env: DB=mariadb.mysqli MARIADB_VERSION=10.2 + php: 7.2 + env: DB=mariadb.mysqli MARIADB_VERSION=10.3 COVERAGE=yes addons: - mariadb: 10.2 - + mariadb: 10.3 - stage: Test - php: 7.1 + php: 7.2 env: DB=pgsql POSTGRESQL_VERSION=9.2 COVERAGE=yes services: - postgresql @@ -188,21 +193,6 @@ jobs: postgresql: "9.2" - stage: Test php: 7.2 - env: DB=pgsql POSTGRESQL_VERSION=9.2 - services: - - postgresql - addons: - postgresql: "9.2" - - stage: Test - php: nightly - env: DB=pgsql POSTGRESQL_VERSION=9.2 - services: - - postgresql - addons: - postgresql: "9.2" - - - stage: Test - php: 7.1 env: DB=pgsql POSTGRESQL_VERSION=9.3 COVERAGE=yes services: - postgresql @@ -210,21 +200,6 @@ jobs: postgresql: "9.3" - stage: Test php: 7.2 - env: DB=pgsql POSTGRESQL_VERSION=9.3 - services: - - postgresql - addons: - postgresql: "9.3" - - stage: Test - php: nightly - env: DB=pgsql POSTGRESQL_VERSION=9.3 - services: - - postgresql - addons: - postgresql: "9.3" - - - stage: Test - php: 7.1 env: DB=pgsql POSTGRESQL_VERSION=9.4 COVERAGE=yes services: - postgresql @@ -232,21 +207,6 @@ jobs: postgresql: "9.4" - stage: Test php: 7.2 - env: DB=pgsql POSTGRESQL_VERSION=9.4 - services: - - postgresql - addons: - postgresql: "9.4" - - stage: Test - php: nightly - env: DB=pgsql POSTGRESQL_VERSION=9.4 - services: - - postgresql - addons: - postgresql: "9.4" - - - stage: Test - php: 7.1 env: DB=pgsql POSTGRESQL_VERSION=9.5 COVERAGE=yes services: - postgresql @@ -254,21 +214,6 @@ jobs: postgresql: "9.5" - stage: Test php: 7.2 - env: DB=pgsql POSTGRESQL_VERSION=9.5 - services: - - postgresql - addons: - postgresql: "9.5" - - stage: Test - php: nightly - env: DB=pgsql POSTGRESQL_VERSION=9.5 - services: - - postgresql - addons: - postgresql: "9.5" - - - stage: Test - php: 7.1 env: DB=pgsql POSTGRESQL_VERSION=9.6 COVERAGE=yes services: - postgresql @@ -276,21 +221,6 @@ jobs: postgresql: "9.6" - stage: Test php: 7.2 - env: DB=pgsql POSTGRESQL_VERSION=9.6 - services: - - postgresql - addons: - postgresql: "9.6" - - stage: Test - php: nightly - env: DB=pgsql POSTGRESQL_VERSION=9.6 - services: - - postgresql - addons: - postgresql: "9.6" - - - stage: Test - php: 7.1 env: DB=pgsql POSTGRESQL_VERSION=10.0 COVERAGE=yes sudo: required services: @@ -301,110 +231,146 @@ jobs: - bash ./tests/travis/install-postgres-10.sh - stage: Test php: 7.2 - env: DB=pgsql POSTGRESQL_VERSION=10.0 + env: DB=pgsql POSTGRESQL_VERSION=11.0 COVERAGE=yes sudo: required services: - - postgresql - addons: - postgresql: "9.6" + - docker before_script: - - bash ./tests/travis/install-postgres-10.sh + - bash ./tests/travis/install-postgres-11.sh - stage: Test - php: nightly - env: DB=pgsql POSTGRESQL_VERSION=10.0 + php: 7.2 + env: DB=sqlite COVERAGE=yes + - stage: Test + php: 7.2 + env: DB=sqlsrv COVERAGE=yes sudo: required services: - - postgresql - addons: - postgresql: "9.6" + - docker before_script: - - bash ./tests/travis/install-postgres-10.sh - + - bash ./tests/travis/install-mssql-sqlsrv.sh + - bash ./tests/travis/install-mssql.sh - stage: Test - php: 7.1 - env: DB=pgsql POSTGRESQL_VERSION=11.0 + php: 7.2 + env: DB=pdo_sqlsrv COVERAGE=yes sudo: required services: - docker before_script: - - bash ./tests/travis/install-postgres-11.sh + - bash ./tests/travis/install-mssql-pdo_sqlsrv.sh + - bash ./tests/travis/install-mssql.sh - stage: Test php: 7.2 - env: DB=pgsql POSTGRESQL_VERSION=11.0 + env: DB=ibm_db2 COVERAGE=yes sudo: required services: - docker before_script: - - bash ./tests/travis/install-postgres-11.sh + - bash ./tests/travis/install-db2.sh + - bash ./tests/travis/install-db2-ibm_db2.sh - stage: Test - php: nightly + php: 7.3 + env: DB=mysql MYSQL_VERSION=5.7 + sudo: required + before_script: + - bash ./tests/travis/install-mysql-5.7.sh + - stage: Test + php: 7.3 + env: DB=mysqli MYSQL_VERSION=5.7 + sudo: required + before_script: + - bash ./tests/travis/install-mysql-5.7.sh + - stage: Test + php: 7.3 + env: DB=mariadb MARIADB_VERSION=10.3 + addons: + mariadb: 10.3 + - stage: Test + php: 7.3 + env: DB=mariadb.mysqli MARIADB_VERSION=10.3 + addons: + mariadb: 10.3 + - stage: Test + php: 7.3 env: DB=pgsql POSTGRESQL_VERSION=11.0 sudo: required services: - docker before_script: - bash ./tests/travis/install-postgres-11.sh - - stage: Test - env: DB=sqlsrv COVERAGE=yes + php: 7.3 + env: DB=sqlite + - stage: Test + php: 7.3 + env: DB=sqlsrv sudo: required services: - docker before_script: - - bash ./tests/travis/install-mssql-$DB.sh + - bash ./tests/travis/install-mssql-sqlsrv.sh - bash ./tests/travis/install-mssql.sh - stage: Test - php: 7.2 - env: DB=sqlsrv + php: 7.3 + env: DB=pdo_sqlsrv sudo: required services: - docker before_script: - - bash ./tests/travis/install-mssql-$DB.sh + - bash ./tests/travis/install-mssql-pdo_sqlsrv.sh - bash ./tests/travis/install-mssql.sh - - stage: Test - php: 7.1 - env: DB=pdo_sqlsrv COVERAGE=yes + php: nightly + env: DB=mysql MYSQL_VERSION=8.0 + dist: xenial sudo: required - services: - - docker before_script: - - bash ./tests/travis/install-mssql-$DB.sh - - bash ./tests/travis/install-mssql.sh + - bash ./tests/travis/install-mysql-8.0.sh - stage: Test - php: 7.2 - env: DB=pdo_sqlsrv + php: nightly + env: DB=mysqli MYSQL_VERSION=8.0 + dist: xenial + sudo: required + before_script: + - bash ./tests/travis/install-mysql-8.0.sh + - stage: Test + php: nightly + env: DB=mariadb MARIADB_VERSION=10.3 + addons: + mariadb: 10.3 + - stage: Test + php: nightly + env: DB=mariadb.mysqli MARIADB_VERSION=10.3 + addons: + mariadb: 10.3 + - stage: Test + php: nightly + env: DB=pgsql POSTGRESQL_VERSION=11.0 sudo: required services: - docker before_script: - - bash ./tests/travis/install-mssql-$DB.sh - - bash ./tests/travis/install-mssql.sh - + - bash ./tests/travis/install-postgres-11.sh - stage: Test - env: DB=ibm_db2 COVERAGE=yes + php: nightly + env: DB=sqlite + - stage: Test + php: nightly + env: DB=sqlsrv sudo: required services: - docker before_script: - - bash ./tests/travis/install-db2.sh - - bash ./tests/travis/install-db2-$DB.sh + - bash ./tests/travis/install-mssql-sqlsrv.sh + - bash ./tests/travis/install-mssql.sh - stage: Test - php: 7.2 - env: DB=ibm_db2 + php: nightly + env: DB=pdo_sqlsrv sudo: required services: - docker before_script: - - bash ./tests/travis/install-db2.sh - - bash ./tests/travis/install-db2-$DB.sh - - - stage: Test - php: 7.1 - env: DB=sqlite DEPENDENCIES=low - install: - - travis_retry composer update --prefer-dist --prefer-lowest + - bash ./tests/travis/install-mssql-pdo_sqlsrv.sh + - bash ./tests/travis/install-mssql.sh - stage: Test if: type = cron @@ -415,27 +381,13 @@ jobs: - travis_retry composer update --prefer-dist - stage: Code Quality + php: 7.2 env: DB=none STATIC_ANALYSIS - install: travis_retry composer update --prefer-dist - script: vendor/bin/phpstan analyse - - - stage: Pull request coding standard - if: type = pull_request - php: 7.1 install: travis_retry composer install --prefer-dist - script: - - | - if [ $TRAVIS_BRANCH != "master" ]; then - git remote set-branches --add origin $TRAVIS_BRANCH; - git fetch origin $TRAVIS_BRANCH; - fi - - git merge-base origin/$TRAVIS_BRANCH $TRAVIS_PULL_REQUEST_SHA || git fetch origin +refs/pull/$TRAVIS_PULL_REQUEST/merge --unshallow - - wget https://github.com/diff-sniffer/git/releases/download/0.1.0/git-phpcs.phar - - php git-phpcs.phar origin/$TRAVIS_BRANCH...$TRAVIS_PULL_REQUEST_SHA + script: vendor/bin/phpstan analyse - stage: Coding standard - if: NOT type = pull_request - php: 7.1 + php: 7.2 install: travis_retry composer install --prefer-dist script: - ./vendor/bin/phpcs diff --git a/README.md b/README.md index 76e95be0c63..7bab7586f04 100644 --- a/README.md +++ b/README.md @@ -40,13 +40,13 @@ $table->addUniqueIndex( ## Original README from doctrine/dbal: -| [Master][Master] | [2.7][2.7] | [2.6][2.6] | [Develop][develop] | -|:----------------:|:----------:|:----------:|:--------------:| -| [![Build status][Master image]][Master] | [![Build status][2.7 image]][2.7] | [![Build status][2.6 image]][2.6] | [![Build status][develop image]][develop] | -| [![Build Status][ContinuousPHP image]][ContinuousPHP] | [![Build Status][ContinuousPHP 2.7 image]][ContinuousPHP] | [![Build Status][ContinuousPHP 2.6 image]][ContinuousPHP] | [![Build Status][ContinuousPHP develop image]][ContinuousPHP] | -| [![Code Coverage][Coverage image]][Scrutinizer Master] | [![Code Coverage][Coverage 2.7 image]][Scrutinizer 2.7] | [![Code Coverage][Coverage 2.6 image]][Scrutinizer 2.6] | [![Code Coverage][Coverage develop image]][Scrutinizer develop] | -| [![Code Quality][Quality image]][Scrutinizer Master] | [![Code Quality][Quality 2.7 image]][Scrutinizer 2.7] | [![Code Quality][Quality 2.6 image]][Scrutinizer 2.6] | [![Code Quality][Quality develop image]][Scrutinizer develop] | -| [![AppVeyor][AppVeyor master image]][AppVeyor master] | [![AppVeyor][AppVeyor 2.7 image]][AppVeyor 2.7] | | [![AppVeyor][AppVeyor develop image]][AppVeyor develop] +| | [Master][Master] | [2.8][2.8] | [Develop][develop] | +|:----------------:|:----------:|:------------------:| +| [![Build status][Master image]][Master] | [![Build status][2.8 image]][2.8] | [![Build status][develop image]][develop] | +| [![Build Status][ContinuousPHP image]][ContinuousPHP] | [![Build Status][ContinuousPHP 2.8 image]][ContinuousPHP] | [![Build Status][ContinuousPHP develop image]][ContinuousPHP] | +| [![Code Coverage][Coverage image]][Scrutinizer Master] | [![Code Coverage][Coverage 2.8 image]][Scrutinizer 2.8] | [![Code Coverage][Coverage develop image]][Scrutinizer develop] | +| [![Code Quality][Quality image]][Scrutinizer Master] | [![Code Quality][Quality 2.8 image]][Scrutinizer 2.8] | [![Code Quality][Quality develop image]][Scrutinizer develop] | +| [![AppVeyor][AppVeyor master image]][AppVeyor master] | [![AppVeyor][AppVeyor 2.8 image]][AppVeyor 2.8] | [![AppVeyor][AppVeyor develop image]][AppVeyor develop] Powerful database abstraction layer with many features for database schema introspection, schema management and PDO abstraction. @@ -66,20 +66,14 @@ Powerful database abstraction layer with many features for database schema intro [AppVeyor master]: https://ci.appveyor.com/project/doctrine/dbal/branch/master [AppVeyor master image]: https://ci.appveyor.com/api/projects/status/i88kitq8qpbm0vie/branch/master?svg=true [ContinuousPHP]: https://continuousphp.com/git-hub/doctrine/dbal - [2.7 image]: https://img.shields.io/travis/doctrine/dbal/2.7.svg?style=flat-square - [Coverage 2.7 image]: https://img.shields.io/scrutinizer/coverage/g/doctrine/dbal/2.7.svg?style=flat-square - [Quality 2.7 image]: https://img.shields.io/scrutinizer/g/doctrine/dbal/2.7.svg?style=flat-square - [ContinuousPHP 2.7 image]: https://img.shields.io/continuousphp/git-hub/doctrine/dbal/2.7.svg?style=flat-square - [2.7]: https://github.com/doctrine/dbal/tree/2.7 - [Scrutinizer 2.7]: https://scrutinizer-ci.com/g/doctrine/dbal/?branch=2.7 - [AppVeyor 2.7]: https://ci.appveyor.com/project/doctrine/dbal/branch/2.7 - [AppVeyor 2.7 image]: https://ci.appveyor.com/api/projects/status/i88kitq8qpbm0vie/branch/2.7?svg=true - [2.6 image]: https://img.shields.io/travis/doctrine/dbal/2.6.svg?style=flat-square - [Coverage 2.6 image]: https://img.shields.io/scrutinizer/coverage/g/doctrine/dbal/2.6.svg?style=flat-square - [Quality 2.6 image]: https://img.shields.io/scrutinizer/g/doctrine/dbal/2.6.svg?style=flat-square - [ContinuousPHP 2.6 image]: https://img.shields.io/continuousphp/git-hub/doctrine/dbal/2.6.svg?style=flat-square - [2.6]: https://github.com/doctrine/dbal/tree/2.6 - [Scrutinizer 2.6]: https://scrutinizer-ci.com/g/doctrine/dbal/?branch=2.6 + [2.8 image]: https://img.shields.io/travis/doctrine/dbal/2.8.svg?style=flat-square + [Coverage 2.8 image]: https://img.shields.io/scrutinizer/coverage/g/doctrine/dbal/2.8.svg?style=flat-square + [Quality 2.8 image]: https://img.shields.io/scrutinizer/g/doctrine/dbal/2.8.svg?style=flat-square + [ContinuousPHP 2.8 image]: https://img.shields.io/continuousphp/git-hub/doctrine/dbal/2.8.svg?style=flat-square + [2.8]: https://github.com/doctrine/dbal/tree/2.8 + [Scrutinizer 2.8]: https://scrutinizer-ci.com/g/doctrine/dbal/?branch=2.8 + [AppVeyor 2.8]: https://ci.appveyor.com/project/doctrine/dbal/branch/2.8 + [AppVeyor 2.8 image]: https://ci.appveyor.com/api/projects/status/i88kitq8qpbm0vie/branch/2.8?svg=true [develop]: https://github.com/doctrine/dbal/tree/develop [develop image]: https://img.shields.io/travis/doctrine/dbal/develop.svg?style=flat-square [Coverage develop image]: https://img.shields.io/scrutinizer/coverage/g/doctrine/dbal/develop.svg?style=flat-square diff --git a/UPGRADE.md b/UPGRADE.md index 25e2747b67f..53bf9420dde 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -1,3 +1,34 @@ +# Upgrade to 2.9 + +## Deprecated `Statement::fetchColumn()` with an invalid index + +Calls to `Statement::fetchColumn()` with an invalid column index currently return `NULL`. In the future, such calls will result in a exception. + +## Deprecated `Configuration::getFilterSchemaAssetsExpression()`, `::setFilterSchemaAssetsExpression()` and `AbstractSchemaManager::getFilterSchemaAssetsExpression()`. + +Regular expression-based filters are hard to extend by combining together. Instead, you may use callback-based filers via `::getSchemaAssetsFilter()` and `::getSchemaAssetsFilter()`. Callbacks can use regular expressions internally. + +## Deprecated `Doctrine\DBAL\Types\Type::getDefaultLength()` + +This method was never used by DBAL internally. It is now deprecated and will be removed in DBAL 3.0. + +## Deprecated `Doctrine\DBAL\Types\Type::__toString()` + +Relying on string representation is discouraged and will be removed in DBAL 3.0. + +## Deprecated `NULL` value of `$offset` in LIMIT queries + +The `NULL` value of the `$offset` argument in `AbstractPlatform::(do)?ModifyLimitQuery()` methods is deprecated. If explicitly used in the method call, the absence of the offset should be indicated with a `0`. + +## Deprecated dbal:import CLI command + +The `dbal:import` CLI command has been deprecated since it only works with PDO-based drivers by relying on a non-documented behavior of the extension, and it's impossible to make it work with other drivers. +Please use other database client applications for import, e.g.: + + * For MySQL and MariaDB: `mysql [dbname] < data.sql`. + * For PostgreSQL: `psql [dbname] < data.sql`. + * For SQLite: `sqlite3 /path/to/file.db < data.sql`. + # Upgrade to 2.8 ## Deprecated usage of DB-generated UUIDs diff --git a/bin/doctrine-dbal.php b/bin/doctrine-dbal.php index 3d1131f1a42..f3e064ffd62 100644 --- a/bin/doctrine-dbal.php +++ b/bin/doctrine-dbal.php @@ -1,29 +1,12 @@ . - */ -use Symfony\Component\Console\Helper\HelperSet; use Doctrine\DBAL\Tools\Console\ConsoleRunner; +use Symfony\Component\Console\Helper\HelperSet; -$files = array(__DIR__ . '/../vendor/autoload.php', __DIR__ . '/../../../autoload.php'); +$files = [__DIR__ . '/../vendor/autoload.php', __DIR__ . '/../../../autoload.php']; $loader = null; $cwd = getcwd(); -$directories = array($cwd, $cwd . DIRECTORY_SEPARATOR . 'config'); +$directories = [$cwd, $cwd . DIRECTORY_SEPARATOR . 'config']; $configFile = null; foreach ($files as $file) { @@ -34,7 +17,7 @@ } } -if ( ! $loader) { +if (! $loader) { throw new RuntimeException('vendor/autoload.php could not be found. Did you run `php composer.phar install`?'); } @@ -46,22 +29,22 @@ } } -if ( ! file_exists($configFile)) { +if (! file_exists($configFile)) { ConsoleRunner::printCliConfigTemplate(); exit(1); } -if ( ! is_readable($configFile)) { +if (! is_readable($configFile)) { echo 'Configuration file [' . $configFile . '] does not have read permission.' . PHP_EOL; exit(1); } -$commands = array(); +$commands = []; $helperSet = require $configFile; -if ( ! $helperSet instanceof HelperSet) { +if (! $helperSet instanceof HelperSet) { foreach ($GLOBALS as $helperSetCandidate) { if ($helperSetCandidate instanceof HelperSet) { $helperSet = $helperSetCandidate; diff --git a/composer.json b/composer.json index 163d80abba8..9d5f610c2b8 100644 --- a/composer.json +++ b/composer.json @@ -1,9 +1,18 @@ { "name": "doctrine/dbal", "type": "library", - "description": "Database Abstraction Layer", - "keywords": ["dbal", "database", "persistence", "queryobject"], - "homepage": "http://www.doctrine-project.org", + "description": "Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.", + "keywords": [ + "php", + "mysql", + "pgsql", + "dbal", + "database", + "abstraction", + "persistence", + "queryobject" + ], + "homepage": "https://www.doctrine-project.org/projects/dbal.html", "license": "MIT", "authors": [ {"name": "Guilherme Blanco", "email": "guilhermeblanco@gmail.com"}, @@ -18,11 +27,10 @@ "doctrine/event-manager": "^1.0" }, "require-dev": { - "doctrine/coding-standard": "^4.0", + "doctrine/coding-standard": "^5.0", "jetbrains/phpstorm-stubs": "^2018.1.2", "phpstan/phpstan": "^0.10.1", - "phpunit/phpunit": "^7.1.2", - "phpunit/phpunit-mock-objects": "!=3.2.4,!=3.2.5", + "phpunit/phpunit": "^7.4", "symfony/console": "^2.0.5|^3.0|^4.0", "symfony/phpunit-bridge": "^3.4.5|^4.0.5" }, @@ -34,18 +42,15 @@ "sort-packages": true }, "autoload": { - "psr-0": { "Doctrine\\DBAL\\": "lib/" } + "psr-4": { "Doctrine\\DBAL\\": "lib/Doctrine/DBAL" } }, "autoload-dev": { - "psr-0": { "Doctrine\\Tests\\": "tests/" } + "psr-4": { "Doctrine\\Tests\\": "tests/Doctrine/Tests" } }, "extra": { "branch-alias": { - "dev-master": "2.8.x-dev", + "dev-master": "2.9.x-dev", "dev-develop": "3.0.x-dev" } - }, - "archive": { - "exclude": ["!vendor", "tests", "*phpunit.xml", ".appveyor.yml", ".travis.yml", "build.xml", "build.properties", "composer.phar"] } } diff --git a/composer.lock b/composer.lock index 4d74e4eb956..0c15627967d 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "69dd02e4a1e8f77823b3676b3f707ef6", + "content-hash": "1147a9427c03f98ca063806250633645", "packages": [ { "name": "doctrine/cache", @@ -270,28 +270,28 @@ }, { "name": "doctrine/coding-standard", - "version": "4.0.0", + "version": "5.0.0", "source": { "type": "git", "url": "https://github.com/doctrine/coding-standard.git", - "reference": "0469c18a1a4724c278f2879c0dd7b1fa860b52de" + "reference": "bb8de042a25c4fb59a2c55c350dc55cc00227a8c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/coding-standard/zipball/0469c18a1a4724c278f2879c0dd7b1fa860b52de", - "reference": "0469c18a1a4724c278f2879c0dd7b1fa860b52de", + "url": "https://api.github.com/repos/doctrine/coding-standard/zipball/bb8de042a25c4fb59a2c55c350dc55cc00227a8c", + "reference": "bb8de042a25c4fb59a2c55c350dc55cc00227a8c", "shasum": "" }, "require": { - "dealerdirect/phpcodesniffer-composer-installer": "^0.4.2", + "dealerdirect/phpcodesniffer-composer-installer": "^0.4.4", "php": "^7.1", - "slevomat/coding-standard": "^4.5.0", - "squizlabs/php_codesniffer": "^3.2.3" + "slevomat/coding-standard": "^4.8.0", + "squizlabs/php_codesniffer": "^3.3.2" }, "type": "phpcodesniffer-standard", "extra": { "branch-alias": { - "dev-master": "3.0.x-dev" + "dev-master": "5.0.x-dev" } }, "autoload": { @@ -313,18 +313,21 @@ "email": "st.mueller@dzh-online.de" } ], - "description": "Doctrine Coding Standard", - "homepage": "http://www.doctrine-project.org", + "description": "The Doctrine Coding Standard is a set of PHPCS rules applied to all Doctrine projects.", + "homepage": "https://www.doctrine-project.org/projects/coding-standard.html", "keywords": [ + "checks", "code", "coding", "cs", "doctrine", + "rules", "sniffer", + "sniffs", "standard", "style" ], - "time": "2018-03-03T23:49:15+00:00" + "time": "2018-09-24T19:08:56+00:00" }, { "name": "doctrine/instantiator", @@ -471,25 +474,28 @@ }, { "name": "myclabs/deep-copy", - "version": "1.7.0", + "version": "1.8.1", "source": { "type": "git", "url": "https://github.com/myclabs/DeepCopy.git", - "reference": "3b8a3a99ba1f6a3952ac2747d989303cbd6b7a3e" + "reference": "3e01bdad3e18354c3dce54466b7fbe33a9f9f7f8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/3b8a3a99ba1f6a3952ac2747d989303cbd6b7a3e", - "reference": "3b8a3a99ba1f6a3952ac2747d989303cbd6b7a3e", + "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/3e01bdad3e18354c3dce54466b7fbe33a9f9f7f8", + "reference": "3e01bdad3e18354c3dce54466b7fbe33a9f9f7f8", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0" + "php": "^7.1" + }, + "replace": { + "myclabs/deep-copy": "self.version" }, "require-dev": { "doctrine/collections": "^1.0", "doctrine/common": "^2.6", - "phpunit/phpunit": "^4.1" + "phpunit/phpunit": "^7.1" }, "type": "library", "autoload": { @@ -512,7 +518,7 @@ "object", "object graph" ], - "time": "2017-10-19T19:58:43+00:00" + "time": "2018-06-11T23:09:50+00:00" }, { "name": "nette/bootstrap", @@ -1093,22 +1099,22 @@ }, { "name": "phar-io/manifest", - "version": "1.0.1", + "version": "1.0.3", "source": { "type": "git", "url": "https://github.com/phar-io/manifest.git", - "reference": "2df402786ab5368a0169091f61a7c1e0eb6852d0" + "reference": "7761fcacf03b4d4f16e7ccb606d4879ca431fcf4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phar-io/manifest/zipball/2df402786ab5368a0169091f61a7c1e0eb6852d0", - "reference": "2df402786ab5368a0169091f61a7c1e0eb6852d0", + "url": "https://api.github.com/repos/phar-io/manifest/zipball/7761fcacf03b4d4f16e7ccb606d4879ca431fcf4", + "reference": "7761fcacf03b4d4f16e7ccb606d4879ca431fcf4", "shasum": "" }, "require": { "ext-dom": "*", "ext-phar": "*", - "phar-io/version": "^1.0.1", + "phar-io/version": "^2.0", "php": "^5.6 || ^7.0" }, "type": "library", @@ -1144,20 +1150,20 @@ } ], "description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)", - "time": "2017-03-05T18:14:27+00:00" + "time": "2018-07-08T19:23:20+00:00" }, { "name": "phar-io/version", - "version": "1.0.1", + "version": "2.0.1", "source": { "type": "git", "url": "https://github.com/phar-io/version.git", - "reference": "a70c0ced4be299a63d32fa96d9281d03e94041df" + "reference": "45a2ec53a73c70ce41d55cedef9063630abaf1b6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phar-io/version/zipball/a70c0ced4be299a63d32fa96d9281d03e94041df", - "reference": "a70c0ced4be299a63d32fa96d9281d03e94041df", + "url": "https://api.github.com/repos/phar-io/version/zipball/45a2ec53a73c70ce41d55cedef9063630abaf1b6", + "reference": "45a2ec53a73c70ce41d55cedef9063630abaf1b6", "shasum": "" }, "require": { @@ -1191,7 +1197,7 @@ } ], "description": "Library for handling version information and constraints", - "time": "2017-03-05T17:38:23+00:00" + "time": "2018-07-08T19:19:57+00:00" }, { "name": "phpdocumentor/reflection-common", @@ -1347,33 +1353,33 @@ }, { "name": "phpspec/prophecy", - "version": "1.7.5", + "version": "1.8.0", "source": { "type": "git", "url": "https://github.com/phpspec/prophecy.git", - "reference": "dfd6be44111a7c41c2e884a336cc4f461b3b2401" + "reference": "4ba436b55987b4bf311cb7c6ba82aa528aac0a06" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpspec/prophecy/zipball/dfd6be44111a7c41c2e884a336cc4f461b3b2401", - "reference": "dfd6be44111a7c41c2e884a336cc4f461b3b2401", + "url": "https://api.github.com/repos/phpspec/prophecy/zipball/4ba436b55987b4bf311cb7c6ba82aa528aac0a06", + "reference": "4ba436b55987b4bf311cb7c6ba82aa528aac0a06", "shasum": "" }, "require": { "doctrine/instantiator": "^1.0.2", "php": "^5.3|^7.0", "phpdocumentor/reflection-docblock": "^2.0|^3.0.2|^4.0", - "sebastian/comparator": "^1.1|^2.0", + "sebastian/comparator": "^1.1|^2.0|^3.0", "sebastian/recursion-context": "^1.0|^2.0|^3.0" }, "require-dev": { "phpspec/phpspec": "^2.5|^3.2", - "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.5" + "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.5 || ^7.1" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.7.x-dev" + "dev-master": "1.8.x-dev" } }, "autoload": { @@ -1406,7 +1412,7 @@ "spy", "stub" ], - "time": "2018-02-19T10:16:54+00:00" + "time": "2018-08-05T17:53:17+00:00" }, { "name": "phpstan/phpdoc-parser", @@ -1524,23 +1530,23 @@ }, { "name": "phpunit/php-code-coverage", - "version": "6.0.5", + "version": "6.0.8", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-code-coverage.git", - "reference": "4cab20a326d14de7575a8e235c70d879b569a57a" + "reference": "848f78b3309780fef7ec8c4666b7ab4e6b09b22f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/4cab20a326d14de7575a8e235c70d879b569a57a", - "reference": "4cab20a326d14de7575a8e235c70d879b569a57a", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/848f78b3309780fef7ec8c4666b7ab4e6b09b22f", + "reference": "848f78b3309780fef7ec8c4666b7ab4e6b09b22f", "shasum": "" }, "require": { "ext-dom": "*", "ext-xmlwriter": "*", "php": "^7.1", - "phpunit/php-file-iterator": "^1.4.2", + "phpunit/php-file-iterator": "^2.0", "phpunit/php-text-template": "^1.2.1", "phpunit/php-token-stream": "^3.0", "sebastian/code-unit-reverse-lookup": "^1.0.1", @@ -1583,29 +1589,32 @@ "testing", "xunit" ], - "time": "2018-05-28T11:49:20+00:00" + "time": "2018-10-04T03:41:23+00:00" }, { "name": "phpunit/php-file-iterator", - "version": "1.4.5", + "version": "2.0.2", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-file-iterator.git", - "reference": "730b01bc3e867237eaac355e06a36b85dd93a8b4" + "reference": "050bedf145a257b1ff02746c31894800e5122946" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/730b01bc3e867237eaac355e06a36b85dd93a8b4", - "reference": "730b01bc3e867237eaac355e06a36b85dd93a8b4", + "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/050bedf145a257b1ff02746c31894800e5122946", + "reference": "050bedf145a257b1ff02746c31894800e5122946", "shasum": "" }, "require": { - "php": ">=5.3.3" + "php": "^7.1" + }, + "require-dev": { + "phpunit/phpunit": "^7.1" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.4.x-dev" + "dev-master": "2.0.x-dev" } }, "autoload": { @@ -1620,7 +1629,7 @@ "authors": [ { "name": "Sebastian Bergmann", - "email": "sb@sebastian-bergmann.de", + "email": "sebastian@phpunit.de", "role": "lead" } ], @@ -1630,7 +1639,7 @@ "filesystem", "iterator" ], - "time": "2017-11-27T13:52:08+00:00" + "time": "2018-09-13T20:33:42+00:00" }, { "name": "phpunit/php-text-template", @@ -1773,47 +1782,51 @@ }, { "name": "phpunit/phpunit", - "version": "7.1.4", + "version": "7.4.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "6d51299e307dc510149e0b7cd1931dd11770e1cb" + "reference": "f3837fa1e07758057ae06e8ddec6d06ba183f126" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/6d51299e307dc510149e0b7cd1931dd11770e1cb", - "reference": "6d51299e307dc510149e0b7cd1931dd11770e1cb", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/f3837fa1e07758057ae06e8ddec6d06ba183f126", + "reference": "f3837fa1e07758057ae06e8ddec6d06ba183f126", "shasum": "" }, "require": { + "doctrine/instantiator": "^1.1", "ext-dom": "*", "ext-json": "*", "ext-libxml": "*", "ext-mbstring": "*", "ext-xml": "*", - "myclabs/deep-copy": "^1.6.1", - "phar-io/manifest": "^1.0.1", - "phar-io/version": "^1.0", + "myclabs/deep-copy": "^1.7", + "phar-io/manifest": "^1.0.2", + "phar-io/version": "^2.0", "php": "^7.1", "phpspec/prophecy": "^1.7", - "phpunit/php-code-coverage": "^6.0.1", - "phpunit/php-file-iterator": "^1.4.3", + "phpunit/php-code-coverage": "^6.0.7", + "phpunit/php-file-iterator": "^2.0.1", "phpunit/php-text-template": "^1.2.1", "phpunit/php-timer": "^2.0", - "phpunit/phpunit-mock-objects": "^6.1.1", - "sebastian/comparator": "^2.1 || ^3.0", + "sebastian/comparator": "^3.0", "sebastian/diff": "^3.0", "sebastian/environment": "^3.1", "sebastian/exporter": "^3.1", "sebastian/global-state": "^2.0", "sebastian/object-enumerator": "^3.0.3", - "sebastian/resource-operations": "^1.0", + "sebastian/resource-operations": "^2.0", "sebastian/version": "^2.0.1" }, + "conflict": { + "phpunit/phpunit-mock-objects": "*" + }, "require-dev": { "ext-pdo": "*" }, "suggest": { + "ext-soap": "*", "ext-xdebug": "*", "phpunit/php-invoker": "^2.0" }, @@ -1823,7 +1836,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "7.1-dev" + "dev-master": "7.4-dev" } }, "autoload": { @@ -1849,63 +1862,7 @@ "testing", "xunit" ], - "time": "2018-04-18T13:41:53+00:00" - }, - { - "name": "phpunit/phpunit-mock-objects", - "version": "6.1.2", - "source": { - "type": "git", - "url": "https://github.com/sebastianbergmann/phpunit-mock-objects.git", - "reference": "f9756fd4f43f014cb2dca98deeaaa8ce5500a36e" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/f9756fd4f43f014cb2dca98deeaaa8ce5500a36e", - "reference": "f9756fd4f43f014cb2dca98deeaaa8ce5500a36e", - "shasum": "" - }, - "require": { - "doctrine/instantiator": "^1.0.5", - "php": "^7.1", - "phpunit/php-text-template": "^1.2.1", - "sebastian/exporter": "^3.1" - }, - "require-dev": { - "phpunit/phpunit": "^7.0" - }, - "suggest": { - "ext-soap": "*" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "6.1-dev" - } - }, - "autoload": { - "classmap": [ - "src/" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "BSD-3-Clause" - ], - "authors": [ - { - "name": "Sebastian Bergmann", - "email": "sebastian@phpunit.de", - "role": "lead" - } - ], - "description": "Mock Object library for PHPUnit", - "homepage": "https://github.com/sebastianbergmann/phpunit-mock-objects/", - "keywords": [ - "mock", - "xunit" - ], - "time": "2018-05-29T13:54:20+00:00" + "time": "2018-10-05T04:05:24+00:00" }, { "name": "psr/log", @@ -2001,30 +1958,30 @@ }, { "name": "sebastian/comparator", - "version": "2.1.3", + "version": "3.0.2", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/comparator.git", - "reference": "34369daee48eafb2651bea869b4b15d75ccc35f9" + "reference": "5de4fc177adf9bce8df98d8d141a7559d7ccf6da" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/34369daee48eafb2651bea869b4b15d75ccc35f9", - "reference": "34369daee48eafb2651bea869b4b15d75ccc35f9", + "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/5de4fc177adf9bce8df98d8d141a7559d7ccf6da", + "reference": "5de4fc177adf9bce8df98d8d141a7559d7ccf6da", "shasum": "" }, "require": { - "php": "^7.0", - "sebastian/diff": "^2.0 || ^3.0", + "php": "^7.1", + "sebastian/diff": "^3.0", "sebastian/exporter": "^3.1" }, "require-dev": { - "phpunit/phpunit": "^6.4" + "phpunit/phpunit": "^7.1" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.1.x-dev" + "dev-master": "3.0-dev" } }, "autoload": { @@ -2061,20 +2018,20 @@ "compare", "equality" ], - "time": "2018-02-01T13:46:46+00:00" + "time": "2018-07-12T15:12:46+00:00" }, { "name": "sebastian/diff", - "version": "3.0.0", + "version": "3.0.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/diff.git", - "reference": "e09160918c66281713f1c324c1f4c4c3037ba1e8" + "reference": "366541b989927187c4ca70490a35615d3fef2dce" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/e09160918c66281713f1c324c1f4c4c3037ba1e8", - "reference": "e09160918c66281713f1c324c1f4c4c3037ba1e8", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/366541b989927187c4ca70490a35615d3fef2dce", + "reference": "366541b989927187c4ca70490a35615d3fef2dce", "shasum": "" }, "require": { @@ -2117,7 +2074,7 @@ "unidiff", "unified diff" ], - "time": "2018-02-01T13:45:15+00:00" + "time": "2018-06-10T07:54:39+00:00" }, { "name": "sebastian/environment", @@ -2434,25 +2391,25 @@ }, { "name": "sebastian/resource-operations", - "version": "1.0.0", + "version": "2.0.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/resource-operations.git", - "reference": "ce990bb21759f94aeafd30209e8cfcdfa8bc3f52" + "reference": "4d7a795d35b889bf80a0cc04e08d77cedfa917a9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/resource-operations/zipball/ce990bb21759f94aeafd30209e8cfcdfa8bc3f52", - "reference": "ce990bb21759f94aeafd30209e8cfcdfa8bc3f52", + "url": "https://api.github.com/repos/sebastianbergmann/resource-operations/zipball/4d7a795d35b889bf80a0cc04e08d77cedfa917a9", + "reference": "4d7a795d35b889bf80a0cc04e08d77cedfa917a9", "shasum": "" }, "require": { - "php": ">=5.6.0" + "php": "^7.1" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.0.x-dev" + "dev-master": "2.0-dev" } }, "autoload": { @@ -2472,7 +2429,7 @@ ], "description": "Provides a list of PHP built-in functions that operate on resources", "homepage": "https://www.github.com/sebastianbergmann/resource-operations", - "time": "2015-07-28T20:34:47+00:00" + "time": "2018-10-04T04:07:39+00:00" }, { "name": "sebastian/version", @@ -2519,30 +2476,29 @@ }, { "name": "slevomat/coding-standard", - "version": "4.5.2", + "version": "4.8.3", "source": { "type": "git", "url": "https://github.com/slevomat/coding-standard.git", - "reference": "1e609159241fa90d5a429f185b2ea9b881340a7c" + "reference": "32e1ca205fc34920f323582ed29c0602e3897ae3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/slevomat/coding-standard/zipball/1e609159241fa90d5a429f185b2ea9b881340a7c", - "reference": "1e609159241fa90d5a429f185b2ea9b881340a7c", + "url": "https://api.github.com/repos/slevomat/coding-standard/zipball/32e1ca205fc34920f323582ed29c0602e3897ae3", + "reference": "32e1ca205fc34920f323582ed29c0602e3897ae3", "shasum": "" }, "require": { "php": "^7.1", - "squizlabs/php_codesniffer": "^3.2.3" + "squizlabs/php_codesniffer": "^3.3.0" }, "require-dev": { "jakub-onderka/php-parallel-lint": "1.0.0", - "phing/phing": "2.16", + "phing/phing": "2.16.1", "phpstan/phpstan": "0.9.2", "phpstan/phpstan-phpunit": "0.9.4", "phpstan/phpstan-strict-rules": "0.9", - "phpunit/php-code-coverage": "6.0.1", - "phpunit/phpunit": "7.0.2" + "phpunit/phpunit": "7.3.5" }, "type": "phpcodesniffer-standard", "autoload": { @@ -2555,20 +2511,20 @@ "MIT" ], "description": "Slevomat Coding Standard for PHP_CodeSniffer complements Consistence Coding Standard by providing sniffs with additional checks.", - "time": "2018-03-08T08:14:33+00:00" + "time": "2018-09-25T21:21:11+00:00" }, { "name": "squizlabs/php_codesniffer", - "version": "3.2.3", + "version": "3.3.2", "source": { "type": "git", "url": "https://github.com/squizlabs/PHP_CodeSniffer.git", - "reference": "4842476c434e375f9d3182ff7b89059583aa8b27" + "reference": "6ad28354c04b364c3c71a34e4a18b629cc3b231e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/4842476c434e375f9d3182ff7b89059583aa8b27", - "reference": "4842476c434e375f9d3182ff7b89059583aa8b27", + "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/6ad28354c04b364c3c71a34e4a18b629cc3b231e", + "reference": "6ad28354c04b364c3c71a34e4a18b629cc3b231e", "shasum": "" }, "require": { @@ -2606,7 +2562,7 @@ "phpcs", "standards" ], - "time": "2018-02-20T21:35:23+00:00" + "time": "2018-09-23T23:08:17+00:00" }, { "name": "symfony/console", diff --git a/docs/en/reference/configuration.rst b/docs/en/reference/configuration.rst index 88f0069506a..4fa8991ec33 100644 --- a/docs/en/reference/configuration.rst +++ b/docs/en/reference/configuration.rst @@ -126,20 +126,19 @@ interfaces to use. It can be configured in one of three ways: - ``driver``: The built-in driver implementation to use. The following drivers are currently available: - - ``pdo_mysql``: A MySQL driver that uses the pdo\_mysql PDO + - ``pdo_mysql``: A MySQL driver that uses the pdo_mysql PDO extension. - - ``drizzle_pdo_mysql``: A Drizzle driver that uses pdo\_mysql PDO + - ``drizzle_pdo_mysql``: A Drizzle driver that uses pdo_mysql PDO extension. - ``mysqli``: A MySQL driver that uses the mysqli extension. - - ``pdo_sqlite``: An SQLite driver that uses the pdo\_sqlite PDO + - ``pdo_sqlite``: An SQLite driver that uses the pdo_sqlite PDO extension. - - ``pdo_pgsql``: A PostgreSQL driver that uses the pdo\_pgsql PDO + - ``pdo_pgsql``: A PostgreSQL driver that uses the pdo_pgsql PDO extension. - - ``pdo_oci``: An Oracle driver that uses the pdo\_oci PDO + - ``pdo_oci``: An Oracle driver that uses the pdo_oci PDO extension. **Note that this driver caused problems in our tests. Prefer the oci8 driver if possible.** - - ``pdo_sqlsrv``: A Microsoft SQL Server driver that uses pdo\_sqlsrv PDO - **Note that this driver caused problems in our tests. Prefer the sqlsrv driver if possible.** + - ``pdo_sqlsrv``: A Microsoft SQL Server driver that uses pdo_sqlsrv PDO - ``sqlsrv``: A Microsoft SQL Server driver that uses the sqlsrv PHP extension. - ``oci8``: An Oracle driver that uses the oci8 PHP extension. - ``sqlanywhere``: A SAP Sybase SQL Anywhere driver that uses the sqlanywhere PHP extension. @@ -170,8 +169,8 @@ options recognized by each built-in driver. When using an existing PDO instance through the ``pdo`` option, specifying connection details is obviously not necessary. -pdo\_sqlite -^^^^^^^^^^^ +pdo_sqlite +^^^^^^^^^^ - ``user`` (string): Username to use when connecting to the database. @@ -183,8 +182,8 @@ pdo\_sqlite in-memory (non-persistent). Mutually exclusive with ``path``. ``path`` takes precedence. -pdo\_mysql -^^^^^^^^^^ +pdo_mysql +^^^^^^^^^ - ``user`` (string): Username to use when connecting to the database. @@ -198,8 +197,8 @@ pdo\_mysql - ``charset`` (string): The charset used when connecting to the database. -drizzle\_pdo\_mysql -^^^^^^^^^^^^^^^^^^^ +drizzle_pdo_mysql +^^^^^^^^^^^^^^^^^ **Requires** drizzle plugin ``mysql_protocol`` or ``mysql_unix_socket_protocol`` to be enabled. On Ubuntu this can be done by editing ``/etc/drizzle/conf.d/mysql-protocol.cnf`` @@ -236,8 +235,8 @@ mysqli - ``ssl_cipher`` (string): A list of allowable ciphers to use for SSL encryption. - ``driverOptions`` Any supported flags for mysqli found on `http://www.php.net/manual/en/mysqli.real-connect.php` -pdo\_pgsql -^^^^^^^^^^ +pdo_pgsql +^^^^^^^^^ - ``user`` (string): Username to use when connecting to the database. @@ -275,8 +274,8 @@ PostgreSQL behaves differently with regard to booleans when you use and ``'false'`` as strings you can change to integers by using: ``$conn->getDatabasePlatform()->setUseBooleanTrueFalseStrings($flag)``. -pdo\_oci / oci8 -^^^^^^^^^^^^^^^ +pdo_oci / oci8 +^^^^^^^^^^^^^^ - ``user`` (string): Username to use when connecting to the database. @@ -307,8 +306,8 @@ pdo\_oci / oci8 and ``getPort`` methods from ``Doctrine\DBAL\Connection`` will no longer function as expected. - ``persistent`` (boolean): Whether to establish a persistent connection. -pdo\_sqlsrv / sqlsrv -^^^^^^^^^^^^^^^^^^^^ +pdo_sqlsrv / sqlsrv +^^^^^^^^^^^^^^^^^^^ - ``user`` (string): Username to use when connecting to the database. diff --git a/docs/en/reference/introduction.rst b/docs/en/reference/introduction.rst index e52f7fff858..ae495ea9815 100644 --- a/docs/en/reference/introduction.rst +++ b/docs/en/reference/introduction.rst @@ -25,19 +25,13 @@ The following database vendors are currently supported: The Doctrine 2 database layer can be used independently of the object-relational mapper. In order to use the DBAL all you need is -the ``Doctrine\Common`` and ``Doctrine\DBAL`` namespaces. Once you -have the Common and DBAL namespaces you must setup a class loader -to be able to autoload the classes: +the class loader provided by Composer, to be able to autoload the classes: .. code-block:: php register(); + + require_once 'vendor/autoload.php'; Now you are able to load classes that are in the ``/path/to/doctrine`` directory like diff --git a/docs/en/reference/known-vendor-issues.rst b/docs/en/reference/known-vendor-issues.rst index b33e80930ac..0ff6824e1db 100644 --- a/docs/en/reference/known-vendor-issues.rst +++ b/docs/en/reference/known-vendor-issues.rst @@ -179,14 +179,3 @@ liberal DateTime parser that detects the format automatically: Type::overrideType('datetime_immutable', 'Doctrine\DBAL\Types\VarDateTimeImmutableType'); Type::overrideType('datetimetz_immutable', 'Doctrine\DBAL\Types\VarDateTimeImmutableType'); Type::overrideType('time_immutable', 'Doctrine\DBAL\Types\VarDateTimeImmutableType'); - -PDO_SQLSRV: VARBINARY/BLOB columns -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The ``PDO_SQLSRV`` driver currently has a bug when binding values to -VARBINARY/BLOB columns with ``bindValue`` in prepared statements. -This raises an implicit conversion from data type error as it tries -to convert a character type value to a binary type value even if -you explicitly define the value as ``ParameterType::LARGE_OBJECT`` type. -Therefore it is highly encouraged to use the native ``sqlsrv`` -driver instead which does not have this limitation. diff --git a/docs/en/reference/platforms.rst b/docs/en/reference/platforms.rst index 5f57fec9226..32ef74304ea 100644 --- a/docs/en/reference/platforms.rst +++ b/docs/en/reference/platforms.rst @@ -37,6 +37,11 @@ MySQL - ``MySQL57Platform`` for version 5.7 (5.7.9 GA) and above. - ``MySQL80Platform`` for version 8.0 (8.0 GA) and above. +MariaDB +^^^^^ + +- ``MariaDb1027Platform`` for version 10.2 (10.2.7 GA) and above. + Oracle ^^^^^^ diff --git a/docs/en/reference/sharding.rst b/docs/en/reference/sharding.rst index 0bade11ccbd..dcdd7d8f660 100644 --- a/docs/en/reference/sharding.rst +++ b/docs/en/reference/sharding.rst @@ -84,8 +84,7 @@ Use GUID/UUIDs The most simple ID-generation mechanism for sharding are universally unique identifiers. These are 16-byte (128-bit) numbers that are guaranteed to be unique across different servers. -You can `read up on UUIDs on Wikipedia -`_. +You can `read up on UUIDs on Wikipedia `_. The drawback of UUIDs is the segmentation they cause on indexes. Because UUIDs are not sequentially generated, they can have negative impact on index access @@ -128,8 +127,7 @@ In your application you should hide this details in Id-Generation services: } A good starting point to read up on GUIDs (vs numerical ids) is this blog post -`Coding Horror: Primary Keys: IDs vs GUIDs -`_. +`Coding Horror: Primary Keys: IDs vs GUIDs `_. Table Generator ~~~~~~~~~~~~~~~ diff --git a/docs/en/reference/sharding_azure_tutorial.rst b/docs/en/reference/sharding_azure_tutorial.rst index 761ed401cbb..71a4fab5594 100644 --- a/docs/en/reference/sharding_azure_tutorial.rst +++ b/docs/en/reference/sharding_azure_tutorial.rst @@ -6,8 +6,7 @@ SQLAzure Sharding Tutorial The sharding extension is currently in transition from a separate Project into DBAL. Class names may differ. -This tutorial builds upon the `Brian Swans tutorial -`_ +This tutorial builds upon the `Brian Swans tutorial `_ on SQLAzure Sharding and turns all the examples into examples using the Doctrine Sharding support. It introduces SQL Azure Sharding, which is an abstraction layer in SQL Azure to diff --git a/lib/Doctrine/DBAL/Cache/ArrayStatement.php b/lib/Doctrine/DBAL/Cache/ArrayStatement.php index 6e09e124d83..449a220a2af 100644 --- a/lib/Doctrine/DBAL/Cache/ArrayStatement.php +++ b/lib/Doctrine/DBAL/Cache/ArrayStatement.php @@ -1,62 +1,43 @@ . - */ namespace Doctrine\DBAL\Cache; +use ArrayIterator; use Doctrine\DBAL\Driver\ResultStatement; use Doctrine\DBAL\FetchMode; +use InvalidArgumentException; +use IteratorAggregate; +use PDO; use function array_merge; use function array_values; use function count; use function reset; -class ArrayStatement implements \IteratorAggregate, ResultStatement +class ArrayStatement implements IteratorAggregate, ResultStatement { - /** - * @var array - */ + /** @var mixed[] */ private $data; - /** - * @var int - */ + /** @var int */ private $columnCount = 0; - /** - * @var int - */ + /** @var int */ private $num = 0; - /** - * @var int - */ + /** @var int */ private $defaultFetchMode = FetchMode::MIXED; /** - * @param array $data + * @param mixed[] $data */ public function __construct(array $data) { $this->data = $data; - if (count($data)) { - $this->columnCount = count($data[0]); + if (! count($data)) { + return; } + + $this->columnCount = count($data[0]); } /** @@ -64,7 +45,7 @@ public function __construct(array $data) */ public function closeCursor() { - unset ($this->data); + unset($this->data); } /** @@ -81,7 +62,7 @@ public function columnCount() public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null) { if ($arg2 !== null || $arg3 !== null) { - throw new \InvalidArgumentException("Caching layer does not support 2nd/3rd argument to setFetchMode()"); + throw new InvalidArgumentException('Caching layer does not support 2nd/3rd argument to setFetchMode()'); } $this->defaultFetchMode = $fetchMode; @@ -96,13 +77,13 @@ public function getIterator() { $data = $this->fetchAll(); - return new \ArrayIterator($data); + return new ArrayIterator($data); } /** * {@inheritdoc} */ - public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) + public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { if (! isset($this->data[$this->num])) { return false; @@ -127,7 +108,7 @@ public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NE return reset($row); } - throw new \InvalidArgumentException('Invalid fetch-style given for fetching result.'); + throw new InvalidArgumentException('Invalid fetch-style given for fetching result.'); } /** diff --git a/lib/Doctrine/DBAL/Cache/CacheException.php b/lib/Doctrine/DBAL/Cache/CacheException.php index 1b69058cde9..636c948a616 100644 --- a/lib/Doctrine/DBAL/Cache/CacheException.php +++ b/lib/Doctrine/DBAL/Cache/CacheException.php @@ -1,36 +1,17 @@ . - */ namespace Doctrine\DBAL\Cache; -/** - * @author Benjamin Eberlei - * @since 2.2 - */ -class CacheException extends \Doctrine\DBAL\DBALException +use Doctrine\DBAL\DBALException; + +class CacheException extends DBALException { /** * @return \Doctrine\DBAL\Cache\CacheException */ public static function noCacheKey() { - return new self("No cache key was set."); + return new self('No cache key was set.'); } /** @@ -38,6 +19,6 @@ public static function noCacheKey() */ public static function noResultDriverConfigured() { - return new self("Trying to cache a query but no result driver is configured."); + return new self('Trying to cache a query but no result driver is configured.'); } } diff --git a/lib/Doctrine/DBAL/Cache/QueryCacheProfile.php b/lib/Doctrine/DBAL/Cache/QueryCacheProfile.php index a722681ce43..9433f982fc5 100644 --- a/lib/Doctrine/DBAL/Cache/QueryCacheProfile.php +++ b/lib/Doctrine/DBAL/Cache/QueryCacheProfile.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Cache; @@ -31,19 +14,13 @@ */ class QueryCacheProfile { - /** - * @var Cache|null - */ + /** @var Cache|null */ private $resultCacheDriver; - /** - * @var int - */ + /** @var int */ private $lifetime = 0; - /** - * @var string|null - */ + /** @var string|null */ private $cacheKey; /** @@ -90,12 +67,12 @@ public function getCacheKey() /** * Generates the real cache key from query, params, types and connection parameters. * - * @param string $query - * @param array $params - * @param array $types - * @param array $connectionParams + * @param string $query + * @param mixed[] $params + * @param int[]|string[] $types + * @param mixed[] $connectionParams * - * @return array + * @return string[] */ public function generateCacheKeys($query, $params, $types, array $connectionParams = []) { @@ -115,7 +92,6 @@ public function generateCacheKeys($query, $params, $types, array $connectionPara } /** - * * @return \Doctrine\DBAL\Cache\QueryCacheProfile */ public function setResultCacheDriver(Cache $cache) diff --git a/lib/Doctrine/DBAL/Cache/ResultCacheStatement.php b/lib/Doctrine/DBAL/Cache/ResultCacheStatement.php index 4b200a5d438..872f3e71fc9 100644 --- a/lib/Doctrine/DBAL/Cache/ResultCacheStatement.php +++ b/lib/Doctrine/DBAL/Cache/ResultCacheStatement.php @@ -1,28 +1,15 @@ . - */ namespace Doctrine\DBAL\Cache; -use Doctrine\DBAL\Driver\Statement; -use Doctrine\DBAL\Driver\ResultStatement; +use ArrayIterator; use Doctrine\Common\Cache\Cache; +use Doctrine\DBAL\Driver\ResultStatement; +use Doctrine\DBAL\Driver\Statement; use Doctrine\DBAL\FetchMode; +use InvalidArgumentException; +use IteratorAggregate; +use PDO; use function array_merge; use function array_values; use function reset; @@ -40,32 +27,21 @@ * Also you have to realize that the cache will load the whole result into memory at once to ensure 2. * This means that the memory usage for cached results might increase by using this feature. */ -class ResultCacheStatement implements \IteratorAggregate, ResultStatement +class ResultCacheStatement implements IteratorAggregate, ResultStatement { - /** - * @var \Doctrine\Common\Cache\Cache - */ + /** @var Cache */ private $resultCache; - /** - * - * @var string - */ + /** @var string */ private $cacheKey; - /** - * @var string - */ + /** @var string */ private $realKey; - /** - * @var int - */ + /** @var int */ private $lifetime; - /** - * @var \Doctrine\DBAL\Driver\Statement - */ + /** @var Statement */ private $statement; /** @@ -75,30 +51,24 @@ class ResultCacheStatement implements \IteratorAggregate, ResultStatement */ private $emptied = false; - /** - * @var array - */ + /** @var mixed[] */ private $data; - /** - * @var int - */ + /** @var int */ private $defaultFetchMode = FetchMode::MIXED; /** - * @param \Doctrine\DBAL\Driver\Statement $stmt - * @param \Doctrine\Common\Cache\Cache $resultCache - * @param string $cacheKey - * @param string $realKey - * @param int $lifetime + * @param string $cacheKey + * @param string $realKey + * @param int $lifetime */ public function __construct(Statement $stmt, Cache $resultCache, $cacheKey, $realKey, $lifetime) { - $this->statement = $stmt; + $this->statement = $stmt; $this->resultCache = $resultCache; - $this->cacheKey = $cacheKey; - $this->realKey = $realKey; - $this->lifetime = $lifetime; + $this->cacheKey = $cacheKey; + $this->realKey = $realKey; + $this->lifetime = $lifetime; } /** @@ -107,16 +77,20 @@ public function __construct(Statement $stmt, Cache $resultCache, $cacheKey, $rea public function closeCursor() { $this->statement->closeCursor(); - if ($this->emptied && $this->data !== null) { - $data = $this->resultCache->fetch($this->cacheKey); - if ( ! $data) { - $data = []; - } - $data[$this->realKey] = $this->data; + if (! $this->emptied || $this->data === null) { + return true; + } - $this->resultCache->save($this->cacheKey, $data, $this->lifetime); - unset($this->data); + $data = $this->resultCache->fetch($this->cacheKey); + if (! $data) { + $data = []; } + $data[$this->realKey] = $this->data; + + $this->resultCache->save($this->cacheKey, $data, $this->lifetime); + unset($this->data); + + return true; } /** @@ -144,13 +118,13 @@ public function getIterator() { $data = $this->fetchAll(); - return new \ArrayIterator($data); + return new ArrayIterator($data); } /** * {@inheritdoc} */ - public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) + public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { if ($this->data === null) { $this->data = []; @@ -179,7 +153,7 @@ public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NE return reset($row); } - throw new \InvalidArgumentException('Invalid fetch-style given for caching result.'); + throw new InvalidArgumentException('Invalid fetch-style given for caching result.'); } $this->emptied = true; @@ -192,12 +166,7 @@ public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NE */ public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null) { - $rows = []; - while ($row = $this->fetch($fetchMode)) { - $rows[] = $row; - } - - return $rows; + return $this->statement->fetchAll($fetchMode, $fetchArgument, $ctorArgs); } /** diff --git a/lib/Doctrine/DBAL/ColumnCase.php b/lib/Doctrine/DBAL/ColumnCase.php index 420d868f582..872d3ede873 100644 --- a/lib/Doctrine/DBAL/ColumnCase.php +++ b/lib/Doctrine/DBAL/ColumnCase.php @@ -2,6 +2,8 @@ namespace Doctrine\DBAL; +use PDO; + /** * Contains portable column case conversions. */ @@ -12,14 +14,14 @@ final class ColumnCase * * @see \PDO::CASE_UPPER */ - public const UPPER = \PDO::CASE_UPPER; + public const UPPER = PDO::CASE_UPPER; /** * Convert column names to lower case. * * @see \PDO::CASE_LOWER */ - public const LOWER = \PDO::CASE_LOWER; + public const LOWER = PDO::CASE_LOWER; /** * This class cannot be instantiated. diff --git a/lib/Doctrine/DBAL/Configuration.php b/lib/Doctrine/DBAL/Configuration.php index fe9465cdd57..9b7b21fb21e 100644 --- a/lib/Doctrine/DBAL/Configuration.php +++ b/lib/Doctrine/DBAL/Configuration.php @@ -1,34 +1,15 @@ . - */ namespace Doctrine\DBAL; -use Doctrine\DBAL\Logging\SQLLogger; use Doctrine\Common\Cache\Cache; +use Doctrine\DBAL\Logging\SQLLogger; +use Doctrine\DBAL\Schema\AbstractAsset; +use function preg_match; /** * Configuration container for the Doctrine DBAL. * - * @since 2.0 - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel * @internal When adding a new configuration option just write a getter/setter * pair and add the option to the _attributes array with a proper default value. */ @@ -38,18 +19,16 @@ class Configuration * The attributes that are contained in the configuration. * Values are default values. * - * @var array + * @var mixed[] */ protected $_attributes = []; /** * Sets the SQL logger to use. Defaults to NULL which means SQL logging is disabled. * - * @param \Doctrine\DBAL\Logging\SQLLogger|null $logger - * * @return void */ - public function setSQLLogger(SQLLogger $logger = null) + public function setSQLLogger(?SQLLogger $logger = null) { $this->_attributes['sqlLogger'] = $logger; } @@ -57,7 +36,7 @@ public function setSQLLogger(SQLLogger $logger = null) /** * Gets the SQL logger that is used. * - * @return \Doctrine\DBAL\Logging\SQLLogger|null + * @return SQLLogger|null */ public function getSQLLogger() { @@ -67,7 +46,7 @@ public function getSQLLogger() /** * Gets the cache driver implementation that is used for query result caching. * - * @return \Doctrine\Common\Cache\Cache|null + * @return Cache|null */ public function getResultCacheImpl() { @@ -77,8 +56,6 @@ public function getResultCacheImpl() /** * Sets the cache driver implementation that is used for query result caching. * - * @param \Doctrine\Common\Cache\Cache $cacheImpl - * * @return void */ public function setResultCacheImpl(Cache $cacheImpl) @@ -93,6 +70,8 @@ public function setResultCacheImpl(Cache $cacheImpl) * schema instances generated for the active connection when calling * {AbstractSchemaManager#createSchema()}. * + * @deprecated Use Configuration::setSchemaAssetsFilter() instead + * * @param string $filterExpression * * @return void @@ -100,11 +79,18 @@ public function setResultCacheImpl(Cache $cacheImpl) public function setFilterSchemaAssetsExpression($filterExpression) { $this->_attributes['filterSchemaAssetsExpression'] = $filterExpression; + if ($filterExpression) { + $this->_attributes['filterSchemaAssetsExpressionCallable'] = $this->buildSchemaAssetsFilterFromExpression($filterExpression); + } else { + $this->_attributes['filterSchemaAssetsExpressionCallable'] = null; + } } /** * Returns filter schema assets expression. * + * @deprecated Use Configuration::getSchemaAssetsFilter() instead + * * @return string|null */ public function getFilterSchemaAssetsExpression() @@ -112,6 +98,36 @@ public function getFilterSchemaAssetsExpression() return $this->_attributes['filterSchemaAssetsExpression'] ?? null; } + /** + * @param string $filterExpression + */ + private function buildSchemaAssetsFilterFromExpression($filterExpression) : callable + { + return static function ($assetName) use ($filterExpression) { + if ($assetName instanceof AbstractAsset) { + $assetName = $assetName->getName(); + } + return preg_match($filterExpression, $assetName); + }; + } + + /** + * Sets the callable to use to filter schema assets. + */ + public function setSchemaAssetsFilter(?callable $callable = null) : ?callable + { + $this->_attributes['filterSchemaAssetsExpression'] = null; + return $this->_attributes['filterSchemaAssetsExpressionCallable'] = $callable; + } + + /** + * Returns the callable to use to filter schema assets. + */ + public function getSchemaAssetsFilter() : ?callable + { + return $this->_attributes['filterSchemaAssetsExpressionCallable'] ?? null; + } + /** * Sets the default auto-commit mode for connections. * @@ -119,21 +135,21 @@ public function getFilterSchemaAssetsExpression() * transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either * the method commit or the method rollback. By default, new connections are in auto-commit mode. * - * @param bool $autoCommit True to enable auto-commit mode; false to disable it. - * * @see getAutoCommit + * + * @param bool $autoCommit True to enable auto-commit mode; false to disable it. */ public function setAutoCommit($autoCommit) { - $this->_attributes['autoCommit'] = (boolean) $autoCommit; + $this->_attributes['autoCommit'] = (bool) $autoCommit; } /** * Returns the default auto-commit mode for connections. * - * @return bool True if auto-commit mode is enabled by default for connections, false otherwise. - * * @see setAutoCommit + * + * @return bool True if auto-commit mode is enabled by default for connections, false otherwise. */ public function getAutoCommit() { diff --git a/lib/Doctrine/DBAL/Connection.php b/lib/Doctrine/DBAL/Connection.php index c1cb8acf521..85761fcca9b 100644 --- a/lib/Doctrine/DBAL/Connection.php +++ b/lib/Doctrine/DBAL/Connection.php @@ -1,42 +1,29 @@ . - */ namespace Doctrine\DBAL; -use Doctrine\DBAL\Driver\ResultStatement; -use Doctrine\DBAL\Driver\ServerInfoAwareConnection; -use Doctrine\DBAL\Exception\InvalidArgumentException; use Closure; -use Exception; -use Doctrine\DBAL\Types\Type; -use Doctrine\DBAL\Driver\Connection as DriverConnection; -use Doctrine\DBAL\Driver\Statement as DriverStatement; use Doctrine\Common\EventManager; -use Doctrine\DBAL\Cache\ResultCacheStatement; -use Doctrine\DBAL\Cache\QueryCacheProfile; use Doctrine\DBAL\Cache\ArrayStatement; use Doctrine\DBAL\Cache\CacheException; +use Doctrine\DBAL\Cache\QueryCacheProfile; +use Doctrine\DBAL\Cache\ResultCacheStatement; +use Doctrine\DBAL\Driver\Connection as DriverConnection; use Doctrine\DBAL\Driver\PingableConnection; +use Doctrine\DBAL\Driver\ResultStatement; +use Doctrine\DBAL\Driver\ServerInfoAwareConnection; +use Doctrine\DBAL\Driver\Statement as DriverStatement; +use Doctrine\DBAL\Exception\InvalidArgumentException; +use Doctrine\DBAL\Platforms\AbstractPlatform; +use Doctrine\DBAL\Query\Expression\ExpressionBuilder; +use Doctrine\DBAL\Query\QueryBuilder; +use Doctrine\DBAL\Schema\AbstractSchemaManager; +use Doctrine\DBAL\Types\Type; +use Exception; use Throwable; -use function assert; use function array_key_exists; use function array_merge; +use function assert; use function func_get_args; use function implode; use function is_int; @@ -47,15 +34,6 @@ * A wrapper around a Doctrine\DBAL\Driver\Connection that adds features like * events, transaction isolation levels, configuration, emulated transaction nesting, * lazy connecting and more. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * @author Konsta Vesterinen - * @author Lukas Smith (MDB2 library) - * @author Benjamin Eberlei */ class Connection implements DriverConnection { @@ -89,24 +67,18 @@ class Connection implements DriverConnection /** * Represents an array of ints to be expanded by Doctrine SQL parsing. - * - * @var int */ public const PARAM_INT_ARRAY = ParameterType::INTEGER + self::ARRAY_PARAM_OFFSET; /** * Represents an array of strings to be expanded by Doctrine SQL parsing. - * - * @var int */ public const PARAM_STR_ARRAY = ParameterType::STRING + self::ARRAY_PARAM_OFFSET; /** * Offset by which PARAM_* constants are detected as arrays of the param type. - * - * @var int */ - const ARRAY_PARAM_OFFSET = 100; + public const ARRAY_PARAM_OFFSET = 100; /** * The wrapped driver connection. @@ -115,19 +87,13 @@ class Connection implements DriverConnection */ protected $_conn; - /** - * @var \Doctrine\DBAL\Configuration - */ + /** @var Configuration */ protected $_config; - /** - * @var \Doctrine\Common\EventManager - */ + /** @var EventManager */ protected $_eventManager; - /** - * @var \Doctrine\DBAL\Query\Expression\ExpressionBuilder - */ + /** @var ExpressionBuilder */ protected $_expr; /** @@ -135,7 +101,7 @@ class Connection implements DriverConnection * * @var bool */ - private $_isConnected = false; + private $isConnected = false; /** * The current auto-commit mode of this connection. @@ -149,48 +115,48 @@ class Connection implements DriverConnection * * @var int */ - private $_transactionNestingLevel = 0; + private $transactionNestingLevel = 0; /** * The currently active transaction isolation level. * * @var int */ - private $_transactionIsolationLevel; + private $transactionIsolationLevel; /** * If nested transactions should use savepoints. * * @var bool */ - private $_nestTransactionsWithSavepoints = false; + private $nestTransactionsWithSavepoints = false; /** * The parameters used during creation of the Connection instance. * - * @var array + * @var mixed[] */ - private $_params = []; + private $params = []; /** * The DatabasePlatform object that provides information about the * database platform used by the connection. * - * @var \Doctrine\DBAL\Platforms\AbstractPlatform + * @var AbstractPlatform */ private $platform; /** * The schema manager. * - * @var \Doctrine\DBAL\Schema\AbstractSchemaManager + * @var AbstractSchemaManager */ protected $_schemaManager; /** * The used DBAL driver. * - * @var \Doctrine\DBAL\Driver + * @var Driver */ protected $_driver; @@ -199,54 +165,55 @@ class Connection implements DriverConnection * * @var bool */ - private $_isRollbackOnly = false; + private $isRollbackOnly = false; - /** - * @var int - */ + /** @var int */ protected $defaultFetchMode = FetchMode::ASSOCIATIVE; /** * Initializes a new instance of the Connection class. * - * @param array $params The connection parameters. - * @param \Doctrine\DBAL\Driver $driver The driver to use. - * @param \Doctrine\DBAL\Configuration|null $config The configuration, optional. - * @param \Doctrine\Common\EventManager|null $eventManager The event manager, optional. + * @param mixed[] $params The connection parameters. + * @param Driver $driver The driver to use. + * @param Configuration|null $config The configuration, optional. + * @param EventManager|null $eventManager The event manager, optional. * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ - public function __construct(array $params, Driver $driver, Configuration $config = null, - EventManager $eventManager = null) - { + public function __construct( + array $params, + Driver $driver, + ?Configuration $config = null, + ?EventManager $eventManager = null + ) { $this->_driver = $driver; - $this->_params = $params; + $this->params = $params; if (isset($params['pdo'])) { - $this->_conn = $params['pdo']; - $this->_isConnected = true; - unset($this->_params['pdo']); + $this->_conn = $params['pdo']; + $this->isConnected = true; + unset($this->params['pdo']); } - if (isset($params["platform"])) { - if ( ! $params['platform'] instanceof Platforms\AbstractPlatform) { + if (isset($params['platform'])) { + if (! $params['platform'] instanceof Platforms\AbstractPlatform) { throw DBALException::invalidPlatformType($params['platform']); } - $this->platform = $params["platform"]; - unset($this->_params["platform"]); + $this->platform = $params['platform']; + unset($this->params['platform']); } // Create default config and event manager if none given - if ( ! $config) { + if (! $config) { $config = new Configuration(); } - if ( ! $eventManager) { + if (! $eventManager) { $eventManager = new EventManager(); } - $this->_config = $config; + $this->_config = $config; $this->_eventManager = $eventManager; $this->_expr = new Query\Expression\ExpressionBuilder($this); @@ -257,11 +224,11 @@ public function __construct(array $params, Driver $driver, Configuration $config /** * Gets the parameters used during instantiation. * - * @return array + * @return mixed[] */ public function getParams() { - return $this->_params; + return $this->params; } /** @@ -281,7 +248,7 @@ public function getDatabase() */ public function getHost() { - return $this->_params['host'] ?? null; + return $this->params['host'] ?? null; } /** @@ -291,7 +258,7 @@ public function getHost() */ public function getPort() { - return $this->_params['port'] ?? null; + return $this->params['port'] ?? null; } /** @@ -301,7 +268,7 @@ public function getPort() */ public function getUsername() { - return $this->_params['user'] ?? null; + return $this->params['user'] ?? null; } /** @@ -311,13 +278,13 @@ public function getUsername() */ public function getPassword() { - return $this->_params['password'] ?? null; + return $this->params['password'] ?? null; } /** * Gets the DBAL driver instance. * - * @return \Doctrine\DBAL\Driver + * @return Driver */ public function getDriver() { @@ -327,7 +294,7 @@ public function getDriver() /** * Gets the Configuration used by the Connection. * - * @return \Doctrine\DBAL\Configuration + * @return Configuration */ public function getConfiguration() { @@ -337,7 +304,7 @@ public function getConfiguration() /** * Gets the EventManager used by the Connection. * - * @return \Doctrine\Common\EventManager + * @return EventManager */ public function getEventManager() { @@ -347,13 +314,13 @@ public function getEventManager() /** * Gets the DatabasePlatform for the connection. * - * @return \Doctrine\DBAL\Platforms\AbstractPlatform + * @return AbstractPlatform * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ public function getDatabasePlatform() { - if (null === $this->platform) { + if ($this->platform === null) { $this->detectDatabasePlatform(); } @@ -363,7 +330,7 @@ public function getDatabasePlatform() /** * Gets the ExpressionBuilder for the connection. * - * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder + * @return ExpressionBuilder */ public function getExpressionBuilder() { @@ -378,18 +345,18 @@ public function getExpressionBuilder() */ public function connect() { - if ($this->_isConnected) { + if ($this->isConnected) { return false; } - $driverOptions = $this->_params['driverOptions'] ?? []; - $user = $this->_params['user'] ?? null; - $password = $this->_params['password'] ?? null; + $driverOptions = $this->params['driverOptions'] ?? []; + $user = $this->params['user'] ?? null; + $password = $this->params['password'] ?? null; - $this->_conn = $this->_driver->connect($this->_params, $user, $password, $driverOptions); - $this->_isConnected = true; + $this->_conn = $this->_driver->connect($this->params, $user, $password, $driverOptions); + $this->isConnected = true; - if (false === $this->autoCommit) { + if ($this->autoCommit === false) { $this->beginTransaction(); } @@ -406,7 +373,7 @@ public function connect() * * Evaluates custom platform class and version in order to set the correct platform. * - * @throws DBALException if an invalid platform was specified for this connection. + * @throws DBALException If an invalid platform was specified for this connection. */ private function detectDatabasePlatform() { @@ -438,50 +405,49 @@ private function detectDatabasePlatform() private function getDatabasePlatformVersion() { // Driver does not support version specific platforms. - if ( ! $this->_driver instanceof VersionAwarePlatformDriver) { + if (! $this->_driver instanceof VersionAwarePlatformDriver) { return null; } // Explicit platform version requested (supersedes auto-detection). - if (isset($this->_params['serverVersion'])) { - return $this->_params['serverVersion']; + if (isset($this->params['serverVersion'])) { + return $this->params['serverVersion']; } // If not connected, we need to connect now to determine the platform version. - if (null === $this->_conn) { + if ($this->_conn === null) { try { $this->connect(); - } catch (\Exception $originalException) { - if (empty($this->_params['dbname'])) { + } catch (Throwable $originalException) { + if (empty($this->params['dbname'])) { throw $originalException; } // The database to connect to might not yet exist. // Retry detection without database name connection parameter. - $databaseName = $this->_params['dbname']; - $this->_params['dbname'] = null; + $databaseName = $this->params['dbname']; + $this->params['dbname'] = null; try { $this->connect(); - } catch (\Exception $fallbackException) { + } catch (Throwable $fallbackException) { // Either the platform does not support database-less connections // or something else went wrong. // Reset connection parameters and rethrow the original exception. - $this->_params['dbname'] = $databaseName; + $this->params['dbname'] = $databaseName; throw $originalException; } // Reset connection parameters. - $this->_params['dbname'] = $databaseName; - $serverVersion = $this->getServerVersion(); + $this->params['dbname'] = $databaseName; + $serverVersion = $this->getServerVersion(); // Close "temporary" connection to allow connecting to the real database again. $this->close(); return $serverVersion; } - } return $this->getServerVersion(); @@ -508,13 +474,13 @@ private function getServerVersion() /** * Returns the current auto-commit mode for this connection. * - * @return bool True if auto-commit mode is currently enabled for this connection, false otherwise. - * * @see setAutoCommit + * + * @return bool True if auto-commit mode is currently enabled for this connection, false otherwise. */ public function isAutoCommit() { - return true === $this->autoCommit; + return $this->autoCommit === true; } /** @@ -527,13 +493,13 @@ public function isAutoCommit() * NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is * committed. If this method is called and the auto-commit mode is not changed, the call is a no-op. * - * @param bool $autoCommit True to enable auto-commit mode; false to disable it. - * * @see isAutoCommit + * + * @param bool $autoCommit True to enable auto-commit mode; false to disable it. */ public function setAutoCommit($autoCommit) { - $autoCommit = (boolean) $autoCommit; + $autoCommit = (bool) $autoCommit; // Mode not changed, no-op. if ($autoCommit === $this->autoCommit) { @@ -543,9 +509,11 @@ public function setAutoCommit($autoCommit) $this->autoCommit = $autoCommit; // Commit all currently active transactions if any when switching auto-commit mode. - if (true === $this->_isConnected && 0 !== $this->_transactionNestingLevel) { - $this->commitAll(); + if ($this->isConnected !== true || $this->transactionNestingLevel === 0) { + return; } + + $this->commitAll(); } /** @@ -564,13 +532,13 @@ public function setFetchMode($fetchMode) * Prepares and executes an SQL query and returns the first row of the result * as an associative array. * - * @param string $statement The SQL query. - * @param array $params The query parameters. - * @param array $types The query parameter types. + * @param string $statement The SQL query. + * @param mixed[] $params The query parameters. + * @param int[]|string[] $types The query parameter types. * - * @return array|bool False is returned if no rows are found. + * @return mixed[]|false False is returned if no rows are found. * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ public function fetchAssoc($statement, array $params = [], array $types = []) { @@ -581,11 +549,11 @@ public function fetchAssoc($statement, array $params = [], array $types = []) * Prepares and executes an SQL query and returns the first row of the result * as a numerically indexed array. * - * @param string $statement The SQL query to be executed. - * @param array $params The prepared statement params. - * @param array $types The query parameter types. + * @param string $statement The SQL query to be executed. + * @param mixed[] $params The prepared statement params. + * @param int[]|string[] $types The query parameter types. * - * @return array|bool False is returned if no rows are found. + * @return mixed[]|false False is returned if no rows are found. */ public function fetchArray($statement, array $params = [], array $types = []) { @@ -596,14 +564,14 @@ public function fetchArray($statement, array $params = [], array $types = []) * Prepares and executes an SQL query and returns the value of a single column * of the first row of the result. * - * @param string $statement The SQL query to be executed. - * @param array $params The prepared statement params. - * @param int $column The 0-indexed column number to retrieve. - * @param array $types The query parameter types. + * @param string $statement The SQL query to be executed. + * @param mixed[] $params The prepared statement params. + * @param int $column The 0-indexed column number to retrieve. + * @param int[]|string[] $types The query parameter types. * - * @return mixed|bool False is returned if no rows are found. + * @return mixed|false False is returned if no rows are found. * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ public function fetchColumn($statement, array $params = [], $column = 0, array $types = []) { @@ -617,7 +585,7 @@ public function fetchColumn($statement, array $params = [], $column = 0, array $ */ public function isConnected() { - return $this->_isConnected; + return $this->isConnected; } /** @@ -627,13 +595,13 @@ public function isConnected() */ public function isTransactionActive() { - return $this->_transactionNestingLevel > 0; + return $this->transactionNestingLevel > 0; } /** * Gathers conditions for an update or delete call. * - * @param array $identifiers Input array of columns to values + * @param mixed[] $identifiers Input array of columns to values * * @return string[][] a triplet with: * - the first key being the columns @@ -642,18 +610,18 @@ public function isTransactionActive() */ private function gatherConditions(array $identifiers) { - $columns = []; - $values = []; + $columns = []; + $values = []; $conditions = []; foreach ($identifiers as $columnName => $value) { - if (null === $value) { + if ($value === null) { $conditions[] = $this->getDatabasePlatform()->getIsNullExpression($columnName); continue; } - $columns[] = $columnName; - $values[] = $value; + $columns[] = $columnName; + $values[] = $value; $conditions[] = $columnName . ' = ?'; } @@ -665,13 +633,13 @@ private function gatherConditions(array $identifiers) * * Table expression and columns are not escaped and are not safe for user-input. * - * @param string $tableExpression The expression of the table on which to delete. - * @param array $identifier The deletion criteria. An associative array containing column-value pairs. - * @param array $types The types of identifiers. + * @param string $tableExpression The expression of the table on which to delete. + * @param mixed[] $identifier The deletion criteria. An associative array containing column-value pairs. + * @param int[]|string[] $types The types of identifiers. * * @return int The number of affected rows. * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException * @throws InvalidArgumentException */ public function delete($tableExpression, array $identifier, array $types = []) @@ -680,7 +648,7 @@ public function delete($tableExpression, array $identifier, array $types = []) throw InvalidArgumentException::fromEmptyCriteria(); } - list($columns, $values, $conditions) = $this->gatherConditions($identifier); + [$columns, $values, $conditions] = $this->gatherConditions($identifier); return $this->executeUpdate( 'DELETE FROM ' . $tableExpression . ' WHERE ' . implode(' AND ', $conditions), @@ -698,7 +666,7 @@ public function close() { $this->_conn = null; - $this->_isConnected = false; + $this->isConnected = false; } /** @@ -710,7 +678,7 @@ public function close() */ public function setTransactionIsolation($level) { - $this->_transactionIsolationLevel = $level; + $this->transactionIsolationLevel = $level; return $this->executeUpdate($this->getDatabasePlatform()->getSetTransactionIsolationSQL($level)); } @@ -722,11 +690,11 @@ public function setTransactionIsolation($level) */ public function getTransactionIsolation() { - if (null === $this->_transactionIsolationLevel) { - $this->_transactionIsolationLevel = $this->getDatabasePlatform()->getDefaultTransactionIsolationLevel(); + if ($this->transactionIsolationLevel === null) { + $this->transactionIsolationLevel = $this->getDatabasePlatform()->getDefaultTransactionIsolationLevel(); } - return $this->_transactionIsolationLevel; + return $this->transactionIsolationLevel; } /** @@ -734,36 +702,36 @@ public function getTransactionIsolation() * * Table expression and columns are not escaped and are not safe for user-input. * - * @param string $tableExpression The expression of the table to update quoted or unquoted. - * @param array $data An associative array containing column-value pairs. - * @param array $identifier The update criteria. An associative array containing column-value pairs. - * @param array $types Types of the merged $data and $identifier arrays in that order. + * @param string $tableExpression The expression of the table to update quoted or unquoted. + * @param mixed[] $data An associative array containing column-value pairs. + * @param mixed[] $identifier The update criteria. An associative array containing column-value pairs. + * @param int[]|string[] $types Types of the merged $data and $identifier arrays in that order. * * @return int The number of affected rows. * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ public function update($tableExpression, array $data, array $identifier, array $types = []) { $setColumns = []; - $setValues = []; - $set = []; + $setValues = []; + $set = []; foreach ($data as $columnName => $value) { $setColumns[] = $columnName; - $setValues[] = $value; - $set[] = $columnName . ' = ?'; + $setValues[] = $value; + $set[] = $columnName . ' = ?'; } - list($conditionColumns, $conditionValues, $conditions) = $this->gatherConditions($identifier); - $columns = array_merge($setColumns, $conditionColumns); - $values = array_merge($setValues, $conditionValues); + [$conditionColumns, $conditionValues, $conditions] = $this->gatherConditions($identifier); + $columns = array_merge($setColumns, $conditionColumns); + $values = array_merge($setValues, $conditionValues); if (is_string(key($types))) { $types = $this->extractTypeValues($columns, $types); } - $sql = 'UPDATE ' . $tableExpression . ' SET ' . implode(', ', $set) + $sql = 'UPDATE ' . $tableExpression . ' SET ' . implode(', ', $set) . ' WHERE ' . implode(' AND ', $conditions); return $this->executeUpdate($sql, $values, $types); @@ -774,28 +742,28 @@ public function update($tableExpression, array $data, array $identifier, array $ * * Table expression and columns are not escaped and are not safe for user-input. * - * @param string $tableExpression The expression of the table to insert data into, quoted or unquoted. - * @param array $data An associative array containing column-value pairs. - * @param array $types Types of the inserted data. + * @param string $tableExpression The expression of the table to insert data into, quoted or unquoted. + * @param mixed[] $data An associative array containing column-value pairs. + * @param int[]|string[] $types Types of the inserted data. * * @return int The number of affected rows. * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ public function insert($tableExpression, array $data, array $types = []) { if (empty($data)) { - return $this->executeUpdate('INSERT INTO ' . $tableExpression . ' ()' . ' VALUES ()'); + return $this->executeUpdate('INSERT INTO ' . $tableExpression . ' () VALUES ()'); } $columns = []; - $values = []; - $set = []; + $values = []; + $set = []; foreach ($data as $columnName => $value) { $columns[] = $columnName; - $values[] = $value; - $set[] = '?'; + $values[] = $value; + $set[] = '?'; } return $this->executeUpdate( @@ -809,10 +777,10 @@ public function insert($tableExpression, array $data, array $types = []) /** * Extract ordered type list from an ordered column list and type map. * - * @param array $columnList - * @param array $types + * @param string[] $columnList + * @param int[]|string[] $types * - * @return array + * @return int[]|string[] */ private function extractTypeValues(array $columnList, array $types) { @@ -856,7 +824,7 @@ public function quote($input, $type = null) { $this->connect(); - list($value, $bindingType) = $this->getBindingInfo($input, $type); + [$value, $bindingType] = $this->getBindingInfo($input, $type); return $this->_conn->quote($value, $bindingType); } @@ -864,11 +832,11 @@ public function quote($input, $type = null) /** * Prepares and executes an SQL query and returns the result as an associative array. * - * @param string $sql The SQL query. - * @param array $params The query parameters. - * @param array $types The query parameter types. + * @param string $sql The SQL query. + * @param mixed[] $params The query parameters. + * @param int[]|string[] $types The query parameter types. * - * @return array + * @return mixed[] */ public function fetchAll($sql, array $params = [], $types = []) { @@ -882,13 +850,13 @@ public function fetchAll($sql, array $params = [], $types = []) * * @return DriverStatement The prepared statement. * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ public function prepare($statement) { try { $stmt = new Statement($statement, $this); - } catch (Exception $ex) { + } catch (Throwable $ex) { throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement); } @@ -903,16 +871,16 @@ public function prepare($statement) * If the query is parametrized, a prepared statement is used. * If an SQLLogger is configured, the execution is logged. * - * @param string $query The SQL query to execute. - * @param array $params The parameters to bind to the query, if any. - * @param array $types The types the previous parameters are in. - * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp The query cache profile, optional. + * @param string $query The SQL query to execute. + * @param mixed[] $params The parameters to bind to the query, if any. + * @param int[]|string[] $types The types the previous parameters are in. + * @param QueryCacheProfile|null $qcp The query cache profile, optional. * * @return ResultStatement The executed statement. * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ - public function executeQuery($query, array $params = [], $types = [], QueryCacheProfile $qcp = null) + public function executeQuery($query, array $params = [], $types = [], ?QueryCacheProfile $qcp = null) { if ($qcp !== null) { return $this->executeCacheQuery($query, $params, $types, $qcp); @@ -927,7 +895,7 @@ public function executeQuery($query, array $params = [], $types = [], QueryCache try { if ($params) { - list($query, $params, $types) = SQLParserUtils::expandListParameters($query, $params, $types); + [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types); $stmt = $this->_conn->prepare($query); if ($types) { @@ -939,7 +907,7 @@ public function executeQuery($query, array $params = [], $types = [], QueryCache } else { $stmt = $this->_conn->query($query); } - } catch (Exception $ex) { + } catch (Throwable $ex) { throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types)); } @@ -955,26 +923,28 @@ public function executeQuery($query, array $params = [], $types = [], QueryCache /** * Executes a caching query. * - * @param string $query The SQL query to execute. - * @param array $params The parameters to bind to the query, if any. - * @param array $types The types the previous parameters are in. - * @param \Doctrine\DBAL\Cache\QueryCacheProfile $qcp The query cache profile. + * @param string $query The SQL query to execute. + * @param mixed[] $params The parameters to bind to the query, if any. + * @param int[]|string[] $types The types the previous parameters are in. + * @param QueryCacheProfile $qcp The query cache profile. * * @return ResultStatement * - * @throws \Doctrine\DBAL\Cache\CacheException + * @throws CacheException */ public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qcp) { $resultCache = $qcp->getResultCacheDriver() ?: $this->_config->getResultCacheImpl(); - if ( ! $resultCache) { + if (! $resultCache) { throw CacheException::noResultDriverConfigured(); } - list($cacheKey, $realKey) = $qcp->generateCacheKeys($query, $params, $types, $this->getParams()); + [$cacheKey, $realKey] = $qcp->generateCacheKeys($query, $params, $types, $this->getParams()); // fetch the row pointers entry - if ($data = $resultCache->fetch($cacheKey)) { + $data = $resultCache->fetch($cacheKey); + + if ($data !== false) { // is the real key part of this row pointers map or is the cache only pointing to other cache keys? if (isset($data[$realKey])) { $stmt = new ArrayStatement($data[$realKey]); @@ -983,7 +953,7 @@ public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qc } } - if (!isset($stmt)) { + if (! isset($stmt)) { $stmt = new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime()); } @@ -996,18 +966,18 @@ public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qc * Executes an, optionally parametrized, SQL query and returns the result, * applying a given projection/transformation function on each row of the result. * - * @param string $query The SQL query to execute. - * @param array $params The parameters, if any. - * @param \Closure $function The transformation function that is applied on each row. + * @param string $query The SQL query to execute. + * @param mixed[] $params The parameters, if any. + * @param Closure $function The transformation function that is applied on each row. * The function receives a single parameter, an array, that * represents a row of the result set. * - * @return array The projected result of the query. + * @return mixed[] The projected result of the query. */ public function project($query, array $params, Closure $function) { $result = []; - $stmt = $this->executeQuery($query, $params); + $stmt = $this->executeQuery($query, $params); while ($row = $stmt->fetch()) { $result[] = $function($row); @@ -1023,7 +993,7 @@ public function project($query, array $params, Closure $function) * * @return \Doctrine\DBAL\Driver\Statement * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ public function query() { @@ -1038,7 +1008,7 @@ public function query() try { $statement = $this->_conn->query(...$args); - } catch (Exception $ex) { + } catch (Throwable $ex) { throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $args[0]); } @@ -1057,13 +1027,13 @@ public function query() * * This method supports PDO binding types as well as DBAL mapping types. * - * @param string $query The SQL query. - * @param array $params The query parameters. - * @param array $types The parameter types. + * @param string $query The SQL query. + * @param mixed[] $params The query parameters. + * @param int[]|string[] $types The parameter types. * * @return int The number of affected rows. * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ public function executeUpdate($query, array $params = [], array $types = []) { @@ -1076,7 +1046,7 @@ public function executeUpdate($query, array $params = [], array $types = []) try { if ($params) { - list($query, $params, $types) = SQLParserUtils::expandListParameters($query, $params, $types); + [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types); $stmt = $this->_conn->prepare($query); if ($types) { @@ -1089,7 +1059,7 @@ public function executeUpdate($query, array $params = [], array $types = []) } else { $result = $this->_conn->exec($query); } - } catch (Exception $ex) { + } catch (Throwable $ex) { throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types)); } @@ -1107,7 +1077,7 @@ public function executeUpdate($query, array $params = [], array $types = []) * * @return int The number of affected rows. * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ public function exec($statement) { @@ -1120,7 +1090,7 @@ public function exec($statement) try { $result = $this->_conn->exec($statement); - } catch (Exception $ex) { + } catch (Throwable $ex) { throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement); } @@ -1138,7 +1108,7 @@ public function exec($statement) */ public function getTransactionNestingLevel() { - return $this->_transactionNestingLevel; + return $this->transactionNestingLevel; } /** @@ -1154,9 +1124,7 @@ public function errorCode() } /** - * Fetches extended error information associated with the last database operation. - * - * @return array The last error information. + * {@inheritDoc} */ public function errorInfo() { @@ -1192,7 +1160,7 @@ public function lastInsertId($seqName = null) * If an exception occurs during execution of the function or transaction commit, * the transaction is rolled back and the exception re-thrown. * - * @param \Closure $func The function to execute transactionally. + * @param Closure $func The function to execute transactionally. * * @return mixed The value returned by $func * @@ -1222,19 +1190,19 @@ public function transactional(Closure $func) * * @return void * - * @throws \Doctrine\DBAL\ConnectionException + * @throws ConnectionException */ public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints) { - if ($this->_transactionNestingLevel > 0) { + if ($this->transactionNestingLevel > 0) { throw ConnectionException::mayNotAlterNestedTransactionWithSavepointsInTransaction(); } - if ( ! $this->getDatabasePlatform()->supportsSavepoints()) { + if (! $this->getDatabasePlatform()->supportsSavepoints()) { throw ConnectionException::savepointsNotSupported(); } - $this->_nestTransactionsWithSavepoints = (bool) $nestTransactionsWithSavepoints; + $this->nestTransactionsWithSavepoints = (bool) $nestTransactionsWithSavepoints; } /** @@ -1244,7 +1212,7 @@ public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoint */ public function getNestTransactionsWithSavepoints() { - return $this->_nestTransactionsWithSavepoints; + return $this->nestTransactionsWithSavepoints; } /** @@ -1255,7 +1223,7 @@ public function getNestTransactionsWithSavepoints() */ protected function _getNestedTransactionSavePointName() { - return 'DOCTRINE2_SAVEPOINT_'.$this->_transactionNestingLevel; + return 'DOCTRINE2_SAVEPOINT_' . $this->transactionNestingLevel; } /** @@ -1267,11 +1235,11 @@ public function beginTransaction() { $this->connect(); - ++$this->_transactionNestingLevel; + ++$this->transactionNestingLevel; $logger = $this->_config->getSQLLogger(); - if ($this->_transactionNestingLevel == 1) { + if ($this->transactionNestingLevel === 1) { if ($logger) { $logger->startQuery('"START TRANSACTION"'); } @@ -1279,7 +1247,7 @@ public function beginTransaction() if ($logger) { $logger->stopQuery(); } - } elseif ($this->_nestTransactionsWithSavepoints) { + } elseif ($this->nestTransactionsWithSavepoints) { if ($logger) { $logger->startQuery('"SAVEPOINT"'); } @@ -1295,15 +1263,15 @@ public function beginTransaction() * * @return void * - * @throws \Doctrine\DBAL\ConnectionException If the commit failed due to no active transaction or + * @throws ConnectionException If the commit failed due to no active transaction or * because the transaction was marked for rollback only. */ public function commit() { - if ($this->_transactionNestingLevel == 0) { + if ($this->transactionNestingLevel === 0) { throw ConnectionException::noActiveTransaction(); } - if ($this->_isRollbackOnly) { + if ($this->isRollbackOnly) { throw ConnectionException::commitFailedRollbackOnly(); } @@ -1311,7 +1279,7 @@ public function commit() $logger = $this->_config->getSQLLogger(); - if ($this->_transactionNestingLevel == 1) { + if ($this->transactionNestingLevel === 1) { if ($logger) { $logger->startQuery('"COMMIT"'); } @@ -1319,7 +1287,7 @@ public function commit() if ($logger) { $logger->stopQuery(); } - } elseif ($this->_nestTransactionsWithSavepoints) { + } elseif ($this->nestTransactionsWithSavepoints) { if ($logger) { $logger->startQuery('"RELEASE SAVEPOINT"'); } @@ -1329,11 +1297,13 @@ public function commit() } } - --$this->_transactionNestingLevel; + --$this->transactionNestingLevel; - if (false === $this->autoCommit && 0 === $this->_transactionNestingLevel) { - $this->beginTransaction(); + if ($this->autoCommit !== false || $this->transactionNestingLevel !== 0) { + return; } + + $this->beginTransaction(); } /** @@ -1341,8 +1311,8 @@ public function commit() */ private function commitAll() { - while (0 !== $this->_transactionNestingLevel) { - if (false === $this->autoCommit && 1 === $this->_transactionNestingLevel) { + while ($this->transactionNestingLevel !== 0) { + if ($this->autoCommit === false && $this->transactionNestingLevel === 1) { // When in no auto-commit mode, the last nesting commit immediately starts a new transaction. // Therefore we need to do the final commit here and then leave to avoid an infinite loop. $this->commit(); @@ -1357,11 +1327,11 @@ private function commitAll() /** * Cancels any database changes done during the current transaction. * - * @throws \Doctrine\DBAL\ConnectionException If the rollback operation failed. + * @throws ConnectionException If the rollback operation failed. */ public function rollBack() { - if ($this->_transactionNestingLevel == 0) { + if ($this->transactionNestingLevel === 0) { throw ConnectionException::noActiveTransaction(); } @@ -1369,32 +1339,32 @@ public function rollBack() $logger = $this->_config->getSQLLogger(); - if ($this->_transactionNestingLevel == 1) { + if ($this->transactionNestingLevel === 1) { if ($logger) { $logger->startQuery('"ROLLBACK"'); } - $this->_transactionNestingLevel = 0; + $this->transactionNestingLevel = 0; $this->_conn->rollBack(); - $this->_isRollbackOnly = false; + $this->isRollbackOnly = false; if ($logger) { $logger->stopQuery(); } - if (false === $this->autoCommit) { + if ($this->autoCommit === false) { $this->beginTransaction(); } - } elseif ($this->_nestTransactionsWithSavepoints) { + } elseif ($this->nestTransactionsWithSavepoints) { if ($logger) { $logger->startQuery('"ROLLBACK TO SAVEPOINT"'); } $this->rollbackSavepoint($this->_getNestedTransactionSavePointName()); - --$this->_transactionNestingLevel; + --$this->transactionNestingLevel; if ($logger) { $logger->stopQuery(); } } else { - $this->_isRollbackOnly = true; - --$this->_transactionNestingLevel; + $this->isRollbackOnly = true; + --$this->transactionNestingLevel; } } @@ -1405,11 +1375,11 @@ public function rollBack() * * @return void * - * @throws \Doctrine\DBAL\ConnectionException + * @throws ConnectionException */ public function createSavepoint($savepoint) { - if ( ! $this->getDatabasePlatform()->supportsSavepoints()) { + if (! $this->getDatabasePlatform()->supportsSavepoints()) { throw ConnectionException::savepointsNotSupported(); } @@ -1423,17 +1393,19 @@ public function createSavepoint($savepoint) * * @return void * - * @throws \Doctrine\DBAL\ConnectionException + * @throws ConnectionException */ public function releaseSavepoint($savepoint) { - if ( ! $this->getDatabasePlatform()->supportsSavepoints()) { + if (! $this->getDatabasePlatform()->supportsSavepoints()) { throw ConnectionException::savepointsNotSupported(); } - if ($this->platform->supportsReleaseSavepoints()) { - $this->_conn->exec($this->platform->releaseSavePoint($savepoint)); + if (! $this->platform->supportsReleaseSavepoints()) { + return; } + + $this->_conn->exec($this->platform->releaseSavePoint($savepoint)); } /** @@ -1443,11 +1415,11 @@ public function releaseSavepoint($savepoint) * * @return void * - * @throws \Doctrine\DBAL\ConnectionException + * @throws ConnectionException */ public function rollbackSavepoint($savepoint) { - if ( ! $this->getDatabasePlatform()->supportsSavepoints()) { + if (! $this->getDatabasePlatform()->supportsSavepoints()) { throw ConnectionException::savepointsNotSupported(); } @@ -1470,11 +1442,11 @@ public function getWrappedConnection() * Gets the SchemaManager that can be used to inspect or change the * database schema through the connection. * - * @return \Doctrine\DBAL\Schema\AbstractSchemaManager + * @return AbstractSchemaManager */ public function getSchemaManager() { - if ( ! $this->_schemaManager) { + if (! $this->_schemaManager) { $this->_schemaManager = $this->_driver->getSchemaManager($this); } @@ -1487,14 +1459,14 @@ public function getSchemaManager() * * @return void * - * @throws \Doctrine\DBAL\ConnectionException If no transaction is active. + * @throws ConnectionException If no transaction is active. */ public function setRollbackOnly() { - if ($this->_transactionNestingLevel == 0) { + if ($this->transactionNestingLevel === 0) { throw ConnectionException::noActiveTransaction(); } - $this->_isRollbackOnly = true; + $this->isRollbackOnly = true; } /** @@ -1502,15 +1474,15 @@ public function setRollbackOnly() * * @return bool * - * @throws \Doctrine\DBAL\ConnectionException If no transaction is active. + * @throws ConnectionException If no transaction is active. */ public function isRollbackOnly() { - if ($this->_transactionNestingLevel == 0) { + if ($this->transactionNestingLevel === 0) { throw ConnectionException::noActiveTransaction(); } - return $this->_isRollbackOnly; + return $this->isRollbackOnly; } /** @@ -1545,14 +1517,14 @@ public function convertToPHPValue($value, $type) * Binds a set of parameters, some or all of which are typed with a PDO binding type * or DBAL mapping type, to a given statement. * + * @internal Duck-typing used on the $stmt parameter to support driver statements as well as + * raw PDOStatement instances. + * * @param \Doctrine\DBAL\Driver\Statement $stmt The statement to bind the values to. - * @param array $params The map/list of named/positional parameters. - * @param array $types The parameter types (PDO binding types or DBAL mapping types). + * @param mixed[] $params The map/list of named/positional parameters. + * @param int[]|string[] $types The parameter types (PDO binding types or DBAL mapping types). * * @return void - * - * @internal Duck-typing used on the $stmt parameter to support driver statements as well as - * raw PDOStatement instances. */ private function _bindTypedValues($stmt, array $params, array $types) { @@ -1560,12 +1532,12 @@ private function _bindTypedValues($stmt, array $params, array $types) if (is_int(key($params))) { // Positional parameters $typeOffset = array_key_exists(0, $types) ? -1 : 0; - $bindIndex = 1; + $bindIndex = 1; foreach ($params as $value) { $typeIndex = $bindIndex + $typeOffset; if (isset($types[$typeIndex])) { - $type = $types[$typeIndex]; - list($value, $bindingType) = $this->getBindingInfo($value, $type); + $type = $types[$typeIndex]; + [$value, $bindingType] = $this->getBindingInfo($value, $type); $stmt->bindValue($bindIndex, $value, $bindingType); } else { $stmt->bindValue($bindIndex, $value); @@ -1576,8 +1548,8 @@ private function _bindTypedValues($stmt, array $params, array $types) // Named parameters foreach ($params as $name => $value) { if (isset($types[$name])) { - $type = $types[$name]; - list($value, $bindingType) = $this->getBindingInfo($value, $type); + $type = $types[$name]; + [$value, $bindingType] = $this->getBindingInfo($value, $type); $stmt->bindValue($name, $value, $bindingType); } else { $stmt->bindValue($name, $value); @@ -1589,10 +1561,10 @@ private function _bindTypedValues($stmt, array $params, array $types) /** * Gets the binding type of a given type. The given type can be a PDO or DBAL mapping type. * - * @param mixed $value The value to bind. - * @param mixed $type The type to bind (PDO or DBAL). + * @param mixed $value The value to bind. + * @param int|string $type The type to bind (PDO or DBAL). * - * @return array [0] => the (escaped) value, [1] => the binding type. + * @return mixed[] [0] => the (escaped) value, [1] => the binding type. */ private function getBindingInfo($value, $type) { @@ -1600,7 +1572,7 @@ private function getBindingInfo($value, $type) $type = Type::getType($type); } if ($type instanceof Type) { - $value = $type->convertToDatabaseValue($value, $this->getDatabasePlatform()); + $value = $type->convertToDatabaseValue($value, $this->getDatabasePlatform()); $bindingType = $type->getBindingType(); } else { $bindingType = $type; @@ -1615,10 +1587,10 @@ private function getBindingInfo($value, $type) * @internal This is a purely internal method. If you rely on this method, you are advised to * copy/paste the code as this method may change, or be removed without prior notice. * - * @param array $params - * @param array $types + * @param mixed[] $params + * @param int[]|string[] $types * - * @return array + * @return mixed[] */ public function resolveParams(array $params, array $types) { @@ -1628,12 +1600,12 @@ public function resolveParams(array $params, array $types) if (is_int(key($params))) { // Positional parameters $typeOffset = array_key_exists(0, $types) ? -1 : 0; - $bindIndex = 1; + $bindIndex = 1; foreach ($params as $value) { $typeIndex = $bindIndex + $typeOffset; if (isset($types[$typeIndex])) { - $type = $types[$typeIndex]; - list($value,) = $this->getBindingInfo($value, $type); + $type = $types[$typeIndex]; + [$value] = $this->getBindingInfo($value, $type); $resolvedParams[$bindIndex] = $value; } else { $resolvedParams[$bindIndex] = $value; @@ -1644,8 +1616,8 @@ public function resolveParams(array $params, array $types) // Named parameters foreach ($params as $name => $value) { if (isset($types[$name])) { - $type = $types[$name]; - list($value,) = $this->getBindingInfo($value, $type); + $type = $types[$name]; + [$value] = $this->getBindingInfo($value, $type); $resolvedParams[$name] = $value; } else { $resolvedParams[$name] = $value; @@ -1659,7 +1631,7 @@ public function resolveParams(array $params, array $types) /** * Creates a new instance of a SQL query builder. * - * @return \Doctrine\DBAL\Query\QueryBuilder + * @return QueryBuilder */ public function createQueryBuilder() { @@ -1673,6 +1645,8 @@ public function createQueryBuilder() * It is responsibility of the developer to handle this case * and abort the request or reconnect manually: * + * @return bool + * * @example * * if ($conn->ping() === false) { @@ -1684,8 +1658,6 @@ public function createQueryBuilder() * or disconnect when the connection is not available anymore * as long it returns TRUE when a reconnect succeeded and * FALSE when the connection was dropped. - * - * @return bool */ public function ping() { diff --git a/lib/Doctrine/DBAL/ConnectionException.php b/lib/Doctrine/DBAL/ConnectionException.php index 86494b0361a..d3d11bc6743 100644 --- a/lib/Doctrine/DBAL/ConnectionException.php +++ b/lib/Doctrine/DBAL/ConnectionException.php @@ -1,29 +1,7 @@ . - */ namespace Doctrine\DBAL; -/** - * @link www.doctrine-project.org - * @since 2.0 - * @author Jonathan H. Wage . - */ namespace Doctrine\DBAL\Connections; +use Doctrine\Common\EventManager; +use Doctrine\DBAL\Configuration; use Doctrine\DBAL\Connection; use Doctrine\DBAL\Driver; use Doctrine\DBAL\Driver\Connection as DriverConnection; -use Doctrine\DBAL\Configuration; -use Doctrine\Common\EventManager; use Doctrine\DBAL\Event\ConnectionEventArgs; use Doctrine\DBAL\Events; +use InvalidArgumentException; use function array_rand; use function count; use function func_get_args; @@ -80,9 +64,6 @@ * )); * * You can also pass 'driverOptions' and any other documented option to each of this drivers to pass additional information. - * - * @author Lars Strojny - * @author Benjamin Eberlei */ class MasterSlaveConnection extends Connection { @@ -104,20 +85,17 @@ class MasterSlaveConnection extends Connection /** * Creates Master Slave Connection. * - * @param array $params - * @param \Doctrine\DBAL\Driver $driver - * @param \Doctrine\DBAL\Configuration|null $config - * @param \Doctrine\Common\EventManager|null $eventManager + * @param mixed[] $params * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ - public function __construct(array $params, Driver $driver, Configuration $config = null, EventManager $eventManager = null) + public function __construct(array $params, Driver $driver, ?Configuration $config = null, ?EventManager $eventManager = null) { if (! isset($params['slaves'], $params['master'])) { - throw new \InvalidArgumentException('master or slaves configuration missing'); + throw new InvalidArgumentException('master or slaves configuration missing'); } - if (count($params['slaves']) == 0) { - throw new \InvalidArgumentException('You have to configure at least one slaves.'); + if (count($params['slaves']) === 0) { + throw new InvalidArgumentException('You have to configure at least one slaves.'); } $params['master']['driver'] = $params['driver']; @@ -149,13 +127,13 @@ public function connect($connectionName = null) $connectionName = $connectionName ?: 'slave'; if ($connectionName !== 'slave' && $connectionName !== 'master') { - throw new \InvalidArgumentException("Invalid option to connect(), only master or slave allowed."); + throw new InvalidArgumentException('Invalid option to connect(), only master or slave allowed.'); } // If we have a connection open, and this is not an explicit connection // change request, then abort right here, because we are already done. // This prevents writes to the slave in case of "keepSlave" option enabled. - if (isset($this->_conn) && $this->_conn && !$requestedConnectionChange) { + if (isset($this->_conn) && $this->_conn && ! $requestedConnectionChange) { return false; } @@ -180,7 +158,7 @@ public function connect($connectionName = null) $this->connections['master'] = $this->_conn = $this->connectTo($connectionName); // Set slave connection to master to avoid invalid reads - if ( ! $this->keepSlave) { + if (! $this->keepSlave) { $this->connections['slave'] = $this->connections['master']; } } else { @@ -210,15 +188,15 @@ protected function connectTo($connectionName) $connectionParams = $this->chooseConnectionConfiguration($connectionName, $params); - $user = $connectionParams['user'] ?? null; + $user = $connectionParams['user'] ?? null; $password = $connectionParams['password'] ?? null; return $this->_driver->connect($connectionParams, $user, $password, $driverOptions); } /** - * @param string $connectionName - * @param array $params + * @param string $connectionName + * @param mixed[] $params * * @return mixed */ @@ -230,7 +208,7 @@ protected function chooseConnectionConfiguration($connectionName, $params) $config = $params['slaves'][array_rand($params['slaves'])]; - if ( ! isset($config['charset']) && isset($params['master']['charset'])) { + if (! isset($config['charset']) && isset($params['master']['charset'])) { $config['charset'] = $params['master']['charset']; } @@ -296,7 +274,7 @@ public function close() parent::close(); - $this->_conn = null; + $this->_conn = null; $this->connections = ['master' => null, 'slave' => null]; } diff --git a/lib/Doctrine/DBAL/DBALException.php b/lib/Doctrine/DBAL/DBALException.php index 67265d954fb..15bac7f0f66 100644 --- a/lib/Doctrine/DBAL/DBALException.php +++ b/lib/Doctrine/DBAL/DBALException.php @@ -1,38 +1,26 @@ . - */ namespace Doctrine\DBAL; -use Doctrine\DBAL\Exception; -use Doctrine\DBAL\Driver; +use Doctrine\DBAL\Driver\DriverException as DriverExceptionInterface; use Doctrine\DBAL\Driver\ExceptionConverterDriver; +use Doctrine\DBAL\Exception\DriverException; use Doctrine\DBAL\Platforms\AbstractPlatform; +use Exception; +use Throwable; use function array_map; use function bin2hex; +use function get_class; +use function gettype; use function implode; +use function is_object; use function is_resource; use function is_string; use function json_encode; use function sprintf; use function str_split; -class DBALException extends \Exception +class DBALException extends Exception { /** * @param string $method @@ -41,14 +29,14 @@ class DBALException extends \Exception */ public static function notSupported($method) { - return new self("Operation '$method' is not supported by platform."); + return new self(sprintf("Operation '%s' is not supported by platform.", $method)); } public static function invalidPlatformSpecified() : self { return new self( - "Invalid 'platform' option specified, need to give an instance of ". - "\Doctrine\DBAL\Platforms\AbstractPlatform."); + "Invalid 'platform' option specified, need to give an instance of " . AbstractPlatform::class . '.' + ); } /** @@ -56,12 +44,12 @@ public static function invalidPlatformSpecified() : self */ public static function invalidPlatformType($invalidPlatform) : self { - if (\is_object($invalidPlatform)) { + if (is_object($invalidPlatform)) { return new self( sprintf( "Option 'platform' must be a subtype of '%s', instance of '%s' given", AbstractPlatform::class, - \get_class($invalidPlatform) + get_class($invalidPlatform) ) ); } @@ -70,7 +58,7 @@ public static function invalidPlatformType($invalidPlatform) : self sprintf( "Option 'platform' must be an object and subtype of '%s'. Got '%s'", AbstractPlatform::class, - \gettype($invalidPlatform) + gettype($invalidPlatform) ) ); } @@ -101,8 +89,8 @@ public static function invalidPlatformVersionSpecified($version, $expectedFormat public static function invalidPdoInstance() { return new self( - "The 'pdo' option was used in DriverManager::getConnection() but no ". - "instance of PDO was given." + "The 'pdo' option was used in DriverManager::getConnection() but no " . + 'instance of PDO was given.' ); } @@ -117,70 +105,67 @@ public static function driverRequired($url = null) return new self( sprintf( "The options 'driver' or 'driverClass' are mandatory if a connection URL without scheme " . - "is given to DriverManager::getConnection(). Given URL: %s", + 'is given to DriverManager::getConnection(). Given URL: %s', $url ) ); } - return new self("The options 'driver' or 'driverClass' are mandatory if no PDO ". - "instance is given to DriverManager::getConnection()."); + return new self("The options 'driver' or 'driverClass' are mandatory if no PDO " . + 'instance is given to DriverManager::getConnection().'); } /** - * @param string $unknownDriverName - * @param array $knownDrivers + * @param string $unknownDriverName + * @param string[] $knownDrivers * * @return \Doctrine\DBAL\DBALException */ public static function unknownDriver($unknownDriverName, array $knownDrivers) { - return new self("The given 'driver' ".$unknownDriverName." is unknown, ". - "Doctrine currently supports only the following drivers: ".implode(", ", $knownDrivers)); + return new self("The given 'driver' " . $unknownDriverName . ' is unknown, ' . + 'Doctrine currently supports only the following drivers: ' . implode(', ', $knownDrivers)); } /** - * @param \Doctrine\DBAL\Driver $driver - * @param \Exception $driverEx - * @param string $sql - * @param array $params + * @param Exception $driverEx + * @param string $sql + * @param mixed[] $params * * @return \Doctrine\DBAL\DBALException */ - public static function driverExceptionDuringQuery(Driver $driver, \Exception $driverEx, $sql, array $params = []) + public static function driverExceptionDuringQuery(Driver $driver, Throwable $driverEx, $sql, array $params = []) { - $msg = "An exception occurred while executing '".$sql."'"; + $msg = "An exception occurred while executing '" . $sql . "'"; if ($params) { - $msg .= " with params " . self::formatParameters($params); + $msg .= ' with params ' . self::formatParameters($params); } - $msg .= ":\n\n".$driverEx->getMessage(); + $msg .= ":\n\n" . $driverEx->getMessage(); return static::wrapException($driver, $driverEx, $msg); } /** - * @param \Doctrine\DBAL\Driver $driver - * @param \Exception $driverEx + * @param Exception $driverEx * * @return \Doctrine\DBAL\DBALException */ - public static function driverException(Driver $driver, \Exception $driverEx) + public static function driverException(Driver $driver, Throwable $driverEx) { - return static::wrapException($driver, $driverEx, "An exception occurred in driver: " . $driverEx->getMessage()); + return static::wrapException($driver, $driverEx, 'An exception occurred in driver: ' . $driverEx->getMessage()); } /** - * @param \Doctrine\DBAL\Driver $driver - * @param \Exception $driverEx + * @param Exception $driverEx * * @return \Doctrine\DBAL\DBALException */ - private static function wrapException(Driver $driver, \Exception $driverEx, $msg) + private static function wrapException(Driver $driver, Throwable $driverEx, $msg) { - if ($driverEx instanceof Exception\DriverException) { + if ($driverEx instanceof DriverException) { return $driverEx; } - if ($driver instanceof ExceptionConverterDriver && $driverEx instanceof Driver\DriverException) { + if ($driver instanceof ExceptionConverterDriver && $driverEx instanceof DriverExceptionInterface) { return $driver->convertException($msg, $driverEx); } @@ -191,20 +176,20 @@ private static function wrapException(Driver $driver, \Exception $driverEx, $msg * Returns a human-readable representation of an array of parameters. * This properly handles binary data by returning a hex representation. * - * @param array $params + * @param mixed[] $params * * @return string */ private static function formatParameters(array $params) { - return '[' . implode(', ', array_map(function ($param) { + return '[' . implode(', ', array_map(static function ($param) { if (is_resource($param)) { return (string) $param; } - + $json = @json_encode($param); - if (! is_string($json) || $json == 'null' && is_string($param)) { + if (! is_string($json) || $json === 'null' && is_string($param)) { // JSON encoding failed, this is not a UTF-8 string. return '"\x' . implode('\x', str_split(bin2hex($param), 2)) . '"'; } @@ -220,8 +205,8 @@ private static function formatParameters(array $params) */ public static function invalidWrapperClass($wrapperClass) { - return new self("The given 'wrapperClass' ".$wrapperClass." has to be a ". - "subtype of \Doctrine\DBAL\Connection."); + return new self("The given 'wrapperClass' " . $wrapperClass . ' has to be a ' . + 'subtype of \Doctrine\DBAL\Connection.'); } /** @@ -231,8 +216,7 @@ public static function invalidWrapperClass($wrapperClass) */ public static function invalidDriverClass($driverClass) { - return new self("The given 'driverClass' ".$driverClass." has to implement the ". - "\Doctrine\DBAL\Driver interface."); + return new self("The given 'driverClass' " . $driverClass . ' has to implement the ' . Driver::class . ' interface.'); } /** @@ -242,7 +226,7 @@ public static function invalidDriverClass($driverClass) */ public static function invalidTableName($tableName) { - return new self("Invalid table name specified: ".$tableName); + return new self('Invalid table name specified: ' . $tableName); } /** @@ -252,7 +236,7 @@ public static function invalidTableName($tableName) */ public static function noColumnsSpecifiedForTable($tableName) { - return new self("No columns specified for table ".$tableName); + return new self('No columns specified for table ' . $tableName); } /** @@ -260,7 +244,7 @@ public static function noColumnsSpecifiedForTable($tableName) */ public static function limitOffsetInvalid() { - return new self("Invalid Offset in Limit Query, it has to be larger than or equal to 0."); + return new self('Invalid Offset in Limit Query, it has to be larger than or equal to 0.'); } /** @@ -270,7 +254,7 @@ public static function limitOffsetInvalid() */ public static function typeExists($name) { - return new self('Type '.$name.' already exists.'); + return new self('Type ' . $name . ' already exists.'); } /** @@ -280,14 +264,13 @@ public static function typeExists($name) */ public static function unknownColumnType($name) { - return new self('Unknown column type "'.$name.'" requested. Any Doctrine type that you use has ' . + return new self('Unknown column type "' . $name . '" requested. Any Doctrine type that you use has ' . 'to be registered with \Doctrine\DBAL\Types\Type::addType(). You can get a list of all the ' . 'known types with \Doctrine\DBAL\Types\Type::getTypesMap(). If this error occurs during database ' . 'introspection then you might have forgotten to register all database types for a Doctrine Type. Use ' . 'AbstractPlatform#registerDoctrineTypeMapping() or have your custom types implement ' . 'Type#getMappedDatabaseTypes(). If the type name is empty you might ' . - 'have a problem with the cache or forgot some mapping information.' - ); + 'have a problem with the cache or forgot some mapping information.'); } /** @@ -297,6 +280,6 @@ public static function unknownColumnType($name) */ public static function typeNotFound($name) { - return new self('Type to be overwritten '.$name.' does not exist.'); + return new self('Type to be overwritten ' . $name . ' does not exist.'); } } diff --git a/lib/Doctrine/DBAL/Driver.php b/lib/Doctrine/DBAL/Driver.php index 300a27dec5b..dcb03b29492 100644 --- a/lib/Doctrine/DBAL/Driver.php +++ b/lib/Doctrine/DBAL/Driver.php @@ -1,39 +1,23 @@ . - */ namespace Doctrine\DBAL; +use Doctrine\DBAL\Platforms\AbstractPlatform; +use Doctrine\DBAL\Schema\AbstractSchemaManager; + /** * Driver interface. * Interface that all DBAL drivers must implement. - * - * @since 2.0 */ interface Driver { /** * Attempts to create a connection with the database. * - * @param array $params All connection parameters passed by the user. + * @param mixed[] $params All connection parameters passed by the user. * @param string|null $username The username to use when connecting. * @param string|null $password The password to use when connecting. - * @param array $driverOptions The driver options to use when connecting. + * @param mixed[] $driverOptions The driver options to use when connecting. * * @return \Doctrine\DBAL\Driver\Connection The database connection. */ @@ -43,7 +27,7 @@ public function connect(array $params, $username = null, $password = null, array * Gets the DatabasePlatform instance that provides all the metadata about * the platform this driver connects to. * - * @return \Doctrine\DBAL\Platforms\AbstractPlatform The database platform. + * @return AbstractPlatform The database platform. */ public function getDatabasePlatform(); @@ -51,9 +35,7 @@ public function getDatabasePlatform(); * Gets the SchemaManager that can be used to inspect and change the underlying * database schema of the platform this driver connects to. * - * @param \Doctrine\DBAL\Connection $conn - * - * @return \Doctrine\DBAL\Schema\AbstractSchemaManager + * @return AbstractSchemaManager */ public function getSchemaManager(Connection $conn); @@ -67,8 +49,6 @@ public function getName(); /** * Gets the name of the database connected to for this driver. * - * @param \Doctrine\DBAL\Connection $conn - * * @return string The name of the database. */ public function getDatabase(Connection $conn); diff --git a/lib/Doctrine/DBAL/Driver/AbstractDB2Driver.php b/lib/Doctrine/DBAL/Driver/AbstractDB2Driver.php index baa081690c0..c6e0565343a 100644 --- a/lib/Doctrine/DBAL/Driver/AbstractDB2Driver.php +++ b/lib/Doctrine/DBAL/Driver/AbstractDB2Driver.php @@ -1,41 +1,21 @@ . - */ namespace Doctrine\DBAL\Driver; +use Doctrine\DBAL\Connection; use Doctrine\DBAL\Driver; use Doctrine\DBAL\Platforms\DB2Platform; use Doctrine\DBAL\Schema\DB2SchemaManager; /** * Abstract base implementation of the {@link Doctrine\DBAL\Driver} interface for IBM DB2 based drivers. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ abstract class AbstractDB2Driver implements Driver { /** * {@inheritdoc} */ - public function getDatabase(\Doctrine\DBAL\Connection $conn) + public function getDatabase(Connection $conn) { $params = $conn->getParams(); @@ -53,7 +33,7 @@ public function getDatabasePlatform() /** * {@inheritdoc} */ - public function getSchemaManager(\Doctrine\DBAL\Connection $conn) + public function getSchemaManager(Connection $conn) { return new DB2SchemaManager($conn); } diff --git a/lib/Doctrine/DBAL/Driver/AbstractDriverException.php b/lib/Doctrine/DBAL/Driver/AbstractDriverException.php index 83c38d71db6..d9af92d1744 100644 --- a/lib/Doctrine/DBAL/Driver/AbstractDriverException.php +++ b/lib/Doctrine/DBAL/Driver/AbstractDriverException.php @@ -1,32 +1,13 @@ . - */ namespace Doctrine\DBAL\Driver; +use Exception; + /** * Abstract base implementation of the {@link DriverException} interface. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ -abstract class AbstractDriverException extends \Exception implements DriverException +abstract class AbstractDriverException extends Exception implements DriverException { /** * The driver specific error code. @@ -43,8 +24,6 @@ abstract class AbstractDriverException extends \Exception implements DriverExcep private $sqlState; /** - * Constructor. - * * @param string $message The driver error message. * @param string|null $sqlState The SQLSTATE the driver is in at the time the error occurred, if any. * @param int|string|null $errorCode The driver specific error code if any. diff --git a/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php b/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php index bf6e11f5f1a..c46ddc63dd7 100644 --- a/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php +++ b/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php @@ -1,24 +1,8 @@ . - */ namespace Doctrine\DBAL\Driver; +use Doctrine\DBAL\Connection; use Doctrine\DBAL\DBALException; use Doctrine\DBAL\Driver; use Doctrine\DBAL\Exception; @@ -34,10 +18,6 @@ /** * Abstract base implementation of the {@link Doctrine\DBAL\Driver} interface for MySQL based drivers. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ abstract class AbstractMySQLDriver implements Driver, ExceptionConverterDriver, VersionAwarePlatformDriver { @@ -133,7 +113,7 @@ public function convertException($message, DriverException $exception) */ public function createDatabasePlatformForVersion($version) { - $mariadb = false !== stripos($version, 'mariadb'); + $mariadb = stripos($version, 'mariadb') !== false; if ($mariadb && version_compare($this->getMariaDbMysqlVersionNumber($version), '10.2.7', '>=')) { return new MariaDb1027Platform(); } @@ -156,11 +136,12 @@ public function createDatabasePlatformForVersion($version) * returned by Oracle MySQL servers. * * @param string $versionString Version string returned by the driver, i.e. '5.7.10' + * * @throws DBALException */ private function getOracleMysqlVersionNumber(string $versionString) : string { - if ( ! preg_match( + if (! preg_match( '/^(?P\d+)(?:\.(?P\d+)(?:\.(?P\d+))?)?/', $versionString, $versionParts @@ -174,7 +155,7 @@ private function getOracleMysqlVersionNumber(string $versionString) : string $minorVersion = $versionParts['minor'] ?? 0; $patchVersion = $versionParts['patch'] ?? null; - if ('5' === $majorVersion && '7' === $minorVersion && null === $patchVersion) { + if ($majorVersion === '5' && $minorVersion === '7' && $patchVersion === null) { $patchVersion = '9'; } @@ -186,11 +167,12 @@ private function getOracleMysqlVersionNumber(string $versionString) : string * that starts with the prefix '5.5.5-' * * @param string $versionString Version string as returned by mariadb server, i.e. '5.5.5-Mariadb-10.0.8-xenial' + * * @throws DBALException */ private function getMariaDbMysqlVersionNumber(string $versionString) : string { - if ( ! preg_match( + if (! preg_match( '/^(?:5\.5\.5-)?(mariadb-)?(?P\d+)\.(?P\d+)\.(?P\d+)/i', $versionString, $versionParts @@ -207,7 +189,7 @@ private function getMariaDbMysqlVersionNumber(string $versionString) : string /** * {@inheritdoc} */ - public function getDatabase(\Doctrine\DBAL\Connection $conn) + public function getDatabase(Connection $conn) { $params = $conn->getParams(); @@ -216,6 +198,7 @@ public function getDatabase(\Doctrine\DBAL\Connection $conn) /** * {@inheritdoc} + * * @return MySqlPlatform */ public function getDatabasePlatform() @@ -225,9 +208,10 @@ public function getDatabasePlatform() /** * {@inheritdoc} + * * @return MySqlSchemaManager */ - public function getSchemaManager(\Doctrine\DBAL\Connection $conn) + public function getSchemaManager(Connection $conn) { return new MySqlSchemaManager($conn); } diff --git a/lib/Doctrine/DBAL/Driver/AbstractOracleDriver.php b/lib/Doctrine/DBAL/Driver/AbstractOracleDriver.php index 00b590fa9be..07e679918b8 100644 --- a/lib/Doctrine/DBAL/Driver/AbstractOracleDriver.php +++ b/lib/Doctrine/DBAL/Driver/AbstractOracleDriver.php @@ -1,26 +1,11 @@ . - */ namespace Doctrine\DBAL\Driver; +use Doctrine\DBAL\Connection; use Doctrine\DBAL\DBALException; use Doctrine\DBAL\Driver; +use Doctrine\DBAL\Driver\AbstractOracleDriver\EasyConnectString; use Doctrine\DBAL\Exception; use Doctrine\DBAL\Platforms\Oracle121Platform; use Doctrine\DBAL\Platforms\Oracle122Platform; @@ -30,10 +15,6 @@ /** * Abstract base implementation of the {@link Doctrine\DBAL\Driver} interface for Oracle based drivers. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ abstract class AbstractOracleDriver implements Driver, ExceptionConverterDriver, VersionAwarePlatformDriver { @@ -114,7 +95,7 @@ public function convertException($message, DriverException $exception) /** * {@inheritdoc} */ - public function getDatabase(\Doctrine\DBAL\Connection $conn) + public function getDatabase(Connection $conn) { $params = $conn->getParams(); @@ -132,7 +113,7 @@ public function getDatabasePlatform() /** * {@inheritdoc} */ - public function getSchemaManager(\Doctrine\DBAL\Connection $conn) + public function getSchemaManager(Connection $conn) { return new OracleSchemaManager($conn); } @@ -140,51 +121,12 @@ public function getSchemaManager(\Doctrine\DBAL\Connection $conn) /** * Returns an appropriate Easy Connect String for the given parameters. * - * @param array $params The connection parameters to return the Easy Connect STring for. + * @param mixed[] $params The connection parameters to return the Easy Connect String for. * * @return string - * - * @link https://docs.oracle.com/database/121/NETAG/naming.htm */ protected function getEasyConnectString(array $params) { - if ( ! empty($params['connectstring'])) { - return $params['connectstring']; - } - - if ( ! empty($params['host'])) { - if ( ! isset($params['port'])) { - $params['port'] = 1521; - } - - $serviceName = $params['dbname']; - - if ( ! empty($params['servicename'])) { - $serviceName = $params['servicename']; - } - - $service = 'SID=' . $serviceName; - $pooled = ''; - $instance = ''; - - if (isset($params['service']) && $params['service'] == true) { - $service = 'SERVICE_NAME=' . $serviceName; - } - - if (isset($params['instancename']) && ! empty($params['instancename'])) { - $instance = '(INSTANCE_NAME = ' . $params['instancename'] . ')'; - } - - if (isset($params['pooled']) && $params['pooled'] == true) { - $pooled = '(SERVER=POOLED)'; - } - - return '(DESCRIPTION=' . - '(ADDRESS=(PROTOCOL=TCP)(HOST=' . $params['host'] . ')(PORT=' . $params['port'] . '))' . - '(CONNECT_DATA=(' . $service . ')' . $instance . $pooled . '))'; - - } - - return $params['dbname'] ?? ''; + return (string) EasyConnectString::fromConnectionParameters($params); } } diff --git a/lib/Doctrine/DBAL/Driver/AbstractOracleDriver/EasyConnectString.php b/lib/Doctrine/DBAL/Driver/AbstractOracleDriver/EasyConnectString.php new file mode 100644 index 00000000000..01f648b3b85 --- /dev/null +++ b/lib/Doctrine/DBAL/Driver/AbstractOracleDriver/EasyConnectString.php @@ -0,0 +1,121 @@ +string = $string; + } + + public function __toString() : string + { + return $this->string; + } + + /** + * Creates the object from an array representation + * + * @param mixed[] $params + */ + public static function fromArray(array $params) : self + { + return new self(self::renderParams($params)); + } + + /** + * Creates the object from the given DBAL connection parameters. + * + * @param mixed[] $params + */ + public static function fromConnectionParameters(array $params) : self + { + if (! empty($params['connectstring'])) { + return new self($params['connectstring']); + } + + if (empty($params['host'])) { + return new self($params['dbname'] ?? ''); + } + + $connectData = []; + + if (isset($params['servicename']) || isset($params['dbname'])) { + $serviceKey = 'SID'; + + if (! empty($params['service'])) { + $serviceKey = 'SERVICE_NAME'; + } + + $serviceName = $params['servicename'] ?? $params['dbname']; + + $connectData[$serviceKey] = $serviceName; + } + + if (! empty($params['instancename'])) { + $connectData['INSTANCE_NAME'] = $params['instancename']; + } + + if (! empty($params['pooled'])) { + $connectData['SERVER'] = 'POOLED'; + } + + return self::fromArray([ + 'DESCRIPTION' => [ + 'ADDRESS' => [ + 'PROTOCOL' => 'TCP', + 'HOST' => $params['host'], + 'PORT' => $params['port'] ?? 1521, + ], + 'CONNECT_DATA' => $connectData, + ], + ]); + } + + /** + * @param mixed[] $params + */ + private static function renderParams(array $params) : string + { + $chunks = []; + + foreach ($params as $key => $value) { + $string = self::renderValue($value); + + if ($string === '') { + continue; + } + + $chunks[] = sprintf('(%s=%s)', $key, $string); + } + + return implode('', $chunks); + } + + /** + * @param mixed $value + */ + private static function renderValue($value) : string + { + if (is_array($value)) { + return self::renderParams($value); + } + + return (string) $value; + } +} diff --git a/lib/Doctrine/DBAL/Driver/AbstractPostgreSQLDriver.php b/lib/Doctrine/DBAL/Driver/AbstractPostgreSQLDriver.php index ea7aa71676b..916d924980c 100644 --- a/lib/Doctrine/DBAL/Driver/AbstractPostgreSQLDriver.php +++ b/lib/Doctrine/DBAL/Driver/AbstractPostgreSQLDriver.php @@ -1,24 +1,8 @@ . - */ namespace Doctrine\DBAL\Driver; +use Doctrine\DBAL\Connection; use Doctrine\DBAL\DBALException; use Doctrine\DBAL\Driver; use Doctrine\DBAL\Exception; @@ -35,10 +19,6 @@ /** * Abstract base implementation of the {@link Doctrine\DBAL\Driver} interface for PostgreSQL based drivers. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ abstract class AbstractPostgreSQLDriver implements Driver, ExceptionConverterDriver, VersionAwarePlatformDriver { @@ -104,7 +84,7 @@ public function convertException($message, DriverException $exception) */ public function createDatabasePlatformForVersion($version) { - if ( ! preg_match('/^(?P\d+)(?:\.(?P\d+)(?:\.(?P\d+))?)?/', $version, $versionParts)) { + if (! preg_match('/^(?P\d+)(?:\.(?P\d+)(?:\.(?P\d+))?)?/', $version, $versionParts)) { throw DBALException::invalidPlatformVersionSpecified( $version, '..' @@ -116,7 +96,7 @@ public function createDatabasePlatformForVersion($version) $patchVersion = $versionParts['patch'] ?? 0; $version = $majorVersion . '.' . $minorVersion . '.' . $patchVersion; - switch(true) { + switch (true) { case version_compare($version, '10.0', '>='): return new PostgreSQL100Platform(); case version_compare($version, '9.4', '>='): @@ -133,7 +113,7 @@ public function createDatabasePlatformForVersion($version) /** * {@inheritdoc} */ - public function getDatabase(\Doctrine\DBAL\Connection $conn) + public function getDatabase(Connection $conn) { $params = $conn->getParams(); @@ -151,7 +131,7 @@ public function getDatabasePlatform() /** * {@inheritdoc} */ - public function getSchemaManager(\Doctrine\DBAL\Connection $conn) + public function getSchemaManager(Connection $conn) { return new PostgreSqlSchemaManager($conn); } diff --git a/lib/Doctrine/DBAL/Driver/AbstractSQLAnywhereDriver.php b/lib/Doctrine/DBAL/Driver/AbstractSQLAnywhereDriver.php index ca966511d3b..88f26ce7def 100644 --- a/lib/Doctrine/DBAL/Driver/AbstractSQLAnywhereDriver.php +++ b/lib/Doctrine/DBAL/Driver/AbstractSQLAnywhereDriver.php @@ -1,24 +1,8 @@ . - */ namespace Doctrine\DBAL\Driver; +use Doctrine\DBAL\Connection; use Doctrine\DBAL\DBALException; use Doctrine\DBAL\Driver; use Doctrine\DBAL\Exception; @@ -33,10 +17,6 @@ /** * Abstract base implementation of the {@link Doctrine\DBAL\Driver} interface for SAP Sybase SQL Anywhere based drivers. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ abstract class AbstractSQLAnywhereDriver implements Driver, ExceptionConverterDriver, VersionAwarePlatformDriver { @@ -90,7 +70,7 @@ public function convertException($message, DriverException $exception) */ public function createDatabasePlatformForVersion($version) { - if ( ! preg_match( + if (! preg_match( '/^(?P\d+)(?:\.(?P\d+)(?:\.(?P\d+)(?:\.(?P\d+))?)?)?/', $version, $versionParts @@ -107,7 +87,7 @@ public function createDatabasePlatformForVersion($version) $buildVersion = $versionParts['build'] ?? 0; $version = $majorVersion . '.' . $minorVersion . '.' . $patchVersion . '.' . $buildVersion; - switch(true) { + switch (true) { case version_compare($version, '16', '>='): return new SQLAnywhere16Platform(); case version_compare($version, '12', '>='): @@ -122,7 +102,7 @@ public function createDatabasePlatformForVersion($version) /** * {@inheritdoc} */ - public function getDatabase(\Doctrine\DBAL\Connection $conn) + public function getDatabase(Connection $conn) { $params = $conn->getParams(); @@ -140,7 +120,7 @@ public function getDatabasePlatform() /** * {@inheritdoc} */ - public function getSchemaManager(\Doctrine\DBAL\Connection $conn) + public function getSchemaManager(Connection $conn) { return new SQLAnywhereSchemaManager($conn); } diff --git a/lib/Doctrine/DBAL/Driver/AbstractSQLServerDriver.php b/lib/Doctrine/DBAL/Driver/AbstractSQLServerDriver.php index fb9c989bd14..421d82b3951 100644 --- a/lib/Doctrine/DBAL/Driver/AbstractSQLServerDriver.php +++ b/lib/Doctrine/DBAL/Driver/AbstractSQLServerDriver.php @@ -1,24 +1,8 @@ . - */ namespace Doctrine\DBAL\Driver; +use Doctrine\DBAL\Connection; use Doctrine\DBAL\DBALException; use Doctrine\DBAL\Driver; use Doctrine\DBAL\Platforms\SQLServer2005Platform; @@ -32,10 +16,6 @@ /** * Abstract base implementation of the {@link Doctrine\DBAL\Driver} interface for Microsoft SQL Server based drivers. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ abstract class AbstractSQLServerDriver implements Driver, VersionAwarePlatformDriver { @@ -44,7 +24,7 @@ abstract class AbstractSQLServerDriver implements Driver, VersionAwarePlatformDr */ public function createDatabasePlatformForVersion($version) { - if ( ! preg_match( + if (! preg_match( '/^(?P\d+)(?:\.(?P\d+)(?:\.(?P\d+)(?:\.(?P\d+))?)?)?/', $version, $versionParts @@ -61,7 +41,7 @@ public function createDatabasePlatformForVersion($version) $buildVersion = $versionParts['build'] ?? 0; $version = $majorVersion . '.' . $minorVersion . '.' . $patchVersion . '.' . $buildVersion; - switch(true) { + switch (true) { case version_compare($version, '11.00.2100', '>='): return new SQLServer2012Platform(); case version_compare($version, '10.00.1600', '>='): @@ -76,7 +56,7 @@ public function createDatabasePlatformForVersion($version) /** * {@inheritdoc} */ - public function getDatabase(\Doctrine\DBAL\Connection $conn) + public function getDatabase(Connection $conn) { $params = $conn->getParams(); @@ -94,8 +74,7 @@ public function getDatabasePlatform() /** * {@inheritdoc} */ - - public function getSchemaManager(\Doctrine\DBAL\Connection $conn) + public function getSchemaManager(Connection $conn) { return new SQLServerSchemaManager($conn); } diff --git a/lib/Doctrine/DBAL/Driver/AbstractSQLiteDriver.php b/lib/Doctrine/DBAL/Driver/AbstractSQLiteDriver.php index 406cb92ef2f..582f7cae20a 100644 --- a/lib/Doctrine/DBAL/Driver/AbstractSQLiteDriver.php +++ b/lib/Doctrine/DBAL/Driver/AbstractSQLiteDriver.php @@ -1,24 +1,8 @@ . - */ namespace Doctrine\DBAL\Driver; +use Doctrine\DBAL\Connection; use Doctrine\DBAL\Driver; use Doctrine\DBAL\Exception; use Doctrine\DBAL\Platforms\SqlitePlatform; @@ -27,10 +11,6 @@ /** * Abstract base implementation of the {@link Doctrine\DBAL\Driver} interface for SQLite based drivers. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ abstract class AbstractSQLiteDriver implements Driver, ExceptionConverterDriver { @@ -93,7 +73,7 @@ public function convertException($message, DriverException $exception) /** * {@inheritdoc} */ - public function getDatabase(\Doctrine\DBAL\Connection $conn) + public function getDatabase(Connection $conn) { $params = $conn->getParams(); @@ -111,7 +91,7 @@ public function getDatabasePlatform() /** * {@inheritdoc} */ - public function getSchemaManager(\Doctrine\DBAL\Connection $conn) + public function getSchemaManager(Connection $conn) { return new SqliteSchemaManager($conn); } diff --git a/lib/Doctrine/DBAL/Driver/Connection.php b/lib/Doctrine/DBAL/Driver/Connection.php index a0dd1e66a45..1574581c2ad 100644 --- a/lib/Doctrine/DBAL/Driver/Connection.php +++ b/lib/Doctrine/DBAL/Driver/Connection.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver; @@ -26,8 +9,6 @@ * Driver connections must implement this interface. * * This resembles (a subset of) the PDO interface. - * - * @since 2.0 */ interface Connection { @@ -43,7 +24,7 @@ public function prepare($prepareString); /** * Executes an SQL statement, returning a result set as a Statement object. * - * @return \Doctrine\DBAL\Driver\Statement + * @return Statement */ public function query(); @@ -106,7 +87,7 @@ public function errorCode(); /** * Returns extended error information associated with the last operation on the database handle. * - * @return array + * @return mixed[] */ public function errorInfo(); } diff --git a/lib/Doctrine/DBAL/Driver/DriverException.php b/lib/Doctrine/DBAL/Driver/DriverException.php index ce1d1e38149..79480ac72be 100644 --- a/lib/Doctrine/DBAL/Driver/DriverException.php +++ b/lib/Doctrine/DBAL/Driver/DriverException.php @@ -1,35 +1,16 @@ . - */ namespace Doctrine\DBAL\Driver; +use Throwable; + /** * Contract for a driver exception. * * Driver exceptions provide the SQLSTATE of the driver * and the driver specific error code at the time the error occurred. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ -interface DriverException extends \Throwable +interface DriverException extends Throwable { /** * Returns the driver specific error code if available. diff --git a/lib/Doctrine/DBAL/Driver/DrizzlePDOMySql/Connection.php b/lib/Doctrine/DBAL/Driver/DrizzlePDOMySql/Connection.php index bfc61acf9b8..4089ab26e11 100644 --- a/lib/Doctrine/DBAL/Driver/DrizzlePDOMySql/Connection.php +++ b/lib/Doctrine/DBAL/Driver/DrizzlePDOMySql/Connection.php @@ -1,30 +1,11 @@ . - */ namespace Doctrine\DBAL\Driver\DrizzlePDOMySql; +use Doctrine\DBAL\Driver\PDOConnection; use Doctrine\DBAL\ParameterType; -/** - * @author Kim Hemsø Rasmussen - */ -class Connection extends \Doctrine\DBAL\Driver\PDOConnection +class Connection extends PDOConnection { /** * {@inheritdoc} diff --git a/lib/Doctrine/DBAL/Driver/DrizzlePDOMySql/Driver.php b/lib/Doctrine/DBAL/Driver/DrizzlePDOMySql/Driver.php index 547fdb79570..851f0ee23c4 100644 --- a/lib/Doctrine/DBAL/Driver/DrizzlePDOMySql/Driver.php +++ b/lib/Doctrine/DBAL/Driver/DrizzlePDOMySql/Driver.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\DrizzlePDOMySql; @@ -24,8 +7,6 @@ /** * Drizzle driver using PDO MySql. - * - * @author Kim Hemsø Rasmussen */ class Driver extends \Doctrine\DBAL\Driver\PDOMySql\Driver { @@ -34,14 +15,12 @@ class Driver extends \Doctrine\DBAL\Driver\PDOMySql\Driver */ public function connect(array $params, $username = null, $password = null, array $driverOptions = []) { - $conn = new Connection( + return new Connection( $this->constructPdoDsn($params), $username, $password, $driverOptions ); - - return $conn; } /** diff --git a/lib/Doctrine/DBAL/Driver/ExceptionConverterDriver.php b/lib/Doctrine/DBAL/Driver/ExceptionConverterDriver.php index 0bd8d516e14..9b79e240c4e 100644 --- a/lib/Doctrine/DBAL/Driver/ExceptionConverterDriver.php +++ b/lib/Doctrine/DBAL/Driver/ExceptionConverterDriver.php @@ -1,31 +1,9 @@ . - */ namespace Doctrine\DBAL\Driver; /** * Contract for a driver that is capable of converting DBAL driver exceptions into standardized DBAL driver exceptions. - * - * @author Benjamin Eberlei - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ interface ExceptionConverterDriver { @@ -35,8 +13,8 @@ interface ExceptionConverterDriver * It evaluates the vendor specific error code and SQLSTATE and transforms * it into a unified {@link Doctrine\DBAL\Exception\DriverException} subclass. * - * @param string $message The DBAL exception message to use. - * @param \Doctrine\DBAL\Driver\DriverException $exception The DBAL driver exception to convert. + * @param string $message The DBAL exception message to use. + * @param DriverException $exception The DBAL driver exception to convert. * * @return \Doctrine\DBAL\Exception\DriverException An instance of one of the DriverException subclasses. */ diff --git a/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Connection.php b/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Connection.php index beae3ba0d86..bd80e6e49a7 100644 --- a/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Connection.php +++ b/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Connection.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\IBMDB2; @@ -43,29 +26,27 @@ class DB2Connection implements Connection, ServerInfoAwareConnection { - /** - * @var resource - */ - private $_conn = null; + /** @var resource */ + private $conn = null; /** - * @param array $params - * @param string $username - * @param string $password - * @param array $driverOptions + * @param mixed[] $params + * @param string $username + * @param string $password + * @param mixed[] $driverOptions * - * @throws \Doctrine\DBAL\Driver\IBMDB2\DB2Exception + * @throws DB2Exception */ public function __construct(array $params, $username, $password, $driverOptions = []) { - $isPersistent = (isset($params['persistent']) && $params['persistent'] == true); + $isPersistent = (isset($params['persistent']) && $params['persistent'] === true); if ($isPersistent) { - $this->_conn = db2_pconnect($params['dbname'], $username, $password, $driverOptions); + $this->conn = db2_pconnect($params['dbname'], $username, $password, $driverOptions); } else { - $this->_conn = db2_connect($params['dbname'], $username, $password, $driverOptions); + $this->conn = db2_connect($params['dbname'], $username, $password, $driverOptions); } - if ( ! $this->_conn) { + if (! $this->conn) { throw new DB2Exception(db2_conn_errormsg()); } } @@ -76,7 +57,7 @@ public function __construct(array $params, $username, $password, $driverOptions public function getServerVersion() { /** @var stdClass $serverInfo */ - $serverInfo = db2_server_info($this->_conn); + $serverInfo = db2_server_info($this->conn); return $serverInfo->DBMS_VER; } @@ -94,8 +75,8 @@ public function requiresQueryForServerVersion() */ public function prepare($sql) { - $stmt = @db2_prepare($this->_conn, $sql); - if ( ! $stmt) { + $stmt = @db2_prepare($this->conn, $sql); + if (! $stmt) { throw new DB2Exception(db2_stmt_errormsg()); } @@ -108,7 +89,7 @@ public function prepare($sql) public function query() { $args = func_get_args(); - $sql = $args[0]; + $sql = $args[0]; $stmt = $this->prepare($sql); $stmt->execute(); @@ -126,7 +107,7 @@ public function quote($input, $type = ParameterType::STRING) return $input; } - return "'".$input."'"; + return "'" . $input . "'"; } /** @@ -134,9 +115,9 @@ public function quote($input, $type = ParameterType::STRING) */ public function exec($statement) { - $stmt = @db2_exec($this->_conn, $statement); + $stmt = @db2_exec($this->conn, $statement); - if (false === $stmt) { + if ($stmt === false) { throw new DB2Exception(db2_stmt_errormsg()); } @@ -148,7 +129,7 @@ public function exec($statement) */ public function lastInsertId($name = null) { - return db2_last_insert_id($this->_conn); + return db2_last_insert_id($this->conn); } /** @@ -156,7 +137,7 @@ public function lastInsertId($name = null) */ public function beginTransaction() { - db2_autocommit($this->_conn, DB2_AUTOCOMMIT_OFF); + db2_autocommit($this->conn, DB2_AUTOCOMMIT_OFF); } /** @@ -164,10 +145,10 @@ public function beginTransaction() */ public function commit() { - if (!db2_commit($this->_conn)) { - throw new DB2Exception(db2_conn_errormsg($this->_conn)); + if (! db2_commit($this->conn)) { + throw new DB2Exception(db2_conn_errormsg($this->conn)); } - db2_autocommit($this->_conn, DB2_AUTOCOMMIT_ON); + db2_autocommit($this->conn, DB2_AUTOCOMMIT_ON); } /** @@ -175,10 +156,10 @@ public function commit() */ public function rollBack() { - if (!db2_rollback($this->_conn)) { - throw new DB2Exception(db2_conn_errormsg($this->_conn)); + if (! db2_rollback($this->conn)) { + throw new DB2Exception(db2_conn_errormsg($this->conn)); } - db2_autocommit($this->_conn, DB2_AUTOCOMMIT_ON); + db2_autocommit($this->conn, DB2_AUTOCOMMIT_ON); } /** @@ -186,7 +167,7 @@ public function rollBack() */ public function errorCode() { - return db2_conn_error($this->_conn); + return db2_conn_error($this->conn); } /** @@ -195,7 +176,7 @@ public function errorCode() public function errorInfo() { return [ - 0 => db2_conn_errormsg($this->_conn), + 0 => db2_conn_errormsg($this->conn), 1 => $this->errorCode(), ]; } diff --git a/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Driver.php b/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Driver.php index de5921edd23..712cbe419f3 100644 --- a/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Driver.php +++ b/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Driver.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\IBMDB2; @@ -23,9 +6,6 @@ /** * IBM DB2 Driver. - * - * @since 2.0 - * @author Benjamin Eberlei */ class DB2Driver extends AbstractDB2Driver { @@ -34,18 +14,18 @@ class DB2Driver extends AbstractDB2Driver */ public function connect(array $params, $username = null, $password = null, array $driverOptions = []) { - if ( ! isset($params['protocol'])) { + if (! isset($params['protocol'])) { $params['protocol'] = 'TCPIP'; } - if ($params['host'] !== 'localhost' && $params['host'] != '127.0.0.1') { + if ($params['host'] !== 'localhost' && $params['host'] !== '127.0.0.1') { // if the host isn't localhost, use extended connection params $params['dbname'] = 'DRIVER={IBM DB2 ODBC DRIVER}' . ';DATABASE=' . $params['dbname'] . ';HOSTNAME=' . $params['host'] . ';PROTOCOL=' . $params['protocol'] . - ';UID=' . $username . - ';PWD=' . $password .';'; + ';UID=' . $username . + ';PWD=' . $password . ';'; if (isset($params['port'])) { $params['dbname'] .= 'PORT=' . $params['port']; } diff --git a/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Exception.php b/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Exception.php index 72775cbfe70..b01c4552a23 100644 --- a/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Exception.php +++ b/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Exception.php @@ -1,24 +1,9 @@ . - */ namespace Doctrine\DBAL\Driver\IBMDB2; -class DB2Exception extends \Exception +use Exception; + +class DB2Exception extends Exception { } diff --git a/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Statement.php b/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Statement.php index 6693d090e5f..9c87d46319b 100644 --- a/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Statement.php +++ b/lib/Doctrine/DBAL/Driver/IBMDB2/DB2Statement.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\IBMDB2; @@ -23,11 +6,19 @@ use Doctrine\DBAL\Driver\StatementIterator; use Doctrine\DBAL\FetchMode; use Doctrine\DBAL\ParameterType; +use IteratorAggregate; +use PDO; +use ReflectionClass; +use ReflectionObject; +use ReflectionProperty; +use stdClass; +use const CASE_LOWER; +use const DB2_BINARY; use const DB2_CHAR; use const DB2_LONG; +use const DB2_PARAM_FILE; use const DB2_PARAM_IN; use function array_change_key_case; -use function call_user_func_array; use function db2_bind_param; use function db2_execute; use function db2_fetch_array; @@ -39,41 +30,46 @@ use function db2_num_rows; use function db2_stmt_error; use function db2_stmt_errormsg; +use function error_get_last; +use function fclose; use function func_get_args; use function func_num_args; +use function fwrite; use function gettype; use function is_object; +use function is_resource; use function is_string; use function ksort; use function sprintf; +use function stream_copy_to_stream; +use function stream_get_meta_data; use function strtolower; +use function tmpfile; -class DB2Statement implements \IteratorAggregate, Statement +class DB2Statement implements IteratorAggregate, Statement { - /** - * @var resource - */ - private $_stmt; + /** @var resource */ + private $stmt; - /** - * @var array - */ - private $_bindParam = []; + /** @var mixed[] */ + private $bindParam = []; /** - * @var string Name of the default class to instantiate when fetching class instances. + * Map of LOB parameter positions to the tuples containing reference to the variable bound to the driver statement + * and the temporary file handle bound to the underlying statement + * + * @var mixed[][] */ + private $lobs = []; + + /** @var string Name of the default class to instantiate when fetching class instances. */ private $defaultFetchClass = '\stdClass'; - /** - * @var mixed[] Constructor arguments for the default class to instantiate when fetching class instances. - */ + /** @var mixed[] Constructor arguments for the default class to instantiate when fetching class instances. */ private $defaultFetchClassCtorArgs = []; - /** - * @var int - */ - private $_defaultFetchMode = FetchMode::MIXED; + /** @var int */ + private $defaultFetchMode = FetchMode::MIXED; /** * Indicates whether the statement is in the state when fetching results is possible @@ -82,22 +78,12 @@ class DB2Statement implements \IteratorAggregate, Statement */ private $result = false; - /** - * DB2_BINARY, DB2_CHAR, DB2_DOUBLE, or DB2_LONG - * - * @var array - */ - static private $_typeMap = [ - ParameterType::INTEGER => DB2_LONG, - ParameterType::STRING => DB2_CHAR, - ]; - /** * @param resource $stmt */ public function __construct($stmt) { - $this->_stmt = $stmt; + $this->stmt = $stmt; } /** @@ -113,33 +99,60 @@ public function bindValue($param, $value, $type = ParameterType::STRING) */ public function bindParam($column, &$variable, $type = ParameterType::STRING, $length = null) { - $this->_bindParam[$column] =& $variable; + switch ($type) { + case ParameterType::INTEGER: + $this->bind($column, $variable, DB2_PARAM_IN, DB2_LONG); + break; - if ($type && isset(self::$_typeMap[$type])) { - $type = self::$_typeMap[$type]; - } else { - $type = DB2_CHAR; - } + case ParameterType::LARGE_OBJECT: + if (isset($this->lobs[$column])) { + [, $handle] = $this->lobs[$column]; + fclose($handle); + } - if (!db2_bind_param($this->_stmt, $column, "variable", DB2_PARAM_IN, $type)) { - throw new DB2Exception(db2_stmt_errormsg()); + $handle = $this->createTemporaryFile(); + $path = stream_get_meta_data($handle)['uri']; + + $this->bind($column, $path, DB2_PARAM_FILE, DB2_BINARY); + + $this->lobs[$column] = [&$variable, $handle]; + break; + + default: + $this->bind($column, $variable, DB2_PARAM_IN, DB2_CHAR); + break; } return true; } + /** + * @param int|string $parameter Parameter position or name + * @param mixed $variable + * + * @throws DB2Exception + */ + private function bind($parameter, &$variable, int $parameterType, int $dataType) : void + { + $this->bindParam[$parameter] =& $variable; + + if (! db2_bind_param($this->stmt, $parameter, 'variable', $parameterType, $dataType)) { + throw new DB2Exception(db2_stmt_errormsg()); + } + } + /** * {@inheritdoc} */ public function closeCursor() { - if ( ! $this->_stmt) { + if (! $this->stmt) { return false; } - $this->_bindParam = []; + $this->bindParam = []; - if (!db2_free_result($this->_stmt)) { + if (! db2_free_result($this->stmt)) { return false; } @@ -153,11 +166,11 @@ public function closeCursor() */ public function columnCount() { - if ( ! $this->_stmt) { + if (! $this->stmt) { return false; } - return db2_num_fields($this->_stmt); + return db2_num_fields($this->stmt); } /** @@ -184,21 +197,37 @@ public function errorInfo() */ public function execute($params = null) { - if ( ! $this->_stmt) { + if (! $this->stmt) { return false; } if ($params === null) { - ksort($this->_bindParam); + ksort($this->bindParam); $params = []; - foreach ($this->_bindParam as $column => $value) { + foreach ($this->bindParam as $column => $value) { $params[] = $value; } } - $retval = db2_execute($this->_stmt, $params); + foreach ($this->lobs as [$source, $target]) { + if (is_resource($source)) { + $this->copyStreamToStream($source, $target); + + continue; + } + + $this->writeStringToStream($source, $target); + } + + $retval = db2_execute($this->stmt, $params); + + foreach ($this->lobs as [, $handle]) { + fclose($handle); + } + + $this->lobs = []; if ($retval === false) { throw new DB2Exception(db2_stmt_errormsg()); @@ -214,7 +243,7 @@ public function execute($params = null) */ public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null) { - $this->_defaultFetchMode = $fetchMode; + $this->defaultFetchMode = $fetchMode; $this->defaultFetchClass = $arg2 ?: $this->defaultFetchClass; $this->defaultFetchClassCtorArgs = $arg3 ? (array) $arg3 : $this->defaultFetchClassCtorArgs; @@ -232,24 +261,24 @@ public function getIterator() /** * {@inheritdoc} */ - public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) + public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { // do not try fetching from the statement if it's not expected to contain result // in order to prevent exceptional situation - if (!$this->result) { + if (! $this->result) { return false; } - $fetchMode = $fetchMode ?: $this->_defaultFetchMode; + $fetchMode = $fetchMode ?: $this->defaultFetchMode; switch ($fetchMode) { case FetchMode::COLUMN: return $this->fetchColumn(); case FetchMode::MIXED: - return db2_fetch_both($this->_stmt); + return db2_fetch_both($this->stmt); case FetchMode::ASSOCIATIVE: - return db2_fetch_assoc($this->_stmt); + return db2_fetch_assoc($this->stmt); case FetchMode::CUSTOM_OBJECT: $className = $this->defaultFetchClass; @@ -261,19 +290,19 @@ public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NE $ctorArgs = $args[2] ?? []; } - $result = db2_fetch_object($this->_stmt); + $result = db2_fetch_object($this->stmt); - if ($result instanceof \stdClass) { + if ($result instanceof stdClass) { $result = $this->castObject($result, $className, $ctorArgs); } return $result; case FetchMode::NUMERIC: - return db2_fetch_array($this->_stmt); + return db2_fetch_array($this->stmt); case FetchMode::STANDARD_OBJECT: - return db2_fetch_object($this->_stmt); + return db2_fetch_object($this->stmt); default: throw new DB2Exception('Given Fetch-Style ' . $fetchMode . ' is not supported.'); @@ -314,7 +343,7 @@ public function fetchColumn($columnIndex = 0) { $row = $this->fetch(FetchMode::NUMERIC); - if (false === $row) { + if ($row === false) { return false; } @@ -326,37 +355,38 @@ public function fetchColumn($columnIndex = 0) */ public function rowCount() { - return (@db2_num_rows($this->_stmt)) ? : 0; + return @db2_num_rows($this->stmt) ? : 0; } /** * Casts a stdClass object to the given class name mapping its' properties. * - * @param \stdClass $sourceObject Object to cast from. + * @param stdClass $sourceObject Object to cast from. * @param string|object $destinationClass Name of the class or class instance to cast to. - * @param array $ctorArgs Arguments to use for constructing the destination class instance. + * @param mixed[] $ctorArgs Arguments to use for constructing the destination class instance. * * @return object * * @throws DB2Exception */ - private function castObject(\stdClass $sourceObject, $destinationClass, array $ctorArgs = []) + private function castObject(stdClass $sourceObject, $destinationClass, array $ctorArgs = []) { - if ( ! is_string($destinationClass)) { - if ( ! is_object($destinationClass)) { + if (! is_string($destinationClass)) { + if (! is_object($destinationClass)) { throw new DB2Exception(sprintf( - 'Destination class has to be of type string or object, %s given.', gettype($destinationClass) + 'Destination class has to be of type string or object, %s given.', + gettype($destinationClass) )); } } else { - $destinationClass = new \ReflectionClass($destinationClass); + $destinationClass = new ReflectionClass($destinationClass); $destinationClass = $destinationClass->newInstanceArgs($ctorArgs); } - $sourceReflection = new \ReflectionObject($sourceObject); - $destinationClassReflection = new \ReflectionObject($destinationClass); - /** @var \ReflectionProperty[] $destinationProperties */ - $destinationProperties = array_change_key_case($destinationClassReflection->getProperties(), \CASE_LOWER); + $sourceReflection = new ReflectionObject($sourceObject); + $destinationClassReflection = new ReflectionObject($destinationClass); + /** @var ReflectionProperty[] $destinationProperties */ + $destinationProperties = array_change_key_case($destinationClassReflection->getProperties(), CASE_LOWER); foreach ($sourceReflection->getProperties() as $sourceProperty) { $sourceProperty->setAccessible(true); @@ -392,4 +422,45 @@ private function castObject(\stdClass $sourceObject, $destinationClass, array $c return $destinationClass; } + + /** + * @return resource + * + * @throws DB2Exception + */ + private function createTemporaryFile() + { + $handle = @tmpfile(); + + if ($handle === false) { + throw new DB2Exception('Could not create temporary file: ' . error_get_last()['message']); + } + + return $handle; + } + + /** + * @param resource $source + * @param resource $target + * + * @throws DB2Exception + */ + private function copyStreamToStream($source, $target) : void + { + if (@stream_copy_to_stream($source, $target) === false) { + throw new DB2Exception('Could not copy source stream to temporary file: ' . error_get_last()['message']); + } + } + + /** + * @param resource $target + * + * @throws DB2Exception + */ + private function writeStringToStream(string $string, $target) : void + { + if (@fwrite($target, $string) === false) { + throw new DB2Exception('Could not write string to temporary file: ' . error_get_last()['message']); + } + } } diff --git a/lib/Doctrine/DBAL/Driver/Mysqli/Driver.php b/lib/Doctrine/DBAL/Driver/Mysqli/Driver.php index d04e194d14f..aaf4f2bd9fd 100644 --- a/lib/Doctrine/DBAL/Driver/Mysqli/Driver.php +++ b/lib/Doctrine/DBAL/Driver/Mysqli/Driver.php @@ -1,30 +1,10 @@ . - */ namespace Doctrine\DBAL\Driver\Mysqli; -use Doctrine\DBAL\Driver\AbstractMySQLDriver; use Doctrine\DBAL\DBALException; +use Doctrine\DBAL\Driver\AbstractMySQLDriver; -/** - * @author Kim Hemsø Rasmussen - */ class Driver extends AbstractMySQLDriver { /** diff --git a/lib/Doctrine/DBAL/Driver/Mysqli/MysqliConnection.php b/lib/Doctrine/DBAL/Driver/Mysqli/MysqliConnection.php index 3a1b18d5781..1f1a1d218c3 100644 --- a/lib/Doctrine/DBAL/Driver/Mysqli/MysqliConnection.php +++ b/lib/Doctrine/DBAL/Driver/Mysqli/MysqliConnection.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\Mysqli; @@ -23,6 +6,13 @@ use Doctrine\DBAL\Driver\PingableConnection; use Doctrine\DBAL\Driver\ServerInfoAwareConnection; use Doctrine\DBAL\ParameterType; +use mysqli; +use const MYSQLI_INIT_COMMAND; +use const MYSQLI_OPT_CONNECT_TIMEOUT; +use const MYSQLI_OPT_LOCAL_INFILE; +use const MYSQLI_READ_DEFAULT_FILE; +use const MYSQLI_READ_DEFAULT_GROUP; +use const MYSQLI_SERVER_PUBLIC_KEY; use function defined; use function floor; use function func_get_args; @@ -37,36 +27,30 @@ use function sprintf; use function stripos; -/** - * @author Kim Hemsø Rasmussen - * @author Till Klampaeckel - */ class MysqliConnection implements Connection, PingableConnection, ServerInfoAwareConnection { /** * Name of the option to set connection flags */ - const OPTION_FLAGS = 'flags'; + public const OPTION_FLAGS = 'flags'; - /** - * @var \mysqli - */ - private $_conn; + /** @var mysqli */ + private $conn; /** - * @param array $params - * @param string $username - * @param string $password - * @param array $driverOptions + * @param mixed[] $params + * @param string $username + * @param string $password + * @param mixed[] $driverOptions * - * @throws \Doctrine\DBAL\Driver\Mysqli\MysqliException + * @throws MysqliException */ public function __construct(array $params, $username, $password, array $driverOptions = []) { $port = $params['port'] ?? ini_get('mysqli.default_port'); // Fallback to default MySQL port if not given. - if ( ! $port) { + if (! $port) { $port = 3306; } @@ -75,23 +59,26 @@ public function __construct(array $params, $username, $password, array $driverOp $flags = $driverOptions[static::OPTION_FLAGS] ?? null; - $this->_conn = mysqli_init(); + $this->conn = mysqli_init(); $this->setSecureConnection($params); $this->setDriverOptions($driverOptions); - set_error_handler(function () {}); + set_error_handler(static function () { + }); try { - if ( ! $this->_conn->real_connect($params['host'], $username, $password, $dbname, $port, $socket, $flags)) { - throw new MysqliException($this->_conn->connect_error, $this->_conn->sqlstate ?? 'HY000', $this->_conn->connect_errno); + if (! $this->conn->real_connect($params['host'], $username, $password, $dbname, $port, $socket, $flags)) { + throw new MysqliException($this->conn->connect_error, $this->conn->sqlstate ?? 'HY000', $this->conn->connect_errno); } } finally { restore_error_handler(); } - if (isset($params['charset'])) { - $this->_conn->set_charset($params['charset']); + if (! isset($params['charset'])) { + return; } + + $this->conn->set_charset($params['charset']); } /** @@ -99,11 +86,11 @@ public function __construct(array $params, $username, $password, array $driverOp * * Could be used if part of your application is not using DBAL. * - * @return \mysqli + * @return mysqli */ public function getWrappedResourceHandle() { - return $this->_conn; + return $this->conn; } /** @@ -111,18 +98,19 @@ public function getWrappedResourceHandle() * * The server version detection includes a special case for MariaDB * to support '5.5.5-' prefixed versions introduced in Maria 10+ + * * @link https://jira.mariadb.org/browse/MDEV-4088 */ public function getServerVersion() { - $serverInfos = $this->_conn->get_server_info(); - if (false !== stripos($serverInfos, 'mariadb')) { + $serverInfos = $this->conn->get_server_info(); + if (stripos($serverInfos, 'mariadb') !== false) { return $serverInfos; } - $majorVersion = floor($this->_conn->server_version / 10000); - $minorVersion = floor(($this->_conn->server_version - $majorVersion * 10000) / 100); - $patchVersion = floor($this->_conn->server_version - $majorVersion * 10000 - $minorVersion * 100); + $majorVersion = floor($this->conn->server_version / 10000); + $minorVersion = floor(($this->conn->server_version - $majorVersion * 10000) / 100); + $patchVersion = floor($this->conn->server_version - $majorVersion * 10000 - $minorVersion * 100); return $majorVersion . '.' . $minorVersion . '.' . $patchVersion; } @@ -140,7 +128,7 @@ public function requiresQueryForServerVersion() */ public function prepare($prepareString) { - return new MysqliStatement($this->_conn, $prepareString); + return new MysqliStatement($this->conn, $prepareString); } /** @@ -149,7 +137,7 @@ public function prepare($prepareString) public function query() { $args = func_get_args(); - $sql = $args[0]; + $sql = $args[0]; $stmt = $this->prepare($sql); $stmt->execute(); @@ -161,7 +149,7 @@ public function query() */ public function quote($input, $type = ParameterType::STRING) { - return "'". $this->_conn->escape_string($input) ."'"; + return "'" . $this->conn->escape_string($input) . "'"; } /** @@ -169,11 +157,11 @@ public function quote($input, $type = ParameterType::STRING) */ public function exec($statement) { - if (false === $this->_conn->query($statement)) { - throw new MysqliException($this->_conn->error, $this->_conn->sqlstate, $this->_conn->errno); + if ($this->conn->query($statement) === false) { + throw new MysqliException($this->conn->error, $this->conn->sqlstate, $this->conn->errno); } - return $this->_conn->affected_rows; + return $this->conn->affected_rows; } /** @@ -181,7 +169,7 @@ public function exec($statement) */ public function lastInsertId($name = null) { - return $this->_conn->insert_id; + return $this->conn->insert_id; } /** @@ -189,7 +177,7 @@ public function lastInsertId($name = null) */ public function beginTransaction() { - $this->_conn->query('START TRANSACTION'); + $this->conn->query('START TRANSACTION'); return true; } @@ -199,7 +187,7 @@ public function beginTransaction() */ public function commit() { - return $this->_conn->commit(); + return $this->conn->commit(); } /** @@ -207,7 +195,7 @@ public function commit() */ public function rollBack() { - return $this->_conn->rollback(); + return $this->conn->rollback(); } /** @@ -215,7 +203,7 @@ public function rollBack() */ public function errorCode() { - return $this->_conn->errno; + return $this->conn->errno; } /** @@ -223,13 +211,13 @@ public function errorCode() */ public function errorInfo() { - return $this->_conn->error; + return $this->conn->error; } /** * Apply the driver options to the connection. * - * @param array $driverOptions + * @param mixed[] $driverOptions * * @throws MysqliException When one of of the options is not supported. * @throws MysqliException When applying doesn't work - e.g. due to incorrect value. @@ -237,42 +225,41 @@ public function errorInfo() private function setDriverOptions(array $driverOptions = []) { $supportedDriverOptions = [ - \MYSQLI_OPT_CONNECT_TIMEOUT, - \MYSQLI_OPT_LOCAL_INFILE, - \MYSQLI_INIT_COMMAND, - \MYSQLI_READ_DEFAULT_FILE, - \MYSQLI_READ_DEFAULT_GROUP, + MYSQLI_OPT_CONNECT_TIMEOUT, + MYSQLI_OPT_LOCAL_INFILE, + MYSQLI_INIT_COMMAND, + MYSQLI_READ_DEFAULT_FILE, + MYSQLI_READ_DEFAULT_GROUP, ]; if (defined('MYSQLI_SERVER_PUBLIC_KEY')) { - $supportedDriverOptions[] = \MYSQLI_SERVER_PUBLIC_KEY; + $supportedDriverOptions[] = MYSQLI_SERVER_PUBLIC_KEY; } $exceptionMsg = "%s option '%s' with value '%s'"; foreach ($driverOptions as $option => $value) { - if ($option === static::OPTION_FLAGS) { continue; } - if (!in_array($option, $supportedDriverOptions, true)) { + if (! in_array($option, $supportedDriverOptions, true)) { throw new MysqliException( sprintf($exceptionMsg, 'Unsupported', $option, $value) ); } - if (@mysqli_options($this->_conn, $option, $value)) { + if (@mysqli_options($this->conn, $option, $value)) { continue; } $msg = sprintf($exceptionMsg, 'Failed to set', $option, $value); - $msg .= sprintf(', error: %s (%d)', mysqli_error($this->_conn), mysqli_errno($this->_conn)); + $msg .= sprintf(', error: %s (%d)', mysqli_error($this->conn), mysqli_errno($this->conn)); throw new MysqliException( $msg, - $this->_conn->sqlstate, - $this->_conn->errno + $this->conn->sqlstate, + $this->conn->errno ); } } @@ -284,13 +271,14 @@ private function setDriverOptions(array $driverOptions = []) */ public function ping() { - return $this->_conn->ping(); + return $this->conn->ping(); } /** * Establish a secure connection * - * @param array $params + * @param mixed[] $params + * * @throws MysqliException */ private function setSecureConnection(array $params) @@ -304,7 +292,7 @@ private function setSecureConnection(array $params) return; } - $this->_conn->ssl_set( + $this->conn->ssl_set( $params['ssl_key'] ?? null, $params['ssl_cert'] ?? null, $params['ssl_ca'] ?? null, diff --git a/lib/Doctrine/DBAL/Driver/Mysqli/MysqliException.php b/lib/Doctrine/DBAL/Driver/Mysqli/MysqliException.php index 23728b113a6..1fa0c900fbd 100644 --- a/lib/Doctrine/DBAL/Driver/Mysqli/MysqliException.php +++ b/lib/Doctrine/DBAL/Driver/Mysqli/MysqliException.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\Mysqli; @@ -23,9 +6,6 @@ /** * Exception thrown in case the mysqli driver errors. - * - * @author Kim Hemsø Rasmussen - * @author Steve Müller */ class MysqliException extends AbstractDriverException { diff --git a/lib/Doctrine/DBAL/Driver/Mysqli/MysqliStatement.php b/lib/Doctrine/DBAL/Driver/Mysqli/MysqliStatement.php index 6941894e009..2bbe0ca8b20 100644 --- a/lib/Doctrine/DBAL/Driver/Mysqli/MysqliStatement.php +++ b/lib/Doctrine/DBAL/Driver/Mysqli/MysqliStatement.php @@ -1,93 +1,65 @@ . - */ namespace Doctrine\DBAL\Driver\Mysqli; use Doctrine\DBAL\Driver\Statement; use Doctrine\DBAL\Driver\StatementIterator; +use Doctrine\DBAL\Exception\InvalidArgumentException; use Doctrine\DBAL\FetchMode; use Doctrine\DBAL\ParameterType; +use IteratorAggregate; +use mysqli; +use mysqli_stmt; +use PDO; +use stdClass; use function array_combine; use function array_fill; -use function call_user_func_array; use function count; +use function feof; +use function fread; +use function get_resource_type; +use function is_resource; +use function sprintf; use function str_repeat; -/** - * @author Kim Hemsø Rasmussen - */ -class MysqliStatement implements \IteratorAggregate, Statement +class MysqliStatement implements IteratorAggregate, Statement { - /** - * @var array - */ + /** @var string[] */ protected static $_paramTypeMap = [ ParameterType::STRING => 's', ParameterType::BINARY => 's', ParameterType::BOOLEAN => 'i', ParameterType::NULL => 's', ParameterType::INTEGER => 'i', - - // TODO Support LOB bigger then max package size - ParameterType::LARGE_OBJECT => 's', + ParameterType::LARGE_OBJECT => 'b', ]; - /** - * @var \mysqli - */ + /** @var mysqli */ protected $_conn; - /** - * @var \mysqli_stmt - */ + /** @var mysqli_stmt */ protected $_stmt; - /** - * @var null|boolean|array - */ + /** @var string[]|bool|null */ protected $_columnNames; - /** - * @var null|array - */ + /** @var mixed[]|null */ protected $_rowBindedValues; - /** - * @var array - */ + /** @var mixed[] */ protected $_bindedValues; - /** - * @var string - */ + /** @var string */ protected $types; /** * Contains ref values for bindValue(). * - * @var array + * @var mixed[] */ protected $_values = []; - /** - * @var int - */ + /** @var int */ protected $_defaultFetchMode = FetchMode::MIXED; /** @@ -98,24 +70,25 @@ class MysqliStatement implements \IteratorAggregate, Statement private $result = false; /** - * @param \mysqli $conn - * @param string $prepareString + * @param string $prepareString * - * @throws \Doctrine\DBAL\Driver\Mysqli\MysqliException + * @throws MysqliException */ - public function __construct(\mysqli $conn, $prepareString) + public function __construct(mysqli $conn, $prepareString) { $this->_conn = $conn; $this->_stmt = $conn->prepare($prepareString); - if (false === $this->_stmt) { + if ($this->_stmt === false) { throw new MysqliException($this->_conn->error, $this->_conn->sqlstate, $this->_conn->errno); } $paramCount = $this->_stmt->param_count; - if (0 < $paramCount) { - $this->types = str_repeat('s', $paramCount); - $this->_bindedValues = array_fill(1, $paramCount, null); + if (0 >= $paramCount) { + return; } + + $this->types = str_repeat('s', $paramCount); + $this->_bindedValues = array_fill(1, $paramCount, null); } /** @@ -123,18 +96,18 @@ public function __construct(\mysqli $conn, $prepareString) */ public function bindParam($column, &$variable, $type = ParameterType::STRING, $length = null) { - if (null === $type) { + if ($type === null) { $type = 's'; } else { - if (isset(self::$_paramTypeMap[$type])) { - $type = self::$_paramTypeMap[$type]; - } else { - throw new MysqliException("Unknown type: '{$type}'"); + if (! isset(self::$_paramTypeMap[$type])) { + throw new MysqliException(sprintf("Unknown type: '%s'", $type)); } + + $type = self::$_paramTypeMap[$type]; } $this->_bindedValues[$column] =& $variable; - $this->types[$column - 1] = $type; + $this->types[$column - 1] = $type; return true; } @@ -144,19 +117,19 @@ public function bindParam($column, &$variable, $type = ParameterType::STRING, $l */ public function bindValue($param, $value, $type = ParameterType::STRING) { - if (null === $type) { + if ($type === null) { $type = 's'; } else { - if (isset(self::$_paramTypeMap[$type])) { - $type = self::$_paramTypeMap[$type]; - } else { - throw new MysqliException("Unknown type: '{$type}'"); + if (! isset(self::$_paramTypeMap[$type])) { + throw new MysqliException(sprintf("Unknown type: '%s'", $type)); } + + $type = self::$_paramTypeMap[$type]; } - $this->_values[$param] = $value; + $this->_values[$param] = $value; $this->_bindedValues[$param] =& $this->_values[$param]; - $this->types[$param - 1] = $type; + $this->types[$param - 1] = $type; return true; } @@ -166,25 +139,27 @@ public function bindValue($param, $value, $type = ParameterType::STRING) */ public function execute($params = null) { - if (null !== $this->_bindedValues) { - if (null !== $params) { - if ( ! $this->_bindValues($params)) { + if ($this->_bindedValues !== null) { + if ($params !== null) { + if (! $this->_bindValues($params)) { throw new MysqliException($this->_stmt->error, $this->_stmt->errno); } } else { - if (!call_user_func_array([$this->_stmt, 'bind_param'], [$this->types] + $this->_bindedValues)) { + [$types, $values, $streams] = $this->separateBoundValues(); + if (! $this->_stmt->bind_param($types, ...$values)) { throw new MysqliException($this->_stmt->error, $this->_stmt->sqlstate, $this->_stmt->errno); } + $this->sendLongData($streams); } } - if ( ! $this->_stmt->execute()) { + if (! $this->_stmt->execute()) { throw new MysqliException($this->_stmt->error, $this->_stmt->sqlstate, $this->_stmt->errno); } - if (null === $this->_columnNames) { + if ($this->_columnNames === null) { $meta = $this->_stmt->result_metadata(); - if (false !== $meta) { + if ($meta !== false) { $columnNames = []; foreach ($meta->fetch_fields() as $col) { $columnNames[] = $col->name; @@ -197,7 +172,7 @@ public function execute($params = null) } } - if (false !== $this->_columnNames) { + if ($this->_columnNames !== false) { // Store result of every execution which has it. Otherwise it will be impossible // to execute a new statement in case if the previous one has non-fetched rows // @link http://dev.mysql.com/doc/refman/5.7/en/commands-out-of-sync.html @@ -221,7 +196,7 @@ public function execute($params = null) $refs[$key] =& $value; } - if (!call_user_func_array([$this->_stmt, 'bind_result'], $refs)) { + if (! $this->_stmt->bind_result(...$refs)) { throw new MysqliException($this->_stmt->error, $this->_stmt->sqlstate, $this->_stmt->errno); } } @@ -231,24 +206,80 @@ public function execute($params = null) return true; } + /** + * Split $this->_bindedValues into those values that need to be sent using mysqli::send_long_data() + * and those that can be bound the usual way. + * + * @return array|string> + */ + private function separateBoundValues() + { + $streams = $values = []; + $types = $this->types; + + foreach ($this->_bindedValues as $parameter => $value) { + if (! isset($types[$parameter - 1])) { + $types[$parameter - 1] = static::$_paramTypeMap[ParameterType::STRING]; + } + + if ($types[$parameter - 1] === static::$_paramTypeMap[ParameterType::LARGE_OBJECT]) { + if (is_resource($value)) { + if (get_resource_type($value) !== 'stream') { + throw new InvalidArgumentException('Resources passed with the LARGE_OBJECT parameter type must be stream resources.'); + } + $streams[$parameter] = $value; + $values[$parameter] = null; + continue; + } else { + $types[$parameter - 1] = static::$_paramTypeMap[ParameterType::STRING]; + } + } + + $values[$parameter] = $value; + } + + return [$types, $values, $streams]; + } + + /** + * Handle $this->_longData after regular query parameters have been bound + * + * @throws MysqliException + */ + private function sendLongData($streams) + { + foreach ($streams as $paramNr => $stream) { + while (! feof($stream)) { + $chunk = fread($stream, 8192); + + if ($chunk === false) { + throw new MysqliException("Failed reading the stream resource for parameter offset ${paramNr}."); + } + + if (! $this->_stmt->send_long_data($paramNr - 1, $chunk)) { + throw new MysqliException($this->_stmt->error, $this->_stmt->sqlstate, $this->_stmt->errno); + } + } + } + } + /** * Binds a array of values to bound parameters. * - * @param array $values + * @param mixed[] $values * * @return bool */ private function _bindValues($values) { $params = []; - $types = str_repeat('s', count($values)); - $params[0] = $types; + $types = str_repeat('s', count($values)); foreach ($values as &$v) { $params[] =& $v; } - return call_user_func_array([$this->_stmt, 'bind_param'], $params); + return $this->_stmt->bind_param($types, ...$params); } /** @@ -258,7 +289,7 @@ private function _fetch() { $ret = $this->_stmt->fetch(); - if (true === $ret) { + if ($ret === true) { $values = []; foreach ($this->_rowBindedValues as $v) { $values[] = $v; @@ -273,11 +304,11 @@ private function _fetch() /** * {@inheritdoc} */ - public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) + public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { // do not try fetching from the statement if it's not expected to contain result // in order to prevent exceptional situation - if (!$this->result) { + if (! $this->result) { return false; } @@ -288,11 +319,11 @@ public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NE } $values = $this->_fetch(); - if (null === $values) { + if ($values === null) { return false; } - if (false === $values) { + if ($values === false) { throw new MysqliException($this->_stmt->error, $this->_stmt->sqlstate, $this->_stmt->errno); } @@ -304,14 +335,14 @@ public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NE return array_combine($this->_columnNames, $values); case FetchMode::MIXED: - $ret = array_combine($this->_columnNames, $values); + $ret = array_combine($this->_columnNames, $values); $ret += $values; return $ret; case FetchMode::STANDARD_OBJECT: $assoc = array_combine($this->_columnNames, $values); - $ret = new \stdClass(); + $ret = new stdClass(); foreach ($assoc as $column => $value) { $ret->$column = $value; @@ -320,7 +351,7 @@ public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NE return $ret; default: - throw new MysqliException("Unknown fetch type '{$fetchMode}'"); + throw new MysqliException(sprintf("Unknown fetch type '%s'", $fetchMode)); } } @@ -353,7 +384,7 @@ public function fetchColumn($columnIndex = 0) { $row = $this->fetch(FetchMode::NUMERIC); - if (false === $row) { + if ($row === false) { return false; } @@ -392,7 +423,7 @@ public function closeCursor() */ public function rowCount() { - if (false === $this->_columnNames) { + if ($this->_columnNames === false) { return $this->_stmt->affected_rows; } diff --git a/lib/Doctrine/DBAL/Driver/OCI8/Driver.php b/lib/Doctrine/DBAL/Driver/OCI8/Driver.php index 1de1bc4b8b1..533db04dcfc 100644 --- a/lib/Doctrine/DBAL/Driver/OCI8/Driver.php +++ b/lib/Doctrine/DBAL/Driver/OCI8/Driver.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\OCI8; @@ -31,9 +14,6 @@ /** * A Doctrine DBAL driver for the Oracle OCI8 PHP extensions. - * - * @author Roman Borschel - * @since 2.0 */ class Driver extends AbstractOracleDriver { @@ -59,7 +39,7 @@ public function connect(array $params, $username = null, $password = null, array /** * Constructs the Oracle DSN. * - * @param array $params + * @param mixed[] $params * * @return string The DSN. */ diff --git a/lib/Doctrine/DBAL/Driver/OCI8/OCI8Connection.php b/lib/Doctrine/DBAL/Driver/OCI8/OCI8Connection.php index e2111d47444..5ebc877a898 100644 --- a/lib/Doctrine/DBAL/Driver/OCI8/OCI8Connection.php +++ b/lib/Doctrine/DBAL/Driver/OCI8/OCI8Connection.php @@ -1,27 +1,11 @@ . - */ namespace Doctrine\DBAL\Driver\OCI8; use Doctrine\DBAL\Driver\Connection; use Doctrine\DBAL\Driver\ServerInfoAwareConnection; use Doctrine\DBAL\ParameterType; +use UnexpectedValueException; use const OCI_COMMIT_ON_SUCCESS; use const OCI_DEFAULT; use const OCI_NO_AUTO_COMMIT; @@ -43,19 +27,13 @@ /** * OCI8 implementation of the Connection interface. - * - * @since 2.0 */ class OCI8Connection implements Connection, ServerInfoAwareConnection { - /** - * @var resource - */ + /** @var resource */ protected $dbh; - /** - * @var int - */ + /** @var int */ protected $executeMode = OCI_COMMIT_ON_SUCCESS; /** @@ -72,7 +50,7 @@ class OCI8Connection implements Connection, ServerInfoAwareConnection */ public function __construct($username, $password, $db, $charset = null, $sessionMode = OCI_DEFAULT, $persistent = false) { - if (!defined('OCI_NO_AUTO_COMMIT')) { + if (! defined('OCI_NO_AUTO_COMMIT')) { define('OCI_NO_AUTO_COMMIT', 0); } @@ -80,7 +58,7 @@ public function __construct($username, $password, $db, $charset = null, $session ? @oci_pconnect($username, $password, $db, $charset, $sessionMode) : @oci_connect($username, $password, $db, $charset, $sessionMode); - if ( ! $this->dbh) { + if (! $this->dbh) { throw OCI8Exception::fromErrorInfo(oci_error()); } } @@ -88,13 +66,13 @@ public function __construct($username, $password, $db, $charset = null, $session /** * {@inheritdoc} * - * @throws \UnexpectedValueException if the version string returned by the database server - * does not contain a parsable version number. + * @throws UnexpectedValueException If the version string returned by the database server + * does not contain a parsable version number. */ public function getServerVersion() { - if ( ! preg_match('/\s+(\d+\.\d+\.\d+\.\d+\.\d+)\s+/', oci_server_version($this->dbh), $version)) { - throw new \UnexpectedValueException( + if (! preg_match('/\s+(\d+\.\d+\.\d+\.\d+\.\d+)\s+/', oci_server_version($this->dbh), $version)) { + throw new UnexpectedValueException( sprintf( 'Unexpected database version string "%s". Cannot parse an appropriate version number from it. ' . 'Please report this database version string to the Doctrine team.', @@ -128,7 +106,7 @@ public function prepare($prepareString) public function query() { $args = func_get_args(); - $sql = $args[0]; + $sql = $args[0]; //$fetchMode = $args[1]; $stmt = $this->prepare($sql); $stmt->execute(); @@ -174,7 +152,7 @@ public function lastInsertId($name = null) $result = $stmt->fetchColumn(); if ($result === false) { - throw new OCI8Exception("lastInsertId failed: Query was executed but no result was returned."); + throw new OCI8Exception('lastInsertId failed: Query was executed but no result was returned.'); } return (int) $result; @@ -205,7 +183,7 @@ public function beginTransaction() */ public function commit() { - if (!oci_commit($this->dbh)) { + if (! oci_commit($this->dbh)) { throw OCI8Exception::fromErrorInfo($this->errorInfo()); } $this->executeMode = OCI_COMMIT_ON_SUCCESS; @@ -218,7 +196,7 @@ public function commit() */ public function rollBack() { - if (!oci_rollback($this->dbh)) { + if (! oci_rollback($this->dbh)) { throw OCI8Exception::fromErrorInfo($this->errorInfo()); } $this->executeMode = OCI_COMMIT_ON_SUCCESS; diff --git a/lib/Doctrine/DBAL/Driver/OCI8/OCI8Exception.php b/lib/Doctrine/DBAL/Driver/OCI8/OCI8Exception.php index 1cd08b8a408..9d61ad42d08 100644 --- a/lib/Doctrine/DBAL/Driver/OCI8/OCI8Exception.php +++ b/lib/Doctrine/DBAL/Driver/OCI8/OCI8Exception.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\OCI8; @@ -24,7 +7,7 @@ class OCI8Exception extends AbstractDriverException { /** - * @param array $error + * @param mixed[] $error * * @return \Doctrine\DBAL\Driver\OCI8\OCI8Exception */ diff --git a/lib/Doctrine/DBAL/Driver/OCI8/OCI8Statement.php b/lib/Doctrine/DBAL/Driver/OCI8/OCI8Statement.php index 0df45fc1b99..8db54c86aa7 100644 --- a/lib/Doctrine/DBAL/Driver/OCI8/OCI8Statement.php +++ b/lib/Doctrine/DBAL/Driver/OCI8/OCI8Statement.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\OCI8; @@ -23,7 +6,9 @@ use Doctrine\DBAL\Driver\StatementIterator; use Doctrine\DBAL\FetchMode; use Doctrine\DBAL\ParameterType; +use InvalidArgumentException; use IteratorAggregate; +use PDO; use const OCI_ASSOC; use const OCI_B_BIN; use const OCI_B_BLOB; @@ -59,35 +44,22 @@ /** * The OCI8 implementation of the Statement interface. - * - * @since 2.0 - * @author Roman Borschel */ class OCI8Statement implements IteratorAggregate, Statement { - /** - * @var resource - */ + /** @var resource */ protected $_dbh; - /** - * @var resource - */ + /** @var resource */ protected $_sth; - /** - * @var \Doctrine\DBAL\Driver\OCI8\OCI8Connection - */ + /** @var OCI8Connection */ protected $_conn; - /** - * @var string - */ + /** @var string */ protected static $_PARAM = ':param'; - /** - * @var array - */ + /** @var int[] */ protected static $fetchModeMap = [ FetchMode::MIXED => OCI_BOTH, FetchMode::ASSOCIATIVE => OCI_ASSOC, @@ -95,14 +67,10 @@ class OCI8Statement implements IteratorAggregate, Statement FetchMode::COLUMN => OCI_NUM, ]; - /** - * @var int - */ + /** @var int */ protected $_defaultFetchMode = FetchMode::MIXED; - /** - * @var array - */ + /** @var string[] */ protected $_paramMap = []; /** @@ -110,7 +78,7 @@ class OCI8Statement implements IteratorAggregate, Statement * * This is a new requirement for PHP7's oci8 extension that prevents bound values from being garbage collected. * - * @var array + * @var mixed[] */ private $boundValues = []; @@ -124,17 +92,16 @@ class OCI8Statement implements IteratorAggregate, Statement /** * Creates a new OCI8Statement that uses the given connection handle and SQL statement. * - * @param resource $dbh The connection handle. - * @param string $statement The SQL statement. - * @param \Doctrine\DBAL\Driver\OCI8\OCI8Connection $conn + * @param resource $dbh The connection handle. + * @param string $statement The SQL statement. */ public function __construct($dbh, $statement, OCI8Connection $conn) { - list($statement, $paramMap) = self::convertPositionalToNamedPlaceholders($statement); - $this->_sth = oci_parse($dbh, $statement); - $this->_dbh = $dbh; - $this->_paramMap = $paramMap; - $this->_conn = $conn; + [$statement, $paramMap] = self::convertPositionalToNamedPlaceholders($statement); + $this->_sth = oci_parse($dbh, $statement); + $this->_dbh = $dbh; + $this->_paramMap = $paramMap; + $this->_conn = $conn; } /** @@ -149,22 +116,23 @@ public function __construct($dbh, $statement, OCI8Connection $conn) * Question marks inside literal strings are therefore handled correctly by this method. * This comes at a cost, the whole sql statement has to be looped over. * - * @todo extract into utility class in Doctrine\DBAL\Util namespace - * @todo review and test for lost spaces. we experienced missing spaces with oci8 in some sql statements. - * * @param string $statement The SQL statement to convert. * - * @return array [0] => the statement value (string), [1] => the paramMap value (array). - * @throws \Doctrine\DBAL\Driver\OCI8\OCI8Exception + * @return mixed[] [0] => the statement value (string), [1] => the paramMap value (array). + * + * @throws OCI8Exception + * + * @todo extract into utility class in Doctrine\DBAL\Util namespace + * @todo review and test for lost spaces. we experienced missing spaces with oci8 in some sql statements. */ public static function convertPositionalToNamedPlaceholders($statement) { - $fragmentOffset = $tokenOffset = 0; - $fragments = $paramMap = []; + $fragmentOffset = $tokenOffset = 0; + $fragments = $paramMap = []; $currentLiteralDelimiter = null; do { - if (!$currentLiteralDelimiter) { + if (! $currentLiteralDelimiter) { $result = self::findPlaceholderOrOpeningQuote( $statement, $tokenOffset, @@ -186,7 +154,7 @@ public static function convertPositionalToNamedPlaceholders($statement) } $fragments[] = substr($statement, $fragmentOffset); - $statement = implode('', $fragments); + $statement = implode('', $fragments); return [$statement, $paramMap]; } @@ -201,6 +169,7 @@ public static function convertPositionalToNamedPlaceholders($statement) * @param string|null $currentLiteralDelimiter The delimiter of the current string literal * or NULL if not currently in a literal * @param array $paramMap Mapping of the original parameter positions to their named replacements + * * @return bool Whether the token was found */ private static function findPlaceholderOrOpeningQuote( @@ -213,18 +182,18 @@ private static function findPlaceholderOrOpeningQuote( ) { $token = self::findToken($statement, $tokenOffset, '/[?\'"]/'); - if (!$token) { + if (! $token) { return false; } if ($token === '?') { - $position = count($paramMap) + 1; - $param = ':param' . $position; - $fragments[] = substr($statement, $fragmentOffset, $tokenOffset - $fragmentOffset); - $fragments[] = $param; + $position = count($paramMap) + 1; + $param = ':param' . $position; + $fragments[] = substr($statement, $fragmentOffset, $tokenOffset - $fragmentOffset); + $fragments[] = $param; $paramMap[$position] = $param; - $tokenOffset += 1; - $fragmentOffset = $tokenOffset; + $tokenOffset += 1; + $fragmentOffset = $tokenOffset; return true; } @@ -242,6 +211,7 @@ private static function findPlaceholderOrOpeningQuote( * @param string $tokenOffset The offset to start searching from * @param string|null $currentLiteralDelimiter The delimiter of the current string literal * or NULL if not currently in a literal + * * @return bool Whether the token was found */ private static function findClosingQuote( @@ -255,7 +225,7 @@ private static function findClosingQuote( '/' . preg_quote($currentLiteralDelimiter, '/') . '/' ); - if (!$token) { + if (! $token) { return false; } @@ -272,6 +242,7 @@ private static function findClosingQuote( * @param string $statement The SQL statement to parse * @param string $offset The offset to start searching from * @param string $regex The regex containing token pattern + * * @return string|null Token or NULL if not found */ private static function findToken($statement, &$offset, $regex) @@ -340,7 +311,7 @@ private function convertParameterType(int $type) : int public function closeCursor() { // not having the result means there's nothing to close - if (!$this->result) { + if (! $this->result) { return true; } @@ -397,7 +368,7 @@ public function execute($params = null) } $ret = @oci_execute($this->_sth, $this->_conn->getExecuteMode()); - if ( ! $ret) { + if (! $ret) { throw OCI8Exception::fromErrorInfo($this->errorInfo()); } @@ -427,11 +398,11 @@ public function getIterator() /** * {@inheritdoc} */ - public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) + public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { // do not try fetching from the statement if it's not expected to contain result // in order to prevent exceptional situation - if (!$this->result) { + if (! $this->result) { return false; } @@ -446,7 +417,7 @@ public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NE } if (! isset(self::$fetchModeMap[$fetchMode])) { - throw new \InvalidArgumentException("Invalid fetch style: " . $fetchMode); + throw new InvalidArgumentException('Invalid fetch style: ' . $fetchMode); } return oci_fetch_array( @@ -472,8 +443,8 @@ public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = n return $result; } - if ( ! isset(self::$fetchModeMap[$fetchMode])) { - throw new \InvalidArgumentException("Invalid fetch style: " . $fetchMode); + if (! isset(self::$fetchModeMap[$fetchMode])) { + throw new InvalidArgumentException('Invalid fetch style: ' . $fetchMode); } if (self::$fetchModeMap[$fetchMode] === OCI_BOTH) { @@ -489,12 +460,17 @@ public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = n // do not try fetching from the statement if it's not expected to contain result // in order to prevent exceptional situation - if (!$this->result) { + if (! $this->result) { return []; } - oci_fetch_all($this->_sth, $result, 0, -1, - self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | $fetchStructure | OCI_RETURN_LOBS); + oci_fetch_all( + $this->_sth, + $result, + 0, + -1, + self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | $fetchStructure | OCI_RETURN_LOBS + ); if ($fetchMode === FetchMode::COLUMN) { $result = $result[0]; @@ -511,13 +487,13 @@ public function fetchColumn($columnIndex = 0) { // do not try fetching from the statement if it's not expected to contain result // in order to prevent exceptional situation - if (!$this->result) { + if (! $this->result) { return false; } $row = oci_fetch_array($this->_sth, OCI_NUM | OCI_RETURN_NULLS | OCI_RETURN_LOBS); - if (false === $row) { + if ($row === false) { return false; } diff --git a/lib/Doctrine/DBAL/Driver/PDOConnection.php b/lib/Doctrine/DBAL/Driver/PDOConnection.php index 62a214a53d2..2155140b2a8 100644 --- a/lib/Doctrine/DBAL/Driver/PDOConnection.php +++ b/lib/Doctrine/DBAL/Driver/PDOConnection.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver; @@ -27,24 +10,22 @@ /** * PDO implementation of the Connection interface. * Used by all PDO-based drivers. - * - * @since 2.0 */ class PDOConnection extends PDO implements Connection, ServerInfoAwareConnection { /** - * @param string $dsn - * @param string|null $user - * @param string|null $password - * @param array|null $options + * @param string $dsn + * @param string|null $user + * @param string|null $password + * @param mixed[]|null $options * - * @throws PDOException in case of an error. + * @throws PDOException In case of an error. */ - public function __construct($dsn, $user = null, $password = null, array $options = null) + public function __construct($dsn, $user = null, $password = null, ?array $options = null) { try { parent::__construct($dsn, $user, $password, $options); - $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, ['Doctrine\DBAL\Driver\PDOStatement', []]); + $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, [PDOStatement::class, []]); $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (\PDOException $exception) { throw new PDOException($exception); @@ -88,19 +69,19 @@ public function prepare($prepareString, $driverOptions = []) */ public function query() { - $args = func_get_args(); + $args = func_get_args(); $argsCount = count($args); try { - if ($argsCount == 4) { + if ($argsCount === 4) { return parent::query($args[0], $args[1], $args[2], $args[3]); } - if ($argsCount == 3) { + if ($argsCount === 3) { return parent::query($args[0], $args[1], $args[2]); } - if ($argsCount == 2) { + if ($argsCount === 2) { return parent::query($args[0], $args[1]); } @@ -123,7 +104,11 @@ public function quote($input, $type = ParameterType::STRING) */ public function lastInsertId($name = null) { - return parent::lastInsertId($name); + try { + return parent::lastInsertId($name); + } catch (\PDOException $exception) { + throw new PDOException($exception); + } } /** diff --git a/lib/Doctrine/DBAL/Driver/PDOException.php b/lib/Doctrine/DBAL/Driver/PDOException.php index 25689b66e2c..277d7a62500 100644 --- a/lib/Doctrine/DBAL/Driver/PDOException.php +++ b/lib/Doctrine/DBAL/Driver/PDOException.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Driver; /** * Tiny wrapper for PDOException instances to implement the {@link DriverException} interface. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class PDOException extends \PDOException implements DriverException { @@ -43,8 +22,6 @@ class PDOException extends \PDOException implements DriverException private $sqlState; /** - * Constructor. - * * @param \PDOException $exception The PDO exception to wrap. */ public function __construct(\PDOException $exception) diff --git a/lib/Doctrine/DBAL/Driver/PDOIbm/Driver.php b/lib/Doctrine/DBAL/Driver/PDOIbm/Driver.php index faebcd84268..4291e1e17f0 100644 --- a/lib/Doctrine/DBAL/Driver/PDOIbm/Driver.php +++ b/lib/Doctrine/DBAL/Driver/PDOIbm/Driver.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\PDOIbm; @@ -24,13 +7,6 @@ /** * Driver for the PDO IBM extension. - * - * @link www.doctrine-project.org - * @since 1.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class Driver extends AbstractDB2Driver { @@ -39,20 +15,18 @@ class Driver extends AbstractDB2Driver */ public function connect(array $params, $username = null, $password = null, array $driverOptions = []) { - $conn = new PDOConnection( + return new PDOConnection( $this->_constructPdoDsn($params), $username, $password, $driverOptions ); - - return $conn; } /** * Constructs the IBM PDO DSN. * - * @param array $params + * @param mixed[] $params * * @return string The DSN. */ diff --git a/lib/Doctrine/DBAL/Driver/PDOMySql/Driver.php b/lib/Doctrine/DBAL/Driver/PDOMySql/Driver.php index 44a9d5b82f6..59d27d3844f 100644 --- a/lib/Doctrine/DBAL/Driver/PDOMySql/Driver.php +++ b/lib/Doctrine/DBAL/Driver/PDOMySql/Driver.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\PDOMySql; @@ -26,8 +9,6 @@ /** * PDO MySql driver. - * - * @since 2.0 */ class Driver extends AbstractMySQLDriver { @@ -53,14 +34,14 @@ public function connect(array $params, $username = null, $password = null, array /** * Constructs the MySql PDO DSN. * - * @param array $params + * @param mixed[] $params * * @return string The DSN. */ protected function constructPdoDsn(array $params) { $dsn = 'mysql:'; - if (isset($params['host']) && $params['host'] != '') { + if (isset($params['host']) && $params['host'] !== '') { $dsn .= 'host=' . $params['host'] . ';'; } if (isset($params['port'])) { diff --git a/lib/Doctrine/DBAL/Driver/PDOOracle/Driver.php b/lib/Doctrine/DBAL/Driver/PDOOracle/Driver.php index 61edca747e9..f1239eafbd4 100644 --- a/lib/Doctrine/DBAL/Driver/PDOOracle/Driver.php +++ b/lib/Doctrine/DBAL/Driver/PDOOracle/Driver.php @@ -1,27 +1,11 @@ . - */ namespace Doctrine\DBAL\Driver\PDOOracle; use Doctrine\DBAL\DBALException; use Doctrine\DBAL\Driver\AbstractOracleDriver; use Doctrine\DBAL\Driver\PDOConnection; +use PDOException; /** * PDO Oracle driver. @@ -45,7 +29,7 @@ public function connect(array $params, $username = null, $password = null, array $password, $driverOptions ); - } catch (\PDOException $e) { + } catch (PDOException $e) { throw DBALException::driverException($this, $e); } } @@ -53,7 +37,7 @@ public function connect(array $params, $username = null, $password = null, array /** * Constructs the Oracle PDO DSN. * - * @param array $params + * @param mixed[] $params * * @return string The DSN. */ diff --git a/lib/Doctrine/DBAL/Driver/PDOPgSql/Driver.php b/lib/Doctrine/DBAL/Driver/PDOPgSql/Driver.php index d0946fd4640..972dbadcd5d 100644 --- a/lib/Doctrine/DBAL/Driver/PDOPgSql/Driver.php +++ b/lib/Doctrine/DBAL/Driver/PDOPgSql/Driver.php @@ -1,35 +1,16 @@ . - */ namespace Doctrine\DBAL\Driver\PDOPgSql; +use Doctrine\DBAL\DBALException; use Doctrine\DBAL\Driver\AbstractPostgreSQLDriver; use Doctrine\DBAL\Driver\PDOConnection; -use Doctrine\DBAL\DBALException; -use PDOException; use PDO; +use PDOException; use function defined; /** * Driver that connects through pdo_pgsql. - * - * @since 2.0 */ class Driver extends AbstractPostgreSQLDriver { @@ -48,7 +29,7 @@ public function connect(array $params, $username = null, $password = null, array if (defined('PDO::PGSQL_ATTR_DISABLE_PREPARES') && (! isset($driverOptions[PDO::PGSQL_ATTR_DISABLE_PREPARES]) - || true === $driverOptions[PDO::PGSQL_ATTR_DISABLE_PREPARES] + || $driverOptions[PDO::PGSQL_ATTR_DISABLE_PREPARES] === true ) ) { $pdo->setAttribute(PDO::PGSQL_ATTR_DISABLE_PREPARES, true); @@ -71,7 +52,7 @@ public function connect(array $params, $username = null, $password = null, array /** * Constructs the Postgres PDO DSN. * - * @param array $params + * @param mixed[] $params * * @return string The DSN. */ @@ -79,11 +60,11 @@ private function _constructPdoDsn(array $params) { $dsn = 'pgsql:'; - if (isset($params['host']) && $params['host'] != '') { + if (isset($params['host']) && $params['host'] !== '') { $dsn .= 'host=' . $params['host'] . ';'; } - if (isset($params['port']) && $params['port'] != '') { + if (isset($params['port']) && $params['port'] !== '') { $dsn .= 'port=' . $params['port'] . ';'; } @@ -95,7 +76,7 @@ private function _constructPdoDsn(array $params) // Used for temporary connections to allow operations like dropping the database currently connected to. // Connecting without an explicit database does not work, therefore "postgres" database is used // as it is mostly present in every server setup. - $dsn .= 'dbname=postgres' . ';'; + $dsn .= 'dbname=postgres;'; } if (isset($params['sslmode'])) { diff --git a/lib/Doctrine/DBAL/Driver/PDOSqlite/Driver.php b/lib/Doctrine/DBAL/Driver/PDOSqlite/Driver.php index 096f7a2b64f..7a28b831027 100644 --- a/lib/Doctrine/DBAL/Driver/PDOSqlite/Driver.php +++ b/lib/Doctrine/DBAL/Driver/PDOSqlite/Driver.php @@ -1,44 +1,24 @@ . - */ namespace Doctrine\DBAL\Driver\PDOSqlite; use Doctrine\DBAL\DBALException; use Doctrine\DBAL\Driver\AbstractSQLiteDriver; use Doctrine\DBAL\Driver\PDOConnection; +use Doctrine\DBAL\Platforms\SqlitePlatform; use PDOException; use function array_merge; /** * The PDO Sqlite driver. - * - * @since 2.0 */ class Driver extends AbstractSQLiteDriver { - /** - * @var array - */ + /** @var mixed[] */ protected $_userDefinedFunctions = [ - 'sqrt' => ['callback' => ['Doctrine\DBAL\Platforms\SqlitePlatform', 'udfSqrt'], 'numArgs' => 1], - 'mod' => ['callback' => ['Doctrine\DBAL\Platforms\SqlitePlatform', 'udfMod'], 'numArgs' => 2], - 'locate' => ['callback' => ['Doctrine\DBAL\Platforms\SqlitePlatform', 'udfLocate'], 'numArgs' => -1], + 'sqrt' => ['callback' => [SqlitePlatform::class, 'udfSqrt'], 'numArgs' => 1], + 'mod' => ['callback' => [SqlitePlatform::class, 'udfMod'], 'numArgs' => 2], + 'locate' => ['callback' => [SqlitePlatform::class, 'udfLocate'], 'numArgs' => -1], ]; /** @@ -48,7 +28,9 @@ public function connect(array $params, $username = null, $password = null, array { if (isset($driverOptions['userDefinedFunctions'])) { $this->_userDefinedFunctions = array_merge( - $this->_userDefinedFunctions, $driverOptions['userDefinedFunctions']); + $this->_userDefinedFunctions, + $driverOptions['userDefinedFunctions'] + ); unset($driverOptions['userDefinedFunctions']); } @@ -73,7 +55,7 @@ public function connect(array $params, $username = null, $password = null, array /** * Constructs the Sqlite PDO DSN. * - * @param array $params + * @param mixed[] $params * * @return string The DSN. */ diff --git a/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Connection.php b/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Connection.php index 7ce7e8a76b6..bd3894477b5 100644 --- a/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Connection.php +++ b/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Connection.php @@ -1,43 +1,25 @@ . - */ namespace Doctrine\DBAL\Driver\PDOSqlsrv; use Doctrine\DBAL\Driver\PDOConnection; use Doctrine\DBAL\ParameterType; +use PDO; use function strpos; use function substr; /** * Sqlsrv Connection implementation. - * - * @since 2.0 */ -class Connection extends PDOConnection implements \Doctrine\DBAL\Driver\Connection +class Connection extends PDOConnection { /** * {@inheritdoc} */ - public function __construct($dsn, $user = null, $password = null, array $options = null) + public function __construct($dsn, $user = null, $password = null, ?array $options = null) { parent::__construct($dsn, $user, $password, $options); - $this->setAttribute(\PDO::ATTR_STATEMENT_CLASS, [Statement::class, []]); + $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, [Statement::class, []]); } /** @@ -45,7 +27,7 @@ public function __construct($dsn, $user = null, $password = null, array $options */ public function lastInsertId($name = null) { - if (null === $name) { + if ($name === null) { return parent::lastInsertId($name); } diff --git a/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Driver.php b/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Driver.php index c27ffe1b209..6543e32392e 100644 --- a/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Driver.php +++ b/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Driver.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\PDOSqlsrv; @@ -25,8 +8,6 @@ /** * The PDO-based Sqlsrv driver. - * - * @since 2.0 */ class Driver extends AbstractSQLServerDriver { @@ -48,7 +29,7 @@ public function connect(array $params, $username = null, $password = null, array /** * Constructs the Sqlsrv PDO DSN. * - * @param array $params + * @param mixed[] $params * @param string[] $connectionOptions * * @return string The DSN. @@ -61,7 +42,7 @@ private function _constructPdoDsn(array $params, array $connectionOptions) $dsn .= $params['host']; } - if (isset($params['port']) && !empty($params['port'])) { + if (isset($params['port']) && ! empty($params['port'])) { $dsn .= ',' . $params['port']; } @@ -73,15 +54,14 @@ private function _constructPdoDsn(array $params, array $connectionOptions) $connectionOptions['MultipleActiveResultSets'] = $params['MultipleActiveResultSets'] ? 'true' : 'false'; } - $dsn .= $this->getConnectionOptionsDsn($connectionOptions); - - return $dsn; + return $dsn . $this->getConnectionOptionsDsn($connectionOptions); } /** * Separates a connection options from a driver options * * @param int[]|string[] $options + * * @return int[][]|string[][] */ private function splitOptions(array $options) : array diff --git a/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Statement.php b/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Statement.php index 3704003425f..6803bb14ed7 100644 --- a/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Statement.php +++ b/lib/Doctrine/DBAL/Driver/PDOSqlsrv/Statement.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\PDOSqlsrv; diff --git a/lib/Doctrine/DBAL/Driver/PDOStatement.php b/lib/Doctrine/DBAL/Driver/PDOStatement.php index 7b292639353..2aed89fbf07 100644 --- a/lib/Doctrine/DBAL/Driver/PDOStatement.php +++ b/lib/Doctrine/DBAL/Driver/PDOStatement.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver; @@ -29,14 +12,9 @@ /** * The PDO implementation of the Statement interface. * Used by all PDO-based drivers. - * - * @since 2.0 */ class PDOStatement extends \PDOStatement implements Statement { - /** - * @var int[] - */ private const PARAM_TYPE_MAP = [ ParameterType::NULL => PDO::PARAM_NULL, ParameterType::INTEGER => PDO::PARAM_INT, @@ -46,9 +24,6 @@ class PDOStatement extends \PDOStatement implements Statement ParameterType::BOOLEAN => PDO::PARAM_BOOL, ]; - /** - * @var int[] - */ private const FETCH_MODE_MAP = [ FetchMode::ASSOCIATIVE => PDO::FETCH_ASSOC, FetchMode::NUMERIC => PDO::FETCH_NUM, @@ -148,20 +123,20 @@ public function execute($params = null) /** * {@inheritdoc} */ - public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) + public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { $fetchMode = $this->convertFetchMode($fetchMode); try { - if ($fetchMode === null && \PDO::FETCH_ORI_NEXT === $cursorOrientation && 0 === $cursorOffset) { + if ($fetchMode === null && $cursorOrientation === PDO::FETCH_ORI_NEXT && $cursorOffset === 0) { return parent::fetch(); } - if (\PDO::FETCH_ORI_NEXT === $cursorOrientation && 0 === $cursorOffset) { + if ($cursorOrientation === PDO::FETCH_ORI_NEXT && $cursorOffset === 0) { return parent::fetch($fetchMode); } - if (0 === $cursorOffset) { + if ($cursorOffset === 0) { return parent::fetch($fetchMode, $cursorOrientation); } @@ -179,15 +154,15 @@ public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = n $fetchMode = $this->convertFetchMode($fetchMode); try { - if ($fetchMode === null && null === $fetchArgument && null === $ctorArgs) { + if ($fetchMode === null && $fetchArgument === null && $ctorArgs === null) { return parent::fetchAll(); } - if (null === $fetchArgument && null === $ctorArgs) { + if ($fetchArgument === null && $ctorArgs === null) { return parent::fetchAll($fetchMode); } - if (null === $ctorArgs) { + if ($ctorArgs === null) { return parent::fetchAll($fetchMode, $fetchArgument); } diff --git a/lib/Doctrine/DBAL/Driver/PingableConnection.php b/lib/Doctrine/DBAL/Driver/PingableConnection.php index 8c85a82c839..06bfb9a7f26 100644 --- a/lib/Doctrine/DBAL/Driver/PingableConnection.php +++ b/lib/Doctrine/DBAL/Driver/PingableConnection.php @@ -1,31 +1,9 @@ . - */ namespace Doctrine\DBAL\Driver; /** * An interface for connections which support a "native" ping method. - * - * @link www.doctrine-project.org - * @since 2.5 - * @author Till Klampaeckel - * @author Benjamin Eberlei */ interface PingableConnection { diff --git a/lib/Doctrine/DBAL/Driver/ResultStatement.php b/lib/Doctrine/DBAL/Driver/ResultStatement.php index b03862ff6e3..1e6df0269b8 100644 --- a/lib/Doctrine/DBAL/Driver/ResultStatement.php +++ b/lib/Doctrine/DBAL/Driver/ResultStatement.php @@ -1,30 +1,14 @@ . - */ namespace Doctrine\DBAL\Driver; +use PDO; +use Traversable; + /** * Interface for the reading part of a prepare statement only. - * - * @author Benjamin Eberlei */ -interface ResultStatement extends \Traversable +interface ResultStatement extends Traversable { /** * Closes the cursor, enabling the statement to be executed again. @@ -78,27 +62,27 @@ public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null); * @return mixed The return value of this method on success depends on the fetch mode. In all cases, FALSE is * returned on failure. */ - public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0); + public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0); /** * Returns an array containing all of the result set rows. * - * @param int|null $fetchMode Controls how the next row will be returned to the caller. - * The value must be one of the {@link \Doctrine\DBAL\FetchMode} constants, - * defaulting to {@link \Doctrine\DBAL\FetchMode::MIXED}. - * @param int|null $fetchArgument This argument has a different meaning depending on the value of the $fetchMode parameter: - * * {@link \Doctrine\DBAL\FetchMode::COLUMN}: - * Returns the indicated 0-indexed column. - * * {@link \Doctrine\DBAL\FetchMode::CUSTOM_OBJECT}: - * Returns instances of the specified class, mapping the columns of each row - * to named properties in the class. - * * \PDO::FETCH_FUNC: Returns the results of calling the specified function, using each row's - * columns as parameters in the call. - * @param array|null $ctorArgs Controls how the next row will be returned to the caller. - * The value must be one of the {@link \Doctrine\DBAL\FetchMode} constants, - * defaulting to {@link \Doctrine\DBAL\FetchMode::MIXED}. + * @param int|null $fetchMode Controls how the next row will be returned to the caller. + * The value must be one of the {@link \Doctrine\DBAL\FetchMode} constants, + * defaulting to {@link \Doctrine\DBAL\FetchMode::MIXED}. + * @param int|null $fetchArgument This argument has a different meaning depending on the value of the $fetchMode parameter: + * * {@link \Doctrine\DBAL\FetchMode::COLUMN}: + * Returns the indicated 0-indexed column. + * * {@link \Doctrine\DBAL\FetchMode::CUSTOM_OBJECT}: + * Returns instances of the specified class, mapping the columns of each row + * to named properties in the class. + * * \PDO::FETCH_FUNC: Returns the results of calling the specified function, using each row's + * columns as parameters in the call. + * @param mixed[]|null $ctorArgs Controls how the next row will be returned to the caller. + * The value must be one of the {@link \Doctrine\DBAL\FetchMode} constants, + * defaulting to {@link \Doctrine\DBAL\FetchMode::MIXED}. * - * @return array + * @return mixed[] */ public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null); @@ -106,10 +90,9 @@ public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = n * Returns a single column from the next row of a result set or FALSE if there are no more rows. * * @param int $columnIndex 0-indexed number of the column you wish to retrieve from the row. - * If no value is supplied, PDOStatement->fetchColumn() - * fetches the first column. + * If no value is supplied, fetches the first column. * - * @return string|boolean A single column in the next row of a result set, or FALSE if there are no more rows. + * @return mixed|false A single column in the next row of a result set, or FALSE if there are no more rows. */ public function fetchColumn($columnIndex = 0); } diff --git a/lib/Doctrine/DBAL/Driver/SQLAnywhere/Driver.php b/lib/Doctrine/DBAL/Driver/SQLAnywhere/Driver.php index 1ff0b04b1ba..294d5c7a5e9 100644 --- a/lib/Doctrine/DBAL/Driver/SQLAnywhere/Driver.php +++ b/lib/Doctrine/DBAL/Driver/SQLAnywhere/Driver.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\SQLAnywhere; @@ -27,17 +10,13 @@ /** * A Doctrine DBAL driver for the SAP Sybase SQL Anywhere PHP extension. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class Driver extends AbstractSQLAnywhereDriver { /** * {@inheritdoc} * - * @throws \Doctrine\DBAL\DBALException if there was a problem establishing the connection. + * @throws DBALException If there was a problem establishing the connection. */ public function connect(array $params, $username = null, $password = null, array $driverOptions = []) { @@ -70,15 +49,15 @@ public function getName() /** * Build the connection string for given connection parameters and driver options. * - * @param string $host Host address to connect to. - * @param int $port Port to use for the connection (default to SQL Anywhere standard port 2638). - * @param string $server Database server name on the host to connect to. - * SQL Anywhere allows multiple database server instances on the same host, - * therefore specifying the server instance name to use is mandatory. - * @param string $dbname Name of the database on the server instance to connect to. - * @param string $username User name to use for connection authentication. - * @param string $password Password to use for connection authentication. - * @param array $driverOptions Additional parameters to use for the connection. + * @param string $host Host address to connect to. + * @param int $port Port to use for the connection (default to SQL Anywhere standard port 2638). + * @param string $server Database server name on the host to connect to. + * SQL Anywhere allows multiple database server instances on the same host, + * therefore specifying the server instance name to use is mandatory. + * @param string $dbname Name of the database on the server instance to connect to. + * @param string $username User name to use for connection authentication. + * @param string $password Password to use for connection authentication. + * @param mixed[] $driverOptions Additional parameters to use for the connection. * * @return string */ @@ -91,15 +70,14 @@ private function buildDsn($host, $port, $server, $dbname, $username = null, $pas $server = ';ServerName=' . $server; } - return - 'HOST=' . $host . ':' . $port . + return 'HOST=' . $host . ':' . $port . $server . ';DBN=' . $dbname . ';UID=' . $username . ';PWD=' . $password . ';' . implode( ';', - array_map(function ($key, $value) { + array_map(static function ($key, $value) { return $key . '=' . $value; }, array_keys($driverOptions), $driverOptions) ); diff --git a/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereConnection.php b/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereConnection.php index be60b2f3f26..d47782003e6 100644 --- a/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereConnection.php +++ b/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereConnection.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\SQLAnywhere; @@ -42,21 +25,13 @@ /** * SAP Sybase SQL Anywhere implementation of the Connection interface. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class SQLAnywhereConnection implements Connection, ServerInfoAwareConnection { - /** - * @var resource The SQL Anywhere connection resource. - */ + /** @var resource The SQL Anywhere connection resource. */ private $connection; /** - * Constructor. - * * Connects to database with given connection string. * * @param string $dsn The connection string. @@ -68,22 +43,17 @@ public function __construct($dsn, $persistent = false) { $this->connection = $persistent ? @sasql_pconnect($dsn) : @sasql_connect($dsn); - if ( ! is_resource($this->connection)) { + if (! is_resource($this->connection)) { throw SQLAnywhereException::fromSQLAnywhereError(); } // Disable PHP warnings on error. - if ( ! sasql_set_option($this->connection, 'verbose_errors', false)) { + if (! sasql_set_option($this->connection, 'verbose_errors', false)) { throw SQLAnywhereException::fromSQLAnywhereError($this->connection); } // Enable auto committing by default. - if ( ! sasql_set_option($this->connection, 'auto_commit', 'on')) { - throw SQLAnywhereException::fromSQLAnywhereError($this->connection); - } - - // Enable exact, non-approximated row count retrieval. - if ( ! sasql_set_option($this->connection, 'row_counts', true)) { + if (! sasql_set_option($this->connection, 'auto_commit', 'on')) { throw SQLAnywhereException::fromSQLAnywhereError($this->connection); } } @@ -95,7 +65,7 @@ public function __construct($dsn, $persistent = false) */ public function beginTransaction() { - if ( ! sasql_set_option($this->connection, 'auto_commit', 'off')) { + if (! sasql_set_option($this->connection, 'auto_commit', 'off')) { throw SQLAnywhereException::fromSQLAnywhereError($this->connection); } @@ -109,7 +79,7 @@ public function beginTransaction() */ public function commit() { - if ( ! sasql_commit($this->connection)) { + if (! sasql_commit($this->connection)) { throw SQLAnywhereException::fromSQLAnywhereError($this->connection); } @@ -139,7 +109,7 @@ public function errorInfo() */ public function exec($statement) { - if (false === sasql_real_query($this->connection, $statement)) { + if (sasql_real_query($this->connection, $statement) === false) { throw SQLAnywhereException::fromSQLAnywhereError($this->connection); } @@ -163,7 +133,7 @@ public function getServerVersion() */ public function lastInsertId($name = null) { - if (null === $name) { + if ($name === null) { return sasql_insert_id($this->connection); } @@ -218,7 +188,7 @@ public function requiresQueryForServerVersion() */ public function rollBack() { - if ( ! sasql_rollback($this->connection)) { + if (! sasql_rollback($this->connection)) { throw SQLAnywhereException::fromSQLAnywhereError($this->connection); } @@ -230,13 +200,13 @@ public function rollBack() /** * Ends transactional mode and enables auto commit again. * - * @throws SQLAnywhereException - * * @return bool Whether or not ending transactional mode succeeded. + * + * @throws SQLAnywhereException */ private function endTransaction() { - if ( ! sasql_set_option($this->connection, 'auto_commit', 'on')) { + if (! sasql_set_option($this->connection, 'auto_commit', 'on')) { throw SQLAnywhereException::fromSQLAnywhereError($this->connection); } diff --git a/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereException.php b/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereException.php index 2a89206d782..9f8aac0608d 100644 --- a/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereException.php +++ b/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereException.php @@ -1,25 +1,9 @@ . - */ namespace Doctrine\DBAL\Driver\SQLAnywhere; use Doctrine\DBAL\Driver\AbstractDriverException; +use InvalidArgumentException; use function is_resource; use function sasql_error; use function sasql_errorcode; @@ -29,10 +13,6 @@ /** * SAP Sybase SQL Anywhere driver exception. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class SQLAnywhereException extends AbstractDriverException { @@ -44,16 +24,16 @@ class SQLAnywhereException extends AbstractDriverException * * @return SQLAnywhereException * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public static function fromSQLAnywhereError($conn = null, $stmt = null) { - if (null !== $conn && ! (is_resource($conn))) { - throw new \InvalidArgumentException('Invalid SQL Anywhere connection resource given: ' . $conn); + if ($conn !== null && ! is_resource($conn)) { + throw new InvalidArgumentException('Invalid SQL Anywhere connection resource given: ' . $conn); } - if (null !== $stmt && ! (is_resource($stmt))) { - throw new \InvalidArgumentException('Invalid SQL Anywhere statement resource given: ' . $stmt); + if ($stmt !== null && ! is_resource($stmt)) { + throw new InvalidArgumentException('Invalid SQL Anywhere statement resource given: ' . $stmt); } $state = $conn ? sasql_sqlstate($conn) : sasql_sqlstate(); @@ -86,7 +66,7 @@ public static function fromSQLAnywhereError($conn = null, $stmt = null) * or the last error could not be retrieved from the given * connection / statement resource. */ - if ( ! $conn || ! $code) { + if (! $conn || ! $code) { $code = sasql_errorcode(); $message = sasql_error(); } diff --git a/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereStatement.php b/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereStatement.php index 1584dadb115..0ed2d454624 100644 --- a/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereStatement.php +++ b/lib/Doctrine/DBAL/Driver/SQLAnywhere/SQLAnywhereStatement.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\SQLAnywhere; @@ -24,9 +7,12 @@ use Doctrine\DBAL\FetchMode; use Doctrine\DBAL\ParameterType; use IteratorAggregate; +use PDO; +use ReflectionClass; +use ReflectionObject; +use stdClass; use const SASQL_BOTH; use function array_key_exists; -use function call_user_func_array; use function func_get_args; use function func_num_args; use function gettype; @@ -52,46 +38,28 @@ /** * SAP SQL Anywhere implementation of the Statement interface. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class SQLAnywhereStatement implements IteratorAggregate, Statement { - /** - * @var resource The connection resource. - */ + /** @var resource The connection resource. */ private $conn; - /** - * @var string Name of the default class to instantiate when fetching class instances. - */ + /** @var string Name of the default class to instantiate when fetching class instances. */ private $defaultFetchClass = '\stdClass'; - /** - * @var mixed[] Constructor arguments for the default class to instantiate when fetching class instances. - */ + /** @var mixed[] Constructor arguments for the default class to instantiate when fetching class instances. */ private $defaultFetchClassCtorArgs = []; - /** - * @var int Default fetch mode to use. - */ + /** @var int Default fetch mode to use. */ private $defaultFetchMode = FetchMode::MIXED; - /** - * @var resource The result set resource to fetch. - */ + /** @var resource The result set resource to fetch. */ private $result; - /** - * @var resource The prepared SQL statement to execute. - */ + /** @var resource The prepared SQL statement to execute. */ private $stmt; /** - * Constructor. - * * Prepares given statement for given connection. * * @param resource $conn The connection resource to use. @@ -101,14 +69,14 @@ class SQLAnywhereStatement implements IteratorAggregate, Statement */ public function __construct($conn, $sql) { - if ( ! is_resource($conn)) { + if (! is_resource($conn)) { throw new SQLAnywhereException('Invalid SQL Anywhere connection resource: ' . $conn); } $this->conn = $conn; $this->stmt = sasql_prepare($conn, $sql); - if ( ! is_resource($this->stmt)) { + if (! is_resource($this->stmt)) { throw SQLAnywhereException::fromSQLAnywhereError($conn); } } @@ -140,7 +108,7 @@ public function bindParam($column, &$variable, $type = ParameterType::STRING, $l throw new SQLAnywhereException('Unknown type: ' . $type); } - if ( ! sasql_stmt_bind_param_ex($this->stmt, $column - 1, $variable, $type, $variable === null)) { + if (! sasql_stmt_bind_param_ex($this->stmt, $column - 1, $variable, $type, $variable === null)) { throw SQLAnywhereException::fromSQLAnywhereError($this->conn, $this->stmt); } @@ -162,7 +130,7 @@ public function bindValue($param, $value, $type = ParameterType::STRING) */ public function closeCursor() { - if (!sasql_stmt_reset($this->stmt)) { + if (! sasql_stmt_reset($this->stmt)) { throw SQLAnywhereException::fromSQLAnywhereError($this->conn, $this->stmt); } @@ -204,13 +172,13 @@ public function execute($params = null) $hasZeroIndex = array_key_exists(0, $params); foreach ($params as $key => $val) { - $key = ($hasZeroIndex && is_numeric($key)) ? $key + 1 : $key; + $key = $hasZeroIndex && is_numeric($key) ? $key + 1 : $key; $this->bindValue($key, $val); } } - if ( ! sasql_stmt_execute($this->stmt)) { + if (! sasql_stmt_execute($this->stmt)) { throw SQLAnywhereException::fromSQLAnywhereError($this->conn, $this->stmt); } @@ -224,9 +192,9 @@ public function execute($params = null) * * @throws SQLAnywhereException */ - public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) + public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { - if ( ! is_resource($this->result)) { + if (! is_resource($this->result)) { return false; } @@ -254,7 +222,7 @@ public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NE $result = sasql_fetch_object($this->result); - if ($result instanceof \stdClass) { + if ($result instanceof stdClass) { $result = $this->castObject($result, $className, $ctorArgs); } @@ -280,7 +248,7 @@ public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = n switch ($fetchMode) { case FetchMode::CUSTOM_OBJECT: - while ($row = call_user_func_array([$this, 'fetch'], func_get_args())) { + while ($row = $this->fetch(...func_get_args())) { $rows[] = $row; } break; @@ -307,7 +275,7 @@ public function fetchColumn($columnIndex = 0) { $row = $this->fetch(FetchMode::NUMERIC); - if (false === $row) { + if ($row === false) { return false; } @@ -343,29 +311,30 @@ public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null) /** * Casts a stdClass object to the given class name mapping its' properties. * - * @param \stdClass $sourceObject Object to cast from. + * @param stdClass $sourceObject Object to cast from. * @param string|object $destinationClass Name of the class or class instance to cast to. - * @param array $ctorArgs Arguments to use for constructing the destination class instance. + * @param mixed[] $ctorArgs Arguments to use for constructing the destination class instance. * * @return object * * @throws SQLAnywhereException */ - private function castObject(\stdClass $sourceObject, $destinationClass, array $ctorArgs = []) + private function castObject(stdClass $sourceObject, $destinationClass, array $ctorArgs = []) { - if ( ! is_string($destinationClass)) { - if ( ! is_object($destinationClass)) { + if (! is_string($destinationClass)) { + if (! is_object($destinationClass)) { throw new SQLAnywhereException(sprintf( - 'Destination class has to be of type string or object, %s given.', gettype($destinationClass) + 'Destination class has to be of type string or object, %s given.', + gettype($destinationClass) )); } } else { - $destinationClass = new \ReflectionClass($destinationClass); + $destinationClass = new ReflectionClass($destinationClass); $destinationClass = $destinationClass->newInstanceArgs($ctorArgs); } - $sourceReflection = new \ReflectionObject($sourceObject); - $destinationClassReflection = new \ReflectionObject($destinationClass); + $sourceReflection = new ReflectionObject($sourceObject); + $destinationClassReflection = new ReflectionObject($destinationClass); foreach ($sourceReflection->getProperties() as $sourceProperty) { $sourceProperty->setAccessible(true); diff --git a/lib/Doctrine/DBAL/Driver/SQLSrv/Driver.php b/lib/Doctrine/DBAL/Driver/SQLSrv/Driver.php index da0409f24c5..a9be26e9dea 100644 --- a/lib/Doctrine/DBAL/Driver/SQLSrv/Driver.php +++ b/lib/Doctrine/DBAL/Driver/SQLSrv/Driver.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\SQLSrv; @@ -31,7 +14,7 @@ class Driver extends AbstractSQLServerDriver */ public function connect(array $params, $username = null, $password = null, array $driverOptions = []) { - if (!isset($params['host'])) { + if (! isset($params['host'])) { throw new SQLSrvException("Missing 'host' in configuration for sqlsrv driver."); } @@ -43,15 +26,20 @@ public function connect(array $params, $username = null, $password = null, array if (isset($params['dbname'])) { $driverOptions['Database'] = $params['dbname']; } - + if (isset($params['charset'])) { $driverOptions['CharacterSet'] = $params['charset']; } - $driverOptions['UID'] = $username; - $driverOptions['PWD'] = $password; + if ($username !== null) { + $driverOptions['UID'] = $username; + } + + if ($password !== null) { + $driverOptions['PWD'] = $password; + } - if (!isset($driverOptions['ReturnDatesAsStrings'])) { + if (! isset($driverOptions['ReturnDatesAsStrings'])) { $driverOptions['ReturnDatesAsStrings'] = 1; } diff --git a/lib/Doctrine/DBAL/Driver/SQLSrv/LastInsertId.php b/lib/Doctrine/DBAL/Driver/SQLSrv/LastInsertId.php index 909f1e444be..363b260950e 100644 --- a/lib/Doctrine/DBAL/Driver/SQLSrv/LastInsertId.php +++ b/lib/Doctrine/DBAL/Driver/SQLSrv/LastInsertId.php @@ -1,35 +1,13 @@ . - */ namespace Doctrine\DBAL\Driver\SQLSrv; /** * Last Id Data Container. - * - * @since 2.3 - * @author Benjamin Eberlei */ class LastInsertId { - /** - * @var int - */ + /** @var int */ private $id; /** diff --git a/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvConnection.php b/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvConnection.php index 6cdd4bca97f..f1f9ddd1d79 100644 --- a/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvConnection.php +++ b/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvConnection.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver\SQLSrv; @@ -40,36 +23,29 @@ /** * SQL Server implementation for the Connection interface. - * - * @since 2.3 - * @author Benjamin Eberlei */ class SQLSrvConnection implements Connection, ServerInfoAwareConnection { - /** - * @var resource - */ + /** @var resource */ protected $conn; - /** - * @var \Doctrine\DBAL\Driver\SQLSrv\LastInsertId - */ + /** @var LastInsertId */ protected $lastInsertId; /** - * @param string $serverName - * @param array $connectionOptions + * @param string $serverName + * @param mixed[] $connectionOptions * - * @throws \Doctrine\DBAL\Driver\SQLSrv\SQLSrvException + * @throws SQLSrvException */ public function __construct($serverName, $connectionOptions) { - if ( ! sqlsrv_configure('WarningsReturnAsErrors', 0)) { + if (! sqlsrv_configure('WarningsReturnAsErrors', 0)) { throw SQLSrvException::fromSqlSrvErrors(); } $this->conn = sqlsrv_connect($serverName, $connectionOptions); - if ( ! $this->conn) { + if (! $this->conn) { throw SQLSrvException::fromSqlSrvErrors(); } $this->lastInsertId = new LastInsertId(); @@ -107,7 +83,7 @@ public function prepare($sql) public function query() { $args = func_get_args(); - $sql = $args[0]; + $sql = $args[0]; $stmt = $this->prepare($sql); $stmt->execute(); @@ -116,7 +92,6 @@ public function query() /** * {@inheritDoc} - * @license New BSD, code from Zend Framework */ public function quote($value, $type = ParameterType::STRING) { @@ -136,7 +111,7 @@ public function exec($statement) { $stmt = sqlsrv_query($this->conn, $statement); - if (false === $stmt) { + if ($stmt === false) { throw SQLSrvException::fromSqlSrvErrors(); } @@ -163,7 +138,7 @@ public function lastInsertId($name = null) */ public function beginTransaction() { - if ( ! sqlsrv_begin_transaction($this->conn)) { + if (! sqlsrv_begin_transaction($this->conn)) { throw SQLSrvException::fromSqlSrvErrors(); } } @@ -173,7 +148,7 @@ public function beginTransaction() */ public function commit() { - if ( ! sqlsrv_commit($this->conn)) { + if (! sqlsrv_commit($this->conn)) { throw SQLSrvException::fromSqlSrvErrors(); } } @@ -183,7 +158,7 @@ public function commit() */ public function rollBack() { - if ( ! sqlsrv_rollback($this->conn)) { + if (! sqlsrv_rollback($this->conn)) { throw SQLSrvException::fromSqlSrvErrors(); } } diff --git a/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvException.php b/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvException.php index 3223c113608..796f5d129d4 100644 --- a/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvException.php +++ b/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvException.php @@ -1,25 +1,7 @@ . - */ namespace Doctrine\DBAL\Driver\SQLSrv; - use Doctrine\DBAL\Driver\AbstractDriverException; use const SQLSRV_ERR_ERRORS; use function rtrim; @@ -34,24 +16,26 @@ class SQLSrvException extends AbstractDriverException */ public static function fromSqlSrvErrors() { - $errors = sqlsrv_errors(SQLSRV_ERR_ERRORS); - $message = ""; - $sqlState = null; + $errors = sqlsrv_errors(SQLSRV_ERR_ERRORS); + $message = ''; + $sqlState = null; $errorCode = null; foreach ($errors as $error) { - $message .= "SQLSTATE [".$error['SQLSTATE'].", ".$error['code']."]: ". $error['message']."\n"; + $message .= 'SQLSTATE [' . $error['SQLSTATE'] . ', ' . $error['code'] . ']: ' . $error['message'] . "\n"; - if (null === $sqlState) { + if ($sqlState === null) { $sqlState = $error['SQLSTATE']; } - if (null === $errorCode) { - $errorCode = $error['code']; + if ($errorCode !== null) { + continue; } + + $errorCode = $error['code']; } - if ( ! $message) { - $message = "SQL Server error occurred but no error message was retrieved from driver."; + if (! $message) { + $message = 'SQL Server error occurred but no error message was retrieved from driver.'; } return new self(rtrim($message), $sqlState, $errorCode); diff --git a/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvStatement.php b/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvStatement.php index e9d35fdb72e..147ef76e1a0 100644 --- a/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvStatement.php +++ b/lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvStatement.php @@ -1,29 +1,13 @@ . - */ namespace Doctrine\DBAL\Driver\SQLSrv; +use Doctrine\DBAL\Driver\Statement; use Doctrine\DBAL\Driver\StatementIterator; use Doctrine\DBAL\FetchMode; use Doctrine\DBAL\ParameterType; use IteratorAggregate; -use Doctrine\DBAL\Driver\Statement; +use PDO; use const SQLSRV_ENC_BINARY; use const SQLSRV_ERR_ERRORS; use const SQLSRV_FETCH_ASSOC; @@ -52,9 +36,6 @@ /** * SQL Server Statement. - * - * @since 2.3 - * @author Benjamin Eberlei */ class SQLSrvStatement implements IteratorAggregate, Statement { @@ -82,21 +63,21 @@ class SQLSrvStatement implements IteratorAggregate, Statement /** * References to the variables bound as statement parameters. * - * @var array + * @var mixed */ private $variables = []; /** * Bound parameter types. * - * @var array + * @var int[] */ private $types = []; /** * Translations. * - * @var array + * @var int[] */ private static $fetchMap = [ FetchMode::MIXED => SQLSRV_FETCH_BOTH, @@ -128,7 +109,7 @@ class SQLSrvStatement implements IteratorAggregate, Statement /** * The last insert ID. * - * @var \Doctrine\DBAL\Driver\SQLSrv\LastInsertId|null + * @var LastInsertId|null */ private $lastInsertId; @@ -141,25 +122,24 @@ class SQLSrvStatement implements IteratorAggregate, Statement /** * Append to any INSERT query to retrieve the last insert id. - * - * @var string */ - const LAST_INSERT_ID_SQL = ';SELECT SCOPE_IDENTITY() AS LastInsertId;'; + public const LAST_INSERT_ID_SQL = ';SELECT SCOPE_IDENTITY() AS LastInsertId;'; /** - * @param resource $conn - * @param string $sql - * @param \Doctrine\DBAL\Driver\SQLSrv\LastInsertId|null $lastInsertId + * @param resource $conn + * @param string $sql */ - public function __construct($conn, $sql, LastInsertId $lastInsertId = null) + public function __construct($conn, $sql, ?LastInsertId $lastInsertId = null) { $this->conn = $conn; - $this->sql = $sql; + $this->sql = $sql; - if (stripos($sql, 'INSERT INTO ') === 0) { - $this->sql .= self::LAST_INSERT_ID_SQL; - $this->lastInsertId = $lastInsertId; + if (stripos($sql, 'INSERT INTO ') !== 0) { + return; } + + $this->sql .= self::LAST_INSERT_ID_SQL; + $this->lastInsertId = $lastInsertId; } /** @@ -167,14 +147,14 @@ public function __construct($conn, $sql, LastInsertId $lastInsertId = null) */ public function bindValue($param, $value, $type = ParameterType::STRING) { - if (!is_numeric($param)) { + if (! is_numeric($param)) { throw new SQLSrvException( 'sqlsrv does not support named parameters to queries, use question mark (?) placeholders instead.' ); } $this->variables[$param] = $value; - $this->types[$param] = $type; + $this->types[$param] = $type; } /** @@ -182,12 +162,12 @@ public function bindValue($param, $value, $type = ParameterType::STRING) */ public function bindParam($column, &$variable, $type = ParameterType::STRING, $length = null) { - if (!is_numeric($column)) { - throw new SQLSrvException("sqlsrv does not support named parameters to queries, use question mark (?) placeholders instead."); + if (! is_numeric($column)) { + throw new SQLSrvException('sqlsrv does not support named parameters to queries, use question mark (?) placeholders instead.'); } $this->variables[$column] =& $variable; - $this->types[$column] = $type; + $this->types[$column] = $type; // unset the statement resource if it exists as the new one will need to be bound to the new variable $this->stmt = null; @@ -199,7 +179,7 @@ public function bindParam($column, &$variable, $type = ParameterType::STRING, $l public function closeCursor() { // not having the result means there's nothing to close - if (!$this->result) { + if (! $this->result) { return true; } @@ -207,7 +187,8 @@ public function closeCursor() // @link http://php.net/manual/en/pdostatement.closecursor.php // @link https://github.com/php/php-src/blob/php-7.0.11/ext/pdo/pdo_stmt.c#L2075 // deliberately do not consider multiple result sets, since doctrine/dbal doesn't support them - while (sqlsrv_fetch($this->stmt)); + while (sqlsrv_fetch($this->stmt)) { + } $this->result = false; @@ -251,16 +232,16 @@ public function execute($params = null) if ($params) { $hasZeroIndex = array_key_exists(0, $params); foreach ($params as $key => $val) { - $key = ($hasZeroIndex && is_numeric($key)) ? $key + 1 : $key; + $key = $hasZeroIndex && is_numeric($key) ? $key + 1 : $key; $this->bindValue($key, $val); } } - if ( ! $this->stmt) { + if (! $this->stmt) { $this->stmt = $this->prepare(); } - if (!sqlsrv_execute($this->stmt)) { + if (! sqlsrv_execute($this->stmt)) { throw SQLSrvException::fromSqlSrvErrors(); } @@ -277,6 +258,7 @@ public function execute($params = null) * Prepares SQL Server statement resource * * @return resource + * * @throws SQLSrvException */ private function prepare() @@ -310,7 +292,7 @@ private function prepare() $stmt = sqlsrv_prepare($this->conn, $this->sql, $params); - if (!$stmt) { + if (! $stmt) { throw SQLSrvException::fromSqlSrvErrors(); } @@ -342,11 +324,11 @@ public function getIterator() * * @throws SQLSrvException */ - public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) + public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { // do not try fetching from the statement if it's not expected to contain result // in order to prevent exceptional situation - if (!$this->result) { + if (! $this->result) { return false; } @@ -412,7 +394,7 @@ public function fetchColumn($columnIndex = 0) { $row = $this->fetch(FetchMode::NUMERIC); - if (false === $row) { + if ($row === false) { return false; } diff --git a/lib/Doctrine/DBAL/Driver/ServerInfoAwareConnection.php b/lib/Doctrine/DBAL/Driver/ServerInfoAwareConnection.php index f47ad0b2701..c97a60fa356 100644 --- a/lib/Doctrine/DBAL/Driver/ServerInfoAwareConnection.php +++ b/lib/Doctrine/DBAL/Driver/ServerInfoAwareConnection.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Driver; /** * Contract for a connection that is able to provide information about the server it is connected to. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ interface ServerInfoAwareConnection { diff --git a/lib/Doctrine/DBAL/Driver/Statement.php b/lib/Doctrine/DBAL/Driver/Statement.php index 95a73442d7d..a3ea74a4df5 100644 --- a/lib/Doctrine/DBAL/Driver/Statement.php +++ b/lib/Doctrine/DBAL/Driver/Statement.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Driver; @@ -26,11 +9,6 @@ * Drivers must implement this interface. * * This resembles (a subset of) the PDOStatement interface. - * - * @author Konsta Vesterinen - * @author Roman Borschel - * @link www.doctrine-project.org - * @since 2.0 */ interface Statement extends ResultStatement { @@ -92,9 +70,7 @@ public function errorCode(); /** * Fetches extended error information associated with the last operation on the statement handle. * - * @see Doctrine_Adapter_Interface::errorInfo() - * - * @return array The error info array. + * @return mixed[] The error info array. */ public function errorInfo(); @@ -107,9 +83,8 @@ public function errorInfo(); * if any, of their associated parameter markers or pass an array of input-only * parameter values. * - * - * @param array|null $params An array of values with as many elements as there are - * bound parameters in the SQL statement being executed. + * @param mixed[]|null $params An array of values with as many elements as there are + * bound parameters in the SQL statement being executed. * * @return bool TRUE on success or FALSE on failure. */ diff --git a/lib/Doctrine/DBAL/Driver/StatementIterator.php b/lib/Doctrine/DBAL/Driver/StatementIterator.php index 2dc3f2b3d13..5246b38a448 100644 --- a/lib/Doctrine/DBAL/Driver/StatementIterator.php +++ b/lib/Doctrine/DBAL/Driver/StatementIterator.php @@ -2,16 +2,13 @@ namespace Doctrine\DBAL\Driver; -class StatementIterator implements \IteratorAggregate +use IteratorAggregate; + +class StatementIterator implements IteratorAggregate { - /** - * @var Statement - */ + /** @var Statement */ private $statement; - /** - * @param Statement $statement - */ public function __construct(Statement $statement) { $this->statement = $statement; @@ -22,7 +19,7 @@ public function __construct(Statement $statement) */ public function getIterator() { - while (false !== ($result = $this->statement->fetch())) { + while (($result = $this->statement->fetch()) !== false) { yield $result; } } diff --git a/lib/Doctrine/DBAL/DriverManager.php b/lib/Doctrine/DBAL/DriverManager.php index 22ae8ac3264..658123199c0 100644 --- a/lib/Doctrine/DBAL/DriverManager.php +++ b/lib/Doctrine/DBAL/DriverManager.php @@ -1,25 +1,20 @@ . - */ namespace Doctrine\DBAL; use Doctrine\Common\EventManager; +use Doctrine\DBAL\Driver\DrizzlePDOMySql\Driver as DrizzlePDOMySQLDriver; +use Doctrine\DBAL\Driver\IBMDB2\DB2Driver; +use Doctrine\DBAL\Driver\Mysqli\Driver as MySQLiDriver; +use Doctrine\DBAL\Driver\OCI8\Driver as OCI8Driver; +use Doctrine\DBAL\Driver\PDOMySql\Driver as PDOMySQLDriver; +use Doctrine\DBAL\Driver\PDOOracle\Driver as PDOOCIDriver; +use Doctrine\DBAL\Driver\PDOPgSql\Driver as PDOPgSQLDriver; +use Doctrine\DBAL\Driver\PDOSqlite\Driver as PDOSQLiteDriver; +use Doctrine\DBAL\Driver\PDOSqlsrv\Driver as PDOSQLSrvDriver; +use Doctrine\DBAL\Driver\SQLAnywhere\Driver as SQLAnywhereDriver; +use Doctrine\DBAL\Driver\SQLSrv\Driver as SQLSrvDriver; +use PDO; use function array_keys; use function array_map; use function array_merge; @@ -35,9 +30,6 @@ /** * Factory for creating Doctrine\DBAL\Connection instances. - * - * @author Roman Borschel - * @since 2.0 */ final class DriverManager { @@ -47,24 +39,26 @@ final class DriverManager * To add your own driver use the 'driverClass' parameter to * {@link DriverManager::getConnection()}. * - * @var array + * @var string[] */ - private static $_driverMap = [ - 'pdo_mysql' => 'Doctrine\DBAL\Driver\PDOMySql\Driver', - 'pdo_sqlite' => 'Doctrine\DBAL\Driver\PDOSqlite\Driver', - 'pdo_pgsql' => 'Doctrine\DBAL\Driver\PDOPgSql\Driver', - 'pdo_oci' => 'Doctrine\DBAL\Driver\PDOOracle\Driver', - 'oci8' => 'Doctrine\DBAL\Driver\OCI8\Driver', - 'ibm_db2' => 'Doctrine\DBAL\Driver\IBMDB2\DB2Driver', - 'pdo_sqlsrv' => 'Doctrine\DBAL\Driver\PDOSqlsrv\Driver', - 'mysqli' => 'Doctrine\DBAL\Driver\Mysqli\Driver', - 'drizzle_pdo_mysql' => 'Doctrine\DBAL\Driver\DrizzlePDOMySql\Driver', - 'sqlanywhere' => 'Doctrine\DBAL\Driver\SQLAnywhere\Driver', - 'sqlsrv' => 'Doctrine\DBAL\Driver\SQLSrv\Driver', + private static $_driverMap = [ + 'pdo_mysql' => PDOMySQLDriver::class, + 'pdo_sqlite' => PDOSQLiteDriver::class, + 'pdo_pgsql' => PDOPgSQLDriver::class, + 'pdo_oci' => PDOOCIDriver::class, + 'oci8' => OCI8Driver::class, + 'ibm_db2' => DB2Driver::class, + 'pdo_sqlsrv' => PDOSQLSrvDriver::class, + 'mysqli' => MySQLiDriver::class, + 'drizzle_pdo_mysql' => DrizzlePDOMySQLDriver::class, + 'sqlanywhere' => SQLAnywhereDriver::class, + 'sqlsrv' => SQLSrvDriver::class, ]; /** * List of URL schemes from a database URL and their mappings to driver. + * + * @var string[] */ private static $driverSchemeAliases = [ 'db2' => 'ibm_db2', @@ -132,35 +126,55 @@ private function __construct() * driverClass: * The driver class to use. * - * @param array $params The parameters. - * @param \Doctrine\DBAL\Configuration|null $config The configuration to use. - * @param \Doctrine\Common\EventManager|null $eventManager The event manager to use. + * @param mixed[] $params The parameters. + * @param Configuration|null $config The configuration to use. + * @param EventManager|null $eventManager The event manager to use. * - * @return \Doctrine\DBAL\Connection - * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ public static function getConnection( - array $params, - Configuration $config = null, - EventManager $eventManager = null): Connection - { + array $params, + ?Configuration $config = null, + ?EventManager $eventManager = null + ) : Connection { // create default config and event manager, if not set - if ( ! $config) { + if (! $config) { $config = new Configuration(); } - if ( ! $eventManager) { + if (! $eventManager) { $eventManager = new EventManager(); } $params = self::parseDatabaseUrl($params); + // URL support for MasterSlaveConnection + if (isset($params['master'])) { + $params['master'] = self::parseDatabaseUrl($params['master']); + } + + if (isset($params['slaves'])) { + foreach ($params['slaves'] as $key => $slaveParams) { + $params['slaves'][$key] = self::parseDatabaseUrl($slaveParams); + } + } + + // URL support for PoolingShardConnection + if (isset($params['global'])) { + $params['global'] = self::parseDatabaseUrl($params['global']); + } + + if (isset($params['shards'])) { + foreach ($params['shards'] as $key => $shardParams) { + $params['shards'][$key] = self::parseDatabaseUrl($shardParams); + } + } + // check for existing pdo object - if (isset($params['pdo']) && ! $params['pdo'] instanceof \PDO) { + if (isset($params['pdo']) && ! $params['pdo'] instanceof PDO) { throw DBALException::invalidPdoInstance(); } elseif (isset($params['pdo'])) { - $params['pdo']->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); - $params['driver'] = 'pdo_' . $params['pdo']->getAttribute(\PDO::ATTR_DRIVER_NAME); + $params['pdo']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $params['driver'] = 'pdo_' . $params['pdo']->getAttribute(PDO::ATTR_DRIVER_NAME); } else { self::_checkParams($params); } @@ -169,13 +183,13 @@ public static function getConnection( $driver = new $className(); - $wrapperClass = 'Doctrine\DBAL\Connection'; + $wrapperClass = Connection::class; if (isset($params['wrapperClass'])) { - if (is_subclass_of($params['wrapperClass'], $wrapperClass)) { - $wrapperClass = $params['wrapperClass']; - } else { + if (! is_subclass_of($params['wrapperClass'], $wrapperClass)) { throw DBALException::invalidWrapperClass($params['wrapperClass']); } + + $wrapperClass = $params['wrapperClass']; } return new $wrapperClass($params, $driver, $config, $eventManager); @@ -184,9 +198,9 @@ public static function getConnection( /** * Returns the list of supported drivers. * - * @return array + * @return string[] */ - public static function getAvailableDrivers(): array + public static function getAvailableDrivers() : array { return array_keys(self::$_driverMap); } @@ -194,18 +208,16 @@ public static function getAvailableDrivers(): array /** * Checks the list of parameters. * - * @param array $params The list of parameters. + * @param mixed[] $params The list of parameters. * - * @return void - * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ - private static function _checkParams(array $params): void + private static function _checkParams(array $params) : void { // check existence of mandatory parameters // driver - if ( ! isset($params['driver']) && ! isset($params['driverClass'])) { + if (! isset($params['driver']) && ! isset($params['driverClass'])) { throw DBALException::driverRequired(); } @@ -216,7 +228,7 @@ private static function _checkParams(array $params): void throw DBALException::unknownDriver($params['driver'], array_keys(self::$_driverMap)); } - if (isset($params['driverClass']) && ! in_array('Doctrine\DBAL\Driver', class_implements($params['driverClass'], true))) { + if (isset($params['driverClass']) && ! in_array(Driver::class, class_implements($params['driverClass'], true))) { throw DBALException::invalidDriverClass($params['driverClass']); } } @@ -224,11 +236,9 @@ private static function _checkParams(array $params): void /** * Normalizes the given connection URL path. * - * @param string $urlPath - * * @return string The normalized connection URL path */ - private static function normalizeDatabaseUrlPath(string $urlPath): string + private static function normalizeDatabaseUrlPath(string $urlPath) : string { // Trim leading slash from URL path. return substr($urlPath, 1); @@ -238,16 +248,16 @@ private static function normalizeDatabaseUrlPath(string $urlPath): string * Extracts parts from a database URL, if present, and returns an * updated list of parameters. * - * @param array $params The list of parameters. + * @param mixed[] $params The list of parameters. * - * @return array A modified list of parameters with info from a database - * URL extracted into indidivual parameter parts. + * @return mixed[] A modified list of parameters with info from a database + * URL extracted into indidivual parameter parts. * * @throws DBALException */ - private static function parseDatabaseUrl(array $params): array + private static function parseDatabaseUrl(array $params) : array { - if (!isset($params['url'])) { + if (! isset($params['url'])) { return $params; } @@ -292,14 +302,14 @@ private static function parseDatabaseUrl(array $params): array * Assumes that the connection URL scheme is already parsed and resolved into the given connection parameters * via {@link parseDatabaseUrlScheme}. * - * @param array $url The URL parts to evaluate. - * @param array $params The connection parameters to resolve. + * @see parseDatabaseUrlScheme * - * @return array The resolved connection parameters. + * @param mixed[] $url The URL parts to evaluate. + * @param mixed[] $params The connection parameters to resolve. * - * @see parseDatabaseUrlScheme + * @return mixed[] The resolved connection parameters. */ - private static function parseDatabaseUrlPath(array $url, array $params): array + private static function parseDatabaseUrlPath(array $url, array $params) : array { if (! isset($url['path'])) { return $params; @@ -323,12 +333,12 @@ private static function parseDatabaseUrlPath(array $url, array $params): array /** * Parses the query part of the given connection URL and resolves the given connection parameters. * - * @param array $url The connection URL parts to evaluate. - * @param array $params The connection parameters to resolve. + * @param mixed[] $url The connection URL parts to evaluate. + * @param mixed[] $params The connection parameters to resolve. * - * @return array The resolved connection parameters. + * @return mixed[] The resolved connection parameters. */ - private static function parseDatabaseUrlQuery(array $url, array $params): array + private static function parseDatabaseUrlQuery(array $url, array $params) : array { if (! isset($url['query'])) { return $params; @@ -346,14 +356,14 @@ private static function parseDatabaseUrlQuery(array $url, array $params): array * * Assumes that the "path" URL part is already normalized via {@link normalizeDatabaseUrlPath}. * - * @param array $url The regular connection URL parts to evaluate. - * @param array $params The connection parameters to resolve. + * @see normalizeDatabaseUrlPath * - * @return array The resolved connection parameters. + * @param mixed[] $url The regular connection URL parts to evaluate. + * @param mixed[] $params The connection parameters to resolve. * - * @see normalizeDatabaseUrlPath + * @return mixed[] The resolved connection parameters. */ - private static function parseRegularDatabaseUrlPath(array $url, array $params): array + private static function parseRegularDatabaseUrlPath(array $url, array $params) : array { $params['dbname'] = $url['path']; @@ -365,14 +375,14 @@ private static function parseRegularDatabaseUrlPath(array $url, array $params): * * Assumes that the "path" URL part is already normalized via {@link normalizeDatabaseUrlPath}. * - * @param array $url The SQLite connection URL parts to evaluate. - * @param array $params The connection parameters to resolve. + * @see normalizeDatabaseUrlPath * - * @return array The resolved connection parameters. + * @param mixed[] $url The SQLite connection URL parts to evaluate. + * @param mixed[] $params The connection parameters to resolve. * - * @see normalizeDatabaseUrlPath + * @return mixed[] The resolved connection parameters. */ - private static function parseSqliteDatabaseUrlPath(array $url, array $params): array + private static function parseSqliteDatabaseUrlPath(array $url, array $params) : array { if ($url['path'] === ':memory:') { $params['memory'] = true; @@ -388,14 +398,14 @@ private static function parseSqliteDatabaseUrlPath(array $url, array $params): a /** * Parses the scheme part from given connection URL and resolves the given connection parameters. * - * @param array $url The connection URL parts to evaluate. - * @param array $params The connection parameters to resolve. + * @param mixed[] $url The connection URL parts to evaluate. + * @param mixed[] $params The connection parameters to resolve. * - * @return array The resolved connection parameters. + * @return mixed[] The resolved connection parameters. * - * @throws DBALException if parsing failed or resolution is not possible. + * @throws DBALException If parsing failed or resolution is not possible. */ - private static function parseDatabaseUrlScheme(array $url, array $params): array + private static function parseDatabaseUrlScheme(array $url, array $params) : array { if (isset($url['scheme'])) { // The requested driver from the URL scheme takes precedence diff --git a/lib/Doctrine/DBAL/Event/ConnectionEventArgs.php b/lib/Doctrine/DBAL/Event/ConnectionEventArgs.php index fd82638e771..bb0ca886d99 100644 --- a/lib/Doctrine/DBAL/Event/ConnectionEventArgs.php +++ b/lib/Doctrine/DBAL/Event/ConnectionEventArgs.php @@ -1,78 +1,55 @@ . - */ namespace Doctrine\DBAL\Event; use Doctrine\Common\EventArgs; use Doctrine\DBAL\Connection; +use Doctrine\DBAL\Driver; +use Doctrine\DBAL\Platforms\AbstractPlatform; +use Doctrine\DBAL\Schema\AbstractSchemaManager; /** * Event Arguments used when a Driver connection is established inside Doctrine\DBAL\Connection. - * - * @link www.doctrine-project.org - * @since 1.0 - * @author Benjamin Eberlei */ class ConnectionEventArgs extends EventArgs { - /** - * @var \Doctrine\DBAL\Connection - */ - private $_connection; + /** @var Connection */ + private $connection; - /** - * @param \Doctrine\DBAL\Connection $connection - */ public function __construct(Connection $connection) { - $this->_connection = $connection; + $this->connection = $connection; } /** - * @return \Doctrine\DBAL\Connection + * @return Connection */ public function getConnection() { - return $this->_connection; + return $this->connection; } /** - * @return \Doctrine\DBAL\Driver + * @return Driver */ public function getDriver() { - return $this->_connection->getDriver(); + return $this->connection->getDriver(); } /** - * @return \Doctrine\DBAL\Platforms\AbstractPlatform + * @return AbstractPlatform */ public function getDatabasePlatform() { - return $this->_connection->getDatabasePlatform(); + return $this->connection->getDatabasePlatform(); } /** - * @return \Doctrine\DBAL\Schema\AbstractSchemaManager + * @return AbstractSchemaManager */ public function getSchemaManager() { - return $this->_connection->getSchemaManager(); + return $this->connection->getSchemaManager(); } } diff --git a/lib/Doctrine/DBAL/Event/Listeners/MysqlSessionInit.php b/lib/Doctrine/DBAL/Event/Listeners/MysqlSessionInit.php index 043f7b5ebc9..9e722904050 100644 --- a/lib/Doctrine/DBAL/Event/Listeners/MysqlSessionInit.php +++ b/lib/Doctrine/DBAL/Event/Listeners/MysqlSessionInit.php @@ -1,34 +1,14 @@ . - */ namespace Doctrine\DBAL\Event\Listeners; +use Doctrine\Common\EventSubscriber; use Doctrine\DBAL\Event\ConnectionEventArgs; use Doctrine\DBAL\Events; -use Doctrine\Common\EventSubscriber; /** * MySQL Session Init Event Subscriber which allows to set the Client Encoding of the Connection. * - * @link www.doctrine-project.org - * @since 1.0 - * @author Benjamin Eberlei * @deprecated Use "charset" option to PDO MySQL Connection instead. */ class MysqlSessionInit implements EventSubscriber @@ -38,36 +18,34 @@ class MysqlSessionInit implements EventSubscriber * * @var string */ - private $_charset; + private $charset; /** * The collation, or FALSE if no collation. * - * @var string|boolean + * @var string|bool */ - private $_collation; + private $collation; /** * Configure Charset and Collation options of MySQL Client for each Connection. * - * @param string $charset The charset. - * @param string|boolean $collation The collation, or FALSE if no collation. + * @param string $charset The charset. + * @param string|bool $collation The collation, or FALSE if no collation. */ public function __construct($charset = 'utf8', $collation = false) { - $this->_charset = $charset; - $this->_collation = $collation; + $this->charset = $charset; + $this->collation = $collation; } /** - * @param \Doctrine\DBAL\Event\ConnectionEventArgs $args - * * @return void */ public function postConnect(ConnectionEventArgs $args) { - $collation = ($this->_collation) ? " COLLATE ".$this->_collation : ""; - $args->getConnection()->executeUpdate("SET NAMES ".$this->_charset . $collation); + $collation = $this->collation ? ' COLLATE ' . $this->collation : ''; + $args->getConnection()->executeUpdate('SET NAMES ' . $this->charset . $collation); } /** diff --git a/lib/Doctrine/DBAL/Event/Listeners/OracleSessionInit.php b/lib/Doctrine/DBAL/Event/Listeners/OracleSessionInit.php index 851986cc1a4..19f2b3fd335 100644 --- a/lib/Doctrine/DBAL/Event/Listeners/OracleSessionInit.php +++ b/lib/Doctrine/DBAL/Event/Listeners/OracleSessionInit.php @@ -1,27 +1,11 @@ . - */ namespace Doctrine\DBAL\Event\Listeners; +use Doctrine\Common\EventSubscriber; use Doctrine\DBAL\Event\ConnectionEventArgs; use Doctrine\DBAL\Events; -use Doctrine\Common\EventSubscriber; +use const CASE_UPPER; use function array_change_key_case; use function array_merge; use function count; @@ -36,26 +20,20 @@ * NLS_DATE_FORMAT="YYYY-MM-DD HH24:MI:SS" * NLS_TIMESTAMP_FORMAT="YYYY-MM-DD HH24:MI:SS" * NLS_TIMESTAMP_TZ_FORMAT="YYYY-MM-DD HH24:MI:SS TZH:TZM" - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ class OracleSessionInit implements EventSubscriber { - /** - * @var array - */ + /** @var string[] */ protected $_defaultSessionVars = [ - 'NLS_TIME_FORMAT' => "HH24:MI:SS", - 'NLS_DATE_FORMAT' => "YYYY-MM-DD HH24:MI:SS", - 'NLS_TIMESTAMP_FORMAT' => "YYYY-MM-DD HH24:MI:SS", - 'NLS_TIMESTAMP_TZ_FORMAT' => "YYYY-MM-DD HH24:MI:SS TZH:TZM", - 'NLS_NUMERIC_CHARACTERS' => ".,", + 'NLS_TIME_FORMAT' => 'HH24:MI:SS', + 'NLS_DATE_FORMAT' => 'YYYY-MM-DD HH24:MI:SS', + 'NLS_TIMESTAMP_FORMAT' => 'YYYY-MM-DD HH24:MI:SS', + 'NLS_TIMESTAMP_TZ_FORMAT' => 'YYYY-MM-DD HH24:MI:SS TZH:TZM', + 'NLS_NUMERIC_CHARACTERS' => '.,', ]; /** - * @param array $oracleSessionVars + * @param string[] $oracleSessionVars */ public function __construct(array $oracleSessionVars = []) { @@ -63,25 +41,25 @@ public function __construct(array $oracleSessionVars = []) } /** - * @param \Doctrine\DBAL\Event\ConnectionEventArgs $args - * * @return void */ public function postConnect(ConnectionEventArgs $args) { - if (count($this->_defaultSessionVars)) { - array_change_key_case($this->_defaultSessionVars, \CASE_UPPER); - $vars = []; - foreach ($this->_defaultSessionVars as $option => $value) { - if ($option === 'CURRENT_SCHEMA') { - $vars[] = $option . " = " . $value; - } else { - $vars[] = $option . " = '" . $value . "'"; - } + if (! count($this->_defaultSessionVars)) { + return; + } + + array_change_key_case($this->_defaultSessionVars, CASE_UPPER); + $vars = []; + foreach ($this->_defaultSessionVars as $option => $value) { + if ($option === 'CURRENT_SCHEMA') { + $vars[] = $option . ' = ' . $value; + } else { + $vars[] = $option . " = '" . $value . "'"; } - $sql = "ALTER SESSION SET ".implode(" ", $vars); - $args->getConnection()->executeUpdate($sql); } + $sql = 'ALTER SESSION SET ' . implode(' ', $vars); + $args->getConnection()->executeUpdate($sql); } /** diff --git a/lib/Doctrine/DBAL/Event/Listeners/SQLSessionInit.php b/lib/Doctrine/DBAL/Event/Listeners/SQLSessionInit.php index 767c804821f..ea63cab43d7 100644 --- a/lib/Doctrine/DBAL/Event/Listeners/SQLSessionInit.php +++ b/lib/Doctrine/DBAL/Event/Listeners/SQLSessionInit.php @@ -1,40 +1,17 @@ . - */ namespace Doctrine\DBAL\Event\Listeners; +use Doctrine\Common\EventSubscriber; use Doctrine\DBAL\Event\ConnectionEventArgs; use Doctrine\DBAL\Events; -use Doctrine\Common\EventSubscriber; /** * Session init listener for executing a single SQL statement right after a connection is opened. - * - * @link www.doctrine-project.org - * @since 2.2 - * @author Benjamin Eberlei */ class SQLSessionInit implements EventSubscriber { - /** - * @var string - */ + /** @var string */ protected $sql; /** @@ -46,8 +23,6 @@ public function __construct($sql) } /** - * @param \Doctrine\DBAL\Event\ConnectionEventArgs $args - * * @return void */ public function postConnect(ConnectionEventArgs $args) diff --git a/lib/Doctrine/DBAL/Event/SchemaAlterTableAddColumnEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaAlterTableAddColumnEventArgs.php index 7cb235ea18b..2f9edfea688 100644 --- a/lib/Doctrine/DBAL/Event/SchemaAlterTableAddColumnEventArgs.php +++ b/lib/Doctrine/DBAL/Event/SchemaAlterTableAddColumnEventArgs.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Event; @@ -27,90 +10,73 @@ /** * Event Arguments used when SQL queries for adding table columns are generated inside Doctrine\DBAL\Platform\*Platform. - * - * @link www.doctrine-project.org - * @since 2.2 - * @author Jan Sorgalla */ class SchemaAlterTableAddColumnEventArgs extends SchemaEventArgs { - /** - * @var \Doctrine\DBAL\Schema\Column - */ - private $_column; + /** @var Column */ + private $column; - /** - * @var \Doctrine\DBAL\Schema\TableDiff - */ - private $_tableDiff; + /** @var TableDiff */ + private $tableDiff; - /** - * @var \Doctrine\DBAL\Platforms\AbstractPlatform - */ - private $_platform; + /** @var AbstractPlatform */ + private $platform; - /** - * @var array - */ - private $_sql = []; + /** @var string[] */ + private $sql = []; - /** - * @param \Doctrine\DBAL\Schema\Column $column - * @param \Doctrine\DBAL\Schema\TableDiff $tableDiff - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - */ public function __construct(Column $column, TableDiff $tableDiff, AbstractPlatform $platform) { - $this->_column = $column; - $this->_tableDiff = $tableDiff; - $this->_platform = $platform; + $this->column = $column; + $this->tableDiff = $tableDiff; + $this->platform = $platform; } /** - * @return \Doctrine\DBAL\Schema\Column + * @return Column */ public function getColumn() { - return $this->_column; + return $this->column; } /** - * @return \Doctrine\DBAL\Schema\TableDiff + * @return TableDiff */ public function getTableDiff() { - return $this->_tableDiff; + return $this->tableDiff; } /** - * @return \Doctrine\DBAL\Platforms\AbstractPlatform + * @return AbstractPlatform */ public function getPlatform() { - return $this->_platform; + return $this->platform; } /** - * @param string|array $sql + * @param string|string[] $sql * * @return \Doctrine\DBAL\Event\SchemaAlterTableAddColumnEventArgs */ public function addSql($sql) { if (is_array($sql)) { - $this->_sql = array_merge($this->_sql, $sql); + $this->sql = array_merge($this->sql, $sql); } else { - $this->_sql[] = $sql; + $this->sql[] = $sql; } return $this; } /** - * @return array + * @return string[] */ public function getSql() { - return $this->_sql; + return $this->sql; } } diff --git a/lib/Doctrine/DBAL/Event/SchemaAlterTableChangeColumnEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaAlterTableChangeColumnEventArgs.php index fdafb45a7a4..55661d5d307 100644 --- a/lib/Doctrine/DBAL/Event/SchemaAlterTableChangeColumnEventArgs.php +++ b/lib/Doctrine/DBAL/Event/SchemaAlterTableChangeColumnEventArgs.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Event; @@ -27,90 +10,73 @@ /** * Event Arguments used when SQL queries for changing table columns are generated inside Doctrine\DBAL\Platform\*Platform. - * - * @link www.doctrine-project.org - * @since 2.2 - * @author Jan Sorgalla */ class SchemaAlterTableChangeColumnEventArgs extends SchemaEventArgs { - /** - * @var \Doctrine\DBAL\Schema\ColumnDiff - */ - private $_columnDiff; + /** @var ColumnDiff */ + private $columnDiff; - /** - * @var \Doctrine\DBAL\Schema\TableDiff - */ - private $_tableDiff; + /** @var TableDiff */ + private $tableDiff; - /** - * @var \Doctrine\DBAL\Platforms\AbstractPlatform - */ - private $_platform; + /** @var AbstractPlatform */ + private $platform; - /** - * @var array - */ - private $_sql = []; + /** @var string[] */ + private $sql = []; - /** - * @param \Doctrine\DBAL\Schema\ColumnDiff $columnDiff - * @param \Doctrine\DBAL\Schema\TableDiff $tableDiff - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - */ public function __construct(ColumnDiff $columnDiff, TableDiff $tableDiff, AbstractPlatform $platform) { - $this->_columnDiff = $columnDiff; - $this->_tableDiff = $tableDiff; - $this->_platform = $platform; + $this->columnDiff = $columnDiff; + $this->tableDiff = $tableDiff; + $this->platform = $platform; } /** - * @return \Doctrine\DBAL\Schema\ColumnDiff + * @return ColumnDiff */ public function getColumnDiff() { - return $this->_columnDiff; + return $this->columnDiff; } /** - * @return \Doctrine\DBAL\Schema\TableDiff + * @return TableDiff */ public function getTableDiff() { - return $this->_tableDiff; + return $this->tableDiff; } /** - * @return \Doctrine\DBAL\Platforms\AbstractPlatform + * @return AbstractPlatform */ public function getPlatform() { - return $this->_platform; + return $this->platform; } /** - * @param string|array $sql + * @param string|string[] $sql * * @return \Doctrine\DBAL\Event\SchemaAlterTableChangeColumnEventArgs */ public function addSql($sql) { if (is_array($sql)) { - $this->_sql = array_merge($this->_sql, $sql); + $this->sql = array_merge($this->sql, $sql); } else { - $this->_sql[] = $sql; + $this->sql[] = $sql; } return $this; } /** - * @return array + * @return string[] */ public function getSql() { - return $this->_sql; + return $this->sql; } } diff --git a/lib/Doctrine/DBAL/Event/SchemaAlterTableEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaAlterTableEventArgs.php index 8e60b2c5f6b..8f5f0ecf563 100644 --- a/lib/Doctrine/DBAL/Event/SchemaAlterTableEventArgs.php +++ b/lib/Doctrine/DBAL/Event/SchemaAlterTableEventArgs.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Event; @@ -26,75 +9,61 @@ /** * Event Arguments used when SQL queries for creating tables are generated inside Doctrine\DBAL\Platform\*Platform. - * - * @link www.doctrine-project.org - * @since 2.2 - * @author Jan Sorgalla */ class SchemaAlterTableEventArgs extends SchemaEventArgs { - /** - * @var \Doctrine\DBAL\Schema\TableDiff - */ - private $_tableDiff; + /** @var TableDiff */ + private $tableDiff; - /** - * @var \Doctrine\DBAL\Platforms\AbstractPlatform - */ - private $_platform; + /** @var AbstractPlatform */ + private $platform; - /** - * @var array - */ - private $_sql = []; + /** @var string[] */ + private $sql = []; - /** - * @param \Doctrine\DBAL\Schema\TableDiff $tableDiff - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - */ public function __construct(TableDiff $tableDiff, AbstractPlatform $platform) { - $this->_tableDiff = $tableDiff; - $this->_platform = $platform; + $this->tableDiff = $tableDiff; + $this->platform = $platform; } /** - * @return \Doctrine\DBAL\Schema\TableDiff + * @return TableDiff */ public function getTableDiff() { - return $this->_tableDiff; + return $this->tableDiff; } /** - * @return \Doctrine\DBAL\Platforms\AbstractPlatform + * @return AbstractPlatform */ public function getPlatform() { - return $this->_platform; + return $this->platform; } /** - * @param string|array $sql + * @param string|string[] $sql * * @return \Doctrine\DBAL\Event\SchemaAlterTableEventArgs */ public function addSql($sql) { if (is_array($sql)) { - $this->_sql = array_merge($this->_sql, $sql); + $this->sql = array_merge($this->sql, $sql); } else { - $this->_sql[] = $sql; + $this->sql[] = $sql; } return $this; } /** - * @return array + * @return string[] */ public function getSql() { - return $this->_sql; + return $this->sql; } } diff --git a/lib/Doctrine/DBAL/Event/SchemaAlterTableRemoveColumnEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaAlterTableRemoveColumnEventArgs.php index 52413ce9173..1bc9f590187 100644 --- a/lib/Doctrine/DBAL/Event/SchemaAlterTableRemoveColumnEventArgs.php +++ b/lib/Doctrine/DBAL/Event/SchemaAlterTableRemoveColumnEventArgs.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Event; @@ -27,90 +10,73 @@ /** * Event Arguments used when SQL queries for removing table columns are generated inside Doctrine\DBAL\Platform\*Platform. - * - * @link www.doctrine-project.org - * @since 2.2 - * @author Jan Sorgalla */ class SchemaAlterTableRemoveColumnEventArgs extends SchemaEventArgs { - /** - * @var \Doctrine\DBAL\Schema\Column - */ - private $_column; + /** @var Column */ + private $column; - /** - * @var \Doctrine\DBAL\Schema\TableDiff - */ - private $_tableDiff; + /** @var TableDiff */ + private $tableDiff; - /** - * @var \Doctrine\DBAL\Platforms\AbstractPlatform - */ - private $_platform; + /** @var AbstractPlatform */ + private $platform; - /** - * @var array - */ - private $_sql = []; + /** @var string[] */ + private $sql = []; - /** - * @param \Doctrine\DBAL\Schema\Column $column - * @param \Doctrine\DBAL\Schema\TableDiff $tableDiff - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - */ public function __construct(Column $column, TableDiff $tableDiff, AbstractPlatform $platform) { - $this->_column = $column; - $this->_tableDiff = $tableDiff; - $this->_platform = $platform; + $this->column = $column; + $this->tableDiff = $tableDiff; + $this->platform = $platform; } /** - * @return \Doctrine\DBAL\Schema\Column + * @return Column */ public function getColumn() { - return $this->_column; + return $this->column; } /** - * @return \Doctrine\DBAL\Schema\TableDiff + * @return TableDiff */ public function getTableDiff() { - return $this->_tableDiff; + return $this->tableDiff; } /** - * @return \Doctrine\DBAL\Platforms\AbstractPlatform + * @return AbstractPlatform */ public function getPlatform() { - return $this->_platform; + return $this->platform; } /** - * @param string|array $sql + * @param string|string[] $sql * * @return \Doctrine\DBAL\Event\SchemaAlterTableRemoveColumnEventArgs */ public function addSql($sql) { if (is_array($sql)) { - $this->_sql = array_merge($this->_sql, $sql); + $this->sql = array_merge($this->sql, $sql); } else { - $this->_sql[] = $sql; + $this->sql[] = $sql; } return $this; } /** - * @return array + * @return string[] */ public function getSql() { - return $this->_sql; + return $this->sql; } } diff --git a/lib/Doctrine/DBAL/Event/SchemaAlterTableRenameColumnEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaAlterTableRenameColumnEventArgs.php index 697660442a5..911ea8b4ab6 100644 --- a/lib/Doctrine/DBAL/Event/SchemaAlterTableRenameColumnEventArgs.php +++ b/lib/Doctrine/DBAL/Event/SchemaAlterTableRenameColumnEventArgs.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Event; @@ -27,50 +10,33 @@ /** * Event Arguments used when SQL queries for renaming table columns are generated inside Doctrine\DBAL\Platform\*Platform. - * - * @link www.doctrine-project.org - * @since 2.2 - * @author Jan Sorgalla */ class SchemaAlterTableRenameColumnEventArgs extends SchemaEventArgs { - /** - * @var string - */ - private $_oldColumnName; + /** @var string */ + private $oldColumnName; - /** - * @var \Doctrine\DBAL\Schema\Column - */ - private $_column; + /** @var Column */ + private $column; - /** - * @var \Doctrine\DBAL\Schema\TableDiff - */ - private $_tableDiff; + /** @var TableDiff */ + private $tableDiff; - /** - * @var \Doctrine\DBAL\Platforms\AbstractPlatform - */ - private $_platform; + /** @var AbstractPlatform */ + private $platform; - /** - * @var array - */ - private $_sql = []; + /** @var string[] */ + private $sql = []; /** - * @param string $oldColumnName - * @param \Doctrine\DBAL\Schema\Column $column - * @param \Doctrine\DBAL\Schema\TableDiff $tableDiff - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform + * @param string $oldColumnName */ public function __construct($oldColumnName, Column $column, TableDiff $tableDiff, AbstractPlatform $platform) { - $this->_oldColumnName = $oldColumnName; - $this->_column = $column; - $this->_tableDiff = $tableDiff; - $this->_platform = $platform; + $this->oldColumnName = $oldColumnName; + $this->column = $column; + $this->tableDiff = $tableDiff; + $this->platform = $platform; } /** @@ -78,54 +44,54 @@ public function __construct($oldColumnName, Column $column, TableDiff $tableDiff */ public function getOldColumnName() { - return $this->_oldColumnName; + return $this->oldColumnName; } /** - * @return \Doctrine\DBAL\Schema\Column + * @return Column */ public function getColumn() { - return $this->_column; + return $this->column; } /** - * @return \Doctrine\DBAL\Schema\TableDiff + * @return TableDiff */ public function getTableDiff() { - return $this->_tableDiff; + return $this->tableDiff; } /** - * @return \Doctrine\DBAL\Platforms\AbstractPlatform + * @return AbstractPlatform */ public function getPlatform() { - return $this->_platform; + return $this->platform; } /** - * @param string|array $sql + * @param string|string[] $sql * * @return \Doctrine\DBAL\Event\SchemaAlterTableRenameColumnEventArgs */ public function addSql($sql) { if (is_array($sql)) { - $this->_sql = array_merge($this->_sql, $sql); + $this->sql = array_merge($this->sql, $sql); } else { - $this->_sql[] = $sql; + $this->sql[] = $sql; } return $this; } /** - * @return array + * @return string[] */ public function getSql() { - return $this->_sql; + return $this->sql; } } diff --git a/lib/Doctrine/DBAL/Event/SchemaColumnDefinitionEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaColumnDefinitionEventArgs.php index 14bb8df73b3..19d9f93a329 100644 --- a/lib/Doctrine/DBAL/Event/SchemaColumnDefinitionEventArgs.php +++ b/lib/Doctrine/DBAL/Event/SchemaColumnDefinitionEventArgs.php @@ -1,106 +1,75 @@ . - */ namespace Doctrine\DBAL\Event; use Doctrine\DBAL\Connection; +use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Schema\Column; /** * Event Arguments used when the portable column definition is generated inside Doctrine\DBAL\Schema\AbstractSchemaManager. - * - * @link www.doctrine-project.org - * @since 2.2 - * @author Jan Sorgalla */ class SchemaColumnDefinitionEventArgs extends SchemaEventArgs { - /** - * @var \Doctrine\DBAL\Schema\Column|null - */ - private $_column = null; + /** @var Column|null */ + private $column = null; /** * Raw column data as fetched from the database. * - * @var array + * @var mixed[] */ - private $_tableColumn; + private $tableColumn; - /** - * @var string - */ - private $_table; + /** @var string */ + private $table; - /** - * @var string - */ - private $_database; + /** @var string */ + private $database; - /** - * @var \Doctrine\DBAL\Connection - */ - private $_connection; + /** @var Connection */ + private $connection; /** - * @param array $tableColumn - * @param string $table - * @param string $database - * @param \Doctrine\DBAL\Connection $connection + * @param mixed[] $tableColumn + * @param string $table + * @param string $database */ public function __construct(array $tableColumn, $table, $database, Connection $connection) { - $this->_tableColumn = $tableColumn; - $this->_table = $table; - $this->_database = $database; - $this->_connection = $connection; + $this->tableColumn = $tableColumn; + $this->table = $table; + $this->database = $database; + $this->connection = $connection; } /** * Allows to clear the column which means the column will be excluded from * tables column list. * - * @param null|\Doctrine\DBAL\Schema\Column $column - * * @return \Doctrine\DBAL\Event\SchemaColumnDefinitionEventArgs */ - public function setColumn(Column $column = null) + public function setColumn(?Column $column = null) { - $this->_column = $column; + $this->column = $column; return $this; } /** - * @return \Doctrine\DBAL\Schema\Column|null + * @return Column|null */ public function getColumn() { - return $this->_column; + return $this->column; } /** - * @return array + * @return mixed[] */ public function getTableColumn() { - return $this->_tableColumn; + return $this->tableColumn; } /** @@ -108,7 +77,7 @@ public function getTableColumn() */ public function getTable() { - return $this->_table; + return $this->table; } /** @@ -116,22 +85,22 @@ public function getTable() */ public function getDatabase() { - return $this->_database; + return $this->database; } /** - * @return \Doctrine\DBAL\Connection + * @return Connection */ public function getConnection() { - return $this->_connection; + return $this->connection; } /** - * @return \Doctrine\DBAL\Platforms\AbstractPlatform + * @return AbstractPlatform */ public function getDatabasePlatform() { - return $this->_connection->getDatabasePlatform(); + return $this->connection->getDatabasePlatform(); } } diff --git a/lib/Doctrine/DBAL/Event/SchemaCreateTableColumnEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaCreateTableColumnEventArgs.php index 824e243b135..9d24b8b9049 100644 --- a/lib/Doctrine/DBAL/Event/SchemaCreateTableColumnEventArgs.php +++ b/lib/Doctrine/DBAL/Event/SchemaCreateTableColumnEventArgs.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Event; @@ -27,90 +10,73 @@ /** * Event Arguments used when SQL queries for creating table columns are generated inside Doctrine\DBAL\Platform\AbstractPlatform. - * - * @link www.doctrine-project.org - * @since 2.2 - * @author Jan Sorgalla */ class SchemaCreateTableColumnEventArgs extends SchemaEventArgs { - /** - * @var \Doctrine\DBAL\Schema\Column - */ - private $_column; + /** @var Column */ + private $column; - /** - * @var \Doctrine\DBAL\Schema\Table - */ - private $_table; + /** @var Table */ + private $table; - /** - * @var \Doctrine\DBAL\Platforms\AbstractPlatform - */ - private $_platform; + /** @var AbstractPlatform */ + private $platform; - /** - * @var array - */ - private $_sql = []; + /** @var string[] */ + private $sql = []; - /** - * @param \Doctrine\DBAL\Schema\Column $column - * @param \Doctrine\DBAL\Schema\Table $table - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - */ public function __construct(Column $column, Table $table, AbstractPlatform $platform) { - $this->_column = $column; - $this->_table = $table; - $this->_platform = $platform; + $this->column = $column; + $this->table = $table; + $this->platform = $platform; } /** - * @return \Doctrine\DBAL\Schema\Column + * @return Column */ public function getColumn() { - return $this->_column; + return $this->column; } /** - * @return \Doctrine\DBAL\Schema\Table + * @return Table */ public function getTable() { - return $this->_table; + return $this->table; } /** - * @return \Doctrine\DBAL\Platforms\AbstractPlatform + * @return AbstractPlatform */ public function getPlatform() { - return $this->_platform; + return $this->platform; } /** - * @param string|array $sql + * @param string|string[] $sql * * @return \Doctrine\DBAL\Event\SchemaCreateTableColumnEventArgs */ public function addSql($sql) { if (is_array($sql)) { - $this->_sql = array_merge($this->_sql, $sql); + $this->sql = array_merge($this->sql, $sql); } else { - $this->_sql[] = $sql; + $this->sql[] = $sql; } return $this; } /** - * @return array + * @return string[] */ public function getSql() { - return $this->_sql; + return $this->sql; } } diff --git a/lib/Doctrine/DBAL/Event/SchemaCreateTableEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaCreateTableEventArgs.php index 7993b3adb15..538617cc328 100644 --- a/lib/Doctrine/DBAL/Event/SchemaCreateTableEventArgs.php +++ b/lib/Doctrine/DBAL/Event/SchemaCreateTableEventArgs.php @@ -1,130 +1,98 @@ . - */ namespace Doctrine\DBAL\Event; use Doctrine\DBAL\Platforms\AbstractPlatform; +use Doctrine\DBAL\Schema\Column; use Doctrine\DBAL\Schema\Table; use function array_merge; use function is_array; /** * Event Arguments used when SQL queries for creating tables are generated inside Doctrine\DBAL\Platform\AbstractPlatform. - * - * @link www.doctrine-project.org - * @since 2.2 - * @author Jan Sorgalla */ class SchemaCreateTableEventArgs extends SchemaEventArgs { - /** - * @var \Doctrine\DBAL\Schema\Table - */ - private $_table; + /** @var Table */ + private $table; - /** - * @var array - */ - private $_columns; + /** @var Column[] */ + private $columns; - /** - * @var array - */ - private $_options; + /** @var mixed[] */ + private $options; - /** - * @var \Doctrine\DBAL\Platforms\AbstractPlatform - */ - private $_platform; + /** @var AbstractPlatform */ + private $platform; - /** - * @var array - */ - private $_sql = []; + /** @var string[] */ + private $sql = []; /** - * @param \Doctrine\DBAL\Schema\Table $table - * @param array $columns - * @param array $options - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform + * @param Column[] $columns + * @param mixed[] $options */ public function __construct(Table $table, array $columns, array $options, AbstractPlatform $platform) { - $this->_table = $table; - $this->_columns = $columns; - $this->_options = $options; - $this->_platform = $platform; + $this->table = $table; + $this->columns = $columns; + $this->options = $options; + $this->platform = $platform; } /** - * @return \Doctrine\DBAL\Schema\Table + * @return Table */ public function getTable() { - return $this->_table; + return $this->table; } /** - * @return array + * @return Column[] */ public function getColumns() { - return $this->_columns; + return $this->columns; } /** - * @return array + * @return mixed[] */ public function getOptions() { - return $this->_options; + return $this->options; } /** - * @return \Doctrine\DBAL\Platforms\AbstractPlatform + * @return AbstractPlatform */ public function getPlatform() { - return $this->_platform; + return $this->platform; } /** - * @param string|array $sql + * @param string|string[] $sql * * @return \Doctrine\DBAL\Event\SchemaCreateTableEventArgs */ public function addSql($sql) { if (is_array($sql)) { - $this->_sql = array_merge($this->_sql, $sql); + $this->sql = array_merge($this->sql, $sql); } else { - $this->_sql[] = $sql; + $this->sql[] = $sql; } return $this; } /** - * @return array + * @return string[] */ public function getSql() { - return $this->_sql; + return $this->sql; } } diff --git a/lib/Doctrine/DBAL/Event/SchemaDropTableEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaDropTableEventArgs.php index b3c90422121..900b9fbfd71 100644 --- a/lib/Doctrine/DBAL/Event/SchemaDropTableEventArgs.php +++ b/lib/Doctrine/DBAL/Event/SchemaDropTableEventArgs.php @@ -1,82 +1,55 @@ . - */ namespace Doctrine\DBAL\Event; use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Schema\Table; +use InvalidArgumentException; use function is_string; /** * Event Arguments used when the SQL query for dropping tables are generated inside Doctrine\DBAL\Platform\AbstractPlatform. - * - * @link www.doctrine-project.org - * @since 2.2 - * @author Jan Sorgalla */ class SchemaDropTableEventArgs extends SchemaEventArgs { - /** - * @var string|\Doctrine\DBAL\Schema\Table - */ - private $_table; + /** @var string|Table */ + private $table; - /** - * @var \Doctrine\DBAL\Platforms\AbstractPlatform - */ - private $_platform; + /** @var AbstractPlatform */ + private $platform; - /** - * @var string|null - */ - private $_sql = null; + /** @var string|null */ + private $sql = null; /** - * @param string|\Doctrine\DBAL\Schema\Table $table - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform + * @param string|Table $table * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function __construct($table, AbstractPlatform $platform) { - if ( ! $table instanceof Table && !is_string($table)) { - throw new \InvalidArgumentException('SchemaDropTableEventArgs expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.'); + if (! $table instanceof Table && ! is_string($table)) { + throw new InvalidArgumentException('SchemaDropTableEventArgs expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.'); } - $this->_table = $table; - $this->_platform = $platform; + $this->table = $table; + $this->platform = $platform; } /** - * @return string|\Doctrine\DBAL\Schema\Table + * @return string|Table */ public function getTable() { - return $this->_table; + return $this->table; } /** - * @return \Doctrine\DBAL\Platforms\AbstractPlatform + * @return AbstractPlatform */ public function getPlatform() { - return $this->_platform; + return $this->platform; } /** @@ -86,7 +59,7 @@ public function getPlatform() */ public function setSql($sql) { - $this->_sql = $sql; + $this->sql = $sql; return $this; } @@ -96,6 +69,6 @@ public function setSql($sql) */ public function getSql() { - return $this->_sql; + return $this->sql; } } diff --git a/lib/Doctrine/DBAL/Event/SchemaEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaEventArgs.php index db12e57ad3b..0db0689c5ad 100644 --- a/lib/Doctrine/DBAL/Event/SchemaEventArgs.php +++ b/lib/Doctrine/DBAL/Event/SchemaEventArgs.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Event; @@ -23,24 +6,18 @@ /** * Base class for schema related events. - * - * @link www.doctrine-project.org - * @since 2.2 - * @author Jan Sorgalla */ class SchemaEventArgs extends EventArgs { - /** - * @var bool - */ - private $_preventDefault = false; + /** @var bool */ + private $preventDefault = false; /** * @return \Doctrine\DBAL\Event\SchemaEventArgs */ public function preventDefault() { - $this->_preventDefault = true; + $this->preventDefault = true; return $this; } @@ -50,6 +27,6 @@ public function preventDefault() */ public function isDefaultPrevented() { - return $this->_preventDefault; + return $this->preventDefault; } } diff --git a/lib/Doctrine/DBAL/Event/SchemaIndexDefinitionEventArgs.php b/lib/Doctrine/DBAL/Event/SchemaIndexDefinitionEventArgs.php index 3fd1d4bf7da..317f352b87a 100644 --- a/lib/Doctrine/DBAL/Event/SchemaIndexDefinitionEventArgs.php +++ b/lib/Doctrine/DBAL/Event/SchemaIndexDefinitionEventArgs.php @@ -1,98 +1,69 @@ . - */ namespace Doctrine\DBAL\Event; use Doctrine\DBAL\Connection; +use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Schema\Index; /** * Event Arguments used when the portable index definition is generated inside Doctrine\DBAL\Schema\AbstractSchemaManager. - * - * @link www.doctrine-project.org - * @since 2.2 - * @author Jan Sorgalla */ class SchemaIndexDefinitionEventArgs extends SchemaEventArgs { - /** - * @var \Doctrine\DBAL\Schema\Index|null - */ - private $_index = null; + /** @var Index|null */ + private $index = null; /** * Raw index data as fetched from the database. * - * @var array + * @var mixed[] */ - private $_tableIndex; + private $tableIndex; - /** - * @var string - */ - private $_table; + /** @var string */ + private $table; - /** - * @var \Doctrine\DBAL\Connection - */ - private $_connection; + /** @var Connection */ + private $connection; /** - * @param array $tableIndex - * @param string $table - * @param \Doctrine\DBAL\Connection $connection + * @param mixed[] $tableIndex + * @param string $table */ public function __construct(array $tableIndex, $table, Connection $connection) { - $this->_tableIndex = $tableIndex; - $this->_table = $table; - $this->_connection = $connection; + $this->tableIndex = $tableIndex; + $this->table = $table; + $this->connection = $connection; } /** * Allows to clear the index which means the index will be excluded from tables index list. * - * @param null|\Doctrine\DBAL\Schema\Index $index - * * @return SchemaIndexDefinitionEventArgs */ - public function setIndex(Index $index = null) + public function setIndex(?Index $index = null) { - $this->_index = $index; + $this->index = $index; return $this; } /** - * @return \Doctrine\DBAL\Schema\Index|null + * @return Index|null */ public function getIndex() { - return $this->_index; + return $this->index; } /** - * @return array + * @return mixed[] */ public function getTableIndex() { - return $this->_tableIndex; + return $this->tableIndex; } /** @@ -100,22 +71,22 @@ public function getTableIndex() */ public function getTable() { - return $this->_table; + return $this->table; } /** - * @return \Doctrine\DBAL\Connection + * @return Connection */ public function getConnection() { - return $this->_connection; + return $this->connection; } /** - * @return \Doctrine\DBAL\Platforms\AbstractPlatform + * @return AbstractPlatform */ public function getDatabasePlatform() { - return $this->_connection->getDatabasePlatform(); + return $this->connection->getDatabasePlatform(); } } diff --git a/lib/Doctrine/DBAL/Events.php b/lib/Doctrine/DBAL/Events.php index 0d31504c70a..5398d0f84c2 100644 --- a/lib/Doctrine/DBAL/Events.php +++ b/lib/Doctrine/DBAL/Events.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL; @@ -23,9 +6,6 @@ * Container for all DBAL events. * * This class cannot be instantiated. - * - * @author Roman Borschel - * @since 2.0 */ final class Events { @@ -36,16 +16,16 @@ private function __construct() { } - const postConnect = 'postConnect'; + public const postConnect = 'postConnect'; - const onSchemaCreateTable = 'onSchemaCreateTable'; - const onSchemaCreateTableColumn = 'onSchemaCreateTableColumn'; - const onSchemaDropTable = 'onSchemaDropTable'; - const onSchemaAlterTable = 'onSchemaAlterTable'; - const onSchemaAlterTableAddColumn = 'onSchemaAlterTableAddColumn'; - const onSchemaAlterTableRemoveColumn = 'onSchemaAlterTableRemoveColumn'; - const onSchemaAlterTableChangeColumn = 'onSchemaAlterTableChangeColumn'; - const onSchemaAlterTableRenameColumn = 'onSchemaAlterTableRenameColumn'; - const onSchemaColumnDefinition = 'onSchemaColumnDefinition'; - const onSchemaIndexDefinition = 'onSchemaIndexDefinition'; + public const onSchemaCreateTable = 'onSchemaCreateTable'; + public const onSchemaCreateTableColumn = 'onSchemaCreateTableColumn'; + public const onSchemaDropTable = 'onSchemaDropTable'; + public const onSchemaAlterTable = 'onSchemaAlterTable'; + public const onSchemaAlterTableAddColumn = 'onSchemaAlterTableAddColumn'; + public const onSchemaAlterTableRemoveColumn = 'onSchemaAlterTableRemoveColumn'; + public const onSchemaAlterTableChangeColumn = 'onSchemaAlterTableChangeColumn'; + public const onSchemaAlterTableRenameColumn = 'onSchemaAlterTableRenameColumn'; + public const onSchemaColumnDefinition = 'onSchemaColumnDefinition'; + public const onSchemaIndexDefinition = 'onSchemaIndexDefinition'; } diff --git a/lib/Doctrine/DBAL/Exception/ConnectionException.php b/lib/Doctrine/DBAL/Exception/ConnectionException.php index 8d976dcb325..e96a29191e4 100644 --- a/lib/Doctrine/DBAL/Exception/ConnectionException.php +++ b/lib/Doctrine/DBAL/Exception/ConnectionException.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Exception; /** * Base class for all connection related errors detected in the driver. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class ConnectionException extends DriverException { diff --git a/lib/Doctrine/DBAL/Exception/ConstraintViolationException.php b/lib/Doctrine/DBAL/Exception/ConstraintViolationException.php index 8dd1cb69452..3959f39af95 100644 --- a/lib/Doctrine/DBAL/Exception/ConstraintViolationException.php +++ b/lib/Doctrine/DBAL/Exception/ConstraintViolationException.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Exception; /** * Base class for all constraint violation related errors detected in the driver. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class ConstraintViolationException extends ServerException { diff --git a/lib/Doctrine/DBAL/Exception/DatabaseObjectExistsException.php b/lib/Doctrine/DBAL/Exception/DatabaseObjectExistsException.php index 279aae9a5a3..7e0ba0299e9 100644 --- a/lib/Doctrine/DBAL/Exception/DatabaseObjectExistsException.php +++ b/lib/Doctrine/DBAL/Exception/DatabaseObjectExistsException.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Exception; @@ -25,10 +8,6 @@ * A database object is considered any asset that can be created in a database * such as schemas, tables, views, sequences, triggers, constraints, indexes, * functions, stored procedures etc. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class DatabaseObjectExistsException extends ServerException { diff --git a/lib/Doctrine/DBAL/Exception/DatabaseObjectNotFoundException.php b/lib/Doctrine/DBAL/Exception/DatabaseObjectNotFoundException.php index fbca22d9942..3342bce8d58 100644 --- a/lib/Doctrine/DBAL/Exception/DatabaseObjectNotFoundException.php +++ b/lib/Doctrine/DBAL/Exception/DatabaseObjectNotFoundException.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Exception; @@ -25,10 +8,6 @@ * A database object is considered any asset that can be created in a database * such as schemas, tables, views, sequences, triggers, constraints, indexes, * functions, stored procedures etc. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class DatabaseObjectNotFoundException extends ServerException { diff --git a/lib/Doctrine/DBAL/Exception/DeadlockException.php b/lib/Doctrine/DBAL/Exception/DeadlockException.php index 05af11e4b6f..fd0550a56b0 100644 --- a/lib/Doctrine/DBAL/Exception/DeadlockException.php +++ b/lib/Doctrine/DBAL/Exception/DeadlockException.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Exception; /** * Exception for a deadlock error of a transaction detected in the driver. - * - * @author Tobias Schultze - * @link www.doctrine-project.org - * @since 2.6 */ class DeadlockException extends ServerException implements RetryableException { diff --git a/lib/Doctrine/DBAL/Exception/DriverException.php b/lib/Doctrine/DBAL/Exception/DriverException.php index 08b7935a0c0..d3753329882 100644 --- a/lib/Doctrine/DBAL/Exception/DriverException.php +++ b/lib/Doctrine/DBAL/Exception/DriverException.php @@ -1,32 +1,12 @@ . - */ namespace Doctrine\DBAL\Exception; use Doctrine\DBAL\DBALException; +use Exception; /** * Base class for all errors detected in the driver. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class DriverException extends DBALException { @@ -38,8 +18,6 @@ class DriverException extends DBALException private $driverException; /** - * Constructor. - * * @param string $message The exception message. * @param \Doctrine\DBAL\Driver\DriverException $driverException The DBAL driver exception to chain. */ @@ -47,7 +25,7 @@ public function __construct($message, \Doctrine\DBAL\Driver\DriverException $dri { $exception = null; - if ($driverException instanceof \Exception) { + if ($driverException instanceof Exception) { $exception = $driverException; } diff --git a/lib/Doctrine/DBAL/Exception/ForeignKeyConstraintViolationException.php b/lib/Doctrine/DBAL/Exception/ForeignKeyConstraintViolationException.php index d244855a16d..48d736f9e28 100644 --- a/lib/Doctrine/DBAL/Exception/ForeignKeyConstraintViolationException.php +++ b/lib/Doctrine/DBAL/Exception/ForeignKeyConstraintViolationException.php @@ -1,31 +1,9 @@ . - */ namespace Doctrine\DBAL\Exception; /** * Exception for a foreign key constraint violation detected in the driver. - * - * @author Benjamin Eberlei - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class ForeignKeyConstraintViolationException extends ConstraintViolationException { diff --git a/lib/Doctrine/DBAL/Exception/InvalidArgumentException.php b/lib/Doctrine/DBAL/Exception/InvalidArgumentException.php index 5b811227bdd..5d431e6031d 100644 --- a/lib/Doctrine/DBAL/Exception/InvalidArgumentException.php +++ b/lib/Doctrine/DBAL/Exception/InvalidArgumentException.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Exception; @@ -23,10 +6,6 @@ /** * Exception to be thrown when invalid arguments are passed to any DBAL API - * - * @author Marco Pivetta - * @link www.doctrine-project.org - * @since 2.5 */ class InvalidArgumentException extends DBALException { diff --git a/lib/Doctrine/DBAL/Exception/InvalidFieldNameException.php b/lib/Doctrine/DBAL/Exception/InvalidFieldNameException.php index e0b1013fe4c..d960feaf869 100644 --- a/lib/Doctrine/DBAL/Exception/InvalidFieldNameException.php +++ b/lib/Doctrine/DBAL/Exception/InvalidFieldNameException.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Exception; /** * Exception for an invalid specified field name in a statement detected in the driver. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class InvalidFieldNameException extends ServerException { diff --git a/lib/Doctrine/DBAL/Exception/LockWaitTimeoutException.php b/lib/Doctrine/DBAL/Exception/LockWaitTimeoutException.php index 915e11b8b93..bfc3a498a3c 100644 --- a/lib/Doctrine/DBAL/Exception/LockWaitTimeoutException.php +++ b/lib/Doctrine/DBAL/Exception/LockWaitTimeoutException.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Exception; /** * Exception for a lock wait timeout error of a transaction detected in the driver. - * - * @author Tobias Schultze - * @link www.doctrine-project.org - * @since 2.6 */ class LockWaitTimeoutException extends ServerException implements RetryableException { diff --git a/lib/Doctrine/DBAL/Exception/NonUniqueFieldNameException.php b/lib/Doctrine/DBAL/Exception/NonUniqueFieldNameException.php index 7b214e3b946..fd56f89691f 100644 --- a/lib/Doctrine/DBAL/Exception/NonUniqueFieldNameException.php +++ b/lib/Doctrine/DBAL/Exception/NonUniqueFieldNameException.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Exception; /** * Exception for a non-unique/ambiguous specified field name in a statement detected in the driver. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class NonUniqueFieldNameException extends ServerException { diff --git a/lib/Doctrine/DBAL/Exception/NotNullConstraintViolationException.php b/lib/Doctrine/DBAL/Exception/NotNullConstraintViolationException.php index a1f45b92a44..e327bc94d4d 100644 --- a/lib/Doctrine/DBAL/Exception/NotNullConstraintViolationException.php +++ b/lib/Doctrine/DBAL/Exception/NotNullConstraintViolationException.php @@ -1,31 +1,9 @@ . - */ namespace Doctrine\DBAL\Exception; /** * Exception for a NOT NULL constraint violation detected in the driver. - * - * @author Benjamin Eberlei - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class NotNullConstraintViolationException extends ConstraintViolationException { diff --git a/lib/Doctrine/DBAL/Exception/ReadOnlyException.php b/lib/Doctrine/DBAL/Exception/ReadOnlyException.php index 0345e88fce0..a846f2501c8 100644 --- a/lib/Doctrine/DBAL/Exception/ReadOnlyException.php +++ b/lib/Doctrine/DBAL/Exception/ReadOnlyException.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Exception; /** * Exception for a write operation attempt on a read-only database element detected in the driver. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class ReadOnlyException extends ServerException { diff --git a/lib/Doctrine/DBAL/Exception/RetryableException.php b/lib/Doctrine/DBAL/Exception/RetryableException.php index 6b019dcc472..e1ccd02ffd9 100644 --- a/lib/Doctrine/DBAL/Exception/RetryableException.php +++ b/lib/Doctrine/DBAL/Exception/RetryableException.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Exception; /** * Marker interface for all exceptions where retrying the transaction makes sense. - * - * @author Tobias Schultze - * @link www.doctrine-project.org - * @since 2.6 */ interface RetryableException { diff --git a/lib/Doctrine/DBAL/Exception/ServerException.php b/lib/Doctrine/DBAL/Exception/ServerException.php index 36460ee0d64..c88c3863b62 100644 --- a/lib/Doctrine/DBAL/Exception/ServerException.php +++ b/lib/Doctrine/DBAL/Exception/ServerException.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Exception; /** * Base class for all server related errors detected in the driver. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class ServerException extends DriverException { diff --git a/lib/Doctrine/DBAL/Exception/SyntaxErrorException.php b/lib/Doctrine/DBAL/Exception/SyntaxErrorException.php index 97b8fd25f3e..0b413b71971 100644 --- a/lib/Doctrine/DBAL/Exception/SyntaxErrorException.php +++ b/lib/Doctrine/DBAL/Exception/SyntaxErrorException.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Exception; /** * Exception for a syntax error in a statement detected in the driver. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class SyntaxErrorException extends ServerException { diff --git a/lib/Doctrine/DBAL/Exception/TableExistsException.php b/lib/Doctrine/DBAL/Exception/TableExistsException.php index c90bfb476c4..ff0df89afac 100644 --- a/lib/Doctrine/DBAL/Exception/TableExistsException.php +++ b/lib/Doctrine/DBAL/Exception/TableExistsException.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Exception; /** * Exception for an already existing table referenced in a statement detected in the driver. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class TableExistsException extends DatabaseObjectExistsException { diff --git a/lib/Doctrine/DBAL/Exception/TableNotFoundException.php b/lib/Doctrine/DBAL/Exception/TableNotFoundException.php index 90793b909de..aeaa0057d49 100644 --- a/lib/Doctrine/DBAL/Exception/TableNotFoundException.php +++ b/lib/Doctrine/DBAL/Exception/TableNotFoundException.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Exception; /** * Exception for an unknown table referenced in a statement detected in the driver. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class TableNotFoundException extends DatabaseObjectNotFoundException { diff --git a/lib/Doctrine/DBAL/Exception/UniqueConstraintViolationException.php b/lib/Doctrine/DBAL/Exception/UniqueConstraintViolationException.php index cd117738dd9..c762ad3c78a 100644 --- a/lib/Doctrine/DBAL/Exception/UniqueConstraintViolationException.php +++ b/lib/Doctrine/DBAL/Exception/UniqueConstraintViolationException.php @@ -1,31 +1,9 @@ . - */ namespace Doctrine\DBAL\Exception; /** * Exception for a unique constraint violation detected in the driver. - * - * @author Benjamin Eberlei - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class UniqueConstraintViolationException extends ConstraintViolationException { diff --git a/lib/Doctrine/DBAL/FetchMode.php b/lib/Doctrine/DBAL/FetchMode.php index a3e7f3ba601..b3fe42f4ceb 100644 --- a/lib/Doctrine/DBAL/FetchMode.php +++ b/lib/Doctrine/DBAL/FetchMode.php @@ -2,6 +2,8 @@ namespace Doctrine\DBAL; +use PDO; + /** * Contains statement fetch modes. */ @@ -15,7 +17,7 @@ final class FetchMode * * @see \PDO::FETCH_ASSOC */ - public const ASSOCIATIVE = \PDO::FETCH_ASSOC; + public const ASSOCIATIVE = PDO::FETCH_ASSOC; /** * Specifies that the fetch method shall return each row as an array indexed @@ -24,7 +26,7 @@ final class FetchMode * * @see \PDO::FETCH_NUM */ - public const NUMERIC = \PDO::FETCH_NUM; + public const NUMERIC = PDO::FETCH_NUM; /** * Specifies that the fetch method shall return each row as an array indexed @@ -33,7 +35,7 @@ final class FetchMode * * @see \PDO::FETCH_BOTH */ - public const MIXED = \PDO::FETCH_BOTH; + public const MIXED = PDO::FETCH_BOTH; /** * Specifies that the fetch method shall return each row as an object with @@ -42,7 +44,7 @@ final class FetchMode * * @see \PDO::FETCH_OBJ */ - public const STANDARD_OBJECT = \PDO::FETCH_OBJ; + public const STANDARD_OBJECT = PDO::FETCH_OBJ; /** * Specifies that the fetch method shall return only a single requested @@ -50,7 +52,7 @@ final class FetchMode * * @see \PDO::FETCH_COLUMN */ - public const COLUMN = \PDO::FETCH_COLUMN; + public const COLUMN = PDO::FETCH_COLUMN; /** * Specifies that the fetch method shall return a new instance of the @@ -58,7 +60,7 @@ final class FetchMode * * @see \PDO::FETCH_CLASS */ - public const CUSTOM_OBJECT = \PDO::FETCH_CLASS; + public const CUSTOM_OBJECT = PDO::FETCH_CLASS; /** * This class cannot be instantiated. diff --git a/lib/Doctrine/DBAL/Id/TableGenerator.php b/lib/Doctrine/DBAL/Id/TableGenerator.php index 068eb6056bf..cb34dcd5c4b 100644 --- a/lib/Doctrine/DBAL/Id/TableGenerator.php +++ b/lib/Doctrine/DBAL/Id/TableGenerator.php @@ -1,28 +1,13 @@ . - */ namespace Doctrine\DBAL\Id; -use Doctrine\DBAL\DriverManager; use Doctrine\DBAL\Connection; +use Doctrine\DBAL\DBALException; +use Doctrine\DBAL\DriverManager; use Doctrine\DBAL\FetchMode; use Doctrine\DBAL\LockMode; +use Throwable; use const CASE_LOWER; use function array_change_key_case; @@ -62,39 +47,30 @@ * * If no row is present for a given sequence a new one will be created with the * default values 'value' = 1 and 'increment_by' = 1 - * - * @author Benjamin Eberlei */ class TableGenerator { - /** - * @var \Doctrine\DBAL\Connection - */ + /** @var Connection */ private $conn; - /** - * @var string - */ + /** @var string */ private $generatorTableName; - /** - * @var array - */ + /** @var mixed[][] */ private $sequences = []; /** - * @param \Doctrine\DBAL\Connection $conn - * @param string $generatorTableName + * @param string $generatorTableName * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ public function __construct(Connection $conn, $generatorTableName = 'sequences') { $params = $conn->getParams(); - if ($params['driver'] == 'pdo_sqlite') { - throw new \Doctrine\DBAL\DBALException("Cannot use TableGenerator with SQLite."); + if ($params['driver'] === 'pdo_sqlite') { + throw new DBALException('Cannot use TableGenerator with SQLite.'); } - $this->conn = DriverManager::getConnection($params, $conn->getConfiguration(), $conn->getEventManager()); + $this->conn = DriverManager::getConnection($params, $conn->getConfiguration(), $conn->getEventManager()); $this->generatorTableName = $generatorTableName; } @@ -105,7 +81,7 @@ public function __construct(Connection $conn, $generatorTableName = 'sequences') * * @return int * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ public function nextValue($sequenceName) { @@ -113,7 +89,7 @@ public function nextValue($sequenceName) $value = $this->sequences[$sequenceName]['value']; $this->sequences[$sequenceName]['value']++; if ($this->sequences[$sequenceName]['value'] >= $this->sequences[$sequenceName]['max']) { - unset ($this->sequences[$sequenceName]); + unset($this->sequences[$sequenceName]); } return $value; @@ -138,17 +114,17 @@ public function nextValue($sequenceName) if ($row['sequence_increment_by'] > 1) { $this->sequences[$sequenceName] = [ 'value' => $value, - 'max' => $row['sequence_value'] + $row['sequence_increment_by'] + 'max' => $row['sequence_value'] + $row['sequence_increment_by'], ]; } - $sql = "UPDATE " . $this->generatorTableName . " ". - "SET sequence_value = sequence_value + sequence_increment_by " . - "WHERE sequence_name = ? AND sequence_value = ?"; + $sql = 'UPDATE ' . $this->generatorTableName . ' ' . + 'SET sequence_value = sequence_value + sequence_increment_by ' . + 'WHERE sequence_name = ? AND sequence_value = ?'; $rows = $this->conn->executeUpdate($sql, [$sequenceName, $row['sequence_value']]); - if ($rows != 1) { - throw new \Doctrine\DBAL\DBALException("Race-condition detected while updating sequence. Aborting generation"); + if ($rows !== 1) { + throw new DBALException('Race-condition detected while updating sequence. Aborting generation'); } } else { $this->conn->insert( @@ -159,10 +135,9 @@ public function nextValue($sequenceName) } $this->conn->commit(); - - } catch (\Exception $e) { + } catch (Throwable $e) { $this->conn->rollBack(); - throw new \Doctrine\DBAL\DBALException("Error occurred while generating ID with TableGenerator, aborted generation: " . $e->getMessage(), 0, $e); + throw new DBALException('Error occurred while generating ID with TableGenerator, aborted generation: ' . $e->getMessage(), 0, $e); } return $value; diff --git a/lib/Doctrine/DBAL/Id/TableGeneratorSchemaVisitor.php b/lib/Doctrine/DBAL/Id/TableGeneratorSchemaVisitor.php index 619a92f7b4d..3ec22f37c5c 100644 --- a/lib/Doctrine/DBAL/Id/TableGeneratorSchemaVisitor.php +++ b/lib/Doctrine/DBAL/Id/TableGeneratorSchemaVisitor.php @@ -1,36 +1,18 @@ . - */ namespace Doctrine\DBAL\Id; -use Doctrine\DBAL\Schema\Table; -use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Column; use Doctrine\DBAL\Schema\ForeignKeyConstraint; -use Doctrine\DBAL\Schema\Sequence; use Doctrine\DBAL\Schema\Index; +use Doctrine\DBAL\Schema\Schema; +use Doctrine\DBAL\Schema\Sequence; +use Doctrine\DBAL\Schema\Table; +use Doctrine\DBAL\Schema\Visitor\Visitor; -class TableGeneratorSchemaVisitor implements \Doctrine\DBAL\Schema\Visitor\Visitor +class TableGeneratorSchemaVisitor implements Visitor { - /** - * @var string - */ + /** @var string */ private $generatorTableName; /** diff --git a/lib/Doctrine/DBAL/LockMode.php b/lib/Doctrine/DBAL/LockMode.php index 8d78180ede2..14e81432b43 100644 --- a/lib/Doctrine/DBAL/LockMode.php +++ b/lib/Doctrine/DBAL/LockMode.php @@ -1,38 +1,16 @@ . - */ namespace Doctrine\DBAL; /** * Contains all DBAL LockModes. - * - * @link www.doctrine-project.org - * @since 1.0 - * @author Benjamin Eberlei - * @author Roman Borschel */ class LockMode { - const NONE = 0; - const OPTIMISTIC = 1; - const PESSIMISTIC_READ = 2; - const PESSIMISTIC_WRITE = 4; + public const NONE = 0; + public const OPTIMISTIC = 1; + public const PESSIMISTIC_READ = 2; + public const PESSIMISTIC_WRITE = 4; /** * Private constructor. This class cannot be instantiated. diff --git a/lib/Doctrine/DBAL/Logging/DebugStack.php b/lib/Doctrine/DBAL/Logging/DebugStack.php index 4cffaa67fce..e1ccaad6ba0 100644 --- a/lib/Doctrine/DBAL/Logging/DebugStack.php +++ b/lib/Doctrine/DBAL/Logging/DebugStack.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Logging; @@ -23,20 +6,13 @@ /** * Includes executed SQLs in a Debug Stack. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class DebugStack implements SQLLogger { /** * Executed SQL queries. * - * @var array + * @var mixed[][] */ public $queries = []; @@ -47,25 +23,23 @@ class DebugStack implements SQLLogger */ public $enabled = true; - /** - * @var float|null - */ + /** @var float|null */ public $start = null; - /** - * @var int - */ + /** @var int */ public $currentQuery = 0; /** * {@inheritdoc} */ - public function startQuery($sql, array $params = null, array $types = null) + public function startQuery($sql, ?array $params = null, ?array $types = null) { - if ($this->enabled) { - $this->start = microtime(true); - $this->queries[++$this->currentQuery] = ['sql' => $sql, 'params' => $params, 'types' => $types, 'executionMS' => 0]; + if (! $this->enabled) { + return; } + + $this->start = microtime(true); + $this->queries[++$this->currentQuery] = ['sql' => $sql, 'params' => $params, 'types' => $types, 'executionMS' => 0]; } /** @@ -73,8 +47,10 @@ public function startQuery($sql, array $params = null, array $types = null) */ public function stopQuery() { - if ($this->enabled) { - $this->queries[$this->currentQuery]['executionMS'] = microtime(true) - $this->start; + if (! $this->enabled) { + return; } + + $this->queries[$this->currentQuery]['executionMS'] = microtime(true) - $this->start; } } diff --git a/lib/Doctrine/DBAL/Logging/EchoSQLLogger.php b/lib/Doctrine/DBAL/Logging/EchoSQLLogger.php index a6c1ae5ea0b..657abb4d378 100644 --- a/lib/Doctrine/DBAL/Logging/EchoSQLLogger.php +++ b/lib/Doctrine/DBAL/Logging/EchoSQLLogger.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Logging; @@ -24,20 +7,13 @@ /** * A SQL logger that logs to the standard output using echo/var_dump. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class EchoSQLLogger implements SQLLogger { /** * {@inheritdoc} */ - public function startQuery($sql, array $params = null, array $types = null) + public function startQuery($sql, ?array $params = null, ?array $types = null) { echo $sql . PHP_EOL; @@ -45,9 +21,11 @@ public function startQuery($sql, array $params = null, array $types = null) var_dump($params); } - if ($types) { - var_dump($types); + if (! $types) { + return; } + + var_dump($types); } /** diff --git a/lib/Doctrine/DBAL/Logging/LoggerChain.php b/lib/Doctrine/DBAL/Logging/LoggerChain.php index fee05a4a004..2b5404b25c7 100644 --- a/lib/Doctrine/DBAL/Logging/LoggerChain.php +++ b/lib/Doctrine/DBAL/Logging/LoggerChain.php @@ -1,43 +1,18 @@ . - */ namespace Doctrine\DBAL\Logging; /** * Chains multiple SQLLogger. - * - * @link www.doctrine-project.org - * @since 2.2 - * @author Christophe Coevoet */ class LoggerChain implements SQLLogger { - /** - * @var \Doctrine\DBAL\Logging\SQLLogger[] - */ + /** @var SQLLogger[] */ private $loggers = []; /** * Adds a logger in the chain. * - * @param \Doctrine\DBAL\Logging\SQLLogger $logger - * * @return void */ public function addLogger(SQLLogger $logger) @@ -48,7 +23,7 @@ public function addLogger(SQLLogger $logger) /** * {@inheritdoc} */ - public function startQuery($sql, array $params = null, array $types = null) + public function startQuery($sql, ?array $params = null, ?array $types = null) { foreach ($this->loggers as $logger) { $logger->startQuery($sql, $params, $types); diff --git a/lib/Doctrine/DBAL/Logging/SQLLogger.php b/lib/Doctrine/DBAL/Logging/SQLLogger.php index 52491e50fe6..2e94611b6a2 100644 --- a/lib/Doctrine/DBAL/Logging/SQLLogger.php +++ b/lib/Doctrine/DBAL/Logging/SQLLogger.php @@ -1,46 +1,22 @@ . - */ namespace Doctrine\DBAL\Logging; /** * Interface for SQL loggers. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ interface SQLLogger { /** * Logs a SQL statement somewhere. * - * @param string $sql The SQL to be executed. - * @param array|null $params The SQL parameters. - * @param array|null $types The SQL parameter types. + * @param string $sql The SQL to be executed. + * @param mixed[]|null $params The SQL parameters. + * @param int[]|string[]|null $types The SQL parameter types. * * @return void */ - public function startQuery($sql, array $params = null, array $types = null); + public function startQuery($sql, ?array $params = null, ?array $types = null); /** * Marks the last started query as stopped. This can be used for timing of queries. diff --git a/lib/Doctrine/DBAL/ParameterType.php b/lib/Doctrine/DBAL/ParameterType.php index be5413e61bb..422fee895ee 100644 --- a/lib/Doctrine/DBAL/ParameterType.php +++ b/lib/Doctrine/DBAL/ParameterType.php @@ -2,6 +2,8 @@ namespace Doctrine\DBAL; +use PDO; + /** * Contains statement parameter types. */ @@ -12,35 +14,35 @@ final class ParameterType * * @see \PDO::PARAM_NULL */ - public const NULL = \PDO::PARAM_NULL; + public const NULL = PDO::PARAM_NULL; /** * Represents the SQL INTEGER data type. * * @see \PDO::PARAM_INT */ - public const INTEGER = \PDO::PARAM_INT; + public const INTEGER = PDO::PARAM_INT; /** * Represents the SQL CHAR, VARCHAR, or other string data type. * * @see \PDO::PARAM_STR */ - public const STRING = \PDO::PARAM_STR; + public const STRING = PDO::PARAM_STR; /** * Represents the SQL large object data type. * * @see \PDO::PARAM_LOB */ - public const LARGE_OBJECT = \PDO::PARAM_LOB; + public const LARGE_OBJECT = PDO::PARAM_LOB; /** * Represents a boolean data type. * * @see \PDO::PARAM_BOOL */ - public const BOOLEAN = \PDO::PARAM_BOOL; + public const BOOLEAN = PDO::PARAM_BOOL; /** * Represents a binary string data type. diff --git a/lib/Doctrine/DBAL/Platforms/AbstractPlatform.php b/lib/Doctrine/DBAL/Platforms/AbstractPlatform.php index a9dbebe48c0..5e4537391ed 100644 --- a/lib/Doctrine/DBAL/Platforms/AbstractPlatform.php +++ b/lib/Doctrine/DBAL/Platforms/AbstractPlatform.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms; @@ -30,6 +13,7 @@ use Doctrine\DBAL\Event\SchemaCreateTableEventArgs; use Doctrine\DBAL\Event\SchemaDropTableEventArgs; use Doctrine\DBAL\Events; +use Doctrine\DBAL\Platforms\Keywords\KeywordList; use Doctrine\DBAL\Schema\Column; use Doctrine\DBAL\Schema\ColumnDiff; use Doctrine\DBAL\Schema\Constraint; @@ -42,6 +26,7 @@ use Doctrine\DBAL\TransactionIsolationLevel; use Doctrine\DBAL\Types; use Doctrine\DBAL\Types\Type; +use InvalidArgumentException; use const E_USER_DEPRECATED; use function addcslashes; use function array_map; @@ -53,14 +38,12 @@ use function func_get_arg; use function func_get_args; use function func_num_args; -use function get_class; use function implode; use function in_array; use function is_array; use function is_bool; use function is_int; use function is_string; -use function join; use function preg_quote; use function preg_replace; use function sprintf; @@ -76,26 +59,13 @@ * point of abstraction of platform-specific behaviors, features and SQL dialects. * They are a passive source of information. * - * @link www.doctrine-project.org - * @since 2.0 - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * @author Lukas Smith (PEAR MDB2 library) - * @author Benjamin Eberlei - * @todo Remove any unnecessary methods. + * @todo Remove any unnecessary methods. */ abstract class AbstractPlatform { - /** - * @var int - */ - const CREATE_INDEXES = 1; + public const CREATE_INDEXES = 1; - /** - * @var int - */ - const CREATE_FOREIGNKEYS = 2; + public const CREATE_FOREIGNKEYS = 2; /** * @deprecated Use DateIntervalUnit::INTERVAL_UNIT_SECOND. @@ -138,69 +108,52 @@ abstract class AbstractPlatform public const DATE_INTERVAL_UNIT_YEAR = DateIntervalUnit::YEAR; /** - * @var int - * * @deprecated Use TrimMode::UNSPECIFIED. */ public const TRIM_UNSPECIFIED = TrimMode::UNSPECIFIED; /** - * @var int - * * @deprecated Use TrimMode::LEADING. */ public const TRIM_LEADING = TrimMode::LEADING; /** - * @var int - * * @deprecated Use TrimMode::TRAILING. */ public const TRIM_TRAILING = TrimMode::TRAILING; /** - * @var int - * * @deprecated Use TrimMode::BOTH. */ public const TRIM_BOTH = TrimMode::BOTH; - /** - * @var array|null - */ + /** @var string[]|null */ protected $doctrineTypeMapping = null; /** * Contains a list of all columns that should generate parseable column comments for type-detection * in reverse engineering scenarios. * - * @var array|null + * @var string[]|null */ protected $doctrineTypeComments = null; - /** - * @var \Doctrine\Common\EventManager - */ + /** @var EventManager */ protected $_eventManager; /** * Holds the KeywordList instance for the current platform. * - * @var \Doctrine\DBAL\Platforms\Keywords\KeywordList + * @var KeywordList */ protected $_keywords; - /** - * Constructor. - */ public function __construct() { } /** * Sets the EventManager used by the Platform. - * - * @param \Doctrine\Common\EventManager $eventManager */ public function setEventManager(EventManager $eventManager) { @@ -210,7 +163,7 @@ public function setEventManager(EventManager $eventManager) /** * Gets the EventManager used by the Platform. * - * @return \Doctrine\Common\EventManager + * @return EventManager */ public function getEventManager() { @@ -220,7 +173,7 @@ public function getEventManager() /** * Returns the SQL snippet that declares a boolean column. * - * @param array $columnDef + * @param mixed[] $columnDef * * @return string */ @@ -229,7 +182,7 @@ abstract public function getBooleanTypeDeclarationSQL(array $columnDef); /** * Returns the SQL snippet that declares a 4 byte integer column. * - * @param array $columnDef + * @param mixed[] $columnDef * * @return string */ @@ -238,7 +191,7 @@ abstract public function getIntegerTypeDeclarationSQL(array $columnDef); /** * Returns the SQL snippet that declares an 8 byte integer column. * - * @param array $columnDef + * @param mixed[] $columnDef * * @return string */ @@ -247,7 +200,7 @@ abstract public function getBigIntTypeDeclarationSQL(array $columnDef); /** * Returns the SQL snippet that declares a 2 byte integer column. * - * @param array $columnDef + * @param mixed[] $columnDef * * @return string */ @@ -256,7 +209,7 @@ abstract public function getSmallIntTypeDeclarationSQL(array $columnDef); /** * Returns the SQL snippet that declares common properties of an integer column. * - * @param array $columnDef + * @param mixed[] $columnDef * * @return string */ @@ -289,13 +242,13 @@ private function initializeAllDoctrineTypeMappings() /** * Returns the SQL snippet used to declare a VARCHAR column type. * - * @param array $field + * @param mixed[] $field * * @return string */ public function getVarcharTypeDeclarationSQL(array $field) { - if ( !isset($field['length'])) { + if (! isset($field['length'])) { $field['length'] = $this->getVarcharDefaultLength(); } @@ -315,13 +268,13 @@ public function getVarcharTypeDeclarationSQL(array $field) /** * Returns the SQL snippet used to declare a BINARY/VARBINARY column type. * - * @param array $field The column definition. + * @param mixed[] $field The column definition. * * @return string */ public function getBinaryTypeDeclarationSQL(array $field) { - if ( ! isset($field['length'])) { + if (! isset($field['length'])) { $field['length'] = $this->getBinaryDefaultLength(); } @@ -350,7 +303,7 @@ public function getBinaryTypeDeclarationSQL(array $field) * By default this maps directly to a CHAR(36) and only maps to more * special datatypes when the underlying databases support this datatype. * - * @param array $field + * @param mixed[] $field * * @return string */ @@ -368,7 +321,7 @@ public function getGuidTypeDeclarationSQL(array $field) * By default this maps directly to a CLOB and only maps to more * special datatypes when the underlying databases support this datatype. * - * @param array $field + * @param mixed[] $field * * @return string */ @@ -383,7 +336,7 @@ public function getJsonTypeDeclarationSQL(array $field) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed) { @@ -398,7 +351,7 @@ protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed) { @@ -408,7 +361,7 @@ protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed) /** * Returns the SQL snippet used to declare a CLOB column type. * - * @param array $field + * @param mixed[] $field * * @return string */ @@ -417,7 +370,7 @@ abstract public function getClobTypeDeclarationSQL(array $field); /** * Returns the SQL Snippet used to declare a BLOB column type. * - * @param array $field + * @param mixed[] $field * * @return string */ @@ -436,7 +389,7 @@ abstract public function getName(); * @param string $dbType * @param string $doctrineType * - * @throws \Doctrine\DBAL\DBALException If the type is not found. + * @throws DBALException If the type is not found. */ public function registerDoctrineTypeMapping($dbType, $doctrineType) { @@ -444,18 +397,20 @@ public function registerDoctrineTypeMapping($dbType, $doctrineType) $this->initializeAllDoctrineTypeMappings(); } - if (!Types\Type::hasType($doctrineType)) { + if (! Types\Type::hasType($doctrineType)) { throw DBALException::typeNotFound($doctrineType); } - $dbType = strtolower($dbType); + $dbType = strtolower($dbType); $this->doctrineTypeMapping[$dbType] = $doctrineType; $doctrineType = Type::getType($doctrineType); - if ($doctrineType->requiresSQLCommentHint($this)) { - $this->markDoctrineTypeCommented($doctrineType); + if (! $doctrineType->requiresSQLCommentHint($this)) { + return; } + + $this->markDoctrineTypeCommented($doctrineType); } /** @@ -465,7 +420,7 @@ public function registerDoctrineTypeMapping($dbType, $doctrineType) * * @return string * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ public function getDoctrineTypeMapping($dbType) { @@ -475,8 +430,8 @@ public function getDoctrineTypeMapping($dbType) $dbType = strtolower($dbType); - if (!isset($this->doctrineTypeMapping[$dbType])) { - throw new \Doctrine\DBAL\DBALException("Unknown database type ".$dbType." requested, " . get_class($this) . " may not support it."); + if (! isset($this->doctrineTypeMapping[$dbType])) { + throw new DBALException('Unknown database type ' . $dbType . ' requested, ' . static::class . ' may not support it.'); } return $this->doctrineTypeMapping[$dbType]; @@ -512,17 +467,17 @@ protected function initializeCommentedDoctrineTypes() foreach (Type::getTypesMap() as $typeName => $className) { $type = Type::getType($typeName); - if ($type->requiresSQLCommentHint($this)) { - $this->doctrineTypeComments[] = $typeName; + if (! $type->requiresSQLCommentHint($this)) { + continue; } + + $this->doctrineTypeComments[] = $typeName; } } /** * Is it necessary for the platform to add a parsable type comment to allow reverse engineering the given type? * - * @param \Doctrine\DBAL\Types\Type $doctrineType - * * @return bool */ public function isCommentedDoctrineType(Type $doctrineType) @@ -537,7 +492,7 @@ public function isCommentedDoctrineType(Type $doctrineType) /** * Marks this type as to be commented in ALTER TABLE and CREATE TABLE statements. * - * @param string|\Doctrine\DBAL\Types\Type $doctrineType + * @param string|Type $doctrineType * * @return void */ @@ -553,8 +508,6 @@ public function markDoctrineTypeCommented($doctrineType) /** * Gets the comment to append to a column comment that helps parsing this type in reverse engineering. * - * @param \Doctrine\DBAL\Types\Type $doctrineType - * * @return string */ public function getDoctrineTypeComment(Type $doctrineType) @@ -565,8 +518,6 @@ public function getDoctrineTypeComment(Type $doctrineType) /** * Gets the comment of a passed column modified by potential doctrine type comment hints. * - * @param \Doctrine\DBAL\Schema\Column $column - * * @return string */ protected function getColumnComment(Column $column) @@ -597,7 +548,7 @@ public function getIdentifierQuoteCharacter() */ public function getSqlCommentStartString() { - return "--"; + return '--'; } /** @@ -661,7 +612,7 @@ public function getBinaryDefaultLength() /** * Gets all SQL wildcard characters of the platform. * - * @return array + * @return string[] */ public function getWildcards() { @@ -673,7 +624,7 @@ public function getWildcards() * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getRegexpExpression() { @@ -683,11 +634,11 @@ public function getRegexpExpression() /** * Returns the global unique identifier expression. * - * @return string + * @deprecated Use application-generated UUIDs instead * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @return string * - * @deprecated Use application-generated UUIDs instead + * @throws DBALException If not supported on this platform. */ public function getGuidExpression() { @@ -711,7 +662,7 @@ public function getAvgExpression($column) * * If a '*' is used instead of a column the number of selected rows is returned. * - * @param string|integer $column The column to use. + * @param string|int $column The column to use. * * @return string Generated SQL including a COUNT aggregate function. */ @@ -919,7 +870,7 @@ public function getLowerExpression($str) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getLocateExpression($str, $substr, $startPos = false) { @@ -967,7 +918,7 @@ public function getSubstringExpression($value, $from, $length = null) */ public function getConcatExpression() { - return join(' || ', func_get_args()); + return implode(' || ', func_get_args()); } /** @@ -1031,7 +982,7 @@ public function getIsNotNullExpression($expression) */ public function getBetweenExpression($expression, $value1, $value2) { - return $expression . ' BETWEEN ' .$value1 . ' AND ' . $value2; + return $expression . ' BETWEEN ' . $value1 . ' AND ' . $value2; } /** @@ -1090,7 +1041,7 @@ public function getCosExpression($value) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateDiffExpression($date1, $date2) { @@ -1105,7 +1056,7 @@ public function getDateDiffExpression($date1, $date2) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateAddSecondsExpression($date, $seconds) { @@ -1120,7 +1071,7 @@ public function getDateAddSecondsExpression($date, $seconds) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateSubSecondsExpression($date, $seconds) { @@ -1135,7 +1086,7 @@ public function getDateSubSecondsExpression($date, $seconds) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateAddMinutesExpression($date, $minutes) { @@ -1150,7 +1101,7 @@ public function getDateAddMinutesExpression($date, $minutes) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateSubMinutesExpression($date, $minutes) { @@ -1165,7 +1116,7 @@ public function getDateSubMinutesExpression($date, $minutes) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateAddHourExpression($date, $hours) { @@ -1180,7 +1131,7 @@ public function getDateAddHourExpression($date, $hours) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateSubHourExpression($date, $hours) { @@ -1195,7 +1146,7 @@ public function getDateSubHourExpression($date, $hours) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateAddDaysExpression($date, $days) { @@ -1210,7 +1161,7 @@ public function getDateAddDaysExpression($date, $days) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateSubDaysExpression($date, $days) { @@ -1225,7 +1176,7 @@ public function getDateSubDaysExpression($date, $days) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateAddWeeksExpression($date, $weeks) { @@ -1240,7 +1191,7 @@ public function getDateAddWeeksExpression($date, $weeks) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateSubWeeksExpression($date, $weeks) { @@ -1255,7 +1206,7 @@ public function getDateSubWeeksExpression($date, $weeks) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateAddMonthExpression($date, $months) { @@ -1270,7 +1221,7 @@ public function getDateAddMonthExpression($date, $months) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateSubMonthExpression($date, $months) { @@ -1285,7 +1236,7 @@ public function getDateSubMonthExpression($date, $months) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateAddQuartersExpression($date, $quarters) { @@ -1300,7 +1251,7 @@ public function getDateAddQuartersExpression($date, $quarters) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateSubQuartersExpression($date, $quarters) { @@ -1315,7 +1266,7 @@ public function getDateSubQuartersExpression($date, $quarters) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateAddYearsExpression($date, $years) { @@ -1330,7 +1281,7 @@ public function getDateAddYearsExpression($date, $years) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateSubYearsExpression($date, $years) { @@ -1348,7 +1299,7 @@ public function getDateSubYearsExpression($date, $years) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit) { @@ -1445,11 +1396,11 @@ public function getDropDatabaseSQL($database) /** * Returns the SQL snippet to drop an existing table. * - * @param \Doctrine\DBAL\Schema\Table|string $table + * @param Table|string $table * * @return string * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function getDropTableSQL($table) { @@ -1457,11 +1408,13 @@ public function getDropTableSQL($table) if ($table instanceof Table) { $table = $table->getQuotedName($this); - } elseif (!is_string($table)) { - throw new \InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.'); } - if (null !== $this->_eventManager && $this->_eventManager->hasListeners(Events::onSchemaDropTable)) { + if (! is_string($table)) { + throw new InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.'); + } + + if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaDropTable)) { $eventArgs = new SchemaDropTableEventArgs($tableArg, $this); $this->_eventManager->dispatchEvent(Events::onSchemaDropTable, $eventArgs); @@ -1476,7 +1429,7 @@ public function getDropTableSQL($table) /** * Returns the SQL to safely drop a temporary table WITHOUT implicitly committing an open transaction. * - * @param \Doctrine\DBAL\Schema\Table|string $table + * @param Table|string $table * * @return string */ @@ -1488,19 +1441,19 @@ public function getDropTemporaryTableSQL($table) /** * Returns the SQL to drop an index from a table. * - * @param \Doctrine\DBAL\Schema\Index|string $index - * @param \Doctrine\DBAL\Schema\Table|string $table + * @param Index|string $index + * @param Table|string $table * * @return string * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function getDropIndexSQL($index, $table = null) { if ($index instanceof Index) { $index = $index->getQuotedName($this); - } elseif (!is_string($index)) { - throw new \InvalidArgumentException('AbstractPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.'); + } elseif (! is_string($index)) { + throw new InvalidArgumentException('AbstractPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.'); } return 'DROP INDEX ' . $index; @@ -1509,8 +1462,8 @@ public function getDropIndexSQL($index, $table = null) /** * Returns the SQL to drop a constraint. * - * @param \Doctrine\DBAL\Schema\Constraint|string $constraint - * @param \Doctrine\DBAL\Schema\Table|string $table + * @param Constraint|string $constraint + * @param Table|string $table * * @return string */ @@ -1525,7 +1478,7 @@ public function getDropConstraintSQL($constraint, $table) } $constraint = $constraint->getQuotedName($this); - $table = $table->getQuotedName($this); + $table = $table->getQuotedName($this); return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $constraint; } @@ -1533,8 +1486,8 @@ public function getDropConstraintSQL($constraint, $table) /** * Returns the SQL to drop a foreign key. * - * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint|string $foreignKey - * @param \Doctrine\DBAL\Schema\Table|string $table + * @param ForeignKeyConstraint|string $foreignKey + * @param Table|string $table * * @return string */ @@ -1549,7 +1502,7 @@ public function getDropForeignKeySQL($foreignKey, $table) } $foreignKey = $foreignKey->getQuotedName($this); - $table = $table->getQuotedName($this); + $table = $table->getQuotedName($this); return 'ALTER TABLE ' . $table . ' DROP FOREIGN KEY ' . $foreignKey; } @@ -1558,33 +1511,32 @@ public function getDropForeignKeySQL($foreignKey, $table) * Returns the SQL statement(s) to create a table with the specified name, columns and constraints * on this platform. * - * @param \Doctrine\DBAL\Schema\Table $table - * @param int $createFlags + * @param int $createFlags * - * @return array The sequence of SQL statements. + * @return string[] The sequence of SQL statements. * - * @throws \Doctrine\DBAL\DBALException - * @throws \InvalidArgumentException + * @throws DBALException + * @throws InvalidArgumentException */ public function getCreateTableSQL(Table $table, $createFlags = self::CREATE_INDEXES) { - if ( ! is_int($createFlags)) { - throw new \InvalidArgumentException("Second argument of AbstractPlatform::getCreateTableSQL() has to be integer."); + if (! is_int($createFlags)) { + throw new InvalidArgumentException('Second argument of AbstractPlatform::getCreateTableSQL() has to be integer.'); } if (count($table->getColumns()) === 0) { throw DBALException::noColumnsSpecifiedForTable($table->getName()); } - $tableName = $table->getQuotedName($this); - $options = $table->getOptions(); + $tableName = $table->getQuotedName($this); + $options = $table->getOptions(); $options['uniqueConstraints'] = []; - $options['indexes'] = []; - $options['primary'] = []; + $options['indexes'] = []; + $options['primary'] = []; if (($createFlags&self::CREATE_INDEXES) > 0) { foreach ($table->getIndexes() as $index) { - /* @var $index Index */ + /** @var $index Index */ if ($index->isPrimary()) { $options['primary'] = $index->getQuotedColumns($this); $options['primary_index'] = $index; @@ -1595,12 +1547,10 @@ public function getCreateTableSQL(Table $table, $createFlags = self::CREATE_INDE } $columnSql = []; - $columns = []; + $columns = []; foreach ($table->getColumns() as $column) { - /* @var \Doctrine\DBAL\Schema\Column $column */ - - if (null !== $this->_eventManager && $this->_eventManager->hasListeners(Events::onSchemaCreateTableColumn)) { + if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaCreateTableColumn)) { $eventArgs = new SchemaCreateTableColumnEventArgs($column, $table, $this); $this->_eventManager->dispatchEvent(Events::onSchemaCreateTableColumn, $eventArgs); @@ -1611,9 +1561,9 @@ public function getCreateTableSQL(Table $table, $createFlags = self::CREATE_INDE } } - $columnData = $column->toArray(); - $columnData['name'] = $column->getQuotedName($this); - $columnData['version'] = $column->hasPlatformOption("version") ? $column->getPlatformOption('version') : false; + $columnData = $column->toArray(); + $columnData['name'] = $column->getQuotedName($this); + $columnData['version'] = $column->hasPlatformOption('version') ? $column->getPlatformOption('version') : false; $columnData['comment'] = $this->getColumnComment($column); if ($columnData['type'] instanceof Types\StringType && $columnData['length'] === null) { @@ -1634,7 +1584,7 @@ public function getCreateTableSQL(Table $table, $createFlags = self::CREATE_INDE } } - if (null !== $this->_eventManager && $this->_eventManager->hasListeners(Events::onSchemaCreateTable)) { + if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaCreateTable)) { $eventArgs = new SchemaCreateTableEventArgs($table, $columns, $options, $this); $this->_eventManager->dispatchEvent(Events::onSchemaCreateTable, $eventArgs); @@ -1648,9 +1598,11 @@ public function getCreateTableSQL(Table $table, $createFlags = self::CREATE_INDE foreach ($table->getColumns() as $column) { $comment = $this->getColumnComment($column); - if (null !== $comment && '' !== $comment) { - $sql[] = $this->getCommentOnColumnSQL($tableName, $column->getQuotedName($this), $comment); + if ($comment === null || $comment === '') { + continue; } + + $sql[] = $this->getCommentOnColumnSQL($tableName, $column->getQuotedName($this), $comment); } } @@ -1666,12 +1618,16 @@ public function getCreateTableSQL(Table $table, $createFlags = self::CREATE_INDE */ public function getCommentOnColumnSQL($tableName, $columnName, $comment) { - $tableName = new Identifier($tableName); + $tableName = new Identifier($tableName); $columnName = new Identifier($columnName); - $comment = $this->quoteStringLiteral($comment); + $comment = $this->quoteStringLiteral($comment); - return "COMMENT ON COLUMN " . $tableName->getQuotedName($this) . "." . $columnName->getQuotedName($this) . - " IS " . $comment; + return sprintf( + 'COMMENT ON COLUMN %s.%s IS %s', + $tableName->getQuotedName($this), + $columnName->getQuotedName($this), + $comment + ); } /** @@ -1681,7 +1637,7 @@ public function getCommentOnColumnSQL($tableName, $columnName, $comment) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getInlineColumnCommentSQL($comment) { @@ -1689,17 +1645,17 @@ public function getInlineColumnCommentSQL($comment) throw DBALException::notSupported(__METHOD__); } - return "COMMENT " . $this->quoteStringLiteral($comment); + return 'COMMENT ' . $this->quoteStringLiteral($comment); } /** * Returns the SQL used to create a table. * - * @param string $tableName - * @param array $columns - * @param array $options + * @param string $tableName + * @param mixed[][] $columns + * @param mixed[] $options * - * @return array + * @return string[] */ protected function _getCreateTableSQL($tableName, array $columns, array $options = []) { @@ -1724,7 +1680,7 @@ protected function _getCreateTableSQL($tableName, array $columns, array $options $query = 'CREATE TABLE ' . $tableName . ' (' . $columnListSql; $check = $this->getCheckDeclarationSQL($columns); - if ( ! empty($check)) { + if (! empty($check)) { $query .= ', ' . $check; } $query .= ')'; @@ -1745,17 +1701,15 @@ protected function _getCreateTableSQL($tableName, array $columns, array $options */ public function getCreateTemporaryTableSnippetSQL() { - return "CREATE TEMPORARY TABLE"; + return 'CREATE TEMPORARY TABLE'; } /** * Returns the SQL to create a sequence on this platform. * - * @param \Doctrine\DBAL\Schema\Sequence $sequence - * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getCreateSequenceSQL(Sequence $sequence) { @@ -1765,11 +1719,9 @@ public function getCreateSequenceSQL(Sequence $sequence) /** * Returns the SQL to change a sequence on this platform. * - * @param \Doctrine\DBAL\Schema\Sequence $sequence - * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getAlterSequenceSQL(Sequence $sequence) { @@ -1779,12 +1731,11 @@ public function getAlterSequenceSQL(Sequence $sequence) /** * Returns the SQL to create a constraint on a table on this platform. * - * @param \Doctrine\DBAL\Schema\Constraint $constraint - * @param \Doctrine\DBAL\Schema\Table|string $table + * @param Table|string $table * * @return string * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function getCreateConstraintSQL(Constraint $constraint, $table) { @@ -1794,7 +1745,7 @@ public function getCreateConstraintSQL(Constraint $constraint, $table) $query = 'ALTER TABLE ' . $table . ' ADD CONSTRAINT ' . $constraint->getQuotedName($this); - $columnList = '('. implode(', ', $constraint->getQuotedColumns($this)) . ')'; + $columnList = '(' . implode(', ', $constraint->getQuotedColumns($this)) . ')'; $referencesClause = ''; if ($constraint instanceof Index) { @@ -1803,7 +1754,7 @@ public function getCreateConstraintSQL(Constraint $constraint, $table) } elseif ($constraint->isUnique()) { $query .= ' UNIQUE'; } else { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Can only create primary or unique constraints, no common indexes with getCreateConstraintSQL().' ); } @@ -1813,7 +1764,7 @@ public function getCreateConstraintSQL(Constraint $constraint, $table) $referencesClause = ' REFERENCES ' . $constraint->getQuotedForeignTableName($this) . ' (' . implode(', ', $constraint->getQuotedForeignColumns($this)) . ')'; } - $query .= ' '.$columnList.$referencesClause; + $query .= ' ' . $columnList . $referencesClause; return $query; } @@ -1821,31 +1772,30 @@ public function getCreateConstraintSQL(Constraint $constraint, $table) /** * Returns the SQL to create an index on a table on this platform. * - * @param \Doctrine\DBAL\Schema\Index $index - * @param \Doctrine\DBAL\Schema\Table|string $table The name of the table on which the index is to be created. + * @param Table|string $table The name of the table on which the index is to be created. * * @return string * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function getCreateIndexSQL(Index $index, $table) { if ($table instanceof Table) { $table = $table->getQuotedName($this); } - $name = $index->getQuotedName($this); - $columns = $index->getQuotedColumns($this); + $name = $index->getQuotedName($this); + $columns = $index->getColumns(); - if (count($columns) == 0) { - throw new \InvalidArgumentException("Incomplete definition. 'columns' required."); + if (count($columns) === 0) { + throw new InvalidArgumentException("Incomplete definition. 'columns' required."); } if ($index->isPrimary()) { return $this->getCreatePrimaryKeySQL($index, $table); } - $query = 'CREATE ' . $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name . ' ON ' . $table; - $query .= ' (' . $this->getIndexFieldDeclarationListSQL($columns) . ')' . $this->getPartialIndexSQL($index); + $query = 'CREATE ' . $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name . ' ON ' . $table; + $query .= ' (' . $this->getIndexFieldDeclarationListSQL($index) . ')' . $this->getPartialIndexSQL($index); return $query; } @@ -1853,14 +1803,12 @@ public function getCreateIndexSQL(Index $index, $table) /** * Adds condition for partial index. * - * @param \Doctrine\DBAL\Schema\Index $index - * * @return string */ protected function getPartialIndexSQL(Index $index) { if ($this->supportsPartialIndexes() && $index->hasOption('where')) { - return ' WHERE ' . $index->getOption('where'); + return ' WHERE ' . $index->getOption('where'); } return ''; @@ -1869,8 +1817,6 @@ protected function getPartialIndexSQL(Index $index) /** * Adds additional flags for index generation. * - * @param \Doctrine\DBAL\Schema\Index $index - * * @return string */ protected function getCreateIndexSQLFlags(Index $index) @@ -1881,14 +1827,13 @@ protected function getCreateIndexSQLFlags(Index $index) /** * Returns the SQL to create an unnamed primary key constraint. * - * @param \Doctrine\DBAL\Schema\Index $index - * @param \Doctrine\DBAL\Schema\Table|string $table + * @param Table|string $table * * @return string */ public function getCreatePrimaryKeySQL(Index $index, $table) { - return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY (' . $this->getIndexFieldDeclarationListSQL($index->getQuotedColumns($this)) . ')'; + return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY (' . $this->getIndexFieldDeclarationListSQL($index) . ')'; } /** @@ -1897,7 +1842,8 @@ public function getCreatePrimaryKeySQL(Index $index, $table) * @param string $schemaName * * @return string - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * + * @throws DBALException If not supported on this platform. */ public function getCreateSchemaSQL($schemaName) { @@ -1919,10 +1865,10 @@ public function getCreateSchemaSQL($schemaName) */ public function quoteIdentifier($str) { - if (strpos($str, ".") !== false) { - $parts = array_map([$this, "quoteSingleIdentifier"], explode(".", $str)); + if (strpos($str, '.') !== false) { + $parts = array_map([$this, 'quoteSingleIdentifier'], explode('.', $str)); - return implode(".", $parts); + return implode('.', $parts); } return $this->quoteSingleIdentifier($str); @@ -1939,14 +1885,14 @@ public function quoteSingleIdentifier($str) { $c = $this->getIdentifierQuoteCharacter(); - return $c . str_replace($c, $c.$c, $str) . $c; + return $c . str_replace($c, $c . $c, $str) . $c; } /** * Returns the SQL to create a new foreign key. * - * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey The foreign key constraint. - * @param \Doctrine\DBAL\Schema\Table|string $table The name of the table on which the foreign key is to be created. + * @param ForeignKeyConstraint $foreignKey The foreign key constraint. + * @param Table|string $table The name of the table on which the foreign key is to be created. * * @return string */ @@ -1956,9 +1902,7 @@ public function getCreateForeignKeySQL(ForeignKeyConstraint $foreignKey, $table) $table = $table->getQuotedName($this); } - $query = 'ALTER TABLE ' . $table . ' ADD ' . $this->getForeignKeyDeclarationSQL($foreignKey); - - return $query; + return 'ALTER TABLE ' . $table . ' ADD ' . $this->getForeignKeyDeclarationSQL($foreignKey); } /** @@ -1966,11 +1910,9 @@ public function getCreateForeignKeySQL(ForeignKeyConstraint $foreignKey, $table) * * This method returns an array of SQL statements, since some platforms need several statements. * - * @param \Doctrine\DBAL\Schema\TableDiff $diff - * - * @return array + * @return string[] * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getAlterTableSQL(TableDiff $diff) { @@ -1978,19 +1920,17 @@ public function getAlterTableSQL(TableDiff $diff) } /** - * @param \Doctrine\DBAL\Schema\Column $column - * @param \Doctrine\DBAL\Schema\TableDiff $diff - * @param array $columnSql + * @param mixed[] $columnSql * * @return bool */ protected function onSchemaAlterTableAddColumn(Column $column, TableDiff $diff, &$columnSql) { - if (null === $this->_eventManager) { + if ($this->_eventManager === null) { return false; } - if ( ! $this->_eventManager->hasListeners(Events::onSchemaAlterTableAddColumn)) { + if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableAddColumn)) { return false; } @@ -2003,19 +1943,17 @@ protected function onSchemaAlterTableAddColumn(Column $column, TableDiff $diff, } /** - * @param \Doctrine\DBAL\Schema\Column $column - * @param \Doctrine\DBAL\Schema\TableDiff $diff - * @param array $columnSql + * @param string[] $columnSql * * @return bool */ protected function onSchemaAlterTableRemoveColumn(Column $column, TableDiff $diff, &$columnSql) { - if (null === $this->_eventManager) { + if ($this->_eventManager === null) { return false; } - if ( ! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRemoveColumn)) { + if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRemoveColumn)) { return false; } @@ -2028,19 +1966,17 @@ protected function onSchemaAlterTableRemoveColumn(Column $column, TableDiff $dif } /** - * @param \Doctrine\DBAL\Schema\ColumnDiff $columnDiff - * @param \Doctrine\DBAL\Schema\TableDiff $diff - * @param array $columnSql + * @param string[] $columnSql * * @return bool */ protected function onSchemaAlterTableChangeColumn(ColumnDiff $columnDiff, TableDiff $diff, &$columnSql) { - if (null === $this->_eventManager) { + if ($this->_eventManager === null) { return false; } - if ( ! $this->_eventManager->hasListeners(Events::onSchemaAlterTableChangeColumn)) { + if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableChangeColumn)) { return false; } @@ -2053,20 +1989,18 @@ protected function onSchemaAlterTableChangeColumn(ColumnDiff $columnDiff, TableD } /** - * @param string $oldColumnName - * @param \Doctrine\DBAL\Schema\Column $column - * @param \Doctrine\DBAL\Schema\TableDiff $diff - * @param array $columnSql + * @param string $oldColumnName + * @param string[] $columnSql * * @return bool */ protected function onSchemaAlterTableRenameColumn($oldColumnName, Column $column, TableDiff $diff, &$columnSql) { - if (null === $this->_eventManager) { + if ($this->_eventManager === null) { return false; } - if ( ! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRenameColumn)) { + if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRenameColumn)) { return false; } @@ -2079,18 +2013,17 @@ protected function onSchemaAlterTableRenameColumn($oldColumnName, Column $column } /** - * @param \Doctrine\DBAL\Schema\TableDiff $diff - * @param array $sql + * @param string[] $sql * * @return bool */ protected function onSchemaAlterTable(TableDiff $diff, &$sql) { - if (null === $this->_eventManager) { + if ($this->_eventManager === null) { return false; } - if ( ! $this->_eventManager->hasListeners(Events::onSchemaAlterTable)) { + if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTable)) { return false; } @@ -2103,9 +2036,7 @@ protected function onSchemaAlterTable(TableDiff $diff, &$sql) } /** - * @param \Doctrine\DBAL\Schema\TableDiff $diff - * - * @return array + * @return string[] */ protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) { @@ -2132,13 +2063,11 @@ protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) } /** - * @param \Doctrine\DBAL\Schema\TableDiff $diff - * - * @return array + * @return string[] */ protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff) { - $tableName = (false !== $diff->newName) + $tableName = $diff->newName !== false ? $diff->getNewName()->getQuotedName($this) : $diff->getName($this)->getQuotedName($this); @@ -2176,26 +2105,24 @@ protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff) /** * Returns the SQL for renaming an index on a table. * - * @param string $oldIndexName The name of the index to rename from. - * @param \Doctrine\DBAL\Schema\Index $index The definition of the index to rename to. - * @param string $tableName The table to rename the given index on. + * @param string $oldIndexName The name of the index to rename from. + * @param Index $index The definition of the index to rename to. + * @param string $tableName The table to rename the given index on. * - * @return array The sequence of SQL statements for renaming the given index. + * @return string[] The sequence of SQL statements for renaming the given index. */ protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName) { return [ $this->getDropIndexSQL($oldIndexName, $tableName), - $this->getCreateIndexSQL($index, $tableName) + $this->getCreateIndexSQL($index, $tableName), ]; } /** * Common code for alter table statement generation that updates the changed Index and Foreign Key definitions. * - * @param \Doctrine\DBAL\Schema\TableDiff $diff - * - * @return array + * @return string[] */ protected function _getAlterTableIndexForeignKeySQL(TableDiff $diff) { @@ -2205,11 +2132,11 @@ protected function _getAlterTableIndexForeignKeySQL(TableDiff $diff) /** * Gets declaration of a number of fields in bulk. * - * @param array $fields A multidimensional associative array. - * The first dimension determines the field name, while the second - * dimension is keyed with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param mixed[][] $fields A multidimensional associative array. + * The first dimension determines the field name, while the second + * dimension is keyed with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -2246,10 +2173,10 @@ public function getColumnDeclarationListSQL(array $fields) * Obtains DBMS specific SQL code portion needed to declare a generic type * field to be used in statements like CREATE TABLE. * - * @param string $name The name the field to be declared. - * @param array $field An associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param string $name The name the field to be declared. + * @param mixed[] $field An associative array with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -2282,21 +2209,21 @@ public function getColumnDeclarationSQL($name, array $field) } else { $default = $this->getDefaultValueDeclarationSQL($field); - $charset = (isset($field['charset']) && $field['charset']) ? + $charset = isset($field['charset']) && $field['charset'] ? ' ' . $this->getColumnCharsetDeclarationSQL($field['charset']) : ''; - $collation = (isset($field['collation']) && $field['collation']) ? + $collation = isset($field['collation']) && $field['collation'] ? ' ' . $this->getColumnCollationDeclarationSQL($field['collation']) : ''; - $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : ''; + $notnull = isset($field['notnull']) && $field['notnull'] ? ' NOT NULL' : ''; - $unique = (isset($field['unique']) && $field['unique']) ? + $unique = isset($field['unique']) && $field['unique'] ? ' ' . $this->getUniqueFieldDeclarationSQL() : ''; - $check = (isset($field['check']) && $field['check']) ? + $check = isset($field['check']) && $field['check'] ? ' ' . $field['check'] : ''; - $typeDecl = $field['type']->getSQLDeclaration($field, $this); + $typeDecl = $field['type']->getSQLDeclaration($field, $this); $columnDef = $typeDecl . $charset . $default . $notnull . $unique . $check . $collation; if ($this->supportsInlineColumnComments() && isset($field['comment']) && $field['comment'] !== '') { @@ -2310,15 +2237,15 @@ public function getColumnDeclarationSQL($name, array $field) /** * Returns the SQL snippet that declares a floating point column of arbitrary precision. * - * @param array $columnDef + * @param mixed[] $columnDef * * @return string */ public function getDecimalTypeDeclarationSQL(array $columnDef) { - $columnDef['precision'] = ( ! isset($columnDef['precision']) || empty($columnDef['precision'])) + $columnDef['precision'] = ! isset($columnDef['precision']) || empty($columnDef['precision']) ? 10 : $columnDef['precision']; - $columnDef['scale'] = ( ! isset($columnDef['scale']) || empty($columnDef['scale'])) + $columnDef['scale'] = ! isset($columnDef['scale']) || empty($columnDef['scale']) ? 0 : $columnDef['scale']; return 'NUMERIC(' . $columnDef['precision'] . ', ' . $columnDef['scale'] . ')'; @@ -2328,19 +2255,19 @@ public function getDecimalTypeDeclarationSQL(array $columnDef) * Obtains DBMS specific SQL code portion needed to set a default value * declaration to be used in statements like CREATE TABLE. * - * @param array $field The field definition array. + * @param mixed[] $field The field definition array. * * @return string DBMS specific SQL code portion needed to set a default value. */ public function getDefaultValueDeclarationSQL($field) { - if ( ! isset($field['default'])) { + if (! isset($field['default'])) { return empty($field['notnull']) ? ' DEFAULT NULL' : ''; } $default = $field['default']; - if ( ! isset($field['type'])) { + if (! isset($field['type'])) { return " DEFAULT '" . $default . "'"; } @@ -2373,7 +2300,7 @@ public function getDefaultValueDeclarationSQL($field) * Obtains DBMS specific SQL code portion needed to set a CHECK constraint * declaration to be used in statements like CREATE TABLE. * - * @param array $definition The check definition. + * @param mixed[][] $definition The check definition. * * @return string DBMS specific SQL code portion needed to set a CHECK constraint. */ @@ -2401,24 +2328,24 @@ public function getCheckDeclarationSQL(array $definition) * Obtains DBMS specific SQL code portion needed to set a unique * constraint declaration to be used in statements like CREATE TABLE. * - * @param string $name The name of the unique constraint. - * @param \Doctrine\DBAL\Schema\Index $index The index definition. + * @param string $name The name of the unique constraint. + * @param Index $index The index definition. * * @return string DBMS specific SQL code portion needed to set a constraint. * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function getUniqueConstraintDeclarationSQL($name, Index $index) { - $columns = $index->getQuotedColumns($this); - $name = new Identifier($name); + $columns = $index->getColumns(); + $name = new Identifier($name); if (count($columns) === 0) { - throw new \InvalidArgumentException("Incomplete definition. 'columns' required."); + throw new InvalidArgumentException("Incomplete definition. 'columns' required."); } return 'CONSTRAINT ' . $name->getQuotedName($this) . ' UNIQUE (' - . $this->getIndexFieldDeclarationListSQL($columns) + . $this->getIndexFieldDeclarationListSQL($index) . ')' . $this->getPartialIndexSQL($index); } @@ -2426,24 +2353,24 @@ public function getUniqueConstraintDeclarationSQL($name, Index $index) * Obtains DBMS specific SQL code portion needed to set an index * declaration to be used in statements like CREATE TABLE. * - * @param string $name The name of the index. - * @param \Doctrine\DBAL\Schema\Index $index The index definition. + * @param string $name The name of the index. + * @param Index $index The index definition. * * @return string DBMS specific SQL code portion needed to set an index. * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function getIndexDeclarationSQL($name, Index $index) { - $columns = $index->getQuotedColumns($this); - $name = new Identifier($name); + $columns = $index->getColumns(); + $name = new Identifier($name); if (count($columns) === 0) { - throw new \InvalidArgumentException("Incomplete definition. 'columns' required."); + throw new InvalidArgumentException("Incomplete definition. 'columns' required."); } return $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name->getQuotedName($this) . ' (' - . $this->getIndexFieldDeclarationListSQL($columns) + . $this->getIndexFieldDeclarationListSQL($index) . ')' . $this->getPartialIndexSQL($index); } @@ -2452,7 +2379,7 @@ public function getIndexDeclarationSQL($name, Index $index) * e.g. when a field has the "columnDefinition" keyword. * Only "AUTOINCREMENT" and "PRIMARY KEY" are added if appropriate. * - * @param array $columnDef + * @param mixed[] $columnDef * * @return string */ @@ -2465,17 +2392,23 @@ public function getCustomTypeDeclarationSQL(array $columnDef) * Obtains DBMS specific SQL code portion needed to set an index * declaration to be used in statements like CREATE TABLE. * - * @param array $fields - * - * @return string + * @param mixed[]|Index $columnsOrIndex array declaration is deprecated, prefer passing Index to this method */ - public function getIndexFieldDeclarationListSQL(array $fields) + public function getIndexFieldDeclarationListSQL($columnsOrIndex) : string { + if ($columnsOrIndex instanceof Index) { + return implode(', ', $columnsOrIndex->getQuotedColumns($this)); + } + + if (! is_array($columnsOrIndex)) { + throw new InvalidArgumentException('Fields argument should be an Index or array.'); + } + $ret = []; - foreach ($fields as $field => $definition) { + foreach ($columnsOrIndex as $column => $definition) { if (is_array($definition)) { - $ret[] = $field; + $ret[] = $column; } else { $ret[] = $definition; } @@ -2519,8 +2452,6 @@ public function getTemporaryTableName($tableName) * Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint * of a field declaration to be used in statements like CREATE TABLE. * - * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey - * * @return string DBMS specific SQL code portion needed to set the FOREIGN KEY constraint * of a field declaration. */ @@ -2536,7 +2467,7 @@ public function getForeignKeyDeclarationSQL(ForeignKeyConstraint $foreignKey) * Returns the FOREIGN KEY query section dealing with non-standard options * as MATCH, INITIALLY DEFERRED, ON UPDATE, ... * - * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey The foreign key definition. + * @param ForeignKeyConstraint $foreignKey The foreign key definition. * * @return string */ @@ -2560,7 +2491,7 @@ public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey * * @return string * - * @throws \InvalidArgumentException if unknown referential action given + * @throws InvalidArgumentException If unknown referential action given. */ public function getForeignKeyReferentialActionSQL($action) { @@ -2573,7 +2504,7 @@ public function getForeignKeyReferentialActionSQL($action) case 'SET DEFAULT': return $upper; default: - throw new \InvalidArgumentException('Invalid foreign key action: ' . $upper); + throw new InvalidArgumentException('Invalid foreign key action: ' . $upper); } } @@ -2581,11 +2512,9 @@ public function getForeignKeyReferentialActionSQL($action) * Obtains DBMS specific SQL code portion needed to set the FOREIGN KEY constraint * of a field declaration to be used in statements like CREATE TABLE. * - * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey - * * @return string * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function getForeignKeyBaseDeclarationSQL(ForeignKeyConstraint $foreignKey) { @@ -2596,21 +2525,19 @@ public function getForeignKeyBaseDeclarationSQL(ForeignKeyConstraint $foreignKey $sql .= 'FOREIGN KEY ('; if (count($foreignKey->getLocalColumns()) === 0) { - throw new \InvalidArgumentException("Incomplete definition. 'local' required."); + throw new InvalidArgumentException("Incomplete definition. 'local' required."); } if (count($foreignKey->getForeignColumns()) === 0) { - throw new \InvalidArgumentException("Incomplete definition. 'foreign' required."); + throw new InvalidArgumentException("Incomplete definition. 'foreign' required."); } if (strlen($foreignKey->getForeignTableName()) === 0) { - throw new \InvalidArgumentException("Incomplete definition. 'foreignTable' required."); + throw new InvalidArgumentException("Incomplete definition. 'foreignTable' required."); } - $sql .= implode(', ', $foreignKey->getQuotedLocalColumns($this)) + return $sql . implode(', ', $foreignKey->getQuotedLocalColumns($this)) . ') REFERENCES ' . $foreignKey->getQuotedForeignTableName($this) . ' (' . implode(', ', $foreignKey->getQuotedForeignColumns($this)) . ')'; - - return $sql; } /** @@ -2693,9 +2620,11 @@ public function convertBooleans($item) { if (is_array($item)) { foreach ($item as $k => $value) { - if (is_bool($value)) { - $item[$k] = (int) $value; + if (! is_bool($value)) { + continue; } + + $item[$k] = (int) $value; } } elseif (is_bool($item)) { $item = (int) $item; @@ -2715,7 +2644,7 @@ public function convertBooleans($item) */ public function convertFromBoolean($item) { - return null === $item ? null: (bool) $item ; + return $item === null ? null: (bool) $item; } /** @@ -2770,7 +2699,7 @@ public function getCurrentTimestampSQL() * * @return string * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ protected function _getTransactionIsolationLevelSQL($level) { @@ -2784,14 +2713,14 @@ protected function _getTransactionIsolationLevelSQL($level) case TransactionIsolationLevel::SERIALIZABLE: return 'SERIALIZABLE'; default: - throw new \InvalidArgumentException('Invalid isolation level:' . $level); + throw new InvalidArgumentException('Invalid isolation level:' . $level); } } /** * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getListDatabasesSQL() { @@ -2803,7 +2732,7 @@ public function getListDatabasesSQL() * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getListNamespacesSQL() { @@ -2815,7 +2744,7 @@ public function getListNamespacesSQL() * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getListSequencesSQL($database) { @@ -2827,7 +2756,7 @@ public function getListSequencesSQL($database) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getListTableConstraintsSQL($table) { @@ -2840,7 +2769,7 @@ public function getListTableConstraintsSQL($table) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getListTableColumnsSQL($table, $database = null) { @@ -2850,7 +2779,7 @@ public function getListTableColumnsSQL($table, $database = null) /** * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getListTablesSQL() { @@ -2860,7 +2789,7 @@ public function getListTablesSQL() /** * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getListUsersSQL() { @@ -2874,7 +2803,7 @@ public function getListUsersSQL() * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getListViewsSQL($database) { @@ -2896,7 +2825,7 @@ public function getListViewsSQL($database) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getListTableIndexesSQL($table, $currentDatabase = null) { @@ -2908,7 +2837,7 @@ public function getListTableIndexesSQL($table, $currentDatabase = null) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getListTableForeignKeysSQL($table) { @@ -2921,7 +2850,7 @@ public function getListTableForeignKeysSQL($table) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getCreateViewSQL($name, $sql) { @@ -2933,7 +2862,7 @@ public function getCreateViewSQL($name, $sql) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDropViewSQL($name) { @@ -2947,7 +2876,7 @@ public function getDropViewSQL($name) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDropSequenceSQL($sequence) { @@ -2959,7 +2888,7 @@ public function getDropSequenceSQL($sequence) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getSequenceNextValSQL($sequenceName) { @@ -2973,7 +2902,7 @@ public function getSequenceNextValSQL($sequenceName) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getCreateDatabaseSQL($database) { @@ -2987,7 +2916,7 @@ public function getCreateDatabaseSQL($database) * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getSetTransactionIsolationSQL($level) { @@ -2998,11 +2927,11 @@ public function getSetTransactionIsolationSQL($level) * Obtains DBMS specific SQL to be used to create datetime fields in * statements like CREATE TABLE. * - * @param array $fieldDeclaration + * @param mixed[] $fieldDeclaration * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration) { @@ -3012,7 +2941,7 @@ public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration) /** * Obtains DBMS specific SQL to be used to create datetime with timezone offset fields. * - * @param array $fieldDeclaration + * @param mixed[] $fieldDeclaration * * @return string */ @@ -3026,11 +2955,11 @@ public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration) * Obtains DBMS specific SQL to be used to create date fields in statements * like CREATE TABLE. * - * @param array $fieldDeclaration + * @param mixed[] $fieldDeclaration * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDateTypeDeclarationSQL(array $fieldDeclaration) { @@ -3041,11 +2970,11 @@ public function getDateTypeDeclarationSQL(array $fieldDeclaration) * Obtains DBMS specific SQL to be used to create time fields in statements * like CREATE TABLE. * - * @param array $fieldDeclaration + * @param mixed[] $fieldDeclaration * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getTimeTypeDeclarationSQL(array $fieldDeclaration) { @@ -3053,7 +2982,7 @@ public function getTimeTypeDeclarationSQL(array $fieldDeclaration) } /** - * @param array $fieldDeclaration + * @param mixed[] $fieldDeclaration * * @return string */ @@ -3065,9 +2994,9 @@ public function getFloatDeclarationSQL(array $fieldDeclaration) /** * Gets the default transaction isolation level of the platform. * - * @return int The default isolation level. - * * @see TransactionIsolationLevel + * + * @return int The default isolation level. */ public function getDefaultTransactionIsolationLevel() { @@ -3116,14 +3045,14 @@ public function usesSequenceEmulatedIdentityColumns() /** * Returns the name of the sequence for a particular identity column in a particular table. * + * @see usesSequenceEmulatedIdentityColumns + * * @param string $tableName The name of the table to return the sequence name for. * @param string $columnName The name of the identity column in the table to return the sequence name for. * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. - * - * @see usesSequenceEmulatedIdentityColumns + * @throws DBALException If not supported on this platform. */ public function getIdentitySequenceName($tableName, $columnName) { @@ -3150,6 +3079,14 @@ public function supportsPartialIndexes() return false; } + /** + * Whether the platform supports indexes with column length definitions. + */ + public function supportsColumnLengthIndexes() : bool + { + return false; + } + /** * Whether the platform supports altering tables. * @@ -3217,7 +3154,7 @@ public function supportsForeignKeyConstraints() */ public function supportsForeignKeyOnUpdate() { - return ($this->supportsForeignKeyConstraints() && true); + return $this->supportsForeignKeyConstraints() && true; } /** @@ -3249,7 +3186,7 @@ public function canEmulateSchemas() * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ public function getDefaultSchemaName() { @@ -3320,11 +3257,12 @@ public function hasNativeJsonType() /** * @deprecated + * * @todo Remove in 3.0 */ public function getIdentityColumnNullInsertSQL() { - return ""; + return ''; } /** @@ -3576,9 +3514,9 @@ public function rollbackSavePoint($savepoint) /** * Returns the keyword list instance of this platform. * - * @return \Doctrine\DBAL\Platforms\Keywords\KeywordList + * @return KeywordList * - * @throws \Doctrine\DBAL\DBALException If no keyword list is specified. + * @throws DBALException If no keyword list is specified. */ final public function getReservedKeywordsList() { @@ -3587,9 +3525,9 @@ final public function getReservedKeywordsList() return $this->_keywords; } - $class = $this->getReservedKeywordsClass(); - $keywords = new $class; - if ( ! $keywords instanceof \Doctrine\DBAL\Platforms\Keywords\KeywordList) { + $class = $this->getReservedKeywordsClass(); + $keywords = new $class(); + if (! $keywords instanceof KeywordList) { throw DBALException::notSupported(__METHOD__); } @@ -3604,7 +3542,7 @@ final public function getReservedKeywordsList() * * @return string * - * @throws \Doctrine\DBAL\DBALException If not supported on this platform. + * @throws DBALException If not supported on this platform. */ protected function getReservedKeywordsClass() { diff --git a/lib/Doctrine/DBAL/Platforms/DB2Platform.php b/lib/Doctrine/DBAL/Platforms/DB2Platform.php index b83c8f1dc7e..605122115d4 100644 --- a/lib/Doctrine/DBAL/Platforms/DB2Platform.php +++ b/lib/Doctrine/DBAL/Platforms/DB2Platform.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms; @@ -195,7 +178,7 @@ public function getSmallIntTypeDeclarationSQL(array $columnDef) protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) { $autoinc = ''; - if ( ! empty($columnDef['autoincrement'])) { + if (! empty($columnDef['autoincrement'])) { $autoinc = ' GENERATED BY DEFAULT AS IDENTITY'; } @@ -251,8 +234,8 @@ public function getDateDiffExpression($date1, $date2) */ public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration) { - if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] == true) { - return "TIMESTAMP(0) WITH DEFAULT"; + if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] === true) { + return 'TIMESTAMP(0) WITH DEFAULT'; } return 'TIMESTAMP(0)'; @@ -287,8 +270,6 @@ public function getTruncateTableSQL($tableName, $cascade = false) /** * This code fragment is originally from the Zend_Db_Adapter_Db2 class, but has been edited. * - * @license New BSD License - * * @param string $table * @param string $database * @@ -331,7 +312,7 @@ public function getListTableColumnsSQL($table, $database = null) ON (c.tabschema = k.tabschema AND c.tabname = k.tabname AND c.colname = k.colname) - WHERE UPPER(c.tabname) = UPPER(" . $table . ") + WHERE UPPER(c.tabname) = UPPER(" . $table . ') ORDER BY c.colno ) subq JOIN syscat.columns cols @@ -339,7 +320,7 @@ public function getListTableColumnsSQL($table, $database = null) AND subq.tabname = cols.tabname AND subq.colno = cols.colno ORDER BY subq.colno - "; + '; } /** @@ -355,7 +336,7 @@ public function getListTablesSQL() */ public function getListViewsSQL($database) { - return "SELECT NAME, TEXT FROM SYSIBM.SYSVIEWS"; + return 'SELECT NAME, TEXT FROM SYSIBM.SYSVIEWS'; } /** @@ -378,8 +359,8 @@ public function getListTableIndexesSQL($table, $currentDatabase = null) FROM SYSCAT.INDEXES AS idx JOIN SYSCAT.INDEXCOLUSE AS idxcol ON idx.INDSCHEMA = idxcol.INDSCHEMA AND idx.INDNAME = idxcol.INDNAME - WHERE idx.TABNAME = UPPER(" . $table . ") - ORDER BY idxcol.COLSEQ ASC"; + WHERE idx.TABNAME = UPPER(" . $table . ') + ORDER BY idxcol.COLSEQ ASC'; } /** @@ -412,8 +393,8 @@ public function getListTableForeignKeysSQL($table) ON fk.REFKEYNAME = pkcol.CONSTNAME AND fk.REFTABSCHEMA = pkcol.TABSCHEMA AND fk.REFTABNAME = pkcol.TABNAME - WHERE fk.TABNAME = UPPER(" . $table . ") - ORDER BY fkcol.COLSEQ ASC"; + WHERE fk.TABNAME = UPPER(" . $table . ') + ORDER BY fkcol.COLSEQ ASC'; } /** @@ -421,7 +402,7 @@ public function getListTableForeignKeysSQL($table) */ public function getCreateViewSQL($name, $sql) { - return "CREATE VIEW ".$name." AS ".$sql; + return 'CREATE VIEW ' . $name . ' AS ' . $sql; } /** @@ -429,7 +410,7 @@ public function getCreateViewSQL($name, $sql) */ public function getDropViewSQL($name) { - return "DROP VIEW ".$name; + return 'DROP VIEW ' . $name; } /** @@ -437,7 +418,7 @@ public function getDropViewSQL($name) */ public function getCreateDatabaseSQL($database) { - return "CREATE DATABASE ".$database; + return 'CREATE DATABASE ' . $database; } /** @@ -445,7 +426,7 @@ public function getCreateDatabaseSQL($database) */ public function getDropDatabaseSQL($database) { - return "DROP DATABASE " . $database; + return 'DROP DATABASE ' . $database; } /** @@ -493,7 +474,7 @@ public function getCurrentTimeSQL() */ public function getCurrentTimestampSQL() { - return "CURRENT TIMESTAMP"; + return 'CURRENT TIMESTAMP'; } /** @@ -529,8 +510,8 @@ protected function _getCreateTableSQL($tableName, array $columns, array $options */ public function getAlterTableSQL(TableDiff $diff) { - $sql = []; - $columnSql = []; + $sql = []; + $columnSql = []; $commentsSQL = []; $queryParts = []; @@ -543,7 +524,7 @@ public function getAlterTableSQL(TableDiff $diff) $queryPart = 'ADD COLUMN ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnDef); // Adding non-nullable columns to a table requires a default value to be specified. - if ( ! empty($columnDef['notnull']) && + if (! empty($columnDef['notnull']) && ! isset($columnDef['default']) && empty($columnDef['autoincrement']) ) { @@ -554,13 +535,15 @@ public function getAlterTableSQL(TableDiff $diff) $comment = $this->getColumnComment($column); - if (null !== $comment && '' !== $comment) { - $commentsSQL[] = $this->getCommentOnColumnSQL( - $diff->getName($this)->getQuotedName($this), - $column->getQuotedName($this), - $comment - ); + if ($comment === null || $comment === '') { + continue; } + + $commentsSQL[] = $this->getCommentOnColumnSQL( + $diff->getName($this)->getQuotedName($this), + $column->getQuotedName($this), + $comment + ); } foreach ($diff->removedColumns as $column) { @@ -604,13 +587,13 @@ public function getAlterTableSQL(TableDiff $diff) $tableSql = []; - if ( ! $this->onSchemaAlterTable($diff, $tableSql)) { + if (! $this->onSchemaAlterTable($diff, $tableSql)) { if (count($queryParts) > 0) { - $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(" ", $queryParts); + $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(' ', $queryParts); } // Some table alteration operations require a table reorganization. - if ( ! empty($diff->removedColumns) || ! empty($diff->changedColumns)) { + if (! empty($diff->removedColumns) || ! empty($diff->changedColumns)) { $sql[] = "CALL SYSPROC.ADMIN_CMD ('REORG TABLE " . $diff->getName($this)->getQuotedName($this) . "')"; } @@ -635,8 +618,8 @@ public function getAlterTableSQL(TableDiff $diff) * * @param Table $table The table to gather the SQL for. * @param ColumnDiff $columnDiff The column diff to evaluate. - * @param array $sql The sequence of table alteration statements to fill. - * @param array $queryParts The sequence of column alteration clauses to fill. + * @param string[] $sql The sequence of table alteration statements to fill. + * @param mixed[] $queryParts The sequence of column alteration clauses to fill. */ private function gatherAlterColumnSQL(Table $table, ColumnDiff $columnDiff, array &$sql, array &$queryParts) { @@ -666,7 +649,7 @@ private function gatherAlterColumnSQL(Table $table, ColumnDiff $columnDiff, arra * * @param ColumnDiff $columnDiff The column diff to evaluate. * - * @return array + * @return string[] */ private function getAlterColumnClausesSQL(ColumnDiff $columnDiff) { @@ -713,12 +696,12 @@ private function getAlterColumnClausesSQL(ColumnDiff $columnDiff) */ protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) { - $sql = []; + $sql = []; $table = $diff->getName($this)->getQuotedName($this); foreach ($diff->removedIndexes as $remKey => $remIndex) { foreach ($diff->addedIndexes as $addKey => $addIndex) { - if ($remIndex->getColumns() == $addIndex->getColumns()) { + if ($remIndex->getColumns() === $addIndex->getColumns()) { if ($remIndex->isPrimary()) { $sql[] = 'ALTER TABLE ' . $table . ' DROP PRIMARY KEY'; } elseif ($remIndex->isUnique()) { @@ -747,7 +730,7 @@ protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName) { if (strpos($tableName, '.') !== false) { - list($schema) = explode('.', $tableName); + [$schema] = explode('.', $tableName); $oldIndexName = $schema . '.' . $oldIndexName; } @@ -759,13 +742,13 @@ protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName) */ public function getDefaultValueDeclarationSQL($field) { - if ( ! empty($field['autoincrement'])) { + if (! empty($field['autoincrement'])) { return ''; } if (isset($field['version']) && $field['version']) { - if ((string) $field['type'] != "DateTime") { - $field['default'] = "1"; + if ((string) $field['type'] !== 'DateTime') { + $field['default'] = '1'; } } @@ -785,7 +768,7 @@ public function getEmptyIdentityInsertSQL($tableName, $identifierColumnName) */ public function getCreateTemporaryTableSnippetSQL() { - return "DECLARE GLOBAL TEMPORARY TABLE"; + return 'DECLARE GLOBAL TEMPORARY TABLE'; } /** @@ -793,7 +776,7 @@ public function getCreateTemporaryTableSnippetSQL() */ public function getTemporaryTableName($tableName) { - return "SESSION." . $tableName; + return 'SESSION.' . $tableName; } /** @@ -828,11 +811,11 @@ protected function doModifyLimitQuery($query, $limit, $offset = null) */ public function getLocateExpression($str, $substr, $startPos = false) { - if ($startPos == false) { + if ($startPos === false) { return 'LOCATE(' . $substr . ', ' . $str . ')'; } - return 'LOCATE(' . $substr . ', ' . $str . ', '.$startPos.')'; + return 'LOCATE(' . $substr . ', ' . $str . ', ' . $startPos . ')'; } /** diff --git a/lib/Doctrine/DBAL/Platforms/DrizzlePlatform.php b/lib/Doctrine/DBAL/Platforms/DrizzlePlatform.php index d8a4d092019..27aacf42286 100644 --- a/lib/Doctrine/DBAL/Platforms/DrizzlePlatform.php +++ b/lib/Doctrine/DBAL/Platforms/DrizzlePlatform.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms; @@ -24,6 +7,7 @@ use Doctrine\DBAL\Schema\Table; use Doctrine\DBAL\Schema\TableDiff; use Doctrine\DBAL\Types\BinaryType; +use InvalidArgumentException; use function array_merge; use function array_unique; use function array_values; @@ -34,14 +18,11 @@ use function is_bool; use function is_numeric; use function is_string; -use function join; use function sprintf; use function trim; /** * Drizzle platform - * - * @author Kim Hemsø Rasmussen */ class DrizzlePlatform extends AbstractPlatform { @@ -68,7 +49,7 @@ public function getConcatExpression() { $args = func_get_args(); - return 'CONCAT(' . join(', ', (array) $args) . ')'; + return 'CONCAT(' . implode(', ', (array) $args) . ')'; } /** @@ -76,7 +57,7 @@ public function getConcatExpression() */ protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit) { - $function = '+' === $operator ? 'DATE_ADD' : 'DATE_SUB'; + $function = $operator === '+' ? 'DATE_ADD' : 'DATE_SUB'; return $function . '(' . $date . ', INTERVAL ' . $interval . ' ' . $unit . ')'; } @@ -111,7 +92,7 @@ public function getIntegerTypeDeclarationSQL(array $field) protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) { $autoinc = ''; - if ( ! empty($columnDef['autoincrement'])) { + if (! empty($columnDef['autoincrement'])) { $autoinc = ' AUTO_INCREMENT'; } @@ -226,13 +207,13 @@ protected function _getCreateTableSQL($tableName, array $columns, array $options // attach all primary keys if (isset($options['primary']) && ! empty($options['primary'])) { - $keyColumns = array_unique(array_values($options['primary'])); + $keyColumns = array_unique(array_values($options['primary'])); $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')'; } $query = 'CREATE '; - if (!empty($options['temporary'])) { + if (! empty($options['temporary'])) { $query .= 'TEMPORARY '; } @@ -254,7 +235,7 @@ protected function _getCreateTableSQL($tableName, array $columns, array $options /** * Build SQL for table options * - * @param array $options + * @param mixed[] $options * * @return string */ @@ -267,14 +248,14 @@ private function buildTableOptions(array $options) $tableOptions = []; // Collate - if ( ! isset($options['collate'])) { + if (! isset($options['collate'])) { $options['collate'] = 'utf8_unicode_ci'; } $tableOptions[] = sprintf('COLLATE %s', $options['collate']); // Engine - if ( ! isset($options['engine'])) { + if (! isset($options['engine'])) { $options['engine'] = 'InnoDB'; } @@ -289,7 +270,7 @@ private function buildTableOptions(array $options) if (isset($options['comment'])) { $comment = trim($options['comment'], " '"); - $tableOptions[] = sprintf("COMMENT = %s ", $this->quoteStringLiteral($comment)); + $tableOptions[] = sprintf('COMMENT = %s ', $this->quoteStringLiteral($comment)); } // Row format @@ -303,13 +284,13 @@ private function buildTableOptions(array $options) /** * Build SQL for partition options. * - * @param array $options + * @param mixed[] $options * * @return string */ private function buildPartitionOptions(array $options) { - return (isset($options['partition_options'])) + return isset($options['partition_options']) ? ' ' . $options['partition_options'] : ''; } @@ -344,15 +325,15 @@ public function getListTablesSQL() public function getListTableColumnsSQL($table, $database = null) { if ($database) { - $database = "'" . $database . "'"; + $databaseSQL = $this->quoteStringLiteral($database); } else { - $database = 'DATABASE()'; + $databaseSQL = 'DATABASE()'; } - return "SELECT COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT, IS_NULLABLE, IS_AUTO_INCREMENT, CHARACTER_MAXIMUM_LENGTH, COLUMN_DEFAULT," . - " NUMERIC_PRECISION, NUMERIC_SCALE, COLLATION_NAME" . - " FROM DATA_DICTIONARY.COLUMNS" . - " WHERE TABLE_SCHEMA=" . $database . " AND TABLE_NAME = '" . $table . "'"; + return 'SELECT COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT, IS_NULLABLE, IS_AUTO_INCREMENT, CHARACTER_MAXIMUM_LENGTH, COLUMN_DEFAULT,' . + ' NUMERIC_PRECISION, NUMERIC_SCALE, COLLATION_NAME' . + ' FROM DATA_DICTIONARY.COLUMNS' . + ' WHERE TABLE_SCHEMA=' . $databaseSQL . ' AND TABLE_NAME = ' . $this->quoteStringLiteral($table); } /** @@ -361,14 +342,14 @@ public function getListTableColumnsSQL($table, $database = null) public function getListTableForeignKeysSQL($table, $database = null) { if ($database) { - $database = "'" . $database . "'"; + $databaseSQL = $this->quoteStringLiteral($database); } else { - $database = 'DATABASE()'; + $databaseSQL = 'DATABASE()'; } - return "SELECT CONSTRAINT_NAME, CONSTRAINT_COLUMNS, REFERENCED_TABLE_NAME, REFERENCED_TABLE_COLUMNS, UPDATE_RULE, DELETE_RULE" . - " FROM DATA_DICTIONARY.FOREIGN_KEYS" . - " WHERE CONSTRAINT_SCHEMA=" . $database . " AND CONSTRAINT_TABLE='" . $table . "'"; + return 'SELECT CONSTRAINT_NAME, CONSTRAINT_COLUMNS, REFERENCED_TABLE_NAME, REFERENCED_TABLE_COLUMNS, UPDATE_RULE, DELETE_RULE' . + ' FROM DATA_DICTIONARY.FOREIGN_KEYS' . + ' WHERE CONSTRAINT_SCHEMA=' . $databaseSQL . ' AND CONSTRAINT_TABLE=' . $this->quoteStringLiteral($table); } /** @@ -377,14 +358,14 @@ public function getListTableForeignKeysSQL($table, $database = null) public function getListTableIndexesSQL($table, $database = null) { if ($database) { - $database = "'" . $database . "'"; + $databaseSQL = $this->quoteStringLiteral($database); } else { - $database = 'DATABASE()'; + $databaseSQL = 'DATABASE()'; } return "SELECT INDEX_NAME AS 'key_name', COLUMN_NAME AS 'column_name', IS_USED_IN_PRIMARY AS 'primary', IS_UNIQUE=0 AS 'non_unique'" . - " FROM DATA_DICTIONARY.INDEX_PARTS" . - " WHERE TABLE_SCHEMA=" . $database . " AND TABLE_NAME='" . $table . "'"; + ' FROM DATA_DICTIONARY.INDEX_PARTS' . + ' WHERE TABLE_SCHEMA=' . $databaseSQL . ' AND TABLE_NAME=' . $this->quoteStringLiteral($table); } /** @@ -430,20 +411,20 @@ public function supportsColumnCollation() /** * {@inheritDoc} */ - public function getDropIndexSQL($index, $table=null) + public function getDropIndexSQL($index, $table = null) { if ($index instanceof Index) { $indexName = $index->getQuotedName($this); } elseif (is_string($index)) { $indexName = $index; } else { - throw new \InvalidArgumentException('DrizzlePlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.'); + throw new InvalidArgumentException('DrizzlePlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.'); } if ($table instanceof Table) { $table = $table->getQuotedName($this); - } elseif (!is_string($table)) { - throw new \InvalidArgumentException('DrizzlePlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.'); + } elseif (! is_string($table)) { + throw new InvalidArgumentException('DrizzlePlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.'); } if ($index instanceof Index && $index->isPrimary()) { @@ -468,7 +449,7 @@ protected function getDropPrimaryKeySQL($table) */ public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration) { - if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] == true) { + if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] === true) { return 'TIMESTAMP'; } @@ -496,7 +477,7 @@ public function getDateTypeDeclarationSQL(array $fieldDeclaration) */ public function getAlterTableSQL(TableDiff $diff) { - $columnSql = []; + $columnSql = []; $queryParts = []; if ($diff->newName !== false) { @@ -508,9 +489,9 @@ public function getAlterTableSQL(TableDiff $diff) continue; } - $columnArray = $column->toArray(); + $columnArray = $column->toArray(); $columnArray['comment'] = $this->getColumnComment($column); - $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray); + $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray); } foreach ($diff->removedColumns as $column) { @@ -526,8 +507,7 @@ public function getAlterTableSQL(TableDiff $diff) continue; } - /* @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */ - $column = $columnDiff->column; + $column = $columnDiff->column; $columnArray = $column->toArray(); // Do not generate column alteration clause if type is binary and only fixed property has changed. @@ -541,7 +521,7 @@ public function getAlterTableSQL(TableDiff $diff) } $columnArray['comment'] = $this->getColumnComment($column); - $queryParts[] = 'CHANGE ' . ($columnDiff->getOldColumnName()->getQuotedName($this)) . ' ' + $queryParts[] = 'CHANGE ' . ($columnDiff->getOldColumnName()->getQuotedName($this)) . ' ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray); } @@ -552,18 +532,18 @@ public function getAlterTableSQL(TableDiff $diff) $oldColumnName = new Identifier($oldColumnName); - $columnArray = $column->toArray(); + $columnArray = $column->toArray(); $columnArray['comment'] = $this->getColumnComment($column); - $queryParts[] = 'CHANGE ' . $oldColumnName->getQuotedName($this) . ' ' + $queryParts[] = 'CHANGE ' . $oldColumnName->getQuotedName($this) . ' ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray); } - $sql = []; + $sql = []; $tableSql = []; - if ( ! $this->onSchemaAlterTable($diff, $tableSql)) { + if (! $this->onSchemaAlterTable($diff, $tableSql)) { if (count($queryParts) > 0) { - $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(", ", $queryParts); + $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(', ', $queryParts); } $sql = array_merge( $this->getPreAlterTableIndexForeignKeySQL($diff), @@ -582,8 +562,8 @@ public function getDropTemporaryTableSQL($table) { if ($table instanceof Table) { $table = $table->getQuotedName($this); - } elseif (!is_string($table)) { - throw new \InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.'); + } elseif (! is_string($table)) { + throw new InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.'); } return 'DROP TEMPORARY TABLE ' . $table; @@ -596,12 +576,14 @@ public function convertBooleans($item) { if (is_array($item)) { foreach ($item as $key => $value) { - if (is_bool($value) || is_numeric($item)) { - $item[$key] = ($value) ? 'true' : 'false'; + if (! is_bool($value) && ! is_numeric($item)) { + continue; } + + $item[$key] = $value ? 'true' : 'false'; } } elseif (is_bool($item) || is_numeric($item)) { - $item = ($item) ? 'true' : 'false'; + $item = $item ? 'true' : 'false'; } return $item; @@ -612,11 +594,11 @@ public function convertBooleans($item) */ public function getLocateExpression($str, $substr, $startPos = false) { - if ($startPos == false) { + if ($startPos === false) { return 'LOCATE(' . $substr . ', ' . $str . ')'; } - return 'LOCATE(' . $substr . ', ' . $str . ', '.$startPos.')'; + return 'LOCATE(' . $substr . ', ' . $str . ', ' . $startPos . ')'; } /** diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/DB2Keywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/DB2Keywords.php index 884cc8ec775..8533f579d71 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/DB2Keywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/DB2Keywords.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; /** * DB2 Keywords. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ class DB2Keywords extends KeywordList { diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/DrizzleKeywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/DrizzleKeywords.php index 46c8b246339..70f69f44b0b 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/DrizzleKeywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/DrizzleKeywords.php @@ -1,28 +1,9 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; /** * Drizzle Keywordlist. - * - * @author Kim Hemsø Rasmussen */ class DrizzleKeywords extends KeywordList { diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/KeywordList.php b/lib/Doctrine/DBAL/Platforms/Keywords/KeywordList.php index e8933a3860d..860d9f21099 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/KeywordList.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/KeywordList.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; @@ -25,16 +8,10 @@ /** * Abstract interface for a SQL reserved keyword dictionary. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ abstract class KeywordList { - /** - * @var array|null - */ + /** @var string[]|null */ private $keywords = null; /** @@ -64,7 +41,7 @@ protected function initializeKeywords() /** * Returns the list of keywords. * - * @return array + * @return string[] */ abstract protected function getKeywords(); diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/MariaDb102Keywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/MariaDb102Keywords.php index 3fb66934f86..1b31c7682e7 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/MariaDb102Keywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/MariaDb102Keywords.php @@ -1,26 +1,10 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; /** * MariaDb reserved keywords list. + * * @link https://mariadb.com/kb/en/the-mariadb-library/reserved-words/ */ final class MariaDb102Keywords extends MySQLKeywords diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/MsSQLKeywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/MsSQLKeywords.php index 9c8f614993a..5306b5b0d2b 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/MsSQLKeywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/MsSQLKeywords.php @@ -1,35 +1,13 @@ . - */ - namespace Doctrine\DBAL\Platforms\Keywords; /** * MsSQL Keywordlist * - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @link www.doctrine-project.com - * @since 2.0 - * @author Benjamin Eberlei - * @author David Coallier - * @author Steve Müller * @deprecated Use SQLServerKeywords class instead. + * + * @link www.doctrine-project.com */ class MsSQLKeywords extends SQLServerKeywords { diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/MySQL57Keywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/MySQL57Keywords.php index ef7c389ed3a..9b60a3f1c54 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/MySQL57Keywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/MySQL57Keywords.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; /** * MySQL 5.7 reserved keywords list. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class MySQL57Keywords extends MySQLKeywords { diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/MySQL80Keywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/MySQL80Keywords.php index 232b85cdd32..4b595d53a08 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/MySQL80Keywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/MySQL80Keywords.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; @@ -23,8 +6,6 @@ /** * MySQL 8.0 reserved keywords list. - * - * @link www.doctrine-project.org */ class MySQL80Keywords extends MySQL57Keywords { diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/MySQLKeywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/MySQLKeywords.php index 8ba9b4d74ac..84ca1446a8b 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/MySQLKeywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/MySQLKeywords.php @@ -1,31 +1,9 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; /** * MySQL Keywordlist. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei - * @author David Coallier */ class MySQLKeywords extends KeywordList { diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/OracleKeywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/OracleKeywords.php index 4914d2e9db4..92ca81a079b 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/OracleKeywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/OracleKeywords.php @@ -1,31 +1,9 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; /** * Oracle Keywordlist. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei - * @author David Coallier */ class OracleKeywords extends KeywordList { diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/PostgreSQL91Keywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/PostgreSQL91Keywords.php index ecbd0a46db0..75a93f5f197 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/PostgreSQL91Keywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/PostgreSQL91Keywords.php @@ -1,31 +1,9 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; /** * PostgreSQL 9.1 reserved keywords list. - * - * @author Martin Hasoň - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class PostgreSQL91Keywords extends PostgreSQLKeywords { diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/PostgreSQL92Keywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/PostgreSQL92Keywords.php index d6c6a9d3f77..5179462fdf3 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/PostgreSQL92Keywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/PostgreSQL92Keywords.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; @@ -23,10 +6,6 @@ /** * PostgreSQL 9.2 reserved keywords list. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class PostgreSQL92Keywords extends PostgreSQL91Keywords { @@ -45,8 +24,6 @@ public function getName() */ protected function getKeywords() { - return array_merge(parent::getKeywords(), [ - 'COLLATION', - ]); + return array_merge(parent::getKeywords(), ['COLLATION']); } } diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/PostgreSQL94Keywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/PostgreSQL94Keywords.php index 8daa59539a4..b33b8a8c00b 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/PostgreSQL94Keywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/PostgreSQL94Keywords.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; @@ -24,10 +7,6 @@ /** * PostgreSQL 9.4 reserved keywords list. - * - * @author Matteo Beccati - * @link www.doctrine-project.org - * @since 2.6 */ class PostgreSQL94Keywords extends PostgreSQL92Keywords { @@ -46,12 +25,8 @@ public function getName() */ protected function getKeywords() { - $parentKeywords = array_diff(parent::getKeywords(), [ - 'OVER', - ]); + $parentKeywords = array_diff(parent::getKeywords(), ['OVER']); - return array_merge($parentKeywords, [ - 'LATERAL', - ]); + return array_merge($parentKeywords, ['LATERAL']); } } diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/PostgreSQLKeywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/PostgreSQLKeywords.php index 571d6f4e818..8c699e25380 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/PostgreSQLKeywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/PostgreSQLKeywords.php @@ -1,31 +1,9 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; /** * PostgreSQL Keywordlist. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei - * @author Marcelo Santos Araujo */ class PostgreSQLKeywords extends KeywordList { @@ -129,7 +107,7 @@ protected function getKeywords() 'USING', 'VERBOSE', 'WHEN', - 'WHERE' + 'WHERE', ]; } } diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/ReservedKeywordsValidator.php b/lib/Doctrine/DBAL/Platforms/Keywords/ReservedKeywordsValidator.php index c6a5954e274..68cdf3d15d8 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/ReservedKeywordsValidator.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/ReservedKeywordsValidator.php @@ -1,48 +1,27 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; -use Doctrine\DBAL\Schema\Visitor\Visitor; -use Doctrine\DBAL\Schema\Table; use Doctrine\DBAL\Schema\Column; use Doctrine\DBAL\Schema\ForeignKeyConstraint; +use Doctrine\DBAL\Schema\Index; use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Sequence; -use Doctrine\DBAL\Schema\Index; +use Doctrine\DBAL\Schema\Table; +use Doctrine\DBAL\Schema\Visitor\Visitor; use function implode; use function str_replace; class ReservedKeywordsValidator implements Visitor { - /** - * @var KeywordList[] - */ + /** @var KeywordList[] */ private $keywordLists = []; - /** - * @var array - */ + /** @var string[] */ private $violations = []; /** - * @param \Doctrine\DBAL\Platforms\Keywords\KeywordList[] $keywordLists + * @param KeywordList[] $keywordLists */ public function __construct(array $keywordLists) { @@ -50,7 +29,7 @@ public function __construct(array $keywordLists) } /** - * @return array + * @return string[] */ public function getViolations() { @@ -60,33 +39,35 @@ public function getViolations() /** * @param string $word * - * @return array + * @return string[] */ private function isReservedWord($word) { - if ($word[0] == "`") { + if ($word[0] === '`') { $word = str_replace('`', '', $word); } $keywordLists = []; foreach ($this->keywordLists as $keywordList) { - if ($keywordList->isKeyword($word)) { - $keywordLists[] = $keywordList->getName(); + if (! $keywordList->isKeyword($word)) { + continue; } + + $keywordLists[] = $keywordList->getName(); } return $keywordLists; } /** - * @param string $asset - * @param array $violatedPlatforms + * @param string $asset + * @param string[] $violatedPlatforms * * @return void */ private function addViolation($asset, $violatedPlatforms) { - if ( ! $violatedPlatforms) { + if (! $violatedPlatforms) { return; } diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/SQLAnywhere11Keywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/SQLAnywhere11Keywords.php index 6e67ee2e6fa..09513c5770e 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/SQLAnywhere11Keywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/SQLAnywhere11Keywords.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; @@ -24,8 +7,6 @@ /** * SAP Sybase SQL Anywhere 11 reserved keywords list. - * - * @author Steve Müller */ class SQLAnywhere11Keywords extends SQLAnywhereKeywords { @@ -51,7 +32,7 @@ protected function getKeywords() ), [ 'MERGE', - 'OPENSTRING' + 'OPENSTRING', ] ); } diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/SQLAnywhere12Keywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/SQLAnywhere12Keywords.php index ebc38bf8440..489a83f7173 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/SQLAnywhere12Keywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/SQLAnywhere12Keywords.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; @@ -24,8 +7,6 @@ /** * SAP Sybase SQL Anywhere 12 reserved keywords list. - * - * @author Steve Müller */ class SQLAnywhere12Keywords extends SQLAnywhere11Keywords { @@ -52,7 +33,7 @@ protected function getKeywords() 'SYNTAX_ERROR', 'WITH_CUBE', 'WITH_LPAREN', - 'WITH_ROLLUP' + 'WITH_ROLLUP', ] ), [ @@ -60,7 +41,7 @@ protected function getKeywords() 'LIMIT', 'OPENXML', 'SPATIAL', - 'TREAT' + 'TREAT', ] ); } diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/SQLAnywhere16Keywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/SQLAnywhere16Keywords.php index 1ec984e789c..fce19b41627 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/SQLAnywhere16Keywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/SQLAnywhere16Keywords.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; @@ -23,8 +6,6 @@ /** * SAP Sybase SQL Anywhere 16 reserved keywords list. - * - * @author Steve Müller */ class SQLAnywhere16Keywords extends SQLAnywhere12Keywords { @@ -51,7 +32,7 @@ protected function getKeywords() 'ROW', 'ROWTYPE', 'UNNEST', - 'VARRAY' + 'VARRAY', ] ); } diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/SQLAnywhereKeywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/SQLAnywhereKeywords.php index 9d5ab5db870..5223d4a9e43 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/SQLAnywhereKeywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/SQLAnywhereKeywords.php @@ -1,28 +1,9 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; /** * SAP Sybase SQL Anywhere 10 reserved keywords list. - * - * @author Steve Müller */ class SQLAnywhereKeywords extends KeywordList { @@ -275,7 +256,7 @@ protected function getKeywords() 'WITHIN', 'WORK', 'WRITETEXT', - 'XML' + 'XML', ]; } } diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/SQLServer2005Keywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/SQLServer2005Keywords.php index 02b4656208d..c4fc6c838ff 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/SQLServer2005Keywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/SQLServer2005Keywords.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; @@ -25,10 +8,7 @@ /** * Microsoft SQL Server 2005 reserved keyword dictionary. * - * @license BSD http://www.opensource.org/licenses/bsd-license.php * @link www.doctrine-project.com - * @since 2.3 - * @author Steve Müller */ class SQLServer2005Keywords extends SQLServerKeywords { @@ -53,7 +33,7 @@ protected function getKeywords() 'REVERT', 'SECURITYAUDIT', 'TABLESAMPLE', - 'UNPIVOT' + 'UNPIVOT', ]); } } diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/SQLServer2008Keywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/SQLServer2008Keywords.php index b5c38610afa..54a4e3a5fd5 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/SQLServer2008Keywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/SQLServer2008Keywords.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; @@ -24,10 +7,7 @@ /** * Microsoft SQL Server 2008 reserved keyword dictionary. * - * @license BSD http://www.opensource.org/licenses/bsd-license.php * @link www.doctrine-project.com - * @since 2.3 - * @author Steve Müller */ class SQLServer2008Keywords extends SQLServer2005Keywords { @@ -46,8 +26,6 @@ public function getName() */ protected function getKeywords() { - return array_merge(parent::getKeywords(), [ - 'MERGE' - ]); + return array_merge(parent::getKeywords(), ['MERGE']); } } diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/SQLServer2012Keywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/SQLServer2012Keywords.php index bf621bff8af..142e8a388d0 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/SQLServer2012Keywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/SQLServer2012Keywords.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; @@ -24,10 +7,7 @@ /** * Microsoft SQL Server 2012 reserved keyword dictionary. * - * @license BSD http://www.opensource.org/licenses/bsd-license.php * @link www.doctrine-project.com - * @since 2.3 - * @author Steve Müller */ class SQLServer2012Keywords extends SQLServer2008Keywords { @@ -51,7 +31,7 @@ protected function getKeywords() 'SEMANTICSIMILARITYDETAILSTABLE', 'SEMANTICSIMILARITYTABLE', 'TRY_CONVERT', - 'WITHIN GROUP' + 'WITHIN GROUP', ]); } } diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/SQLServerKeywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/SQLServerKeywords.php index 5b65cbc8721..1e477309c16 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/SQLServerKeywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/SQLServerKeywords.php @@ -1,33 +1,11 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; /** * Microsoft SQL Server 2000 reserved keyword dictionary. * - * @license BSD http://www.opensource.org/licenses/bsd-license.php * @link www.doctrine-project.com - * @since 2.0 - * @author Benjamin Eberlei - * @author David Coallier - * @author Steve Müller */ class SQLServerKeywords extends KeywordList { @@ -225,7 +203,7 @@ protected function getKeywords() 'WHERE', 'WHILE', 'WITH', - 'WRITETEXT' + 'WRITETEXT', ]; } } diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/SQLiteKeywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/SQLiteKeywords.php index f240aa64469..a0c9c797ef9 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/SQLiteKeywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/SQLiteKeywords.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Platforms\Keywords; /** * SQLite Keywordlist. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ class SQLiteKeywords extends KeywordList { @@ -162,7 +141,7 @@ protected function getKeywords() 'VIEW', 'VIRTUAL', 'WHEN', - 'WHERE' + 'WHERE', ]; } } diff --git a/lib/Doctrine/DBAL/Platforms/MariaDb1027Platform.php b/lib/Doctrine/DBAL/Platforms/MariaDb1027Platform.php index 1955fb05912..25420a0476e 100644 --- a/lib/Doctrine/DBAL/Platforms/MariaDb1027Platform.php +++ b/lib/Doctrine/DBAL/Platforms/MariaDb1027Platform.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms; @@ -24,21 +7,10 @@ /** * Provides the behavior, features and SQL dialect of the MariaDB 10.2 (10.2.7 GA) database platform. * - * Note: Should not be used with versions prior ro 10.2.7. - * - * @author Vanvelthem Sébastien - * @link www.doctrine-project.org + * Note: Should not be used with versions prior to 10.2.7. */ final class MariaDb1027Platform extends MySqlPlatform { - /** - * {@inheritdoc} - */ - public function hasNativeJsonType() : bool - { - return false; - } - /** * {@inheritdoc} * diff --git a/lib/Doctrine/DBAL/Platforms/MySQL57Platform.php b/lib/Doctrine/DBAL/Platforms/MySQL57Platform.php index 5b2328b2e65..71ef6ca96c7 100644 --- a/lib/Doctrine/DBAL/Platforms/MySQL57Platform.php +++ b/lib/Doctrine/DBAL/Platforms/MySQL57Platform.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms; @@ -25,11 +8,6 @@ /** * Provides the behavior, features and SQL dialect of the MySQL 5.7 (5.7.9 GA) database platform. - * - * @author İsmail BASKIN - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class MySQL57Platform extends MySqlPlatform { @@ -70,9 +48,7 @@ protected function getPostAlterTableRenameIndexForeignKeySQL(TableDiff $diff) */ protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName) { - return [ - 'ALTER TABLE ' . $tableName . ' RENAME INDEX ' . $oldIndexName . ' TO ' . $index->getQuotedName($this) - ]; + return ['ALTER TABLE ' . $tableName . ' RENAME INDEX ' . $oldIndexName . ' TO ' . $index->getQuotedName($this)]; } /** diff --git a/lib/Doctrine/DBAL/Platforms/MySQL80Platform.php b/lib/Doctrine/DBAL/Platforms/MySQL80Platform.php index e0727237b88..f6d4be9dc4c 100644 --- a/lib/Doctrine/DBAL/Platforms/MySQL80Platform.php +++ b/lib/Doctrine/DBAL/Platforms/MySQL80Platform.php @@ -1,28 +1,9 @@ . - */ namespace Doctrine\DBAL\Platforms; /** * Provides the behavior, features and SQL dialect of the MySQL 8.0 (8.0 GA) database platform. - * - * @link www.doctrine-project.org */ class MySQL80Platform extends MySQL57Platform { diff --git a/lib/Doctrine/DBAL/Platforms/MySqlPlatform.php b/lib/Doctrine/DBAL/Platforms/MySqlPlatform.php index a16bfe79da0..98228fc50b3 100644 --- a/lib/Doctrine/DBAL/Platforms/MySqlPlatform.php +++ b/lib/Doctrine/DBAL/Platforms/MySqlPlatform.php @@ -1,24 +1,8 @@ . - */ namespace Doctrine\DBAL\Platforms; +use Doctrine\DBAL\Schema\ForeignKeyConstraint; use Doctrine\DBAL\Schema\Identifier; use Doctrine\DBAL\Schema\Index; use Doctrine\DBAL\Schema\Table; @@ -26,6 +10,7 @@ use Doctrine\DBAL\TransactionIsolationLevel; use Doctrine\DBAL\Types\BlobType; use Doctrine\DBAL\Types\TextType; +use InvalidArgumentException; use function array_diff_key; use function array_merge; use function array_unique; @@ -36,7 +21,6 @@ use function in_array; use function is_numeric; use function is_string; -use function join; use function sprintf; use function str_replace; use function strtoupper; @@ -47,20 +31,17 @@ * MySQL database platform. This platform represents a MySQL 5.0 or greater platform that * uses the InnoDB storage engine. * - * @since 2.0 - * @author Roman Borschel - * @author Benjamin Eberlei * @todo Rename: MySQLPlatform */ class MySqlPlatform extends AbstractPlatform { - const LENGTH_LIMIT_TINYTEXT = 255; - const LENGTH_LIMIT_TEXT = 65535; - const LENGTH_LIMIT_MEDIUMTEXT = 16777215; + public const LENGTH_LIMIT_TINYTEXT = 255; + public const LENGTH_LIMIT_TEXT = 65535; + public const LENGTH_LIMIT_MEDIUMTEXT = 16777215; - const LENGTH_LIMIT_TINYBLOB = 255; - const LENGTH_LIMIT_BLOB = 65535; - const LENGTH_LIMIT_MEDIUMBLOB = 16777215; + public const LENGTH_LIMIT_TINYBLOB = 255; + public const LENGTH_LIMIT_BLOB = 65535; + public const LENGTH_LIMIT_MEDIUMBLOB = 16777215; /** * {@inheritDoc} @@ -112,11 +93,11 @@ public function getGuidExpression() */ public function getLocateExpression($str, $substr, $startPos = false) { - if ($startPos == false) { + if ($startPos === false) { return 'LOCATE(' . $substr . ', ' . $str . ')'; } - return 'LOCATE(' . $substr . ', ' . $str . ', '.$startPos.')'; + return 'LOCATE(' . $substr . ', ' . $str . ', ' . $startPos . ')'; } /** @@ -124,9 +105,7 @@ public function getLocateExpression($str, $substr, $startPos = false) */ public function getConcatExpression() { - $args = func_get_args(); - - return 'CONCAT(' . join(', ', (array) $args) . ')'; + return sprintf('CONCAT(%s)', implode(', ', func_get_args())); } /** @@ -134,7 +113,7 @@ public function getConcatExpression() */ protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit) { - $function = '+' === $operator ? 'DATE_ADD' : 'DATE_SUB'; + $function = $operator === '+' ? 'DATE_ADD' : 'DATE_SUB'; return $function . '(' . $date . ', INTERVAL ' . $interval . ' ' . $unit . ')'; } @@ -173,13 +152,14 @@ public function getListTableIndexesSQL($table, $currentDatabase = null) { if ($currentDatabase) { $currentDatabase = $this->quoteStringLiteral($currentDatabase); - $table = $this->quoteStringLiteral($table); - - return "SELECT TABLE_NAME AS `Table`, NON_UNIQUE AS Non_Unique, INDEX_NAME AS Key_name, ". - "SEQ_IN_INDEX AS Seq_in_index, COLUMN_NAME AS Column_Name, COLLATION AS Collation, ". - "CARDINALITY AS Cardinality, SUB_PART AS Sub_Part, PACKED AS Packed, " . - "NULLABLE AS `Null`, INDEX_TYPE AS Index_Type, COMMENT AS Comment " . - "FROM information_schema.STATISTICS WHERE TABLE_NAME = " . $table . " AND TABLE_SCHEMA = " . $currentDatabase; + $table = $this->quoteStringLiteral($table); + + return 'SELECT TABLE_NAME AS `Table`, NON_UNIQUE AS Non_Unique, INDEX_NAME AS Key_name, ' . + 'SEQ_IN_INDEX AS Seq_in_index, COLUMN_NAME AS Column_Name, COLLATION AS Collation, ' . + 'CARDINALITY AS Cardinality, SUB_PART AS Sub_Part, PACKED AS Packed, ' . + 'NULLABLE AS `Null`, INDEX_TYPE AS Index_Type, COMMENT AS Comment ' . + 'FROM information_schema.STATISTICS WHERE TABLE_NAME = ' . $table . ' AND TABLE_SCHEMA = ' . $currentDatabase . + ' ORDER BY SEQ_IN_INDEX ASC'; } return 'SHOW INDEX FROM ' . $table; @@ -192,7 +172,7 @@ public function getListViewsSQL($database) { $database = $this->quoteStringLiteral($database); - return "SELECT * FROM information_schema.VIEWS WHERE TABLE_SCHEMA = " . $database; + return 'SELECT * FROM information_schema.VIEWS WHERE TABLE_SCHEMA = ' . $database; } /** @@ -202,21 +182,21 @@ public function getListTableForeignKeysSQL($table, $database = null) { $table = $this->quoteStringLiteral($table); - if (null !== $database) { + if ($database !== null) { $database = $this->quoteStringLiteral($database); } - $sql = "SELECT DISTINCT k.`CONSTRAINT_NAME`, k.`COLUMN_NAME`, k.`REFERENCED_TABLE_NAME`, ". - "k.`REFERENCED_COLUMN_NAME` /*!50116 , c.update_rule, c.delete_rule */ ". - "FROM information_schema.key_column_usage k /*!50116 ". - "INNER JOIN information_schema.referential_constraints c ON ". - " c.constraint_name = k.constraint_name AND ". - " c.table_name = $table */ WHERE k.table_name = $table"; + $sql = 'SELECT DISTINCT k.`CONSTRAINT_NAME`, k.`COLUMN_NAME`, k.`REFERENCED_TABLE_NAME`, ' . + 'k.`REFERENCED_COLUMN_NAME` /*!50116 , c.update_rule, c.delete_rule */ ' . + 'FROM information_schema.key_column_usage k /*!50116 ' . + 'INNER JOIN information_schema.referential_constraints c ON ' . + ' c.constraint_name = k.constraint_name AND ' . + ' c.table_name = ' . $table . ' */ WHERE k.table_name = ' . $table; $databaseNameSql = $database ?? 'DATABASE()'; - $sql .= " AND k.table_schema = $databaseNameSql /*!50116 AND c.constraint_schema = $databaseNameSql */"; - $sql .= " AND k.`REFERENCED_COLUMN_NAME` is not NULL"; + $sql .= ' AND k.table_schema = ' . $databaseNameSql . ' /*!50116 AND c.constraint_schema = ' . $databaseNameSql . ' */'; + $sql .= ' AND k.`REFERENCED_COLUMN_NAME` is not NULL'; return $sql; } @@ -234,7 +214,7 @@ public function getCreateViewSQL($name, $sql) */ public function getDropViewSQL($name) { - return 'DROP VIEW '. $name; + return 'DROP VIEW ' . $name; } /** @@ -261,13 +241,11 @@ protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed) * MEDIUMTEXT : 2 ^ 24 - 1 = 16777215 * LONGTEXT : 2 ^ 32 - 1 = 4294967295 * - * @param array $field - * - * @return string + * {@inheritDoc} */ public function getClobTypeDeclarationSQL(array $field) { - if ( ! empty($field['length']) && is_numeric($field['length'])) { + if (! empty($field['length']) && is_numeric($field['length'])) { $length = $field['length']; if ($length <= static::LENGTH_LIMIT_TINYTEXT) { @@ -291,7 +269,7 @@ public function getClobTypeDeclarationSQL(array $field) */ public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration) { - if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] == true) { + if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] === true) { return 'TIMESTAMP'; } @@ -396,10 +374,25 @@ public function getListTableColumnsSQL($table, $database = null) $database = 'DATABASE()'; } - return "SELECT COLUMN_NAME AS Field, COLUMN_TYPE AS Type, IS_NULLABLE AS `Null`, ". - "COLUMN_KEY AS `Key`, COLUMN_DEFAULT AS `Default`, EXTRA AS Extra, COLUMN_COMMENT AS Comment, " . - "CHARACTER_SET_NAME AS CharacterSet, COLLATION_NAME AS Collation ". - "FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = " . $database . " AND TABLE_NAME = " . $table; + return 'SELECT COLUMN_NAME AS Field, COLUMN_TYPE AS Type, IS_NULLABLE AS `Null`, ' . + 'COLUMN_KEY AS `Key`, COLUMN_DEFAULT AS `Default`, EXTRA AS Extra, COLUMN_COMMENT AS Comment, ' . + 'CHARACTER_SET_NAME AS CharacterSet, COLLATION_NAME AS Collation ' . + 'FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ' . $database . ' AND TABLE_NAME = ' . $table . + ' ORDER BY ORDINAL_POSITION ASC'; + } + + public function getListTableMetadataSQL(string $table, ?string $database = null) : string + { + return sprintf( + <<<'SQL' +SELECT ENGINE, AUTO_INCREMENT, TABLE_COLLATION, TABLE_COMMENT, CREATE_OPTIONS +FROM information_schema.TABLES +WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = %s AND TABLE_NAME = %s +SQL + , + $database ? $this->quoteStringLiteral($database) : 'DATABASE()', + $this->quoteStringLiteral($table) + ); } /** @@ -440,13 +433,13 @@ protected function _getCreateTableSQL($tableName, array $columns, array $options // attach all primary keys if (isset($options['primary']) && ! empty($options['primary'])) { - $keyColumns = array_unique(array_values($options['primary'])); + $keyColumns = array_unique(array_values($options['primary'])); $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')'; } $query = 'CREATE '; - if (!empty($options['temporary'])) { + if (! empty($options['temporary'])) { $query .= 'TEMPORARY '; } @@ -487,7 +480,7 @@ public function getDefaultValueDeclarationSQL($field) /** * Build SQL for table options * - * @param array $options + * @param mixed[] $options * * @return string */ @@ -500,21 +493,21 @@ private function buildTableOptions(array $options) $tableOptions = []; // Charset - if ( ! isset($options['charset'])) { + if (! isset($options['charset'])) { $options['charset'] = 'utf8'; } $tableOptions[] = sprintf('DEFAULT CHARACTER SET %s', $options['charset']); // Collate - if ( ! isset($options['collate'])) { + if (! isset($options['collate'])) { $options['collate'] = $options['charset'] . '_unicode_ci'; } $tableOptions[] = sprintf('COLLATE %s', $options['collate']); // Engine - if ( ! isset($options['engine'])) { + if (! isset($options['engine'])) { $options['engine'] = 'InnoDB'; } @@ -529,7 +522,7 @@ private function buildTableOptions(array $options) if (isset($options['comment'])) { $comment = trim($options['comment'], " '"); - $tableOptions[] = sprintf("COMMENT = %s ", $this->quoteStringLiteral($comment)); + $tableOptions[] = sprintf('COMMENT = %s ', $this->quoteStringLiteral($comment)); } // Row format @@ -543,13 +536,13 @@ private function buildTableOptions(array $options) /** * Build SQL for partition options. * - * @param array $options + * @param mixed[] $options * * @return string */ private function buildPartitionOptions(array $options) { - return (isset($options['partition_options'])) + return isset($options['partition_options']) ? ' ' . $options['partition_options'] : ''; } @@ -559,7 +552,7 @@ private function buildPartitionOptions(array $options) */ public function getAlterTableSQL(TableDiff $diff) { - $columnSql = []; + $columnSql = []; $queryParts = []; if ($diff->newName !== false) { $queryParts[] = 'RENAME TO ' . $diff->getNewName()->getQuotedName($this); @@ -570,9 +563,9 @@ public function getAlterTableSQL(TableDiff $diff) continue; } - $columnArray = $column->toArray(); + $columnArray = $column->toArray(); $columnArray['comment'] = $this->getColumnComment($column); - $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray); + $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray); } foreach ($diff->removedColumns as $column) { @@ -588,8 +581,7 @@ public function getAlterTableSQL(TableDiff $diff) continue; } - /* @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */ - $column = $columnDiff->column; + $column = $columnDiff->column; $columnArray = $column->toArray(); // Don't propagate default value changes for unsupported column types. @@ -601,7 +593,7 @@ public function getAlterTableSQL(TableDiff $diff) } $columnArray['comment'] = $this->getColumnComment($column); - $queryParts[] = 'CHANGE ' . ($columnDiff->getOldColumnName()->getQuotedName($this)) . ' ' + $queryParts[] = 'CHANGE ' . ($columnDiff->getOldColumnName()->getQuotedName($this)) . ' ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray); } @@ -610,25 +602,25 @@ public function getAlterTableSQL(TableDiff $diff) continue; } - $oldColumnName = new Identifier($oldColumnName); - $columnArray = $column->toArray(); + $oldColumnName = new Identifier($oldColumnName); + $columnArray = $column->toArray(); $columnArray['comment'] = $this->getColumnComment($column); - $queryParts[] = 'CHANGE ' . $oldColumnName->getQuotedName($this) . ' ' + $queryParts[] = 'CHANGE ' . $oldColumnName->getQuotedName($this) . ' ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray); } if (isset($diff->addedIndexes['primary'])) { - $keyColumns = array_unique(array_values($diff->addedIndexes['primary']->getColumns())); + $keyColumns = array_unique(array_values($diff->addedIndexes['primary']->getColumns())); $queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')'; unset($diff->addedIndexes['primary']); } - $sql = []; + $sql = []; $tableSql = []; - if ( ! $this->onSchemaAlterTable($diff, $tableSql)) { + if (! $this->onSchemaAlterTable($diff, $tableSql)) { if (count($queryParts) > 0) { - $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(", ", $queryParts); + $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(', ', $queryParts); } $sql = array_merge( $this->getPreAlterTableIndexForeignKeySQL($diff), @@ -645,7 +637,7 @@ public function getAlterTableSQL(TableDiff $diff) */ protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) { - $sql = []; + $sql = []; $table = $diff->getName($this)->getQuotedName($this); foreach ($diff->changedIndexes as $changedIndex) { @@ -656,8 +648,7 @@ protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) $sql = array_merge($sql, $this->getPreAlterTableAlterPrimaryKeySQL($diff, $remIndex)); foreach ($diff->addedIndexes as $addKey => $addIndex) { - if ($remIndex->getColumns() == $addIndex->getColumns()) { - + if ($remIndex->getColumns() === $addIndex->getColumns()) { $indexClause = 'INDEX ' . $addIndex->getName(); if ($addIndex->isPrimary()) { @@ -666,9 +657,9 @@ protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) $indexClause = 'UNIQUE INDEX ' . $addIndex->getName(); } - $query = 'ALTER TABLE ' . $table . ' DROP INDEX ' . $remIndex->getName() . ', '; + $query = 'ALTER TABLE ' . $table . ' DROP INDEX ' . $remIndex->getName() . ', '; $query .= 'ADD ' . $indexClause; - $query .= ' (' . $this->getIndexFieldDeclarationListSQL($addIndex->getQuotedColumns($this)) . ')'; + $query .= ' (' . $this->getIndexFieldDeclarationListSQL($addIndex) . ')'; $sql[] = $query; @@ -686,7 +677,7 @@ protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) } // Suppress foreign key constraint propagation on non-supporting engines. - if ('INNODB' !== $engine) { + if ($engine !== 'INNODB') { $diff->addedForeignKeys = []; $diff->changedForeignKeys = []; $diff->removedForeignKeys = []; @@ -703,9 +694,6 @@ protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) } /** - * @param TableDiff $diff - * @param Index $index - * * @return string[] */ private function getPreAlterTableAlterPrimaryKeySQL(TableDiff $diff, Index $index) @@ -726,15 +714,17 @@ private function getPreAlterTableAlterPrimaryKeySQL(TableDiff $diff, Index $inde $column = $diff->fromTable->getColumn($columnName); - if ($column->getAutoincrement() === true) { - $column->setAutoincrement(false); + if ($column->getAutoincrement() !== true) { + continue; + } - $sql[] = 'ALTER TABLE ' . $tableName . ' MODIFY ' . - $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray()); + $column->setAutoincrement(false); - // original autoincrement information might be needed later on by other parts of the table alteration - $column->setAutoincrement(true); - } + $sql[] = 'ALTER TABLE ' . $tableName . ' MODIFY ' . + $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray()); + + // original autoincrement information might be needed later on by other parts of the table alteration + $column->setAutoincrement(true); } return $sql; @@ -743,33 +733,37 @@ private function getPreAlterTableAlterPrimaryKeySQL(TableDiff $diff, Index $inde /** * @param TableDiff $diff The table diff to gather the SQL for. * - * @return array + * @return string[] */ private function getPreAlterTableAlterIndexForeignKeySQL(TableDiff $diff) { - $sql = []; + $sql = []; $table = $diff->getName($this)->getQuotedName($this); foreach ($diff->changedIndexes as $changedIndex) { // Changed primary key - if ($changedIndex->isPrimary() && $diff->fromTable instanceof Table) { - foreach ($diff->fromTable->getPrimaryKeyColumns() as $columnName) { - $column = $diff->fromTable->getColumn($columnName); - - // Check if an autoincrement column was dropped from the primary key. - if ($column->getAutoincrement() && ! in_array($columnName, $changedIndex->getColumns())) { - // The autoincrement attribute needs to be removed from the dropped column - // before we can drop and recreate the primary key. - $column->setAutoincrement(false); - - $sql[] = 'ALTER TABLE ' . $table . ' MODIFY ' . - $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray()); - - // Restore the autoincrement attribute as it might be needed later on - // by other parts of the table alteration. - $column->setAutoincrement(true); - } + if (! $changedIndex->isPrimary() || ! ($diff->fromTable instanceof Table)) { + continue; + } + + foreach ($diff->fromTable->getPrimaryKeyColumns() as $columnName) { + $column = $diff->fromTable->getColumn($columnName); + + // Check if an autoincrement column was dropped from the primary key. + if (! $column->getAutoincrement() || in_array($columnName, $changedIndex->getColumns())) { + continue; } + + // The autoincrement attribute needs to be removed from the dropped column + // before we can drop and recreate the primary key. + $column->setAutoincrement(false); + + $sql[] = 'ALTER TABLE ' . $table . ' MODIFY ' . + $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray()); + + // Restore the autoincrement attribute as it might be needed later on + // by other parts of the table alteration. + $column->setAutoincrement(true); } } @@ -779,17 +773,19 @@ private function getPreAlterTableAlterIndexForeignKeySQL(TableDiff $diff) /** * @param TableDiff $diff The table diff to gather the SQL for. * - * @return array + * @return string[] */ protected function getPreAlterTableRenameIndexForeignKeySQL(TableDiff $diff) { - $sql = []; + $sql = []; $tableName = $diff->getName($this)->getQuotedName($this); foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) { - if (! in_array($foreignKey, $diff->changedForeignKeys, true)) { - $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName); + if (in_array($foreignKey, $diff->changedForeignKeys, true)) { + continue; } + + $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName); } return $sql; @@ -803,7 +799,7 @@ protected function getPreAlterTableRenameIndexForeignKeySQL(TableDiff $diff) * * @param TableDiff $diff The table diff to evaluate. * - * @return array + * @return ForeignKeyConstraint[] */ private function getRemainingForeignKeyConstraintsRequiringRenamedIndexes(TableDiff $diff) { @@ -812,7 +808,7 @@ private function getRemainingForeignKeyConstraintsRequiringRenamedIndexes(TableD } $foreignKeys = []; - /** @var \Doctrine\DBAL\Schema\ForeignKeyConstraint[] $remainingForeignKeys */ + /** @var ForeignKeyConstraint[] $remainingForeignKeys */ $remainingForeignKeys = array_diff_key( $diff->fromTable->getForeignKeys(), $diff->removedForeignKeys @@ -845,19 +841,21 @@ protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff) /** * @param TableDiff $diff The table diff to gather the SQL for. * - * @return array + * @return string[] */ protected function getPostAlterTableRenameIndexForeignKeySQL(TableDiff $diff) { - $sql = []; - $tableName = (false !== $diff->newName) + $sql = []; + $tableName = $diff->newName !== false ? $diff->getNewName()->getQuotedName($this) : $diff->getName($this)->getQuotedName($this); foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) { - if (! in_array($foreignKey, $diff->changedForeignKeys, true)) { - $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName); + if (in_array($foreignKey, $diff->changedForeignKeys, true)) { + continue; } + + $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName); } return $sql; @@ -923,7 +921,7 @@ public function getDecimalTypeDeclarationSQL(array $columnDef) /** * Get unsigned declaration for a column. * - * @param array $columnDef + * @param mixed[] $columnDef * * @return string */ @@ -938,7 +936,7 @@ private function getUnsignedDeclaration(array $columnDef) protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) { $autoinc = ''; - if ( ! empty($columnDef['autoincrement'])) { + if (! empty($columnDef['autoincrement'])) { $autoinc = ' AUTO_INCREMENT'; } @@ -948,7 +946,7 @@ protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) /** * {@inheritDoc} */ - public function getAdvancedForeignKeyOptionsSQL(\Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey) + public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey) { $query = ''; if ($foreignKey->hasOption('match')) { @@ -962,20 +960,20 @@ public function getAdvancedForeignKeyOptionsSQL(\Doctrine\DBAL\Schema\ForeignKey /** * {@inheritDoc} */ - public function getDropIndexSQL($index, $table=null) + public function getDropIndexSQL($index, $table = null) { if ($index instanceof Index) { $indexName = $index->getQuotedName($this); } elseif (is_string($index)) { $indexName = $index; } else { - throw new \InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.'); + throw new InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.'); } if ($table instanceof Table) { $table = $table->getQuotedName($this); - } elseif (!is_string($table)) { - throw new \InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.'); + } elseif (! is_string($table)) { + throw new InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.'); } if ($index instanceof Index && $index->isPrimary()) { @@ -1094,8 +1092,8 @@ public function getDropTemporaryTableSQL($table) { if ($table instanceof Table) { $table = $table->getQuotedName($this); - } elseif (!is_string($table)) { - throw new \InvalidArgumentException('getDropTemporaryTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.'); + } elseif (! is_string($table)) { + throw new InvalidArgumentException('getDropTemporaryTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.'); } return 'DROP TEMPORARY TABLE ' . $table; @@ -1108,13 +1106,11 @@ public function getDropTemporaryTableSQL($table) * MEDIUMBLOB : 2 ^ 24 - 1 = 16777215 * LONGBLOB : 2 ^ 32 - 1 = 4294967295 * - * @param array $field - * - * @return string + * {@inheritDoc} */ public function getBlobTypeDeclarationSQL(array $field) { - if ( ! empty($field['length']) && is_numeric($field['length'])) { + if (! empty($field['length']) && is_numeric($field['length'])) { $length = $field['length']; if ($length <= static::LENGTH_LIMIT_TINYBLOB) { @@ -1150,4 +1146,12 @@ public function getDefaultTransactionIsolationLevel() { return TransactionIsolationLevel::REPEATABLE_READ; } + + /** + * {@inheritdoc} + */ + public function supportsColumnLengthIndexes() : bool + { + return true; + } } diff --git a/lib/Doctrine/DBAL/Platforms/OraclePlatform.php b/lib/Doctrine/DBAL/Platforms/OraclePlatform.php index 32b12a0bc1f..537a566bada 100644 --- a/lib/Doctrine/DBAL/Platforms/OraclePlatform.php +++ b/lib/Doctrine/DBAL/Platforms/OraclePlatform.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms; @@ -28,6 +11,7 @@ use Doctrine\DBAL\Schema\TableDiff; use Doctrine\DBAL\TransactionIsolationLevel; use Doctrine\DBAL\Types\BinaryType; +use InvalidArgumentException; use function array_merge; use function count; use function explode; @@ -36,7 +20,6 @@ use function implode; use function preg_match; use function sprintf; -use function str_replace; use function strlen; use function strpos; use function strtoupper; @@ -44,11 +27,6 @@ /** * OraclePlatform. - * - * @since 2.0 - * @author Roman Borschel - * @author Lukas Smith (PEAR MDB2 library) - * @author Benjamin Eberlei */ class OraclePlatform extends AbstractPlatform { @@ -63,8 +41,8 @@ class OraclePlatform extends AbstractPlatform */ public static function assertValidIdentifier($identifier) { - if ( ! preg_match('(^(([a-zA-Z]{1}[a-zA-Z0-9_$#]{0,})|("[^"]+"))$)', $identifier)) { - throw new DBALException("Invalid Oracle identifier"); + if (! preg_match('(^(([a-zA-Z]{1}[a-zA-Z0-9_$#]{0,})|("[^"]+"))$)', $identifier)) { + throw new DBALException('Invalid Oracle identifier'); } } @@ -74,10 +52,10 @@ public static function assertValidIdentifier($identifier) public function getSubstringExpression($value, $position, $length = null) { if ($length !== null) { - return "SUBSTR($value, $position, $length)"; + return sprintf('SUBSTR(%s, %d, %d)', $value, $position, $length); } - return "SUBSTR($value, $position)"; + return sprintf('SUBSTR(%s, %d)', $value, $position); } /** @@ -99,11 +77,11 @@ public function getNowExpression($type = 'timestamp') */ public function getLocateExpression($str, $substr, $startPos = false) { - if ($startPos == false) { - return 'INSTR('.$str.', '.$substr.')'; + if ($startPos === false) { + return 'INSTR(' . $str . ', ' . $substr . ')'; } - return 'INSTR('.$str.', '.$substr.', '.$startPos.')'; + return 'INSTR(' . $str . ', ' . $substr . ', ' . $startPos . ')'; } /** @@ -175,7 +153,7 @@ public function getDateDiffExpression($date1, $date2) */ public function getBitAndComparisonExpression($value1, $value2) { - return 'BITAND('.$value1 . ', ' . $value2 . ')'; + return 'BITAND(' . $value1 . ', ' . $value2 . ')'; } /** @@ -217,17 +195,15 @@ public function getAlterSequenceSQL(Sequence $sequence) /** * Cache definition for sequences * - * @param Sequence $sequence - * * @return string */ private function getSequenceCacheSQL(Sequence $sequence) { if ($sequence->getCache() === 0) { return ' NOCACHE'; - } else if ($sequence->getCache() === 1) { + } elseif ($sequence->getCache() === 1) { return ' NOCACHE'; - } else if ($sequence->getCache() > 1) { + } elseif ($sequence->getCache() > 1) { return ' CACHE ' . $sequence->getCache(); } @@ -389,8 +365,8 @@ public function getListSequencesSQL($database) $database = $this->normalizeIdentifier($database); $database = $this->quoteStringLiteral($database->getName()); - return "SELECT sequence_name, min_value, increment_by FROM sys.all_sequences ". - "WHERE SEQUENCE_OWNER = " . $database; + return 'SELECT sequence_name, min_value, increment_by FROM sys.all_sequences ' . + 'WHERE SEQUENCE_OWNER = ' . $database; } /** @@ -407,10 +383,12 @@ protected function _getCreateTableSQL($table, array $columns, array $options = [ $sql[] = $this->getCreateSequenceSQL($column['sequence']); } - if (isset($column['autoincrement']) && $column['autoincrement'] || - (isset($column['autoinc']) && $column['autoinc'])) { - $sql = array_merge($sql, $this->getCreateAutoincrementSql($name, $table)); + if (! isset($column['autoincrement']) || ! $column['autoincrement'] && + (! isset($column['autoinc']) || ! $column['autoinc'])) { + continue; } + + $sql = array_merge($sql, $this->getCreateAutoincrementSql($name, $table)); } if (isset($indexes) && ! empty($indexes)) { @@ -425,7 +403,6 @@ protected function _getCreateTableSQL($table, array $columns, array $options = [ /** * {@inheritDoc} * - * @license New BSD License * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaOracleReader.html */ public function getListTableIndexesSQL($table, $currentDatabase = null) @@ -458,8 +435,8 @@ public function getListTableIndexesSQL($table, $currentDatabase = null) WHERE ucon.index_name = uind_col.index_name ) AS is_primary FROM user_ind_columns uind_col - WHERE uind_col.table_name = " . $table . " - ORDER BY uind_col.column_position ASC"; + WHERE uind_col.table_name = " . $table . ' + ORDER BY uind_col.column_position ASC'; } /** @@ -491,7 +468,7 @@ public function getCreateViewSQL($name, $sql) */ public function getDropViewSQL($name) { - return 'DROP VIEW '. $name; + return 'DROP VIEW ' . $name; } /** @@ -499,17 +476,17 @@ public function getDropViewSQL($name) * @param string $table * @param int $start * - * @return array + * @return string[] */ public function getCreateAutoincrementSql($name, $table, $start = 1) { - $tableIdentifier = $this->normalizeIdentifier($table); - $quotedTableName = $tableIdentifier->getQuotedName($this); + $tableIdentifier = $this->normalizeIdentifier($table); + $quotedTableName = $tableIdentifier->getQuotedName($this); $unquotedTableName = $tableIdentifier->getName(); $nameIdentifier = $this->normalizeIdentifier($name); - $quotedName = $nameIdentifier->getQuotedName($this); - $unquotedName = $nameIdentifier->getName(); + $quotedName = $nameIdentifier->getQuotedName($this); + $unquotedName = $nameIdentifier->getName(); $sql = []; @@ -522,7 +499,7 @@ public function getCreateAutoincrementSql($name, $table, $start = 1) BEGIN SELECT COUNT(CONSTRAINT_NAME) INTO constraints_Count FROM USER_CONSTRAINTS WHERE TABLE_NAME = \'' . $unquotedTableName . '\' AND CONSTRAINT_TYPE = \'P\'; IF constraints_Count = 0 OR constraints_Count = \'\' THEN - EXECUTE IMMEDIATE \''.$this->getCreateConstraintSQL($idx, $quotedTableName).'\'; + EXECUTE IMMEDIATE \'' . $this->getCreateConstraintSQL($idx, $quotedTableName) . '\'; END IF; END;'; @@ -530,8 +507,8 @@ public function getCreateAutoincrementSql($name, $table, $start = 1) $tableIdentifier->isQuoted() ? $quotedTableName : $unquotedTableName, $nameIdentifier->isQuoted() ? $quotedName : $unquotedName ); - $sequence = new Sequence($sequenceName, $start); - $sql[] = $this->getCreateSequenceSQL($sequence); + $sequence = new Sequence($sequenceName, $start); + $sql[] = $this->getCreateSequenceSQL($sequence); $sql[] = 'CREATE TRIGGER ' . $autoincrementIdentifierName . ' BEFORE INSERT @@ -542,7 +519,7 @@ public function getCreateAutoincrementSql($name, $table, $start = 1) last_InsertID NUMBER; BEGIN SELECT ' . $sequenceName . '.NEXTVAL INTO :NEW.' . $quotedName . ' FROM DUAL; - IF (:NEW.' . $quotedName . ' IS NULL OR :NEW.'.$quotedName.' = 0) THEN + IF (:NEW.' . $quotedName . ' IS NULL OR :NEW.' . $quotedName . ' = 0) THEN SELECT ' . $sequenceName . '.NEXTVAL INTO :NEW.' . $quotedName . ' FROM DUAL; ELSE SELECT NVL(Last_Number, 0) INTO last_Sequence @@ -563,13 +540,13 @@ public function getCreateAutoincrementSql($name, $table, $start = 1) * * @param string $table The table name to drop the autoincrement for. * - * @return array + * @return string[] */ public function getDropAutoincrementSql($table) { - $table = $this->normalizeIdentifier($table); + $table = $this->normalizeIdentifier($table); $autoincrementIdentifierName = $this->getAutoincrementIdentifierName($table); - $identitySequenceName = $this->getIdentitySequenceName( + $identitySequenceName = $this->getIdentitySequenceName( $table->isQuoted() ? $table->getQuotedName($this) : $table->getName(), '' ); @@ -645,8 +622,8 @@ public function getListTableForeignKeysSQL($table) JOIN user_constraints alc ON alc.constraint_name = cols.constraint_name AND alc.constraint_type = 'R' - AND alc.table_name = " . $table . " - ORDER BY cols.constraint_name ASC, cols.position ASC"; + AND alc.table_name = " . $table . ' + ORDER BY cols.constraint_name ASC, cols.position ASC'; } /** @@ -657,7 +634,7 @@ public function getListTableConstraintsSQL($table) $table = $this->normalizeIdentifier($table); $table = $this->quoteStringLiteral($table->getName()); - return "SELECT * FROM user_constraints WHERE table_name = " . $table; + return 'SELECT * FROM user_constraints WHERE table_name = ' . $table; } /** @@ -668,30 +645,40 @@ public function getListTableColumnsSQL($table, $database = null) $table = $this->normalizeIdentifier($table); $table = $this->quoteStringLiteral($table->getName()); - $tabColumnsTableName = "user_tab_columns"; - $colCommentsTableName = "user_col_comments"; - $tabColumnsOwnerCondition = ''; + $tabColumnsTableName = 'user_tab_columns'; + $colCommentsTableName = 'user_col_comments'; + $tabColumnsOwnerCondition = ''; $colCommentsOwnerCondition = ''; - if (null !== $database && '/' !== $database) { - $database = $this->normalizeIdentifier($database); - $database = $this->quoteStringLiteral($database->getName()); - $tabColumnsTableName = "all_tab_columns"; - $colCommentsTableName = "all_col_comments"; - $tabColumnsOwnerCondition = "AND c.owner = " . $database; - $colCommentsOwnerCondition = "AND d.OWNER = c.OWNER"; + if ($database !== null && $database !== '/') { + $database = $this->normalizeIdentifier($database); + $database = $this->quoteStringLiteral($database->getName()); + $tabColumnsTableName = 'all_tab_columns'; + $colCommentsTableName = 'all_col_comments'; + $tabColumnsOwnerCondition = ' AND c.owner = ' . $database; + $colCommentsOwnerCondition = ' AND d.OWNER = c.OWNER'; } - return "SELECT c.*, - ( - SELECT d.comments - FROM $colCommentsTableName d - WHERE d.TABLE_NAME = c.TABLE_NAME " . $colCommentsOwnerCondition . " - AND d.COLUMN_NAME = c.COLUMN_NAME - ) AS comments - FROM $tabColumnsTableName c - WHERE c.table_name = " . $table . " $tabColumnsOwnerCondition - ORDER BY c.column_id"; + return sprintf( + <<<'SQL' +SELECT c.*, + ( + SELECT d.comments + FROM %s d + WHERE d.TABLE_NAME = c.TABLE_NAME%s + AND d.COLUMN_NAME = c.COLUMN_NAME + ) AS comments +FROM %s c +WHERE c.table_name = %s%s +ORDER BY c.column_id +SQL + , + $colCommentsTableName, + $colCommentsOwnerCondition, + $tabColumnsTableName, + $table, + $tabColumnsOwnerCondition + ); } /** @@ -720,7 +707,7 @@ public function getDropForeignKeySQL($foreignKey, $table) } $foreignKey = $foreignKey->getQuotedName($this); - $table = $table->getQuotedName($this); + $table = $table->getQuotedName($this); return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $foreignKey; } @@ -759,7 +746,7 @@ public function getForeignKeyReferentialActionSQL($action) default: // SET DEFAULT is not supported, throw exception instead. - throw new \InvalidArgumentException('Invalid foreign key action: ' . $action); + throw new InvalidArgumentException('Invalid foreign key action: ' . $action); } } @@ -776,9 +763,9 @@ public function getDropDatabaseSQL($database) */ public function getAlterTableSQL(TableDiff $diff) { - $sql = []; + $sql = []; $commentsSQL = []; - $columnSql = []; + $columnSql = []; $fields = []; @@ -788,13 +775,17 @@ public function getAlterTableSQL(TableDiff $diff) } $fields[] = $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray()); - if ($comment = $this->getColumnComment($column)) { - $commentsSQL[] = $this->getCommentOnColumnSQL( - $diff->getName($this)->getQuotedName($this), - $column->getQuotedName($this), - $comment - ); + $comment = $this->getColumnComment($column); + + if (! $comment) { + continue; } + + $commentsSQL[] = $this->getCommentOnColumnSQL( + $diff->getName($this)->getQuotedName($this), + $column->getQuotedName($this), + $comment + ); } if (count($fields)) { @@ -807,7 +798,6 @@ public function getAlterTableSQL(TableDiff $diff) continue; } - /* @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */ $column = $columnDiff->column; // Do not generate column alteration clause if type is binary and only fixed property has changed. @@ -825,23 +815,25 @@ public function getAlterTableSQL(TableDiff $diff) /** * Do not add query part if only comment has changed */ - if ( ! ($columnHasChangedComment && count($columnDiff->changedProperties) === 1)) { + if (! ($columnHasChangedComment && count($columnDiff->changedProperties) === 1)) { $columnInfo = $column->toArray(); - if ( ! $columnDiff->hasChanged('notnull')) { + if (! $columnDiff->hasChanged('notnull')) { unset($columnInfo['notnull']); } $fields[] = $column->getQuotedName($this) . $this->getColumnDeclarationSQL('', $columnInfo); } - if ($columnHasChangedComment) { - $commentsSQL[] = $this->getCommentOnColumnSQL( - $diff->getName($this)->getQuotedName($this), - $column->getQuotedName($this), - $this->getColumnComment($column) - ); + if (! $columnHasChangedComment) { + continue; } + + $commentsSQL[] = $this->getCommentOnColumnSQL( + $diff->getName($this)->getQuotedName($this), + $column->getQuotedName($this), + $this->getColumnComment($column) + ); } if (count($fields)) { @@ -856,7 +848,7 @@ public function getAlterTableSQL(TableDiff $diff) $oldColumnName = new Identifier($oldColumnName); $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . - ' RENAME COLUMN ' . $oldColumnName->getQuotedName($this) .' TO ' . $column->getQuotedName($this); + ' RENAME COLUMN ' . $oldColumnName->getQuotedName($this) . ' TO ' . $column->getQuotedName($this); } $fields = []; @@ -869,12 +861,12 @@ public function getAlterTableSQL(TableDiff $diff) } if (count($fields)) { - $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' DROP (' . implode(', ', $fields).')'; + $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' DROP (' . implode(', ', $fields) . ')'; } $tableSql = []; - if ( ! $this->onSchemaAlterTable($diff, $tableSql)) { + if (! $this->onSchemaAlterTable($diff, $tableSql)) { $sql = array_merge($sql, $commentsSQL); if ($diff->newName !== false) { @@ -907,13 +899,13 @@ public function getColumnDeclarationSQL($name, array $field) $notnull = $field['notnull'] ? ' NOT NULL' : ' NULL'; } - $unique = (isset($field['unique']) && $field['unique']) ? + $unique = isset($field['unique']) && $field['unique'] ? ' ' . $this->getUniqueFieldDeclarationSQL() : ''; - $check = (isset($field['check']) && $field['check']) ? + $check = isset($field['check']) && $field['check'] ? ' ' . $field['check'] : ''; - $typeDecl = $field['type']->getSQLDeclaration($field, $this); + $typeDecl = $field['type']->getSQLDeclaration($field, $this); $columnDef = $typeDecl . $default . $notnull . $unique . $check; } @@ -926,7 +918,7 @@ public function getColumnDeclarationSQL($name, array $field) protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName) { if (strpos($tableName, '.') !== false) { - list($schema) = explode('.', $tableName); + [$schema] = explode('.', $tableName); $oldIndexName = $schema . '.' . $oldIndexName; } @@ -994,8 +986,8 @@ protected function doModifyLimitQuery($query, $limit, $offset = null) } if (preg_match('/^\s*SELECT/i', $query)) { - if (!preg_match('/\sFROM\s/i', $query)) { - $query .= " FROM dual"; + if (! preg_match('/\sFROM\s/i', $query)) { + $query .= ' FROM dual'; } $columns = ['a.*']; @@ -1033,7 +1025,7 @@ public function getSQLResultCasing($column) */ public function getCreateTemporaryTableSnippetSQL() { - return "CREATE GLOBAL TEMPORARY TABLE"; + return 'CREATE GLOBAL TEMPORARY TABLE'; } /** @@ -1180,14 +1172,4 @@ public function getBlobTypeDeclarationSQL(array $field) { return 'BLOB'; } - - /** - * {@inheritdoc} - */ - public function quoteStringLiteral($str) - { - $str = str_replace('\\', '\\\\', $str); // Oracle requires backslashes to be escaped aswell. - - return parent::quoteStringLiteral($str); - } } diff --git a/lib/Doctrine/DBAL/Platforms/PostgreSQL100Platform.php b/lib/Doctrine/DBAL/Platforms/PostgreSQL100Platform.php index 0d379f2fb6c..cfb079f94dd 100644 --- a/lib/Doctrine/DBAL/Platforms/PostgreSQL100Platform.php +++ b/lib/Doctrine/DBAL/Platforms/PostgreSQL100Platform.php @@ -21,12 +21,12 @@ protected function getReservedKeywordsClass() : string public function getListSequencesSQL($database) : string { - return "SELECT sequence_name AS relname, + return 'SELECT sequence_name AS relname, sequence_schema AS schemaname, minimum_value AS min_value, increment AS increment_by FROM information_schema.sequences - WHERE sequence_catalog = " . $this->quoteStringLiteral($database) . " + WHERE sequence_catalog = ' . $this->quoteStringLiteral($database) . " AND sequence_schema NOT LIKE 'pg\_%' AND sequence_schema != 'information_schema'"; } diff --git a/lib/Doctrine/DBAL/Platforms/PostgreSQL91Platform.php b/lib/Doctrine/DBAL/Platforms/PostgreSQL91Platform.php index 94d810483d4..f558409831c 100644 --- a/lib/Doctrine/DBAL/Platforms/PostgreSQL91Platform.php +++ b/lib/Doctrine/DBAL/Platforms/PostgreSQL91Platform.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms; @@ -23,10 +6,6 @@ /** * Provides the behavior, features and SQL dialect of the PostgreSQL 9.1 database platform. - * - * @author Martin Hasoň - * @link www.doctrine-project.org - * @since 2.5 */ class PostgreSQL91Platform extends PostgreSqlPlatform { @@ -59,9 +38,9 @@ public function getColumnCollationDeclarationSQL($collation) */ public function getListTableColumnsSQL($table, $database = null) { - $sql = parent::getListTableColumnsSQL($table, $database); + $sql = parent::getListTableColumnsSQL($table, $database); $parts = explode('AS complete_type,', $sql, 2); - return $parts[0].'AS complete_type, (SELECT tc.collcollate FROM pg_catalog.pg_collation tc WHERE tc.oid = a.attcollation) AS collation,'.$parts[1]; + return $parts[0] . 'AS complete_type, (SELECT tc.collcollate FROM pg_catalog.pg_collation tc WHERE tc.oid = a.attcollation) AS collation,' . $parts[1]; } } diff --git a/lib/Doctrine/DBAL/Platforms/PostgreSQL92Platform.php b/lib/Doctrine/DBAL/Platforms/PostgreSQL92Platform.php index 052b75fa4af..b302c0ceb83 100644 --- a/lib/Doctrine/DBAL/Platforms/PostgreSQL92Platform.php +++ b/lib/Doctrine/DBAL/Platforms/PostgreSQL92Platform.php @@ -1,32 +1,12 @@ . - */ namespace Doctrine\DBAL\Platforms; use Doctrine\DBAL\Types\Type; +use function sprintf; /** * Provides the behavior, features and SQL dialect of the PostgreSQL 9.2 database platform. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class PostgreSQL92Platform extends PostgreSQL91Platform { @@ -43,7 +23,7 @@ public function getJsonTypeDeclarationSQL(array $field) */ public function getSmallIntTypeDeclarationSQL(array $field) { - if ( ! empty($field['autoincrement'])) { + if (! empty($field['autoincrement'])) { return 'SMALLSERIAL'; } @@ -81,8 +61,9 @@ protected function initializeDoctrineTypeMappings() */ public function getCloseActiveDatabaseConnectionsSQL($database) { - $database = $this->quoteStringLiteral($database); - - return "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $database"; + return sprintf( + 'SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = %s', + $this->quoteStringLiteral($database) + ); } } diff --git a/lib/Doctrine/DBAL/Platforms/PostgreSQL94Platform.php b/lib/Doctrine/DBAL/Platforms/PostgreSQL94Platform.php index 68700b1962d..9db0ecbbd2a 100644 --- a/lib/Doctrine/DBAL/Platforms/PostgreSQL94Platform.php +++ b/lib/Doctrine/DBAL/Platforms/PostgreSQL94Platform.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms; @@ -23,10 +6,6 @@ /** * Provides the behavior, features and SQL dialect of the PostgreSQL 9.4 database platform. - * - * @author Matteo Beccati - * @link www.doctrine-project.org - * @since 2.6 */ class PostgreSQL94Platform extends PostgreSQL92Platform { @@ -35,7 +14,7 @@ class PostgreSQL94Platform extends PostgreSQL92Platform */ public function getJsonTypeDeclarationSQL(array $field) { - if (!empty($field['jsonb'])) { + if (! empty($field['jsonb'])) { return 'JSONB'; } diff --git a/lib/Doctrine/DBAL/Platforms/PostgreSqlPlatform.php b/lib/Doctrine/DBAL/Platforms/PostgreSqlPlatform.php index 04d431caf3d..cb4603f5199 100644 --- a/lib/Doctrine/DBAL/Platforms/PostgreSqlPlatform.php +++ b/lib/Doctrine/DBAL/Platforms/PostgreSqlPlatform.php @@ -1,35 +1,20 @@ . - */ namespace Doctrine\DBAL\Platforms; use Doctrine\DBAL\Schema\Column; use Doctrine\DBAL\Schema\ColumnDiff; +use Doctrine\DBAL\Schema\ForeignKeyConstraint; use Doctrine\DBAL\Schema\Identifier; use Doctrine\DBAL\Schema\Index; use Doctrine\DBAL\Schema\Sequence; use Doctrine\DBAL\Schema\TableDiff; -use Doctrine\DBAL\Types\BinaryType; use Doctrine\DBAL\Types\BigIntType; +use Doctrine\DBAL\Types\BinaryType; use Doctrine\DBAL\Types\BlobType; use Doctrine\DBAL\Types\IntegerType; use Doctrine\DBAL\Types\Type; +use UnexpectedValueException; use function array_diff; use function array_merge; use function array_unique; @@ -42,7 +27,7 @@ use function is_bool; use function is_numeric; use function is_string; -use function str_replace; +use function sprintf; use function strpos; use function strtolower; use function trim; @@ -50,22 +35,14 @@ /** * PostgreSqlPlatform. * - * @since 2.0 - * @author Roman Borschel - * @author Lukas Smith (PEAR MDB2 library) - * @author Benjamin Eberlei * @todo Rename: PostgreSQLPlatform */ class PostgreSqlPlatform extends AbstractPlatform { - /** - * @var bool - */ + /** @var bool */ private $useBooleanTrueFalseStrings = true; - /** - * @var array PostgreSQL booleans literals - */ + /** @var string[][] PostgreSQL booleans literals */ private $booleanLiterals = [ 'true' => [ 't', @@ -73,7 +50,7 @@ class PostgreSqlPlatform extends AbstractPlatform 'y', 'yes', 'on', - '1' + '1', ], 'false' => [ 'f', @@ -81,8 +58,8 @@ class PostgreSqlPlatform extends AbstractPlatform 'n', 'no', 'off', - '0' - ] + '0', + ], ]; /** @@ -134,10 +111,10 @@ public function getLocateExpression($str, $substr, $startPos = false) if ($startPos !== false) { $str = $this->getSubstringExpression($str, $startPos); - return 'CASE WHEN (POSITION('.$substr.' IN '.$str.') = 0) THEN 0 ELSE (POSITION('.$substr.' IN '.$str.') + '.($startPos-1).') END'; + return 'CASE WHEN (POSITION(' . $substr . ' IN ' . $str . ') = 0) THEN 0 ELSE (POSITION(' . $substr . ' IN ' . $str . ') + ' . ($startPos-1) . ') END'; } - return 'POSITION('.$substr.' IN '.$str.')'; + return 'POSITION(' . $substr . ' IN ' . $str . ')'; } /** @@ -150,7 +127,7 @@ protected function getDateArithmeticIntervalExpression($date, $operator, $interv $unit = DateIntervalUnit::MONTH; } - return "(" . $date ." " . $operator . " (" . $interval . " || ' " . $unit . "')::interval)"; + return '(' . $date . ' ' . $operator . ' (' . $interval . " || ' " . $unit . "')::interval)"; } /** @@ -304,13 +281,13 @@ public function getListViewsSQL($database) */ public function getListTableForeignKeysSQL($table, $database = null) { - return "SELECT quote_ident(r.conname) as conname, pg_catalog.pg_get_constraintdef(r.oid, true) as condef + return 'SELECT quote_ident(r.conname) as conname, pg_catalog.pg_get_constraintdef(r.oid, true) as condef FROM pg_catalog.pg_constraint r WHERE r.conrelid = ( SELECT c.oid FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n - WHERE " .$this->getTableWhereClause($table) ." AND n.oid = c.relnamespace + WHERE ' . $this->getTableWhereClause($table) . " AND n.oid = c.relnamespace ) AND r.contype = 'f'"; } @@ -328,7 +305,7 @@ public function getCreateViewSQL($name, $sql) */ public function getDropViewSQL($name) { - return 'DROP VIEW '. $name; + return 'DROP VIEW ' . $name; } /** @@ -339,36 +316,41 @@ public function getListTableConstraintsSQL($table) $table = new Identifier($table); $table = $this->quoteStringLiteral($table->getName()); - return "SELECT - quote_ident(relname) as relname - FROM - pg_class - WHERE oid IN ( - SELECT indexrelid - FROM pg_index, pg_class - WHERE pg_class.relname = $table - AND pg_class.oid = pg_index.indrelid - AND (indisunique = 't' OR indisprimary = 't') - )"; + return sprintf( + <<<'SQL' +SELECT + quote_ident(relname) as relname +FROM + pg_class +WHERE oid IN ( + SELECT indexrelid + FROM pg_index, pg_class + WHERE pg_class.relname = %s + AND pg_class.oid = pg_index.indrelid + AND (indisunique = 't' OR indisprimary = 't') + ) +SQL + , + $table + ); } /** * {@inheritDoc} * - * @license New BSD License * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html */ public function getListTableIndexesSQL($table, $currentDatabase = null) { - return "SELECT quote_ident(relname) as relname, pg_index.indisunique, pg_index.indisprimary, + return 'SELECT quote_ident(relname) as relname, pg_index.indisunique, pg_index.indisprimary, pg_index.indkey, pg_index.indrelid, pg_get_expr(indpred, indrelid) AS where FROM pg_class, pg_index WHERE oid IN ( SELECT indexrelid FROM pg_index si, pg_class sc, pg_namespace sn - WHERE " . $this->getTableWhereClause($table, 'sc', 'sn')." AND sc.oid=si.indrelid AND sc.relnamespace = sn.oid - ) AND pg_index.indexrelid = oid"; + WHERE ' . $this->getTableWhereClause($table, 'sc', 'sn') . ' AND sc.oid=si.indrelid AND sc.relnamespace = sn.oid + ) AND pg_index.indexrelid = oid'; } /** @@ -380,19 +362,24 @@ public function getListTableIndexesSQL($table, $currentDatabase = null) */ private function getTableWhereClause($table, $classAlias = 'c', $namespaceAlias = 'n') { - $whereClause = $namespaceAlias.".nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast') AND "; - if (strpos($table, ".") !== false) { - list($schema, $table) = explode(".", $table); - $schema = $this->quoteStringLiteral($schema); + $whereClause = $namespaceAlias . ".nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast') AND "; + if (strpos($table, '.') !== false) { + [$schema, $table] = explode('.', $table); + $schema = $this->quoteStringLiteral($schema); } else { $schema = "ANY(string_to_array((select replace(replace(setting,'\"\$user\"',user),' ','') from pg_catalog.pg_settings where name = 'search_path'),','))"; } $table = new Identifier($table); $table = $this->quoteStringLiteral($table->getName()); - $whereClause .= "$classAlias.relname = " . $table . " AND $namespaceAlias.nspname = $schema"; - return $whereClause; + return $whereClause . sprintf( + '%s.relname = %s AND %s.nspname = %s', + $classAlias, + $table, + $namespaceAlias, + $schema + ); } /** @@ -424,12 +411,12 @@ public function getListTableColumnsSQL($table, $database = null) FROM pg_description WHERE pg_description.objoid = c.oid AND a.attnum = pg_description.objsubid ) AS comment FROM pg_attribute a, pg_class c, pg_type t, pg_namespace n - WHERE ".$this->getTableWhereClause($table, 'c', 'n') ." + WHERE " . $this->getTableWhereClause($table, 'c', 'n') . ' AND a.attnum > 0 AND a.attrelid = c.oid AND a.atttypid = t.oid AND n.oid = c.relnamespace - ORDER BY a.attnum"; + ORDER BY a.attnum'; } /** @@ -451,7 +438,7 @@ public function getCreateDatabaseSQL($name) */ public function getDisallowDatabaseConnectionsSQL($database) { - return "UPDATE pg_database SET datallowconn = 'false' WHERE datname = '$database'"; + return "UPDATE pg_database SET datallowconn = 'false' WHERE datname = " . $this->quoteStringLiteral($database); } /** @@ -465,15 +452,14 @@ public function getDisallowDatabaseConnectionsSQL($database) */ public function getCloseActiveDatabaseConnectionsSQL($database) { - $database = $this->quoteStringLiteral($database); - - return "SELECT pg_terminate_backend(procpid) FROM pg_stat_activity WHERE datname = $database"; + return 'SELECT pg_terminate_backend(procpid) FROM pg_stat_activity WHERE datname = ' + . $this->quoteStringLiteral($database); } /** * {@inheritDoc} */ - public function getAdvancedForeignKeyOptionsSQL(\Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey) + public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey) { $query = ''; @@ -505,9 +491,9 @@ public function getAdvancedForeignKeyOptionsSQL(\Doctrine\DBAL\Schema\ForeignKey */ public function getAlterTableSQL(TableDiff $diff) { - $sql = []; + $sql = []; $commentsSQL = []; - $columnSql = []; + $columnSql = []; foreach ($diff->addedColumns as $column) { if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) { @@ -519,13 +505,15 @@ public function getAlterTableSQL(TableDiff $diff) $comment = $this->getColumnComment($column); - if (null !== $comment && '' !== $comment) { - $commentsSQL[] = $this->getCommentOnColumnSQL( - $diff->getName($this)->getQuotedName($this), - $column->getQuotedName($this), - $comment - ); + if ($comment === null || $comment === '') { + continue; } + + $commentsSQL[] = $this->getCommentOnColumnSQL( + $diff->getName($this)->getQuotedName($this), + $column->getQuotedName($this), + $comment + ); } foreach ($diff->removedColumns as $column) { @@ -548,13 +536,13 @@ public function getAlterTableSQL(TableDiff $diff) } $oldColumnName = $columnDiff->getOldColumnName()->getQuotedName($this); - $column = $columnDiff->column; + $column = $columnDiff->column; if ($columnDiff->hasChanged('type') || $columnDiff->hasChanged('precision') || $columnDiff->hasChanged('scale') || $columnDiff->hasChanged('fixed')) { $type = $column->getType(); // SERIAL/BIGSERIAL are not "real" types and we can't alter a column to that type - $columnDefinition = $column->toArray(); + $columnDefinition = $column->toArray(); $columnDefinition['autoincrement'] = false; // here was a server version check before, but DBAL API does not support this anymore. @@ -563,11 +551,11 @@ public function getAlterTableSQL(TableDiff $diff) } if ($columnDiff->hasChanged('default') || $this->typeChangeBreaksDefaultValue($columnDiff)) { - $defaultClause = null === $column->getDefault() + $defaultClause = $column->getDefault() === null ? ' DROP DEFAULT' : ' SET' . $this->getDefaultValueDeclarationSQL($column->toArray()); - $query = 'ALTER ' . $oldColumnName . $defaultClause; - $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query; + $query = 'ALTER ' . $oldColumnName . $defaultClause; + $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query; } if ($columnDiff->hasChanged('notnull')) { @@ -580,29 +568,34 @@ public function getAlterTableSQL(TableDiff $diff) // add autoincrement $seqName = $this->getIdentitySequenceName($diff->name, $oldColumnName); - $sql[] = "CREATE SEQUENCE " . $seqName; - $sql[] = "SELECT setval('" . $seqName . "', (SELECT MAX(" . $oldColumnName . ") FROM " . $diff->getName($this)->getQuotedName($this) . "))"; - $query = "ALTER " . $oldColumnName . " SET DEFAULT nextval('" . $seqName . "')"; - $sql[] = "ALTER TABLE " . $diff->getName($this)->getQuotedName($this) . " " . $query; + $sql[] = 'CREATE SEQUENCE ' . $seqName; + $sql[] = "SELECT setval('" . $seqName . "', (SELECT MAX(" . $oldColumnName . ') FROM ' . $diff->getName($this)->getQuotedName($this) . '))'; + $query = 'ALTER ' . $oldColumnName . " SET DEFAULT nextval('" . $seqName . "')"; + $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query; } else { // Drop autoincrement, but do NOT drop the sequence. It might be re-used by other tables or have - $query = "ALTER " . $oldColumnName . " " . "DROP DEFAULT"; - $sql[] = "ALTER TABLE " . $diff->getName($this)->getQuotedName($this) . " " . $query; + $query = 'ALTER ' . $oldColumnName . ' DROP DEFAULT'; + $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query; } } - if ($columnDiff->hasChanged('comment')) { + $newComment = $this->getColumnComment($column); + $oldComment = $this->getOldColumnComment($columnDiff); + + if ($columnDiff->hasChanged('comment') || ($columnDiff->fromColumn !== null && $oldComment !== $newComment)) { $commentsSQL[] = $this->getCommentOnColumnSQL( $diff->getName($this)->getQuotedName($this), $column->getQuotedName($this), - $this->getColumnComment($column) + $newComment ); } - if ($columnDiff->hasChanged('length')) { - $query = 'ALTER ' . $oldColumnName . ' TYPE ' . $column->getType()->getSQLDeclaration($column->toArray(), $this); - $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query; + if (! $columnDiff->hasChanged('length')) { + continue; } + + $query = 'ALTER ' . $oldColumnName . ' TYPE ' . $column->getType()->getSQLDeclaration($column->toArray(), $this); + $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query; } foreach ($diff->renamedColumns as $oldColumnName => $column) { @@ -618,7 +611,7 @@ public function getAlterTableSQL(TableDiff $diff) $tableSql = []; - if ( ! $this->onSchemaAlterTable($diff, $tableSql)) { + if (! $this->onSchemaAlterTable($diff, $tableSql)) { $sql = array_merge($sql, $commentsSQL); if ($diff->newName !== false) { @@ -653,7 +646,7 @@ private function isUnchangedBinaryColumn(ColumnDiff $columnDiff) { $columnType = $columnDiff->column->getType(); - if ( ! $columnType instanceof BinaryType && ! $columnType instanceof BlobType) { + if (! $columnType instanceof BinaryType && ! $columnType instanceof BlobType) { return false; } @@ -662,7 +655,7 @@ private function isUnchangedBinaryColumn(ColumnDiff $columnDiff) if ($fromColumn) { $fromColumnType = $fromColumn->getType(); - if ( ! $fromColumnType instanceof BinaryType && ! $fromColumnType instanceof BlobType) { + if (! $fromColumnType instanceof BinaryType && ! $fromColumnType instanceof BlobType) { return false; } @@ -682,7 +675,7 @@ private function isUnchangedBinaryColumn(ColumnDiff $columnDiff) protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName) { if (strpos($tableName, '.') !== false) { - list($schema) = explode('.', $tableName); + [$schema] = explode('.', $tableName); $oldIndexName = $schema . '.' . $oldIndexName; } @@ -694,12 +687,16 @@ protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName) */ public function getCommentOnColumnSQL($tableName, $columnName, $comment) { - $tableName = new Identifier($tableName); + $tableName = new Identifier($tableName); $columnName = new Identifier($columnName); - $comment = $comment === null ? 'NULL' : $this->quoteStringLiteral($comment); + $comment = $comment === null ? 'NULL' : $this->quoteStringLiteral($comment); - return "COMMENT ON COLUMN " . $tableName->getQuotedName($this) . "." . $columnName->getQuotedName($this) . - " IS $comment"; + return sprintf( + 'COMMENT ON COLUMN %s.%s IS %s', + $tableName->getQuotedName($this), + $columnName->getQuotedName($this), + $comment + ); } /** @@ -727,8 +724,6 @@ public function getAlterSequenceSQL(Sequence $sequence) /** * Cache definition for sequences * - * @param Sequence $sequence - * * @return string */ private function getSequenceCacheSQL(Sequence $sequence) @@ -776,7 +771,7 @@ protected function _getCreateTableSQL($tableName, array $columns, array $options $queryFields = $this->getColumnDeclarationListSQL($columns); if (isset($options['primary']) && ! empty($options['primary'])) { - $keyColumns = array_unique(array_values($options['primary'])); + $keyColumns = array_unique(array_values($options['primary'])); $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')'; } @@ -810,11 +805,12 @@ protected function _getCreateTableSQL($tableName, array $columns, array $options * @param callable $callback The callback function to use for converting the real boolean value. * * @return mixed - * @throws \UnexpectedValueException + * + * @throws UnexpectedValueException */ private function convertSingleBooleanValue($value, $callback) { - if (null === $value) { + if ($value === null) { return $callback(null); } @@ -822,7 +818,7 @@ private function convertSingleBooleanValue($value, $callback) return $callback($value ? true : false); } - if (!is_string($value)) { + if (! is_string($value)) { return $callback(true); } @@ -837,7 +833,7 @@ private function convertSingleBooleanValue($value, $callback) return $callback(true); } - throw new \UnexpectedValueException("Unrecognized boolean literal '${value}'"); + throw new UnexpectedValueException("Unrecognized boolean literal '${value}'"); } /** @@ -872,18 +868,18 @@ private function doConvertBooleans($item, $callback) */ public function convertBooleans($item) { - if ( ! $this->useBooleanTrueFalseStrings) { + if (! $this->useBooleanTrueFalseStrings) { return parent::convertBooleans($item); } return $this->doConvertBooleans( $item, - function ($boolean) { - if (null === $boolean) { + static function ($boolean) { + if ($boolean === null) { return 'NULL'; } - return true === $boolean ? 'true' : 'false'; + return $boolean === true ? 'true' : 'false'; } ); } @@ -893,14 +889,14 @@ function ($boolean) { */ public function convertBooleansToDatabaseValue($item) { - if ( ! $this->useBooleanTrueFalseStrings) { + if (! $this->useBooleanTrueFalseStrings) { return parent::convertBooleansToDatabaseValue($item); } return $this->doConvertBooleans( $item, - function ($boolean) { - return null === $boolean ? null : (int) $boolean; + static function ($boolean) { + return $boolean === null ? null : (int) $boolean; } ); } @@ -947,7 +943,7 @@ public function getBooleanTypeDeclarationSQL(array $field) */ public function getIntegerTypeDeclarationSQL(array $field) { - if ( ! empty($field['autoincrement'])) { + if (! empty($field['autoincrement'])) { return 'SERIAL'; } @@ -959,7 +955,7 @@ public function getIntegerTypeDeclarationSQL(array $field) */ public function getBigIntTypeDeclarationSQL(array $field) { - if ( ! empty($field['autoincrement'])) { + if (! empty($field['autoincrement'])) { return 'BIGSERIAL'; } @@ -1097,7 +1093,7 @@ public function getEmptyIdentityInsertSQL($quotedTableName, $quotedIdentifierCol public function getTruncateTableSQL($tableName, $cascade = false) { $tableIdentifier = new Identifier($tableName); - $sql = 'TRUNCATE ' . $tableIdentifier->getQuotedName($this); + $sql = 'TRUNCATE ' . $tableIdentifier->getQuotedName($this); if ($cascade) { $sql .= ' CASCADE'; @@ -1202,16 +1198,6 @@ public function getBlobTypeDeclarationSQL(array $field) return 'BYTEA'; } - /** - * {@inheritdoc} - */ - public function quoteStringLiteral($str) - { - $str = str_replace('\\', '\\\\', $str); // PostgreSQL requires backslashes to be escaped aswell. - - return parent::quoteStringLiteral($str); - } - /** * {@inheritdoc} */ @@ -1224,6 +1210,9 @@ public function getDefaultValueDeclarationSQL($field) return parent::getDefaultValueDeclarationSQL($field); } + /** + * @param mixed[] $field + */ private function isSerialField(array $field) : bool { return $field['autoincrement'] ?? false === true && isset($field['type']) @@ -1232,9 +1221,6 @@ private function isSerialField(array $field) : bool /** * Check whether the type of a column is changed in a way that invalidates the default value for the column - * - * @param ColumnDiff $columnDiff - * @return bool */ private function typeChangeBreaksDefaultValue(ColumnDiff $columnDiff) : bool { @@ -1254,4 +1240,9 @@ private function isNumericType(Type $type) : bool { return $type instanceof IntegerType || $type instanceof BigIntType; } + + private function getOldColumnComment(ColumnDiff $columnDiff) : ?string + { + return $columnDiff->fromColumn ? $this->getColumnComment($columnDiff->fromColumn) : null; + } } diff --git a/lib/Doctrine/DBAL/Platforms/SQLAnywhere11Platform.php b/lib/Doctrine/DBAL/Platforms/SQLAnywhere11Platform.php index e2773696072..a46ae9352c4 100644 --- a/lib/Doctrine/DBAL/Platforms/SQLAnywhere11Platform.php +++ b/lib/Doctrine/DBAL/Platforms/SQLAnywhere11Platform.php @@ -1,31 +1,10 @@ . - */ namespace Doctrine\DBAL\Platforms; /** * The SQLAnywhere11Platform provides the behavior, features and SQL dialect of the * SAP Sybase SQL Anywhere 11 database platform. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class SQLAnywhere11Platform extends SQLAnywherePlatform { diff --git a/lib/Doctrine/DBAL/Platforms/SQLAnywhere12Platform.php b/lib/Doctrine/DBAL/Platforms/SQLAnywhere12Platform.php index 1b52bfee56e..dd73ef736ad 100644 --- a/lib/Doctrine/DBAL/Platforms/SQLAnywhere12Platform.php +++ b/lib/Doctrine/DBAL/Platforms/SQLAnywhere12Platform.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms; @@ -25,10 +8,6 @@ /** * The SQLAnywhere12Platform provides the behavior, features and SQL dialect of the * SAP Sybase SQL Anywhere 12 database platform. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class SQLAnywhere12Platform extends SQLAnywhere11Platform { @@ -109,7 +88,7 @@ public function supportsSequences() */ protected function getAdvancedIndexOptionsSQL(Index $index) { - if ( ! $index->isPrimary() && $index->isUnique() && $index->hasFlag('with_nulls_not_distinct')) { + if (! $index->isPrimary() && $index->isUnique() && $index->hasFlag('with_nulls_not_distinct')) { return ' WITH NULLS NOT DISTINCT' . parent::getAdvancedIndexOptionsSQL($index); } diff --git a/lib/Doctrine/DBAL/Platforms/SQLAnywhere16Platform.php b/lib/Doctrine/DBAL/Platforms/SQLAnywhere16Platform.php index 1d59e2c0043..35d4238e4a3 100644 --- a/lib/Doctrine/DBAL/Platforms/SQLAnywhere16Platform.php +++ b/lib/Doctrine/DBAL/Platforms/SQLAnywhere16Platform.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms; @@ -25,10 +8,6 @@ /** * The SQLAnywhere16Platform provides the behavior, features and SQL dialect of the * SAP Sybase SQL Anywhere 16 database platform. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class SQLAnywhere16Platform extends SQLAnywhere12Platform { @@ -43,7 +22,7 @@ protected function getAdvancedIndexOptionsSQL(Index $index) ); } - if ( ! $index->isPrimary() && $index->isUnique() && $index->hasFlag('with_nulls_distinct')) { + if (! $index->isPrimary() && $index->isUnique() && $index->hasFlag('with_nulls_distinct')) { return ' WITH NULLS DISTINCT' . parent::getAdvancedIndexOptionsSQL($index); } diff --git a/lib/Doctrine/DBAL/Platforms/SQLAnywherePlatform.php b/lib/Doctrine/DBAL/Platforms/SQLAnywherePlatform.php index 79a6e483ab9..a8fbfeb46e4 100644 --- a/lib/Doctrine/DBAL/Platforms/SQLAnywherePlatform.php +++ b/lib/Doctrine/DBAL/Platforms/SQLAnywherePlatform.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms; @@ -30,6 +13,7 @@ use Doctrine\DBAL\Schema\Table; use Doctrine\DBAL\Schema\TableDiff; use Doctrine\DBAL\TransactionIsolationLevel; +use InvalidArgumentException; use function array_merge; use function array_unique; use function array_values; @@ -40,6 +24,7 @@ use function implode; use function is_string; use function preg_replace; +use function sprintf; use function strlen; use function strpos; use function strtoupper; @@ -48,29 +33,13 @@ /** * The SQLAnywherePlatform provides the behavior, features and SQL dialect of the * SAP Sybase SQL Anywhere 10 database platform. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class SQLAnywherePlatform extends AbstractPlatform { - /** - * @var int - */ - const FOREIGN_KEY_MATCH_SIMPLE = 1; - /** - * @var int - */ - const FOREIGN_KEY_MATCH_FULL = 2; - /** - * @var int - */ - const FOREIGN_KEY_MATCH_SIMPLE_UNIQUE = 129; - /** - * @var int - */ - const FOREIGN_KEY_MATCH_FULL_UNIQUE = 130; + 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; /** * {@inheritdoc} @@ -121,15 +90,15 @@ public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey); - if ($foreignKey->hasOption('check_on_commit') && (boolean) $foreignKey->getOption('check_on_commit')) { + if ($foreignKey->hasOption('check_on_commit') && (bool) $foreignKey->getOption('check_on_commit')) { $query .= ' CHECK ON COMMIT'; } - if ($foreignKey->hasOption('clustered') && (boolean) $foreignKey->getOption('clustered')) { + if ($foreignKey->hasOption('clustered') && (bool) $foreignKey->getOption('clustered')) { $query .= ' CLUSTERED'; } - if ($foreignKey->hasOption('for_olap_workload') && (boolean) $foreignKey->getOption('for_olap_workload')) { + if ($foreignKey->hasOption('for_olap_workload') && (bool) $foreignKey->getOption('for_olap_workload')) { $query .= ' FOR OLAP WORKLOAD'; } @@ -147,7 +116,6 @@ public function getAlterTableSQL(TableDiff $diff) $tableSql = []; $alterClauses = []; - /** @var \Doctrine\DBAL\Schema\Column $column */ foreach ($diff->addedColumns as $column) { if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) { continue; @@ -157,16 +125,17 @@ public function getAlterTableSQL(TableDiff $diff) $comment = $this->getColumnComment($column); - if (null !== $comment && '' !== $comment) { - $commentsSQL[] = $this->getCommentOnColumnSQL( - $diff->getName($this)->getQuotedName($this), - $column->getQuotedName($this), - $comment - ); + if ($comment === null || $comment === '') { + continue; } + + $commentsSQL[] = $this->getCommentOnColumnSQL( + $diff->getName($this)->getQuotedName($this), + $column->getQuotedName($this), + $comment + ); } - /** @var \Doctrine\DBAL\Schema\Column $column */ foreach ($diff->removedColumns as $column) { if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) { continue; @@ -175,7 +144,6 @@ public function getAlterTableSQL(TableDiff $diff) $alterClauses[] = $this->getAlterTableRemoveColumnClause($column); } - /** @var \Doctrine\DBAL\Schema\ColumnDiff $columnDiff */ foreach ($diff->changedColumns as $columnDiff) { if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) { continue; @@ -183,19 +151,21 @@ public function getAlterTableSQL(TableDiff $diff) $alterClause = $this->getAlterTableChangeColumnClause($columnDiff); - if (null !== $alterClause) { + if ($alterClause !== null) { $alterClauses[] = $alterClause; } - if ($columnDiff->hasChanged('comment')) { - $column = $columnDiff->column; - - $commentsSQL[] = $this->getCommentOnColumnSQL( - $diff->getName($this)->getQuotedName($this), - $column->getQuotedName($this), - $this->getColumnComment($column) - ); + if (! $columnDiff->hasChanged('comment')) { + continue; } + + $column = $columnDiff->column; + + $commentsSQL[] = $this->getCommentOnColumnSQL( + $diff->getName($this)->getQuotedName($this), + $column->getQuotedName($this), + $this->getColumnComment($column) + ); } foreach ($diff->renamedColumns as $oldColumnName => $column) { @@ -207,9 +177,9 @@ public function getAlterTableSQL(TableDiff $diff) $this->getAlterTableRenameColumnClause($oldColumnName, $column); } - if ( ! $this->onSchemaAlterTable($diff, $tableSql)) { - if ( ! empty($alterClauses)) { - $sql[] = $this->getAlterTableClause($diff->getName($this)) . ' ' . implode(", ", $alterClauses); + if (! $this->onSchemaAlterTable($diff, $tableSql)) { + if (! empty($alterClauses)) { + $sql[] = $this->getAlterTableClause($diff->getName($this)) . ' ' . implode(', ', $alterClauses); } $sql = array_merge($sql, $commentsSQL); @@ -277,7 +247,7 @@ protected function getAlterTableRenameColumnClause($oldColumnName, Column $colum { $oldColumnName = new Identifier($oldColumnName); - return 'RENAME ' . $oldColumnName->getQuotedName($this) .' TO ' . $column->getQuotedName($this); + return 'RENAME ' . $oldColumnName->getQuotedName($this) . ' TO ' . $column->getQuotedName($this); } /** @@ -307,11 +277,11 @@ protected function getAlterTableChangeColumnClause(ColumnDiff $columnDiff) $column = $columnDiff->column; // Do not return alter clause if only comment has changed. - if ( ! ($columnDiff->hasChanged('comment') && count($columnDiff->changedProperties) === 1)) { + if (! ($columnDiff->hasChanged('comment') && count($columnDiff->changedProperties) === 1)) { $columnAlterationClause = 'ALTER ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray()); - if ($columnDiff->hasChanged('default') && null === $column->getDefault()) { + if ($columnDiff->hasChanged('default') && $column->getDefault() === null) { $columnAlterationClause .= ', ALTER ' . $column->getQuotedName($this) . ' DROP DEFAULT'; } @@ -365,7 +335,7 @@ public function getBlobTypeDeclarationSQL(array $field) */ public function getBooleanTypeDeclarationSQL(array $columnDef) { - $nullClause = isset($columnDef['notnull']) && (boolean) $columnDef['notnull'] === false ? ' NULL' : ''; + $nullClause = isset($columnDef['notnull']) && (bool) $columnDef['notnull'] === false ? ' NULL' : ''; return 'BIT' . $nullClause; } @@ -383,12 +353,16 @@ public function getClobTypeDeclarationSQL(array $field) */ public function getCommentOnColumnSQL($tableName, $columnName, $comment) { - $tableName = new Identifier($tableName); + $tableName = new Identifier($tableName); $columnName = new Identifier($columnName); - $comment = $comment === null ? 'NULL' : $this->quoteStringLiteral($comment); + $comment = $comment === null ? 'NULL' : $this->quoteStringLiteral($comment); - return "COMMENT ON COLUMN " . $tableName->getQuotedName($this) . '.' . $columnName->getQuotedName($this) . - " IS $comment"; + return sprintf( + 'COMMENT ON COLUMN %s.%s IS %s', + $tableName->getQuotedName($this), + $columnName->getQuotedName($this), + $comment + ); } /** @@ -433,7 +407,7 @@ public function getCreateDatabaseSQL($database) */ public function getCreateIndexSQL(Index $index, $table) { - return parent::getCreateIndexSQL($index, $table). $this->getAdvancedIndexOptionsSQL($index); + return parent::getCreateIndexSQL($index, $table) . $this->getAdvancedIndexOptionsSQL($index); } /** @@ -495,7 +469,7 @@ protected function getDateArithmeticIntervalExpression($date, $operator, $interv { $factorClause = ''; - if ('-' === $operator) { + if ($operator === '-') { $factorClause = '-1 * '; } @@ -569,14 +543,13 @@ public function getDropIndexSQL($index, $table = null) $index = $index->getQuotedName($this); } - if ( ! is_string($index)) { - throw new \InvalidArgumentException( - 'SQLAnywherePlatform::getDropIndexSQL() expects $index parameter to be string or ' . - '\Doctrine\DBAL\Schema\Index.' + if (! is_string($index)) { + throw new InvalidArgumentException( + 'SQLAnywherePlatform::getDropIndexSQL() expects $index parameter to be string or ' . Index::class . '.' ); } - if ( ! isset($table)) { + if (! isset($table)) { return 'DROP INDEX ' . $index; } @@ -584,10 +557,9 @@ public function getDropIndexSQL($index, $table = null) $table = $table->getQuotedName($this); } - if ( ! is_string($table)) { - throw new \InvalidArgumentException( - 'SQLAnywherePlatform::getDropIndexSQL() expects $table parameter to be string or ' . - '\Doctrine\DBAL\Schema\Table.' + if (! is_string($table)) { + throw new InvalidArgumentException( + 'SQLAnywherePlatform::getDropIndexSQL() expects $table parameter to be string or ' . Index::class . '.' ); } @@ -613,23 +585,23 @@ public function getForeignKeyBaseDeclarationSQL(ForeignKeyConstraint $foreignKey $foreignColumns = $foreignKey->getQuotedForeignColumns($this); $foreignTableName = $foreignKey->getQuotedForeignTableName($this); - if ( ! empty($foreignKeyName)) { + if (! empty($foreignKeyName)) { $sql .= 'CONSTRAINT ' . $foreignKey->getQuotedName($this) . ' '; } if (empty($localColumns)) { - throw new \InvalidArgumentException("Incomplete definition. 'local' required."); + throw new InvalidArgumentException("Incomplete definition. 'local' required."); } if (empty($foreignColumns)) { - throw new \InvalidArgumentException("Incomplete definition. 'foreign' required."); + throw new InvalidArgumentException("Incomplete definition. 'foreign' required."); } if (empty($foreignTableName)) { - throw new \InvalidArgumentException("Incomplete definition. 'foreignTable' required."); + throw new InvalidArgumentException("Incomplete definition. 'foreignTable' required."); } - if ($foreignKey->hasOption('notnull') && (boolean) $foreignKey->getOption('notnull')) { + if ($foreignKey->hasOption('notnull') && (bool) $foreignKey->getOption('notnull')) { $sql .= 'NOT NULL '; } @@ -646,7 +618,7 @@ public function getForeignKeyBaseDeclarationSQL(ForeignKeyConstraint $foreignKey * * @return string * - * @throws \InvalidArgumentException if unknown match type given + * @throws InvalidArgumentException If unknown match type given. */ public function getForeignKeyMatchClauseSQL($type) { @@ -663,7 +635,7 @@ public function getForeignKeyMatchClauseSQL($type) case self::FOREIGN_KEY_MATCH_FULL_UNIQUE: return 'UNIQUE FULL'; default: - throw new \InvalidArgumentException('Invalid foreign key match type: ' . $type); + throw new InvalidArgumentException('Invalid foreign key match type: ' . $type); } } @@ -741,26 +713,33 @@ public function getListTableColumnsSQL($table, $database = null) $user = 'USER_NAME()'; if (strpos($table, '.') !== false) { - list($user, $table) = explode('.', $table); - $user = $this->quoteStringLiteral($user); + [$user, $table] = explode('.', $table); + $user = $this->quoteStringLiteral($user); } - return "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 \"$table\"') 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 = $user - ORDER BY def.base_column_id ASC"; + 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 + ); } /** @@ -773,18 +752,25 @@ public function getListTableConstraintsSQL($table) $user = ''; if (strpos($table, '.') !== false) { - list($user, $table) = explode('.', $table); - $user = $this->quoteStringLiteral($user); - $table = $this->quoteStringLiteral($table); + [$user, $table] = explode('.', $table); + $user = $this->quoteStringLiteral($user); + $table = $this->quoteStringLiteral($table); } else { $table = $this->quoteStringLiteral($table); } - return "SELECT con.* - FROM SYS.SYSCONSTRAINT AS con - JOIN SYS.SYSTAB AS tab ON con.table_object_id = tab.object_id - WHERE tab.table_name = $table - AND tab.creator = USER_ID($user)"; + 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 + ); } /** @@ -795,82 +781,89 @@ public function getListTableForeignKeysSQL($table) $user = ''; if (strpos($table, '.') !== false) { - list($user, $table) = explode('.', $table); - $user = $this->quoteStringLiteral($user); - $table = $this->quoteStringLiteral($table); + [$user, $table] = explode('.', $table); + $user = $this->quoteStringLiteral($user); + $table = $this->quoteStringLiteral($table); } else { $table = $this->quoteStringLiteral($table); } - return "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 = $table - AND ftbl.creator = USER_ID($user) - ORDER BY fk.foreign_index_id ASC, idxcol.sequence ASC"; + 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 + ); } /** @@ -881,49 +874,56 @@ public function getListTableIndexesSQL($table, $currentDatabase = null) $user = ''; if (strpos($table, '.') !== false) { - list($user, $table) = explode('.', $table); - $user = $this->quoteStringLiteral($user); - $table = $this->quoteStringLiteral($table); + [$user, $table] = explode('.', $table); + $user = $this->quoteStringLiteral($user); + $table = $this->quoteStringLiteral($table); } else { $table = $this->quoteStringLiteral($table); } - return "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 = $table - AND tbl.creator = USER_ID($user) - AND idx.index_category != 2 -- exclude indexes implicitly created by foreign key constraints - ORDER BY idx.index_id ASC, idxcol.sequence ASC"; + 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 + ); } /** @@ -970,7 +970,7 @@ public function getListViewsSQL($database) */ public function getLocateExpression($str, $substr, $startPos = false) { - if ($startPos == false) { + if ($startPos === false) { return 'LOCATE(' . $str . ', ' . $substr . ')'; } @@ -990,7 +990,7 @@ public function getMaxIdentifierLength() */ public function getMd5Expression($column) { - return "HASH(" . $column . ", 'MD5')"; + return 'HASH(' . $column . ", 'MD5')"; } /** @@ -1010,12 +1010,12 @@ public function getName() * * @return string DBMS specific SQL code portion needed to set a primary key * - * @throws \InvalidArgumentException if the given index is not a primary key. + * @throws InvalidArgumentException If the given index is not a primary key. */ public function getPrimaryKeyDeclarationSQL(Index $index, $name = null) { - if ( ! $index->isPrimary()) { - throw new \InvalidArgumentException( + if (! $index->isPrimary()) { + throw new InvalidArgumentException( 'Can only create primary key declarations with getPrimaryKeyDeclarationSQL()' ); } @@ -1085,7 +1085,7 @@ public function getStopDatabaseSQL($database) */ public function getSubstringExpression($value, $from, $length = null) { - if (null === $length) { + if ($length === null) { return 'SUBSTRING(' . $value . ', ' . $from . ')'; } @@ -1121,7 +1121,7 @@ public function getTimeTypeDeclarationSQL(array $fieldDeclaration) */ public function getTrimExpression($str, $pos = TrimMode::UNSPECIFIED, $char = false) { - if ( ! $char) { + if (! $char) { switch ($pos) { case TrimMode::LEADING: return $this->getLtrimExpression($str); @@ -1132,7 +1132,7 @@ public function getTrimExpression($str, $pos = TrimMode::UNSPECIFIED, $char = fa } } - $pattern = "'%[^' + $char + ']%'"; + $pattern = "'%[^' + " . $char . " + ']%'"; switch ($pos) { case TrimMode::LEADING: @@ -1140,8 +1140,7 @@ public function getTrimExpression($str, $pos = TrimMode::UNSPECIFIED, $char = fa case TrimMode::TRAILING: return 'REVERSE(SUBSTR(REVERSE(' . $str . '), PATINDEX(' . $pattern . ', REVERSE(' . $str . '))))'; default: - return - 'REVERSE(SUBSTR(REVERSE(SUBSTR(' . $str . ', PATINDEX(' . $pattern . ', ' . $str . '))), ' . + return 'REVERSE(SUBSTR(REVERSE(SUBSTR(' . $str . ', PATINDEX(' . $pattern . ', ' . $str . '))), ' . 'PATINDEX(' . $pattern . ', REVERSE(SUBSTR(' . $str . ', PATINDEX(' . $pattern . ', ' . $str . '))))))'; } } @@ -1162,13 +1161,13 @@ public function getTruncateTableSQL($tableName, $cascade = false) public function getUniqueConstraintDeclarationSQL($name, Index $index) { if ($index->isPrimary()) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Cannot create primary key constraint declarations with getUniqueConstraintDeclarationSQL().' ); } - if ( ! $index->isUnique()) { - throw new \InvalidArgumentException( + if (! $index->isUnique()) { + throw new InvalidArgumentException( 'Can only create unique constraint declarations, no common index declarations with ' . 'getUniqueConstraintDeclarationSQL().' ); @@ -1242,22 +1241,22 @@ protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) protected function _getCreateTableSQL($tableName, array $columns, array $options = []) { $columnListSql = $this->getColumnDeclarationListSQL($columns); - $indexSql = []; + $indexSql = []; - if ( ! empty($options['uniqueConstraints'])) { + if (! empty($options['uniqueConstraints'])) { foreach ((array) $options['uniqueConstraints'] as $name => $definition) { $columnListSql .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition); } } - if ( ! empty($options['indexes'])) { - /** @var \Doctrine\DBAL\Schema\Index $index */ + if (! empty($options['indexes'])) { + /** @var Index $index */ foreach ((array) $options['indexes'] as $index) { $indexSql[] = $this->getCreateIndexSQL($index, $tableName); } } - if ( ! empty($options['primary'])) { + if (! empty($options['primary'])) { $flags = ''; if (isset($options['primary_index']) && $options['primary_index']->hasFlag('clustered')) { @@ -1267,7 +1266,7 @@ protected function _getCreateTableSQL($tableName, array $columns, array $options $columnListSql .= ', PRIMARY KEY' . $flags . ' (' . implode(', ', array_unique(array_values((array) $options['primary']))) . ')'; } - if ( ! empty($options['foreignKeys'])) { + if (! empty($options['foreignKeys'])) { foreach ((array) $options['foreignKeys'] as $definition) { $columnListSql .= ', ' . $this->getForeignKeyDeclarationSQL($definition); } @@ -1276,7 +1275,7 @@ protected function _getCreateTableSQL($tableName, array $columns, array $options $query = 'CREATE TABLE ' . $tableName . ' (' . $columnListSql; $check = $this->getCheckDeclarationSQL($columns); - if ( ! empty($check)) { + if (! empty($check)) { $query .= ', ' . $check; } @@ -1300,7 +1299,7 @@ protected function _getTransactionIsolationLevelSQL($level) case TransactionIsolationLevel::SERIALIZABLE: return 3; default: - throw new \InvalidArgumentException('Invalid isolation level:' . $level); + throw new InvalidArgumentException('Invalid isolation level:' . $level); } } @@ -1316,7 +1315,7 @@ protected function doModifyLimitQuery($query, $limit, $offset) } if ($offset > 0) { - if ($limit == 0) { + if ($limit === 0) { $limitOffsetClause = 'TOP ALL '; } @@ -1342,7 +1341,7 @@ protected function getAdvancedIndexOptionsSQL(Index $index) { $sql = ''; - if ( ! $index->isPrimary() && $index->hasFlag('for_olap_workload')) { + if (! $index->isPrimary() && $index->hasFlag('for_olap_workload')) { $sql .= ' FOR OLAP WORKLOAD'; } @@ -1367,7 +1366,7 @@ protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed) * * @return string * - * @throws \InvalidArgumentException if the given table constraint type is not supported by this method. + * @throws InvalidArgumentException If the given table constraint type is not supported by this method. */ protected function getTableConstraintDeclarationSQL(Constraint $constraint, $name = null) { @@ -1375,12 +1374,12 @@ protected function getTableConstraintDeclarationSQL(Constraint $constraint, $nam return $this->getForeignKeyDeclarationSQL($constraint); } - if ( ! $constraint instanceof Index) { - throw new \InvalidArgumentException('Unsupported constraint type: ' . get_class($constraint)); + if (! $constraint instanceof Index) { + throw new InvalidArgumentException('Unsupported constraint type: ' . get_class($constraint)); } - if ( ! $constraint->isPrimary() && ! $constraint->isUnique()) { - throw new \InvalidArgumentException( + if (! $constraint->isPrimary() && ! $constraint->isUnique()) { + throw new InvalidArgumentException( 'Can only create primary, unique or foreign key constraint declarations, no common index declarations ' . 'with getTableConstraintDeclarationSQL().' ); @@ -1389,13 +1388,13 @@ protected function getTableConstraintDeclarationSQL(Constraint $constraint, $nam $constraintColumns = $constraint->getQuotedColumns($this); if (empty($constraintColumns)) { - throw new \InvalidArgumentException("Incomplete definition. 'columns' required."); + throw new InvalidArgumentException("Incomplete definition. 'columns' required."); } $sql = ''; $flags = ''; - if ( ! empty($name)) { + if (! empty($name)) { $name = new Identifier($name); $sql .= 'CONSTRAINT ' . $name->getQuotedName($this) . ' '; } @@ -1405,10 +1404,10 @@ protected function getTableConstraintDeclarationSQL(Constraint $constraint, $nam } if ($constraint->isPrimary()) { - return $sql . 'PRIMARY KEY ' . $flags . '('. $this->getIndexFieldDeclarationListSQL($constraintColumns) . ')'; + return $sql . 'PRIMARY KEY ' . $flags . '(' . $this->getIndexFieldDeclarationListSQL($constraintColumns) . ')'; } - return $sql . 'UNIQUE ' . $flags . '('. $this->getIndexFieldDeclarationListSQL($constraintColumns) . ')'; + return $sql . 'UNIQUE ' . $flags . '(' . $this->getIndexFieldDeclarationListSQL($constraintColumns) . ')'; } /** @@ -1437,9 +1436,7 @@ protected function getCreateIndexSQLFlags(Index $index) */ protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName) { - return [ - 'ALTER INDEX ' . $oldIndexName . ' ON ' . $tableName . ' RENAME TO ' . $index->getQuotedName($this) - ]; + return ['ALTER INDEX ' . $oldIndexName . ' ON ' . $tableName . ' RENAME TO ' . $index->getQuotedName($this)]; } /** @@ -1487,9 +1484,9 @@ protected function initializeDoctrineTypeMappings() 'unsigned int' => 'integer', 'numeric' => 'decimal', 'smallint' => 'smallint', - 'unsigned smallint', 'smallint', + 'unsigned smallint' => 'smallint', 'tinyint' => 'smallint', - 'unsigned tinyint', 'smallint', + 'unsigned tinyint' => 'smallint', 'money' => 'decimal', 'smallmoney' => 'decimal', 'long varbit' => 'text', diff --git a/lib/Doctrine/DBAL/Platforms/SQLAzurePlatform.php b/lib/Doctrine/DBAL/Platforms/SQLAzurePlatform.php index 71829cd0e0d..a104848f84e 100644 --- a/lib/Doctrine/DBAL/Platforms/SQLAzurePlatform.php +++ b/lib/Doctrine/DBAL/Platforms/SQLAzurePlatform.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms; @@ -33,7 +16,7 @@ class SQLAzurePlatform extends SQLServer2008Platform /** * {@inheritDoc} */ - public function getCreateTableSQL(Table $table, $createFlags=self::CREATE_INDEXES) + public function getCreateTableSQL(Table $table, $createFlags = self::CREATE_INDEXES) { $sql = parent::getCreateTableSQL($table, $createFlags); @@ -42,7 +25,7 @@ public function getCreateTableSQL(Table $table, $createFlags=self::CREATE_INDEXE $columnName = $table->getOption('azure.federatedOnColumnName'); $stmt = ' FEDERATED ON (' . $distributionName . ' = ' . $columnName . ')'; - $sql[0] = $sql[0] . $stmt; + $sql[0] .= $stmt; } return $sql; diff --git a/lib/Doctrine/DBAL/Platforms/SQLServer2005Platform.php b/lib/Doctrine/DBAL/Platforms/SQLServer2005Platform.php index af42f516641..1026a934f00 100644 --- a/lib/Doctrine/DBAL/Platforms/SQLServer2005Platform.php +++ b/lib/Doctrine/DBAL/Platforms/SQLServer2005Platform.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms; diff --git a/lib/Doctrine/DBAL/Platforms/SQLServer2008Platform.php b/lib/Doctrine/DBAL/Platforms/SQLServer2008Platform.php index b9a672e6c4b..c2e36f34e67 100644 --- a/lib/Doctrine/DBAL/Platforms/SQLServer2008Platform.php +++ b/lib/Doctrine/DBAL/Platforms/SQLServer2008Platform.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms; @@ -111,9 +94,9 @@ public function getTimeFormatString() protected function initializeDoctrineTypeMappings() { parent::initializeDoctrineTypeMappings(); - $this->doctrineTypeMapping['datetime2'] = 'datetime'; - $this->doctrineTypeMapping['date'] = 'date'; - $this->doctrineTypeMapping['time'] = 'time'; + $this->doctrineTypeMapping['datetime2'] = 'datetime'; + $this->doctrineTypeMapping['date'] = 'date'; + $this->doctrineTypeMapping['time'] = 'time'; $this->doctrineTypeMapping['datetimeoffset'] = 'datetimetz'; } diff --git a/lib/Doctrine/DBAL/Platforms/SQLServer2012Platform.php b/lib/Doctrine/DBAL/Platforms/SQLServer2012Platform.php index c95d7b05f5d..009a37d33b0 100644 --- a/lib/Doctrine/DBAL/Platforms/SQLServer2012Platform.php +++ b/lib/Doctrine/DBAL/Platforms/SQLServer2012Platform.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms; @@ -30,8 +13,6 @@ * * Differences to SQL Server 2008 and before are that sequences are introduced, * and support for the new OFFSET... FETCH syntax for result pagination has been added. - * - * @author Steve Müller */ class SQLServer2012Platform extends SQLServer2008Platform { @@ -120,15 +101,15 @@ protected function doModifyLimitQuery($query, $limit, $offset = null) // Queries using OFFSET... FETCH MUST have an ORDER BY clause // Find the position of the last instance of ORDER BY and ensure it is not within a parenthetical statement // but can be in a newline - $matches = []; - $matchesCount = preg_match_all("/[\\s]+order\\s+by\\s/im", $query, $matches, PREG_OFFSET_CAPTURE); - $orderByPos = false; + $matches = []; + $matchesCount = preg_match_all('/[\\s]+order\\s+by\\s/im', $query, $matches, PREG_OFFSET_CAPTURE); + $orderByPos = false; if ($matchesCount > 0) { $orderByPos = $matches[0][($matchesCount - 1)][1]; } if ($orderByPos === false - || substr_count($query, "(", $orderByPos) - substr_count($query, ")", $orderByPos) + || substr_count($query, '(', $orderByPos) - substr_count($query, ')', $orderByPos) ) { if (preg_match('/^SELECT\s+DISTINCT/im', $query)) { // SQL Server won't let us order by a non-selected column in a DISTINCT query, @@ -136,11 +117,11 @@ protected function doModifyLimitQuery($query, $limit, $offset = null) // result. SQL Server's docs say that a nonordered query's result order is non- // deterministic anyway, so this won't do anything that a bunch of update and // deletes to the table wouldn't do anyway. - $query .= " ORDER BY 1"; + $query .= ' ORDER BY 1'; } else { // In another DBMS, we could do ORDER BY 0, but SQL Server gets angry if you // use constant expressions in the order by list. - $query .= " ORDER BY (SELECT 0)"; + $query .= ' ORDER BY (SELECT 0)'; } } @@ -151,10 +132,10 @@ protected function doModifyLimitQuery($query, $limit, $offset = null) // This looks somewhat like MYSQL, but limit/offset are in inverse positions // Supposedly SQL:2008 core standard. // Per TSQL spec, FETCH NEXT n ROWS ONLY is not valid without OFFSET n ROWS. - $query .= " OFFSET " . (int) $offset . " ROWS"; + $query .= ' OFFSET ' . (int) $offset . ' ROWS'; if ($limit !== null) { - $query .= " FETCH NEXT " . (int) $limit . " ROWS ONLY"; + $query .= ' FETCH NEXT ' . (int) $limit . ' ROWS ONLY'; } return $query; diff --git a/lib/Doctrine/DBAL/Platforms/SQLServerPlatform.php b/lib/Doctrine/DBAL/Platforms/SQLServerPlatform.php index 48cbcc6c1c8..dc8775e61ab 100644 --- a/lib/Doctrine/DBAL/Platforms/SQLServerPlatform.php +++ b/lib/Doctrine/DBAL/Platforms/SQLServerPlatform.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms; @@ -28,6 +11,7 @@ use Doctrine\DBAL\Schema\Table; use Doctrine\DBAL\Schema\TableDiff; use Doctrine\DBAL\Types; +use InvalidArgumentException; use function array_merge; use function array_unique; use function array_values; @@ -56,12 +40,6 @@ /** * The SQLServerPlatform provides the behavior, features and SQL dialect of the * Microsoft SQL Server database platform. - * - * @since 2.0 - * @author Roman Borschel - * @author Jonathan H. Wage - * @author Benjamin Eberlei - * @author Steve Müller */ class SQLServerPlatform extends AbstractPlatform { @@ -101,7 +79,7 @@ protected function getDateArithmeticIntervalExpression($date, $operator, $interv { $factorClause = ''; - if ('-' === $operator) { + if ($operator === '-') { $factorClause = '-1 * '; } @@ -223,7 +201,7 @@ public function getDropForeignKeySQL($foreignKey, $table) } $foreignKey = $foreignKey->getQuotedName($this); - $table = $table->getQuotedName($this); + $table = $table->getQuotedName($this); return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $foreignKey; } @@ -235,11 +213,11 @@ public function getDropIndexSQL($index, $table = null) { if ($index instanceof Index) { $index = $index->getQuotedName($this); - } elseif (!is_string($index)) { - throw new \InvalidArgumentException('AbstractPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.'); + } elseif (! is_string($index)) { + throw new InvalidArgumentException('AbstractPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.'); } - if (!isset($table)) { + if (! isset($table)) { return 'DROP INDEX ' . $index; } @@ -247,10 +225,20 @@ public function getDropIndexSQL($index, $table = null) $table = $table->getQuotedName($this); } - return "IF EXISTS (SELECT * FROM sysobjects WHERE name = '$index') - ALTER TABLE " . $table . " DROP CONSTRAINT " . $index . " - ELSE - DROP INDEX " . $index . " ON " . $table; + return sprintf( + <<getDefaultConstraintDeclarationSQL($tableName, $column); } - if ( ! empty($column['comment']) || is_numeric($column['comment'])) { - $commentsSql[] = $this->getCreateColumnCommentSQL($tableName, $column['name'], $column['comment']); + if (empty($column['comment']) && ! is_numeric($column['comment'])) { + continue; } + + $commentsSql[] = $this->getCreateColumnCommentSQL($tableName, $column['name'], $column['comment']); } $columnListSql = $this->getColumnDeclarationListSQL($columns); - if (isset($options['uniqueConstraints']) && !empty($options['uniqueConstraints'])) { + if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) { foreach ($options['uniqueConstraints'] as $name => $definition) { $columnListSql .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition); } } - if (isset($options['primary']) && !empty($options['primary'])) { + if (isset($options['primary']) && ! empty($options['primary'])) { $flags = ''; if (isset($options['primary_index']) && $options['primary_index']->hasFlag('nonclustered')) { $flags = ' NONCLUSTERED'; @@ -298,14 +288,14 @@ protected function _getCreateTableSQL($tableName, array $columns, array $options $query = 'CREATE TABLE ' . $tableName . ' (' . $columnListSql; $check = $this->getCheckDeclarationSQL($columns); - if (!empty($check)) { + if (! empty($check)) { $query .= ', ' . $check; } $query .= ')'; $sql = [$query]; - if (isset($options['indexes']) && !empty($options['indexes'])) { + if (isset($options['indexes']) && ! empty($options['indexes'])) { foreach ($options['indexes'] as $index) { $sql[] = $this->getCreateIndexSQL($index, $tableName); } @@ -330,7 +320,7 @@ public function getCreatePrimaryKeySQL(Index $index, $table) $flags = ' NONCLUSTERED'; } - return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY' . $flags . ' (' . $this->getIndexFieldDeclarationListSQL($index->getQuotedColumns($this)) . ')'; + return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY' . $flags . ' (' . $this->getIndexFieldDeclarationListSQL($index) . ')'; } /** @@ -376,23 +366,22 @@ protected function getCreateColumnCommentSQL($tableName, $columnName, $comment) /** * Returns the SQL snippet for declaring a default constraint. * - * @param string $table Name of the table to return the default constraint declaration for. - * @param array $column Column definition. + * @param string $table Name of the table to return the default constraint declaration for. + * @param mixed[] $column Column definition. * * @return string * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function getDefaultConstraintDeclarationSQL($table, array $column) { - if ( ! isset($column['default'])) { - throw new \InvalidArgumentException("Incomplete column definition. 'default' required."); + if (! isset($column['default'])) { + throw new InvalidArgumentException("Incomplete column definition. 'default' required."); } $columnName = new Identifier($column['name']); - return - ' CONSTRAINT ' . + return ' CONSTRAINT ' . $this->generateDefaultConstraintName($table, $column['name']) . $this->getDefaultValueDeclarationSQL($column) . ' FOR ' . $columnName->getQuotedName($this); @@ -417,7 +406,7 @@ public function getCreateIndexSQL(Index $index, $table) { $constraint = parent::getCreateIndexSQL($index, $table); - if ($index->isUnique() && !$index->isPrimary()) { + if ($index->isUnique() && ! $index->isPrimary()) { $constraint = $this->_appendUniqueConstraintDefinition($constraint, $index); } @@ -446,8 +435,7 @@ protected function getCreateIndexSQLFlags(Index $index) /** * Extend unique key constraint with required filters * - * @param string $sql - * @param \Doctrine\DBAL\Schema\Index $index + * @param string $sql * * @return string */ @@ -472,13 +460,12 @@ public function getAlterTableSQL(TableDiff $diff) $columnSql = []; $commentsSql = []; - /** @var \Doctrine\DBAL\Schema\Column $column */ foreach ($diff->addedColumns as $column) { if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) { continue; } - $columnDef = $column->toArray(); + $columnDef = $column->toArray(); $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnDef); if (isset($columnDef['default'])) { @@ -487,13 +474,15 @@ public function getAlterTableSQL(TableDiff $diff) $comment = $this->getColumnComment($column); - if ( ! empty($comment) || is_numeric($comment)) { - $commentsSql[] = $this->getCreateColumnCommentSQL( - $diff->name, - $column->getQuotedName($this), - $comment - ); + if (empty($comment) && ! is_numeric($comment)) { + continue; } + + $commentsSql[] = $this->getCreateColumnCommentSQL( + $diff->name, + $column->getQuotedName($this), + $comment + ); } foreach ($diff->removedColumns as $column) { @@ -504,7 +493,6 @@ public function getAlterTableSQL(TableDiff $diff) $queryParts[] = 'DROP COLUMN ' . $column->getQuotedName($this); } - /* @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */ foreach ($diff->changedColumns as $columnDiff) { if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) { continue; @@ -512,13 +500,13 @@ public function getAlterTableSQL(TableDiff $diff) $column = $columnDiff->column; $comment = $this->getColumnComment($column); - $hasComment = ! empty ($comment) || is_numeric($comment); + $hasComment = ! empty($comment) || is_numeric($comment); if ($columnDiff->fromColumn instanceof Column) { $fromComment = $this->getColumnComment($columnDiff->fromColumn); - $hasFromComment = ! empty ($fromComment) || is_numeric($fromComment); + $hasFromComment = ! empty($fromComment) || is_numeric($fromComment); - if ($hasFromComment && $hasComment && $fromComment != $comment) { + if ($hasFromComment && $hasComment && $fromComment !== $comment) { $commentsSql[] = $this->getAlterColumnCommentSQL( $diff->name, $column->getQuotedName($this), @@ -533,8 +521,6 @@ public function getAlterTableSQL(TableDiff $diff) $comment ); } - } else { - // todo: Original comment cannot be determined. What to do? Add, update, drop or skip? } // Do not add query part if only comment has changed. @@ -556,9 +542,11 @@ public function getAlterTableSQL(TableDiff $diff) $queryParts[] = 'ALTER COLUMN ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnDef); - if (isset($columnDef['default']) && ($requireDropDefaultConstraint || $columnDiff->hasChanged('default'))) { - $queryParts[] = $this->getAlterTableAddDefaultConstraintClause($diff->name, $column); + if (! isset($columnDef['default']) || (! $requireDropDefaultConstraint && ! $columnDiff->hasChanged('default'))) { + continue; } + + $queryParts[] = $this->getAlterTableAddDefaultConstraintClause($diff->name, $column); } foreach ($diff->renamedColumns as $oldColumnName => $column) { @@ -569,17 +557,19 @@ public function getAlterTableSQL(TableDiff $diff) $oldColumnName = new Identifier($oldColumnName); $sql[] = "sp_RENAME '" . - $diff->getName($this)->getQuotedName($this) . "." . $oldColumnName->getQuotedName($this) . + $diff->getName($this)->getQuotedName($this) . '.' . $oldColumnName->getQuotedName($this) . "', '" . $column->getQuotedName($this) . "', 'COLUMN'"; // Recreate default constraint with new column name if necessary (for future reference). - if ($column->getDefault() !== null) { - $queryParts[] = $this->getAlterTableDropDefaultConstraintClause( - $diff->name, - $oldColumnName->getQuotedName($this) - ); - $queryParts[] = $this->getAlterTableAddDefaultConstraintClause($diff->name, $column); + if ($column->getDefault() === null) { + continue; } + + $queryParts[] = $this->getAlterTableDropDefaultConstraintClause( + $diff->name, + $oldColumnName->getQuotedName($this) + ); + $queryParts[] = $this->getAlterTableAddDefaultConstraintClause($diff->name, $column); } $tableSql = []; @@ -609,10 +599,10 @@ public function getAlterTableSQL(TableDiff $diff) "SELECT @sql += N'EXEC sp_rename N''' + dc.name + ''', N''' " . "+ REPLACE(dc.name, '" . $this->generateIdentifierName($diff->name) . "', " . "'" . $this->generateIdentifierName($diff->newName) . "') + ''', ''OBJECT'';' " . - "FROM sys.default_constraints dc " . - "JOIN sys.tables tbl ON dc.parent_object_id = tbl.object_id " . + 'FROM sys.default_constraints dc ' . + 'JOIN sys.tables tbl ON dc.parent_object_id = tbl.object_id ' . "WHERE tbl.name = '" . $diff->getNewName()->getName() . "';" . - "EXEC sp_executesql @sql"; + 'EXEC sp_executesql @sql'; } $sql = array_merge( @@ -634,7 +624,7 @@ public function getAlterTableSQL(TableDiff $diff) */ private function getAlterTableAddDefaultConstraintClause($tableName, Column $column) { - $columnDef = $column->toArray(); + $columnDef = $column->toArray(); $columnDef['name'] = $column->getQuotedName($this); return 'ADD' . $this->getDefaultConstraintDeclarationSQL($tableName, $columnDef); @@ -669,7 +659,7 @@ private function alterColumnRequiresDropDefaultConstraint(ColumnDiff $columnDiff { // We can only decide whether to drop an existing default constraint // if we know the original default value. - if ( ! $columnDiff->fromColumn instanceof Column) { + if (! $columnDiff->fromColumn instanceof Column) { return false; } @@ -773,19 +763,20 @@ protected function getDropColumnCommentSQL($tableName, $columnName) */ protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName) { - return [ - sprintf( - "EXEC sp_RENAME N'%s.%s', N'%s', N'INDEX'", - $tableName, - $oldIndexName, - $index->getQuotedName($this) - ) + return [sprintf( + "EXEC sp_RENAME N'%s.%s', N'%s', N'INDEX'", + $tableName, + $oldIndexName, + $index->getQuotedName($this) + ), ]; } /** * Returns the SQL statement for adding an extended property to a database object. * + * @link http://msdn.microsoft.com/en-us/library/ms180047%28v=sql.90%29.aspx + * * @param string $name The name of the property to add. * @param string|null $value The value of the property to add. * @param string|null $level0Type The type of the object at level 0 the property belongs to. @@ -796,8 +787,6 @@ protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName) * @param string|null $level2Name The name of the object at level 2 the property belongs to. * * @return string - * - * @link http://msdn.microsoft.com/en-us/library/ms180047%28v=sql.90%29.aspx */ public function getAddExtendedPropertySQL( $name, @@ -809,16 +798,18 @@ public function getAddExtendedPropertySQL( $level2Type = null, $level2Name = null ) { - return "EXEC sp_addextendedproperty " . - "N" . $this->quoteStringLiteral($name) . ", N" . $this->quoteStringLiteral($value) . ", " . - "N" . $this->quoteStringLiteral($level0Type) . ", " . $level0Name . ', ' . - "N" . $this->quoteStringLiteral($level1Type) . ", " . $level1Name . ', ' . - "N" . $this->quoteStringLiteral($level2Type) . ", " . $level2Name; + return 'EXEC sp_addextendedproperty ' . + 'N' . $this->quoteStringLiteral($name) . ', N' . $this->quoteStringLiteral($value) . ', ' . + 'N' . $this->quoteStringLiteral($level0Type) . ', ' . $level0Name . ', ' . + 'N' . $this->quoteStringLiteral($level1Type) . ', ' . $level1Name . ', ' . + 'N' . $this->quoteStringLiteral($level2Type) . ', ' . $level2Name; } /** * Returns the SQL statement for dropping an extended property from a database object. * + * @link http://technet.microsoft.com/en-gb/library/ms178595%28v=sql.90%29.aspx + * * @param string $name The name of the property to drop. * @param string|null $level0Type The type of the object at level 0 the property belongs to. * @param string|null $level0Name The name of the object at level 0 the property belongs to. @@ -828,8 +819,6 @@ public function getAddExtendedPropertySQL( * @param string|null $level2Name The name of the object at level 2 the property belongs to. * * @return string - * - * @link http://technet.microsoft.com/en-gb/library/ms178595%28v=sql.90%29.aspx */ public function getDropExtendedPropertySQL( $name, @@ -840,16 +829,18 @@ public function getDropExtendedPropertySQL( $level2Type = null, $level2Name = null ) { - return "EXEC sp_dropextendedproperty " . - "N" . $this->quoteStringLiteral($name) . ", " . - "N" . $this->quoteStringLiteral($level0Type) . ", " . $level0Name . ', ' . - "N" . $this->quoteStringLiteral($level1Type) . ", " . $level1Name . ', ' . - "N" . $this->quoteStringLiteral($level2Type) . ", " . $level2Name; + return 'EXEC sp_dropextendedproperty ' . + 'N' . $this->quoteStringLiteral($name) . ', ' . + 'N' . $this->quoteStringLiteral($level0Type) . ', ' . $level0Name . ', ' . + 'N' . $this->quoteStringLiteral($level1Type) . ', ' . $level1Name . ', ' . + 'N' . $this->quoteStringLiteral($level2Type) . ', ' . $level2Name; } /** * Returns the SQL statement for updating an extended property of a database object. * + * @link http://msdn.microsoft.com/en-us/library/ms186885%28v=sql.90%29.aspx + * * @param string $name The name of the property to update. * @param string|null $value The value of the property to update. * @param string|null $level0Type The type of the object at level 0 the property belongs to. @@ -860,8 +851,6 @@ public function getDropExtendedPropertySQL( * @param string|null $level2Name The name of the object at level 2 the property belongs to. * * @return string - * - * @link http://msdn.microsoft.com/en-us/library/ms186885%28v=sql.90%29.aspx */ public function getUpdateExtendedPropertySQL( $name, @@ -873,11 +862,11 @@ public function getUpdateExtendedPropertySQL( $level2Type = null, $level2Name = null ) { - return "EXEC sp_updateextendedproperty " . - "N" . $this->quoteStringLiteral($name) . ", N" . $this->quoteStringLiteral($value) . ", " . - "N" . $this->quoteStringLiteral($level0Type) . ", " . $level0Name . ', ' . - "N" . $this->quoteStringLiteral($level1Type) . ", " . $level1Name . ', ' . - "N" . $this->quoteStringLiteral($level2Type) . ", " . $level2Name; + return 'EXEC sp_updateextendedproperty ' . + 'N' . $this->quoteStringLiteral($name) . ', N' . $this->quoteStringLiteral($value) . ', ' . + 'N' . $this->quoteStringLiteral($level0Type) . ', ' . $level0Name . ', ' . + 'N' . $this->quoteStringLiteral($level1Type) . ', ' . $level1Name . ', ' . + 'N' . $this->quoteStringLiteral($level2Type) . ', ' . $level2Name; } /** @@ -936,7 +925,7 @@ public function getListTableColumnsSQL($table, $database = null) */ public function getListTableForeignKeysSQL($table, $database = null) { - return "SELECT f.name AS ForeignKey, + return 'SELECT f.name AS ForeignKey, SCHEMA_NAME (f.SCHEMA_ID) AS SchemaName, OBJECT_NAME (f.parent_object_id) AS TableName, COL_NAME (fc.parent_object_id,fc.parent_column_id) AS ColumnName, @@ -949,7 +938,7 @@ public function getListTableForeignKeysSQL($table, $database = null) INNER JOIN sys.foreign_key_columns AS fc INNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_id ON f.OBJECT_ID = fc.constraint_object_id - WHERE " . + WHERE ' . $this->getTableWhereClause($table, 'SCHEMA_NAME (f.schema_id)', 'OBJECT_NAME (f.parent_object_id)'); } @@ -972,8 +961,8 @@ public function getListTableIndexesSQL($table, $currentDatabase = null) JOIN sys.indexes AS idx ON tbl.object_id = idx.object_id JOIN sys.index_columns AS idxcol ON idx.object_id = idxcol.object_id AND idx.index_id = idxcol.index_id JOIN sys.columns AS col ON idxcol.object_id = col.object_id AND idxcol.column_id = col.column_id - WHERE " . $this->getTableWhereClause($table, 'scm.name', 'tbl.name') . " - ORDER BY idx.index_id ASC, idxcol.key_ordinal ASC"; + WHERE " . $this->getTableWhereClause($table, 'scm.name', 'tbl.name') . ' + ORDER BY idx.index_id ASC, idxcol.key_ordinal ASC'; } /** @@ -1003,16 +992,16 @@ public function getListViewsSQL($database) */ private function getTableWhereClause($table, $schemaColumn, $tableColumn) { - if (strpos($table, ".") !== false) { - list($schema, $table) = explode(".", $table); - $schema = $this->quoteStringLiteral($schema); - $table = $this->quoteStringLiteral($table); + if (strpos($table, '.') !== false) { + [$schema, $table] = explode('.', $table); + $schema = $this->quoteStringLiteral($schema); + $table = $this->quoteStringLiteral($table); } else { - $schema = "SCHEMA_NAME()"; - $table = $this->quoteStringLiteral($table); + $schema = 'SCHEMA_NAME()'; + $table = $this->quoteStringLiteral($table); } - return "({$tableColumn} = {$table} AND {$schemaColumn} = {$schema})"; + return sprintf('(%s = %s AND %s = %s)', $tableColumn, $table, $schemaColumn, $schema); } /** @@ -1038,7 +1027,7 @@ public function getGuidExpression() */ public function getLocateExpression($str, $substr, $startPos = false) { - if ($startPos == false) { + if ($startPos === false) { return 'CHARINDEX(' . $substr . ', ' . $str . ')'; } @@ -1058,7 +1047,7 @@ public function getModExpression($expression1, $expression2) */ public function getTrimExpression($str, $pos = TrimMode::UNSPECIFIED, $char = false) { - if ( ! $char) { + if (! $char) { switch ($pos) { case TrimMode::LEADING: $trimFn = 'LTRIM'; @@ -1084,7 +1073,7 @@ public function getTrimExpression($str, $pos = TrimMode::UNSPECIFIED, $char = fa , reverse(stuff(reverse(@c), 1, patindex(@pat, reverse(@c)) - 1, null)) as trim_trailing , reverse(stuff(reverse(stuff(@c, 1, patindex(@pat, @c) - 1, null)), 1, patindex(@pat, reverse(stuff(@c, 1, patindex(@pat, @c) - 1, null))) - 1, null)) as trim_both; */ - $pattern = "'%[^' + $char + ']%'"; + $pattern = "'%[^' + " . $char . " + ']%'"; if ($pos === TrimMode::LEADING) { return 'stuff(' . $str . ', 1, patindex(' . $pattern . ', ' . $str . ') - 1, null)'; @@ -1220,7 +1209,7 @@ public function getClobTypeDeclarationSQL(array $field) */ protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) { - return (!empty($columnDef['autoincrement'])) ? ' IDENTITY' : ''; + return ! empty($columnDef['autoincrement']) ? ' IDENTITY' : ''; } /** @@ -1281,11 +1270,11 @@ protected function doModifyLimitQuery($query, $limit, $offset = null) // Even if the TOP n is very large, the use of a CTE will // allow the SQL Server query planner to optimize it so it doesn't // actually scan the entire range covered by the TOP clause. - $selectPattern = '/^(\s*SELECT\s+(?:DISTINCT\s+)?)(.*)$/im'; + $selectPattern = '/^(\s*SELECT\s+(?:DISTINCT\s+)?)(.*)$/im'; $replacePattern = sprintf('$1%s $2', $top); - $query = preg_replace($selectPattern, $replacePattern, $query); + $query = preg_replace($selectPattern, $replacePattern, $query); - if (stristr($query, "ORDER BY")) { + if (stristr($query, 'ORDER BY')) { // Inner order by is not valid in SQL Server for our purposes // unless it's in a TOP N subquery. $query = $this->scrubInnerOrderBy($query); @@ -1293,10 +1282,10 @@ protected function doModifyLimitQuery($query, $limit, $offset = null) // Build a new limited query around the original, using a CTE return sprintf( - "WITH dctrn_cte AS (%s) " - . "SELECT * FROM (" - . "SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS doctrine_rownum FROM dctrn_cte" - . ") AS doctrine_tbl " + 'WITH dctrn_cte AS (%s) ' + . 'SELECT * FROM (' + . 'SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS doctrine_rownum FROM dctrn_cte' + . ') AS doctrine_tbl ' . 'WHERE %s ORDER BY doctrine_rownum ASC', $query, implode(' AND ', $where) @@ -1308,11 +1297,12 @@ protected function doModifyLimitQuery($query, $limit, $offset = null) * Caveat: will leave ORDER BY in TOP N subqueries. * * @param string $query + * * @return string */ private function scrubInnerOrderBy($query) { - $count = substr_count(strtoupper($query), 'ORDER BY'); + $count = substr_count(strtoupper($query), 'ORDER BY'); $offset = 0; while ($count-- > 0) { @@ -1321,8 +1311,8 @@ private function scrubInnerOrderBy($query) break; } - $qLen = strlen($query); - $parenCount = 0; + $qLen = strlen($query); + $parenCount = 0; $currentPosition = $orderByPos; while ($parenCount >= 0 && $currentPosition < $qLen) { @@ -1342,10 +1332,12 @@ private function scrubInnerOrderBy($query) continue; } - if ($currentPosition < $qLen - 1) { - $query = substr($query, 0, $orderByPos) . substr($query, $currentPosition - 1); - $offset = $orderByPos; + if ($currentPosition >= $qLen - 1) { + continue; } + + $query = substr($query, 0, $orderByPos) . substr($query, $currentPosition - 1); + $offset = $orderByPos; } return $query; } @@ -1355,13 +1347,14 @@ private function scrubInnerOrderBy($query) * * @param string $query The query * @param int $currentPosition Start position of ORDER BY clause + * * @return bool true if ORDER BY is in a TOP N query, false otherwise */ private function isOrderByInTopNSubquery($query, $currentPosition) { // Grab query text on the same nesting level as the ORDER BY clause we're examining. $subQueryBuffer = ''; - $parenCount = 0; + $parenCount = 0; // If $parenCount goes negative, we've exited the subquery we're examining. // If $currentPosition goes negative, we've reached the beginning of the query. @@ -1396,12 +1389,14 @@ public function convertBooleans($item) { if (is_array($item)) { foreach ($item as $key => $value) { - if (is_bool($value) || is_numeric($item)) { - $item[$key] = ($value) ? 1 : 0; + if (! is_bool($value) && ! is_numeric($item)) { + continue; } + + $item[$key] = $value ? 1 : 0; } } elseif (is_bool($item) || is_numeric($item)) { - $item = ($item) ? 1 : 0; + $item = $item ? 1 : 0; } return $item; @@ -1412,7 +1407,7 @@ public function convertBooleans($item) */ public function getCreateTemporaryTableSnippetSQL() { - return "CREATE TABLE"; + return 'CREATE TABLE'; } /** @@ -1540,13 +1535,13 @@ public function getForeignKeyReferentialActionSQL($action) public function appendLockHint($fromClause, $lockMode) { switch (true) { - case LockMode::NONE === $lockMode: + case $lockMode === LockMode::NONE: return $fromClause . ' WITH (NOLOCK)'; - case LockMode::PESSIMISTIC_READ === $lockMode: + case $lockMode === LockMode::PESSIMISTIC_READ: return $fromClause . ' WITH (HOLDLOCK, ROWLOCK)'; - case LockMode::PESSIMISTIC_WRITE === $lockMode: + case $lockMode === LockMode::PESSIMISTIC_WRITE: return $fromClause . ' WITH (UPDLOCK, ROWLOCK)'; default: @@ -1575,7 +1570,7 @@ protected function getReservedKeywordsClass() */ public function quoteSingleIdentifier($str) { - return "[" . str_replace("]", "][", $str) . "]"; + return '[' . str_replace(']', '][', $str) . ']'; } /** @@ -1601,22 +1596,22 @@ public function getBlobTypeDeclarationSQL(array $field) */ public function getDefaultValueDeclarationSQL($field) { - if ( ! isset($field['default'])) { + if (! isset($field['default'])) { return empty($field['notnull']) ? ' NULL' : ''; } - if ( ! isset($field['type'])) { + if (! isset($field['type'])) { return " DEFAULT '" . $field['default'] . "'"; } $type = $field['type']; if ($type instanceof Types\PhpIntegerMappingType) { - return " DEFAULT " . $field['default']; + return ' DEFAULT ' . $field['default']; } if ($type instanceof Types\PhpDateTimeMappingType && $field['default'] === $this->getCurrentTimestampSQL()) { - return " DEFAULT " . $this->getCurrentTimestampSQL(); + return ' DEFAULT ' . $this->getCurrentTimestampSQL(); } if ($type instanceof Types\BooleanType) { @@ -1636,18 +1631,18 @@ public function getColumnDeclarationSQL($name, array $field) if (isset($field['columnDefinition'])) { $columnDef = $this->getCustomTypeDeclarationSQL($field); } else { - $collation = (isset($field['collation']) && $field['collation']) ? + $collation = isset($field['collation']) && $field['collation'] ? ' ' . $this->getColumnCollationDeclarationSQL($field['collation']) : ''; - $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : ''; + $notnull = isset($field['notnull']) && $field['notnull'] ? ' NOT NULL' : ''; - $unique = (isset($field['unique']) && $field['unique']) ? + $unique = isset($field['unique']) && $field['unique'] ? ' ' . $this->getUniqueFieldDeclarationSQL() : ''; - $check = (isset($field['check']) && $field['check']) ? + $check = isset($field['check']) && $field['check'] ? ' ' . $field['check'] : ''; - $typeDecl = $field['type']->getSQLDeclaration($field, $this); + $typeDecl = $field['type']->getSQLDeclaration($field, $this); $columnDef = $typeDecl . $collation . $notnull . $unique . $check; } diff --git a/lib/Doctrine/DBAL/Platforms/SqlitePlatform.php b/lib/Doctrine/DBAL/Platforms/SqlitePlatform.php index 3c99e0f0853..819421d3469 100644 --- a/lib/Doctrine/DBAL/Platforms/SqlitePlatform.php +++ b/lib/Doctrine/DBAL/Platforms/SqlitePlatform.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Platforms; @@ -45,10 +28,6 @@ * The SqlitePlatform class describes the specifics and dialects of the SQLite * database platform. * - * @since 2.0 - * @author Roman Borschel - * @author Benjamin Eberlei - * @author Martin Hasoň * @todo Rename: SQLitePlatform */ class SqlitePlatform extends AbstractPlatform @@ -95,7 +74,7 @@ public function getNowExpression($type = 'timestamp') */ public function getTrimExpression($str, $pos = TrimMode::UNSPECIFIED, $char = false) { - $trimChar = ($char != false) ? (', ' . $char) : ''; + $trimChar = $char !== false ? (', ' . $char) : ''; switch ($pos) { case TrimMode::LEADING: @@ -132,11 +111,11 @@ public function getSubstringExpression($value, $position, $length = null) */ public function getLocateExpression($str, $substr, $startPos = false) { - if ($startPos == false) { - return 'LOCATE('.$str.', '.$substr.')'; + if ($startPos === false) { + return 'LOCATE(' . $str . ', ' . $substr . ')'; } - return 'LOCATE('.$str.', '.$substr.', '.$startPos.')'; + return 'LOCATE(' . $str . ', ' . $substr . ', ' . $startPos . ')'; } /** @@ -148,7 +127,7 @@ protected function getDateArithmeticIntervalExpression($date, $operator, $interv case DateIntervalUnit::SECOND: case DateIntervalUnit::MINUTE: case DateIntervalUnit::HOUR: - return "DATETIME(" . $date . ",'" . $operator . $interval . " " . $unit . "')"; + return 'DATETIME(' . $date . ",'" . $operator . $interval . ' ' . $unit . "')"; default: switch ($unit) { @@ -167,7 +146,7 @@ protected function getDateArithmeticIntervalExpression($date, $operator, $interv $interval = "' || " . $interval . " || '"; } - return "DATE(" . $date . ",'" . $operator . $interval . " " . $unit . "')"; + return 'DATE(' . $date . ",'" . $operator . $interval . ' ' . $unit . "')"; } } @@ -234,7 +213,7 @@ public function getIntegerTypeDeclarationSQL(array $field) public function getBigIntTypeDeclarationSQL(array $field) { // SQLite autoincrement is implicit for INTEGER PKs, but not for BIGINT fields. - if ( ! empty($field['autoincrement'])) { + if (! empty($field['autoincrement'])) { return $this->getIntegerTypeDeclarationSQL($field); } @@ -247,7 +226,7 @@ public function getBigIntTypeDeclarationSQL(array $field) public function getTinyIntTypeDeclarationSql(array $field) { // SQLite autoincrement is implicit for INTEGER PKs, but not for TINYINT fields. - if ( ! empty($field['autoincrement'])) { + if (! empty($field['autoincrement'])) { return $this->getIntegerTypeDeclarationSQL($field); } @@ -260,7 +239,7 @@ public function getTinyIntTypeDeclarationSql(array $field) public function getSmallIntTypeDeclarationSQL(array $field) { // SQLite autoincrement is implicit for INTEGER PKs, but not for SMALLINT fields. - if ( ! empty($field['autoincrement'])) { + if (! empty($field['autoincrement'])) { return $this->getIntegerTypeDeclarationSQL($field); } @@ -273,7 +252,7 @@ public function getSmallIntTypeDeclarationSQL(array $field) public function getMediumIntTypeDeclarationSql(array $field) { // SQLite autoincrement is implicit for INTEGER PKs, but not for MEDIUMINT fields. - if ( ! empty($field['autoincrement'])) { + if (! empty($field['autoincrement'])) { return $this->getIntegerTypeDeclarationSQL($field); } @@ -310,7 +289,7 @@ public function getTimeTypeDeclarationSQL(array $fieldDeclaration) protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) { // sqlite autoincrement is only possible for the primary key - if ( ! empty($columnDef['autoincrement'])) { + if (! empty($columnDef['autoincrement'])) { return ' PRIMARY KEY AUTOINCREMENT'; } @@ -336,7 +315,7 @@ public function getForeignKeyDeclarationSQL(ForeignKeyConstraint $foreignKey) */ protected function _getCreateTableSQL($name, array $columns, array $options = []) { - $name = str_replace('.', '__', $name); + $name = str_replace('.', '__', $name); $queryFields = $this->getColumnDeclarationListSQL($columns); if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) { @@ -349,13 +328,13 @@ protected function _getCreateTableSQL($name, array $columns, array $options = [] if (isset($options['foreignKeys'])) { foreach ($options['foreignKeys'] as $foreignKey) { - $queryFields.= ', '.$this->getForeignKeyDeclarationSQL($foreignKey); + $queryFields .= ', ' . $this->getForeignKeyDeclarationSQL($foreignKey); } } $query = ['CREATE TABLE ' . $name . ' (' . $queryFields . ')']; - if (isset($options['alter']) && true === $options['alter']) { + if (isset($options['alter']) && $options['alter'] === true) { return $query; } @@ -444,9 +423,11 @@ public function getClobTypeDeclarationSQL(array $field) public function getListTableConstraintsSQL($table) { $table = str_replace('.', '__', $table); - $table = $this->quoteStringLiteral($table); - return "SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name = $table AND sql NOT NULL ORDER BY name"; + return sprintf( + "SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name = %s AND sql NOT NULL ORDER BY name", + $this->quoteStringLiteral($table) + ); } /** @@ -455,9 +436,8 @@ public function getListTableConstraintsSQL($table) public function getListTableColumnsSQL($table, $currentDatabase = null) { $table = str_replace('.', '__', $table); - $table = $this->quoteStringLiteral($table); - return "PRAGMA table_info($table)"; + return sprintf('PRAGMA table_info(%s)', $this->quoteStringLiteral($table)); } /** @@ -466,9 +446,8 @@ public function getListTableColumnsSQL($table, $currentDatabase = null) public function getListTableIndexesSQL($table, $currentDatabase = null) { $table = str_replace('.', '__', $table); - $table = $this->quoteStringLiteral($table); - return "PRAGMA index_list($table)"; + return sprintf('PRAGMA index_list(%s)', $this->quoteStringLiteral($table)); } /** @@ -477,7 +456,7 @@ public function getListTableIndexesSQL($table, $currentDatabase = null) public function getListTablesSQL() { return "SELECT name FROM sqlite_master WHERE type = 'table' AND name != 'sqlite_sequence' AND name != 'geometry_columns' AND name != 'spatial_ref_sys' " - . "UNION ALL SELECT name FROM sqlite_temp_master " + . 'UNION ALL SELECT name FROM sqlite_temp_master ' . "WHERE type = 'table' ORDER BY name"; } @@ -502,7 +481,7 @@ public function getCreateViewSQL($name, $sql) */ public function getDropViewSQL($name) { - return 'DROP VIEW '. $name; + return 'DROP VIEW ' . $name; } /** @@ -512,8 +491,8 @@ public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey { $query = parent::getAdvancedForeignKeyOptionsSQL($foreignKey); - $query .= (($foreignKey->hasOption('deferrable') && $foreignKey->getOption('deferrable') !== false) ? ' ' : ' NOT ') . 'DEFERRABLE'; - $query .= ' INITIALLY ' . (($foreignKey->hasOption('deferred') && $foreignKey->getOption('deferred') !== false) ? 'DEFERRED' : 'IMMEDIATE'); + $query .= ($foreignKey->hasOption('deferrable') && $foreignKey->getOption('deferrable') !== false ? ' ' : ' NOT ') . 'DEFERRABLE'; + $query .= ' INITIALLY ' . ($foreignKey->hasOption('deferred') && $foreignKey->getOption('deferred') !== false ? 'DEFERRED' : 'IMMEDIATE'); return $query; } @@ -556,7 +535,7 @@ public function getName() public function getTruncateTableSQL($tableName, $cascade = false) { $tableIdentifier = new Identifier($tableName); - $tableName = str_replace('.', '__', $tableIdentifier->getQuotedName($this)); + $tableName = str_replace('.', '__', $tableIdentifier->getQuotedName($this)); return 'DELETE FROM ' . $tableName; } @@ -583,7 +562,7 @@ public static function udfSqrt($value) */ public static function udfMod($a, $b) { - return ($a % $b); + return $a % $b; } /** @@ -680,15 +659,17 @@ protected function getReservedKeywordsClass() */ protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) { - if ( ! $diff->fromTable instanceof Table) { + if (! $diff->fromTable instanceof Table) { throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema'); } $sql = []; foreach ($diff->fromTable->getIndexes() as $index) { - if ( ! $index->isPrimary()) { - $sql[] = $this->getDropIndexSQL($index, $diff->name); + if ($index->isPrimary()) { + continue; } + + $sql[] = $this->getDropIndexSQL($index, $diff->name); } return $sql; @@ -699,11 +680,11 @@ protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) */ protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff) { - if ( ! $diff->fromTable instanceof Table) { + if (! $diff->fromTable instanceof Table) { throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema'); } - $sql = []; + $sql = []; $tableName = $diff->newName ? $diff->getNewName(): $diff->getName($this); foreach ($this->getIndexesInAlteredTable($diff) as $index) { if ($index->isPrimary()) { @@ -816,9 +797,8 @@ public function getCreateTableSQL(Table $table, $createFlags = null) public function getListTableForeignKeysSQL($table, $database = null) { $table = str_replace('.', '__', $table); - $table = $this->quoteStringLiteral($table); - return "PRAGMA foreign_key_list($table)"; + return sprintf('PRAGMA foreign_key_list(%s)', $this->quoteStringLiteral($table)); } /** @@ -827,25 +807,25 @@ public function getListTableForeignKeysSQL($table, $database = null) public function getAlterTableSQL(TableDiff $diff) { $sql = $this->getSimpleAlterTableSQL($diff); - if (false !== $sql) { + if ($sql !== false) { return $sql; } $fromTable = $diff->fromTable; - if ( ! $fromTable instanceof Table) { + if (! $fromTable instanceof Table) { throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema'); } $table = clone $fromTable; - $columns = []; + $columns = []; $oldColumnNames = []; $newColumnNames = []; - $columnSql = []; + $columnSql = []; foreach ($table->getColumns() as $columnName => $column) { - $columnName = strtolower($columnName); - $columns[$columnName] = $column; + $columnName = strtolower($columnName); + $columns[$columnName] = $column; $oldColumnNames[$columnName] = $newColumnNames[$columnName] = $column->getQuotedName($this); } @@ -855,13 +835,15 @@ public function getAlterTableSQL(TableDiff $diff) } $columnName = strtolower($columnName); - if (isset($columns[$columnName])) { - unset( - $columns[$columnName], - $oldColumnNames[$columnName], - $newColumnNames[$columnName] - ); + if (! isset($columns[$columnName])) { + continue; } + + unset( + $columns[$columnName], + $oldColumnNames[$columnName], + $newColumnNames[$columnName] + ); } foreach ($diff->renamedColumns as $oldColumnName => $column) { @@ -876,9 +858,11 @@ public function getAlterTableSQL(TableDiff $diff) $columns[strtolower($column->getName())] = $column; - if (isset($newColumnNames[$oldColumnName])) { - $newColumnNames[$oldColumnName] = $column->getQuotedName($this); + if (! isset($newColumnNames[$oldColumnName])) { + continue; } + + $newColumnNames[$oldColumnName] = $column->getQuotedName($this); } foreach ($diff->changedColumns as $oldColumnName => $columnDiff) { @@ -892,9 +876,11 @@ public function getAlterTableSQL(TableDiff $diff) $columns[strtolower($columnDiff->column->getName())] = $columnDiff->column; - if (isset($newColumnNames[$oldColumnName])) { - $newColumnNames[$oldColumnName] = $columnDiff->column->getQuotedName($this); + if (! isset($newColumnNames[$oldColumnName])) { + continue; } + + $newColumnNames[$oldColumnName] = $columnDiff->column->getQuotedName($this); } foreach ($diff->addedColumns as $columnName => $column) { @@ -905,10 +891,10 @@ public function getAlterTableSQL(TableDiff $diff) $columns[strtolower($columnName)] = $column; } - $sql = []; + $sql = []; $tableSql = []; - if ( ! $this->onSchemaAlterTable($diff, $tableSql)) { - $dataTable = new Table('__temp__'.$table->getName()); + if (! $this->onSchemaAlterTable($diff, $tableSql)) { + $dataTable = new Table('__temp__' . $table->getName()); $newTable = new Table($table->getQuotedName($this), $columns, $this->getPrimaryIndexInAlteredTable($diff), $this->getForeignKeysInAlteredTable($diff), 0, $table->getOptions()); $newTable->addOption('alter', true); @@ -918,13 +904,13 @@ public function getAlterTableSQL(TableDiff $diff) $sql[] = sprintf('CREATE TEMPORARY TABLE %s AS SELECT %s FROM %s', $dataTable->getQuotedName($this), implode(', ', $oldColumnNames), $table->getQuotedName($this)); $sql[] = $this->getDropTableSQL($fromTable); - $sql = array_merge($sql, $this->getCreateTableSQL($newTable)); + $sql = array_merge($sql, $this->getCreateTableSQL($newTable)); $sql[] = sprintf('INSERT INTO %s (%s) SELECT %s FROM %s', $newTable->getQuotedName($this), implode(', ', $newColumnNames), implode(', ', $oldColumnNames), $dataTable->getQuotedName($this)); $sql[] = $this->getDropTableSQL($dataTable); - if ($diff->newName && $diff->newName != $diff->name) { + if ($diff->newName && $diff->newName !== $diff->name) { $renamedTable = $diff->getNewName(); - $sql[] = 'ALTER TABLE '.$newTable->getQuotedName($this).' RENAME TO '.$renamedTable->getQuotedName($this); + $sql[] = 'ALTER TABLE ' . $newTable->getQuotedName($this) . ' RENAME TO ' . $renamedTable->getQuotedName($this); } $sql = array_merge($sql, $this->getPostAlterTableIndexForeignKeySQL($diff)); @@ -934,15 +920,13 @@ public function getAlterTableSQL(TableDiff $diff) } /** - * @param \Doctrine\DBAL\Schema\TableDiff $diff - * * @return string[]|false */ private function getSimpleAlterTableSQL(TableDiff $diff) { // Suppress changes on integer type autoincrement columns. foreach ($diff->changedColumns as $oldColumnName => $columnDiff) { - if ( ! $columnDiff->fromColumn instanceof Column || + if (! $columnDiff->fromColumn instanceof Column || ! $columnDiff->column instanceof Column || ! $columnDiff->column->getAutoincrement() || ! $columnDiff->column->getType() instanceof Types\IntegerType @@ -950,7 +934,7 @@ private function getSimpleAlterTableSQL(TableDiff $diff) continue; } - if ( ! $columnDiff->hasChanged('type') && $columnDiff->hasChanged('unsigned')) { + if (! $columnDiff->hasChanged('type') && $columnDiff->hasChanged('unsigned')) { unset($diff->changedColumns[$oldColumnName]); continue; @@ -958,12 +942,14 @@ private function getSimpleAlterTableSQL(TableDiff $diff) $fromColumnType = $columnDiff->fromColumn->getType(); - if ($fromColumnType instanceof Types\SmallIntType || $fromColumnType instanceof Types\BigIntType) { - unset($diff->changedColumns[$oldColumnName]); + if (! ($fromColumnType instanceof Types\SmallIntType) && ! ($fromColumnType instanceof Types\BigIntType)) { + continue; } + + unset($diff->changedColumns[$oldColumnName]); } - if ( ! empty($diff->renamedColumns) || ! empty($diff->addedForeignKeys) || ! empty($diff->addedIndexes) + if (! empty($diff->renamedColumns) || ! empty($diff->addedForeignKeys) || ! empty($diff->addedIndexes) || ! empty($diff->changedColumns) || ! empty($diff->changedForeignKeys) || ! empty($diff->changedIndexes) || ! empty($diff->removedColumns) || ! empty($diff->removedForeignKeys) || ! empty($diff->removedIndexes) || ! empty($diff->renamedIndexes) @@ -973,8 +959,8 @@ private function getSimpleAlterTableSQL(TableDiff $diff) $table = new Table($diff->name); - $sql = []; - $tableSql = []; + $sql = []; + $tableSql = []; $columnSql = []; foreach ($diff->addedColumns as $column) { @@ -983,12 +969,12 @@ private function getSimpleAlterTableSQL(TableDiff $diff) } $field = array_merge(['unique' => null, 'autoincrement' => null, 'default' => null], $column->toArray()); - $type = $field['type']; + $type = $field['type']; switch (true) { case isset($field['columnDefinition']) || $field['autoincrement'] || $field['unique']: - case $type instanceof Types\DateTimeType && $field['default'] == $this->getCurrentTimestampSQL(): - case $type instanceof Types\DateType && $field['default'] == $this->getCurrentDateSQL(): - case $type instanceof Types\TimeType && $field['default'] == $this->getCurrentTimeSQL(): + case $type instanceof Types\DateTimeType && $field['default'] === $this->getCurrentTimestampSQL(): + case $type instanceof Types\DateType && $field['default'] === $this->getCurrentDateSQL(): + case $type instanceof Types\TimeType && $field['default'] === $this->getCurrentTimeSQL(): return false; } @@ -997,13 +983,13 @@ private function getSimpleAlterTableSQL(TableDiff $diff) $field['length'] = 255; } - $sql[] = 'ALTER TABLE '.$table->getQuotedName($this).' ADD COLUMN '.$this->getColumnDeclarationSQL($field['name'], $field); + $sql[] = 'ALTER TABLE ' . $table->getQuotedName($this) . ' ADD COLUMN ' . $this->getColumnDeclarationSQL($field['name'], $field); } - if ( ! $this->onSchemaAlterTable($diff, $tableSql)) { + if (! $this->onSchemaAlterTable($diff, $tableSql)) { if ($diff->newName !== false) { $newTable = new Identifier($diff->newName); - $sql[] = 'ALTER TABLE '.$table->getQuotedName($this).' RENAME TO '.$newTable->getQuotedName($this); + $sql[] = 'ALTER TABLE ' . $table->getQuotedName($this) . ' RENAME TO ' . $newTable->getQuotedName($this); } } @@ -1011,9 +997,7 @@ private function getSimpleAlterTableSQL(TableDiff $diff) } /** - * @param \Doctrine\DBAL\Schema\TableDiff $diff - * - * @return array + * @return string[] */ private function getColumnNamesInAlteredTable(TableDiff $diff) { @@ -1025,21 +1009,23 @@ private function getColumnNamesInAlteredTable(TableDiff $diff) foreach ($diff->removedColumns as $columnName => $column) { $columnName = strtolower($columnName); - if (isset($columns[$columnName])) { - unset($columns[$columnName]); + if (! isset($columns[$columnName])) { + continue; } + + unset($columns[$columnName]); } foreach ($diff->renamedColumns as $oldColumnName => $column) { - $columnName = $column->getName(); + $columnName = $column->getName(); $columns[strtolower($oldColumnName)] = $columnName; - $columns[strtolower($columnName)] = $columnName; + $columns[strtolower($columnName)] = $columnName; } foreach ($diff->changedColumns as $oldColumnName => $columnDiff) { - $columnName = $columnDiff->column->getName(); + $columnName = $columnDiff->column->getName(); $columns[strtolower($oldColumnName)] = $columnName; - $columns[strtolower($columnName)] = $columnName; + $columns[strtolower($columnName)] = $columnName; } foreach ($diff->addedColumns as $columnName => $column) { @@ -1050,27 +1036,27 @@ private function getColumnNamesInAlteredTable(TableDiff $diff) } /** - * @param \Doctrine\DBAL\Schema\TableDiff $diff - * - * @return \Doctrine\DBAL\Schema\Index[] + * @return Index[] */ private function getIndexesInAlteredTable(TableDiff $diff) { - $indexes = $diff->fromTable->getIndexes(); + $indexes = $diff->fromTable->getIndexes(); $columnNames = $this->getColumnNamesInAlteredTable($diff); foreach ($indexes as $key => $index) { foreach ($diff->renamedIndexes as $oldIndexName => $renamedIndex) { - if (strtolower($key) === strtolower($oldIndexName)) { - unset($indexes[$key]); + if (strtolower($key) !== strtolower($oldIndexName)) { + continue; } + + unset($indexes[$key]); } - $changed = false; + $changed = false; $indexColumns = []; foreach ($index->getColumns() as $columnName) { $normalizedColumnName = strtolower($columnName); - if ( ! isset($columnNames[$normalizedColumnName])) { + if (! isset($columnNames[$normalizedColumnName])) { unset($indexes[$key]); continue 2; } else { @@ -1081,16 +1067,20 @@ private function getIndexesInAlteredTable(TableDiff $diff) } } - if ($changed) { - $indexes[$key] = new Index($index->getName(), $indexColumns, $index->isUnique(), $index->isPrimary(), $index->getFlags()); + if (! $changed) { + continue; } + + $indexes[$key] = new Index($index->getName(), $indexColumns, $index->isUnique(), $index->isPrimary(), $index->getFlags()); } foreach ($diff->removedIndexes as $index) { $indexName = strtolower($index->getName()); - if (strlen($indexName) && isset($indexes[$indexName])) { - unset($indexes[$indexName]); + if (! strlen($indexName) || ! isset($indexes[$indexName])) { + continue; } + + unset($indexes[$indexName]); } foreach (array_merge($diff->changedIndexes, $diff->addedIndexes, $diff->renamedIndexes) as $index) { @@ -1106,9 +1096,7 @@ private function getIndexesInAlteredTable(TableDiff $diff) } /** - * @param \Doctrine\DBAL\Schema\TableDiff $diff - * - * @return array + * @return ForeignKeyConstraint[] */ private function getForeignKeysInAlteredTable(TableDiff $diff) { @@ -1116,11 +1104,11 @@ private function getForeignKeysInAlteredTable(TableDiff $diff) $columnNames = $this->getColumnNamesInAlteredTable($diff); foreach ($foreignKeys as $key => $constraint) { - $changed = false; + $changed = false; $localColumns = []; foreach ($constraint->getLocalColumns() as $columnName) { $normalizedColumnName = strtolower($columnName); - if ( ! isset($columnNames[$normalizedColumnName])) { + if (! isset($columnNames[$normalizedColumnName])) { unset($foreignKeys[$key]); continue 2; } else { @@ -1131,16 +1119,20 @@ private function getForeignKeysInAlteredTable(TableDiff $diff) } } - if ($changed) { - $foreignKeys[$key] = new ForeignKeyConstraint($localColumns, $constraint->getForeignTableName(), $constraint->getForeignColumns(), $constraint->getName(), $constraint->getOptions()); + if (! $changed) { + continue; } + + $foreignKeys[$key] = new ForeignKeyConstraint($localColumns, $constraint->getForeignTableName(), $constraint->getForeignColumns(), $constraint->getName(), $constraint->getOptions()); } foreach ($diff->removedForeignKeys as $constraint) { $constraintName = strtolower($constraint->getName()); - if (strlen($constraintName) && isset($foreignKeys[$constraintName])) { - unset($foreignKeys[$constraintName]); + if (! strlen($constraintName) || ! isset($foreignKeys[$constraintName])) { + continue; } + + unset($foreignKeys[$constraintName]); } foreach (array_merge($diff->changedForeignKeys, $diff->addedForeignKeys) as $constraint) { @@ -1156,18 +1148,18 @@ private function getForeignKeysInAlteredTable(TableDiff $diff) } /** - * @param \Doctrine\DBAL\Schema\TableDiff $diff - * - * @return array + * @return Index[] */ private function getPrimaryIndexInAlteredTable(TableDiff $diff) { $primaryIndex = []; foreach ($this->getIndexesInAlteredTable($diff) as $index) { - if ($index->isPrimary()) { - $primaryIndex = [$index->getName() => $index]; + if (! $index->isPrimary()) { + continue; } + + $primaryIndex = [$index->getName() => $index]; } return $primaryIndex; diff --git a/lib/Doctrine/DBAL/Portability/Connection.php b/lib/Doctrine/DBAL/Portability/Connection.php index 723a333bb18..32186dcb0ec 100644 --- a/lib/Doctrine/DBAL/Portability/Connection.php +++ b/lib/Doctrine/DBAL/Portability/Connection.php @@ -1,62 +1,39 @@ . - */ namespace Doctrine\DBAL\Portability; use Doctrine\DBAL\Cache\QueryCacheProfile; use Doctrine\DBAL\ColumnCase; +use Doctrine\DBAL\Driver\PDOConnection; +use PDO; use const CASE_LOWER; use const CASE_UPPER; use function func_get_args; /** * Portability wrapper for a Connection. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ class Connection extends \Doctrine\DBAL\Connection { - const PORTABILITY_ALL = 255; - const PORTABILITY_NONE = 0; - const PORTABILITY_RTRIM = 1; - const PORTABILITY_EMPTY_TO_NULL = 4; - const PORTABILITY_FIX_CASE = 8; - - const PORTABILITY_DB2 = 13; - const PORTABILITY_ORACLE = 9; - const PORTABILITY_POSTGRESQL = 13; - const PORTABILITY_SQLITE = 13; - const PORTABILITY_OTHERVENDORS = 12; - const PORTABILITY_DRIZZLE = 13; - const PORTABILITY_SQLANYWHERE = 13; - const PORTABILITY_SQLSRV = 13; - - /** - * @var int - */ + public const PORTABILITY_ALL = 255; + public const PORTABILITY_NONE = 0; + public const PORTABILITY_RTRIM = 1; + public const PORTABILITY_EMPTY_TO_NULL = 4; + public const PORTABILITY_FIX_CASE = 8; + + public const PORTABILITY_DB2 = 13; + public const PORTABILITY_ORACLE = 9; + public const PORTABILITY_POSTGRESQL = 13; + public const PORTABILITY_SQLITE = 13; + public const PORTABILITY_OTHERVENDORS = 12; + public const PORTABILITY_DRIZZLE = 13; + public const PORTABILITY_SQLANYWHERE = 13; + public const PORTABILITY_SQLSRV = 13; + + /** @var int */ private $portability = self::PORTABILITY_NONE; - /** - * @var int - */ + /** @var int */ private $case; /** @@ -68,32 +45,32 @@ public function connect() if ($ret) { $params = $this->getParams(); if (isset($params['portability'])) { - if ($this->getDatabasePlatform()->getName() === "oracle") { - $params['portability'] = $params['portability'] & self::PORTABILITY_ORACLE; - } elseif ($this->getDatabasePlatform()->getName() === "postgresql") { - $params['portability'] = $params['portability'] & self::PORTABILITY_POSTGRESQL; - } elseif ($this->getDatabasePlatform()->getName() === "sqlite") { - $params['portability'] = $params['portability'] & self::PORTABILITY_SQLITE; - } elseif ($this->getDatabasePlatform()->getName() === "drizzle") { - $params['portability'] = $params['portability'] & self::PORTABILITY_DRIZZLE; + if ($this->getDatabasePlatform()->getName() === 'oracle') { + $params['portability'] &= self::PORTABILITY_ORACLE; + } elseif ($this->getDatabasePlatform()->getName() === 'postgresql') { + $params['portability'] &= self::PORTABILITY_POSTGRESQL; + } elseif ($this->getDatabasePlatform()->getName() === 'sqlite') { + $params['portability'] &= self::PORTABILITY_SQLITE; + } elseif ($this->getDatabasePlatform()->getName() === 'drizzle') { + $params['portability'] &= self::PORTABILITY_DRIZZLE; } elseif ($this->getDatabasePlatform()->getName() === 'sqlanywhere') { - $params['portability'] = $params['portability'] & self::PORTABILITY_SQLANYWHERE; + $params['portability'] &= self::PORTABILITY_SQLANYWHERE; } elseif ($this->getDatabasePlatform()->getName() === 'db2') { - $params['portability'] = $params['portability'] & self::PORTABILITY_DB2; + $params['portability'] &= self::PORTABILITY_DB2; } elseif ($this->getDatabasePlatform()->getName() === 'mssql') { - $params['portability'] = $params['portability'] & self::PORTABILITY_SQLSRV; + $params['portability'] &= self::PORTABILITY_SQLSRV; } else { - $params['portability'] = $params['portability'] & self::PORTABILITY_OTHERVENDORS; + $params['portability'] &= self::PORTABILITY_OTHERVENDORS; } $this->portability = $params['portability']; } if (isset($params['fetch_case']) && $this->portability & self::PORTABILITY_FIX_CASE) { - if ($this->_conn instanceof \Doctrine\DBAL\Driver\PDOConnection) { + if ($this->_conn instanceof PDOConnection) { // make use of c-level support for case handling - $this->_conn->setAttribute(\PDO::ATTR_CASE, $params['fetch_case']); + $this->_conn->setAttribute(PDO::ATTR_CASE, $params['fetch_case']); } else { - $this->case = ($params['fetch_case'] === ColumnCase::LOWER) ? CASE_LOWER : CASE_UPPER; + $this->case = $params['fetch_case'] === ColumnCase::LOWER ? CASE_LOWER : CASE_UPPER; } } } @@ -120,7 +97,7 @@ public function getFetchCase() /** * {@inheritdoc} */ - public function executeQuery($query, array $params = [], $types = [], QueryCacheProfile $qcp = null) + public function executeQuery($query, array $params = [], $types = [], ?QueryCacheProfile $qcp = null) { $stmt = new Statement(parent::executeQuery($query, $params, $types, $qcp), $this); $stmt->setFetchMode($this->defaultFetchMode); diff --git a/lib/Doctrine/DBAL/Portability/Statement.php b/lib/Doctrine/DBAL/Portability/Statement.php index d8826f2d2c6..1499ff1bf48 100644 --- a/lib/Doctrine/DBAL/Portability/Statement.php +++ b/lib/Doctrine/DBAL/Portability/Statement.php @@ -1,72 +1,44 @@ . - */ namespace Doctrine\DBAL\Portability; +use Doctrine\DBAL\Driver\Statement as DriverStatement; use Doctrine\DBAL\Driver\StatementIterator; use Doctrine\DBAL\FetchMode; use Doctrine\DBAL\ParameterType; +use IteratorAggregate; +use PDO; use function array_change_key_case; -use function is_null; use function is_string; use function rtrim; /** * Portability wrapper for a Statement. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ -class Statement implements \IteratorAggregate, \Doctrine\DBAL\Driver\Statement +class Statement implements IteratorAggregate, DriverStatement { - /** - * @var int - */ + /** @var int */ private $portability; - /** - * @var \Doctrine\DBAL\Driver\Statement - */ + /** @var DriverStatement */ private $stmt; - /** - * @var int - */ + /** @var int */ private $case; - /** - * @var int - */ + /** @var int */ private $defaultFetchMode = FetchMode::MIXED; /** * Wraps Statement and applies portability measures. * - * @param \Doctrine\DBAL\Driver\Statement $stmt - * @param \Doctrine\DBAL\Portability\Connection $conn + * @param DriverStatement $stmt */ public function __construct($stmt, Connection $conn) { - $this->stmt = $stmt; + $this->stmt = $stmt; $this->portability = $conn->getPortability(); - $this->case = $conn->getFetchCase(); + $this->case = $conn->getFetchCase(); } /** @@ -146,7 +118,7 @@ public function getIterator() /** * {@inheritdoc} */ - public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) + public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { $fetchMode = $fetchMode ?: $this->defaultFetchMode; @@ -180,7 +152,7 @@ public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = n && ($fetchMode === FetchMode::ASSOCIATIVE || $fetchMode === FetchMode::MIXED) && ($this->portability & Connection::PORTABILITY_FIX_CASE); - if ( ! $iterateRow && !$fixCase) { + if (! $iterateRow && ! $fixCase) { return $rows; } @@ -208,11 +180,11 @@ public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = n * @param int $iterateRow * @param bool $fixCase * - * @return array + * @return mixed */ protected function fixRow($row, $iterateRow, $fixCase) { - if ( ! $row) { + if (! $row) { return $row; } diff --git a/lib/Doctrine/DBAL/Query/Expression/CompositeExpression.php b/lib/Doctrine/DBAL/Query/Expression/CompositeExpression.php index 00802a44ee8..443d71bc37e 100644 --- a/lib/Doctrine/DBAL/Query/Expression/CompositeExpression.php +++ b/lib/Doctrine/DBAL/Query/Expression/CompositeExpression.php @@ -1,46 +1,25 @@ . - */ namespace Doctrine\DBAL\Query\Expression; +use Countable; use function count; use function implode; /** * Composite expression is responsible to build a group of similar expression. - * - * @link www.doctrine-project.org - * @since 2.1 - * @author Guilherme Blanco - * @author Benjamin Eberlei */ -class CompositeExpression implements \Countable +class CompositeExpression implements Countable { /** * Constant that represents an AND composite expression. */ - const TYPE_AND = 'AND'; + public const TYPE_AND = 'AND'; /** * Constant that represents an OR composite expression. */ - const TYPE_OR = 'OR'; + public const TYPE_OR = 'OR'; /** * The instance type of composite expression. @@ -52,15 +31,13 @@ class CompositeExpression implements \Countable /** * Each expression part of the composite expression. * - * @var array + * @var self[]|string[] */ private $parts = []; /** - * Constructor. - * - * @param string $type Instance type of composite expression. - * @param array $parts Composition of expressions to be joined on composite expression. + * @param string $type Instance type of composite expression. + * @param self[]|string[] $parts Composition of expressions to be joined on composite expression. */ public function __construct($type, array $parts = []) { @@ -72,7 +49,7 @@ public function __construct($type, array $parts = []) /** * Adds multiple parts to composite expression. * - * @param array $parts + * @param self[]|string[] $parts * * @return \Doctrine\DBAL\Query\Expression\CompositeExpression */ @@ -98,7 +75,7 @@ public function add($part) return $this; } - if ($part instanceof self && 0 === count($part)) { + if ($part instanceof self && count($part) === 0) { return $this; } diff --git a/lib/Doctrine/DBAL/Query/Expression/ExpressionBuilder.php b/lib/Doctrine/DBAL/Query/Expression/ExpressionBuilder.php index 1ee72484775..91f370aecb6 100644 --- a/lib/Doctrine/DBAL/Query/Expression/ExpressionBuilder.php +++ b/lib/Doctrine/DBAL/Query/Expression/ExpressionBuilder.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Query\Expression; @@ -28,32 +11,27 @@ /** * ExpressionBuilder class is responsible to dynamically create SQL query parts. - * - * @link www.doctrine-project.org - * @since 2.1 - * @author Guilherme Blanco - * @author Benjamin Eberlei */ class ExpressionBuilder { - const EQ = '='; - const NEQ = '<>'; - const LT = '<'; - const LTE = '<='; - const GT = '>'; - const GTE = '>='; + public const EQ = '='; + public const NEQ = '<>'; + public const LT = '<'; + public const LTE = '<='; + public const GT = '>'; + public const GTE = '>='; /** * The DBAL Connection. * - * @var \Doctrine\DBAL\Connection + * @var Connection */ private $connection; /** * Initializes a new ExpressionBuilder. * - * @param \Doctrine\DBAL\Connection $connection The DBAL Connection. + * @param Connection $connection The DBAL Connection. */ public function __construct(Connection $connection) { @@ -72,7 +50,7 @@ public function __construct(Connection $connection) * @param mixed $x Optional clause. Defaults = null, but requires * at least one defined when converting to string. * - * @return \Doctrine\DBAL\Query\Expression\CompositeExpression + * @return CompositeExpression */ public function andX($x = null) { @@ -91,7 +69,7 @@ public function andX($x = null) * @param mixed $x Optional clause. Defaults = null, but requires * at least one defined when converting to string. * - * @return \Doctrine\DBAL\Query\Expression\CompositeExpression + * @return CompositeExpression */ public function orX($x = null) { @@ -282,27 +260,27 @@ public function notLike($x, $y/*, ?string $escapeChar = null */) /** * Creates a IN () comparison expression with the given arguments. * - * @param string $x The field in string format to be inspected by IN() comparison. - * @param string|array $y The placeholder or the array of values to be used by IN() comparison. + * @param string $x The field in string format to be inspected by IN() comparison. + * @param string|string[] $y The placeholder or the array of values to be used by IN() comparison. * * @return string */ public function in($x, $y) { - return $this->comparison($x, 'IN', '('.implode(', ', (array) $y).')'); + return $this->comparison($x, 'IN', '(' . implode(', ', (array) $y) . ')'); } /** * Creates a NOT IN () comparison expression with the given arguments. * - * @param string $x The field in string format to be inspected by NOT IN() comparison. - * @param string|array $y The placeholder or the array of values to be used by NOT IN() comparison. + * @param string $x The field in string format to be inspected by NOT IN() comparison. + * @param string|string[] $y The placeholder or the array of values to be used by NOT IN() comparison. * * @return string */ public function notIn($x, $y) { - return $this->comparison($x, 'NOT IN', '('.implode(', ', (array) $y).')'); + return $this->comparison($x, 'NOT IN', '(' . implode(', ', (array) $y) . ')'); } /** diff --git a/lib/Doctrine/DBAL/Query/QueryBuilder.php b/lib/Doctrine/DBAL/Query/QueryBuilder.php index 8a69806b3a9..12584d960ab 100644 --- a/lib/Doctrine/DBAL/Query/QueryBuilder.php +++ b/lib/Doctrine/DBAL/Query/QueryBuilder.php @@ -1,27 +1,12 @@ . - */ namespace Doctrine\DBAL\Query; +use Doctrine\DBAL\Connection; +use Doctrine\DBAL\Driver\Statement; use Doctrine\DBAL\ParameterType; use Doctrine\DBAL\Query\Expression\CompositeExpression; -use Doctrine\DBAL\Connection; +use Doctrine\DBAL\Query\Expression\ExpressionBuilder; use function array_key_exists; use function array_keys; use function array_unshift; @@ -29,7 +14,6 @@ use function func_num_args; use function implode; use function is_array; -use function is_null; use function is_object; use function key; use function strtoupper; @@ -44,37 +28,34 @@ * The query builder does no validation whatsoever if certain features even work with the * underlying database vendor. Limit queries and joins are NOT applied to UPDATE and DELETE statements * even if some vendors such as MySQL support it. - * - * @link www.doctrine-project.org - * @since 2.1 - * @author Guilherme Blanco - * @author Benjamin Eberlei */ class QueryBuilder { /* * The query types. */ - const SELECT = 0; - const DELETE = 1; - const UPDATE = 2; - const INSERT = 3; + public const SELECT = 0; + public const DELETE = 1; + public const UPDATE = 2; + public const INSERT = 3; /* * The builder states. */ - const STATE_DIRTY = 0; - const STATE_CLEAN = 1; + public const STATE_DIRTY = 0; + public const STATE_CLEAN = 1; /** * The DBAL Connection. * - * @var \Doctrine\DBAL\Connection + * @var Connection */ private $connection; /** - * @var array The array of SQL parts collected. + * The array of SQL parts collected. + * + * @var mixed[] */ private $sqlParts = [ 'select' => [], @@ -98,14 +79,14 @@ class QueryBuilder /** * The query parameters. * - * @var array + * @var mixed[] */ private $params = []; /** * The parameter type map of this query. * - * @var array + * @var int[]|string[] */ private $paramTypes = []; @@ -147,7 +128,7 @@ class QueryBuilder /** * Initializes a new QueryBuilder. * - * @param \Doctrine\DBAL\Connection $connection The DBAL Connection. + * @param Connection $connection The DBAL Connection. */ public function __construct(Connection $connection) { @@ -168,7 +149,7 @@ public function __construct(Connection $connection) * For more complex expression construction, consider storing the expression * builder object in a local variable. * - * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder + * @return ExpressionBuilder */ public function expr() { @@ -188,7 +169,7 @@ public function getType() /** * Gets the associated DBAL Connection for this query builder. * - * @return \Doctrine\DBAL\Connection + * @return Connection */ public function getConnection() { @@ -211,11 +192,11 @@ public function getState() * Uses {@see Connection::executeQuery} for select statements and {@see Connection::executeUpdate} * for insert, update and delete statements. * - * @return \Doctrine\DBAL\Driver\Statement|int + * @return Statement|int */ public function execute() { - if ($this->type == self::SELECT) { + if ($this->type === self::SELECT) { return $this->connection->executeQuery($this->getSQL(), $this->params, $this->paramTypes); } @@ -259,7 +240,7 @@ public function getSQL() } $this->state = self::STATE_CLEAN; - $this->sql = $sql; + $this->sql = $sql; return $sql; } @@ -306,15 +287,15 @@ public function setParameter($key, $value, $type = null) * )); * * - * @param array $params The query parameters to set. - * @param array $types The query parameters types to set. + * @param mixed[] $params The query parameters to set. + * @param int[]|string[] $types The query parameters types to set. * * @return $this This QueryBuilder instance. */ public function setParameters(array $params, array $types = []) { $this->paramTypes = $types; - $this->params = $params; + $this->params = $params; return $this; } @@ -322,7 +303,7 @@ public function setParameters(array $params, array $types = []) /** * Gets all defined query parameters for the query being constructed indexed by parameter index or name. * - * @return array The currently defined query parameters indexed by parameter index or name. + * @return mixed[] The currently defined query parameters indexed by parameter index or name. */ public function getParameters() { @@ -344,7 +325,7 @@ public function getParameter($key) /** * Gets all defined query parameter types for the query being constructed indexed by parameter index or name. * - * @return array The currently defined query parameter types indexed by parameter index or name. + * @return int[]|string[] The currently defined query parameter types indexed by parameter index or name. */ public function getParameterTypes() { @@ -372,7 +353,7 @@ public function getParameterType($key) */ public function setFirstResult($firstResult) { - $this->state = self::STATE_DIRTY; + $this->state = self::STATE_DIRTY; $this->firstResult = $firstResult; return $this; @@ -398,7 +379,7 @@ public function getFirstResult() */ public function setMaxResults($maxResults) { - $this->state = self::STATE_DIRTY; + $this->state = self::STATE_DIRTY; $this->maxResults = $maxResults; return $this; @@ -429,22 +410,22 @@ public function getMaxResults() */ public function add($sqlPartName, $sqlPart, $append = false) { - $isArray = is_array($sqlPart); + $isArray = is_array($sqlPart); $isMultiple = is_array($this->sqlParts[$sqlPartName]); - if ($isMultiple && !$isArray) { + if ($isMultiple && ! $isArray) { $sqlPart = [$sqlPart]; } $this->state = self::STATE_DIRTY; if ($append) { - if ($sqlPartName == "orderBy" || $sqlPartName == "groupBy" || $sqlPartName == "select" || $sqlPartName == "set") { + if ($sqlPartName === 'orderBy' || $sqlPartName === 'groupBy' || $sqlPartName === 'select' || $sqlPartName === 'set') { foreach ($sqlPart as $part) { $this->sqlParts[$sqlPartName][] = $part; } } elseif ($isArray && is_array($sqlPart[key($sqlPart)])) { - $key = key($sqlPart); + $key = key($sqlPart); $this->sqlParts[$sqlPartName][$key][] = $sqlPart[$key]; } elseif ($isMultiple) { $this->sqlParts[$sqlPartName][] = $sqlPart; @@ -536,13 +517,13 @@ public function delete($delete = null, $alias = null) { $this->type = self::DELETE; - if ( ! $delete) { + if (! $delete) { return $this; } return $this->add('from', [ 'table' => $delete, - 'alias' => $alias + 'alias' => $alias, ]); } @@ -552,9 +533,9 @@ public function delete($delete = null, $alias = null) * * * $qb = $conn->createQueryBuilder() - * ->update('users', 'u') - * ->set('u.last_login', 'NOW()') - * ->where('u.id = ?'); + * ->update('counters', 'c') + * ->set('c.value', 'c.value + 1') + * ->where('c.id = ?'); * * * @param string $update The table whose rows are subject to the update. @@ -566,13 +547,13 @@ public function update($update = null, $alias = null) { $this->type = self::UPDATE; - if ( ! $update) { + if (! $update) { return $this; } return $this->add('from', [ 'table' => $update, - 'alias' => $alias + 'alias' => $alias, ]); } @@ -599,13 +580,11 @@ public function insert($insert = null) { $this->type = self::INSERT; - if ( ! $insert) { + if (! $insert) { return $this; } - return $this->add('from', [ - 'table' => $insert - ]); + return $this->add('from', ['table' => $insert]); } /** @@ -627,7 +606,7 @@ public function from($from, $alias = null) { return $this->add('from', [ 'table' => $from, - 'alias' => $alias + 'alias' => $alias, ], true); } @@ -677,8 +656,8 @@ public function innerJoin($fromAlias, $join, $alias, $condition = null) 'joinType' => 'inner', 'joinTable' => $join, 'joinAlias' => $alias, - 'joinCondition' => $condition - ] + 'joinCondition' => $condition, + ], ], true); } @@ -706,8 +685,8 @@ public function leftJoin($fromAlias, $join, $alias, $condition = null) 'joinType' => 'left', 'joinTable' => $join, 'joinAlias' => $alias, - 'joinCondition' => $condition - ] + 'joinCondition' => $condition, + ], ], true); } @@ -735,8 +714,8 @@ public function rightJoin($fromAlias, $join, $alias, $condition = null) 'joinType' => 'right', 'joinTable' => $join, 'joinAlias' => $alias, - 'joinCondition' => $condition - ] + 'joinCondition' => $condition, + ], ], true); } @@ -745,9 +724,9 @@ public function rightJoin($fromAlias, $join, $alias, $condition = null) * * * $qb = $conn->createQueryBuilder() - * ->update('users', 'u') - * ->set('u.last_login', 'NOW()') - * ->where('u.id = ?'); + * ->update('counters', 'c') + * ->set('c.value', 'c.value + 1') + * ->where('c.id = ?'); * * * @param string $key The column to set. @@ -757,7 +736,7 @@ public function rightJoin($fromAlias, $join, $alias, $condition = null) */ public function set($key, $value) { - return $this->add('set', $key .' = ' . $value, true); + return $this->add('set', $key . ' = ' . $value, true); } /** @@ -766,19 +745,19 @@ public function set($key, $value) * * * $qb = $conn->createQueryBuilder() - * ->select('u.name') - * ->from('users', 'u') - * ->where('u.id = ?'); + * ->select('c.value') + * ->from('counters', 'c') + * ->where('c.id = ?'); * * // You can optionally programatically build and/or expressions * $qb = $conn->createQueryBuilder(); * * $or = $qb->expr()->orx(); - * $or->add($qb->expr()->eq('u.id', 1)); - * $or->add($qb->expr()->eq('u.id', 2)); + * $or->add($qb->expr()->eq('c.id', 1)); + * $or->add($qb->expr()->eq('c.id', 2)); * - * $qb->update('users', 'u') - * ->set('u.last_login', 'NOW()') + * $qb->update('counters', 'c') + * ->set('c.value', 'c.value + 1') * ->where($or); * * @@ -788,7 +767,7 @@ public function set($key, $value) */ public function where($predicates) { - if ( ! (func_num_args() == 1 && $predicates instanceof CompositeExpression)) { + if (! (func_num_args() === 1 && $predicates instanceof CompositeExpression)) { $predicates = new CompositeExpression(CompositeExpression::TYPE_AND, func_get_args()); } @@ -807,15 +786,15 @@ public function where($predicates) * ->andWhere('u.is_active = 1'); * * + * @see where() + * * @param mixed $where The query restrictions. * * @return $this This QueryBuilder instance. - * - * @see where() */ public function andWhere($where) { - $args = func_get_args(); + $args = func_get_args(); $where = $this->getQueryPart('where'); if ($where instanceof CompositeExpression && $where->getType() === CompositeExpression::TYPE_AND) { @@ -840,15 +819,15 @@ public function andWhere($where) * ->orWhere('u.id = 2'); * * + * @see where() + * * @param mixed $where The WHERE statement. * * @return $this This QueryBuilder instance. - * - * @see where() */ public function orWhere($where) { - $args = func_get_args(); + $args = func_get_args(); $where = $this->getQueryPart('where'); if ($where instanceof CompositeExpression && $where->getType() === CompositeExpression::TYPE_OR) { @@ -955,7 +934,7 @@ public function setValue($column, $value) * ); * * - * @param array $values The values to specify for the insert query indexed by column names. + * @param mixed[] $values The values to specify for the insert query indexed by column names. * * @return $this This QueryBuilder instance. */ @@ -974,7 +953,7 @@ public function values(array $values) */ public function having($having) { - if ( ! (func_num_args() == 1 && $having instanceof CompositeExpression)) { + if (! (func_num_args() === 1 && $having instanceof CompositeExpression)) { $having = new CompositeExpression(CompositeExpression::TYPE_AND, func_get_args()); } @@ -991,7 +970,7 @@ public function having($having) */ public function andHaving($having) { - $args = func_get_args(); + $args = func_get_args(); $having = $this->getQueryPart('having'); if ($having instanceof CompositeExpression && $having->getType() === CompositeExpression::TYPE_AND) { @@ -1014,7 +993,7 @@ public function andHaving($having) */ public function orHaving($having) { - $args = func_get_args(); + $args = func_get_args(); $having = $this->getQueryPart('having'); if ($having instanceof CompositeExpression && $having->getType() === CompositeExpression::TYPE_OR) { @@ -1069,7 +1048,7 @@ public function getQueryPart($queryPartName) /** * Gets all query parts. * - * @return array + * @return mixed[] */ public function getQueryParts() { @@ -1079,7 +1058,7 @@ public function getQueryParts() /** * Resets SQL parts. * - * @param array|null $queryPartNames + * @param string[]|null $queryPartNames * * @return $this This QueryBuilder instance. */ @@ -1116,7 +1095,7 @@ public function resetQueryPart($queryPartName) /** * @return string * - * @throws \Doctrine\DBAL\Query\QueryException + * @throws QueryException */ private function getSQLForSelect() { @@ -1144,16 +1123,16 @@ private function getSQLForSelect() */ private function getFromClauses() { - $fromClauses = []; + $fromClauses = []; $knownAliases = []; // Loop through all FROM clauses foreach ($this->sqlParts['from'] as $from) { if ($from['alias'] === null) { - $tableSql = $from['table']; + $tableSql = $from['table']; $tableReference = $from['table']; } else { - $tableSql = $from['table'] . ' ' . $from['alias']; + $tableSql = $from['table'] . ' ' . $from['alias']; $tableReference = $from['alias']; } @@ -1168,14 +1147,14 @@ private function getFromClauses() } /** - * @param array $knownAliases + * @param string[] $knownAliases * * @throws QueryException */ private function verifyAllAliasesAreKnown(array $knownAliases) { foreach ($this->sqlParts['join'] as $fromAlias => $joins) { - if ( ! isset($knownAliases[$fromAlias])) { + if (! isset($knownAliases[$fromAlias])) { throw QueryException::unknownAlias($fromAlias, array_keys($knownAliases)); } } @@ -1209,11 +1188,9 @@ private function getSQLForInsert() private function getSQLForUpdate() { $table = $this->sqlParts['from']['table'] . ($this->sqlParts['from']['alias'] ? ' ' . $this->sqlParts['from']['alias'] : ''); - $query = 'UPDATE ' . $table - . ' SET ' . implode(", ", $this->sqlParts['set']) + return 'UPDATE ' . $table + . ' SET ' . implode(', ', $this->sqlParts['set']) . ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : ''); - - return $query; } /** @@ -1224,9 +1201,7 @@ private function getSQLForUpdate() private function getSQLForDelete() { $table = $this->sqlParts['from']['table'] . ($this->sqlParts['from']['alias'] ? ' ' . $this->sqlParts['from']['alias'] : ''); - $query = 'DELETE FROM ' . $table . ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : ''); - - return $query; + return 'DELETE FROM ' . $table . ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : ''); } /** @@ -1260,7 +1235,6 @@ public function __toString() * $stmt = $q->executeQuery(); // executed with 'id = 2' * * - * @license New BSD License * @link http://www.zetacomponents.org * * @param mixed $value @@ -1273,7 +1247,7 @@ public function createNamedParameter($value, $type = ParameterType::STRING, $pla { if ($placeHolder === null) { $this->boundCounter++; - $placeHolder = ":dcValue" . $this->boundCounter; + $placeHolder = ':dcValue' . $this->boundCounter; } $this->setParameter(substr($placeHolder, 1), $value, $type); @@ -1307,12 +1281,12 @@ public function createPositionalParameter($value, $type = ParameterType::STRING) $this->boundCounter++; $this->setParameter($this->boundCounter, $value, $type); - return "?"; + return '?'; } /** - * @param string $fromAlias - * @param array $knownAliases + * @param string $fromAlias + * @param string[] $knownAliases * * @return string * @@ -1327,7 +1301,7 @@ private function getSQLForJoins($fromAlias, array &$knownAliases) if (array_key_exists($join['joinAlias'], $knownAliases)) { throw QueryException::nonUniqueAlias($join['joinAlias'], array_keys($knownAliases)); } - $sql .= ' ' . strtoupper($join['joinType']) + $sql .= ' ' . strtoupper($join['joinType']) . ' JOIN ' . $join['joinTable'] . ' ' . $join['joinAlias'] . ' ON ' . ((string) $join['joinCondition']); $knownAliases[$join['joinAlias']] = true; @@ -1351,9 +1325,11 @@ public function __clone() foreach ($this->sqlParts as $part => $elements) { if (is_array($this->sqlParts[$part])) { foreach ($this->sqlParts[$part] as $idx => $element) { - if (is_object($element)) { - $this->sqlParts[$part][$idx] = clone $element; + if (! is_object($element)) { + continue; } + + $this->sqlParts[$part][$idx] = clone $element; } } elseif (is_object($elements)) { $this->sqlParts[$part] = clone $elements; @@ -1361,9 +1337,11 @@ public function __clone() } foreach ($this->params as $name => $param) { - if (is_object($param)) { - $this->params[$name] = clone $param; + if (! is_object($param)) { + continue; } + + $this->params[$name] = clone $param; } } } diff --git a/lib/Doctrine/DBAL/Query/QueryException.php b/lib/Doctrine/DBAL/Query/QueryException.php index 45a3d55f650..3fcb3b480ec 100644 --- a/lib/Doctrine/DBAL/Query/QueryException.php +++ b/lib/Doctrine/DBAL/Query/QueryException.php @@ -1,55 +1,35 @@ . - */ namespace Doctrine\DBAL\Query; use Doctrine\DBAL\DBALException; use function implode; -/** - * @since 2.1.4 - */ class QueryException extends DBALException { /** - * @param string $alias - * @param array $registeredAliases + * @param string $alias + * @param string[] $registeredAliases * * @return \Doctrine\DBAL\Query\QueryException */ public static function unknownAlias($alias, $registeredAliases) { return new self("The given alias '" . $alias . "' is not part of " . - "any FROM or JOIN clause table. The currently registered " . - "aliases are: " . implode(", ", $registeredAliases) . "."); + 'any FROM or JOIN clause table. The currently registered ' . + 'aliases are: ' . implode(', ', $registeredAliases) . '.'); } /** - * @param string $alias - * @param array $registeredAliases + * @param string $alias + * @param string[] $registeredAliases * * @return \Doctrine\DBAL\Query\QueryException */ public static function nonUniqueAlias($alias, $registeredAliases) { return new self("The given alias '" . $alias . "' is not unique " . - "in FROM and JOIN clause table. The currently registered " . - "aliases are: " . implode(", ", $registeredAliases) . "."); + 'in FROM and JOIN clause table. The currently registered ' . + 'aliases are: ' . implode(', ', $registeredAliases) . '.'); } } diff --git a/lib/Doctrine/DBAL/SQLParserUtils.php b/lib/Doctrine/DBAL/SQLParserUtils.php index e635af754d9..537cd9e4884 100644 --- a/lib/Doctrine/DBAL/SQLParserUtils.php +++ b/lib/Doctrine/DBAL/SQLParserUtils.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL; @@ -31,27 +14,24 @@ use function key; use function ksort; use function preg_match_all; +use function sprintf; use function strlen; use function strpos; use function substr; /** * Utility class that parses sql statements with regard to types and parameters. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ class SQLParserUtils { - const POSITIONAL_TOKEN = '\?'; - const NAMED_TOKEN = '(? $needlePos) { - if ( ! isset($arrayPositions[$needle])) { + if (! isset($arrayPositions[$needle])) { continue; } @@ -162,8 +142,8 @@ public static function expandListParameters($query, $params, $types) array_slice($types, $needle + 1) ); - $expandStr = $count ? implode(", ", array_fill(0, $count, "?")) : 'NULL'; - $query = substr($query, 0, $needlePos) . $expandStr . substr($query, $needlePos + 1); + $expandStr = $count ? implode(', ', array_fill(0, $count, '?')) : 'NULL'; + $query = substr($query, 0, $needlePos) . $expandStr . substr($query, $needlePos + 1); $paramOffset += ($count - 1); // Grows larger by number of parameters minus the replaced needle. $queryOffset += (strlen($expandStr) - 1); @@ -180,7 +160,7 @@ public static function expandListParameters($query, $params, $types) $paramLen = strlen($paramName) + 1; $value = static::extractParam($paramName, $params, true); - if ( ! isset($arrayPositions[$paramName]) && ! isset($arrayPositions[':' . $paramName])) { + if (! isset($arrayPositions[$paramName]) && ! isset($arrayPositions[':' . $paramName])) { $pos += $queryOffset; $queryOffset -= ($paramLen - 1); $paramsOrd[] = $value; @@ -190,8 +170,8 @@ public static function expandListParameters($query, $params, $types) continue; } - $count = count($value); - $expandStr = $count > 0 ? implode(', ', array_fill(0, $count, '?')) : 'NULL'; + $count = count($value); + $expandStr = $count > 0 ? implode(', ', array_fill(0, $count, '?')) : 'NULL'; foreach ($value as $val) { $paramsOrd[] = $val; @@ -215,27 +195,31 @@ public static function expandListParameters($query, $params, $types) * 1 => offset of fragment in $statement * * @param string $statement - * @return array + * + * @return mixed[][] */ private static function getUnquotedStatementFragments($statement) { - $literal = self::ESCAPED_SINGLE_QUOTED_TEXT . '|' . - self::ESCAPED_DOUBLE_QUOTED_TEXT . '|' . - self::ESCAPED_BACKTICK_QUOTED_TEXT . '|' . - self::ESCAPED_BRACKET_QUOTED_TEXT; - preg_match_all("/([^'\"`\[]+)(?:$literal)?/s", $statement, $fragments, PREG_OFFSET_CAPTURE); + $literal = self::ESCAPED_SINGLE_QUOTED_TEXT . '|' . + self::ESCAPED_DOUBLE_QUOTED_TEXT . '|' . + self::ESCAPED_BACKTICK_QUOTED_TEXT . '|' . + self::ESCAPED_BRACKET_QUOTED_TEXT; + $expression = sprintf('/((.+(?i:ARRAY)\\[.+\\])|([^\'"`\\[]+))(?:%s)?/s', $literal); + + preg_match_all($expression, $statement, $fragments, PREG_OFFSET_CAPTURE); return $fragments[1]; } /** * @param string $paramName The name of the parameter (without a colon in front) - * @param array $paramsOrTypes A hash of parameters or types + * @param mixed $paramsOrTypes A hash of parameters or types * @param bool $isParam * @param mixed $defaultValue An optional default value. If omitted, an exception is thrown * - * @throws SQLParserUtilsException * @return mixed + * + * @throws SQLParserUtilsException */ private static function extractParam($paramName, $paramsOrTypes, $isParam, $defaultValue = null) { @@ -248,7 +232,7 @@ private static function extractParam($paramName, $paramsOrTypes, $isParam, $defa return $paramsOrTypes[':' . $paramName]; } - if (null !== $defaultValue) { + if ($defaultValue !== null) { return $defaultValue; } diff --git a/lib/Doctrine/DBAL/SQLParserUtilsException.php b/lib/Doctrine/DBAL/SQLParserUtilsException.php index e7c15c53e84..a500ed52dd3 100644 --- a/lib/Doctrine/DBAL/SQLParserUtilsException.php +++ b/lib/Doctrine/DBAL/SQLParserUtilsException.php @@ -1,23 +1,4 @@ . - */ namespace Doctrine\DBAL; @@ -25,11 +6,6 @@ /** * Doctrine\DBAL\ConnectionException - * - * @license http://www.opensource.org/licenses/mit-license.php MIT - * @link www.doctrine-project.org - * @since 2.4 - * @author Lars Strojny */ class SQLParserUtilsException extends DBALException { diff --git a/lib/Doctrine/DBAL/Schema/AbstractAsset.php b/lib/Doctrine/DBAL/Schema/AbstractAsset.php index 86f353cb993..eb7262e32a6 100644 --- a/lib/Doctrine/DBAL/Schema/AbstractAsset.php +++ b/lib/Doctrine/DBAL/Schema/AbstractAsset.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Schema; @@ -36,16 +19,10 @@ * * This encapsulation hack is necessary to keep a consistent state of the database schema. Say we have a list of tables * array($tableName => Table($tableName)); if you want to rename the table, you have to make sure - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ abstract class AbstractAsset { - /** - * @var string - */ + /** @var string */ protected $_name; /** @@ -55,9 +32,7 @@ abstract class AbstractAsset */ protected $_namespace = null; - /** - * @var bool - */ + /** @var bool */ protected $_quoted = false; /** @@ -71,12 +46,12 @@ protected function _setName($name) { if ($this->isIdentifierQuoted($name)) { $this->_quoted = true; - $name = $this->trimQuotes($name); + $name = $this->trimQuotes($name); } - if (strpos($name, ".") !== false) { - $parts = explode(".", $name); + if (strpos($name, '.') !== false) { + $parts = explode('.', $name); $this->_namespace = $parts[0]; - $name = $parts[1]; + $name = $parts[1]; } $this->_name = $name; } @@ -90,7 +65,7 @@ protected function _setName($name) */ public function isInDefaultNamespace($defaultNamespaceName) { - return $this->_namespace == $defaultNamespaceName || $this->_namespace === null; + return $this->_namespace === $defaultNamespaceName || $this->_namespace === null; } /** @@ -116,7 +91,7 @@ public function getNamespaceName() public function getShortestName($defaultNamespaceName) { $shortestName = $this->getName(); - if ($this->_namespace == $defaultNamespaceName) { + if ($this->_namespace === $defaultNamespaceName) { $shortestName = $this->_name; } @@ -139,8 +114,8 @@ public function getShortestName($defaultNamespaceName) public function getFullQualifiedName($defaultNamespaceName) { $name = $this->getName(); - if ( ! $this->_namespace) { - $name = $defaultNamespaceName . "." . $name; + if (! $this->_namespace) { + $name = $defaultNamespaceName . '.' . $name; } return strtolower($name); @@ -165,7 +140,7 @@ public function isQuoted() */ protected function isIdentifierQuoted($identifier) { - return (isset($identifier[0]) && ($identifier[0] == '`' || $identifier[0] == '"' || $identifier[0] == '[')); + return isset($identifier[0]) && ($identifier[0] === '`' || $identifier[0] === '"' || $identifier[0] === '['); } /** @@ -188,7 +163,7 @@ protected function trimQuotes($identifier) public function getName() { if ($this->_namespace) { - return $this->_namespace . "." . $this->_name; + return $this->_namespace . '.' . $this->_name; } return $this->_name; @@ -198,19 +173,17 @@ public function getName() * Gets the quoted representation of this asset but only if it was defined with one. Otherwise * return the plain unquoted value as inserted. * - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - * * @return string */ public function getQuotedName(AbstractPlatform $platform) { $keywords = $platform->getReservedKeywordsList(); - $parts = explode(".", $this->getName()); + $parts = explode('.', $this->getName()); foreach ($parts as $k => $v) { - $parts[$k] = ($this->_quoted || $keywords->isKeyword($v)) ? $platform->quoteIdentifier($v) : $v; + $parts[$k] = $this->_quoted || $keywords->isKeyword($v) ? $platform->quoteIdentifier($v) : $v; } - return implode(".", $parts); + return implode('.', $parts); } /** @@ -220,15 +193,15 @@ public function getQuotedName(AbstractPlatform $platform) * however building idents automatically for foreign keys, composite keys or such can easily create * very long names. * - * @param array $columnNames - * @param string $prefix - * @param int $maxSize + * @param string[] $columnNames + * @param string $prefix + * @param int $maxSize * * @return string */ - protected function _generateIdentifierName($columnNames, $prefix='', $maxSize=30) + protected function _generateIdentifierName($columnNames, $prefix = '', $maxSize = 30) { - $hash = implode("", array_map(function ($column) { + $hash = implode('', array_map(static function ($column) { return dechex(crc32($column)); }, $columnNames)); diff --git a/lib/Doctrine/DBAL/Schema/AbstractSchemaManager.php b/lib/Doctrine/DBAL/Schema/AbstractSchemaManager.php index f9f7cff7af6..9b917427fd8 100644 --- a/lib/Doctrine/DBAL/Schema/AbstractSchemaManager.php +++ b/lib/Doctrine/DBAL/Schema/AbstractSchemaManager.php @@ -1,37 +1,23 @@ . - */ namespace Doctrine\DBAL\Schema; -use Doctrine\DBAL\Events; +use Doctrine\DBAL\Connection; +use Doctrine\DBAL\ConnectionException; +use Doctrine\DBAL\DBALException; use Doctrine\DBAL\Event\SchemaColumnDefinitionEventArgs; use Doctrine\DBAL\Event\SchemaIndexDefinitionEventArgs; -use Doctrine\DBAL\DBALException; +use Doctrine\DBAL\Events; use Doctrine\DBAL\Platforms\AbstractPlatform; +use Throwable; use function array_filter; +use function array_intersect; use function array_map; use function array_values; use function call_user_func_array; use function count; use function func_get_args; use function is_array; -use function is_null; use function preg_match; use function str_replace; use function strtolower; @@ -39,37 +25,27 @@ /** * Base class for schema managers. Schema managers are used to inspect and/or * modify the database schema/structure. - * - * @author Konsta Vesterinen - * @author Lukas Smith (PEAR MDB2 library) - * @author Roman Borschel - * @author Jonathan H. Wage - * @author Benjamin Eberlei - * @since 2.0 */ abstract class AbstractSchemaManager { /** * Holds instance of the Doctrine connection for this schema manager. * - * @var \Doctrine\DBAL\Connection + * @var Connection */ protected $_conn; /** * Holds instance of the database platform used for this schema manager. * - * @var \Doctrine\DBAL\Platforms\AbstractPlatform + * @var AbstractPlatform */ protected $_platform; /** * Constructor. Accepts the Connection instance to manage the schema for. - * - * @param \Doctrine\DBAL\Connection $conn - * @param \Doctrine\DBAL\Platforms\AbstractPlatform|null $platform */ - public function __construct(\Doctrine\DBAL\Connection $conn, AbstractPlatform $platform = null) + public function __construct(Connection $conn, ?AbstractPlatform $platform = null) { $this->_conn = $conn; $this->_platform = $platform ?: $this->_conn->getDatabasePlatform(); @@ -78,7 +54,7 @@ public function __construct(\Doctrine\DBAL\Connection $conn, AbstractPlatform $p /** * Returns the associated platform. * - * @return \Doctrine\DBAL\Platforms\AbstractPlatform + * @return AbstractPlatform */ public function getDatabasePlatform() { @@ -99,14 +75,14 @@ public function getDatabasePlatform() */ public function tryMethod() { - $args = func_get_args(); + $args = func_get_args(); $method = $args[0]; unset($args[0]); $args = array_values($args); try { return call_user_func_array([$this, $method], $args); - } catch (\Exception $e) { + } catch (Throwable $e) { return false; } } @@ -114,7 +90,7 @@ public function tryMethod() /** * Lists the available databases for this connection. * - * @return array + * @return string[] */ public function listDatabases() { @@ -128,7 +104,7 @@ public function listDatabases() /** * Returns a list of all namespaces in the current database. * - * @return array + * @return string[] */ public function listNamespaceNames() { @@ -144,7 +120,7 @@ public function listNamespaceNames() * * @param string|null $database * - * @return \Doctrine\DBAL\Schema\Sequence[] + * @return Sequence[] */ public function listSequences($database = null) { @@ -171,11 +147,11 @@ public function listSequences($database = null) * @param string $table The name of the table. * @param string|null $database * - * @return \Doctrine\DBAL\Schema\Column[] + * @return Column[] */ public function listTableColumns($table, $database = null) { - if ( ! $database) { + if (! $database) { $database = $this->_conn->getDatabase(); } @@ -193,7 +169,7 @@ public function listTableColumns($table, $database = null) * * @param string $table The name of the table. * - * @return \Doctrine\DBAL\Schema\Index[] + * @return Index[] */ public function listTableIndexes($table) { @@ -207,7 +183,7 @@ public function listTableIndexes($table) /** * Returns true if all the given tables exist. * - * @param array $tableNames + * @param string[] $tableNames * * @return bool */ @@ -215,19 +191,19 @@ public function tablesExist($tableNames) { $tableNames = array_map('strtolower', (array) $tableNames); - return count($tableNames) == count(\array_intersect($tableNames, array_map('strtolower', $this->listTableNames()))); + return count($tableNames) === count(array_intersect($tableNames, array_map('strtolower', $this->listTableNames()))); } /** * Returns a list of all tables in the current database. * - * @return array + * @return string[] */ public function listTableNames() { $sql = $this->_platform->getListTablesSQL(); - $tables = $this->_conn->fetchAll($sql); + $tables = $this->_conn->fetchAll($sql); $tableNames = $this->_getPortableTablesList($tables); return $this->filterAssetNames($tableNames); @@ -237,27 +213,23 @@ public function listTableNames() * Filters asset names if they are configured to return only a subset of all * the found elements. * - * @param array $assetNames + * @param mixed[] $assetNames * - * @return array + * @return mixed[] */ protected function filterAssetNames($assetNames) { - $filterExpr = $this->getFilterSchemaAssetsExpression(); - if ( ! $filterExpr) { + $filter = $this->_conn->getConfiguration()->getSchemaAssetsFilter(); + if (! $filter) { return $assetNames; } - return array_values( - array_filter($assetNames, function ($assetName) use ($filterExpr) { - $assetName = ($assetName instanceof AbstractAsset) ? $assetName->getName() : $assetName; - - return preg_match($filterExpr, $assetName); - }) - ); + return array_values(array_filter($assetNames, $filter)); } /** + * @deprecated Use Configuration::getSchemaAssetsFilter() instead + * * @return string|null */ protected function getFilterSchemaAssetsExpression() @@ -268,7 +240,7 @@ protected function getFilterSchemaAssetsExpression() /** * Lists the tables for this connection. * - * @return \Doctrine\DBAL\Schema\Table[] + * @return Table[] */ public function listTables() { @@ -285,11 +257,11 @@ public function listTables() /** * @param string $tableName * - * @return \Doctrine\DBAL\Schema\Table + * @return Table */ public function listTableDetails($tableName) { - $columns = $this->listTableColumns($tableName); + $columns = $this->listTableColumns($tableName); $foreignKeys = []; if ($this->_platform->supportsForeignKeyConstraints()) { $foreignKeys = $this->listTableForeignKeys($tableName); @@ -302,13 +274,13 @@ public function listTableDetails($tableName) /** * Lists the views this connection has. * - * @return \Doctrine\DBAL\Schema\View[] + * @return View[] */ public function listViews() { $database = $this->_conn->getDatabase(); - $sql = $this->_platform->getListViewsSQL($database); - $views = $this->_conn->fetchAll($sql); + $sql = $this->_platform->getListViewsSQL($database); + $views = $this->_conn->fetchAll($sql); return $this->_getPortableViewsList($views); } @@ -319,14 +291,14 @@ public function listViews() * @param string $table The name of the table. * @param string|null $database * - * @return \Doctrine\DBAL\Schema\ForeignKeyConstraint[] + * @return ForeignKeyConstraint[] */ public function listTableForeignKeys($table, $database = null) { if ($database === null) { $database = $this->_conn->getDatabase(); } - $sql = $this->_platform->getListTableForeignKeysSQL($table, $database); + $sql = $this->_platform->getListTableForeignKeysSQL($table, $database); $tableForeignKeys = $this->_conn->fetchAll($sql); return $this->_getPortableTableForeignKeysList($tableForeignKeys); @@ -363,8 +335,8 @@ public function dropTable($tableName) /** * Drops the index from the given table. * - * @param \Doctrine\DBAL\Schema\Index|string $index The name of the index. - * @param \Doctrine\DBAL\Schema\Table|string $table The name of the table. + * @param Index|string $index The name of the index. + * @param Table|string $table The name of the table. * * @return void */ @@ -380,8 +352,7 @@ public function dropIndex($index, $table) /** * Drops the constraint from the given table. * - * @param \Doctrine\DBAL\Schema\Constraint $constraint - * @param \Doctrine\DBAL\Schema\Table|string $table The name of the table. + * @param Table|string $table The name of the table. * * @return void */ @@ -393,8 +364,8 @@ public function dropConstraint(Constraint $constraint, $table) /** * Drops a foreign key from a table. * - * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint|string $foreignKey The name of the foreign key. - * @param \Doctrine\DBAL\Schema\Table|string $table The name of the table with the foreign key. + * @param ForeignKeyConstraint|string $foreignKey The name of the foreign key. + * @param Table|string $table The name of the table with the foreign key. * * @return void */ @@ -444,8 +415,6 @@ public function createDatabase($database) /** * Creates a new table. * - * @param \Doctrine\DBAL\Schema\Table $table - * * @return void */ public function createTable(Table $table) @@ -457,11 +426,11 @@ public function createTable(Table $table) /** * Creates a new sequence. * - * @param \Doctrine\DBAL\Schema\Sequence $sequence + * @param Sequence $sequence * * @return void * - * @throws \Doctrine\DBAL\ConnectionException If something fails at database level. + * @throws ConnectionException If something fails at database level. */ public function createSequence($sequence) { @@ -471,8 +440,7 @@ public function createSequence($sequence) /** * Creates a constraint on a table. * - * @param \Doctrine\DBAL\Schema\Constraint $constraint - * @param \Doctrine\DBAL\Schema\Table|string $table + * @param Table|string $table * * @return void */ @@ -484,8 +452,7 @@ public function createConstraint(Constraint $constraint, $table) /** * Creates a new index on a table. * - * @param \Doctrine\DBAL\Schema\Index $index - * @param \Doctrine\DBAL\Schema\Table|string $table The name of the table on which the index is to be created. + * @param Table|string $table The name of the table on which the index is to be created. * * @return void */ @@ -497,8 +464,8 @@ public function createIndex(Index $index, $table) /** * Creates a new foreign key. * - * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey The ForeignKey instance. - * @param \Doctrine\DBAL\Schema\Table|string $table The name of the table on which the foreign key is to be created. + * @param ForeignKeyConstraint $foreignKey The ForeignKey instance. + * @param Table|string $table The name of the table on which the foreign key is to be created. * * @return void */ @@ -510,8 +477,6 @@ public function createForeignKey(ForeignKeyConstraint $foreignKey, $table) /** * Creates a new view. * - * @param \Doctrine\DBAL\Schema\View $view - * * @return void */ public function createView(View $view) @@ -527,8 +492,7 @@ public function createView(View $view) * @see dropConstraint() * @see createConstraint() * - * @param \Doctrine\DBAL\Schema\Constraint $constraint - * @param \Doctrine\DBAL\Schema\Table|string $table + * @param Table|string $table * * @return void */ @@ -541,8 +505,7 @@ public function dropAndCreateConstraint(Constraint $constraint, $table) /** * Drops and creates a new index on a table. * - * @param \Doctrine\DBAL\Schema\Index $index - * @param \Doctrine\DBAL\Schema\Table|string $table The name of the table on which the index is to be created. + * @param Table|string $table The name of the table on which the index is to be created. * * @return void */ @@ -555,8 +518,8 @@ public function dropAndCreateIndex(Index $index, $table) /** * Drops and creates a new foreign key. * - * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey An associative array that defines properties of the foreign key to be created. - * @param \Doctrine\DBAL\Schema\Table|string $table The name of the table on which the foreign key is to be created. + * @param ForeignKeyConstraint $foreignKey An associative array that defines properties of the foreign key to be created. + * @param Table|string $table The name of the table on which the foreign key is to be created. * * @return void */ @@ -569,11 +532,9 @@ public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table /** * Drops and create a new sequence. * - * @param \Doctrine\DBAL\Schema\Sequence $sequence - * * @return void * - * @throws \Doctrine\DBAL\ConnectionException If something fails at database level. + * @throws ConnectionException If something fails at database level. */ public function dropAndCreateSequence(Sequence $sequence) { @@ -584,8 +545,6 @@ public function dropAndCreateSequence(Sequence $sequence) /** * Drops and creates a new table. * - * @param \Doctrine\DBAL\Schema\Table $table - * * @return void */ public function dropAndCreateTable(Table $table) @@ -610,8 +569,6 @@ public function dropAndCreateDatabase($database) /** * Drops and creates a new view. * - * @param \Doctrine\DBAL\Schema\View $view - * * @return void */ public function dropAndCreateView(View $view) @@ -625,17 +582,17 @@ public function dropAndCreateView(View $view) /** * Alters an existing tables schema. * - * @param \Doctrine\DBAL\Schema\TableDiff $tableDiff - * * @return void */ public function alterTable(TableDiff $tableDiff) { $queries = $this->_platform->getAlterTableSQL($tableDiff); - if (is_array($queries) && count($queries)) { - foreach ($queries as $ddlQuery) { - $this->_execSql($ddlQuery); - } + if (! is_array($queries) || ! count($queries)) { + return; + } + + foreach ($queries as $ddlQuery) { + $this->_execSql($ddlQuery); } } @@ -649,7 +606,7 @@ public function alterTable(TableDiff $tableDiff) */ public function renameTable($name, $newName) { - $tableDiff = new TableDiff($name); + $tableDiff = new TableDiff($name); $tableDiff->newName = $newName; $this->alterTable($tableDiff); } @@ -660,17 +617,21 @@ public function renameTable($name, $newName) */ /** - * @param array $databases + * @param mixed[] $databases * - * @return array + * @return string[] */ protected function _getPortableDatabasesList($databases) { $list = []; foreach ($databases as $value) { - if ($value = $this->_getPortableDatabaseDefinition($value)) { - $list[] = $value; + $value = $this->_getPortableDatabaseDefinition($value); + + if (! $value) { + continue; } + + $list[] = $value; } return $list; @@ -679,9 +640,9 @@ protected function _getPortableDatabasesList($databases) /** * Converts a list of namespace names from the native DBMS data definition to a portable Doctrine definition. * - * @param array $namespaces The list of namespace names in the native DBMS data definition. + * @param mixed[][] $namespaces The list of namespace names in the native DBMS data definition. * - * @return array + * @return string[] */ protected function getPortableNamespacesList(array $namespaces) { @@ -695,7 +656,7 @@ protected function getPortableNamespacesList(array $namespaces) } /** - * @param array $database + * @param mixed $database * * @return mixed */ @@ -707,7 +668,7 @@ protected function _getPortableDatabaseDefinition($database) /** * Converts a namespace definition from the native DBMS data definition to a portable Doctrine definition. * - * @param array $namespace The native DBMS namespace definition. + * @param mixed[] $namespace The native DBMS namespace definition. * * @return mixed */ @@ -717,24 +678,28 @@ protected function getPortableNamespaceDefinition(array $namespace) } /** - * @param array $functions + * @param mixed[][] $functions * - * @return array + * @return mixed[][] */ protected function _getPortableFunctionsList($functions) { $list = []; foreach ($functions as $value) { - if ($value = $this->_getPortableFunctionDefinition($value)) { - $list[] = $value; + $value = $this->_getPortableFunctionDefinition($value); + + if (! $value) { + continue; } + + $list[] = $value; } return $list; } /** - * @param array $function + * @param mixed[] $function * * @return mixed */ @@ -744,24 +709,28 @@ protected function _getPortableFunctionDefinition($function) } /** - * @param array $triggers + * @param mixed[][] $triggers * - * @return array + * @return mixed[][] */ protected function _getPortableTriggersList($triggers) { $list = []; foreach ($triggers as $value) { - if ($value = $this->_getPortableTriggerDefinition($value)) { - $list[] = $value; + $value = $this->_getPortableTriggerDefinition($value); + + if (! $value) { + continue; } + + $list[] = $value; } return $list; } /** - * @param array $trigger + * @param mixed[] $trigger * * @return mixed */ @@ -771,28 +740,32 @@ protected function _getPortableTriggerDefinition($trigger) } /** - * @param array $sequences + * @param mixed[][] $sequences * - * @return array + * @return Sequence[] */ protected function _getPortableSequencesList($sequences) { $list = []; foreach ($sequences as $value) { - if ($value = $this->_getPortableSequenceDefinition($value)) { - $list[] = $value; + $value = $this->_getPortableSequenceDefinition($value); + + if (! $value) { + continue; } + + $list[] = $value; } return $list; } /** - * @param array $sequence + * @param mixed[] $sequence * - * @return \Doctrine\DBAL\Schema\Sequence + * @return Sequence * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ protected function _getPortableSequenceDefinition($sequence) { @@ -804,11 +777,11 @@ protected function _getPortableSequenceDefinition($sequence) * * The name of the created column instance however is kept in its case. * - * @param string $table The name of the table. - * @param string $database - * @param array $tableColumns + * @param string $table The name of the table. + * @param string $database + * @param mixed[][] $tableColumns * - * @return array + * @return Column[] */ protected function _getPortableTableColumnList($table, $database, $tableColumns) { @@ -816,25 +789,27 @@ protected function _getPortableTableColumnList($table, $database, $tableColumns) $list = []; foreach ($tableColumns as $tableColumn) { - $column = null; + $column = null; $defaultPrevented = false; - if (null !== $eventManager && $eventManager->hasListeners(Events::onSchemaColumnDefinition)) { + if ($eventManager !== null && $eventManager->hasListeners(Events::onSchemaColumnDefinition)) { $eventArgs = new SchemaColumnDefinitionEventArgs($tableColumn, $table, $database, $this->_conn); $eventManager->dispatchEvent(Events::onSchemaColumnDefinition, $eventArgs); $defaultPrevented = $eventArgs->isDefaultPrevented(); - $column = $eventArgs->getColumn(); + $column = $eventArgs->getColumn(); } - if ( ! $defaultPrevented) { + if (! $defaultPrevented) { $column = $this->_getPortableTableColumnDefinition($tableColumn); } - if ($column) { - $name = strtolower($column->getQuotedName($this->_platform)); - $list[$name] = $column; + if (! $column) { + continue; } + + $name = strtolower($column->getQuotedName($this->_platform)); + $list[$name] = $column; } return $list; @@ -843,21 +818,21 @@ protected function _getPortableTableColumnList($table, $database, $tableColumns) /** * Gets Table Column Definition. * - * @param array $tableColumn + * @param mixed[] $tableColumn * - * @return \Doctrine\DBAL\Schema\Column + * @return Column */ abstract protected function _getPortableTableColumnDefinition($tableColumn); /** * Aggregates and groups the index results according to the required data result. * - * @param array $tableIndexRows + * @param mixed[][] $tableIndexRows * @param string|null $tableName * - * @return array + * @return Index[] */ - protected function _getPortableTableIndexesList($tableIndexRows, $tableName=null) + protected function _getPortableTableIndexesList($tableIndexRows, $tableName = null) { $result = []; foreach ($tableIndexRows as $tableIndex) { @@ -867,68 +842,83 @@ protected function _getPortableTableIndexesList($tableIndexRows, $tableName=null } $keyName = strtolower($keyName); - if (!isset($result[$keyName])) { + if (! isset($result[$keyName])) { + $options = [ + 'lengths' => [], + ]; + + if (isset($tableIndex['where'])) { + $options['where'] = $tableIndex['where']; + } + $result[$keyName] = [ 'name' => $indexName, - 'columns' => [$tableIndex['column_name']], + 'columns' => [], 'unique' => $tableIndex['non_unique'] ? false : true, 'primary' => $tableIndex['primary'], 'flags' => $tableIndex['flags'] ?? [], - 'options' => isset($tableIndex['where']) ? ['where' => $tableIndex['where']] : [], + 'options' => $options, ]; - } else { - $result[$keyName]['columns'][] = $tableIndex['column_name']; } + + $result[$keyName]['columns'][] = $tableIndex['column_name']; + $result[$keyName]['options']['lengths'][] = $tableIndex['length'] ?? null; } $eventManager = $this->_platform->getEventManager(); $indexes = []; foreach ($result as $indexKey => $data) { - $index = null; + $index = null; $defaultPrevented = false; - if (null !== $eventManager && $eventManager->hasListeners(Events::onSchemaIndexDefinition)) { + if ($eventManager !== null && $eventManager->hasListeners(Events::onSchemaIndexDefinition)) { $eventArgs = new SchemaIndexDefinitionEventArgs($data, $tableName, $this->_conn); $eventManager->dispatchEvent(Events::onSchemaIndexDefinition, $eventArgs); $defaultPrevented = $eventArgs->isDefaultPrevented(); - $index = $eventArgs->getIndex(); + $index = $eventArgs->getIndex(); } - if ( ! $defaultPrevented) { + if (! $defaultPrevented) { $index = new Index($data['name'], $data['columns'], $data['unique'], $data['primary'], $data['flags'], $data['options']); } - if ($index) { - $indexes[$indexKey] = $index; + if (! $index) { + continue; } + + $indexes[$indexKey] = $index; } return $indexes; } /** - * @param array $tables + * @param mixed[][] $tables * - * @return array + * @return string[] */ protected function _getPortableTablesList($tables) { $list = []; foreach ($tables as $value) { - if ($value = $this->_getPortableTableDefinition($value)) { - $list[] = $value; + $value = $this->_getPortableTableDefinition($value); + + if (! $value) { + continue; } + + $list[] = $value; } return $list; } /** - * @param array $table + * @param mixed $table * - * @return array + * @return string */ protected function _getPortableTableDefinition($table) { @@ -936,26 +926,30 @@ protected function _getPortableTableDefinition($table) } /** - * @param array $users + * @param mixed[][] $users * - * @return array + * @return string[][] */ protected function _getPortableUsersList($users) { $list = []; foreach ($users as $value) { - if ($value = $this->_getPortableUserDefinition($value)) { - $list[] = $value; + $value = $this->_getPortableUserDefinition($value); + + if (! $value) { + continue; } + + $list[] = $value; } return $list; } /** - * @param array $user + * @param mixed[] $user * - * @return mixed + * @return mixed[] */ protected function _getPortableUserDefinition($user) { @@ -963,27 +957,31 @@ protected function _getPortableUserDefinition($user) } /** - * @param array $views + * @param mixed[][] $views * - * @return array + * @return View[] */ protected function _getPortableViewsList($views) { $list = []; foreach ($views as $value) { - if ($view = $this->_getPortableViewDefinition($value)) { - $viewName = strtolower($view->getQuotedName($this->_platform)); - $list[$viewName] = $view; + $view = $this->_getPortableViewDefinition($value); + + if (! $view) { + continue; } + + $viewName = strtolower($view->getQuotedName($this->_platform)); + $list[$viewName] = $view; } return $list; } /** - * @param array $view + * @param mixed[] $view * - * @return mixed + * @return View|false */ protected function _getPortableViewDefinition($view) { @@ -991,26 +989,30 @@ protected function _getPortableViewDefinition($view) } /** - * @param array $tableForeignKeys + * @param mixed[][] $tableForeignKeys * - * @return array + * @return ForeignKeyConstraint[] */ protected function _getPortableTableForeignKeysList($tableForeignKeys) { $list = []; foreach ($tableForeignKeys as $value) { - if ($value = $this->_getPortableTableForeignKeyDefinition($value)) { - $list[] = $value; + $value = $this->_getPortableTableForeignKeyDefinition($value); + + if (! $value) { + continue; } + + $list[] = $value; } return $list; } /** - * @param array $tableForeignKey + * @param mixed $tableForeignKey * - * @return mixed + * @return ForeignKeyConstraint */ protected function _getPortableTableForeignKeyDefinition($tableForeignKey) { @@ -1018,7 +1020,7 @@ protected function _getPortableTableForeignKeyDefinition($tableForeignKey) } /** - * @param array|string $sql + * @param string[]|string $sql * * @return void */ @@ -1032,7 +1034,7 @@ protected function _execSql($sql) /** * Creates a schema instance for the current database. * - * @return \Doctrine\DBAL\Schema\Schema + * @return Schema */ public function createSchema() { @@ -1056,7 +1058,7 @@ public function createSchema() /** * Creates the configuration for this schema. * - * @return \Doctrine\DBAL\Schema\SchemaConfig + * @return SchemaConfig */ public function createSchemaConfig() { @@ -1090,7 +1092,7 @@ public function createSchemaConfig() * For databases that don't support subschema/namespaces this method * returns the name of the currently connected database. * - * @return array + * @return string[] */ public function getSchemaSearchPaths() { @@ -1108,7 +1110,7 @@ public function getSchemaSearchPaths() */ public function extractDoctrineTypeFromComment($comment, $currentType) { - if (preg_match("(\(DC2Type:(((?!\)).)+)\))", $comment, $match)) { + if (preg_match('(\(DC2Type:(((?!\)).)+)\))', $comment, $match)) { $currentType = $match[1]; } @@ -1123,6 +1125,6 @@ public function extractDoctrineTypeFromComment($comment, $currentType) */ public function removeDoctrineTypeFromComment($comment, $type) { - return str_replace('(DC2Type:'.$type.')', '', $comment); + return str_replace('(DC2Type:' . $type . ')', '', $comment); } } diff --git a/lib/Doctrine/DBAL/Schema/Column.php b/lib/Doctrine/DBAL/Schema/Column.php index eead5e6aa82..aef471e06fe 100644 --- a/lib/Doctrine/DBAL/Schema/Column.php +++ b/lib/Doctrine/DBAL/Schema/Column.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Schema; @@ -29,86 +12,55 @@ /** * Object representation of a database column. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ class Column extends AbstractAsset { - /** - * @var Type - */ + /** @var Type */ protected $_type; - /** - * @var int|null - */ + /** @var int|null */ protected $_length = null; - /** - * @var int - */ + /** @var int */ protected $_precision = 10; - /** - * @var int - */ + /** @var int */ protected $_scale = 0; - /** - * @var bool - */ + /** @var bool */ protected $_unsigned = false; - /** - * @var bool - */ + /** @var bool */ protected $_fixed = false; - /** - * @var bool - */ + /** @var bool */ protected $_notnull = true; - /** - * @var string|null - */ + /** @var string|null */ protected $_default = null; - /** - * @var bool - */ + /** @var bool */ protected $_autoincrement = false; - /** - * @var array - */ + /** @var mixed[] */ protected $_platformOptions = []; - /** - * @var string|null - */ + /** @var string|null */ protected $_columnDefinition = null; - /** - * @var string|null - */ + /** @var string|null */ protected $_comment = null; - /** - * @var array - */ + /** @var mixed[] */ protected $_customSchemaOptions = []; /** * Creates a new Column. * - * @param string $columnName - * @param Type $type - * @param array $options + * @param string $columnName + * @param mixed[] $options */ - public function __construct($columnName, Type $type, array $options=[]) + public function __construct($columnName, Type $type, array $options = []) { $this->_setName($columnName); $this->setType($type); @@ -116,18 +68,18 @@ public function __construct($columnName, Type $type, array $options=[]) } /** - * @param array $options + * @param mixed[] $options * * @return Column */ public function setOptions(array $options) { foreach ($options as $name => $value) { - $method = "set".$name; - if ( ! method_exists($this, $method)) { + $method = 'set' . $name; + if (! method_exists($this, $method)) { // next major: throw an exception @trigger_error(sprintf( - 'The "%s" column option is not supported,'. + 'The "%s" column option is not supported,' . ' setting it is deprecated and will cause an error in Doctrine 3.0', $name ), E_USER_DEPRECATED); @@ -141,8 +93,6 @@ public function setOptions(array $options) } /** - * @param Type $type - * * @return Column */ public function setType(Type $type) @@ -175,7 +125,7 @@ public function setLength($length) */ public function setPrecision($precision) { - if (!is_numeric($precision)) { + if (! is_numeric($precision)) { $precision = 10; // defaults to 10 when no valid precision is given. } @@ -191,7 +141,7 @@ public function setPrecision($precision) */ public function setScale($scale) { - if (!is_numeric($scale)) { + if (! is_numeric($scale)) { $scale = 0; } @@ -249,7 +199,7 @@ public function setDefault($default) } /** - * @param array $platformOptions + * @param mixed[] $platformOptions * * @return Column */ @@ -350,7 +300,7 @@ public function getDefault() } /** - * @return array + * @return mixed[] */ public function getPlatformOptions() { @@ -459,7 +409,7 @@ public function getCustomSchemaOption($name) } /** - * @param array $customSchemaOptions + * @param mixed[] $customSchemaOptions * * @return Column */ @@ -471,7 +421,7 @@ public function setCustomSchemaOptions(array $customSchemaOptions) } /** - * @return array + * @return mixed[] */ public function getCustomSchemaOptions() { @@ -479,7 +429,7 @@ public function getCustomSchemaOptions() } /** - * @return array + * @return mixed[] */ public function toArray() { diff --git a/lib/Doctrine/DBAL/Schema/ColumnDiff.php b/lib/Doctrine/DBAL/Schema/ColumnDiff.php index 65517d75cb5..cb64592109b 100644 --- a/lib/Doctrine/DBAL/Schema/ColumnDiff.php +++ b/lib/Doctrine/DBAL/Schema/ColumnDiff.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Schema; @@ -23,45 +6,31 @@ /** * Represents the change of a column. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ class ColumnDiff { - /** - * @var string - */ + /** @var string */ public $oldColumnName; - /** - * @var Column - */ + /** @var Column */ public $column; - /** - * @var array - */ + /** @var string[] */ public $changedProperties = []; - /** - * @var Column - */ + /** @var Column */ public $fromColumn; /** * @param string $oldColumnName - * @param Column $column * @param string[] $changedProperties - * @param Column $fromColumn */ - public function __construct($oldColumnName, Column $column, array $changedProperties = [], Column $fromColumn = null) + public function __construct($oldColumnName, Column $column, array $changedProperties = [], ?Column $fromColumn = null) { - $this->oldColumnName = $oldColumnName; - $this->column = $column; + $this->oldColumnName = $oldColumnName; + $this->column = $column; $this->changedProperties = $changedProperties; - $this->fromColumn = $fromColumn; + $this->fromColumn = $fromColumn; } /** diff --git a/lib/Doctrine/DBAL/Schema/Comparator.php b/lib/Doctrine/DBAL/Schema/Comparator.php index 63389cd42d0..3b5a0b155d0 100644 --- a/lib/Doctrine/DBAL/Schema/Comparator.php +++ b/lib/Doctrine/DBAL/Schema/Comparator.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Schema; @@ -32,18 +15,11 @@ /** * Compares two Schemas and return an instance of SchemaDiff. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ class Comparator { /** - * @param \Doctrine\DBAL\Schema\Schema $fromSchema - * @param \Doctrine\DBAL\Schema\Schema $toSchema - * - * @return \Doctrine\DBAL\Schema\SchemaDiff + * @return SchemaDiff */ public static function compareSchemas(Schema $fromSchema, Schema $toSchema) { @@ -59,33 +35,34 @@ public static function compareSchemas(Schema $fromSchema, Schema $toSchema) * operations to change the schema stored in $fromSchema to the schema that is * stored in $toSchema. * - * @param \Doctrine\DBAL\Schema\Schema $fromSchema - * @param \Doctrine\DBAL\Schema\Schema $toSchema - * - * @return \Doctrine\DBAL\Schema\SchemaDiff + * @return SchemaDiff */ public function compare(Schema $fromSchema, Schema $toSchema) { - $diff = new SchemaDiff(); + $diff = new SchemaDiff(); $diff->fromSchema = $fromSchema; $foreignKeysToTable = []; foreach ($toSchema->getNamespaces() as $namespace) { - if ( ! $fromSchema->hasNamespace($namespace)) { - $diff->newNamespaces[$namespace] = $namespace; + if ($fromSchema->hasNamespace($namespace)) { + continue; } + + $diff->newNamespaces[$namespace] = $namespace; } foreach ($fromSchema->getNamespaces() as $namespace) { - if ( ! $toSchema->hasNamespace($namespace)) { - $diff->removedNamespaces[$namespace] = $namespace; + if ($toSchema->hasNamespace($namespace)) { + continue; } + + $diff->removedNamespaces[$namespace] = $namespace; } foreach ($toSchema->getTables() as $table) { $tableName = $table->getShortestName($toSchema->getName()); - if ( ! $fromSchema->hasTable($tableName)) { + if (! $fromSchema->hasTable($tableName)) { $diff->newTables[$tableName] = $toSchema->getTable($tableName); } else { $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName)); @@ -100,14 +77,14 @@ public function compare(Schema $fromSchema, Schema $toSchema) $tableName = $table->getShortestName($fromSchema->getName()); $table = $fromSchema->getTable($tableName); - if ( ! $toSchema->hasTable($tableName)) { + if (! $toSchema->hasTable($tableName)) { $diff->removedTables[$tableName] = $table; } // also remember all foreign keys that point to a specific table foreach ($table->getForeignKeys() as $foreignKey) { $foreignTable = strtolower($foreignKey->getForeignTableName()); - if (!isset($foreignKeysToTable[$foreignTable])) { + if (! isset($foreignKeysToTable[$foreignTable])) { $foreignKeysToTable[$foreignTable] = []; } $foreignKeysToTable[$foreignTable][] = $foreignKey; @@ -115,31 +92,35 @@ public function compare(Schema $fromSchema, Schema $toSchema) } foreach ($diff->removedTables as $tableName => $table) { - if (isset($foreignKeysToTable[$tableName])) { - $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]); - - // deleting duplicated foreign keys present on both on the orphanedForeignKey - // and the removedForeignKeys from changedTables - foreach ($foreignKeysToTable[$tableName] as $foreignKey) { - // strtolower the table name to make if compatible with getShortestName - $localTableName = strtolower($foreignKey->getLocalTableName()); - if (isset($diff->changedTables[$localTableName])) { - foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) { - // We check if the key is from the removed table if not we skip. - if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) { - continue; - } - unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]); - } + if (! isset($foreignKeysToTable[$tableName])) { + continue; + } + + $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]); + + // deleting duplicated foreign keys present on both on the orphanedForeignKey + // and the removedForeignKeys from changedTables + foreach ($foreignKeysToTable[$tableName] as $foreignKey) { + // strtolower the table name to make if compatible with getShortestName + $localTableName = strtolower($foreignKey->getLocalTableName()); + if (! isset($diff->changedTables[$localTableName])) { + continue; + } + + foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) { + // We check if the key is from the removed table if not we skip. + if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) { + continue; } + unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]); } } } foreach ($toSchema->getSequences() as $sequence) { $sequenceName = $sequence->getShortestName($toSchema->getName()); - if ( ! $fromSchema->hasSequence($sequenceName)) { - if ( ! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) { + if (! $fromSchema->hasSequence($sequenceName)) { + if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) { $diff->newSequences[] = $sequence; } } else { @@ -156,17 +137,19 @@ public function compare(Schema $fromSchema, Schema $toSchema) $sequenceName = $sequence->getShortestName($fromSchema->getName()); - if ( ! $toSchema->hasSequence($sequenceName)) { - $diff->removedSequences[] = $sequence; + if ($toSchema->hasSequence($sequenceName)) { + continue; } + + $diff->removedSequences[] = $sequence; } return $diff; } /** - * @param \Doctrine\DBAL\Schema\Schema $schema - * @param \Doctrine\DBAL\Schema\Sequence $sequence + * @param Schema $schema + * @param Sequence $sequence * * @return bool */ @@ -182,14 +165,11 @@ private function isAutoIncrementSequenceInSchema($schema, $sequence) } /** - * @param \Doctrine\DBAL\Schema\Sequence $sequence1 - * @param \Doctrine\DBAL\Schema\Sequence $sequence2 - * * @return bool */ public function diffSequence(Sequence $sequence1, Sequence $sequence2) { - if ($sequence1->getAllocationSize() != $sequence2->getAllocationSize()) { + if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) { return true; } @@ -201,15 +181,12 @@ public function diffSequence(Sequence $sequence1, Sequence $sequence2) * * If there are no differences this method returns the boolean false. * - * @param \Doctrine\DBAL\Schema\Table $table1 - * @param \Doctrine\DBAL\Schema\Table $table2 - * * @return TableDiff|false */ public function diffTable(Table $table1, Table $table2) { - $changes = 0; - $tableDifferences = new TableDiff($table1->getName()); + $changes = 0; + $tableDifferences = new TableDiff($table1->getName()); $tableDifferences->fromTable = $table1; $table1Columns = $table1->getColumns(); @@ -217,15 +194,17 @@ public function diffTable(Table $table1, Table $table2) /* See if all the fields in table 1 exist in table 2 */ foreach ($table2Columns as $columnName => $column) { - if ( !$table1->hasColumn($columnName)) { - $tableDifferences->addedColumns[$columnName] = $column; - $changes++; + if ($table1->hasColumn($columnName)) { + continue; } + + $tableDifferences->addedColumns[$columnName] = $column; + $changes++; } /* See if there are any removed fields in table 2 */ foreach ($table1Columns as $columnName => $column) { // See if column is removed in table 2. - if ( ! $table2->hasColumn($columnName)) { + if (! $table2->hasColumn($columnName)) { $tableDifferences->removedColumns[$columnName] = $column; $changes++; continue; @@ -234,12 +213,14 @@ public function diffTable(Table $table1, Table $table2) // See if column has changed properties in table 2. $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName)); - if ( ! empty($changedProperties)) { - $columnDiff = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties); - $columnDiff->fromColumn = $column; - $tableDifferences->changedColumns[$column->getName()] = $columnDiff; - $changes++; + if (empty($changedProperties)) { + continue; } + + $columnDiff = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties); + $columnDiff->fromColumn = $column; + $tableDifferences->changedColumns[$column->getName()] = $columnDiff; + $changes++; } $this->detectColumnRenamings($tableDifferences); @@ -270,23 +251,25 @@ public function diffTable(Table $table1, Table $table2) // See if index has changed in table 2. $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName); - if ($this->diffIndex($index, $table2Index)) { - $tableDifferences->changedIndexes[$indexName] = $table2Index; - $changes++; + if (! $this->diffIndex($index, $table2Index)) { + continue; } + + $tableDifferences->changedIndexes[$indexName] = $table2Index; + $changes++; } $this->detectIndexRenamings($tableDifferences); $fromFkeys = $table1->getForeignKeys(); - $toFkeys = $table2->getForeignKeys(); + $toFkeys = $table2->getForeignKeys(); foreach ($fromFkeys as $key1 => $constraint1) { foreach ($toFkeys as $key2 => $constraint2) { if ($this->diffForeignKey($constraint1, $constraint2) === false) { unset($fromFkeys[$key1], $toFkeys[$key2]); } else { - if (strtolower($constraint1->getName()) == strtolower($constraint2->getName())) { + if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) { $tableDifferences->changedForeignKeys[] = $constraint2; $changes++; unset($fromFkeys[$key1], $toFkeys[$key2]); @@ -319,26 +302,32 @@ private function detectColumnRenamings(TableDiff $tableDifferences) $renameCandidates = []; foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) { foreach ($tableDifferences->removedColumns as $removedColumn) { - if (count($this->diffColumn($addedColumn, $removedColumn)) == 0) { - $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName]; + if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) { + continue; } + + $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName]; } } foreach ($renameCandidates as $candidateColumns) { - if (count($candidateColumns) == 1) { - list($removedColumn, $addedColumn) = $candidateColumns[0]; - $removedColumnName = strtolower($removedColumn->getName()); - $addedColumnName = strtolower($addedColumn->getName()); - - if ( ! isset($tableDifferences->renamedColumns[$removedColumnName])) { - $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn; - unset( - $tableDifferences->addedColumns[$addedColumnName], - $tableDifferences->removedColumns[$removedColumnName] - ); - } + if (count($candidateColumns) !== 1) { + continue; + } + + [$removedColumn, $addedColumn] = $candidateColumns[0]; + $removedColumnName = strtolower($removedColumn->getName()); + $addedColumnName = strtolower($addedColumn->getName()); + + if (isset($tableDifferences->renamedColumns[$removedColumnName])) { + continue; } + + $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn; + unset( + $tableDifferences->addedColumns[$addedColumnName], + $tableDifferences->removedColumns[$removedColumnName] + ); } } @@ -355,9 +344,11 @@ private function detectIndexRenamings(TableDiff $tableDifferences) // Gather possible rename candidates by comparing each added and removed index based on semantics. foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) { foreach ($tableDifferences->removedIndexes as $removedIndex) { - if (! $this->diffIndex($addedIndex, $removedIndex)) { - $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName]; + if ($this->diffIndex($addedIndex, $removedIndex)) { + continue; } + + $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName]; } } @@ -366,36 +357,37 @@ private function detectIndexRenamings(TableDiff $tableDifferences) // we can safely rename it. // Otherwise it is unclear if a rename action is really intended, // therefore we let those ambiguous indexes be added/dropped. - if (count($candidateIndexes) === 1) { - list($removedIndex, $addedIndex) = $candidateIndexes[0]; - - $removedIndexName = strtolower($removedIndex->getName()); - $addedIndexName = strtolower($addedIndex->getName()); - - if (! isset($tableDifferences->renamedIndexes[$removedIndexName])) { - $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex; - unset( - $tableDifferences->addedIndexes[$addedIndexName], - $tableDifferences->removedIndexes[$removedIndexName] - ); - } + if (count($candidateIndexes) !== 1) { + continue; } + + [$removedIndex, $addedIndex] = $candidateIndexes[0]; + + $removedIndexName = strtolower($removedIndex->getName()); + $addedIndexName = strtolower($addedIndex->getName()); + + if (isset($tableDifferences->renamedIndexes[$removedIndexName])) { + continue; + } + + $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex; + unset( + $tableDifferences->addedIndexes[$addedIndexName], + $tableDifferences->removedIndexes[$removedIndexName] + ); } } /** - * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key1 - * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key2 - * * @return bool */ public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2) { - if (array_map('strtolower', $key1->getUnquotedLocalColumns()) != array_map('strtolower', $key2->getUnquotedLocalColumns())) { + if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) { return true; } - if (array_map('strtolower', $key1->getUnquotedForeignColumns()) != array_map('strtolower', $key2->getUnquotedForeignColumns())) { + if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) { return true; } @@ -403,7 +395,7 @@ public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint return true; } - if ($key1->onUpdate() != $key2->onUpdate()) { + if ($key1->onUpdate() !== $key2->onUpdate()) { return true; } @@ -416,10 +408,7 @@ public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint * If there are differences this method returns $field2, otherwise the * boolean false. * - * @param \Doctrine\DBAL\Schema\Column $column1 - * @param \Doctrine\DBAL\Schema\Column $column2 - * - * @return array + * @return string[] */ public function diffColumn(Column $column1, Column $column2) { @@ -429,9 +418,11 @@ public function diffColumn(Column $column1, Column $column2) $changedProperties = []; foreach (['type', 'notnull', 'unsigned', 'autoincrement'] as $property) { - if ($properties1[$property] != $properties2[$property]) { - $changedProperties[] = $property; + if ($properties1[$property] === $properties2[$property]) { + continue; } + + $changedProperties[] = $property; } // This is a very nasty hack to make comparator work with the legacy json_array type, which should be killed in v3 @@ -441,12 +432,10 @@ public function diffColumn(Column $column1, Column $column2) $changedProperties[] = 'comment'; } - if ($properties1['default'] != $properties2['default'] || - // Null values need to be checked additionally as they tell whether to create or drop a default value. - // null != 0, null != false, null != '' etc. This affects platform's table alteration SQL generation. - (null === $properties1['default'] && null !== $properties2['default']) || - (null === $properties2['default'] && null !== $properties1['default']) - ) { + // Null values need to be checked additionally as they tell whether to create or drop a default value. + // null != 0, null != false, null != '' etc. This affects platform's table alteration SQL generation. + if (($properties1['default'] === null) !== ($properties2['default'] === null) + || (string) $properties1['default'] !== (string) $properties2['default']) { $changedProperties[] = 'default'; } @@ -456,26 +445,26 @@ public function diffColumn(Column $column1, Column $column2) // check if value of length is set at all, default value assumed otherwise. $length1 = $properties1['length'] ?: 255; $length2 = $properties2['length'] ?: 255; - if ($length1 != $length2) { + if ($length1 !== $length2) { $changedProperties[] = 'length'; } - if ($properties1['fixed'] != $properties2['fixed']) { + if ($properties1['fixed'] !== $properties2['fixed']) { $changedProperties[] = 'fixed'; } } elseif ($properties1['type'] instanceof Types\DecimalType) { - if (($properties1['precision'] ?: 10) != ($properties2['precision'] ?: 10)) { + if (($properties1['precision'] ?: 10) !== ($properties2['precision'] ?: 10)) { $changedProperties[] = 'precision'; } - if ($properties1['scale'] != $properties2['scale']) { + if ($properties1['scale'] !== $properties2['scale']) { $changedProperties[] = 'scale'; } } // A null value and an empty string are actually equal for a comment so they should not trigger a change. if ($properties1['comment'] !== $properties2['comment'] && - ! (null === $properties1['comment'] && '' === $properties2['comment']) && - ! (null === $properties2['comment'] && '' === $properties1['comment']) + ! ($properties1['comment'] === null && $properties2['comment'] === '') && + ! ($properties2['comment'] === null && $properties1['comment'] === '') ) { $changedProperties[] = 'comment'; } @@ -484,7 +473,7 @@ public function diffColumn(Column $column1, Column $column2) $customOptions2 = $column2->getCustomSchemaOptions(); foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) { - if ( ! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) { + if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) { $changedProperties[] = $key; } elseif ($properties1[$key] !== $properties2[$key]) { $changedProperties[] = $key; @@ -495,9 +484,11 @@ public function diffColumn(Column $column1, Column $column2) $platformOptions2 = $column2->getPlatformOptions(); foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) { - if ($properties1[$key] !== $properties2[$key]) { - $changedProperties[] = $key; + if ($properties1[$key] === $properties2[$key]) { + continue; } + + $changedProperties[] = $key; } return array_unique($changedProperties); @@ -510,7 +501,7 @@ public function diffColumn(Column $column1, Column $column2) */ private function isALegacyJsonComparison(Types\Type $one, Types\Type $other) : bool { - if ( ! $one instanceof Types\JsonType || ! $other instanceof Types\JsonType) { + if (! $one instanceof Types\JsonType || ! $other instanceof Types\JsonType) { return false; } @@ -524,9 +515,6 @@ private function isALegacyJsonComparison(Types\Type $one, Types\Type $other) : b * Compares $index1 with $index2 and returns $index2 if there are any * differences or false in case there are no differences. * - * @param \Doctrine\DBAL\Schema\Index $index1 - * @param \Doctrine\DBAL\Schema\Index $index2 - * * @return bool */ public function diffIndex(Index $index1, Index $index2) diff --git a/lib/Doctrine/DBAL/Schema/Constraint.php b/lib/Doctrine/DBAL/Schema/Constraint.php index 2e68a771019..65e239ec119 100644 --- a/lib/Doctrine/DBAL/Schema/Constraint.php +++ b/lib/Doctrine/DBAL/Schema/Constraint.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Schema; @@ -23,10 +6,6 @@ /** * Marker interface for constraints. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ interface Constraint { @@ -36,8 +15,6 @@ interface Constraint public function getName(); /** - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - * * @return string */ public function getQuotedName(AbstractPlatform $platform); @@ -46,7 +23,7 @@ public function getQuotedName(AbstractPlatform $platform); * Returns the names of the referencing table columns * the constraint is associated with. * - * @return array + * @return string[] */ public function getColumns(); @@ -58,9 +35,9 @@ public function getColumns(); * is a keyword reserved by the platform. * Otherwise the plain unquoted value as inserted is returned. * - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform The platform to use for quotation. + * @param AbstractPlatform $platform The platform to use for quotation. * - * @return array + * @return string[] */ public function getQuotedColumns(AbstractPlatform $platform); } diff --git a/lib/Doctrine/DBAL/Schema/DB2SchemaManager.php b/lib/Doctrine/DBAL/Schema/DB2SchemaManager.php index c97685b5d0e..f5e225512ab 100644 --- a/lib/Doctrine/DBAL/Schema/DB2SchemaManager.php +++ b/lib/Doctrine/DBAL/Schema/DB2SchemaManager.php @@ -1,24 +1,9 @@ . - */ namespace Doctrine\DBAL\Schema; +use Doctrine\DBAL\Types\Type; +use const CASE_LOWER; use function array_change_key_case; use function is_resource; use function strpos; @@ -28,10 +13,6 @@ /** * IBM Db2 Schema Manager. - * - * @link www.doctrine-project.org - * @since 1.0 - * @author Benjamin Eberlei */ class DB2SchemaManager extends AbstractSchemaManager { @@ -43,8 +24,8 @@ class DB2SchemaManager extends AbstractSchemaManager */ public function listTableNames() { - $sql = $this->_platform->getListTablesSQL(); - $sql .= " AND CREATOR = UPPER('".$this->_conn->getUsername()."')"; + $sql = $this->_platform->getListTablesSQL(); + $sql .= ' AND CREATOR = UPPER(' . $this->_conn->quote($this->_conn->getUsername()) . ')'; $tables = $this->_conn->fetchAll($sql); @@ -56,35 +37,35 @@ public function listTableNames() */ protected function _getPortableTableColumnDefinition($tableColumn) { - $tableColumn = array_change_key_case($tableColumn, \CASE_LOWER); + $tableColumn = array_change_key_case($tableColumn, CASE_LOWER); - $length = null; - $fixed = null; - $unsigned = false; - $scale = false; + $length = null; + $fixed = null; + $unsigned = false; + $scale = false; $precision = false; $default = null; - if (null !== $tableColumn['default'] && 'NULL' != $tableColumn['default']) { + if ($tableColumn['default'] !== null && $tableColumn['default'] !== 'NULL') { $default = trim($tableColumn['default'], "'"); } $type = $this->_platform->getDoctrineTypeMapping($tableColumn['typename']); if (isset($tableColumn['comment'])) { - $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type); + $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type); $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type); } switch (strtolower($tableColumn['typename'])) { case 'varchar': $length = $tableColumn['length']; - $fixed = false; + $fixed = false; break; case 'character': $length = $tableColumn['length']; - $fixed = true; + $fixed = true; break; case 'clob': $length = $tableColumn['length']; @@ -92,7 +73,7 @@ protected function _getPortableTableColumnDefinition($tableColumn) case 'decimal': case 'double': case 'real': - $scale = $tableColumn['scale']; + $scale = $tableColumn['scale']; $precision = $tableColumn['length']; break; } @@ -102,8 +83,8 @@ protected function _getPortableTableColumnDefinition($tableColumn) 'unsigned' => (bool) $unsigned, 'fixed' => (bool) $fixed, 'default' => $default, - 'autoincrement' => (boolean) $tableColumn['autoincrement'], - 'notnull' => (bool) ($tableColumn['nulls'] == 'N'), + 'autoincrement' => (bool) $tableColumn['autoincrement'], + 'notnull' => (bool) ($tableColumn['nulls'] === 'N'), 'scale' => null, 'precision' => null, 'comment' => isset($tableColumn['comment']) && $tableColumn['comment'] !== '' @@ -113,11 +94,11 @@ protected function _getPortableTableColumnDefinition($tableColumn) ]; if ($scale !== null && $precision !== null) { - $options['scale'] = $scale; + $options['scale'] = $scale; $options['precision'] = $precision; } - return new Column($tableColumn['colname'], \Doctrine\DBAL\Types\Type::getType($type), $options); + return new Column($tableColumn['colname'], Type::getType($type), $options); } /** @@ -127,7 +108,7 @@ protected function _getPortableTablesList($tables) { $tableNames = []; foreach ($tables as $tableRow) { - $tableRow = array_change_key_case($tableRow, \CASE_LOWER); + $tableRow = array_change_key_case($tableRow, CASE_LOWER); $tableNames[] = $tableRow['name']; } @@ -140,8 +121,8 @@ protected function _getPortableTablesList($tables) protected function _getPortableTableIndexesList($tableIndexRows, $tableName = null) { foreach ($tableIndexRows as &$tableIndexRow) { - $tableIndexRow = array_change_key_case($tableIndexRow, \CASE_LOWER); - $tableIndexRow['primary'] = (boolean) $tableIndexRow['primary']; + $tableIndexRow = array_change_key_case($tableIndexRow, CASE_LOWER); + $tableIndexRow['primary'] = (bool) $tableIndexRow['primary']; } return parent::_getPortableTableIndexesList($tableIndexRows, $tableName); @@ -169,9 +150,9 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys) $foreignKeys = []; foreach ($tableForeignKeys as $tableForeignKey) { - $tableForeignKey = array_change_key_case($tableForeignKey, \CASE_LOWER); + $tableForeignKey = array_change_key_case($tableForeignKey, CASE_LOWER); - if (!isset($foreignKeys[$tableForeignKey['index_name']])) { + if (! isset($foreignKeys[$tableForeignKey['index_name']])) { $foreignKeys[$tableForeignKey['index_name']] = [ 'local_columns' => [$tableForeignKey['local_column']], 'foreign_table' => $tableForeignKey['foreign_table'], @@ -180,10 +161,10 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys) 'options' => [ 'onUpdate' => $tableForeignKey['on_update'], 'onDelete' => $tableForeignKey['on_delete'], - ] + ], ]; } else { - $foreignKeys[$tableForeignKey['index_name']]['local_columns'][] = $tableForeignKey['local_column']; + $foreignKeys[$tableForeignKey['index_name']]['local_columns'][] = $tableForeignKey['local_column']; $foreignKeys[$tableForeignKey['index_name']]['foreign_columns'][] = $tableForeignKey['foreign_column']; } } @@ -196,10 +177,10 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys) */ protected function _getPortableForeignKeyRuleDef($def) { - if ($def == "C") { - return "CASCADE"; - } elseif ($def == "N") { - return "SET NULL"; + if ($def === 'C') { + return 'CASCADE'; + } elseif ($def === 'N') { + return 'SET NULL'; } return null; @@ -210,10 +191,10 @@ protected function _getPortableForeignKeyRuleDef($def) */ protected function _getPortableViewDefinition($view) { - $view = array_change_key_case($view, \CASE_LOWER); + $view = array_change_key_case($view, CASE_LOWER); // sadly this still segfaults on PDO_IBM, see http://pecl.php.net/bugs/bug.php?id=17199 //$view['text'] = (is_resource($view['text']) ? stream_get_contents($view['text']) : $view['text']); - if (!is_resource($view['text'])) { + if (! is_resource($view['text'])) { $pos = strpos($view['text'], ' AS '); $sql = substr($view['text'], $pos+4); } else { diff --git a/lib/Doctrine/DBAL/Schema/DrizzleSchemaManager.php b/lib/Doctrine/DBAL/Schema/DrizzleSchemaManager.php index a10eb3da066..c334db2797b 100644 --- a/lib/Doctrine/DBAL/Schema/DrizzleSchemaManager.php +++ b/lib/Doctrine/DBAL/Schema/DrizzleSchemaManager.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Schema; @@ -26,8 +9,6 @@ /** * Schema manager for the Drizzle RDBMS. - * - * @author Kim Hemsø Rasmussen */ class DrizzleSchemaManager extends AbstractSchemaManager { @@ -38,25 +19,25 @@ protected function _getPortableTableColumnDefinition($tableColumn) { $dbType = strtolower($tableColumn['DATA_TYPE']); - $type = $this->_platform->getDoctrineTypeMapping($dbType); - $type = $this->extractDoctrineTypeFromComment($tableColumn['COLUMN_COMMENT'], $type); + $type = $this->_platform->getDoctrineTypeMapping($dbType); + $type = $this->extractDoctrineTypeFromComment($tableColumn['COLUMN_COMMENT'], $type); $tableColumn['COLUMN_COMMENT'] = $this->removeDoctrineTypeFromComment($tableColumn['COLUMN_COMMENT'], $type); $options = [ - 'notnull' => !(bool) $tableColumn['IS_NULLABLE'], + 'notnull' => ! (bool) $tableColumn['IS_NULLABLE'], 'length' => (int) $tableColumn['CHARACTER_MAXIMUM_LENGTH'], 'default' => $tableColumn['COLUMN_DEFAULT'] ?? null, 'autoincrement' => (bool) $tableColumn['IS_AUTO_INCREMENT'], 'scale' => (int) $tableColumn['NUMERIC_SCALE'], 'precision' => (int) $tableColumn['NUMERIC_PRECISION'], - 'comment' => isset($tableColumn['COLUMN_COMMENT']) && '' !== $tableColumn['COLUMN_COMMENT'] + 'comment' => isset($tableColumn['COLUMN_COMMENT']) && $tableColumn['COLUMN_COMMENT'] !== '' ? $tableColumn['COLUMN_COMMENT'] : null, ]; $column = new Column($tableColumn['COLUMN_NAME'], Type::getType($type), $options); - if ( ! empty($tableColumn['COLLATION_NAME'])) { + if (! empty($tableColumn['COLLATION_NAME'])) { $column->setPlatformOption('collation', $tableColumn['COLLATION_NAME']); } @@ -113,8 +94,8 @@ protected function _getPortableTableIndexesList($tableIndexes, $tableName = null { $indexes = []; foreach ($tableIndexes as $k) { - $k['primary'] = (boolean) $k['primary']; - $indexes[] = $k; + $k['primary'] = (bool) $k['primary']; + $indexes[] = $k; } return parent::_getPortableTableIndexesList($indexes, $tableName); diff --git a/lib/Doctrine/DBAL/Schema/ForeignKeyConstraint.php b/lib/Doctrine/DBAL/Schema/ForeignKeyConstraint.php index a50b7a0b5c5..31850d7f23e 100644 --- a/lib/Doctrine/DBAL/Schema/ForeignKeyConstraint.php +++ b/lib/Doctrine/DBAL/Schema/ForeignKeyConstraint.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Schema; @@ -31,18 +14,13 @@ /** * An abstraction class for a foreign key constraint. - * - * @author Benjamin Eberlei - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.0 */ class ForeignKeyConstraint extends AbstractAsset implements Constraint { /** * Instance of the referencing table the foreign key constraint is associated with. * - * @var \Doctrine\DBAL\Schema\Table + * @var Table */ protected $_localTable; @@ -70,26 +48,28 @@ class ForeignKeyConstraint extends AbstractAsset implements Constraint protected $_foreignColumnNames; /** - * @var array Options associated with the foreign key constraint. + * Options associated with the foreign key constraint. + * + * @var mixed[] */ protected $_options; /** * Initializes the foreign key constraint. * - * @param array $localColumnNames Names of the referencing table columns. + * @param string[] $localColumnNames Names of the referencing table columns. * @param Table|string $foreignTableName Referenced table. - * @param array $foreignColumnNames Names of the referenced table columns. + * @param string[] $foreignColumnNames Names of the referenced table columns. * @param string|null $name Name of the foreign key constraint. - * @param array $options Options associated with the foreign key constraint. + * @param mixed[] $options Options associated with the foreign key constraint. */ public function __construct(array $localColumnNames, $foreignTableName, array $foreignColumnNames, $name = null, array $options = []) { $this->_setName($name); - $identifierConstructorCallback = function ($column) { + $identifierConstructorCallback = static function ($column) { return new Identifier($column); }; - $this->_localColumnNames = $localColumnNames + $this->_localColumnNames = $localColumnNames ? array_combine($localColumnNames, array_map($identifierConstructorCallback, $localColumnNames)) : []; @@ -102,7 +82,7 @@ public function __construct(array $localColumnNames, $foreignTableName, array $f $this->_foreignColumnNames = $foreignColumnNames ? array_combine($foreignColumnNames, array_map($identifierConstructorCallback, $foreignColumnNames)) : []; - $this->_options = $options; + $this->_options = $options; } /** @@ -120,7 +100,7 @@ public function getLocalTableName() * Sets the Table instance of the referencing table * the foreign key constraint is associated with. * - * @param \Doctrine\DBAL\Schema\Table $table Instance of the referencing table. + * @param Table $table Instance of the referencing table. * * @return void */ @@ -141,7 +121,7 @@ public function getLocalTable() * Returns the names of the referencing table columns * the foreign key constraint is associated with. * - * @return array + * @return string[] */ public function getLocalColumns() { @@ -156,9 +136,9 @@ public function getLocalColumns() * is a keyword reserved by the platform. * Otherwise the plain unquoted value as inserted is returned. * - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform The platform to use for quotation. + * @param AbstractPlatform $platform The platform to use for quotation. * - * @return array + * @return string[] */ public function getQuotedLocalColumns(AbstractPlatform $platform) { @@ -174,7 +154,7 @@ public function getQuotedLocalColumns(AbstractPlatform $platform) /** * Returns unquoted representation of local table column names for comparison with other FK * - * @return array + * @return string[] */ public function getUnquotedLocalColumns() { @@ -184,7 +164,7 @@ public function getUnquotedLocalColumns() /** * Returns unquoted representation of foreign table column names for comparison with other FK * - * @return array + * @return string[] */ public function getUnquotedForeignColumns() { @@ -209,11 +189,11 @@ public function getColumns() * is a keyword reserved by the platform. * Otherwise the plain unquoted value as inserted is returned. * - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform The platform to use for quotation. - * * @see getQuotedLocalColumns * - * @return array + * @param AbstractPlatform $platform The platform to use for quotation. + * + * @return string[] */ public function getQuotedColumns(AbstractPlatform $platform) { @@ -238,7 +218,7 @@ public function getForeignTableName() */ public function getUnqualifiedForeignTableName() { - $parts = explode(".", $this->_foreignTableName->getName()); + $parts = explode('.', $this->_foreignTableName->getName()); return strtolower(end($parts)); } @@ -251,7 +231,7 @@ public function getUnqualifiedForeignTableName() * is a keyword reserved by the platform. * Otherwise the plain unquoted value as inserted is returned. * - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform The platform to use for quotation. + * @param AbstractPlatform $platform The platform to use for quotation. * * @return string */ @@ -264,7 +244,7 @@ public function getQuotedForeignTableName(AbstractPlatform $platform) * Returns the names of the referenced table columns * the foreign key constraint is associated with. * - * @return array + * @return string[] */ public function getForeignColumns() { @@ -279,9 +259,9 @@ public function getForeignColumns() * is a keyword reserved by the platform. * Otherwise the plain unquoted value as inserted is returned. * - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform The platform to use for quotation. + * @param AbstractPlatform $platform The platform to use for quotation. * - * @return array + * @return string[] */ public function getQuotedForeignColumns(AbstractPlatform $platform) { @@ -322,7 +302,7 @@ public function getOption($name) /** * Returns the options associated with the foreign key constraint. * - * @return array + * @return mixed[] */ public function getOptions() { @@ -364,7 +344,7 @@ private function onEvent($event) if (isset($this->_options[$event])) { $onEvent = strtoupper($this->_options[$event]); - if ( ! in_array($onEvent, ['NO ACTION', 'RESTRICT'])) { + if (! in_array($onEvent, ['NO ACTION', 'RESTRICT'])) { return $onEvent; } } diff --git a/lib/Doctrine/DBAL/Schema/Identifier.php b/lib/Doctrine/DBAL/Schema/Identifier.php index babe583e43a..f34465e9efb 100644 --- a/lib/Doctrine/DBAL/Schema/Identifier.php +++ b/lib/Doctrine/DBAL/Schema/Identifier.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Schema; @@ -24,16 +7,10 @@ * * Wraps identifier names like column names in indexes / foreign keys * in an abstract class for proper quotation capabilities. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.4 */ class Identifier extends AbstractAsset { /** - * Constructor. - * * @param string $identifier Identifier name to wrap. * @param bool $quote Whether to force quoting the given identifier. */ @@ -41,8 +18,10 @@ public function __construct($identifier, $quote = false) { $this->_setName($identifier); - if ($quote && ! $this->_quoted) { - $this->_setName('"' . $this->getName() . '"'); + if (! $quote || $this->_quoted) { + return; } + + $this->_setName('"' . $this->getName() . '"'); } } diff --git a/lib/Doctrine/DBAL/Schema/Index.php b/lib/Doctrine/DBAL/Schema/Index.php index 78a2322c8d0..bae6d218cb6 100644 --- a/lib/Doctrine/DBAL/Schema/Index.php +++ b/lib/Doctrine/DBAL/Schema/Index.php @@ -1,28 +1,13 @@ . - */ namespace Doctrine\DBAL\Schema; use Doctrine\DBAL\Platforms\AbstractPlatform; +use InvalidArgumentException; use function array_keys; use function array_map; use function array_search; +use function array_shift; use function count; use function is_string; use function strtolower; @@ -37,21 +22,17 @@ class Index extends AbstractAsset implements Constraint */ protected $_columns = []; - /** - * @var bool - */ + /** @var bool */ protected $_isUnique = false; - /** - * @var bool - */ + /** @var bool */ protected $_isPrimary = false; /** * Platform specific flags for indexes. * array($flagName => true) * - * @var array + * @var true[] */ protected $_flags = []; @@ -59,8 +40,7 @@ class Index extends AbstractAsset implements Constraint * Platform specific options * * @todo $_flags should eventually be refactored into options - * - * @var array + * @var mixed[] */ private $options = []; @@ -70,16 +50,16 @@ class Index extends AbstractAsset implements Constraint * @param bool $isUnique * @param bool $isPrimary * @param string[] $flags - * @param array $options + * @param mixed[] $options */ public function __construct($indexName, array $columns, $isUnique = false, $isPrimary = false, array $flags = [], array $options = []) { $isUnique = $isUnique || $isPrimary; $this->_setName($indexName); - $this->_isUnique = $isUnique; + $this->_isUnique = $isUnique; $this->_isPrimary = $isPrimary; - $this->options = $options; + $this->options = $options; foreach ($columns as $column) { $this->_addColumn($column); @@ -94,15 +74,15 @@ public function __construct($indexName, array $columns, $isUnique = false, $isPr * * @return void * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ protected function _addColumn($column) { - if (is_string($column)) { - $this->_columns[$column] = new Identifier($column); - } else { - throw new \InvalidArgumentException("Expecting a string as Index Column"); + if (! is_string($column)) { + throw new InvalidArgumentException('Expecting a string as Index Column'); } + + $this->_columns[$column] = new Identifier($column); } /** @@ -118,10 +98,21 @@ public function getColumns() */ public function getQuotedColumns(AbstractPlatform $platform) { + $subParts = $platform->supportsColumnLengthIndexes() && $this->hasOption('lengths') + ? $this->getOption('lengths') : []; + $columns = []; foreach ($this->_columns as $column) { - $columns[] = $column->getQuotedName($platform); + $length = array_shift($subParts); + + $quotedColumn = $column->getQuotedName($platform); + + if ($length !== null) { + $quotedColumn .= '(' . $length . ')'; + } + + $columns[] = $quotedColumn; } return $columns; @@ -142,7 +133,7 @@ public function getUnquotedColumns() */ public function isSimpleIndex() { - return !$this->_isPrimary && !$this->_isUnique; + return ! $this->_isPrimary && ! $this->_isUnique; } /** @@ -178,7 +169,7 @@ public function hasColumnAtPosition($columnName, $pos = 0) /** * Checks if this index exactly spans the given column names in the correct order. * - * @param array $columnNames + * @param string[] $columnNames * * @return bool */ @@ -189,9 +180,11 @@ public function spansColumns(array $columnNames) $sameColumns = true; for ($i = 0; $i < $numberOfColumns; $i++) { - if ( ! isset($columnNames[$i]) || $this->trimQuotes(strtolower($columns[$i])) !== $this->trimQuotes(strtolower($columnNames[$i]))) { - $sameColumns = false; + if (isset($columnNames[$i]) && $this->trimQuotes(strtolower($columns[$i])) === $this->trimQuotes(strtolower($columnNames[$i]))) { + continue; } + + $sameColumns = false; } return $sameColumns; @@ -200,15 +193,13 @@ public function spansColumns(array $columnNames) /** * Checks if the other index already fulfills all the indexing and constraint needs of the current one. * - * @param Index $other - * * @return bool */ public function isFullfilledBy(Index $other) { // allow the other index to be equally large only. It being larger is an option // but it creates a problem with scenarios of the kind PRIMARY KEY(foo,bar) UNIQUE(foo) - if (count($other->getColumns()) != count($this->getColumns())) { + if (count($other->getColumns()) !== count($this->getColumns())) { return false; } @@ -216,11 +207,11 @@ public function isFullfilledBy(Index $other) $sameColumns = $this->spansColumns($other->getColumns()); if ($sameColumns) { - if ( ! $this->samePartialIndex($other)) { + if (! $this->samePartialIndex($other)) { return false; } - if ( ! $this->isUnique() && ! $this->isPrimary()) { + if (! $this->isUnique() && ! $this->isPrimary()) { // this is a special case: If the current key is neither primary or unique, any unique or // primary key will always have the same effect for the index and there cannot be any constraint // overlaps. This means a primary or unique index can always fulfill the requirements of just an @@ -228,7 +219,7 @@ public function isFullfilledBy(Index $other) return true; } - if ($other->isPrimary() != $this->isPrimary()) { + if ($other->isPrimary() !== $this->isPrimary()) { return false; } @@ -241,8 +232,6 @@ public function isFullfilledBy(Index $other) /** * Detects if the other index is a non-unique, non primary index that can be overwritten by this one. * - * @param Index $other - * * @return bool */ public function overrules(Index $other) @@ -269,11 +258,11 @@ public function getFlags() /** * Adds Flag for an index that translates to platform specific handling. * - * @example $index->addFlag('CLUSTERED') - * * @param string $flag * * @return Index + * + * @example $index->addFlag('CLUSTERED') */ public function addFlag($flag) { @@ -327,7 +316,7 @@ public function getOption($name) } /** - * @return array + * @return mixed[] */ public function getOptions() { @@ -336,17 +325,15 @@ public function getOptions() /** * Return whether the two indexes have the same partial index - * @param \Doctrine\DBAL\Schema\Index $other * * @return bool */ private function samePartialIndex(Index $other) { - if ($this->hasOption('where') && $other->hasOption('where') && $this->getOption('where') == $other->getOption('where')) { + if ($this->hasOption('where') && $other->hasOption('where') && $this->getOption('where') === $other->getOption('where')) { return true; } return ! $this->hasOption('where') && ! $other->hasOption('where'); } - } diff --git a/lib/Doctrine/DBAL/Schema/MySqlSchemaManager.php b/lib/Doctrine/DBAL/Schema/MySqlSchemaManager.php index a56a6af86b2..b6332026cdd 100644 --- a/lib/Doctrine/DBAL/Schema/MySqlSchemaManager.php +++ b/lib/Doctrine/DBAL/Schema/MySqlSchemaManager.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Schema; @@ -27,6 +10,7 @@ use function array_shift; use function array_values; use function end; +use function explode; use function preg_match; use function preg_replace; use function str_replace; @@ -34,15 +18,10 @@ use function strpos; use function strtok; use function strtolower; +use function trim; /** * Schema manager for the MySql RDBMS. - * - * @author Konsta Vesterinen - * @author Lukas Smith (PEAR MDB2 library) - * @author Roman Borschel - * @author Benjamin Eberlei - * @since 2.0 */ class MySqlSchemaManager extends AbstractSchemaManager { @@ -90,6 +69,8 @@ protected function _getPortableTableIndexesList($tableIndexes, $tableName = null } elseif (strpos($v['index_type'], 'SPATIAL') !== false) { $v['flags'] = ['SPATIAL']; } + $v['length'] = $v['sub_part'] ?? null; + $tableIndexes[$k] = $v; } @@ -125,7 +106,7 @@ protected function _getPortableTableColumnDefinition($tableColumn) $fixed = null; - if ( ! isset($tableColumn['name'])) { + if (! isset($tableColumn['name'])) { $tableColumn['name'] = ''; } @@ -233,7 +214,7 @@ protected function _getPortableTableColumnDefinition($tableColumn) * @link https://mariadb.com/kb/en/library/information-schema-columns-table/ * @link https://jira.mariadb.org/browse/MDEV-13132 * - * @param null|string $columnDefault default value as stored in information_schema for MariaDB >= 10.2.7 + * @param string|null $columnDefault default value as stored in information_schema for MariaDB >= 10.2.7 */ private function getMariaDb1027ColumnDefault(MariaDb1027Platform $platform, ?string $columnDefault) : ?string { @@ -242,7 +223,9 @@ private function getMariaDb1027ColumnDefault(MariaDb1027Platform $platform, ?str } if ($columnDefault[0] === "'") { return stripslashes( - str_replace("''", "'", + str_replace( + "''", + "'", preg_replace('/^\'(.*)\'$/', '$1', $columnDefault) ) ); @@ -266,11 +249,11 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys) $list = []; foreach ($tableForeignKeys as $value) { $value = array_change_key_case($value, CASE_LOWER); - if ( ! isset($list[$value['constraint_name']])) { - if ( ! isset($value['delete_rule']) || $value['delete_rule'] === "RESTRICT") { + if (! isset($list[$value['constraint_name']])) { + if (! isset($value['delete_rule']) || $value['delete_rule'] === 'RESTRICT') { $value['delete_rule'] = null; } - if ( ! isset($value['update_rule']) || $value['update_rule'] === "RESTRICT") { + if (! isset($value['update_rule']) || $value['update_rule'] === 'RESTRICT') { $value['update_rule'] = null; } @@ -303,4 +286,44 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys) return $result; } + + public function listTableDetails($tableName) + { + $table = parent::listTableDetails($tableName); + + /** @var MySqlPlatform $platform */ + $platform = $this->_platform; + $sql = $platform->getListTableMetadataSQL($tableName); + + $tableOptions = $this->_conn->fetchAssoc($sql); + + $table->addOption('engine', $tableOptions['ENGINE']); + if ($tableOptions['TABLE_COLLATION'] !== null) { + $table->addOption('collation', $tableOptions['TABLE_COLLATION']); + } + if ($tableOptions['AUTO_INCREMENT'] !== null) { + $table->addOption('autoincrement', $tableOptions['AUTO_INCREMENT']); + } + $table->addOption('comment', $tableOptions['TABLE_COMMENT']); + + if ($tableOptions['CREATE_OPTIONS'] === null) { + return $table; + } + + $createOptionsString = trim($tableOptions['CREATE_OPTIONS']); + + $createOptions = []; + + if ($createOptionsString !== '') { + foreach (explode(' ', $createOptionsString) as $option) { + [$createOption, $value] = explode('=', $option); + + $createOptions[$createOption] = $value; + } + } + + $table->addOption('create_options', $createOptions); + + return $table; + } } diff --git a/lib/Doctrine/DBAL/Schema/OracleSchemaManager.php b/lib/Doctrine/DBAL/Schema/OracleSchemaManager.php index 1f0bba466d2..c4d05aa1858 100644 --- a/lib/Doctrine/DBAL/Schema/OracleSchemaManager.php +++ b/lib/Doctrine/DBAL/Schema/OracleSchemaManager.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Schema; @@ -27,7 +10,6 @@ use function array_change_key_case; use function array_values; use function assert; -use function is_null; use function preg_match; use function sprintf; use function strpos; @@ -37,11 +19,6 @@ /** * Oracle Schema Manager. - * - * @author Konsta Vesterinen - * @author Lukas Smith (PEAR MDB2 library) - * @author Benjamin Eberlei - * @since 2.0 */ class OracleSchemaManager extends AbstractSchemaManager { @@ -78,7 +55,7 @@ public function dropDatabase($database) */ protected function _getPortableViewDefinition($view) { - $view = \array_change_key_case($view, CASE_LOWER); + $view = array_change_key_case($view, CASE_LOWER); return new View($this->getQuotedIdentifierName($view['view_name']), $view['text']); } @@ -88,7 +65,7 @@ protected function _getPortableViewDefinition($view) */ protected function _getPortableUserDefinition($user) { - $user = \array_change_key_case($user, CASE_LOWER); + $user = array_change_key_case($user, CASE_LOWER); return [ 'user' => $user['username'], @@ -100,7 +77,7 @@ protected function _getPortableUserDefinition($user) */ protected function _getPortableTableDefinition($table) { - $table = \array_change_key_case($table, CASE_LOWER); + $table = array_change_key_case($table, CASE_LOWER); return $this->getQuotedIdentifierName($table['table_name']); } @@ -108,29 +85,28 @@ protected function _getPortableTableDefinition($table) /** * {@inheritdoc} * - * @license New BSD License * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html */ - protected function _getPortableTableIndexesList($tableIndexes, $tableName=null) + protected function _getPortableTableIndexesList($tableIndexes, $tableName = null) { $indexBuffer = []; foreach ($tableIndexes as $tableIndex) { - $tableIndex = \array_change_key_case($tableIndex, CASE_LOWER); + $tableIndex = array_change_key_case($tableIndex, CASE_LOWER); $keyName = strtolower($tableIndex['name']); $buffer = []; - if (strtolower($tableIndex['is_primary']) == "p") { - $keyName = 'primary'; - $buffer['primary'] = true; + if (strtolower($tableIndex['is_primary']) === 'p') { + $keyName = 'primary'; + $buffer['primary'] = true; $buffer['non_unique'] = false; } else { - $buffer['primary'] = false; + $buffer['primary'] = false; $buffer['non_unique'] = ! $tableIndex['is_unique']; } - $buffer['key_name'] = $keyName; + $buffer['key_name'] = $keyName; $buffer['column_name'] = $this->getQuotedIdentifierName($tableIndex['column_name']); - $indexBuffer[] = $buffer; + $indexBuffer[] = $buffer; } return parent::_getPortableTableIndexesList($indexBuffer, $tableName); @@ -141,20 +117,20 @@ protected function _getPortableTableIndexesList($tableIndexes, $tableName=null) */ protected function _getPortableTableColumnDefinition($tableColumn) { - $tableColumn = \array_change_key_case($tableColumn, CASE_LOWER); + $tableColumn = array_change_key_case($tableColumn, CASE_LOWER); $dbType = strtolower($tableColumn['data_type']); - if (strpos($dbType, "timestamp(") === 0) { - if (strpos($dbType, "with time zone")) { - $dbType = "timestamptz"; + if (strpos($dbType, 'timestamp(') === 0) { + if (strpos($dbType, 'with time zone')) { + $dbType = 'timestamptz'; } else { - $dbType = "timestamp"; + $dbType = 'timestamp'; } } $unsigned = $fixed = null; - if ( ! isset($tableColumn['column_name'])) { + if (! isset($tableColumn['column_name'])) { $tableColumn['column_name'] = ''; } @@ -165,36 +141,36 @@ protected function _getPortableTableColumnDefinition($tableColumn) $tableColumn['data_default'] = null; } - if (null !== $tableColumn['data_default']) { + if ($tableColumn['data_default'] !== null) { // Default values returned from database are enclosed in single quotes. $tableColumn['data_default'] = trim($tableColumn['data_default'], "'"); } $precision = null; - $scale = null; + $scale = null; - $type = $this->_platform->getDoctrineTypeMapping($dbType); - $type = $this->extractDoctrineTypeFromComment($tableColumn['comments'], $type); + $type = $this->_platform->getDoctrineTypeMapping($dbType); + $type = $this->extractDoctrineTypeFromComment($tableColumn['comments'], $type); $tableColumn['comments'] = $this->removeDoctrineTypeFromComment($tableColumn['comments'], $type); switch ($dbType) { case 'number': - if ($tableColumn['data_precision'] == 20 && $tableColumn['data_scale'] == 0) { + if ($tableColumn['data_precision'] === 20 && $tableColumn['data_scale'] === 0) { $precision = 20; - $scale = 0; - $type = 'bigint'; - } elseif ($tableColumn['data_precision'] == 5 && $tableColumn['data_scale'] == 0) { - $type = 'smallint'; + $scale = 0; + $type = 'bigint'; + } elseif ($tableColumn['data_precision'] === 5 && $tableColumn['data_scale'] === 0) { + $type = 'smallint'; $precision = 5; - $scale = 0; - } elseif ($tableColumn['data_precision'] == 1 && $tableColumn['data_scale'] == 0) { + $scale = 0; + } elseif ($tableColumn['data_precision'] === 1 && $tableColumn['data_scale'] === 0) { $precision = 1; - $scale = 0; - $type = 'boolean'; + $scale = 0; + $type = 'boolean'; } elseif ($tableColumn['data_scale'] > 0) { $precision = $tableColumn['data_precision']; - $scale = $tableColumn['data_scale']; - $type = 'decimal'; + $scale = $tableColumn['data_scale']; + $type = 'decimal'; } $length = null; break; @@ -206,12 +182,12 @@ protected function _getPortableTableColumnDefinition($tableColumn) case 'varchar2': case 'nvarchar2': $length = $tableColumn['char_length']; - $fixed = false; + $fixed = false; break; case 'char': case 'nchar': $length = $tableColumn['char_length']; - $fixed = true; + $fixed = true; break; case 'date': case 'timestamp': @@ -221,8 +197,8 @@ protected function _getPortableTableColumnDefinition($tableColumn) case 'binary_float': case 'binary_double': $precision = $tableColumn['data_precision']; - $scale = $tableColumn['data_scale']; - $length = null; + $scale = $tableColumn['data_scale']; + $length = null; break; case 'clob': case 'nclob': @@ -248,7 +224,7 @@ protected function _getPortableTableColumnDefinition($tableColumn) 'length' => $length, 'precision' => $precision, 'scale' => $scale, - 'comment' => isset($tableColumn['comments']) && '' !== $tableColumn['comments'] + 'comment' => isset($tableColumn['comments']) && $tableColumn['comments'] !== '' ? $tableColumn['comments'] : null, ]; @@ -263,9 +239,9 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys) { $list = []; foreach ($tableForeignKeys as $value) { - $value = \array_change_key_case($value, CASE_LOWER); - if (!isset($list[$value['constraint_name']])) { - if ($value['delete_rule'] == "NO ACTION") { + $value = array_change_key_case($value, CASE_LOWER); + if (! isset($list[$value['constraint_name']])) { + if ($value['delete_rule'] === 'NO ACTION') { $value['delete_rule'] = null; } @@ -278,18 +254,20 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys) ]; } - $localColumn = $this->getQuotedIdentifierName($value['local_column']); + $localColumn = $this->getQuotedIdentifierName($value['local_column']); $foreignColumn = $this->getQuotedIdentifierName($value['foreign_column']); - $list[$value['constraint_name']]['local'][$value['position']] = $localColumn; + $list[$value['constraint_name']]['local'][$value['position']] = $localColumn; $list[$value['constraint_name']]['foreign'][$value['position']] = $foreignColumn; } $result = []; foreach ($list as $constraint) { $result[] = new ForeignKeyConstraint( - array_values($constraint['local']), $this->getQuotedIdentifierName($constraint['foreignTable']), - array_values($constraint['foreign']), $this->getQuotedIdentifierName($constraint['name']), + array_values($constraint['local']), + $this->getQuotedIdentifierName($constraint['foreignTable']), + array_values($constraint['foreign']), + $this->getQuotedIdentifierName($constraint['name']), ['onDelete' => $constraint['onDelete']] ); } @@ -302,7 +280,7 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys) */ protected function _getPortableSequenceDefinition($sequence) { - $sequence = \array_change_key_case($sequence, CASE_LOWER); + $sequence = array_change_key_case($sequence, CASE_LOWER); return new Sequence( $this->getQuotedIdentifierName($sequence['sequence_name']), @@ -316,7 +294,7 @@ protected function _getPortableSequenceDefinition($sequence) */ protected function _getPortableFunctionDefinition($function) { - $function = \array_change_key_case($function, CASE_LOWER); + $function = array_change_key_case($function, CASE_LOWER); return $function['name']; } @@ -326,7 +304,7 @@ protected function _getPortableFunctionDefinition($function) */ protected function _getPortableDatabaseDefinition($database) { - $database = \array_change_key_case($database, CASE_LOWER); + $database = array_change_key_case($database, CASE_LOWER); return $database['username']; } @@ -340,11 +318,11 @@ public function createDatabase($database = null) $database = $this->_conn->getDatabase(); } - $params = $this->_conn->getParams(); - $username = $database; - $password = $params['password']; + $params = $this->_conn->getParams(); + $username = $database; + $password = $params['password']; - $query = 'CREATE USER ' . $username . ' IDENTIFIED BY ' . $password; + $query = 'CREATE USER ' . $username . ' IDENTIFIED BY ' . $password; $this->_conn->executeUpdate($query); $query = 'GRANT DBA TO ' . $username; @@ -423,7 +401,7 @@ protected function killUserSessions($user) $activeUserSessions = $this->_conn->fetchAll($sql, [strtoupper($user)]); foreach ($activeUserSessions as $activeUserSession) { - $activeUserSession = array_change_key_case($activeUserSession, \CASE_LOWER); + $activeUserSession = array_change_key_case($activeUserSession, CASE_LOWER); $this->_execSql( sprintf( diff --git a/lib/Doctrine/DBAL/Schema/PostgreSqlSchemaManager.php b/lib/Doctrine/DBAL/Schema/PostgreSqlSchemaManager.php index 621fdc2454c..168e74ea87f 100644 --- a/lib/Doctrine/DBAL/Schema/PostgreSqlSchemaManager.php +++ b/lib/Doctrine/DBAL/Schema/PostgreSqlSchemaManager.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Schema; @@ -31,10 +14,11 @@ use function array_shift; use function assert; use function explode; +use function implode; use function in_array; -use function join; use function preg_match; use function preg_replace; +use function sprintf; use function str_replace; use function stripos; use function strlen; @@ -44,23 +28,16 @@ /** * PostgreSQL Schema Manager. - * - * @author Konsta Vesterinen - * @author Lukas Smith (PEAR MDB2 library) - * @author Benjamin Eberlei - * @since 2.0 */ class PostgreSqlSchemaManager extends AbstractSchemaManager { - /** - * @var array - */ + /** @var string[] */ private $existingSchemaPaths; /** * Gets all the existing schema names. * - * @return array + * @return string[] */ public function getSchemaNames() { @@ -74,12 +51,12 @@ public function getSchemaNames() * * This is a PostgreSQL only function. * - * @return array + * @return string[] */ public function getSchemaSearchPaths() { $params = $this->_conn->getParams(); - $schema = explode(",", $this->_conn->fetchColumn('SHOW search_path')); + $schema = explode(',', $this->_conn->fetchColumn('SHOW search_path')); if (isset($params['user'])) { $schema = str_replace('"$user"', $params['user'], $schema); @@ -93,7 +70,7 @@ public function getSchemaSearchPaths() * * This is a PostgreSQL only function. * - * @return array + * @return string[] */ public function getExistingSchemaSearchPaths() { @@ -116,7 +93,7 @@ public function determineExistingSchemaSearchPaths() $names = $this->getSchemaNames(); $paths = $this->getSchemaSearchPaths(); - $this->existingSchemaPaths = array_filter($paths, function ($v) use ($names) { + $this->existingSchemaPaths = array_filter($paths, static function ($v) use ($names) { return in_array($v, $names); }); } @@ -171,13 +148,16 @@ protected function _getPortableTableForeignKeyDefinition($tableForeignKey) if (preg_match('/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)/', $tableForeignKey['condef'], $values)) { // PostgreSQL returns identifiers that are keywords with quotes, we need them later, don't get // the idea to trim them here. - $localColumns = array_map('trim', explode(",", $values[1])); - $foreignColumns = array_map('trim', explode(",", $values[3])); - $foreignTable = $values[2]; + $localColumns = array_map('trim', explode(',', $values[1])); + $foreignColumns = array_map('trim', explode(',', $values[3])); + $foreignTable = $values[2]; } return new ForeignKeyConstraint( - $localColumns, $foreignTable, $foreignColumns, $tableForeignKey['conname'], + $localColumns, + $foreignTable, + $foreignColumns, + $tableForeignKey['conname'], ['onUpdate' => $onUpdate, 'onDelete' => $onDelete] ); } @@ -195,7 +175,7 @@ protected function _getPortableTriggerDefinition($trigger) */ protected function _getPortableViewDefinition($view) { - return new View($view['schemaname'].'.'.$view['viewname'], $view['definition']); + return new View($view['schemaname'] . '.' . $view['viewname'], $view['definition']); } /** @@ -205,7 +185,7 @@ protected function _getPortableUserDefinition($user) { return [ 'user' => $user['usename'], - 'password' => $user['passwd'] + 'password' => $user['passwd'], ]; } @@ -214,46 +194,49 @@ protected function _getPortableUserDefinition($user) */ protected function _getPortableTableDefinition($table) { - $schemas = $this->getExistingSchemaSearchPaths(); + $schemas = $this->getExistingSchemaSearchPaths(); $firstSchema = array_shift($schemas); - if ($table['schema_name'] == $firstSchema) { + if ($table['schema_name'] === $firstSchema) { return $table['table_name']; } - return $table['schema_name'] . "." . $table['table_name']; + return $table['schema_name'] . '.' . $table['table_name']; } /** * {@inheritdoc} * - * @license New BSD License * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html */ - protected function _getPortableTableIndexesList($tableIndexes, $tableName=null) + protected function _getPortableTableIndexesList($tableIndexes, $tableName = null) { $buffer = []; foreach ($tableIndexes as $row) { - $colNumbers = explode(' ', $row['indkey']); - $colNumbersSql = 'IN (' . join(' ,', $colNumbers) . ' )'; - $columnNameSql = "SELECT attnum, attname FROM pg_attribute - WHERE attrelid={$row['indrelid']} AND attnum $colNumbersSql ORDER BY attnum ASC;"; + $colNumbers = array_map('intval', explode(' ', $row['indkey'])); + $columnNameSql = sprintf( + 'SELECT attnum, attname FROM pg_attribute WHERE attrelid=%d AND attnum IN (%s) ORDER BY attnum ASC', + $row['indrelid'], + implode(' ,', $colNumbers) + ); - $stmt = $this->_conn->executeQuery($columnNameSql); + $stmt = $this->_conn->executeQuery($columnNameSql); $indexColumns = $stmt->fetchAll(); // required for getting the order of the columns right. foreach ($colNumbers as $colNum) { foreach ($indexColumns as $colRow) { - if ($colNum == $colRow['attnum']) { - $buffer[] = [ - 'key_name' => $row['relname'], - 'column_name' => trim($colRow['attname']), - 'non_unique' => !$row['indisunique'], - 'primary' => $row['indisprimary'], - 'where' => $row['where'], - ]; + if ($colNum !== $colRow['attnum']) { + continue; } + + $buffer[] = [ + 'key_name' => $row['relname'], + 'column_name' => trim($colRow['attname']), + 'non_unique' => ! $row['indisunique'], + 'primary' => $row['indisprimary'], + 'where' => $row['where'], + ]; } } } @@ -277,8 +260,8 @@ protected function _getPortableSequencesList($sequences) $sequenceDefinitions = []; foreach ($sequences as $sequence) { - if ($sequence['schemaname'] != 'public') { - $sequenceName = $sequence['schemaname'] . "." . $sequence['relname']; + if ($sequence['schemaname'] !== 'public') { + $sequenceName = $sequence['schemaname'] . '.' . $sequence['relname']; } else { $sequenceName = $sequence['relname']; } @@ -309,14 +292,14 @@ protected function getPortableNamespaceDefinition(array $namespace) protected function _getPortableSequenceDefinition($sequence) { if ($sequence['schemaname'] !== 'public') { - $sequenceName = $sequence['schemaname'] . "." . $sequence['relname']; + $sequenceName = $sequence['schemaname'] . '.' . $sequence['relname']; } else { $sequenceName = $sequence['relname']; } - if ( ! isset($sequence['increment_by'], $sequence['min_value'])) { + if (! isset($sequence['increment_by'], $sequence['min_value'])) { /** @var string[] $data */ - $data = $this->_conn->fetchAssoc('SELECT min_value, increment_by FROM ' . $this->_platform->quoteIdentifier($sequenceName)); + $data = $this->_conn->fetchAssoc('SELECT min_value, increment_by FROM ' . $this->_platform->quoteIdentifier($sequenceName)); $sequence += $data; } @@ -333,7 +316,7 @@ protected function _getPortableTableColumnDefinition($tableColumn) if (strtolower($tableColumn['type']) === 'varchar' || strtolower($tableColumn['type']) === 'bpchar') { // get length from varchar definition - $length = preg_replace('~.*\(([0-9]*)\).*~', '$1', $tableColumn['complete_type']); + $length = preg_replace('~.*\(([0-9]*)\).*~', '$1', $tableColumn['complete_type']); $tableColumn['length'] = $length; } @@ -342,8 +325,8 @@ protected function _getPortableTableColumnDefinition($tableColumn) $autoincrement = false; if (preg_match("/^nextval\('(.*)'(::.*)?\)$/", $tableColumn['default'], $matches)) { $tableColumn['sequence'] = $matches[1]; - $tableColumn['default'] = null; - $autoincrement = true; + $tableColumn['default'] = null; + $autoincrement = true; } if (preg_match("/^['(](.*)[')]::.*$/", $tableColumn['default'], $matches)) { @@ -355,7 +338,7 @@ protected function _getPortableTableColumnDefinition($tableColumn) } $length = $tableColumn['length'] ?? null; - if ($length == '-1' && isset($tableColumn['atttypmod'])) { + if ($length === '-1' && isset($tableColumn['atttypmod'])) { $length = $tableColumn['atttypmod'] - 4; } if ((int) $length <= 0) { @@ -363,40 +346,40 @@ protected function _getPortableTableColumnDefinition($tableColumn) } $fixed = null; - if (!isset($tableColumn['name'])) { + if (! isset($tableColumn['name'])) { $tableColumn['name'] = ''; } $precision = null; - $scale = null; - $jsonb = null; + $scale = null; + $jsonb = null; $dbType = strtolower($tableColumn['type']); - if (strlen($tableColumn['domain_type']) && !$this->_platform->hasDoctrineTypeMappingFor($tableColumn['type'])) { - $dbType = strtolower($tableColumn['domain_type']); + if (strlen($tableColumn['domain_type']) && ! $this->_platform->hasDoctrineTypeMappingFor($tableColumn['type'])) { + $dbType = strtolower($tableColumn['domain_type']); $tableColumn['complete_type'] = $tableColumn['domain_complete_type']; } - $type = $this->_platform->getDoctrineTypeMapping($dbType); - $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type); + $type = $this->_platform->getDoctrineTypeMapping($dbType); + $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type); $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type); switch ($dbType) { case 'smallint': case 'int2': $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']); - $length = null; + $length = null; break; case 'int': case 'int4': case 'integer': $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']); - $length = null; + $length = null; break; case 'bigint': case 'int8': $tableColumn['default'] = $this->fixVersion94NegativeNumericDefaultValue($tableColumn['default']); - $length = null; + $length = null; break; case 'bool': case 'boolean': @@ -435,8 +418,8 @@ protected function _getPortableTableColumnDefinition($tableColumn) if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['complete_type'], $match)) { $precision = $match[1]; - $scale = $match[2]; - $length = null; + $scale = $match[2]; + $length = null; } break; case 'year': @@ -469,7 +452,7 @@ protected function _getPortableTableColumnDefinition($tableColumn) $column = new Column($tableColumn['field'], Type::getType($type), $options); - if (isset($tableColumn['collation']) && !empty($tableColumn['collation'])) { + if (isset($tableColumn['collation']) && ! empty($tableColumn['collation'])) { $column->setPlatformOption('collation', $tableColumn['collation']); } diff --git a/lib/Doctrine/DBAL/Schema/SQLAnywhereSchemaManager.php b/lib/Doctrine/DBAL/Schema/SQLAnywhereSchemaManager.php index 84a04a34883..62d5fa88e89 100644 --- a/lib/Doctrine/DBAL/Schema/SQLAnywhereSchemaManager.php +++ b/lib/Doctrine/DBAL/Schema/SQLAnywhereSchemaManager.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Schema; @@ -26,10 +9,6 @@ /** * SAP Sybase SQL Anywhere schema manager. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ class SQLAnywhereSchemaManager extends AbstractSchemaManager { @@ -114,11 +93,11 @@ protected function _getPortableTableColumnDefinition($tableColumn) $fixed = false; $default = null; - if (null !== $tableColumn['default']) { + if ($tableColumn['default'] !== null) { // Strip quotes from default value. - $default = preg_replace(["/^'(.*)'$/", "/''/"], ["$1", "'"], $tableColumn['default']); + $default = preg_replace(["/^'(.*)'$/", "/''/"], ['$1', "'"], $tableColumn['default']); - if ('autoincrement' == $default) { + if ($default === 'autoincrement') { $default = null; } } @@ -134,14 +113,14 @@ protected function _getPortableTableColumnDefinition($tableColumn) case 'decimal': case 'float': $precision = $tableColumn['length']; - $scale = $tableColumn['scale']; + $scale = $tableColumn['scale']; } return new Column( $tableColumn['column_name'], Type::getType($type), [ - 'length' => $type == 'string' ? $tableColumn['length'] : null, + 'length' => $type === 'string' ? $tableColumn['length'] : null, 'precision' => $precision, 'scale' => $scale, 'unsigned' => (bool) $tableColumn['unsigned'], @@ -149,7 +128,7 @@ protected function _getPortableTableColumnDefinition($tableColumn) 'notnull' => (bool) $tableColumn['notnull'], 'default' => $default, 'autoincrement' => (bool) $tableColumn['autoincrement'], - 'comment' => isset($tableColumn['comment']) && '' !== $tableColumn['comment'] + 'comment' => isset($tableColumn['comment']) && $tableColumn['comment'] !== '' ? $tableColumn['comment'] : null, ] @@ -186,7 +165,7 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys) $foreignKeys = []; foreach ($tableForeignKeys as $tableForeignKey) { - if (!isset($foreignKeys[$tableForeignKey['index_name']])) { + if (! isset($foreignKeys[$tableForeignKey['index_name']])) { $foreignKeys[$tableForeignKey['index_name']] = [ 'local_columns' => [$tableForeignKey['local_column']], 'foreign_table' => $tableForeignKey['foreign_table'], @@ -199,11 +178,11 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys) 'onDelete' => $tableForeignKey['on_delete'], 'check_on_commit' => $tableForeignKey['check_on_commit'], 'clustered' => $tableForeignKey['clustered'], - 'for_olap_workload' => $tableForeignKey['for_olap_workload'] - ] + 'for_olap_workload' => $tableForeignKey['for_olap_workload'], + ], ]; } else { - $foreignKeys[$tableForeignKey['index_name']]['local_columns'][] = $tableForeignKey['local_column']; + $foreignKeys[$tableForeignKey['index_name']]['local_columns'][] = $tableForeignKey['local_column']; $foreignKeys[$tableForeignKey['index_name']]['foreign_columns'][] = $tableForeignKey['foreign_column']; } } @@ -217,8 +196,8 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys) protected function _getPortableTableIndexesList($tableIndexRows, $tableName = null) { foreach ($tableIndexRows as &$tableIndex) { - $tableIndex['primary'] = (boolean) $tableIndex['primary']; - $tableIndex['flags'] = []; + $tableIndex['primary'] = (bool) $tableIndex['primary']; + $tableIndex['flags'] = []; if ($tableIndex['clustered']) { $tableIndex['flags'][] = 'clustered'; @@ -228,9 +207,11 @@ protected function _getPortableTableIndexesList($tableIndexRows, $tableName = nu $tableIndex['flags'][] = 'with_nulls_not_distinct'; } - if ($tableIndex['for_olap_workload']) { - $tableIndex['flags'][] = 'for_olap_workload'; + if (! $tableIndex['for_olap_workload']) { + continue; } + + $tableIndex['flags'][] = 'for_olap_workload'; } return parent::_getPortableTableIndexesList($tableIndexRows, $tableName); @@ -243,7 +224,7 @@ protected function _getPortableViewDefinition($view) { return new View( $view['table_name'], - preg_replace('/^.*\s+as\s+SELECT(.*)/i', "SELECT$1", $view['view_def']) + preg_replace('/^.*\s+as\s+SELECT(.*)/i', 'SELECT$1', $view['view_def']) ); } } diff --git a/lib/Doctrine/DBAL/Schema/SQLServerSchemaManager.php b/lib/Doctrine/DBAL/Schema/SQLServerSchemaManager.php index f5383fb7f73..6cd82b2ffaf 100644 --- a/lib/Doctrine/DBAL/Schema/SQLServerSchemaManager.php +++ b/lib/Doctrine/DBAL/Schema/SQLServerSchemaManager.php @@ -1,27 +1,11 @@ . - */ namespace Doctrine\DBAL\Schema; use Doctrine\DBAL\DBALException; use Doctrine\DBAL\Driver\DriverException; use Doctrine\DBAL\Types\Type; +use PDOException; use function count; use function in_array; use function preg_replace; @@ -33,13 +17,6 @@ /** * SQL Server Schema Manager. - * - * @license http://www.opensource.org/licenses/mit-license.php MIT - * @author Konsta Vesterinen - * @author Lukas Smith (PEAR MDB2 library) - * @author Juozas Kaziukenas - * @author Steve Müller - * @since 2.0 */ class SQLServerSchemaManager extends AbstractSchemaManager { @@ -84,19 +61,23 @@ protected function _getPortableSequenceDefinition($sequence) */ protected function _getPortableTableColumnDefinition($tableColumn) { - $dbType = strtok($tableColumn['type'], '(), '); - $fixed = null; - $length = (int) $tableColumn['length']; + $dbType = strtok($tableColumn['type'], '(), '); + $fixed = null; + $length = (int) $tableColumn['length']; $default = $tableColumn['default']; - if (!isset($tableColumn['name'])) { + if (! isset($tableColumn['name'])) { $tableColumn['name'] = ''; } - while ($default != ($default2 = preg_replace("/^\((.*)\)$/", '$1', $default))) { - $default = trim($default2, "'"); + if ($default !== null) { + while ($default !== ($default2 = preg_replace('/^\((.*)\)$/', '$1', $default))) { + $default = trim($default2, "'"); + + if ($default !== 'getdate()') { + continue; + } - if ($default == 'getdate()') { $default = $this->_platform->getCurrentTimestampSQL(); } } @@ -106,17 +87,17 @@ protected function _getPortableTableColumnDefinition($tableColumn) case 'nvarchar': case 'ntext': // Unicode data requires 2 bytes per character - $length = $length / 2; + $length /= 2; break; case 'varchar': // TEXT type is returned as VARCHAR(MAX) with a length of -1 - if ($length == -1) { + if ($length === -1) { $dbType = 'text'; } break; } - if ('char' === $dbType || 'nchar' === $dbType || 'binary' === $dbType) { + if ($dbType === 'char' || $dbType === 'nchar' || $dbType === 'binary') { $fixed = true; } @@ -125,7 +106,7 @@ protected function _getPortableTableColumnDefinition($tableColumn) $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type); $options = [ - 'length' => ($length == 0 || !in_array($type, ['text', 'string'])) ? null : $length, + 'length' => $length === 0 || ! in_array($type, ['text', 'string']) ? null : $length, 'unsigned' => false, 'fixed' => (bool) $fixed, 'default' => $default !== 'NULL' ? $default : null, @@ -153,7 +134,7 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys) $foreignKeys = []; foreach ($tableForeignKeys as $tableForeignKey) { - if ( ! isset($foreignKeys[$tableForeignKey['ForeignKey']])) { + if (! isset($foreignKeys[$tableForeignKey['ForeignKey']])) { $foreignKeys[$tableForeignKey['ForeignKey']] = [ 'local_columns' => [$tableForeignKey['ColumnName']], 'foreign_table' => $tableForeignKey['ReferenceTableName'], @@ -161,11 +142,11 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys) 'name' => $tableForeignKey['ForeignKey'], 'options' => [ 'onUpdate' => str_replace('_', ' ', $tableForeignKey['update_referential_action_desc']), - 'onDelete' => str_replace('_', ' ', $tableForeignKey['delete_referential_action_desc']) - ] + 'onDelete' => str_replace('_', ' ', $tableForeignKey['delete_referential_action_desc']), + ], ]; } else { - $foreignKeys[$tableForeignKey['ForeignKey']]['local_columns'][] = $tableForeignKey['ColumnName']; + $foreignKeys[$tableForeignKey['ForeignKey']]['local_columns'][] = $tableForeignKey['ColumnName']; $foreignKeys[$tableForeignKey['ForeignKey']]['foreign_columns'][] = $tableForeignKey['ReferenceColumnName']; } } @@ -176,12 +157,12 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys) /** * {@inheritdoc} */ - protected function _getPortableTableIndexesList($tableIndexRows, $tableName=null) + protected function _getPortableTableIndexesList($tableIndexRows, $tableName = null) { foreach ($tableIndexRows as &$tableIndex) { - $tableIndex['non_unique'] = (boolean) $tableIndex['non_unique']; - $tableIndex['primary'] = (boolean) $tableIndex['primary']; - $tableIndex['flags'] = $tableIndex['flags'] ? [$tableIndex['flags']] : null; + $tableIndex['non_unique'] = (bool) $tableIndex['non_unique']; + $tableIndex['primary'] = (bool) $tableIndex['primary']; + $tableIndex['flags'] = $tableIndex['flags'] ? [$tableIndex['flags']] : null; } return parent::_getPortableTableIndexesList($tableIndexRows, $tableName); @@ -247,18 +228,18 @@ public function listTableIndexes($table) try { $tableIndexes = $this->_conn->fetchAll($sql); - } catch (\PDOException $e) { - if ($e->getCode() == "IMSSP") { + } catch (PDOException $e) { + if ($e->getCode() === 'IMSSP') { return []; - } else { - throw $e; } + + throw $e; } catch (DBALException $e) { if (strpos($e->getMessage(), 'SQLSTATE [01000, 15472]') === 0) { return []; - } else { - throw $e; } + + throw $e; } return $this->_getPortableTableIndexesList($tableIndexes, $table); @@ -273,7 +254,13 @@ public function alterTable(TableDiff $tableDiff) foreach ($tableDiff->removedColumns as $col) { $columnConstraintSql = $this->getColumnConstraintSQL($tableDiff->name, $col->getName()); foreach ($this->_conn->fetchAll($columnConstraintSql) as $constraint) { - $this->_conn->exec("ALTER TABLE $tableDiff->name DROP CONSTRAINT " . $constraint['Name']); + $this->_conn->exec( + sprintf( + 'ALTER TABLE %s DROP CONSTRAINT %s', + $tableDiff->name, + $constraint['Name'] + ) + ); } } } @@ -296,8 +283,8 @@ private function getColumnConstraintSQL($table, $column) ON Tab.[ID] = Sysobjects.[Parent_Obj] INNER JOIN sys.default_constraints DefCons ON DefCons.[object_id] = Sysobjects.[ID] INNER JOIN SysColumns Col ON Col.[ColID] = DefCons.[parent_column_id] AND Col.[ID] = Tab.[ID] - WHERE Col.[Name] = " . $this->_conn->quote($column) ." AND Tab.[Name] = " . $this->_conn->quote($table) . " - ORDER BY Col.[Name]"; + WHERE Col.[Name] = " . $this->_conn->quote($column) . ' AND Tab.[Name] = ' . $this->_conn->quote($table) . ' + ORDER BY Col.[Name]'; } /** diff --git a/lib/Doctrine/DBAL/Schema/Schema.php b/lib/Doctrine/DBAL/Schema/Schema.php index cf5ed4054cb..7b75f4fb743 100644 --- a/lib/Doctrine/DBAL/Schema/Schema.php +++ b/lib/Doctrine/DBAL/Schema/Schema.php @@ -1,29 +1,12 @@ . - */ namespace Doctrine\DBAL\Schema; +use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Schema\Visitor\CreateSchemaSqlCollector; use Doctrine\DBAL\Schema\Visitor\DropSchemaSqlCollector; use Doctrine\DBAL\Schema\Visitor\NamespaceVisitor; use Doctrine\DBAL\Schema\Visitor\Visitor; -use Doctrine\DBAL\Platforms\AbstractPlatform; use function array_keys; use function strpos; use function strtolower; @@ -51,48 +34,37 @@ * the CREATE/DROP SQL visitors will just filter this queries and do not * execute them. Only the queries for the currently connected database are * executed. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ class Schema extends AbstractAsset { /** * The namespaces in this schema. * - * @var array + * @var string[] */ private $namespaces = []; - /** - * @var \Doctrine\DBAL\Schema\Table[] - */ + /** @var Table[] */ protected $_tables = []; - /** - * @var \Doctrine\DBAL\Schema\Sequence[] - */ + /** @var Sequence[] */ protected $_sequences = []; - /** - * @var SchemaConfig - */ + /** @var SchemaConfig */ protected $_schemaConfig = false; /** - * @param \Doctrine\DBAL\Schema\Table[] $tables - * @param \Doctrine\DBAL\Schema\Sequence[] $sequences - * @param \Doctrine\DBAL\Schema\SchemaConfig $schemaConfig - * @param array $namespaces + * @param Table[] $tables + * @param Sequence[] $sequences + * @param string[] $namespaces */ public function __construct( array $tables = [], array $sequences = [], - SchemaConfig $schemaConfig = null, + ?SchemaConfig $schemaConfig = null, array $namespaces = [] ) { - if ($schemaConfig == null) { + if ($schemaConfig === null) { $schemaConfig = new SchemaConfig(); } $this->_schemaConfig = $schemaConfig; @@ -120,22 +92,20 @@ public function hasExplicitForeignKeyIndexes() } /** - * @param \Doctrine\DBAL\Schema\Table $table - * * @return void * - * @throws \Doctrine\DBAL\Schema\SchemaException + * @throws SchemaException */ protected function _addTable(Table $table) { $namespaceName = $table->getNamespaceName(); - $tableName = $table->getFullQualifiedName($this->getName()); + $tableName = $table->getFullQualifiedName($this->getName()); if (isset($this->_tables[$tableName])) { throw SchemaException::tableAlreadyExists($tableName); } - if ( ! $table->isInDefaultNamespace($this->getName()) && ! $this->hasNamespace($namespaceName)) { + if (! $table->isInDefaultNamespace($this->getName()) && ! $this->hasNamespace($namespaceName)) { $this->createNamespace($namespaceName); } @@ -144,22 +114,20 @@ protected function _addTable(Table $table) } /** - * @param \Doctrine\DBAL\Schema\Sequence $sequence - * * @return void * - * @throws \Doctrine\DBAL\Schema\SchemaException + * @throws SchemaException */ protected function _addSequence(Sequence $sequence) { $namespaceName = $sequence->getNamespaceName(); - $seqName = $sequence->getFullQualifiedName($this->getName()); + $seqName = $sequence->getFullQualifiedName($this->getName()); if (isset($this->_sequences[$seqName])) { throw SchemaException::sequenceAlreadyExists($seqName); } - if ( ! $sequence->isInDefaultNamespace($this->getName()) && ! $this->hasNamespace($namespaceName)) { + if (! $sequence->isInDefaultNamespace($this->getName()) && ! $this->hasNamespace($namespaceName)) { $this->createNamespace($namespaceName); } @@ -169,7 +137,7 @@ protected function _addSequence(Sequence $sequence) /** * Returns the namespaces of this schema. * - * @return array A list of namespace names. + * @return string[] A list of namespace names. */ public function getNamespaces() { @@ -179,7 +147,7 @@ public function getNamespaces() /** * Gets all tables of this schema. * - * @return \Doctrine\DBAL\Schema\Table[] + * @return Table[] */ public function getTables() { @@ -189,14 +157,14 @@ public function getTables() /** * @param string $tableName * - * @return \Doctrine\DBAL\Schema\Table + * @return Table * - * @throws \Doctrine\DBAL\Schema\SchemaException + * @throws SchemaException */ public function getTable($tableName) { $tableName = $this->getFullQualifiedAssetName($tableName); - if (!isset($this->_tables[$tableName])) { + if (! isset($this->_tables[$tableName])) { throw SchemaException::tableDoesNotExist($tableName); } @@ -212,8 +180,8 @@ private function getFullQualifiedAssetName($name) { $name = $this->getUnquotedAssetName($name); - if (strpos($name, ".") === false) { - $name = $this->getName() . "." . $name; + if (strpos($name, '.') === false) { + $name = $this->getName() . '.' . $name; } return strtolower($name); @@ -266,7 +234,7 @@ public function hasTable($tableName) /** * Gets all table names, prefixed with a schema name, even the default one if present. * - * @return array + * @return string[] */ public function getTableNames() { @@ -288,14 +256,14 @@ public function hasSequence($sequenceName) /** * @param string $sequenceName * - * @return \Doctrine\DBAL\Schema\Sequence + * @return Sequence * - * @throws \Doctrine\DBAL\Schema\SchemaException + * @throws SchemaException */ public function getSequence($sequenceName) { $sequenceName = $this->getFullQualifiedAssetName($sequenceName); - if (!$this->hasSequence($sequenceName)) { + if (! $this->hasSequence($sequenceName)) { throw SchemaException::sequenceDoesNotExist($sequenceName); } @@ -303,7 +271,7 @@ public function getSequence($sequenceName) } /** - * @return \Doctrine\DBAL\Schema\Sequence[] + * @return Sequence[] */ public function getSequences() { @@ -337,7 +305,7 @@ public function createNamespace($namespaceName) * * @param string $tableName * - * @return \Doctrine\DBAL\Schema\Table + * @return Table */ public function createTable($tableName) { @@ -393,9 +361,9 @@ public function dropTable($tableName) * @param int $allocationSize * @param int $initialValue * - * @return \Doctrine\DBAL\Schema\Sequence + * @return Sequence */ - public function createSequence($sequenceName, $allocationSize=1, $initialValue=1) + public function createSequence($sequenceName, $allocationSize = 1, $initialValue = 1) { $seq = new Sequence($sequenceName, $allocationSize, $initialValue); $this->_addSequence($seq); @@ -419,9 +387,7 @@ public function dropSequence($sequenceName) /** * Returns an array of necessary SQL queries to create the schema on the given platform. * - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - * - * @return array + * @return string[] */ public function toSql(AbstractPlatform $platform) { @@ -434,9 +400,7 @@ public function toSql(AbstractPlatform $platform) /** * Return an array of necessary SQL queries to drop the schema on the given platform. * - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - * - * @return array + * @return string[] */ public function toDropSql(AbstractPlatform $platform) { @@ -447,10 +411,7 @@ public function toDropSql(AbstractPlatform $platform) } /** - * @param \Doctrine\DBAL\Schema\Schema $toSchema - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - * - * @return array + * @return string[] */ public function getMigrateToSql(Schema $toSchema, AbstractPlatform $platform) { @@ -461,10 +422,7 @@ public function getMigrateToSql(Schema $toSchema, AbstractPlatform $platform) } /** - * @param \Doctrine\DBAL\Schema\Schema $fromSchema - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - * - * @return array + * @return string[] */ public function getMigrateFromSql(Schema $fromSchema, AbstractPlatform $platform) { @@ -475,8 +433,6 @@ public function getMigrateFromSql(Schema $fromSchema, AbstractPlatform $platform } /** - * @param \Doctrine\DBAL\Schema\Visitor\Visitor $visitor - * * @return void */ public function visit(Visitor $visitor) diff --git a/lib/Doctrine/DBAL/Schema/SchemaConfig.php b/lib/Doctrine/DBAL/Schema/SchemaConfig.php index c8c7673bae2..b8c3502f758 100644 --- a/lib/Doctrine/DBAL/Schema/SchemaConfig.php +++ b/lib/Doctrine/DBAL/Schema/SchemaConfig.php @@ -1,51 +1,22 @@ . - */ namespace Doctrine\DBAL\Schema; /** * Configuration for a Schema. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ class SchemaConfig { - /** - * @var bool - */ + /** @var bool */ protected $hasExplicitForeignKeyIndexes = false; - /** - * @var int - */ + /** @var int */ protected $maxIdentifierLength = 63; - /** - * @var string - */ + /** @var string */ protected $name; - /** - * @var array - */ + /** @var mixed[] */ protected $defaultTableOptions = []; /** @@ -110,7 +81,7 @@ public function setName($name) * Gets the default options that are passed to Table instances created with * Schema#createTable(). * - * @return array + * @return mixed[] */ public function getDefaultTableOptions() { @@ -118,7 +89,7 @@ public function getDefaultTableOptions() } /** - * @param array $defaultTableOptions + * @param mixed[] $defaultTableOptions * * @return void */ diff --git a/lib/Doctrine/DBAL/Schema/SchemaDiff.php b/lib/Doctrine/DBAL/Schema/SchemaDiff.php index ec9ccba933d..0f2e25fb32b 100644 --- a/lib/Doctrine/DBAL/Schema/SchemaDiff.php +++ b/lib/Doctrine/DBAL/Schema/SchemaDiff.php @@ -1,41 +1,16 @@ . - */ namespace Doctrine\DBAL\Schema; -use \Doctrine\DBAL\Platforms\AbstractPlatform; +use Doctrine\DBAL\Platforms\AbstractPlatform; use function array_merge; /** * Schema Diff. - * - * @link www.doctrine-project.org - * @copyright Copyright (C) 2005-2009 eZ Systems AS. All rights reserved. - * @license http://ez.no/licenses/new_bsd New BSD License - * @since 2.0 - * @author Benjamin Eberlei */ class SchemaDiff { - /** - * @var \Doctrine\DBAL\Schema\Schema - */ + /** @var Schema */ public $fromSchema; /** @@ -55,53 +30,44 @@ class SchemaDiff /** * All added tables. * - * @var \Doctrine\DBAL\Schema\Table[] + * @var Table[] */ public $newTables = []; /** * All changed tables. * - * @var \Doctrine\DBAL\Schema\TableDiff[] + * @var TableDiff[] */ public $changedTables = []; /** * All removed tables. * - * @var \Doctrine\DBAL\Schema\Table[] + * @var Table[] */ public $removedTables = []; - /** - * @var \Doctrine\DBAL\Schema\Sequence[] - */ + /** @var Sequence[] */ public $newSequences = []; - /** - * @var \Doctrine\DBAL\Schema\Sequence[] - */ + /** @var Sequence[] */ public $changedSequences = []; - /** - * @var \Doctrine\DBAL\Schema\Sequence[] - */ + /** @var Sequence[] */ public $removedSequences = []; - /** - * @var \Doctrine\DBAL\Schema\ForeignKeyConstraint[] - */ + /** @var ForeignKeyConstraint[] */ public $orphanedForeignKeys = []; /** * Constructs an SchemaDiff object. * - * @param \Doctrine\DBAL\Schema\Table[] $newTables - * @param \Doctrine\DBAL\Schema\TableDiff[] $changedTables - * @param \Doctrine\DBAL\Schema\Table[] $removedTables - * @param \Doctrine\DBAL\Schema\Schema|null $fromSchema + * @param Table[] $newTables + * @param TableDiff[] $changedTables + * @param Table[] $removedTables */ - public function __construct($newTables = [], $changedTables = [], $removedTables = [], Schema $fromSchema = null) + public function __construct($newTables = [], $changedTables = [], $removedTables = [], ?Schema $fromSchema = null) { $this->newTables = $newTables; $this->changedTables = $changedTables; @@ -118,9 +84,7 @@ public function __construct($newTables = [], $changedTables = [], $removedTables * * This way it is ensured that assets are deleted which might not be relevant to the metadata schema at all. * - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - * - * @return array + * @return string[] */ public function toSaveSql(AbstractPlatform $platform) { @@ -128,9 +92,7 @@ public function toSaveSql(AbstractPlatform $platform) } /** - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - * - * @return array + * @return string[] */ public function toSql(AbstractPlatform $platform) { @@ -138,10 +100,9 @@ public function toSql(AbstractPlatform $platform) } /** - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - * @param bool $saveMode + * @param bool $saveMode * - * @return array + * @return string[] */ protected function _toSql(AbstractPlatform $platform, $saveMode = false) { @@ -153,13 +114,13 @@ protected function _toSql(AbstractPlatform $platform, $saveMode = false) } } - if ($platform->supportsForeignKeyConstraints() && $saveMode == false) { + if ($platform->supportsForeignKeyConstraints() && $saveMode === false) { foreach ($this->orphanedForeignKeys as $orphanedForeignKey) { $sql[] = $platform->getDropForeignKeySQL($orphanedForeignKey, $orphanedForeignKey->getLocalTable()); } } - if ($platform->supportsSequences() == true) { + if ($platform->supportsSequences() === true) { foreach ($this->changedSequences as $sequence) { $sql[] = $platform->getAlterSequenceSQL($sequence); } @@ -182,10 +143,12 @@ protected function _toSql(AbstractPlatform $platform, $saveMode = false) $platform->getCreateTableSQL($table, AbstractPlatform::CREATE_INDEXES) ); - if ($platform->supportsForeignKeyConstraints()) { - foreach ($table->getForeignKeys() as $foreignKey) { - $foreignKeySql[] = $platform->getCreateForeignKeySQL($foreignKey, $table); - } + if (! $platform->supportsForeignKeyConstraints()) { + continue; + } + + foreach ($table->getForeignKeys() as $foreignKey) { + $foreignKeySql[] = $platform->getCreateForeignKeySQL($foreignKey, $table); } } $sql = array_merge($sql, $foreignKeySql); diff --git a/lib/Doctrine/DBAL/Schema/SchemaException.php b/lib/Doctrine/DBAL/Schema/SchemaException.php index 7285d81cbf0..213d218475b 100644 --- a/lib/Doctrine/DBAL/Schema/SchemaException.php +++ b/lib/Doctrine/DBAL/Schema/SchemaException.php @@ -1,40 +1,24 @@ . - */ namespace Doctrine\DBAL\Schema; +use Doctrine\DBAL\DBALException; use function implode; use function sprintf; -class SchemaException extends \Doctrine\DBAL\DBALException +class SchemaException extends DBALException { - const TABLE_DOESNT_EXIST = 10; - const TABLE_ALREADY_EXISTS = 20; - const COLUMN_DOESNT_EXIST = 30; - const COLUMN_ALREADY_EXISTS = 40; - const INDEX_DOESNT_EXIST = 50; - const INDEX_ALREADY_EXISTS = 60; - const SEQUENCE_DOENST_EXIST = 70; - const SEQUENCE_ALREADY_EXISTS = 80; - const INDEX_INVALID_NAME = 90; - const FOREIGNKEY_DOESNT_EXIST = 100; - const NAMESPACE_ALREADY_EXISTS = 110; + public const TABLE_DOESNT_EXIST = 10; + public const TABLE_ALREADY_EXISTS = 20; + public const COLUMN_DOESNT_EXIST = 30; + public const COLUMN_ALREADY_EXISTS = 40; + public const INDEX_DOESNT_EXIST = 50; + public const INDEX_ALREADY_EXISTS = 60; + public const SEQUENCE_DOENST_EXIST = 70; + public const SEQUENCE_ALREADY_EXISTS = 80; + public const INDEX_INVALID_NAME = 90; + public const FOREIGNKEY_DOESNT_EXIST = 100; + public const NAMESPACE_ALREADY_EXISTS = 110; /** * @param string $tableName @@ -43,7 +27,7 @@ class SchemaException extends \Doctrine\DBAL\DBALException */ public static function tableDoesNotExist($tableName) { - return new self("There is no table with name '".$tableName."' in the schema.", self::TABLE_DOESNT_EXIST); + return new self("There is no table with name '" . $tableName . "' in the schema.", self::TABLE_DOESNT_EXIST); } /** @@ -53,7 +37,10 @@ public static function tableDoesNotExist($tableName) */ public static function indexNameInvalid($indexName) { - return new self("Invalid index-name $indexName given, has to be [a-zA-Z0-9_]", self::INDEX_INVALID_NAME); + return new self( + sprintf('Invalid index-name %s given, has to be [a-zA-Z0-9_]', $indexName), + self::INDEX_INVALID_NAME + ); } /** @@ -64,7 +51,10 @@ public static function indexNameInvalid($indexName) */ public static function indexDoesNotExist($indexName, $table) { - return new self("Index '$indexName' does not exist on table '$table'.", self::INDEX_DOESNT_EXIST); + return new self( + sprintf("Index '%s' does not exist on table '%s'.", $indexName, $table), + self::INDEX_DOESNT_EXIST + ); } /** @@ -75,7 +65,10 @@ public static function indexDoesNotExist($indexName, $table) */ public static function indexAlreadyExists($indexName, $table) { - return new self("An index with name '$indexName' was already defined on table '$table'.", self::INDEX_ALREADY_EXISTS); + return new self( + sprintf("An index with name '%s' was already defined on table '%s'.", $indexName, $table), + self::INDEX_ALREADY_EXISTS + ); } /** @@ -86,7 +79,10 @@ public static function indexAlreadyExists($indexName, $table) */ public static function columnDoesNotExist($columnName, $table) { - return new self("There is no column with name '$columnName' on table '$table'.", self::COLUMN_DOESNT_EXIST); + return new self( + sprintf("There is no column with name '%s' on table '%s'.", $columnName, $table), + self::COLUMN_DOESNT_EXIST + ); } /** @@ -109,7 +105,7 @@ public static function namespaceAlreadyExists($namespaceName) */ public static function tableAlreadyExists($tableName) { - return new self("The table with name '".$tableName."' already exists.", self::TABLE_ALREADY_EXISTS); + return new self("The table with name '" . $tableName . "' already exists.", self::TABLE_ALREADY_EXISTS); } /** @@ -121,7 +117,8 @@ public static function tableAlreadyExists($tableName) public static function columnAlreadyExists($tableName, $columnName) { return new self( - "The column '".$columnName."' on table '".$tableName."' already exists.", self::COLUMN_ALREADY_EXISTS + "The column '" . $columnName . "' on table '" . $tableName . "' already exists.", + self::COLUMN_ALREADY_EXISTS ); } @@ -132,7 +129,7 @@ public static function columnAlreadyExists($tableName, $columnName) */ public static function sequenceAlreadyExists($sequenceName) { - return new self("The sequence '".$sequenceName."' already exists.", self::SEQUENCE_ALREADY_EXISTS); + return new self("The sequence '" . $sequenceName . "' already exists.", self::SEQUENCE_ALREADY_EXISTS); } /** @@ -142,7 +139,7 @@ public static function sequenceAlreadyExists($sequenceName) */ public static function sequenceDoesNotExist($sequenceName) { - return new self("There exists no sequence with the name '".$sequenceName."'.", self::SEQUENCE_DOENST_EXIST); + return new self("There exists no sequence with the name '" . $sequenceName . "'.", self::SEQUENCE_DOENST_EXIST); } /** @@ -153,22 +150,22 @@ public static function sequenceDoesNotExist($sequenceName) */ public static function foreignKeyDoesNotExist($fkName, $table) { - return new self("There exists no foreign key with the name '$fkName' on table '$table'.", self::FOREIGNKEY_DOESNT_EXIST); + return new self( + sprintf("There exists no foreign key with the name '%s' on table '%s'.", $fkName, $table), + self::FOREIGNKEY_DOESNT_EXIST + ); } /** - * @param \Doctrine\DBAL\Schema\Table $localTable - * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey - * * @return \Doctrine\DBAL\Schema\SchemaException */ public static function namedForeignKeyRequired(Table $localTable, ForeignKeyConstraint $foreignKey) { return new self( - "The performed schema operation on ".$localTable->getName()." requires a named foreign key, ". - "but the given foreign key from (".implode(", ", $foreignKey->getColumns()).") onto foreign table ". - "'".$foreignKey->getForeignTableName()."' (".implode(", ", $foreignKey->getForeignColumns()).") is currently ". - "unnamed." + 'The performed schema operation on ' . $localTable->getName() . ' requires a named foreign key, ' . + 'but the given foreign key from (' . implode(', ', $foreignKey->getColumns()) . ') onto foreign table ' . + "'" . $foreignKey->getForeignTableName() . "' (" . implode(', ', $foreignKey->getForeignColumns()) . ') is currently ' . + 'unnamed.' ); } @@ -179,6 +176,8 @@ public static function namedForeignKeyRequired(Table $localTable, ForeignKeyCons */ public static function alterTableChangeNotSupported($changeName) { - return new self("Alter table change not supported, given '$changeName'"); + return new self( + sprintf("Alter table change not supported, given '%s'", $changeName) + ); } } diff --git a/lib/Doctrine/DBAL/Schema/Sequence.php b/lib/Doctrine/DBAL/Schema/Sequence.php index 6d304cde4b6..24cf4aae0b4 100644 --- a/lib/Doctrine/DBAL/Schema/Sequence.php +++ b/lib/Doctrine/DBAL/Schema/Sequence.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Schema; @@ -26,26 +9,16 @@ /** * Sequence structure. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ class Sequence extends AbstractAsset { - /** - * @var int - */ + /** @var int */ protected $allocationSize = 1; - /** - * @var int - */ + /** @var int */ protected $initialValue = 1; - /** - * @var int|null - */ + /** @var int|null */ protected $cache = null; /** @@ -57,9 +30,9 @@ class Sequence extends AbstractAsset public function __construct($name, $allocationSize = 1, $initialValue = 1, $cache = null) { $this->_setName($name); - $this->allocationSize = is_numeric($allocationSize) ? $allocationSize : 1; - $this->initialValue = is_numeric($initialValue) ? $initialValue : 1; - $this->cache = $cache; + $this->setAllocationSize($allocationSize); + $this->setInitialValue($initialValue); + $this->cache = $cache; } /** @@ -93,7 +66,7 @@ public function getCache() */ public function setAllocationSize($allocationSize) { - $this->allocationSize = is_numeric($allocationSize) ? $allocationSize : 1; + $this->allocationSize = is_numeric($allocationSize) ? (int) $allocationSize : 1; return $this; } @@ -105,7 +78,7 @@ public function setAllocationSize($allocationSize) */ public function setInitialValue($initialValue) { - $this->initialValue = is_numeric($initialValue) ? $initialValue : 1; + $this->initialValue = is_numeric($initialValue) ? (int) $initialValue : 1; return $this; } @@ -128,25 +101,23 @@ public function setCache($cache) * This is used inside the comparator to not report sequences as missing, * when the "from" schema implicitly creates the sequences. * - * @param \Doctrine\DBAL\Schema\Table $table - * * @return bool */ public function isAutoIncrementsFor(Table $table) { - if ( ! $table->hasPrimaryKey()) { + if (! $table->hasPrimaryKey()) { return false; } $pkColumns = $table->getPrimaryKey()->getColumns(); - if (count($pkColumns) != 1) { + if (count($pkColumns) !== 1) { return false; } $column = $table->getColumn($pkColumns[0]); - if ( ! $column->getAutoincrement()) { + if (! $column->getAutoincrement()) { return false; } @@ -158,8 +129,6 @@ public function isAutoIncrementsFor(Table $table) } /** - * @param \Doctrine\DBAL\Schema\Visitor\Visitor $visitor - * * @return void */ public function visit(Visitor $visitor) diff --git a/lib/Doctrine/DBAL/Schema/SqliteSchemaManager.php b/lib/Doctrine/DBAL/Schema/SqliteSchemaManager.php index dbe0cc2d563..744acedabb5 100644 --- a/lib/Doctrine/DBAL/Schema/SqliteSchemaManager.php +++ b/lib/Doctrine/DBAL/Schema/SqliteSchemaManager.php @@ -1,25 +1,9 @@ . - */ namespace Doctrine\DBAL\Schema; use Doctrine\DBAL\DBALException; +use Doctrine\DBAL\DriverManager; use Doctrine\DBAL\FetchMode; use Doctrine\DBAL\Types\StringType; use Doctrine\DBAL\Types\TextType; @@ -46,12 +30,6 @@ /** * Sqlite SchemaManager. - * - * @author Konsta Vesterinen - * @author Lukas Smith (PEAR MDB2 library) - * @author Jonathan H. Wage - * @author Martin Hasoň - * @since 2.0 */ class SqliteSchemaManager extends AbstractSchemaManager { @@ -60,9 +38,11 @@ class SqliteSchemaManager extends AbstractSchemaManager */ public function dropDatabase($database) { - if (file_exists($database)) { - unlink($database); + if (! file_exists($database)) { + return; } + + unlink($database); } /** @@ -70,13 +50,13 @@ public function dropDatabase($database) */ public function createDatabase($database) { - $params = $this->_conn->getParams(); - $driver = $params['driver']; + $params = $this->_conn->getParams(); + $driver = $params['driver']; $options = [ 'driver' => $driver, - 'path' => $database + 'path' => $database, ]; - $conn = \Doctrine\DBAL\DriverManager::getConnection($options); + $conn = DriverManager::getConnection($options); $conn->connect(); $conn->close(); } @@ -86,9 +66,9 @@ public function createDatabase($database) */ public function renameTable($name, $newName) { - $tableDiff = new TableDiff($name); + $tableDiff = new TableDiff($name); $tableDiff->fromTable = $this->listTableDetails($name); - $tableDiff->newName = $newName; + $tableDiff->newName = $newName; $this->alterTable($tableDiff); } @@ -97,7 +77,7 @@ public function renameTable($name, $newName) */ public function createForeignKey(ForeignKeyConstraint $foreignKey, $table) { - $tableDiff = $this->getTableDiffForAlterForeignKey($foreignKey, $table); + $tableDiff = $this->getTableDiffForAlterForeignKey($foreignKey, $table); $tableDiff->addedForeignKeys[] = $foreignKey; $this->alterTable($tableDiff); @@ -108,7 +88,7 @@ public function createForeignKey(ForeignKeyConstraint $foreignKey, $table) */ public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table) { - $tableDiff = $this->getTableDiffForAlterForeignKey($foreignKey, $table); + $tableDiff = $this->getTableDiffForAlterForeignKey($foreignKey, $table); $tableDiff->changedForeignKeys[] = $foreignKey; $this->alterTable($tableDiff); @@ -119,7 +99,7 @@ public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table */ public function dropForeignKey($foreignKey, $table) { - $tableDiff = $this->getTableDiffForAlterForeignKey($foreignKey, $table); + $tableDiff = $this->getTableDiffForAlterForeignKey($foreignKey, $table); $tableDiff->removedForeignKeys[] = $foreignKey; $this->alterTable($tableDiff); @@ -130,17 +110,17 @@ public function dropForeignKey($foreignKey, $table) */ public function listTableForeignKeys($table, $database = null) { - if (null === $database) { + if ($database === null) { $database = $this->_conn->getDatabase(); } - $sql = $this->_platform->getListTableForeignKeysSQL($table, $database); + $sql = $this->_platform->getListTableForeignKeysSQL($table, $database); $tableForeignKeys = $this->_conn->fetchAll($sql); - if ( ! empty($tableForeignKeys)) { - $createSql = $this->_conn->fetchAll("SELECT sql FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type = 'table' AND name = '$table'"); - $createSql = $createSql[0]['sql'] ?? ''; + if (! empty($tableForeignKeys)) { + $createSql = $this->getCreateTableSQL($table); - if (preg_match_all('# + if ($createSql !== null && preg_match_all( + '# (?:CONSTRAINT\s+([^\s]+)\s+)? (?:FOREIGN\s+KEY[^\)]+\)\s*)? REFERENCES\s+[^\s]+\s+(?:\([^\)]+\))? @@ -149,18 +129,19 @@ public function listTableForeignKeys($table, $database = null) (NOT\s+DEFERRABLE|DEFERRABLE) (?:\s+INITIALLY\s+(DEFERRED|IMMEDIATE))? )?#isx', - $createSql, $match)) { - - $names = array_reverse($match[1]); + $createSql, + $match + )) { + $names = array_reverse($match[1]); $deferrable = array_reverse($match[2]); - $deferred = array_reverse($match[3]); + $deferred = array_reverse($match[3]); } else { $names = $deferrable = $deferred = []; } foreach ($tableForeignKeys as $key => $value) { - $id = $value['id']; - $tableForeignKeys[$key]['constraint_name'] = isset($names[$id]) && '' != $names[$id] ? $names[$id] : $id; + $id = $value['id']; + $tableForeignKeys[$key]['constraint_name'] = isset($names[$id]) && $names[$id] !== '' ? $names[$id] : $id; $tableForeignKeys[$key]['deferrable'] = isset($deferrable[$id]) && strtolower($deferrable[$id]) === 'deferrable'; $tableForeignKeys[$key]['deferred'] = isset($deferred[$id]) && strtolower($deferred[$id]) === 'deferred'; } @@ -180,52 +161,61 @@ protected function _getPortableTableDefinition($table) /** * {@inheritdoc} * - * @license New BSD License * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html */ - protected function _getPortableTableIndexesList($tableIndexes, $tableName=null) + protected function _getPortableTableIndexesList($tableIndexes, $tableName = null) { $indexBuffer = []; // fetch primary - $stmt = $this->_conn->executeQuery("PRAGMA TABLE_INFO ('$tableName')"); + $stmt = $this->_conn->executeQuery(sprintf( + 'PRAGMA TABLE_INFO (%s)', + $this->_conn->quote($tableName) + )); $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE); - usort($indexArray, function($a, $b) { - if ($a['pk'] == $b['pk']) { + usort($indexArray, static function ($a, $b) { + if ($a['pk'] === $b['pk']) { return $a['cid'] - $b['cid']; } return $a['pk'] - $b['pk']; }); foreach ($indexArray as $indexColumnRow) { - if ($indexColumnRow['pk'] != "0") { - $indexBuffer[] = [ - 'key_name' => 'primary', - 'primary' => true, - 'non_unique' => false, - 'column_name' => $indexColumnRow['name'] - ]; + if ($indexColumnRow['pk'] === '0') { + continue; } + + $indexBuffer[] = [ + 'key_name' => 'primary', + 'primary' => true, + 'non_unique' => false, + 'column_name' => $indexColumnRow['name'], + ]; } // fetch regular indexes foreach ($tableIndexes as $tableIndex) { // Ignore indexes with reserved names, e.g. autoindexes - if (strpos($tableIndex['name'], 'sqlite_') !== 0) { - $keyName = $tableIndex['name']; - $idx = []; - $idx['key_name'] = $keyName; - $idx['primary'] = false; - $idx['non_unique'] = $tableIndex['unique']?false:true; - - $stmt = $this->_conn->executeQuery("PRAGMA INDEX_INFO ('{$keyName}')"); + if (strpos($tableIndex['name'], 'sqlite_') === 0) { + continue; + } + + $keyName = $tableIndex['name']; + $idx = []; + $idx['key_name'] = $keyName; + $idx['primary'] = false; + $idx['non_unique'] = $tableIndex['unique']?false:true; + + $stmt = $this->_conn->executeQuery(sprintf( + 'PRAGMA INDEX_INFO (%s)', + $this->_conn->quote($keyName) + )); $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE); - foreach ($indexArray as $indexColumnRow) { - $idx['column_name'] = $indexColumnRow['name']; - $indexBuffer[] = $idx; - } + foreach ($indexArray as $indexColumnRow) { + $idx['column_name'] = $indexColumnRow['name']; + $indexBuffer[] = $idx; } } @@ -239,7 +229,7 @@ protected function _getPortableTableIndexDefinition($tableIndex) { return [ 'name' => $tableIndex['name'], - 'unique' => (bool) $tableIndex['unique'] + 'unique' => (bool) $tableIndex['unique'], ]; } @@ -252,28 +242,33 @@ protected function _getPortableTableColumnList($table, $database, $tableColumns) // find column with autoincrement $autoincrementColumn = null; - $autoincrementCount = 0; + $autoincrementCount = 0; foreach ($tableColumns as $tableColumn) { - if ('0' != $tableColumn['pk']) { - $autoincrementCount++; - if (null === $autoincrementColumn && 'integer' == strtolower($tableColumn['type'])) { - $autoincrementColumn = $tableColumn['name']; - } + if ($tableColumn['pk'] === '0') { + continue; } + + $autoincrementCount++; + if ($autoincrementColumn !== null || strtolower($tableColumn['type']) !== 'integer') { + continue; + } + + $autoincrementColumn = $tableColumn['name']; } - if (1 == $autoincrementCount && null !== $autoincrementColumn) { + if ($autoincrementCount === 1 && $autoincrementColumn !== null) { foreach ($list as $column) { - if ($autoincrementColumn == $column->getName()) { - $column->setAutoincrement(true); + if ($autoincrementColumn !== $column->getName()) { + continue; } + + $column->setAutoincrement(true); } } // inspect column collation and comments - $createSql = $this->_conn->fetchAll("SELECT sql FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type = 'table' AND name = '$table'"); - $createSql = $createSql[0]['sql'] ?? ''; + $createSql = $this->getCreateTableSQL($table) ?? ''; foreach ($list as $columnName => $column) { $type = $column->getType(); @@ -284,17 +279,19 @@ protected function _getPortableTableColumnList($table, $database, $tableColumns) $comment = $this->parseColumnCommentFromSQL($columnName, $createSql); - if ($comment !== null) { - $type = $this->extractDoctrineTypeFromComment($comment, null); + if ($comment === null) { + continue; + } - if (null !== $type) { - $column->setType(Type::getType($type)); + $type = $this->extractDoctrineTypeFromComment($comment, null); - $comment = $this->removeDoctrineTypeFromComment($comment, $type); - } + if ($type !== null) { + $column->setType(Type::getType($type)); - $column->setComment($comment); + $comment = $this->removeDoctrineTypeFromComment($comment, $type); } + + $column->setComment($comment); } return $list; @@ -305,10 +302,10 @@ protected function _getPortableTableColumnList($table, $database, $tableColumns) */ protected function _getPortableTableColumnDefinition($tableColumn) { - $parts = explode('(', $tableColumn['type']); + $parts = explode('(', $tableColumn['type']); $tableColumn['type'] = trim($parts[0]); if (isset($parts[1])) { - $length = trim($parts[1], ')'); + $length = trim($parts[1], ')'); $tableColumn['length'] = $length; } @@ -317,14 +314,14 @@ protected function _getPortableTableColumnDefinition($tableColumn) $unsigned = false; if (strpos($dbType, ' unsigned') !== false) { - $dbType = str_replace(' unsigned', '', $dbType); + $dbType = str_replace(' unsigned', '', $dbType); $unsigned = true; } - $fixed = false; - $type = $this->_platform->getDoctrineTypeMapping($dbType); + $fixed = false; + $type = $this->_platform->getDoctrineTypeMapping($dbType); $default = $tableColumn['dflt_value']; - if ($default == 'NULL') { + if ($default === 'NULL') { $default = null; } if ($default !== null) { @@ -333,12 +330,12 @@ protected function _getPortableTableColumnDefinition($tableColumn) } $notnull = (bool) $tableColumn['notnull']; - if ( ! isset($tableColumn['name'])) { + if (! isset($tableColumn['name'])) { $tableColumn['name'] = ''; } $precision = null; - $scale = null; + $scale = null; switch ($dbType) { case 'char': @@ -351,9 +348,9 @@ protected function _getPortableTableColumnDefinition($tableColumn) case 'numeric': if (isset($tableColumn['length'])) { if (strpos($tableColumn['length'], ',') === false) { - $tableColumn['length'] .= ",0"; + $tableColumn['length'] .= ',0'; } - list($precision, $scale) = array_map('trim', explode(',', $tableColumn['length'])); + [$precision, $scale] = array_map('trim', explode(',', $tableColumn['length'])); } $length = null; break; @@ -370,7 +367,7 @@ protected function _getPortableTableColumnDefinition($tableColumn) 'autoincrement' => false, ]; - return new Column($tableColumn['name'], \Doctrine\DBAL\Types\Type::getType($type), $options); + return new Column($tableColumn['name'], Type::getType($type), $options); } /** @@ -389,12 +386,12 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys) $list = []; foreach ($tableForeignKeys as $value) { $value = array_change_key_case($value, CASE_LOWER); - $name = $value['constraint_name']; - if ( ! isset($list[$name])) { - if ( ! isset($value['on_delete']) || $value['on_delete'] == "RESTRICT") { + $name = $value['constraint_name']; + if (! isset($list[$name])) { + if (! isset($value['on_delete']) || $value['on_delete'] === 'RESTRICT') { $value['on_delete'] = null; } - if ( ! isset($value['on_update']) || $value['on_update'] == "RESTRICT") { + if (! isset($value['on_update']) || $value['on_update'] === 'RESTRICT') { $value['on_update'] = null; } @@ -409,15 +406,17 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys) 'deferred'=> $value['deferred'], ]; } - $list[$name]['local'][] = $value['from']; + $list[$name]['local'][] = $value['from']; $list[$name]['foreign'][] = $value['to']; } $result = []; foreach ($list as $constraint) { $result[] = new ForeignKeyConstraint( - array_values($constraint['local']), $constraint['foreignTable'], - array_values($constraint['foreign']), $constraint['name'], + array_values($constraint['local']), + $constraint['foreignTable'], + array_values($constraint['foreign']), + $constraint['name'], [ 'onDelete' => $constraint['onDelete'], 'onUpdate' => $constraint['onUpdate'], @@ -431,25 +430,24 @@ protected function _getPortableTableForeignKeysList($tableForeignKeys) } /** - * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey - * @param \Doctrine\DBAL\Schema\Table|string $table + * @param Table|string $table * - * @return \Doctrine\DBAL\Schema\TableDiff + * @return TableDiff * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ private function getTableDiffForAlterForeignKey(ForeignKeyConstraint $foreignKey, $table) { - if ( ! $table instanceof Table) { + if (! $table instanceof Table) { $tableDetails = $this->tryMethod('listTableDetails', $table); - if (false === $table) { + if ($table === false) { throw new DBALException(sprintf('Sqlite schema manager requires to modify foreign keys table definition "%s".', $table)); } $table = $tableDetails; } - $tableDiff = new TableDiff($table->getName()); + $tableDiff = new TableDiff($table->getName()); $tableDiff->fromTable = $table; return $tableDiff; @@ -478,6 +476,26 @@ private function parseColumnCommentFromSQL(string $column, string $sql) : ?strin $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n")); - return '' === $comment ? null : $comment; + return $comment === '' ? null : $comment; + } + + private function getCreateTableSQL(string $table) : ?string + { + return $this->_conn->fetchColumn( + <<<'SQL' +SELECT sql + FROM ( + SELECT * + FROM sqlite_master + UNION ALL + SELECT * + FROM sqlite_temp_master + ) +WHERE type = 'table' +AND name = ? +SQL + , + [$table] + ) ?: null; } } diff --git a/lib/Doctrine/DBAL/Schema/Synchronizer/AbstractSchemaSynchronizer.php b/lib/Doctrine/DBAL/Schema/Synchronizer/AbstractSchemaSynchronizer.php index 3158df47de1..b597b8db9b2 100644 --- a/lib/Doctrine/DBAL/Schema/Synchronizer/AbstractSchemaSynchronizer.php +++ b/lib/Doctrine/DBAL/Schema/Synchronizer/AbstractSchemaSynchronizer.php @@ -1,60 +1,38 @@ . - */ namespace Doctrine\DBAL\Schema\Synchronizer; use Doctrine\DBAL\Connection; +use Throwable; /** * Abstract schema synchronizer with methods for executing batches of SQL. */ abstract class AbstractSchemaSynchronizer implements SchemaSynchronizer { - /** - * @var \Doctrine\DBAL\Connection - */ + /** @var Connection */ protected $conn; - /** - * @param \Doctrine\DBAL\Connection $conn - */ public function __construct(Connection $conn) { $this->conn = $conn; } /** - * @param array $sql + * @param string[] $sql */ protected function processSqlSafely(array $sql) { foreach ($sql as $s) { try { $this->conn->exec($s); - } catch (\Exception $e) { - + } catch (Throwable $e) { } } } /** - * @param array $sql + * @param string[] $sql */ protected function processSql(array $sql) { diff --git a/lib/Doctrine/DBAL/Schema/Synchronizer/SchemaSynchronizer.php b/lib/Doctrine/DBAL/Schema/Synchronizer/SchemaSynchronizer.php index b65efbbb99f..3e7beea7508 100644 --- a/lib/Doctrine/DBAL/Schema/Synchronizer/SchemaSynchronizer.php +++ b/lib/Doctrine/DBAL/Schema/Synchronizer/SchemaSynchronizer.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Schema\Synchronizer; @@ -24,78 +7,66 @@ /** * The synchronizer knows how to synchronize a schema with the configured * database. - * - * @author Benjamin Eberlei */ interface SchemaSynchronizer { /** * Gets the SQL statements that can be executed to create the schema. * - * @param \Doctrine\DBAL\Schema\Schema $createSchema - * - * @return array + * @return string[] */ - function getCreateSchema(Schema $createSchema); + public function getCreateSchema(Schema $createSchema); /** * Gets the SQL Statements to update given schema with the underlying db. * - * @param \Doctrine\DBAL\Schema\Schema $toSchema - * @param bool $noDrops + * @param bool $noDrops * - * @return array + * @return string[] */ - function getUpdateSchema(Schema $toSchema, $noDrops = false); + public function getUpdateSchema(Schema $toSchema, $noDrops = false); /** * Gets the SQL Statements to drop the given schema from underlying db. * - * @param \Doctrine\DBAL\Schema\Schema $dropSchema - * - * @return array + * @return string[] */ - function getDropSchema(Schema $dropSchema); + public function getDropSchema(Schema $dropSchema); /** * Gets the SQL statements to drop all schema assets from underlying db. * - * @return array + * @return string[] */ - function getDropAllSchema(); + public function getDropAllSchema(); /** * Creates the Schema. * - * @param \Doctrine\DBAL\Schema\Schema $createSchema - * * @return void */ - function createSchema(Schema $createSchema); + public function createSchema(Schema $createSchema); /** * Updates the Schema to new schema version. * - * @param \Doctrine\DBAL\Schema\Schema $toSchema - * @param bool $noDrops + * @param bool $noDrops * * @return void */ - function updateSchema(Schema $toSchema, $noDrops = false); + public function updateSchema(Schema $toSchema, $noDrops = false); /** * Drops the given database schema from the underlying db. * - * @param \Doctrine\DBAL\Schema\Schema $dropSchema - * * @return void */ - function dropSchema(Schema $dropSchema); + public function dropSchema(Schema $dropSchema); /** * Drops all assets from the underlying db. * * @return void */ - function dropAllSchema(); + public function dropAllSchema(); } diff --git a/lib/Doctrine/DBAL/Schema/Synchronizer/SingleDatabaseSynchronizer.php b/lib/Doctrine/DBAL/Schema/Synchronizer/SingleDatabaseSynchronizer.php index f22607e6b96..e51b27f3726 100644 --- a/lib/Doctrine/DBAL/Schema/Synchronizer/SingleDatabaseSynchronizer.php +++ b/lib/Doctrine/DBAL/Schema/Synchronizer/SingleDatabaseSynchronizer.php @@ -1,45 +1,22 @@ . - */ namespace Doctrine\DBAL\Schema\Synchronizer; use Doctrine\DBAL\Connection; -use Doctrine\DBAL\Schema\Schema; +use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Schema\Comparator; +use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Visitor\DropSchemaSqlCollector; use function count; /** * Schema Synchronizer for Default DBAL Connection. - * - * @author Benjamin Eberlei */ class SingleDatabaseSynchronizer extends AbstractSchemaSynchronizer { - /** - * @var \Doctrine\DBAL\Platforms\AbstractPlatform - */ + /** @var AbstractPlatform */ private $platform; - /** - * @param \Doctrine\DBAL\Connection $conn - */ public function __construct(Connection $conn) { parent::__construct($conn); @@ -78,8 +55,8 @@ public function getUpdateSchema(Schema $toSchema, $noDrops = false) */ public function getDropSchema(Schema $dropSchema) { - $visitor = new DropSchemaSqlCollector($this->platform); - $sm = $this->conn->getSchemaManager(); + $visitor = new DropSchemaSqlCollector($this->platform); + $sm = $this->conn->getSchemaManager(); $fullSchema = $sm->createSchema(); @@ -89,11 +66,11 @@ public function getDropSchema(Schema $dropSchema) } foreach ($table->getForeignKeys() as $foreignKey) { - if ( ! $dropSchema->hasTable($table->getName())) { + if (! $dropSchema->hasTable($table->getName())) { continue; } - if ( ! $dropSchema->hasTable($foreignKey->getForeignTableName())) { + if (! $dropSchema->hasTable($foreignKey->getForeignTableName())) { continue; } @@ -101,7 +78,7 @@ public function getDropSchema(Schema $dropSchema) } } - if ( ! $this->platform->supportsSequences()) { + if (! $this->platform->supportsSequences()) { return $visitor->getQueries(); } @@ -110,7 +87,7 @@ public function getDropSchema(Schema $dropSchema) } foreach ($dropSchema->getTables() as $table) { - if ( ! $table->hasPrimaryKey()) { + if (! $table->hasPrimaryKey()) { continue; } @@ -119,10 +96,12 @@ public function getDropSchema(Schema $dropSchema) continue; } - $checkSequence = $table->getName() . "_" . $columns[0] . "_seq"; - if ($fullSchema->hasSequence($checkSequence)) { - $visitor->acceptSequence($fullSchema->getSequence($checkSequence)); + $checkSequence = $table->getName() . '_' . $columns[0] . '_seq'; + if (! $fullSchema->hasSequence($checkSequence)) { + continue; } + + $visitor->acceptSequence($fullSchema->getSequence($checkSequence)); } return $visitor->getQueries(); @@ -136,8 +115,7 @@ public function getDropAllSchema() $sm = $this->conn->getSchemaManager(); $visitor = new DropSchemaSqlCollector($this->platform); - /* @var $schema \Doctrine\DBAL\Schema\Schema */ - $schema = $sm->createSchema(); + $schema = $sm->createSchema(); $schema->visit($visitor); return $visitor->getQueries(); diff --git a/lib/Doctrine/DBAL/Schema/Table.php b/lib/Doctrine/DBAL/Schema/Table.php index bc7f8197908..5dac5bb1a34 100644 --- a/lib/Doctrine/DBAL/Schema/Table.php +++ b/lib/Doctrine/DBAL/Schema/Table.php @@ -1,27 +1,10 @@ . - */ namespace Doctrine\DBAL\Schema; -use Doctrine\DBAL\Types\Type; -use Doctrine\DBAL\Schema\Visitor\Visitor; use Doctrine\DBAL\DBALException; +use Doctrine\DBAL\Schema\Visitor\Visitor; +use Doctrine\DBAL\Types\Type; use const ARRAY_FILTER_USE_KEY; use function array_filter; use function array_merge; @@ -34,51 +17,31 @@ /** * Object Representation of a table. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ class Table extends AbstractAsset { - /** - * @var string - */ + /** @var string */ protected $_name = null; - /** - * @var Column[] - */ + /** @var Column[] */ protected $_columns = []; - /** - * @var Index[] - */ + /** @var Index[] */ private $implicitIndexes = []; - /** - * @var Index[] - */ + /** @var Index[] */ protected $_indexes = []; - /** - * @var string - */ + /** @var string */ protected $_primaryKeyName = false; - /** - * @var ForeignKeyConstraint[] - */ + /** @var ForeignKeyConstraint[] */ protected $_fkConstraints = []; - /** - * @var array - */ + /** @var mixed[] */ protected $_options = []; - /** - * @var SchemaConfig|null - */ + /** @var SchemaConfig|null */ protected $_schemaConfig = null; /** @@ -87,13 +50,13 @@ class Table extends AbstractAsset * @param Index[] $indexes * @param ForeignKeyConstraint[] $fkConstraints * @param int $idGeneratorType - * @param array $options + * @param mixed[] $options * * @throws DBALException */ - public function __construct($tableName, array $columns=[], array $indexes=[], array $fkConstraints=[], $idGeneratorType = 0, array $options=[]) + public function __construct($tableName, array $columns = [], array $indexes = [], array $fkConstraints = [], $idGeneratorType = 0, array $options = []) { - if (strlen($tableName) == 0) { + if (strlen($tableName) === 0) { throw DBALException::invalidTableName($tableName); } @@ -115,8 +78,6 @@ public function __construct($tableName, array $columns=[], array $indexes=[], ar } /** - * @param SchemaConfig $schemaConfig - * * @return void */ public function setSchemaConfig(SchemaConfig $schemaConfig) @@ -139,14 +100,14 @@ protected function _getMaxIdentifierLength() /** * Sets the Primary Key. * - * @param array $columns - * @param string|boolean $indexName + * @param mixed[][] $columns + * @param string|bool $indexName * * @return self */ public function setPrimaryKey(array $columns, $indexName = false) { - $this->_addIndex($this->_createIndex($columns, $indexName ?: "primary", true, true)); + $this->_addIndex($this->_createIndex($columns, $indexName ?: 'primary', true, true)); foreach ($columns as $columnName) { $column = $this->getColumn($columnName); @@ -157,18 +118,20 @@ public function setPrimaryKey(array $columns, $indexName = false) } /** - * @param array $columnNames + * @param mixed[][] $columnNames * @param string|null $indexName - * @param array $flags - * @param array $options + * @param string[] $flags + * @param mixed[] $options * * @return self */ public function addIndex(array $columnNames, $indexName = null, array $flags = [], array $options = []) { - if ($indexName == null) { + if ($indexName === null) { $indexName = $this->_generateIdentifierName( - array_merge([$this->getName()], $columnNames), "idx", $this->_getMaxIdentifierLength() + array_merge([$this->getName()], $columnNames), + 'idx', + $this->_getMaxIdentifierLength() ); } @@ -198,16 +161,16 @@ public function dropPrimaryKey() public function dropIndex($indexName) { $indexName = $this->normalizeIdentifier($indexName); - if ( ! $this->hasIndex($indexName)) { + if (! $this->hasIndex($indexName)) { throw SchemaException::indexDoesNotExist($indexName, $this->_name); } unset($this->_indexes[$indexName]); } /** - * @param array $columnNames + * @param mixed[][] $columnNames * @param string|null $indexName - * @param array $options + * @param mixed[] $options * * @return self */ @@ -215,7 +178,9 @@ public function addUniqueIndex(array $columnNames, $indexName = null, array $opt { if ($indexName === null) { $indexName = $this->_generateIdentifierName( - array_merge([$this->getName()], $columnNames), "uniq", $this->_getMaxIdentifierLength() + array_merge([$this->getName()], $columnNames), + 'uniq', + $this->_getMaxIdentifierLength() ); } @@ -231,7 +196,7 @@ public function addUniqueIndex(array $columnNames, $indexName = null, array $opt * * @return self This table instance. * - * @throws SchemaException if no index exists for the given current name + * @throws SchemaException If no index exists for the given current name * or if an index with the given new name already exists on this table. */ public function renameIndex($oldIndexName, $newIndexName = null) @@ -243,7 +208,7 @@ public function renameIndex($oldIndexName, $newIndexName = null) return $this; } - if ( ! $this->hasIndex($oldIndexName)) { + if (! $this->hasIndex($oldIndexName)) { throw SchemaException::indexDoesNotExist($oldIndexName, $this->_name); } @@ -271,14 +236,14 @@ public function renameIndex($oldIndexName, $newIndexName = null) /** * Checks if an index begins in the order of the given columns. * - * @param array $columnsNames + * @param mixed[][] $columnsNames * * @return bool */ public function columnsAreIndexed(array $columnsNames) { foreach ($this->getIndexes() as $index) { - /* @var $index Index */ + /** @var $index Index */ if ($index->spansColumns($columnsNames)) { return true; } @@ -288,12 +253,12 @@ public function columnsAreIndexed(array $columnsNames) } /** - * @param array $columnNames - * @param string $indexName - * @param bool $isUnique - * @param bool $isPrimary - * @param array $flags - * @param array $options + * @param mixed[][] $columnNames + * @param string $indexName + * @param bool $isUnique + * @param bool $isPrimary + * @param string[] $flags + * @param mixed[] $options * * @return Index * @@ -310,7 +275,7 @@ private function _createIndex(array $columnNames, $indexName, $isUnique, $isPrim $columnName = $indexColOptions; } - if ( ! $this->hasColumn($columnName)) { + if (! $this->hasColumn($columnName)) { throw SchemaException::columnDoesNotExist($columnName, $this->_name); } } @@ -319,13 +284,13 @@ private function _createIndex(array $columnNames, $indexName, $isUnique, $isPrim } /** - * @param string $columnName - * @param string $typeName - * @param array $options + * @param string $columnName + * @param string $typeName + * @param mixed[] $options * * @return Column */ - public function addColumn($columnName, $typeName, array $options=[]) + public function addColumn($columnName, $typeName, array $options = []) { $column = new Column($columnName, Type::getType($typeName), $options); @@ -337,25 +302,25 @@ public function addColumn($columnName, $typeName, array $options=[]) /** * Renames a Column. * + * @deprecated + * * @param string $oldColumnName * @param string $newColumnName * - * @deprecated - * * @throws DBALException */ public function renameColumn($oldColumnName, $newColumnName) { - throw new DBALException("Table#renameColumn() was removed, because it drops and recreates " . - "the column instead. There is no fix available, because a schema diff cannot reliably detect if a " . - "column was renamed or one column was created and another one dropped."); + throw new DBALException('Table#renameColumn() was removed, because it drops and recreates ' . + 'the column instead. There is no fix available, because a schema diff cannot reliably detect if a ' . + 'column was renamed or one column was created and another one dropped.'); } /** * Change Column Details. * - * @param string $columnName - * @param array $options + * @param string $columnName + * @param mixed[] $options * * @return self */ @@ -388,16 +353,16 @@ public function dropColumn($columnName) * Name is inferred from the local columns. * * @param Table|string $foreignTable Table schema instance or table name - * @param array $localColumnNames - * @param array $foreignColumnNames - * @param array $options + * @param string[] $localColumnNames + * @param string[] $foreignColumnNames + * @param mixed[] $options * @param string|null $constraintName * * @return self */ - public function addForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=[], $constraintName = null) + public function addForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options = [], $constraintName = null) { - $constraintName = $constraintName ?: $this->_generateIdentifierName(array_merge((array) $this->getName(), $localColumnNames), "fk", $this->_getMaxIdentifierLength()); + $constraintName = $constraintName ?: $this->_generateIdentifierName(array_merge((array) $this->getName(), $localColumnNames), 'fk', $this->_getMaxIdentifierLength()); return $this->addNamedForeignKeyConstraint($constraintName, $foreignTable, $localColumnNames, $foreignColumnNames, $options); } @@ -410,13 +375,13 @@ public function addForeignKeyConstraint($foreignTable, array $localColumnNames, * @deprecated Use {@link addForeignKeyConstraint} * * @param Table|string $foreignTable Table schema instance or table name - * @param array $localColumnNames - * @param array $foreignColumnNames - * @param array $options + * @param string[] $localColumnNames + * @param string[] $foreignColumnNames + * @param mixed[] $options * * @return self */ - public function addUnnamedForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=[]) + public function addUnnamedForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options = []) { return $this->addForeignKeyConstraint($foreignTable, $localColumnNames, $foreignColumnNames, $options); } @@ -428,32 +393,36 @@ public function addUnnamedForeignKeyConstraint($foreignTable, array $localColumn * * @param string $name * @param Table|string $foreignTable Table schema instance or table name - * @param array $localColumnNames - * @param array $foreignColumnNames - * @param array $options + * @param string[] $localColumnNames + * @param string[] $foreignColumnNames + * @param mixed[] $options * * @return self * * @throws SchemaException */ - public function addNamedForeignKeyConstraint($name, $foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=[]) + public function addNamedForeignKeyConstraint($name, $foreignTable, array $localColumnNames, array $foreignColumnNames, array $options = []) { if ($foreignTable instanceof Table) { foreach ($foreignColumnNames as $columnName) { - if ( ! $foreignTable->hasColumn($columnName)) { + if (! $foreignTable->hasColumn($columnName)) { throw SchemaException::columnDoesNotExist($columnName, $foreignTable->getName()); } } } foreach ($localColumnNames as $columnName) { - if ( ! $this->hasColumn($columnName)) { + if (! $this->hasColumn($columnName)) { throw SchemaException::columnDoesNotExist($columnName, $this->_name); } } $constraint = new ForeignKeyConstraint( - $localColumnNames, $foreignTable, $foreignColumnNames, $name, $options + $localColumnNames, + $foreignTable, + $foreignColumnNames, + $name, + $options ); $this->_addForeignKeyConstraint($constraint); @@ -474,8 +443,6 @@ public function addOption($name, $value) } /** - * @param Column $column - * * @return void * * @throws SchemaException @@ -495,26 +462,26 @@ protected function _addColumn(Column $column) /** * Adds an index to the table. * - * @param Index $indexCandidate - * * @return self * * @throws SchemaException */ protected function _addIndex(Index $indexCandidate) { - $indexName = $indexCandidate->getName(); - $indexName = $this->normalizeIdentifier($indexName); + $indexName = $indexCandidate->getName(); + $indexName = $this->normalizeIdentifier($indexName); $replacedImplicitIndexes = []; foreach ($this->implicitIndexes as $name => $implicitIndex) { - if ($implicitIndex->isFullfilledBy($indexCandidate) && isset($this->_indexes[$name])) { - $replacedImplicitIndexes[] = $name; + if (! $implicitIndex->isFullfilledBy($indexCandidate) || ! isset($this->_indexes[$name])) { + continue; } + + $replacedImplicitIndexes[] = $name; } if ((isset($this->_indexes[$indexName]) && ! in_array($indexName, $replacedImplicitIndexes, true)) || - ($this->_primaryKeyName != false && $indexCandidate->isPrimary()) + ($this->_primaryKeyName !== false && $indexCandidate->isPrimary()) ) { throw SchemaException::indexAlreadyExists($indexName, $this->_name); } @@ -533,8 +500,6 @@ protected function _addIndex(Index $indexCandidate) } /** - * @param ForeignKeyConstraint $constraint - * * @return void */ protected function _addForeignKeyConstraint(ForeignKeyConstraint $constraint) @@ -545,7 +510,9 @@ protected function _addForeignKeyConstraint(ForeignKeyConstraint $constraint) $name = $constraint->getName(); } else { $name = $this->_generateIdentifierName( - array_merge((array) $this->getName(), $constraint->getLocalColumns()), "fk", $this->_getMaxIdentifierLength() + array_merge((array) $this->getName(), $constraint->getLocalColumns()), + 'fk', + $this->_getMaxIdentifierLength() ); } $name = $this->normalizeIdentifier($name); @@ -555,9 +522,9 @@ protected function _addForeignKeyConstraint(ForeignKeyConstraint $constraint) // add an explicit index on the foreign key columns. If there is already an index that fulfils this requirements drop the request. // In the case of __construct calling this method during hydration from schema-details all the explicitly added indexes // lead to duplicates. This creates computation overhead in this case, however no duplicate indexes are ever added (based on columns). - $indexName = $this->_generateIdentifierName( + $indexName = $this->_generateIdentifierName( array_merge([$this->getName()], $constraint->getColumns()), - "idx", + 'idx', $this->_getMaxIdentifierLength() ); $indexCandidate = $this->_createIndex($constraint->getColumns(), $indexName, false, false); @@ -598,7 +565,7 @@ public function hasForeignKey($constraintName) public function getForeignKey($constraintName) { $constraintName = $this->normalizeIdentifier($constraintName); - if (!$this->hasForeignKey($constraintName)) { + if (! $this->hasForeignKey($constraintName)) { throw SchemaException::foreignKeyDoesNotExist($constraintName, $this->_name); } @@ -617,7 +584,7 @@ public function getForeignKey($constraintName) public function removeForeignKey($constraintName) { $constraintName = $this->normalizeIdentifier($constraintName); - if (!$this->hasForeignKey($constraintName)) { + if (! $this->hasForeignKey($constraintName)) { throw SchemaException::foreignKeyDoesNotExist($constraintName, $this->_name); } @@ -626,6 +593,7 @@ public function removeForeignKey($constraintName) /** * Returns ordered list of columns (primary keys are first, then foreign keys, then the rest) + * * @return Column[] */ public function getColumns() @@ -640,13 +608,13 @@ public function getColumns() /** * Returns foreign key columns + * * @return Column[] */ private function getForeignKeyColumns() { $foreignKeyColumns = []; foreach ($this->getForeignKeys() as $foreignKey) { - /* @var $foreignKey ForeignKeyConstraint */ $foreignKeyColumns = array_merge($foreignKeyColumns, $foreignKey->getColumns()); } return $this->filterColumns($foreignKeyColumns); @@ -654,12 +622,14 @@ private function getForeignKeyColumns() /** * Returns only columns that have specified names - * @param array $columnNames + * + * @param string[] $columnNames + * * @return Column[] */ private function filterColumns(array $columnNames) { - return array_filter($this->_columns, function ($columnName) use ($columnNames) { + return array_filter($this->_columns, static function ($columnName) use ($columnNames) { return in_array($columnName, $columnNames, true); }, ARRAY_FILTER_USE_KEY); } @@ -690,7 +660,7 @@ public function hasColumn($columnName) public function getColumn($columnName) { $columnName = $this->normalizeIdentifier($columnName); - if ( ! $this->hasColumn($columnName)) { + if (! $this->hasColumn($columnName)) { throw SchemaException::columnDoesNotExist($columnName, $this->_name); } @@ -704,7 +674,7 @@ public function getColumn($columnName) */ public function getPrimaryKey() { - if ( ! $this->hasPrimaryKey()) { + if (! $this->hasPrimaryKey()) { return null; } @@ -714,14 +684,14 @@ public function getPrimaryKey() /** * Returns the primary key columns. * - * @return array + * @return string[] * * @throws DBALException */ public function getPrimaryKeyColumns() { - if ( ! $this->hasPrimaryKey()) { - throw new DBALException("Table " . $this->getName() . " has no primary key."); + if (! $this->hasPrimaryKey()) { + throw new DBALException('Table ' . $this->getName() . ' has no primary key.'); } return $this->getPrimaryKey()->getColumns(); } @@ -733,7 +703,7 @@ public function getPrimaryKeyColumns() */ public function hasPrimaryKey() { - return ($this->_primaryKeyName && $this->hasIndex($this->_primaryKeyName)); + return $this->_primaryKeyName && $this->hasIndex($this->_primaryKeyName); } /** @@ -747,7 +717,7 @@ public function hasIndex($indexName) { $indexName = $this->normalizeIdentifier($indexName); - return (isset($this->_indexes[$indexName])); + return isset($this->_indexes[$indexName]); } /** @@ -762,7 +732,7 @@ public function hasIndex($indexName) public function getIndex($indexName) { $indexName = $this->normalizeIdentifier($indexName); - if ( ! $this->hasIndex($indexName)) { + if (! $this->hasIndex($indexName)) { throw SchemaException::indexDoesNotExist($indexName, $this->_name); } @@ -808,7 +778,7 @@ public function getOption($name) } /** - * @return array + * @return mixed[] */ public function getOptions() { @@ -816,8 +786,6 @@ public function getOptions() } /** - * @param Visitor $visitor - * * @return void */ public function visit(Visitor $visitor) diff --git a/lib/Doctrine/DBAL/Schema/TableDiff.php b/lib/Doctrine/DBAL/Schema/TableDiff.php index a50c6b40628..457e1b6a963 100644 --- a/lib/Doctrine/DBAL/Schema/TableDiff.php +++ b/lib/Doctrine/DBAL/Schema/TableDiff.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Schema; @@ -23,76 +6,68 @@ /** * Table Diff. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ class TableDiff { - /** - * @var string - */ + /** @var string */ public $name = null; - /** - * @var string|boolean - */ + /** @var string|bool */ public $newName = false; /** * All added fields. * - * @var \Doctrine\DBAL\Schema\Column[] + * @var Column[] */ public $addedColumns; /** * All changed fields. * - * @var \Doctrine\DBAL\Schema\ColumnDiff[] + * @var ColumnDiff[] */ public $changedColumns = []; /** * All removed fields. * - * @var \Doctrine\DBAL\Schema\Column[] + * @var Column[] */ public $removedColumns = []; /** * Columns that are only renamed from key to column instance name. * - * @var \Doctrine\DBAL\Schema\Column[] + * @var Column[] */ public $renamedColumns = []; /** * All added indexes. * - * @var \Doctrine\DBAL\Schema\Index[] + * @var Index[] */ public $addedIndexes = []; /** * All changed indexes. * - * @var \Doctrine\DBAL\Schema\Index[] + * @var Index[] */ public $changedIndexes = []; /** * All removed indexes * - * @var \Doctrine\DBAL\Schema\Index[] + * @var Index[] */ public $removedIndexes = []; /** * Indexes that are only renamed but are identical otherwise. * - * @var \Doctrine\DBAL\Schema\Index[] + * @var Index[] */ public $renamedIndexes = []; @@ -106,7 +81,7 @@ class TableDiff /** * All changed foreign keys * - * @var \Doctrine\DBAL\Schema\ForeignKeyConstraint[] + * @var ForeignKeyConstraint[] */ public $changedForeignKeys = []; @@ -117,41 +92,44 @@ class TableDiff */ public $removedForeignKeys = []; - /** - * @var \Doctrine\DBAL\Schema\Table - */ + /** @var Table */ public $fromTable; /** * Constructs an TableDiff object. * - * @param string $tableName - * @param \Doctrine\DBAL\Schema\Column[] $addedColumns - * @param \Doctrine\DBAL\Schema\ColumnDiff[] $changedColumns - * @param \Doctrine\DBAL\Schema\Column[] $removedColumns - * @param \Doctrine\DBAL\Schema\Index[] $addedIndexes - * @param \Doctrine\DBAL\Schema\Index[] $changedIndexes - * @param \Doctrine\DBAL\Schema\Index[] $removedIndexes - * @param \Doctrine\DBAL\Schema\Table|null $fromTable - */ - public function __construct($tableName, $addedColumns = [], - $changedColumns = [], $removedColumns = [], $addedIndexes = [], - $changedIndexes = [], $removedIndexes = [], Table $fromTable = null) - { - $this->name = $tableName; - $this->addedColumns = $addedColumns; + * @param string $tableName + * @param Column[] $addedColumns + * @param ColumnDiff[] $changedColumns + * @param Column[] $removedColumns + * @param Index[] $addedIndexes + * @param Index[] $changedIndexes + * @param Index[] $removedIndexes + */ + public function __construct( + $tableName, + $addedColumns = [], + $changedColumns = [], + $removedColumns = [], + $addedIndexes = [], + $changedIndexes = [], + $removedIndexes = [], + ?Table $fromTable = null + ) { + $this->name = $tableName; + $this->addedColumns = $addedColumns; $this->changedColumns = $changedColumns; $this->removedColumns = $removedColumns; - $this->addedIndexes = $addedIndexes; + $this->addedIndexes = $addedIndexes; $this->changedIndexes = $changedIndexes; $this->removedIndexes = $removedIndexes; - $this->fromTable = $fromTable; + $this->fromTable = $fromTable; } /** * @param AbstractPlatform $platform The platform to use for retrieving this table diff's name. * - * @return \Doctrine\DBAL\Schema\Identifier + * @return Identifier */ public function getName(AbstractPlatform $platform) { diff --git a/lib/Doctrine/DBAL/Schema/View.php b/lib/Doctrine/DBAL/Schema/View.php index 0ef7d305bbb..ac8d6cb5cb4 100644 --- a/lib/Doctrine/DBAL/Schema/View.php +++ b/lib/Doctrine/DBAL/Schema/View.php @@ -1,37 +1,14 @@ . - */ namespace Doctrine\DBAL\Schema; /** * Representation of a Database View. - * - * @link www.doctrine-project.org - * @since 1.0 - * @author Benjamin Eberlei */ class View extends AbstractAsset { - /** - * @var string - */ - private $_sql; + /** @var string */ + private $sql; /** * @param string $name @@ -40,7 +17,7 @@ class View extends AbstractAsset public function __construct($name, $sql) { $this->_setName($name); - $this->_sql = $sql; + $this->sql = $sql; } /** @@ -48,6 +25,6 @@ public function __construct($name, $sql) */ public function getSql() { - return $this->_sql; + return $this->sql; } } diff --git a/lib/Doctrine/DBAL/Schema/Visitor/AbstractVisitor.php b/lib/Doctrine/DBAL/Schema/Visitor/AbstractVisitor.php index 7bf5b2fec32..47169044274 100644 --- a/lib/Doctrine/DBAL/Schema/Visitor/AbstractVisitor.php +++ b/lib/Doctrine/DBAL/Schema/Visitor/AbstractVisitor.php @@ -1,39 +1,19 @@ . - */ namespace Doctrine\DBAL\Schema\Visitor; -use Doctrine\DBAL\Schema\Table; -use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Column; use Doctrine\DBAL\Schema\ForeignKeyConstraint; -use Doctrine\DBAL\Schema\Sequence; use Doctrine\DBAL\Schema\Index; +use Doctrine\DBAL\Schema\Schema; +use Doctrine\DBAL\Schema\Sequence; +use Doctrine\DBAL\Schema\Table; /** * Abstract Visitor with empty methods for easy extension. */ class AbstractVisitor implements Visitor, NamespaceVisitor { - /** - * @param \Doctrine\DBAL\Schema\Schema $schema - */ public function acceptSchema(Schema $schema) { } @@ -45,40 +25,22 @@ public function acceptNamespace($namespaceName) { } - /** - * @param \Doctrine\DBAL\Schema\Table $table - */ public function acceptTable(Table $table) { } - /** - * @param \Doctrine\DBAL\Schema\Table $table - * @param \Doctrine\DBAL\Schema\Column $column - */ public function acceptColumn(Table $table, Column $column) { } - /** - * @param \Doctrine\DBAL\Schema\Table $localTable - * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $fkConstraint - */ public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkConstraint) { } - /** - * @param \Doctrine\DBAL\Schema\Table $table - * @param \Doctrine\DBAL\Schema\Index $index - */ public function acceptIndex(Table $table, Index $index) { } - /** - * @param \Doctrine\DBAL\Schema\Sequence $sequence - */ public function acceptSequence(Sequence $sequence) { } diff --git a/lib/Doctrine/DBAL/Schema/Visitor/CreateSchemaSqlCollector.php b/lib/Doctrine/DBAL/Schema/Visitor/CreateSchemaSqlCollector.php index 0d92edb0998..318c8b26222 100644 --- a/lib/Doctrine/DBAL/Schema/Visitor/CreateSchemaSqlCollector.php +++ b/lib/Doctrine/DBAL/Schema/Visitor/CreateSchemaSqlCollector.php @@ -1,61 +1,30 @@ . - */ namespace Doctrine\DBAL\Schema\Visitor; use Doctrine\DBAL\Platforms\AbstractPlatform; -use Doctrine\DBAL\Schema\Table; use Doctrine\DBAL\Schema\ForeignKeyConstraint; use Doctrine\DBAL\Schema\Sequence; +use Doctrine\DBAL\Schema\Table; use function array_merge; class CreateSchemaSqlCollector extends AbstractVisitor { - /** - * @var array - */ + /** @var string[] */ private $createNamespaceQueries = []; - /** - * @var array - */ + /** @var string[] */ private $createTableQueries = []; - /** - * @var array - */ + /** @var string[] */ private $createSequenceQueries = []; - /** - * @var array - */ + /** @var string[] */ private $createFkConstraintQueries = []; - /** - * - * @var \Doctrine\DBAL\Platforms\AbstractPlatform - */ + /** @var AbstractPlatform */ private $platform = null; - /** - * @param AbstractPlatform $platform - */ public function __construct(AbstractPlatform $platform) { $this->platform = $platform; @@ -66,9 +35,11 @@ public function __construct(AbstractPlatform $platform) */ public function acceptNamespace($namespaceName) { - if ($this->platform->supportsSchemas()) { - $this->createNamespaceQueries[] = $this->platform->getCreateSchemaSQL($namespaceName); + if (! $this->platform->supportsSchemas()) { + return; } + + $this->createNamespaceQueries[] = $this->platform->getCreateSchemaSQL($namespaceName); } /** @@ -84,9 +55,11 @@ public function acceptTable(Table $table) */ public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkConstraint) { - if ($this->platform->supportsForeignKeyConstraints()) { - $this->createFkConstraintQueries[] = $this->platform->getCreateForeignKeySQL($fkConstraint, $localTable); + if (! $this->platform->supportsForeignKeyConstraints()) { + return; } + + $this->createFkConstraintQueries[] = $this->platform->getCreateForeignKeySQL($fkConstraint, $localTable); } /** @@ -102,16 +75,16 @@ public function acceptSequence(Sequence $sequence) */ public function resetQueries() { - $this->createNamespaceQueries = []; - $this->createTableQueries = []; - $this->createSequenceQueries = []; + $this->createNamespaceQueries = []; + $this->createTableQueries = []; + $this->createSequenceQueries = []; $this->createFkConstraintQueries = []; } /** * Gets all queries collected so far. * - * @return array + * @return string[] */ public function getQueries() { diff --git a/lib/Doctrine/DBAL/Schema/Visitor/DropSchemaSqlCollector.php b/lib/Doctrine/DBAL/Schema/Visitor/DropSchemaSqlCollector.php index abd183d5ae5..44f5ea80af5 100644 --- a/lib/Doctrine/DBAL/Schema/Visitor/DropSchemaSqlCollector.php +++ b/lib/Doctrine/DBAL/Schema/Visitor/DropSchemaSqlCollector.php @@ -1,63 +1,32 @@ . - */ namespace Doctrine\DBAL\Schema\Visitor; use Doctrine\DBAL\Platforms\AbstractPlatform; -use Doctrine\DBAL\Schema\Table; use Doctrine\DBAL\Schema\ForeignKeyConstraint; -use Doctrine\DBAL\Schema\Sequence; use Doctrine\DBAL\Schema\SchemaException; +use Doctrine\DBAL\Schema\Sequence; +use Doctrine\DBAL\Schema\Table; +use SplObjectStorage; use function strlen; /** * Gathers SQL statements that allow to completely drop the current schema. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ class DropSchemaSqlCollector extends AbstractVisitor { - /** - * @var \SplObjectStorage - */ + /** @var SplObjectStorage */ private $constraints; - /** - * @var \SplObjectStorage - */ + /** @var SplObjectStorage */ private $sequences; - /** - * @var \SplObjectStorage - */ + /** @var SplObjectStorage */ private $tables; - /** - * @var AbstractPlatform - */ + /** @var AbstractPlatform */ private $platform; - /** - * @param AbstractPlatform $platform - */ public function __construct(AbstractPlatform $platform) { $this->platform = $platform; @@ -77,7 +46,7 @@ public function acceptTable(Table $table) */ public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkConstraint) { - if (strlen($fkConstraint->getName()) == 0) { + if (strlen($fkConstraint->getName()) === 0) { throw SchemaException::namedForeignKeyRequired($localTable, $fkConstraint); } @@ -97,13 +66,13 @@ public function acceptSequence(Sequence $sequence) */ public function clearQueries() { - $this->constraints = new \SplObjectStorage(); - $this->sequences = new \SplObjectStorage(); - $this->tables = new \SplObjectStorage(); + $this->constraints = new SplObjectStorage(); + $this->sequences = new SplObjectStorage(); + $this->tables = new SplObjectStorage(); } /** - * @return array + * @return string[] */ public function getQueries() { @@ -111,7 +80,7 @@ public function getQueries() foreach ($this->constraints as $fkConstraint) { $localTable = $this->constraints[$fkConstraint]; - $sql[] = $this->platform->getDropForeignKeySQL($fkConstraint, $localTable); + $sql[] = $this->platform->getDropForeignKeySQL($fkConstraint, $localTable); } foreach ($this->sequences as $sequence) { diff --git a/lib/Doctrine/DBAL/Schema/Visitor/Graphviz.php b/lib/Doctrine/DBAL/Schema/Visitor/Graphviz.php index daec58ef064..889f9611254 100644 --- a/lib/Doctrine/DBAL/Schema/Visitor/Graphviz.php +++ b/lib/Doctrine/DBAL/Schema/Visitor/Graphviz.php @@ -1,27 +1,10 @@ . - */ namespace Doctrine\DBAL\Schema\Visitor; -use Doctrine\DBAL\Schema\Table; -use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\ForeignKeyConstraint; +use Doctrine\DBAL\Schema\Schema; +use Doctrine\DBAL\Schema\Table; use function current; use function file_put_contents; use function in_array; @@ -34,9 +17,7 @@ */ class Graphviz extends AbstractVisitor { - /** - * @var string - */ + /** @var string */ private $output = ''; /** @@ -45,8 +26,8 @@ class Graphviz extends AbstractVisitor public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkConstraint) { $this->output .= $this->createNodeRelation( - $fkConstraint->getLocalTableName() . ":col" . current($fkConstraint->getLocalColumns()).":se", - $fkConstraint->getForeignTableName() . ":col" . current($fkConstraint->getForeignColumns()).":se", + $fkConstraint->getLocalTableName() . ':col' . current($fkConstraint->getLocalColumns()) . ':se', + $fkConstraint->getForeignTableName() . ':col' . current($fkConstraint->getForeignColumns()) . ':se', [ 'dir' => 'back', 'arrowtail' => 'dot', @@ -63,7 +44,7 @@ public function acceptSchema(Schema $schema) $this->output = 'digraph "' . sha1(mt_rand()) . '" {' . "\n"; $this->output .= 'splines = true;' . "\n"; $this->output .= 'overlap = false;' . "\n"; - $this->output .= 'outputorder=edgesfirst;'."\n"; + $this->output .= 'outputorder=edgesfirst;' . "\n"; $this->output .= 'mindist = 0.6;' . "\n"; $this->output .= 'sep = .2;' . "\n"; } @@ -83,8 +64,6 @@ public function acceptTable(Table $table) } /** - * @param \Doctrine\DBAL\Schema\Table $table - * * @return string */ private function createTableLabel(Table $table) @@ -103,7 +82,7 @@ private function createTableLabel(Table $table) $label .= ''; $label .= '' . $columnLabel . ''; $label .= '' . strtolower($column->getType()) . ''; - $label .= ''; + $label .= ''; if ($table->hasPrimaryKey() && in_array($column->getName(), $table->getPrimaryKey()->getColumns())) { $label .= "\xe2\x9c\xb7"; } @@ -117,14 +96,14 @@ private function createTableLabel(Table $table) } /** - * @param string $name - * @param array $options + * @param string $name + * @param string[] $options * * @return string */ private function createNode($name, $options) { - $node = $name . " ["; + $node = $name . ' ['; foreach ($options as $key => $value) { $node .= $key . '=' . $value . ' '; } @@ -134,9 +113,9 @@ private function createNode($name, $options) } /** - * @param string $node1 - * @param string $node2 - * @param array $options + * @param string $node1 + * @param string $node2 + * @param string[] $options * * @return string */ @@ -158,7 +137,7 @@ private function createNodeRelation($node1, $node2, $options) */ public function getOutput() { - return $this->output . "}"; + return $this->output . '}'; } /** diff --git a/lib/Doctrine/DBAL/Schema/Visitor/NamespaceVisitor.php b/lib/Doctrine/DBAL/Schema/Visitor/NamespaceVisitor.php index da7b1edbcaa..186fe1b4213 100644 --- a/lib/Doctrine/DBAL/Schema/Visitor/NamespaceVisitor.php +++ b/lib/Doctrine/DBAL/Schema/Visitor/NamespaceVisitor.php @@ -1,30 +1,9 @@ . - */ namespace Doctrine\DBAL\Schema\Visitor; /** * Visitor that can visit schema namespaces. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ interface NamespaceVisitor { diff --git a/lib/Doctrine/DBAL/Schema/Visitor/RemoveNamespacedAssets.php b/lib/Doctrine/DBAL/Schema/Visitor/RemoveNamespacedAssets.php index e328d071cde..9b23b395885 100644 --- a/lib/Doctrine/DBAL/Schema/Visitor/RemoveNamespacedAssets.php +++ b/lib/Doctrine/DBAL/Schema/Visitor/RemoveNamespacedAssets.php @@ -1,28 +1,11 @@ . - */ namespace Doctrine\DBAL\Schema\Visitor; -use Doctrine\DBAL\Schema\Table; -use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\ForeignKeyConstraint; +use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Sequence; +use Doctrine\DBAL\Schema\Table; /** * Removes assets from a schema that are not in the default namespace. @@ -34,15 +17,10 @@ * * This visitor filters all these non-default namespaced tables and sequences * and removes them from the SChema instance. - * - * @author Benjamin Eberlei - * @since 2.2 */ class RemoveNamespacedAssets extends AbstractVisitor { - /** - * @var \Doctrine\DBAL\Schema\Schema - */ + /** @var Schema */ private $schema; /** @@ -58,9 +36,11 @@ public function acceptSchema(Schema $schema) */ public function acceptTable(Table $table) { - if ( ! $table->isInDefaultNamespace($this->schema->getName())) { - $this->schema->dropTable($table->getName()); + if ($table->isInDefaultNamespace($this->schema->getName())) { + return; } + + $this->schema->dropTable($table->getName()); } /** @@ -68,9 +48,11 @@ public function acceptTable(Table $table) */ public function acceptSequence(Sequence $sequence) { - if ( ! $sequence->isInDefaultNamespace($this->schema->getName())) { - $this->schema->dropSequence($sequence->getName()); + if ($sequence->isInDefaultNamespace($this->schema->getName())) { + return; } + + $this->schema->dropSequence($sequence->getName()); } /** @@ -81,14 +63,16 @@ public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkCons // The table may already be deleted in a previous // RemoveNamespacedAssets#acceptTable call. Removing Foreign keys that // point to nowhere. - if ( ! $this->schema->hasTable($fkConstraint->getForeignTableName())) { + if (! $this->schema->hasTable($fkConstraint->getForeignTableName())) { $localTable->removeForeignKey($fkConstraint->getName()); return; } $foreignTable = $this->schema->getTable($fkConstraint->getForeignTableName()); - if ( ! $foreignTable->isInDefaultNamespace($this->schema->getName())) { - $localTable->removeForeignKey($fkConstraint->getName()); + if ($foreignTable->isInDefaultNamespace($this->schema->getName())) { + return; } + + $localTable->removeForeignKey($fkConstraint->getName()); } } diff --git a/lib/Doctrine/DBAL/Schema/Visitor/SchemaDiffVisitor.php b/lib/Doctrine/DBAL/Schema/Visitor/SchemaDiffVisitor.php index bde4453b357..5ec843d9be6 100644 --- a/lib/Doctrine/DBAL/Schema/Visitor/SchemaDiffVisitor.php +++ b/lib/Doctrine/DBAL/Schema/Visitor/SchemaDiffVisitor.php @@ -1,82 +1,39 @@ . - */ namespace Doctrine\DBAL\Schema\Visitor; -use Doctrine\DBAL\Schema\Table; -use Doctrine\DBAL\Schema\TableDiff; use Doctrine\DBAL\Schema\ForeignKeyConstraint; use Doctrine\DBAL\Schema\Sequence; +use Doctrine\DBAL\Schema\Table; +use Doctrine\DBAL\Schema\TableDiff; /** * Visit a SchemaDiff. - * - * @link www.doctrine-project.org - * @since 2.4 - * @author Benjamin Eberlei */ interface SchemaDiffVisitor { /** * Visit an orphaned foreign key whose table was deleted. - * - * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey */ - function visitOrphanedForeignKey(ForeignKeyConstraint $foreignKey); + public function visitOrphanedForeignKey(ForeignKeyConstraint $foreignKey); /** * Visit a sequence that has changed. - * - * @param \Doctrine\DBAL\Schema\Sequence $sequence */ - function visitChangedSequence(Sequence $sequence); + public function visitChangedSequence(Sequence $sequence); /** * Visit a sequence that has been removed. - * - * @param \Doctrine\DBAL\Schema\Sequence $sequence */ - function visitRemovedSequence(Sequence $sequence); + public function visitRemovedSequence(Sequence $sequence); - /** - * @param \Doctrine\DBAL\Schema\Sequence $sequence - */ - function visitNewSequence(Sequence $sequence); + public function visitNewSequence(Sequence $sequence); - /** - * @param \Doctrine\DBAL\Schema\Table $table - */ - function visitNewTable(Table $table); + public function visitNewTable(Table $table); - /** - * @param \Doctrine\DBAL\Schema\Table $table - * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey - */ - function visitNewTableForeignKey(Table $table, ForeignKeyConstraint $foreignKey); + public function visitNewTableForeignKey(Table $table, ForeignKeyConstraint $foreignKey); - /** - * @param \Doctrine\DBAL\Schema\Table $table - */ - function visitRemovedTable(Table $table); + public function visitRemovedTable(Table $table); - /** - * @param \Doctrine\DBAL\Schema\TableDiff $tableDiff - */ - function visitChangedTable(TableDiff $tableDiff); + public function visitChangedTable(TableDiff $tableDiff); } diff --git a/lib/Doctrine/DBAL/Schema/Visitor/Visitor.php b/lib/Doctrine/DBAL/Schema/Visitor/Visitor.php index 656f0e20c6f..05c842830c5 100644 --- a/lib/Doctrine/DBAL/Schema/Visitor/Visitor.php +++ b/lib/Doctrine/DBAL/Schema/Visitor/Visitor.php @@ -1,81 +1,45 @@ . - */ namespace Doctrine\DBAL\Schema\Visitor; -use Doctrine\DBAL\Schema\Table; -use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Column; use Doctrine\DBAL\Schema\ForeignKeyConstraint; -use Doctrine\DBAL\Schema\Sequence; use Doctrine\DBAL\Schema\Index; +use Doctrine\DBAL\Schema\Schema; +use Doctrine\DBAL\Schema\Sequence; +use Doctrine\DBAL\Schema\Table; /** * Schema Visitor used for Validation or Generation purposes. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei */ interface Visitor { /** - * @param \Doctrine\DBAL\Schema\Schema $schema - * * @return void */ public function acceptSchema(Schema $schema); /** - * @param \Doctrine\DBAL\Schema\Table $table - * * @return void */ public function acceptTable(Table $table); /** - * @param \Doctrine\DBAL\Schema\Table $table - * @param \Doctrine\DBAL\Schema\Column $column - * * @return void */ public function acceptColumn(Table $table, Column $column); /** - * @param \Doctrine\DBAL\Schema\Table $localTable - * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $fkConstraint - * * @return void */ public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkConstraint); /** - * @param \Doctrine\DBAL\Schema\Table $table - * @param \Doctrine\DBAL\Schema\Index $index - * * @return void */ public function acceptIndex(Table $table, Index $index); /** - * @param \Doctrine\DBAL\Schema\Sequence $sequence - * * @return void */ public function acceptSequence(Sequence $sequence); diff --git a/lib/Doctrine/DBAL/Sharding/PoolingShardConnection.php b/lib/Doctrine/DBAL/Sharding/PoolingShardConnection.php index e307d5ebc4d..abb5b4004e2 100644 --- a/lib/Doctrine/DBAL/Sharding/PoolingShardConnection.php +++ b/lib/Doctrine/DBAL/Sharding/PoolingShardConnection.php @@ -1,32 +1,16 @@ . - */ namespace Doctrine\DBAL\Sharding; use Doctrine\Common\EventManager; use Doctrine\DBAL\Configuration; use Doctrine\DBAL\Connection; -use Doctrine\DBAL\Driver\Connection as DriverConnection; use Doctrine\DBAL\Driver; +use Doctrine\DBAL\Driver\Connection as DriverConnection; use Doctrine\DBAL\Event\ConnectionEventArgs; use Doctrine\DBAL\Events; use Doctrine\DBAL\Sharding\ShardChoser\ShardChoser; +use InvalidArgumentException; use function array_merge; use function is_numeric; use function is_string; @@ -63,65 +47,54 @@ * $shardManager = $conn->getShardManager(); * $shardManager->selectGlobal(); * $shardManager->selectShard($value); - * - * @author Benjamin Eberlei */ class PoolingShardConnection extends Connection { - /** - * @var DriverConnection[] - */ + /** @var DriverConnection[] */ private $activeConnections = []; - /** - * @var int|null - */ + /** @var int|null */ private $activeShardId; - /** - * @var mixed[] - */ + /** @var mixed[] */ private $connectionParameters = []; /** - * @param array $params - * @param \Doctrine\DBAL\Driver $driver - * @param \Doctrine\DBAL\Configuration $config - * @param \Doctrine\Common\EventManager $eventManager + * {@inheritDoc} * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ - public function __construct(array $params, Driver $driver, Configuration $config = null, EventManager $eventManager = null) + public function __construct(array $params, Driver $driver, ?Configuration $config = null, ?EventManager $eventManager = null) { if (! isset($params['global'], $params['shards'])) { - throw new \InvalidArgumentException("Connection Parameters require 'global' and 'shards' configurations."); + throw new InvalidArgumentException("Connection Parameters require 'global' and 'shards' configurations."); } if (! isset($params['shardChoser'])) { - throw new \InvalidArgumentException("Missing Shard Choser configuration 'shardChoser'"); + throw new InvalidArgumentException("Missing Shard Choser configuration 'shardChoser'"); } if (is_string($params['shardChoser'])) { - $params['shardChoser'] = new $params['shardChoser']; + $params['shardChoser'] = new $params['shardChoser'](); } - if ( ! ($params['shardChoser'] instanceof ShardChoser)) { - throw new \InvalidArgumentException("The 'shardChoser' configuration is not a valid instance of Doctrine\DBAL\Sharding\ShardChoser\ShardChoser"); + if (! ($params['shardChoser'] instanceof ShardChoser)) { + throw new InvalidArgumentException("The 'shardChoser' configuration is not a valid instance of Doctrine\DBAL\Sharding\ShardChoser\ShardChoser"); } $this->connectionParameters[0] = array_merge($params, $params['global']); foreach ($params['shards'] as $shard) { - if ( ! isset($shard['id'])) { - throw new \InvalidArgumentException("Missing 'id' for one configured shard. Please specify a unique shard-id."); + if (! isset($shard['id'])) { + throw new InvalidArgumentException("Missing 'id' for one configured shard. Please specify a unique shard-id."); } - if ( !is_numeric($shard['id']) || $shard['id'] < 1) { - throw new \InvalidArgumentException("Shard Id has to be a non-negative number."); + if (! is_numeric($shard['id']) || $shard['id'] < 1) { + throw new InvalidArgumentException('Shard Id has to be a non-negative number.'); } if (isset($this->connectionParameters[$shard['id']])) { - throw new \InvalidArgumentException("Shard " . $shard['id'] . " is duplicated in the configuration."); + throw new InvalidArgumentException('Shard ' . $shard['id'] . ' is duplicated in the configuration.'); } $this->connectionParameters[$shard['id']] = array_merge($params, $shard); @@ -195,7 +168,7 @@ public function getPassword() * * @return bool * - * @throws \Doctrine\DBAL\Sharding\ShardingException + * @throws ShardingException */ public function connect($shardId = null) { @@ -208,7 +181,7 @@ public function connect($shardId = null) } if ($this->getTransactionNestingLevel() > 0) { - throw new ShardingException("Cannot switch shard when transaction is active."); + throw new ShardingException('Cannot switch shard when transaction is active.'); } $this->activeShardId = (int) $shardId; @@ -244,7 +217,7 @@ protected function connectTo($shardId) $connectionParams = $this->connectionParameters[$shardId]; - $user = $connectionParams['user'] ?? null; + $user = $connectionParams['user'] ?? null; $password = $connectionParams['password'] ?? null; return $this->_driver->connect($connectionParams, $user, $password, $driverOptions); diff --git a/lib/Doctrine/DBAL/Sharding/PoolingShardManager.php b/lib/Doctrine/DBAL/Sharding/PoolingShardManager.php index 7f9a33fc5b2..5edc56b8778 100644 --- a/lib/Doctrine/DBAL/Sharding/PoolingShardManager.php +++ b/lib/Doctrine/DBAL/Sharding/PoolingShardManager.php @@ -1,51 +1,24 @@ . - */ namespace Doctrine\DBAL\Sharding; use Doctrine\DBAL\Sharding\ShardChoser\ShardChoser; +use RuntimeException; /** * Shard Manager for the Connection Pooling Shard Strategy - * - * @author Benjamin Eberlei */ class PoolingShardManager implements ShardManager { - /** - * @var PoolingShardConnection - */ + /** @var PoolingShardConnection */ private $conn; - /** - * @var ShardChoser - */ + /** @var ShardChoser */ private $choser; - /** - * @var string|null - */ + /** @var string|null */ private $currentDistributionValue; - /** - * @param PoolingShardConnection $conn - */ public function __construct(PoolingShardConnection $conn) { $params = $conn->getParams(); @@ -96,22 +69,18 @@ public function getShards() } /** - * @param string $sql - * @param array $params - * @param array $types - * - * @return array + * {@inheritDoc} * - * @throws \RuntimeException + * @throws RuntimeException */ public function queryAll($sql, array $params, array $types) { $shards = $this->getShards(); - if (!$shards) { - throw new \RuntimeException("No shards found."); + if (! $shards) { + throw new RuntimeException('No shards found.'); } - $result = []; + $result = []; $oldDistribution = $this->getCurrentDistributionValue(); foreach ($shards as $shard) { diff --git a/lib/Doctrine/DBAL/Sharding/SQLAzure/SQLAzureFederationsSynchronizer.php b/lib/Doctrine/DBAL/Sharding/SQLAzure/SQLAzureFederationsSynchronizer.php index 2b700b38a4a..32d642365b0 100644 --- a/lib/Doctrine/DBAL/Sharding/SQLAzure/SQLAzureFederationsSynchronizer.php +++ b/lib/Doctrine/DBAL/Sharding/SQLAzure/SQLAzureFederationsSynchronizer.php @@ -1,31 +1,15 @@ . - */ namespace Doctrine\DBAL\Sharding\SQLAzure; -use Doctrine\DBAL\Schema\Schema; +use Closure; use Doctrine\DBAL\Connection; -use Doctrine\DBAL\Types\Type; - +use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Synchronizer\AbstractSchemaSynchronizer; -use Doctrine\DBAL\Schema\Synchronizer\SingleDatabaseSynchronizer; use Doctrine\DBAL\Schema\Synchronizer\SchemaSynchronizer; +use Doctrine\DBAL\Schema\Synchronizer\SingleDatabaseSynchronizer; +use Doctrine\DBAL\Types\Type; +use RuntimeException; use function array_merge; /** @@ -35,30 +19,19 @@ * by partitioning the passed schema into subschemas for the federation and the * global database and then applying the operations step by step using the * {@see \Doctrine\DBAL\Schema\Synchronizer\SingleDatabaseSynchronizer}. - * - * @author Benjamin Eberlei */ class SQLAzureFederationsSynchronizer extends AbstractSchemaSynchronizer { - const FEDERATION_TABLE_FEDERATED = 'azure.federated'; - const FEDERATION_DISTRIBUTION_NAME = 'azure.federatedOnDistributionName'; + public const FEDERATION_TABLE_FEDERATED = 'azure.federated'; + public const FEDERATION_DISTRIBUTION_NAME = 'azure.federatedOnDistributionName'; - /** - * @var \Doctrine\DBAL\Sharding\SQLAzure\SQLAzureShardManager - */ + /** @var SQLAzureShardManager */ private $shardManager; - /** - * @var \Doctrine\DBAL\Schema\Synchronizer\SchemaSynchronizer - */ + /** @var SchemaSynchronizer */ private $synchronizer; - /** - * @param \Doctrine\DBAL\Connection $conn - * @param \Doctrine\DBAL\Sharding\SQLAzure\SQLAzureShardManager $shardManager - * @param \Doctrine\DBAL\Schema\Synchronizer\SchemaSynchronizer|null $sync - */ - public function __construct(Connection $conn, SQLAzureShardManager $shardManager, SchemaSynchronizer $sync = null) + public function __construct(Connection $conn, SQLAzureShardManager $shardManager, ?SchemaSynchronizer $sync = null) { parent::__construct($conn); $this->shardManager = $shardManager; @@ -72,13 +45,13 @@ public function getCreateSchema(Schema $createSchema) { $sql = []; - list($global, $federation) = $this->partitionSchema($createSchema); + [$global, $federation] = $this->partitionSchema($createSchema); $globalSql = $this->synchronizer->getCreateSchema($global); if ($globalSql) { $sql[] = "-- Create Root Federation\n" . - "USE FEDERATION ROOT WITH RESET;"; - $sql = array_merge($sql, $globalSql); + 'USE FEDERATION ROOT WITH RESET;'; + $sql = array_merge($sql, $globalSql); } $federationSql = $this->synchronizer->getCreateSchema($federation); @@ -87,8 +60,8 @@ public function getCreateSchema(Schema $createSchema) $defaultValue = $this->getFederationTypeDefaultValue(); $sql[] = $this->getCreateFederationStatement(); - $sql[] = "USE FEDERATION " . $this->shardManager->getFederationName() . " (" . $this->shardManager->getDistributionKey() . " = " . $defaultValue . ") WITH RESET, FILTERING = OFF;"; - $sql = array_merge($sql, $federationSql); + $sql[] = 'USE FEDERATION ' . $this->shardManager->getFederationName() . ' (' . $this->shardManager->getDistributionKey() . ' = ' . $defaultValue . ') WITH RESET, FILTERING = OFF;'; + $sql = array_merge($sql, $federationSql); } return $sql; @@ -99,7 +72,7 @@ public function getCreateSchema(Schema $createSchema) */ public function getUpdateSchema(Schema $toSchema, $noDrops = false) { - return $this->work($toSchema, function ($synchronizer, $schema) use ($noDrops) { + return $this->work($toSchema, static function ($synchronizer, $schema) use ($noDrops) { return $synchronizer->getUpdateSchema($schema, $noDrops); }); } @@ -109,7 +82,7 @@ public function getUpdateSchema(Schema $toSchema, $noDrops = false) */ public function getDropSchema(Schema $dropSchema) { - return $this->work($dropSchema, function ($synchronizer, $schema) { + return $this->work($dropSchema, static function ($synchronizer, $schema) { return $synchronizer->getDropSchema($schema); }); } @@ -148,7 +121,7 @@ public function getDropAllSchema() if ($globalSql) { $sql[] = "-- Work on Root Federation\nUSE FEDERATION ROOT WITH RESET;"; - $sql = array_merge($sql, $globalSql); + $sql = array_merge($sql, $globalSql); } $shards = $this->shardManager->getShards(); @@ -156,15 +129,17 @@ public function getDropAllSchema() $this->shardManager->selectShard($shard['rangeLow']); $federationSql = $this->synchronizer->getDropAllSchema(); - if ($federationSql) { - $sql[] = "-- Work on Federation ID " . $shard['id'] . "\n" . - "USE FEDERATION " . $this->shardManager->getFederationName() . " (" . $this->shardManager->getDistributionKey() . " = " . $shard['rangeLow'].") WITH RESET, FILTERING = OFF;"; - $sql = array_merge($sql, $federationSql); + if (! $federationSql) { + continue; } + + $sql[] = '-- Work on Federation ID ' . $shard['id'] . "\n" . + 'USE FEDERATION ' . $this->shardManager->getFederationName() . ' (' . $this->shardManager->getDistributionKey() . ' = ' . $shard['rangeLow'] . ') WITH RESET, FILTERING = OFF;'; + $sql = array_merge($sql, $federationSql); } - $sql[] = "USE FEDERATION ROOT WITH RESET;"; - $sql[] = "DROP FEDERATION " . $this->shardManager->getFederationName(); + $sql[] = 'USE FEDERATION ROOT WITH RESET;'; + $sql[] = 'DROP FEDERATION ' . $this->shardManager->getFederationName(); return $sql; } @@ -178,9 +153,7 @@ public function dropAllSchema() } /** - * @param \Doctrine\DBAL\Schema\Schema $schema - * - * @return array + * @return Schema[] */ private function partitionSchema(Schema $schema) { @@ -191,12 +164,11 @@ private function partitionSchema(Schema $schema) } /** - * @param \Doctrine\DBAL\Schema\Schema $schema - * @param bool $isFederation + * @param bool $isFederation * - * @return \Doctrine\DBAL\Schema\Schema + * @return Schema * - * @throws \RuntimeException + * @throws RuntimeException */ private function extractSchemaFederation(Schema $schema, $isFederation) { @@ -213,7 +185,7 @@ private function extractSchemaFederation(Schema $schema, $isFederation) foreach ($table->getForeignKeys() as $fk) { $foreignTable = $schema->getTable($fk->getForeignTableName()); if ($foreignTable->hasOption(self::FEDERATION_TABLE_FEDERATED) !== $isFederation) { - throw new \RuntimeException("Cannot have foreign key between global/federation."); + throw new RuntimeException('Cannot have foreign key between global/federation.'); } } } @@ -227,15 +199,12 @@ private function extractSchemaFederation(Schema $schema, $isFederation) * perform the given operation on the underlying schema synchronizer given * the different partitioned schema instances. * - * @param \Doctrine\DBAL\Schema\Schema $schema - * @param \Closure $operation - * - * @return array + * @return string[] */ - private function work(Schema $schema, \Closure $operation) + private function work(Schema $schema, Closure $operation) { - list($global, $federation) = $this->partitionSchema($schema); - $sql = []; + [$global, $federation] = $this->partitionSchema($schema); + $sql = []; $this->shardManager->selectGlobal(); $globalSql = $operation($this->synchronizer, $global); @@ -251,11 +220,13 @@ private function work(Schema $schema, \Closure $operation) $this->shardManager->selectShard($shard['rangeLow']); $federationSql = $operation($this->synchronizer, $federation); - if ($federationSql) { - $sql[] = "-- Work on Federation ID " . $shard['id'] . "\n" . - "USE FEDERATION " . $this->shardManager->getFederationName() . " (" . $this->shardManager->getDistributionKey() . " = " . $shard['rangeLow'].") WITH RESET, FILTERING = OFF;"; - $sql = array_merge($sql, $federationSql); + if (! $federationSql) { + continue; } + + $sql[] = '-- Work on Federation ID ' . $shard['id'] . "\n" . + 'USE FEDERATION ' . $this->shardManager->getFederationName() . ' (' . $this->shardManager->getDistributionKey() . ' = ' . $shard['rangeLow'] . ') WITH RESET, FILTERING = OFF;'; + $sql = array_merge($sql, $federationSql); } return $sql; @@ -290,10 +261,10 @@ private function getFederationTypeDefaultValue() */ private function getCreateFederationStatement() { - $federationType = Type::getType($this->shardManager->getDistributionType()); + $federationType = Type::getType($this->shardManager->getDistributionType()); $federationTypeSql = $federationType->getSQLDeclaration([], $this->conn->getDatabasePlatform()); return "--Create Federation\n" . - "CREATE FEDERATION " . $this->shardManager->getFederationName() . " (" . $this->shardManager->getDistributionKey() . " " . $federationTypeSql ." RANGE)"; + 'CREATE FEDERATION ' . $this->shardManager->getFederationName() . ' (' . $this->shardManager->getDistributionKey() . ' ' . $federationTypeSql . ' RANGE)'; } } diff --git a/lib/Doctrine/DBAL/Sharding/SQLAzure/SQLAzureShardManager.php b/lib/Doctrine/DBAL/Sharding/SQLAzure/SQLAzureShardManager.php index 255ca8b418e..7c5dfe5c4be 100644 --- a/lib/Doctrine/DBAL/Sharding/SQLAzure/SQLAzureShardManager.php +++ b/lib/Doctrine/DBAL/Sharding/SQLAzure/SQLAzureShardManager.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Sharding\SQLAzure; @@ -23,71 +6,56 @@ use Doctrine\DBAL\Sharding\ShardingException; use Doctrine\DBAL\Sharding\ShardManager; use Doctrine\DBAL\Types\Type; +use RuntimeException; use function is_bool; use function is_scalar; use function sprintf; /** * Sharding using the SQL Azure Federations support. - * - * @author Benjamin Eberlei */ class SQLAzureShardManager implements ShardManager { - /** - * @var string - */ + /** @var string */ private $federationName; - /** - * @var bool - */ + /** @var bool */ private $filteringEnabled; - /** - * @var string - */ + /** @var string */ private $distributionKey; - /** - * @var string - */ + /** @var string */ private $distributionType; - /** - * @var \Doctrine\DBAL\Connection - */ + /** @var Connection */ private $conn; - /** - * @var string|null - */ + /** @var string|null */ private $currentDistributionValue; /** - * @param \Doctrine\DBAL\Connection $conn - * - * @throws \Doctrine\DBAL\Sharding\ShardingException + * @throws ShardingException */ public function __construct(Connection $conn) { $this->conn = $conn; - $params = $conn->getParams(); + $params = $conn->getParams(); - if ( ! isset($params['sharding']['federationName'])) { + if (! isset($params['sharding']['federationName'])) { throw ShardingException::missingDefaultFederationName(); } - if ( ! isset($params['sharding']['distributionKey'])) { + if (! isset($params['sharding']['distributionKey'])) { throw ShardingException::missingDefaultDistributionKey(); } - if ( ! isset($params['sharding']['distributionType'])) { + if (! isset($params['sharding']['distributionType'])) { throw ShardingException::missingDistributionType(); } - $this->federationName = $params['sharding']['federationName']; - $this->distributionKey = $params['sharding']['distributionKey']; + $this->federationName = $params['sharding']['federationName']; + $this->distributionKey = $params['sharding']['distributionKey']; $this->distributionType = $params['sharding']['distributionType']; $this->filteringEnabled = (bool) ($params['sharding']['filteringEnabled'] ?? false); } @@ -143,7 +111,7 @@ public function selectGlobal() throw ShardingException::activeTransaction(); } - $sql = "USE FEDERATION ROOT WITH RESET"; + $sql = 'USE FEDERATION ROOT WITH RESET'; $this->conn->exec($sql); $this->currentDistributionValue = null; } @@ -157,13 +125,13 @@ public function selectShard($distributionValue) throw ShardingException::activeTransaction(); } - if ($distributionValue === null || is_bool($distributionValue) || !is_scalar($distributionValue)) { + if ($distributionValue === null || is_bool($distributionValue) || ! is_scalar($distributionValue)) { throw ShardingException::noShardDistributionValue(); } $platform = $this->conn->getDatabasePlatform(); - $sql = sprintf( - "USE FEDERATION %s (%s = %s) WITH RESET, FILTERING = %s;", + $sql = sprintf( + 'USE FEDERATION %s (%s = %s) WITH RESET, FILTERING = %s;', $platform->quoteIdentifier($this->federationName), $platform->quoteIdentifier($this->distributionKey), $this->conn->quote($distributionValue), @@ -187,13 +155,13 @@ public function getCurrentDistributionValue() */ public function getShards() { - $sql = "SELECT member_id as id, + $sql = 'SELECT member_id as id, distribution_name as distribution_key, CAST(range_low AS CHAR) AS rangeLow, CAST(range_high AS CHAR) AS rangeHigh FROM sys.federation_member_distributions d INNER JOIN sys.federations f ON f.federation_id = d.federation_id - WHERE f.name = " . $this->conn->quote($this->federationName); + WHERE f.name = ' . $this->conn->quote($this->federationName); return $this->conn->fetchAll($sql); } @@ -204,11 +172,11 @@ public function getShards() public function queryAll($sql, array $params = [], array $types = []) { $shards = $this->getShards(); - if (!$shards) { - throw new \RuntimeException("No shards found for " . $this->federationName); + if (! $shards) { + throw new RuntimeException('No shards found for ' . $this->federationName); } - $result = []; + $result = []; $oldDistribution = $this->getCurrentDistributionValue(); foreach ($shards as $shard) { @@ -238,9 +206,9 @@ public function splitFederation($splitDistributionValue) { $type = Type::getType($this->distributionType); - $sql = "ALTER FEDERATION " . $this->getFederationName() . " " . - "SPLIT AT (" . $this->getDistributionKey() . " = " . - $this->conn->quote($splitDistributionValue, $type->getBindingType()) . ")"; + $sql = 'ALTER FEDERATION ' . $this->getFederationName() . ' ' . + 'SPLIT AT (' . $this->getDistributionKey() . ' = ' . + $this->conn->quote($splitDistributionValue, $type->getBindingType()) . ')'; $this->conn->exec($sql); } } diff --git a/lib/Doctrine/DBAL/Sharding/SQLAzure/Schema/MultiTenantVisitor.php b/lib/Doctrine/DBAL/Sharding/SQLAzure/Schema/MultiTenantVisitor.php index 92851d00182..a83b401c2cd 100644 --- a/lib/Doctrine/DBAL/Sharding/SQLAzure/Schema/MultiTenantVisitor.php +++ b/lib/Doctrine/DBAL/Sharding/SQLAzure/Schema/MultiTenantVisitor.php @@ -1,31 +1,15 @@ . - */ namespace Doctrine\DBAL\Sharding\SQLAzure\Schema; -use Doctrine\DBAL\Schema\Visitor\Visitor; -use Doctrine\DBAL\Schema\Table; -use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Column; use Doctrine\DBAL\Schema\ForeignKeyConstraint; -use Doctrine\DBAL\Schema\Sequence; use Doctrine\DBAL\Schema\Index; +use Doctrine\DBAL\Schema\Schema; +use Doctrine\DBAL\Schema\Sequence; +use Doctrine\DBAL\Schema\Table; +use Doctrine\DBAL\Schema\Visitor\Visitor; +use RuntimeException; use function in_array; /** @@ -46,24 +30,16 @@ * (otherwise they will affect the same-id rows from other tenants as well). * SQLAzure throws errors when you try to create IDENTIY columns on federated * tables. - * - * @author Benjamin Eberlei */ class MultiTenantVisitor implements Visitor { - /** - * @var array - */ + /** @var string[] */ private $excludedTables = []; - /** - * @var string - */ + /** @var string */ private $tenantColumnName; - /** - * @var string - */ + /** @var string */ private $tenantColumnType = 'integer'; /** @@ -75,13 +51,13 @@ class MultiTenantVisitor implements Visitor private $distributionName; /** - * @param array $excludedTables + * @param string[] $excludedTables * @param string $tenantColumnName * @param string|null $distributionName */ public function __construct(array $excludedTables = [], $tenantColumnName = 'tenant_id', $distributionName = null) { - $this->excludedTables = $excludedTables; + $this->excludedTables = $excludedTables; $this->tenantColumnName = $tenantColumnName; $this->distributionName = $distributionName ?: $tenantColumnName; } @@ -96,12 +72,12 @@ public function acceptTable(Table $table) } $table->addColumn($this->tenantColumnName, $this->tenantColumnType, [ - 'default' => "federation_filtering_value('". $this->distributionName ."')", + 'default' => "federation_filtering_value('" . $this->distributionName . "')", ]); $clusteredIndex = $this->getClusteredIndex($table); - $indexColumns = $clusteredIndex->getColumns(); + $indexColumns = $clusteredIndex->getColumns(); $indexColumns[] = $this->tenantColumnName; if ($clusteredIndex->isPrimary()) { @@ -115,22 +91,24 @@ public function acceptTable(Table $table) } /** - * @param \Doctrine\DBAL\Schema\Table $table + * @param Table $table * - * @return \Doctrine\DBAL\Schema\Index + * @return Index * - * @throws \RuntimeException + * @throws RuntimeException */ private function getClusteredIndex($table) { foreach ($table->getIndexes() as $index) { if ($index->isPrimary() && ! $index->hasFlag('nonclustered')) { return $index; - } elseif ($index->hasFlag('clustered')) { + } + + if ($index->hasFlag('clustered')) { return $index; } } - throw new \RuntimeException("No clustered index found on table " . $table->getName()); + throw new RuntimeException('No clustered index found on table ' . $table->getName()); } /** diff --git a/lib/Doctrine/DBAL/Sharding/ShardChoser/MultiTenantShardChoser.php b/lib/Doctrine/DBAL/Sharding/ShardChoser/MultiTenantShardChoser.php index f1d51b8c957..584e8155ae9 100644 --- a/lib/Doctrine/DBAL/Sharding/ShardChoser/MultiTenantShardChoser.php +++ b/lib/Doctrine/DBAL/Sharding/ShardChoser/MultiTenantShardChoser.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Sharding\ShardChoser; @@ -24,8 +7,6 @@ /** * The MultiTenant Shard choser assumes that the distribution value directly * maps to the shard id. - * - * @author Benjamin Eberlei */ class MultiTenantShardChoser implements ShardChoser { diff --git a/lib/Doctrine/DBAL/Sharding/ShardChoser/ShardChoser.php b/lib/Doctrine/DBAL/Sharding/ShardChoser/ShardChoser.php index 8bbf799b892..6f8a9d47702 100644 --- a/lib/Doctrine/DBAL/Sharding/ShardChoser/ShardChoser.php +++ b/lib/Doctrine/DBAL/Sharding/ShardChoser/ShardChoser.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Sharding\ShardChoser; @@ -24,18 +7,15 @@ /** * Given a distribution value this shard-choser strategy will pick the shard to * connect to for retrieving rows with the distribution value. - * - * @author Benjamin Eberlei */ interface ShardChoser { /** * Picks a shard for the given distribution value. * - * @param string|int $distributionValue - * @param \Doctrine\DBAL\Sharding\PoolingShardConnection $conn + * @param string|int $distributionValue * * @return string|int */ - function pickShard($distributionValue, PoolingShardConnection $conn); + public function pickShard($distributionValue, PoolingShardConnection $conn); } diff --git a/lib/Doctrine/DBAL/Sharding/ShardManager.php b/lib/Doctrine/DBAL/Sharding/ShardManager.php index 98c8351d7c2..7b37bb2c7e1 100644 --- a/lib/Doctrine/DBAL/Sharding/ShardManager.php +++ b/lib/Doctrine/DBAL/Sharding/ShardManager.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Sharding; @@ -34,8 +17,6 @@ * executed against the last shard that was selected. If a query is created for * a shard Y but then a shard X is selected when its actually executed you * will hit the wrong shard. - * - * @author Benjamin Eberlei */ interface ShardManager { @@ -47,7 +28,7 @@ interface ShardManager * * @return void */ - function selectGlobal(); + public function selectGlobal(); /** * Selects the shard against which the queries after this statement will be issued. @@ -56,16 +37,16 @@ function selectGlobal(); * * @return void * - * @throws \Doctrine\DBAL\Sharding\ShardingException If no value is passed as shard identifier. + * @throws ShardingException If no value is passed as shard identifier. */ - function selectShard($distributionValue); + public function selectShard($distributionValue); /** * Gets the distribution value currently used for sharding. * * @return string|null */ - function getCurrentDistributionValue(); + public function getCurrentDistributionValue(); /** * Gets information about the amount of shards and other details. @@ -73,9 +54,9 @@ function getCurrentDistributionValue(); * Format is implementation specific, each shard is one element and has an * 'id' attribute at least. * - * @return array + * @return mixed[][] */ - function getShards(); + public function getShards(); /** * Queries all shards in undefined order and return the results appended to @@ -83,11 +64,11 @@ function getShards(); * * Using {@link \Doctrine\DBAL\Connection::fetchAll} to retrieve rows internally. * - * @param string $sql - * @param array $params - * @param array $types + * @param string $sql + * @param mixed[] $params + * @param int[]|string[] $types * - * @return array + * @return mixed[] */ - function queryAll($sql, array $params, array $types); + public function queryAll($sql, array $params, array $types); } diff --git a/lib/Doctrine/DBAL/Sharding/ShardingException.php b/lib/Doctrine/DBAL/Sharding/ShardingException.php index aa14d32af30..b46bda2ff0d 100644 --- a/lib/Doctrine/DBAL/Sharding/ShardingException.php +++ b/lib/Doctrine/DBAL/Sharding/ShardingException.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Sharding; @@ -23,8 +6,6 @@ /** * Sharding related Exceptions - * - * @since 2.3 */ class ShardingException extends DBALException { @@ -33,7 +14,7 @@ class ShardingException extends DBALException */ public static function notImplemented() { - return new self("This functionality is not implemented with this sharding provider.", 1331557937); + return new self('This functionality is not implemented with this sharding provider.', 1331557937); } /** @@ -41,7 +22,7 @@ public static function notImplemented() */ public static function missingDefaultFederationName() { - return new self("SQLAzure requires a federation name to be set during sharding configuration.", 1332141280); + return new self('SQLAzure requires a federation name to be set during sharding configuration.', 1332141280); } /** @@ -49,7 +30,7 @@ public static function missingDefaultFederationName() */ public static function missingDefaultDistributionKey() { - return new self("SQLAzure requires a distribution key to be set during sharding configuration.", 1332141329); + return new self('SQLAzure requires a distribution key to be set during sharding configuration.', 1332141329); } /** @@ -57,7 +38,7 @@ public static function missingDefaultDistributionKey() */ public static function activeTransaction() { - return new self("Cannot switch shard during an active transaction.", 1332141766); + return new self('Cannot switch shard during an active transaction.', 1332141766); } /** @@ -65,7 +46,7 @@ public static function activeTransaction() */ public static function noShardDistributionValue() { - return new self("You have to specify a string or integer as shard distribution value.", 1332142103); + return new self('You have to specify a string or integer as shard distribution value.', 1332142103); } /** diff --git a/lib/Doctrine/DBAL/Statement.php b/lib/Doctrine/DBAL/Statement.php index 9ee252bd7d0..b65fa95e33a 100644 --- a/lib/Doctrine/DBAL/Statement.php +++ b/lib/Doctrine/DBAL/Statement.php @@ -1,37 +1,21 @@ . - */ namespace Doctrine\DBAL; -use Doctrine\DBAL\Types\Type; use Doctrine\DBAL\Driver\Statement as DriverStatement; +use Doctrine\DBAL\Platforms\AbstractPlatform; +use Doctrine\DBAL\Types\Type; +use IteratorAggregate; +use PDO; +use Throwable; use function is_array; use function is_string; /** * A thin wrapper around a Doctrine\DBAL\Driver\Statement that adds support * for logging, DBAL mapping types, etc. - * - * @author Roman Borschel - * @since 2.0 */ -class Statement implements \IteratorAggregate, DriverStatement +class Statement implements IteratorAggregate, DriverStatement { /** * The SQL statement. @@ -43,14 +27,14 @@ class Statement implements \IteratorAggregate, DriverStatement /** * The bound parameters. * - * @var array + * @var mixed[] */ protected $params = []; /** * The parameter types. * - * @var array + * @var int[]|string[] */ protected $types = []; @@ -64,28 +48,28 @@ class Statement implements \IteratorAggregate, DriverStatement /** * The underlying database platform. * - * @var \Doctrine\DBAL\Platforms\AbstractPlatform + * @var AbstractPlatform */ protected $platform; /** * The connection this statement is bound to and executed on. * - * @var \Doctrine\DBAL\Connection + * @var Connection */ protected $conn; /** * Creates a new Statement for the given SQL and Connection. * - * @param string $sql The SQL of the statement. - * @param \Doctrine\DBAL\Connection $conn The connection on which the statement should be executed. + * @param string $sql The SQL of the statement. + * @param Connection $conn The connection on which the statement should be executed. */ public function __construct($sql, Connection $conn) { - $this->sql = $sql; - $this->stmt = $conn->getWrappedConnection()->prepare($sql); - $this->conn = $conn; + $this->sql = $sql; + $this->stmt = $conn->getWrappedConnection()->prepare($sql); + $this->conn = $conn; $this->platform = $conn->getDatabasePlatform(); } @@ -97,22 +81,22 @@ public function __construct($sql, Connection $conn) * type and the value undergoes the conversion routines of the mapping type before * being bound. * - * @param string $name The name or position of the parameter. - * @param mixed $value The value of the parameter. - * @param mixed $type Either a PDO binding type or a DBAL mapping type name or instance. + * @param string|int $name The name or position of the parameter. + * @param mixed $value The value of the parameter. + * @param mixed $type Either a PDO binding type or a DBAL mapping type name or instance. * * @return bool TRUE on success, FALSE on failure. */ public function bindValue($name, $value, $type = ParameterType::STRING) { $this->params[$name] = $value; - $this->types[$name] = $type; + $this->types[$name] = $type; if ($type !== null) { if (is_string($type)) { $type = Type::getType($type); } if ($type instanceof Type) { - $value = $type->convertToDatabaseValue($value, $this->platform); + $value = $type->convertToDatabaseValue($value, $this->platform); $bindingType = $type->getBindingType(); } else { $bindingType = $type; @@ -129,18 +113,18 @@ public function bindValue($name, $value, $type = ParameterType::STRING) * * Binding a parameter by reference does not support DBAL mapping types. * - * @param string $name The name or position of the parameter. - * @param mixed $var The reference to the variable to bind. - * @param int $type The PDO binding type. - * @param int|null $length Must be specified when using an OUT bind - * so that PHP allocates enough memory to hold the returned value. + * @param string|int $name The name or position of the parameter. + * @param mixed $var The reference to the variable to bind. + * @param int $type The PDO binding type. + * @param int|null $length Must be specified when using an OUT bind + * so that PHP allocates enough memory to hold the returned value. * * @return bool TRUE on success, FALSE on failure. */ public function bindParam($name, &$var, $type = ParameterType::STRING, $length = null) { $this->params[$name] = $var; - $this->types[$name] = $type; + $this->types[$name] = $type; return $this->stmt->bindParam($name, $var, $type, $length); } @@ -148,11 +132,11 @@ public function bindParam($name, &$var, $type = ParameterType::STRING, $length = /** * Executes the statement with the currently bound parameters. * - * @param array|null $params + * @param mixed[]|null $params * * @return bool TRUE on success, FALSE on failure. * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ public function execute($params = null) { @@ -167,7 +151,7 @@ public function execute($params = null) try { $stmt = $this->stmt->execute($params); - } catch (\Exception $ex) { + } catch (Throwable $ex) { if ($logger) { $logger->stopQuery(); } @@ -183,7 +167,7 @@ public function execute($params = null) $logger->stopQuery(); } $this->params = []; - $this->types = []; + $this->types = []; return $stmt; } @@ -219,9 +203,7 @@ public function errorCode() } /** - * Fetches extended error information associated with the last operation on the statement. - * - * @return array + * {@inheritDoc} */ public function errorInfo() { @@ -255,7 +237,7 @@ public function getIterator() /** * {@inheritdoc} */ - public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) + public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { return $this->stmt->fetch($fetchMode); } @@ -273,11 +255,7 @@ public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = n } /** - * Returns a single column from the next row of a result set. - * - * @param int $columnIndex - * - * @return mixed A single column from the next row of a result set or FALSE if there are no more rows. + * {@inheritDoc} */ public function fetchColumn($columnIndex = 0) { diff --git a/lib/Doctrine/DBAL/Tools/Console/Command/ImportCommand.php b/lib/Doctrine/DBAL/Tools/Console/Command/ImportCommand.php index 61fb07fb0d6..0e815663786 100644 --- a/lib/Doctrine/DBAL/Tools/Console/Command/ImportCommand.php +++ b/lib/Doctrine/DBAL/Tools/Console/Command/ImportCommand.php @@ -1,25 +1,12 @@ . - */ namespace Doctrine\DBAL\Tools\Console\Command; +use Doctrine\DBAL\Driver\PDOConnection; use Doctrine\DBAL\Driver\PDOStatement; +use InvalidArgumentException; +use PDOException; +use RuntimeException; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; @@ -36,12 +23,7 @@ * Task for executing arbitrary SQL that can come from a file or directly from * the command line. * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel + * @deprecated Use a database client application instead */ class ImportCommand extends Command { @@ -53,10 +35,11 @@ protected function configure() $this ->setName('dbal:import') ->setDescription('Import SQL file(s) directly to Database.') - ->setDefinition([ - new InputArgument( - 'file', InputArgument::REQUIRED | InputArgument::IS_ARRAY, 'File path(s) of SQL to be executed.' - ) + ->setDefinition([new InputArgument( + 'file', + InputArgument::REQUIRED | InputArgument::IS_ARRAY, + 'File path(s) of SQL to be executed.' + ), ]) ->setHelp(<<getHelper('db')->getConnection(); - if (($fileNames = $input->getArgument('file')) !== null) { - foreach ((array) $fileNames as $fileName) { - $filePath = realpath($fileName); + $fileNames = $input->getArgument('file'); - // Phar compatibility. - if (false === $filePath) { - $filePath = $fileName; - } + if ($fileNames === null) { + return null; + } - if ( ! file_exists($filePath)) { - throw new \InvalidArgumentException( - sprintf("SQL file '%s' does not exist.", $filePath) - ); - } elseif ( ! is_readable($filePath)) { - throw new \InvalidArgumentException( - sprintf("SQL file '%s' does not have read permissions.", $filePath) - ); - } + foreach ((array) $fileNames as $fileName) { + $filePath = realpath($fileName); + + // Phar compatibility. + if ($filePath === false) { + $filePath = $fileName; + } - $output->write(sprintf("Processing file '%s'... ", $filePath)); - $sql = file_get_contents($filePath); + if (! file_exists($filePath)) { + throw new InvalidArgumentException( + sprintf("SQL file '%s' does not exist.", $filePath) + ); + } elseif (! is_readable($filePath)) { + throw new InvalidArgumentException( + sprintf("SQL file '%s' does not have read permissions.", $filePath) + ); + } - if ($conn instanceof \Doctrine\DBAL\Driver\PDOConnection) { - // PDO Drivers - try { - $lines = 0; + $output->write(sprintf("Processing file '%s'... ", $filePath)); + $sql = file_get_contents($filePath); - $stmt = $conn->prepare($sql); - assert($stmt instanceof PDOStatement); + if ($conn instanceof PDOConnection) { + // PDO Drivers + try { + $lines = 0; - $stmt->execute(); + $stmt = $conn->prepare($sql); + assert($stmt instanceof PDOStatement); - do { - // Required due to "MySQL has gone away!" issue - $stmt->fetch(); - $stmt->closeCursor(); + $stmt->execute(); - $lines++; - } while ($stmt->nextRowset()); + do { + // Required due to "MySQL has gone away!" issue + $stmt->fetch(); + $stmt->closeCursor(); - $output->write(sprintf('%d statements executed!', $lines) . PHP_EOL); - } catch (\PDOException $e) { - $output->write('error!' . PHP_EOL); + $lines++; + } while ($stmt->nextRowset()); - throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); - } - } else { - // Non-PDO Drivers (ie. OCI8 driver) - $stmt = $conn->prepare($sql); - $rs = $stmt->execute(); + $output->write(sprintf('%d statements executed!', $lines) . PHP_EOL); + } catch (PDOException $e) { + $output->write('error!' . PHP_EOL); - if ($rs) { - $output->writeln('OK!' . PHP_EOL); - } else { - $error = $stmt->errorInfo(); + throw new RuntimeException($e->getMessage(), $e->getCode(), $e); + } + } else { + // Non-PDO Drivers (ie. OCI8 driver) + $stmt = $conn->prepare($sql); + $rs = $stmt->execute(); - $output->write('error!' . PHP_EOL); + if (! $rs) { + $error = $stmt->errorInfo(); - throw new \RuntimeException($error[2], $error[0]); - } + $output->write('error!' . PHP_EOL); - $stmt->closeCursor(); + throw new RuntimeException($error[2], $error[0]); } + + $output->writeln('OK!' . PHP_EOL); + + $stmt->closeCursor(); } } + + return null; } } diff --git a/lib/Doctrine/DBAL/Tools/Console/Command/ReservedWordsCommand.php b/lib/Doctrine/DBAL/Tools/Console/Command/ReservedWordsCommand.php index 83587bdb544..2e0c48a815b 100644 --- a/lib/Doctrine/DBAL/Tools/Console/Command/ReservedWordsCommand.php +++ b/lib/Doctrine/DBAL/Tools/Console/Command/ReservedWordsCommand.php @@ -1,25 +1,27 @@ . - */ namespace Doctrine\DBAL\Tools\Console\Command; +use Doctrine\DBAL\Connection; +use Doctrine\DBAL\Platforms\Keywords\DB2Keywords; +use Doctrine\DBAL\Platforms\Keywords\MySQL57Keywords; +use Doctrine\DBAL\Platforms\Keywords\MySQL80Keywords; +use Doctrine\DBAL\Platforms\Keywords\MySQLKeywords; +use Doctrine\DBAL\Platforms\Keywords\OracleKeywords; +use Doctrine\DBAL\Platforms\Keywords\PostgreSQL91Keywords; +use Doctrine\DBAL\Platforms\Keywords\PostgreSQL92Keywords; +use Doctrine\DBAL\Platforms\Keywords\PostgreSQLKeywords; use Doctrine\DBAL\Platforms\Keywords\ReservedKeywordsValidator; +use Doctrine\DBAL\Platforms\Keywords\SQLAnywhere11Keywords; +use Doctrine\DBAL\Platforms\Keywords\SQLAnywhere12Keywords; +use Doctrine\DBAL\Platforms\Keywords\SQLAnywhere16Keywords; +use Doctrine\DBAL\Platforms\Keywords\SQLAnywhereKeywords; +use Doctrine\DBAL\Platforms\Keywords\SQLiteKeywords; +use Doctrine\DBAL\Platforms\Keywords\SQLServer2005Keywords; +use Doctrine\DBAL\Platforms\Keywords\SQLServer2008Keywords; +use Doctrine\DBAL\Platforms\Keywords\SQLServer2012Keywords; +use Doctrine\DBAL\Platforms\Keywords\SQLServerKeywords; +use InvalidArgumentException; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; @@ -30,27 +32,25 @@ class ReservedWordsCommand extends Command { - /** - * @var array - */ + /** @var string[] */ private $keywordListClasses = [ - 'mysql' => 'Doctrine\DBAL\Platforms\Keywords\MySQLKeywords', - 'mysql57' => 'Doctrine\DBAL\Platforms\Keywords\MySQL57Keywords', - 'mysql80' => 'Doctrine\DBAL\Platforms\Keywords\MySQL80Keywords', - 'sqlserver' => 'Doctrine\DBAL\Platforms\Keywords\SQLServerKeywords', - 'sqlserver2005' => 'Doctrine\DBAL\Platforms\Keywords\SQLServer2005Keywords', - 'sqlserver2008' => 'Doctrine\DBAL\Platforms\Keywords\SQLServer2008Keywords', - 'sqlserver2012' => 'Doctrine\DBAL\Platforms\Keywords\SQLServer2012Keywords', - 'sqlite' => 'Doctrine\DBAL\Platforms\Keywords\SQLiteKeywords', - 'pgsql' => 'Doctrine\DBAL\Platforms\Keywords\PostgreSQLKeywords', - 'pgsql91' => 'Doctrine\DBAL\Platforms\Keywords\PostgreSQL91Keywords', - 'pgsql92' => 'Doctrine\DBAL\Platforms\Keywords\PostgreSQL92Keywords', - 'oracle' => 'Doctrine\DBAL\Platforms\Keywords\OracleKeywords', - 'db2' => 'Doctrine\DBAL\Platforms\Keywords\DB2Keywords', - 'sqlanywhere' => 'Doctrine\DBAL\Platforms\Keywords\SQLAnywhereKeywords', - 'sqlanywhere11' => 'Doctrine\DBAL\Platforms\Keywords\SQLAnywhere11Keywords', - 'sqlanywhere12' => 'Doctrine\DBAL\Platforms\Keywords\SQLAnywhere12Keywords', - 'sqlanywhere16' => 'Doctrine\DBAL\Platforms\Keywords\SQLAnywhere16Keywords', + 'mysql' => MySQLKeywords::class, + 'mysql57' => MySQL57Keywords::class, + 'mysql80' => MySQL80Keywords::class, + 'sqlserver' => SQLServerKeywords::class, + 'sqlserver2005' => SQLServer2005Keywords::class, + 'sqlserver2008' => SQLServer2008Keywords::class, + 'sqlserver2012' => SQLServer2012Keywords::class, + 'sqlite' => SQLiteKeywords::class, + 'pgsql' => PostgreSQLKeywords::class, + 'pgsql91' => PostgreSQL91Keywords::class, + 'pgsql92' => PostgreSQL92Keywords::class, + 'oracle' => OracleKeywords::class, + 'db2' => DB2Keywords::class, + 'sqlanywhere' => SQLAnywhereKeywords::class, + 'sqlanywhere11' => SQLAnywhere11Keywords::class, + 'sqlanywhere12' => SQLAnywhere12Keywords::class, + 'sqlanywhere16' => SQLAnywhere16Keywords::class, ]; /** @@ -74,10 +74,12 @@ protected function configure() $this ->setName('dbal:reserved-words') ->setDescription('Checks if the current database contains identifiers that are reserved.') - ->setDefinition([ - new InputOption( - 'list', 'l', InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Keyword-List name.' - ) + ->setDefinition([new InputOption( + 'list', + 'l', + InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, + 'Keyword-List name.' + ), ]) ->setHelp(<<getHelper('db')->getConnection(); $keywordLists = (array) $input->getOption('list'); - if ( ! $keywordLists) { + if (! $keywordLists) { $keywordLists = [ 'mysql', 'mysql57', @@ -146,27 +148,24 @@ protected function execute(InputInterface $input, OutputInterface $output) $keywords = []; foreach ($keywordLists as $keywordList) { - if (!isset($this->keywordListClasses[$keywordList])) { - throw new \InvalidArgumentException( - "There exists no keyword list with name '" . $keywordList . "'. ". - "Known lists: " . implode(", ", array_keys($this->keywordListClasses)) + if (! isset($this->keywordListClasses[$keywordList])) { + throw new InvalidArgumentException( + "There exists no keyword list with name '" . $keywordList . "'. " . + 'Known lists: ' . implode(', ', array_keys($this->keywordListClasses)) ); } - $class = $this->keywordListClasses[$keywordList]; - $keywords[] = new $class; + $class = $this->keywordListClasses[$keywordList]; + $keywords[] = new $class(); } - $output->write('Checking keyword violations for ' . implode(", ", $keywordLists) . "...", true); + $output->write('Checking keyword violations for ' . implode(', ', $keywordLists) . '...', true); - /* @var $schema \Doctrine\DBAL\Schema\Schema */ - $schema = $conn->getSchemaManager()->createSchema(); + $schema = $conn->getSchemaManager()->createSchema(); $visitor = new ReservedKeywordsValidator($keywords); $schema->visit($visitor); $violations = $visitor->getViolations(); - if (count($violations) == 0) { - $output->write("No reserved keywords violations have been found!", true); - } else { + if (count($violations) !== 0) { $output->write('There are ' . count($violations) . ' reserved keyword violations in your database schema:', true); foreach ($violations as $violation) { $output->write(' - ' . $violation, true); @@ -175,6 +174,8 @@ protected function execute(InputInterface $input, OutputInterface $output) return 1; } + $output->write('No reserved keywords violations have been found!', true); + return 0; } } diff --git a/lib/Doctrine/DBAL/Tools/Console/Command/RunSqlCommand.php b/lib/Doctrine/DBAL/Tools/Console/Command/RunSqlCommand.php index f65b0de0f7e..8361219ad08 100644 --- a/lib/Doctrine/DBAL/Tools/Console/Command/RunSqlCommand.php +++ b/lib/Doctrine/DBAL/Tools/Console/Command/RunSqlCommand.php @@ -1,43 +1,21 @@ . - */ namespace Doctrine\DBAL\Tools\Console\Command; use Doctrine\DBAL\Tools\Dumper; +use LogicException; +use RuntimeException; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; use function is_numeric; use function stripos; /** * Task for executing arbitrary SQL that can come from a file or directly from * the command line. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class RunSqlCommand extends Command { @@ -67,14 +45,16 @@ protected function execute(InputInterface $input, OutputInterface $output) { $conn = $this->getHelper('db')->getConnection(); - if (($sql = $input->getArgument('sql')) === null) { - throw new \RuntimeException("Argument 'SQL' is required in order to execute this command correctly."); + $sql = $input->getArgument('sql'); + + if ($sql === null) { + throw new RuntimeException("Argument 'SQL' is required in order to execute this command correctly."); } $depth = $input->getOption('depth'); - if ( ! is_numeric($depth)) { - throw new \LogicException("Option 'depth' must contains an integer value"); + if (! is_numeric($depth)) { + throw new LogicException("Option 'depth' must contains an integer value"); } if (stripos($sql, 'select') === 0 || $input->getOption('force-fetch')) { diff --git a/lib/Doctrine/DBAL/Tools/Console/ConsoleRunner.php b/lib/Doctrine/DBAL/Tools/Console/ConsoleRunner.php index 61412a7cc5a..520a9af80aa 100644 --- a/lib/Doctrine/DBAL/Tools/Console/ConsoleRunner.php +++ b/lib/Doctrine/DBAL/Tools/Console/ConsoleRunner.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Tools\Console; @@ -26,6 +9,7 @@ use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper; use Doctrine\DBAL\Version; use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Helper\HelperSet; /** @@ -36,22 +20,19 @@ class ConsoleRunner /** * Create a Symfony Console HelperSet * - * @param Connection $connection - * * @return HelperSet */ public static function createHelperSet(Connection $connection) { return new HelperSet([ - 'db' => new ConnectionHelper($connection) + 'db' => new ConnectionHelper($connection), ]); } /** * Runs console with the given helperset. * - * @param \Symfony\Component\Console\Helper\HelperSet $helperSet - * @param \Symfony\Component\Console\Command\Command[] $commands + * @param Command[] $commands * * @return void */ @@ -69,8 +50,6 @@ public static function run(HelperSet $helperSet, $commands = []) } /** - * @param Application $cli - * * @return void */ public static function addCommands(Application $cli) diff --git a/lib/Doctrine/DBAL/Tools/Console/Helper/ConnectionHelper.php b/lib/Doctrine/DBAL/Tools/Console/Helper/ConnectionHelper.php index 1331c2baea4..b5497d068a0 100644 --- a/lib/Doctrine/DBAL/Tools/Console/Helper/ConnectionHelper.php +++ b/lib/Doctrine/DBAL/Tools/Console/Helper/ConnectionHelper.php @@ -1,50 +1,24 @@ . - */ namespace Doctrine\DBAL\Tools\Console\Helper; -use Symfony\Component\Console\Helper\Helper; use Doctrine\DBAL\Connection; +use Symfony\Component\Console\Helper\Helper; /** * Doctrine CLI Connection Helper. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class ConnectionHelper extends Helper { /** * The Doctrine database Connection. * - * @var \Doctrine\DBAL\Connection + * @var Connection */ protected $_connection; /** - * Constructor. - * - * @param \Doctrine\DBAL\Connection $connection The Doctrine database Connection. + * @param Connection $connection The Doctrine database Connection. */ public function __construct(Connection $connection) { @@ -54,7 +28,7 @@ public function __construct(Connection $connection) /** * Retrieves the Doctrine database Connection. * - * @return \Doctrine\DBAL\Connection + * @return Connection */ public function getConnection() { diff --git a/lib/Doctrine/DBAL/Types/ArrayType.php b/lib/Doctrine/DBAL/Types/ArrayType.php index 7fc4fcc9be6..9bb8e578b23 100644 --- a/lib/Doctrine/DBAL/Types/ArrayType.php +++ b/lib/Doctrine/DBAL/Types/ArrayType.php @@ -1,34 +1,17 @@ . - */ namespace Doctrine\DBAL\Types; use Doctrine\DBAL\Platforms\AbstractPlatform; use function is_resource; +use function restore_error_handler; use function serialize; +use function set_error_handler; use function stream_get_contents; use function unserialize; /** * Type that maps a PHP array to a clob SQL type. - * - * @since 2.0 */ class ArrayType extends Type { @@ -58,13 +41,17 @@ public function convertToPHPValue($value, AbstractPlatform $platform) return null; } - $value = (is_resource($value)) ? stream_get_contents($value) : $value; - $val = unserialize($value); - if ($val === false && $value != 'b:0;') { - throw ConversionException::conversionFailed($value, $this->getName()); - } + $value = is_resource($value) ? stream_get_contents($value) : $value; - return $val; + set_error_handler(function (int $code, string $message) : void { + throw ConversionException::conversionFailedUnserialization($this->getName(), $message); + }); + + try { + return unserialize($value); + } finally { + restore_error_handler(); + } } /** diff --git a/lib/Doctrine/DBAL/Types/BigIntType.php b/lib/Doctrine/DBAL/Types/BigIntType.php index 9a2b42953ad..1d320d624d4 100644 --- a/lib/Doctrine/DBAL/Types/BigIntType.php +++ b/lib/Doctrine/DBAL/Types/BigIntType.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Types; @@ -24,9 +7,6 @@ /** * Type that maps a database BIGINT to a PHP string. - * - * @author robo - * @since 2.0 */ class BigIntType extends Type implements PhpIntegerMappingType { @@ -59,6 +39,6 @@ public function getBindingType() */ public function convertToPHPValue($value, AbstractPlatform $platform) { - return (null === $value) ? null : (string) $value; + return $value === null ? null : (string) $value; } } diff --git a/lib/Doctrine/DBAL/Types/BinaryType.php b/lib/Doctrine/DBAL/Types/BinaryType.php index 57f0bbf0f8f..14362e840ae 100644 --- a/lib/Doctrine/DBAL/Types/BinaryType.php +++ b/lib/Doctrine/DBAL/Types/BinaryType.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Types; @@ -29,9 +12,6 @@ /** * Type that maps ab SQL BINARY/VARBINARY to a PHP resource stream. - * - * @author Steve Müller - * @since 2.5 */ class BinaryType extends Type { @@ -48,7 +28,7 @@ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $pla */ public function convertToPHPValue($value, AbstractPlatform $platform) { - if (null === $value) { + if ($value === null) { return null; } @@ -59,7 +39,7 @@ public function convertToPHPValue($value, AbstractPlatform $platform) $value = $fp; } - if ( ! is_resource($value)) { + if (! is_resource($value)) { throw ConversionException::conversionFailed($value, self::BINARY); } diff --git a/lib/Doctrine/DBAL/Types/BlobType.php b/lib/Doctrine/DBAL/Types/BlobType.php index 84ee48af83e..c309f0f0637 100644 --- a/lib/Doctrine/DBAL/Types/BlobType.php +++ b/lib/Doctrine/DBAL/Types/BlobType.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Types; @@ -29,8 +12,6 @@ /** * Type that maps an SQL BLOB to a PHP resource stream. - * - * @since 2.2 */ class BlobType extends Type { @@ -47,7 +28,7 @@ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $pla */ public function convertToPHPValue($value, AbstractPlatform $platform) { - if (null === $value) { + if ($value === null) { return null; } @@ -58,7 +39,7 @@ public function convertToPHPValue($value, AbstractPlatform $platform) $value = $fp; } - if ( ! is_resource($value)) { + if (! is_resource($value)) { throw ConversionException::conversionFailed($value, self::BLOB); } diff --git a/lib/Doctrine/DBAL/Types/BooleanType.php b/lib/Doctrine/DBAL/Types/BooleanType.php index 748f7f52942..976f00e1fb7 100644 --- a/lib/Doctrine/DBAL/Types/BooleanType.php +++ b/lib/Doctrine/DBAL/Types/BooleanType.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Types; @@ -24,8 +7,6 @@ /** * Type that maps an SQL boolean to a PHP boolean. - * - * @since 2.0 */ class BooleanType extends Type { diff --git a/lib/Doctrine/DBAL/Types/ConversionException.php b/lib/Doctrine/DBAL/Types/ConversionException.php index df2eb74a38f..b9f8a82e7ec 100644 --- a/lib/Doctrine/DBAL/Types/ConversionException.php +++ b/lib/Doctrine/DBAL/Types/ConversionException.php @@ -1,34 +1,9 @@ . - */ -/** - * Conversion Exception is thrown when the database to PHP conversion fails. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - */ namespace Doctrine\DBAL\Types; +use Doctrine\DBAL\DBALException; +use Throwable; use function get_class; use function gettype; use function implode; @@ -38,7 +13,10 @@ use function strlen; use function substr; -class ConversionException extends \Doctrine\DBAL\DBALException +/** + * Conversion Exception is thrown when the database to PHP conversion fails. + */ +class ConversionException extends DBALException { /** * Thrown when a Database to Doctrine Type Conversion fails. @@ -50,7 +28,7 @@ class ConversionException extends \Doctrine\DBAL\DBALException */ public static function conversionFailed($value, $toType) { - $value = (strlen($value) > 32) ? substr($value, 0, 20) . '...' : $value; + $value = strlen($value) > 32 ? substr($value, 0, 20) . '...' : $value; return new self('Could not convert database value "' . $value . '" to Doctrine Type ' . $toType); } @@ -59,16 +37,15 @@ public static function conversionFailed($value, $toType) * Thrown when a Database to Doctrine Type Conversion fails and we can make a statement * about the expected format. * - * @param string $value - * @param string $toType - * @param string $expectedFormat - * @param \Exception|null $previous + * @param string $value + * @param string $toType + * @param string $expectedFormat * * @return \Doctrine\DBAL\Types\ConversionException */ - public static function conversionFailedFormat($value, $toType, $expectedFormat, \Exception $previous = null) + public static function conversionFailedFormat($value, $toType, $expectedFormat, ?Throwable $previous = null) { - $value = (strlen($value) > 32) ? substr($value, 0, 20) . '...' : $value; + $value = strlen($value) > 32 ? substr($value, 0, 20) . '...' : $value; return new self( 'Could not convert database value "' . $value . '" to Doctrine Type ' . @@ -120,4 +97,13 @@ public static function conversionFailedSerialization($value, $format, $error) $error )); } + + public static function conversionFailedUnserialization(string $format, string $error) : self + { + return new self(sprintf( + "Could not convert database value to '%s' as an error was triggered by the unserialization: '%s'", + $format, + $error + )); + } } diff --git a/lib/Doctrine/DBAL/Types/DateImmutableType.php b/lib/Doctrine/DBAL/Types/DateImmutableType.php index 8b9a91d7d32..196fc88c7b4 100644 --- a/lib/Doctrine/DBAL/Types/DateImmutableType.php +++ b/lib/Doctrine/DBAL/Types/DateImmutableType.php @@ -1,31 +1,12 @@ . - */ namespace Doctrine\DBAL\Types; +use DateTimeImmutable; use Doctrine\DBAL\Platforms\AbstractPlatform; /** * Immutable type of {@see DateType}. - * - * @since 2.6 - * @author Steve Müller */ class DateImmutableType extends DateType { @@ -42,18 +23,18 @@ public function getName() */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { - if (null === $value) { + if ($value === null) { return $value; } - if ($value instanceof \DateTimeImmutable) { + if ($value instanceof DateTimeImmutable) { return $value->format($platform->getDateFormatString()); } throw ConversionException::conversionFailedInvalidType( $value, $this->getName(), - ['null', \DateTimeImmutable::class] + ['null', DateTimeImmutable::class] ); } @@ -62,11 +43,11 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) */ public function convertToPHPValue($value, AbstractPlatform $platform) { - if ($value === null || $value instanceof \DateTimeImmutable) { + if ($value === null || $value instanceof DateTimeImmutable) { return $value; } - $dateTime = \DateTimeImmutable::createFromFormat('!' . $platform->getDateFormatString(), $value); + $dateTime = DateTimeImmutable::createFromFormat('!' . $platform->getDateFormatString(), $value); if (! $dateTime) { throw ConversionException::conversionFailedFormat( diff --git a/lib/Doctrine/DBAL/Types/DateIntervalType.php b/lib/Doctrine/DBAL/Types/DateIntervalType.php index 89425aa4547..30e61c9eaa5 100644 --- a/lib/Doctrine/DBAL/Types/DateIntervalType.php +++ b/lib/Doctrine/DBAL/Types/DateIntervalType.php @@ -2,7 +2,9 @@ namespace Doctrine\DBAL\Types; +use DateInterval; use Doctrine\DBAL\Platforms\AbstractPlatform; +use Throwable; use function substr; /** @@ -35,11 +37,11 @@ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $pla */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { - if (null === $value) { + if ($value === null) { return null; } - if ($value instanceof \DateInterval) { + if ($value instanceof DateInterval) { return $value->format(self::FORMAT); } @@ -51,7 +53,7 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) */ public function convertToPHPValue($value, AbstractPlatform $platform) { - if ($value === null || $value instanceof \DateInterval) { + if ($value === null || $value instanceof DateInterval) { return $value; } @@ -63,14 +65,14 @@ public function convertToPHPValue($value, AbstractPlatform $platform) } try { - $interval = new \DateInterval($value); + $interval = new DateInterval($value); if ($negative) { $interval->invert = 1; } return $interval; - } catch (\Exception $exception) { + } catch (Throwable $exception) { throw ConversionException::conversionFailedFormat($value, $this->getName(), self::FORMAT, $exception); } } diff --git a/lib/Doctrine/DBAL/Types/DateTimeImmutableType.php b/lib/Doctrine/DBAL/Types/DateTimeImmutableType.php index b8564fcddc3..fdda50faa44 100644 --- a/lib/Doctrine/DBAL/Types/DateTimeImmutableType.php +++ b/lib/Doctrine/DBAL/Types/DateTimeImmutableType.php @@ -1,31 +1,13 @@ . - */ namespace Doctrine\DBAL\Types; +use DateTimeImmutable; use Doctrine\DBAL\Platforms\AbstractPlatform; +use function date_create_immutable; /** * Immutable type of {@see DateTimeType}. - * - * @since 2.6 - * @author Steve Müller */ class DateTimeImmutableType extends DateTimeType { @@ -42,18 +24,18 @@ public function getName() */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { - if (null === $value) { + if ($value === null) { return $value; } - if ($value instanceof \DateTimeImmutable) { + if ($value instanceof DateTimeImmutable) { return $value->format($platform->getDateTimeFormatString()); } throw ConversionException::conversionFailedInvalidType( $value, $this->getName(), - ['null', \DateTimeImmutable::class] + ['null', DateTimeImmutable::class] ); } @@ -62,14 +44,14 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) */ public function convertToPHPValue($value, AbstractPlatform $platform) { - if ($value === null || $value instanceof \DateTimeImmutable) { + if ($value === null || $value instanceof DateTimeImmutable) { return $value; } - $dateTime = \DateTimeImmutable::createFromFormat($platform->getDateTimeFormatString(), $value); + $dateTime = DateTimeImmutable::createFromFormat($platform->getDateTimeFormatString(), $value); if (! $dateTime) { - $dateTime = \date_create_immutable($value); + $dateTime = date_create_immutable($value); } if (! $dateTime) { diff --git a/lib/Doctrine/DBAL/Types/DateTimeType.php b/lib/Doctrine/DBAL/Types/DateTimeType.php index 3cb76ee5b54..962d9d38da0 100644 --- a/lib/Doctrine/DBAL/Types/DateTimeType.php +++ b/lib/Doctrine/DBAL/Types/DateTimeType.php @@ -1,31 +1,14 @@ . - */ namespace Doctrine\DBAL\Types; +use DateTime; +use DateTimeInterface; use Doctrine\DBAL\Platforms\AbstractPlatform; use function date_create; /** * Type that maps an SQL DATETIME/TIMESTAMP to a PHP DateTime object. - * - * @since 2.0 */ class DateTimeType extends Type implements PhpDateTimeMappingType { @@ -50,11 +33,11 @@ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $pla */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { - if (null === $value) { + if ($value === null) { return $value; } - if ($value instanceof \DateTimeInterface) { + if ($value instanceof DateTimeInterface) { return $value->format($platform->getDateTimeFormatString()); } @@ -66,17 +49,17 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) */ public function convertToPHPValue($value, AbstractPlatform $platform) { - if ($value === null || $value instanceof \DateTimeInterface) { + if ($value === null || $value instanceof DateTimeInterface) { return $value; } - $val = \DateTime::createFromFormat($platform->getDateTimeFormatString(), $value); + $val = DateTime::createFromFormat($platform->getDateTimeFormatString(), $value); - if ( ! $val) { + if (! $val) { $val = date_create($value); } - if ( ! $val) { + if (! $val) { throw ConversionException::conversionFailedFormat($value, $this->getName(), $platform->getDateTimeFormatString()); } diff --git a/lib/Doctrine/DBAL/Types/DateTimeTzImmutableType.php b/lib/Doctrine/DBAL/Types/DateTimeTzImmutableType.php index 91f3eda75de..253c02e002b 100644 --- a/lib/Doctrine/DBAL/Types/DateTimeTzImmutableType.php +++ b/lib/Doctrine/DBAL/Types/DateTimeTzImmutableType.php @@ -1,31 +1,12 @@ . - */ namespace Doctrine\DBAL\Types; +use DateTimeImmutable; use Doctrine\DBAL\Platforms\AbstractPlatform; /** * Immutable type of {@see DateTimeTzType}. - * - * @since 2.6 - * @author Steve Müller */ class DateTimeTzImmutableType extends DateTimeTzType { @@ -42,18 +23,18 @@ public function getName() */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { - if (null === $value) { + if ($value === null) { return $value; } - if ($value instanceof \DateTimeImmutable) { + if ($value instanceof DateTimeImmutable) { return $value->format($platform->getDateTimeTzFormatString()); } throw ConversionException::conversionFailedInvalidType( $value, $this->getName(), - ['null', \DateTimeImmutable::class] + ['null', DateTimeImmutable::class] ); } @@ -62,11 +43,11 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) */ public function convertToPHPValue($value, AbstractPlatform $platform) { - if ($value === null || $value instanceof \DateTimeImmutable) { + if ($value === null || $value instanceof DateTimeImmutable) { return $value; } - $dateTime = \DateTimeImmutable::createFromFormat($platform->getDateTimeTzFormatString(), $value); + $dateTime = DateTimeImmutable::createFromFormat($platform->getDateTimeTzFormatString(), $value); if (! $dateTime) { throw ConversionException::conversionFailedFormat( diff --git a/lib/Doctrine/DBAL/Types/DateTimeTzType.php b/lib/Doctrine/DBAL/Types/DateTimeTzType.php index f731baf141d..0b78720ec3e 100644 --- a/lib/Doctrine/DBAL/Types/DateTimeTzType.php +++ b/lib/Doctrine/DBAL/Types/DateTimeTzType.php @@ -1,24 +1,9 @@ . - */ namespace Doctrine\DBAL\Types; +use DateTime; +use DateTimeInterface; use Doctrine\DBAL\Platforms\AbstractPlatform; /** @@ -36,13 +21,6 @@ * attached with a timezone such as Europe/Berlin gets saved into the database with * the offset and re-created from persistence with only the offset, not the original timezone * attached. - * - * @link www.doctrine-project.org - * @since 1.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class DateTimeTzType extends Type implements PhpDateTimeMappingType { @@ -67,11 +45,11 @@ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $pla */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { - if (null === $value) { + if ($value === null) { return $value; } - if ($value instanceof \DateTimeInterface) { + if ($value instanceof DateTimeInterface) { return $value->format($platform->getDateTimeTzFormatString()); } @@ -83,12 +61,12 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) */ public function convertToPHPValue($value, AbstractPlatform $platform) { - if ($value === null || $value instanceof \DateTimeInterface) { + if ($value === null || $value instanceof DateTimeInterface) { return $value; } - $val = \DateTime::createFromFormat($platform->getDateTimeTzFormatString(), $value); - if ( ! $val) { + $val = DateTime::createFromFormat($platform->getDateTimeTzFormatString(), $value); + if (! $val) { throw ConversionException::conversionFailedFormat($value, $this->getName(), $platform->getDateTimeTzFormatString()); } diff --git a/lib/Doctrine/DBAL/Types/DateType.php b/lib/Doctrine/DBAL/Types/DateType.php index e3ed6a9e71e..b5ad5356f69 100644 --- a/lib/Doctrine/DBAL/Types/DateType.php +++ b/lib/Doctrine/DBAL/Types/DateType.php @@ -1,30 +1,13 @@ . - */ namespace Doctrine\DBAL\Types; +use DateTime; +use DateTimeInterface; use Doctrine\DBAL\Platforms\AbstractPlatform; /** * Type that maps an SQL DATE to a PHP Date object. - * - * @since 2.0 */ class DateType extends Type { @@ -49,11 +32,11 @@ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $pla */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { - if (null === $value) { + if ($value === null) { return $value; } - if ($value instanceof \DateTimeInterface) { + if ($value instanceof DateTimeInterface) { return $value->format($platform->getDateFormatString()); } @@ -65,12 +48,12 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) */ public function convertToPHPValue($value, AbstractPlatform $platform) { - if ($value === null || $value instanceof \DateTimeInterface) { + if ($value === null || $value instanceof DateTimeInterface) { return $value; } - $val = \DateTime::createFromFormat('!'.$platform->getDateFormatString(), $value); - if ( ! $val) { + $val = DateTime::createFromFormat('!' . $platform->getDateFormatString(), $value); + if (! $val) { throw ConversionException::conversionFailedFormat($value, $this->getName(), $platform->getDateFormatString()); } diff --git a/lib/Doctrine/DBAL/Types/DecimalType.php b/lib/Doctrine/DBAL/Types/DecimalType.php index 42c05d69a71..318cb2476b7 100644 --- a/lib/Doctrine/DBAL/Types/DecimalType.php +++ b/lib/Doctrine/DBAL/Types/DecimalType.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Types; @@ -23,8 +6,6 @@ /** * Type that maps an SQL DECIMAL to a PHP string. - * - * @since 2.0 */ class DecimalType extends Type { diff --git a/lib/Doctrine/DBAL/Types/FloatType.php b/lib/Doctrine/DBAL/Types/FloatType.php index 87f9c32ae1a..3ad9aa737fa 100644 --- a/lib/Doctrine/DBAL/Types/FloatType.php +++ b/lib/Doctrine/DBAL/Types/FloatType.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Types; @@ -44,6 +27,6 @@ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $pla */ public function convertToPHPValue($value, AbstractPlatform $platform) { - return (null === $value) ? null : (double) $value; + return $value === null ? null : (float) $value; } } diff --git a/lib/Doctrine/DBAL/Types/GuidType.php b/lib/Doctrine/DBAL/Types/GuidType.php index 761d58a8e85..a9ab21537c5 100644 --- a/lib/Doctrine/DBAL/Types/GuidType.php +++ b/lib/Doctrine/DBAL/Types/GuidType.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Types; @@ -23,9 +6,6 @@ /** * Represents a GUID/UUID datatype (both are actually synonyms) in the database. - * - * @author Benjamin Eberlei - * @since 2.3 */ class GuidType extends StringType { @@ -50,6 +30,6 @@ public function getName() */ public function requiresSQLCommentHint(AbstractPlatform $platform) { - return !$platform->hasNativeGuidType(); + return ! $platform->hasNativeGuidType(); } } diff --git a/lib/Doctrine/DBAL/Types/IntegerType.php b/lib/Doctrine/DBAL/Types/IntegerType.php index 3c83341ded0..f04f3c7e008 100644 --- a/lib/Doctrine/DBAL/Types/IntegerType.php +++ b/lib/Doctrine/DBAL/Types/IntegerType.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Types; @@ -24,9 +7,6 @@ /** * Type that maps an SQL INT to a PHP integer. - * - * @author Roman Borschel - * @since 2.0 */ class IntegerType extends Type implements PhpIntegerMappingType { @@ -51,7 +31,7 @@ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $pla */ public function convertToPHPValue($value, AbstractPlatform $platform) { - return (null === $value) ? null : (int) $value; + return $value === null ? null : (int) $value; } /** diff --git a/lib/Doctrine/DBAL/Types/JsonArrayType.php b/lib/Doctrine/DBAL/Types/JsonArrayType.php index 5650eb51856..beae8038737 100644 --- a/lib/Doctrine/DBAL/Types/JsonArrayType.php +++ b/lib/Doctrine/DBAL/Types/JsonArrayType.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Types; @@ -27,9 +10,7 @@ /** * Array Type which can be used to generate json arrays. * - * @since 2.3 * @deprecated Use JsonType instead - * @author Johannes M. Schmitt */ class JsonArrayType extends JsonType { @@ -42,7 +23,7 @@ public function convertToPHPValue($value, AbstractPlatform $platform) return []; } - $value = (is_resource($value)) ? stream_get_contents($value) : $value; + $value = is_resource($value) ? stream_get_contents($value) : $value; return json_decode($value, true); } diff --git a/lib/Doctrine/DBAL/Types/JsonType.php b/lib/Doctrine/DBAL/Types/JsonType.php index 6395332c682..00cd3f80fcf 100644 --- a/lib/Doctrine/DBAL/Types/JsonType.php +++ b/lib/Doctrine/DBAL/Types/JsonType.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Types; @@ -30,9 +13,6 @@ /** * Type generating json objects values - * - * @since 2.6 - * @author Baptiste Clavié */ class JsonType extends Type { @@ -49,13 +29,13 @@ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $pla */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { - if (null === $value) { + if ($value === null) { return null; } $encoded = json_encode($value); - if (JSON_ERROR_NONE !== json_last_error()) { + if (json_last_error() !== JSON_ERROR_NONE) { throw ConversionException::conversionFailedSerialization($value, 'json', json_last_error_msg()); } diff --git a/lib/Doctrine/DBAL/Types/ObjectType.php b/lib/Doctrine/DBAL/Types/ObjectType.php index 95fe84a5a19..081ec483b16 100644 --- a/lib/Doctrine/DBAL/Types/ObjectType.php +++ b/lib/Doctrine/DBAL/Types/ObjectType.php @@ -1,34 +1,17 @@ . - */ namespace Doctrine\DBAL\Types; use Doctrine\DBAL\Platforms\AbstractPlatform; use function is_resource; +use function restore_error_handler; use function serialize; +use function set_error_handler; use function stream_get_contents; use function unserialize; /** * Type that maps a PHP object to a clob SQL type. - * - * @since 2.0 */ class ObjectType extends Type { @@ -57,13 +40,17 @@ public function convertToPHPValue($value, AbstractPlatform $platform) return null; } - $value = (is_resource($value)) ? stream_get_contents($value) : $value; - $val = unserialize($value); - if ($val === false && $value !== 'b:0;') { - throw ConversionException::conversionFailed($value, $this->getName()); - } + $value = is_resource($value) ? stream_get_contents($value) : $value; - return $val; + set_error_handler(function (int $code, string $message) : void { + throw ConversionException::conversionFailedUnserialization($this->getName(), $message); + }); + + try { + return unserialize($value); + } finally { + restore_error_handler(); + } } /** diff --git a/lib/Doctrine/DBAL/Types/PhpDateTimeMappingType.php b/lib/Doctrine/DBAL/Types/PhpDateTimeMappingType.php index d530d8cf074..45658505330 100644 --- a/lib/Doctrine/DBAL/Types/PhpDateTimeMappingType.php +++ b/lib/Doctrine/DBAL/Types/PhpDateTimeMappingType.php @@ -1,26 +1,10 @@ . - */ namespace Doctrine\DBAL\Types; /** * Implementations should map a database type to a PHP DateTimeInterface instance. + * * @internal */ interface PhpDateTimeMappingType diff --git a/lib/Doctrine/DBAL/Types/PhpIntegerMappingType.php b/lib/Doctrine/DBAL/Types/PhpIntegerMappingType.php index 034aaecb33a..b48e29c865a 100644 --- a/lib/Doctrine/DBAL/Types/PhpIntegerMappingType.php +++ b/lib/Doctrine/DBAL/Types/PhpIntegerMappingType.php @@ -1,26 +1,10 @@ . - */ namespace Doctrine\DBAL\Types; /** * Implementations should map a database type to a PHP integer. + * * @internal */ interface PhpIntegerMappingType diff --git a/lib/Doctrine/DBAL/Types/SimpleArrayType.php b/lib/Doctrine/DBAL/Types/SimpleArrayType.php index fb01479e322..d23776f5f0a 100644 --- a/lib/Doctrine/DBAL/Types/SimpleArrayType.php +++ b/lib/Doctrine/DBAL/Types/SimpleArrayType.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Types; @@ -29,9 +12,6 @@ * Array Type which can be used for simple values. * * Only use this type if you are sure that your values cannot contain a ",". - * - * @since 2.3 - * @author Johannes M. Schmitt */ class SimpleArrayType extends Type { @@ -48,7 +28,7 @@ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $pla */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { - if (!$value) { + if (! $value) { return null; } @@ -64,7 +44,7 @@ public function convertToPHPValue($value, AbstractPlatform $platform) return []; } - $value = (is_resource($value)) ? stream_get_contents($value) : $value; + $value = is_resource($value) ? stream_get_contents($value) : $value; return explode(',', $value); } diff --git a/lib/Doctrine/DBAL/Types/SmallIntType.php b/lib/Doctrine/DBAL/Types/SmallIntType.php index 1a2abdbe062..bca8a533f06 100644 --- a/lib/Doctrine/DBAL/Types/SmallIntType.php +++ b/lib/Doctrine/DBAL/Types/SmallIntType.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Types; @@ -24,8 +7,6 @@ /** * Type that maps a database SMALLINT to a PHP integer. - * - * @author robo */ class SmallIntType extends Type implements PhpIntegerMappingType { @@ -50,7 +31,7 @@ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $pla */ public function convertToPHPValue($value, AbstractPlatform $platform) { - return (null === $value) ? null : (int) $value; + return $value === null ? null : (int) $value; } /** diff --git a/lib/Doctrine/DBAL/Types/StringType.php b/lib/Doctrine/DBAL/Types/StringType.php index 39bd32dbc8e..879359a13d8 100644 --- a/lib/Doctrine/DBAL/Types/StringType.php +++ b/lib/Doctrine/DBAL/Types/StringType.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Types; @@ -23,8 +6,6 @@ /** * Type that maps an SQL VARCHAR to a PHP string. - * - * @since 2.0 */ class StringType extends Type { diff --git a/lib/Doctrine/DBAL/Types/TextType.php b/lib/Doctrine/DBAL/Types/TextType.php index bd72355464d..635d4f7de49 100644 --- a/lib/Doctrine/DBAL/Types/TextType.php +++ b/lib/Doctrine/DBAL/Types/TextType.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL\Types; @@ -25,8 +8,6 @@ /** * Type that maps an SQL CLOB to a PHP string. - * - * @since 2.0 */ class TextType extends Type { @@ -43,7 +24,7 @@ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $pla */ public function convertToPHPValue($value, AbstractPlatform $platform) { - return (is_resource($value)) ? stream_get_contents($value) : $value; + return is_resource($value) ? stream_get_contents($value) : $value; } /** diff --git a/lib/Doctrine/DBAL/Types/TimeImmutableType.php b/lib/Doctrine/DBAL/Types/TimeImmutableType.php index 118d80ea8df..8cb870fb393 100644 --- a/lib/Doctrine/DBAL/Types/TimeImmutableType.php +++ b/lib/Doctrine/DBAL/Types/TimeImmutableType.php @@ -1,31 +1,12 @@ . - */ namespace Doctrine\DBAL\Types; +use DateTimeImmutable; use Doctrine\DBAL\Platforms\AbstractPlatform; /** * Immutable type of {@see TimeType}. - * - * @since 2.6 - * @author Steve Müller */ class TimeImmutableType extends TimeType { @@ -42,18 +23,18 @@ public function getName() */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { - if (null === $value) { + if ($value === null) { return $value; } - if ($value instanceof \DateTimeImmutable) { + if ($value instanceof DateTimeImmutable) { return $value->format($platform->getTimeFormatString()); } throw ConversionException::conversionFailedInvalidType( $value, $this->getName(), - ['null', \DateTimeImmutable::class] + ['null', DateTimeImmutable::class] ); } @@ -62,11 +43,11 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) */ public function convertToPHPValue($value, AbstractPlatform $platform) { - if ($value === null || $value instanceof \DateTimeImmutable) { + if ($value === null || $value instanceof DateTimeImmutable) { return $value; } - $dateTime = \DateTimeImmutable::createFromFormat('!' . $platform->getTimeFormatString(), $value); + $dateTime = DateTimeImmutable::createFromFormat('!' . $platform->getTimeFormatString(), $value); if (! $dateTime) { throw ConversionException::conversionFailedFormat( diff --git a/lib/Doctrine/DBAL/Types/TimeType.php b/lib/Doctrine/DBAL/Types/TimeType.php index 639533fad5c..c9895294e03 100644 --- a/lib/Doctrine/DBAL/Types/TimeType.php +++ b/lib/Doctrine/DBAL/Types/TimeType.php @@ -1,30 +1,13 @@ . - */ namespace Doctrine\DBAL\Types; +use DateTime; +use DateTimeInterface; use Doctrine\DBAL\Platforms\AbstractPlatform; /** * Type that maps an SQL TIME to a PHP DateTime object. - * - * @since 2.0 */ class TimeType extends Type { @@ -49,11 +32,11 @@ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $pla */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { - if (null === $value) { + if ($value === null) { return $value; } - if ($value instanceof \DateTimeInterface) { + if ($value instanceof DateTimeInterface) { return $value->format($platform->getTimeFormatString()); } @@ -65,12 +48,12 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) */ public function convertToPHPValue($value, AbstractPlatform $platform) { - if ($value === null || $value instanceof \DateTimeInterface) { + if ($value === null || $value instanceof DateTimeInterface) { return $value; } - $val = \DateTime::createFromFormat('!' . $platform->getTimeFormatString(), $value); - if ( ! $val) { + $val = DateTime::createFromFormat('!' . $platform->getTimeFormatString(), $value); + if (! $val) { throw ConversionException::conversionFailedFormat($value, $this->getName(), $platform->getTimeFormatString()); } diff --git a/lib/Doctrine/DBAL/Types/Type.php b/lib/Doctrine/DBAL/Types/Type.php index 453631e0aaa..ec1ab681356 100644 --- a/lib/Doctrine/DBAL/Types/Type.php +++ b/lib/Doctrine/DBAL/Types/Type.php @@ -1,80 +1,58 @@ . - */ namespace Doctrine\DBAL\Types; +use Doctrine\DBAL\DBALException; use Doctrine\DBAL\ParameterType; use Doctrine\DBAL\Platforms\AbstractPlatform; -use Doctrine\DBAL\DBALException; use function end; use function explode; -use function get_class; use function str_replace; /** * The base class for so-called Doctrine mapping types. * * A Type object is obtained by calling the static {@link getType()} method. - * - * @author Roman Borschel - * @author Benjamin Eberlei - * @since 2.0 */ abstract class Type { - const TARRAY = 'array'; - const SIMPLE_ARRAY = 'simple_array'; - const JSON_ARRAY = 'json_array'; - const JSON = 'json'; - const BIGINT = 'bigint'; - const BOOLEAN = 'boolean'; - const DATETIME = 'datetime'; - const DATETIME_IMMUTABLE = 'datetime_immutable'; - const DATETIMETZ = 'datetimetz'; - const DATETIMETZ_IMMUTABLE = 'datetimetz_immutable'; - const DATE = 'date'; - const DATE_IMMUTABLE = 'date_immutable'; - const TIME = 'time'; - const TIME_IMMUTABLE = 'time_immutable'; - const DECIMAL = 'decimal'; - const INTEGER = 'integer'; - const OBJECT = 'object'; - const SMALLINT = 'smallint'; - const STRING = 'string'; - const TEXT = 'text'; - const BINARY = 'binary'; - const BLOB = 'blob'; - const FLOAT = 'float'; - const GUID = 'guid'; - const DATEINTERVAL = 'dateinterval'; + public const TARRAY = 'array'; + public const SIMPLE_ARRAY = 'simple_array'; + public const JSON_ARRAY = 'json_array'; + public const JSON = 'json'; + public const BIGINT = 'bigint'; + public const BOOLEAN = 'boolean'; + public const DATETIME = 'datetime'; + public const DATETIME_IMMUTABLE = 'datetime_immutable'; + public const DATETIMETZ = 'datetimetz'; + public const DATETIMETZ_IMMUTABLE = 'datetimetz_immutable'; + public const DATE = 'date'; + public const DATE_IMMUTABLE = 'date_immutable'; + public const TIME = 'time'; + public const TIME_IMMUTABLE = 'time_immutable'; + public const DECIMAL = 'decimal'; + public const INTEGER = 'integer'; + public const OBJECT = 'object'; + public const SMALLINT = 'smallint'; + public const STRING = 'string'; + public const TEXT = 'text'; + public const BINARY = 'binary'; + public const BLOB = 'blob'; + public const FLOAT = 'float'; + public const GUID = 'guid'; + public const DATEINTERVAL = 'dateinterval'; /** * Map of already instantiated type objects. One instance per type (flyweight). * - * @var array + * @var self[] */ private static $_typeObjects = []; /** * The map of supported doctrine mapping types. * - * @var array + * @var string[] */ private static $_typesMap = [ self::TARRAY => ArrayType::class, @@ -115,8 +93,8 @@ final private function __construct() * Converts a value from its PHP representation to its database representation * of this type. * - * @param mixed $value The value to convert. - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform The currently used database platform. + * @param mixed $value The value to convert. + * @param AbstractPlatform $platform The currently used database platform. * * @return mixed The database representation of the value. */ @@ -129,8 +107,8 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) * Converts a value from its database representation to its PHP representation * of this type. * - * @param mixed $value The value to convert. - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform The currently used database platform. + * @param mixed $value The value to convert. + * @param AbstractPlatform $platform The currently used database platform. * * @return mixed The PHP representation of the value. */ @@ -142,11 +120,9 @@ public function convertToPHPValue($value, AbstractPlatform $platform) /** * Gets the default length of this type. * - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform + * @deprecated Rely on information provided by the platform instead. * * @return int|null - * - * @todo Needed? */ public function getDefaultLength(AbstractPlatform $platform) { @@ -156,8 +132,8 @@ public function getDefaultLength(AbstractPlatform $platform) /** * Gets the SQL declaration snippet for a field of this type. * - * @param array $fieldDeclaration The field declaration. - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform The currently used database platform. + * @param mixed[] $fieldDeclaration The field declaration. + * @param AbstractPlatform $platform The currently used database platform. * * @return string */ @@ -180,12 +156,12 @@ abstract public function getName(); * * @return \Doctrine\DBAL\Types\Type * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ public static function getType($name) { - if ( ! isset(self::$_typeObjects[$name])) { - if ( ! isset(self::$_typesMap[$name])) { + if (! isset(self::$_typeObjects[$name])) { + if (! isset(self::$_typesMap[$name])) { throw DBALException::unknownColumnType($name); } self::$_typeObjects[$name] = new self::$_typesMap[$name](); @@ -202,7 +178,7 @@ public static function getType($name) * * @return void * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ public static function addType($name, $className) { @@ -233,11 +209,11 @@ public static function hasType($name) * * @return void * - * @throws \Doctrine\DBAL\DBALException + * @throws DBALException */ public static function overrideType($name, $className) { - if ( ! isset(self::$_typesMap[$name])) { + if (! isset(self::$_typesMap[$name])) { throw DBALException::typeNotFound($name); } @@ -265,7 +241,7 @@ public function getBindingType() * Gets the types array map which holds all registered types and the corresponding * type class * - * @return array + * @return string[] */ public static function getTypesMap() { @@ -273,11 +249,13 @@ public static function getTypesMap() } /** + * @deprecated Relying on string representation is discouraged and will be removed in DBAL 3.0. + * * @return string */ public function __toString() { - $e = explode('\\', get_class($this)); + $e = explode('\\', static::class); return str_replace('Type', '', end($e)); } @@ -300,8 +278,7 @@ public function canRequireSQLConversion() /** * Modifies the SQL expression (identifier, parameter) to convert to a database value. * - * @param string $sqlExpr - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform + * @param string $sqlExpr * * @return string */ @@ -313,8 +290,8 @@ public function convertToDatabaseValueSQL($sqlExpr, AbstractPlatform $platform) /** * Modifies the SQL expression (identifier, parameter) to convert to a PHP value. * - * @param string $sqlExpr - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform + * @param string $sqlExpr + * @param AbstractPlatform $platform * * @return string */ @@ -326,9 +303,7 @@ public function convertToPHPValueSQL($sqlExpr, $platform) /** * Gets an array of database types that map to this Doctrine type. * - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - * - * @return array + * @return string[] */ public function getMappedDatabaseTypes(AbstractPlatform $platform) { @@ -341,8 +316,6 @@ public function getMappedDatabaseTypes(AbstractPlatform $platform) * one of those types as commented, which will have Doctrine use an SQL * comment to typehint the actual Doctrine Type. * - * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform - * * @return bool */ public function requiresSQLCommentHint(AbstractPlatform $platform) diff --git a/lib/Doctrine/DBAL/Types/VarDateTimeImmutableType.php b/lib/Doctrine/DBAL/Types/VarDateTimeImmutableType.php index f0e8ff84482..6636f53a5b2 100644 --- a/lib/Doctrine/DBAL/Types/VarDateTimeImmutableType.php +++ b/lib/Doctrine/DBAL/Types/VarDateTimeImmutableType.php @@ -1,32 +1,13 @@ . - */ namespace Doctrine\DBAL\Types; +use DateTimeImmutable; use Doctrine\DBAL\Platforms\AbstractPlatform; use function date_create_immutable; /** * Immutable type of {@see VarDateTimeType}. - * - * @since 2.6 - * @author Steve Müller */ class VarDateTimeImmutableType extends VarDateTimeType { @@ -43,18 +24,18 @@ public function getName() */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { - if (null === $value) { + if ($value === null) { return $value; } - if ($value instanceof \DateTimeImmutable) { + if ($value instanceof DateTimeImmutable) { return $value->format($platform->getDateTimeFormatString()); } throw ConversionException::conversionFailedInvalidType( $value, $this->getName(), - ['null', \DateTimeImmutable::class] + ['null', DateTimeImmutable::class] ); } @@ -63,7 +44,7 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) */ public function convertToPHPValue($value, AbstractPlatform $platform) { - if ($value === null || $value instanceof \DateTimeImmutable) { + if ($value === null || $value instanceof DateTimeImmutable) { return $value; } diff --git a/lib/Doctrine/DBAL/Types/VarDateTimeType.php b/lib/Doctrine/DBAL/Types/VarDateTimeType.php index b55e0b05b3e..1d9dbd3a6c6 100644 --- a/lib/Doctrine/DBAL/Types/VarDateTimeType.php +++ b/lib/Doctrine/DBAL/Types/VarDateTimeType.php @@ -1,24 +1,8 @@ . - */ namespace Doctrine\DBAL\Types; +use DateTime; use Doctrine\DBAL\Platforms\AbstractPlatform; use function date_create; @@ -28,13 +12,6 @@ * This type has performance implications as it runs twice as long as the regular * {@see DateTimeType}, however in certain PostgreSQL configurations with * TIMESTAMP(n) columns where n > 0 it is necessary to use this type. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class VarDateTimeType extends DateTimeType { @@ -43,12 +20,12 @@ class VarDateTimeType extends DateTimeType */ public function convertToPHPValue($value, AbstractPlatform $platform) { - if ($value === null || $value instanceof \DateTime) { + if ($value === null || $value instanceof DateTime) { return $value; } $val = date_create($value); - if ( ! $val) { + if (! $val) { throw ConversionException::conversionFailed($value, $this->getName()); } diff --git a/lib/Doctrine/DBAL/Version.php b/lib/Doctrine/DBAL/Version.php index a9b5ac02330..570f56afba0 100644 --- a/lib/Doctrine/DBAL/Version.php +++ b/lib/Doctrine/DBAL/Version.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\DBAL; @@ -25,20 +8,13 @@ /** * Class to store and retrieve the version of Doctrine. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel */ class Version { /** * Current Doctrine Version. */ - public const VERSION = '2.8.0'; + public const VERSION = '2.9.0'; /** * Compares a Doctrine version with the current one. @@ -50,7 +26,7 @@ class Version public static function compare($version) { $currentVersion = str_replace(' ', '', strtolower(self::VERSION)); - $version = str_replace(' ', '', $version); + $version = str_replace(' ', '', $version); return version_compare($version, $currentVersion); } diff --git a/lib/Doctrine/DBAL/VersionAwarePlatformDriver.php b/lib/Doctrine/DBAL/VersionAwarePlatformDriver.php index 53e2d3ab781..a4864d0b287 100644 --- a/lib/Doctrine/DBAL/VersionAwarePlatformDriver.php +++ b/lib/Doctrine/DBAL/VersionAwarePlatformDriver.php @@ -1,24 +1,9 @@ . - */ namespace Doctrine\DBAL; +use Doctrine\DBAL\Platforms\AbstractPlatform; + /** * Contract for a driver that is able to create platform instances by version. * @@ -26,10 +11,6 @@ * support the correct features and SQL syntax of each version. * This interface should be implemented by drivers that are capable to do this * distinction. - * - * @author Steve Müller - * @link www.doctrine-project.org - * @since 2.5 */ interface VersionAwarePlatformDriver { @@ -39,9 +20,9 @@ interface VersionAwarePlatformDriver * @param string $version The platform/server version string to evaluate. This should be given in the notation * the underlying database vendor uses. * - * @return \Doctrine\DBAL\Platforms\AbstractPlatform + * @return AbstractPlatform * - * @throws DBALException if the given version string could not be evaluated. + * @throws DBALException If the given version string could not be evaluated. */ public function createDatabasePlatformForVersion($version); } diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 7385edd063d..aaa6b5f04a5 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -9,6 +9,7 @@ + bin lib tests @@ -35,4 +36,26 @@ tests/Doctrine/Tests/DBAL/Tools/TestAsset/* + + + + lib/Doctrine/DBAL/Platforms/AbstractPlatform.php + lib/Doctrine/DBAL/Schema/AbstractSchemaManager.php + + + + + lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvStatement.php + + + + + lib/Doctrine/DBAL/Driver/SQLSrv/SQLSrvStatement.php + + + + + tests/Doctrine/Tests/DBAL/Platforms/OraclePlatformTest.php + tests/Doctrine/Tests/DBAL/SQLParserUtilsTest.php + diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 9dab4abdaa5..b212ccf7e0d 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -2,7 +2,7 @@