From 9654020d67aeae672e3d4c71496f6ae8d1f0fe2c Mon Sep 17 00:00:00 2001 From: Jenny Tam Date: Fri, 20 Jul 2018 17:24:48 -0700 Subject: [PATCH 01/10] Dev (#820) * Fixed the potential error reported by Prefast code analysis * Use SQLSRV_ASSERT for checking NULL ptrs * For these AKV tests check env despite not AE connected * Added the driver option to run functional tests * Fixed connection pooling tests for more than one ODBC drivers * added driver option to pdo isPooled.php * Removed win32 ifdefs re connection resiliency (#802) * Set the driver argument for getDSN to null by default (#798) * Added the driver argument to getDSN * Dropped the driver argument but set to null as default * Removed the AE condition in locale support * Modified the AE condition for locale support * Changed int to SQLLEN to avoid infinite loop (#806) * Version 5.3.0 (#803) * Version 5.3.0 * Fixed the wrong replacements * Added comments block to m4 files * Use dnl for comments * Modified AE fetch phptypes test to insert only one row at a time and loop through php types (#801) * Modified AE fetch phptypes test to insert only one row at a time and loop through php types * Fixed formatting * Streamlined two very similar large column name tests (#807) * Streamlined two very similar large column name tests * Changed the EOL * Updates to change log and readme (#811) * Updates to change log and readme * Dropped support for Ubuntu 17 * Modified as per review comments * Fixed connection resiliency tests for Unix, updated AppVeyor for ODBC 17.2 * Fixed expected output * Fixed output and skipifs * Fixed skipifs and output * Fixed driver name * Updated installation instructions and sample script (#813) * Updated instructions and sample test for 5.3.0 RTW * Fixed sample code to adhere to php coding standard * Fixed cases and spaces * Modified NOTE for UB 18.04 based on review comments * Added 'exit' * Modified change log and readme based on review to PR 811 * Applied review comments * build output to debug appveyor failure * removed debug output * Streamlined two very similar large column name tests (#815) * Streamlined two very similar large column name tests * Added random number of test table names to avoid operand clash issues * Replaced to with for based on review * Changelog updated * changelog updated, test skipif changed to run on unix platforms * Fixed skipif typo * Fixed typo in skipif for pdo * Fixed some output for Travis * Moved error checking inside pdo connres tests * Added links back to changelog * Fixed output for sqlsrv connres tests * Fixed output * Fixed output again --- CHANGELOG.md | 35 ++++ LICENSE | 26 +-- Linux-mac-install.md | 70 +++---- README.md | 20 +- appveyor.yml | 6 +- source/pdo_sqlsrv/config.m4 | 20 ++ source/pdo_sqlsrv/config.w32 | 2 +- source/pdo_sqlsrv/pdo_dbh.cpp | 12 +- source/pdo_sqlsrv/pdo_init.cpp | 2 +- source/pdo_sqlsrv/pdo_parser.cpp | 2 +- source/pdo_sqlsrv/pdo_stmt.cpp | 2 +- source/pdo_sqlsrv/pdo_util.cpp | 2 +- source/pdo_sqlsrv/php_pdo_sqlsrv.h | 2 +- source/pdo_sqlsrv/template.rc | 2 +- source/shared/FormattedPrint.cpp | 2 +- source/shared/FormattedPrint.h | 2 +- source/shared/StringFunctions.cpp | 2 +- source/shared/StringFunctions.h | 2 +- source/shared/core_conn.cpp | 2 +- source/shared/core_init.cpp | 2 +- source/shared/core_results.cpp | 7 +- source/shared/core_sqlsrv.h | 6 +- source/shared/core_stmt.cpp | 2 +- source/shared/core_stream.cpp | 6 +- source/shared/core_util.cpp | 2 +- source/shared/globalization.h | 2 +- source/shared/interlockedatomic.h | 2 +- source/shared/interlockedatomic_gcc.h | 2 +- source/shared/interlockedslist.h | 2 +- source/shared/localization.hpp | 2 +- source/shared/localizationimpl.cpp | 2 +- source/shared/msodbcsql.h | 2 +- source/shared/sal_def.h | 2 +- source/shared/typedefs_for_linux.h | 2 +- source/shared/version.h | 8 +- source/shared/xplat.h | 2 +- source/shared/xplat_intsafe.h | 2 +- source/shared/xplat_winerror.h | 2 +- source/shared/xplat_winnls.h | 2 +- source/sqlsrv/config.m4 | 20 ++ source/sqlsrv/config.w32 | 2 +- source/sqlsrv/conn.cpp | 8 +- source/sqlsrv/init.cpp | 2 +- source/sqlsrv/php_sqlsrv.h | 2 +- source/sqlsrv/stmt.cpp | 2 +- source/sqlsrv/template.rc | 2 +- source/sqlsrv/util.cpp | 2 +- test/functional/pdo_sqlsrv/MsCommon.inc | 158 +--------------- .../pdo_sqlsrv/MsCommon_mid-refactor.inc | 11 +- test/functional/pdo_sqlsrv/MsSetup.inc | 4 +- .../pdo_sqlsrv/PDO101_LargeColumnName.phpt | 95 +++++----- ...O101_LargeColumnName_unicode_col_name.phpt | 65 +++---- .../pdo_sqlsrv/PDO21_Connection.phpt | 2 +- .../pdo_sqlsrv/PDO_ConnPool_Unix.phpt | 13 +- test/functional/pdo_sqlsrv/isPooled.php | 4 +- .../pdo_sqlsrv/pdo_020_bind_params_array.phpt | 2 + .../pdo_sqlsrv/pdo_040_error_information.phpt | 2 + .../pdo_065_construct_persistent.phpt | 2 +- .../pdo_065_construct_prefetch.phpt | 2 +- .../pdo_707_ae_output_param_decimals.phpt | 2 +- .../pdo_ae_azure_key_vault_client_secret.phpt | 2 +- .../pdo_ae_azure_key_vault_keywords.phpt | 2 +- ..._ae_azure_key_vault_username_password.phpt | 2 +- .../pdo_sqlsrv/pdo_ae_output_param_all.phpt | 1 + .../pdo_sqlsrv/pdo_connect_encrypted.phpt | 2 +- .../pdo_sqlsrv/pdo_connection_resiliency.phpt | 16 +- .../pdo_connection_resiliency_keywords.phpt | 13 +- ...onnection_resiliency_prepare_transact.phpt | 18 +- .../pdo_connection_resiliency_timeouts.phpt | 9 +- test/functional/pdo_sqlsrv/pdo_utf8_conn.phpt | 3 +- test/functional/pdo_sqlsrv/skipif_not_akv.inc | 20 ++ .../pdo_sqlsrv/skipif_protocol_not_tcp.inc | 2 - .../skipif_version_less_than_2k14.inc | 37 +++- .../skipif_version_less_than_2k16.inc | 37 +++- .../pdo_sqlsrv/test_ae_keys_setup.phpt | 83 +++++---- test/functional/sqlsrv/MsCommon.inc | 2 +- test/functional/sqlsrv/MsSetup.inc | 4 +- test/functional/sqlsrv/TC52_StreamSend.phpt | 2 +- .../sqlsrv/TC54_StreamPrepared.phpt | 2 +- .../sqlsrv/TC84_LargeColumnName.phpt | 49 ++--- .../sqlsrv/TC84_LargeColumnName_unicode.phpt | 51 ++--- ...TC84_LargeColumnName_unicode_col_name.phpt | 75 -------- .../sqlsrv/connection_resiliency.phpt | 64 ++----- .../connection_resiliency_keywords.phpt | 15 +- ...onnection_resiliency_prepare_transact.phpt | 34 +--- .../connection_resiliency_timeouts.phpt | 32 +--- test/functional/sqlsrv/skipif_not_akv.inc | 21 +++ .../sqlsrv/skipif_protocol_not_tcp.inc | 2 - .../sqlsrv/skipif_version_less_than_2k14.inc | 37 +++- .../sqlsrv/skipif_version_less_than_2k16.inc | 36 +++- .../sqlsrv/sqlsrv_ConnPool_Unix.phpt | 13 +- ...lsrv_ae_azure_key_vault_client_secret.phpt | 2 +- .../sqlsrv_ae_azure_key_vault_keywords.phpt | 2 +- ..._ae_azure_key_vault_username_password.phpt | 2 +- .../sqlsrv/sqlsrv_ae_fetch_phptypes.phpt | 174 ++++++++++-------- .../sqlsrv/sqlsrv_connect_encrypted.phpt | 2 +- .../functional/sqlsrv/test_ae_keys_setup.phpt | 39 ++-- 97 files changed, 765 insertions(+), 816 deletions(-) create mode 100644 test/functional/pdo_sqlsrv/skipif_not_akv.inc delete mode 100644 test/functional/sqlsrv/TC84_LargeColumnName_unicode_col_name.phpt create mode 100644 test/functional/sqlsrv/skipif_not_akv.inc diff --git a/CHANGELOG.md b/CHANGELOG.md index 765bb786c..abaa24db6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,41 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) +## 5.3.0 - 2018-07-20 +Updated PECL release packages. Here is the list of updates: + +### Added +- Added support for Azure Key Vault for Always Encrypted functionality. Always Encrypted functionality is supported on Linux and macOS through Azure Key Vault +- Added support for connection resiliency on Linux and macOS (requires version 17.2 or higher of the [ODBC driver](https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-2017)) +- Added support for macOS High Sierra (requires version 17 or higher of the [ODBC driver](https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-2017)) +- Added support for Ubuntu 18.04 (requires version 17.2 or higher of the [ODBC driver](https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-2017)) + +### Fixed +- Issue [#577](https://github.com/Microsoft/msphpsql/issues/577) - Idle Connection Resiliency doesn't work with Column Encryption enabled connections (fixed in MS ODBC Driver 17.1) +- Issue [#678](https://github.com/Microsoft/msphpsql/issues/678) - Idle Connection Resiliency doesn't work with Connection Pooling (fixed in MS ODBC Driver 17.1) +- Issue [#699](https://github.com/Microsoft/msphpsql/issues/699) - Binding output parameters fails when the query in the stored procedure returns no data. The test case has been added to the test lab. +- Issue [#705](https://github.com/Microsoft/msphpsql/issues/705) - Always Encrypted - Retrieving a negative decimal value (edge case) as output parameter causes truncation +- Issue [#706](https://github.com/Microsoft/msphpsql/issues/706) - Always Encrypted - Cannot insert double with precision and scale (38, 38) +- Issue [#707](https://github.com/Microsoft/msphpsql/issues/707) - Always Encrypted - Fetching decimals / numerics as output parameters bound to PDO::PARAM_BOOL or PDO::PARAM_INT returns floats, not integers +- Issue [#735](https://github.com/Microsoft/msphpsql/issues/735) - Extended the buffer size for PDO::lastInsertId so that data types other than integers can be supported +- Pull Request [#759](https://github.com/Microsoft/msphpsql/pull/759) - Removed the limitation of binding a binary as inout param as PDO::PARAM_STR with SQLSRV_ENCODING_BINARY +- Pull Request [#775](https://github.com/Microsoft/msphpsql/pull/775) - Fixed the truncation problem for output params with SQL types specified as SQLSRV_SQLTYPE_DECIMAL or SQLSRV_SQLTYPE_NUMERIC + +### Limitations +- No support for inout / output params when using sql_variant type +- In Linux and macOS, setlocale() only takes effect if it is invoked before the first connection. Attempting to set the locale after connecting will not work +- Always Encrypted requires [MS ODBC Driver 17+](https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-2017) + - Only Windows Certificate Store and Azure Key Vault are supported. Custom Keystores are not yet supported + - Issue [#716](https://github.com/Microsoft/msphpsql/issues/716) - With Always Encrypted enabled, named parameters in subqueries are not supported + - [Always Encrypted limitations](https://docs.microsoft.com/en-us/sql/connect/php/using-always-encrypted-php-drivers?view=sql-server-2017#limitations-of-the-php-drivers-when-using-always-encrypted) + +### Known Issues +- Connection pooling on Linux or macOS is not recommended with [unixODBC](http://www.unixodbc.org/) < 2.3.6 +- When pooling is enabled in Linux or macOS + - unixODBC <= 2.3.4 (Linux and macOS) might not return proper diagnostic information, such as error messages, warnings and informative messages + - due to this unixODBC bug, fetch large data (such as xml, binary) as streams as a workaround. See the examples [here](https://github.com/Microsoft/msphpsql/wiki/Features#pooling) +- With ColumnEncryption enabled, calling stored procedures with XML parameters does not work (Issue [#674](https://github.com/Microsoft/msphpsql/issues/674)) + ## 5.2.1-preview - 2018-06-01 Updated PECL release packages. Here is the list of updates: diff --git a/LICENSE b/LICENSE index b52d9d433..13fab6115 100644 --- a/LICENSE +++ b/LICENSE @@ -1,14 +1,14 @@ -Copyright(c) 2017 Microsoft Corporation -All rights reserved. - -MIT License -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), -to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, -and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +Copyright(c) 2018 Microsoft Corporation +All rights reserved. + +MIT License +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), +to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/Linux-mac-install.md b/Linux-mac-install.md index 6964ca0e2..d84eca655 100644 --- a/Linux-mac-install.md +++ b/Linux-mac-install.md @@ -1,20 +1,24 @@ -# PHP Linux and Mac Drivers Installation Tutorial -The following instructions assume a clean environment and show how to install PHP 7.x, the Microsoft ODBC driver, Apache, and the Microsoft drivers for PHP for Microsoft SQL Server on Ubuntu 16.04 and 17.10, RedHat 7, Debian 8 and 9, Suse 12, and macOS 10.11 and 10.12. These instructions advise installing the drivers using PECL, but you can also download the prebuilt binaries from the [Microsoft Drivers for PHP for Microsoft SQL Server](https://github.com/Microsoft/msphpsql/releases) Github project page and install them following the instructions in [Loading the Microsoft Drivers for PHP for Microsoft SQL Server](https://docs.microsoft.com/sql/connect/php/loading-the-php-sql-driver)). For an explanation of extension loading and why we do not add the extensions to php.ini, see the section on [loading the drivers](https://docs.microsoft.com/sql/connect/php/loading-the-php-sql-driver#loading-the-driver-at-php-startup). +# Linux and macOS Installation Tutorial for the Microsoft Drivers for PHP for SQL Server +The following instructions assume a clean environment and show how to install PHP 7.x, the Microsoft ODBC driver, Apache, and the Microsoft drivers for PHP for Microsoft SQL Server on Ubuntu 16.04, 17.10 and 18.04, RedHat 7, Debian 8 and 9, Suse 12, and macOS 10.11, 10.12 and 10.13. These instructions advise installing the drivers using PECL, but you can also download the prebuilt binaries from the [Microsoft Drivers for PHP for Microsoft SQL Server](https://github.com/Microsoft/msphpsql/releases) Github project page and install them following the instructions in [Loading the Microsoft Drivers for PHP for Microsoft SQL Server](https://docs.microsoft.com/sql/connect/php/loading-the-php-sql-driver)). For an explanation of extension loading and why we do not add the extensions to php.ini, see the section on [loading the drivers](https://docs.microsoft.com/sql/connect/php/loading-the-php-sql-driver#loading-the-driver-at-php-startup). -These instruction install PHP 7.2 by default -- see the notes at the beginning of each section to install PHP 7.0 or 7.1. +These instructions install PHP 7.2 by default -- see the notes at the beginning of each section to install PHP 7.0 or 7.1. ## Contents of this page: -- [Installing the drivers on Ubuntu 16.04 and 17.10](#installing-the-drivers-on-ubuntu-1604-and-1710) +- [Installing the drivers on Ubuntu 16.04, 17.10, and 18.04](#installing-the-drivers-on-ubuntu-1604-1710-and-1804) - [Installing the drivers on Red Hat 7](#installing-the-drivers-on-red-hat-7) - [Installing the drivers on Debian 8 and 9](#installing-the-drivers-on-debian-8-and-9) - [Installing the drivers on Suse 12](#installing-the-drivers-on-suse-12) - [Installing the drivers on macOS El Capitan, Sierra and High Sierra](#installing-the-drivers-on-macos-el-capitan-sierra-and-high-sierra) -## Installing the drivers on Ubuntu 16.04 and 17.10 +## Installing the drivers on Ubuntu 16.04, 17.10 and 18.04 > [!NOTE] > To install PHP 7.0 or 7.1, replace 7.2 with 7.0 or 7.1 in the following commands. +> For Ubuntu 18.04, the step to add the ondrej repository is not required unless +> PHP 7.0 or 7.1 is needed. However, installing PHP 7.0 or 7.1 in Ubuntu 18.04 may +> not work as packages from the ondrej repository come with dependencies that may +> conflict with a base Ubuntu 18.04 install. ### Step 1. Install PHP ``` @@ -44,6 +48,7 @@ a2enmod mpm_prefork a2enmod php7.2 echo "extension=pdo_sqlsrv.so" >> /etc/php/7.2/apache2/conf.d/30-pdo_sqlsrv.ini echo "extension=sqlsrv.so" >> /etc/php/7.2/apache2/conf.d/20-sqlsrv.ini +exit ``` ### Step 5. Restart Apache and test the sample script ``` @@ -86,11 +91,11 @@ echo extension=pdo_sqlsrv.so >> `php --ini | grep "Scan for additional .ini file echo extension=sqlsrv.so >> `php --ini | grep "Scan for additional .ini files" | sed -e "s|.*:\s*||"`/20-sqlsrv.ini exit ``` -An issue in PECL may prevent correct installation of the latest version of the drivers even if you have upgraded GCC. To install, download the packages and compile manually: +An issue in PECL may prevent correct installation of the latest version of the drivers even if you have upgraded GCC. To install, download the packages and compile manually (similar steps for pdo_sqlsrv): ``` pecl download sqlsrv -tar xvzf sqlsrv-5.2.0.tgz -cd sqlsrv-5.2.0/ +tar xvzf sqlsrv-5.3.0.tgz +cd sqlsrv-5.3.0/ phpize ./configure --with-php-config=/usr/bin/php-config make @@ -196,6 +201,7 @@ zypper install apache2 apache2-mod_php7 a2enmod php7 echo "extension=sqlsrv.so" >> /etc/php7/apache2/php.ini echo "extension=pdo_sqlsrv.so" >> /etc/php7/apache2/php.ini +exit ``` ### Step 5. Restart Apache and test the sample script ``` @@ -266,47 +272,47 @@ To test this sample script, create a file called testsql.php in your system's do "yourDatabase", - "Uid" => "yourUsername", - "PWD" => "yourPassword" + "database" => "yourDatabase", + "uid" => "yourUsername", + "pwd" => "yourPassword" ); -//Establishes the connection +// Establishes the connection $conn = sqlsrv_connect($serverName, $connectionOptions); -if( $conn === false ) { - die( FormatErrors( sqlsrv_errors())); +if ($conn === false) { + die(formatErrors(sqlsrv_errors())); } -//Select Query -$tsql= "SELECT @@Version as SQL_VERSION"; +// Select Query +$tsql = "SELECT @@Version AS SQL_VERSION"; -//Executes the query -$getResults= sqlsrv_query($conn, $tsql); +// Executes the query +$stmt = sqlsrv_query($conn, $tsql); -//Error handling -if ($getResults == FALSE) - die(FormatErrors(sqlsrv_errors())); +// Error handling +if ($stmt === false) { + die(formatErrors(sqlsrv_errors())); +} ?>

Results :

"); +while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) { + echo $row['SQL_VERSION'] . PHP_EOL; } -sqlsrv_free_stmt($getResults); +sqlsrv_free_stmt($stmt); +sqlsrv_close($conn); -function FormatErrors( $errors ) +function formatErrors($errors) { - /* Display errors. */ + // Display errors echo "Error information:
"; - foreach ( $errors as $error ) - { - echo "SQLSTATE: ".$error['SQLSTATE']."
"; - echo "Code: ".$error['code']."
"; - echo "Message: ".$error['message']."
"; + foreach ($errors as $error) { + echo "SQLSTATE: ". $error['SQLSTATE'] . "
"; + echo "Code: ". $error['code'] . "
"; + echo "Message: ". $error['message'] . "
"; } } ?> diff --git a/README.md b/README.md index b30a3fa0f..20e3c0e98 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ For full details on the system requirements for the drivers, see the [system req On the client machine: - PHP 7.0.x, 7.1.x, or 7.2.x (7.2.0 and up on Unix, 7.2.1 and up on Windows) - A Web server such as Internet Information Services (IIS) is required. Your Web server must be configured to run PHP -- [Microsoft ODBC Driver 17][odbc17], [Microsoft ODBC Driver 13][odbc13], or [Microsoft ODBC Driver 11][odbc11] +- [Microsoft ODBC Driver 17, Microsoft ODBC Driver 13, or Microsoft ODBC Driver 11](https://docs.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-2017) On the server side, Microsoft SQL Server 2008 R2 and above on Windows are supported, as are Microsoft SQL Server 2016 and above on Linux. @@ -86,14 +86,14 @@ The version number may have trailing pre-release version identifiers to indicate - Build metadata may be denoted by a plus sign followed by 4 or 5 digits, such as `1.2.3-preview+5678` or `1.2.3+5678`. Build metadata does not figure into the precedence order. ## Future Plans -- Expand SQL Server 2016 feature support (example: Always Encrypted) +- Expand SQL Server 2016 feature support (example: Azure Active Directory) - Add more verification/fundamental tests - Bug fixes ## Guidelines for Reporting Issues We appreciate you taking the time to test the driver, provide feedback and report any issues. It would be extremely helpful if you: -- First check the [FAQ](https://github.com/Microsoft/msphpsql/wiki/FAQ) +- First check the [FAQ](https://github.com/Microsoft/msphpsql/wiki/FAQ) for common problems - Report each issue as a new issue (but check first if it's already been reported) - Please address the questions in the new issue template and provide scripts, table schema, and/or any details that may help reproduce the problem(s) @@ -106,15 +106,15 @@ Thank you! **Q:** What's next? -**A:** On March 23, 2018 we released the production release version 5.2.0 of our PHP Driver. We will continue working on our future plans and releasing previews of upcoming releases frequently. +**A:** On July 20, 2018 we released the production release version 5.3.0 of our PHP Driver. We will continue working on our future plans and releasing previews of upcoming releases. **Q:** Is Microsoft taking pull requests for this project? -**A:** Yes. Please submit pull requests to the **dev** branch and not the **master** branch. +**A:** Yes. Please submit pull requests to the **dev** branch, not the **master** branch. ## License -The Microsoft Drivers for PHP for SQL Server are licensed under the MIT license. See the LICENSE file for more details. +The Microsoft Drivers for PHP for SQL Server are licensed under the MIT license. See the LICENSE file for more details. ## Code of conduct @@ -138,12 +138,6 @@ This project has adopted the Microsoft Open Source Code of Conduct. For more inf [phpbuild]: https://wiki.php.net/internals/windows/stepbystepbuild -[phpdoc]: http://msdn.microsoft.com/library/dd903047%28SQL.11%29.aspx - -[odbc11]: https://www.microsoft.com/download/details.aspx?id=36434 - -[odbc13]: https://www.microsoft.com/download/details.aspx?id=50420 - -[odbc17]: https://www.microsoft.com/download/details.aspx?id=56567 +[phpdoc]: https://docs.microsoft.com/en-us/sql/connect/php/microsoft-php-driver-for-sql-server?view=sql-server-2017 [PHPMan]: http://php.net/manual/install.unix.php diff --git a/appveyor.yml b/appveyor.yml index 9d2cdeea1..4a0fcbddd 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -81,10 +81,10 @@ install: } Else { $env:PHP_VERSION=$env:PHP_MAJOR_VER + '.' + $env:PHP_MINOR_VER; } - - echo Downloading MSODBCSQL 17.1 + - echo Downloading MSODBCSQL 17.2 # AppVeyor build works are x64 VMs and 32-bit ODBC driver cannot be installed on it - - ps: (new-object net.webclient).DownloadFile('https://download.microsoft.com/download/E/6/B/E6BFDC7A-5BCD-4C51-9912-635646DA801E/msodbcsql_17.1.0.1_x64.msi', 'c:\projects\msodbcsql_17.1.0.1_x64.msi') - - cmd /c start /wait msiexec /i "c:\projects\msodbcsql_17.1.0.1_x64.msi" /q IACCEPTMSODBCSQLLICENSETERMS=YES ADDLOCAL=ALL + - ps: (new-object net.webclient).DownloadFile('https://download.microsoft.com/download/E/6/B/E6BFDC7A-5BCD-4C51-9912-635646DA801E/en-US/msodbcsql_17.2.0.1_x64.msi', 'c:\projects\msodbcsql_17.2.0.1_x64.msi') + - cmd /c start /wait msiexec /i "c:\projects\msodbcsql_17.2.0.1_x64.msi" /q IACCEPTMSODBCSQLLICENSETERMS=YES ADDLOCAL=ALL - echo Checking the version of MSODBCSQL - reg query "HKLM\SOFTWARE\ODBC\odbcinst.ini\ODBC Driver 17 for SQL Server" - dir %WINDIR%\System32\msodbcsql*.dll diff --git a/source/pdo_sqlsrv/config.m4 b/source/pdo_sqlsrv/config.m4 index 46e22960d..b1bfd6e48 100644 --- a/source/pdo_sqlsrv/config.m4 +++ b/source/pdo_sqlsrv/config.m4 @@ -1,3 +1,23 @@ +dnl ---------------------------------------------------------------------------------------------------------------------------------- +dnl File: config.m4 +dnl +dnl Contents: the code that will go into the configure script, indicating options, +dnl external libraries and includes, and what source files are to be compiled. +dnl +dnl Microsoft Drivers 5.3 for PHP for SQL Server +dnl Copyright(c) Microsoft Corporation +dnl All rights reserved. +dnl MIT License +dnl Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the ""Software""), +dnl to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +dnl and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : +dnl The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +dnl THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +dnl FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +dnl LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +dnl IN THE SOFTWARE. +dnl --------------------------------------------------------------------------------------------------------------------------------- + PHP_ARG_WITH(pdo_sqlsrv, for pdo_sqlsrv support, [ --with-pdo_sqlsrv Include pdo_sqlsrv support]) diff --git a/source/pdo_sqlsrv/config.w32 b/source/pdo_sqlsrv/config.w32 index bd1eaf048..7066e6254 100644 --- a/source/pdo_sqlsrv/config.w32 +++ b/source/pdo_sqlsrv/config.w32 @@ -3,7 +3,7 @@ // // Contents: JScript build configuration used by buildconf.bat // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/pdo_sqlsrv/pdo_dbh.cpp b/source/pdo_sqlsrv/pdo_dbh.cpp index 48ed3b123..330205565 100644 --- a/source/pdo_sqlsrv/pdo_dbh.cpp +++ b/source/pdo_sqlsrv/pdo_dbh.cpp @@ -3,7 +3,7 @@ // // Contents: Implements the PDO object for PDO_SQLSRV // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -43,10 +43,8 @@ const char AttachDBFileName[] = "AttachDbFileName"; const char Authentication[] = "Authentication"; const char ColumnEncryption[] = "ColumnEncryption"; const char ConnectionPooling[] = "ConnectionPooling"; -#ifdef _WIN32 const char ConnectRetryCount[] = "ConnectRetryCount"; const char ConnectRetryInterval[] = "ConnectRetryInterval"; -#endif // _WIN32 const char Database[] = "Database"; const char Driver[] = "Driver"; const char Encrypt[] = "Encrypt"; @@ -109,7 +107,6 @@ struct pdo_txn_isolation_conn_attr_func static void func( connection_option const* /*option*/, _In_ zval* value_z, _Inout_ sqlsrv_conn* conn, std::string& /*conn_str*/ TSRMLS_DC ); }; -#ifdef _WIN32 struct pdo_int_conn_str_func { static void func( _In_ connection_option const* option, _In_ zval* value, sqlsrv_conn* /*conn*/, _Out_ std::string& conn_str TSRMLS_DC ) @@ -125,7 +122,6 @@ struct pdo_int_conn_str_func { conn_str += "};"; } }; -#endif // _WIN32 template struct pdo_int_conn_attr_func { @@ -243,7 +239,6 @@ const connection_option PDO_CONN_OPTS[] = { CONN_ATTR_STRING, column_encryption_set_func::func }, -#ifdef _WIN32 { PDOConnOptionNames::ConnectRetryCount, sizeof( PDOConnOptionNames::ConnectRetryCount ), @@ -262,7 +257,6 @@ const connection_option PDO_CONN_OPTS[] = { CONN_ATTR_INT, pdo_int_conn_str_func::func }, -#endif // _WIN32 { PDOConnOptionNames::Database, sizeof( PDOConnOptionNames::Database ), @@ -1276,7 +1270,7 @@ char * pdo_sqlsrv_dbh_last_id( _Inout_ pdo_dbh_t *dbh, _In_z_ const char *name, try { - char last_insert_id_query[ LAST_INSERT_ID_QUERY_MAX_LEN ]; + char last_insert_id_query[ LAST_INSERT_ID_QUERY_MAX_LEN ] = {'\0'}; if( name == NULL ) { strcpy_s( last_insert_id_query, sizeof( last_insert_id_query ), LAST_INSERT_ID_QUERY ); } @@ -1300,7 +1294,7 @@ char * pdo_sqlsrv_dbh_last_id( _Inout_ pdo_dbh_t *dbh, _In_z_ const char *name, sqlsrv_malloc_auto_ptr wsql_string; unsigned int wsql_len; - wsql_string = utf16_string_from_mbcs_string( SQLSRV_ENCODING_CHAR, reinterpret_cast( last_insert_id_query ), static_cast( strnlen_s( last_insert_id_query )), &wsql_len ); + wsql_string = utf16_string_from_mbcs_string( SQLSRV_ENCODING_CHAR, reinterpret_cast( last_insert_id_query ), sizeof(last_insert_id_query), &wsql_len ); CHECK_CUSTOM_ERROR( wsql_string == 0, driver_stmt, SQLSRV_ERROR_QUERY_STRING_ENCODING_TRANSLATE, get_last_error_message() ) { throw core::CoreException(); diff --git a/source/pdo_sqlsrv/pdo_init.cpp b/source/pdo_sqlsrv/pdo_init.cpp index 0fa961c6e..65e7a0786 100644 --- a/source/pdo_sqlsrv/pdo_init.cpp +++ b/source/pdo_sqlsrv/pdo_init.cpp @@ -3,7 +3,7 @@ // // Contents: initialization routines for PDO_SQLSRV // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/pdo_sqlsrv/pdo_parser.cpp b/source/pdo_sqlsrv/pdo_parser.cpp index 8c783b39f..baafeed73 100644 --- a/source/pdo_sqlsrv/pdo_parser.cpp +++ b/source/pdo_sqlsrv/pdo_parser.cpp @@ -5,7 +5,7 @@ // // Copyright Microsoft Corporation // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/pdo_sqlsrv/pdo_stmt.cpp b/source/pdo_sqlsrv/pdo_stmt.cpp index fd65b9eac..d41dde3b7 100644 --- a/source/pdo_sqlsrv/pdo_stmt.cpp +++ b/source/pdo_sqlsrv/pdo_stmt.cpp @@ -3,7 +3,7 @@ // // Contents: Implements the PDOStatement object for the PDO_SQLSRV // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/pdo_sqlsrv/pdo_util.cpp b/source/pdo_sqlsrv/pdo_util.cpp index 343537dd6..a05e75471 100644 --- a/source/pdo_sqlsrv/pdo_util.cpp +++ b/source/pdo_sqlsrv/pdo_util.cpp @@ -3,7 +3,7 @@ // // Contents: Utility functions used by both connection or statement functions // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/pdo_sqlsrv/php_pdo_sqlsrv.h b/source/pdo_sqlsrv/php_pdo_sqlsrv.h index ba7dd4b76..38e4cec42 100644 --- a/source/pdo_sqlsrv/php_pdo_sqlsrv.h +++ b/source/pdo_sqlsrv/php_pdo_sqlsrv.h @@ -6,7 +6,7 @@ // // Contents: Declarations for the extension // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/pdo_sqlsrv/template.rc b/source/pdo_sqlsrv/template.rc index 248c99ccc..8b94ddfad 100644 --- a/source/pdo_sqlsrv/template.rc +++ b/source/pdo_sqlsrv/template.rc @@ -3,7 +3,7 @@ // // Contents: Version resource // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/FormattedPrint.cpp b/source/shared/FormattedPrint.cpp index 6a19a4259..1b48c0e92 100644 --- a/source/shared/FormattedPrint.cpp +++ b/source/shared/FormattedPrint.cpp @@ -6,7 +6,7 @@ // Contents: Contains functions for handling Windows format strings // and UTF-16 on non-Windows platforms // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/FormattedPrint.h b/source/shared/FormattedPrint.h index 61080a424..87f15f463 100644 --- a/source/shared/FormattedPrint.h +++ b/source/shared/FormattedPrint.h @@ -4,7 +4,7 @@ // Contents: Contains functions for handling Windows format strings // and UTF-16 on non-Windows platforms // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/StringFunctions.cpp b/source/shared/StringFunctions.cpp index 550c0d359..d5183fc52 100644 --- a/source/shared/StringFunctions.cpp +++ b/source/shared/StringFunctions.cpp @@ -3,7 +3,7 @@ // // Contents: Contains functions for handling UTF-16 on non-Windows platforms // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/StringFunctions.h b/source/shared/StringFunctions.h index a0b31b783..b12e789b7 100644 --- a/source/shared/StringFunctions.h +++ b/source/shared/StringFunctions.h @@ -3,7 +3,7 @@ // // Contents: Contains functions for handling UTF-16 on non-Windows platforms // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/core_conn.cpp b/source/shared/core_conn.cpp index 7f2d16eb5..b094e110b 100644 --- a/source/shared/core_conn.cpp +++ b/source/shared/core_conn.cpp @@ -3,7 +3,7 @@ // // Contents: Core routines that use connection handles shared between sqlsrv and pdo_sqlsrv // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/core_init.cpp b/source/shared/core_init.cpp index d47080066..cda38fa55 100644 --- a/source/shared/core_init.cpp +++ b/source/shared/core_init.cpp @@ -3,7 +3,7 @@ // // Contents: common initialization routines shared by PDO and sqlsrv // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/core_results.cpp b/source/shared/core_results.cpp index d5882f2c6..62a757d86 100644 --- a/source/shared/core_results.cpp +++ b/source/shared/core_results.cpp @@ -3,7 +3,7 @@ // // Contents: Result sets // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -345,7 +345,8 @@ sqlsrv_error* odbc_get_diag_rec( _In_ sqlsrv_stmt* odbc, _In_ SQLSMALLINT record SQLWCHAR wnative_message[ SQL_MAX_ERROR_MESSAGE_LENGTH + 1 ]; SQLINTEGER native_code; SQLSMALLINT wnative_message_len = 0; - + + SQLSRV_ASSERT(odbc != NULL, "odbc_get_diag_rec: sqlsrv_stmt* odbc was null."); SQLRETURN r = SQLGetDiagRecW( SQL_HANDLE_STMT, odbc->handle(), record_number, wsql_state, &native_code, wnative_message, SQL_MAX_ERROR_MESSAGE_LENGTH + 1, &wnative_message_len ); if( !SQL_SUCCEEDED( r ) || r == SQL_NO_DATA ) { @@ -963,7 +964,7 @@ SQLRETURN binary_to_string( _Inout_ SQLCHAR* field_data, _Inout_ SQLLEN& read_so // to_copy contains the number of bytes to copy, so we divide the number in half (or quarter) // to get the number of hex digits we can copy SQLLEN to_copy_hex = to_copy / (2 * extra); - for( int i = 0; i < to_copy_hex; ++i ) { + for( SQLLEN i = 0; i < to_copy_hex; ++i ) { *h = hex_chars[ (*b & 0xf0) >> 4 ]; h++; *h = hex_chars[ (*b++ & 0x0f) ]; diff --git a/source/shared/core_sqlsrv.h b/source/shared/core_sqlsrv.h index 39e53b19a..5530a5540 100644 --- a/source/shared/core_sqlsrv.h +++ b/source/shared/core_sqlsrv.h @@ -6,7 +6,7 @@ // // Contents: Core routines and constants shared by the Microsoft Drivers for PHP for SQL Server // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -1112,10 +1112,8 @@ const char Driver[] = "Driver"; const char CharacterSet[] = "CharacterSet"; const char ConnectionPooling[] = "ConnectionPooling"; const char ColumnEncryption[] = "ColumnEncryption"; -#ifdef _WIN32 const char ConnectRetryCount[] = "ConnectRetryCount"; const char ConnectRetryInterval[] = "ConnectRetryInterval"; -#endif // _WIN32 const char Database[] = "Database"; const char Encrypt[] = "Encrypt"; const char Failover_Partner[] = "Failover_Partner"; @@ -1168,10 +1166,8 @@ enum SQLSRV_CONN_OPTIONS { SQLSRV_CONN_OPTION_KEYSTORE_PRINCIPAL_ID, SQLSRV_CONN_OPTION_KEYSTORE_SECRET, SQLSRV_CONN_OPTION_TRANSPARENT_NETWORK_IP_RESOLUTION, -#ifdef _WIN32 SQLSRV_CONN_OPTION_CONN_RETRY_COUNT, SQLSRV_CONN_OPTION_CONN_RETRY_INTERVAL, -#endif // _WIN32 // Driver specific connection options SQLSRV_CONN_OPTION_DRIVER_SPECIFIC = 1000, diff --git a/source/shared/core_stmt.cpp b/source/shared/core_stmt.cpp index 2cdb7a003..6d4d4f613 100644 --- a/source/shared/core_stmt.cpp +++ b/source/shared/core_stmt.cpp @@ -3,7 +3,7 @@ // // Contents: Core routines that use statement handles shared between sqlsrv and pdo_sqlsrv // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/core_stream.cpp b/source/shared/core_stream.cpp index 5309f0043..32780a5b2 100644 --- a/source/shared/core_stream.cpp +++ b/source/shared/core_stream.cpp @@ -3,7 +3,7 @@ // // Contents: Implementation of PHP streams for reading SQL Server data // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -26,7 +26,7 @@ namespace { int sqlsrv_stream_close( _Inout_ php_stream* stream, int /*close_handle*/ TSRMLS_DC ) { sqlsrv_stream* ss = static_cast( stream->abstract ); - SQLSRV_ASSERT( ss != NULL, "sqlsrv_stream_close: sqlsrv_stream* ss was null." ); + SQLSRV_ASSERT( ss != NULL && ss->stmt != NULL, "sqlsrv_stream_close: sqlsrv_stream* ss was null." ); // free the stream resources in the Zend engine php_stream_free( stream, PHP_STREAM_FREE_RELEASE_STREAM ); @@ -52,7 +52,7 @@ size_t sqlsrv_stream_read( _Inout_ php_stream* stream, _Out_writes_bytes_(count) sqlsrv_malloc_auto_ptr temp_buf; sqlsrv_stream* ss = static_cast( stream->abstract ); - SQLSRV_ASSERT( ss != NULL, "sqlsrv_stream_read: sqlsrv_stream* ss is NULL." ); + SQLSRV_ASSERT( ss != NULL && ss->stmt != NULL, "sqlsrv_stream_read: sqlsrv_stream* ss is NULL." ); try { diff --git a/source/shared/core_util.cpp b/source/shared/core_util.cpp index c537f766e..d8b7b2445 100644 --- a/source/shared/core_util.cpp +++ b/source/shared/core_util.cpp @@ -5,7 +5,7 @@ // // Comments: Mostly error handling and some type handling // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/globalization.h b/source/shared/globalization.h index 486a381d2..88e8d1a40 100644 --- a/source/shared/globalization.h +++ b/source/shared/globalization.h @@ -4,7 +4,7 @@ // Contents: Contains functions for handling Windows format strings // and UTF-16 on non-Windows platforms // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/interlockedatomic.h b/source/shared/interlockedatomic.h index 39e615f48..cc0163f0f 100644 --- a/source/shared/interlockedatomic.h +++ b/source/shared/interlockedatomic.h @@ -4,7 +4,7 @@ // Contents: Contains a portable abstraction for interlocked, atomic // operations on int32_t and pointer types. // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/interlockedatomic_gcc.h b/source/shared/interlockedatomic_gcc.h index 7f5a974aa..e8c8e5bb2 100644 --- a/source/shared/interlockedatomic_gcc.h +++ b/source/shared/interlockedatomic_gcc.h @@ -4,7 +4,7 @@ // Contents: Contains a portable abstraction for interlocked, atomic // operations on int32_t and pointer types. // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/interlockedslist.h b/source/shared/interlockedslist.h index 6c88f0e59..bf2bc9ca2 100644 --- a/source/shared/interlockedslist.h +++ b/source/shared/interlockedslist.h @@ -4,7 +4,7 @@ // Contents: Contains a portable abstraction for interlocked, singly // linked list. // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/localization.hpp b/source/shared/localization.hpp index 136c5a519..2ec13e09d 100644 --- a/source/shared/localization.hpp +++ b/source/shared/localization.hpp @@ -3,7 +3,7 @@ // // Contents: Contains portable classes for localization // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/localizationimpl.cpp b/source/shared/localizationimpl.cpp index 92221e984..75251eb6d 100644 --- a/source/shared/localizationimpl.cpp +++ b/source/shared/localizationimpl.cpp @@ -5,7 +5,7 @@ // Must be included in one c/cpp file per binary // A build error will occur if this inclusion policy is not followed // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/msodbcsql.h b/source/shared/msodbcsql.h index d6b74a5b8..3a759252e 100644 --- a/source/shared/msodbcsql.h +++ b/source/shared/msodbcsql.h @@ -20,7 +20,7 @@ // pecuniary loss) arising out of the use of or inability to use // this SDK, even if Microsoft has been advised of the possibility // of such damages. -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/sal_def.h b/source/shared/sal_def.h index 7be9ba68a..78478eaa1 100644 --- a/source/shared/sal_def.h +++ b/source/shared/sal_def.h @@ -3,7 +3,7 @@ // // Contents: Contains the minimal definitions to build on non-Windows platforms // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/typedefs_for_linux.h b/source/shared/typedefs_for_linux.h index 6daf7fcd6..dc3b4ca5b 100644 --- a/source/shared/typedefs_for_linux.h +++ b/source/shared/typedefs_for_linux.h @@ -1,7 +1,7 @@ //--------------------------------------------------------------------------------------------------------------------------------- // File: typedefs_for_linux.h // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/version.h b/source/shared/version.h index 140e24484..7d6554431 100644 --- a/source/shared/version.h +++ b/source/shared/version.h @@ -4,7 +4,7 @@ // File: version.h // Contents: Version number constants // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -26,12 +26,12 @@ // Increase Minor with backward compatible new functionalities and API changes. // Increase Patch for backward compatible fixes. #define SQLVERSION_MAJOR 5 -#define SQLVERSION_MINOR 2 -#define SQLVERSION_PATCH 1 +#define SQLVERSION_MINOR 3 +#define SQLVERSION_PATCH 0 #define SQLVERSION_BUILD 0 // For previews, set this constant to 1. Otherwise, set it to 0 -#define PREVIEW 1 +#define PREVIEW 0 #define SEMVER_PRERELEASE // Semantic versioning build metadata, build meta data is not counted in precedence order. diff --git a/source/shared/xplat.h b/source/shared/xplat.h index f768f112f..baa393e22 100644 --- a/source/shared/xplat.h +++ b/source/shared/xplat.h @@ -3,7 +3,7 @@ // // Contents: include for definition of Windows types for non-Windows platforms // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/xplat_intsafe.h b/source/shared/xplat_intsafe.h index 68595afb9..1baa473a7 100644 --- a/source/shared/xplat_intsafe.h +++ b/source/shared/xplat_intsafe.h @@ -4,7 +4,7 @@ // Contents: This module defines helper functions to prevent // integer overflow bugs. // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/xplat_winerror.h b/source/shared/xplat_winerror.h index 292960694..44eb7c844 100644 --- a/source/shared/xplat_winerror.h +++ b/source/shared/xplat_winerror.h @@ -3,7 +3,7 @@ // // Contents: Contains the minimal definitions to build on non-Windows platforms // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/xplat_winnls.h b/source/shared/xplat_winnls.h index 3b1cbc68b..36aceae16 100644 --- a/source/shared/xplat_winnls.h +++ b/source/shared/xplat_winnls.h @@ -3,7 +3,7 @@ // // Contents: Contains the minimal definitions to build on non-Windows platforms // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/sqlsrv/config.m4 b/source/sqlsrv/config.m4 index e03ab0f4c..6b4190665 100644 --- a/source/sqlsrv/config.m4 +++ b/source/sqlsrv/config.m4 @@ -1,3 +1,23 @@ +dnl ---------------------------------------------------------------------------------------------------------------------------------- +dnl File: config.m4 +dnl +dnl Contents: the code that will go into the configure script, indicating options, +dnl external libraries and includes, and what source files are to be compiled. +dnl +dnl Microsoft Drivers 5.3 for PHP for SQL Server +dnl Copyright(c) Microsoft Corporation +dnl All rights reserved. +dnl MIT License +dnl Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the ""Software""), +dnl to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +dnl and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : +dnl The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +dnl THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +dnl FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +dnl LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +dnl IN THE SOFTWARE. +dnl --------------------------------------------------------------------------------------------------------------------------------- + PHP_ARG_ENABLE(sqlsrv, whether to enable sqlsrv functions, [ --disable-sqlsrv Disable sqlsrv functions], yes) diff --git a/source/sqlsrv/config.w32 b/source/sqlsrv/config.w32 index 77d8c4d11..449789c4b 100644 --- a/source/sqlsrv/config.w32 +++ b/source/sqlsrv/config.w32 @@ -3,7 +3,7 @@ // // Contents: JScript build configuration used by buildconf.bat // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/sqlsrv/conn.cpp b/source/sqlsrv/conn.cpp index 183ac3c55..7bf805089 100644 --- a/source/sqlsrv/conn.cpp +++ b/source/sqlsrv/conn.cpp @@ -3,7 +3,7 @@ // // Contents: Routines that use connection handles // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -95,7 +95,6 @@ struct bool_conn_str_func { } }; -#ifdef _WIN32 struct int_conn_str_func { static void func( _In_ connection_option const* option, _In_ zval* value, sqlsrv_conn* /*conn*/, _Out_ std::string& conn_str TSRMLS_DC ) @@ -111,7 +110,6 @@ struct int_conn_str_func { conn_str += "};"; } }; -#endif // _WIN32 template struct int_conn_attr_func { @@ -188,10 +186,8 @@ const char Authentication[] = "Authentication"; const char CharacterSet[] = "CharacterSet"; const char ColumnEncryption[] = "ColumnEncryption"; const char ConnectionPooling[] = "ConnectionPooling"; -#ifdef _WIN32 const char ConnectRetryCount[] = "ConnectRetryCount"; const char ConnectRetryInterval[] = "ConnectRetryInterval"; -#endif // _WIN32 const char Database[] = "Database"; const char DateAsString[] = "ReturnDatesAsStrings"; const char Driver[] = "Driver"; @@ -324,7 +320,6 @@ const connection_option SS_CONN_OPTS[] = { CONN_ATTR_STRING, column_encryption_set_func::func }, -#ifdef _WIN32 { SSConnOptionNames::ConnectRetryCount, sizeof( SSConnOptionNames::ConnectRetryCount ), @@ -343,7 +338,6 @@ const connection_option SS_CONN_OPTS[] = { CONN_ATTR_INT, int_conn_str_func::func }, -#endif // _WIN32 { SSConnOptionNames::Database, sizeof( SSConnOptionNames::Database ), diff --git a/source/sqlsrv/init.cpp b/source/sqlsrv/init.cpp index 7385dc6b1..bb8ab04b4 100644 --- a/source/sqlsrv/init.cpp +++ b/source/sqlsrv/init.cpp @@ -2,7 +2,7 @@ // File: init.cpp // Contents: initialization routines for the extension // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/sqlsrv/php_sqlsrv.h b/source/sqlsrv/php_sqlsrv.h index 17175730a..6c5e7b015 100644 --- a/source/sqlsrv/php_sqlsrv.h +++ b/source/sqlsrv/php_sqlsrv.h @@ -8,7 +8,7 @@ // // Comments: Also contains "internal" declarations shared across source files. // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/sqlsrv/stmt.cpp b/source/sqlsrv/stmt.cpp index 96aeae8a0..ac334cb9b 100644 --- a/source/sqlsrv/stmt.cpp +++ b/source/sqlsrv/stmt.cpp @@ -3,7 +3,7 @@ // // Contents: Routines that use statement handles // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/sqlsrv/template.rc b/source/sqlsrv/template.rc index 446f50d88..ffee85372 100644 --- a/source/sqlsrv/template.rc +++ b/source/sqlsrv/template.rc @@ -3,7 +3,7 @@ // // Contents: Version resource // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/sqlsrv/util.cpp b/source/sqlsrv/util.cpp index 50b963e48..bc26658c0 100644 --- a/source/sqlsrv/util.cpp +++ b/source/sqlsrv/util.cpp @@ -5,7 +5,7 @@ // // Comments: Mostly error handling and some type handling // -// Microsoft Drivers 5.2 for PHP for SQL Server +// Microsoft Drivers 5.3 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/test/functional/pdo_sqlsrv/MsCommon.inc b/test/functional/pdo_sqlsrv/MsCommon.inc index cddfdab9c..b1c479e95 100644 --- a/test/functional/pdo_sqlsrv/MsCommon.inc +++ b/test/functional/pdo_sqlsrv/MsCommon.inc @@ -8,30 +8,6 @@ */ -// -// looks like an additional file (in addition to pdo_test_base.inc) may be needed for these PHPTs -// to be runnable from the MSSQL teams' internal proprietary test running system -// - -function IsAEQualified($conn) -{ - $msodbcsql_ver = $conn->getAttribute(PDO::ATTR_CLIENT_VERSION)["DriverVer"]; - $msodbcsql_maj = explode(".", $msodbcsql_ver)[0]; - if ($msodbcsql_maj < 17) { - return false; - } - require 'MsSetup.inc'; - if ($daasMode) { - // running against Azure - return true; - } - // if not Azure, check the server version - $server_ver = $conn->getAttribute(PDO::ATTR_SERVER_VERSION); - if (explode('.', $server_ver)[0] < 13) - return false; - return true; -} - // TO BE DELETED function connect($options=array()) { @@ -40,7 +16,7 @@ function connect($options=array()) // simply use $databaseName from MsSetup.inc to facilitate testing in Azure, // which does not support switching databases require 'MsSetup.inc'; - $conn = new PDO( "sqlsrv:Server=$server;database=$databaseName;ConnectionPooling=false;" , $uid, $pwd, $options); + $conn = new PDO( "sqlsrv:Server=$server;database=$databaseName;Driver=$driver;ConnectionPooling=false;" , $uid, $pwd, $options); $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); return $conn; } @@ -58,138 +34,6 @@ function connect($options=array()) } } - -/** - * Connect to the database specified in MsSetup.inc; Column Encryption keywords automatically added when $keystore is not none - * @param string $keywords : string to append to the dsn string in PDO::_construct - * @param array $options : attributes to pass to PDO::_construct - * @param bool $disableCE : flag for disabling column encryption even when keystore is NOT none - * for testing fetching encrypted data when connection column encryption is off - * @return PDO connection object - */ -function ae_connect( $keywords='', $options=array(), $disableCE = false ) -{ - try - { - // simply use $databaseName from MsSetup.inc to facilitate testing in Azure, - // which does not support switching databases - require 'MsSetup.inc'; - $dsn = "sqlsrv:Server=$server;database=$databaseName;ConnectionPooling=false;"; - if ( $keystore != "none" && !$disableCE ) - { - $dsn .= "ColumnEncryption=Enabled;"; - } - if ( $keystore == "ksp" && !$disableCE ) - { - require( 'AE_Ksp.inc' ); - $ksp_path = getKSPPath(); - $dsn .= "CEKeystoreProvider=$ksp_path;CEKeystoreName=$ksp_name;CEKeystoreEncryptKey=$encrypt_key;"; - } - if ( $keywords ) - { - $dsn .= $keywords; - } - $conn = new PDO( $dsn, $uid, $pwd, $options ); - $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); - return $conn; - } - catch( PDOException $e ) - { - var_dump( $e ); - exit; - } - catch(Exception $e) - { - var_dump( $e ); - exit; - } -} - - -/** - * @return string CEK name depending on the connection keywords - */ -function getCekName() -{ - require 'MsSetup.inc'; - $cekName = ''; - switch ( $keystore ) { - case "none": - $cekName = ''; - break; - case "win": - $cekName = 'AEColumnKey'; - break; - case "ksp": - $cekName = 'CustomCEK'; - break; - case "akv": - $cekName = 'AKVColumnKey'; - break; - default: - echo "getCekName: Invalid keystore name.\n"; - } - return $cekName; -} - - -/** - * class for encapsulating column metadata needed for creating a table - */ -class columnMeta { - public $colName; - public $dataType; //a string that includes the size of the type if necessary (e.g., decimal(10,5)) - public $encType; //randomized or deterministic; default is deterministic - public $options; //a string that is null by default (e.g. NOT NULL Identity (1,1) ) - - function __construct( $dataType, $colName = null, $options = null, $encType = "deterministic" ) - { - if ( is_null( $colName )) - { - $this->colName = get_default_colname( $dataType ); - } - else - { - $this->colName = $colName; - } - $this->dataType = $dataType; - $this->encType = $encType; - $this->options = $options; - } - /** - * @return string column definition for creating a table - */ - function getColDef() - { - require 'MsSetup.inc'; - $append = " "; - - // an identity column is not encrypted because a select query with identity column as the where clause is often run and the user want to have to bind parameter every time - if ( $keystore != "none" && stripos( $this->options, "identity" ) === false ) - { - $cekName = getCekName(); - if ( stripos( $this->dataType, "char" ) !== false ) - $append .= "COLLATE Latin1_General_BIN2 "; - $append .= sprintf( "ENCRYPTED WITH (ENCRYPTION_TYPE = %s, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = $cekName) ", $this->encType ); - } - $append .= $this->options; - $colDef = "[" . $this->colName . "] " . $this->dataType . $append; - return $colDef; - } -} - - -/** - * @return string default column name when a name is not provided in the columnMeta class - */ -function get_default_colname( $dataType ) -{ - $colName = "c_" . str_replace( ",", "_", str_replace( "(", "_", $dataType )); - $colName = rtrim( $colName, ")" ); - return $colName; -} - - /** * Create a table * @param object $conn : PDO connection object diff --git a/test/functional/pdo_sqlsrv/MsCommon_mid-refactor.inc b/test/functional/pdo_sqlsrv/MsCommon_mid-refactor.inc index dd183c32a..cf2ff605c 100644 --- a/test/functional/pdo_sqlsrv/MsCommon_mid-refactor.inc +++ b/test/functional/pdo_sqlsrv/MsCommon_mid-refactor.inc @@ -13,10 +13,6 @@ // to be runnable from the MSSQL teams' internal proprietary test running system // -const KSP_NAME = 'MyCustomKSPName'; -const ENCRYPT_KEY = 'LPKCWVD07N3RG98J0MBLG4H2'; -const KSP_TEST_TABLE = 'CustomKSPTestTable'; - function isAEQualified($conn) { $msodbcsql_ver = $conn->getAttribute(PDO::ATTR_CLIENT_VERSION)["DriverVer"]; @@ -52,7 +48,7 @@ function connect($keywords = '', $options=array(), $errmode = PDO::ERRMODE_EXCEP // simply use $databaseName from MsSetup.inc to facilitate testing in Azure, // which does not support switching databases require("MsSetup.inc"); - $dsn = getDSN($server, $databaseName, $keywords, $disableCE); + $dsn = getDSN($server, $databaseName, $driver, $keywords, $disableCE); $conn = new PDO($dsn, $uid, $pwd, $options); if ($errmode == PDO::ERRMODE_EXCEPTION || $errmode == PDO::ERRMODE_WARNING || $errmode == PDO::ERRMODE_SILENT) { $conn->setAttribute(PDO::ATTR_ERRMODE, $errmode); @@ -76,7 +72,7 @@ function connect($keywords = '', $options=array(), $errmode = PDO::ERRMODE_EXCEP * @param bool $disableCE : flag for disabling column encryption even when keystore is NOT none * @return string dsn string used for PDO constructor */ -function getDSN($sqlsrvserver, $database, $keywords = '', $disableCE = false) +function getDSN($sqlsrvserver, $database, $driver = null, $keywords = '', $disableCE = false) { require("MsSetup.inc"); $dsn = ""; @@ -89,6 +85,9 @@ function getDSN($sqlsrvserver, $database, $keywords = '', $disableCE = false) if ($database) { $dsn .= "database=$database;"; } + if (!is_null($driver)) { + $dsn .= "driver=$driver;"; + } if ($keystore != "none" && !$disableCE) { $dsn .= "ColumnEncryption=Enabled;"; } diff --git a/test/functional/pdo_sqlsrv/MsSetup.inc b/test/functional/pdo_sqlsrv/MsSetup.inc index e07c46a7d..823f283cc 100644 --- a/test/functional/pdo_sqlsrv/MsSetup.inc +++ b/test/functional/pdo_sqlsrv/MsSetup.inc @@ -18,7 +18,6 @@ if (isset($_ENV['MSSQL_SERVER']) || isset($_ENV['MSSQL_USER']) || isset($_ENV['M $uid = 'TARGET_USERNAME'; $pwd = 'TARGET_PASSWORD'; $databaseName = 'TARGET_DATABASE'; - $DriverName = "ODBC Driver 11 for SQL Server"; } $adServer = 'TARGET_AD_SERVER'; @@ -27,13 +26,12 @@ $adUser = 'TARGET_AD_USERNAME'; $adPassword = 'TARGET_AD_PASSWORD'; $driverType = true; -$PhpDriver = "ODBC Driver 11 for SQL Server"; +$driver = "ODBC Driver 17 for SQL Server"; $tableName = 'pdo_test_table'; $tableIndex = 'php_test_table_idx'; $procName = 'php_test_proc'; $fileName = 'php_test_file.dat'; -$dsn = "odbc:Driver={$DriverName};Server=$server"; $connectionOptions = array(); $daasMode = false; $marsMode = true; diff --git a/test/functional/pdo_sqlsrv/PDO101_LargeColumnName.phpt b/test/functional/pdo_sqlsrv/PDO101_LargeColumnName.phpt index b5019290d..be6234f2e 100644 --- a/test/functional/pdo_sqlsrv/PDO101_LargeColumnName.phpt +++ b/test/functional/pdo_sqlsrv/PDO101_LargeColumnName.phpt @@ -1,76 +1,77 @@ ---TEST-- -PDO - Large Column Name Test ---DESCRIPTION-- -Verifies that long column names are supported (up to 128 chars). ---ENV-- -PHPT_EXEC=true ---SKIPIF-- - ---FILE-- +--TEST-- +PDO - Large Column Name Test +--DESCRIPTION-- +Verifies that long column names are supported (up to 128 chars). +--ENV-- +PHPT_EXEC=true +--SKIPIF-- + +--FILE-- query("CREATE TABLE [$tableName] ([$columnName] int)"); - $conn->query("INSERT INTO [$tableName] ([$columnName]) VALUES (5)"); $stmt = $conn->query("SELECT * from [$tableName]"); - if ( null == $stmt ) - { - if (!$expectfail) - FatalError("Possible regression: Unable to retrieve inserted value."); - } - - DropTable($conn, $tableName); - + dropTable($conn, $tableName); } //-------------------------------------------------------------------- -// Repro +// repro // //-------------------------------------------------------------------- -function Repro() +function repro() { - $testName = "PDO - Large Column Name Test"; - StartTest($testName); - - $columnName = "a"; - - try - { - for ($a = 1; $a <= 128; $a++) - { - LargeColumnNameTest($columnName, $a > 128); - $columnName .= "A"; - } - } - catch (Exception $e) - { - echo $e->getMessage(); + startTest($testName); + + // The maximum size of a column name is 128 characters + $maxlen = 128; + $columnName = str_repeat('A', $maxlen); + + try { + largeColumnNameTest($columnName); + } catch (Exception $e) { + echo "Possible regression: Unable to retrieve inserted value\n"; + print_r($e->getMessage()); + echo "\n"; } - - EndTest($testName); + + // Now add another character to the name + $columnName .= 'A'; + try { + largeColumnNameTest($columnName); + } catch (Exception $e) { + // Expects to fail + $expected = 'is too long. Maximum length is 128.'; + if (strpos($e->getMessage(), $expected) === false) { + print_r($e->getMessage()); + echo "\n"; + } + } + + endTest($testName); } -Repro(); -?> ---EXPECT-- -Test "PDO - Large Column Name Test" completed successfully. +repro(); +?> +--EXPECT-- +Test "PDO - Large Column Name Test" completed successfully. diff --git a/test/functional/pdo_sqlsrv/PDO101_LargeColumnName_unicode_col_name.phpt b/test/functional/pdo_sqlsrv/PDO101_LargeColumnName_unicode_col_name.phpt index 634dc5272..9ad27164e 100644 --- a/test/functional/pdo_sqlsrv/PDO101_LargeColumnName_unicode_col_name.phpt +++ b/test/functional/pdo_sqlsrv/PDO101_LargeColumnName_unicode_col_name.phpt @@ -8,69 +8,70 @@ PHPT_EXEC=true --FILE-- query("CREATE TABLE [$tableName] ([$columnName] int)"); - $conn->query("INSERT INTO [$tableName] ([$columnName]) VALUES (5)"); $stmt = $conn->query("SELECT * from [$tableName]"); - if ( null == $stmt ) - { - if (!$expectfail) - FatalError("Possible regression: Unable to retrieve inserted value."); - } - - DropTable($conn, $tableName); - + dropTable($conn, $tableName); } //-------------------------------------------------------------------- -// Repro +// repro // //-------------------------------------------------------------------- -function Repro() +function repro() { - $testName = "PDO - Large Column Name Test"; - StartTest($testName); + startTest($testName); - $columnName = "是"; + // The maximum size of a column name is 128 characters + $maxlen = 128; + $columnName = str_repeat('是', $maxlen); - try - { - for ($a = 1; $a <= 128; $a++) - { - LargeColumnNameTest($columnName, $a > 128); - $columnName .= "是"; - } + try { + largeColumnNameTest($columnName); + } catch (Exception $e) { + echo "Possible regression: Unable to retrieve inserted value\n"; + print_r($e->getMessage()); + echo "\n"; } - catch (Exception $e) - { - echo $e->getMessage(); + + // Now add another character to the name + $columnName .= '是'; + try { + largeColumnNameTest($columnName); + } catch (Exception $e) { + // Expects to fail + $expected = 'is too long. Maximum length is 128.'; + if (strpos($e->getMessage(), $expected) === false) { + print_r($e->getMessage()); + echo "\n"; + } } - EndTest($testName); + endTest($testName); } -Repro(); +repro(); + ?> --EXPECT-- Test "PDO - Large Column Name Test" completed successfully. diff --git a/test/functional/pdo_sqlsrv/PDO21_Connection.phpt b/test/functional/pdo_sqlsrv/PDO21_Connection.phpt index f09899626..9498a3585 100644 --- a/test/functional/pdo_sqlsrv/PDO21_Connection.phpt +++ b/test/functional/pdo_sqlsrv/PDO21_Connection.phpt @@ -15,7 +15,7 @@ try { // Invalid connection attempt => errors are expected $serverName="InvalidServerName"; - $dsn = getDSN($serverName, $databaseName); + $dsn = getDSN($serverName, $databaseName, $driver); $conn1 = new PDO($dsn, $uid, $pwd, $connectionOptions); if ($conn1) { printf("Invalid connection attempt should have failed.\n"); diff --git a/test/functional/pdo_sqlsrv/PDO_ConnPool_Unix.phpt b/test/functional/pdo_sqlsrv/PDO_ConnPool_Unix.phpt index 05bf24a71..c68a46b14 100644 --- a/test/functional/pdo_sqlsrv/PDO_ConnPool_Unix.phpt +++ b/test/functional/pdo_sqlsrv/PDO_ConnPool_Unix.phpt @@ -6,6 +6,15 @@ This test assumes the default odbcinst.ini has not been modified. --FILE-- exec($sql); diff --git a/test/functional/pdo_sqlsrv/pdo_040_error_information.phpt b/test/functional/pdo_sqlsrv/pdo_040_error_information.phpt index 93b6e2fd4..c8424856d 100644 --- a/test/functional/pdo_sqlsrv/pdo_040_error_information.phpt +++ b/test/functional/pdo_sqlsrv/pdo_040_error_information.phpt @@ -12,6 +12,8 @@ try { // Create table $tableName = 'pdo_040test'; + dropTable($conn, $tableName); + // common function insertRow() is not used here since the test deliberately // executes an invalid insertion statement // thus it's not necessary to create an encrypted column for testing column encryption diff --git a/test/functional/pdo_sqlsrv/pdo_065_construct_persistent.phpt b/test/functional/pdo_sqlsrv/pdo_065_construct_persistent.phpt index 883da0299..8f2d8e8f7 100644 --- a/test/functional/pdo_sqlsrv/pdo_065_construct_persistent.phpt +++ b/test/functional/pdo_sqlsrv/pdo_065_construct_persistent.phpt @@ -13,7 +13,7 @@ require_once("MsCommon_mid-refactor.inc"); try { echo "Testing a connection with ATTR_PERSISTENT...\n"; // setting PDO::ATTR_PERSISTENT in PDO constructor returns an exception - $dsn = getDSN($server, $databaseName); + $dsn = getDSN($server, $databaseName, $driver); $attr = array(PDO::ATTR_PERSISTENT => true); $conn = new PDO($dsn, $uid, $pwd, $attr); //free the connection diff --git a/test/functional/pdo_sqlsrv/pdo_065_construct_prefetch.phpt b/test/functional/pdo_sqlsrv/pdo_065_construct_prefetch.phpt index 463b7ac4d..88f47495f 100644 --- a/test/functional/pdo_sqlsrv/pdo_065_construct_prefetch.phpt +++ b/test/functional/pdo_sqlsrv/pdo_065_construct_prefetch.phpt @@ -10,7 +10,7 @@ require_once("MsSetup.inc"); require_once("MsCommon_mid-refactor.inc"); try { echo "Testing a connection with ATTR_PREFETCH before ERRMODE_EXCEPTION...\n"; - $dsn = getDSN($server, $databaseName); + $dsn = getDSN($server, $databaseName, $driver); $attr = array(PDO::ATTR_PREFETCH => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION); $conn = new PDO($dsn, $uid, $pwd, $attr); diff --git a/test/functional/pdo_sqlsrv/pdo_707_ae_output_param_decimals.phpt b/test/functional/pdo_sqlsrv/pdo_707_ae_output_param_decimals.phpt index 6b59c134e..67c0f4fd0 100644 --- a/test/functional/pdo_sqlsrv/pdo_707_ae_output_param_decimals.phpt +++ b/test/functional/pdo_sqlsrv/pdo_707_ae_output_param_decimals.phpt @@ -7,7 +7,7 @@ do not need to be encrypted --ENV-- PHPT_EXEC=true --SKIPIF-- - + --FILE-- + --FILE-- + --FILE-- + --FILE-- "int", createTable($conn, $tbname, $colMetaArr); // Create a Store Procedure $spname = 'selectAllColumns'; +dropProc($conn, $spname); $spSql = "CREATE PROCEDURE $spname ( @c1_int int OUTPUT, @c2_smallint smallint OUTPUT, @c3_tinyint tinyint OUTPUT, @c4_bit bit OUTPUT, diff --git a/test/functional/pdo_sqlsrv/pdo_connect_encrypted.phpt b/test/functional/pdo_sqlsrv/pdo_connect_encrypted.phpt index 8b3b0a0e6..124df22b7 100644 --- a/test/functional/pdo_sqlsrv/pdo_connect_encrypted.phpt +++ b/test/functional/pdo_sqlsrv/pdo_connect_encrypted.phpt @@ -1,7 +1,7 @@ --TEST-- Test new connection keyword ColumnEncryption --SKIPIF-- - + --FILE-- getMessage()); + $err = $e->getMessage(); + if (strpos($err, 'SQLSTATE[08S02]')===false or (strpos($err, 'TCP Provider')===false and strpos($err, 'SMux Provider')===false)) { + echo "Error: Wrong error message.\n"; + print_r($err); + } } unset($conn); @@ -200,14 +204,18 @@ try { } } catch (PDOException $e) { echo "Error executing statement 8.\n"; - print_r($e->getMessage()); + $err = $e->getMessage(); + if (strpos($err, 'SQLSTATE[IMSSP]')===false or strpos($err, 'The connection cannot process this operation because there is a statement with pending results')===false) { + echo "Error: Wrong error message.\n"; + print_r($err); + } } unset($conn); unset($conn_break); ?> ---EXPECTREGEX-- +--EXPECT-- Statement 1 successful. 16 rows in result set. Statement 2 successful. @@ -219,7 +227,5 @@ Statement 4 successful. Statement 5 successful. -1 rows in result set. Error executing statement 6. -SQLSTATE\[08S02\]: \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]TCP Provider: An existing connection was forcibly closed by the remote host. Statement 7 successful. Error executing statement 8. -SQLSTATE\[IMSSP\]: The connection cannot process this operation because there is a statement with pending results. To make the connection available for other queries, either fetch all results or cancel or free the statement. For more information, see the product documentation about the MultipleActiveResultSets connection option. diff --git a/test/functional/pdo_sqlsrv/pdo_connection_resiliency_keywords.phpt b/test/functional/pdo_sqlsrv/pdo_connection_resiliency_keywords.phpt index 1d7b066e9..b012eed98 100644 --- a/test/functional/pdo_sqlsrv/pdo_connection_resiliency_keywords.phpt +++ b/test/functional/pdo_sqlsrv/pdo_connection_resiliency_keywords.phpt @@ -1,8 +1,7 @@ --TEST-- Test the connection resiliency keywords ConnectRetryCount and ConnectRetryInterval and their ranges of acceptable values --SKIPIF-- - + --FILE-- getMessage() ); + echo "Transaction failed.\n"; + $err = $e->getMessage(); + if (strpos($err, 'SQLSTATE[08S02]')===false or (strpos($err, 'TCP Provider')===false and strpos($err, 'SMux Provider')===false)) { + echo "Error: Wrong error message.\n"; + print_r($err); + } } // This try catch block prevents an Uncaught PDOException error that occurs @@ -201,17 +206,20 @@ try } catch ( PDOException $e ) { - print_r( $e->getMessage() ); + $err = $e->getMessage(); + if (strpos($err, 'SQLSTATE[08S01]')===false or strpos($err, 'Communication link failure')===false) { + echo "Error: Wrong error message.\n"; + print_r($err); + } } $conn_break = null; ?> ---EXPECTREGEX-- +--EXPECT-- Statement 1 prepared. Statement 1 executed. Transaction begun. Transaction was committed. Transaction begun. -SQLSTATE\[08S02\]: \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]TCP Provider: An existing connection was forcibly closed by the remote host. -SQLSTATE\[08S01\]: \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Communication link failure +Transaction failed. diff --git a/test/functional/pdo_sqlsrv/pdo_connection_resiliency_timeouts.phpt b/test/functional/pdo_sqlsrv/pdo_connection_resiliency_timeouts.phpt index 4389b3a95..279a7eb48 100644 --- a/test/functional/pdo_sqlsrv/pdo_connection_resiliency_timeouts.phpt +++ b/test/functional/pdo_sqlsrv/pdo_connection_resiliency_timeouts.phpt @@ -40,7 +40,11 @@ try catch( PDOException $e ) { echo "Error executing statement 1.\n"; - print_r( $e->getMessage() ); + $err = $e->getMessage(); + if (strpos($err, 'SQLSTATE[08S02]')===false or (strpos($err, 'TCP Provider')===false and strpos($err, 'SMux Provider')===false)) { + echo "Error: Wrong error message.\n"; + print_r($err); + } } $conn = null; @@ -82,7 +86,6 @@ $conn_break = null; DropTables( $server, $uid, $pwd, $tableName1, $tableName2 ); ?> ---EXPECTREGEX-- +--EXPECT-- Error executing statement 1. -SQLSTATE\[08S02\]: \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]TCP Provider: An existing connection was forcibly closed by the remote host. Query successfully executed. diff --git a/test/functional/pdo_sqlsrv/pdo_utf8_conn.phpt b/test/functional/pdo_sqlsrv/pdo_utf8_conn.phpt index f51d3ba6b..a5c31e09e 100644 --- a/test/functional/pdo_sqlsrv/pdo_utf8_conn.phpt +++ b/test/functional/pdo_sqlsrv/pdo_utf8_conn.phpt @@ -4,6 +4,7 @@ UTF-8 connection strings --FILE-- query( "SELECT @@VERSION" ); -if ($stmt) { - $ver_string = $stmt->fetch(PDO::FETCH_NUM)[0]; -} else { - die( "skip Could not fetch SQL Server version during SKIPIF."); +$msodbcsql_ver = $conn->getAttribute(PDO::ATTR_CLIENT_VERSION)["DriverVer"]; +$msodbcsql_maj = explode(".", $msodbcsql_ver)[0]; +$msodbcsql_min = explode(".", $msodbcsql_ver)[1]; + +if (!$is_win) { + if ($msodbcsql_maj < 17 or $msodbcsql_min < 2) { + die("skip Unsupported ODBC driver version"); + } } -$version = explode(' ', $ver_string); +// Get SQL Server Version +// Exclude this check if running on Azure +if (!$daasMode) { + $stmt = $conn->query( "SELECT @@VERSION" ); + if ($stmt) { + $ver_string = $stmt->fetch(PDO::FETCH_NUM)[0]; + } else { + die( "skip Could not fetch SQL Server version during SKIPIF."); + } + + $version = explode(' ', $ver_string); -if ($version[3] < '2014') { - die("skip Wrong version of SQL Server, 2014 or later required"); + if ($version[3] < '2014') { + die("skip Wrong version of SQL Server, 2014 or later required"); + } } ?> diff --git a/test/functional/pdo_sqlsrv/skipif_version_less_than_2k16.inc b/test/functional/pdo_sqlsrv/skipif_version_less_than_2k16.inc index e2f9456bf..72553974b 100644 --- a/test/functional/pdo_sqlsrv/skipif_version_less_than_2k16.inc +++ b/test/functional/pdo_sqlsrv/skipif_version_less_than_2k16.inc @@ -1,10 +1,14 @@ query( "SELECT @@VERSION" ); -if ($stmt) { - $ver_string = $stmt->fetch(PDO::FETCH_NUM)[0]; -} else { - die( "skip Could not fetch SQL Server version during SKIPIF."); +$msodbcsql_ver = $conn->getAttribute(PDO::ATTR_CLIENT_VERSION)["DriverVer"]; +$msodbcsql_maj = explode(".", $msodbcsql_ver)[0]; +$msodbcsql_min = explode(".", $msodbcsql_ver)[1]; + +if (!$is_win) { + if ($msodbcsql_maj < 17) { + die("skip Unsupported ODBC driver version"); + } } -$version = explode(' ', $ver_string); +// Get SQL Server Version +// Exclude this check if running on Azure +if (!$daasMode) { + $stmt = $conn->query( "SELECT @@VERSION" ); + if ($stmt) { + $ver_string = $stmt->fetch(PDO::FETCH_NUM)[0]; + } else { + die( "skip Could not fetch SQL Server version during SKIPIF."); + } + + $version = explode(' ', $ver_string); -if ($version[3] < '2016') { - die("skip Wrong version of SQL Server, 2016 or later required"); + if ($version[3] < '2016') { + die("skip Wrong version of SQL Server, 2016 or later required"); + } } ?> diff --git a/test/functional/pdo_sqlsrv/test_ae_keys_setup.phpt b/test/functional/pdo_sqlsrv/test_ae_keys_setup.phpt index ed42f74c6..e8f46546d 100644 --- a/test/functional/pdo_sqlsrv/test_ae_keys_setup.phpt +++ b/test/functional/pdo_sqlsrv/test_ae_keys_setup.phpt @@ -1,36 +1,49 @@ ---TEST-- -retrieval of names of column master key and column encryption key generated in the database setup ---SKIPIF-- - ---FILE-- -query($query); - $master_key_row = $stmt->fetch(); - - $query = "SELECT name FROM sys.column_encryption_keys"; - $stmt = $conn->query($query); - $encryption_key_row = $stmt->fetch(); - - if ($master_key_row[0] == 'AEMasterKey' && $encryption_key_row[0] == 'AEColumnKey'){ - echo "Test Successfully done.\n"; - } - else { - die("Column Master Key and Column Encryption Key not created.\n"); - } - unset($stmt); -} -else { - echo "Test Successfully done.\n"; -} -unset($conn); -?> ---EXPECT-- +--TEST-- +Test the existence of Windows Always Encrypted keys generated in the database setup +--DESCRIPTION-- +This test iterates through the rows of sys.column_master_keys and/or +sys.column_encryption_keys to look for the specific column master key and +column encryption key generated in the database setup +--SKIPIF-- + +--FILE-- +query($query); + + // Do not assume the master key must be the first one created + $found = false; + while ($master_key_row = $stmt->fetch()) { + if ($master_key_row[0] == 'AEMasterKey') { + $found = true; + } + } + if (!$found) { + die("Windows Column Master Key not created.\n"); + } + + // Do not assume the encryption key must be the first one created + $query = "SELECT name FROM sys.column_encryption_keys"; + $stmt = $conn->query($query); + + $found = false; + while ($encryption_key_row = $stmt->fetch()) { + if ($encryption_key_row[0] == 'AEColumnKey') { + $found = true; + } + } + if (!$found) { + die("Windows Column Encryption Key not created.\n"); + } + unset($stmt); +} + +echo "Test Successfully done.\n"; +unset($conn); +?> +--EXPECT-- Test Successfully done. \ No newline at end of file diff --git a/test/functional/sqlsrv/MsCommon.inc b/test/functional/sqlsrv/MsCommon.inc index 13900e2ec..def2d0f50 100644 --- a/test/functional/sqlsrv/MsCommon.inc +++ b/test/functional/sqlsrv/MsCommon.inc @@ -472,7 +472,7 @@ function isLocaleSupported() if (isWindows()) { return true; } - if (AE\isColEncrypted()) { + if (AE\isDataEncrypted()) { return false; } // now check ODBC version diff --git a/test/functional/sqlsrv/MsSetup.inc b/test/functional/sqlsrv/MsSetup.inc index 1ec7ceef4..aec2b4bb1 100644 --- a/test/functional/sqlsrv/MsSetup.inc +++ b/test/functional/sqlsrv/MsSetup.inc @@ -18,7 +18,9 @@ $tableIndex = "php_test_table_index"; $procName = "php_test_proc"; $fileName = "php_test_file.dat"; -$connectionOptions = array("Database"=>$database, "UID"=>$userName, "PWD"=>$userPassword, "TraceOn"=>false); +$driver = "ODBC Driver 17 for SQL Server"; + +$connectionOptions = array("Database" => $database, "UID" => $userName, "PWD" => $userPassword, "TraceOn" => false, "Driver" => $driver); $daasMode = false; $marsMode = true; diff --git a/test/functional/sqlsrv/TC52_StreamSend.phpt b/test/functional/sqlsrv/TC52_StreamSend.phpt index 648c23fdf..3779e4448 100644 --- a/test/functional/sqlsrv/TC52_StreamSend.phpt +++ b/test/functional/sqlsrv/TC52_StreamSend.phpt @@ -19,7 +19,7 @@ function sendStream($minType, $maxType, $atExec) startTest($testName); setup(); - $tableName = "TC52test"; + $tableName = "TC52test" . rand(0, 100); $fileName = "TC52test.dat"; $conn1 = AE\connect(); diff --git a/test/functional/sqlsrv/TC54_StreamPrepared.phpt b/test/functional/sqlsrv/TC54_StreamPrepared.phpt index 94a6bbe88..a22868f90 100644 --- a/test/functional/sqlsrv/TC54_StreamPrepared.phpt +++ b/test/functional/sqlsrv/TC54_StreamPrepared.phpt @@ -18,7 +18,7 @@ function sendStream($minType, $maxType) startTest($testName); setup(); - $tableName = "TC54test"; + $tableName = "TC54test" . rand(0, 100); $fileName = "TC53test.dat"; $conn1 = AE\connect(); diff --git a/test/functional/sqlsrv/TC84_LargeColumnName.phpt b/test/functional/sqlsrv/TC84_LargeColumnName.phpt index bebcfadc4..b7cc3d570 100644 --- a/test/functional/sqlsrv/TC84_LargeColumnName.phpt +++ b/test/functional/sqlsrv/TC84_LargeColumnName.phpt @@ -10,7 +10,7 @@ PHPT_EXEC=true 128); - $columnName .= "A"; - } - } catch (Exception $e) { - echo $e->getMessage(); - } + // The maximum size of a column name is 128 characters + $maxlen = 128; + $columnName = str_repeat('a', $maxlen); + largeColumnNameTest($columnName); + + // Now add another character to the name + $columnName .= "A"; + + largeColumnNameTest($columnName, true); endTest($testName); } diff --git a/test/functional/sqlsrv/TC84_LargeColumnName_unicode.phpt b/test/functional/sqlsrv/TC84_LargeColumnName_unicode.phpt index 48bdc11c9..7a0aca36f 100644 --- a/test/functional/sqlsrv/TC84_LargeColumnName_unicode.phpt +++ b/test/functional/sqlsrv/TC84_LargeColumnName_unicode.phpt @@ -10,35 +10,44 @@ PHPT_EXEC=true 'UTF-8' )); + $conn = connect(array('CharacterSet'=>'UTF-8')); $tableName = "LargeColumnNameTest"; dropTable($conn, $tableName); - sqlsrv_query($conn, "CREATE TABLE [$tableName] ([$columnName] int)"); - - sqlsrv_query($conn, "INSERT INTO [$tableName] ([$columnName]) VALUES (5)"); + $stmt = sqlsrv_query($conn, "CREATE TABLE [$tableName] ([$columnName] int)"); + if ($stmt == null) { + if (!$expectFail) { + fatalError("Possible regression: Unable to create test $tableName."); + } else { + $expected = 'is too long. Maximum length is 128.'; + if (strpos(sqlsrv_errors()[0]['message'], $expected) === false) { + print_r(sqlsrv_errors()); + } + echo "$"; + echo "stmt = null"; + echo "\n"; + } + } else { + sqlsrv_query($conn, "INSERT INTO [$tableName] ([$columnName]) VALUES (5)"); - $stmt = sqlsrv_query($conn, "SELECT * from [$tableName]"); + $stmt = sqlsrv_query($conn, "SELECT * from [$tableName]"); - if (null == $stmt) { - echo "$"; - echo "stmt = null"; - echo "\n"; - } else { if (null == sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) { - if (!$expectfail) { + if (!$expectFail) { fatalError("Possible regression: Unable to retrieve inserted value."); } } sqlsrv_free_stmt($stmt); } + dropTable($conn, $tableName); + sqlsrv_close($conn); } @@ -53,16 +62,16 @@ function repro() startTest($testName); - $columnName = "银"; + // The maximum size of a column name is 128 characters + $maxlen = 128; + $columnName = str_repeat('银', $maxlen); - try { - for ($a = 1; $a <= 129; $a++) { - LargeColumnNameTest($columnName, $a > 128); - $columnName .= "银"; - } - } catch (Exception $e) { - echo $e->getMessage(); - } + largeColumnNameTest($columnName); + + // Now add another character to the name + $columnName .= "银"; + + largeColumnNameTest($columnName, true); endTest($testName); } diff --git a/test/functional/sqlsrv/TC84_LargeColumnName_unicode_col_name.phpt b/test/functional/sqlsrv/TC84_LargeColumnName_unicode_col_name.phpt deleted file mode 100644 index dc7a1eb2d..000000000 --- a/test/functional/sqlsrv/TC84_LargeColumnName_unicode_col_name.phpt +++ /dev/null @@ -1,75 +0,0 @@ ---TEST-- -PHP - Large Unicode Column Name Test ---DESCRIPTION-- -Verifies that long column names are supported (up to 128 chars). ---ENV-- -PHPT_EXEC=true ---SKIPIF-- - ---FILE-- -'UTF-8' )); - - $tableName = "LargeColumnNameTest"; - - dropTable($conn, $tableName); - - sqlsrv_query($conn, "CREATE TABLE [$tableName] ([$columnName] int)"); - - sqlsrv_query($conn, "INSERT INTO [$tableName] ([$columnName]) VALUES (5)"); - - $stmt = sqlsrv_query($conn, "SELECT * from [$tableName]"); - - if (null == $stmt) { - echo "$"; - echo "stmt = null"; - echo "\n"; - } else { - if (null == sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) { - if (!$expectfail) { - fatalError("Possible regression: Unable to retrieve inserted value."); - } - } - sqlsrv_free_stmt($stmt); - } - - sqlsrv_close($conn); -} - - -//-------------------------------------------------------------------- -// repro -// -//-------------------------------------------------------------------- -function repro() -{ - $testName = "PHP - Large Unicode Column Name Test"; - - startTest($testName); - - $columnName = "银"; - - try { - for ($a = 1; $a <= 129; $a++) { - LargeColumnNameTest($columnName, $a > 128); - $columnName .= "银"; - } - } catch (Exception $e) { - echo $e->getMessage(); - } - - - endTest($testName); -} - -repro(); -?> ---EXPECT-- -$stmt = null -Test "PHP - Large Unicode Column Name Test" completed successfully. diff --git a/test/functional/sqlsrv/connection_resiliency.phpt b/test/functional/sqlsrv/connection_resiliency.phpt index 59ee6c277..2d47f6fe5 100644 --- a/test/functional/sqlsrv/connection_resiliency.phpt +++ b/test/functional/sqlsrv/connection_resiliency.phpt @@ -144,7 +144,12 @@ $stmt6 = sqlsrv_query( $conn, "SELECT * FROM $tableName2" ); if( $stmt6 === false ) { echo "Error in statement 6.\n"; - print_r( sqlsrv_errors() ); + $err = sqlsrv_errors(); + if (strpos($err[0][0], '08S01')===false or + (strpos($err[0][2], 'TCP Provider:')===false and strpos($err[0][2], 'SMux Provider:')===false and strpos($err[0][2], 'Session Provider:')===false)) { + echo "Error: Wrong error message.\n"; + print_r($err); + } } else { @@ -188,7 +193,12 @@ $stmt8 = sqlsrv_query( $conn, "SELECT * FROM $tableName2" ); if( $stmt8 === false ) { echo "Error in statement 8.\n"; - print_r( sqlsrv_errors() ); + $err = sqlsrv_errors(); + if (strpos($err[0][0], 'IMSSP')===false or + strpos($err[0][2], 'The connection cannot process this operation because there is a statement with pending results')===false) { + echo "Error: Wrong error message.\n"; + print_r($err); + } } else { @@ -199,7 +209,7 @@ sqlsrv_close( $conn ); sqlsrv_close( $conn_break ); ?> ---EXPECTREGEX-- +--EXPECT-- Statement 1 successful. 16 rows in result set. Statement 2 successful. @@ -211,53 +221,5 @@ Statement 4 successful. Statement 5 successful. rows in result set. Error in statement 6. -Array -\( - \[0\] => Array - \( - \[0\] => 08S01 - \[SQLSTATE\] => 08S01 - \[1\] => 10054 - \[code\] => 10054 - \[2\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]TCP Provider: An existing connection was forcibly closed by the remote host. - - \[message\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]TCP Provider: An existing connection was forcibly closed by the remote host. - - \) - - \[1\] => Array - \( - \[0\] => 08S01 - \[SQLSTATE\] => 08S01 - \[1\] => 10054 - \[code\] => 10054 - \[2\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Communication link failure - \[message\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Communication link failure - \) - -\) Statement 7 successful. Error in statement 8. -Array -\( - \[0\] => Array - \( - \[0\] => IMSSP - \[SQLSTATE\] => IMSSP - \[1\] => -44 - \[code\] => -44 - \[2\] => The connection cannot process this operation because there is a statement with pending results. To make the connection available for other queries, either fetch all results or cancel or free the statement. For more information, see the product documentation about the MultipleActiveResultSets connection option. - \[message\] => The connection cannot process this operation because there is a statement with pending results. To make the connection available for other queries, either fetch all results or cancel or free the statement. For more information, see the product documentation about the MultipleActiveResultSets connection option. - \) - - \[1\] => Array - \( - \[0\] => HY000 - \[SQLSTATE\] => HY000 - \[1\] => 0 - \[code\] => 0 - \[2\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Connection is busy with results for another command - \[message\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Connection is busy with results for another command - \) - -\) diff --git a/test/functional/sqlsrv/connection_resiliency_keywords.phpt b/test/functional/sqlsrv/connection_resiliency_keywords.phpt index 0211b47c1..7dd50fb57 100644 --- a/test/functional/sqlsrv/connection_resiliency_keywords.phpt +++ b/test/functional/sqlsrv/connection_resiliency_keywords.phpt @@ -3,8 +3,7 @@ Test the connection resiliency keywords --DESCRIPTION-- Test the connection resiliency keywords ConnectRetryCount and ConnectRetryInterval and their ranges of acceptable values --SKIPIF-- - + --FILE-- 08001 \[1\] => 0 \[code\] => 0 - \[2\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Invalid value specified for connection string attribute 'ConnectRetryCount' - \[message\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Invalid value specified for connection string attribute 'ConnectRetryCount' + \[2\] => (\[unixODBC\]|)\[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Invalid value specified for connection string attribute 'ConnectRetryCount' + \[message\] => (\[unixODBC\]|)\[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Invalid value specified for connection string attribute 'ConnectRetryCount' \) \) @@ -90,8 +89,8 @@ Array \[SQLSTATE\] => 08001 \[1\] => 0 \[code\] => 0 - \[2\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Invalid value specified for connection string attribute 'ConnectRetryInterval' - \[message\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Invalid value specified for connection string attribute 'ConnectRetryInterval' + \[2\] => (\[unixODBC\]|)\[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Invalid value specified for connection string attribute 'ConnectRetryInterval' + \[message\] => (\[unixODBC\]|)\[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Invalid value specified for connection string attribute 'ConnectRetryInterval' \) \) @@ -104,8 +103,8 @@ Array \[SQLSTATE\] => 08001 \[1\] => 0 \[code\] => 0 - \[2\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Invalid value specified for connection string attribute 'ConnectRetryCount' - \[message\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Invalid value specified for connection string attribute 'ConnectRetryCount' + \[2\] => (\[unixODBC\]|)\[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Invalid value specified for connection string attribute 'ConnectRetryCount' + \[message\] => (\[unixODBC\]|)\[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Invalid value specified for connection string attribute 'ConnectRetryCount' \) \) diff --git a/test/functional/sqlsrv/connection_resiliency_prepare_transact.phpt b/test/functional/sqlsrv/connection_resiliency_prepare_transact.phpt index 3d713c2ee..c42a4e447 100644 --- a/test/functional/sqlsrv/connection_resiliency_prepare_transact.phpt +++ b/test/functional/sqlsrv/connection_resiliency_prepare_transact.phpt @@ -167,42 +167,22 @@ else else { echo "Statement not valid and rollback failed.\n"; - print_r( sqlsrv_errors() ); + $err = sqlsrv_errors(); + if (strpos($err[0][0], '08S02')===false or + (strpos($err[0][2], 'TCP Provider:')===false and strpos($err[0][2], 'SMux Provider:')===false and strpos($err[0][2], 'Session Provider:')===false)) { + echo "Error: Wrong error message.\n"; + print_r($err); + } } } sqlsrv_close( $conn ); sqlsrv_close( $conn_break ); ?> ---EXPECTREGEX-- +--EXPECT-- Statement 1 prepared. Statement 1 executed. Transaction begun. Transaction was committed. Transaction begun. Statement not valid and rollback failed. -Array -\( - \[0\] => Array - \( - \[0\] => 08S02 - \[SQLSTATE\] => 08S02 - \[1\] => 10054 - \[code\] => 10054 - \[2\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]TCP Provider: An existing connection was forcibly closed by the remote host. - - \[message\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]TCP Provider: An existing connection was forcibly closed by the remote host. - - \) - - \[1\] => Array - \( - \[0\] => 08S02 - \[SQLSTATE\] => 08S02 - \[1\] => 10054 - \[code\] => 10054 - \[2\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Unable to open a logical session - \[message\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Unable to open a logical session - \) - -\) diff --git a/test/functional/sqlsrv/connection_resiliency_timeouts.phpt b/test/functional/sqlsrv/connection_resiliency_timeouts.phpt index 06a8d28f3..1abfdd309 100644 --- a/test/functional/sqlsrv/connection_resiliency_timeouts.phpt +++ b/test/functional/sqlsrv/connection_resiliency_timeouts.phpt @@ -33,7 +33,12 @@ $stmt1 = sqlsrv_query( $conn, "SELECT * FROM $tableName1" ); if( $stmt1 === false ) { echo "Error in statement 1.\n"; - print_r( sqlsrv_errors() ); + $err = sqlsrv_errors(); + if (strpos($err[0][0], '08S01')===false or + (strpos($err[0][2], 'TCP Provider:')===false and strpos($err[0][2], 'SMux Provider:')===false and strpos($err[0][2], 'Session Provider:')===false)) { + echo "Error: Wrong error message.\n"; + print_r($err); + } } else { @@ -78,29 +83,4 @@ DropTables( $server, $uid, $pwd, $tableName1, $tableName2 ) ?> --EXPECTREGEX-- Error in statement 1. -Array -\( - \[0\] => Array - \( - \[0\] => 08S01 - \[SQLSTATE\] => 08S01 - \[1\] => 10054 - \[code\] => 10054 - \[2\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]TCP Provider: An existing connection was forcibly closed by the remote host. - - \[message\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]TCP Provider: An existing connection was forcibly closed by the remote host. - - \) - - \[1\] => Array - \( - \[0\] => 08S01 - \[SQLSTATE\] => 08S01 - \[1\] => 10054 - \[code\] => 10054 - \[2\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Communication link failure - \[message\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Communication link failure - \) - -\) Statement 2 successful. diff --git a/test/functional/sqlsrv/skipif_not_akv.inc b/test/functional/sqlsrv/skipif_not_akv.inc new file mode 100644 index 000000000..9746db712 --- /dev/null +++ b/test/functional/sqlsrv/skipif_not_akv.inc @@ -0,0 +1,21 @@ + \ No newline at end of file diff --git a/test/functional/sqlsrv/skipif_protocol_not_tcp.inc b/test/functional/sqlsrv/skipif_protocol_not_tcp.inc index 4dc4921e7..26d960ca3 100644 --- a/test/functional/sqlsrv/skipif_protocol_not_tcp.inc +++ b/test/functional/sqlsrv/skipif_protocol_not_tcp.inc @@ -1,6 +1,4 @@ $userName, "PWD"=>$userPassword ); @@ -14,17 +18,30 @@ if ($conn === false) { die( "skip Could not connect during SKIPIF." ); } -// Get SQL Server version -$stmt = sqlsrv_query( $conn, "SELECT @@VERSION" ); -if (sqlsrv_fetch($stmt)) { - $ver_string = sqlsrv_get_field( $stmt, 0 ); -} else { - die("skip Could not fetch SQL Server version."); +$msodbcsql_ver = sqlsrv_client_info($conn)["DriverVer"]; +$msodbcsql_maj = explode(".", $msodbcsql_ver)[0]; +$msodbcsql_min = explode(".", $msodbcsql_ver)[1]; + +if (!$is_win) { + if ($msodbcsql_maj < 17 or $msodbcsql_min < 2) { + die("skip Unsupported ODBC driver version"); + } } -$version = explode(' ', $ver_string); +// Get SQL Server version +// Exclude this check if running on Azure +if (!$daasMode) { + $stmt = sqlsrv_query( $conn, "SELECT @@VERSION" ); + if (sqlsrv_fetch($stmt)) { + $ver_string = sqlsrv_get_field( $stmt, 0 ); + } else { + die("skip Could not fetch SQL Server version."); + } + + $version = explode(' ', $ver_string); -if ($version[3] < '2014') { - die("skip Wrong version of SQL Server, 2014 or later required"); + if ($version[3] < '2014') { + die("skip Wrong version of SQL Server, 2014 or later required"); + } } ?> diff --git a/test/functional/sqlsrv/skipif_version_less_than_2k16.inc b/test/functional/sqlsrv/skipif_version_less_than_2k16.inc index 692523d66..ce06258a2 100644 --- a/test/functional/sqlsrv/skipif_version_less_than_2k16.inc +++ b/test/functional/sqlsrv/skipif_version_less_than_2k16.inc @@ -1,10 +1,14 @@ $userName, "PWD"=>$userPassword ); @@ -14,17 +18,29 @@ if ($conn === false) { die( "skip Could not connect during SKIPIF." ); } -// Get SQL Server version -$stmt = sqlsrv_query( $conn, "SELECT @@VERSION" ); -if (sqlsrv_fetch($stmt)) { - $ver_string = sqlsrv_get_field( $stmt, 0 ); -} else { - die("skip Could not fetch SQL Server version."); +$msodbcsql_ver = sqlsrv_client_info($conn)["DriverVer"]; +$msodbcsql_maj = explode(".", $msodbcsql_ver)[0]; + +if (!$is_win) { + if ($msodbcsql_maj < 17) { + die("skip Unsupported ODBC driver version"); + } } -$version = explode(' ', $ver_string); +// Get SQL Server version +// Exclude this check if running on Azure +if (!$daasMode) { + $stmt = sqlsrv_query( $conn, "SELECT @@VERSION" ); + if (sqlsrv_fetch($stmt)) { + $ver_string = sqlsrv_get_field( $stmt, 0 ); + } else { + die("skip Could not fetch SQL Server version."); + } + + $version = explode(' ', $ver_string); -if ($version[3] < '2016') { - die("skip Wrong version of SQL Server, 2016 or later required"); + if ($version[3] < '2016') { + die("skip Wrong version of SQL Server, 2016 or later required"); + } } ?> diff --git a/test/functional/sqlsrv/sqlsrv_ConnPool_Unix.phpt b/test/functional/sqlsrv/sqlsrv_ConnPool_Unix.phpt index 57aafff60..bd00ac689 100644 --- a/test/functional/sqlsrv/sqlsrv_ConnPool_Unix.phpt +++ b/test/functional/sqlsrv/sqlsrv_ConnPool_Unix.phpt @@ -6,6 +6,15 @@ This test assumes the default odbcinst.ini has not been modified. --FILE-- + --FILE-- + --FILE-- + --FILE-- --FILE-- s; - - if ($diff == 0) { - $value = $valueAE; - } + + $dataArray = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_NUMERIC); + for ($i = 0; $i < sizeof($SQLSRV_PHPTYPE_CONST); ++$i) { + if (!sqlsrv_execute($stmt)) { + fatalError("Execute failed for $SQLSRV_PHPTYPE_CONST[$i]\n"); + } + + if ($result = sqlsrv_fetch($stmt)) { + for ($j = 0; $j < $numFields; $j++) { + $value = sqlsrv_get_field($stmt, $j, $SQLSRV_PHPTYPE_CONST[$i]); + $valueFromArray = $dataArray[$j]; + + // PHPTYPE_STREAM returns a PHP resource, so check the type + if (is_resource($value)) { + $value = get_resource_type($value); } - - if ($valueAE != $value or $valueFromArrayAE != $valueFromArray) { - echo "Values do not match! PHPType $i Field $j\n"; - print_r($valueAE);echo "\n"; - print_r($value);echo "\n"; - print_r($valueFromArrayAE);echo "\n"; - print_r($valueFromArray);echo "\n"; - print_r(sqlsrv_errors()); - fatalError("Test failed, values do not match.\n"); + + // For each type, the AE values come first and non-AE values second + // So let's do the comparison every second field + if ($j%2 == 0) { + $valueAE = $value; + $valueFromArrayAE = $valueFromArray; + } elseif ($j%2 == 1) { + // If returning a DateTime PHP type from a date only SQL type, + // PHP adds the current timestamp to make a DateTime object, + // and in this case the AE and non-AE times may be off by a + // fraction of a second since they are retrieved at ever-so-slightly + // different times. This not a test-failing discrepancy, so + // below the DateTime objects are made equal again for the next if + // block. + if ($value instanceof DateTime) { + // date_diff returns a DateInterval object, and s is + // the difference in seconds. s should be zero because + // the difference should be just a fraction of a second. + $datediff = date_diff($value, $valueAE); + $diff = $datediff->s; + + if ($diff == 0) { + $value = $valueAE; + } + } + + if ($valueAE != $value or $valueFromArrayAE != $valueFromArray) { + $index = floor($j / 2); + echo "Values do not match! PHPType $i Field $dataTypes[$index]\n"; + print_r($valueAE); + echo "\n--------\n\n"; + print_r($value); + echo "\n--------\n\n"; + print_r($valueFromArrayAE); + echo "\n--------\n\n"; + print_r($valueFromArray); + echo "\n--------\n\n"; + print_r(sqlsrv_errors()); + echo("Test failed, values do not match.\n"); + } } } } - ++$i; } - + sqlsrv_free_stmt($stmt); sqlsrv_free_stmt($stmt2); - - $deleteQuery = "DELETE FROM $tableName"; + + $deleteQuery = "TRUNCATE TABLE $tableName"; $stmt = sqlsrv_query($conn, $deleteQuery); if ($stmt == false) { print_r(sqlsrv_errors()); - fatalError("Delete statement failed"); + fatalError("Truncate statement failed"); } - + sqlsrv_free_stmt($stmt); } diff --git a/test/functional/sqlsrv/sqlsrv_connect_encrypted.phpt b/test/functional/sqlsrv/sqlsrv_connect_encrypted.phpt index 5a39140e1..e6a5bbb6d 100644 --- a/test/functional/sqlsrv/sqlsrv_connect_encrypted.phpt +++ b/test/functional/sqlsrv/sqlsrv_connect_encrypted.phpt @@ -1,7 +1,7 @@ --TEST-- Test new connection keyword ColumnEncryption --SKIPIF-- - + --FILE-- --FILE-- @@ -13,23 +17,34 @@ $conn = connect(); if (AE\IsQualified($conn)) { $query = "SELECT name FROM sys.column_master_keys"; $stmt = sqlsrv_query($conn, $query); - sqlsrv_fetch($stmt); - $master_key_name = sqlsrv_get_field($stmt, 0); + $found = false; + while (sqlsrv_fetch($stmt)) { + $master_key_name = sqlsrv_get_field($stmt, 0); + if ($master_key_name == 'AEMasterKey') { + $found = true; + } + } + // $master_key_name = sqlsrv_get_field($stmt, 0); + if (!$found) { + die("Windows Column Master Key not created.\n"); + } $query = "SELECT name FROM sys.column_encryption_keys"; $stmt = sqlsrv_query($conn, $query); - sqlsrv_fetch($stmt); - $encryption_key_name = sqlsrv_get_field($stmt, 0); - - if ($master_key_name == 'AEMasterKey' && $encryption_key_name == 'AEColumnKey') { - echo "Test Successfully done.\n"; - } else { - echo "Column Master Key and Column Encryption Key not created.\n"; + $found = false; + while (sqlsrv_fetch($stmt)) { + $encryption_key_name = sqlsrv_get_field($stmt, 0); + if ($encryption_key_name == 'AEColumnKey') { + $found = true; + } + } + if (!$found) { + die("Windows Column Encryption Key not created.\n"); } sqlsrv_free_stmt($stmt); -} else { - echo "Test Successfully done.\n"; } + +echo "Test Successfully done.\n"; sqlsrv_close($conn); ?> --EXPECT-- From b47cec284bf5a99a023e299067f10687922b7655 Mon Sep 17 00:00:00 2001 From: Jenny Tam Date: Mon, 24 Sep 2018 13:26:43 -0700 Subject: [PATCH 02/10] Dev to Master - 5.4.0-preview (#853) * Fixed the potential error reported by Prefast code analysis * Use SQLSRV_ASSERT for checking NULL ptrs * For these AKV tests check env despite not AE connected * Added the driver option to run functional tests * Fixed connection pooling tests for more than one ODBC drivers * added driver option to pdo isPooled.php * Removed win32 ifdefs re connection resiliency (#802) * Set the driver argument for getDSN to null by default (#798) * Added the driver argument to getDSN * Dropped the driver argument but set to null as default * Removed the AE condition in locale support * Modified the AE condition for locale support * Changed int to SQLLEN to avoid infinite loop (#806) * Version 5.3.0 (#803) * Version 5.3.0 * Fixed the wrong replacements * Added comments block to m4 files * Use dnl for comments * Modified AE fetch phptypes test to insert only one row at a time and loop through php types (#801) * Modified AE fetch phptypes test to insert only one row at a time and loop through php types * Fixed formatting * Streamlined two very similar large column name tests (#807) * Streamlined two very similar large column name tests * Changed the EOL * Updates to change log and readme (#811) * Updates to change log and readme * Dropped support for Ubuntu 17 * Modified as per review comments * Fixed connection resiliency tests for Unix, updated AppVeyor for ODBC 17.2 * Fixed expected output * Fixed output and skipifs * Fixed skipifs and output * Fixed driver name * Updated installation instructions and sample script (#813) * Updated instructions and sample test for 5.3.0 RTW * Fixed sample code to adhere to php coding standard * Fixed cases and spaces * Modified NOTE for UB 18.04 based on review comments * Added 'exit' * Modified change log and readme based on review to PR 811 * Applied review comments * build output to debug appveyor failure * removed debug output * Streamlined two very similar large column name tests (#815) * Streamlined two very similar large column name tests * Added random number of test table names to avoid operand clash issues * Replaced to with for based on review * Changelog updated * changelog updated, test skipif changed to run on unix platforms * Fixed skipif typo * Fixed typo in skipif for pdo * Fixed some output for Travis * Moved error checking inside pdo connres tests * Added links back to changelog * Fixed output for sqlsrv connres tests * Fixed output * Fixed output again * Fixed skipifs for connres * Tweaked per review comments * Changes made to source and tests to support PHP 7.3 (#822) * Changes made to support php 7.3 * Correct use of the smart pointer * Fixed the tests for 7.3 * Some clean up for array_init() * Fixed formattings and clean up * One more fix * Initialising strings with nulls * Removed some spaces * Made array index spacing consistent * Fix for compilation problem * Fix for compilation problem again * Before freeing stmt in destructor check if dbh driver data is NULL (#829) * Issue 434 - set dbh driver data to NULL as well in destructor * Reverted the last change but instead check if dbh driver_data is already freed * Modified the comment * Added driver to the skipif conditions (#831) * Used git clone instead to download source from a branch of a tag (#832) * Modified the error handling to make it more flexible (#833) * Made error handling more flexible * Fixed a minor issue with a test * Enabled Spectre Mitigations (#836) * Incorporated changes in PR 634 to pdo_sqlsrv (#834) * Incorporated changes in PR 634 to pdo_sqlsrv * Reverted the changes because the array is for internal use only * Modified README re user's suggestion (#841) * Modified README re user's suggestion * Moved the if condition to the end as per review * Adding supporting for Azure AD access token (#837) * Adding supporting for Azure AD access token * Added more comments for the AD access token skipif files * Save the pointer to access token struct until after connecting * Clear the access token data before freeing the memory * Added a reference as per review * Feature request - new PDO_STMT_OPTION_FETCHES_DATETIME_TYPE flag for pdo_sqlsrv to return datetime as objects (#842) * Feature request - issue 648 * Fixed constructor for field_cache and added another test * Added tests for FETCH_BOUND * Added a new test for output param * Modified output param test to set attributes differently * Removed a useless helped function in a test * Combined two new tests into one as per review * Uncommented dropTable * Feature request - add ReturnDatesAsStrings option to statement level for sqlsrv (#844) * Added ReturnDatesAsStrings option to the statement level * Added new tests for ReturnDatesAsStrings at statement level * Added more datetime types as per review * Updated version 5.4.0-preview (#846) * Updated version 5.4.0-preview * Replaced 5.3 with 5.4 * Fixed sqlsrv datetime tests to connect with ColumnEncryption variables (#849) * Change log for 5.4.0-preview (#850) * Updated change log for 5.4.0-preview * Updated 5.4.0 preview to add two new feature requests * Modified change log as per review * Modified the wordings * Updated readme, changelog, and install instructions --- CHANGELOG.md | 35 +++ Linux-mac-install.md | 4 +- README.md | 32 +-- buildscripts/builddrivers.py | 4 +- buildscripts/buildtools.py | 37 +-- source/pdo_sqlsrv/config.m4 | 2 +- source/pdo_sqlsrv/config.w32 | 5 +- source/pdo_sqlsrv/pdo_dbh.cpp | 102 +++++--- source/pdo_sqlsrv/pdo_init.cpp | 9 +- source/pdo_sqlsrv/pdo_parser.cpp | 50 ++-- source/pdo_sqlsrv/pdo_stmt.cpp | 165 +++++++----- source/pdo_sqlsrv/pdo_util.cpp | 15 +- source/pdo_sqlsrv/php_pdo_sqlsrv.h | 13 +- source/pdo_sqlsrv/template.rc | 2 +- source/shared/FormattedPrint.cpp | 12 +- source/shared/FormattedPrint.h | 2 +- source/shared/StringFunctions.cpp | 2 +- source/shared/StringFunctions.h | 2 +- source/shared/core_conn.cpp | 147 ++++++++--- source/shared/core_init.cpp | 2 +- source/shared/core_results.cpp | 164 ++++++------ source/shared/core_sqlsrv.h | 60 +++-- source/shared/core_stmt.cpp | 47 ++-- source/shared/core_stream.cpp | 4 +- source/shared/core_util.cpp | 46 +++- source/shared/globalization.h | 4 +- source/shared/interlockedatomic.h | 2 +- source/shared/interlockedatomic_gcc.h | 2 +- source/shared/interlockedslist.h | 2 +- source/shared/localization.hpp | 2 +- source/shared/localizationimpl.cpp | 2 +- source/shared/msodbcsql.h | 9 +- source/shared/sal_def.h | 2 +- source/shared/typedefs_for_linux.h | 2 +- source/shared/version.h | 6 +- source/shared/xplat.h | 2 +- source/shared/xplat_intsafe.h | 2 +- source/shared/xplat_winerror.h | 2 +- source/shared/xplat_winnls.h | 2 +- source/sqlsrv/config.m4 | 2 +- source/sqlsrv/config.w32 | 5 +- source/sqlsrv/conn.cpp | 45 ++-- source/sqlsrv/init.cpp | 8 +- source/sqlsrv/php_sqlsrv.h | 2 +- source/sqlsrv/stmt.cpp | 35 ++- source/sqlsrv/template.rc | 2 +- source/sqlsrv/util.cpp | 65 +++-- test/functional/pdo_sqlsrv/access_token.inc | 3 + .../pdo_sqlsrv/pdo_azure_ad_access_token.phpt | 157 ++++++++++++ .../pdo_fetch_datetime_as_output_param.phpt | 87 +++++++ .../pdo_fetch_datetime_time_as_objects.phpt | 238 ++++++++++++++++++ .../pdo_fetch_datetime_time_nulls.phpt | 163 ++++++++++++ .../skipif_azure_ad_acess_token.inc | 41 +++ .../skipif_version_less_than_2k14.inc | 18 +- .../skipif_version_less_than_2k16.inc | 6 +- test/functional/sqlsrv/access_token.inc | 3 + .../sqlsrv/skipif_azure_ad_acess_token.inc | 45 ++++ .../sqlsrv/skipif_version_less_than_2k14.inc | 20 +- .../sqlsrv/skipif_version_less_than_2k16.inc | 6 +- .../sqlsrv_ae_type_conversion_select.phpt | 10 +- .../sqlsrv/sqlsrv_azure_ad_access_token.phpt | 131 ++++++++++ test/functional/sqlsrv/sqlsrv_errors.phpt | 6 +- .../sqlsrv_statement_datetimes_as_nulls.phpt | 120 +++++++++ ...sqlsrv_statement_datetimes_as_strings.phpt | 202 +++++++++++++++ ...lsrv_statement_datetimes_output_param.phpt | 113 +++++++++ test/functional/sqlsrv/test_conn_execute.phpt | 48 ++-- .../sqlsrv/test_non_alpha_password.phpt | 122 ++++----- 67 files changed, 2164 insertions(+), 543 deletions(-) create mode 100644 test/functional/pdo_sqlsrv/access_token.inc create mode 100644 test/functional/pdo_sqlsrv/pdo_azure_ad_access_token.phpt create mode 100644 test/functional/pdo_sqlsrv/pdo_fetch_datetime_as_output_param.phpt create mode 100644 test/functional/pdo_sqlsrv/pdo_fetch_datetime_time_as_objects.phpt create mode 100644 test/functional/pdo_sqlsrv/pdo_fetch_datetime_time_nulls.phpt create mode 100644 test/functional/pdo_sqlsrv/skipif_azure_ad_acess_token.inc create mode 100644 test/functional/sqlsrv/access_token.inc create mode 100644 test/functional/sqlsrv/skipif_azure_ad_acess_token.inc create mode 100644 test/functional/sqlsrv/sqlsrv_azure_ad_access_token.phpt create mode 100644 test/functional/sqlsrv/sqlsrv_statement_datetimes_as_nulls.phpt create mode 100644 test/functional/sqlsrv/sqlsrv_statement_datetimes_as_strings.phpt create mode 100644 test/functional/sqlsrv/sqlsrv_statement_datetimes_output_param.phpt diff --git a/CHANGELOG.md b/CHANGELOG.md index abaa24db6..ecb2ee3f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,41 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) +## 5.4.0-preview - 2018-09-24 +Updated PECL release packages. Here is the list of updates: + +### Added +- Added support for PHP 7.3.0 RC 1 +- Added support for Azure AD Access Token (in Linux / macOS this requires [MS ODBC Driver 17+](https://docs.microsoft.com/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server) and [unixODBC](http://www.unixodbc.org/) 2.3.6+) +- Feature Request [#842](https://github.com/Microsoft/msphpsql/pull/842) - new PDO_STMT_OPTION_FETCHES_DATETIME_TYPE flag for pdo_sqlsrv to return datetime as objects +- Feature Request [#844](https://github.com/Microsoft/msphpsql/pull/844) - add ReturnDatesAsStrings option to statement level for sqlsrv +- Compatible with [ODBC Driver 17.3 CTP](https://blogs.msdn.microsoft.com/sqlnativeclient/2018/09/24/odbc-driver-17-3-preview-for-sql-server-released/) + +### Removed +- Dropped support for Ubuntu 17.10 +- Dropped support for PHP 7.0 - [Version 5.3](https://docs.microsoft.com/sql/connect/php/system-requirements-for-the-php-sql-driver?view=sql-server-2017) is the last to support PHP 7.0. + +### Fixed +- Issue [#434](https://github.com/Microsoft/msphpsql/issues/434) - To avoid the pitfall that could result in a crash, before freeing stmt in the destructor check if its dbh driver data is NULL +- Pull Request [#836](https://github.com/Microsoft/msphpsql/pull/836) - Modified the config files to enable Spectre Mitigations (use /Qspectre switch) for PHP 7.2 +- Pull Request [#833](https://github.com/Microsoft/msphpsql/pull/833) - Streamlined the error handling to remove a potential cause of crash + +### Limitations +- No support for inout / output params when using sql_variant type +- In Linux and macOS, setlocale() only takes effect if it is invoked before the first connection. Attempting to set the locale after connecting will not work +- Always Encrypted requires [MS ODBC Driver 17+](https://docs.microsoft.com/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server) + - Only Windows Certificate Store and Azure Key Vault are supported. Custom Keystores are not yet supported + - Issue [#716](https://github.com/Microsoft/msphpsql/issues/716) - With Always Encrypted enabled, named parameters in subqueries are not supported + - [Always Encrypted limitations](https://docs.microsoft.com/sql/connect/php/using-always-encrypted-php-drivers#limitations-of-the-php-drivers-when-using-always-encrypted) + +### Known Issues +- Connection pooling on Linux or macOS is not recommended with [unixODBC](http://www.unixodbc.org/) < 2.3.7 +- When pooling is enabled in Linux or macOS + - unixODBC <= 2.3.4 (Linux and macOS) might not return proper diagnostic information, such as error messages, warnings and informative messages + - due to this unixODBC bug, fetch large data (such as xml, binary) as streams as a workaround. See the examples [here](https://github.com/Microsoft/msphpsql/wiki/Features#pooling) +- With ColumnEncryption enabled, calling stored procedures with XML parameters does not work (Issue [#674](https://github.com/Microsoft/msphpsql/issues/674)) +- With ColumnEncryption enabled, fetching varbinary(max), varchar(max) or nvarchar(max) may fail with [ODBC Driver 17.3 CTP](https://blogs.msdn.microsoft.com/sqlnativeclient/2018/09/24/odbc-driver-17-3-preview-for-sql-server-released/) + ## 5.3.0 - 2018-07-20 Updated PECL release packages. Here is the list of updates: diff --git a/Linux-mac-install.md b/Linux-mac-install.md index d84eca655..970bc3d00 100644 --- a/Linux-mac-install.md +++ b/Linux-mac-install.md @@ -5,13 +5,13 @@ These instructions install PHP 7.2 by default -- see the notes at the beginning ## Contents of this page: -- [Installing the drivers on Ubuntu 16.04, 17.10, and 18.04](#installing-the-drivers-on-ubuntu-1604-1710-and-1804) +- [Installing the drivers on Ubuntu 16.04 and 18.04](#installing-the-drivers-on-ubuntu-1604-and-1804) - [Installing the drivers on Red Hat 7](#installing-the-drivers-on-red-hat-7) - [Installing the drivers on Debian 8 and 9](#installing-the-drivers-on-debian-8-and-9) - [Installing the drivers on Suse 12](#installing-the-drivers-on-suse-12) - [Installing the drivers on macOS El Capitan, Sierra and High Sierra](#installing-the-drivers-on-macos-el-capitan-sierra-and-high-sierra) -## Installing the drivers on Ubuntu 16.04, 17.10 and 18.04 +## Installing the drivers on Ubuntu 16.04 and 18.04 > [!NOTE] > To install PHP 7.0 or 7.1, replace 7.2 with 7.0 or 7.1 in the following commands. diff --git a/README.md b/README.md index 20e3c0e98..071d582f0 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,9 @@ **Welcome to the Microsoft Drivers for PHP for Microsoft SQL Server** -The Microsoft Drivers for PHP for Microsoft SQL Server are PHP extensions that allow for the reading and writing of SQL Server data from within PHP scripts. The SQLSRV extension provides a procedural interface while the PDO_SQLSRV extension implements PHP Data Objects (PDO) for accessing data in all editions of SQL Server 2008 R2 and later (including Azure SQL DB). These drivers rely on the [Microsoft ODBC Driver for SQL Server](https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-2017) to handle the low-level communication with SQL Server. +The Microsoft Drivers for PHP for Microsoft SQL Server are PHP extensions that allow for the reading and writing of SQL Server data from within PHP scripts. The SQLSRV extension provides a procedural interface while the PDO_SQLSRV extension implements PHP Data Objects (PDO) for accessing data in all editions of SQL Server 2008 R2 and later (including Azure SQL DB). These drivers rely on the [Microsoft ODBC Driver for SQL Server](https://docs.microsoft.com/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-2017) to handle the low-level communication with SQL Server. -This release contains the SQLSRV and PDO_SQLSRV drivers for PHP 7.* with improvements on both drivers and some limitations (see Limitations below for details). Upcoming releases will contain additional functionalities, bug fixes, and more. +This release contains the SQLSRV and PDO_SQLSRV drivers for PHP 7.1+ with improvements on both drivers and some [limitations](https://github.com/Microsoft/msphpsql/releases). Upcoming releases will contain additional functionalities, bug fixes, and more. ## Take our survey @@ -28,11 +28,11 @@ Thank you for taking the time to participate in our last survey. You can continu ## Get Started -* [**Windows + SQL Server + PHP 7**](https://www.microsoft.com/en-us/sql-server/developer-get-started/php/windows) -* [**Ubuntu + SQL Server + PHP 7**](https://www.microsoft.com/en-us/sql-server/developer-get-started/php/ubuntu) -* [**RedHat + SQL Server + PHP 7**](https://www.microsoft.com/en-us/sql-server/developer-get-started/php/rhel) -* [**SUSE + SQL Server + PHP 7**](https://www.microsoft.com/en-us/sql-server/developer-get-started/php/sles) -* [**macOS + SQL Server + PHP 7**](https://www.microsoft.com/en-us/sql-server/developer-get-started/php/mac/) +* [**Windows + SQL Server + PHP 7**](https://www.microsoft.com/sql-server/developer-get-started/php/windows) +* [**Ubuntu + SQL Server + PHP 7**](https://www.microsoft.com/sql-server/developer-get-started/php/ubuntu) +* [**RedHat + SQL Server + PHP 7**](https://www.microsoft.com/sql-server/developer-get-started/php/rhel) +* [**SUSE + SQL Server + PHP 7**](https://www.microsoft.com/sql-server/developer-get-started/php/sles) +* [**macOS + SQL Server + PHP 7**](https://www.microsoft.com/sql-server/developer-get-started/php/mac/) * [**Docker**](https://hub.docker.com/r/lbosqmsft/mssql-php-msphpsql/) @@ -42,12 +42,12 @@ Thank you for taking the time to participate in our last survey. You can continu ## Prerequisites -For full details on the system requirements for the drivers, see the [system requirements](https://docs.microsoft.com/en-us/sql/connect/php/system-requirements-for-the-php-sql-driver) on Microsoft Docs. +For full details on the system requirements for the drivers, see the [system requirements](https://docs.microsoft.com/sql/connect/php/system-requirements-for-the-php-sql-driver) on Microsoft Docs. On the client machine: -- PHP 7.0.x, 7.1.x, or 7.2.x (7.2.0 and up on Unix, 7.2.1 and up on Windows) -- A Web server such as Internet Information Services (IIS) is required. Your Web server must be configured to run PHP -- [Microsoft ODBC Driver 17, Microsoft ODBC Driver 13, or Microsoft ODBC Driver 11](https://docs.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-2017) +- PHP 7.1.x, or 7.2.x (7.2.0 and up on Unix, 7.2.1 and up on Windows) +- [Microsoft ODBC Driver 17, Microsoft ODBC Driver 13, or Microsoft ODBC Driver 11](https://docs.microsoft.com/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-2017) +- If using a Web server such as Internet Information Services (IIS) or Apache, it must be configured to run PHP On the server side, Microsoft SQL Server 2008 R2 and above on Windows are supported, as are Microsoft SQL Server 2016 and above on Linux. @@ -57,16 +57,16 @@ The drivers are distributed as pre-compiled extensions for PHP found on the [rel If you choose to build the drivers, you must be able to build PHP 7 without including these extensions. For help building PHP on Windows, see the [official PHP website][phpbuild]. For details on compiling the drivers, see the [documentation](https://github.com/Microsoft/msphpsql/tree/dev/buildscripts#windows) -- an example buildscript is provided, but you can also compile the drivers manually. -To load the drivers, make sure that the driver is in your PHP extension directory and enable it in your PHP installation's php.ini file by adding `extension=php_sqlsrv.dll` and/or `extension=php_pdo_sqlsrv.dll` to it. If necessary, specify the extension directory using `extension_dir`, for example: `extension_dir = "C:\PHP\ext"`. Note that the precompiled binaries have different names -- substitute accordingly in php.ini. For more details on loading the drivers, see [Loading the PHP SQL Driver](https://docs.microsoft.com/en-us/sql/connect/php/loading-the-php-sql-driver) on Microsoft Docs. +To load the drivers, make sure that the driver is in your PHP extension directory and enable it in your PHP installation's php.ini file by adding `extension=php_sqlsrv.dll` and/or `extension=php_pdo_sqlsrv.dll` to it. If necessary, specify the extension directory using `extension_dir`, for example: `extension_dir = "C:\PHP\ext"`. Note that the precompiled binaries have different names -- substitute accordingly in php.ini. For more details on loading the drivers, see [Loading the PHP SQL Driver](https://docs.microsoft.com/sql/connect/php/loading-the-php-sql-driver) on Microsoft Docs. -Finally, restart the Web server. +Finally, if running PHP in a Web server, restart the Web server. ## Install (UNIX) -For full instructions on installing the drivers on all supported Unix platforms, see [the installation instructions on Microsoft Docs](https://docs.microsoft.com/en-us/sql/connect/php/installation-tutorial-linux-mac). +For full instructions on installing the drivers on all supported Unix platforms, see [the installation instructions on Microsoft Docs](https://docs.microsoft.com/sql/connect/php/installation-tutorial-linux-mac). ## Sample Code -For PHP code samples, please see the [sample](https://github.com/Microsoft/msphpsql/tree/master/sample) folder or the [code samples on Microsoft Docs](https://docs.microsoft.com/en-us/sql/connect/php/code-samples-for-php-sql-driver). +For PHP code samples, please see the [sample](https://github.com/Microsoft/msphpsql/tree/master/sample) folder or the [code samples on Microsoft Docs](https://docs.microsoft.com/sql/connect/php/code-samples-for-php-sql-driver). ## Limitations and Known Issues Please refer to [Releases](https://github.com/Microsoft/msphpsql/releases) for the latest limitations and known issues. @@ -138,6 +138,6 @@ This project has adopted the Microsoft Open Source Code of Conduct. For more inf [phpbuild]: https://wiki.php.net/internals/windows/stepbystepbuild -[phpdoc]: https://docs.microsoft.com/en-us/sql/connect/php/microsoft-php-driver-for-sql-server?view=sql-server-2017 +[phpdoc]: https://docs.microsoft.com/sql/connect/php/microsoft-php-driver-for-sql-server?view=sql-server-2017 [PHPMan]: http://php.net/manual/install.unix.php diff --git a/buildscripts/builddrivers.py b/buildscripts/builddrivers.py index 4378ad1f1..e9ac02dcd 100644 --- a/buildscripts/builddrivers.py +++ b/buildscripts/builddrivers.py @@ -239,7 +239,7 @@ def validate_input(question, values): parser.add_argument('--DRIVER', default='all', choices=['all', 'sqlsrv', 'pdo_sqlsrv'], help="driver to build (default: all)") parser.add_argument('--DEBUG', action='store_true', help="enable debug mode (default: False)") parser.add_argument('--REPO', default='Microsoft', help="GitHub repository (default: Microsoft)") - parser.add_argument('--BRANCH', default='dev', help="GitHub repository branch (default: dev)") + parser.add_argument('--BRANCH', default='dev', help="GitHub repository branch or tag (default: dev)") parser.add_argument('--SOURCE', default=None, help="a local path to source file (default: None)") parser.add_argument('--TESTING', action='store_true', help="turns on testing mode (default: False)") parser.add_argument('--DESTPATH', default=None, help="an alternative destination for the drivers (default: None)") @@ -280,7 +280,7 @@ def validate_input(question, values): answer = input("Download source from a GitHub repo? [y/n]: ") if answer == 'yes' or answer == 'y' or answer == '': repo = input("Name of the repo (hit enter for 'Microsoft'): ") - branch = input("Name of the branch (hit enter for 'dev'): ") + branch = input("Name of the branch or tag (hit enter for 'dev'): ") if repo == '': repo = 'Microsoft' if branch == '': diff --git a/buildscripts/buildtools.py b/buildscripts/buildtools.py index 306aafaa7..79b36923a 100644 --- a/buildscripts/buildtools.py +++ b/buildscripts/buildtools.py @@ -193,7 +193,7 @@ def write_lines_to_copy_source(driver, file): file.write('@CALL ROBOCOPY ' + source + ' ' + dest + ' /s /xx /xo' + os.linesep) @staticmethod - def download_msphpsql_source(repo, branch, dest_folder = 'Source', clean_up = True): + def download_msphpsql_source(repo, branch, dest_folder = 'Source'): """Download to *dest_folder* the msphpsql archive of the specified GitHub *repo* and *branch*. The downloaded files will be removed by default. """ @@ -201,40 +201,25 @@ def download_msphpsql_source(repo, branch, dest_folder = 'Source', clean_up = Tr work_dir = os.path.dirname(os.path.realpath(__file__)) temppath = os.path.join(work_dir, 'temp') - if os.path.exists(temppath): - shutil.rmtree(temppath) - os.makedirs(temppath) + # There is no need to remove tree - + # for Bamboo, it will be cleaned up eventually + # for local development, this can act as a cached copy of the repo + if not os.path.exists(temppath): + os.makedirs(temppath) os.chdir(temppath) - file = branch + '.zip' - url = 'https://github.com/' + repo + '/msphpsql/archive/' + branch + '.zip' - - print('Downloading ' + url + ' ...') - try: - with urllib.request.urlopen(url) as response, open(file, 'wb') as out_file: - shutil.copyfileobj(response, out_file) - except: - print ("Resort to skip ssl verification...") - # need to skip ssl verification on some agents - # see https://www.python.org/dev/peps/pep-0476/ - with urllib.request.urlopen(url, context=ssl._create_unverified_context()) as response, open(file, 'wb') as out_file: - shutil.copyfileobj(response, out_file) - - print('Extracting ' + file + ' ...') - zip = zipfile.ZipFile(file) - zip.extractall() - zip.close() - msphpsqlFolder = os.path.join(temppath, 'msphpsql-' + branch) + + url = 'https://github.com/' + repo + '/msphpsql.git' + command = 'git clone ' + url + ' -b ' + branch + ' --single-branch --depth 1 ' + msphpsqlFolder + os.system(command) + source = os.path.join(msphpsqlFolder, 'source') os.chdir(work_dir) os.system('ROBOCOPY ' + source + '\shared ' + dest_folder + '\shared /xx /xo') os.system('ROBOCOPY ' + source + '\pdo_sqlsrv ' + dest_folder + '\pdo_sqlsrv /xx /xo') os.system('ROBOCOPY ' + source + '\sqlsrv ' + dest_folder + '\sqlsrv /xx /xo') - - if clean_up: - shutil.rmtree(temppath) except: print('Error occurred when downloading source') diff --git a/source/pdo_sqlsrv/config.m4 b/source/pdo_sqlsrv/config.m4 index b1bfd6e48..3de4fefc5 100644 --- a/source/pdo_sqlsrv/config.m4 +++ b/source/pdo_sqlsrv/config.m4 @@ -4,7 +4,7 @@ dnl dnl Contents: the code that will go into the configure script, indicating options, dnl external libraries and includes, and what source files are to be compiled. dnl -dnl Microsoft Drivers 5.3 for PHP for SQL Server +dnl Microsoft Drivers 5.4 for PHP for SQL Server dnl Copyright(c) Microsoft Corporation dnl All rights reserved. dnl MIT License diff --git a/source/pdo_sqlsrv/config.w32 b/source/pdo_sqlsrv/config.w32 index 7066e6254..cd6e3a063 100644 --- a/source/pdo_sqlsrv/config.w32 +++ b/source/pdo_sqlsrv/config.w32 @@ -3,7 +3,7 @@ // // Contents: JScript build configuration used by buildconf.bat // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -36,6 +36,9 @@ if( PHP_PDO_SQLSRV != "no" ) { ADD_FLAG( "CFLAGS_PDO_SQLSRV", "/Zi" ); if (PHP_DEBUG != "yes") ADD_FLAG( "CFLAGS_PDO_SQLSRV", "/guard:cf /O2" ); ADD_FLAG( "CFLAGS_PDO_SQLSRV", "/D ZEND_WIN32_FORCE_INLINE" ); + if (VCVERS >= 1913) { + ADD_FLAG("CFLAGS_PDO_SQLSRV", "/Qspectre"); + } ADD_EXTENSION_DEP('pdo_sqlsrv', 'pdo'); EXTENSION("pdo_sqlsrv", pdo_sqlsrv_src_class, PHP_PDO_SQLSRV_SHARED, "/DZEND_ENABLE_STATIC_TSRMLS_CACHE=1"); } else { diff --git a/source/pdo_sqlsrv/pdo_dbh.cpp b/source/pdo_sqlsrv/pdo_dbh.cpp index 330205565..b424866e4 100644 --- a/source/pdo_sqlsrv/pdo_dbh.cpp +++ b/source/pdo_sqlsrv/pdo_dbh.cpp @@ -3,7 +3,7 @@ // // Contents: Implements the PDO object for PDO_SQLSRV // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -38,6 +38,7 @@ namespace PDOConnOptionNames { const char Server[] = "Server"; const char APP[] = "APP"; +const char AccessToken[] = "AccessToken"; const char ApplicationIntent[] = "ApplicationIntent"; const char AttachDBFileName[] = "AttachDbFileName"; const char Authentication[] = "Authentication"; @@ -79,6 +80,7 @@ enum PDO_STMT_OPTIONS { PDO_STMT_OPTION_CLIENT_BUFFER_MAX_KB_SIZE, PDO_STMT_OPTION_EMULATE_PREPARES, PDO_STMT_OPTION_FETCHES_NUMERIC_TYPE, + PDO_STMT_OPTION_FETCHES_DATETIME_TYPE }; // List of all the statement options supported by this driver. @@ -92,6 +94,7 @@ const stmt_option PDO_STMT_OPTS[] = { { NULL, 0, PDO_STMT_OPTION_CLIENT_BUFFER_MAX_KB_SIZE, std::unique_ptr( new stmt_option_buffered_query_limit ) }, { NULL, 0, PDO_STMT_OPTION_EMULATE_PREPARES, std::unique_ptr( new stmt_option_emulate_prepares ) }, { NULL, 0, PDO_STMT_OPTION_FETCHES_NUMERIC_TYPE, std::unique_ptr( new stmt_option_fetch_numeric ) }, + { NULL, 0, PDO_STMT_OPTION_FETCHES_DATETIME_TYPE, std::unique_ptr( new stmt_option_fetch_datetime ) }, { NULL, 0, SQLSRV_STMT_OPTION_INVALID, std::unique_ptr{} }, }; @@ -185,6 +188,15 @@ const connection_option PDO_CONN_OPTS[] = { CONN_ATTR_STRING, conn_str_append_func::func }, + { + PDOConnOptionNames::AccessToken, + sizeof( PDOConnOptionNames::AccessToken ), + SQLSRV_CONN_OPTION_ACCESS_TOKEN, + ODBCConnOptions::AccessToken, + sizeof( ODBCConnOptions::AccessToken), + CONN_ATTR_STRING, + access_token_set_func::func + }, { PDOConnOptionNames::ApplicationIntent, sizeof( PDOConnOptionNames::ApplicationIntent ), @@ -464,6 +476,7 @@ struct pdo_dbh_methods pdo_sqlsrv_dbh_methods = { driver_dbh->set_func( __FUNCTION__ ); \ int length = strlen( __FUNCTION__ ) + strlen( ": entering" ); \ char func[length+1]; \ + memset(func, '\0', length+1); \ strcpy_s( func, sizeof( __FUNCTION__ ), __FUNCTION__ ); \ strcat_s( func, length+1, ": entering" ); \ LOG( SEV_NOTICE, func ); \ @@ -484,7 +497,8 @@ pdo_sqlsrv_dbh::pdo_sqlsrv_dbh( _In_ SQLHANDLE h, _In_ error_callback e, _In_ vo direct_query( false ), query_timeout( QUERY_TIMEOUT_INVALID ), client_buffer_max_size( PDO_SQLSRV_G( client_buffer_max_size )), - fetch_numeric( false ) + fetch_numeric( false ), + fetch_datetime( false ) { if( client_buffer_max_size < 0 ) { client_buffer_max_size = sqlsrv_buffered_result_set::BUFFERED_QUERY_LIMIT_DEFAULT; @@ -546,7 +560,7 @@ int pdo_sqlsrv_db_handle_factory( _Inout_ pdo_dbh_t *dbh, _In_opt_ zval *driver_ ALLOC_HASHTABLE( pdo_conn_options_ht ); core::sqlsrv_zend_hash_init( *g_pdo_henv_cp, pdo_conn_options_ht, 10 /* # of buckets */, - ZVAL_INTERNAL_DTOR, 0 /*persistent*/ TSRMLS_CC ); + ZVAL_PTR_DTOR, 0 /*persistent*/ TSRMLS_CC ); // Either of g_pdo_henv_cp or g_pdo_henv_ncp can be used to propogate the error. dsn_parser = new ( sqlsrv_malloc( sizeof( conn_string_parser ))) conn_string_parser( *g_pdo_henv_cp, dbh->data_source, @@ -1050,6 +1064,10 @@ int pdo_sqlsrv_dbh_set_attr( _Inout_ pdo_dbh_t *dbh, _In_ zend_long attr, _Inout driver_dbh->fetch_numeric = (zend_is_true(val)) ? true : false; break; + case SQLSRV_ATTR_FETCHES_DATETIME_TYPE: + driver_dbh->fetch_datetime = (zend_is_true(val)) ? true : false; + break; + // Not supported case PDO_ATTR_FETCH_TABLE_NAMES: case PDO_ATTR_FETCH_CATALOG_NAMES: @@ -1201,6 +1219,12 @@ int pdo_sqlsrv_dbh_get_attr( _Inout_ pdo_dbh_t *dbh, _In_ zend_long attr, _Inout break; } + case SQLSRV_ATTR_FETCHES_DATETIME_TYPE: + { + ZVAL_BOOL( return_value, driver_dbh->fetch_datetime ); + break; + } + default: { THROW_PDO_ERROR( driver_dbh, PDO_SQLSRV_ERROR_INVALID_DBH_ATTR ); @@ -1270,7 +1294,7 @@ char * pdo_sqlsrv_dbh_last_id( _Inout_ pdo_dbh_t *dbh, _In_z_ const char *name, try { - char last_insert_id_query[ LAST_INSERT_ID_QUERY_MAX_LEN ] = {'\0'}; + char last_insert_id_query[LAST_INSERT_ID_QUERY_MAX_LEN] = {'\0'}; if( name == NULL ) { strcpy_s( last_insert_id_query, sizeof( last_insert_id_query ), LAST_INSERT_ID_QUERY ); } @@ -1379,11 +1403,15 @@ int pdo_sqlsrv_dbh_quote( _Inout_ pdo_dbh_t* dbh, _In_reads_(unquoted_len) const } // only change the encoding if quote is called from the statement level (which should only be called when a statement // is prepared with emulate prepared on) - if ( is_statement ) { - pdo_stmt_t *stmt = Z_PDO_STMT_P( object ); + if (is_statement) { + pdo_stmt_t *stmt = Z_PDO_STMT_P(object); + SQLSRV_ASSERT(stmt != NULL, "pdo_sqlsrv_dbh_quote: stmt object was null"); // set the encoding to be the encoding of the statement otherwise set to be the encoding of the dbh - pdo_sqlsrv_stmt* driver_stmt = reinterpret_cast( stmt->driver_data ); - if ( driver_stmt->encoding() != SQLSRV_ENCODING_INVALID ) { + + pdo_sqlsrv_stmt* driver_stmt = reinterpret_cast(stmt->driver_data); + SQLSRV_ASSERT(driver_stmt != NULL, "pdo_sqlsrv_dbh_quote: driver_data object was null"); + + if (driver_stmt->encoding() != SQLSRV_ENCODING_INVALID) { encoding = driver_stmt->encoding(); } else { @@ -1391,18 +1419,20 @@ int pdo_sqlsrv_dbh_quote( _Inout_ pdo_dbh_t* dbh, _In_reads_(unquoted_len) const encoding = driver_dbh->encoding(); } // get the placeholder at the current position in driver_stmt->placeholders ht + // Normally it's not a good idea to alter the internal pointer in a hashed array + // (see pull request 634 on GitHub) but in this case this is for internal use only zval* placeholder = NULL; - if (( placeholder = zend_hash_get_current_data( driver_stmt->placeholders )) != NULL && zend_hash_move_forward( driver_stmt->placeholders ) == SUCCESS && stmt->bound_params != NULL ) { + if ((placeholder = zend_hash_get_current_data(driver_stmt->placeholders)) != NULL && zend_hash_move_forward(driver_stmt->placeholders) == SUCCESS && stmt->bound_params != NULL) { pdo_bound_param_data* param = NULL; - if ( Z_TYPE_P( placeholder ) == IS_STRING ) { - param = reinterpret_cast( zend_hash_find_ptr( stmt->bound_params, Z_STR_P( placeholder ))); + if (Z_TYPE_P(placeholder) == IS_STRING) { + param = reinterpret_cast(zend_hash_find_ptr(stmt->bound_params, Z_STR_P(placeholder))); } - else if ( Z_TYPE_P( placeholder ) == IS_LONG) { - param = reinterpret_cast( zend_hash_index_find_ptr( stmt->bound_params, Z_LVAL_P( placeholder ))); + else if (Z_TYPE_P(placeholder) == IS_LONG) { + param = reinterpret_cast(zend_hash_index_find_ptr(stmt->bound_params, Z_LVAL_P(placeholder))); } - if ( NULL != param ) { - SQLSRV_ENCODING param_encoding = static_cast( Z_LVAL( param->driver_params )); - if ( param_encoding != SQLSRV_ENCODING_INVALID ) { + if (NULL != param) { + SQLSRV_ENCODING param_encoding = static_cast(Z_LVAL(param->driver_params)); + if (param_encoding != SQLSRV_ENCODING_INVALID) { encoding = param_encoding; } } @@ -1412,13 +1442,13 @@ int pdo_sqlsrv_dbh_quote( _Inout_ pdo_dbh_t* dbh, _In_reads_(unquoted_len) const if ( encoding == SQLSRV_ENCODING_BINARY ) { // convert from char* to hex digits using os std::basic_ostringstream os; - for ( size_t index = 0; index < unquoted_len && unquoted[ index ] != '\0'; ++index ) { + for ( size_t index = 0; index < unquoted_len && unquoted[index] != '\0'; ++index ) { // if unquoted is < 0 or > 255, that means this is a non-ascii character. Translation from non-ascii to binary is not supported. // return an empty terminated string for now - if (( int )unquoted[ index ] < 0 || ( int )unquoted[ index ] > 255) { + if (( int )unquoted[index] < 0 || ( int )unquoted[index] > 255) { *quoted_len = 0; *quoted = reinterpret_cast( sqlsrv_malloc( *quoted_len, sizeof( char ), 1 )); - ( *quoted )[ 0 ] = '\0'; + ( *quoted )[0] = '\0'; return 1; } // when an int is < 16 and is appended to os, its hex representation which starts @@ -1427,7 +1457,7 @@ int pdo_sqlsrv_dbh_quote( _Inout_ pdo_dbh_t* dbh, _In_reads_(unquoted_len) const if (( int )unquoted[index] < 16 ) { os << '0'; } - os << std::hex << ( int )unquoted[ index ]; + os << std::hex << ( int )unquoted[index]; } std::basic_string str_hex = os.str(); // each character is represented by 2 digits of hex @@ -1439,13 +1469,13 @@ int pdo_sqlsrv_dbh_quote( _Inout_ pdo_dbh_t* dbh, _In_reads_(unquoted_len) const *quoted = reinterpret_cast( sqlsrv_malloc( *quoted_len, sizeof( char ), 1 )); unsigned int out_current = 0; // insert '0x' - ( *quoted )[ out_current++ ] = '0'; - ( *quoted )[ out_current++ ] = 'x'; - for ( size_t index = 0; index < unquoted_str_len && unquoted_str[ index ] != '\0'; ++index ) { - ( *quoted )[ out_current++ ] = unquoted_str[ index ]; + ( *quoted )[out_current++] = '0'; + ( *quoted )[out_current++] = 'x'; + for ( size_t index = 0; index < unquoted_str_len && unquoted_str[index] != '\0'; ++index ) { + ( *quoted )[out_current++] = unquoted_str[index]; } // null terminator - ( *quoted )[ out_current ] = '\0'; + ( *quoted )[out_current] = '\0'; sqlsrv_free( unquoted_str ); return 1; } @@ -1457,7 +1487,7 @@ int pdo_sqlsrv_dbh_quote( _Inout_ pdo_dbh_t* dbh, _In_reads_(unquoted_len) const quotes_needed = 3; } for ( size_t index = 0; index < unquoted_len; ++index ) { - if ( unquoted[ index ] == '\'' ) { + if ( unquoted[index] == '\'' ) { ++quotes_needed; } } @@ -1468,24 +1498,24 @@ int pdo_sqlsrv_dbh_quote( _Inout_ pdo_dbh_t* dbh, _In_reads_(unquoted_len) const // insert N if the encoding is UTF8 if ( encoding == SQLSRV_ENCODING_UTF8 ) { - ( *quoted )[ out_current++ ] = 'N'; + ( *quoted )[out_current++] = 'N'; } // insert initial quote - ( *quoted )[ out_current++ ] = '\''; + ( *quoted )[out_current++] = '\''; for ( size_t index = 0; index < unquoted_len; ++index ) { - if ( unquoted[ index ] == '\'' ) { - ( *quoted )[ out_current++ ] = '\''; - ( *quoted )[ out_current++ ] = '\''; + if ( unquoted[index] == '\'' ) { + ( *quoted )[out_current++] = '\''; + ( *quoted )[out_current++] = '\''; } else { - ( *quoted )[ out_current++ ] = unquoted[ index ]; + ( *quoted )[out_current++] = unquoted[index]; } } // trailing quote and null terminator - ( *quoted )[ out_current++ ] = '\''; - ( *quoted )[ out_current ] = '\0'; + ( *quoted )[out_current++] = '\''; + ( *quoted )[out_current] = '\0'; return 1; } @@ -1552,6 +1582,10 @@ void add_stmt_option_key( _Inout_ sqlsrv_context& ctx, _In_ size_t key, _Inout_ option_key = PDO_STMT_OPTION_FETCHES_NUMERIC_TYPE; break; + case SQLSRV_ATTR_FETCHES_DATETIME_TYPE: + option_key = PDO_STMT_OPTION_FETCHES_DATETIME_TYPE; + break; + default: CHECK_CUSTOM_ERROR( true, ctx, PDO_SQLSRV_ERROR_INVALID_STMT_OPTION ) { throw core::CoreException(); diff --git a/source/pdo_sqlsrv/pdo_init.cpp b/source/pdo_sqlsrv/pdo_init.cpp index 65e7a0786..a5fcbdd0c 100644 --- a/source/pdo_sqlsrv/pdo_init.cpp +++ b/source/pdo_sqlsrv/pdo_init.cpp @@ -3,7 +3,7 @@ // // Contents: initialization routines for PDO_SQLSRV // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -132,10 +132,10 @@ PHP_MINIT_FUNCTION(pdo_sqlsrv) g_pdo_errors_ht = reinterpret_cast( pemalloc( sizeof( HashTable ), 1 )); ::zend_hash_init( g_pdo_errors_ht, 50, NULL, pdo_error_dtor /*pDestructor*/, 1 ); - for( int i = 0; PDO_ERRORS[ i ].error_code != -1; ++i ) { + for( int i = 0; PDO_ERRORS[i].error_code != -1; ++i ) { - void* zr = ::zend_hash_index_update_mem( g_pdo_errors_ht, PDO_ERRORS[ i ].error_code, - &( PDO_ERRORS[ i ].sqlsrv_error ), sizeof( PDO_ERRORS[ i ].sqlsrv_error ) ); + void* zr = ::zend_hash_index_update_mem( g_pdo_errors_ht, PDO_ERRORS[i].error_code, + &( PDO_ERRORS[i].sqlsrv_error ), sizeof( PDO_ERRORS[i].sqlsrv_error ) ); if( zr == NULL ) { LOG( SEV_ERROR, "Failed to insert data into PDO errors hashtable." ); @@ -285,6 +285,7 @@ namespace { { "SQLSRV_ATTR_CURSOR_SCROLL_TYPE" , SQLSRV_ATTR_CURSOR_SCROLL_TYPE }, { "SQLSRV_ATTR_CLIENT_BUFFER_MAX_KB_SIZE", SQLSRV_ATTR_CLIENT_BUFFER_MAX_KB_SIZE }, { "SQLSRV_ATTR_FETCHES_NUMERIC_TYPE", SQLSRV_ATTR_FETCHES_NUMERIC_TYPE }, + { "SQLSRV_ATTR_FETCHES_DATETIME_TYPE", SQLSRV_ATTR_FETCHES_DATETIME_TYPE }, // used for the size for output parameters: PDO::PARAM_INT and PDO::PARAM_BOOL use the default size of int, // PDO::PARAM_STR uses the size of the string in the variable diff --git a/source/pdo_sqlsrv/pdo_parser.cpp b/source/pdo_sqlsrv/pdo_parser.cpp index baafeed73..e6a70d4d7 100644 --- a/source/pdo_sqlsrv/pdo_parser.cpp +++ b/source/pdo_sqlsrv/pdo_parser.cpp @@ -5,7 +5,7 @@ // // Copyright Microsoft Corporation // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -108,7 +108,7 @@ bool string_parser::discard_white_spaces() return false; } - while( this->is_white_space( this->orig_str[ pos ] )) { + while( this->is_white_space( this->orig_str[pos] )) { if( !next() ) return false; @@ -148,13 +148,13 @@ void conn_string_parser::validate_key( _In_reads_(key_len) const char *key, _Ino { int new_len = discard_trailing_white_spaces( key, key_len ); - for( int i=0; PDO_CONN_OPTS[ i ].conn_option_key != SQLSRV_CONN_OPTION_INVALID; ++i ) + for( int i=0; PDO_CONN_OPTS[i].conn_option_key != SQLSRV_CONN_OPTION_INVALID; ++i ) { // discard the null terminator. - if( new_len == ( PDO_CONN_OPTS[ i ].sqlsrv_len - 1 ) && !strncasecmp( key, PDO_CONN_OPTS[ i ].sqlsrv_name, new_len )) { + if( new_len == ( PDO_CONN_OPTS[i].sqlsrv_len - 1 ) && !strncasecmp( key, PDO_CONN_OPTS[i].sqlsrv_name, new_len )) { - this->current_key = PDO_CONN_OPTS[ i ].conn_option_key; - this->current_key_name = PDO_CONN_OPTS[ i ].sqlsrv_name; + this->current_key = PDO_CONN_OPTS[i].conn_option_key; + this->current_key_name = PDO_CONN_OPTS[i].sqlsrv_name; return; } } @@ -164,7 +164,7 @@ void conn_string_parser::validate_key( _In_reads_(key_len) const char *key, _Ino key_name = static_cast( sqlsrv_malloc( new_len + 1 )); memcpy_s( key_name, new_len + 1 ,key, new_len ); - key_name[ new_len ] = '\0'; + key_name[new_len] = '\0'; THROW_PDO_ERROR( this->ctx, PDO_SQLSRV_ERROR_INVALID_DSN_KEY, static_cast( key_name ) ); } @@ -232,7 +232,7 @@ void conn_string_parser:: parse_conn_string( TSRMLS_D ) start_pos = this->pos; // read the key name - while( this->orig_str[ pos ] != '=' ) { + while( this->orig_str[pos] != '=' ) { if( !next() ) { @@ -240,7 +240,7 @@ void conn_string_parser:: parse_conn_string( TSRMLS_D ) } } - this->validate_key( &( this->orig_str[ start_pos ] ), ( pos - start_pos ) TSRMLS_CC ); + this->validate_key( &( this->orig_str[start_pos] ), ( pos - start_pos ) TSRMLS_CC ); state = Value; @@ -249,13 +249,13 @@ void conn_string_parser:: parse_conn_string( TSRMLS_D ) case Value: { - SQLSRV_ASSERT(( this->orig_str[ pos ] == '=' ), "conn_string_parser:: parse_conn_string: " + SQLSRV_ASSERT(( this->orig_str[pos] == '=' ), "conn_string_parser:: parse_conn_string: " "Equal was expected" ); next(); // skip "=" // if EOS encountered after 0 or more spaces OR semi-colon encountered. - if( !discard_white_spaces() || this->orig_str[ pos ] == ';' ) { + if( !discard_white_spaces() || this->orig_str[pos] == ';' ) { add_key_value_pair( NULL, 0 TSRMLS_CC ); @@ -265,13 +265,13 @@ void conn_string_parser:: parse_conn_string( TSRMLS_D ) } else { - // this->orig_str[ pos ] == ';' + // this->orig_str[pos] == ';' state = NextKeyValuePair; } } // if LCB - else if( this->orig_str[ pos ] == '{' ) { + else if( this->orig_str[pos] == '{' ) { start_pos = this->pos; // starting character is LCB state = ValueContent1; @@ -289,7 +289,7 @@ void conn_string_parser:: parse_conn_string( TSRMLS_D ) case ValueContent1: { - while ( this->orig_str[ pos ] != '}' ) { + while ( this->orig_str[pos] != '}' ) { if ( ! next() ) { @@ -305,7 +305,7 @@ void conn_string_parser:: parse_conn_string( TSRMLS_D ) case ValueContent2: { - while( this->orig_str[ pos ] != ';' ) { + while( this->orig_str[pos] != ';' ) { if( ! next() ) { @@ -313,13 +313,13 @@ void conn_string_parser:: parse_conn_string( TSRMLS_D ) } } - if( !this->is_eos() && this->orig_str[ pos ] == ';' ) { + if( !this->is_eos() && this->orig_str[pos] == ';' ) { // semi-colon encountered, so go to next key-value pair state = NextKeyValuePair; } - add_key_value_pair( &( this->orig_str[ start_pos ] ), this->pos - start_pos TSRMLS_CC ); + add_key_value_pair( &( this->orig_str[start_pos] ), this->pos - start_pos TSRMLS_CC ); SQLSRV_ASSERT((( state == NextKeyValuePair ) || ( this->is_eos() )), "conn_string_parser::parse_conn_string: Invalid state encountered " ); @@ -334,14 +334,14 @@ void conn_string_parser:: parse_conn_string( TSRMLS_D ) if( !next() ) { // EOS - add_key_value_pair( &( this->orig_str[ start_pos ] ), this->pos - start_pos TSRMLS_CC ); + add_key_value_pair( &( this->orig_str[start_pos] ), this->pos - start_pos TSRMLS_CC ); break; } SQLSRV_ASSERT( !this->is_eos(), "conn_string_parser::parse_conn_string: Unexpected EOS encountered" ); // if second RCB encountered than go back to ValueContent1 - if( this->orig_str[ pos ] == '}' ) { + if( this->orig_str[pos] == '}' ) { if( !next() ) { @@ -356,20 +356,20 @@ void conn_string_parser:: parse_conn_string( TSRMLS_D ) int end_pos = this->pos; // discard any trailing white-spaces. - if( this->is_white_space( this->orig_str[ pos ] )) { + if( this->is_white_space( this->orig_str[pos] )) { if( ! this->discard_white_spaces() ) { //EOS - add_key_value_pair( &( this->orig_str[ start_pos ] ), end_pos - start_pos TSRMLS_CC ); + add_key_value_pair( &( this->orig_str[start_pos] ), end_pos - start_pos TSRMLS_CC ); break; } } // if semi-colon than go to next key-value pair - if ( this->orig_str[ pos ] == ';' ) { + if ( this->orig_str[pos] == ';' ) { - add_key_value_pair( &( this->orig_str[ start_pos ] ), end_pos - start_pos TSRMLS_CC ); + add_key_value_pair( &( this->orig_str[start_pos] ), end_pos - start_pos TSRMLS_CC ); state = NextKeyValuePair; break; } @@ -380,7 +380,7 @@ void conn_string_parser:: parse_conn_string( TSRMLS_D ) } case NextKeyValuePair: { - SQLSRV_ASSERT(( this->orig_str[ pos ] == ';' ), + SQLSRV_ASSERT(( this->orig_str[pos] == ';' ), "conn_string_parser::parse_conn_string: semi-colon was expected." ); // Call next() to skip the semi-colon. @@ -390,7 +390,7 @@ void conn_string_parser:: parse_conn_string( TSRMLS_D ) break; } - if( this->orig_str[ pos ] == ';' ) { + if( this->orig_str[pos] == ';' ) { // a second semi-colon is error case. THROW_PDO_ERROR( this->ctx, PDO_SQLSRV_ERROR_EXTRA_SEMI_COLON_IN_DSN_STRING, this->pos ); diff --git a/source/pdo_sqlsrv/pdo_stmt.cpp b/source/pdo_sqlsrv/pdo_stmt.cpp index d41dde3b7..3f6bc3283 100644 --- a/source/pdo_sqlsrv/pdo_stmt.cpp +++ b/source/pdo_sqlsrv/pdo_stmt.cpp @@ -3,7 +3,7 @@ // // Contents: Implements the PDOStatement object for the PDO_SQLSRV // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -51,6 +51,9 @@ inline SQLSMALLINT pdo_fetch_ori_to_odbc_fetch_ori ( _In_ enum pdo_fetch_orienta // for list of supported pdo types. SQLSRV_PHPTYPE pdo_type_to_sqlsrv_php_type( _Inout_ sqlsrv_stmt* driver_stmt, _In_ enum pdo_param_type pdo_type TSRMLS_DC ) { + pdo_sqlsrv_stmt *pdo_stmt = static_cast(driver_stmt); + SQLSRV_ASSERT(pdo_stmt != NULL, "pdo_type_to_sqlsrv_php_type: pdo_stmt object was null"); + switch( pdo_type ) { case PDO_PARAM_BOOL: @@ -64,9 +67,12 @@ SQLSRV_PHPTYPE pdo_type_to_sqlsrv_php_type( _Inout_ sqlsrv_stmt* driver_stmt, _I return SQLSRV_PHPTYPE_NULL; case PDO_PARAM_LOB: - // TODO: This will eventually be changed to SQLSRV_PHPTYPE_STREAM when output streaming is implemented. - return SQLSRV_PHPTYPE_STRING; - + if (pdo_stmt->fetch_datetime) { + return SQLSRV_PHPTYPE_DATETIME; + } else { + // TODO: This will eventually be changed to SQLSRV_PHPTYPE_STREAM when output streaming is implemented. + return SQLSRV_PHPTYPE_STRING; + } case PDO_PARAM_STMT: THROW_PDO_ERROR( driver_stmt, PDO_SQLSRV_ERROR_PDO_STMT_UNSUPPORTED ); break; @@ -213,61 +219,63 @@ void meta_data_free( _Inout_ field_meta_data* meta ) zval convert_to_zval( _In_ SQLSRV_PHPTYPE sqlsrv_php_type, _Inout_ void** in_val, _In_opt_ SQLLEN field_len ) { zval out_zval; - ZVAL_UNDEF( &out_zval ); + ZVAL_UNDEF(&out_zval); - switch( sqlsrv_php_type ) { - - case SQLSRV_PHPTYPE_INT: - case SQLSRV_PHPTYPE_FLOAT: - { - if( *in_val == NULL ) { - ZVAL_NULL( &out_zval ); - } - else { + switch (sqlsrv_php_type) { - if( sqlsrv_php_type == SQLSRV_PHPTYPE_INT ) { - ZVAL_LONG( &out_zval, **( reinterpret_cast( in_val ))); - } - else { - ZVAL_DOUBLE( &out_zval, **( reinterpret_cast( in_val ))); - } - } + case SQLSRV_PHPTYPE_INT: + case SQLSRV_PHPTYPE_FLOAT: + { + if (*in_val == NULL) { + ZVAL_NULL(&out_zval); + } + else { - if( *in_val ) { - sqlsrv_free( *in_val ); + if (sqlsrv_php_type == SQLSRV_PHPTYPE_INT) { + ZVAL_LONG(&out_zval, **(reinterpret_cast(in_val))); + } + else { + ZVAL_DOUBLE(&out_zval, **(reinterpret_cast(in_val))); } - - break; } - case SQLSRV_PHPTYPE_STRING: - case SQLSRV_PHPTYPE_STREAM: // TODO: this will be moved when output streaming is implemented - { + if (*in_val) { + sqlsrv_free(*in_val); + } - if( *in_val == NULL ) { + break; + } + case SQLSRV_PHPTYPE_STRING: + case SQLSRV_PHPTYPE_STREAM: // TODO: this will be moved when output streaming is implemented + { + if (*in_val == NULL) { - ZVAL_NULL( &out_zval ); - } - else { + ZVAL_NULL(&out_zval); + } + else { - ZVAL_STRINGL( &out_zval, reinterpret_cast( *in_val ), field_len ); - sqlsrv_free( *in_val ); - } - break; + ZVAL_STRINGL(&out_zval, reinterpret_cast(*in_val), field_len); + sqlsrv_free(*in_val); } - - case SQLSRV_PHPTYPE_DATETIME: - DIE( "Unsupported php type" ); - out_zval = *( reinterpret_cast( *in_val )); - break; + break; + } + case SQLSRV_PHPTYPE_DATETIME: + if (*in_val == NULL) { - case SQLSRV_PHPTYPE_NULL: - ZVAL_NULL( &out_zval ); - break; + ZVAL_NULL(&out_zval); + } + else { - default: - DIE( "Unknown php type" ); - break; + out_zval = *(reinterpret_cast(*in_val)); + sqlsrv_free(*in_val); + } + break; + case SQLSRV_PHPTYPE_NULL: + ZVAL_NULL(&out_zval); + break; + default: + DIE("Unknown php type"); + break; } return out_zval; @@ -339,6 +347,11 @@ void stmt_option_fetch_numeric:: operator()( _Inout_ sqlsrv_stmt* stmt, stmt_opt pdo_stmt->fetch_numeric = ( zend_is_true( value_z )) ? true : false; } +void stmt_option_fetch_datetime:: operator()( _Inout_ sqlsrv_stmt* stmt, stmt_option const* /*opt*/, _In_ zval* value_z TSRMLS_DC ) +{ + pdo_sqlsrv_stmt *pdo_stmt = static_cast( stmt ); + pdo_stmt->fetch_datetime = ( zend_is_true( value_z )) ? true : false; +} // log a function entry point #ifndef _WIN32 @@ -348,6 +361,7 @@ void stmt_option_fetch_numeric:: operator()( _Inout_ sqlsrv_stmt* stmt, stmt_opt driver_stmt->set_func( __FUNCTION__ ); \ int length = strlen( __FUNCTION__ ) + strlen( ": entering" ); \ char func[length+1]; \ + memset(func, '\0', length+1); \ strcpy_s( func, sizeof( __FUNCTION__ ), __FUNCTION__ ); \ strcat_s( func, length+1, ": entering" ); \ LOG( SEV_NOTICE, func ); \ @@ -495,8 +509,13 @@ int pdo_sqlsrv_stmt_dtor( _Inout_ pdo_stmt_t *stmt TSRMLS_DC ) LOG( SEV_NOTICE, "pdo_sqlsrv_stmt_dtor: entering" ); // if a PDO statement didn't complete preparation, its driver_data can be NULL - if( driver_stmt == NULL ) { + if (driver_stmt == NULL) { + return 1; + } + // occasionally stmt->dbh->driver_data is already freed and reset but its driver_data is not + if (stmt->dbh != NULL && stmt->dbh->driver_data == NULL) { + stmt->driver_data = NULL; return 1; } @@ -554,12 +573,15 @@ int pdo_sqlsrv_stmt_execute( _Inout_ pdo_stmt_t *stmt TSRMLS_DC ) // if the user is using prepare emulation (PDO::ATTR_EMULATE_PREPARES), set the query to the // subtituted query provided by PDO - if( stmt->supports_placeholders == PDO_PLACEHOLDER_NONE ) { + if (stmt->supports_placeholders == PDO_PLACEHOLDER_NONE) { // reset the placeholders hashtable internal in case the user reexecutes a statement + // Normally it's not a good idea to alter the internal pointer in a hashed array + // (see pull request 634 on GitHub) but in this case this is for internal use only + zend_hash_internal_pointer_reset(driver_stmt->placeholders); query = stmt->active_query_string; - query_len = static_cast( stmt->active_query_stringlen ); + query_len = static_cast(stmt->active_query_stringlen); } SQLRETURN execReturn = core_sqlsrv_execute( driver_stmt TSRMLS_CC, query, query_len ); @@ -651,13 +673,13 @@ int pdo_sqlsrv_stmt_fetch( _Inout_ pdo_stmt_t *stmt, _In_ enum pdo_fetch_orienta if (NULL== (bind_data = reinterpret_cast(zend_hash_index_find_ptr(stmt->bound_columns, i))) && (NULL == (bind_data = reinterpret_cast(zend_hash_find_ptr(stmt->bound_columns, stmt->columns[i].name))))) { - driver_stmt->bound_column_param_types[ i ] = PDO_PARAM_ZVAL; + driver_stmt->bound_column_param_types[i] = PDO_PARAM_ZVAL; continue; } if( bind_data->param_type != PDO_PARAM_ZVAL ) { - driver_stmt->bound_column_param_types[ i ] = bind_data->param_type; + driver_stmt->bound_column_param_types[i] = bind_data->param_type; bind_data->param_type = PDO_PARAM_ZVAL; } } @@ -744,10 +766,10 @@ int pdo_sqlsrv_stmt_get_col_data( _Inout_ pdo_stmt_t *stmt, _In_ int colno, // if a column is bound to a type different than the column type, figure out a way to convert it to the // type they want - if( stmt->bound_columns && driver_stmt->bound_column_param_types[ colno ] != PDO_PARAM_ZVAL ) { + if( stmt->bound_columns && driver_stmt->bound_column_param_types[colno] != PDO_PARAM_ZVAL ) { sqlsrv_php_type.typeinfo.type = pdo_type_to_sqlsrv_php_type( driver_stmt, - driver_stmt->bound_column_param_types[ colno ] + driver_stmt->bound_column_param_types[colno] TSRMLS_CC ); pdo_bound_param_data* bind_data = NULL; @@ -764,8 +786,8 @@ int pdo_sqlsrv_stmt_get_col_data( _Inout_ pdo_stmt_t *stmt, _In_ int colno, throw pdo::PDOException(); } - CHECK_CUSTOM_ERROR( driver_stmt->bound_column_param_types[ colno ] != PDO_PARAM_STR - && driver_stmt->bound_column_param_types[ colno ] != PDO_PARAM_LOB, driver_stmt, + CHECK_CUSTOM_ERROR( driver_stmt->bound_column_param_types[colno] != PDO_PARAM_STR + && driver_stmt->bound_column_param_types[colno] != PDO_PARAM_LOB, driver_stmt, PDO_SQLSRV_ERROR_COLUMN_TYPE_DOES_NOT_SUPPORT_ENCODING, colno + 1 ) { throw pdo::PDOException(); @@ -856,6 +878,10 @@ int pdo_sqlsrv_stmt_set_attr( _Inout_ pdo_stmt_t *stmt, _In_ zend_long attr, _In driver_stmt->fetch_numeric = ( zend_is_true( val )) ? true : false; break; + case SQLSRV_ATTR_FETCHES_DATETIME_TYPE: + driver_stmt->fetch_datetime = ( zend_is_true( val )) ? true : false; + break; + default: THROW_PDO_ERROR( driver_stmt, PDO_SQLSRV_ERROR_INVALID_STMT_ATTR ); break; @@ -937,6 +963,12 @@ int pdo_sqlsrv_stmt_get_attr( _Inout_ pdo_stmt_t *stmt, _In_ zend_long attr, _In break; } + case SQLSRV_ATTR_FETCHES_DATETIME_TYPE: + { + ZVAL_BOOL( return_value, driver_stmt->fetch_datetime ); + break; + } + default: THROW_PDO_ERROR( driver_stmt, PDO_SQLSRV_ERROR_INVALID_STMT_ATTR ); break; @@ -991,7 +1023,7 @@ int pdo_sqlsrv_stmt_get_col_meta( _Inout_ pdo_stmt_t *stmt, _In_ zend_long colno add_assoc_long( return_value, "flags", 0 ); // get the name of the data type - char field_type_name[ SQL_SERVER_IDENT_SIZE_MAX ]; + char field_type_name[SQL_SERVER_IDENT_SIZE_MAX] = {'\0'}; SQLSMALLINT out_buff_len; SQLLEN not_used; core::SQLColAttribute( driver_stmt, (SQLUSMALLINT) colno + 1, SQL_DESC_TYPE_NAME, field_type_name, @@ -1017,13 +1049,13 @@ int pdo_sqlsrv_stmt_get_col_meta( _Inout_ pdo_stmt_t *stmt, _In_ zend_long colno } // add the table name of the field. All the tests so far show this to always be "", but we adhere to the PDO spec - char table_name[ SQL_SERVER_IDENT_SIZE_MAX ]; + char table_name[SQL_SERVER_IDENT_SIZE_MAX] = {'\0'}; SQLLEN field_type_num; core::SQLColAttribute( driver_stmt, (SQLUSMALLINT) colno + 1, SQL_DESC_TABLE_NAME, table_name, SQL_SERVER_IDENT_SIZE_MAX, &out_buff_len, &field_type_num TSRMLS_CC ); add_assoc_string( return_value, "table", table_name ); - if( stmt->columns && stmt->columns[ colno ].param_type == PDO_PARAM_ZVAL ) { + if( stmt->columns && stmt->columns[colno].param_type == PDO_PARAM_ZVAL ) { add_assoc_long( return_value, "pdo_type", pdo_type ); } @@ -1356,6 +1388,17 @@ sqlsrv_phptype pdo_sqlsrv_stmt::sql_type_to_php_type( _In_ SQLINTEGER sql_type, sqlsrv_phptype.typeinfo.type = SQLSRV_PHPTYPE_STRING; } break; + case SQL_TYPE_DATE: + case SQL_SS_TIMESTAMPOFFSET: + case SQL_SS_TIME2: + case SQL_TYPE_TIMESTAMP: + if ( this->fetch_datetime ) { + sqlsrv_phptype.typeinfo.type = SQLSRV_PHPTYPE_DATETIME; + } + else { + sqlsrv_phptype.typeinfo.type = SQLSRV_PHPTYPE_STRING; + } + break; case SQL_BIGINT: case SQL_CHAR: case SQL_DECIMAL: @@ -1364,10 +1407,6 @@ sqlsrv_phptype pdo_sqlsrv_stmt::sql_type_to_php_type( _In_ SQLINTEGER sql_type, case SQL_WCHAR: case SQL_VARCHAR: case SQL_WVARCHAR: - case SQL_TYPE_DATE: - case SQL_SS_TIMESTAMPOFFSET: - case SQL_SS_TIME2: - case SQL_TYPE_TIMESTAMP: case SQL_LONGVARCHAR: case SQL_WLONGVARCHAR: case SQL_SS_XML: diff --git a/source/pdo_sqlsrv/pdo_util.cpp b/source/pdo_sqlsrv/pdo_util.cpp index a05e75471..dee2e3e06 100644 --- a/source/pdo_sqlsrv/pdo_util.cpp +++ b/source/pdo_sqlsrv/pdo_util.cpp @@ -3,7 +3,7 @@ // // Contents: Utility functions used by both connection or statement functions // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -37,7 +37,7 @@ const int WARNING_MIN_LENGTH = static_cast( strlen( WARNING_TEMPLATE // buffer used to hold a formatted log message prior to actually logging it. const int LOG_MSG_SIZE = 2048; -char log_msg[ LOG_MSG_SIZE ]; +char log_msg[LOG_MSG_SIZE] = {'\0'}; // internal error that says that FormatMessage failed SQLCHAR INTERNAL_FORMAT_ERROR[] = "An internal error occurred. FormatMessage failed writing an error message."; @@ -429,6 +429,15 @@ pdo_error PDO_ERRORS[] = { SQLSRV_ERROR_KEYSTORE_INVALID_VALUE, { IMSSP, (SQLCHAR*) "Invalid value for loading Azure Key Vault.", -89, false} }, + { + SQLSRV_ERROR_INVALID_OPTION_WITH_ACCESS_TOKEN, + { IMSSP, (SQLCHAR*) "When using Azure AD Access Token, the connection string must not contain UID, PWD, or Authentication keywords.", -90, false} + }, + { + SQLSRV_ERROR_EMPTY_ACCESS_TOKEN, + { IMSSP, (SQLCHAR*) "The Azure AD Access Token is empty. Expected a byte string.", -91, false} + }, + { UINT_MAX, {} } }; @@ -512,7 +521,7 @@ bool pdo_sqlsrv_handle_dbh_error( _Inout_ sqlsrv_context& ctx, _In_opt_ unsigned msg = static_cast( sqlsrv_malloc( msg_len ) ); core_sqlsrv_format_message( msg, static_cast( msg_len ), WARNING_TEMPLATE, error->sqlstate, error->native_code, error->native_message ); - php_error( E_WARNING, msg ); + php_error(E_WARNING, "%s", msg.get()); } ctx.set_last_error( error ); break; diff --git a/source/pdo_sqlsrv/php_pdo_sqlsrv.h b/source/pdo_sqlsrv/php_pdo_sqlsrv.h index 38e4cec42..c110a9c6e 100644 --- a/source/pdo_sqlsrv/php_pdo_sqlsrv.h +++ b/source/pdo_sqlsrv/php_pdo_sqlsrv.h @@ -6,7 +6,7 @@ // // Contents: Declarations for the extension // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -48,6 +48,7 @@ enum PDO_SQLSRV_ATTR { SQLSRV_ATTR_CURSOR_SCROLL_TYPE, SQLSRV_ATTR_CLIENT_BUFFER_MAX_KB_SIZE, SQLSRV_ATTR_FETCHES_NUMERIC_TYPE, + SQLSRV_ATTR_FETCHES_DATETIME_TYPE }; // valid set of values for TransactionIsolation connection option @@ -203,6 +204,7 @@ struct pdo_sqlsrv_dbh : public sqlsrv_conn { long query_timeout; zend_long client_buffer_max_size; bool fetch_numeric; + bool fetch_datetime; pdo_sqlsrv_dbh( _In_ SQLHANDLE h, _In_ error_callback e, _In_ void* driver TSRMLS_DC ); }; @@ -241,6 +243,10 @@ struct stmt_option_fetch_numeric : public stmt_option_functor { virtual void operator()( _Inout_ sqlsrv_stmt* stmt, stmt_option const* /*opt*/, _In_ zval* value_z TSRMLS_DC ); }; +struct stmt_option_fetch_datetime : public stmt_option_functor { + virtual void operator()( _Inout_ sqlsrv_stmt* stmt, stmt_option const* /*opt*/, _In_ zval* value_z TSRMLS_DC ); +}; + extern struct pdo_stmt_methods pdo_sqlsrv_stmt_methods; // a core layer pdo stmt object. This object inherits and overrides the callbacks necessary @@ -253,11 +259,13 @@ struct pdo_sqlsrv_stmt : public sqlsrv_stmt { direct_query_subst_string_len( 0 ), placeholders(NULL), bound_column_param_types( NULL ), - fetch_numeric( false ) + fetch_numeric( false ), + fetch_datetime( false ) { pdo_sqlsrv_dbh* db = static_cast( c ); direct_query = db->direct_query; fetch_numeric = db->fetch_numeric; + fetch_datetime = db->fetch_datetime; } virtual ~pdo_sqlsrv_stmt( void ); @@ -275,6 +283,7 @@ struct pdo_sqlsrv_stmt : public sqlsrv_stmt { std::vector > current_meta_data; pdo_param_type* bound_column_param_types; bool fetch_numeric; + bool fetch_datetime; }; diff --git a/source/pdo_sqlsrv/template.rc b/source/pdo_sqlsrv/template.rc index 8b94ddfad..435fa9a3b 100644 --- a/source/pdo_sqlsrv/template.rc +++ b/source/pdo_sqlsrv/template.rc @@ -3,7 +3,7 @@ // // Contents: Version resource // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/FormattedPrint.cpp b/source/shared/FormattedPrint.cpp index 1b48c0e92..a5033db49 100644 --- a/source/shared/FormattedPrint.cpp +++ b/source/shared/FormattedPrint.cpp @@ -6,7 +6,7 @@ // Contents: Contains functions for handling Windows format strings // and UTF-16 on non-Windows platforms // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -254,7 +254,7 @@ errno_t mplat_wctomb_s( void _CFLTCVT( double * dbl, char * buf, int bufSize, char fmt, int precision, int caps, _locale_t loc = NULL ) { const size_t local_bufsize = 8; - char local_fmt[local_bufsize]; + char local_fmt[local_bufsize] = {'\0'}; if ( 0 != caps ) { @@ -387,7 +387,7 @@ int FormattedPrintA( IFormattedPrintOutput * output, const char *format, v textlen is in multibyte or wide chars if _UNICODE */ union { char sz[BUFFERSIZE]; - } buffer; + } buffer = {'\0'}; WCHAR wchar; /* temp wchar_t */ int buffersize; /* size of text.sz (used only for the call to _cfltcvt) */ int bufferiswide=0; /* non-zero = buffer contains wide chars already */ @@ -905,7 +905,7 @@ int FormattedPrintA( IFormattedPrintOutput * output, const char *format, v WCHAR *p; int retval, count; errno_t e = 0; - char L_buffer[MB_LEN_MAX+1]; + char L_buffer[MB_LEN_MAX+1] = {'\0'}; p = text.wz; count = textlen; @@ -1221,7 +1221,7 @@ static DWORD FormatMessageToBufferA( const char * format, char * buffer, DWORD b DWORD bufsize = std::min(bufferWCharSize, (DWORD)64000); DWORD msg_pos = 0; const DWORD fmtsize = 32; - char fmt[fmtsize]; + char fmt[fmtsize] = {'\0'}; DWORD fmt_pos; char fmt_ch; @@ -1429,7 +1429,7 @@ DWORD FormatMessageA(DWORD dwFlags, LPCVOID lpSource, DWORD dwMessageId, DWORD d *((char**)lpBuffer) = NULL; const DWORD max_size = 64000; - char local_buf[max_size]; + char local_buf[max_size] = {'\0'}; chars_printed = FormatMessageToBufferA( reinterpret_cast(lpSource), local_buf, max_size, args ); if ( 0 < chars_printed ) { diff --git a/source/shared/FormattedPrint.h b/source/shared/FormattedPrint.h index 87f15f463..f7933f97f 100644 --- a/source/shared/FormattedPrint.h +++ b/source/shared/FormattedPrint.h @@ -4,7 +4,7 @@ // Contents: Contains functions for handling Windows format strings // and UTF-16 on non-Windows platforms // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/StringFunctions.cpp b/source/shared/StringFunctions.cpp index d5183fc52..354ebbf6c 100644 --- a/source/shared/StringFunctions.cpp +++ b/source/shared/StringFunctions.cpp @@ -3,7 +3,7 @@ // // Contents: Contains functions for handling UTF-16 on non-Windows platforms // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/StringFunctions.h b/source/shared/StringFunctions.h index b12e789b7..475cd84cf 100644 --- a/source/shared/StringFunctions.h +++ b/source/shared/StringFunctions.h @@ -3,7 +3,7 @@ // // Contents: Contains functions for handling UTF-16 on non-Windows platforms // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/core_conn.cpp b/source/shared/core_conn.cpp index b094e110b..da6284dc7 100644 --- a/source/shared/core_conn.cpp +++ b/source/shared/core_conn.cpp @@ -3,7 +3,7 @@ // // Contents: Core routines that use connection handles shared between sqlsrv and pdo_sqlsrv // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -120,11 +120,11 @@ sqlsrv_conn* core_sqlsrv_connect( _In_ sqlsrv_context& henv_cp, _In_ sqlsrv_cont // Instead, MSPHPSQL connection pooling is set according to the ODBCINST.INI file in [ODBC] section. #ifndef _WIN32 - char pooling_string[ 128 ] = {0}; + char pooling_string[128] = {'\0'}; SQLGetPrivateProfileString( "ODBC", "Pooling", "0", pooling_string, sizeof( pooling_string ), "ODBCINST.INI" ); - if ( pooling_string[ 0 ] == '1' || toupper( pooling_string[ 0 ] ) == 'Y' || - ( toupper( pooling_string[ 0 ] ) == 'O' && toupper( pooling_string[ 1 ] ) == 'N' )) + if ( pooling_string[0] == '1' || toupper( pooling_string[0] ) == 'Y' || + ( toupper( pooling_string[0] ) == 'O' && toupper( pooling_string[1] ) == 'N' )) { henv = &henv_cp; is_pooled = true; @@ -243,6 +243,12 @@ sqlsrv_conn* core_sqlsrv_connect( _In_ sqlsrv_context& henv_cp, _In_ sqlsrv_cont } // else driver_version not unknown #endif // !_WIN32 + // time to free the access token, if not null + if (conn->azure_ad_access_token != NULL) { + memset(conn->azure_ad_access_token->data, 0, conn->azure_ad_access_token->dataSize); // clear the memory + conn->azure_ad_access_token.reset(); + } + CHECK_SQL_ERROR( r, conn ) { throw core::CoreException(); } @@ -310,7 +316,7 @@ bool core_compare_error_state( _In_ sqlsrv_conn* conn, _In_ SQLRETURN rc, _In_ if( SQL_SUCCEEDED( rc ) ) return false; - SQLCHAR state[ SQL_SQLSTATE_BUFSIZE ] = { 0 }; + SQLCHAR state[SQL_SQLSTATE_BUFSIZE] = {'\0'}; SQLSMALLINT len; SQLRETURN sr = SQLGetDiagField( SQL_HANDLE_DBC, conn->handle(), 1, SQL_DIAG_SQLSTATE, state, SQL_SQLSTATE_BUFSIZE, &len ); @@ -327,7 +333,7 @@ bool core_compare_error_state( _In_ sqlsrv_conn* conn, _In_ SQLRETURN rc, _In_ bool core_search_odbc_driver_unix( _In_ DRIVER_VERSION driver_version ) { #ifndef _WIN32 - char szBuf[DEFAULT_CONN_STR_LEN+1]; // use a large enough buffer size + char szBuf[DEFAULT_CONN_STR_LEN+1] = {'\0'}; // use a large enough buffer size WORD cbBufMax = DEFAULT_CONN_STR_LEN; WORD cbBufOut; char *pszBuf = szBuf; @@ -695,7 +701,7 @@ bool core_is_conn_opt_value_escaped( _Inout_ const char* value, _Inout_ size_t v { // if the value is already quoted, then only analyse the part inside the quotes and return it as // unquoted since we quote it when adding it to the connection string. - if( value_len > 0 && value[0] == '{' && value[ value_len - 1 ] == '}' ) { + if( value_len > 0 && value[0] == '{' && value[value_len - 1] == '}' ) { ++value; value_len -= 2; } @@ -736,11 +742,11 @@ namespace { connection_option const* get_connection_option( sqlsrv_conn* conn, _In_ SQLULEN key, _In_ const connection_option conn_opts[] TSRMLS_DC ) { - for( int opt_idx = 0; conn_opts[ opt_idx ].conn_option_key != SQLSRV_CONN_OPTION_INVALID; ++opt_idx ) { + for( int opt_idx = 0; conn_opts[opt_idx].conn_option_key != SQLSRV_CONN_OPTION_INVALID; ++opt_idx ) { - if( key == conn_opts[ opt_idx ].conn_option_key ) { + if( key == conn_opts[opt_idx].conn_option_key ) { - return &conn_opts[ opt_idx ]; + return &conn_opts[opt_idx]; } } @@ -759,35 +765,53 @@ void build_connection_string_and_set_conn_attr( _Inout_ sqlsrv_conn* conn, _Inou { bool mars_mentioned = false; connection_option const* conn_opt; + bool access_token_used = false; try { + // First of all, check if access token is specified. If so, check if UID, PWD, Authentication exist + // No need to check the keyword Trusted_Connection because it is not among the acceptable options for SQLSRV drivers + if (zend_hash_index_exists(options, SQLSRV_CONN_OPTION_ACCESS_TOKEN)) { + bool invalidOptions = false; + + // UID and PWD have to be NULLs... throw an exception as long as the user has specified any of them in the connection string, + // even if they may be empty strings. Likewise if the keyword Authentication exists + if (uid != NULL || pwd != NULL || zend_hash_index_exists(options, SQLSRV_CONN_OPTION_AUTHENTICATION)) { + invalidOptions = true; + } - // Add the server name - common_conn_str_append_func( ODBCConnOptions::SERVER, server, strnlen_s( server ), connection_string TSRMLS_CC ); - - // if uid is not present then we use trusted connection. - if(uid == NULL || strnlen_s( uid ) == 0 ) { - - connection_string += "Trusted_Connection={Yes};"; - } - else { - - bool escaped = core_is_conn_opt_value_escaped( uid, strnlen_s( uid )); - CHECK_CUSTOM_ERROR( !escaped, conn, SQLSRV_ERROR_UID_PWD_BRACES_NOT_ESCAPED ) { + CHECK_CUSTOM_ERROR(invalidOptions, conn, SQLSRV_ERROR_INVALID_OPTION_WITH_ACCESS_TOKEN ) { throw core::CoreException(); } - common_conn_str_append_func( ODBCConnOptions::UID, uid, strnlen_s( uid ), connection_string TSRMLS_CC ); + access_token_used = true; + } - // if no password was given, then don't add a password to the connection string. Perhaps the UID - // given doesn't have a password? - if( pwd != NULL ) { - escaped = core_is_conn_opt_value_escaped( pwd, strnlen_s( pwd )); - CHECK_CUSTOM_ERROR( !escaped, conn, SQLSRV_ERROR_UID_PWD_BRACES_NOT_ESCAPED ) { + // Add the server name + common_conn_str_append_func( ODBCConnOptions::SERVER, server, strnlen_s( server ), connection_string TSRMLS_CC ); + + // if uid is not present then we use trusted connection -- but not when access token is used, because they are incompatible + if (!access_token_used) { + if (uid == NULL || strnlen_s(uid) == 0) { + connection_string += CONNECTION_OPTION_NO_CREDENTIALS; // "Trusted_Connection={Yes};" + } + else { + bool escaped = core_is_conn_opt_value_escaped(uid, strnlen_s(uid)); + CHECK_CUSTOM_ERROR(!escaped, conn, SQLSRV_ERROR_UID_PWD_BRACES_NOT_ESCAPED) { throw core::CoreException(); } - common_conn_str_append_func( ODBCConnOptions::PWD, pwd, strnlen_s( pwd ), connection_string TSRMLS_CC ); + common_conn_str_append_func(ODBCConnOptions::UID, uid, strnlen_s(uid), connection_string TSRMLS_CC); + + // if no password was given, then don't add a password to the connection string. Perhaps the UID + // given doesn't have a password? + if (pwd != NULL) { + escaped = core_is_conn_opt_value_escaped(pwd, strnlen_s(pwd)); + CHECK_CUSTOM_ERROR(!escaped, conn, SQLSRV_ERROR_UID_PWD_BRACES_NOT_ESCAPED) { + throw core::CoreException(); + } + + common_conn_str_append_func(ODBCConnOptions::PWD, pwd, strnlen_s(pwd), connection_string TSRMLS_CC); + } } } @@ -919,15 +943,15 @@ const char* get_processor_arch( void ) void determine_server_version( _Inout_ sqlsrv_conn* conn TSRMLS_DC ) { SQLSMALLINT info_len; - char p[ INFO_BUFFER_LEN ]; + char p[INFO_BUFFER_LEN] = {'\0'}; core::SQLGetInfo( conn, SQL_DBMS_VER, p, INFO_BUFFER_LEN, &info_len TSRMLS_CC ); errno = 0; - char version_major_str[ 3 ]; + char version_major_str[3] = {'\0'}; SERVER_VERSION version_major; memcpy_s( version_major_str, sizeof( version_major_str ), p, 2 ); - version_major_str[ 2 ] = '\0'; + version_major_str[2] = {'\0'}; version_major = static_cast( atoi( version_major_str )); CHECK_CUSTOM_ERROR( version_major == 0 && ( errno == ERANGE || errno == EINVAL ), conn, SQLSRV_ERROR_UNKNOWN_SERVER_VERSION ) @@ -1025,7 +1049,7 @@ void common_conn_str_append_func( _In_z_ const char* odbc_name, _In_reads_(val_l // be escaped, such as a closing }. TSRMLS_C; - if( val_len > 0 && val[0] == '{' && val[ val_len - 1 ] == '}' ) { + if( val_len > 0 && val[0] == '{' && val[val_len - 1] == '}' ) { ++val; val_len -= 2; } @@ -1151,8 +1175,8 @@ size_t core_str_zval_is_true( _Inout_ zval* value_z ) // strip any whitespace at the end (whitespace is the same value in ASCII and UTF-8) size_t last_char = val_len - 1; - while( isspace(( unsigned char )value_in[ last_char ] )) { - value_in[ last_char ] = '\0'; + while( isspace(( unsigned char )value_in[last_char] )) { + value_in[last_char] = '\0'; val_len = last_char; --last_char; } @@ -1172,3 +1196,56 @@ size_t core_str_zval_is_true( _Inout_ zval* value_z ) return 0; // false } + +void access_token_set_func::func( _In_ connection_option const* option, _In_ zval* value, _Inout_ sqlsrv_conn* conn, _Inout_ std::string& conn_str TSRMLS_DC ) +{ + SQLSRV_ASSERT(Z_TYPE_P(value) == IS_STRING, "An access token must be a byte string."); + + size_t value_len = Z_STRLEN_P(value); + + CHECK_CUSTOM_ERROR(value_len <= 0, conn, SQLSRV_ERROR_EMPTY_ACCESS_TOKEN) { + throw core::CoreException(); + } + + const char* value_str = Z_STRVAL_P( value ); + + // The SQL_COPT_SS_ACCESS_TOKEN pre-connection attribute allows the use of an access token (in the format extracted from + // an OAuth JSON response), obtained from Azure AD for authentication instead of username and password, and also + // bypasses the negotiation and obtaining of an access token by the driver. To use an access token, set the + // SQL_COPT_SS_ACCESS_TOKEN connection attribute to a pointer to an ACCESSTOKEN structure + // + // typedef struct AccessToken + // { + // unsigned int dataSize; + // char data[]; + // } ACCESSTOKEN; + // + // NOTE: The ODBC Driver version 13.1 only supports this authentication on Windows. + // + // A valid access token byte string must be expanded so that each byte is followed by a 0 padding byte, + // similar to a UCS-2 string containing only ASCII characters + // + // See https://docs.microsoft.com/sql/connect/odbc/using-azure-active-directory#authenticating-with-an-access-token + + size_t dataSize = 2 * value_len; + + sqlsrv_malloc_auto_ptr accToken; + accToken = reinterpret_cast(sqlsrv_malloc(sizeof(ACCESSTOKEN) + dataSize)); + + ACCESSTOKEN *pAccToken = accToken.get(); + SQLSRV_ASSERT(pAccToken != NULL, "Something went wrong when trying to allocate memory for the access token."); + + pAccToken->dataSize = dataSize; + + // Expand access token with padding bytes + for (size_t i = 0, j = 0; i < dataSize; i += 2, j++) { + pAccToken->data[i] = value_str[j]; + pAccToken->data[i+1] = 0; + } + + core::SQLSetConnectAttr(conn, SQL_COPT_SS_ACCESS_TOKEN, reinterpret_cast(pAccToken), SQL_IS_POINTER); + + // Save the pointer because SQLDriverConnect() will use it to make connection to the server + conn->azure_ad_access_token = pAccToken; + accToken.transferred(); +} diff --git a/source/shared/core_init.cpp b/source/shared/core_init.cpp index cda38fa55..274c10d26 100644 --- a/source/shared/core_init.cpp +++ b/source/shared/core_init.cpp @@ -3,7 +3,7 @@ // // Contents: common initialization routines shared by PDO and sqlsrv // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/core_results.cpp b/source/shared/core_results.cpp index 62a757d86..67a805558 100644 --- a/source/shared/core_results.cpp +++ b/source/shared/core_results.cpp @@ -3,7 +3,7 @@ // // Contents: Result sets // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -341,8 +341,8 @@ struct row_dtor_closure { sqlsrv_error* odbc_get_diag_rec( _In_ sqlsrv_stmt* odbc, _In_ SQLSMALLINT record_number ) { - SQLWCHAR wsql_state[ SQL_SQLSTATE_BUFSIZE ]; - SQLWCHAR wnative_message[ SQL_MAX_ERROR_MESSAGE_LENGTH + 1 ]; + SQLWCHAR wsql_state[SQL_SQLSTATE_BUFSIZE] = {L'\0'}; + SQLWCHAR wnative_message[SQL_MAX_ERROR_MESSAGE_LENGTH + 1] = {L'\0'}; SQLINTEGER native_code; SQLSMALLINT wnative_message_len = 0; @@ -459,29 +459,29 @@ sqlsrv_buffered_result_set::sqlsrv_buffered_result_set( _Inout_ sqlsrv_stmt* stm // set up the conversion matrix if this is the first time we're called if( conv_matrix.size() == 0 ) { - conv_matrix[ SQL_C_CHAR ][ SQL_C_CHAR ] = &sqlsrv_buffered_result_set::to_same_string; - conv_matrix[ SQL_C_CHAR ][ SQL_C_WCHAR ] = &sqlsrv_buffered_result_set::system_to_wide_string; - conv_matrix[ SQL_C_CHAR ][ SQL_C_BINARY ] = &sqlsrv_buffered_result_set::to_binary_string; - conv_matrix[ SQL_C_CHAR ][ SQL_C_DOUBLE ] = &sqlsrv_buffered_result_set::string_to_double; - conv_matrix[ SQL_C_CHAR ][ SQL_C_LONG ] = &sqlsrv_buffered_result_set::string_to_long; - conv_matrix[ SQL_C_WCHAR ][ SQL_C_WCHAR ] = &sqlsrv_buffered_result_set::to_same_string; - conv_matrix[ SQL_C_WCHAR ][ SQL_C_BINARY ] = &sqlsrv_buffered_result_set::to_binary_string; - conv_matrix[ SQL_C_WCHAR ][ SQL_C_CHAR ] = &sqlsrv_buffered_result_set::wide_to_system_string; - conv_matrix[ SQL_C_WCHAR ][ SQL_C_DOUBLE ] = &sqlsrv_buffered_result_set::wstring_to_double; - conv_matrix[ SQL_C_WCHAR ][ SQL_C_LONG ] = &sqlsrv_buffered_result_set::wstring_to_long; - conv_matrix[ SQL_C_BINARY ][ SQL_C_BINARY ] = &sqlsrv_buffered_result_set::to_same_string; - conv_matrix[ SQL_C_BINARY ][ SQL_C_CHAR ] = &sqlsrv_buffered_result_set::binary_to_system_string; - conv_matrix[ SQL_C_BINARY ][ SQL_C_WCHAR ] = &sqlsrv_buffered_result_set::binary_to_wide_string; - conv_matrix[ SQL_C_LONG ][ SQL_C_DOUBLE ] = &sqlsrv_buffered_result_set::long_to_double; - conv_matrix[ SQL_C_LONG ][ SQL_C_LONG ] = &sqlsrv_buffered_result_set::to_long; - conv_matrix[ SQL_C_LONG ][ SQL_C_BINARY ] = &sqlsrv_buffered_result_set::to_long; - conv_matrix[ SQL_C_LONG ][ SQL_C_CHAR ] = &sqlsrv_buffered_result_set::long_to_system_string; - conv_matrix[ SQL_C_LONG ][ SQL_C_WCHAR ] = &sqlsrv_buffered_result_set::long_to_wide_string; - conv_matrix[ SQL_C_DOUBLE ][ SQL_C_DOUBLE ] = &sqlsrv_buffered_result_set::to_double; - conv_matrix[ SQL_C_DOUBLE ][ SQL_C_BINARY ] = &sqlsrv_buffered_result_set::to_double; - conv_matrix[ SQL_C_DOUBLE ][ SQL_C_CHAR ] = &sqlsrv_buffered_result_set::double_to_system_string; - conv_matrix[ SQL_C_DOUBLE ][ SQL_C_LONG ] = &sqlsrv_buffered_result_set::double_to_long; - conv_matrix[ SQL_C_DOUBLE ][ SQL_C_WCHAR ] = &sqlsrv_buffered_result_set::double_to_wide_string; + conv_matrix[SQL_C_CHAR][SQL_C_CHAR] = &sqlsrv_buffered_result_set::to_same_string; + conv_matrix[SQL_C_CHAR][SQL_C_WCHAR] = &sqlsrv_buffered_result_set::system_to_wide_string; + conv_matrix[SQL_C_CHAR][SQL_C_BINARY] = &sqlsrv_buffered_result_set::to_binary_string; + conv_matrix[SQL_C_CHAR][SQL_C_DOUBLE] = &sqlsrv_buffered_result_set::string_to_double; + conv_matrix[SQL_C_CHAR][SQL_C_LONG] = &sqlsrv_buffered_result_set::string_to_long; + conv_matrix[SQL_C_WCHAR][SQL_C_WCHAR] = &sqlsrv_buffered_result_set::to_same_string; + conv_matrix[SQL_C_WCHAR][SQL_C_BINARY] = &sqlsrv_buffered_result_set::to_binary_string; + conv_matrix[SQL_C_WCHAR][SQL_C_CHAR] = &sqlsrv_buffered_result_set::wide_to_system_string; + conv_matrix[SQL_C_WCHAR][SQL_C_DOUBLE] = &sqlsrv_buffered_result_set::wstring_to_double; + conv_matrix[SQL_C_WCHAR][SQL_C_LONG] = &sqlsrv_buffered_result_set::wstring_to_long; + conv_matrix[SQL_C_BINARY][SQL_C_BINARY] = &sqlsrv_buffered_result_set::to_same_string; + conv_matrix[SQL_C_BINARY][SQL_C_CHAR] = &sqlsrv_buffered_result_set::binary_to_system_string; + conv_matrix[SQL_C_BINARY][SQL_C_WCHAR] = &sqlsrv_buffered_result_set::binary_to_wide_string; + conv_matrix[SQL_C_LONG][SQL_C_DOUBLE] = &sqlsrv_buffered_result_set::long_to_double; + conv_matrix[SQL_C_LONG][SQL_C_LONG] = &sqlsrv_buffered_result_set::to_long; + conv_matrix[SQL_C_LONG][SQL_C_BINARY] = &sqlsrv_buffered_result_set::to_long; + conv_matrix[SQL_C_LONG][SQL_C_CHAR] = &sqlsrv_buffered_result_set::long_to_system_string; + conv_matrix[SQL_C_LONG][SQL_C_WCHAR] = &sqlsrv_buffered_result_set::long_to_wide_string; + conv_matrix[SQL_C_DOUBLE][SQL_C_DOUBLE] = &sqlsrv_buffered_result_set::to_double; + conv_matrix[SQL_C_DOUBLE][SQL_C_BINARY] = &sqlsrv_buffered_result_set::to_double; + conv_matrix[SQL_C_DOUBLE][SQL_C_CHAR] = &sqlsrv_buffered_result_set::double_to_system_string; + conv_matrix[SQL_C_DOUBLE][SQL_C_LONG] = &sqlsrv_buffered_result_set::double_to_long; + conv_matrix[SQL_C_DOUBLE][SQL_C_WCHAR] = &sqlsrv_buffered_result_set::double_to_wide_string; } SQLSRV_ENCODING encoding = (( stmt->encoding() == SQLSRV_ENCODING_DEFAULT ) ? stmt->conn->encoding() : @@ -687,7 +687,7 @@ sqlsrv_buffered_result_set::sqlsrv_buffered_result_set( _Inout_ sqlsrv_stmt* stm if( meta[i].length == sqlsrv_buffered_result_set::meta_data::SIZE_UNKNOWN ) { out_buffer_length = &out_buffer_temp; - SQLPOINTER* lob_addr = reinterpret_cast( &row[ meta[i].offset ] ); + SQLPOINTER* lob_addr = reinterpret_cast( &row[meta[i].offset] ); *lob_addr = read_lob_field( stmt, i, meta[i], mem_used TSRMLS_CC ); // a NULL pointer means NULL field if( *lob_addr == NULL ) { @@ -854,7 +854,7 @@ SQLRETURN sqlsrv_buffered_result_set::get_data( _In_ SQLUSMALLINT field_index, _ return SQL_ERROR; } - return (( this )->*( conv_matrix[ meta[ field_index ].c_type ][ target_type ] ))( field_index, buffer, buffer_length, + return (( this )->*( conv_matrix[meta[field_index].c_type][target_type] ))( field_index, buffer, buffer_length, out_buffer_length ); } @@ -965,9 +965,9 @@ SQLRETURN binary_to_string( _Inout_ SQLCHAR* field_data, _Inout_ SQLLEN& read_so // to get the number of hex digits we can copy SQLLEN to_copy_hex = to_copy / (2 * extra); for( SQLLEN i = 0; i < to_copy_hex; ++i ) { - *h = hex_chars[ (*b & 0xf0) >> 4 ]; + *h = hex_chars[(*b & 0xf0) >> 4]; h++; - *h = hex_chars[ (*b++ & 0x0f) ]; + *h = hex_chars[(*b++ & 0x0f)]; h++; } read_so_far += to_copy_hex; @@ -986,13 +986,13 @@ SQLRETURN sqlsrv_buffered_result_set::binary_to_system_string( _In_ SQLSMALLINT SQLCHAR* row = get_row(); SQLCHAR* field_data = NULL; - if( meta[ field_index ].length == sqlsrv_buffered_result_set::meta_data::SIZE_UNKNOWN ) { + if( meta[field_index].length == sqlsrv_buffered_result_set::meta_data::SIZE_UNKNOWN ) { - field_data = *reinterpret_cast( &row[ meta[ field_index ].offset ] ) + sizeof( SQLULEN ); + field_data = *reinterpret_cast( &row[meta[field_index].offset] ) + sizeof( SQLULEN ); } else { - field_data = &row[ meta[ field_index ].offset ] + sizeof( SQLULEN ); + field_data = &row[meta[field_index].offset] + sizeof( SQLULEN ); } return binary_to_string( field_data, read_so_far, buffer, buffer_length, out_buffer_length, last_error ); @@ -1004,13 +1004,13 @@ SQLRETURN sqlsrv_buffered_result_set::binary_to_wide_string( _In_ SQLSMALLINT fi SQLCHAR* row = get_row(); SQLCHAR* field_data = NULL; - if( meta[ field_index ].length == sqlsrv_buffered_result_set::meta_data::SIZE_UNKNOWN ) { + if( meta[field_index].length == sqlsrv_buffered_result_set::meta_data::SIZE_UNKNOWN ) { - field_data = *reinterpret_cast( &row[ meta[ field_index ].offset ] ) + sizeof( SQLULEN ); + field_data = *reinterpret_cast( &row[meta[field_index].offset] ) + sizeof( SQLULEN ); } else { - field_data = &row[ meta[ field_index ].offset ] + sizeof( SQLULEN ); + field_data = &row[meta[field_index].offset] + sizeof( SQLULEN ); } return binary_to_string( field_data, read_so_far, buffer, buffer_length, out_buffer_length, last_error ); @@ -1020,12 +1020,12 @@ SQLRETURN sqlsrv_buffered_result_set::binary_to_wide_string( _In_ SQLSMALLINT fi SQLRETURN sqlsrv_buffered_result_set::double_to_long( _In_ SQLSMALLINT field_index, _Inout_updates_bytes_(*out_buffer_length) void* buffer, _In_ SQLLEN buffer_length, _Inout_ SQLLEN* out_buffer_length ) { - SQLSRV_ASSERT( meta[ field_index ].c_type == SQL_C_DOUBLE, "Invalid conversion to long" ); + SQLSRV_ASSERT( meta[field_index].c_type == SQL_C_DOUBLE, "Invalid conversion to long" ); SQLSRV_ASSERT( buffer_length >= sizeof(SQLLEN), "Buffer length must be able to find a long in " "sqlsrv_buffered_result_set::double_to_long" ); unsigned char* row = get_row(); - double* double_data = reinterpret_cast( &row[ meta[ field_index ].offset ] ); + double* double_data = reinterpret_cast( &row[meta[field_index].offset] ); LONG* long_data = reinterpret_cast( buffer ); if( *double_data < double( LONG_MIN ) || *double_data > double( LONG_MAX )) { @@ -1049,11 +1049,11 @@ SQLRETURN sqlsrv_buffered_result_set::double_to_long( _In_ SQLSMALLINT field_ind SQLRETURN sqlsrv_buffered_result_set::double_to_system_string( _In_ SQLSMALLINT field_index, _Out_writes_bytes_to_opt_(buffer_length, *out_buffer_length) void* buffer, _In_ SQLLEN buffer_length, _Inout_ SQLLEN* out_buffer_length ) { - SQLSRV_ASSERT( meta[ field_index ].c_type == SQL_C_DOUBLE, "Invalid conversion to system string" ); + SQLSRV_ASSERT( meta[field_index].c_type == SQL_C_DOUBLE, "Invalid conversion to system string" ); SQLSRV_ASSERT( buffer_length > 0, "Buffer length must be > 0 in sqlsrv_buffered_result_set::double_to_system_string" ); unsigned char* row = get_row(); - double* double_data = reinterpret_cast( &row[ meta[ field_index ].offset ] ); + double* double_data = reinterpret_cast( &row[meta[field_index].offset] ); SQLRETURN r = SQL_SUCCESS; #ifdef _WIN32 r = number_to_string( double_data, buffer, buffer_length, out_buffer_length, last_error ); @@ -1066,11 +1066,11 @@ SQLRETURN sqlsrv_buffered_result_set::double_to_system_string( _In_ SQLSMALLINT SQLRETURN sqlsrv_buffered_result_set::double_to_wide_string( _In_ SQLSMALLINT field_index, _Out_writes_bytes_to_opt_(buffer_length, *out_buffer_length) void* buffer, _In_ SQLLEN buffer_length, _Inout_ SQLLEN* out_buffer_length ) { - SQLSRV_ASSERT( meta[ field_index ].c_type == SQL_C_DOUBLE, "Invalid conversion to wide string" ); + SQLSRV_ASSERT( meta[field_index].c_type == SQL_C_DOUBLE, "Invalid conversion to wide string" ); SQLSRV_ASSERT( buffer_length > 0, "Buffer length must be > 0 in sqlsrv_buffered_result_set::double_to_wide_string" ); unsigned char* row = get_row(); - double* double_data = reinterpret_cast( &row[ meta[ field_index ].offset ] ); + double* double_data = reinterpret_cast( &row[meta[field_index].offset] ); SQLRETURN r = SQL_SUCCESS; #ifdef _WIN32 r = number_to_string( double_data, buffer, buffer_length, out_buffer_length, last_error ); @@ -1083,12 +1083,12 @@ SQLRETURN sqlsrv_buffered_result_set::double_to_wide_string( _In_ SQLSMALLINT fi SQLRETURN sqlsrv_buffered_result_set::long_to_double( _In_ SQLSMALLINT field_index, _Out_writes_bytes_(*out_buffer_length) void* buffer, _In_ SQLLEN buffer_length, _Out_ SQLLEN* out_buffer_length ) { - SQLSRV_ASSERT( meta[ field_index ].c_type == SQL_C_LONG, "Invalid conversion to long" ); + SQLSRV_ASSERT( meta[field_index].c_type == SQL_C_LONG, "Invalid conversion to long" ); SQLSRV_ASSERT( buffer_length >= sizeof(double), "Buffer length must be able to find a long in sqlsrv_buffered_result_set::double_to_long" ); unsigned char* row = get_row(); double* double_data = reinterpret_cast( buffer ); - LONG* long_data = reinterpret_cast( &row[ meta[ field_index ].offset ] ); + LONG* long_data = reinterpret_cast( &row[meta[field_index].offset] ); *double_data = static_cast( *long_data ); *out_buffer_length = sizeof( double ); @@ -1098,11 +1098,11 @@ SQLRETURN sqlsrv_buffered_result_set::long_to_double( _In_ SQLSMALLINT field_ind SQLRETURN sqlsrv_buffered_result_set::long_to_system_string( _In_ SQLSMALLINT field_index, _Out_writes_bytes_to_opt_(buffer_length, *out_buffer_length) void* buffer, _In_ SQLLEN buffer_length, _Inout_ SQLLEN* out_buffer_length ) { - SQLSRV_ASSERT( meta[ field_index ].c_type == SQL_C_LONG, "Invalid conversion to system string" ); + SQLSRV_ASSERT( meta[field_index].c_type == SQL_C_LONG, "Invalid conversion to system string" ); SQLSRV_ASSERT( buffer_length > 0, "Buffer length must be > 0 in sqlsrv_buffered_result_set::long_to_system_string" ); unsigned char* row = get_row(); - LONG* long_data = reinterpret_cast( &row[ meta[ field_index ].offset ] ); + LONG* long_data = reinterpret_cast( &row[meta[field_index].offset] ); SQLRETURN r = SQL_SUCCESS; #ifdef _WIN32 r = number_to_string( long_data, buffer, buffer_length, out_buffer_length, last_error ); @@ -1115,11 +1115,11 @@ SQLRETURN sqlsrv_buffered_result_set::long_to_system_string( _In_ SQLSMALLINT fi SQLRETURN sqlsrv_buffered_result_set::long_to_wide_string( _In_ SQLSMALLINT field_index, _Out_writes_bytes_to_opt_(buffer_length, *out_buffer_length) void* buffer, _In_ SQLLEN buffer_length, _Inout_ SQLLEN* out_buffer_length ) { - SQLSRV_ASSERT( meta[ field_index ].c_type == SQL_C_LONG, "Invalid conversion to wide string" ); + SQLSRV_ASSERT( meta[field_index].c_type == SQL_C_LONG, "Invalid conversion to wide string" ); SQLSRV_ASSERT( buffer_length > 0, "Buffer length must be > 0 in sqlsrv_buffered_result_set::long_to_wide_string" ); unsigned char* row = get_row(); - LONG* long_data = reinterpret_cast( &row[ meta[ field_index ].offset ] ); + LONG* long_data = reinterpret_cast( &row[meta[field_index].offset] ); SQLRETURN r = SQL_SUCCESS; #ifdef _WIN32 r = number_to_string( long_data, buffer, buffer_length, out_buffer_length, last_error ); @@ -1132,49 +1132,49 @@ SQLRETURN sqlsrv_buffered_result_set::long_to_wide_string( _In_ SQLSMALLINT fiel SQLRETURN sqlsrv_buffered_result_set::string_to_double( _In_ SQLSMALLINT field_index, _Out_writes_bytes_(*out_buffer_length) void* buffer, _In_ SQLLEN buffer_length, _Inout_ SQLLEN* out_buffer_length ) { - SQLSRV_ASSERT( meta[ field_index ].c_type == SQL_C_CHAR, "Invalid conversion from string to double" ); + SQLSRV_ASSERT( meta[field_index].c_type == SQL_C_CHAR, "Invalid conversion from string to double" ); SQLSRV_ASSERT( buffer_length >= sizeof( double ), "Buffer needs to be big enough to hold a double" ); unsigned char* row = get_row(); - char* string_data = reinterpret_cast( &row[ meta[ field_index ].offset ] ) + sizeof( SQLULEN ); + char* string_data = reinterpret_cast( &row[meta[field_index].offset] ) + sizeof( SQLULEN ); - return string_to_number( string_data, meta[ field_index ].length, buffer, buffer_length, out_buffer_length, last_error ); + return string_to_number( string_data, meta[field_index].length, buffer, buffer_length, out_buffer_length, last_error ); } SQLRETURN sqlsrv_buffered_result_set::wstring_to_double( _In_ SQLSMALLINT field_index, _Out_writes_bytes_(*out_buffer_length) void* buffer, _In_ SQLLEN buffer_length, _Inout_ SQLLEN* out_buffer_length ) { - SQLSRV_ASSERT( meta[ field_index ].c_type == SQL_C_WCHAR, "Invalid conversion from wide string to double" ); + SQLSRV_ASSERT( meta[field_index].c_type == SQL_C_WCHAR, "Invalid conversion from wide string to double" ); SQLSRV_ASSERT( buffer_length >= sizeof( double ), "Buffer needs to be big enough to hold a double" ); unsigned char* row = get_row(); - SQLWCHAR* string_data = reinterpret_cast( &row[ meta[ field_index ].offset ] ) + sizeof( SQLULEN ) / sizeof( SQLWCHAR ); + SQLWCHAR* string_data = reinterpret_cast( &row[meta[field_index].offset] ) + sizeof( SQLULEN ) / sizeof( SQLWCHAR ); - return string_to_number( string_data, meta[ field_index ].length, buffer, buffer_length, out_buffer_length, last_error ); + return string_to_number( string_data, meta[field_index].length, buffer, buffer_length, out_buffer_length, last_error ); } SQLRETURN sqlsrv_buffered_result_set::string_to_long( _In_ SQLSMALLINT field_index, _Out_writes_bytes_(*out_buffer_length) void* buffer, _In_ SQLLEN buffer_length, _Inout_ SQLLEN* out_buffer_length ) { - SQLSRV_ASSERT( meta[ field_index ].c_type == SQL_C_CHAR, "Invalid conversion from string to long" ); + SQLSRV_ASSERT( meta[field_index].c_type == SQL_C_CHAR, "Invalid conversion from string to long" ); SQLSRV_ASSERT( buffer_length >= sizeof( LONG ), "Buffer needs to be big enough to hold a long" ); unsigned char* row = get_row(); - char* string_data = reinterpret_cast( &row[ meta[ field_index ].offset ] ) + sizeof( SQLULEN ); + char* string_data = reinterpret_cast( &row[meta[field_index].offset] ) + sizeof( SQLULEN ); - return string_to_number( string_data, meta[ field_index ].length, buffer, buffer_length, out_buffer_length, last_error ); + return string_to_number( string_data, meta[field_index].length, buffer, buffer_length, out_buffer_length, last_error ); } SQLRETURN sqlsrv_buffered_result_set::wstring_to_long( _In_ SQLSMALLINT field_index, _Out_writes_bytes_(*out_buffer_length) void* buffer, _In_ SQLLEN buffer_length, _Inout_ SQLLEN* out_buffer_length ) { - SQLSRV_ASSERT( meta[ field_index ].c_type == SQL_C_WCHAR, "Invalid conversion from wide string to long" ); + SQLSRV_ASSERT( meta[field_index].c_type == SQL_C_WCHAR, "Invalid conversion from wide string to long" ); SQLSRV_ASSERT( buffer_length >= sizeof( LONG ), "Buffer needs to be big enough to hold a long" ); unsigned char* row = get_row(); - SQLWCHAR* string_data = reinterpret_cast( &row[ meta[ field_index ].offset ] ) + sizeof( SQLULEN ) / sizeof( SQLWCHAR ); + SQLWCHAR* string_data = reinterpret_cast( &row[meta[field_index].offset] ) + sizeof( SQLULEN ) / sizeof( SQLWCHAR ); - return string_to_number( string_data, meta[ field_index ].length, buffer, buffer_length, out_buffer_length, last_error ); + return string_to_number( string_data, meta[field_index].length, buffer, buffer_length, out_buffer_length, last_error ); } SQLRETURN sqlsrv_buffered_result_set::system_to_wide_string( _In_ SQLSMALLINT field_index, _Out_writes_z_(*out_buffer_length) void* buffer, _In_ SQLLEN buffer_length, @@ -1189,15 +1189,15 @@ SQLRETURN sqlsrv_buffered_result_set::system_to_wide_string( _In_ SQLSMALLINT fi SQLCHAR* field_data = NULL; SQLULEN field_len = 0; - if( meta[ field_index ].length == sqlsrv_buffered_result_set::meta_data::SIZE_UNKNOWN ) { + if( meta[field_index].length == sqlsrv_buffered_result_set::meta_data::SIZE_UNKNOWN ) { - field_len = **reinterpret_cast( &row[ meta[ field_index ].offset ] ); - field_data = *reinterpret_cast( &row[ meta[ field_index ].offset ] ) + sizeof( SQLULEN ) + read_so_far; + field_len = **reinterpret_cast( &row[meta[field_index].offset] ); + field_data = *reinterpret_cast( &row[meta[field_index].offset] ) + sizeof( SQLULEN ) + read_so_far; } else { - field_len = *reinterpret_cast( &row[ meta[ field_index ].offset ] ); - field_data = &row[ meta[ field_index ].offset ] + sizeof( SQLULEN ) + read_so_far; + field_len = *reinterpret_cast( &row[meta[field_index].offset] ); + field_data = &row[meta[field_index].offset] + sizeof( SQLULEN ) + read_so_far; } // all fields will be treated as ODBC returns varchar(max) fields: @@ -1264,7 +1264,7 @@ SQLRETURN sqlsrv_buffered_result_set::system_to_wide_string( _In_ SQLSMALLINT fi return SQL_ERROR; } - ((WCHAR*)buffer)[ to_copy ] = L'\0'; + ((WCHAR*)buffer)[to_copy] = L'\0'; read_so_far += to_copy; break; @@ -1288,7 +1288,7 @@ SQLRETURN sqlsrv_buffered_result_set::to_same_string( _In_ SQLSMALLINT field_ind // Set the amount of space necessary for null characters at the end of the data. SQLSMALLINT extra = 0; - switch( meta[ field_index ].c_type ) { + switch( meta[field_index].c_type ) { case SQL_C_WCHAR: extra = sizeof( SQLWCHAR ); break; @@ -1305,13 +1305,13 @@ SQLRETURN sqlsrv_buffered_result_set::to_same_string( _In_ SQLSMALLINT field_ind SQLCHAR* field_data = NULL; - if( meta[ field_index ].length == sqlsrv_buffered_result_set::meta_data::SIZE_UNKNOWN ) { + if( meta[field_index].length == sqlsrv_buffered_result_set::meta_data::SIZE_UNKNOWN ) { - field_data = *reinterpret_cast( &row[ meta[ field_index ].offset ] ) + sizeof( SQLULEN ); + field_data = *reinterpret_cast( &row[meta[field_index].offset] ) + sizeof( SQLULEN ); } else { - field_data = &row[ meta[ field_index ].offset ] + sizeof( SQLULEN ); + field_data = &row[meta[field_index].offset] + sizeof( SQLULEN ); } // all fields will be treated as ODBC returns varchar(max) fields: @@ -1366,15 +1366,15 @@ SQLRETURN sqlsrv_buffered_result_set::wide_to_system_string( _In_ SQLSMALLINT fi if( read_so_far == 0 ) { - if( meta[ field_index ].length == sqlsrv_buffered_result_set::meta_data::SIZE_UNKNOWN ) { + if( meta[field_index].length == sqlsrv_buffered_result_set::meta_data::SIZE_UNKNOWN ) { - field_len = **reinterpret_cast( &row[ meta[ field_index ].offset ] ); - field_data = *reinterpret_cast( &row[ meta[ field_index ].offset ] ) + sizeof( SQLULEN ) + read_so_far; + field_len = **reinterpret_cast( &row[meta[field_index].offset] ); + field_data = *reinterpret_cast( &row[meta[field_index].offset] ) + sizeof( SQLULEN ) + read_so_far; } else { - field_len = *reinterpret_cast( &row[ meta[ field_index ].offset ] ); - field_data = &row[ meta[ field_index ].offset ] + sizeof( SQLULEN ) + read_so_far; + field_len = *reinterpret_cast( &row[meta[field_index].offset] ); + field_data = &row[meta[field_index].offset] + sizeof( SQLULEN ) + read_so_far; } if ( field_len == 0 ) { // empty string, no need for conversion @@ -1434,7 +1434,7 @@ SQLRETURN sqlsrv_buffered_result_set::wide_to_system_string( _In_ SQLSMALLINT fi } SQLSRV_ASSERT( to_copy >= 0, "Invalid field copy length" ); OACR_WARNING_SUPPRESS( BUFFER_UNDERFLOW, "Buffer length verified above" ); - ((SQLCHAR*) buffer)[ to_copy ] = '\0'; + ((SQLCHAR*) buffer)[to_copy] = '\0'; read_so_far += to_copy; return r; @@ -1450,11 +1450,11 @@ SQLRETURN sqlsrv_buffered_result_set::to_binary_string( _In_ SQLSMALLINT field_i SQLRETURN sqlsrv_buffered_result_set::to_long( _In_ SQLSMALLINT field_index, _Out_writes_bytes_to_opt_(buffer_length, *out_buffer_length) void* buffer, _In_ SQLLEN buffer_length, _Out_ SQLLEN* out_buffer_length ) { - SQLSRV_ASSERT( meta[ field_index ].c_type == SQL_C_LONG, "Invalid conversion to long" ); + SQLSRV_ASSERT( meta[field_index].c_type == SQL_C_LONG, "Invalid conversion to long" ); SQLSRV_ASSERT( buffer_length >= sizeof( LONG ), "Buffer too small for SQL_C_LONG" ); // technically should ignore this unsigned char* row = get_row(); - LONG* long_data = reinterpret_cast( &row[ meta[ field_index ].offset ] ); + LONG* long_data = reinterpret_cast( &row[meta[field_index].offset] ); memcpy_s( buffer, buffer_length, long_data, sizeof( LONG )); *out_buffer_length = sizeof( LONG ); @@ -1464,11 +1464,11 @@ SQLRETURN sqlsrv_buffered_result_set::to_long( _In_ SQLSMALLINT field_index, _Ou SQLRETURN sqlsrv_buffered_result_set::to_double( _In_ SQLSMALLINT field_index, _Out_writes_bytes_to_opt_(buffer_length, *out_buffer_length) void* buffer, _In_ SQLLEN buffer_length, _Out_ SQLLEN* out_buffer_length ) { - SQLSRV_ASSERT( meta[ field_index ].c_type == SQL_C_DOUBLE, "Invalid conversion to double" ); + SQLSRV_ASSERT( meta[field_index].c_type == SQL_C_DOUBLE, "Invalid conversion to double" ); SQLSRV_ASSERT( buffer_length >= sizeof( double ), "Buffer too small for SQL_C_DOUBLE" ); // technically should ignore this unsigned char* row = get_row(); - double* double_data = reinterpret_cast( &row[ meta[ field_index ].offset ] ); + double* double_data = reinterpret_cast( &row[meta[field_index].offset] ); memcpy_s( buffer, buffer_length, double_data, sizeof( double )); *out_buffer_length = sizeof( double ); @@ -1489,7 +1489,7 @@ void cache_row_dtor( _In_ zval* data ) if( result_set->col_meta_data(i).length == sqlsrv_buffered_result_set::meta_data::SIZE_UNKNOWN ) { - void* out_of_row_data = *reinterpret_cast( &row[ result_set->col_meta_data(i).offset ] ); + void* out_of_row_data = *reinterpret_cast( &row[result_set->col_meta_data(i).offset] ); sqlsrv_free( out_of_row_data ); } } @@ -1525,7 +1525,7 @@ SQLPOINTER read_lob_field( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT field_in sqlsrv_malloc_auto_ptr buffer; buffer = static_cast( sqlsrv_malloc( INITIAL_LOB_FIELD_LEN + extra + sizeof( SQLULEN ))); SQLRETURN r = SQL_SUCCESS; - SQLCHAR state[ SQL_SQLSTATE_BUFSIZE ]; + SQLCHAR state[SQL_SQLSTATE_BUFSIZE] = {'\0'}; SQLLEN last_field_len = 0; bool full_length_returned = false; diff --git a/source/shared/core_sqlsrv.h b/source/shared/core_sqlsrv.h index 5530a5540..6c49464cd 100644 --- a/source/shared/core_sqlsrv.h +++ b/source/shared/core_sqlsrv.h @@ -6,7 +6,7 @@ // // Contents: Core routines and constants shared by the Microsoft Drivers for PHP for SQL Server // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -70,7 +70,7 @@ typedef struct _OSVERSIONINFOA { DWORD dwMinorVersion; DWORD dwBuildNumber; DWORD dwPlatformId; - CHAR szCSDVersion[ 128 ]; // Maintenance string for PSS usage + CHAR szCSDVersion[128]; // Maintenance string for PSS usage } OSVERSIONINFOA, *POSVERSIONINFOA, *LPOSVERSIONINFOA; typedef OSVERSIONINFOA OSVERSIONINFO; #endif // !_WIN32 @@ -175,7 +175,7 @@ const int SQL_SERVER_MAX_TYPE_SIZE = 0; const int SQL_SERVER_MAX_PARAMS = 2100; // increase the maximum message length to accommodate for the long error returned for operand type clash // or for conversion of a long string -const int SQL_MAX_ERROR_MESSAGE_LENGTH = SQL_MAX_MESSAGE_LENGTH * 8; +const int SQL_MAX_ERROR_MESSAGE_LENGTH = SQL_MAX_MESSAGE_LENGTH * 2; // max size of a date time string when converting from a DateTime object to a string const int MAX_DATETIME_STRING_LEN = 256; @@ -546,21 +546,21 @@ class sqlsrv_auto_ptr { // an array of elements, so this operator allows us to treat the memory as such. T& operator[]( _In_ int index ) const { - return _ptr[ index ]; + return _ptr[index]; } // there are a number of places where we allocate a block intended to be accessed as // an array of elements, so this operator allows us to treat the memory as such. T& operator[]( _In_ unsigned int index ) const { - return _ptr[ index ]; + return _ptr[index]; } // there are a number of places where we allocate a block intended to be accessed as // an array of elements, so this operator allows us to treat the memory as such. T& operator[]( _In_ long index ) const { - return _ptr[ index ]; + return _ptr[index]; } @@ -577,7 +577,7 @@ class sqlsrv_auto_ptr { // an array of elements, so this operator allows us to treat the memory as such. T& operator[]( _In_ unsigned short index ) const { - return _ptr[ index ]; + return _ptr[index]; } // access elements of a structure through the auto ptr @@ -693,9 +693,9 @@ class hash_auto_ptr : public sqlsrv_auto_ptr { // free the original pointer and assign a new pointer. Use NULL to simply free the pointer. void reset( _In_opt_ HashTable* ptr = NULL ) { - if( _ptr ) { - zend_hash_destroy( _ptr ); - FREE_HASHTABLE( _ptr ); + if (_ptr != NULL) { + zend_hash_destroy(_ptr); + FREE_HASHTABLE(_ptr); } _ptr = ptr; } @@ -1076,6 +1076,8 @@ struct sqlsrv_conn : public sqlsrv_context { col_encryption_option ce_option; // holds the details of what are required to enable column encryption DRIVER_VERSION driver_version; // version of ODBC driver + sqlsrv_malloc_auto_ptr azure_ad_access_token; + // initialize with default values sqlsrv_conn( _In_ SQLHANDLE h, _In_ error_callback e, _In_opt_ void* drv, _In_ SQLSRV_ENCODING encoding TSRMLS_DC ) : sqlsrv_context( h, SQL_HANDLE_DBC, e, drv, encoding ) @@ -1096,6 +1098,7 @@ enum SQLSRV_STMT_OPTIONS { SQLSRV_STMT_OPTION_SEND_STREAMS_AT_EXEC, SQLSRV_STMT_OPTION_SCROLLABLE, SQLSRV_STMT_OPTION_CLIENT_BUFFER_MAX_SIZE, + SQLSRV_STMT_OPTION_DATE_AS_STRING, // Driver specific connection options SQLSRV_STMT_OPTION_DRIVER_SPECIFIC = 1000, @@ -1105,6 +1108,7 @@ enum SQLSRV_STMT_OPTIONS { namespace ODBCConnOptions { const char APP[] = "APP"; +const char AccessToken[] = "AccessToken"; const char ApplicationIntent[] = "ApplicationIntent"; const char AttachDBFileName[] = "AttachDbFileName"; const char Authentication[] = "Authentication"; @@ -1140,6 +1144,7 @@ enum SQLSRV_CONN_OPTIONS { SQLSRV_CONN_OPTION_INVALID, SQLSRV_CONN_OPTION_APP, + SQLSRV_CONN_OPTION_ACCESS_TOKEN, SQLSRV_CONN_OPTION_CHARACTERSET, SQLSRV_CONN_OPTION_CONN_POOLING, SQLSRV_CONN_OPTION_DATABASE, @@ -1222,14 +1227,14 @@ struct driver_set_func { static void func( _In_ connection_option const* option, _In_ zval* value, _Inout_ sqlsrv_conn* conn, _Inout_ std::string& conn_str TSRMLS_DC ); }; -struct ce_ksp_provider_set_func { - static void func( _In_ connection_option const* option, _In_ zval* value, _Inout_ sqlsrv_conn* conn, _Inout_ std::string& conn_str TSRMLS_DC ); -}; - struct ce_akv_str_set_func { static void func( _In_ connection_option const* option, _In_ zval* value, _Inout_ sqlsrv_conn* conn, _Inout_ std::string& conn_str TSRMLS_DC ); }; +struct access_token_set_func { + static void func( _In_ connection_option const* option, _In_ zval* value, _Inout_ sqlsrv_conn* conn, _Inout_ std::string& conn_str TSRMLS_DC ); +}; + // factory to create a connection (since they are subclassed to instantiate statements) typedef sqlsrv_conn* (*driver_conn_factory)( _In_ SQLHANDLE h, _In_ error_callback e, _In_ void* drv TSRMLS_DC ); @@ -1278,6 +1283,11 @@ struct stmt_option_buffered_query_limit : public stmt_option_functor { virtual void operator()( _Inout_ sqlsrv_stmt* stmt, stmt_option const* opt, _In_ zval* value_z TSRMLS_DC ); }; +struct stmt_option_date_as_string : public stmt_option_functor { + + virtual void operator()( _Inout_ sqlsrv_stmt* stmt, stmt_option const* opt, _In_ zval* value_z TSRMLS_DC ); +}; + // used to hold the table for statment options struct stmt_option { @@ -1389,6 +1399,7 @@ struct sqlsrv_stmt : public sqlsrv_context { // last results unsigned long query_timeout; // maximum allowed statement execution time zend_long buffered_query_limit; // maximum allowed memory for a buffered query (measured in KB) + bool date_as_string; // false by default but the user can set this to true to retrieve datetime values as strings // holds output pointers for SQLBindParameter // We use a deque because it 1) provides the at/[] access in constant time, and 2) grows dynamically without moving @@ -1718,6 +1729,8 @@ enum SQLSRV_ERROR_CODES { SQLSRV_ERROR_AKV_SECRET_MISSING, SQLSRV_ERROR_KEYSTORE_INVALID_VALUE, SQLSRV_ERROR_DOUBLE_CONVERSION_FAILED, + SQLSRV_ERROR_INVALID_OPTION_WITH_ACCESS_TOKEN, + SQLSRV_ERROR_EMPTY_ACCESS_TOKEN, // Driver specific error codes starts from here. SQLSRV_ERROR_DRIVER_SPECIFIC = 1000, @@ -1889,14 +1902,20 @@ namespace core { // and return a more helpful message prepended to the ODBC errors if that error occurs if( !SQL_SUCCEEDED( r )) { - SQLCHAR err_msg[ SQL_MAX_ERROR_MESSAGE_LENGTH + 1 ] = { '\0' }; + SQLCHAR err_msg[SQL_MAX_MESSAGE_LENGTH + 1] = {'\0'}; SQLSMALLINT len = 0; SQLRETURN rtemp = ::SQLGetDiagField( stmt->handle_type(), stmt->handle(), 1, SQL_DIAG_MESSAGE_TEXT, - err_msg, SQL_MAX_ERROR_MESSAGE_LENGTH, &len ); + err_msg, SQL_MAX_MESSAGE_LENGTH, &len ); + if (rtemp == SQL_SUCCESS_WITH_INFO && len > SQL_MAX_MESSAGE_LENGTH) { + // if the error message is this long, then it must not be the mars message + // defined as ODBC_CONNECTION_BUSY_ERROR -- so return here and continue the + // regular error handling + return; + } CHECK_SQL_ERROR_OR_WARNING( rtemp, stmt ) { - + throw CoreException(); } @@ -2377,10 +2396,13 @@ namespace core { inline void sqlsrv_array_init( _Inout_ sqlsrv_context& ctx, _Out_ zval* new_array TSRMLS_DC) { - int zr = ::array_init(new_array); - CHECK_ZEND_ERROR( zr, ctx, SQLSRV_ERROR_ZEND_HASH ) { +#if PHP_VERSION_ID < 70300 + CHECK_ZEND_ERROR(::array_init(new_array), ctx, SQLSRV_ERROR_ZEND_HASH) { throw CoreException(); } +#else + array_init(new_array); +#endif } inline void sqlsrv_php_stream_from_zval_no_verify( _Inout_ sqlsrv_context& ctx, _Outref_result_maybenull_ php_stream*& stream, _In_opt_ zval* stream_z TSRMLS_DC ) diff --git a/source/shared/core_stmt.cpp b/source/shared/core_stmt.cpp index 6d4d4f613..46d609078 100644 --- a/source/shared/core_stmt.cpp +++ b/source/shared/core_stmt.cpp @@ -3,7 +3,7 @@ // // Contents: Core routines that use statement handles shared between sqlsrv and pdo_sqlsrv // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -36,7 +36,8 @@ struct field_cache { : type( t ) { // if the value is NULL, then just record a NULL pointer - if( field_value != NULL ) { + // field_len may be equal to SQL_NULL_DATA even when field_value is not null + if( field_value != NULL && field_len != SQL_NULL_DATA) { value = sqlsrv_malloc( field_len ); memcpy_s( value, field_len, field_value, field_len ); len = field_len; @@ -140,6 +141,7 @@ sqlsrv_stmt::sqlsrv_stmt( _In_ sqlsrv_conn* c, _In_ SQLHANDLE handle, _In_ error last_field_index( -1 ), past_next_result_end( false ), query_timeout( QUERY_TIMEOUT_INVALID ), + date_as_string(false), buffered_query_limit( sqlsrv_buffered_result_set::BUFFERED_QUERY_LIMIT_INVALID ), param_ind_ptrs( 10 ), // initially hold 10 elements, which should cover 90% of the cases and only take < 100 byte send_streams_at_exec( true ), @@ -364,7 +366,7 @@ void core_sqlsrv_bind_param( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT param_ if( stmt->param_ind_ptrs.size() < static_cast( param_num + 1 )){ stmt->param_ind_ptrs.resize( param_num + 1, SQL_NULL_DATA ); } - SQLLEN& ind_ptr = stmt->param_ind_ptrs[ param_num ]; + SQLLEN& ind_ptr = stmt->param_ind_ptrs[param_num]; zval* param_ref = param_z; if( Z_ISREF_P( param_z )){ @@ -964,7 +966,7 @@ void core_sqlsrv_get_field( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT field_i memcpy_s( field_value, ( cached->len * sizeof( char )), cached->value, cached->len ); if( cached->type.typeinfo.type == SQLSRV_PHPTYPE_STRING) { // prevent the 'string not null terminated' warning - reinterpret_cast( field_value )[ cached->len ] = '\0'; + reinterpret_cast( field_value )[cached->len] = '\0'; } *field_len = cached->len; if( sqlsrv_php_type_out) { *sqlsrv_php_type_out = static_cast(cached->type.typeinfo.type); } @@ -1236,7 +1238,7 @@ void core_sqlsrv_set_query_timeout( _Inout_ sqlsrv_stmt* stmt, _In_ long timeout int lock_timeout = (( timeout == 0 ) ? -1 : timeout * 1000 /*convert to milliseconds*/ ); // set the LOCK_TIMEOUT on the server. - char lock_timeout_sql[ 32 ]; + char lock_timeout_sql[32] = {'\0'}; int written = snprintf( lock_timeout_sql, sizeof( lock_timeout_sql ), "SET LOCK_TIMEOUT %d", lock_timeout ); SQLSRV_ASSERT( (written != -1 && written != sizeof( lock_timeout_sql )), @@ -1304,7 +1306,7 @@ bool core_sqlsrv_send_stream_packet( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) } // read the data from the stream, send it via SQLPutData and track how much we've sent. else { - char buffer[ PHP_STREAM_BUFFER_SIZE + 1 ]; + char buffer[PHP_STREAM_BUFFER_SIZE + 1] = {'\0'}; std::size_t buffer_size = sizeof( buffer ) - 3; // -3 to preserve enough space for a cut off UTF-8 character std::size_t read = php_stream_read( param_stream, buffer, buffer_size ); @@ -1325,7 +1327,7 @@ bool core_sqlsrv_send_stream_packet( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) // the size of wbuffer is set for the worst case of UTF-8 to UTF-16 conversion, which is a // expansion of 2x the UTF-8 size. - SQLWCHAR wbuffer[ PHP_STREAM_BUFFER_SIZE + 1 ]; + SQLWCHAR wbuffer[PHP_STREAM_BUFFER_SIZE + 1] = {L'\0'}; int wbuffer_size = static_cast( sizeof( wbuffer ) / sizeof( SQLWCHAR )); DWORD last_error_code = ERROR_SUCCESS; // buffer_size is the # of wchars. Since it set to stmt->param_buffer_size / 2, this is accurate @@ -1403,6 +1405,15 @@ void stmt_option_buffered_query_limit:: operator()( _Inout_ sqlsrv_stmt* stmt, s core_sqlsrv_set_buffered_query_limit( stmt, value_z TSRMLS_CC ); } +void stmt_option_date_as_string:: operator()( _Inout_ sqlsrv_stmt* stmt, stmt_option const* /**/, _In_ zval* value_z TSRMLS_DC ) +{ + if (zend_is_true(value_z)) { + stmt->date_as_string = true; + } + else { + stmt->date_as_string = false; + } +} // internal function to release the active stream. Called by each main API function // that will alter the statement and cancel any retrieval of data from a stream. @@ -1631,7 +1642,7 @@ void core_get_field_common( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT field_i // convert it to a DateTime object and return the created object case SQLSRV_PHPTYPE_DATETIME: { - char field_value_temp[ MAX_DATETIME_STRING_LEN ]; + char field_value_temp[MAX_DATETIME_STRING_LEN] = {'\0'}; zval params[1]; zval field_value_temp_z; zval function_z; @@ -1823,7 +1834,7 @@ bool convert_input_param_to_utf16( _In_ zval* input_param_z, _Inout_ zval* conve } // null terminate the string, set the size within the zval, and return success - wbuffer[ wchar_size ] = L'\0'; + wbuffer[wchar_size] = L'\0'; core::sqlsrv_zval_stringl( converted_param_z, reinterpret_cast( wbuffer.get() ), wchar_size * sizeof( SQLWCHAR ) ); sqlsrv_free(wbuffer); wbuffer.transferred(); @@ -2075,7 +2086,7 @@ void finalize_output_parameters( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) { // adjust the length of the string to the value returned by SQLBindParameter in the ind_ptr parameter char* str = Z_STRVAL_P( value_z ); - SQLLEN str_len = stmt->param_ind_ptrs[ output_param->param_num ]; + SQLLEN str_len = stmt->param_ind_ptrs[output_param->param_num]; if( str_len == 0 ) { core::sqlsrv_zval_stringl( value_z, "", 0 ); continue; @@ -2127,7 +2138,7 @@ void finalize_output_parameters( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) // ODBC doesn't null terminate binary encodings, but PHP complains if a string isn't null terminated // so we do that here if the length of the returned data is less than the original allocation. The // original allocation null terminates the buffer already. - str[ str_len ] = '\0'; + str[str_len] = '\0'; core::sqlsrv_zval_stringl(value_z, str, str_len); } else { @@ -2137,7 +2148,7 @@ void finalize_output_parameters( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) break; case IS_LONG: // for a long or a float, simply check if NULL was returned and set the parameter to a PHP null if so - if( stmt->param_ind_ptrs[ output_param->param_num ] == SQL_NULL_DATA ) { + if( stmt->param_ind_ptrs[output_param->param_num] == SQL_NULL_DATA ) { ZVAL_NULL( value_z ); } else if( output_param->is_bool ) { @@ -2258,7 +2269,7 @@ void get_field_as_string( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT field_ind if( r == SQL_SUCCESS_WITH_INFO ) { - SQLCHAR state[SQL_SQLSTATE_BUFSIZE] = { 0 }; + SQLCHAR state[SQL_SQLSTATE_BUFSIZE] = {L'\0'}; SQLSMALLINT len = 0; stmt->current_results->get_diag_field( 1, SQL_DIAG_SQLSTATE, state, SQL_SQLSTATE_BUFSIZE, &len TSRMLS_CC ); @@ -2442,11 +2453,11 @@ field_value = field_value_temp; stmt_option const* get_stmt_option( sqlsrv_conn const* conn, _In_ zend_ulong key, _In_ const stmt_option stmt_opts[] TSRMLS_DC ) { - for( int i = 0; stmt_opts[ i ].key != SQLSRV_STMT_OPTION_INVALID; ++i ) { + for( int i = 0; stmt_opts[i].key != SQLSRV_STMT_OPTION_INVALID; ++i ) { // if we find the key we're looking for, return it - if( key == stmt_opts[ i ].key ) { - return &stmt_opts[ i ]; + if( key == stmt_opts[i].key ) { + return &stmt_opts[i]; } } @@ -2580,8 +2591,8 @@ void resize_output_buffer_if_necessary( _Inout_ sqlsrv_stmt* stmt, _Inout_ zval* // The StrLen_Ind_Ptr parameter of SQLBindParameter should contain the length of the data to send, which // may be less than the size of the buffer since the output may be more than the input. If it is greater, // than the error 22001 is returned by ODBC. - if( stmt->param_ind_ptrs[ paramno ] > buffer_len - (elem_size - buffer_null_extra)) { - stmt->param_ind_ptrs[ paramno ] = buffer_len - (elem_size - buffer_null_extra); + if( stmt->param_ind_ptrs[paramno] > buffer_len - (elem_size - buffer_null_extra)) { + stmt->param_ind_ptrs[paramno] = buffer_len - (elem_size - buffer_null_extra); } } diff --git a/source/shared/core_stream.cpp b/source/shared/core_stream.cpp index 32780a5b2..e4e9e485f 100644 --- a/source/shared/core_stream.cpp +++ b/source/shared/core_stream.cpp @@ -3,7 +3,7 @@ // // Contents: Implementation of PHP streams for reading SQL Server data // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -106,7 +106,7 @@ size_t sqlsrv_stream_read( _Inout_ php_stream* stream, _Out_writes_bytes_(count) // if it's not a binary encoded field if( r == SQL_SUCCESS_WITH_INFO ) { - SQLCHAR state[SQL_SQLSTATE_BUFSIZE] = { 0 }; + SQLCHAR state[SQL_SQLSTATE_BUFSIZE] = {L'\0'}; SQLSMALLINT len = 0; ss->stmt->current_results->get_diag_field( 1, SQL_DIAG_SQLSTATE, state, SQL_SQLSTATE_BUFSIZE, &len TSRMLS_CC ); diff --git a/source/shared/core_util.cpp b/source/shared/core_util.cpp index d8b7b2445..ca097a24b 100644 --- a/source/shared/core_util.cpp +++ b/source/shared/core_util.cpp @@ -5,7 +5,7 @@ // // Comments: Mostly error handling and some type handling // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -28,7 +28,7 @@ log_callback g_driver_log; // internal error that says that FormatMessage failed SQLCHAR INTERNAL_FORMAT_ERROR[] = "An internal error occurred. FormatMessage failed writing an error message."; // buffer used to hold a formatted log message prior to actually logging it. -char last_err_msg[ 2048 ]; // 2k to hold the error messages +char last_err_msg[2048] = {'\0'}; // 2k to hold the error messages // routine used by utf16_string_from_mbcs_string unsigned int convert_string_from_default_encoding( _In_ unsigned int php_encoding, _In_reads_bytes_(mbcs_len) char const* mbcs_in_string, @@ -219,8 +219,8 @@ bool core_sqlsrv_get_odbc_error( _Inout_ sqlsrv_context& ctx, _In_ int record_nu SQLRETURN r = SQL_SUCCESS; SQLSMALLINT wmessage_len = 0; - SQLWCHAR wsqlstate[ SQL_SQLSTATE_BUFSIZE ] = { L'\0' }; - SQLWCHAR wnative_message[ SQL_MAX_ERROR_MESSAGE_LENGTH + 1 ] = { L'\0' }; + SQLWCHAR wsqlstate[SQL_SQLSTATE_BUFSIZE] = {L'\0'}; + SQLWCHAR wnative_message[SQL_MAX_ERROR_MESSAGE_LENGTH + 1] = {L'\0'}; SQLSRV_ENCODING enc = ctx.encoding(); switch( h_type ) { @@ -265,10 +265,36 @@ bool core_sqlsrv_get_odbc_error( _Inout_ sqlsrv_context& ctx, _In_ int record_nu // We need to calculate number of characters SQLINTEGER wsqlstate_len = sizeof( wsqlstate ) / sizeof( SQLWCHAR ); SQLLEN sqlstate_len = 0; - convert_string_from_utf16(enc, wsqlstate, wsqlstate_len, (char**)&error->sqlstate, sqlstate_len); + convert_string_from_utf16(enc, wsqlstate, wsqlstate_len, (char**)&error->sqlstate, sqlstate_len); + SQLLEN message_len = 0; - convert_string_from_utf16(enc, wnative_message, wmessage_len, (char**)&error->native_message, message_len); + if (r == SQL_SUCCESS_WITH_INFO && wmessage_len > SQL_MAX_ERROR_MESSAGE_LENGTH) { + // note that wmessage_len is the number of characters required for the error message -- + // create a new buffer big enough for this lengthy error message + sqlsrv_malloc_auto_ptr wnative_message_str; + + SQLSMALLINT expected_len = wmessage_len * sizeof(SQLWCHAR); + SQLSMALLINT returned_len = 0; + + wnative_message_str = reinterpret_cast(sqlsrv_malloc(expected_len)); + memset(wnative_message_str, '\0', expected_len); + + SQLRETURN rtemp = ::SQLGetDiagFieldW(h_type, h, record_number, SQL_DIAG_MESSAGE_TEXT, wnative_message_str, wmessage_len, &returned_len); + if (!SQL_SUCCEEDED(rtemp) || returned_len != expected_len) { + // something went wrong + return false; + } + + convert_string_from_utf16(enc, wnative_message_str, wmessage_len, (char**)&error->native_message, message_len); + } else { + convert_string_from_utf16(enc, wnative_message, wmessage_len, (char**)&error->native_message, message_len); + } + + if (message_len == 0 && error->native_message == NULL) { + // something went wrong + return false; + } break; } @@ -352,11 +378,11 @@ void die( _In_opt_ const char* msg, ... ) va_start( format_args, msg ); DWORD rc = FormatMessage( FORMAT_MESSAGE_FROM_STRING, msg, 0, 0, last_err_msg, sizeof( last_err_msg ), &format_args ); va_end( format_args ); - if( rc == 0 ) { - php_error( E_ERROR, reinterpret_cast( INTERNAL_FORMAT_ERROR )); + if (rc == 0) { + php_error(E_ERROR, "%s", reinterpret_cast(INTERNAL_FORMAT_ERROR)); } - php_error( E_ERROR, last_err_msg ); + php_error(E_ERROR, "%s", last_err_msg); } namespace { @@ -393,7 +419,7 @@ unsigned int convert_string_from_default_encoding( _In_ unsigned int php_encodin if( required_len == 0 ) { return 0; } - utf16_out_string[ required_len ] = '\0'; + utf16_out_string[required_len] = '\0'; return required_len; } diff --git a/source/shared/globalization.h b/source/shared/globalization.h index 88e8d1a40..98619d61a 100644 --- a/source/shared/globalization.h +++ b/source/shared/globalization.h @@ -4,7 +4,7 @@ // Contents: Contains functions for handling Windows format strings // and UTF-16 on non-Windows platforms // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -362,7 +362,7 @@ class EncodingConverter { // Use fixed size buffer iteratively to determine final required length const size_t CCH_FIXED_SIZE = 256; - char fixed_buf[ CCH_FIXED_SIZE*sizeof(DestType) ]; + char fixed_buf[CCH_FIXED_SIZE*sizeof(DestType)] = {'\0'}; iconv_buffer dest( &fixed_buf[0], CCH_FIXED_SIZE ); diff --git a/source/shared/interlockedatomic.h b/source/shared/interlockedatomic.h index cc0163f0f..b8c04643c 100644 --- a/source/shared/interlockedatomic.h +++ b/source/shared/interlockedatomic.h @@ -4,7 +4,7 @@ // Contents: Contains a portable abstraction for interlocked, atomic // operations on int32_t and pointer types. // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/interlockedatomic_gcc.h b/source/shared/interlockedatomic_gcc.h index e8c8e5bb2..6977ff229 100644 --- a/source/shared/interlockedatomic_gcc.h +++ b/source/shared/interlockedatomic_gcc.h @@ -4,7 +4,7 @@ // Contents: Contains a portable abstraction for interlocked, atomic // operations on int32_t and pointer types. // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/interlockedslist.h b/source/shared/interlockedslist.h index bf2bc9ca2..6aa43fb00 100644 --- a/source/shared/interlockedslist.h +++ b/source/shared/interlockedslist.h @@ -4,7 +4,7 @@ // Contents: Contains a portable abstraction for interlocked, singly // linked list. // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/localization.hpp b/source/shared/localization.hpp index 2ec13e09d..79bd860e2 100644 --- a/source/shared/localization.hpp +++ b/source/shared/localization.hpp @@ -3,7 +3,7 @@ // // Contents: Contains portable classes for localization // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/localizationimpl.cpp b/source/shared/localizationimpl.cpp index 75251eb6d..669462abc 100644 --- a/source/shared/localizationimpl.cpp +++ b/source/shared/localizationimpl.cpp @@ -5,7 +5,7 @@ // Must be included in one c/cpp file per binary // A build error will occur if this inclusion policy is not followed // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/msodbcsql.h b/source/shared/msodbcsql.h index 3a759252e..f4912b118 100644 --- a/source/shared/msodbcsql.h +++ b/source/shared/msodbcsql.h @@ -20,7 +20,7 @@ // pecuniary loss) arising out of the use of or inability to use // this SDK, even if Microsoft has been advised of the possibility // of such damages. -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -92,6 +92,7 @@ #define SQL_COPT_SS_TRUSTEDCMKPATHS (SQL_COPT_SS_BASE_EX+13)// List of trusted CMK paths #define SQL_COPT_SS_CEKCACHETTL (SQL_COPT_SS_BASE_EX+14)// Symmetric Key Cache TTL #define SQL_COPT_SS_AUTHENTICATION (SQL_COPT_SS_BASE_EX+15)// The authentication method used for the connection +#define SQL_COPT_SS_ACCESS_TOKEN (SQL_COPT_SS_BASE_EX+16)// The authentication access token used for the connection // SQLColAttributes driver specific defines. // SQLSetDescField/SQLGetDescField driver specific defines. @@ -370,6 +371,12 @@ #pragma warning(disable:4200) #endif +typedef struct AccessToken +{ + unsigned int dataSize; + char data[]; +} ACCESSTOKEN; + // Keystore Provider interface definition typedef struct CEKeystoreContext { diff --git a/source/shared/sal_def.h b/source/shared/sal_def.h index 78478eaa1..8d5b785c3 100644 --- a/source/shared/sal_def.h +++ b/source/shared/sal_def.h @@ -3,7 +3,7 @@ // // Contents: Contains the minimal definitions to build on non-Windows platforms // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/typedefs_for_linux.h b/source/shared/typedefs_for_linux.h index dc3b4ca5b..574dc51a0 100644 --- a/source/shared/typedefs_for_linux.h +++ b/source/shared/typedefs_for_linux.h @@ -1,7 +1,7 @@ //--------------------------------------------------------------------------------------------------------------------------------- // File: typedefs_for_linux.h // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/version.h b/source/shared/version.h index 7d6554431..0ad9dcd14 100644 --- a/source/shared/version.h +++ b/source/shared/version.h @@ -4,7 +4,7 @@ // File: version.h // Contents: Version number constants // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -26,12 +26,12 @@ // Increase Minor with backward compatible new functionalities and API changes. // Increase Patch for backward compatible fixes. #define SQLVERSION_MAJOR 5 -#define SQLVERSION_MINOR 3 +#define SQLVERSION_MINOR 4 #define SQLVERSION_PATCH 0 #define SQLVERSION_BUILD 0 // For previews, set this constant to 1. Otherwise, set it to 0 -#define PREVIEW 0 +#define PREVIEW 1 #define SEMVER_PRERELEASE // Semantic versioning build metadata, build meta data is not counted in precedence order. diff --git a/source/shared/xplat.h b/source/shared/xplat.h index baa393e22..8e113a5cb 100644 --- a/source/shared/xplat.h +++ b/source/shared/xplat.h @@ -3,7 +3,7 @@ // // Contents: include for definition of Windows types for non-Windows platforms // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/xplat_intsafe.h b/source/shared/xplat_intsafe.h index 1baa473a7..03706dd36 100644 --- a/source/shared/xplat_intsafe.h +++ b/source/shared/xplat_intsafe.h @@ -4,7 +4,7 @@ // Contents: This module defines helper functions to prevent // integer overflow bugs. // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/xplat_winerror.h b/source/shared/xplat_winerror.h index 44eb7c844..a5bdf6415 100644 --- a/source/shared/xplat_winerror.h +++ b/source/shared/xplat_winerror.h @@ -3,7 +3,7 @@ // // Contents: Contains the minimal definitions to build on non-Windows platforms // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/xplat_winnls.h b/source/shared/xplat_winnls.h index 36aceae16..274263107 100644 --- a/source/shared/xplat_winnls.h +++ b/source/shared/xplat_winnls.h @@ -3,7 +3,7 @@ // // Contents: Contains the minimal definitions to build on non-Windows platforms // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/sqlsrv/config.m4 b/source/sqlsrv/config.m4 index 6b4190665..c0e4d3af8 100644 --- a/source/sqlsrv/config.m4 +++ b/source/sqlsrv/config.m4 @@ -4,7 +4,7 @@ dnl dnl Contents: the code that will go into the configure script, indicating options, dnl external libraries and includes, and what source files are to be compiled. dnl -dnl Microsoft Drivers 5.3 for PHP for SQL Server +dnl Microsoft Drivers 5.4 for PHP for SQL Server dnl Copyright(c) Microsoft Corporation dnl All rights reserved. dnl MIT License diff --git a/source/sqlsrv/config.w32 b/source/sqlsrv/config.w32 index 449789c4b..b6c2b1b1a 100644 --- a/source/sqlsrv/config.w32 +++ b/source/sqlsrv/config.w32 @@ -3,7 +3,7 @@ // // Contents: JScript build configuration used by buildconf.bat // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -35,6 +35,9 @@ if( PHP_SQLSRV != "no" ) { ADD_FLAG( "CFLAGS_SQLSRV", "/EHsc" ); ADD_FLAG( "CFLAGS_SQLSRV", "/GS" ); ADD_FLAG( "CFLAGS_SQLSRV", "/Zi" ); + if (VCVERS >= 1913) { + ADD_FLAG("CFLAGS_SQLSRV", "/Qspectre"); + } if (PHP_DEBUG != "yes") ADD_FLAG( "CFLAGS_SQLSRV", "/guard:cf /O2" ); EXTENSION("sqlsrv", sqlsrv_src_class , PHP_SQLSRV_SHARED, "/DZEND_ENABLE_STATIC_TSRMLS_CACHE=1"); } else { diff --git a/source/sqlsrv/conn.cpp b/source/sqlsrv/conn.cpp index 7bf805089..dcfc755e2 100644 --- a/source/sqlsrv/conn.cpp +++ b/source/sqlsrv/conn.cpp @@ -3,7 +3,7 @@ // // Contents: Routines that use connection handles // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -173,6 +173,7 @@ namespace SSStmtOptionNames { const char SEND_STREAMS_AT_EXEC[] = "SendStreamParamsAtExec"; const char SCROLLABLE[] = "Scrollable"; const char CLIENT_BUFFER_MAX_SIZE[] = INI_BUFFERED_QUERY_LIMIT; + const char DATE_AS_STRING[] = "ReturnDatesAsStrings"; } namespace SSConnOptionNames { @@ -180,6 +181,7 @@ namespace SSConnOptionNames { // most of these strings are the same for both the sqlsrv_connect connection option // and the name put into the connection string. MARS is the only one that's different. const char APP[] = "APP"; +const char AccessToken[] = "AccessToken"; const char ApplicationIntent[] = "ApplicationIntent"; const char AttachDBFileName[] = "AttachDbFileName"; const char Authentication[] = "Authentication"; @@ -242,6 +244,12 @@ const stmt_option SS_STMT_OPTS[] = { SQLSRV_STMT_OPTION_CLIENT_BUFFER_MAX_SIZE, std::unique_ptr( new stmt_option_buffered_query_limit ) }, + { + SSStmtOptionNames::DATE_AS_STRING, + sizeof( SSStmtOptionNames::DATE_AS_STRING ), + SQLSRV_STMT_OPTION_DATE_AS_STRING, + std::unique_ptr( new stmt_option_date_as_string ) + }, { NULL, 0, SQLSRV_STMT_OPTION_INVALID, std::unique_ptr{} }, }; @@ -257,6 +265,15 @@ const connection_option SS_CONN_OPTS[] = { CONN_ATTR_STRING, conn_str_append_func::func }, + { + SSConnOptionNames::AccessToken, + sizeof( SSConnOptionNames::AccessToken ), + SQLSRV_CONN_OPTION_ACCESS_TOKEN, + ODBCConnOptions::AccessToken, + sizeof( ODBCConnOptions::AccessToken), + CONN_ATTR_STRING, + access_token_set_func::func + }, { SSConnOptionNames::ApplicationIntent, sizeof( SSConnOptionNames::ApplicationIntent ), @@ -978,7 +995,7 @@ PHP_FUNCTION( sqlsrv_prepare ) // Initialize the options array to be passed to the core layer ALLOC_HASHTABLE( ss_stmt_options_ht ); - core::sqlsrv_zend_hash_init( *conn , ss_stmt_options_ht, 3 /* # of buckets */, + core::sqlsrv_zend_hash_init( *conn , ss_stmt_options_ht, 5 /* # of buckets */, ZVAL_PTR_DTOR, 0 /*persistent*/ TSRMLS_CC ); validate_stmt_options( *conn, options_z, ss_stmt_options_ht TSRMLS_CC ); @@ -1101,7 +1118,7 @@ PHP_FUNCTION( sqlsrv_query ) // Initialize the options array to be passed to the core layer ALLOC_HASHTABLE( ss_stmt_options_ht ); - core::sqlsrv_zend_hash_init( *conn , ss_stmt_options_ht, 3 /* # of buckets */, ZVAL_PTR_DTOR, + core::sqlsrv_zend_hash_init( *conn , ss_stmt_options_ht, 5 /* # of buckets */, ZVAL_PTR_DTOR, 0 /*persistent*/ TSRMLS_CC ); validate_stmt_options( *conn, options_z, ss_stmt_options_ht TSRMLS_CC ); @@ -1234,12 +1251,12 @@ void sqlsrv_conn_close_stmts( _Inout_ ss_sqlsrv_conn* conn TSRMLS_DC ) int get_conn_option_key( _Inout_ sqlsrv_context& ctx, _In_ zend_string* key, _In_ size_t key_len, _Inout_ zval const* value_z TSRMLS_DC ) { - for( int i=0; SS_CONN_OPTS[ i ].conn_option_key != SQLSRV_CONN_OPTION_INVALID; ++i ) + for( int i=0; SS_CONN_OPTS[i].conn_option_key != SQLSRV_CONN_OPTION_INVALID; ++i ) { - if( key_len == SS_CONN_OPTS[ i ].sqlsrv_len && !stricmp( ZSTR_VAL( key ), SS_CONN_OPTS[ i ].sqlsrv_name )) { + if( key_len == SS_CONN_OPTS[i].sqlsrv_len && !stricmp( ZSTR_VAL( key ), SS_CONN_OPTS[i].sqlsrv_name )) { - switch( SS_CONN_OPTS[ i ].value_type ) { + switch( SS_CONN_OPTS[i].value_type ) { case CONN_ATTR_BOOL: // bool attributes can be either strings to be appended to the connection string @@ -1250,7 +1267,7 @@ int get_conn_option_key( _Inout_ sqlsrv_context& ctx, _In_ zend_string* key, _In case CONN_ATTR_INT: { CHECK_CUSTOM_ERROR( (Z_TYPE_P( value_z ) != IS_LONG ), ctx, SQLSRV_ERROR_INVALID_OPTION_TYPE_INT, - SS_CONN_OPTS[ i ].sqlsrv_name ) + SS_CONN_OPTS[i].sqlsrv_name ) { throw ss::SSException(); } @@ -1259,7 +1276,7 @@ int get_conn_option_key( _Inout_ sqlsrv_context& ctx, _In_ zend_string* key, _In case CONN_ATTR_STRING: { CHECK_CUSTOM_ERROR( Z_TYPE_P( value_z ) != IS_STRING, ctx, SQLSRV_ERROR_INVALID_OPTION_TYPE_STRING, - SS_CONN_OPTS[ i ].sqlsrv_name ) { + SS_CONN_OPTS[i].sqlsrv_name ) { throw ss::SSException(); } @@ -1268,7 +1285,7 @@ int get_conn_option_key( _Inout_ sqlsrv_context& ctx, _In_ zend_string* key, _In size_t value_len = Z_STRLEN_P( value_z ); bool escaped = core_is_conn_opt_value_escaped( value, value_len ); - CHECK_CUSTOM_ERROR( !escaped, ctx, SS_SQLSRV_ERROR_CONNECT_BRACES_NOT_ESCAPED, SS_CONN_OPTS[ i ].sqlsrv_name ) { + CHECK_CUSTOM_ERROR( !escaped, ctx, SS_SQLSRV_ERROR_CONNECT_BRACES_NOT_ESCAPED, SS_CONN_OPTS[i].sqlsrv_name ) { throw ss::SSException(); } @@ -1278,7 +1295,7 @@ int get_conn_option_key( _Inout_ sqlsrv_context& ctx, _In_ zend_string* key, _In valid = core_is_authentication_option_valid( value, value_len ); } - CHECK_CUSTOM_ERROR( !valid, ctx, SS_SQLSRV_ERROR_INVALID_AUTHENTICATION_OPTION, SS_CONN_OPTS[ i ].sqlsrv_name ) { + CHECK_CUSTOM_ERROR( !valid, ctx, SS_SQLSRV_ERROR_INVALID_AUTHENTICATION_OPTION, SS_CONN_OPTS[i].sqlsrv_name ) { throw ss::SSException(); } @@ -1287,7 +1304,7 @@ int get_conn_option_key( _Inout_ sqlsrv_context& ctx, _In_ zend_string* key, _In } } - return SS_CONN_OPTS[ i ].conn_option_key; + return SS_CONN_OPTS[i].conn_option_key; } } return SQLSRV_CONN_OPTION_INVALID; @@ -1295,10 +1312,10 @@ int get_conn_option_key( _Inout_ sqlsrv_context& ctx, _In_ zend_string* key, _In int get_stmt_option_key( _In_ zend_string* key, _In_ size_t key_len TSRMLS_DC ) { - for( int i = 0; SS_STMT_OPTS[ i ].key != SQLSRV_STMT_OPTION_INVALID; ++i ) + for( int i = 0; SS_STMT_OPTS[i].key != SQLSRV_STMT_OPTION_INVALID; ++i ) { - if( key_len == SS_STMT_OPTS[ i ].name_len && !stricmp( ZSTR_VAL( key ), SS_STMT_OPTS[ i ].name )) { - return SS_STMT_OPTS[ i ].key; + if( key_len == SS_STMT_OPTS[i].name_len && !stricmp( ZSTR_VAL( key ), SS_STMT_OPTS[i].name )) { + return SS_STMT_OPTS[i].key; } } return SQLSRV_STMT_OPTION_INVALID; diff --git a/source/sqlsrv/init.cpp b/source/sqlsrv/init.cpp index bb8ab04b4..45dfb0e58 100644 --- a/source/sqlsrv/init.cpp +++ b/source/sqlsrv/init.cpp @@ -2,7 +2,7 @@ // File: init.cpp // Contents: initialization routines for the extension // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -537,9 +537,9 @@ PHP_MINIT_FUNCTION(sqlsrv) g_ss_errors_ht = reinterpret_cast( pemalloc( sizeof( HashTable ), 1 )); ::zend_hash_init( g_ss_errors_ht, 50, NULL, sqlsrv_error_const_dtor /*pDestructor*/, 1 ); - for( int i = 0; SS_ERRORS[ i ].error_code != UINT_MAX; ++i ) { - if (NULL == ::zend_hash_index_update_mem( g_ss_errors_ht, SS_ERRORS[ i ].error_code, - &( SS_ERRORS[ i ].sqlsrv_error ), sizeof( SS_ERRORS[ i ].sqlsrv_error ))) { + for( int i = 0; SS_ERRORS[i].error_code != UINT_MAX; ++i ) { + if (NULL == ::zend_hash_index_update_mem( g_ss_errors_ht, SS_ERRORS[i].error_code, + &( SS_ERRORS[i].sqlsrv_error ), sizeof( SS_ERRORS[i].sqlsrv_error ))) { LOG( SEV_ERROR, "%1!s!: Failed to insert data into sqlsrv errors hashtable.", _FN_ ); return FAILURE; } diff --git a/source/sqlsrv/php_sqlsrv.h b/source/sqlsrv/php_sqlsrv.h index 6c5e7b015..1816942ac 100644 --- a/source/sqlsrv/php_sqlsrv.h +++ b/source/sqlsrv/php_sqlsrv.h @@ -8,7 +8,7 @@ // // Comments: Also contains "internal" declarations shared across source files. // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/sqlsrv/stmt.cpp b/source/sqlsrv/stmt.cpp index ac334cb9b..3bbd4af65 100644 --- a/source/sqlsrv/stmt.cpp +++ b/source/sqlsrv/stmt.cpp @@ -3,7 +3,7 @@ // // Contents: Routines that use statement handles // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -129,6 +129,10 @@ ss_sqlsrv_stmt::ss_sqlsrv_stmt( _In_ sqlsrv_conn* c, _In_ SQLHANDLE handle, _In_ fetch_fields_count ( 0 ) { core_sqlsrv_set_buffered_query_limit( this, SQLSRV_G( buffered_query_limit ) TSRMLS_CC ); + + // initialize date_as_string based on the corresponding connection option + ss_sqlsrv_conn* ss_conn = static_cast(conn); + date_as_string = ss_conn->date_as_string; } ss_sqlsrv_stmt::~ss_sqlsrv_stmt( void ) @@ -137,7 +141,7 @@ ss_sqlsrv_stmt::~ss_sqlsrv_stmt( void ) for( int i=0; i < fetch_fields_count; ++i ) { - sqlsrv_free( fetch_field_names[ i ].name ); + sqlsrv_free( fetch_field_names[i].name ); } sqlsrv_free( fetch_field_names ); } @@ -155,7 +159,7 @@ void ss_sqlsrv_stmt::new_result_set( TSRMLS_D ) for( int i=0; i < fetch_fields_count; ++i ) { - sqlsrv_free( fetch_field_names[ i ].name ); + sqlsrv_free( fetch_field_names[i].name ); } sqlsrv_free( fetch_field_names ); } @@ -230,7 +234,7 @@ sqlsrv_phptype ss_sqlsrv_stmt::sql_type_to_php_type( _In_ SQLINTEGER sql_type, _ case SQL_SS_TIMESTAMPOFFSET: case SQL_SS_TIME2: case SQL_TYPE_TIMESTAMP: - if( reinterpret_cast( this->conn )->date_as_string ) { + if (this->date_as_string) { ss_phptype.typeinfo.type = SQLSRV_PHPTYPE_STRING; ss_phptype.typeinfo.encoding = this->conn->encoding(); } @@ -719,7 +723,7 @@ PHP_FUNCTION( sqlsrv_num_fields ) } } -// sqlsrv_fetch_object( resource $stmt [, string $className [, array $ctorParams ]]) +// sqlsrv_fetch_object( resource $stmt [, string $className [, array $ctorParams]]) // // Retrieves the next row of data as a PHP object. // @@ -889,7 +893,9 @@ PHP_FUNCTION( sqlsrv_fetch_object ) fci.object = Z_OBJ_P( &retval_z ); memset( &fcic, 0, sizeof( fcic )); +#if PHP_VERSION_ID < 70300 fcic.initialized = 1; +#endif fcic.function_handler = class_entry->constructor; fcic.calling_scope = class_entry; @@ -1676,8 +1682,7 @@ sqlsrv_phptype determine_sqlsrv_php_type( _In_ ss_sqlsrv_stmt const* stmt, _In_ case SQL_SS_TIME2: case SQL_TYPE_TIMESTAMP: { - ss_sqlsrv_conn* c = static_cast( stmt->conn ); - if( c->date_as_string ) { + if (stmt->date_as_string) { sqlsrv_phptype.typeinfo.type = SQLSRV_PHPTYPE_STRING; sqlsrv_phptype.typeinfo.encoding = stmt->encoding(); } @@ -1776,7 +1781,7 @@ void fetch_fields_common( _Inout_ ss_sqlsrv_stmt* stmt, _In_ zend_long fetch_typ SQLLEN field_name_len = 0; SQLSMALLINT field_name_len_w = 0; - SQLWCHAR field_name_w[( SS_MAXCOLNAMELEN + 1 ) * 2 ] = { L'\0' }; + SQLWCHAR field_name_w[( SS_MAXCOLNAMELEN + 1 ) * 2] = {L'\0'}; sqlsrv_malloc_auto_ptr field_name; sqlsrv_malloc_auto_ptr field_names; field_names = static_cast( sqlsrv_malloc( num_cols * sizeof( sqlsrv_fetch_field_name ))); @@ -1806,10 +1811,14 @@ void fetch_fields_common( _Inout_ ss_sqlsrv_stmt* stmt, _In_ zend_long fetch_typ field_names.transferred(); } - int zr = array_init( &fields ); - CHECK_ZEND_ERROR( zr, stmt, SQLSRV_ERROR_ZEND_HASH ) { - throw ss::SSException(); - } + int zr = SUCCESS; +#if PHP_VERSION_ID < 70300 + CHECK_ZEND_ERROR(array_init(&fields), stmt, SQLSRV_ERROR_ZEND_HASH) { + throw ss::SSException(); + } +#else + array_init(&fields); +#endif for( int i = 0; i < num_cols; ++i ) { SQLLEN field_len = -1; @@ -1836,7 +1845,7 @@ void fetch_fields_common( _Inout_ ss_sqlsrv_stmt* stmt, _In_ zend_long fetch_typ throw ss::SSException(); } - if( stmt->fetch_field_names[ i ].len > 1 || allow_empty_field_names ) { + if( stmt->fetch_field_names[i].len > 1 || allow_empty_field_names ) { zr = add_assoc_zval( &fields, stmt->fetch_field_names[i].name, &field ); CHECK_ZEND_ERROR( zr, stmt, SQLSRV_ERROR_ZEND_HASH ) { diff --git a/source/sqlsrv/template.rc b/source/sqlsrv/template.rc index ffee85372..d70a93a9d 100644 --- a/source/sqlsrv/template.rc +++ b/source/sqlsrv/template.rc @@ -3,7 +3,7 @@ // // Contents: Version resource // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/sqlsrv/util.cpp b/source/sqlsrv/util.cpp index bc26658c0..aab5e2ebd 100644 --- a/source/sqlsrv/util.cpp +++ b/source/sqlsrv/util.cpp @@ -5,7 +5,7 @@ // // Comments: Mostly error handling and some type handling // -// Microsoft Drivers 5.3 for PHP for SQL Server +// Microsoft Drivers 5.4 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -28,7 +28,7 @@ unsigned int current_log_subsystem = LOG_UTIL; // buffer used to hold a formatted log message prior to actually logging it. const int LOG_MSG_SIZE = 2048; -char log_msg[ LOG_MSG_SIZE ]; +char log_msg[LOG_MSG_SIZE] = {'\0'}; // internal error that says that FormatMessage failed SQLCHAR INTERNAL_FORMAT_ERROR[] = "An internal error occurred. FormatMessage failed writing an error message."; @@ -420,6 +420,14 @@ ss_error SS_ERRORS[] = { SQLSRV_ERROR_KEYSTORE_INVALID_VALUE, { IMSSP, (SQLCHAR*) "Invalid value for loading Azure Key Vault.", -114, false} }, + { + SQLSRV_ERROR_INVALID_OPTION_WITH_ACCESS_TOKEN, + { IMSSP, (SQLCHAR*) "When using Azure AD Access Token, the connection string must not contain UID, PWD, or Authentication keywords.", -115, false} + }, + { + SQLSRV_ERROR_EMPTY_ACCESS_TOKEN, + { IMSSP, (SQLCHAR*) "The Azure AD Access Token is empty. Expected a byte string.", -116, false} + }, // terminate the list of errors/warnings { UINT_MAX, {} } @@ -498,18 +506,21 @@ PHP_FUNCTION( sqlsrv_errors ) LOG_FUNCTION( "sqlsrv_errors" ); - if(( zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "|l", &flags ) == FAILURE ) || - ( flags != SQLSRV_ERR_ALL && flags != SQLSRV_ERR_ERRORS && flags != SQLSRV_ERR_WARNINGS )) { - LOG( SEV_ERROR, "An invalid parameter was passed to %1!s!.", _FN_ ); - RETURN_FALSE; - } - int result; - zval err_z; - ZVAL_UNDEF( &err_z ); - result = array_init( &err_z ); - if( result == FAILURE ) { - RETURN_FALSE; - } + if(( zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "|l", &flags ) == FAILURE ) || + ( flags != SQLSRV_ERR_ALL && flags != SQLSRV_ERR_ERRORS && flags != SQLSRV_ERR_WARNINGS )) { + LOG( SEV_ERROR, "An invalid parameter was passed to %1!s!.", _FN_ ); + RETURN_FALSE; + } + zval err_z; + ZVAL_UNDEF(&err_z); +#if PHP_VERSION_ID < 70300 + if (array_init(&err_z) == FAILURE) { + RETURN_FALSE; + } +#else + array_init(&err_z); +#endif + if( flags == SQLSRV_ERR_ALL || flags == SQLSRV_ERR_ERRORS ) { if( Z_TYPE( SQLSRV_G( errors )) == IS_ARRAY && !sqlsrv_merge_zend_hash( &err_z, &SQLSRV_G( errors ) TSRMLS_CC )) { zval_ptr_dtor(&err_z); @@ -746,10 +757,13 @@ sqlsrv_error_const* get_error_message( _In_ unsigned int sqlsrv_error_code ) { void copy_error_to_zval( _Inout_ zval* error_z, _In_ sqlsrv_error_const* error, _Inout_ zval* reported_chain, _Inout_ zval* ignored_chain, _In_ bool warning TSRMLS_DC ) { - - if( array_init( error_z ) == FAILURE ) { +#if PHP_VERSION_ID < 70300 + if (array_init(error_z) == FAILURE) { DIE( "Fatal error during error processing" ); } +#else + array_init(error_z); +#endif // sqlstate zval temp; @@ -828,7 +842,6 @@ bool handle_errors_and_warnings( _Inout_ sqlsrv_context& ctx, _Inout_ zval* repo size_t prev_reported_cnt = 0; bool reported_chain_was_null = false; bool ignored_chain_was_null = false; - int zr = SUCCESS; zval error_z; ZVAL_UNDEF(&error_z); sqlsrv_error_auto_ptr error; @@ -837,10 +850,13 @@ bool handle_errors_and_warnings( _Inout_ sqlsrv_context& ctx, _Inout_ zval* repo if( Z_TYPE_P( reported_chain ) == IS_NULL ) { reported_chain_was_null = true; - zr = array_init( reported_chain ); - if( zr == FAILURE ) { - DIE( "Fatal error in handle_errors_and_warnings" ); +#if PHP_VERSION_ID < 70300 + if (array_init(reported_chain) == FAILURE) { + DIE( "Fatal error during error processing" ); } +#else + array_init(reported_chain); +#endif } else { prev_reported_cnt = zend_hash_num_elements( Z_ARRVAL_P( reported_chain )); @@ -851,11 +867,14 @@ bool handle_errors_and_warnings( _Inout_ sqlsrv_context& ctx, _Inout_ zval* repo if( Z_TYPE_P( ignored_chain ) == IS_NULL ) { - ignored_chain_was_null = true; - zr = array_init( ignored_chain ); - if( zr == FAILURE ) { + ignored_chain_was_null = true; +#if PHP_VERSION_ID < 70300 + if (array_init(ignored_chain) == FAILURE) { DIE( "Fatal error in handle_errors_and_warnings" ); } +#else + array_init( ignored_chain ); +#endif } } diff --git a/test/functional/pdo_sqlsrv/access_token.inc b/test/functional/pdo_sqlsrv/access_token.inc new file mode 100644 index 000000000..dbb2f7786 --- /dev/null +++ b/test/functional/pdo_sqlsrv/access_token.inc @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/test/functional/pdo_sqlsrv/pdo_azure_ad_access_token.phpt b/test/functional/pdo_sqlsrv/pdo_azure_ad_access_token.phpt new file mode 100644 index 000000000..f468ffd6e --- /dev/null +++ b/test/functional/pdo_sqlsrv/pdo_azure_ad_access_token.phpt @@ -0,0 +1,157 @@ +--TEST-- +Test some basics of Azure AD Access Token support +--DESCRIPTION-- +This test also expects certain exceptions to be thrown under some conditions. +--SKIPIF-- + +--FILE-- +getMessage(), $expectedError) === false) { + echo "AzureAD access token test: expected to fail with $msg\n"; + + print_r($exception->getMessage()); + echo "\n"; + } +} + +function connectWithEmptyAccessToken($server) +{ + $dummyToken = ''; + $expectedError = 'The Azure AD Access Token is empty. Expected a byte string.'; + + $connectionInfo = "AccessToken = $dummyToken;"; + $testCase = 'empty token'; + try { + $conn = new PDO("sqlsrv:server = $server; $connectionInfo"); + echo $message . $testCase . PHP_EOL; + } catch(PDOException $e) { + verifyErrorMessage($e, $expectedError, $testCase); + } + unset($connectionInfo); +} + +function connectWithInvalidOptions($server) +{ + $dummyToken = 'abcde'; + $expectedError = 'When using Azure AD Access Token, the connection string must not contain UID, PWD, or Authentication keywords.'; + $message = 'AzureAD access token test: expected to fail with '; + + $uid = ''; + $connectionInfo = "AccessToken = $dummyToken;"; + $testCase = 'empty UID provided'; + try { + $conn = new PDO("sqlsrv:server = $server; $connectionInfo", $uid); + echo $message . $testCase . PHP_EOL; + } catch(PDOException $e) { + verifyErrorMessage($e, $expectedError, $testCase); + } + unset($connectionInfo); + + $pwd = ''; + $connectionInfo = "AccessToken = $dummyToken;"; + $testCase = 'empty PWD provided'; + try { + $conn = new PDO("sqlsrv:server = $server; $connectionInfo", null, $pwd); + echo $message . $testCase . PHP_EOL; + } catch(PDOException $e) { + verifyErrorMessage($e, $expectedError, $testCase); + } + unset($connectionInfo); + + $uid = 'uid'; + $connectionInfo = "AccessToken = $dummyToken;"; + $testCase = 'UID provided'; + try { + $conn = new PDO("sqlsrv:server = $server; $connectionInfo", $uid); + echo $message . $testCase . PHP_EOL; + } catch(PDOException $e) { + verifyErrorMessage($e, $expectedError, $testCase); + } + unset($connectionInfo); + + $pwd = ''; + $connectionInfo = "AccessToken = $dummyToken;"; + $testCase = 'PWD provided'; + try { + $conn = new PDO("sqlsrv:server = $server; $connectionInfo", null, $pwd); + echo $message . $testCase . PHP_EOL; + } catch(PDOException $e) { + verifyErrorMessage($e, $expectedError, $testCase); + } + unset($connectionInfo); + + $connectionInfo = "Authentication = SqlPassword; AccessToken = $dummyToken;"; + $testCase = 'Authentication keyword'; + try { + $conn = new PDO("sqlsrv:server = $server; $connectionInfo"); + echo $message . $testCase . PHP_EOL; + } catch(PDOException $e) { + verifyErrorMessage($e, $expectedError, $testCase); + } + unset($connectionInfo); +} + +function simpleTest($conn) +{ + // Create table + $tableName = 'Simple'; + $col1 = 'Some simple string value'; + + dropTable($conn, $tableName); + + $query = "CREATE TABLE $tableName(ID INT IDENTITY(1,1), COL1 VARCHAR(25))"; + $stmt = $conn->query($query); + + // Insert one row + $query = "INSERT INTO $tableName VALUES ('$col1')"; + $stmt = $conn->query($query); + + // Fetch data + $query = "SELECT * FROM $tableName"; + $stmt = $conn->query($query); + + $result = $stmt->fetch(PDO::FETCH_NUM); + $id = $result[0]; + if ($id != 1) { + echo "AzureAD access token test: fetched id $id unexpected\n"; + } + + $field = $result[1]; + if ($field !== $col1) { + echo "AzureAD access token test: fetched value $field unexpected\n"; + } + + dropTable($conn, $tableName); +} + +// First test some error conditions +require_once('MsSetup.inc'); +connectWithInvalidOptions($server); + +// Then, test with an empty access token +connectWithEmptyAccessToken($server); + +// Next, test with a valid access token and perform some simple tasks +require_once('access_token.inc'); +try { + if ($adServer != 'TARGET_AD_SERVER' && $accToken != 'TARGET_ACCESS_TOKEN') { + $connectionInfo = "Database = $adDatabase; AccessToken = $accToken;"; + $conn = new PDO("sqlsrv:server = $adServer; $connectionInfo"); + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE, true); + simpleTest($conn); + unset($conn); + } +} catch(PDOException $e) { + print_r( $e->getMessage() ); + echo PHP_EOL; +} + +echo "Done\n"; +?> +--EXPECT-- +Done \ No newline at end of file diff --git a/test/functional/pdo_sqlsrv/pdo_fetch_datetime_as_output_param.phpt b/test/functional/pdo_sqlsrv/pdo_fetch_datetime_as_output_param.phpt new file mode 100644 index 000000000..9cc1bc3b3 --- /dev/null +++ b/test/functional/pdo_sqlsrv/pdo_fetch_datetime_as_output_param.phpt @@ -0,0 +1,87 @@ +--TEST-- +Test attribute PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE and datetimes as output params +--DESCRIPTION-- +Do not support returning DateTime objects as output parameters. Setting attribute PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE to true should have no effect. +--SKIPIF-- + +--FILE-- + false); + $conn = connect("", $attr); + + // Generate input values for the test table + $query = 'SELECT SYSDATETIME(), SYSDATETIMEOFFSET(), CONVERT(time, CURRENT_TIMESTAMP)'; + $stmt = $conn->query($query); + $values = $stmt->fetch(PDO::FETCH_NUM); + + // create a test table with the above input date time values + $tableName = "TestDateTimeOutParam"; + $columns = array('c1', 'c2', 'c3'); + $dataTypes = array("datetime2", "datetimeoffset", "time"); + + $colMeta = array(new ColumnMeta($dataTypes[0], $columns[0]), + new ColumnMeta($dataTypes[1], $columns[1]), + new ColumnMeta($dataTypes[2], $columns[2])); + createTable($conn, $tableName, $colMeta); + + $query = "INSERT INTO $tableName VALUES(?, ?, ?)"; + $stmt = $conn->prepare($query); + for ($i = 0; $i < count($columns); $i++) { + $stmt->bindParam($i+1, $values[$i], PDO::PARAM_LOB); + } + $stmt->execute(); + + $lobException = 'An invalid PHP type was specified as an output parameter. DateTime objects, NULL values, and streams cannot be specified as output parameters.'; + + for ($i = 0; $i < count($columns); $i++) { + // create the stored procedure first + $storedProcName = "spDateTimeOutParam" . $i; + $procArgs = "@col $dataTypes[$i] OUTPUT"; + $procCode = "SELECT @col = $columns[$i] FROM $tableName"; + createProc($conn, $storedProcName, $procArgs, $procCode); + + // call stored procedure to retrieve output param type PDO::PARAM_STR + $dateStr = ''; + $outSql = getCallProcSqlPlaceholders($storedProcName, 1); + $options = array(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE => true); + $stmt = $conn->prepare($outSql, $options); + $stmt->bindParam(1, $dateStr, PDO::PARAM_STR, 1024); + $stmt->execute(); + + if ($dateStr != $values[$i]) { + echo "Expected $values[$i] for column ' . ($i+1) .' but got: "; + var_dump($dateStr); + } + + // for output param type PDO::PARAM_LOB it should fail with the correct exception + try { + $stmt->bindParam(1, $dateStr, PDO::PARAM_LOB, 1024); + $stmt->execute(); + echo "Expected this to fail\n"; + } catch (PDOException $e) { + $message = $e->getMessage(); + $matched = strpos($message, $lobException); + if (!$matched) { + var_dump($e->errorInfo); + } + } + + dropProc($conn, $storedProcName); + } + + dropTable($conn, $tableName); + echo "Done\n"; + + unset($stmt); + unset($conn); +} catch (PDOException $e) { + var_dump($e->errorInfo); +} +?> +--EXPECT-- +Done diff --git a/test/functional/pdo_sqlsrv/pdo_fetch_datetime_time_as_objects.phpt b/test/functional/pdo_sqlsrv/pdo_fetch_datetime_time_as_objects.phpt new file mode 100644 index 000000000..ab8ba5ece --- /dev/null +++ b/test/functional/pdo_sqlsrv/pdo_fetch_datetime_time_as_objects.phpt @@ -0,0 +1,238 @@ +--TEST-- +Test attribute PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE for date, time and datetime columns +--DESCRIPTION-- +Test attribute PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE for datetime, datetime2, +smalldatetime, datetimeoffset and time columns. The input values are based on current +timestamp and they are retrieved either as strings or date time objects. Note that the +existing attributes ATTR_STRINGIFY_FETCHES and SQLSRV_ATTR_FETCHES_NUMERIC_TYPE +should have no effect on data retrieval. +--SKIPIF-- + +--FILE-- +format('Y-m-d H:i:s.u'); + + // actual datetime value from date time object to string + $dtActual = date_format($dtObj, 'Y-m-d H:i:s.u'); + if ($dtActual != $dtExpected) { + echo "Expected $dtExpected for column $column but the actual value was $dtActual\n"; + } +} + +function runTest($conn, $query, $columns, $values, $useBuffer = false) +{ + // fetch the date time values as strings or date time objects + // prepare with or without buffered cursor + $options = array(); + if ($useBuffer) { + $options = array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL, + PDO::SQLSRV_ATTR_CURSOR_SCROLL_TYPE => PDO::SQLSRV_CURSOR_BUFFERED); + } + + // fetch_numeric off, fetch_datetime off + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE, false); + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, false); + $stmt = $conn->prepare($query, $options); + $stmt->execute(); + $obj = $stmt->fetch(PDO::FETCH_OBJ); + checkStringValues($obj, $columns, $values); + + // fetch_numeric off, fetch_datetime on + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE, false); + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, true); + $stmt = $conn->prepare($query, $options); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + checkDTObjectValues($row, $columns, $values, PDO::FETCH_ASSOC); + + // fetch_numeric on, fetch_datetime on + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE, true); + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, true); + $stmt = $conn->prepare($query, $options); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_BOTH); + checkDTObjectValues($row, $columns, $values, PDO::FETCH_BOTH); + + // ATTR_STRINGIFY_FETCHES should have no effect when fetching date time objects + // Setting it to true only converts numeric values to strings when fetching + // See http://www.php.net/manual/en/pdo.setattribute.php for details + // stringify on, fetch_numeric off, fetch_datetime on + $conn->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true); + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE, false); + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, true); + $stmt = $conn->prepare($query, $options); + $i = 0; + do { + $stmt->execute(); + $dtObj = $stmt->fetchColumn($i); + checkColumnDTValue($i, $columns[$i], $values, $dtObj); + } while (++$i < count($columns)); + + // reset stringify to off + // fetch_numeric off, fetch_datetime off + $conn->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false); + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, false); + $stmt = $conn->prepare($query, $options); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_OBJ); + checkStringValues($obj, $columns, $values); + + // conn attribute fetch_datetime on, but statement attribute fetch_datetime off -- + // expected strings to be returned because statement attribute overrides the + // connection attribute + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, true); + $stmt = $conn->prepare($query, $options); + $stmt->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, false); + $stmt->execute(); + $obj = $stmt->fetch(PDO::FETCH_OBJ); + checkStringValues($obj, $columns, $values); + + // conn attribute fetch_datetime unchanged, but statement attribute fetch_datetime on -- + // expected datetime objects to be returned (this time no need to prepare the statement) + $stmt->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, true); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + checkDTObjectValues($row, $columns, $values, PDO::FETCH_ASSOC); + + // likewise, conn attribute fetch_datetime off, but statement attribute + // fetch_datetime on -- expected datetime objects to be returned + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, false); + $stmt = $conn->prepare($query, $options); + $stmt->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, true); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_BOTH); + checkDTObjectValues($row, $columns, $values, PDO::FETCH_BOTH); + + // conn attribute fetch_datetime unchanged, but statement attribute fetch_datetime off -- + // expected strings to be returned (again no need to prepare the statement) + $stmt->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, false); + $stmt->execute(); + $obj = $stmt->fetch(PDO::FETCH_LAZY); + checkStringValues($obj, $columns, $values); + + // last test: set statement attribute fetch_datetime on with no change to + // prepared statement -- expected datetime objects to be returned + $stmt->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, true); + $stmt->execute(); + $i = 0; + do { + $stmt->execute(); + $dtObj = $stmt->fetchColumn($i); + checkColumnDTValue($i, $columns[$i], $values, $dtObj); + } while (++$i < count($columns)); + + // keep the same settings but test with FETCH_BOUND + for ($i = 0; $i < count($columns); $i++) { + $dateObj = null; + $stmt->execute(); + $stmt->bindColumn($i + 1, $dateObj, PDO::PARAM_LOB); + $row = $stmt->fetch(PDO::FETCH_BOUND); + checkColumnDTValue($i, $columns[$i], $values, $dateObj); + } + + // redo the test but with fetch_datetime off + // expected strings to be returned + $stmt->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, false); + for ($i = 0; $i < count($columns); $i++) { + $dateStr = null; + $stmt->execute(); + $stmt->bindColumn($i + 1, $dateStr); + $row = $stmt->fetch(PDO::FETCH_BOUND); + if ($dateStr != $values[$i]) { + $col = $columns[$i]; + echo "Expected $values[$i] for column $col but the bound value was: "; + var_dump($dateStr); + } + } +} + +try { + date_default_timezone_set('America/Los_Angeles'); + + $conn = connect(); + + // Generate input values for the test table + $query = 'SELECT CONVERT(date, SYSDATETIME()), SYSDATETIME(), + CONVERT(smalldatetime, SYSDATETIME()), + CONVERT(datetime, SYSDATETIME()), + SYSDATETIMEOFFSET(), + CONVERT(time, SYSDATETIME())'; + + $stmt = $conn->query($query); + $values = $stmt->fetch(PDO::FETCH_NUM); + + // create a test table with the above input date time values + $tableName = "TestDateTimeOffset"; + $columns = array('c1', 'c2', 'c3', 'c4', 'c5', 'c6'); + $dataTypes = array('date', 'datetime2', 'smalldatetime', 'datetime', 'datetimeoffset', 'time'); + + $colMeta = array(new ColumnMeta($dataTypes[0], $columns[0]), + new ColumnMeta($dataTypes[1], $columns[1]), + new ColumnMeta($dataTypes[2], $columns[2]), + new ColumnMeta($dataTypes[3], $columns[3]), + new ColumnMeta($dataTypes[4], $columns[4]), + new ColumnMeta($dataTypes[5], $columns[5])); + createTable($conn, $tableName, $colMeta); + + $query = "INSERT INTO $tableName VALUES(?, ?, ?, ?, ?, ?)"; + $stmt = $conn->prepare($query); + for ($i = 0; $i < count($columns); $i++) { + $stmt->bindParam($i+1, $values[$i], PDO::PARAM_LOB); + } + $stmt->execute(); + + $query = "SELECT * FROM $tableName"; + + runTest($conn, $query, $columns, $values); + runTest($conn, $query, $columns, $values, true); + + dropTable($conn, $tableName); + + echo "Done\n"; + + unset($stmt); + unset($conn); +} catch (PDOException $e) { + var_dump($e->errorInfo); +} +?> +--EXPECT-- +Done diff --git a/test/functional/pdo_sqlsrv/pdo_fetch_datetime_time_nulls.phpt b/test/functional/pdo_sqlsrv/pdo_fetch_datetime_time_nulls.phpt new file mode 100644 index 000000000..9bffdf751 --- /dev/null +++ b/test/functional/pdo_sqlsrv/pdo_fetch_datetime_time_nulls.phpt @@ -0,0 +1,163 @@ +--TEST-- +Test attribute PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE for datetime types with null values +--DESCRIPTION-- +Test attribute PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE for different datetime types with +null values. Whether retrieved as strings or date time objects should return NULLs. +--SKIPIF-- + +--FILE-- + PDO::CURSOR_SCROLL, + PDO::SQLSRV_ATTR_CURSOR_SCROLL_TYPE => PDO::SQLSRV_CURSOR_BUFFERED); + } + + // fetch_numeric off, fetch_datetime off + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE, false); + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, false); + $stmt = $conn->prepare($query, $options); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_NUM); + checkNullStrings($row, $columns); + + // fetch_numeric off, fetch_datetime on + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE, false); + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, true); + $stmt = $conn->prepare($query, $options); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + checkNullDTObjects($row, $columns, PDO::FETCH_ASSOC); + + // fetch_numeric on, fetch_datetime on + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE, true); + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, true); + $stmt = $conn->prepare($query, $options); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_BOTH); + checkNullDTObjects($row, $columns, PDO::FETCH_BOTH); + + // conn attribute fetch_datetime on, but statement attribute fetch_datetime off -- + // expected strings to be returned because statement attribute overrides the + // connection attribute + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, true); + $stmt = $conn->prepare($query, $options); + $stmt->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, false); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_NUM); + checkNullStrings($row, $columns); + + // conn attribute fetch_datetime unchanged, but statement attribute fetch_datetime on -- + // expected datetime objects to be returned (this time no need to prepare the statement) + $stmt->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, true); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + checkNullDTObjects($row, $columns, PDO::FETCH_ASSOC); + + // likewise, conn attribute fetch_datetime off, but statement attribute + // fetch_datetime on -- expected datetime objects to be returned + $conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, false); + $stmt = $conn->prepare($query, $options); + $stmt->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, true); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_BOTH); + checkNullDTObjects($row, $columns, PDO::FETCH_BOTH); + + // conn attribute fetch_datetime unchanged, but statement attribute fetch_datetime off -- + // expected strings to be returned (again no need to prepare the statement) + $stmt->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, false); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_NUM); + checkNullStrings($row, $columns); + + // last test: set statement attribute fetch_datetime on with no change to + // prepared statement -- expected datetime objects to be returned + $stmt->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, true); + $stmt->execute(); + $i = 0; + do { + $stmt->execute(); + $dtObj = $stmt->fetchColumn($i); + if (!is_null($dtObj)) { + echo "Expected NULL for column " . ($i + 1) . " but got: "; + var_dump($dtObj); + } + } while (++$i < count($columns)); +} + +try { + $conn = connect(); + + // create a test table + $tableName = "TestNullDateTime"; + $columns = array('c1', 'c2', 'c3', 'c4', 'c5', 'c6'); + $colMeta = array(new ColumnMeta('date', $columns[0]), + new ColumnMeta('datetime', $columns[1]), + new ColumnMeta('smalldatetime', $columns[2]), + new ColumnMeta('datetime2', $columns[3]), + new ColumnMeta('datetimeoffset', $columns[4]), + new ColumnMeta('time', $columns[5])); + createTable($conn, $tableName, $colMeta); + + $value = null; + $query = "INSERT INTO $tableName VALUES(?, ?, ?, ?, ?, ?)"; + $stmt = $conn->prepare($query); + for ($i = 0; $i < count($columns); $i++) { + $stmt->bindParam($i+1, $value, PDO::PARAM_NULL); + } + $stmt->execute(); + + $query = "SELECT * FROM $tableName"; + + runTest($conn, $query, $columns); + runTest($conn, $query, $columns, true); + + dropTable($conn, $tableName); + + echo "Done\n"; + + unset($stmt); + unset($conn); +} catch (PDOException $e) { + var_dump($e->errorInfo); +} +?> +--EXPECT-- +Done diff --git a/test/functional/pdo_sqlsrv/skipif_azure_ad_acess_token.inc b/test/functional/pdo_sqlsrv/skipif_azure_ad_acess_token.inc new file mode 100644 index 000000000..d59c02bf6 --- /dev/null +++ b/test/functional/pdo_sqlsrv/skipif_azure_ad_acess_token.inc @@ -0,0 +1,41 @@ +getAttribute(PDO::ATTR_CLIENT_VERSION)["DriverVer"]; +$msodbcsqlMaj = explode(".", $msodbcsqlVer)[0]; + +$isWin = (strtoupper(substr(php_uname('s'), 0, 3)) === 'WIN'); +if (!$isWin && $msodbcsqlMaj < 17) { + die("skip: Unsupported ODBC driver version"); +} + +// Now check SQL Server version - exclude this check if running on Azure +if (!$daasMode) { + $stmt = $conn->query("SELECT @@VERSION"); + if ($stmt) { + $ver_string = $stmt->fetch(PDO::FETCH_NUM)[0]; + } else { + die("skip Could not fetch SQL Server version during SKIPIF."); + } + + $version = explode(' ', $ver_string); + + if ($version[3] < '2016') { + die("skip: Wrong version of SQL Server, 2016 or later required"); + } +} + +?> diff --git a/test/functional/pdo_sqlsrv/skipif_version_less_than_2k14.inc b/test/functional/pdo_sqlsrv/skipif_version_less_than_2k14.inc index 10849b9b2..39d92e39e 100644 --- a/test/functional/pdo_sqlsrv/skipif_version_less_than_2k14.inc +++ b/test/functional/pdo_sqlsrv/skipif_version_less_than_2k14.inc @@ -7,13 +7,13 @@ if (!extension_loaded("pdo_sqlsrv")) { die("skip Extension not loaded"); } -$is_win = ( strtoupper( substr( php_uname( 's' ),0,3 ) ) === 'WIN' ); +$is_win = (strtoupper(substr(php_uname('s'),0,3)) === 'WIN'); -require_once( "MsSetup.inc" ); +require_once("MsSetup.inc"); -$conn = new PDO( "sqlsrv:server = $server ;", $uid, $pwd ); +$conn = new PDO("sqlsrv:server = $server; driver=$driver;", $uid, $pwd); if ($conn === false) { - die( "skip Could not connect during SKIPIF." ); + die("skip Could not connect during SKIPIF."); } $msodbcsql_ver = $conn->getAttribute(PDO::ATTR_CLIENT_VERSION)["DriverVer"]; @@ -21,19 +21,23 @@ $msodbcsql_maj = explode(".", $msodbcsql_ver)[0]; $msodbcsql_min = explode(".", $msodbcsql_ver)[1]; if (!$is_win) { - if ($msodbcsql_maj < 17 or $msodbcsql_min < 2) { + if ($msodbcsql_maj < 17) { die("skip Unsupported ODBC driver version"); + } else { + if ($msodbcsql_maj==17 && $msodbcsql_min < 2) { + die("skip Unsupported ODBC driver version"); + } } } // Get SQL Server Version // Exclude this check if running on Azure if (!$daasMode) { - $stmt = $conn->query( "SELECT @@VERSION" ); + $stmt = $conn->query("SELECT @@VERSION"); if ($stmt) { $ver_string = $stmt->fetch(PDO::FETCH_NUM)[0]; } else { - die( "skip Could not fetch SQL Server version during SKIPIF."); + die("skip Could not fetch SQL Server version during SKIPIF."); } $version = explode(' ', $ver_string); diff --git a/test/functional/pdo_sqlsrv/skipif_version_less_than_2k16.inc b/test/functional/pdo_sqlsrv/skipif_version_less_than_2k16.inc index 72553974b..376567733 100644 --- a/test/functional/pdo_sqlsrv/skipif_version_less_than_2k16.inc +++ b/test/functional/pdo_sqlsrv/skipif_version_less_than_2k16.inc @@ -7,11 +7,11 @@ if (!extension_loaded("pdo_sqlsrv")) { die("skip Extension not loaded"); } -$is_win = ( strtoupper( substr( php_uname( 's' ),0,3 ) ) === 'WIN' ); +$is_win = (strtoupper(substr(php_uname('s'),0,3)) === 'WIN'); -require_once( "MsSetup.inc" ); +require_once("MsSetup.inc"); -$conn = new PDO( "sqlsrv:server = $server ;", $uid, $pwd ); +$conn = new PDO("sqlsrv:server = $server; driver=$driver;", $uid, $pwd); if ($conn === false) { die( "skip Could not connect during SKIPIF." ); } diff --git a/test/functional/sqlsrv/access_token.inc b/test/functional/sqlsrv/access_token.inc new file mode 100644 index 000000000..dbb2f7786 --- /dev/null +++ b/test/functional/sqlsrv/access_token.inc @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/test/functional/sqlsrv/skipif_azure_ad_acess_token.inc b/test/functional/sqlsrv/skipif_azure_ad_acess_token.inc new file mode 100644 index 000000000..3c7c447cc --- /dev/null +++ b/test/functional/sqlsrv/skipif_azure_ad_acess_token.inc @@ -0,0 +1,45 @@ +$userName, "PWD"=>$userPassword, "Driver" => $driver); + +$conn = sqlsrv_connect($server, $connectionInfo); +if ($conn === false) { + die("skip: Could not connect during SKIPIF."); +} + +$msodbcsqlVer = sqlsrv_client_info($conn)['DriverVer']; +$msodbcsqlMaj = explode(".", $msodbcsqlVer)[0]; + +$isWin = (strtoupper(substr(php_uname('s'), 0, 3)) === 'WIN'); + +if (!$isWin && $msodbcsqlMaj < 17) { + die("skip: Unsupported ODBC driver version"); +} + +// Now check SQL Server version - exclude this check if running on Azure +if (!$daasMode) { + // Get SQL Server version + $stmt = sqlsrv_query($conn, "SELECT @@VERSION"); + if (sqlsrv_fetch($stmt)) { + $verString = sqlsrv_get_field($stmt, 0); + } else { + die("skip Could not fetch SQL Server version."); + } + + $version = explode(' ', $verString); + + if ($version[3] < '2016') { + die("skip: Wrong version of SQL Server, 2016 or later required"); + } +} + +?> diff --git a/test/functional/sqlsrv/skipif_version_less_than_2k14.inc b/test/functional/sqlsrv/skipif_version_less_than_2k14.inc index 74d041fff..e8c53f2d7 100644 --- a/test/functional/sqlsrv/skipif_version_less_than_2k14.inc +++ b/test/functional/sqlsrv/skipif_version_less_than_2k14.inc @@ -7,15 +7,15 @@ if (!extension_loaded("sqlsrv")) { die("skip Extension not loaded"); } -$is_win = ( strtoupper( substr( php_uname( 's' ),0,3 ) ) === 'WIN' ); +$is_win = (strtoupper(substr(php_uname('s'),0,3)) === 'WIN'); -require_once( "MsSetup.inc" ); +require_once("MsSetup.inc"); -$connectionInfo = array( "UID"=>$userName, "PWD"=>$userPassword ); +$connectionInfo = array("UID"=>$userName, "PWD"=>$userPassword, "Driver" => $driver); -$conn = sqlsrv_connect( $server, $connectionInfo ); +$conn = sqlsrv_connect($server, $connectionInfo); if ($conn === false) { - die( "skip Could not connect during SKIPIF." ); + die("skip Could not connect during SKIPIF."); } $msodbcsql_ver = sqlsrv_client_info($conn)["DriverVer"]; @@ -23,17 +23,21 @@ $msodbcsql_maj = explode(".", $msodbcsql_ver)[0]; $msodbcsql_min = explode(".", $msodbcsql_ver)[1]; if (!$is_win) { - if ($msodbcsql_maj < 17 or $msodbcsql_min < 2) { + if ($msodbcsql_maj < 17) { die("skip Unsupported ODBC driver version"); + } else { + if ($msodbcsql_maj==17 && $msodbcsql_min < 2) { + die("skip Unsupported ODBC driver version"); + } } } // Get SQL Server version // Exclude this check if running on Azure if (!$daasMode) { - $stmt = sqlsrv_query( $conn, "SELECT @@VERSION" ); + $stmt = sqlsrv_query($conn, "SELECT @@VERSION"); if (sqlsrv_fetch($stmt)) { - $ver_string = sqlsrv_get_field( $stmt, 0 ); + $ver_string = sqlsrv_get_field($stmt, 0); } else { die("skip Could not fetch SQL Server version."); } diff --git a/test/functional/sqlsrv/skipif_version_less_than_2k16.inc b/test/functional/sqlsrv/skipif_version_less_than_2k16.inc index ce06258a2..303a2030b 100644 --- a/test/functional/sqlsrv/skipif_version_less_than_2k16.inc +++ b/test/functional/sqlsrv/skipif_version_less_than_2k16.inc @@ -7,11 +7,11 @@ if (!extension_loaded("sqlsrv")) { die("skip Extension not loaded"); } -$is_win = ( strtoupper( substr( php_uname( 's' ),0,3 ) ) === 'WIN' ); +$is_win = (strtoupper(substr(php_uname('s'),0,3)) === 'WIN'); -require_once( "MsSetup.inc" ); +require_once("MsSetup.inc"); -$connectionInfo = array( "UID"=>$userName, "PWD"=>$userPassword ); +$connectionInfo = array("UID"=>$userName, "PWD"=>$userPassword, "Driver" => $driver); $conn = sqlsrv_connect( $server, $connectionInfo ); if ($conn === false) { diff --git a/test/functional/sqlsrv/sqlsrv_ae_type_conversion_select.phpt b/test/functional/sqlsrv/sqlsrv_ae_type_conversion_select.phpt index ba48e9f67..d4ea1c940 100644 --- a/test/functional/sqlsrv/sqlsrv_ae_type_conversion_select.phpt +++ b/test/functional/sqlsrv/sqlsrv_ae_type_conversion_select.phpt @@ -29,8 +29,10 @@ function checkErrors(&$convError) $convError[0][1] != '8114' and $convError[0][1] != '8169') { print_r($convError); - fatalError("Conversion failed with unexpected error message. i=$i, j=$j, v=$v\n"); - } + return false; + } + + return true; } // Build the select queries. We want every combination of types for conversion @@ -202,7 +204,9 @@ for ($v = 0; $v < sizeof($values); ++$v) { if ($stmt == false) { $convError = sqlsrv_errors(); - checkErrors($convError); + if (!checkErrors($convError)) { + fatalError("Conversion failed with unexpected error message. i=$i, j=$j, v=$v\n"); + } if (AE\isDataEncrypted()) { $stmtAE = sqlsrv_query($conn, $selectQueryAE[$i][$j]); diff --git a/test/functional/sqlsrv/sqlsrv_azure_ad_access_token.phpt b/test/functional/sqlsrv/sqlsrv_azure_ad_access_token.phpt new file mode 100644 index 000000000..96c82d63a --- /dev/null +++ b/test/functional/sqlsrv/sqlsrv_azure_ad_access_token.phpt @@ -0,0 +1,131 @@ +--TEST-- +Test some basics of Azure AD Access Token support +--DESCRIPTION-- +This test also expects certain exceptions to be thrown under some conditions. +--SKIPIF-- + +--FILE-- + "$dummyToken"); + $conn = sqlsrv_connect($server, $connectionInfo); + verifyErrorMessage($conn, $expectedError, 'empty token'); + unset($connectionInfo); +} + +function connectWithInvalidOptions($server) +{ + $dummyToken = 'abcde'; + $expectedError = 'When using Azure AD Access Token, the connection string must not contain UID, PWD, or Authentication keywords.'; + + $connectionInfo = array("UID"=>"", "AccessToken" => "$dummyToken"); + $conn = sqlsrv_connect($server, $connectionInfo); + verifyErrorMessage($conn, $expectedError, 'empty UID provided'); + unset($connectionInfo); + + $connectionInfo = array("PWD"=>"", "AccessToken" => "$dummyToken"); + $conn = sqlsrv_connect($server, $connectionInfo); + verifyErrorMessage($conn, $expectedError, 'empty PWD provided'); + unset($connectionInfo); + + $connectionInfo = array("UID"=>"uid", "AccessToken" => "$dummyToken"); + $conn = sqlsrv_connect($server, $connectionInfo); + verifyErrorMessage($conn, $expectedError, 'UID provided'); + unset($connectionInfo); + + $connectionInfo = array("PWD"=>"pwd", "AccessToken" => "$dummyToken"); + $conn = sqlsrv_connect($server, $connectionInfo); + verifyErrorMessage($conn, $expectedError, 'PWD provided'); + unset($connectionInfo); + + $connectionInfo = array("Authentication"=>"SqlPassword", "AccessToken" => "$dummyToken"); + $conn = sqlsrv_connect($server, $connectionInfo); + verifyErrorMessage($conn, $expectedError, 'Authentication keyword'); + unset($connectionInfo); +} + +function simpleTest($conn) +{ + // Create table + $tableName = 'Simple'; + $col1 = 'Some simple string value'; + + dropTable($conn, $tableName); + + $query = "CREATE TABLE $tableName(ID INT IDENTITY(1,1), COL1 VARCHAR(25))"; + $stmt = sqlsrv_query($conn, $query); + if (!$stmt) { + fatalError("AzureAD access token test: failed to create a table\n"); + } + + // Insert one row + $query = "INSERT INTO $tableName VALUES ('$col1')"; + $stmt = sqlsrv_query($conn, $query); + if (!$stmt) { + fatalError("AzureAD access token test: failed to insert a row\n"); + } + + // Fetch data + $query = "SELECT * FROM $tableName"; + $stmt = sqlsrv_query($conn, $query); + if (!$stmt) { + fatalError("AzureAD access token test: failed to fetch a table\n"); + } + + while (sqlsrv_fetch($stmt)) { + $id = sqlsrv_get_field($stmt, 0); + if ($id != 1) { + fatalError("AzureAD access token test: fetched id $id unexpected\n"); + } + $field = sqlsrv_get_field($stmt, 1); + if ($field !== $col1) { + fatalError("AzureAD access token test: fetched value $field unexpected\n"); + } + } + + dropTable($conn, $tableName); +} + +// First test some error conditions +connectWithInvalidOptions($server); + +// Then, test with an empty access token +connectWithEmptyAccessToken($server); + +// Next, test with a valid access token and perform some simple tasks +require_once('access_token.inc'); +if ($adServer != 'TARGET_AD_SERVER' && $accToken != 'TARGET_ACCESS_TOKEN') { + $connectionInfo = array("Database"=>$adDatabase, "AccessToken"=>$accToken); + + $conn = sqlsrv_connect($adServer, $connectionInfo); + if ($conn === false) { + fatalError("Could not connect with Azure AD AccessToken.\n"); + } else { + simpleTest($conn); + + sqlsrv_close($conn); + } +} + +echo "Done\n"; +?> +--EXPECT-- +Done \ No newline at end of file diff --git a/test/functional/sqlsrv/sqlsrv_errors.phpt b/test/functional/sqlsrv/sqlsrv_errors.phpt index 064357da2..fe70816a8 100644 --- a/test/functional/sqlsrv/sqlsrv_errors.phpt +++ b/test/functional/sqlsrv/sqlsrv_errors.phpt @@ -119,7 +119,7 @@ sqlsrv_close returns true even if an error happens. echo "Test successfully done.\n"; ?> --EXPECTF-- -Warning: sqlsrv_close() expects parameter 1 to be resource, boolean given in %Ssqlsrv_errors.php on line %x +Warning: sqlsrv_close() expects parameter 1 to be resource, bool%S given in %Ssqlsrv_errors.php on line %x Array ( [0] => Array @@ -153,7 +153,7 @@ Array ) -Warning: sqlsrv_free_stmt() expects parameter 1 to be resource, integer given in %Ssqlsrv_errors.php on line %x +Warning: sqlsrv_free_stmt() expects parameter 1 to be resource, int%S given in %Ssqlsrv_errors.php on line %x Array ( [0] => Array @@ -172,7 +172,7 @@ Warning: sqlsrv_close(): supplied resource is not a valid ss_sqlsrv_conn resourc Warning: sqlsrv_close() expects parameter 1 to be resource, null given in %Ssqlsrv_errors.php on line %x -Warning: sqlsrv_close() expects parameter 1 to be resource, integer given in %Ssqlsrv_errors.php on line %x +Warning: sqlsrv_close() expects parameter 1 to be resource, int%S given in %Ssqlsrv_errors.php on line %x Array ( [0] => Array diff --git a/test/functional/sqlsrv/sqlsrv_statement_datetimes_as_nulls.phpt b/test/functional/sqlsrv/sqlsrv_statement_datetimes_as_nulls.phpt new file mode 100644 index 000000000..7c8a16ef2 --- /dev/null +++ b/test/functional/sqlsrv/sqlsrv_statement_datetimes_as_nulls.phpt @@ -0,0 +1,120 @@ +--TEST-- +Test retrieving null datetime values with statement option ReturnDatesAsStrings as true +--DESCRIPTION-- +Test retrieving null datetime values with statement option ReturnDatesAsStrings as true, +which is false by default. Whether retrieved as strings or date time objects should return +NULLs. +--SKIPIF-- + +--FILE-- + 'buffered', 'ReturnDatesAsStrings' => true); + } else { + $options = array('ReturnDatesAsStrings' => true); + } + + $size = count($columns); + $stmt = sqlsrv_prepare($conn, $query, array(), $options); + // Fetch by getting one field at a time + sqlsrv_execute($stmt); + if( sqlsrv_fetch( $stmt ) === false) { + fatalError("Failed in retrieving data\n"); + } + for ($i = 0; $i < $size; $i++) { + $field = sqlsrv_get_field($stmt, $i); // expect string + if (!is_null($field)) { + echo "Expected null for column $columns[$i] but got: "; + var_dump($field); + } + } + + // Fetch row as an object + sqlsrv_execute($stmt); + $object = sqlsrv_fetch_object($stmt); + + $objArray = (array)$object; // turn the object into an associated array + for ($i = 0; $i < $size; $i++) { + $col = $columns[$i]; + $val = $objArray[$col]; + + if (!is_null($val)) { + echo "Expected null for column $columns[$i] but got: "; + var_dump($val); + } + } +} + +function createTestTable($conn, $tableName, $columns) +{ + // Create the test table of date and time columns + $dataTypes = array('date', 'smalldatetime', 'datetime', 'datetime2', 'datetimeoffset', 'time'); + + $colMeta = array(new AE\ColumnMeta($dataTypes[0], $columns[0]), + new AE\ColumnMeta($dataTypes[1], $columns[1]), + new AE\ColumnMeta($dataTypes[2], $columns[2]), + new AE\ColumnMeta($dataTypes[3], $columns[3]), + new AE\ColumnMeta($dataTypes[4], $columns[4]), + new AE\ColumnMeta($dataTypes[5], $columns[5])); + AE\createTable($conn, $tableName, $colMeta); + + // Insert null values + $inputData = array($colMeta[0]->colName => null, + $colMeta[1]->colName => null, + $colMeta[2]->colName => null, + $colMeta[3]->colName => null, + $colMeta[4]->colName => null, + $colMeta[5]->colName => null); + $stmt = AE\insertRow($conn, $tableName, $inputData); + if (!$stmt) { + fatalError("Failed to insert data.\n"); + } + sqlsrv_free_stmt($stmt); +} + +function runTest($tableName, $columns, $dateAsString) +{ + // Connect + $conn = AE\connect(array('ReturnDatesAsStrings' => $dateAsString)); + if (!$conn) { + fatalError("Could not connect.\n"); + } + + $query = "SELECT * FROM $tableName"; + testFetch($conn, $query, $columns); + testFetch($conn, $query, $columns, true); + + sqlsrv_close($conn); +} + +set_time_limit(0); +sqlsrv_configure('WarningsReturnAsErrors', 1); + +$tableName = "TestNullDateTime"; +$columns = array('c1', 'c2', 'c3', 'c4', 'c5', 'c6'); + +// Connect +$conn = AE\connect(); +if (!$conn) { + fatalError("Could not connect.\n"); +} + +createTestTable($conn, $tableName, $columns); + +runTest($tableName, $columns, true); +runTest($tableName, $columns, false); + +dropTable($conn, $tableName); + +sqlsrv_close($conn); + +echo "Done\n"; +?> +--EXPECT-- +Done diff --git a/test/functional/sqlsrv/sqlsrv_statement_datetimes_as_strings.phpt b/test/functional/sqlsrv/sqlsrv_statement_datetimes_as_strings.phpt new file mode 100644 index 000000000..01cc16f2e --- /dev/null +++ b/test/functional/sqlsrv/sqlsrv_statement_datetimes_as_strings.phpt @@ -0,0 +1,202 @@ +--TEST-- +Test retrieving datetime values with statement option ReturnDatesAsStrings set to true +--DESCRIPTION-- +Test retrieving datetime values with statement option ReturnDatesAsStrings set to true, +which is false by default. The statement option should override the corresponding +connection option ReturnDatesAsStrings. +--SKIPIF-- + +--FILE-- +format('Y-m-d H:i:s.u'); + + // actual datetime value from date time object to string + $dtActual = date_format($actualObj, 'Y-m-d H:i:s.u'); + + return ($dtActual === $dtExpected); +} + +function testNoOption($conn, $tableName, $inputs, $exec) +{ + // Without the statement option, should return datetime values as strings + // because the connection option ReturnDatesAsStrings is set to true + $query = "SELECT * FROM $tableName"; + if ($exec) { + $stmt = sqlsrv_query($conn, $query); + } else { + $stmt = sqlsrv_prepare($conn, $query); + sqlsrv_execute($stmt); + } + + $results = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); + + // Compare values only + $diffs = array_diff($inputs, $results); + if (!empty($diffs)) { + echo 'The results are different from the input values: '; + print_r($diffs); + } +} + +function testStmtOption($conn, $tableName, $inputs, $stmtDateAsStr) +{ + // The statement option should always override the connection option + $query = "SELECT * FROM $tableName"; + $options = array('ReturnDatesAsStrings' => $stmtDateAsStr); + $stmt = sqlsrv_query($conn, $query, array(), $options); + + if ($stmtDateAsStr) { + $results = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC); + + // Compare values only + $diffs = array_diff($inputs, $results); + if (!empty($diffs)) { + echo 'The results are different from the input values: '; + print_r($diffs); + } + } else { + $results = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); + + // Expect DateTime Objects in $results + for ($i = 0; $i < count($inputs); $i++) { + if (is_object($results[$i])) { + $matched = compareDateTime($inputs[$i], $results[$i]); + if (!$matched) { + echo "Expected a DateTime object of $inputs[$i] but got: \n"; + var_dump($results[$i]); + } + } else { + echo "Expect a DateTime object but got $results[$i]\n"; + } + } + } +} + +function testFetching($conn, $tableName, $inputs, $columns, $withBuffer) +{ + // The statement option ReturnDatesAsStrings set to true + // Test different fetching + $query = "SELECT * FROM $tableName"; + if ($withBuffer){ + $options = array('Scrollable' => 'buffered', 'ReturnDatesAsStrings' => true); + } else { + $options = array('ReturnDatesAsStrings' => true); + } + + $size = count($inputs); + $stmt = sqlsrv_prepare($conn, $query, array(), $options); + + // Fetch by getting one field at a time + sqlsrv_execute($stmt); + + if( sqlsrv_fetch( $stmt ) === false) { + fatalError("Failed in retrieving data\n"); + } + for ($i = 0; $i < $size; $i++) { + $field = sqlsrv_get_field($stmt, $i); // expect string + if ($field != $inputs[$i]) { + echo "Expected $inputs[$i] for column $columns[$i] but got: "; + var_dump($field); + } + } + + // Fetch row as an object + sqlsrv_execute($stmt); + $object = sqlsrv_fetch_object($stmt); + + $objArray = (array)$object; // turn the object into an associated array + for ($i = 0; $i < $size; $i++) { + $col = $columns[$i]; + $val = $objArray[$col]; + + if ($val != $inputs[$i]) { + echo "Expected $inputs[$i] for column $columns[$i] but got: "; + var_dump($val); + } + } +} + +set_time_limit(0); +sqlsrv_configure('WarningsReturnAsErrors', 1); +date_default_timezone_set('America/Los_Angeles'); + +// Connect with ReturnDatesAsStrings option set to true +$conn = connect(array('ReturnDatesAsStrings' => true)); +if (!$conn) { + fatalError("Could not connect.\n"); +} + +// Generate input values for the test table +$query = 'SELECT CONVERT(date, SYSDATETIME()), SYSDATETIME(), + CONVERT(smalldatetime, SYSDATETIME()), + CONVERT(datetime, SYSDATETIME()), + SYSDATETIMEOFFSET(), + CONVERT(time, SYSDATETIME())'; +$stmt = sqlsrv_query($conn, $query); +$values = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); +sqlsrv_free_stmt($stmt); +sqlsrv_close($conn); + +// Connect again with ColumnEncryption data +$conn = AE\connect(array('ReturnDatesAsStrings' => true)); + +// Create the test table of date and time columns +$tableName = 'StmtDateAsString'; +$columns = array('c1', 'c2', 'c3', 'c4', 'c5', 'c6'); +$dataTypes = array('date', 'datetime2', 'smalldatetime', 'datetime', 'datetimeoffset', 'time'); + +$colMeta = array(new AE\ColumnMeta($dataTypes[0], $columns[0]), + new AE\ColumnMeta($dataTypes[1], $columns[1]), + new AE\ColumnMeta($dataTypes[2], $columns[2]), + new AE\ColumnMeta($dataTypes[3], $columns[3]), + new AE\ColumnMeta($dataTypes[4], $columns[4]), + new AE\ColumnMeta($dataTypes[5], $columns[5])); +AE\createTable($conn, $tableName, $colMeta); + +// Insert data values +$inputData = array($colMeta[0]->colName => $values[0], + $colMeta[1]->colName => $values[1], + $colMeta[2]->colName => $values[2], + $colMeta[3]->colName => $values[3], + $colMeta[4]->colName => $values[4], + $colMeta[5]->colName => $values[5]); +$stmt = AE\insertRow($conn, $tableName, $inputData); +if (!$stmt) { + fatalError("Failed to insert data.\n"); +} +sqlsrv_free_stmt($stmt); + +// Do not set ReturnDatesAsStrings at statement level +testNoOption($conn, $tableName, $values, true); +testNoOption($conn, $tableName, $values, false); + +// Set ReturnDatesAsStrings to false at statement level +testStmtOption($conn, $tableName, $values, false); + +sqlsrv_close($conn); + +// Now connect but with ReturnDatesAsStrings option set to false +$conn = AE\connect(array('ReturnDatesAsStrings' => false)); +if (!$conn) { + fatalError("Could not connect.\n"); +} + +// Set ReturnDatesAsStrings to true at statement level +testStmtOption($conn, $tableName, $values, true); + +// Test fetching by setting ReturnDatesAsStrings to true at statement level +testFetching($conn, $tableName, $values, $columns, true); +testFetching($conn, $tableName, $values, $columns, false); + +dropTable($conn, $tableName); +sqlsrv_close($conn); + +echo "Done\n"; +?> +--EXPECT-- +Done diff --git a/test/functional/sqlsrv/sqlsrv_statement_datetimes_output_param.phpt b/test/functional/sqlsrv/sqlsrv_statement_datetimes_output_param.phpt new file mode 100644 index 000000000..4e3add8af --- /dev/null +++ b/test/functional/sqlsrv/sqlsrv_statement_datetimes_output_param.phpt @@ -0,0 +1,113 @@ +--TEST-- +Test retrieving datetime values as output params with statement option ReturnDatesAsStrings +--DESCRIPTION-- +Test retrieving datetime values as output params with statement option ReturnDatesAsStrings +with sqlsrv_prepare. When ReturnDatesAsStrings option is false, expect an error to return. +--SKIPIF-- + +--FILE-- + $dateAsString)); + if (!$stmt) { + fatalError("Failed when preparing to call $storedProcName"); + } + $result = sqlsrv_execute($stmt); + if ($dateAsString) { + // Expect to succeed when returning a DateTime value as a string + // The output param value should be the same as the input value + if (!$result) { + fatalError("Failed when invoking $storedProcName"); + } + if ($outDateStr != $inputValue) { + echo "Expected $inputValue but got $outDateStr\n"; + } + } else { + // Expect to fail with an error message because setting a DateTime object as the + // output parameter is not allowed + if ($result) { + fatalError("Returning DateTime as output param is expected to fail!"); + } + // Check if the error message is the expected one + $error = sqlsrv_errors()[0]['message']; + $message = 'An invalid PHP type was specified as an output parameter. DateTime objects, NULL values, and streams cannot be specified as output parameters'; + if (strpos($error, $message) === false) { + print_r(sqlsrv_errors()); + } + } +} + +set_time_limit(0); +sqlsrv_configure('WarningsReturnAsErrors', 1); +date_default_timezone_set('America/Los_Angeles'); + +// Connect with ReturnDatesAsStrings option set to true +$conn = connect(array('ReturnDatesAsStrings' => true)); +if (!$conn) { + fatalError("Could not connect.\n"); +} + +// Generate input values for the test table +$query = 'SELECT CONVERT(date, SYSDATETIME()), SYSDATETIME(), SYSDATETIMEOFFSET(), CONVERT(time, CURRENT_TIMESTAMP)'; +$stmt = sqlsrv_query($conn, $query); +$values = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); + +sqlsrv_free_stmt($stmt); +sqlsrv_close($conn); + +// Connect again with ColumnEncryption data +$conn = AE\connect(array('ReturnDatesAsStrings' => true)); +if (!$conn) { + fatalError("Could not connect.\n"); +} + +// Create the test table of date and time columns +$tableName = 'OuputParamDateAsString'; +$columns = array('c1', 'c2', 'c3', 'c4'); +$dataTypes = array('date', 'datetime2', 'datetimeoffset', 'time'); +$sqlTypes = array(SQLSRV_SQLTYPE_DATE, + SQLSRV_SQLTYPE_DATETIME2, + SQLSRV_SQLTYPE_DATETIMEOFFSET, + SQLSRV_SQLTYPE_TIME); +$colMeta = array(new AE\ColumnMeta($dataTypes[0], $columns[0]), + new AE\ColumnMeta($dataTypes[1], $columns[1]), + new AE\ColumnMeta($dataTypes[2], $columns[2]), + new AE\ColumnMeta($dataTypes[3], $columns[3])); +AE\createTable($conn, $tableName, $colMeta); + +// Insert data values +$inputData = array($colMeta[0]->colName => $values[0], + $colMeta[1]->colName => $values[1], + $colMeta[2]->colName => $values[2], + $colMeta[3]->colName => $values[3]); +$stmt = AE\insertRow($conn, $tableName, $inputData); +if (!$stmt) { + fatalError("Failed to insert data.\n"); +} +sqlsrv_free_stmt($stmt); + +for ($i = 0; $i < count($columns); $i++) { + // create the stored procedure first + $storedProcName = "spDateTimeOutParam" . $i; + $procArgs = "@col $dataTypes[$i] OUTPUT"; + $procCode = "SELECT @col = $columns[$i] FROM $tableName"; + createProc($conn, $storedProcName, $procArgs, $procCode); + + // call stored procedure to retrieve output param + runTest($conn, $storedProcName, $values[$i], $sqlTypes[$i], true); + runTest($conn, $storedProcName, $values[$i], $sqlTypes[$i], false); +} + +dropTable($conn, $tableName); +sqlsrv_close($conn); + +echo "Done\n"; +?> +--EXPECT-- +Done diff --git a/test/functional/sqlsrv/test_conn_execute.phpt b/test/functional/sqlsrv/test_conn_execute.phpt index edd979984..55731ef1d 100644 --- a/test/functional/sqlsrv/test_conn_execute.phpt +++ b/test/functional/sqlsrv/test_conn_execute.phpt @@ -1,24 +1,24 @@ ---TEST-- -crash caused by a statement being orphaned when an error occurred during sqlsrv_conn_execute. ---SKIPIF-- - ---FILE-- - ---EXPECTREGEX-- -Warning: sqlsrv_fetch_array\(\) expects parameter 1 to be resource, boolean given in .+(\/|\\)test_conn_execute\.php on line 11 -Test successful +--TEST-- +crash caused by a statement being orphaned when an error occurred during sqlsrv_conn_execute. +--SKIPIF-- + +--FILE-- + +--EXPECTREGEX-- +Warning: sqlsrv_fetch_array\(\) expects parameter 1 to be resource, bool(ean){0,1} given in .+(\/|\\)test_conn_execute\.php on line 11 +Test successful diff --git a/test/functional/sqlsrv/test_non_alpha_password.phpt b/test/functional/sqlsrv/test_non_alpha_password.phpt index ffd138c91..a288a1d4c 100644 --- a/test/functional/sqlsrv/test_non_alpha_password.phpt +++ b/test/functional/sqlsrv/test_non_alpha_password.phpt @@ -1,61 +1,61 @@ ---TEST-- -password with non alphanumeric characters ---DESCRIPTION-- -The first three cases should have no problem connecting. Only the last case fails because the -right curly brace should be escaped with another right brace. -In Azure for this test to pass do not specify any particular database when connecting ---SKIPIF-- - ---FILE-- - "test_password", "pwd" => "! ;4triou" )); -if (!$conn) -{ - $errors = sqlsrv_errors(); - echo( $errors[0]["message"]); -} -sqlsrv_close( $conn ); - -$conn = toConnect(array( "UID" => "test_password2", "pwd" => "!}} ;4triou" )); -if (!$conn) -{ - $errors = sqlsrv_errors(); - echo( $errors[0]["message"]); -} -sqlsrv_close( $conn ); - -$conn = toConnect(array( "UID" => "test_password3", "pwd" => "! ;4triou}}" )); -if (!$conn) -{ - $errors = sqlsrv_errors(); - echo( $errors[0]["message"]); -} -sqlsrv_close( $conn ); - -$conn = toConnect(array( "UID" => "test_password3", "pwd" => "! ;4triou}" )); -if ($conn) -{ - echo( "Shouldn't have connected" ); -} -$errors = sqlsrv_errors(); -echo $errors[0]["message"]; -sqlsrv_close( $conn ); - -print "Test successful"; -?> ---EXPECTREGEX-- -An unescaped right brace \(}\) was found in either the user name or password. All right braces must be escaped with another right brace \(}}\)\. -Warning: sqlsrv_close\(\) expects parameter 1 to be resource, boolean given in .+(\/|\\)test_non_alpha_password\.php on line 45 -Test successful +--TEST-- +password with non alphanumeric characters +--DESCRIPTION-- +The first three cases should have no problem connecting. Only the last case fails because the +right curly brace should be escaped with another right brace. +In Azure for this test to pass do not specify any particular database when connecting +--SKIPIF-- + +--FILE-- + "test_password", "pwd" => "! ;4triou" )); +if (!$conn) +{ + $errors = sqlsrv_errors(); + echo( $errors[0]["message"]); +} +sqlsrv_close( $conn ); + +$conn = toConnect(array( "UID" => "test_password2", "pwd" => "!}} ;4triou" )); +if (!$conn) +{ + $errors = sqlsrv_errors(); + echo( $errors[0]["message"]); +} +sqlsrv_close( $conn ); + +$conn = toConnect(array( "UID" => "test_password3", "pwd" => "! ;4triou}}" )); +if (!$conn) +{ + $errors = sqlsrv_errors(); + echo( $errors[0]["message"]); +} +sqlsrv_close( $conn ); + +$conn = toConnect(array( "UID" => "test_password3", "pwd" => "! ;4triou}" )); +if ($conn) +{ + echo( "Shouldn't have connected" ); +} +$errors = sqlsrv_errors(); +echo $errors[0]["message"]; +sqlsrv_close( $conn ); + +print "Test successful"; +?> +--EXPECTREGEX-- +An unescaped right brace \(}\) was found in either the user name or password. All right braces must be escaped with another right brace \(}}\)\. +Warning: sqlsrv_close\(\) expects parameter 1 to be resource, bool(ean){0,1} given in .+(\/|\\)test_non_alpha_password\.php on line 45 +Test successful From 80442d45dbf4688b9ec64ebdf48f5f3648f91578 Mon Sep 17 00:00:00 2001 From: Gert de Pagter Date: Mon, 1 Oct 2018 23:01:10 +0200 Subject: [PATCH 03/10] Change readme links to https --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 071d582f0..23baf6e89 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ For PHP code samples, please see the [sample](https://github.com/Microsoft/msphp Please refer to [Releases](https://github.com/Microsoft/msphpsql/releases) for the latest limitations and known issues. ## Version number -The version numbers of the PHP drivers follow [semantic versioning](http://semver.org/): +The version numbers of the PHP drivers follow [semantic versioning](https://semver.org/): Given a version number MAJOR.MINOR.PATCH, @@ -128,16 +128,16 @@ This project has adopted the Microsoft Open Source Code of Conduct. For more inf **Known Issues**: Please visit the [project on Github][project] to view outstanding [issues][issues] and report new ones. -[blog]: http://blogs.msdn.com/b/sqlphp/ +[blog]: https://blogs.msdn.com/b/sqlphp/ [project]: https://github.com/Microsoft/msphpsql [issues]: https://github.com/Microsoft/msphpsql/issues -[phpweb]: http://php.net +[phpweb]: https://php.net [phpbuild]: https://wiki.php.net/internals/windows/stepbystepbuild [phpdoc]: https://docs.microsoft.com/sql/connect/php/microsoft-php-driver-for-sql-server?view=sql-server-2017 -[PHPMan]: http://php.net/manual/install.unix.php +[PHPMan]: https://php.net/manual/install.unix.php From eb679eab6a66337dd9ef6b8c9a247ddb7e746aa1 Mon Sep 17 00:00:00 2001 From: David Engel Date: Tue, 13 Nov 2018 16:32:43 -0800 Subject: [PATCH 04/10] Update survey image link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 23baf6e89..93c19e3db 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ This release contains the SQLSRV and PDO_SQLSRV drivers for PHP 7.1+ with improv Thank you for taking the time to participate in our last survey. You can continue to help us improve by letting us know how we are doing and how you use PHP by taking our December pulse survey: - + ### Status of Most Recent Builds | AppVeyor (Windows) | Travis CI (Linux) | Coverage (Windows) | Coverage (Linux) | From 463727923e29d5d46ade6b2cd57e5541119c415e Mon Sep 17 00:00:00 2001 From: Jenny Tam Date: Thu, 22 Nov 2018 16:56:23 -0800 Subject: [PATCH 05/10] Decimal places for money types only --- source/pdo_sqlsrv/pdo_dbh.cpp | 49 +++- source/pdo_sqlsrv/pdo_init.cpp | 1 + source/pdo_sqlsrv/pdo_stmt.cpp | 18 +- source/pdo_sqlsrv/pdo_util.cpp | 6 +- source/pdo_sqlsrv/php_pdo_sqlsrv.h | 7 +- source/shared/core_sqlsrv.h | 34 ++- source/shared/core_stmt.cpp | 190 ++++++++----- source/sqlsrv/conn.cpp | 68 +++++ source/sqlsrv/php_sqlsrv.h | 4 + source/sqlsrv/stmt.cpp | 4 +- source/sqlsrv/util.cpp | 6 +- .../pdostatement_format_decimals.phpt | 227 ++++----------- .../pdostatement_format_decimals_scales.phpt | 248 ----------------- .../pdostatement_format_money_types.phpt | 245 ++++++++++++++++ .../sqlsrv_statement_format_decimals.phpt | 255 +++++------------ ...lsrv_statement_format_decimals_scales.phpt | 255 ----------------- .../sqlsrv_statement_format_money_types.phpt | 261 ++++++++++++++++++ 17 files changed, 911 insertions(+), 967 deletions(-) delete mode 100644 test/functional/pdo_sqlsrv/pdostatement_format_decimals_scales.phpt create mode 100644 test/functional/pdo_sqlsrv/pdostatement_format_money_types.phpt delete mode 100644 test/functional/sqlsrv/sqlsrv_statement_format_decimals_scales.phpt create mode 100644 test/functional/sqlsrv/sqlsrv_statement_format_money_types.phpt diff --git a/source/pdo_sqlsrv/pdo_dbh.cpp b/source/pdo_sqlsrv/pdo_dbh.cpp index bf25d5a84..77e30f3d3 100644 --- a/source/pdo_sqlsrv/pdo_dbh.cpp +++ b/source/pdo_sqlsrv/pdo_dbh.cpp @@ -81,7 +81,8 @@ enum PDO_STMT_OPTIONS { PDO_STMT_OPTION_EMULATE_PREPARES, PDO_STMT_OPTION_FETCHES_NUMERIC_TYPE, PDO_STMT_OPTION_FETCHES_DATETIME_TYPE, - PDO_STMT_OPTION_FORMAT_DECIMALS + PDO_STMT_OPTION_FORMAT_DECIMALS, + PDO_STMT_OPTION_DECIMAL_PLACES }; // List of all the statement options supported by this driver. @@ -97,6 +98,7 @@ const stmt_option PDO_STMT_OPTS[] = { { NULL, 0, PDO_STMT_OPTION_FETCHES_NUMERIC_TYPE, std::unique_ptr( new stmt_option_fetch_numeric ) }, { NULL, 0, PDO_STMT_OPTION_FETCHES_DATETIME_TYPE, std::unique_ptr( new stmt_option_fetch_datetime ) }, { NULL, 0, PDO_STMT_OPTION_FORMAT_DECIMALS, std::unique_ptr( new stmt_option_format_decimals ) }, + { NULL, 0, PDO_STMT_OPTION_DECIMAL_PLACES, std::unique_ptr( new stmt_option_decimal_places ) }, { NULL, 0, SQLSRV_STMT_OPTION_INVALID, std::unique_ptr{} }, }; @@ -500,7 +502,9 @@ pdo_sqlsrv_dbh::pdo_sqlsrv_dbh( _In_ SQLHANDLE h, _In_ error_callback e, _In_ vo query_timeout( QUERY_TIMEOUT_INVALID ), client_buffer_max_size( PDO_SQLSRV_G( client_buffer_max_size )), fetch_numeric( false ), - fetch_datetime( false ) + fetch_datetime( false ), + format_decimals( false ), + decimal_places( NO_CHANGE_DECIMAL_PLACES ) { if( client_buffer_max_size < 0 ) { client_buffer_max_size = sqlsrv_buffered_result_set::BUFFERED_QUERY_LIMIT_DEFAULT; @@ -1069,7 +1073,28 @@ int pdo_sqlsrv_dbh_set_attr( _Inout_ pdo_dbh_t *dbh, _In_ zend_long attr, _Inout case SQLSRV_ATTR_FETCHES_DATETIME_TYPE: driver_dbh->fetch_datetime = (zend_is_true(val)) ? true : false; break; - + + case SQLSRV_ATTR_FORMAT_DECIMALS: + driver_dbh->format_decimals = (zend_is_true(val)) ? true : false; + break; + + case SQLSRV_ATTR_DECIMAL_PLACES: + { + // first check if the input is an integer + if (Z_TYPE_P(val) != IS_LONG) { + THROW_PDO_ERROR(driver_dbh, SQLSRV_ERROR_INVALID_DECIMAL_PLACES); + } + + zend_long decimal_places = Z_LVAL_P(val); + if (decimal_places < 0 || decimal_places > SQL_SERVER_MAX_MONEY_SCALE) { + // ignore decimal_places as this is out of range + decimal_places = NO_CHANGE_DECIMAL_PLACES; + } + + driver_dbh->decimal_places = static_cast(decimal_places); + } + break; + // Not supported case PDO_ATTR_FETCH_TABLE_NAMES: case PDO_ATTR_FETCH_CATALOG_NAMES: @@ -1097,7 +1122,6 @@ int pdo_sqlsrv_dbh_set_attr( _Inout_ pdo_dbh_t *dbh, _In_ zend_long attr, _Inout case PDO_ATTR_EMULATE_PREPARES: case PDO_ATTR_CURSOR: case SQLSRV_ATTR_CURSOR_SCROLL_TYPE: - case SQLSRV_ATTR_FORMAT_DECIMALS: { THROW_PDO_ERROR( driver_dbh, PDO_SQLSRV_ERROR_STMT_LEVEL_ATTR ); } @@ -1156,7 +1180,6 @@ int pdo_sqlsrv_dbh_get_attr( _Inout_ pdo_dbh_t *dbh, _In_ zend_long attr, _Inout case PDO_ATTR_EMULATE_PREPARES: case PDO_ATTR_CURSOR: case SQLSRV_ATTR_CURSOR_SCROLL_TYPE: - case SQLSRV_ATTR_FORMAT_DECIMALS: { THROW_PDO_ERROR( driver_dbh, PDO_SQLSRV_ERROR_STMT_LEVEL_ATTR ); } @@ -1229,6 +1252,18 @@ int pdo_sqlsrv_dbh_get_attr( _Inout_ pdo_dbh_t *dbh, _In_ zend_long attr, _Inout break; } + case SQLSRV_ATTR_FORMAT_DECIMALS: + { + ZVAL_BOOL( return_value, driver_dbh->format_decimals ); + break; + } + + case SQLSRV_ATTR_DECIMAL_PLACES: + { + ZVAL_LONG( return_value, driver_dbh->decimal_places ); + break; + } + default: { THROW_PDO_ERROR( driver_dbh, PDO_SQLSRV_ERROR_INVALID_DBH_ATTR ); @@ -1594,6 +1629,10 @@ void add_stmt_option_key( _Inout_ sqlsrv_context& ctx, _In_ size_t key, _Inout_ option_key = PDO_STMT_OPTION_FORMAT_DECIMALS; break; + case SQLSRV_ATTR_DECIMAL_PLACES: + option_key = PDO_STMT_OPTION_DECIMAL_PLACES; + break; + default: CHECK_CUSTOM_ERROR( true, ctx, PDO_SQLSRV_ERROR_INVALID_STMT_OPTION ) { throw core::CoreException(); diff --git a/source/pdo_sqlsrv/pdo_init.cpp b/source/pdo_sqlsrv/pdo_init.cpp index 6d47cf5b6..000878fae 100644 --- a/source/pdo_sqlsrv/pdo_init.cpp +++ b/source/pdo_sqlsrv/pdo_init.cpp @@ -287,6 +287,7 @@ namespace { { "SQLSRV_ATTR_FETCHES_NUMERIC_TYPE", SQLSRV_ATTR_FETCHES_NUMERIC_TYPE }, { "SQLSRV_ATTR_FETCHES_DATETIME_TYPE", SQLSRV_ATTR_FETCHES_DATETIME_TYPE }, { "SQLSRV_ATTR_FORMAT_DECIMALS" , SQLSRV_ATTR_FORMAT_DECIMALS }, + { "SQLSRV_ATTR_DECIMAL_PLACES" , SQLSRV_ATTR_DECIMAL_PLACES }, // used for the size for output parameters: PDO::PARAM_INT and PDO::PARAM_BOOL use the default size of int, // PDO::PARAM_STR uses the size of the string in the variable diff --git a/source/pdo_sqlsrv/pdo_stmt.cpp b/source/pdo_sqlsrv/pdo_stmt.cpp index de1fc882a..d90fd50a7 100644 --- a/source/pdo_sqlsrv/pdo_stmt.cpp +++ b/source/pdo_sqlsrv/pdo_stmt.cpp @@ -883,7 +883,11 @@ int pdo_sqlsrv_stmt_set_attr( _Inout_ pdo_stmt_t *stmt, _In_ zend_long attr, _In break; case SQLSRV_ATTR_FORMAT_DECIMALS: - core_sqlsrv_set_format_decimals(driver_stmt, val TSRMLS_CC); + driver_stmt->format_decimals = ( zend_is_true( val )) ? true : false; + break; + + case SQLSRV_ATTR_DECIMAL_PLACES: + core_sqlsrv_set_decimal_places(driver_stmt, val TSRMLS_CC); break; default: @@ -973,6 +977,18 @@ int pdo_sqlsrv_stmt_get_attr( _Inout_ pdo_stmt_t *stmt, _In_ zend_long attr, _In break; } + case SQLSRV_ATTR_FORMAT_DECIMALS: + { + ZVAL_BOOL( return_value, driver_stmt->format_decimals ); + break; + } + + case SQLSRV_ATTR_DECIMAL_PLACES: + { + ZVAL_LONG( return_value, driver_stmt->decimal_places ); + break; + } + default: THROW_PDO_ERROR( driver_stmt, PDO_SQLSRV_ERROR_INVALID_STMT_ATTR ); break; diff --git a/source/pdo_sqlsrv/pdo_util.cpp b/source/pdo_sqlsrv/pdo_util.cpp index 0295b406b..4120876b0 100644 --- a/source/pdo_sqlsrv/pdo_util.cpp +++ b/source/pdo_sqlsrv/pdo_util.cpp @@ -438,13 +438,9 @@ pdo_error PDO_ERRORS[] = { { IMSSP, (SQLCHAR*) "The Azure AD Access Token is empty. Expected a byte string.", -91, false} }, { - SQLSRV_ERROR_INVALID_FORMAT_DECIMALS, + SQLSRV_ERROR_INVALID_DECIMAL_PLACES, { IMSSP, (SQLCHAR*) "Expected an integer to specify number of decimals to format the output values of decimal data types.", -92, false} }, - { - SQLSRV_ERROR_FORMAT_DECIMALS_OUT_OF_RANGE, - { IMSSP, (SQLCHAR*) "For formatting decimal data values, %1!d! is out of range. Expected an integer from 0 to 38, inclusive.", -93, true} - }, { UINT_MAX, {} } }; diff --git a/source/pdo_sqlsrv/php_pdo_sqlsrv.h b/source/pdo_sqlsrv/php_pdo_sqlsrv.h index ced89eeef..d9bb55e59 100644 --- a/source/pdo_sqlsrv/php_pdo_sqlsrv.h +++ b/source/pdo_sqlsrv/php_pdo_sqlsrv.h @@ -49,7 +49,8 @@ enum PDO_SQLSRV_ATTR { SQLSRV_ATTR_CLIENT_BUFFER_MAX_KB_SIZE, SQLSRV_ATTR_FETCHES_NUMERIC_TYPE, SQLSRV_ATTR_FETCHES_DATETIME_TYPE, - SQLSRV_ATTR_FORMAT_DECIMALS + SQLSRV_ATTR_FORMAT_DECIMALS, + SQLSRV_ATTR_DECIMAL_PLACES }; // valid set of values for TransactionIsolation connection option @@ -206,6 +207,8 @@ struct pdo_sqlsrv_dbh : public sqlsrv_conn { zend_long client_buffer_max_size; bool fetch_numeric; bool fetch_datetime; + bool format_decimals; + short decimal_places; pdo_sqlsrv_dbh( _In_ SQLHANDLE h, _In_ error_callback e, _In_ void* driver TSRMLS_DC ); }; @@ -267,6 +270,8 @@ struct pdo_sqlsrv_stmt : public sqlsrv_stmt { direct_query = db->direct_query; fetch_numeric = db->fetch_numeric; fetch_datetime = db->fetch_datetime; + format_decimals = db->format_decimals; + decimal_places = db->decimal_places; } virtual ~pdo_sqlsrv_stmt( void ); diff --git a/source/shared/core_sqlsrv.h b/source/shared/core_sqlsrv.h index 91be215d8..363ccad19 100644 --- a/source/shared/core_sqlsrv.h +++ b/source/shared/core_sqlsrv.h @@ -173,6 +173,8 @@ const int SQL_SERVER_MAX_FIELD_SIZE = 8000; const int SQL_SERVER_MAX_PRECISION = 38; const int SQL_SERVER_MAX_TYPE_SIZE = 0; const int SQL_SERVER_MAX_PARAMS = 2100; +const int SQL_SERVER_MAX_MONEY_SCALE = 4; + // increase the maximum message length to accommodate for the long error returned for operand type clash // or for conversion of a long string const int SQL_MAX_ERROR_MESSAGE_LENGTH = SQL_MAX_MESSAGE_LENGTH * 2; @@ -230,6 +232,9 @@ enum SQLSRV_FETCH_TYPE { // buffer size of a sql state (including the null character) const int SQL_SQLSTATE_BUFSIZE = SQL_SQLSTATE_SIZE + 1; +// default value of decimal places (no formatting required) +const short NO_CHANGE_DECIMAL_PLACES = -1; + // buffer size allocated to retrieve data from a PHP stream. This number // was chosen since PHP doesn't return more than 8k at a time even if // the amount requested was more. @@ -1108,6 +1113,7 @@ enum SQLSRV_STMT_OPTIONS { SQLSRV_STMT_OPTION_CLIENT_BUFFER_MAX_SIZE, SQLSRV_STMT_OPTION_DATE_AS_STRING, SQLSRV_STMT_OPTION_FORMAT_DECIMALS, + SQLSRV_STMT_OPTION_DECIMAL_PLACES, // Driver specific connection options SQLSRV_STMT_OPTION_DRIVER_SPECIFIC = 1000, @@ -1302,6 +1308,11 @@ struct stmt_option_format_decimals : public stmt_option_functor { virtual void operator()( _Inout_ sqlsrv_stmt* stmt, stmt_option const* opt, _In_ zval* value_z TSRMLS_DC ); }; +struct stmt_option_decimal_places : public stmt_option_functor { + + virtual void operator()( _Inout_ sqlsrv_stmt* stmt, stmt_option const* opt, _In_ zval* value_z TSRMLS_DC ); +}; + // used to hold the table for statment options struct stmt_option { @@ -1372,7 +1383,7 @@ struct sqlsrv_output_param { SQLLEN original_buffer_len; // used to make sure the returned length didn't overflow the buffer SQLSRV_PHPTYPE php_out_type; // used to convert output param if necessary bool is_bool; - param_meta_data meta_data; // parameter meta data + param_meta_data meta_data; // parameter meta data // string output param constructor sqlsrv_output_param( _In_ zval* p_z, _In_ SQLSRV_ENCODING enc, _In_ int num, _In_ SQLUINTEGER buffer_len ) : @@ -1399,15 +1410,9 @@ struct sqlsrv_output_param { meta_data.nullable = nullable; } - SQLSMALLINT getDecimalDigits() + param_meta_data& getMetaData() { - // Return decimal_digits only for decimal / numeric types. Otherwise, return -1 - if (meta_data.sql_type == SQL_DECIMAL || meta_data.sql_type == SQL_NUMERIC) { - return meta_data.decimal_digits; - } - else { - return -1; - } + return meta_data; } }; @@ -1435,7 +1440,8 @@ struct sqlsrv_stmt : public sqlsrv_context { unsigned long query_timeout; // maximum allowed statement execution time zend_long buffered_query_limit; // maximum allowed memory for a buffered query (measured in KB) bool date_as_string; // false by default but the user can set this to true to retrieve datetime values as strings - short num_decimals; // indicates number of decimals shown in fetched results (-1 by default, which means no formatting required) + bool format_decimals; // false by default but the user can set this to true to add the missing leading zeroes and/or control number of decimal digits to show + short decimal_places; // indicates number of decimals shown in fetched results (-1 by default, which means no change to number of decimal digits) // holds output pointers for SQLBindParameter // We use a deque because it 1) provides the at/[] access in constant time, and 2) grows dynamically without moving @@ -1476,9 +1482,10 @@ struct field_meta_data { SQLULEN field_precision; SQLSMALLINT field_scale; SQLSMALLINT field_is_nullable; + bool field_is_money_type; field_meta_data() : field_name_len(0), field_type(0), field_size(0), field_precision(0), - field_scale (0), field_is_nullable(0) + field_scale (0), field_is_nullable(0), field_is_money_type(false) { } @@ -1527,7 +1534,7 @@ void core_sqlsrv_set_send_at_exec( _Inout_ sqlsrv_stmt* stmt, _In_ zval* value_z bool core_sqlsrv_send_stream_packet( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ); void core_sqlsrv_set_buffered_query_limit( _Inout_ sqlsrv_stmt* stmt, _In_ zval* value_z TSRMLS_DC ); void core_sqlsrv_set_buffered_query_limit( _Inout_ sqlsrv_stmt* stmt, _In_ SQLLEN limit TSRMLS_DC ); -void core_sqlsrv_set_format_decimals(_Inout_ sqlsrv_stmt* stmt, _In_ zval* value_z TSRMLS_DC); +void core_sqlsrv_set_decimal_places(_Inout_ sqlsrv_stmt* stmt, _In_ zval* value_z TSRMLS_DC); //********************************************************************************************************************************* // Result Set @@ -1769,8 +1776,7 @@ enum SQLSRV_ERROR_CODES { SQLSRV_ERROR_DOUBLE_CONVERSION_FAILED, SQLSRV_ERROR_INVALID_OPTION_WITH_ACCESS_TOKEN, SQLSRV_ERROR_EMPTY_ACCESS_TOKEN, - SQLSRV_ERROR_INVALID_FORMAT_DECIMALS, - SQLSRV_ERROR_FORMAT_DECIMALS_OUT_OF_RANGE, + SQLSRV_ERROR_INVALID_DECIMAL_PLACES, // Driver specific error codes starts from here. SQLSRV_ERROR_DRIVER_SPECIFIC = 1000, diff --git a/source/shared/core_stmt.cpp b/source/shared/core_stmt.cpp index 206fe11d5..8a4cc227d 100644 --- a/source/shared/core_stmt.cpp +++ b/source/shared/core_stmt.cpp @@ -107,7 +107,7 @@ void default_sql_type( _Inout_ sqlsrv_stmt* stmt, _In_opt_ SQLULEN paramno, _In_ _Out_ SQLSMALLINT& sql_type TSRMLS_DC ); void col_cache_dtor( _Inout_ zval* data_z ); void field_cache_dtor( _Inout_ zval* data_z ); -void format_decimal_numbers(_In_ SQLSMALLINT decimals_digits, _In_ SQLSMALLINT field_scale, _Inout_updates_bytes_(*field_len) char*& field_value, _Inout_ SQLLEN* field_len); +void format_decimal_numbers(_In_ SQLSMALLINT decimals_places, _In_ SQLSMALLINT field_scale, _Inout_updates_bytes_(*field_len) char*& field_value, _Inout_ SQLLEN* field_len); void finalize_output_parameters( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ); void get_field_as_string( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT field_index, _Inout_ sqlsrv_phptype sqlsrv_php_type, _Inout_updates_bytes_(*field_len) void*& field_value, _Inout_ SQLLEN* field_len TSRMLS_DC ); @@ -142,7 +142,8 @@ sqlsrv_stmt::sqlsrv_stmt( _In_ sqlsrv_conn* c, _In_ SQLHANDLE handle, _In_ error past_next_result_end( false ), query_timeout( QUERY_TIMEOUT_INVALID ), date_as_string(false), - num_decimals(-1), // -1 means no formatting required + format_decimals(false), // no formatting needed + decimal_places(NO_CHANGE_DECIMAL_PLACES), // the default is no formatting to resultset required buffered_query_limit( sqlsrv_buffered_result_set::BUFFERED_QUERY_LIMIT_INVALID ), param_ind_ptrs( 10 ), // initially hold 10 elements, which should cover 90% of the cases and only take < 100 byte send_streams_at_exec( true ), @@ -925,6 +926,19 @@ field_meta_data* core_sqlsrv_field_metadata( _Inout_ sqlsrv_stmt* stmt, _In_ SQL } } + if (meta_data->field_type == SQL_DECIMAL) { + // Check if it is money type -- get the name of the data type + char field_type_name[SS_MAXCOLNAMELEN] = {'\0'}; + SQLSMALLINT out_buff_len; + SQLLEN not_used; + core::SQLColAttribute(stmt, colno + 1, SQL_DESC_TYPE_NAME, field_type_name, + sizeof( field_type_name ), &out_buff_len, ¬_used TSRMLS_CC); + + if (!strcmp(field_type_name, "money") || !strcmp(field_type_name, "smallmoney")) { + meta_data->field_is_money_type = true; + } + } + // Set the field name lenth meta_data->field_name_len = static_cast( field_name_len ); @@ -1258,20 +1272,21 @@ void core_sqlsrv_set_query_timeout( _Inout_ sqlsrv_stmt* stmt, _In_ long timeout } } -void core_sqlsrv_set_format_decimals(_Inout_ sqlsrv_stmt* stmt, _In_ zval* value_z TSRMLS_DC) +void core_sqlsrv_set_decimal_places(_Inout_ sqlsrv_stmt* stmt, _In_ zval* value_z TSRMLS_DC) { try { // first check if the input is an integer - CHECK_CUSTOM_ERROR(Z_TYPE_P(value_z) != IS_LONG, stmt, SQLSRV_ERROR_INVALID_FORMAT_DECIMALS) { + CHECK_CUSTOM_ERROR(Z_TYPE_P(value_z) != IS_LONG, stmt, SQLSRV_ERROR_INVALID_DECIMAL_PLACES) { throw core::CoreException(); } - zend_long format_decimals = Z_LVAL_P(value_z); - CHECK_CUSTOM_ERROR(format_decimals < 0 || format_decimals > SQL_SERVER_MAX_PRECISION, stmt, SQLSRV_ERROR_FORMAT_DECIMALS_OUT_OF_RANGE, format_decimals) { - throw core::CoreException(); + zend_long decimal_places = Z_LVAL_P(value_z); + if (decimal_places < 0 || decimal_places > SQL_SERVER_MAX_MONEY_SCALE) { + // ignore decimal_places because it is out of range + decimal_places = NO_CHANGE_DECIMAL_PLACES; } - stmt->num_decimals = static_cast(format_decimals); + stmt->decimal_places = static_cast(decimal_places); } catch( core::CoreException& ) { throw; @@ -1447,7 +1462,17 @@ void stmt_option_date_as_string:: operator()( _Inout_ sqlsrv_stmt* stmt, stmt_op void stmt_option_format_decimals:: operator()( _Inout_ sqlsrv_stmt* stmt, stmt_option const* /**/, _In_ zval* value_z TSRMLS_DC ) { - core_sqlsrv_set_format_decimals(stmt, value_z TSRMLS_CC); + if (zend_is_true(value_z)) { + stmt->format_decimals = true; + } + else { + stmt->format_decimals = false; + } +} + +void stmt_option_decimal_places:: operator()( _Inout_ sqlsrv_stmt* stmt, stmt_option const* /**/, _In_ zval* value_z TSRMLS_DC ) +{ + core_sqlsrv_set_decimal_places(stmt, value_z TSRMLS_CC); } // internal function to release the active stream. Called by each main API function @@ -2114,25 +2139,29 @@ void field_cache_dtor( _Inout_ zval* data_z ) } // To be called for formatting decimal / numeric fetched values from finalize_output_parameters() and/or get_field_as_string() -void format_decimal_numbers(_In_ SQLSMALLINT decimals_digits, _In_ SQLSMALLINT field_scale, _Inout_updates_bytes_(*field_len) char*& field_value, _Inout_ SQLLEN* field_len) +void format_decimal_numbers(_In_ SQLSMALLINT decimals_places, _In_ SQLSMALLINT field_scale, _Inout_updates_bytes_(*field_len) char*& field_value, _Inout_ SQLLEN* field_len) { // In SQL Server, the default maximum precision of numeric and decimal data types is 38 // - // Note: stmt->num_decimals is -1 by default, which means no formatting on decimals / numerics is necessary - // If the required number of decimals is larger than the field scale, will use the column field scale instead. - // This is to ensure the number of decimals adheres to the column field scale. If smaller, the output value may be rounded up. + // Note: decimals_places is NO_CHANGE_DECIMAL_PLACES by default, which means no formatting on decimal data is necessary + // This function assumes stmt->format_decimals is true, so it first checks if it is necessary to add the leading zero. + // + // Likewise, if decimals_places is larger than the field scale, decimals_places wil be ignored. This is to ensure the + // number of decimals adheres to the column field scale. If smaller, the output value may be rounded up. // - // Note: it's possible that the decimal / numeric value does not contain a decimal dot because the field scale is 0. - // Thus, first check if the decimal dot exists. If not, no formatting necessary, regardless of decimals_digits + // Note: it's possible that the decimal data does not contain a decimal dot because the field scale is 0. + // Thus, first check if the decimal dot exists. If not, no formatting necessary, regardless of + // format_decimals and decimals_places // std::string str = field_value; size_t pos = str.find_first_of('.'); - if (pos == std::string::npos || decimals_digits < 0) { + // The decimal dot is not found, simply return + if (pos == std::string::npos) { return; } - SQLSMALLINT num_decimals = decimals_digits; + SQLSMALLINT num_decimals = decimals_places; if (num_decimals > field_scale) { num_decimals = field_scale; } @@ -2160,47 +2189,24 @@ void format_decimal_numbers(_In_ SQLSMALLINT decimals_digits, _In_ SQLSMALLINT f pos++; } - size_t last = 0; - if (num_decimals == 0) { - // Chop all decimal digits, including the decimal dot - size_t pos2 = pos + 1; - short n = str[pos2] - '0'; - if (n >= 5) { - // Start rounding up - starting from the digit left of the dot all the way to the first digit - bool carry_over = true; - for (short p = pos - 1; p >= 0 && carry_over; p--) { - n = str[p] - '0'; - if (n == 9) { - str[p] = '0' ; - carry_over = true; - } - else { - n++; - carry_over = false; - str[p] = '0' + n; - } - } - if (carry_over) { - std::ostringstream oss; - oss << '1' << str.substr(0, pos); - str = oss.str(); - pos++; - } - } - last = pos; - } - else { - size_t pos2 = pos + num_decimals + 1; - // No need to check if rounding is necessary when pos2 has passed the last digit in the input string - if (pos2 < str.length()) { + if (num_decimals == NO_CHANGE_DECIMAL_PLACES) { + // Add the minus sign back if negative + if (isNegative) { + std::ostringstream oss; + oss << '-' << str.substr(0); + str = oss.str(); + } + } else { + // Start formatting + size_t last = 0; + if (num_decimals == 0) { + // Chop all decimal digits, including the decimal dot + size_t pos2 = pos + 1; short n = str[pos2] - '0'; if (n >= 5) { - // Start rounding up - starting from the digit left of pos2 all the way to the first digit + // Start rounding up - starting from the digit left of the dot all the way to the first digit bool carry_over = true; - for (short p = pos2 - 1; p >= 0 && carry_over; p--) { - if (str[p] == '.') { // Skip the dot - continue; - } + for (short p = pos - 1; p >= 0 && carry_over; p--) { n = str[p] - '0'; if (n == 9) { str[p] = '0' ; @@ -2214,22 +2220,54 @@ void format_decimal_numbers(_In_ SQLSMALLINT decimals_digits, _In_ SQLSMALLINT f } if (carry_over) { std::ostringstream oss; - oss << '1' << str.substr(0, pos2); + oss << '1' << str.substr(0, pos); str = oss.str(); - pos2++; + pos++; } } + last = pos; + } + else { + size_t pos2 = pos + num_decimals + 1; + // No need to check if rounding is necessary when pos2 has passed the last digit in the input string + if (pos2 < str.length()) { + short n = str[pos2] - '0'; + if (n >= 5) { + // Start rounding up - starting from the digit left of pos2 all the way to the first digit + bool carry_over = true; + for (short p = pos2 - 1; p >= 0 && carry_over; p--) { + if (str[p] == '.') { // Skip the dot + continue; + } + n = str[p] - '0'; + if (n == 9) { + str[p] = '0' ; + carry_over = true; + } + else { + n++; + carry_over = false; + str[p] = '0' + n; + } + } + if (carry_over) { + std::ostringstream oss; + oss << '1' << str.substr(0, pos2); + str = oss.str(); + pos2++; + } + } + } + last = pos2; + } + // Add the minus sign back if negative + if (isNegative) { + std::ostringstream oss; + oss << '-' << str.substr(0, last); + str = oss.str(); + } else { + str = str.substr(0, last); } - last = pos2; - } - - // Add the minus sign back if negative - if (isNegative) { - std::ostringstream oss; - oss << '-' << str.substr(0, last); - str = oss.str(); - } else { - str = str.substr(0, last); } size_t len = str.length(); @@ -2313,7 +2351,8 @@ void finalize_output_parameters( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) core::sqlsrv_zval_stringl(value_z, str, str_len); } else { - SQLSMALLINT decimal_digits = output_param->getDecimalDigits(); + //SQLSMALLINT decimal_digits = output_param->getDecimalDigits(); + param_meta_data metaData = output_param->getMetaData(); if (output_param->encoding != SQLSRV_ENCODING_CHAR) { char* outString = NULL; @@ -2323,15 +2362,16 @@ void finalize_output_parameters( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) throw core::CoreException(); } - if (stmt->num_decimals >= 0 && decimal_digits >= 0) { - format_decimal_numbers(stmt->num_decimals, decimal_digits, outString, &outLen); + if (stmt->format_decimals && (metaData.sql_type == SQL_DECIMAL || metaData.sql_type == SQL_NUMERIC)) { + format_decimal_numbers(NO_CHANGE_DECIMAL_PLACES, metaData.decimal_digits, outString, &outLen); } + core::sqlsrv_zval_stringl(value_z, outString, outLen); sqlsrv_free(outString); } else { - if (stmt->num_decimals >= 0 && decimal_digits >= 0) { - format_decimal_numbers(stmt->num_decimals, decimal_digits, str, &str_len); + if (stmt->format_decimals && (metaData.sql_type == SQL_DECIMAL || metaData.sql_type == SQL_NUMERIC)) { + format_decimal_numbers(NO_CHANGE_DECIMAL_PLACES, metaData.decimal_digits, str, &str_len); } core::sqlsrv_zval_stringl(value_z, str, str_len); @@ -2601,8 +2641,10 @@ void get_field_as_string( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT field_ind } } - if (stmt->num_decimals >= 0 && (sql_field_type == SQL_DECIMAL || sql_field_type == SQL_NUMERIC)) { - format_decimal_numbers(stmt->num_decimals, stmt->current_meta_data[field_index]->field_scale, field_value_temp, &field_len_temp); + if (stmt->format_decimals && (sql_field_type == SQL_DECIMAL || sql_field_type == SQL_NUMERIC)) { + // number of decimal places only affect money / smallmoney fields + SQLSMALLINT decimal_places = (stmt->current_meta_data[field_index]->field_is_money_type) ? stmt->decimal_places : NO_CHANGE_DECIMAL_PLACES; + format_decimal_numbers(decimal_places, stmt->current_meta_data[field_index]->field_scale, field_value_temp, &field_len_temp); } } // else if( sql_display_size >= 1 && sql_display_size <= SQL_SERVER_MAX_FIELD_SIZE ) diff --git a/source/sqlsrv/conn.cpp b/source/sqlsrv/conn.cpp index d5f324a23..60b9f0d16 100644 --- a/source/sqlsrv/conn.cpp +++ b/source/sqlsrv/conn.cpp @@ -46,6 +46,45 @@ struct date_as_string_func { } }; +struct format_decimals_func +{ + static void func(connection_option const* /*option*/, _In_ zval* value, _Inout_ sqlsrv_conn* conn, std::string& /*conn_str*/ TSRMLS_DC) + { + TSRMLS_C; // show as used to avoid a warning + + ss_sqlsrv_conn* ss_conn = static_cast(conn); + + if (zend_is_true(value)) { + ss_conn->format_decimals = true; + } + else { + ss_conn->format_decimals = false; + } + } +}; + +struct decimal_places_func +{ + + static void func(connection_option const* /*option*/, _In_ zval* value, _Inout_ sqlsrv_conn* conn, std::string& /*conn_str*/ TSRMLS_DC) + { + TSRMLS_C; // show as used to avoid a warning + + // first check if the input is an integer + if (Z_TYPE_P(value) != IS_LONG) { + THROW_SS_ERROR(conn, SQLSRV_ERROR_INVALID_DECIMAL_PLACES); + } + + zend_long decimal_places = Z_LVAL_P(value); + if (decimal_places < 0 || decimal_places > SQL_SERVER_MAX_MONEY_SCALE) { + decimal_places = NO_CHANGE_DECIMAL_PLACES; + } + + ss_sqlsrv_conn* ss_conn = static_cast(conn); + ss_conn->decimal_places = static_cast(decimal_places); + } +}; + struct conn_char_set_func { static void func( connection_option const* /*option*/, _Inout_ zval* value, _Inout_ sqlsrv_conn* conn, std::string& /*conn_str*/ TSRMLS_DC ) @@ -175,6 +214,7 @@ namespace SSStmtOptionNames { const char CLIENT_BUFFER_MAX_SIZE[] = INI_BUFFERED_QUERY_LIMIT; const char DATE_AS_STRING[] = "ReturnDatesAsStrings"; const char FORMAT_DECIMALS[] = "FormatDecimals"; + const char DECIMAL_PLACES[] = "DecimalPlaces"; } namespace SSConnOptionNames { @@ -192,6 +232,8 @@ const char ConnectionPooling[] = "ConnectionPooling"; const char ConnectRetryCount[] = "ConnectRetryCount"; const char ConnectRetryInterval[] = "ConnectRetryInterval"; const char Database[] = "Database"; +const char DecimalPlaces[] = "DecimalPlaces"; +const char FormatDecimals[] = "FormatDecimals"; const char DateAsString[] = "ReturnDatesAsStrings"; const char Driver[] = "Driver"; const char Encrypt[] = "Encrypt"; @@ -217,6 +259,8 @@ const char WSID[] = "WSID"; enum SS_CONN_OPTIONS { SS_CONN_OPTION_DATE_AS_STRING = SQLSRV_CONN_OPTION_DRIVER_SPECIFIC, + SS_CONN_OPTION_FORMAT_DECIMALS, + SS_CONN_OPTION_DECIMAL_PLACES, }; //List of all statement options supported by this driver @@ -257,6 +301,12 @@ const stmt_option SS_STMT_OPTS[] = { SQLSRV_STMT_OPTION_FORMAT_DECIMALS, std::unique_ptr( new stmt_option_format_decimals ) }, + { + SSStmtOptionNames::DECIMAL_PLACES, + sizeof( SSStmtOptionNames::DECIMAL_PLACES), + SQLSRV_STMT_OPTION_DECIMAL_PLACES, + std::unique_ptr( new stmt_option_decimal_places ) + }, { NULL, 0, SQLSRV_STMT_OPTION_INVALID, std::unique_ptr{} }, }; @@ -515,6 +565,24 @@ const connection_option SS_CONN_OPTS[] = { CONN_ATTR_BOOL, date_as_string_func::func }, + { + SSConnOptionNames::FormatDecimals, + sizeof( SSConnOptionNames::FormatDecimals), + SS_CONN_OPTION_FORMAT_DECIMALS, + SSConnOptionNames::FormatDecimals, + sizeof( SSConnOptionNames::FormatDecimals), + CONN_ATTR_BOOL, + format_decimals_func::func + }, + { + SSConnOptionNames::DecimalPlaces, + sizeof( SSConnOptionNames::DecimalPlaces), + SS_CONN_OPTION_DECIMAL_PLACES, + SSConnOptionNames::DecimalPlaces, + sizeof( SSConnOptionNames::DecimalPlaces), + CONN_ATTR_INT, + decimal_places_func::func + }, { NULL, 0, SQLSRV_CONN_OPTION_INVALID, NULL, 0 , CONN_ATTR_INVALID, NULL }, //terminate the table }; diff --git a/source/sqlsrv/php_sqlsrv.h b/source/sqlsrv/php_sqlsrv.h index 1816942ac..3f77ecbcf 100644 --- a/source/sqlsrv/php_sqlsrv.h +++ b/source/sqlsrv/php_sqlsrv.h @@ -131,6 +131,8 @@ struct ss_sqlsrv_conn : sqlsrv_conn { HashTable* stmts; bool date_as_string; + bool format_decimals; // flag set to turn on formatting for values of decimal / numeric types + short decimal_places; // number of decimal digits to show in a result set unless format_numbers is false bool in_transaction; // flag set when inside a transaction and used for checking validity of tran API calls // static variables used in process_params @@ -142,6 +144,8 @@ struct ss_sqlsrv_conn : sqlsrv_conn sqlsrv_conn( h, e, drv, SQLSRV_ENCODING_SYSTEM TSRMLS_CC ), stmts( NULL ), date_as_string( false ), + format_decimals( false ), + decimal_places( NO_CHANGE_DECIMAL_PLACES ), in_transaction( false ) { } diff --git a/source/sqlsrv/stmt.cpp b/source/sqlsrv/stmt.cpp index 3da4ebcc7..e9ce41e8a 100644 --- a/source/sqlsrv/stmt.cpp +++ b/source/sqlsrv/stmt.cpp @@ -139,9 +139,11 @@ ss_sqlsrv_stmt::ss_sqlsrv_stmt( _In_ sqlsrv_conn* c, _In_ SQLHANDLE handle, _In_ { core_sqlsrv_set_buffered_query_limit( this, SQLSRV_G( buffered_query_limit ) TSRMLS_CC ); - // initialize date_as_string based on the corresponding connection option + // inherit other values based on the corresponding connection options ss_sqlsrv_conn* ss_conn = static_cast(conn); date_as_string = ss_conn->date_as_string; + format_decimals = ss_conn->format_decimals; + decimal_places = ss_conn->decimal_places; } ss_sqlsrv_stmt::~ss_sqlsrv_stmt( void ) diff --git a/source/sqlsrv/util.cpp b/source/sqlsrv/util.cpp index 545f699d0..ff9e7c863 100644 --- a/source/sqlsrv/util.cpp +++ b/source/sqlsrv/util.cpp @@ -429,13 +429,9 @@ ss_error SS_ERRORS[] = { { IMSSP, (SQLCHAR*) "The Azure AD Access Token is empty. Expected a byte string.", -116, false} }, { - SQLSRV_ERROR_INVALID_FORMAT_DECIMALS, + SQLSRV_ERROR_INVALID_DECIMAL_PLACES, { IMSSP, (SQLCHAR*) "Expected an integer to specify number of decimals to format the output values of decimal data types.", -117, false} }, - { - SQLSRV_ERROR_FORMAT_DECIMALS_OUT_OF_RANGE, - { IMSSP, (SQLCHAR*) "For formatting decimal data values, %1!d! is out of range. Expected an integer from 0 to 38, inclusive.", -118, true} - }, // terminate the list of errors/warnings { UINT_MAX, {} } diff --git a/test/functional/pdo_sqlsrv/pdostatement_format_decimals.phpt b/test/functional/pdo_sqlsrv/pdostatement_format_decimals.phpt index ff29a8086..07303c4b7 100644 --- a/test/functional/pdo_sqlsrv/pdostatement_format_decimals.phpt +++ b/test/functional/pdo_sqlsrv/pdostatement_format_decimals.phpt @@ -1,24 +1,17 @@ --TEST-- -Test statement attribute PDO::SQLSRV_ATTR_FORMAT_DECIMALS for decimal types +Test connection and statement attributes for formatting decimal and numeric data (feature request issue 415) --DESCRIPTION-- -Test statement attribute PDO::SQLSRV_ATTR_FORMAT_DECIMALS for decimal or -money types (feature request issue 415), which are always fetched as strings -to preserve accuracy and precision, unlike other primitive numeric types, -where there is an option to retrieve them as numbers. +Test the attributes PDO::SQLSRV_ATTR_FORMAT_DECIMALS and PDO::SQLSRV_ATTR_DECIMAL_PLACES, the latter affects money types only, not decimal or numeric types (feature request issue 415). +Money, decimal or numeric types are always fetched as strings to preserve accuracy and precision, unlike other primitive numeric types, where there is an option to retrieve them as numbers. -This attribute expects an integer value from the range [0,38], the money or -decimal types in the fetched result set can be formatted. - -No effect on other operations like insertion or update. +Setting PDO::SQLSRV_ATTR_FORMAT_DECIMALS to false will turn off all formatting, regardless of PDO::SQLSRV_ATTR_DECIMAL_PLACES value. Also, any negative PDO::SQLSRV_ATTR_DECIMAL_PLACES value will be ignored. Likewise, since money or smallmoney fields have scale 4, if PDO::SQLSRV_ATTR_DECIMAL_PLACES value is larger than 4, it will be ignored as well. 1. By default, data will be returned with the original precision and scale -2. The data column original scale still takes precedence – for example, if the user -specifies 3 decimal digits for a column of decimal(5,2), the result still shows only 2 -decimals to the right of the dot -3. After formatting, the missing leading zeroes will be padded -4. The underlying data will not be altered, but formatted results may likely be rounded -up (e.g. .2954 will be displayed as 0.30 if the user wants only two decimals) -5. Do not support output params +2. Set PDO::SQLSRV_ATTR_FORMAT_DECIMALS to true to add the leading zeroes to money and decimal types, if missing. +3. No support for output params + +The attributes PDO::SQLSRV_ATTR_FORMAT_DECIMALS and PDO::SQLSRV_ATTR_DECIMAL_PLACES will only format the +fetched results and have no effect on other operations like insertion or update. --ENV-- PHPT_EXEC=true --SKIPIF-- @@ -35,171 +28,52 @@ function checkException($exception, $expected) } } -function testPdoAttribute($conn, $setAttr) +function testErrorCases($conn) { - // Expects exception because PDO::SQLSRV_ATTR_FORMAT_DECIMALS - // is a statement level attribute + $expected = 'Expected an integer to specify number of decimals to format the output values of decimal data types'; + $query = "SELECT 0.0001"; + try { - $res = true; - if ($setAttr) { - $res = $conn->setAttribute(PDO::SQLSRV_ATTR_FORMAT_DECIMALS, 1); - } else { - $res = $conn->getAttribute(PDO::SQLSRV_ATTR_FORMAT_DECIMALS); - } - if ($res) { - echo "setAttribute at PDO level should have failed!\n"; + $conn->setAttribute(PDO::SQLSRV_ATTR_FORMAT_DECIMALS, 0); + $format = $conn->getAttribute(PDO::SQLSRV_ATTR_FORMAT_DECIMALS); + if ($format !== false) { + echo 'The value of PDO::SQLSRV_ATTR_FORMAT_DECIMALS should be false\n'; + var_dump($format); } + + $conn->setAttribute(PDO::SQLSRV_ATTR_DECIMAL_PLACES, 1.5); } catch (PdoException $e) { - if ($setAttr) { - $expected = 'The given attribute is only supported on the PDOStatement object.'; - } else { - $expected = 'driver does not support that attribute'; - } - checkException($e, $expected); } -} - -function testErrorCases($conn) -{ - $query = "SELECT 0.0001"; try { - $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => 0.9); + $options = array(PDO::SQLSRV_ATTR_DECIMAL_PLACES => 0.9); $stmt = $conn->prepare($query, $options); } catch (PdoException $e) { - $expected = 'Expected an integer to specify number of decimals to format the output values of decimal data types'; checkException($e, $expected); } try { - $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => 100); + $options = array(PDO::SQLSRV_ATTR_DECIMAL_PLACES => true); $stmt = $conn->prepare($query, $options); } catch (PdoException $e) { - $expected = 'For formatting decimal data values, 100 is out of range. Expected an integer from 0 to 38, inclusive.'; checkException($e, $expected); } } -function verifyMoneyValues($conn, $query, $values, $numDigits) -{ - $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => $numDigits); - $stmt = $conn->prepare($query, $options); - $stmt->execute(); - $results = $stmt->fetch(PDO::FETCH_NUM); - - trace("\nverifyMoneyValues:\n"); - for ($i = 0; $i < count($values); $i++) { - $value = number_format($values[$i], $numDigits); - trace("$results[$i], $value\n"); - - if ($value !== $results[$i]) { - echo "testMoneyTypes: Expected $value but got $results[$i]\n"; - } - } -} - -function testFloatTypes($conn) -{ - // This test with the float types of various number of bits, which are retrieved - // as numbers by default. When fetched as strings, no formatting is done even with - // the statement option FormatDecimals set - $epsilon = 0.001; - $values = array(); - for ($i = 0; $i < 5; $i++) { - $n1 = rand(1, 100); - $n2 = rand(1, 100); - $neg = ($i % 2 == 0) ? -1 : 1; - - $n = $neg * $n1 / $n2; - array_push($values, $n); - } - - $query = "SELECT CONVERT(float(1), $values[0]), - CONVERT(float(12), $values[1]), - CONVERT(float(24), $values[2]), - CONVERT(float(36), $values[3]), - CONVERT(float(53), $values[4])"; - $stmt = $conn->query($query); - $floats = $stmt->fetch(PDO::FETCH_NUM); - unset($stmt); - - // Set PDO::SQLSRV_ATTR_FORMAT_DECIMALS to 2 should - // have no effect on floating point numbers - $numDigits = 2; - $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => $numDigits); - $stmt = $conn->prepare($query, $options); - - // By default the floating point numbers are fetched as strings - for ($i = 0; $i < 5; $i++) { - $stmt->execute(); - $floatStr = $stmt->fetchColumn($i); - - $floatVal = floatVal($floats[$i]); - $floatVal1 = floatval($floatStr); - - trace("testFloatTypes: $floatVal1, $floatVal\n"); - - // Check if the numbers of decimal digits are the same - // It is highly unlikely but not impossible - $numbers = explode('.', $floatStr); - $len = strlen($numbers[1]); - if ($len == $numDigits && $floatVal1 != $floatVal) { - echo "Expected $floatVal but $floatVal1 returned. \n"; - } else { - $diff = abs($floatVal1 - $floatVal) / $floatVal; - if ($diff > $epsilon) { - echo "Expected $floatVal but $floatVal1 returned. \n"; - } - } - } -} - -function testMoneyTypes($conn) -{ - // With money and smallmoney types, which are essentially decimal types - // ODBC driver does not support Always Encrypted feature with money / smallmoney - $values = array('24.559', '0', '-0.946', '0.2985', '-99.675', '79.995'); - $defaults = array('24.5590', '.0000', '-.9460', '.2985', '-99.6750', '79.9950'); - - $query = "SELECT CONVERT(smallmoney, $values[0]), - CONVERT(money, $values[1]), - CONVERT(smallmoney, $values[2]), - CONVERT(money, $values[3]), - CONVERT(smallmoney, $values[4]), - CONVERT(money, $values[5])"; - - $stmt = $conn->query($query); - $results = $stmt->fetch(PDO::FETCH_NUM); - for ($i = 0; $i < count($values); $i++) { - if ($defaults[$i] !== $results[$i]) { - echo "testMoneyTypes: Expected $defaults[$i] but got $results[$i]\n"; - } - } - unset($stmt); - - // Set PDO::SQLSRV_ATTR_FORMAT_DECIMALS to 0 then 2 - verifyMoneyValues($conn, $query, $values, 0); - verifyMoneyValues($conn, $query, $values, 2); -} - -function compareNumbers($actual, $input, $column, $fieldScale, $formatDecimal = -1) +function compareNumbers($actual, $input, $column, $fieldScale, $format = true) { $matched = false; if ($actual === $input) { $matched = true; trace("Matched: $actual, $input\n"); } else { - // When $formatDecimal is negative, that means no formatting done - // Otherwise, if $formatDecimal > $fieldScale, will show $fieldScale decimal digits - if ($formatDecimal >= 0) { - $numDecimals = ($formatDecimal > $fieldScale) ? $fieldScale : $formatDecimal; - $expected = number_format($input, $numDecimals); - } else { - $expected = number_format($input, $fieldScale); + // if no formatting, there will be no leading zero + $expected = number_format($input, $fieldScale); + if (!$format) { if (abs($input) < 1) { // Since no formatting, the leading zero should not be there - trace("Drop leading zero of $input--"); + trace("Drop leading zero of $input: "); $expected = str_replace('0.', '.', $expected); } } @@ -207,7 +81,7 @@ function compareNumbers($actual, $input, $column, $fieldScale, $formatDecimal = if ($actual === $expected) { $matched = true; } else { - echo "For $column ($formatDecimal): expected $expected ($input) but the value is $actual\n"; + echo "For $column ($fieldScale): expected $expected ($input) but the value is $actual\n"; } } return $matched; @@ -223,35 +97,35 @@ function testNoOption($conn, $tableName, $inputs, $columns) $results = $stmt->fetch(PDO::FETCH_NUM); trace("\ntestNoOption:\n"); for ($i = 0; $i < count($inputs); $i++) { - compareNumbers($results[$i], $inputs[$i], $columns[$i], $i); + compareNumbers($results[$i], $inputs[$i], $columns[$i], $i, false); } } -function testStmtOption($conn, $tableName, $inputs, $columns, $formatDecimal, $withBuffer) +function testStmtOption($conn, $tableName, $inputs, $columns, $decimalPlaces, $withBuffer) { - // Decimal values should return decimal digits based on the valid statement - // option PDO::SQLSRV_ATTR_FORMAT_DECIMALS + // Decimal values should NOT be affected by the statement + // attribute PDO::SQLSRV_ATTR_FORMAT_DECIMALS $query = "SELECT * FROM $tableName"; if ($withBuffer){ $options = array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL, PDO::SQLSRV_ATTR_CURSOR_SCROLL_TYPE => PDO::SQLSRV_CURSOR_BUFFERED, - PDO::SQLSRV_ATTR_FORMAT_DECIMALS => $formatDecimal); + PDO::SQLSRV_ATTR_DECIMAL_PLACES => $decimalPlaces); } else { - $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => $formatDecimal); + $options = array(PDO::SQLSRV_ATTR_DECIMAL_PLACES => $decimalPlaces); } $size = count($inputs); $stmt = $conn->prepare($query, $options); // Fetch by getting one field at a time - trace("\ntestStmtOption: $formatDecimal and buffered $withBuffer\n"); + trace("\ntestStmtOption: $decimalPlaces and buffered $withBuffer\n"); for ($i = 0; $i < $size; $i++) { $stmt->execute(); $stmt->bindColumn($columns[$i], $field); $result = $stmt->fetch(PDO::FETCH_BOUND); - compareNumbers($field, $inputs[$i], $columns[$i], $i, $formatDecimal); + compareNumbers($field, $inputs[$i], $columns[$i], $i); } } @@ -262,7 +136,7 @@ function getOutputParam($conn, $storedProcName, $inputValue, $prec, $scale, $ino $outSql = getCallProcSqlPlaceholders($storedProcName, 1); - $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => $numDigits); + $options = array(PDO::SQLSRV_ATTR_DECIMAL_PLACES => $numDigits); $stmt = $conn->prepare($outSql, $options); $len = 1024; @@ -279,17 +153,17 @@ function getOutputParam($conn, $storedProcName, $inputValue, $prec, $scale, $ino $stmt->execute(); // The output param value should be the same as the input value, - // unaffected by the statement attr PDO::SQLSRV_ATTR_FORMAT_DECIMALS, - // unless ColumnEncryption is enabled, in which case the driver is able - // to derive the decimal type + // unaffected by the statement attr PDO::SQLSRV_ATTR_DECIMAL_PLACES. + // If ColumnEncryption is enabled, in which case the driver is able + // to derive the decimal type, leading zero will be added if missing if (isAEConnected()) { trace("\ngetOutputParam ($inout) with AE:\n"); $column = 'outputParamAE'; - compareNumbers($outString, $inputValue, $column, $scale, $numDigits); + compareNumbers($outString, $inputValue, $column, $scale, true); } else { trace("\ngetOutputParam ($inout) without AE:\n"); $column = 'outputParam'; - compareNumbers($outString, $inputValue, $column, $scale); + compareNumbers($outString, $inputValue, $column, $scale, false); } } @@ -314,16 +188,8 @@ try { $conn = connect(); // Test some error conditions - testPdoAttribute($conn, true); - testPdoAttribute($conn, false); testErrorCases($conn); - // First test with money types - testMoneyTypes($conn); - - // Also test using regular floats - testFloatTypes($conn); - // Create the test table of decimal / numeric data columns $tableName = 'pdoFormatDecimals'; @@ -347,8 +213,8 @@ try { $n = rand(1, 6); $neg = ($n % 2 == 0) ? -1 : 1; - // $n1 may or may not be negative - $n1 = rand(0, 1000) * $neg; + // $n1, a tiny number, which may or may not be negative, + $n1 = rand(0, 5) * $neg; if ($s > 0) { $max *= 10; @@ -371,6 +237,11 @@ try { testNoOption($conn, $tableName, $values, $columns, true); + // Turn on formatting, which only add leading zeroes, if missing + // decimal and numeric types should be unaffected by + // PDO::SQLSRV_ATTR_DECIMAL_PLACES whatsoever + $conn->setAttribute(PDO::SQLSRV_ATTR_FORMAT_DECIMALS, true); + // Now try with setting number decimals to 3 then 2 testStmtOption($conn, $tableName, $values, $columns, 3, false); testStmtOption($conn, $tableName, $values, $columns, 3, true); diff --git a/test/functional/pdo_sqlsrv/pdostatement_format_decimals_scales.phpt b/test/functional/pdo_sqlsrv/pdostatement_format_decimals_scales.phpt deleted file mode 100644 index a8a40d482..000000000 --- a/test/functional/pdo_sqlsrv/pdostatement_format_decimals_scales.phpt +++ /dev/null @@ -1,248 +0,0 @@ ---TEST-- -Test various precisions of formatting decimal data output values (feature request issue 415) ---DESCRIPTION-- -In SQL Server, the maximum allowed precision is 38. The scale can range from 0 up to the -defined precision. Generate a long numeric string and get rid of the last digit to make it a -39-digit-string. Then replace one digit at a time with a dot '.' to make it a decimal -input string for testing with various scales. -For example, -string(39) ".23456789012345678901234567890123456789" -string(39) "1.3456789012345678901234567890123456789" -string(39) "12.456789012345678901234567890123456789" -string(39) "123.56789012345678901234567890123456789" -string(39) "1234.6789012345678901234567890123456789" -string(39) "12345.789012345678901234567890123456789" -... ... -string(39) "1234567890123456789012345678901234.6789" -string(39) "12345678901234567890123456789012345.789" -string(39) "123456789012345678901234567890123456.89" -string(39) "1234567890123456789012345678901234567.9" -string(38) "12345678901234567890123456789012345678" - -Note: PHP number_format() will not be used for verification in this test -because the function starts losing accuracy with large number of precisions / scales. ---ENV-- -PHPT_EXEC=true ---SKIPIF-- - ---FILE-- - $digits)); - - // Restore the $i-th digit with its original digit - $digits[$i] = $d; - } - - $stmt = insertRow($conn, $tableName, $inputData); - unset($stmt); - - return $inputData; -} - -function verifyNoDecimals($value, $input, $round) -{ - global $prec, $dot; - - // Use PHP explode() to separate the input string into an array - $parts = explode($dot, $input); - $len = strlen($parts[0]); - if ($len == 0) { - // The original input string is missing a leading zero - $parts[0] = '0'; - } - - // No need to worry about carry over for the input data of this test - // Check the first digit of $parts[1] - if ($len < $prec) { - // Only need to round up when $len < $prec - $ch = $parts[1][0]; - - // Round the last digit of $parts[0] if $ch is '5' or above - if ($ch >= '5') { - $len = strlen($parts[0]); - $parts[0][$len-1] = $parts[0][$len-1] + 1 + '0'; - } - } - - // No decimal digits left in the expected string - $expected = $parts[0]; - if ($value !== $expected) { - echo "Round $round scale 0: expected $expected but returned $value\n"; - } -} - -function verifyWithDecimals($value, $input, $round, $scale) -{ - global $dot; - - // Use PHP explode() to separate the input string into an array - $parts = explode($dot, $input); - if (strlen($parts[0]) == 0) { - // The original input string is missing a leading zero - $parts[0] = '0'; - } - - // No need to worry about carry over for the input data of this test - // Check the digit at the position $scale of $parts[1] - $len = strlen($parts[1]); - if ($scale < $len) { - // Only need to round up when $scale < $len - $ch = $parts[1][$scale]; - - // Round the previous digit if $ch is '5' or above - if ($ch >= '5') { - $parts[1][$scale-1] = $parts[1][$scale-1] + 1 + '0'; - } - } - - // Use substr() to get up to $scale - $parts[1] = substr($parts[1], 0, $scale); - - // Join the array elements together - $expected = implode($dot, $parts); - if ($value !== $expected) { - echo "Round $round scale $scale: expected $expected but returned $value\n"; - } -} - -/**** -The function testVariousScales() will fetch one column at a time, using scale from -0 up to the maximum scale allowed for that column type. - -For example, for column of type decimal(38,4), the input string is -1234567890123456789012345678901234.6789 - -When fetching data, using scale from 0 to 4, the following values are expected to return: -1234567890123456789012345678901235 -1234567890123456789012345678901234.7 -1234567890123456789012345678901234.68 -1234567890123456789012345678901234.679 -1234567890123456789012345678901234.6789 - -For example, for column of type decimal(38,6), the input string is -12345678901234567890123456789012.456789 - -When fetching data, using scale from 0 to 6, the following values are expected to return: -12345678901234567890123456789012 -12345678901234567890123456789012.5 -12345678901234567890123456789012.46 -12345678901234567890123456789012.457 -12345678901234567890123456789012.4568 -12345678901234567890123456789012.45679 -12345678901234567890123456789012.456789 - -etc. -****/ -function testVariousScales($conn, $tableName, $inputData) -{ - global $prec; - $max = $prec + 1; - - for ($i = 0; $i < $max; $i++) { - $scale = $prec - $i; - $column = "col_$scale"; - - $query = "SELECT $column as col1 FROM $tableName"; - $input = $inputData[$column]; - - // Default case: the fetched value should be the same as the corresponding input - $stmt = $conn->query($query); - if ($obj = $stmt->fetchObject()) { - trace("\n$obj->col1\n"); - if ($obj->col1 !== $input) { - echo "default case: expected $input but returned $obj->col1\n"; - } - } else { - echo "In testVariousScales: fetchObject failed\n"; - } - - // Next, format how many decimal digits to be displayed - $query = "SELECT $column FROM $tableName"; - for ($j = 0; $j <= $scale; $j++) { - $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => $j); - $stmt = $conn->prepare($query, $options); - $stmt->execute(); - - $stmt->bindColumn($column, $value); - if ($stmt->fetch(PDO::FETCH_BOUND)) { - trace("$value\n"); - if ($j == 0) { - verifyNoDecimals($value, $input, $i); - } else { - verifyWithDecimals($value, $input, $i, $j); - } - } else { - echo "Round $i scale $j: fetch failed\n"; - } - } - } -} - -try { - // This helper method sets PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION - $conn = connect(); - - $tableName = createTestTable($conn); - $inputData = insertTestData($conn, $tableName); - testVariousScales($conn, $tableName, $inputData); - - dropTable($conn, $tableName); - - echo "Done\n"; - - unset($conn); -} catch (PdoException $e) { - echo $e->getMessage() . PHP_EOL; -} -?> ---EXPECT-- -Done diff --git a/test/functional/pdo_sqlsrv/pdostatement_format_money_types.phpt b/test/functional/pdo_sqlsrv/pdostatement_format_money_types.phpt new file mode 100644 index 000000000..5152e1f59 --- /dev/null +++ b/test/functional/pdo_sqlsrv/pdostatement_format_money_types.phpt @@ -0,0 +1,245 @@ +--TEST-- +Test connection attributes for formatting money data (feature request issue 415) +--DESCRIPTION-- +Test how money data in the fetched values can be formatted by using the connection attributes PDO::SQLSRV_ATTR_FORMAT_DECIMALS and PDO::SQLSRV_ATTR_DECIMAL_PLACES, the latter works only with integer values. No effect on other operations like insertion or update. + +The PDO::SQLSRV_ATTR_DECIMAL_PLACES attribute only affects money/smallmoney fields. If its value is out of range, for example, it's negative or larger than the original scale, then its value will be ignored. + +The underlying data will not be altered, but formatted results may likely be rounded up (e.g. .2954 will be displayed as 0.30 if the user wants only two decimals). For this reason, it is not recommended to use formatted money values as inputs to any calculation. + +The corresponding statement attributes always override the inherited values from the connection object. Setting PDO::SQLSRV_ATTR_FORMAT_DECIMALS to false will automatically turn off any formatting of decimal data in the result set, ignoring PDO::SQLSRV_ATTR_DECIMAL_PLACES value. + +By only setting PDO::SQLSRV_ATTR_FORMAT_DECIMALS to true will add the leading zeroes, if missing. + +Do not support output params. +--ENV-- +PHPT_EXEC=true +--SKIPIF-- + +--FILE-- +query($query); + $floats = $stmt->fetch(PDO::FETCH_NUM); + unset($stmt); + + // By default the floating point numbers are fetched as strings + $stmt = $conn->prepare($query); + for ($i = 0; $i < 5; $i++) { + $stmt->execute(); + $floatStr = $stmt->fetchColumn($i); + + $floatVal = floatVal($floats[$i]); + $floatVal1 = floatval($floatStr); + + trace("testFloatTypes: $floatVal1, $floatVal\n"); + + // Check if the numbers of decimal digits are the same + // It is highly unlikely but not impossible + $numbers = explode('.', $floatStr); + $len = strlen($numbers[1]); + if ($len == $numDigits && $floatVal1 != $floatVal) { + echo "Expected $floatVal but $floatVal1 returned. \n"; + } else { + $diff = abs($floatVal1 - $floatVal) / $floatVal; + if ($diff > $epsilon) { + echo "$diff: Expected $floatVal but $floatVal1 returned. \n"; + } + } + } +} + +function verifyMoneyFormatting($conn, $query, $values, $format) +{ + if ($format) { + // Set SQLSRV_ATTR_FORMAT_DECIMALS to true but + // set SQLSRV_ATTR_DECIMAL_PLACES to a negative number + // to override the inherited attribute + $options = array(PDO::SQLSRV_ATTR_DECIMAL_PLACES => -1, PDO::SQLSRV_ATTR_FORMAT_DECIMALS => true); + } else { + // Set SQLSRV_ATTR_FORMAT_DECIMALS to false will + // turn off any formatting -- overriding the inherited + // attributes + $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => false); + } + + $stmt = $conn->prepare($query, $options); + $stmt->execute(); + $results = $stmt->fetch(PDO::FETCH_NUM); + + trace("\verifyMoneyFormatting:\n"); + for ($i = 0; $i < count($values); $i++) { + // money types have a scale of 4 + $default = numberFormat($values[$i], 4); + if (!$format) { + // No formatting - should drop the leading zero, if exists + if (abs($values[$i]) < 1) { + $default = str_replace('0.', '.', $default); + } + } + if ($default !== $results[$i]) { + echo "verifyMoneyFormatting ($format): Expected $default but got $results[$i]\n"; + } + } +} + +function verifyMoneyValues($conn, $numDigits, $query, $values, $override) +{ + if ($override) { + $options = array(PDO::SQLSRV_ATTR_DECIMAL_PLACES => $numDigits); + $stmt = $conn->prepare($query, $options); + } else { + // Use the connection defaults + $stmt = $conn->prepare($query); + } + $stmt->execute(); + $results = $stmt->fetch(PDO::FETCH_NUM); + + trace("\nverifyMoneyValues:\n"); + for ($i = 0; $i < count($values); $i++) { + $value = numberFormat($values[$i], $numDigits); + trace("$results[$i], $value\n"); + + if ($value !== $results[$i]) { + echo "testMoneyTypes ($override, $numDigits): Expected $value but got $results[$i]\n"; + } + } +} + +function testMoneyTypes($conn, $numDigits) +{ + // With money and smallmoney types, which are essentially decimal types + // As of today, ODBC driver does not support Always Encrypted feature with money / smallmoney + + $values = array(); + $nColumns = 6; + for ($i = 0; $i < $nColumns; $i++) { + // First get a random number + $n = rand(0, 10); + $neg = ($n % 2 == 0) ? -1 : 1; + + // $n1 may or may not be negative + $max = 10; + $n1 = rand(0, $max) * $neg; + $n2 = rand(1, $max * 1000); + + $number = sprintf("%d.%d", $n1, $n2); + array_push($values, $number); + } + + $query = "SELECT CONVERT(smallmoney, $values[0]), + CONVERT(money, $values[1]), + CONVERT(smallmoney, $values[2]), + CONVERT(money, $values[3]), + CONVERT(smallmoney, $values[4]), + CONVERT(money, $values[5])"; + + // Do not override the connection attributes + verifyMoneyValues($conn, $numDigits, $query, $values, false); + // Next, override statement attribute to set number of + // decimal places + verifyMoneyValues($conn, 0, $query, $values, true); + + // Set Formatting attribute to true then false + verifyMoneyFormatting($conn, $query, $values, true); + verifyMoneyFormatting($conn, $query, $values, false); +} + +function connGetAttributes($conn, $numDigits) +{ + $format = $conn->getAttribute(PDO::SQLSRV_ATTR_FORMAT_DECIMALS); + if ($format !== true) { + echo "The returned value of SQLSRV_ATTR_FORMAT_DECIMALS, $format, is wrong\n"; + + return false; + } + + $digits = $conn->getAttribute(PDO::SQLSRV_ATTR_DECIMAL_PLACES); + if ($digits != $numDigits) { + echo "The returned value of SQLSRV_ATTR_DECIMAL_PLACES, $digits, is wrong\n"; + + return false; + } + + return true; +} + +function connectWithAttrs($numDigits) +{ + $attr = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => true, + PDO::SQLSRV_ATTR_DECIMAL_PLACES => $numDigits); + + // This helper method sets PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION + $conn = connect('', $attr); + + if (connGetAttributes($conn, $numDigits)) { + // First test with money types + testMoneyTypes($conn, $numDigits); + + // Also test using regular floats + testFloatTypes($conn, $numDigits); + } + unset($conn); +} + +function connectSetAttrs($numDigits) +{ + // This helper method sets PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION + $conn = connect(); + $conn->setAttribute(PDO::SQLSRV_ATTR_FORMAT_DECIMALS, true); + $conn->setAttribute(PDO::SQLSRV_ATTR_DECIMAL_PLACES, $numDigits); + + if (connGetAttributes($conn, $numDigits)) { + // First test with money types + testMoneyTypes($conn, $numDigits); + + // Also test using regular floats + testFloatTypes($conn, $numDigits); + } + + unset($conn); +} + +try { + connectWithAttrs(2); + connectSetAttrs(3); + + echo "Done\n"; + + unset($conn); +} catch (PdoException $e) { + echo $e->getMessage() . PHP_EOL; +} +?> +--EXPECT-- +Done diff --git a/test/functional/sqlsrv/sqlsrv_statement_format_decimals.phpt b/test/functional/sqlsrv/sqlsrv_statement_format_decimals.phpt index 223e4fb6b..3db5d1784 100644 --- a/test/functional/sqlsrv/sqlsrv_statement_format_decimals.phpt +++ b/test/functional/sqlsrv/sqlsrv_statement_format_decimals.phpt @@ -1,22 +1,18 @@ --TEST-- -Test how decimal data output values can be formatted (feature request issue 415) +Test connection and statement attributes for formatting decimal and numeric data (feature request issue 415) --DESCRIPTION-- -Test how numeric and decimal data output values can be formatted by using the -statement option FormatDecimals, which expects an integer value from the range [0,38], -affecting only the money / decimal types in the fetched result set because they are -always strings to preserve accuracy and precision, unlike other primitive numeric -types that can be retrieved as numbers. - -No effect on other operations like insertion or update. - -1. By default, data will be returned with the original precision and scale -2. The data column original scale still takes precedence – for example, if the user -specifies 3 decimal digits for a column of decimal(5,2), the result still shows only 2 -decimals to the right of the dot -3. After formatting, the missing leading zeroes will be padded -4. The underlying data will not be altered, but formatted results may likely be rounded -up (e.g. .2954 will be displayed as 0.30 if the user wants only two decimals) -5. For output params use SQLSRV_SQLTYPE_DECIMAL with the correct precision and scale +Test the connection and statement options, FormatDecimals and +DecimalPlaces, the latter affects money types only, not +decimal or numeric types (feature request issue 415). +Money, decimal or numeric types are always fetched as strings to preserve accuracy and precision, unlike other primitive numeric types, where there is an option to retrieve them as numbers. + +Setting FormatDecimals to false will turn off all formatting, regardless of DecimalPlaces value. Also, any negative DecimalPlaces value will be ignored. Likewise, since money or smallmoney fields have scale 4, if DecimalPlaces value is larger than 4, it will be ignored as well. + +1. By default, data will be returned with the original precision and scale +2. Set FormatDecimals to true to add the leading zeroes to money and decimal types, if missing. +3. For output params, leading zeroes will be added for any decimal fields if FormatDecimals is true, but only if either SQLSRV_SQLTYPE_DECIMAL or SQLSRV_SQLTYPE_NUMERIC is set correctly to match the original column type and its precision / scale. + +FormatDecimals and DecimalPlaces will only format the fetched results and have no effect on other operatioins like insertion or update. --ENV-- PHPT_EXEC=true --SKIPIF-- @@ -25,23 +21,19 @@ PHPT_EXEC=true $fieldScale, will show $fieldScale decimal digits - if ($formatDecimal >= 0) { - $numDecimals = ($formatDecimal > $fieldScale) ? $fieldScale : $formatDecimal; - $expected = number_format($input, $numDecimals); - } else { - $expected = number_format($input, $fieldScale); + // If no formatting, there will be no leading zero + $expected = number_format($input, $fieldScale); + if (!$format) { if (abs($input) < 1) { // Since no formatting, the leading zero should not be there - trace("Drop leading zero of $input--"); + trace("Drop leading zero of $input: "); $expected = str_replace('0.', '.', $expected); } } @@ -49,7 +41,7 @@ function compareNumbers($actual, $input, $column, $fieldScale, $formatDecimal = if ($actual === $expected) { $matched = true; } else { - echo "For $column ($formatDecimal): expected $expected ($input) but the value is $actual\n"; + echo "For $column ($fieldScale): expected $expected ($input) but the value is $actual\n"; } } return $matched; @@ -58,134 +50,34 @@ function compareNumbers($actual, $input, $column, $fieldScale, $formatDecimal = function testErrorCases($conn) { $query = "SELECT 0.0001"; - - $options = array('FormatDecimals' => 1.5); + $message = 'Expected an integer to specify number of decimals to format the output values of decimal data types.'; + + $options = array('DecimalPlaces' => 1.5); $stmt = sqlsrv_query($conn, $query, array(), $options); if ($stmt) { fatalError("Case 1: expected query to fail!!"); } else { $error = sqlsrv_errors()[0]['message']; - $message = 'Expected an integer to specify number of decimals to format the output values of decimal data types.'; - if (strpos($error, $message) === false) { print_r(sqlsrv_errors()); } } - $options = array('FormatDecimals' => -1); + $options = array('DecimalPlaces' => true); $stmt = sqlsrv_query($conn, $query, array(), $options); if ($stmt) { fatalError("Case 2: expected query to fail!!"); } else { $error = sqlsrv_errors()[0]['message']; - $message = 'For formatting decimal data values, -1 is out of range. Expected an integer from 0 to 38, inclusive.'; - if (strpos($error, $message) === false) { print_r(sqlsrv_errors()); } } } -function testFloatTypes($conn) -{ - // This test with the float types of various number of bits, which are retrieved - // as numbers by default. When fetched as strings, no formatting is done even with - // the statement option FormatDecimals set - $values = array('2.9978', '-0.2982', '33.2434', '329.690734', '110.913498'); - $epsilon = 0.001; - - $query = "SELECT CONVERT(float(1), $values[0]), - CONVERT(float(12), $values[1]), - CONVERT(float(24), $values[2]), - CONVERT(float(36), $values[3]), - CONVERT(float(53), $values[4])"; - - $stmt = sqlsrv_query($conn, $query); - $floats = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); - if (!$floats) { - echo "testFloatTypes: sqlsrv_fetch_array failed\n"; - } - - // Set FormatDecimals to 2, but the number of decimals in each of the results - // will vary -- FormatDecimals has no effect - $numDigits = 2; - $options = array('FormatDecimals' => $numDigits); - $stmt = sqlsrv_query($conn, $query, array(), $options); - if (sqlsrv_fetch($stmt)) { - for ($i = 0; $i < count($values); $i++) { - $floatStr = sqlsrv_get_field($stmt, $i, SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_CHAR)); - $floatVal = floatval($floatStr); - - // Check if the numbers of decimal digits are the same - // It is highly unlikely but not impossible - $numbers = explode('.', $floatStr); - $len = strlen($numbers[1]); - if ($len == $numDigits && $floatVal != $floats[$i]) { - echo "Expected $floats[$i] but returned "; - var_dump($floatVal); - } else { - $diff = abs($floatVal - $floats[$i]) / $floats[$i]; - if ($diff > $epsilon) { - echo "Expected $floats[$i] but returned "; - var_dump($floatVal); - } - } - } - } else { - echo "testFloatTypes: sqlsrv_fetch failed\n"; - } -} - -function testMoneyTypes($conn) -{ - // With money and smallmoney types, which are essentially decimal types - // ODBC driver does not support Always Encrypted feature with money / smallmoney - $values = array('1.9954', '0', '-0.5', '0.2954', '9.6789', '99.991'); - $defaults = array('1.9954', '.0000', '-.5000', '.2954', '9.6789', '99.9910'); - - $query = "SELECT CONVERT(smallmoney, $values[0]), - CONVERT(money, $values[1]), - CONVERT(smallmoney, $values[2]), - CONVERT(money, $values[3]), - CONVERT(smallmoney, $values[4]), - CONVERT(money, $values[5])"; - - $stmt = sqlsrv_query($conn, $query); - $results = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); - for ($i = 0; $i < count($values); $i++) { - if ($defaults[$i] !== $results[$i]) { - echo "testMoneyTypes: Expected default $defaults[$i] but got $results[$i]\n"; - } - } - - // Set FormatDecimals to 0 decimal digits - $numDigits = 0; - $options = array('FormatDecimals' => $numDigits); - $stmt = sqlsrv_query($conn, $query, array(), $options); - $results = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); - for ($i = 0; $i < count($values); $i++) { - $value = number_format($values[$i], $numDigits); - if ($value !== $results[$i]) { - echo "testMoneyTypes: Expected $value but got $results[$i]\n"; - } - } - - // Set FormatDecimals to 2 decimal digits - $numDigits = 2; - $options = array('FormatDecimals' => $numDigits); - $stmt = sqlsrv_query($conn, $query, array(), $options); - $results = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); - for ($i = 0; $i < count($values); $i++) { - $value = number_format($values[$i], $numDigits); - if ($value !== $results[$i]) { - echo "testMoneyTypes: Expected $value but got $results[$i]\n"; - } - } -} - function testNoOption($conn, $tableName, $inputs, $columns, $exec) { - // Without the statement option, should return decimal values as they are + // This should return decimal values as they are $query = "SELECT * FROM $tableName"; if ($exec) { $stmt = sqlsrv_query($conn, $query); @@ -194,27 +86,27 @@ function testNoOption($conn, $tableName, $inputs, $columns, $exec) sqlsrv_execute($stmt); } - // Compare values + // Compare values $results = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); for ($i = 0; $i < count($inputs); $i++) { - compareNumbers($results[$i], $inputs[$i], $columns[$i], $i); + compareNumbers($results[$i], $inputs[$i], $columns[$i], $i, false); } } -function testStmtOption($conn, $tableName, $inputs, $columns, $formatDecimal, $withBuffer) +function testStmtOption($conn, $tableName, $inputs, $columns, $decimalPlaces, $withBuffer) { - // Decimal values should return decimal digits based on the valid statement - // option FormatDecimals + // Decimal values should NOT be affected by the statement + // option DecimalPlaces $query = "SELECT * FROM $tableName"; if ($withBuffer){ - $options = array('Scrollable' => 'buffered', 'FormatDecimals' => $formatDecimal); + $options = array('Scrollable' => 'buffered', 'DecimalPlaces' => $decimalPlaces); } else { - $options = array('FormatDecimals' => $formatDecimal); + $options = array('DecimalPlaces' => $decimalPlaces); } $size = count($inputs); $stmt = sqlsrv_prepare($conn, $query, array(), $options); - + // Fetch by getting one field at a time sqlsrv_execute($stmt); @@ -223,26 +115,28 @@ function testStmtOption($conn, $tableName, $inputs, $columns, $formatDecimal, $w } for ($i = 0; $i < $size; $i++) { $field = sqlsrv_get_field($stmt, $i); // Expect a string - compareNumbers($field, $inputs[$i], $columns[$i], $i, $formatDecimal); + compareNumbers($field, $inputs[$i], $columns[$i], $i, true); } } -function getOutputParam($conn, $storedProcName, $inputValue, $prec, $scale, $inout) +function getOutputParam($conn, $storedProcName, $inputValue, $prec, $scale, $numeric, $inout) { $outString = ''; $numDigits = 2; $dir = SQLSRV_PARAM_OUT; - - // The output param value should be the same as the input value, - // unaffected by the statement attr FormatDecimals, unless - // ColumnEncryption is enabled, in which case the driver is able - // to derive the decimal type. Another workaround is to specify - // the SQLSRV_SQLTYPE_DECIMAL type with the correct precision and scale + + // The output param value should be the same as the input, + // unaffected by the statement attr DecimalPlaces. If + // the correct sql type is specified or ColumnEncryption + // is enabled, in which case the driver is able to derive + // the correct field type, leading zero will be added + // if missing $sqlType = null; if (!AE\isColEncrypted()) { - $sqlType = call_user_func('SQLSRV_SQLTYPE_DECIMAL', $prec, $scale); + $type = ($numeric) ? 'SQLSRV_SQLTYPE_NUMERIC' : 'SQLSRV_SQLTYPE_DECIMAL'; + $sqlType = call_user_func($type, $prec, $scale); } - + // For inout parameters the input type should match the output one if ($inout) { $dir = SQLSRV_PARAM_INOUT; @@ -250,38 +144,37 @@ function getOutputParam($conn, $storedProcName, $inputValue, $prec, $scale, $ino } $outSql = AE\getCallProcSqlPlaceholders($storedProcName, 1); - $stmt = sqlsrv_prepare($conn, $outSql, - array(array(&$outString, $dir, null, $sqlType)), - array('FormatDecimals' => $numDigits)); + $stmt = sqlsrv_prepare($conn, $outSql, + array(array(&$outString, $dir, null, $sqlType)), + array('DecimalPlaces' => $numDigits)); if (!$stmt) { fatalError("getOutputParam: failed when preparing to call $storedProcName"); } if (!sqlsrv_execute($stmt)) { fatalError("getOutputParam: failed to execute procedure $storedProcName"); } - - // The output param should have been formatted based on $numDigits, if less - // than $scale + + // Verify value of output param $column = 'outputParam'; - compareNumbers($outString, $inputValue, $column, $scale, $numDigits); + compareNumbers($outString, $inputValue, $column, $scale, true); sqlsrv_free_stmt($stmt); - + if (!AE\isColEncrypted()) { // With ColumnEncryption enabled, the driver is able to derive the decimal type, // so skip this part of the test $outString2 = $inout ? '0.0' : ''; - $stmt = sqlsrv_prepare($conn, $outSql, - array(array(&$outString2, $dir)), - array('FormatDecimals' => $numDigits)); + $stmt = sqlsrv_prepare($conn, $outSql, + array(array(&$outString2, $dir)), + array('DecimalPlaces' => $numDigits)); if (!$stmt) { fatalError("getOutputParam2: failed when preparing to call $storedProcName"); } if (!sqlsrv_execute($stmt)) { fatalError("getOutputParam2: failed to execute procedure $storedProcName"); } - + $column = 'outputParam2'; - compareNumbers($outString2, $inputValue, $column, $scale); + compareNumbers($outString2, $inputValue, $column, $scale, true); sqlsrv_free_stmt($stmt); } } @@ -296,8 +189,8 @@ function testOutputParam($conn, $tableName, $inputs, $columns, $dataTypes, $inou createProc($conn, $storedProcName, $procArgs, $procCode); // Call stored procedure to retrieve output param - getOutputParam($conn, $storedProcName, $inputs[$i], $p, $i, $inout); - + getOutputParam($conn, $storedProcName, $inputs[$i], $p, $i, $i > 2, $inout); + dropProc($conn, $storedProcName); } } @@ -310,16 +203,10 @@ if (!$conn) { fatalError("Could not connect.\n"); } -// First to test if leading zero is added -testMoneyTypes($conn); - -// Then test error conditions +// Test error conditions testErrorCases($conn); -// Also test using regular floats -testFloatTypes($conn); - -// Create the test table of decimal / numeric data columns +// Create the test table of decimal / numeric data columns $tableName = 'sqlsrvFormatDecimals'; $columns = array('c1', 'c2', 'c3', 'c4', 'c5', 'c6'); @@ -338,13 +225,13 @@ $values = array(); $max2 = 1; for ($s = 0, $p = 3; $s < count($columns); $s++, $p++) { // First get a random number - $n = rand(0, 10); + $n = rand(1, 6); $neg = ($n % 2 == 0) ? -1 : 1; - - // $n1 may or may not be negative - $max1 = 1000; + + // $n1 is a tiny number, which may or may not be negative + $max1 = 5; $n1 = rand(0, $max1) * $neg; - + if ($s > 0) { $max2 *= 10; $n2 = rand(0, $max2); @@ -352,7 +239,7 @@ for ($s = 0, $p = 3; $s < count($columns); $s++, $p++) { } else { $number = sprintf("%d", $n1); } - + array_push($values, $number); } @@ -373,6 +260,14 @@ sqlsrv_free_stmt($stmt); testNoOption($conn, $tableName, $values, $columns, true); testNoOption($conn, $tableName, $values, $columns, false); +sqlsrv_close($conn); + +// Reconnect with FormatDecimals option set to true +$conn = AE\connect(array('FormatDecimals' => true)); +if (!$conn) { + fatalError("Could not connect.\n"); +} + // Now try with setting number decimals to 3 then 2 testStmtOption($conn, $tableName, $values, $columns, 3, false); testStmtOption($conn, $tableName, $values, $columns, 3, true); @@ -384,7 +279,7 @@ testStmtOption($conn, $tableName, $values, $columns, 2, true); testOutputParam($conn, $tableName, $values, $columns, $dataTypes); testOutputParam($conn, $tableName, $values, $columns, $dataTypes, true); -dropTable($conn, $tableName); +dropTable($conn, $tableName); sqlsrv_close($conn); echo "Done\n"; diff --git a/test/functional/sqlsrv/sqlsrv_statement_format_decimals_scales.phpt b/test/functional/sqlsrv/sqlsrv_statement_format_decimals_scales.phpt deleted file mode 100644 index 4abb0398d..000000000 --- a/test/functional/sqlsrv/sqlsrv_statement_format_decimals_scales.phpt +++ /dev/null @@ -1,255 +0,0 @@ ---TEST-- -Test various precisions of formatting decimal data output values (feature request issue 415) ---DESCRIPTION-- -In SQL Server, the maximum allowed precision is 38. The scale can range from 0 up to the -defined precision. Generate a long numeric string and get rid of the last digit to make it a -39-digit-string. Then replace one digit at a time with a dot '.' to make it a decimal -input string for testing with various scales. -For example, -string(39) ".23456789012345678901234567890123456789" -string(39) "1.3456789012345678901234567890123456789" -string(39) "12.456789012345678901234567890123456789" -string(39) "123.56789012345678901234567890123456789" -string(39) "1234.6789012345678901234567890123456789" -string(39) "12345.789012345678901234567890123456789" -... ... -string(39) "1234567890123456789012345678901234.6789" -string(39) "12345678901234567890123456789012345.789" -string(39) "123456789012345678901234567890123456.89" -string(39) "1234567890123456789012345678901234567.9" -string(38) "12345678901234567890123456789012345678" - -Note: PHP number_format() will not be used for verification in this test -because the function starts losing accuracy with large number of precisions / scales. ---ENV-- -PHPT_EXEC=true ---SKIPIF-- - ---FILE-- - $digits)); - - // Restore the $i-th digit with its original digit - $digits[$i] = $d; - } - - $stmt = AE\insertRow($conn, $tableName, $inputData); - if (!$stmt) { - fatalError("Failed to insert data\n"); - } - sqlsrv_free_stmt($stmt); - - return $inputData; -} - -function verifyNoDecimals($value, $input, $round) -{ - global $prec, $dot; - - // Use PHP explode() to separate the input string into an array - $parts = explode($dot, $input); - $len = strlen($parts[0]); - if ($len == 0) { - // The original input string is missing a leading zero - $parts[0] = '0'; - } - - // No need to worry about carry over for the input data of this test - // Check the first digit of $parts[1] - if ($len < $prec) { - // Only need to round up when $len < $prec - $ch = $parts[1][0]; - - // Round the last digit of $parts[0] if $ch is '5' or above - if ($ch >= '5') { - $len = strlen($parts[0]); - $parts[0][$len-1] = $parts[0][$len-1] + 1 + '0'; - } - } - - // No decimal digits left in the expected string - $expected = $parts[0]; - if ($value !== $expected) { - echo "Round $round scale 0: expected $expected but returned $value\n"; - } -} - -function verifyWithDecimals($value, $input, $round, $scale) -{ - global $dot; - - // Use PHP explode() to separate the input string into an array - $parts = explode($dot, $input); - if (strlen($parts[0]) == 0) { - // The original input string is missing a leading zero - $parts[0] = '0'; - } - - // No need to worry about carry over for the input data of this test - // Check the digit at the position $scale of $parts[1] - $len = strlen($parts[1]); - if ($scale < $len) { - // Only need to round up when $scale < $len - $ch = $parts[1][$scale]; - - // Round the previous digit if $ch is '5' or above - if ($ch >= '5') { - $parts[1][$scale-1] = $parts[1][$scale-1] + 1 + '0'; - } - } - - // Use substr() to get up to $scale - $parts[1] = substr($parts[1], 0, $scale); - - // Join the array elements together - $expected = implode($dot, $parts); - if ($value !== $expected) { - echo "Round $round scale $scale: expected $expected but returned $value\n"; - } -} - -/**** -The function testVariousScales() will fetch one column at a time, using scale from -0 up to the maximum scale allowed for that column type. - -For example, for column of type decimal(38,4), the input string is -1234567890123456789012345678901234.6789 - -When fetching data, using scale from 0 to 4, the following values are expected to return: -1234567890123456789012345678901235 -1234567890123456789012345678901234.7 -1234567890123456789012345678901234.68 -1234567890123456789012345678901234.679 -1234567890123456789012345678901234.6789 - -For example, for column of type decimal(38,6), the input string is -12345678901234567890123456789012.456789 - -When fetching data, using scale from 0 to 6, the following values are expected to return: -12345678901234567890123456789012 -12345678901234567890123456789012.5 -12345678901234567890123456789012.46 -12345678901234567890123456789012.457 -12345678901234567890123456789012.4568 -12345678901234567890123456789012.45679 -12345678901234567890123456789012.456789 - -etc. -****/ -function testVariousScales($conn, $tableName, $inputData) -{ - global $prec; - $max = $prec + 1; - - for ($i = 0; $i < $max; $i++) { - $scale = $prec - $i; - $column = "col_$scale"; - - $query = "SELECT $column as col1 FROM $tableName"; - $input = $inputData[$column]; - - // Default case: the fetched value should be the same as the corresponding input - $stmt = sqlsrv_query($conn, $query); - if (!$stmt) { - fatalError("In testVariousScales: failed in default case\n"); - } - if ($obj = sqlsrv_fetch_object($stmt)) { - trace("\n$obj->col1\n"); - if ($obj->col1 !== $input) { - echo "default case: expected $input but returned $obj->col1\n"; - } - } else { - fatalError("In testVariousScales: sqlsrv_fetch_object failed\n"); - } - - // Next, format how many decimal digits to be displayed - $query = "SELECT $column FROM $tableName"; - for ($j = 0; $j <= $scale; $j++) { - $options = array('FormatDecimals' => $j); - $stmt = sqlsrv_query($conn, $query, array(), $options); - - if (sqlsrv_fetch($stmt)) { - $value = sqlsrv_get_field($stmt, 0); - trace("$value\n"); - - if ($j == 0) { - verifyNoDecimals($value, $input, $i); - } else { - verifyWithDecimals($value, $input, $i, $j); - } - } else { - fatalError("Round $i scale $j: sqlsrv_fetch failed\n"); - } - } - } -} - -set_time_limit(0); -sqlsrv_configure('WarningsReturnAsErrors', 1); - -$conn = AE\connect(); -if (!$conn) { - fatalError("Could not connect.\n"); -} - -$tableName = createTestTable($conn); -$inputData = insertTestData($conn, $tableName); -testVariousScales($conn, $tableName, $inputData); - -dropTable($conn, $tableName); - -sqlsrv_close($conn); - -echo "Done\n"; -?> ---EXPECT-- -Done \ No newline at end of file diff --git a/test/functional/sqlsrv/sqlsrv_statement_format_money_types.phpt b/test/functional/sqlsrv/sqlsrv_statement_format_money_types.phpt new file mode 100644 index 000000000..ae1befa4c --- /dev/null +++ b/test/functional/sqlsrv/sqlsrv_statement_format_money_types.phpt @@ -0,0 +1,261 @@ +--TEST-- +Test the options for formatting money data (feature request issue 415) +--DESCRIPTION-- +Test how money data in the fetched values can be formatted by using the connection +option FormatDecimals and DecimalPlaces, the latter works only with integer +values. No effect on other operations like insertion or update. + +The option DecimalPlaces only affects money/smallmoney fields. If its value is out of range, for example, it's negative or larger than the original scale, then its value will be ignored. + +The underlying data will not be altered, but formatted results may likely be rounded up (e.g. .2954 will be displayed as 0.30 if the user wants only two decimals). For this reason, it is not recommended to use formatted money values as inputs to any calculation. + +The corresponding statement options always override the inherited values from the connection object. Setting FormatDecimals to false will automatically turn off any formatting of decimal data in the result set, ignoring DecimalPlaces value. + +By only setting FormatDecimals to true will add the leading zeroes, if missing. For output params, missing zeroes will be added if either SQLSRV_SQLTYPE_MONEY or SQLSRV_SQLTYPE_SMALLMONEY is set as the SQLSRV SQL Type. +--ENV-- +PHPT_EXEC=true +--SKIPIF-- + +--FILE-- + $epsilon) { + echo "$diff: Expected $floats[$i] but returned "; + var_dump($floatVal); + } + } + } + } else { + echo "testFloatTypes: sqlsrv_fetch failed\n"; + } +} + +function verifyMoneyValues($conn, $numDigits, $query, $values, $override) +{ + if ($override) { + $options = array('DecimalPlaces' => $numDigits); + $stmt = sqlsrv_query($conn, $query, array(), $options); + } else { + $stmt = sqlsrv_query($conn, $query); + } + + $results = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); + trace("\nverifyMoneyValues:\n"); + for ($i = 0; $i < count($values); $i++) { + $value = numberFormat($values[$i], $numDigits); + trace("$results[$i], $value\n"); + + if ($value !== $results[$i]) { + echo "verifyMoneyValues ($override, $numDigits): Expected $value but got $results[$i]\n"; + } + } +} + +function verifyMoneyFormatting($conn, $query, $values, $format) +{ + if ($format) { + // Set FormatDecimals to true to turn on formatting, but setting + // DecimalPlaces to a negative number, which will be ignored. + $nDigits = -1; + $options = array('FormatDecimals' => true, 'DecimalPlaces' => $nDigits); + $stmt = sqlsrv_query($conn, $query, array(), $options); + } else { + // Set FormatDecimals to false to turn off formatting. + // This should override the inherited connection + // options, and by default, money and smallmoney types + // have scale of 4 digits + $options = array('FormatDecimals' => false); + $stmt = sqlsrv_query($conn, $query, array(), $options); + } + $results = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); + + for ($i = 0; $i < count($values); $i++) { + $default = numberFormat($values[$i], 4); + if (!$format) { + // No formatting - should drop the leading zero, if exists + if (abs($values[$i]) < 1) { + $default = str_replace('0.', '.', $default); + } + } + if ($default !== $results[$i]) { + echo "verifyMoneyFormatting ($format): Expected default $default but got $results[$i]\n"; + } + } +} + +function getOutputParam($conn, $spProcName, $input, $money, $inout) +{ + $outString = '0.0'; + $dir = ($inout) ? SQLSRV_PARAM_INOUT : SQLSRV_PARAM_OUT; + $sqlType = ($money) ? SQLSRV_SQLTYPE_MONEY : SQLSRV_SQLTYPE_SMALLMONEY; + + $outSql = AE\getCallProcSqlPlaceholders($spProcName, 1); + $stmt = sqlsrv_prepare($conn, $outSql, + array(array(&$outString, $dir, null, $sqlType))); + if (!$stmt) { + fatalError("getOutputParam: failed when preparing to call $spProcName"); + } + if (!sqlsrv_execute($stmt)) { + fatalError("getOutputParam: failed to execute procedure $spProcName"); + } + + // FormatDecimals only add leading zeroes, but do + // not support controlling decimal places, so + // use scale 4 for money/smallmoney types + $expected = numberFormat($input, 4); + trace("getOutputParam result is $outString and expected $expected\n"); + + if ($outString !== $expected) { + echo "getOutputParam ($inout): Expected $expected but got $outString\n"; + var_dump($expected); + var_dump($outString); + } +} + +function testOutputParam($conn) +{ + // Create a table for testing output param + $tableName = 'sqlsrvMoneyFormats'; + $values = array(0.12345, 0.34567); + $query = "SELECT CONVERT(smallmoney, $values[0]) AS m1, + CONVERT(money, $values[1]) AS m2 + INTO $tableName"; + + $stmt = sqlsrv_query($conn, $query); + for ($i = 0; $i < 2; $i++) { + // Create the stored procedure first + $storedProcName = "spMoneyFormats" . $i; + $dataType = ($i == 0) ? 'smallmoney' : 'money'; + $procArgs = "@col $dataType OUTPUT"; + $column = 'm' . ($i + 1); + $procCode = "SELECT @col = $column FROM $tableName"; + createProc($conn, $storedProcName, $procArgs, $procCode); + + getOutputParam($conn, $storedProcName, $values[$i], $i, false); + getOutputParam($conn, $storedProcName, $values[$i], $i, true); + + dropProc($conn, $storedProcName); + } + + dropTable($conn, $tableName); +} + +function testMoneyTypes($conn) +{ + global $numDigits; // inherited from connection option + + // With money and smallmoney types, which are essentially decimal types + // As of today, ODBC driver does not support Always Encrypted feature with money / smallmoney + $values = array(); + $nColumns = 6; + for ($i = 0; $i < $nColumns; $i++) { + // First get a random number + $n = rand(0, 10); + $neg = ($n % 2 == 0) ? -1 : 1; + + // $n1 may or may not be negative + $max = 10; + $n1 = rand(0, $max) * $neg; + $n2 = rand(1, $max * 1000); + + $number = sprintf("%d.%d", $n1, $n2); + array_push($values, $number); + } + + $query = "SELECT CONVERT(smallmoney, $values[0]), + CONVERT(money, $values[1]), + CONVERT(smallmoney, $values[2]), + CONVERT(money, $values[3]), + CONVERT(smallmoney, $values[4]), + CONVERT(money, $values[5])"; + + // Do not override the connection attributes + verifyMoneyValues($conn, $numDigits, $query, $values, false); + // Next, override statement attribute to set number of + // decimal places to 0 + verifyMoneyValues($conn, 0, $query, $values, true); + + // Set Formatting attribute to true then false + verifyMoneyFormatting($conn, $query, $values, true); + verifyMoneyFormatting($conn, $query, $values, false); +} + +set_time_limit(0); +sqlsrv_configure('WarningsReturnAsErrors', 1); + +$numDigits = 2; + +$conn = AE\connect(array('FormatDecimals' => true, 'DecimalPlaces' => $numDigits)); +if (!$conn) { + fatalError("Could not connect.\n"); +} +/* +// First to test if leading zero is added +testMoneyTypes($conn); + +// Also test using regular floats +testFloatTypes($conn); +*/ +// Test output params +testOutputParam($conn); + +sqlsrv_close($conn); + +echo "Done\n"; +?> +--EXPECT-- +Done From fc5d86dc2321618785dcb37590a2595e46568ce9 Mon Sep 17 00:00:00 2001 From: Jenny Tam Date: Fri, 23 Nov 2018 14:14:50 -0800 Subject: [PATCH 06/10] Adding new tests for various decimal places --- .../pdostatement_format_money_scales.phpt | 229 ++++++++++++++++++ .../sqlsrv_statement_format_money_scales.phpt | 167 +++++++++++++ 2 files changed, 396 insertions(+) create mode 100644 test/functional/pdo_sqlsrv/pdostatement_format_money_scales.phpt create mode 100644 test/functional/sqlsrv/sqlsrv_statement_format_money_scales.phpt diff --git a/test/functional/pdo_sqlsrv/pdostatement_format_money_scales.phpt b/test/functional/pdo_sqlsrv/pdostatement_format_money_scales.phpt new file mode 100644 index 000000000..9bd2e8e98 --- /dev/null +++ b/test/functional/pdo_sqlsrv/pdostatement_format_money_scales.phpt @@ -0,0 +1,229 @@ +--TEST-- +Test various decimal places of money values (feature request issue 415) +--DESCRIPTION-- +In SQL Server, the maximum precision of money type is 19 with scale 4. Generate a long numeric string and get rid of the last digit to make it a 15-digit-string. Then replace one digit at a time with a dot '.' to make it a decimal input string for testing. + +For example, +string(15) ".23456789098765" +string(15) "1.3456789098765" +string(15) "12.456789098765" +string(15) "123.56789098765" +string(15) "1234.6789098765" +... +string(15) "1234567890987.5" +string(15) "12345678909876." + +The inserted money data will be +0.2346 +1.3457 +12.4568 +123.5679 +1234.6789 +... +1234567890987.5000 +12345678909876.0000 + +--ENV-- +PHPT_EXEC=true +--SKIPIF-- + +--FILE-- + $digits)); + + // Restore the $i-th digit with its original digit + $digits[$i] = $d; + } + + $stmt = insertRow($conn, $tableName, $inputData); + unset($stmt); +} +/* +function verifyNoDecimals($value, $input, $round) +{ + global $prec, $dot; + + // Use PHP explode() to separate the input string into an array + $parts = explode($dot, $input); + $len = strlen($parts[0]); + if ($len == 0) { + // The original input string is missing a leading zero + $parts[0] = '0'; + } + + // No need to worry about carry over for the input data of this test + // Check the first digit of $parts[1] + if ($len < $prec) { + // Only need to round up when $len < $prec + $ch = $parts[1][0]; + + // Round the last digit of $parts[0] if $ch is '5' or above + if ($ch >= '5') { + $len = strlen($parts[0]); + $parts[0][$len-1] = $parts[0][$len-1] + 1 + '0'; + } + } + + // No decimal digits left in the expected string + $expected = $parts[0]; + if ($value !== $expected) { + echo "Round $round scale 0: expected $expected but returned $value\n"; + } +} + +function verifyWithDecimals($value, $input, $round, $scale) +{ + global $dot; + + // Use PHP explode() to separate the input string into an array + $parts = explode($dot, $input); + if (strlen($parts[0]) == 0) { + // The original input string is missing a leading zero + $parts[0] = '0'; + } + + // No need to worry about carry over for the input data of this test + // Check the digit at the position $scale of $parts[1] + $len = strlen($parts[1]); + if ($scale < $len) { + // Only need to round up when $scale < $len + $ch = $parts[1][$scale]; + + // Round the previous digit if $ch is '5' or above + if ($ch >= '5') { + $parts[1][$scale-1] = $parts[1][$scale-1] + 1 + '0'; + } + } + + // Use substr() to get up to $scale + $parts[1] = substr($parts[1], 0, $scale); + + // Join the array elements together + $expected = implode($dot, $parts); + if ($value !== $expected) { + echo "Round $round scale $scale: expected $expected but returned $value\n"; + } +} +*/ + +function numberFormat($value, $numDecimals) +{ + return number_format($value, $numDecimals, '.', ''); +} + +/**** +The function testVariousScales() will fetch one column at a time, using scale from 0 up to 4 allowed for that column type. + +For example, if the input string is +1234567890.2345 + +When fetching data, using scale from 0 to 4, the following values are expected to return: +1234567890 +1234567890.2 +1234567890.23 +1234567890.235 +1234567890.2345 +****/ +function testVariousScales($conn, $tableName) +{ + global $prec, $scale; + $max = $prec - $scale; + + for ($i = 0; $i < $max; $i++) { + $column = "col_$i"; + + $query = "SELECT $column as col1 FROM $tableName"; + + // Default case: no formatting + $stmt = $conn->query($query); + if ($obj = $stmt->fetchObject()) { + trace("\n$obj->col1\n"); + $input = $obj->col1; + } else { + echo "In testVariousScales: fetchObject failed\n"; + } + + // Next, format how many decimals to be displayed + $query = "SELECT $column FROM $tableName"; + for ($j = 0; $j <= $scale; $j++) { + $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => true, PDO::SQLSRV_ATTR_DECIMAL_PLACES => $j); + $stmt = $conn->prepare($query, $options); + $stmt->execute(); + + $stmt->bindColumn($column, $value); + if ($stmt->fetch(PDO::FETCH_BOUND)) { + trace("$value\n"); + + $expected = numberFormat($input, $j); + if ($value !== $expected) { + echo "testVariousScales ($j): Expected $expected but got $value\n"; + } + } else { + echo "Round $i scale $j: fetch failed\n"; + } + } + } +} + +try { + // This helper method sets PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION + // Default is no formatting, but set it to false anyway + $conn = connect(); + $conn->setAttribute(PDO::SQLSRV_ATTR_FORMAT_DECIMALS, false); + + $tableName = createTestTable($conn); + insertTestData($conn, $tableName); + testVariousScales($conn, $tableName); + + dropTable($conn, $tableName); + + echo "Done\n"; + + unset($conn); +} catch (PdoException $e) { + echo $e->getMessage() . PHP_EOL; +} +?> +--EXPECT-- +Done diff --git a/test/functional/sqlsrv/sqlsrv_statement_format_money_scales.phpt b/test/functional/sqlsrv/sqlsrv_statement_format_money_scales.phpt new file mode 100644 index 000000000..b27a3c480 --- /dev/null +++ b/test/functional/sqlsrv/sqlsrv_statement_format_money_scales.phpt @@ -0,0 +1,167 @@ +--TEST-- +Test various decimal places of money values (feature request issue 415) +--DESCRIPTION-- +In SQL Server, the maximum precision of money type is 19 with scale 4. Generate a long numeric string and get rid of the last digit to make it a 15-digit-string. Then replace one digit at a time with a dot '.' to make it a decimal input string for testing. + +For example, +string(15) ".23456789098765" +string(15) "1.3456789098765" +string(15) "12.456789098765" +string(15) "123.56789098765" +string(15) "1234.6789098765" +... +string(15) "1234567890987.5" +string(15) "12345678909876." + +The inserted money data will be +0.2346 +1.3457 +12.4568 +123.5679 +1234.6789 +... +1234567890987.5000 +12345678909876.0000 + +--ENV-- +PHPT_EXEC=true +--SKIPIF-- + +--FILE-- + $digits)); + trace($digits); + + // Restore the $i-th digit with its original digit + $digits[$i] = $d; + } + + $stmt = AE\insertRow($conn, $tableName, $inputData); + if (!$stmt) { + fatalError("Failed to insert data\n"); + } + sqlsrv_free_stmt($stmt); +} + +function numberFormat($value, $numDecimals) +{ + return number_format($value, $numDecimals, '.', ''); +} + +/**** +The function testVariousScales() will fetch one column at a time, using scale from 0 up to 4 allowed for that column type. + +For example, if the input string is +1234567890.2345 + +When fetching data, using scale from 0 to 4, the following values are expected to return: +1234567890 +1234567890.2 +1234567890.23 +1234567890.235 +1234567890.2345 +****/ +function testVariousScales($conn, $tableName) +{ + global $prec, $scale; + $max = $prec - $scale; + + for ($i = 0; $i < $max; $i++) { + $column = "col_$i"; + + $query = "SELECT $column as col1 FROM $tableName"; + // Default case: no formatting + $stmt = sqlsrv_query($conn, $query); + if (!$stmt) { + fatalError("In testVariousScales: failed in default case\n"); + } + if ($obj = sqlsrv_fetch_object($stmt)) { + trace("\n$obj->col1\n"); + $input = $obj->col1; + } else { + fatalError("In testVariousScales: sqlsrv_fetch_object failed\n"); + } + + // Next, format how many decimals to be displayed + $query = "SELECT $column FROM $tableName"; + for ($j = 0; $j <= $scale; $j++) { + $options = array('FormatDecimals' => true,'DecimalPlaces' => $j); + $stmt = sqlsrv_query($conn, $query, array(), $options); + + if (sqlsrv_fetch($stmt)) { + $value = sqlsrv_get_field($stmt, 0); + trace("$value\n"); + + $expected = numberFormat($input, $j); + if ($value !== $expected) { + echo "testVariousScales ($j): Expected $expected but got $value\n"; + } + } else { + fatalError("Round $i scale $j: sqlsrv_fetch failed\n"); + } + } + } +} + +set_time_limit(0); +sqlsrv_configure('WarningsReturnAsErrors', 1); + +// Default is no formatting, but set it to false anyway +$conn = AE\connect(array('FormatDecimals' => false)); +if (!$conn) { + fatalError("Could not connect.\n"); +} + +$tableName = createTestTable($conn); +insertTestData($conn, $tableName); +testVariousScales($conn, $tableName); + +dropTable($conn, $tableName); + +sqlsrv_close($conn); + +echo "Done\n"; +?> +--EXPECT-- +Done \ No newline at end of file From 1378d4b06b4e179b9efa1ed747d996d34cf4a96e Mon Sep 17 00:00:00 2001 From: Jenny Tam Date: Thu, 22 Nov 2018 16:56:23 -0800 Subject: [PATCH 07/10] Decimal places for money types only --- source/pdo_sqlsrv/pdo_dbh.cpp | 49 +++- source/pdo_sqlsrv/pdo_init.cpp | 1 + source/pdo_sqlsrv/pdo_stmt.cpp | 18 +- source/pdo_sqlsrv/pdo_util.cpp | 6 +- source/pdo_sqlsrv/php_pdo_sqlsrv.h | 7 +- source/shared/core_sqlsrv.h | 34 ++- source/shared/core_stmt.cpp | 190 ++++++++----- source/sqlsrv/conn.cpp | 68 +++++ source/sqlsrv/php_sqlsrv.h | 4 + source/sqlsrv/stmt.cpp | 4 +- source/sqlsrv/util.cpp | 6 +- .../pdostatement_format_decimals.phpt | 227 ++++----------- .../pdostatement_format_decimals_scales.phpt | 248 ----------------- .../pdostatement_format_money_types.phpt | 245 ++++++++++++++++ .../sqlsrv_statement_format_decimals.phpt | 255 +++++------------ ...lsrv_statement_format_decimals_scales.phpt | 255 ----------------- .../sqlsrv_statement_format_money_types.phpt | 261 ++++++++++++++++++ 17 files changed, 911 insertions(+), 967 deletions(-) delete mode 100644 test/functional/pdo_sqlsrv/pdostatement_format_decimals_scales.phpt create mode 100644 test/functional/pdo_sqlsrv/pdostatement_format_money_types.phpt delete mode 100644 test/functional/sqlsrv/sqlsrv_statement_format_decimals_scales.phpt create mode 100644 test/functional/sqlsrv/sqlsrv_statement_format_money_types.phpt diff --git a/source/pdo_sqlsrv/pdo_dbh.cpp b/source/pdo_sqlsrv/pdo_dbh.cpp index bf25d5a84..77e30f3d3 100644 --- a/source/pdo_sqlsrv/pdo_dbh.cpp +++ b/source/pdo_sqlsrv/pdo_dbh.cpp @@ -81,7 +81,8 @@ enum PDO_STMT_OPTIONS { PDO_STMT_OPTION_EMULATE_PREPARES, PDO_STMT_OPTION_FETCHES_NUMERIC_TYPE, PDO_STMT_OPTION_FETCHES_DATETIME_TYPE, - PDO_STMT_OPTION_FORMAT_DECIMALS + PDO_STMT_OPTION_FORMAT_DECIMALS, + PDO_STMT_OPTION_DECIMAL_PLACES }; // List of all the statement options supported by this driver. @@ -97,6 +98,7 @@ const stmt_option PDO_STMT_OPTS[] = { { NULL, 0, PDO_STMT_OPTION_FETCHES_NUMERIC_TYPE, std::unique_ptr( new stmt_option_fetch_numeric ) }, { NULL, 0, PDO_STMT_OPTION_FETCHES_DATETIME_TYPE, std::unique_ptr( new stmt_option_fetch_datetime ) }, { NULL, 0, PDO_STMT_OPTION_FORMAT_DECIMALS, std::unique_ptr( new stmt_option_format_decimals ) }, + { NULL, 0, PDO_STMT_OPTION_DECIMAL_PLACES, std::unique_ptr( new stmt_option_decimal_places ) }, { NULL, 0, SQLSRV_STMT_OPTION_INVALID, std::unique_ptr{} }, }; @@ -500,7 +502,9 @@ pdo_sqlsrv_dbh::pdo_sqlsrv_dbh( _In_ SQLHANDLE h, _In_ error_callback e, _In_ vo query_timeout( QUERY_TIMEOUT_INVALID ), client_buffer_max_size( PDO_SQLSRV_G( client_buffer_max_size )), fetch_numeric( false ), - fetch_datetime( false ) + fetch_datetime( false ), + format_decimals( false ), + decimal_places( NO_CHANGE_DECIMAL_PLACES ) { if( client_buffer_max_size < 0 ) { client_buffer_max_size = sqlsrv_buffered_result_set::BUFFERED_QUERY_LIMIT_DEFAULT; @@ -1069,7 +1073,28 @@ int pdo_sqlsrv_dbh_set_attr( _Inout_ pdo_dbh_t *dbh, _In_ zend_long attr, _Inout case SQLSRV_ATTR_FETCHES_DATETIME_TYPE: driver_dbh->fetch_datetime = (zend_is_true(val)) ? true : false; break; - + + case SQLSRV_ATTR_FORMAT_DECIMALS: + driver_dbh->format_decimals = (zend_is_true(val)) ? true : false; + break; + + case SQLSRV_ATTR_DECIMAL_PLACES: + { + // first check if the input is an integer + if (Z_TYPE_P(val) != IS_LONG) { + THROW_PDO_ERROR(driver_dbh, SQLSRV_ERROR_INVALID_DECIMAL_PLACES); + } + + zend_long decimal_places = Z_LVAL_P(val); + if (decimal_places < 0 || decimal_places > SQL_SERVER_MAX_MONEY_SCALE) { + // ignore decimal_places as this is out of range + decimal_places = NO_CHANGE_DECIMAL_PLACES; + } + + driver_dbh->decimal_places = static_cast(decimal_places); + } + break; + // Not supported case PDO_ATTR_FETCH_TABLE_NAMES: case PDO_ATTR_FETCH_CATALOG_NAMES: @@ -1097,7 +1122,6 @@ int pdo_sqlsrv_dbh_set_attr( _Inout_ pdo_dbh_t *dbh, _In_ zend_long attr, _Inout case PDO_ATTR_EMULATE_PREPARES: case PDO_ATTR_CURSOR: case SQLSRV_ATTR_CURSOR_SCROLL_TYPE: - case SQLSRV_ATTR_FORMAT_DECIMALS: { THROW_PDO_ERROR( driver_dbh, PDO_SQLSRV_ERROR_STMT_LEVEL_ATTR ); } @@ -1156,7 +1180,6 @@ int pdo_sqlsrv_dbh_get_attr( _Inout_ pdo_dbh_t *dbh, _In_ zend_long attr, _Inout case PDO_ATTR_EMULATE_PREPARES: case PDO_ATTR_CURSOR: case SQLSRV_ATTR_CURSOR_SCROLL_TYPE: - case SQLSRV_ATTR_FORMAT_DECIMALS: { THROW_PDO_ERROR( driver_dbh, PDO_SQLSRV_ERROR_STMT_LEVEL_ATTR ); } @@ -1229,6 +1252,18 @@ int pdo_sqlsrv_dbh_get_attr( _Inout_ pdo_dbh_t *dbh, _In_ zend_long attr, _Inout break; } + case SQLSRV_ATTR_FORMAT_DECIMALS: + { + ZVAL_BOOL( return_value, driver_dbh->format_decimals ); + break; + } + + case SQLSRV_ATTR_DECIMAL_PLACES: + { + ZVAL_LONG( return_value, driver_dbh->decimal_places ); + break; + } + default: { THROW_PDO_ERROR( driver_dbh, PDO_SQLSRV_ERROR_INVALID_DBH_ATTR ); @@ -1594,6 +1629,10 @@ void add_stmt_option_key( _Inout_ sqlsrv_context& ctx, _In_ size_t key, _Inout_ option_key = PDO_STMT_OPTION_FORMAT_DECIMALS; break; + case SQLSRV_ATTR_DECIMAL_PLACES: + option_key = PDO_STMT_OPTION_DECIMAL_PLACES; + break; + default: CHECK_CUSTOM_ERROR( true, ctx, PDO_SQLSRV_ERROR_INVALID_STMT_OPTION ) { throw core::CoreException(); diff --git a/source/pdo_sqlsrv/pdo_init.cpp b/source/pdo_sqlsrv/pdo_init.cpp index 6d47cf5b6..000878fae 100644 --- a/source/pdo_sqlsrv/pdo_init.cpp +++ b/source/pdo_sqlsrv/pdo_init.cpp @@ -287,6 +287,7 @@ namespace { { "SQLSRV_ATTR_FETCHES_NUMERIC_TYPE", SQLSRV_ATTR_FETCHES_NUMERIC_TYPE }, { "SQLSRV_ATTR_FETCHES_DATETIME_TYPE", SQLSRV_ATTR_FETCHES_DATETIME_TYPE }, { "SQLSRV_ATTR_FORMAT_DECIMALS" , SQLSRV_ATTR_FORMAT_DECIMALS }, + { "SQLSRV_ATTR_DECIMAL_PLACES" , SQLSRV_ATTR_DECIMAL_PLACES }, // used for the size for output parameters: PDO::PARAM_INT and PDO::PARAM_BOOL use the default size of int, // PDO::PARAM_STR uses the size of the string in the variable diff --git a/source/pdo_sqlsrv/pdo_stmt.cpp b/source/pdo_sqlsrv/pdo_stmt.cpp index de1fc882a..d90fd50a7 100644 --- a/source/pdo_sqlsrv/pdo_stmt.cpp +++ b/source/pdo_sqlsrv/pdo_stmt.cpp @@ -883,7 +883,11 @@ int pdo_sqlsrv_stmt_set_attr( _Inout_ pdo_stmt_t *stmt, _In_ zend_long attr, _In break; case SQLSRV_ATTR_FORMAT_DECIMALS: - core_sqlsrv_set_format_decimals(driver_stmt, val TSRMLS_CC); + driver_stmt->format_decimals = ( zend_is_true( val )) ? true : false; + break; + + case SQLSRV_ATTR_DECIMAL_PLACES: + core_sqlsrv_set_decimal_places(driver_stmt, val TSRMLS_CC); break; default: @@ -973,6 +977,18 @@ int pdo_sqlsrv_stmt_get_attr( _Inout_ pdo_stmt_t *stmt, _In_ zend_long attr, _In break; } + case SQLSRV_ATTR_FORMAT_DECIMALS: + { + ZVAL_BOOL( return_value, driver_stmt->format_decimals ); + break; + } + + case SQLSRV_ATTR_DECIMAL_PLACES: + { + ZVAL_LONG( return_value, driver_stmt->decimal_places ); + break; + } + default: THROW_PDO_ERROR( driver_stmt, PDO_SQLSRV_ERROR_INVALID_STMT_ATTR ); break; diff --git a/source/pdo_sqlsrv/pdo_util.cpp b/source/pdo_sqlsrv/pdo_util.cpp index 0295b406b..4120876b0 100644 --- a/source/pdo_sqlsrv/pdo_util.cpp +++ b/source/pdo_sqlsrv/pdo_util.cpp @@ -438,13 +438,9 @@ pdo_error PDO_ERRORS[] = { { IMSSP, (SQLCHAR*) "The Azure AD Access Token is empty. Expected a byte string.", -91, false} }, { - SQLSRV_ERROR_INVALID_FORMAT_DECIMALS, + SQLSRV_ERROR_INVALID_DECIMAL_PLACES, { IMSSP, (SQLCHAR*) "Expected an integer to specify number of decimals to format the output values of decimal data types.", -92, false} }, - { - SQLSRV_ERROR_FORMAT_DECIMALS_OUT_OF_RANGE, - { IMSSP, (SQLCHAR*) "For formatting decimal data values, %1!d! is out of range. Expected an integer from 0 to 38, inclusive.", -93, true} - }, { UINT_MAX, {} } }; diff --git a/source/pdo_sqlsrv/php_pdo_sqlsrv.h b/source/pdo_sqlsrv/php_pdo_sqlsrv.h index ced89eeef..d9bb55e59 100644 --- a/source/pdo_sqlsrv/php_pdo_sqlsrv.h +++ b/source/pdo_sqlsrv/php_pdo_sqlsrv.h @@ -49,7 +49,8 @@ enum PDO_SQLSRV_ATTR { SQLSRV_ATTR_CLIENT_BUFFER_MAX_KB_SIZE, SQLSRV_ATTR_FETCHES_NUMERIC_TYPE, SQLSRV_ATTR_FETCHES_DATETIME_TYPE, - SQLSRV_ATTR_FORMAT_DECIMALS + SQLSRV_ATTR_FORMAT_DECIMALS, + SQLSRV_ATTR_DECIMAL_PLACES }; // valid set of values for TransactionIsolation connection option @@ -206,6 +207,8 @@ struct pdo_sqlsrv_dbh : public sqlsrv_conn { zend_long client_buffer_max_size; bool fetch_numeric; bool fetch_datetime; + bool format_decimals; + short decimal_places; pdo_sqlsrv_dbh( _In_ SQLHANDLE h, _In_ error_callback e, _In_ void* driver TSRMLS_DC ); }; @@ -267,6 +270,8 @@ struct pdo_sqlsrv_stmt : public sqlsrv_stmt { direct_query = db->direct_query; fetch_numeric = db->fetch_numeric; fetch_datetime = db->fetch_datetime; + format_decimals = db->format_decimals; + decimal_places = db->decimal_places; } virtual ~pdo_sqlsrv_stmt( void ); diff --git a/source/shared/core_sqlsrv.h b/source/shared/core_sqlsrv.h index 91be215d8..363ccad19 100644 --- a/source/shared/core_sqlsrv.h +++ b/source/shared/core_sqlsrv.h @@ -173,6 +173,8 @@ const int SQL_SERVER_MAX_FIELD_SIZE = 8000; const int SQL_SERVER_MAX_PRECISION = 38; const int SQL_SERVER_MAX_TYPE_SIZE = 0; const int SQL_SERVER_MAX_PARAMS = 2100; +const int SQL_SERVER_MAX_MONEY_SCALE = 4; + // increase the maximum message length to accommodate for the long error returned for operand type clash // or for conversion of a long string const int SQL_MAX_ERROR_MESSAGE_LENGTH = SQL_MAX_MESSAGE_LENGTH * 2; @@ -230,6 +232,9 @@ enum SQLSRV_FETCH_TYPE { // buffer size of a sql state (including the null character) const int SQL_SQLSTATE_BUFSIZE = SQL_SQLSTATE_SIZE + 1; +// default value of decimal places (no formatting required) +const short NO_CHANGE_DECIMAL_PLACES = -1; + // buffer size allocated to retrieve data from a PHP stream. This number // was chosen since PHP doesn't return more than 8k at a time even if // the amount requested was more. @@ -1108,6 +1113,7 @@ enum SQLSRV_STMT_OPTIONS { SQLSRV_STMT_OPTION_CLIENT_BUFFER_MAX_SIZE, SQLSRV_STMT_OPTION_DATE_AS_STRING, SQLSRV_STMT_OPTION_FORMAT_DECIMALS, + SQLSRV_STMT_OPTION_DECIMAL_PLACES, // Driver specific connection options SQLSRV_STMT_OPTION_DRIVER_SPECIFIC = 1000, @@ -1302,6 +1308,11 @@ struct stmt_option_format_decimals : public stmt_option_functor { virtual void operator()( _Inout_ sqlsrv_stmt* stmt, stmt_option const* opt, _In_ zval* value_z TSRMLS_DC ); }; +struct stmt_option_decimal_places : public stmt_option_functor { + + virtual void operator()( _Inout_ sqlsrv_stmt* stmt, stmt_option const* opt, _In_ zval* value_z TSRMLS_DC ); +}; + // used to hold the table for statment options struct stmt_option { @@ -1372,7 +1383,7 @@ struct sqlsrv_output_param { SQLLEN original_buffer_len; // used to make sure the returned length didn't overflow the buffer SQLSRV_PHPTYPE php_out_type; // used to convert output param if necessary bool is_bool; - param_meta_data meta_data; // parameter meta data + param_meta_data meta_data; // parameter meta data // string output param constructor sqlsrv_output_param( _In_ zval* p_z, _In_ SQLSRV_ENCODING enc, _In_ int num, _In_ SQLUINTEGER buffer_len ) : @@ -1399,15 +1410,9 @@ struct sqlsrv_output_param { meta_data.nullable = nullable; } - SQLSMALLINT getDecimalDigits() + param_meta_data& getMetaData() { - // Return decimal_digits only for decimal / numeric types. Otherwise, return -1 - if (meta_data.sql_type == SQL_DECIMAL || meta_data.sql_type == SQL_NUMERIC) { - return meta_data.decimal_digits; - } - else { - return -1; - } + return meta_data; } }; @@ -1435,7 +1440,8 @@ struct sqlsrv_stmt : public sqlsrv_context { unsigned long query_timeout; // maximum allowed statement execution time zend_long buffered_query_limit; // maximum allowed memory for a buffered query (measured in KB) bool date_as_string; // false by default but the user can set this to true to retrieve datetime values as strings - short num_decimals; // indicates number of decimals shown in fetched results (-1 by default, which means no formatting required) + bool format_decimals; // false by default but the user can set this to true to add the missing leading zeroes and/or control number of decimal digits to show + short decimal_places; // indicates number of decimals shown in fetched results (-1 by default, which means no change to number of decimal digits) // holds output pointers for SQLBindParameter // We use a deque because it 1) provides the at/[] access in constant time, and 2) grows dynamically without moving @@ -1476,9 +1482,10 @@ struct field_meta_data { SQLULEN field_precision; SQLSMALLINT field_scale; SQLSMALLINT field_is_nullable; + bool field_is_money_type; field_meta_data() : field_name_len(0), field_type(0), field_size(0), field_precision(0), - field_scale (0), field_is_nullable(0) + field_scale (0), field_is_nullable(0), field_is_money_type(false) { } @@ -1527,7 +1534,7 @@ void core_sqlsrv_set_send_at_exec( _Inout_ sqlsrv_stmt* stmt, _In_ zval* value_z bool core_sqlsrv_send_stream_packet( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ); void core_sqlsrv_set_buffered_query_limit( _Inout_ sqlsrv_stmt* stmt, _In_ zval* value_z TSRMLS_DC ); void core_sqlsrv_set_buffered_query_limit( _Inout_ sqlsrv_stmt* stmt, _In_ SQLLEN limit TSRMLS_DC ); -void core_sqlsrv_set_format_decimals(_Inout_ sqlsrv_stmt* stmt, _In_ zval* value_z TSRMLS_DC); +void core_sqlsrv_set_decimal_places(_Inout_ sqlsrv_stmt* stmt, _In_ zval* value_z TSRMLS_DC); //********************************************************************************************************************************* // Result Set @@ -1769,8 +1776,7 @@ enum SQLSRV_ERROR_CODES { SQLSRV_ERROR_DOUBLE_CONVERSION_FAILED, SQLSRV_ERROR_INVALID_OPTION_WITH_ACCESS_TOKEN, SQLSRV_ERROR_EMPTY_ACCESS_TOKEN, - SQLSRV_ERROR_INVALID_FORMAT_DECIMALS, - SQLSRV_ERROR_FORMAT_DECIMALS_OUT_OF_RANGE, + SQLSRV_ERROR_INVALID_DECIMAL_PLACES, // Driver specific error codes starts from here. SQLSRV_ERROR_DRIVER_SPECIFIC = 1000, diff --git a/source/shared/core_stmt.cpp b/source/shared/core_stmt.cpp index 206fe11d5..8a4cc227d 100644 --- a/source/shared/core_stmt.cpp +++ b/source/shared/core_stmt.cpp @@ -107,7 +107,7 @@ void default_sql_type( _Inout_ sqlsrv_stmt* stmt, _In_opt_ SQLULEN paramno, _In_ _Out_ SQLSMALLINT& sql_type TSRMLS_DC ); void col_cache_dtor( _Inout_ zval* data_z ); void field_cache_dtor( _Inout_ zval* data_z ); -void format_decimal_numbers(_In_ SQLSMALLINT decimals_digits, _In_ SQLSMALLINT field_scale, _Inout_updates_bytes_(*field_len) char*& field_value, _Inout_ SQLLEN* field_len); +void format_decimal_numbers(_In_ SQLSMALLINT decimals_places, _In_ SQLSMALLINT field_scale, _Inout_updates_bytes_(*field_len) char*& field_value, _Inout_ SQLLEN* field_len); void finalize_output_parameters( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ); void get_field_as_string( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT field_index, _Inout_ sqlsrv_phptype sqlsrv_php_type, _Inout_updates_bytes_(*field_len) void*& field_value, _Inout_ SQLLEN* field_len TSRMLS_DC ); @@ -142,7 +142,8 @@ sqlsrv_stmt::sqlsrv_stmt( _In_ sqlsrv_conn* c, _In_ SQLHANDLE handle, _In_ error past_next_result_end( false ), query_timeout( QUERY_TIMEOUT_INVALID ), date_as_string(false), - num_decimals(-1), // -1 means no formatting required + format_decimals(false), // no formatting needed + decimal_places(NO_CHANGE_DECIMAL_PLACES), // the default is no formatting to resultset required buffered_query_limit( sqlsrv_buffered_result_set::BUFFERED_QUERY_LIMIT_INVALID ), param_ind_ptrs( 10 ), // initially hold 10 elements, which should cover 90% of the cases and only take < 100 byte send_streams_at_exec( true ), @@ -925,6 +926,19 @@ field_meta_data* core_sqlsrv_field_metadata( _Inout_ sqlsrv_stmt* stmt, _In_ SQL } } + if (meta_data->field_type == SQL_DECIMAL) { + // Check if it is money type -- get the name of the data type + char field_type_name[SS_MAXCOLNAMELEN] = {'\0'}; + SQLSMALLINT out_buff_len; + SQLLEN not_used; + core::SQLColAttribute(stmt, colno + 1, SQL_DESC_TYPE_NAME, field_type_name, + sizeof( field_type_name ), &out_buff_len, ¬_used TSRMLS_CC); + + if (!strcmp(field_type_name, "money") || !strcmp(field_type_name, "smallmoney")) { + meta_data->field_is_money_type = true; + } + } + // Set the field name lenth meta_data->field_name_len = static_cast( field_name_len ); @@ -1258,20 +1272,21 @@ void core_sqlsrv_set_query_timeout( _Inout_ sqlsrv_stmt* stmt, _In_ long timeout } } -void core_sqlsrv_set_format_decimals(_Inout_ sqlsrv_stmt* stmt, _In_ zval* value_z TSRMLS_DC) +void core_sqlsrv_set_decimal_places(_Inout_ sqlsrv_stmt* stmt, _In_ zval* value_z TSRMLS_DC) { try { // first check if the input is an integer - CHECK_CUSTOM_ERROR(Z_TYPE_P(value_z) != IS_LONG, stmt, SQLSRV_ERROR_INVALID_FORMAT_DECIMALS) { + CHECK_CUSTOM_ERROR(Z_TYPE_P(value_z) != IS_LONG, stmt, SQLSRV_ERROR_INVALID_DECIMAL_PLACES) { throw core::CoreException(); } - zend_long format_decimals = Z_LVAL_P(value_z); - CHECK_CUSTOM_ERROR(format_decimals < 0 || format_decimals > SQL_SERVER_MAX_PRECISION, stmt, SQLSRV_ERROR_FORMAT_DECIMALS_OUT_OF_RANGE, format_decimals) { - throw core::CoreException(); + zend_long decimal_places = Z_LVAL_P(value_z); + if (decimal_places < 0 || decimal_places > SQL_SERVER_MAX_MONEY_SCALE) { + // ignore decimal_places because it is out of range + decimal_places = NO_CHANGE_DECIMAL_PLACES; } - stmt->num_decimals = static_cast(format_decimals); + stmt->decimal_places = static_cast(decimal_places); } catch( core::CoreException& ) { throw; @@ -1447,7 +1462,17 @@ void stmt_option_date_as_string:: operator()( _Inout_ sqlsrv_stmt* stmt, stmt_op void stmt_option_format_decimals:: operator()( _Inout_ sqlsrv_stmt* stmt, stmt_option const* /**/, _In_ zval* value_z TSRMLS_DC ) { - core_sqlsrv_set_format_decimals(stmt, value_z TSRMLS_CC); + if (zend_is_true(value_z)) { + stmt->format_decimals = true; + } + else { + stmt->format_decimals = false; + } +} + +void stmt_option_decimal_places:: operator()( _Inout_ sqlsrv_stmt* stmt, stmt_option const* /**/, _In_ zval* value_z TSRMLS_DC ) +{ + core_sqlsrv_set_decimal_places(stmt, value_z TSRMLS_CC); } // internal function to release the active stream. Called by each main API function @@ -2114,25 +2139,29 @@ void field_cache_dtor( _Inout_ zval* data_z ) } // To be called for formatting decimal / numeric fetched values from finalize_output_parameters() and/or get_field_as_string() -void format_decimal_numbers(_In_ SQLSMALLINT decimals_digits, _In_ SQLSMALLINT field_scale, _Inout_updates_bytes_(*field_len) char*& field_value, _Inout_ SQLLEN* field_len) +void format_decimal_numbers(_In_ SQLSMALLINT decimals_places, _In_ SQLSMALLINT field_scale, _Inout_updates_bytes_(*field_len) char*& field_value, _Inout_ SQLLEN* field_len) { // In SQL Server, the default maximum precision of numeric and decimal data types is 38 // - // Note: stmt->num_decimals is -1 by default, which means no formatting on decimals / numerics is necessary - // If the required number of decimals is larger than the field scale, will use the column field scale instead. - // This is to ensure the number of decimals adheres to the column field scale. If smaller, the output value may be rounded up. + // Note: decimals_places is NO_CHANGE_DECIMAL_PLACES by default, which means no formatting on decimal data is necessary + // This function assumes stmt->format_decimals is true, so it first checks if it is necessary to add the leading zero. + // + // Likewise, if decimals_places is larger than the field scale, decimals_places wil be ignored. This is to ensure the + // number of decimals adheres to the column field scale. If smaller, the output value may be rounded up. // - // Note: it's possible that the decimal / numeric value does not contain a decimal dot because the field scale is 0. - // Thus, first check if the decimal dot exists. If not, no formatting necessary, regardless of decimals_digits + // Note: it's possible that the decimal data does not contain a decimal dot because the field scale is 0. + // Thus, first check if the decimal dot exists. If not, no formatting necessary, regardless of + // format_decimals and decimals_places // std::string str = field_value; size_t pos = str.find_first_of('.'); - if (pos == std::string::npos || decimals_digits < 0) { + // The decimal dot is not found, simply return + if (pos == std::string::npos) { return; } - SQLSMALLINT num_decimals = decimals_digits; + SQLSMALLINT num_decimals = decimals_places; if (num_decimals > field_scale) { num_decimals = field_scale; } @@ -2160,47 +2189,24 @@ void format_decimal_numbers(_In_ SQLSMALLINT decimals_digits, _In_ SQLSMALLINT f pos++; } - size_t last = 0; - if (num_decimals == 0) { - // Chop all decimal digits, including the decimal dot - size_t pos2 = pos + 1; - short n = str[pos2] - '0'; - if (n >= 5) { - // Start rounding up - starting from the digit left of the dot all the way to the first digit - bool carry_over = true; - for (short p = pos - 1; p >= 0 && carry_over; p--) { - n = str[p] - '0'; - if (n == 9) { - str[p] = '0' ; - carry_over = true; - } - else { - n++; - carry_over = false; - str[p] = '0' + n; - } - } - if (carry_over) { - std::ostringstream oss; - oss << '1' << str.substr(0, pos); - str = oss.str(); - pos++; - } - } - last = pos; - } - else { - size_t pos2 = pos + num_decimals + 1; - // No need to check if rounding is necessary when pos2 has passed the last digit in the input string - if (pos2 < str.length()) { + if (num_decimals == NO_CHANGE_DECIMAL_PLACES) { + // Add the minus sign back if negative + if (isNegative) { + std::ostringstream oss; + oss << '-' << str.substr(0); + str = oss.str(); + } + } else { + // Start formatting + size_t last = 0; + if (num_decimals == 0) { + // Chop all decimal digits, including the decimal dot + size_t pos2 = pos + 1; short n = str[pos2] - '0'; if (n >= 5) { - // Start rounding up - starting from the digit left of pos2 all the way to the first digit + // Start rounding up - starting from the digit left of the dot all the way to the first digit bool carry_over = true; - for (short p = pos2 - 1; p >= 0 && carry_over; p--) { - if (str[p] == '.') { // Skip the dot - continue; - } + for (short p = pos - 1; p >= 0 && carry_over; p--) { n = str[p] - '0'; if (n == 9) { str[p] = '0' ; @@ -2214,22 +2220,54 @@ void format_decimal_numbers(_In_ SQLSMALLINT decimals_digits, _In_ SQLSMALLINT f } if (carry_over) { std::ostringstream oss; - oss << '1' << str.substr(0, pos2); + oss << '1' << str.substr(0, pos); str = oss.str(); - pos2++; + pos++; } } + last = pos; + } + else { + size_t pos2 = pos + num_decimals + 1; + // No need to check if rounding is necessary when pos2 has passed the last digit in the input string + if (pos2 < str.length()) { + short n = str[pos2] - '0'; + if (n >= 5) { + // Start rounding up - starting from the digit left of pos2 all the way to the first digit + bool carry_over = true; + for (short p = pos2 - 1; p >= 0 && carry_over; p--) { + if (str[p] == '.') { // Skip the dot + continue; + } + n = str[p] - '0'; + if (n == 9) { + str[p] = '0' ; + carry_over = true; + } + else { + n++; + carry_over = false; + str[p] = '0' + n; + } + } + if (carry_over) { + std::ostringstream oss; + oss << '1' << str.substr(0, pos2); + str = oss.str(); + pos2++; + } + } + } + last = pos2; + } + // Add the minus sign back if negative + if (isNegative) { + std::ostringstream oss; + oss << '-' << str.substr(0, last); + str = oss.str(); + } else { + str = str.substr(0, last); } - last = pos2; - } - - // Add the minus sign back if negative - if (isNegative) { - std::ostringstream oss; - oss << '-' << str.substr(0, last); - str = oss.str(); - } else { - str = str.substr(0, last); } size_t len = str.length(); @@ -2313,7 +2351,8 @@ void finalize_output_parameters( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) core::sqlsrv_zval_stringl(value_z, str, str_len); } else { - SQLSMALLINT decimal_digits = output_param->getDecimalDigits(); + //SQLSMALLINT decimal_digits = output_param->getDecimalDigits(); + param_meta_data metaData = output_param->getMetaData(); if (output_param->encoding != SQLSRV_ENCODING_CHAR) { char* outString = NULL; @@ -2323,15 +2362,16 @@ void finalize_output_parameters( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) throw core::CoreException(); } - if (stmt->num_decimals >= 0 && decimal_digits >= 0) { - format_decimal_numbers(stmt->num_decimals, decimal_digits, outString, &outLen); + if (stmt->format_decimals && (metaData.sql_type == SQL_DECIMAL || metaData.sql_type == SQL_NUMERIC)) { + format_decimal_numbers(NO_CHANGE_DECIMAL_PLACES, metaData.decimal_digits, outString, &outLen); } + core::sqlsrv_zval_stringl(value_z, outString, outLen); sqlsrv_free(outString); } else { - if (stmt->num_decimals >= 0 && decimal_digits >= 0) { - format_decimal_numbers(stmt->num_decimals, decimal_digits, str, &str_len); + if (stmt->format_decimals && (metaData.sql_type == SQL_DECIMAL || metaData.sql_type == SQL_NUMERIC)) { + format_decimal_numbers(NO_CHANGE_DECIMAL_PLACES, metaData.decimal_digits, str, &str_len); } core::sqlsrv_zval_stringl(value_z, str, str_len); @@ -2601,8 +2641,10 @@ void get_field_as_string( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT field_ind } } - if (stmt->num_decimals >= 0 && (sql_field_type == SQL_DECIMAL || sql_field_type == SQL_NUMERIC)) { - format_decimal_numbers(stmt->num_decimals, stmt->current_meta_data[field_index]->field_scale, field_value_temp, &field_len_temp); + if (stmt->format_decimals && (sql_field_type == SQL_DECIMAL || sql_field_type == SQL_NUMERIC)) { + // number of decimal places only affect money / smallmoney fields + SQLSMALLINT decimal_places = (stmt->current_meta_data[field_index]->field_is_money_type) ? stmt->decimal_places : NO_CHANGE_DECIMAL_PLACES; + format_decimal_numbers(decimal_places, stmt->current_meta_data[field_index]->field_scale, field_value_temp, &field_len_temp); } } // else if( sql_display_size >= 1 && sql_display_size <= SQL_SERVER_MAX_FIELD_SIZE ) diff --git a/source/sqlsrv/conn.cpp b/source/sqlsrv/conn.cpp index d5f324a23..60b9f0d16 100644 --- a/source/sqlsrv/conn.cpp +++ b/source/sqlsrv/conn.cpp @@ -46,6 +46,45 @@ struct date_as_string_func { } }; +struct format_decimals_func +{ + static void func(connection_option const* /*option*/, _In_ zval* value, _Inout_ sqlsrv_conn* conn, std::string& /*conn_str*/ TSRMLS_DC) + { + TSRMLS_C; // show as used to avoid a warning + + ss_sqlsrv_conn* ss_conn = static_cast(conn); + + if (zend_is_true(value)) { + ss_conn->format_decimals = true; + } + else { + ss_conn->format_decimals = false; + } + } +}; + +struct decimal_places_func +{ + + static void func(connection_option const* /*option*/, _In_ zval* value, _Inout_ sqlsrv_conn* conn, std::string& /*conn_str*/ TSRMLS_DC) + { + TSRMLS_C; // show as used to avoid a warning + + // first check if the input is an integer + if (Z_TYPE_P(value) != IS_LONG) { + THROW_SS_ERROR(conn, SQLSRV_ERROR_INVALID_DECIMAL_PLACES); + } + + zend_long decimal_places = Z_LVAL_P(value); + if (decimal_places < 0 || decimal_places > SQL_SERVER_MAX_MONEY_SCALE) { + decimal_places = NO_CHANGE_DECIMAL_PLACES; + } + + ss_sqlsrv_conn* ss_conn = static_cast(conn); + ss_conn->decimal_places = static_cast(decimal_places); + } +}; + struct conn_char_set_func { static void func( connection_option const* /*option*/, _Inout_ zval* value, _Inout_ sqlsrv_conn* conn, std::string& /*conn_str*/ TSRMLS_DC ) @@ -175,6 +214,7 @@ namespace SSStmtOptionNames { const char CLIENT_BUFFER_MAX_SIZE[] = INI_BUFFERED_QUERY_LIMIT; const char DATE_AS_STRING[] = "ReturnDatesAsStrings"; const char FORMAT_DECIMALS[] = "FormatDecimals"; + const char DECIMAL_PLACES[] = "DecimalPlaces"; } namespace SSConnOptionNames { @@ -192,6 +232,8 @@ const char ConnectionPooling[] = "ConnectionPooling"; const char ConnectRetryCount[] = "ConnectRetryCount"; const char ConnectRetryInterval[] = "ConnectRetryInterval"; const char Database[] = "Database"; +const char DecimalPlaces[] = "DecimalPlaces"; +const char FormatDecimals[] = "FormatDecimals"; const char DateAsString[] = "ReturnDatesAsStrings"; const char Driver[] = "Driver"; const char Encrypt[] = "Encrypt"; @@ -217,6 +259,8 @@ const char WSID[] = "WSID"; enum SS_CONN_OPTIONS { SS_CONN_OPTION_DATE_AS_STRING = SQLSRV_CONN_OPTION_DRIVER_SPECIFIC, + SS_CONN_OPTION_FORMAT_DECIMALS, + SS_CONN_OPTION_DECIMAL_PLACES, }; //List of all statement options supported by this driver @@ -257,6 +301,12 @@ const stmt_option SS_STMT_OPTS[] = { SQLSRV_STMT_OPTION_FORMAT_DECIMALS, std::unique_ptr( new stmt_option_format_decimals ) }, + { + SSStmtOptionNames::DECIMAL_PLACES, + sizeof( SSStmtOptionNames::DECIMAL_PLACES), + SQLSRV_STMT_OPTION_DECIMAL_PLACES, + std::unique_ptr( new stmt_option_decimal_places ) + }, { NULL, 0, SQLSRV_STMT_OPTION_INVALID, std::unique_ptr{} }, }; @@ -515,6 +565,24 @@ const connection_option SS_CONN_OPTS[] = { CONN_ATTR_BOOL, date_as_string_func::func }, + { + SSConnOptionNames::FormatDecimals, + sizeof( SSConnOptionNames::FormatDecimals), + SS_CONN_OPTION_FORMAT_DECIMALS, + SSConnOptionNames::FormatDecimals, + sizeof( SSConnOptionNames::FormatDecimals), + CONN_ATTR_BOOL, + format_decimals_func::func + }, + { + SSConnOptionNames::DecimalPlaces, + sizeof( SSConnOptionNames::DecimalPlaces), + SS_CONN_OPTION_DECIMAL_PLACES, + SSConnOptionNames::DecimalPlaces, + sizeof( SSConnOptionNames::DecimalPlaces), + CONN_ATTR_INT, + decimal_places_func::func + }, { NULL, 0, SQLSRV_CONN_OPTION_INVALID, NULL, 0 , CONN_ATTR_INVALID, NULL }, //terminate the table }; diff --git a/source/sqlsrv/php_sqlsrv.h b/source/sqlsrv/php_sqlsrv.h index 1816942ac..3f77ecbcf 100644 --- a/source/sqlsrv/php_sqlsrv.h +++ b/source/sqlsrv/php_sqlsrv.h @@ -131,6 +131,8 @@ struct ss_sqlsrv_conn : sqlsrv_conn { HashTable* stmts; bool date_as_string; + bool format_decimals; // flag set to turn on formatting for values of decimal / numeric types + short decimal_places; // number of decimal digits to show in a result set unless format_numbers is false bool in_transaction; // flag set when inside a transaction and used for checking validity of tran API calls // static variables used in process_params @@ -142,6 +144,8 @@ struct ss_sqlsrv_conn : sqlsrv_conn sqlsrv_conn( h, e, drv, SQLSRV_ENCODING_SYSTEM TSRMLS_CC ), stmts( NULL ), date_as_string( false ), + format_decimals( false ), + decimal_places( NO_CHANGE_DECIMAL_PLACES ), in_transaction( false ) { } diff --git a/source/sqlsrv/stmt.cpp b/source/sqlsrv/stmt.cpp index 3da4ebcc7..e9ce41e8a 100644 --- a/source/sqlsrv/stmt.cpp +++ b/source/sqlsrv/stmt.cpp @@ -139,9 +139,11 @@ ss_sqlsrv_stmt::ss_sqlsrv_stmt( _In_ sqlsrv_conn* c, _In_ SQLHANDLE handle, _In_ { core_sqlsrv_set_buffered_query_limit( this, SQLSRV_G( buffered_query_limit ) TSRMLS_CC ); - // initialize date_as_string based on the corresponding connection option + // inherit other values based on the corresponding connection options ss_sqlsrv_conn* ss_conn = static_cast(conn); date_as_string = ss_conn->date_as_string; + format_decimals = ss_conn->format_decimals; + decimal_places = ss_conn->decimal_places; } ss_sqlsrv_stmt::~ss_sqlsrv_stmt( void ) diff --git a/source/sqlsrv/util.cpp b/source/sqlsrv/util.cpp index 545f699d0..ff9e7c863 100644 --- a/source/sqlsrv/util.cpp +++ b/source/sqlsrv/util.cpp @@ -429,13 +429,9 @@ ss_error SS_ERRORS[] = { { IMSSP, (SQLCHAR*) "The Azure AD Access Token is empty. Expected a byte string.", -116, false} }, { - SQLSRV_ERROR_INVALID_FORMAT_DECIMALS, + SQLSRV_ERROR_INVALID_DECIMAL_PLACES, { IMSSP, (SQLCHAR*) "Expected an integer to specify number of decimals to format the output values of decimal data types.", -117, false} }, - { - SQLSRV_ERROR_FORMAT_DECIMALS_OUT_OF_RANGE, - { IMSSP, (SQLCHAR*) "For formatting decimal data values, %1!d! is out of range. Expected an integer from 0 to 38, inclusive.", -118, true} - }, // terminate the list of errors/warnings { UINT_MAX, {} } diff --git a/test/functional/pdo_sqlsrv/pdostatement_format_decimals.phpt b/test/functional/pdo_sqlsrv/pdostatement_format_decimals.phpt index ff29a8086..07303c4b7 100644 --- a/test/functional/pdo_sqlsrv/pdostatement_format_decimals.phpt +++ b/test/functional/pdo_sqlsrv/pdostatement_format_decimals.phpt @@ -1,24 +1,17 @@ --TEST-- -Test statement attribute PDO::SQLSRV_ATTR_FORMAT_DECIMALS for decimal types +Test connection and statement attributes for formatting decimal and numeric data (feature request issue 415) --DESCRIPTION-- -Test statement attribute PDO::SQLSRV_ATTR_FORMAT_DECIMALS for decimal or -money types (feature request issue 415), which are always fetched as strings -to preserve accuracy and precision, unlike other primitive numeric types, -where there is an option to retrieve them as numbers. +Test the attributes PDO::SQLSRV_ATTR_FORMAT_DECIMALS and PDO::SQLSRV_ATTR_DECIMAL_PLACES, the latter affects money types only, not decimal or numeric types (feature request issue 415). +Money, decimal or numeric types are always fetched as strings to preserve accuracy and precision, unlike other primitive numeric types, where there is an option to retrieve them as numbers. -This attribute expects an integer value from the range [0,38], the money or -decimal types in the fetched result set can be formatted. - -No effect on other operations like insertion or update. +Setting PDO::SQLSRV_ATTR_FORMAT_DECIMALS to false will turn off all formatting, regardless of PDO::SQLSRV_ATTR_DECIMAL_PLACES value. Also, any negative PDO::SQLSRV_ATTR_DECIMAL_PLACES value will be ignored. Likewise, since money or smallmoney fields have scale 4, if PDO::SQLSRV_ATTR_DECIMAL_PLACES value is larger than 4, it will be ignored as well. 1. By default, data will be returned with the original precision and scale -2. The data column original scale still takes precedence – for example, if the user -specifies 3 decimal digits for a column of decimal(5,2), the result still shows only 2 -decimals to the right of the dot -3. After formatting, the missing leading zeroes will be padded -4. The underlying data will not be altered, but formatted results may likely be rounded -up (e.g. .2954 will be displayed as 0.30 if the user wants only two decimals) -5. Do not support output params +2. Set PDO::SQLSRV_ATTR_FORMAT_DECIMALS to true to add the leading zeroes to money and decimal types, if missing. +3. No support for output params + +The attributes PDO::SQLSRV_ATTR_FORMAT_DECIMALS and PDO::SQLSRV_ATTR_DECIMAL_PLACES will only format the +fetched results and have no effect on other operations like insertion or update. --ENV-- PHPT_EXEC=true --SKIPIF-- @@ -35,171 +28,52 @@ function checkException($exception, $expected) } } -function testPdoAttribute($conn, $setAttr) +function testErrorCases($conn) { - // Expects exception because PDO::SQLSRV_ATTR_FORMAT_DECIMALS - // is a statement level attribute + $expected = 'Expected an integer to specify number of decimals to format the output values of decimal data types'; + $query = "SELECT 0.0001"; + try { - $res = true; - if ($setAttr) { - $res = $conn->setAttribute(PDO::SQLSRV_ATTR_FORMAT_DECIMALS, 1); - } else { - $res = $conn->getAttribute(PDO::SQLSRV_ATTR_FORMAT_DECIMALS); - } - if ($res) { - echo "setAttribute at PDO level should have failed!\n"; + $conn->setAttribute(PDO::SQLSRV_ATTR_FORMAT_DECIMALS, 0); + $format = $conn->getAttribute(PDO::SQLSRV_ATTR_FORMAT_DECIMALS); + if ($format !== false) { + echo 'The value of PDO::SQLSRV_ATTR_FORMAT_DECIMALS should be false\n'; + var_dump($format); } + + $conn->setAttribute(PDO::SQLSRV_ATTR_DECIMAL_PLACES, 1.5); } catch (PdoException $e) { - if ($setAttr) { - $expected = 'The given attribute is only supported on the PDOStatement object.'; - } else { - $expected = 'driver does not support that attribute'; - } - checkException($e, $expected); } -} - -function testErrorCases($conn) -{ - $query = "SELECT 0.0001"; try { - $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => 0.9); + $options = array(PDO::SQLSRV_ATTR_DECIMAL_PLACES => 0.9); $stmt = $conn->prepare($query, $options); } catch (PdoException $e) { - $expected = 'Expected an integer to specify number of decimals to format the output values of decimal data types'; checkException($e, $expected); } try { - $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => 100); + $options = array(PDO::SQLSRV_ATTR_DECIMAL_PLACES => true); $stmt = $conn->prepare($query, $options); } catch (PdoException $e) { - $expected = 'For formatting decimal data values, 100 is out of range. Expected an integer from 0 to 38, inclusive.'; checkException($e, $expected); } } -function verifyMoneyValues($conn, $query, $values, $numDigits) -{ - $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => $numDigits); - $stmt = $conn->prepare($query, $options); - $stmt->execute(); - $results = $stmt->fetch(PDO::FETCH_NUM); - - trace("\nverifyMoneyValues:\n"); - for ($i = 0; $i < count($values); $i++) { - $value = number_format($values[$i], $numDigits); - trace("$results[$i], $value\n"); - - if ($value !== $results[$i]) { - echo "testMoneyTypes: Expected $value but got $results[$i]\n"; - } - } -} - -function testFloatTypes($conn) -{ - // This test with the float types of various number of bits, which are retrieved - // as numbers by default. When fetched as strings, no formatting is done even with - // the statement option FormatDecimals set - $epsilon = 0.001; - $values = array(); - for ($i = 0; $i < 5; $i++) { - $n1 = rand(1, 100); - $n2 = rand(1, 100); - $neg = ($i % 2 == 0) ? -1 : 1; - - $n = $neg * $n1 / $n2; - array_push($values, $n); - } - - $query = "SELECT CONVERT(float(1), $values[0]), - CONVERT(float(12), $values[1]), - CONVERT(float(24), $values[2]), - CONVERT(float(36), $values[3]), - CONVERT(float(53), $values[4])"; - $stmt = $conn->query($query); - $floats = $stmt->fetch(PDO::FETCH_NUM); - unset($stmt); - - // Set PDO::SQLSRV_ATTR_FORMAT_DECIMALS to 2 should - // have no effect on floating point numbers - $numDigits = 2; - $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => $numDigits); - $stmt = $conn->prepare($query, $options); - - // By default the floating point numbers are fetched as strings - for ($i = 0; $i < 5; $i++) { - $stmt->execute(); - $floatStr = $stmt->fetchColumn($i); - - $floatVal = floatVal($floats[$i]); - $floatVal1 = floatval($floatStr); - - trace("testFloatTypes: $floatVal1, $floatVal\n"); - - // Check if the numbers of decimal digits are the same - // It is highly unlikely but not impossible - $numbers = explode('.', $floatStr); - $len = strlen($numbers[1]); - if ($len == $numDigits && $floatVal1 != $floatVal) { - echo "Expected $floatVal but $floatVal1 returned. \n"; - } else { - $diff = abs($floatVal1 - $floatVal) / $floatVal; - if ($diff > $epsilon) { - echo "Expected $floatVal but $floatVal1 returned. \n"; - } - } - } -} - -function testMoneyTypes($conn) -{ - // With money and smallmoney types, which are essentially decimal types - // ODBC driver does not support Always Encrypted feature with money / smallmoney - $values = array('24.559', '0', '-0.946', '0.2985', '-99.675', '79.995'); - $defaults = array('24.5590', '.0000', '-.9460', '.2985', '-99.6750', '79.9950'); - - $query = "SELECT CONVERT(smallmoney, $values[0]), - CONVERT(money, $values[1]), - CONVERT(smallmoney, $values[2]), - CONVERT(money, $values[3]), - CONVERT(smallmoney, $values[4]), - CONVERT(money, $values[5])"; - - $stmt = $conn->query($query); - $results = $stmt->fetch(PDO::FETCH_NUM); - for ($i = 0; $i < count($values); $i++) { - if ($defaults[$i] !== $results[$i]) { - echo "testMoneyTypes: Expected $defaults[$i] but got $results[$i]\n"; - } - } - unset($stmt); - - // Set PDO::SQLSRV_ATTR_FORMAT_DECIMALS to 0 then 2 - verifyMoneyValues($conn, $query, $values, 0); - verifyMoneyValues($conn, $query, $values, 2); -} - -function compareNumbers($actual, $input, $column, $fieldScale, $formatDecimal = -1) +function compareNumbers($actual, $input, $column, $fieldScale, $format = true) { $matched = false; if ($actual === $input) { $matched = true; trace("Matched: $actual, $input\n"); } else { - // When $formatDecimal is negative, that means no formatting done - // Otherwise, if $formatDecimal > $fieldScale, will show $fieldScale decimal digits - if ($formatDecimal >= 0) { - $numDecimals = ($formatDecimal > $fieldScale) ? $fieldScale : $formatDecimal; - $expected = number_format($input, $numDecimals); - } else { - $expected = number_format($input, $fieldScale); + // if no formatting, there will be no leading zero + $expected = number_format($input, $fieldScale); + if (!$format) { if (abs($input) < 1) { // Since no formatting, the leading zero should not be there - trace("Drop leading zero of $input--"); + trace("Drop leading zero of $input: "); $expected = str_replace('0.', '.', $expected); } } @@ -207,7 +81,7 @@ function compareNumbers($actual, $input, $column, $fieldScale, $formatDecimal = if ($actual === $expected) { $matched = true; } else { - echo "For $column ($formatDecimal): expected $expected ($input) but the value is $actual\n"; + echo "For $column ($fieldScale): expected $expected ($input) but the value is $actual\n"; } } return $matched; @@ -223,35 +97,35 @@ function testNoOption($conn, $tableName, $inputs, $columns) $results = $stmt->fetch(PDO::FETCH_NUM); trace("\ntestNoOption:\n"); for ($i = 0; $i < count($inputs); $i++) { - compareNumbers($results[$i], $inputs[$i], $columns[$i], $i); + compareNumbers($results[$i], $inputs[$i], $columns[$i], $i, false); } } -function testStmtOption($conn, $tableName, $inputs, $columns, $formatDecimal, $withBuffer) +function testStmtOption($conn, $tableName, $inputs, $columns, $decimalPlaces, $withBuffer) { - // Decimal values should return decimal digits based on the valid statement - // option PDO::SQLSRV_ATTR_FORMAT_DECIMALS + // Decimal values should NOT be affected by the statement + // attribute PDO::SQLSRV_ATTR_FORMAT_DECIMALS $query = "SELECT * FROM $tableName"; if ($withBuffer){ $options = array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL, PDO::SQLSRV_ATTR_CURSOR_SCROLL_TYPE => PDO::SQLSRV_CURSOR_BUFFERED, - PDO::SQLSRV_ATTR_FORMAT_DECIMALS => $formatDecimal); + PDO::SQLSRV_ATTR_DECIMAL_PLACES => $decimalPlaces); } else { - $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => $formatDecimal); + $options = array(PDO::SQLSRV_ATTR_DECIMAL_PLACES => $decimalPlaces); } $size = count($inputs); $stmt = $conn->prepare($query, $options); // Fetch by getting one field at a time - trace("\ntestStmtOption: $formatDecimal and buffered $withBuffer\n"); + trace("\ntestStmtOption: $decimalPlaces and buffered $withBuffer\n"); for ($i = 0; $i < $size; $i++) { $stmt->execute(); $stmt->bindColumn($columns[$i], $field); $result = $stmt->fetch(PDO::FETCH_BOUND); - compareNumbers($field, $inputs[$i], $columns[$i], $i, $formatDecimal); + compareNumbers($field, $inputs[$i], $columns[$i], $i); } } @@ -262,7 +136,7 @@ function getOutputParam($conn, $storedProcName, $inputValue, $prec, $scale, $ino $outSql = getCallProcSqlPlaceholders($storedProcName, 1); - $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => $numDigits); + $options = array(PDO::SQLSRV_ATTR_DECIMAL_PLACES => $numDigits); $stmt = $conn->prepare($outSql, $options); $len = 1024; @@ -279,17 +153,17 @@ function getOutputParam($conn, $storedProcName, $inputValue, $prec, $scale, $ino $stmt->execute(); // The output param value should be the same as the input value, - // unaffected by the statement attr PDO::SQLSRV_ATTR_FORMAT_DECIMALS, - // unless ColumnEncryption is enabled, in which case the driver is able - // to derive the decimal type + // unaffected by the statement attr PDO::SQLSRV_ATTR_DECIMAL_PLACES. + // If ColumnEncryption is enabled, in which case the driver is able + // to derive the decimal type, leading zero will be added if missing if (isAEConnected()) { trace("\ngetOutputParam ($inout) with AE:\n"); $column = 'outputParamAE'; - compareNumbers($outString, $inputValue, $column, $scale, $numDigits); + compareNumbers($outString, $inputValue, $column, $scale, true); } else { trace("\ngetOutputParam ($inout) without AE:\n"); $column = 'outputParam'; - compareNumbers($outString, $inputValue, $column, $scale); + compareNumbers($outString, $inputValue, $column, $scale, false); } } @@ -314,16 +188,8 @@ try { $conn = connect(); // Test some error conditions - testPdoAttribute($conn, true); - testPdoAttribute($conn, false); testErrorCases($conn); - // First test with money types - testMoneyTypes($conn); - - // Also test using regular floats - testFloatTypes($conn); - // Create the test table of decimal / numeric data columns $tableName = 'pdoFormatDecimals'; @@ -347,8 +213,8 @@ try { $n = rand(1, 6); $neg = ($n % 2 == 0) ? -1 : 1; - // $n1 may or may not be negative - $n1 = rand(0, 1000) * $neg; + // $n1, a tiny number, which may or may not be negative, + $n1 = rand(0, 5) * $neg; if ($s > 0) { $max *= 10; @@ -371,6 +237,11 @@ try { testNoOption($conn, $tableName, $values, $columns, true); + // Turn on formatting, which only add leading zeroes, if missing + // decimal and numeric types should be unaffected by + // PDO::SQLSRV_ATTR_DECIMAL_PLACES whatsoever + $conn->setAttribute(PDO::SQLSRV_ATTR_FORMAT_DECIMALS, true); + // Now try with setting number decimals to 3 then 2 testStmtOption($conn, $tableName, $values, $columns, 3, false); testStmtOption($conn, $tableName, $values, $columns, 3, true); diff --git a/test/functional/pdo_sqlsrv/pdostatement_format_decimals_scales.phpt b/test/functional/pdo_sqlsrv/pdostatement_format_decimals_scales.phpt deleted file mode 100644 index a8a40d482..000000000 --- a/test/functional/pdo_sqlsrv/pdostatement_format_decimals_scales.phpt +++ /dev/null @@ -1,248 +0,0 @@ ---TEST-- -Test various precisions of formatting decimal data output values (feature request issue 415) ---DESCRIPTION-- -In SQL Server, the maximum allowed precision is 38. The scale can range from 0 up to the -defined precision. Generate a long numeric string and get rid of the last digit to make it a -39-digit-string. Then replace one digit at a time with a dot '.' to make it a decimal -input string for testing with various scales. -For example, -string(39) ".23456789012345678901234567890123456789" -string(39) "1.3456789012345678901234567890123456789" -string(39) "12.456789012345678901234567890123456789" -string(39) "123.56789012345678901234567890123456789" -string(39) "1234.6789012345678901234567890123456789" -string(39) "12345.789012345678901234567890123456789" -... ... -string(39) "1234567890123456789012345678901234.6789" -string(39) "12345678901234567890123456789012345.789" -string(39) "123456789012345678901234567890123456.89" -string(39) "1234567890123456789012345678901234567.9" -string(38) "12345678901234567890123456789012345678" - -Note: PHP number_format() will not be used for verification in this test -because the function starts losing accuracy with large number of precisions / scales. ---ENV-- -PHPT_EXEC=true ---SKIPIF-- - ---FILE-- - $digits)); - - // Restore the $i-th digit with its original digit - $digits[$i] = $d; - } - - $stmt = insertRow($conn, $tableName, $inputData); - unset($stmt); - - return $inputData; -} - -function verifyNoDecimals($value, $input, $round) -{ - global $prec, $dot; - - // Use PHP explode() to separate the input string into an array - $parts = explode($dot, $input); - $len = strlen($parts[0]); - if ($len == 0) { - // The original input string is missing a leading zero - $parts[0] = '0'; - } - - // No need to worry about carry over for the input data of this test - // Check the first digit of $parts[1] - if ($len < $prec) { - // Only need to round up when $len < $prec - $ch = $parts[1][0]; - - // Round the last digit of $parts[0] if $ch is '5' or above - if ($ch >= '5') { - $len = strlen($parts[0]); - $parts[0][$len-1] = $parts[0][$len-1] + 1 + '0'; - } - } - - // No decimal digits left in the expected string - $expected = $parts[0]; - if ($value !== $expected) { - echo "Round $round scale 0: expected $expected but returned $value\n"; - } -} - -function verifyWithDecimals($value, $input, $round, $scale) -{ - global $dot; - - // Use PHP explode() to separate the input string into an array - $parts = explode($dot, $input); - if (strlen($parts[0]) == 0) { - // The original input string is missing a leading zero - $parts[0] = '0'; - } - - // No need to worry about carry over for the input data of this test - // Check the digit at the position $scale of $parts[1] - $len = strlen($parts[1]); - if ($scale < $len) { - // Only need to round up when $scale < $len - $ch = $parts[1][$scale]; - - // Round the previous digit if $ch is '5' or above - if ($ch >= '5') { - $parts[1][$scale-1] = $parts[1][$scale-1] + 1 + '0'; - } - } - - // Use substr() to get up to $scale - $parts[1] = substr($parts[1], 0, $scale); - - // Join the array elements together - $expected = implode($dot, $parts); - if ($value !== $expected) { - echo "Round $round scale $scale: expected $expected but returned $value\n"; - } -} - -/**** -The function testVariousScales() will fetch one column at a time, using scale from -0 up to the maximum scale allowed for that column type. - -For example, for column of type decimal(38,4), the input string is -1234567890123456789012345678901234.6789 - -When fetching data, using scale from 0 to 4, the following values are expected to return: -1234567890123456789012345678901235 -1234567890123456789012345678901234.7 -1234567890123456789012345678901234.68 -1234567890123456789012345678901234.679 -1234567890123456789012345678901234.6789 - -For example, for column of type decimal(38,6), the input string is -12345678901234567890123456789012.456789 - -When fetching data, using scale from 0 to 6, the following values are expected to return: -12345678901234567890123456789012 -12345678901234567890123456789012.5 -12345678901234567890123456789012.46 -12345678901234567890123456789012.457 -12345678901234567890123456789012.4568 -12345678901234567890123456789012.45679 -12345678901234567890123456789012.456789 - -etc. -****/ -function testVariousScales($conn, $tableName, $inputData) -{ - global $prec; - $max = $prec + 1; - - for ($i = 0; $i < $max; $i++) { - $scale = $prec - $i; - $column = "col_$scale"; - - $query = "SELECT $column as col1 FROM $tableName"; - $input = $inputData[$column]; - - // Default case: the fetched value should be the same as the corresponding input - $stmt = $conn->query($query); - if ($obj = $stmt->fetchObject()) { - trace("\n$obj->col1\n"); - if ($obj->col1 !== $input) { - echo "default case: expected $input but returned $obj->col1\n"; - } - } else { - echo "In testVariousScales: fetchObject failed\n"; - } - - // Next, format how many decimal digits to be displayed - $query = "SELECT $column FROM $tableName"; - for ($j = 0; $j <= $scale; $j++) { - $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => $j); - $stmt = $conn->prepare($query, $options); - $stmt->execute(); - - $stmt->bindColumn($column, $value); - if ($stmt->fetch(PDO::FETCH_BOUND)) { - trace("$value\n"); - if ($j == 0) { - verifyNoDecimals($value, $input, $i); - } else { - verifyWithDecimals($value, $input, $i, $j); - } - } else { - echo "Round $i scale $j: fetch failed\n"; - } - } - } -} - -try { - // This helper method sets PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION - $conn = connect(); - - $tableName = createTestTable($conn); - $inputData = insertTestData($conn, $tableName); - testVariousScales($conn, $tableName, $inputData); - - dropTable($conn, $tableName); - - echo "Done\n"; - - unset($conn); -} catch (PdoException $e) { - echo $e->getMessage() . PHP_EOL; -} -?> ---EXPECT-- -Done diff --git a/test/functional/pdo_sqlsrv/pdostatement_format_money_types.phpt b/test/functional/pdo_sqlsrv/pdostatement_format_money_types.phpt new file mode 100644 index 000000000..5152e1f59 --- /dev/null +++ b/test/functional/pdo_sqlsrv/pdostatement_format_money_types.phpt @@ -0,0 +1,245 @@ +--TEST-- +Test connection attributes for formatting money data (feature request issue 415) +--DESCRIPTION-- +Test how money data in the fetched values can be formatted by using the connection attributes PDO::SQLSRV_ATTR_FORMAT_DECIMALS and PDO::SQLSRV_ATTR_DECIMAL_PLACES, the latter works only with integer values. No effect on other operations like insertion or update. + +The PDO::SQLSRV_ATTR_DECIMAL_PLACES attribute only affects money/smallmoney fields. If its value is out of range, for example, it's negative or larger than the original scale, then its value will be ignored. + +The underlying data will not be altered, but formatted results may likely be rounded up (e.g. .2954 will be displayed as 0.30 if the user wants only two decimals). For this reason, it is not recommended to use formatted money values as inputs to any calculation. + +The corresponding statement attributes always override the inherited values from the connection object. Setting PDO::SQLSRV_ATTR_FORMAT_DECIMALS to false will automatically turn off any formatting of decimal data in the result set, ignoring PDO::SQLSRV_ATTR_DECIMAL_PLACES value. + +By only setting PDO::SQLSRV_ATTR_FORMAT_DECIMALS to true will add the leading zeroes, if missing. + +Do not support output params. +--ENV-- +PHPT_EXEC=true +--SKIPIF-- + +--FILE-- +query($query); + $floats = $stmt->fetch(PDO::FETCH_NUM); + unset($stmt); + + // By default the floating point numbers are fetched as strings + $stmt = $conn->prepare($query); + for ($i = 0; $i < 5; $i++) { + $stmt->execute(); + $floatStr = $stmt->fetchColumn($i); + + $floatVal = floatVal($floats[$i]); + $floatVal1 = floatval($floatStr); + + trace("testFloatTypes: $floatVal1, $floatVal\n"); + + // Check if the numbers of decimal digits are the same + // It is highly unlikely but not impossible + $numbers = explode('.', $floatStr); + $len = strlen($numbers[1]); + if ($len == $numDigits && $floatVal1 != $floatVal) { + echo "Expected $floatVal but $floatVal1 returned. \n"; + } else { + $diff = abs($floatVal1 - $floatVal) / $floatVal; + if ($diff > $epsilon) { + echo "$diff: Expected $floatVal but $floatVal1 returned. \n"; + } + } + } +} + +function verifyMoneyFormatting($conn, $query, $values, $format) +{ + if ($format) { + // Set SQLSRV_ATTR_FORMAT_DECIMALS to true but + // set SQLSRV_ATTR_DECIMAL_PLACES to a negative number + // to override the inherited attribute + $options = array(PDO::SQLSRV_ATTR_DECIMAL_PLACES => -1, PDO::SQLSRV_ATTR_FORMAT_DECIMALS => true); + } else { + // Set SQLSRV_ATTR_FORMAT_DECIMALS to false will + // turn off any formatting -- overriding the inherited + // attributes + $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => false); + } + + $stmt = $conn->prepare($query, $options); + $stmt->execute(); + $results = $stmt->fetch(PDO::FETCH_NUM); + + trace("\verifyMoneyFormatting:\n"); + for ($i = 0; $i < count($values); $i++) { + // money types have a scale of 4 + $default = numberFormat($values[$i], 4); + if (!$format) { + // No formatting - should drop the leading zero, if exists + if (abs($values[$i]) < 1) { + $default = str_replace('0.', '.', $default); + } + } + if ($default !== $results[$i]) { + echo "verifyMoneyFormatting ($format): Expected $default but got $results[$i]\n"; + } + } +} + +function verifyMoneyValues($conn, $numDigits, $query, $values, $override) +{ + if ($override) { + $options = array(PDO::SQLSRV_ATTR_DECIMAL_PLACES => $numDigits); + $stmt = $conn->prepare($query, $options); + } else { + // Use the connection defaults + $stmt = $conn->prepare($query); + } + $stmt->execute(); + $results = $stmt->fetch(PDO::FETCH_NUM); + + trace("\nverifyMoneyValues:\n"); + for ($i = 0; $i < count($values); $i++) { + $value = numberFormat($values[$i], $numDigits); + trace("$results[$i], $value\n"); + + if ($value !== $results[$i]) { + echo "testMoneyTypes ($override, $numDigits): Expected $value but got $results[$i]\n"; + } + } +} + +function testMoneyTypes($conn, $numDigits) +{ + // With money and smallmoney types, which are essentially decimal types + // As of today, ODBC driver does not support Always Encrypted feature with money / smallmoney + + $values = array(); + $nColumns = 6; + for ($i = 0; $i < $nColumns; $i++) { + // First get a random number + $n = rand(0, 10); + $neg = ($n % 2 == 0) ? -1 : 1; + + // $n1 may or may not be negative + $max = 10; + $n1 = rand(0, $max) * $neg; + $n2 = rand(1, $max * 1000); + + $number = sprintf("%d.%d", $n1, $n2); + array_push($values, $number); + } + + $query = "SELECT CONVERT(smallmoney, $values[0]), + CONVERT(money, $values[1]), + CONVERT(smallmoney, $values[2]), + CONVERT(money, $values[3]), + CONVERT(smallmoney, $values[4]), + CONVERT(money, $values[5])"; + + // Do not override the connection attributes + verifyMoneyValues($conn, $numDigits, $query, $values, false); + // Next, override statement attribute to set number of + // decimal places + verifyMoneyValues($conn, 0, $query, $values, true); + + // Set Formatting attribute to true then false + verifyMoneyFormatting($conn, $query, $values, true); + verifyMoneyFormatting($conn, $query, $values, false); +} + +function connGetAttributes($conn, $numDigits) +{ + $format = $conn->getAttribute(PDO::SQLSRV_ATTR_FORMAT_DECIMALS); + if ($format !== true) { + echo "The returned value of SQLSRV_ATTR_FORMAT_DECIMALS, $format, is wrong\n"; + + return false; + } + + $digits = $conn->getAttribute(PDO::SQLSRV_ATTR_DECIMAL_PLACES); + if ($digits != $numDigits) { + echo "The returned value of SQLSRV_ATTR_DECIMAL_PLACES, $digits, is wrong\n"; + + return false; + } + + return true; +} + +function connectWithAttrs($numDigits) +{ + $attr = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => true, + PDO::SQLSRV_ATTR_DECIMAL_PLACES => $numDigits); + + // This helper method sets PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION + $conn = connect('', $attr); + + if (connGetAttributes($conn, $numDigits)) { + // First test with money types + testMoneyTypes($conn, $numDigits); + + // Also test using regular floats + testFloatTypes($conn, $numDigits); + } + unset($conn); +} + +function connectSetAttrs($numDigits) +{ + // This helper method sets PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION + $conn = connect(); + $conn->setAttribute(PDO::SQLSRV_ATTR_FORMAT_DECIMALS, true); + $conn->setAttribute(PDO::SQLSRV_ATTR_DECIMAL_PLACES, $numDigits); + + if (connGetAttributes($conn, $numDigits)) { + // First test with money types + testMoneyTypes($conn, $numDigits); + + // Also test using regular floats + testFloatTypes($conn, $numDigits); + } + + unset($conn); +} + +try { + connectWithAttrs(2); + connectSetAttrs(3); + + echo "Done\n"; + + unset($conn); +} catch (PdoException $e) { + echo $e->getMessage() . PHP_EOL; +} +?> +--EXPECT-- +Done diff --git a/test/functional/sqlsrv/sqlsrv_statement_format_decimals.phpt b/test/functional/sqlsrv/sqlsrv_statement_format_decimals.phpt index 223e4fb6b..3db5d1784 100644 --- a/test/functional/sqlsrv/sqlsrv_statement_format_decimals.phpt +++ b/test/functional/sqlsrv/sqlsrv_statement_format_decimals.phpt @@ -1,22 +1,18 @@ --TEST-- -Test how decimal data output values can be formatted (feature request issue 415) +Test connection and statement attributes for formatting decimal and numeric data (feature request issue 415) --DESCRIPTION-- -Test how numeric and decimal data output values can be formatted by using the -statement option FormatDecimals, which expects an integer value from the range [0,38], -affecting only the money / decimal types in the fetched result set because they are -always strings to preserve accuracy and precision, unlike other primitive numeric -types that can be retrieved as numbers. - -No effect on other operations like insertion or update. - -1. By default, data will be returned with the original precision and scale -2. The data column original scale still takes precedence – for example, if the user -specifies 3 decimal digits for a column of decimal(5,2), the result still shows only 2 -decimals to the right of the dot -3. After formatting, the missing leading zeroes will be padded -4. The underlying data will not be altered, but formatted results may likely be rounded -up (e.g. .2954 will be displayed as 0.30 if the user wants only two decimals) -5. For output params use SQLSRV_SQLTYPE_DECIMAL with the correct precision and scale +Test the connection and statement options, FormatDecimals and +DecimalPlaces, the latter affects money types only, not +decimal or numeric types (feature request issue 415). +Money, decimal or numeric types are always fetched as strings to preserve accuracy and precision, unlike other primitive numeric types, where there is an option to retrieve them as numbers. + +Setting FormatDecimals to false will turn off all formatting, regardless of DecimalPlaces value. Also, any negative DecimalPlaces value will be ignored. Likewise, since money or smallmoney fields have scale 4, if DecimalPlaces value is larger than 4, it will be ignored as well. + +1. By default, data will be returned with the original precision and scale +2. Set FormatDecimals to true to add the leading zeroes to money and decimal types, if missing. +3. For output params, leading zeroes will be added for any decimal fields if FormatDecimals is true, but only if either SQLSRV_SQLTYPE_DECIMAL or SQLSRV_SQLTYPE_NUMERIC is set correctly to match the original column type and its precision / scale. + +FormatDecimals and DecimalPlaces will only format the fetched results and have no effect on other operatioins like insertion or update. --ENV-- PHPT_EXEC=true --SKIPIF-- @@ -25,23 +21,19 @@ PHPT_EXEC=true $fieldScale, will show $fieldScale decimal digits - if ($formatDecimal >= 0) { - $numDecimals = ($formatDecimal > $fieldScale) ? $fieldScale : $formatDecimal; - $expected = number_format($input, $numDecimals); - } else { - $expected = number_format($input, $fieldScale); + // If no formatting, there will be no leading zero + $expected = number_format($input, $fieldScale); + if (!$format) { if (abs($input) < 1) { // Since no formatting, the leading zero should not be there - trace("Drop leading zero of $input--"); + trace("Drop leading zero of $input: "); $expected = str_replace('0.', '.', $expected); } } @@ -49,7 +41,7 @@ function compareNumbers($actual, $input, $column, $fieldScale, $formatDecimal = if ($actual === $expected) { $matched = true; } else { - echo "For $column ($formatDecimal): expected $expected ($input) but the value is $actual\n"; + echo "For $column ($fieldScale): expected $expected ($input) but the value is $actual\n"; } } return $matched; @@ -58,134 +50,34 @@ function compareNumbers($actual, $input, $column, $fieldScale, $formatDecimal = function testErrorCases($conn) { $query = "SELECT 0.0001"; - - $options = array('FormatDecimals' => 1.5); + $message = 'Expected an integer to specify number of decimals to format the output values of decimal data types.'; + + $options = array('DecimalPlaces' => 1.5); $stmt = sqlsrv_query($conn, $query, array(), $options); if ($stmt) { fatalError("Case 1: expected query to fail!!"); } else { $error = sqlsrv_errors()[0]['message']; - $message = 'Expected an integer to specify number of decimals to format the output values of decimal data types.'; - if (strpos($error, $message) === false) { print_r(sqlsrv_errors()); } } - $options = array('FormatDecimals' => -1); + $options = array('DecimalPlaces' => true); $stmt = sqlsrv_query($conn, $query, array(), $options); if ($stmt) { fatalError("Case 2: expected query to fail!!"); } else { $error = sqlsrv_errors()[0]['message']; - $message = 'For formatting decimal data values, -1 is out of range. Expected an integer from 0 to 38, inclusive.'; - if (strpos($error, $message) === false) { print_r(sqlsrv_errors()); } } } -function testFloatTypes($conn) -{ - // This test with the float types of various number of bits, which are retrieved - // as numbers by default. When fetched as strings, no formatting is done even with - // the statement option FormatDecimals set - $values = array('2.9978', '-0.2982', '33.2434', '329.690734', '110.913498'); - $epsilon = 0.001; - - $query = "SELECT CONVERT(float(1), $values[0]), - CONVERT(float(12), $values[1]), - CONVERT(float(24), $values[2]), - CONVERT(float(36), $values[3]), - CONVERT(float(53), $values[4])"; - - $stmt = sqlsrv_query($conn, $query); - $floats = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); - if (!$floats) { - echo "testFloatTypes: sqlsrv_fetch_array failed\n"; - } - - // Set FormatDecimals to 2, but the number of decimals in each of the results - // will vary -- FormatDecimals has no effect - $numDigits = 2; - $options = array('FormatDecimals' => $numDigits); - $stmt = sqlsrv_query($conn, $query, array(), $options); - if (sqlsrv_fetch($stmt)) { - for ($i = 0; $i < count($values); $i++) { - $floatStr = sqlsrv_get_field($stmt, $i, SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_CHAR)); - $floatVal = floatval($floatStr); - - // Check if the numbers of decimal digits are the same - // It is highly unlikely but not impossible - $numbers = explode('.', $floatStr); - $len = strlen($numbers[1]); - if ($len == $numDigits && $floatVal != $floats[$i]) { - echo "Expected $floats[$i] but returned "; - var_dump($floatVal); - } else { - $diff = abs($floatVal - $floats[$i]) / $floats[$i]; - if ($diff > $epsilon) { - echo "Expected $floats[$i] but returned "; - var_dump($floatVal); - } - } - } - } else { - echo "testFloatTypes: sqlsrv_fetch failed\n"; - } -} - -function testMoneyTypes($conn) -{ - // With money and smallmoney types, which are essentially decimal types - // ODBC driver does not support Always Encrypted feature with money / smallmoney - $values = array('1.9954', '0', '-0.5', '0.2954', '9.6789', '99.991'); - $defaults = array('1.9954', '.0000', '-.5000', '.2954', '9.6789', '99.9910'); - - $query = "SELECT CONVERT(smallmoney, $values[0]), - CONVERT(money, $values[1]), - CONVERT(smallmoney, $values[2]), - CONVERT(money, $values[3]), - CONVERT(smallmoney, $values[4]), - CONVERT(money, $values[5])"; - - $stmt = sqlsrv_query($conn, $query); - $results = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); - for ($i = 0; $i < count($values); $i++) { - if ($defaults[$i] !== $results[$i]) { - echo "testMoneyTypes: Expected default $defaults[$i] but got $results[$i]\n"; - } - } - - // Set FormatDecimals to 0 decimal digits - $numDigits = 0; - $options = array('FormatDecimals' => $numDigits); - $stmt = sqlsrv_query($conn, $query, array(), $options); - $results = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); - for ($i = 0; $i < count($values); $i++) { - $value = number_format($values[$i], $numDigits); - if ($value !== $results[$i]) { - echo "testMoneyTypes: Expected $value but got $results[$i]\n"; - } - } - - // Set FormatDecimals to 2 decimal digits - $numDigits = 2; - $options = array('FormatDecimals' => $numDigits); - $stmt = sqlsrv_query($conn, $query, array(), $options); - $results = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); - for ($i = 0; $i < count($values); $i++) { - $value = number_format($values[$i], $numDigits); - if ($value !== $results[$i]) { - echo "testMoneyTypes: Expected $value but got $results[$i]\n"; - } - } -} - function testNoOption($conn, $tableName, $inputs, $columns, $exec) { - // Without the statement option, should return decimal values as they are + // This should return decimal values as they are $query = "SELECT * FROM $tableName"; if ($exec) { $stmt = sqlsrv_query($conn, $query); @@ -194,27 +86,27 @@ function testNoOption($conn, $tableName, $inputs, $columns, $exec) sqlsrv_execute($stmt); } - // Compare values + // Compare values $results = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); for ($i = 0; $i < count($inputs); $i++) { - compareNumbers($results[$i], $inputs[$i], $columns[$i], $i); + compareNumbers($results[$i], $inputs[$i], $columns[$i], $i, false); } } -function testStmtOption($conn, $tableName, $inputs, $columns, $formatDecimal, $withBuffer) +function testStmtOption($conn, $tableName, $inputs, $columns, $decimalPlaces, $withBuffer) { - // Decimal values should return decimal digits based on the valid statement - // option FormatDecimals + // Decimal values should NOT be affected by the statement + // option DecimalPlaces $query = "SELECT * FROM $tableName"; if ($withBuffer){ - $options = array('Scrollable' => 'buffered', 'FormatDecimals' => $formatDecimal); + $options = array('Scrollable' => 'buffered', 'DecimalPlaces' => $decimalPlaces); } else { - $options = array('FormatDecimals' => $formatDecimal); + $options = array('DecimalPlaces' => $decimalPlaces); } $size = count($inputs); $stmt = sqlsrv_prepare($conn, $query, array(), $options); - + // Fetch by getting one field at a time sqlsrv_execute($stmt); @@ -223,26 +115,28 @@ function testStmtOption($conn, $tableName, $inputs, $columns, $formatDecimal, $w } for ($i = 0; $i < $size; $i++) { $field = sqlsrv_get_field($stmt, $i); // Expect a string - compareNumbers($field, $inputs[$i], $columns[$i], $i, $formatDecimal); + compareNumbers($field, $inputs[$i], $columns[$i], $i, true); } } -function getOutputParam($conn, $storedProcName, $inputValue, $prec, $scale, $inout) +function getOutputParam($conn, $storedProcName, $inputValue, $prec, $scale, $numeric, $inout) { $outString = ''; $numDigits = 2; $dir = SQLSRV_PARAM_OUT; - - // The output param value should be the same as the input value, - // unaffected by the statement attr FormatDecimals, unless - // ColumnEncryption is enabled, in which case the driver is able - // to derive the decimal type. Another workaround is to specify - // the SQLSRV_SQLTYPE_DECIMAL type with the correct precision and scale + + // The output param value should be the same as the input, + // unaffected by the statement attr DecimalPlaces. If + // the correct sql type is specified or ColumnEncryption + // is enabled, in which case the driver is able to derive + // the correct field type, leading zero will be added + // if missing $sqlType = null; if (!AE\isColEncrypted()) { - $sqlType = call_user_func('SQLSRV_SQLTYPE_DECIMAL', $prec, $scale); + $type = ($numeric) ? 'SQLSRV_SQLTYPE_NUMERIC' : 'SQLSRV_SQLTYPE_DECIMAL'; + $sqlType = call_user_func($type, $prec, $scale); } - + // For inout parameters the input type should match the output one if ($inout) { $dir = SQLSRV_PARAM_INOUT; @@ -250,38 +144,37 @@ function getOutputParam($conn, $storedProcName, $inputValue, $prec, $scale, $ino } $outSql = AE\getCallProcSqlPlaceholders($storedProcName, 1); - $stmt = sqlsrv_prepare($conn, $outSql, - array(array(&$outString, $dir, null, $sqlType)), - array('FormatDecimals' => $numDigits)); + $stmt = sqlsrv_prepare($conn, $outSql, + array(array(&$outString, $dir, null, $sqlType)), + array('DecimalPlaces' => $numDigits)); if (!$stmt) { fatalError("getOutputParam: failed when preparing to call $storedProcName"); } if (!sqlsrv_execute($stmt)) { fatalError("getOutputParam: failed to execute procedure $storedProcName"); } - - // The output param should have been formatted based on $numDigits, if less - // than $scale + + // Verify value of output param $column = 'outputParam'; - compareNumbers($outString, $inputValue, $column, $scale, $numDigits); + compareNumbers($outString, $inputValue, $column, $scale, true); sqlsrv_free_stmt($stmt); - + if (!AE\isColEncrypted()) { // With ColumnEncryption enabled, the driver is able to derive the decimal type, // so skip this part of the test $outString2 = $inout ? '0.0' : ''; - $stmt = sqlsrv_prepare($conn, $outSql, - array(array(&$outString2, $dir)), - array('FormatDecimals' => $numDigits)); + $stmt = sqlsrv_prepare($conn, $outSql, + array(array(&$outString2, $dir)), + array('DecimalPlaces' => $numDigits)); if (!$stmt) { fatalError("getOutputParam2: failed when preparing to call $storedProcName"); } if (!sqlsrv_execute($stmt)) { fatalError("getOutputParam2: failed to execute procedure $storedProcName"); } - + $column = 'outputParam2'; - compareNumbers($outString2, $inputValue, $column, $scale); + compareNumbers($outString2, $inputValue, $column, $scale, true); sqlsrv_free_stmt($stmt); } } @@ -296,8 +189,8 @@ function testOutputParam($conn, $tableName, $inputs, $columns, $dataTypes, $inou createProc($conn, $storedProcName, $procArgs, $procCode); // Call stored procedure to retrieve output param - getOutputParam($conn, $storedProcName, $inputs[$i], $p, $i, $inout); - + getOutputParam($conn, $storedProcName, $inputs[$i], $p, $i, $i > 2, $inout); + dropProc($conn, $storedProcName); } } @@ -310,16 +203,10 @@ if (!$conn) { fatalError("Could not connect.\n"); } -// First to test if leading zero is added -testMoneyTypes($conn); - -// Then test error conditions +// Test error conditions testErrorCases($conn); -// Also test using regular floats -testFloatTypes($conn); - -// Create the test table of decimal / numeric data columns +// Create the test table of decimal / numeric data columns $tableName = 'sqlsrvFormatDecimals'; $columns = array('c1', 'c2', 'c3', 'c4', 'c5', 'c6'); @@ -338,13 +225,13 @@ $values = array(); $max2 = 1; for ($s = 0, $p = 3; $s < count($columns); $s++, $p++) { // First get a random number - $n = rand(0, 10); + $n = rand(1, 6); $neg = ($n % 2 == 0) ? -1 : 1; - - // $n1 may or may not be negative - $max1 = 1000; + + // $n1 is a tiny number, which may or may not be negative + $max1 = 5; $n1 = rand(0, $max1) * $neg; - + if ($s > 0) { $max2 *= 10; $n2 = rand(0, $max2); @@ -352,7 +239,7 @@ for ($s = 0, $p = 3; $s < count($columns); $s++, $p++) { } else { $number = sprintf("%d", $n1); } - + array_push($values, $number); } @@ -373,6 +260,14 @@ sqlsrv_free_stmt($stmt); testNoOption($conn, $tableName, $values, $columns, true); testNoOption($conn, $tableName, $values, $columns, false); +sqlsrv_close($conn); + +// Reconnect with FormatDecimals option set to true +$conn = AE\connect(array('FormatDecimals' => true)); +if (!$conn) { + fatalError("Could not connect.\n"); +} + // Now try with setting number decimals to 3 then 2 testStmtOption($conn, $tableName, $values, $columns, 3, false); testStmtOption($conn, $tableName, $values, $columns, 3, true); @@ -384,7 +279,7 @@ testStmtOption($conn, $tableName, $values, $columns, 2, true); testOutputParam($conn, $tableName, $values, $columns, $dataTypes); testOutputParam($conn, $tableName, $values, $columns, $dataTypes, true); -dropTable($conn, $tableName); +dropTable($conn, $tableName); sqlsrv_close($conn); echo "Done\n"; diff --git a/test/functional/sqlsrv/sqlsrv_statement_format_decimals_scales.phpt b/test/functional/sqlsrv/sqlsrv_statement_format_decimals_scales.phpt deleted file mode 100644 index 4abb0398d..000000000 --- a/test/functional/sqlsrv/sqlsrv_statement_format_decimals_scales.phpt +++ /dev/null @@ -1,255 +0,0 @@ ---TEST-- -Test various precisions of formatting decimal data output values (feature request issue 415) ---DESCRIPTION-- -In SQL Server, the maximum allowed precision is 38. The scale can range from 0 up to the -defined precision. Generate a long numeric string and get rid of the last digit to make it a -39-digit-string. Then replace one digit at a time with a dot '.' to make it a decimal -input string for testing with various scales. -For example, -string(39) ".23456789012345678901234567890123456789" -string(39) "1.3456789012345678901234567890123456789" -string(39) "12.456789012345678901234567890123456789" -string(39) "123.56789012345678901234567890123456789" -string(39) "1234.6789012345678901234567890123456789" -string(39) "12345.789012345678901234567890123456789" -... ... -string(39) "1234567890123456789012345678901234.6789" -string(39) "12345678901234567890123456789012345.789" -string(39) "123456789012345678901234567890123456.89" -string(39) "1234567890123456789012345678901234567.9" -string(38) "12345678901234567890123456789012345678" - -Note: PHP number_format() will not be used for verification in this test -because the function starts losing accuracy with large number of precisions / scales. ---ENV-- -PHPT_EXEC=true ---SKIPIF-- - ---FILE-- - $digits)); - - // Restore the $i-th digit with its original digit - $digits[$i] = $d; - } - - $stmt = AE\insertRow($conn, $tableName, $inputData); - if (!$stmt) { - fatalError("Failed to insert data\n"); - } - sqlsrv_free_stmt($stmt); - - return $inputData; -} - -function verifyNoDecimals($value, $input, $round) -{ - global $prec, $dot; - - // Use PHP explode() to separate the input string into an array - $parts = explode($dot, $input); - $len = strlen($parts[0]); - if ($len == 0) { - // The original input string is missing a leading zero - $parts[0] = '0'; - } - - // No need to worry about carry over for the input data of this test - // Check the first digit of $parts[1] - if ($len < $prec) { - // Only need to round up when $len < $prec - $ch = $parts[1][0]; - - // Round the last digit of $parts[0] if $ch is '5' or above - if ($ch >= '5') { - $len = strlen($parts[0]); - $parts[0][$len-1] = $parts[0][$len-1] + 1 + '0'; - } - } - - // No decimal digits left in the expected string - $expected = $parts[0]; - if ($value !== $expected) { - echo "Round $round scale 0: expected $expected but returned $value\n"; - } -} - -function verifyWithDecimals($value, $input, $round, $scale) -{ - global $dot; - - // Use PHP explode() to separate the input string into an array - $parts = explode($dot, $input); - if (strlen($parts[0]) == 0) { - // The original input string is missing a leading zero - $parts[0] = '0'; - } - - // No need to worry about carry over for the input data of this test - // Check the digit at the position $scale of $parts[1] - $len = strlen($parts[1]); - if ($scale < $len) { - // Only need to round up when $scale < $len - $ch = $parts[1][$scale]; - - // Round the previous digit if $ch is '5' or above - if ($ch >= '5') { - $parts[1][$scale-1] = $parts[1][$scale-1] + 1 + '0'; - } - } - - // Use substr() to get up to $scale - $parts[1] = substr($parts[1], 0, $scale); - - // Join the array elements together - $expected = implode($dot, $parts); - if ($value !== $expected) { - echo "Round $round scale $scale: expected $expected but returned $value\n"; - } -} - -/**** -The function testVariousScales() will fetch one column at a time, using scale from -0 up to the maximum scale allowed for that column type. - -For example, for column of type decimal(38,4), the input string is -1234567890123456789012345678901234.6789 - -When fetching data, using scale from 0 to 4, the following values are expected to return: -1234567890123456789012345678901235 -1234567890123456789012345678901234.7 -1234567890123456789012345678901234.68 -1234567890123456789012345678901234.679 -1234567890123456789012345678901234.6789 - -For example, for column of type decimal(38,6), the input string is -12345678901234567890123456789012.456789 - -When fetching data, using scale from 0 to 6, the following values are expected to return: -12345678901234567890123456789012 -12345678901234567890123456789012.5 -12345678901234567890123456789012.46 -12345678901234567890123456789012.457 -12345678901234567890123456789012.4568 -12345678901234567890123456789012.45679 -12345678901234567890123456789012.456789 - -etc. -****/ -function testVariousScales($conn, $tableName, $inputData) -{ - global $prec; - $max = $prec + 1; - - for ($i = 0; $i < $max; $i++) { - $scale = $prec - $i; - $column = "col_$scale"; - - $query = "SELECT $column as col1 FROM $tableName"; - $input = $inputData[$column]; - - // Default case: the fetched value should be the same as the corresponding input - $stmt = sqlsrv_query($conn, $query); - if (!$stmt) { - fatalError("In testVariousScales: failed in default case\n"); - } - if ($obj = sqlsrv_fetch_object($stmt)) { - trace("\n$obj->col1\n"); - if ($obj->col1 !== $input) { - echo "default case: expected $input but returned $obj->col1\n"; - } - } else { - fatalError("In testVariousScales: sqlsrv_fetch_object failed\n"); - } - - // Next, format how many decimal digits to be displayed - $query = "SELECT $column FROM $tableName"; - for ($j = 0; $j <= $scale; $j++) { - $options = array('FormatDecimals' => $j); - $stmt = sqlsrv_query($conn, $query, array(), $options); - - if (sqlsrv_fetch($stmt)) { - $value = sqlsrv_get_field($stmt, 0); - trace("$value\n"); - - if ($j == 0) { - verifyNoDecimals($value, $input, $i); - } else { - verifyWithDecimals($value, $input, $i, $j); - } - } else { - fatalError("Round $i scale $j: sqlsrv_fetch failed\n"); - } - } - } -} - -set_time_limit(0); -sqlsrv_configure('WarningsReturnAsErrors', 1); - -$conn = AE\connect(); -if (!$conn) { - fatalError("Could not connect.\n"); -} - -$tableName = createTestTable($conn); -$inputData = insertTestData($conn, $tableName); -testVariousScales($conn, $tableName, $inputData); - -dropTable($conn, $tableName); - -sqlsrv_close($conn); - -echo "Done\n"; -?> ---EXPECT-- -Done \ No newline at end of file diff --git a/test/functional/sqlsrv/sqlsrv_statement_format_money_types.phpt b/test/functional/sqlsrv/sqlsrv_statement_format_money_types.phpt new file mode 100644 index 000000000..ae1befa4c --- /dev/null +++ b/test/functional/sqlsrv/sqlsrv_statement_format_money_types.phpt @@ -0,0 +1,261 @@ +--TEST-- +Test the options for formatting money data (feature request issue 415) +--DESCRIPTION-- +Test how money data in the fetched values can be formatted by using the connection +option FormatDecimals and DecimalPlaces, the latter works only with integer +values. No effect on other operations like insertion or update. + +The option DecimalPlaces only affects money/smallmoney fields. If its value is out of range, for example, it's negative or larger than the original scale, then its value will be ignored. + +The underlying data will not be altered, but formatted results may likely be rounded up (e.g. .2954 will be displayed as 0.30 if the user wants only two decimals). For this reason, it is not recommended to use formatted money values as inputs to any calculation. + +The corresponding statement options always override the inherited values from the connection object. Setting FormatDecimals to false will automatically turn off any formatting of decimal data in the result set, ignoring DecimalPlaces value. + +By only setting FormatDecimals to true will add the leading zeroes, if missing. For output params, missing zeroes will be added if either SQLSRV_SQLTYPE_MONEY or SQLSRV_SQLTYPE_SMALLMONEY is set as the SQLSRV SQL Type. +--ENV-- +PHPT_EXEC=true +--SKIPIF-- + +--FILE-- + $epsilon) { + echo "$diff: Expected $floats[$i] but returned "; + var_dump($floatVal); + } + } + } + } else { + echo "testFloatTypes: sqlsrv_fetch failed\n"; + } +} + +function verifyMoneyValues($conn, $numDigits, $query, $values, $override) +{ + if ($override) { + $options = array('DecimalPlaces' => $numDigits); + $stmt = sqlsrv_query($conn, $query, array(), $options); + } else { + $stmt = sqlsrv_query($conn, $query); + } + + $results = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); + trace("\nverifyMoneyValues:\n"); + for ($i = 0; $i < count($values); $i++) { + $value = numberFormat($values[$i], $numDigits); + trace("$results[$i], $value\n"); + + if ($value !== $results[$i]) { + echo "verifyMoneyValues ($override, $numDigits): Expected $value but got $results[$i]\n"; + } + } +} + +function verifyMoneyFormatting($conn, $query, $values, $format) +{ + if ($format) { + // Set FormatDecimals to true to turn on formatting, but setting + // DecimalPlaces to a negative number, which will be ignored. + $nDigits = -1; + $options = array('FormatDecimals' => true, 'DecimalPlaces' => $nDigits); + $stmt = sqlsrv_query($conn, $query, array(), $options); + } else { + // Set FormatDecimals to false to turn off formatting. + // This should override the inherited connection + // options, and by default, money and smallmoney types + // have scale of 4 digits + $options = array('FormatDecimals' => false); + $stmt = sqlsrv_query($conn, $query, array(), $options); + } + $results = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); + + for ($i = 0; $i < count($values); $i++) { + $default = numberFormat($values[$i], 4); + if (!$format) { + // No formatting - should drop the leading zero, if exists + if (abs($values[$i]) < 1) { + $default = str_replace('0.', '.', $default); + } + } + if ($default !== $results[$i]) { + echo "verifyMoneyFormatting ($format): Expected default $default but got $results[$i]\n"; + } + } +} + +function getOutputParam($conn, $spProcName, $input, $money, $inout) +{ + $outString = '0.0'; + $dir = ($inout) ? SQLSRV_PARAM_INOUT : SQLSRV_PARAM_OUT; + $sqlType = ($money) ? SQLSRV_SQLTYPE_MONEY : SQLSRV_SQLTYPE_SMALLMONEY; + + $outSql = AE\getCallProcSqlPlaceholders($spProcName, 1); + $stmt = sqlsrv_prepare($conn, $outSql, + array(array(&$outString, $dir, null, $sqlType))); + if (!$stmt) { + fatalError("getOutputParam: failed when preparing to call $spProcName"); + } + if (!sqlsrv_execute($stmt)) { + fatalError("getOutputParam: failed to execute procedure $spProcName"); + } + + // FormatDecimals only add leading zeroes, but do + // not support controlling decimal places, so + // use scale 4 for money/smallmoney types + $expected = numberFormat($input, 4); + trace("getOutputParam result is $outString and expected $expected\n"); + + if ($outString !== $expected) { + echo "getOutputParam ($inout): Expected $expected but got $outString\n"; + var_dump($expected); + var_dump($outString); + } +} + +function testOutputParam($conn) +{ + // Create a table for testing output param + $tableName = 'sqlsrvMoneyFormats'; + $values = array(0.12345, 0.34567); + $query = "SELECT CONVERT(smallmoney, $values[0]) AS m1, + CONVERT(money, $values[1]) AS m2 + INTO $tableName"; + + $stmt = sqlsrv_query($conn, $query); + for ($i = 0; $i < 2; $i++) { + // Create the stored procedure first + $storedProcName = "spMoneyFormats" . $i; + $dataType = ($i == 0) ? 'smallmoney' : 'money'; + $procArgs = "@col $dataType OUTPUT"; + $column = 'm' . ($i + 1); + $procCode = "SELECT @col = $column FROM $tableName"; + createProc($conn, $storedProcName, $procArgs, $procCode); + + getOutputParam($conn, $storedProcName, $values[$i], $i, false); + getOutputParam($conn, $storedProcName, $values[$i], $i, true); + + dropProc($conn, $storedProcName); + } + + dropTable($conn, $tableName); +} + +function testMoneyTypes($conn) +{ + global $numDigits; // inherited from connection option + + // With money and smallmoney types, which are essentially decimal types + // As of today, ODBC driver does not support Always Encrypted feature with money / smallmoney + $values = array(); + $nColumns = 6; + for ($i = 0; $i < $nColumns; $i++) { + // First get a random number + $n = rand(0, 10); + $neg = ($n % 2 == 0) ? -1 : 1; + + // $n1 may or may not be negative + $max = 10; + $n1 = rand(0, $max) * $neg; + $n2 = rand(1, $max * 1000); + + $number = sprintf("%d.%d", $n1, $n2); + array_push($values, $number); + } + + $query = "SELECT CONVERT(smallmoney, $values[0]), + CONVERT(money, $values[1]), + CONVERT(smallmoney, $values[2]), + CONVERT(money, $values[3]), + CONVERT(smallmoney, $values[4]), + CONVERT(money, $values[5])"; + + // Do not override the connection attributes + verifyMoneyValues($conn, $numDigits, $query, $values, false); + // Next, override statement attribute to set number of + // decimal places to 0 + verifyMoneyValues($conn, 0, $query, $values, true); + + // Set Formatting attribute to true then false + verifyMoneyFormatting($conn, $query, $values, true); + verifyMoneyFormatting($conn, $query, $values, false); +} + +set_time_limit(0); +sqlsrv_configure('WarningsReturnAsErrors', 1); + +$numDigits = 2; + +$conn = AE\connect(array('FormatDecimals' => true, 'DecimalPlaces' => $numDigits)); +if (!$conn) { + fatalError("Could not connect.\n"); +} +/* +// First to test if leading zero is added +testMoneyTypes($conn); + +// Also test using regular floats +testFloatTypes($conn); +*/ +// Test output params +testOutputParam($conn); + +sqlsrv_close($conn); + +echo "Done\n"; +?> +--EXPECT-- +Done From 8779520f574c20e4c457592440bee6887f1fd544 Mon Sep 17 00:00:00 2001 From: Jenny Tam Date: Fri, 23 Nov 2018 14:14:50 -0800 Subject: [PATCH 08/10] Adding new tests for various decimal places --- .../pdostatement_format_money_scales.phpt | 229 ++++++++++++++++++ .../sqlsrv_statement_format_money_scales.phpt | 167 +++++++++++++ 2 files changed, 396 insertions(+) create mode 100644 test/functional/pdo_sqlsrv/pdostatement_format_money_scales.phpt create mode 100644 test/functional/sqlsrv/sqlsrv_statement_format_money_scales.phpt diff --git a/test/functional/pdo_sqlsrv/pdostatement_format_money_scales.phpt b/test/functional/pdo_sqlsrv/pdostatement_format_money_scales.phpt new file mode 100644 index 000000000..9bd2e8e98 --- /dev/null +++ b/test/functional/pdo_sqlsrv/pdostatement_format_money_scales.phpt @@ -0,0 +1,229 @@ +--TEST-- +Test various decimal places of money values (feature request issue 415) +--DESCRIPTION-- +In SQL Server, the maximum precision of money type is 19 with scale 4. Generate a long numeric string and get rid of the last digit to make it a 15-digit-string. Then replace one digit at a time with a dot '.' to make it a decimal input string for testing. + +For example, +string(15) ".23456789098765" +string(15) "1.3456789098765" +string(15) "12.456789098765" +string(15) "123.56789098765" +string(15) "1234.6789098765" +... +string(15) "1234567890987.5" +string(15) "12345678909876." + +The inserted money data will be +0.2346 +1.3457 +12.4568 +123.5679 +1234.6789 +... +1234567890987.5000 +12345678909876.0000 + +--ENV-- +PHPT_EXEC=true +--SKIPIF-- + +--FILE-- + $digits)); + + // Restore the $i-th digit with its original digit + $digits[$i] = $d; + } + + $stmt = insertRow($conn, $tableName, $inputData); + unset($stmt); +} +/* +function verifyNoDecimals($value, $input, $round) +{ + global $prec, $dot; + + // Use PHP explode() to separate the input string into an array + $parts = explode($dot, $input); + $len = strlen($parts[0]); + if ($len == 0) { + // The original input string is missing a leading zero + $parts[0] = '0'; + } + + // No need to worry about carry over for the input data of this test + // Check the first digit of $parts[1] + if ($len < $prec) { + // Only need to round up when $len < $prec + $ch = $parts[1][0]; + + // Round the last digit of $parts[0] if $ch is '5' or above + if ($ch >= '5') { + $len = strlen($parts[0]); + $parts[0][$len-1] = $parts[0][$len-1] + 1 + '0'; + } + } + + // No decimal digits left in the expected string + $expected = $parts[0]; + if ($value !== $expected) { + echo "Round $round scale 0: expected $expected but returned $value\n"; + } +} + +function verifyWithDecimals($value, $input, $round, $scale) +{ + global $dot; + + // Use PHP explode() to separate the input string into an array + $parts = explode($dot, $input); + if (strlen($parts[0]) == 0) { + // The original input string is missing a leading zero + $parts[0] = '0'; + } + + // No need to worry about carry over for the input data of this test + // Check the digit at the position $scale of $parts[1] + $len = strlen($parts[1]); + if ($scale < $len) { + // Only need to round up when $scale < $len + $ch = $parts[1][$scale]; + + // Round the previous digit if $ch is '5' or above + if ($ch >= '5') { + $parts[1][$scale-1] = $parts[1][$scale-1] + 1 + '0'; + } + } + + // Use substr() to get up to $scale + $parts[1] = substr($parts[1], 0, $scale); + + // Join the array elements together + $expected = implode($dot, $parts); + if ($value !== $expected) { + echo "Round $round scale $scale: expected $expected but returned $value\n"; + } +} +*/ + +function numberFormat($value, $numDecimals) +{ + return number_format($value, $numDecimals, '.', ''); +} + +/**** +The function testVariousScales() will fetch one column at a time, using scale from 0 up to 4 allowed for that column type. + +For example, if the input string is +1234567890.2345 + +When fetching data, using scale from 0 to 4, the following values are expected to return: +1234567890 +1234567890.2 +1234567890.23 +1234567890.235 +1234567890.2345 +****/ +function testVariousScales($conn, $tableName) +{ + global $prec, $scale; + $max = $prec - $scale; + + for ($i = 0; $i < $max; $i++) { + $column = "col_$i"; + + $query = "SELECT $column as col1 FROM $tableName"; + + // Default case: no formatting + $stmt = $conn->query($query); + if ($obj = $stmt->fetchObject()) { + trace("\n$obj->col1\n"); + $input = $obj->col1; + } else { + echo "In testVariousScales: fetchObject failed\n"; + } + + // Next, format how many decimals to be displayed + $query = "SELECT $column FROM $tableName"; + for ($j = 0; $j <= $scale; $j++) { + $options = array(PDO::SQLSRV_ATTR_FORMAT_DECIMALS => true, PDO::SQLSRV_ATTR_DECIMAL_PLACES => $j); + $stmt = $conn->prepare($query, $options); + $stmt->execute(); + + $stmt->bindColumn($column, $value); + if ($stmt->fetch(PDO::FETCH_BOUND)) { + trace("$value\n"); + + $expected = numberFormat($input, $j); + if ($value !== $expected) { + echo "testVariousScales ($j): Expected $expected but got $value\n"; + } + } else { + echo "Round $i scale $j: fetch failed\n"; + } + } + } +} + +try { + // This helper method sets PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION + // Default is no formatting, but set it to false anyway + $conn = connect(); + $conn->setAttribute(PDO::SQLSRV_ATTR_FORMAT_DECIMALS, false); + + $tableName = createTestTable($conn); + insertTestData($conn, $tableName); + testVariousScales($conn, $tableName); + + dropTable($conn, $tableName); + + echo "Done\n"; + + unset($conn); +} catch (PdoException $e) { + echo $e->getMessage() . PHP_EOL; +} +?> +--EXPECT-- +Done diff --git a/test/functional/sqlsrv/sqlsrv_statement_format_money_scales.phpt b/test/functional/sqlsrv/sqlsrv_statement_format_money_scales.phpt new file mode 100644 index 000000000..b27a3c480 --- /dev/null +++ b/test/functional/sqlsrv/sqlsrv_statement_format_money_scales.phpt @@ -0,0 +1,167 @@ +--TEST-- +Test various decimal places of money values (feature request issue 415) +--DESCRIPTION-- +In SQL Server, the maximum precision of money type is 19 with scale 4. Generate a long numeric string and get rid of the last digit to make it a 15-digit-string. Then replace one digit at a time with a dot '.' to make it a decimal input string for testing. + +For example, +string(15) ".23456789098765" +string(15) "1.3456789098765" +string(15) "12.456789098765" +string(15) "123.56789098765" +string(15) "1234.6789098765" +... +string(15) "1234567890987.5" +string(15) "12345678909876." + +The inserted money data will be +0.2346 +1.3457 +12.4568 +123.5679 +1234.6789 +... +1234567890987.5000 +12345678909876.0000 + +--ENV-- +PHPT_EXEC=true +--SKIPIF-- + +--FILE-- + $digits)); + trace($digits); + + // Restore the $i-th digit with its original digit + $digits[$i] = $d; + } + + $stmt = AE\insertRow($conn, $tableName, $inputData); + if (!$stmt) { + fatalError("Failed to insert data\n"); + } + sqlsrv_free_stmt($stmt); +} + +function numberFormat($value, $numDecimals) +{ + return number_format($value, $numDecimals, '.', ''); +} + +/**** +The function testVariousScales() will fetch one column at a time, using scale from 0 up to 4 allowed for that column type. + +For example, if the input string is +1234567890.2345 + +When fetching data, using scale from 0 to 4, the following values are expected to return: +1234567890 +1234567890.2 +1234567890.23 +1234567890.235 +1234567890.2345 +****/ +function testVariousScales($conn, $tableName) +{ + global $prec, $scale; + $max = $prec - $scale; + + for ($i = 0; $i < $max; $i++) { + $column = "col_$i"; + + $query = "SELECT $column as col1 FROM $tableName"; + // Default case: no formatting + $stmt = sqlsrv_query($conn, $query); + if (!$stmt) { + fatalError("In testVariousScales: failed in default case\n"); + } + if ($obj = sqlsrv_fetch_object($stmt)) { + trace("\n$obj->col1\n"); + $input = $obj->col1; + } else { + fatalError("In testVariousScales: sqlsrv_fetch_object failed\n"); + } + + // Next, format how many decimals to be displayed + $query = "SELECT $column FROM $tableName"; + for ($j = 0; $j <= $scale; $j++) { + $options = array('FormatDecimals' => true,'DecimalPlaces' => $j); + $stmt = sqlsrv_query($conn, $query, array(), $options); + + if (sqlsrv_fetch($stmt)) { + $value = sqlsrv_get_field($stmt, 0); + trace("$value\n"); + + $expected = numberFormat($input, $j); + if ($value !== $expected) { + echo "testVariousScales ($j): Expected $expected but got $value\n"; + } + } else { + fatalError("Round $i scale $j: sqlsrv_fetch failed\n"); + } + } + } +} + +set_time_limit(0); +sqlsrv_configure('WarningsReturnAsErrors', 1); + +// Default is no formatting, but set it to false anyway +$conn = AE\connect(array('FormatDecimals' => false)); +if (!$conn) { + fatalError("Could not connect.\n"); +} + +$tableName = createTestTable($conn); +insertTestData($conn, $tableName); +testVariousScales($conn, $tableName); + +dropTable($conn, $tableName); + +sqlsrv_close($conn); + +echo "Done\n"; +?> +--EXPECT-- +Done \ No newline at end of file From f7904696f1d8daf73564b97b721d54458f3d5418 Mon Sep 17 00:00:00 2001 From: Jenny Tam Date: Fri, 23 Nov 2018 14:33:49 -0800 Subject: [PATCH 09/10] Minor fixes to the tests --- .../pdostatement_format_money_scales.phpt | 67 ------------------- .../pdostatement_format_money_types.phpt | 1 - .../sqlsrv_statement_format_money_types.phpt | 4 +- 3 files changed, 2 insertions(+), 70 deletions(-) diff --git a/test/functional/pdo_sqlsrv/pdostatement_format_money_scales.phpt b/test/functional/pdo_sqlsrv/pdostatement_format_money_scales.phpt index 9bd2e8e98..f7618fe0d 100644 --- a/test/functional/pdo_sqlsrv/pdostatement_format_money_scales.phpt +++ b/test/functional/pdo_sqlsrv/pdostatement_format_money_scales.phpt @@ -79,73 +79,6 @@ function insertTestData($conn, $tableName) $stmt = insertRow($conn, $tableName, $inputData); unset($stmt); } -/* -function verifyNoDecimals($value, $input, $round) -{ - global $prec, $dot; - - // Use PHP explode() to separate the input string into an array - $parts = explode($dot, $input); - $len = strlen($parts[0]); - if ($len == 0) { - // The original input string is missing a leading zero - $parts[0] = '0'; - } - - // No need to worry about carry over for the input data of this test - // Check the first digit of $parts[1] - if ($len < $prec) { - // Only need to round up when $len < $prec - $ch = $parts[1][0]; - - // Round the last digit of $parts[0] if $ch is '5' or above - if ($ch >= '5') { - $len = strlen($parts[0]); - $parts[0][$len-1] = $parts[0][$len-1] + 1 + '0'; - } - } - - // No decimal digits left in the expected string - $expected = $parts[0]; - if ($value !== $expected) { - echo "Round $round scale 0: expected $expected but returned $value\n"; - } -} - -function verifyWithDecimals($value, $input, $round, $scale) -{ - global $dot; - - // Use PHP explode() to separate the input string into an array - $parts = explode($dot, $input); - if (strlen($parts[0]) == 0) { - // The original input string is missing a leading zero - $parts[0] = '0'; - } - - // No need to worry about carry over for the input data of this test - // Check the digit at the position $scale of $parts[1] - $len = strlen($parts[1]); - if ($scale < $len) { - // Only need to round up when $scale < $len - $ch = $parts[1][$scale]; - - // Round the previous digit if $ch is '5' or above - if ($ch >= '5') { - $parts[1][$scale-1] = $parts[1][$scale-1] + 1 + '0'; - } - } - - // Use substr() to get up to $scale - $parts[1] = substr($parts[1], 0, $scale); - - // Join the array elements together - $expected = implode($dot, $parts); - if ($value !== $expected) { - echo "Round $round scale $scale: expected $expected but returned $value\n"; - } -} -*/ function numberFormat($value, $numDecimals) { diff --git a/test/functional/pdo_sqlsrv/pdostatement_format_money_types.phpt b/test/functional/pdo_sqlsrv/pdostatement_format_money_types.phpt index 5152e1f59..c02d634ab 100644 --- a/test/functional/pdo_sqlsrv/pdostatement_format_money_types.phpt +++ b/test/functional/pdo_sqlsrv/pdostatement_format_money_types.phpt @@ -140,7 +140,6 @@ function testMoneyTypes($conn, $numDigits) { // With money and smallmoney types, which are essentially decimal types // As of today, ODBC driver does not support Always Encrypted feature with money / smallmoney - $values = array(); $nColumns = 6; for ($i = 0; $i < $nColumns; $i++) { diff --git a/test/functional/sqlsrv/sqlsrv_statement_format_money_types.phpt b/test/functional/sqlsrv/sqlsrv_statement_format_money_types.phpt index ae1befa4c..ac2c1cd01 100644 --- a/test/functional/sqlsrv/sqlsrv_statement_format_money_types.phpt +++ b/test/functional/sqlsrv/sqlsrv_statement_format_money_types.phpt @@ -243,13 +243,13 @@ $conn = AE\connect(array('FormatDecimals' => true, 'DecimalPlaces' => $numDigits if (!$conn) { fatalError("Could not connect.\n"); } -/* + // First to test if leading zero is added testMoneyTypes($conn); // Also test using regular floats testFloatTypes($conn); -*/ + // Test output params testOutputParam($conn); From 7b8a3096435f68445b9bd3fcc368584159341a15 Mon Sep 17 00:00:00 2001 From: Jenny Tam Date: Tue, 27 Nov 2018 16:50:16 -0800 Subject: [PATCH 10/10] Applied review comments --- source/shared/core_stmt.cpp | 1 - test/functional/sqlsrv/sqlsrv_statement_format_decimals.phpt | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/source/shared/core_stmt.cpp b/source/shared/core_stmt.cpp index 8a4cc227d..1a4fb7a21 100644 --- a/source/shared/core_stmt.cpp +++ b/source/shared/core_stmt.cpp @@ -2351,7 +2351,6 @@ void finalize_output_parameters( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) core::sqlsrv_zval_stringl(value_z, str, str_len); } else { - //SQLSMALLINT decimal_digits = output_param->getDecimalDigits(); param_meta_data metaData = output_param->getMetaData(); if (output_param->encoding != SQLSRV_ENCODING_CHAR) { diff --git a/test/functional/sqlsrv/sqlsrv_statement_format_decimals.phpt b/test/functional/sqlsrv/sqlsrv_statement_format_decimals.phpt index 3db5d1784..a2faf7cf4 100644 --- a/test/functional/sqlsrv/sqlsrv_statement_format_decimals.phpt +++ b/test/functional/sqlsrv/sqlsrv_statement_format_decimals.phpt @@ -12,7 +12,7 @@ Setting FormatDecimals to false will turn off all formatting, regardless of Deci 2. Set FormatDecimals to true to add the leading zeroes to money and decimal types, if missing. 3. For output params, leading zeroes will be added for any decimal fields if FormatDecimals is true, but only if either SQLSRV_SQLTYPE_DECIMAL or SQLSRV_SQLTYPE_NUMERIC is set correctly to match the original column type and its precision / scale. -FormatDecimals and DecimalPlaces will only format the fetched results and have no effect on other operatioins like insertion or update. +FormatDecimals and DecimalPlaces will only format the fetched results and have no effect on other operations like insertion or update. --ENV-- PHPT_EXEC=true --SKIPIF--