From 9654020d67aeae672e3d4c71496f6ae8d1f0fe2c Mon Sep 17 00:00:00 2001 From: Jenny Tam Date: Fri, 20 Jul 2018 17:24:48 -0700 Subject: [PATCH 1/5] 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 | 91 +++++----- ...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 | 51 +++--- .../sqlsrv/TC84_LargeColumnName_unicode.phpt | 53 +++--- ...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 | 170 ++++++++++-------- .../sqlsrv/sqlsrv_connect_encrypted.phpt | 2 +- .../functional/sqlsrv/test_ae_keys_setup.phpt | 39 ++-- 97 files changed, 763 insertions(+), 814 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 765bb786..abaa24db 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 b52d9d43..13fab611 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 6964ca0e..d84eca65 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 b30a3fa0..20e3c0e9 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 9d2cdeea..4a0fcbdd 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 46e22960..b1bfd6e4 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 bd1eaf04..7066e625 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 48ed3b12..33020556 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 0fa961c6..65e7a078 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 8c783b39..baafeed7 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 fd65b9ea..d41dde3b 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 343537dd..a05e7547 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 ba7dd4b7..38e4cec4 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 248c99cc..8b94ddfa 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 6a19a425..1b48c0e9 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 61080a42..87f15f46 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 550c0d35..d5183fc5 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 a0b31b78..b12e789b 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 7f2d16eb..b094e110 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 d4708006..cda38fa5 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 d5882f2c..62a757d8 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 39e53b19..5530a554 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 2cdb7a00..6d4d4f61 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 5309f004..32780a5b 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 c537f766..d8b7b244 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 486a381d..88e8d1a4 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 39e615f4..cc0163f0 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 7f5a974a..e8c8e5bb 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 6c88f0e5..bf2bc9ca 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 136c5a51..2ec13e09 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 92221e98..75251eb6 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 d6b74a5b..3a759252 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 7be9ba68..78478eaa 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 6daf7fcd..dc3b4ca5 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 140e2448..7d655443 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 f768f112..baa393e2 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 68595afb..1baa473a 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 29296069..44eb7c84 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 3b1cbc68..36aceae1 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 e03ab0f4..6b419066 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 77d8c4d1..449789c4 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 183ac3c5..7bf80508 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 7385dc6b..bb8ab04b 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 17175730..6c5e7b01 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 96aeae8a..ac334cb9 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 446f50d8..ffee8537 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 50b963e4..bc26658c 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 cddfdab9..b1c479e9 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 dd183c32..cf2ff605 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 e07c46a7..823f283c 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 b5019290..be6234f2 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); + startTest($testName); + + // The maximum size of a column name is 128 characters + $maxlen = 128; + $columnName = str_repeat('A', $maxlen); - $columnName = "a"; - - try - { - for ($a = 1; $a <= 128; $a++) - { - LargeColumnNameTest($columnName, $a > 128); - $columnName .= "A"; - } - } - catch (Exception $e) - { - echo $e->getMessage(); + try { + largeColumnNameTest($columnName); + } catch (Exception $e) { + echo "Possible regression: Unable to retrieve inserted value\n"; + print_r($e->getMessage()); + echo "\n"; } + + // 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); + 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 634dc527..9ad27164 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"; + } + + // 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"; } } - catch (Exception $e) - { - echo $e->getMessage(); - } - 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 f0989962..9498a358 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 05bf24a7..c68a46b1 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 93b6e2fd..c8424856 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 883da029..8f2d8e8f 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 463b7ac4..88f47495 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 6b59c134..67c0f4fd 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 8b3b0a0e..124df22b 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 1d7b066e..b012eed9 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 4389b3a9..279a7eb4 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 f51d3ba6..a5c31e09 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."); + } -if ($version[3] < '2014') { - die("skip Wrong version of SQL Server, 2014 or later required"); + $version = explode(' ', $ver_string); + + 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 e2f9456b..72553974 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."); + } -if ($version[3] < '2016') { - die("skip Wrong version of SQL Server, 2016 or later required"); + $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/test_ae_keys_setup.phpt b/test/functional/pdo_sqlsrv/test_ae_keys_setup.phpt index ed42f74c..e8f46546 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 13900e2e..def2d0f5 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 1ec7ceef..aec2b4bb 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 648c23fd..3779e444 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 94a6bbe8..a22868f9 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 bebcfadc..b7cc3d57 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 48bdc11c..7a0aca36 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, "SELECT * from [$tableName]"); - - if (null == $stmt) { - echo "$"; - echo "stmt = null"; - echo "\n"; + $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]"); + 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 dc7a1eb2..00000000 --- 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 59ee6c27..2d47f6fe 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 0211b47c..7dd50fb5 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 3d713c2e..c42a4e44 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 06a8d28f..1abfdd30 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 00000000..9746db71 --- /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 4dc4921e..26d960ca 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."); + } -if ($version[3] < '2014') { - die("skip Wrong version of SQL Server, 2014 or later required"); + $version = explode(' ', $ver_string); + + 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 692523d6..ce06258a 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."); + } -if ($version[3] < '2016') { - die("skip Wrong version of SQL Server, 2016 or later required"); + $version = explode(' ', $ver_string); + + 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 57aafff6..bd00ac68 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 5a39140e..e6a5bbb6 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 2/5] 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 | 171 ++++++++----- 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 | 145 ++++++++--- 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, 2166 insertions(+), 545 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 abaa24db..ecb2ee3f 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 d84eca65..970bc3d0 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 20e3c0e9..071d582f 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 4378ad1f..e9ac02dc 100644 --- a/buildscripts/builddrivers.py +++ b/buildscripts/builddrivers.py @@ -239,7 +239,7 @@ if __name__ == '__main__': 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 @@ if __name__ == '__main__': 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 306aafaa..79b36923 100644 --- a/buildscripts/buildtools.py +++ b/buildscripts/buildtools.py @@ -193,7 +193,7 @@ class BuildUtil(object): 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 @@ class BuildUtil(object): 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 b1bfd6e4..3de4fefc 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 7066e625..cd6e3a06 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 33020556..b424866e 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 65e7a078..a5fcbdd0 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 baafeed7..e6a70d4d 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 d41dde3b..3f6bc328 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 ); + switch (sqlsrv_php_type) { + + case SQLSRV_PHPTYPE_INT: + case SQLSRV_PHPTYPE_FLOAT: + { + if (*in_val == NULL) { + ZVAL_NULL(&out_zval); + } + else { + + if (sqlsrv_php_type == SQLSRV_PHPTYPE_INT) { + ZVAL_LONG(&out_zval, **(reinterpret_cast(in_val))); } else { - - if( sqlsrv_php_type == SQLSRV_PHPTYPE_INT ) { - ZVAL_LONG( &out_zval, **( reinterpret_cast( in_val ))); - } - else { - ZVAL_DOUBLE( &out_zval, **( reinterpret_cast( in_val ))); - } + ZVAL_DOUBLE(&out_zval, **(reinterpret_cast(in_val))); } - - if( *in_val ) { - sqlsrv_free( *in_val ); - } - - 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_STRINGL( &out_zval, reinterpret_cast( *in_val ), field_len ); - sqlsrv_free( *in_val ); - } - break; + if (*in_val) { + sqlsrv_free(*in_val); } - - case SQLSRV_PHPTYPE_DATETIME: - DIE( "Unsupported php type" ); - out_zval = *( reinterpret_cast( *in_val )); - break; - case SQLSRV_PHPTYPE_NULL: - ZVAL_NULL( &out_zval ); - break; + break; + } + case SQLSRV_PHPTYPE_STRING: + case SQLSRV_PHPTYPE_STREAM: // TODO: this will be moved when output streaming is implemented + { + if (*in_val == NULL) { - default: - DIE( "Unknown php type" ); - break; + ZVAL_NULL(&out_zval); + } + else { + + ZVAL_STRINGL(&out_zval, reinterpret_cast(*in_val), field_len); + sqlsrv_free(*in_val); + } + break; + } + case SQLSRV_PHPTYPE_DATETIME: + if (*in_val == NULL) { + + ZVAL_NULL(&out_zval); + } + else { + + 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 a05e7547..dee2e3e0 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 38e4cec4..c110a9c6 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 8b94ddfa..435fa9a3 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 1b48c0e9..a5033db4 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 87f15f46..f7933f97 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 d5183fc5..354ebbf6 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 b12e789b..475cd84c 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 b094e110..da6284dc 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; - // Add the server name - common_conn_str_append_func( ODBCConnOptions::SERVER, server, strnlen_s( server ), connection_string TSRMLS_CC ); + // 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; + } - // 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 cda38fa5..274c10d2 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 62a757d8..67a80555 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 5530a554..6c49464c 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 @@ public: // 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 @@ public: // 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 @@ public: // 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 6d4d4f61..46d60907 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 32780a5b..e4e9e485 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 d8b7b244..ca097a24 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 88e8d1a4..98619d61 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 @@ public: { // 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 cc0163f0..b8c04643 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 e8c8e5bb..6977ff22 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 bf2bc9ca..6aa43fb0 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 2ec13e09..79bd860e 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 75251eb6..669462ab 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 3a759252..f4912b11 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 78478eaa..8d5b785c 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 dc3b4ca5..574dc51a 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 7d655443..0ad9dcd1 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 baa393e2..8e113a5c 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 1baa473a..03706dd3 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 44eb7c84..a5bdf641 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 36aceae1..27426310 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 6b419066..c0e4d3af 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 449789c4..b6c2b1b1 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 7bf80508..dcfc755e 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 bb8ab04b..45dfb0e5 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 6c5e7b01..1816942a 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 ac334cb9..3bbd4af6 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 ffee8537..d70a93a9 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 bc26658c..aab5e2eb 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 00000000..dbb2f778 --- /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 00000000..f468ffd6 --- /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 00000000..9cc1bc3b --- /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 00000000..ab8ba5ec --- /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 00000000..9bffdf75 --- /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 00000000..d59c02bf --- /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 10849b9b..39d92e39 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 72553974..37656773 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 00000000..dbb2f778 --- /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 00000000..3c7c447c --- /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 74d041ff..e8c53f2d 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 ce06258a..303a2030 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 ba48e9f6..d4ea1c94 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 00000000..96c82d63 --- /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 064357da..fe70816a 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 00000000..7c8a16ef --- /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 00000000..01cc16f2 --- /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 00000000..4e3add8a --- /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 edd97998..55731ef1 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 ffd138c9..a288a1d4 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 3/5] Change readme links to https --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 071d582f..23baf6e8 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 4/5] Update survey image link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 23baf6e8..93c19e3d 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 b65e28ccb6de41cdc4bcda297c3a60f9360c3c91 Mon Sep 17 00:00:00 2001 From: Jenny Tam Date: Fri, 7 Dec 2018 15:03:48 -0800 Subject: [PATCH 5/5] 5.5.0-preview (#903) --- CHANGELOG.md | 155 +++-- Dockerfile-msphpsql | 6 +- Linux-mac-install.md | 71 +- README.md | 8 +- appveyor.yml | 2 +- sample/pdo_sqlsrv_sample.php | 123 ++-- sample/sqlsrv_sample.php | 120 ++-- source/pdo_sqlsrv/config.m4 | 2 +- source/pdo_sqlsrv/config.w32 | 11 +- source/pdo_sqlsrv/pdo_dbh.cpp | 55 +- source/pdo_sqlsrv/pdo_init.cpp | 4 +- source/pdo_sqlsrv/pdo_parser.cpp | 2 +- source/pdo_sqlsrv/pdo_stmt.cpp | 31 +- source/pdo_sqlsrv/pdo_util.cpp | 6 +- source/pdo_sqlsrv/php_pdo_sqlsrv.h | 14 +- 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 | 41 +- source/shared/core_init.cpp | 2 +- source/shared/core_results.cpp | 2 +- source/shared/core_sqlsrv.h | 131 ++-- source/shared/core_stmt.cpp | 627 ++++++++++++------ source/shared/core_stream.cpp | 2 +- source/shared/core_util.cpp | 39 +- 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 | 10 +- source/shared/localizationimpl.cpp | 582 +++++++++++++++- source/shared/msodbcsql.h | 2 +- source/shared/sal_def.h | 2 +- source/shared/typedefs_for_linux.h | 2 +- source/shared/version.h | 4 +- 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 | 13 +- source/sqlsrv/conn.cpp | 77 ++- source/sqlsrv/init.cpp | 2 +- source/sqlsrv/php_sqlsrv.h | 6 +- source/sqlsrv/stmt.cpp | 129 ++-- source/sqlsrv/template.rc | 2 +- source/sqlsrv/util.cpp | 6 +- .../pdo_sqlsrv/MsData_PDO_AllTypes.inc | 2 +- .../pdo_sqlsrv/PDO81_MemoryCheck.phpt | 2 +- test/functional/pdo_sqlsrv/issue_52_pdo.phpt | 2 +- .../pdo_ae_azure_key_vault_keywords.phpt | 3 +- .../pdo_sqlsrv/pdostatement_GetDataType.phpt | Bin 5677 -> 5692 bytes .../pdostatement_bindParam_empty_binary.phpt | 92 +++ .../pdo_sqlsrv/pdostatement_fetchAll.phpt | Bin 17989 -> 18019 bytes .../pdo_sqlsrv/pdostatement_fetchObject.phpt | Bin 3978 -> 3993 bytes .../pdostatement_format_decimals.phpt | 268 ++++++++ .../pdostatement_format_money_scales.phpt | 162 +++++ .../pdostatement_format_money_types.phpt | 244 +++++++ .../pdo_sqlsrv/pdostatement_nextRowset.phpt | Bin 10727 -> 10757 bytes test/functional/pdo_sqlsrv/skipif_not_akv.inc | 4 + test/functional/sqlsrv/MsCommon.inc | 12 + test/functional/sqlsrv/TC81_MemoryCheck.phpt | 3 +- test/functional/sqlsrv/issue_52.phpt | 2 +- test/functional/sqlsrv/skipif_not_akv.inc | 3 + .../sqlsrv_ae_azure_key_vault_keywords.phpt | 3 +- .../sqlsrv_azure_ad_authentication.phpt | 2 +- .../sqlsrv/sqlsrv_param_empty_binary.phpt | 105 +++ .../sqlsrv_statement_format_decimals.phpt | 288 ++++++++ .../sqlsrv_statement_format_money_scales.phpt | 167 +++++ .../sqlsrv_statement_format_money_types.phpt | 261 ++++++++ test/functional/sqlsrv/test_largeData.phpt | 6 + 73 files changed, 3354 insertions(+), 598 deletions(-) create mode 100644 test/functional/pdo_sqlsrv/pdostatement_bindParam_empty_binary.phpt create mode 100644 test/functional/pdo_sqlsrv/pdostatement_format_decimals.phpt create mode 100644 test/functional/pdo_sqlsrv/pdostatement_format_money_scales.phpt create mode 100644 test/functional/pdo_sqlsrv/pdostatement_format_money_types.phpt create mode 100644 test/functional/sqlsrv/sqlsrv_param_empty_binary.phpt create mode 100644 test/functional/sqlsrv/sqlsrv_statement_format_decimals.phpt create mode 100644 test/functional/sqlsrv/sqlsrv_statement_format_money_scales.phpt create mode 100644 test/functional/sqlsrv/sqlsrv_statement_format_money_types.phpt diff --git a/CHANGELOG.md b/CHANGELOG.md index ecb2ee3f..83a46a7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,40 @@ # Change Log All notable changes to this project will be documented in this file. -The format is based on [Keep a Changelog](http://keepachangelog.com/) +The format is based on [Keep a Changelog](http://keepachangelog.com/) + +## 5.5.0-preview - 2018-12-07 +Updated PECL release packages. Here is the list of updates: + +### Added +- Added support for PHP 7.3.0 +- Added support for Linux Ubuntu 18.10 and mac OS Mojave +- Feature Request [#415](https://github.com/Microsoft/msphpsql/pull/886) - new options at connection and statement levels for both drivers for formatting decimal values in the fetched results + +### Fixed +- Pull Request [#854](https://github.com/Microsoft/msphpsql/pull/854) - Clear Azure Key Vault data after connection attributes are successfully set or when exception is thrown +- Pull Request [#855](https://github.com/Microsoft/msphpsql/pull/855) - Improved performance by saving meta data before fetching and skipping unnecessary conversions for numeric data +- Pull Request [#865](https://github.com/Microsoft/msphpsql/pull/865) - Corrected the way SQLPutData and SQLParamData are used when sending stream data to the server +- Pull Request [#878](https://github.com/Microsoft/msphpsql/pull/878) - Modified the config files to enable Spectre Mitigations for PHP 7.1 (see related Request [#836](https://github.com/Microsoft/msphpsql/pull/836)) +- Pull Request [#891](https://github.com/Microsoft/msphpsql/pull/891) - Improved performance of Unicode conversions +- Pull Request [#892](https://github.com/Microsoft/msphpsql/pull/892) - Removed warning messages while compiling extensions + +### Limitations +- No support for inout / output params when using sql_variant type +- No support for inout / output params when formatting decimal values +- 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.4.0-preview - 2018-09-24 Updated PECL release packages. Here is the list of updates: @@ -53,7 +86,7 @@ Updated PECL release packages. Here is the list of updates: - 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 [#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 @@ -77,7 +110,7 @@ Updated PECL release packages. Here is the list of updates: Updated PECL release packages. Here is the list of updates: ### Added -- Added support for Azure Key Vault for Always Encrypted for basic CRUD functionalities such that Always Encrypted feature is also available to Linux or macOS users +- Added support for Azure Key Vault for Always Encrypted for basic CRUD functionalities such that Always Encrypted feature is also available to Linux or macOS users - Added support for macOS High Sierra (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)) ### Fixed @@ -86,7 +119,7 @@ Updated PECL release packages. Here is the list of updates: - Issue [#699](https://github.com/Microsoft/msphpsql/issues/699) - Binding output parameter failed when the query in the stored procedure returned no data. The test case has been added to the test lab. - Issue [#705](https://github.com/Microsoft/msphpsql/issues/705) - AE - Retrieving a negative decimal value (edge case) as output parameter causes truncation - Issue [#706](https://github.com/Microsoft/msphpsql/issues/706) - AE - Cannot insert double with precision and scale (38, 38) -- Issue [#707](https://github.com/Microsoft/msphpsql/issues/707) - AE - Fetching decimals / numerics as output parameters bound to PDO::PARAM_BOOL or PDO::PARAM_INT returns floats, not integers +- Issue [#707](https://github.com/Microsoft/msphpsql/issues/707) - AE - 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 such 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 problem for output params with SQL types specified as SQLSRV_SQLTYPE_DECIMAL or SQLSRV_SQLTYPE_NUMERIC @@ -227,7 +260,7 @@ Updated PECL release packages. Here is the list of updates: - PDO::quote with string containing ASCII NUL character (Issue [#538]( https://github.com/Microsoft/msphpsql/issues/538)) - Appropriate error message is returned when calling nextRowset() or sqlsrv_next_result() on an empty result set (issue [#507 ](https://github.com/Microsoft/msphpsql/issues/507)) - Decimal types with no decimals are correctly handled when AE is enabled (PR [#544](https://github.com/Microsoft/msphpsql/pull/544)) -- Search for installed ODBC drivers in Linux/macOS first before attempting to connect using the default ODBC driver +- Search for installed ODBC drivers in Linux/macOS first before attempting to connect using the default ODBC driver - BIGINT as an output param no longer results in value out of range exception when the returned value is larger than a maximum integer ([PR #567](https://github.com/Microsoft/msphpsql/pull/567)) ### Limitations @@ -282,7 +315,7 @@ Updated PECL release packages. Here is the list of updates: ### Changed - Implementation of PDO::lastInsertId($name) to return the last inserted sequence number if the sequence name is supplied to the function ([lastInsertId](https://github.com/Microsoft/msphpsql/wiki/Features#lastinsertid)) - + ### Removed - No longer support Ubuntu 15 - Supplying tablename into PDO::lastInsertId($name) no longer return the last inserted row ([lastInsertId](https://github.com/Microsoft/msphpsql/wiki/Features#lastinsertid)) @@ -299,45 +332,45 @@ Updated PECL release packages. Here is the list of updates: Production Ready release for SQLSRV and PDO_SQLSRV drivers on Sierra, El Capitan, Debian 8, Ubuntu 15, Ubuntu 16, CentOS 7, and Windows. Here is the changlog since the last Production Ready release. ### Added -- Added Unicode Column name support ([issue #138](https://github.com/Microsoft/msphpsql/issues/138)). -- Support for Always On Availability groups via Transparent Network IP Resolution ([TNIR](https://github.com/Microsoft/msphpsql/wiki/Features#TNIR)) +- Added Unicode Column name support ([issue #138](https://github.com/Microsoft/msphpsql/issues/138)). +- Support for Always On Availability groups via Transparent Network IP Resolution ([TNIR](https://github.com/Microsoft/msphpsql/wiki/Features#TNIR)) - Added support for sql_variant data type with limitation ([issue #51](https://github.com/Microsoft/msphpsql/issues/51) and [issue #127](https://github.com/Microsoft/msphpsql/issues/127)) -- Support drivers on Debian Jessie (tested on Debian 8.7) -- Connection Resiliency support in Windows -- Connection pooling support for Linux and macOS -- Support for Mac (El Capitan and above) +- Support drivers on Debian Jessie (tested on Debian 8.7) +- Connection Resiliency support in Windows +- Connection pooling support for Linux and macOS +- Support for Mac (El Capitan and above) - Azure Active Directory Authentication with ActiveDirectoryPassword and SqlPassword ### Fixed -- Fixed PECL installation errors when PHP was installed from source ([issue #213](https://github.com/Microsoft/msphpsql/issues/213)). -- Fixed the assertion error (Linux) when fetching data from a binary column using the binary encoding ([issue #226](https://github.com/Microsoft/msphpsql/issues/226)). -- Fixed issue output parameters bound to empty string ([issue #182](https://github.com/Microsoft/msphpsql/issues/182)). -- Fixed a memory leak in closing connection resources. -- Fixed load ordering issue in MacOS ([issue #417](https://github.com/Microsoft/msphpsql/issues/417)) -- Added a workaround for a bug in unixODBC 2.3.4 when connection pooling is enabled. -- Fixed the issue with driver loading order in macOS +- Fixed PECL installation errors when PHP was installed from source ([issue #213](https://github.com/Microsoft/msphpsql/issues/213)). +- Fixed the assertion error (Linux) when fetching data from a binary column using the binary encoding ([issue #226](https://github.com/Microsoft/msphpsql/issues/226)). +- Fixed issue output parameters bound to empty string ([issue #182](https://github.com/Microsoft/msphpsql/issues/182)). +- Fixed a memory leak in closing connection resources. +- Fixed load ordering issue in MacOS ([issue #417](https://github.com/Microsoft/msphpsql/issues/417)) +- Added a workaround for a bug in unixODBC 2.3.4 when connection pooling is enabled. +- Fixed the issue with driver loading order in macOS - Fixed null returned when an empty string is set to an output parameter ([issue #308](https://github.com/Microsoft/msphpsql/issues/308)). -- #### Fixed in SQLSRV - - Fixed sqlsrv client buffer size to only allow positive integers ([issue #228](https://github.com/Microsoft/msphpsql/issues/228)). - - Fixed sqlsrv_num_rows() when the client buffered result is null ([issue #330](https://github.com/Microsoft/msphpsql/issues/330)). - - Fixed issues with sqlsrv_has_rows() to prevent it from moving statement cursor ([issue #37](https://github.com/Microsoft/msphpsql/issues/37)). - - Fixed conversion warnings because of some const chars ([issue #332](https://github.com/Microsoft/msphpsql/issues/332)). - - Fixed debug abort error when building the driver in debug mode with PHP 7.1. - - Fixed string truncation when binding varchar(max), nvarchar(max), varbinary(max), and xml types ([issue #231](https://github.com/Microsoft/msphpsql/issues/231)). - - Fixed fatal error when fetching empty nvarchar ([issue #69](https://github.com/Microsoft/msphpsql/issues/69)). +- #### Fixed in SQLSRV + - Fixed sqlsrv client buffer size to only allow positive integers ([issue #228](https://github.com/Microsoft/msphpsql/issues/228)). + - Fixed sqlsrv_num_rows() when the client buffered result is null ([issue #330](https://github.com/Microsoft/msphpsql/issues/330)). + - Fixed issues with sqlsrv_has_rows() to prevent it from moving statement cursor ([issue #37](https://github.com/Microsoft/msphpsql/issues/37)). + - Fixed conversion warnings because of some const chars ([issue #332](https://github.com/Microsoft/msphpsql/issues/332)). + - Fixed debug abort error when building the driver in debug mode with PHP 7.1. + - Fixed string truncation when binding varchar(max), nvarchar(max), varbinary(max), and xml types ([issue #231](https://github.com/Microsoft/msphpsql/issues/231)). + - Fixed fatal error when fetching empty nvarchar ([issue #69](https://github.com/Microsoft/msphpsql/issues/69)). - Fixed fatal error when calling sqlsrv_fetch() with an out of bound offset for SQLSRV_SCROLL_ABSOLUTE ([issue #223](https://github.com/Microsoft/msphpsql/issues/223)). - #### Fixed in PDO_SQLSRV - - Fixed issue with SQLSRV_ATTR_FETCHES_NUMERIC_TYPE when column return type is set on statement ([issue #173](https://github.com/Microsoft/msphpsql/issues/173)). - - Improved performance by implementing a cache to store column SQL types and display sizes ([issue #189](https://github.com/Microsoft/msphpsql/issues/189)). - - Fixed segmentation fault with PDOStatement::getColumnMeta() when the supplied column index is out of range ([issue #224](https://github.com/Microsoft/msphpsql/issues/224)). - - Fixed issue with the unsupported attribute PDO::ATTR_PERSISTENT in connection ([issue #65](https://github.com/Microsoft/msphpsql/issues/65)). - - Fixed the issue with executing DELETE operation on a non-existent value ([issue #336](https://github.com/Microsoft/msphpsql/issues/336)). - - Fixed incorrectly binding of unicode parameter when emulate prepare is on and the encoding is set at the statement level ([issue #92](https://github.com/Microsoft/msphpsql/issues/92)). - - Fixed binary column binding when emulate prepare is on ([issue #140](https://github.com/Microsoft/msphpsql/issues/140)). - - Fixed wrong value returned when fetching varbinary value on Linux ([issue #270](https://github.com/Microsoft/msphpsql/issues/270)). - - Fixed binary data not returned when the column is bound by name ([issue #35](https://github.com/Microsoft/msphpsql/issues/35)). + - Fixed issue with SQLSRV_ATTR_FETCHES_NUMERIC_TYPE when column return type is set on statement ([issue #173](https://github.com/Microsoft/msphpsql/issues/173)). + - Improved performance by implementing a cache to store column SQL types and display sizes ([issue #189](https://github.com/Microsoft/msphpsql/issues/189)). + - Fixed segmentation fault with PDOStatement::getColumnMeta() when the supplied column index is out of range ([issue #224](https://github.com/Microsoft/msphpsql/issues/224)). + - Fixed issue with the unsupported attribute PDO::ATTR_PERSISTENT in connection ([issue #65](https://github.com/Microsoft/msphpsql/issues/65)). + - Fixed the issue with executing DELETE operation on a non-existent value ([issue #336](https://github.com/Microsoft/msphpsql/issues/336)). + - Fixed incorrectly binding of unicode parameter when emulate prepare is on and the encoding is set at the statement level ([issue #92](https://github.com/Microsoft/msphpsql/issues/92)). + - Fixed binary column binding when emulate prepare is on ([issue #140](https://github.com/Microsoft/msphpsql/issues/140)). + - Fixed wrong value returned when fetching varbinary value on Linux ([issue #270](https://github.com/Microsoft/msphpsql/issues/270)). + - Fixed binary data not returned when the column is bound by name ([issue #35](https://github.com/Microsoft/msphpsql/issues/35)). - Fixed exception thrown on closeCursor() when the statement has not been executed ([issue #267](https://github.com/Microsoft/msphpsql/issues/267)). - + ### Limitation - No support for inout / output params when using sql_variant type @@ -363,7 +396,7 @@ Here is the list of updates: - When pooling is enabled in Linux or MAC - unixODBC <= 2.3.4 (Linux and MAC) might not return proper diagnostics 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/Connection-Pooling-on-Linux-and-Mac) - + ## Windows/Linux/MAC 4.2.0-preview - 2017-05-19 Here is the list of updates: @@ -386,7 +419,7 @@ Here is the list of updates: - 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/Connection-Pooling-on-Linux-and-Mac) ## Windows/Linux/MAC 4.1.9-preview - 2017-05-08 -- Updated documentation for Readme regarding instructions for Linux and MAC +- Updated documentation for Readme regarding instructions for Linux and MAC - Updated PECL release packages. Here is the list of updates: ### Added - Azure Active Directory Authentication with ActiveDirectoryPassword and SqlPassword @@ -405,11 +438,11 @@ Here is the list of updates: - 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/Connection-Pooling-on-Linux-and-Mac) ## Windows/Linux/MAC 4.1.8-preview - 2017-04-10 -Updated documentation for Readme regarding instructions for Linux and MAC +Updated documentation for Readme regarding instructions for Linux and MAC Updated PECL release packages. Here is the list of updates: ### Added -- [Connection Resiliency](https://github.com/Microsoft/msphpsql/wiki/Connection-Resiliency) now supported in Windows -- [Connection pooling](https://github.com/Microsoft/msphpsql/wiki/Connection-Pooling-on-Linux-and-Mac) now works in MAC +- [Connection Resiliency](https://github.com/Microsoft/msphpsql/wiki/Connection-Resiliency) now supported in Windows +- [Connection pooling](https://github.com/Microsoft/msphpsql/wiki/Connection-Pooling-on-Linux-and-Mac) now works in MAC ### Fixed #### SQLSRV and PDO_SQLSRV @@ -485,27 +518,27 @@ Updated Windows drivers (4.1.5) compiled with PHP 7.0.14 and 7.1 are available. ###Fixed - Fixed issue output parameters bound to empty string ([issue #182](https://github.com/Microsoft/msphpsql/issues/182)). -- Fixed issue with SQLSRV_ATTR_FETCHES_NUMERIC_TYPE when column return type is set on statement ([issue #173](https://github.com/Microsoft/msphpsql/issues/173)). +- Fixed issue with SQLSRV_ATTR_FETCHES_NUMERIC_TYPE when column return type is set on statement ([issue #173](https://github.com/Microsoft/msphpsql/issues/173)). ### Changed - Code structure is updated to facilitate the development; shared codes between both drivers are moved to "shared" folder to avoid code duplication issues in development. To build the driver from source: - - if you are building the driver from source using PHP source, copy the "shared" folder as a subfolder to both the sqlsrv and pdo_sqlsrv folders. + - if you are building the driver from source using PHP source, copy the "shared" folder as a subfolder to both the sqlsrv and pdo_sqlsrv folders. ## Linux 4.0.8 - 2016-12-19 Production release of Linux drivers is available for Ubuntu 15.04, Ubuntu 16.04, and RedHat 7.2. Here is the list of updates: ### Added - Added `SQLSRV_ATTR_FETCHES_NUMERIC_TYPE` attribute support in PDO_SQLSRV driver.`SQLSRV_ATTR_FETCHES_NUMERIC_TYPE` connection attribute flag handles numeric fetches from columns with numeric Sql types (only bit, integer, smallint, tinyint, float and real). This flag can be turned on by setting its value in `PDO::setAttribute` to `true`, For example, - `$conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE,true);` - If `SQLSRV_ATTR_FETCHES_NUMERIC_TYPE` is set to `true` the results from an integer column will be represented as an `int`, likewise, Sql types float and real will be represented as `float`. + `$conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE,true);` + If `SQLSRV_ATTR_FETCHES_NUMERIC_TYPE` is set to `true` the results from an integer column will be represented as an `int`, likewise, Sql types float and real will be represented as `float`. Note for exceptions: - When connection option flag `ATTR_STRINGIFY_FETCHES` is on, even when `SQLSRV_ATTR_FETCHES_NUMERIC_TYPE` is on, the return value will still be string. - When the returned PDO type in bind column is `PDO_PARAM_INT`, the return value from a integer column will be int even if `SQLSRV_ATTR_FETCHES_NUMERIC_TYPE` is off. - Added Unicode Column name support([issue #138](https://github.com/Microsoft/msphpsql/issues/138)). ###Fixed -- Fixed issue with SQLSRV_ATTR_FETCHES_NUMERIC_TYPE when column return type is set on statement ([issue #173](https://github.com/Microsoft/msphpsql/issues/173)). +- Fixed issue with SQLSRV_ATTR_FETCHES_NUMERIC_TYPE when column return type is set on statement ([issue #173](https://github.com/Microsoft/msphpsql/issues/173)). - Fixed precision issues when double data type returned as strings using buffered queries in PDO_SQLSRV driver. - Fixed issue with buffered cursor in PDO_SQLSRV driver when CharacterSet is UTF-8 ([issue #192](https://github.com/Microsoft/msphpsql/issues/192)). - Fixed segmentation fault in error cases when error message is returned with emulate prepare attribute is set to true in PDO_SQLSRV driver. @@ -514,7 +547,7 @@ Production release of Linux drivers is available for Ubuntu 15.04, Ubuntu 16.04, ## Linux 4.0.7 - 2016-11-23 -Linux drivers compiled with PHP 7.0.13 are available for Ubuntu 15.04, Ubuntu 16.04, and RedHat 7.2. +Linux drivers compiled with PHP 7.0.13 are available for Ubuntu 15.04, Ubuntu 16.04, and RedHat 7.2. ### Added - Ported buffered cursor to Linux. @@ -522,7 +555,7 @@ Linux drivers compiled with PHP 7.0.13 are available for Ubuntu 15.04, Ubuntu 16 ### Changed - Code structure is updated to facilitate the development; shared codes between both drivers are moved to "shared" folder to avoid code duplication issues in development. To build the driver from source, use "packagize" script as follows: - if you are using the phpize, clone or download the “sourceâ€, run the script within the “source†directory and then run phpize. - - if you are building the driver from source using PHP source, give the path to the PHP source to the script. + - if you are building the driver from source using PHP source, give the path to the PHP source to the script. ### Fixed - Fixed string truncation error when inserting long strings. @@ -532,7 +565,7 @@ Linux drivers compiled with PHP 7.0.13 are available for Ubuntu 15.04, Ubuntu 16 - Fixed issues with binding input text, ntext, and image parameters. ## Linux 4.0.6 - 2016-10-25 -Linux drivers compiled with PHP 7.0.12 are available for Ubuntu 15.04, Ubuntu 16.04, and RedHat 7.2. +Linux drivers compiled with PHP 7.0.12 are available for Ubuntu 15.04, Ubuntu 16.04, and RedHat 7.2. ### Changed - Drivers versioning has been redesigned as Major#.Minor#.Release#.Build#. Build number is specific to binaries and it doesn't match with the number on the source. @@ -540,7 +573,7 @@ Linux drivers compiled with PHP 7.0.12 are available for Ubuntu 15.04, Ubuntu 16 ### Fixed - Fixed the issue with duplicate warning messages in PDO_SQLSRV drivers when error mode is set to PDO::ERRMODE_WARNING. - - Fixed the issue with invalid UTF-8 strings, those are detected before executing any queries and proper error message is returned. + - Fixed the issue with invalid UTF-8 strings, those are detected before executing any queries and proper error message is returned. - Fixed segmentation fault in sqlsrv_fetch_object and sqlsrv_fetch_array function. ## Windows 4.1.4 - 2016-10-25 @@ -551,9 +584,9 @@ Windows drivers compiled with PHP 7.0.12 and 7.1 are available. Here is the lis ### Fixed - Fixed the issue with duplicate warning messages in PDO_SQLSRV drivers when error mode is set to PDO::ERRMODE_WARNING. - + ## Linux 4.0.5 - 2016-10-04 -Linux drivers compiled with PHP 7.0.11 are available for Ubuntu 15.04, Ubuntu 16.04, and RedHat 7.2. +Linux drivers compiled with PHP 7.0.11 are available for Ubuntu 15.04, Ubuntu 16.04, and RedHat 7.2. ### Fixed - Fixed segmentation fault when calling PDOStatement::getColumnMeta on RedHat 7.2. @@ -567,7 +600,7 @@ Updated Windows drivers (4.1.3) compiled with PHP 7.0.11 and 7.1.0RC3 are avail - Fixed [issue #139](https://github.com/Microsoft/msphpsql/issues/139) : sqlsrv_fetch_object calls custom class constructor in static context and outputs an error. ##Linux 4.0.4 - 2016-09-09 -Linux drivers compiled with PHP 7.0.10 are available for Ubuntu 15.04, Ubuntu 16.04, and RedHat 7.2. +Linux drivers compiled with PHP 7.0.10 are available for Ubuntu 15.04, Ubuntu 16.04, and RedHat 7.2. ### Added - Added Support for EMULATE_PREPARE feature. @@ -613,10 +646,10 @@ Updated Windows drivers (4.1.2) compiled with PHP 7.0.10 are available. Here is ### Fixed - Fixed [issue #119](https://github.com/Microsoft/msphpsql/issues/119) (modifying class name in sqlsrv_fetch_object). - - + + ## Linux 4.0.3 - 2016-08-23 -Linux drivers compiled with PHP 7.0.9 are available for Ubuntu 15.04, Ubuntu 16.04, and RedHat 7.2. +Linux drivers compiled with PHP 7.0.9 are available for Ubuntu 15.04, Ubuntu 16.04, and RedHat 7.2. ### Fixed - Fixed data corruption in binding integer parameters. @@ -646,17 +679,17 @@ Updated Windows drivers(4.1.1) compiled with PHP 7.0.9 are available and include ### Fixed - `SQLSRV_ATTR_FETCHES_NUMERIC_TYPE` connection attribute flag is added to PDO_SQLSRV driver to handle numeric fetches from columns with numeric Sql types (only bit, integer, smallint, tinyint, float and real). This flag can be turned on by setting its value in `PDO::setAttribute` to `true`, For example, - `$conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE,true);` - If `SQLSRV_ATTR_FETCHES_NUMERIC_TYPE` is set to `true` the results from an integer column will be represented as an `int`, likewise, Sql types float and real will be represented as `float`. + `$conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE,true);` + If `SQLSRV_ATTR_FETCHES_NUMERIC_TYPE` is set to `true` the results from an integer column will be represented as an `int`, likewise, Sql types float and real will be represented as `float`. Note for exceptions: - When connection option flag `ATTR_STRINGIFY_FETCHES` is on, even when `SQLSRV_ATTR_FETCHES_NUMERIC_TYPE` is on, the return value will still be string. - When the returned PDO type in bind column is `PDO_PARAM_INT`, the return value from a integer column will be int even if `SQLSRV_ATTR_FETCHES_NUMERIC_TYPE` is off. - - Fixed float truncation when using buffered query. + - Fixed float truncation when using buffered query. - Fixed handling of Unicode strings and binary when emulate prepare is on in `PDOStatement::bindParam`. To bind a unicode string, `PDO::SQLSRV_ENCODING_UTF8` should be set using `$driverOption`, and to bind a string to column of Sql type binary, `PDO::SQLSRV_ENCODING_BINARY` should be set. - Fixed string truncation in bind output parameters when the size is not set and the length of initialized variable is less than the output. - Fixed bind string parameters as bidirectional parameters (`PDO::PARAM_INPUT_OUTPUT `) in PDO_SQLSRV driver. Note for output or bidirectional parameters, `PDOStatement::closeCursor` should be called to get the output value. - + ## Linux 4.0.1 - 2016-07-09 ### Added diff --git a/Dockerfile-msphpsql b/Dockerfile-msphpsql index 43435eb3..ab289479 100644 --- a/Dockerfile-msphpsql +++ b/Dockerfile-msphpsql @@ -44,8 +44,10 @@ RUN curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list > /etc/apt RUN export DEBIAN_FRONTEND=noninteractive && apt-get update && ACCEPT_EULA=Y apt-get install -y msodbcsql17 mssql-tools ENV PATH="/opt/mssql-tools/bin:${PATH}" -#install coveralls -RUN python -m pip install --upgrade pip && pip install cpp-coveralls +#install coveralls (upgrade both pip and requests first) +RUN python -m pip install --upgrade pip +RUN python -m pip install --upgrade requests +RUN python -m pip install cpp-coveralls #Either Install git / download zip (One can see other strategies : https://ryanfb.github.io/etc/2015/07/29/git_strategies_for_docker.html ) #One option is to get source from zip file of repository. diff --git a/Linux-mac-install.md b/Linux-mac-install.md index 970bc3d0..c83bec3f 100644 --- a/Linux-mac-install.md +++ b/Linux-mac-install.md @@ -1,24 +1,20 @@ # 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). +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 SQL Server on Ubuntu 16.04, 18.04, and 18.10, RedHat 7, Debian 8 and 9, Suse 12, and macOS 10.11, 10.12, 10.13, and 10.14. These instructions advise installing the drivers using PECL, but you can also download the prebuilt binaries from the [Microsoft Drivers for PHP for 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 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.md##loading-the-driver-at-php-startup). 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 18.04](#installing-the-drivers-on-ubuntu-1604-and-1804) +- [Installing the drivers on Ubuntu 16.04, 18.04, and 18.10](#installing-the-drivers-on-ubuntu-1604-1804-and-1810) - [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 macOS El Capitan, Sierra, High Sierra, and Mojave](#installing-the-drivers-on-macos-el-capitan-sierra-high-sierra-and-mojave) -## Installing the drivers on Ubuntu 16.04 and 18.04 +## Installing the drivers on Ubuntu 16.04, 18.04, and 18.10 > [!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. +> To install PHP 7.0, 7.1, or 7.3, replace `7.2` with `7.0`, `7.1`, or `7.3` in the following commands. ### Step 1. Install PHP ``` @@ -28,9 +24,14 @@ apt-get update apt-get install php7.2 php7.2-dev php7.2-xml -y --allow-unauthenticated ``` ### Step 2. Install prerequisites -Install the ODBC driver for Ubuntu by following the instructions on the [Linux and macOS installation page](https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server). +Install the ODBC driver for Ubuntu by following the instructions on the [Linux and macOS installation page](https://docs.microsoft.com/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server). + +For Ubuntu 18.10, follow the above steps for Ubuntu 18.04 except replace `18.04` by `18.10` and download ODBC 17.3 preview [here](https://www.microsoft.com/download/details.aspx?id=57341). ### Step 3. Install the PHP drivers for Microsoft SQL Server + +> [!NOTE] +> If using PHP 7.3, replace `sqlsrv` and `pdo_sqlsrv` in the following commands with `sqlsrv-5.4.0preview` and `pdo_sqlsrv-5.4.0preview` or later, as earlier versions are not compatible with PHP 7.3. ``` sudo pecl install sqlsrv sudo pecl install pdo_sqlsrv @@ -59,22 +60,23 @@ To test your installation, see [Testing your installation](#testing-your-install ## Installing the drivers on Red Hat 7 > [!NOTE] -> To install PHP 7.0 or 7.1, replace remi-php72 with remi-php70 or remi-php71 respectively in the following commands. +> To install PHP 7.0, 7.1, or 7.3, replace `remi-php72` with `remi-php70`, `remi-php71`, or `remi-php73` respectively in the following commands. ### Step 1. Install PHP ``` sudo su wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm -wget http://rpms.remirepo.net/enterprise/remi-release-7.rpm +wget https://rpms.remirepo.net/enterprise/remi-release-7.rpm rpm -Uvh remi-release-7.rpm epel-release-latest-7.noarch.rpm subscription-manager repos --enable=rhel-7-server-optional-rpms +yum install yum-utils yum-config-manager --enable remi-php72 yum update yum install php php-pdo php-xml php-pear php-devel re2c gcc-c++ gcc ``` ### Step 2. Install prerequisites -Install the ODBC driver for Red Hat 7 by following the instructions on the [Linux and macOS installation page](https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server). +Install the ODBC driver for Red Hat 7 by following the instructions on the [Linux and macOS installation page](https://docs.microsoft.com/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server). Compiling the PHP drivers with PECL with PHP 7.2 requires a more recent GCC than the default: ``` @@ -83,6 +85,9 @@ sudo yum install devtoolset-7 scl enable devtoolset-7 bash ``` ### Step 3. Install the PHP drivers for Microsoft SQL Server + +> [!NOTE] +> If using PHP 7.3, replace `sqlsrv` and `pdo_sqlsrv` in the following commands with `sqlsrv-5.4.0preview` and `pdo_sqlsrv-5.4.0preview` or later, as earlier versions are not compatible with PHP 7.3. ``` sudo pecl install sqlsrv sudo pecl install pdo_sqlsrv @@ -103,7 +108,7 @@ sudo make install ``` You can alternatively download the prebuilt binaries from the [Github project page](https://github.com/Microsoft/msphpsql/releases), or install from the Remi repo: ``` -sudo yum install php-sqlsrv php-pdo_sqlsrv +sudo yum install php-sqlsrv ``` ### Step 4. Install Apache ``` @@ -122,7 +127,7 @@ To test your installation, see [Testing your installation](#testing-your-install ## Installing the drivers on Debian 8 and 9 > [!NOTE] -> To install PHP 7.0 or 7.1, replace 7.2 in the following commands with 7.0 or 7.1. +> To install PHP 7.0, 7.1, or 7.3, replace `7.2` with `7.0`, `7.1`, or `7.3` in the following commands. ### Step 1. Install PHP ``` @@ -134,7 +139,7 @@ apt-get update apt-get install -y php7.2 php7.2-dev php7.2-xml ``` ### Step 2. Install prerequisites -Install the ODBC driver for Debian by following the instructions on the [Linux and macOS installation page](https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server). +Install the ODBC driver for Debian by following the instructions on the [Linux and macOS installation page](https://docs.microsoft.com/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server). You may also need to generate the correct locale to get PHP output to display correctly in a browser. For example, for the en_US UTF-8 locale, run the following commands: ``` @@ -144,6 +149,9 @@ locale-gen ``` ### Step 3. Install the PHP drivers for Microsoft SQL Server + +> [!NOTE] +> If using PHP 7.3, replace `sqlsrv` and `pdo_sqlsrv` in the following commands with `sqlsrv-5.4.0preview` and `pdo_sqlsrv-5.4.0preview` or later, as earlier versions are not compatible with PHP 7.3. ``` sudo pecl install sqlsrv sudo pecl install pdo_sqlsrv @@ -171,21 +179,24 @@ To test your installation, see [Testing your installation](#testing-your-install ## Installing the drivers on Suse 12 > [!NOTE] -> To install PHP 7.0, skip the command below adding the repository - 7.0 is the default PHP on suse 12. -> To install PHP 7.1, replace the repository URL below with the following URL: - `http://download.opensuse.org/repositories/devel:/languages:/php:/php71/SLE_12/devel:languages:php:php71.repo` +> To install PHP 7.0 or 7.1, replace the repository URL below with one of the following URLs: +`https://download.opensuse.org/repositories/devel:languages:php:php70/SLE_12_SP3/devel:languages:php:php70.repo` +`https://download.opensuse.org/repositories/devel:languages:php:php71/SLE_12_SP3/devel:languages:php:php71.repo` ### Step 1. Install PHP ``` sudo su -zypper -n ar -f http://download.opensuse.org/repositories/devel:languages:php/SLE_12/devel:languages:php.repo +zypper -n ar -f https://download.opensuse.org/repositories/devel:languages:php/SLE_12_SP3/devel:languages:php.repo zypper --gpg-auto-import-keys refresh zypper -n install php7 php7-pear php7-devel ``` ### Step 2. Install prerequisites -Install the ODBC driver for Suse 12 by following the instructions on the [Linux and macOS installation page](https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server). +Install the ODBC driver for Suse 12 by following the instructions on the [Linux and macOS installation page](https://docs.microsoft.com/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server). ### Step 3. Install the PHP drivers for Microsoft SQL Server + +> [!NOTE] +> If using PHP 7.3, replace `sqlsrv` and `pdo_sqlsrv` in the following commands with `sqlsrv-5.4.0preview` and `pdo_sqlsrv-5.4.0preview` or later, as earlier versions are not compatible with PHP 7.3. ``` sudo pecl install sqlsrv sudo pecl install pdo_sqlsrv @@ -209,7 +220,7 @@ sudo systemctl restart apache2 ``` To test your installation, see [Testing your installation](#testing-your-installation) at the end of this document. -## Installing the drivers on macOS El Capitan, Sierra and High Sierra +## Installing the drivers on macOS El Capitan, Sierra, High Sierra, and Mojave If you do not already have it, install brew as follows: ``` @@ -217,7 +228,7 @@ If you do not already have it, install brew as follows: ``` > [!NOTE] -> To install PHP 7.0 or 7.1, replace php@7.2 with php@7.0 or php@7.1 respectively in the following commands. +> To install PHP 7.0, 7.1, or 7.3, replace `php@7.2` with `php@7.0`, `php@7.1`, or `php@7.3` respectively in the following commands. ### Step 1. Install PHP @@ -226,15 +237,13 @@ brew tap brew tap homebrew/core brew install php@7.2 ``` - PHP should now be in your path -- run `php -v` to verify that you are running the correct version of PHP. If PHP is not in your path or it is not the correct version, run the following: - ``` brew link --force --overwrite php@7.2 ``` ### Step 2. Install prerequisites -Install the ODBC driver for macOS by following the instructions on the [Linux and macOS installation page](https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server). +Install the ODBC driver for macOS by following the instructions on the [Linux and macOS installation page](https://docs.microsoft.com/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server). In addition, you may need to install the GNU make tools: ``` @@ -242,6 +251,9 @@ brew install autoconf automake libtool ``` ### Step 3. Install the PHP drivers for Microsoft SQL Server + +> [!NOTE] +> If using PHP 7.3, replace `sqlsrv` and `pdo_sqlsrv` in the following commands with `sqlsrv-5.4.0preview` and `pdo_sqlsrv-5.4.0preview` or later, as earlier versions are not compatible with PHP 7.3. ``` sudo pecl install sqlsrv sudo pecl install pdo_sqlsrv @@ -250,10 +262,10 @@ sudo pecl install pdo_sqlsrv ``` brew install apache2 ``` -To find the Apache configuration file for your Apache installation, run +To find the Apache configuration file for your Apache installation, run ``` apachectl -V | grep SERVER_CONFIG_FILE -``` +``` and substitute the path for `httpd.conf` in the following commands: ``` echo "LoadModule php7_module /usr/local/opt/php@7.2/lib/httpd/modules/libphp7.so" >> /usr/local/etc/httpd/httpd.conf @@ -317,4 +329,5 @@ function formatErrors($errors) } ?> ``` -Point your browser to http://localhost/testsql.php (http://localhost:8080/testsql.php on macOS). You should now be able to connect to your SQL Server/Azure SQL database. +Point your browser to https://localhost/testsql.php (https://localhost:8080/testsql.php on macOS). You should now be able to connect to your SQL Server/Azure SQL database. + diff --git a/README.md b/README.md index 93c19e3d..bd2b2349 100644 --- a/README.md +++ b/README.md @@ -17,8 +17,8 @@ Thank you for taking the time to participate in our last survey. You can continu |--------------------------|--------------------------|---------------------------------------|-------------------------------------------| | [![av-image][]][av-site] | [![tv-image][]][tv-site] | [![Coverage Codecov][]][codecov-site] | [![Coverage Coveralls][]][coveralls-site] | -[av-image]: https://ci.appveyor.com/api/projects/status/xhp4nq9ouljnhxqf/branch/dev?svg=true -[av-site]: https://ci.appveyor.com/project/Microsoft-PHPSQL/msphpsql-frhmr/branch/dev +[av-image]: https://ci.appveyor.com/api/projects/status/vo4rfei6lxlamrnc?svg=true +[av-site]: https://ci.appveyor.com/project/msphpsql/msphpsql/branch/dev [tv-image]: https://travis-ci.org/Microsoft/msphpsql.svg?branch=dev [tv-site]: https://travis-ci.org/Microsoft/msphpsql/ [Coverage Coveralls]: https://coveralls.io/repos/github/Microsoft/msphpsql/badge.svg?branch=dev @@ -45,8 +45,8 @@ Thank you for taking the time to participate in our last survey. You can continu 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.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) +- PHP 7.1.x, 7.2.x (7.2.0 and up on Unix, 7.2.1 and up on Windows), or 7.3.x +- [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) - 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. diff --git a/appveyor.yml b/appveyor.yml index 4a0fcbdd..ee9f2eb3 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -24,7 +24,7 @@ environment: SQL_INSTANCE: SQL2017 PHP_VC: 15 PHP_MAJOR_VER: 7.2 - PHP_MINOR_VER: latest + PHP_MINOR_VER: 11 PHP_EXE_PATH: x64\Release_TS THREAD: ts platform: x64 diff --git a/sample/pdo_sqlsrv_sample.php b/sample/pdo_sqlsrv_sample.php index 3c92efa3..4c1f61cd 100644 --- a/sample/pdo_sqlsrv_sample.php +++ b/sample/pdo_sqlsrv_sample.php @@ -1,74 +1,73 @@ query( $tsql ); - - //Error handling - FormatErrors ($conn->errorInfo()); - - $productCount = 0; - $ctr = 0; - ?> + $database = "yourdatabase"; + $uid = "yourusername"; + $pwd = "yourpassword"; + + //Establishes the connection + $conn = new PDO("sqlsrv:server=$serverName ; Database = $database", $uid, $pwd); + + //Select Query + $tsql = "SELECT [CompanyName] FROM SalesLT.Customer"; + + //Executes the query + $getProducts = $conn->query($tsql); + + //Error handling + FormatErrors($conn->errorInfo()); + + $productCount = 0; + $ctr = 0; + ?>

First 10 results are :

fetch(PDO::FETCH_ASSOC)) - { - if($ctr>9) - break; - $ctr++; - echo($row['CompanyName']); - echo("
"); - $productCount++; - } - $getProducts = NULL; - - $tsql = "INSERT INTO SalesLT.Product (Name, ProductNumber, StandardCost, ListPrice, SellStartDate) OUTPUT INSERTED.* VALUES ('SQL New 1', 'SQL New 2', 0, 0, getdate())"; - - //Insert query - $insertReview = $conn->query( $tsql ); - FormatErrors ($conn->errorInfo()); - ?> + while ($row = $getProducts->fetch(PDO::FETCH_ASSOC)) { + if ($ctr>9) { + break; + } + $ctr++; + echo($row['CompanyName']); + echo("
"); + $productCount++; + } + $getProducts = null; + + $tsql = "INSERT INTO SalesLT.Product (Name, ProductNumber, StandardCost, ListPrice, SellStartDate) OUTPUT INSERTED.* VALUES ('SQL New 1', 'SQL New 2', 0, 0, getdate())"; + + //Insert query + $insertReview = $conn->query($tsql); + FormatErrors($conn->errorInfo()); + ?>

Product Key inserted is :

fetch(PDO::FETCH_ASSOC)) - { - echo($row['ProductID']."
"); - } - $insertReview = NULL; - - //Delete Query - //We are deleting the same record - $tsql = "DELETE FROM [SalesLT].[Product] WHERE Name=?"; - $param = "SQL New 1"; - - $deleteReview = $conn->prepare($tsql); - $deleteReview->bindParam(1, $param); - - $deleteReview->execute(); - FormatErrors ($deleteReview->errorInfo()); - - function FormatErrors( $error ) - { - /* Display error. */ - echo "Error information:
"; - - echo "SQLSTATE: ".$error[0]."
"; - echo "Code: ".$error[1]."
"; - echo "Message: ".$error[2]."
"; - } + while ($row = $insertReview->fetch(PDO::FETCH_ASSOC)) { + echo($row['ProductID']."
"); + } + $insertReview = null; + + //Delete Query + //We are deleting the same record + $tsql = "DELETE FROM [SalesLT].[Product] WHERE Name=?"; + $param = "SQL New 1"; + + $deleteReview = $conn->prepare($tsql); + $deleteReview->bindParam(1, $param); + + $deleteReview->execute(); + FormatErrors($deleteReview->errorInfo()); + + function FormatErrors($error) + { + /* Display error. */ + echo "Error information:
"; + + echo "SQLSTATE: ".$error[0]."
"; + echo "Code: ".$error[1]."
"; + echo "Message: ".$error[2]."
"; + } ?> \ No newline at end of file diff --git a/sample/sqlsrv_sample.php b/sample/sqlsrv_sample.php index 886e06da..db0a0ede 100644 --- a/sample/sqlsrv_sample.php +++ b/sample/sqlsrv_sample.php @@ -2,68 +2,70 @@ echo "\n"; $serverName = "tcp:yourserver.database.windows.net,1433"; $connectionOptions = array("Database"=>"yourdatabase", "Uid"=>"yourusername", "PWD"=>"yourpassword"); - - //Establishes the connection - $conn = sqlsrv_connect($serverName, $connectionOptions); - //Select Query - $tsql = "SELECT [CompanyName] FROM SalesLT.Customer"; - //Executes the query - $getProducts = sqlsrv_query($conn, $tsql); - //Error handling - if ($getProducts == FALSE) - die(FormatErrors(sqlsrv_errors())); - $productCount = 0; - $ctr = 0; - ?> + + //Establishes the connection + $conn = sqlsrv_connect($serverName, $connectionOptions); + //Select Query + $tsql = "SELECT [CompanyName] FROM SalesLT.Customer"; + //Executes the query + $getProducts = sqlsrv_query($conn, $tsql); + //Error handling + if ($getProducts == false) { + die(FormatErrors(sqlsrv_errors())); + } + $productCount = 0; + $ctr = 0; + ?>

First 10 results are :

9) - break; - $ctr++; - echo($row['CompanyName']); - echo("
"); - $productCount++; - } - sqlsrv_free_stmt($getProducts); - - $tsql = "INSERT INTO SalesLT.Product (Name, ProductNumber, StandardCost, ListPrice, SellStartDate) OUTPUT INSERTED.ProductID VALUES ('SQL New 1', 'SQL New 2', 0, 0, getdate())"; - //Insert query - $insertReview = sqlsrv_query($conn, $tsql); - if($insertReview == FALSE) - die(FormatErrors( sqlsrv_errors())); - ?> + while ($row = sqlsrv_fetch_array($getProducts, SQLSRV_FETCH_ASSOC)) { + if ($ctr>9) { + break; + } + $ctr++; + echo($row['CompanyName']); + echo("
"); + $productCount++; + } + sqlsrv_free_stmt($getProducts); + + $tsql = "INSERT INTO SalesLT.Product (Name, ProductNumber, StandardCost, ListPrice, SellStartDate) OUTPUT INSERTED.ProductID VALUES ('SQL New 1', 'SQL New 2', 0, 0, getdate())"; + //Insert query + $insertReview = sqlsrv_query($conn, $tsql); + if ($insertReview == false) { + die(FormatErrors(sqlsrv_errors())); + } + ?>

Product Key inserted is :

"; - - foreach ( $errors as $error ) - { - echo "SQLSTATE: ".$error['SQLSTATE']."
"; - echo "Code: ".$error['code']."
"; - echo "Message: ".$error['message']."
"; - } - } + while ($row = sqlsrv_fetch_array($insertReview, SQLSRV_FETCH_ASSOC)) { + echo($row['ProductID']); + } + sqlsrv_free_stmt($insertReview); + //Delete Query + //We are deleting the same record + $tsql = "DELETE FROM [SalesLT].[Product] WHERE Name=?"; + $params = array("SQL New 1"); + + $deleteReview = sqlsrv_prepare($conn, $tsql, $params); + if ($deleteReview == false) { + die(FormatErrors(sqlsrv_errors())); + } + + if (sqlsrv_execute($deleteReview) == false) { + die(FormatErrors(sqlsrv_errors())); + } + + function FormatErrors($errors) + { + /* Display errors. */ + echo "Error information:
"; + + foreach ($errors as $error) { + echo "SQLSTATE: ".$error['SQLSTATE']."
"; + echo "Code: ".$error['code']."
"; + echo "Message: ".$error['message']."
"; + } + } ?> \ No newline at end of file diff --git a/source/pdo_sqlsrv/config.m4 b/source/pdo_sqlsrv/config.m4 index 3de4fefc..82aa69e2 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.4 for PHP for SQL Server +dnl Microsoft Drivers 5.5 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 cd6e3a06..14362748 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -37,8 +37,15 @@ if( PHP_PDO_SQLSRV != "no" ) { 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("LDFLAGS_PDO_SQLSRV", "/d2:-guardspecload"); ADD_FLAG("CFLAGS_PDO_SQLSRV", "/Qspectre"); - } + } else if (VCVERS == 1900) { + var subver1900 = probe_binary(PHP_CL).substr(6); + if (subver1900 >= 24241) { + ADD_FLAG("LDFLAGS_PDO_SQLSRV", "/d2:-guardspecload"); + 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 b424866e..d1f76e49 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -80,7 +80,9 @@ 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 + PDO_STMT_OPTION_FETCHES_DATETIME_TYPE, + PDO_STMT_OPTION_FORMAT_DECIMALS, + PDO_STMT_OPTION_DECIMAL_PLACES }; // List of all the statement options supported by this driver. @@ -95,6 +97,8 @@ const stmt_option PDO_STMT_OPTS[] = { { 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, 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{} }, }; @@ -498,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; @@ -1067,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: @@ -1225,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 ); @@ -1586,6 +1625,14 @@ void add_stmt_option_key( _Inout_ sqlsrv_context& ctx, _In_ size_t key, _Inout_ option_key = PDO_STMT_OPTION_FETCHES_DATETIME_TYPE; break; + case SQLSRV_ATTR_FORMAT_DECIMALS: + 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 a5fcbdd0..6b7b54e3 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -286,6 +286,8 @@ namespace { { "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 }, + { "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_parser.cpp b/source/pdo_sqlsrv/pdo_parser.cpp index e6a70d4d..984f983c 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 3f6bc328..3f7e72b8 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -882,6 +882,14 @@ int pdo_sqlsrv_stmt_set_attr( _Inout_ pdo_stmt_t *stmt, _In_ zend_long attr, _In driver_stmt->fetch_datetime = ( zend_is_true( val )) ? true : false; break; + case SQLSRV_ATTR_FORMAT_DECIMALS: + 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: THROW_PDO_ERROR( driver_stmt, PDO_SQLSRV_ERROR_INVALID_STMT_ATTR ); break; @@ -969,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; @@ -1377,6 +1397,7 @@ sqlsrv_phptype pdo_sqlsrv_stmt::sql_type_to_php_type( _In_ SQLINTEGER sql_type, } else { sqlsrv_phptype.typeinfo.type = SQLSRV_PHPTYPE_STRING; + sqlsrv_phptype.typeinfo.encoding = SQLSRV_ENCODING_CHAR; } break; case SQL_FLOAT: @@ -1386,6 +1407,7 @@ sqlsrv_phptype pdo_sqlsrv_stmt::sql_type_to_php_type( _In_ SQLINTEGER sql_type, } else { sqlsrv_phptype.typeinfo.type = SQLSRV_PHPTYPE_STRING; + sqlsrv_phptype.typeinfo.encoding = SQLSRV_ENCODING_CHAR; } break; case SQL_TYPE_DATE: @@ -1400,10 +1422,13 @@ sqlsrv_phptype pdo_sqlsrv_stmt::sql_type_to_php_type( _In_ SQLINTEGER sql_type, } break; case SQL_BIGINT: - case SQL_CHAR: case SQL_DECIMAL: - case SQL_GUID: case SQL_NUMERIC: + sqlsrv_phptype.typeinfo.type = SQLSRV_PHPTYPE_STRING; + sqlsrv_phptype.typeinfo.encoding = SQLSRV_ENCODING_CHAR; + break; + case SQL_CHAR: + case SQL_GUID: case SQL_WCHAR: case SQL_VARCHAR: case SQL_WVARCHAR: diff --git a/source/pdo_sqlsrv/pdo_util.cpp b/source/pdo_sqlsrv/pdo_util.cpp index dee2e3e0..91efcb90 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -437,6 +437,10 @@ pdo_error PDO_ERRORS[] = { SQLSRV_ERROR_EMPTY_ACCESS_TOKEN, { IMSSP, (SQLCHAR*) "The Azure AD Access Token is empty. Expected a byte string.", -91, false} }, + { + 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} + }, { UINT_MAX, {} } }; diff --git a/source/pdo_sqlsrv/php_pdo_sqlsrv.h b/source/pdo_sqlsrv/php_pdo_sqlsrv.h index c110a9c6..f31da7c7 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -41,14 +41,16 @@ extern "C" { // sqlsrv driver specific PDO attributes enum PDO_SQLSRV_ATTR { - // Currently there are only three custom attributes for this driver. + // The custom attributes for this driver: SQLSRV_ATTR_ENCODING = PDO_ATTR_DRIVER_SPECIFIC, SQLSRV_ATTR_QUERY_TIMEOUT, SQLSRV_ATTR_DIRECT_QUERY, SQLSRV_ATTR_CURSOR_SCROLL_TYPE, SQLSRV_ATTR_CLIENT_BUFFER_MAX_KB_SIZE, SQLSRV_ATTR_FETCHES_NUMERIC_TYPE, - SQLSRV_ATTR_FETCHES_DATETIME_TYPE + SQLSRV_ATTR_FETCHES_DATETIME_TYPE, + SQLSRV_ATTR_FORMAT_DECIMALS, + SQLSRV_ATTR_DECIMAL_PLACES }; // valid set of values for TransactionIsolation connection option @@ -205,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 ); }; @@ -266,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 ); @@ -279,8 +285,6 @@ struct pdo_sqlsrv_stmt : public sqlsrv_stmt { size_t direct_query_subst_string_len; // length of query string used for direct queries HashTable* placeholders; // hashtable of named placeholders to keep track of params ordering in emulate prepare - // meta data for current result set - 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 435fa9a3..7b74950a 100644 --- a/source/pdo_sqlsrv/template.rc +++ b/source/pdo_sqlsrv/template.rc @@ -3,7 +3,7 @@ // // Contents: Version resource // -// Microsoft Drivers 5.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 a5033db4..0e3beadd 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 f7933f97..0c29e81f 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 354ebbf6..6f494dc4 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 475cd84c..bcd250b6 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 da6284dc..8ec79e0c 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -244,7 +244,7 @@ sqlsrv_conn* core_sqlsrv_connect( _In_ sqlsrv_context& henv_cp, _In_ sqlsrv_cont #endif // !_WIN32 // time to free the access token, if not null - if (conn->azure_ad_access_token != NULL) { + if (conn->azure_ad_access_token) { memset(conn->azure_ad_access_token->data, 0, conn->azure_ad_access_token->dataSize); // clear the memory conn->azure_ad_access_token.reset(); } @@ -257,7 +257,9 @@ sqlsrv_conn* core_sqlsrv_connect( _In_ sqlsrv_context& henv_cp, _In_ sqlsrv_cont throw core::CoreException(); } - load_azure_key_vault( conn ); + // After load_azure_key_vault, reset AKV related variables regardless + load_azure_key_vault(conn); + conn->ce_option.akv_reset(); // determine the version of the server we're connected to. The server version is left in the // connection upon return. @@ -292,6 +294,7 @@ sqlsrv_conn* core_sqlsrv_connect( _In_ sqlsrv_context& henv_cp, _In_ sqlsrv_cont throw; } catch( core::CoreException& ) { + conn->ce_option.akv_reset(); conn_str.clear(); conn->invalidate(); throw; @@ -862,6 +865,7 @@ void build_connection_string_and_set_conn_attr( _Inout_ sqlsrv_conn* conn, _Inou } catch( core::CoreException& ) { + conn->ce_option.akv_reset(); throw; } } @@ -976,18 +980,18 @@ void load_azure_key_vault(_Inout_ sqlsrv_conn* conn TSRMLS_DC) throw core::CoreException(); } - CHECK_CUSTOM_ERROR(conn->ce_option.akv_id == NULL, conn, SQLSRV_ERROR_AKV_NAME_MISSING) { + CHECK_CUSTOM_ERROR(!conn->ce_option.akv_id, conn, SQLSRV_ERROR_AKV_NAME_MISSING) { throw core::CoreException(); } - CHECK_CUSTOM_ERROR(conn->ce_option.akv_secret == NULL, conn, SQLSRV_ERROR_AKV_SECRET_MISSING) { + CHECK_CUSTOM_ERROR(!conn->ce_option.akv_secret, conn, SQLSRV_ERROR_AKV_SECRET_MISSING) { throw core::CoreException(); } - char *akv_id = Z_STRVAL_P(conn->ce_option.akv_id); - char *akv_secret = Z_STRVAL_P(conn->ce_option.akv_secret); - unsigned int id_len = static_cast(Z_STRLEN_P(conn->ce_option.akv_id)); - unsigned int key_size = static_cast(Z_STRLEN_P(conn->ce_option.akv_secret)); + char *akv_id = conn->ce_option.akv_id.get(); + char *akv_secret = conn->ce_option.akv_secret.get(); + unsigned int id_len = strnlen_s(akv_id); + unsigned int key_size = strnlen_s(akv_secret); configure_azure_key_vault(conn, AKV_CONFIG_FLAGS, conn->ce_option.akv_mode, 0); configure_azure_key_vault(conn, AKV_CONFIG_PRINCIPALID, akv_id, id_len); @@ -1120,6 +1124,7 @@ void ce_akv_str_set_func::func(_In_ connection_option const* option, _In_ zval* { SQLSRV_ASSERT(Z_TYPE_P(value) == IS_STRING, "Azure Key Vault keywords accept only strings."); + const char *value_str = Z_STRVAL_P(value); size_t value_len = Z_STRLEN_P(value); CHECK_CUSTOM_ERROR(value_len <= 0, conn, SQLSRV_ERROR_KEYSTORE_INVALID_VALUE) { @@ -1130,7 +1135,6 @@ void ce_akv_str_set_func::func(_In_ connection_option const* option, _In_ zval* { case SQLSRV_CONN_OPTION_KEYSTORE_AUTHENTICATION: { - char *value_str = Z_STRVAL_P(value); if (!stricmp(value_str, "KeyVaultPassword")) { conn->ce_option.akv_mode = AKVCFG_AUTHMODE_PASSWORD; } else if (!stricmp(value_str, "KeyVaultClientSecret")) { @@ -1145,14 +1149,19 @@ void ce_akv_str_set_func::func(_In_ connection_option const* option, _In_ zval* break; } case SQLSRV_CONN_OPTION_KEYSTORE_PRINCIPAL_ID: - { - conn->ce_option.akv_id = value; - conn->ce_option.akv_required = true; - break; - } case SQLSRV_CONN_OPTION_KEYSTORE_SECRET: { - conn->ce_option.akv_secret = value; + // Create a new string to save a copy of the zvalue + char *pValue = static_cast(sqlsrv_malloc(value_len + 1)); + memcpy_s(pValue, value_len + 1, value_str, value_len); + pValue[value_len] = '\0'; // this makes sure there will be no trailing garbage + + // This will free the existing memory block before assigning the new pointer -- the user might set the value(s) more than once + if (option->conn_option_key == SQLSRV_CONN_OPTION_KEYSTORE_PRINCIPAL_ID) { + conn->ce_option.akv_id = pValue; + } else { + conn->ce_option.akv_secret = pValue; + } conn->ce_option.akv_required = true; break; } diff --git a/source/shared/core_init.cpp b/source/shared/core_init.cpp index 274c10d2..ea604e79 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 67a80555..f4f00b37 100644 --- a/source/shared/core_results.cpp +++ b/source/shared/core_results.cpp @@ -3,7 +3,7 @@ // // Contents: Result sets // -// Microsoft Drivers 5.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/core_sqlsrv.h b/source/shared/core_sqlsrv.h index 6c49464c..400e9ea2 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -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. @@ -1055,15 +1060,23 @@ struct stmt_option; // This holds the various details of column encryption. struct col_encryption_option { - bool enabled; // column encryption enabled, false by default - SQLINTEGER akv_mode; - zval_auto_ptr akv_id; - zval_auto_ptr akv_secret; - bool akv_required; + bool enabled; // column encryption enabled, false by default + SQLINTEGER akv_mode; + sqlsrv_malloc_auto_ptr akv_id; + sqlsrv_malloc_auto_ptr akv_secret; + bool akv_required; col_encryption_option() : enabled( false ), akv_mode(-1), akv_required( false ) { } + + void akv_reset() + { + akv_id.reset(); + akv_secret.reset(); + akv_required = false; + akv_mode = -1; + } }; // *** connection resource structure *** @@ -1099,6 +1112,8 @@ enum SQLSRV_STMT_OPTIONS { SQLSRV_STMT_OPTION_SCROLLABLE, 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, @@ -1288,6 +1303,16 @@ 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 ); }; +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 { @@ -1326,38 +1351,6 @@ extern php_stream_wrapper g_sqlsrv_stream_wrapper; #define SQLSRV_STREAM_WRAPPER "sqlsrv" #define SQLSRV_STREAM "sqlsrv_stream" -// holds the output parameter information. Strings also need the encoding and other information for -// after processing. Only integer, float, and strings are allowable output parameters. -struct sqlsrv_output_param { - - zval* param_z; - SQLSRV_ENCODING encoding; - SQLUSMALLINT param_num; // used to index into the ind_or_len of the statement - 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; - - // string output param constructor - sqlsrv_output_param( _In_ zval* p_z, _In_ SQLSRV_ENCODING enc, _In_ int num, _In_ SQLUINTEGER buffer_len ) : - param_z(p_z), encoding(enc), param_num(num), original_buffer_len(buffer_len), is_bool(false), php_out_type(SQLSRV_PHPTYPE_INVALID) - { - } - - // every other type output parameter constructor - sqlsrv_output_param( _In_ zval* p_z, _In_ int num, _In_ bool is_bool, _In_ SQLSRV_PHPTYPE php_out_type) : - param_z( p_z ), - encoding( SQLSRV_ENCODING_INVALID ), - param_num( num ), - original_buffer_len( -1 ), - is_bool( is_bool ), - php_out_type(php_out_type) - { - } -}; - -// forward decls -struct sqlsrv_result_set; - // *** parameter metadata struct *** struct param_meta_data { @@ -1380,6 +1373,53 @@ struct param_meta_data SQLULEN get_column_size() { return column_size; } }; +// holds the output parameter information. Strings also need the encoding and other information for +// after processing. Only integer, float, and strings are allowable output parameters. +struct sqlsrv_output_param { + + zval* param_z; + SQLSRV_ENCODING encoding; + SQLUSMALLINT param_num; // used to index into the ind_or_len of the statement + 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 + + // string output param constructor + sqlsrv_output_param( _In_ zval* p_z, _In_ SQLSRV_ENCODING enc, _In_ int num, _In_ SQLUINTEGER buffer_len ) : + param_z(p_z), encoding(enc), param_num(num), original_buffer_len(buffer_len), is_bool(false), php_out_type(SQLSRV_PHPTYPE_INVALID) + { + } + + // every other type output parameter constructor + sqlsrv_output_param( _In_ zval* p_z, _In_ int num, _In_ bool is_bool, _In_ SQLSRV_PHPTYPE php_out_type) : + param_z( p_z ), + encoding( SQLSRV_ENCODING_INVALID ), + param_num( num ), + original_buffer_len( -1 ), + is_bool( is_bool ), + php_out_type(php_out_type) + { + } + + void saveMetaData(SQLSMALLINT sql_type, SQLSMALLINT column_size, SQLSMALLINT decimal_digits, SQLSMALLINT nullable = SQL_NULLABLE) + { + meta_data.sql_type = sql_type; + meta_data.column_size = column_size; + meta_data.decimal_digits = decimal_digits; + meta_data.nullable = nullable; + } + + param_meta_data& getMetaData() + { + return meta_data; + } +}; + +// forward decls +struct sqlsrv_result_set; +struct field_meta_data; + // *** Statement resource structure *** struct sqlsrv_stmt : public sqlsrv_context { @@ -1400,6 +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 + 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 @@ -1419,6 +1461,9 @@ struct sqlsrv_stmt : public sqlsrv_context { std::vector param_descriptions; + // meta data for current result set + std::vector> current_meta_data; + sqlsrv_stmt( _In_ sqlsrv_conn* c, _In_ SQLHANDLE handle, _In_ error_callback e, _In_opt_ void* drv TSRMLS_DC ); virtual ~sqlsrv_stmt( void ); @@ -1437,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) { } @@ -1488,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_decimal_places(_Inout_ sqlsrv_stmt* stmt, _In_ zval* value_z TSRMLS_DC); //********************************************************************************************************************************* // Result Set @@ -1668,7 +1714,6 @@ struct sqlsrv_buffered_result_set : public sqlsrv_result_set { // utility functions shared by multiple callers across files bool convert_string_from_utf16_inplace( _In_ SQLSRV_ENCODING encoding, _Inout_updates_z_(len) char** string, _Inout_ SQLLEN& len); -bool convert_zval_string_from_utf16( _In_ SQLSRV_ENCODING encoding, _Inout_ zval* value_z, _Inout_ SQLLEN& len); bool validate_string( _In_ char* string, _In_ SQLLEN& len); bool convert_string_from_utf16( _In_ SQLSRV_ENCODING encoding, _In_reads_bytes_(cchInLen) const SQLWCHAR* inString, _In_ SQLINTEGER cchInLen, _Inout_updates_bytes_(cchOutLen) char** outString, _Out_ SQLLEN& cchOutLen ); SQLWCHAR* utf16_string_from_mbcs_string( _In_ SQLSRV_ENCODING php_encoding, _In_reads_bytes_(mbcs_len) const char* mbcs_string, _In_ unsigned int mbcs_len, _Out_ unsigned int* utf16_len ); @@ -1731,6 +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_DECIMAL_PLACES, // Driver specific error codes starts from here. SQLSRV_ERROR_DRIVER_SPECIFIC = 1000, @@ -1898,9 +1944,10 @@ namespace core { inline void check_for_mars_error( _Inout_ sqlsrv_stmt* stmt, _In_ SQLRETURN r TSRMLS_DC ) { + // Skip this if not SQL_ERROR - // We check for the 'connection busy' error caused by having MultipleActiveResultSets off // and return a more helpful message prepended to the ODBC errors if that error occurs - if( !SQL_SUCCEEDED( r )) { + if (r == SQL_ERROR) { SQLCHAR err_msg[SQL_MAX_MESSAGE_LENGTH + 1] = {'\0'}; SQLSMALLINT len = 0; diff --git a/source/shared/core_stmt.cpp b/source/shared/core_stmt.cpp index 46d60907..3b263fe2 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -97,7 +97,7 @@ size_t calc_utf8_missing( _Inout_ sqlsrv_stmt* stmt, _In_reads_(buffer_end) cons bool check_for_next_stream_parameter( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ); bool convert_input_param_to_utf16( _In_ zval* input_param_z, _Inout_ zval* convert_param_z ); void core_get_field_common(_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); + sqlsrv_php_type, _Inout_updates_bytes_(*field_len) void*& field_value, _Inout_ SQLLEN* field_len TSRMLS_DC); // returns the ODBC C type constant that matches the PHP type and encoding given SQLSMALLINT default_c_type( _Inout_ sqlsrv_stmt* stmt, _In_opt_ SQLULEN paramno, _In_ zval const* param_z, _In_ SQLSRV_ENCODING encoding TSRMLS_DC ); void default_sql_size_and_scale( _Inout_ sqlsrv_stmt* stmt, _In_opt_ unsigned int paramno, _In_ zval* param_z, _In_ SQLSRV_ENCODING encoding, @@ -107,9 +107,10 @@ 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_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 ); + _Inout_updates_bytes_(*field_len) void*& field_value, _Inout_ SQLLEN* field_len TSRMLS_DC ); stmt_option const* get_stmt_option( sqlsrv_conn const* conn, _In_ zend_ulong key, _In_ const stmt_option stmt_opts[] TSRMLS_DC ); bool is_valid_sqlsrv_phptype( _In_ sqlsrv_phptype type ); // assure there is enough space for the output parameter string @@ -124,7 +125,6 @@ void send_param_streams( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ); void sqlsrv_output_param_dtor( _Inout_ zval* data ); // called when a bound stream parameter is to be destroyed. void sqlsrv_stream_dtor( _Inout_ zval* data ); -bool is_streamable_type( _In_ SQLINTEGER sql_type ); } @@ -142,13 +142,15 @@ 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), + 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 + 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 ), current_stream( NULL, SQLSRV_ENCODING_DEFAULT ), current_stream_read( 0 ) { - ZVAL_UNDEF( &active_stream ); + ZVAL_UNDEF( &active_stream ); // initialize the input string parameters array (which holds zvals) core::sqlsrv_array_init( *conn, ¶m_input_strings TSRMLS_CC ); @@ -260,7 +262,7 @@ void sqlsrv_stmt::new_result_set( TSRMLS_D ) sqlsrv_stmt* core_sqlsrv_create_stmt( _Inout_ sqlsrv_conn* conn, _In_ driver_stmt_factory stmt_factory, _In_opt_ HashTable* options_ht, _In_opt_ const stmt_option valid_stmt_opts[], _In_ error_callback const err, _In_opt_ void* driver TSRMLS_DC ) { - sqlsrv_malloc_auto_ptr stmt; + sqlsrv_malloc_auto_ptr stmt; SQLHANDLE stmt_h = SQL_NULL_HANDLE; sqlsrv_stmt* return_stmt = NULL; @@ -278,26 +280,26 @@ sqlsrv_stmt* core_sqlsrv_create_stmt( _Inout_ sqlsrv_conn* conn, _In_ driver_stm // process the options array given to core_sqlsrv_prepare. if( options_ht && zend_hash_num_elements( options_ht ) > 0 && valid_stmt_opts ) { - zend_ulong index = -1; - zend_string *key = NULL; - zval* value_z = NULL; + zend_ulong index = -1; + zend_string *key = NULL; + zval* value_z = NULL; - ZEND_HASH_FOREACH_KEY_VAL( options_ht, index, key, value_z ) { + ZEND_HASH_FOREACH_KEY_VAL( options_ht, index, key, value_z ) { - int type = key ? HASH_KEY_IS_STRING : HASH_KEY_IS_LONG; + int type = key ? HASH_KEY_IS_STRING : HASH_KEY_IS_LONG; - // The driver layer should ensure a valid key. - DEBUG_SQLSRV_ASSERT(( type == HASH_KEY_IS_LONG ), "allocate_stmt: Invalid statment option key provided." ); + // The driver layer should ensure a valid key. + DEBUG_SQLSRV_ASSERT(( type == HASH_KEY_IS_LONG ), "allocate_stmt: Invalid statment option key provided." ); - const stmt_option* stmt_opt = get_stmt_option( stmt->conn, index, valid_stmt_opts TSRMLS_CC ); + const stmt_option* stmt_opt = get_stmt_option( stmt->conn, index, valid_stmt_opts TSRMLS_CC ); - // if the key didn't match, then return the error to the script. - // The driver layer should ensure that the key is valid. - DEBUG_SQLSRV_ASSERT( stmt_opt != NULL, "allocate_stmt: unexpected null value for statement option." ); + // if the key didn't match, then return the error to the script. + // The driver layer should ensure that the key is valid. + DEBUG_SQLSRV_ASSERT( stmt_opt != NULL, "allocate_stmt: unexpected null value for statement option." ); - // perform the actions the statement option needs done. - (*stmt_opt->func)( stmt, stmt_opt, value_z TSRMLS_CC ); - } ZEND_HASH_FOREACH_END(); + // perform the actions the statement option needs done. + (*stmt_opt->func)( stmt, stmt_opt, value_z TSRMLS_CC ); + } ZEND_HASH_FOREACH_END(); } return_stmt = stmt; @@ -493,7 +495,7 @@ void core_sqlsrv_bind_param( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT param_ ind_ptr = buffer_len; if( direction != SQL_PARAM_INPUT ){ // save the parameter so that 1) the buffer doesn't go away, and 2) we can set it to NULL if returned - sqlsrv_output_param output_param( param_ref, static_cast( param_num ), zval_was_bool, php_out_type); + sqlsrv_output_param output_param( param_ref, static_cast( param_num ), zval_was_bool, php_out_type); save_output_param_for_later( stmt, output_param TSRMLS_CC ); } } @@ -501,11 +503,11 @@ void core_sqlsrv_bind_param( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT param_ case IS_DOUBLE: { buffer = ¶m_z->value; - buffer_len = sizeof( Z_DVAL_P( param_z )); + buffer_len = sizeof( Z_DVAL_P( param_z )); ind_ptr = buffer_len; if( direction != SQL_PARAM_INPUT ){ // save the parameter so that 1) the buffer doesn't go away, and 2) we can set it to NULL if returned - sqlsrv_output_param output_param( param_ref, static_cast( param_num ), zval_was_bool, php_out_type); + sqlsrv_output_param output_param( param_ref, static_cast( param_num ), zval_was_bool, php_out_type); save_output_param_for_later( stmt, output_param TSRMLS_CC ); } } @@ -572,6 +574,8 @@ void core_sqlsrv_bind_param( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT param_ // save the parameter to be adjusted and/or converted after the results are processed sqlsrv_output_param output_param( param_ref, encoding, param_num, static_cast( buffer_len ) ); + output_param.saveMetaData(sql_type, column_size, decimal_digits); + save_output_param_for_later( stmt, output_param TSRMLS_CC ); // For output parameters, if we set the column_size to be same as the buffer_len, @@ -617,10 +621,10 @@ void core_sqlsrv_bind_param( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT param_ zval buffer_z; zval format_z; zval params[1]; - ZVAL_UNDEF( &function_z ); - ZVAL_UNDEF( &buffer_z ); - ZVAL_UNDEF( &format_z ); - ZVAL_UNDEF( params ); + ZVAL_UNDEF( &function_z ); + ZVAL_UNDEF( &buffer_z ); + ZVAL_UNDEF( &format_z ); + ZVAL_UNDEF( params ); bool valid_class_name_found = false; @@ -649,23 +653,23 @@ void core_sqlsrv_bind_param( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT param_ // meaning there is too much information in the character string. If the user specifies the 'datetimeoffset' // sql type, it lacks the timezone. if( sql_type == SQL_SS_TIMESTAMPOFFSET ){ - core::sqlsrv_zval_stringl( &format_z, const_cast( DateTime::DATETIMEOFFSET_FORMAT ), + core::sqlsrv_zval_stringl( &format_z, const_cast( DateTime::DATETIMEOFFSET_FORMAT ), DateTime::DATETIMEOFFSET_FORMAT_LEN ); } else if( sql_type == SQL_TYPE_DATE ){ - core::sqlsrv_zval_stringl( &format_z, const_cast( DateTime::DATE_FORMAT ), DateTime::DATE_FORMAT_LEN ); + core::sqlsrv_zval_stringl( &format_z, const_cast( DateTime::DATE_FORMAT ), DateTime::DATE_FORMAT_LEN ); } else{ - core::sqlsrv_zval_stringl( &format_z, const_cast( DateTime::DATETIME_FORMAT ), DateTime::DATETIME_FORMAT_LEN ); + core::sqlsrv_zval_stringl( &format_z, const_cast( DateTime::DATETIME_FORMAT ), DateTime::DATETIME_FORMAT_LEN ); } // call the DateTime::format member function to convert the object to a string that SQL Server understands - core::sqlsrv_zval_stringl( &function_z, "format", sizeof( "format" ) - 1 ); + core::sqlsrv_zval_stringl( &function_z, "format", sizeof( "format" ) - 1 ); params[0] = format_z; // This is equivalent to the PHP code: $param_z->format( $format_z ); where param_z is the // DateTime object and $format_z is the format string. int zr = call_user_function( EG( function_table ), param_z, &function_z, &buffer_z, 1, params TSRMLS_CC ); - zend_string_release( Z_STR( format_z )); - zend_string_release( Z_STR( function_z )); + zend_string_release( Z_STR( format_z )); + zend_string_release( Z_STR( function_z )); CHECK_CUSTOM_ERROR( zr == FAILURE, stmt, SQLSRV_ERROR_INVALID_PARAMETER_PHPTYPE, param_num + 1 ){ throw core::CoreException(); } @@ -692,7 +696,7 @@ void core_sqlsrv_bind_param( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT param_ } core::SQLBindParameter( stmt, param_num + 1, direction, - c_type, sql_type, column_size, decimal_digits, buffer, buffer_len, &ind_ptr TSRMLS_CC ); + c_type, sql_type, column_size, decimal_digits, buffer, buffer_len, &ind_ptr TSRMLS_CC ); if ( stmt->conn->ce_option.enabled && sql_type == SQL_TYPE_TIMESTAMP ) { if( decimal_digits == 3 ) @@ -881,14 +885,14 @@ field_meta_data* core_sqlsrv_field_metadata( _Inout_ sqlsrv_stmt* stmt, _In_ SQL meta_data = new ( sqlsrv_malloc( sizeof( field_meta_data ))) field_meta_data(); field_name_temp = static_cast( sqlsrv_malloc( ( SS_MAXCOLNAMELEN + 1 ) * sizeof( SQLWCHAR ) )); SQLSRV_ENCODING encoding = ( (stmt->encoding() == SQLSRV_ENCODING_DEFAULT ) ? stmt->conn->encoding() : stmt->encoding()); - try{ + try{ core::SQLDescribeColW( stmt, colno + 1, field_name_temp, SS_MAXCOLNAMELEN + 1, &field_len_temp, &( meta_data->field_type ), & ( meta_data->field_size ), & ( meta_data->field_scale ), &( meta_data->field_is_nullable ) TSRMLS_CC ); - } - catch ( core::CoreException& e ) { - throw e; - } + } + catch ( core::CoreException& e ) { + throw e; + } bool converted = convert_string_from_utf16( encoding, field_name_temp, field_len_temp, ( char** ) &( meta_data->field_name ), field_name_len ); @@ -922,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 ); @@ -943,50 +960,50 @@ field_meta_data* core_sqlsrv_field_metadata( _Inout_ sqlsrv_stmt* stmt, _In_ SQL // Nothing, excpetion thrown if an error occurs void core_sqlsrv_get_field( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT field_index, _In_ sqlsrv_phptype sqlsrv_php_type_in, _In_ bool prefer_string, - _Outref_result_bytebuffer_maybenull_(*field_len) void*& field_value, _Inout_ SQLLEN* field_len, _In_ bool cache_field, - _Out_ SQLSRV_PHPTYPE *sqlsrv_php_type_out TSRMLS_DC) + _Outref_result_bytebuffer_maybenull_(*field_len) void*& field_value, _Inout_ SQLLEN* field_len, _In_ bool cache_field, + _Out_ SQLSRV_PHPTYPE *sqlsrv_php_type_out TSRMLS_DC) { - try { + try { - // close the stream to release the resource - close_active_stream(stmt TSRMLS_CC); + // close the stream to release the resource + close_active_stream(stmt TSRMLS_CC); - // if the field has been retrieved before, return the previous result - field_cache* cached = NULL; - if (NULL != ( cached = static_cast( zend_hash_index_find_ptr( Z_ARRVAL( stmt->field_cache ), static_cast( field_index ))))) { - // the field value is NULL - if( cached->value == NULL ) { - field_value = NULL; - *field_len = 0; - if( sqlsrv_php_type_out ) { *sqlsrv_php_type_out = SQLSRV_PHPTYPE_NULL; } - } - else { + // if the field has been retrieved before, return the previous result + field_cache* cached = NULL; + if (NULL != ( cached = static_cast( zend_hash_index_find_ptr( Z_ARRVAL( stmt->field_cache ), static_cast( field_index ))))) { + // the field value is NULL + if( cached->value == NULL ) { + field_value = NULL; + *field_len = 0; + if( sqlsrv_php_type_out ) { *sqlsrv_php_type_out = SQLSRV_PHPTYPE_NULL; } + } + else { - field_value = sqlsrv_malloc( cached->len, sizeof( char ), 1 ); - 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'; - } - *field_len = cached->len; - if( sqlsrv_php_type_out) { *sqlsrv_php_type_out = static_cast(cached->type.typeinfo.type); } - } - return; - } + field_value = sqlsrv_malloc( cached->len, sizeof( char ), 1 ); + 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'; + } + *field_len = cached->len; + if( sqlsrv_php_type_out) { *sqlsrv_php_type_out = static_cast(cached->type.typeinfo.type); } + } + return; + } - sqlsrv_phptype sqlsrv_php_type = sqlsrv_php_type_in; + sqlsrv_phptype sqlsrv_php_type = sqlsrv_php_type_in; - SQLLEN sql_field_type = 0; - SQLLEN sql_field_len = 0; + SQLLEN sql_field_type = 0; + SQLLEN sql_field_len = 0; - // Make sure that the statement was executed and not just prepared. - CHECK_CUSTOM_ERROR( !stmt->executed, stmt, SQLSRV_ERROR_STATEMENT_NOT_EXECUTED ) { - throw core::CoreException(); - } + // Make sure that the statement was executed and not just prepared. + CHECK_CUSTOM_ERROR( !stmt->executed, stmt, SQLSRV_ERROR_STATEMENT_NOT_EXECUTED ) { + throw core::CoreException(); + } - // if the field is to be cached, and this field is being retrieved out of order, cache prior fields so they - // may also be retrieved. - if( cache_field && (field_index - stmt->last_field_index ) >= 2 ) { + // if the field is to be cached, and this field is being retrieved out of order, cache prior fields so they + // may also be retrieved. + if( cache_field && (field_index - stmt->last_field_index ) >= 2 ) { sqlsrv_phptype invalid; invalid.typeinfo.type = SQLSRV_PHPTYPE_INVALID; for( int i = stmt->last_field_index + 1; i < field_index; ++i ) { @@ -997,44 +1014,46 @@ void core_sqlsrv_get_field( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT field_i efree( field_value ); field_value = NULL; *field_len = 0; - } - } - } + } + } + } - // If the php type was not specified set the php type to be the default type. - if( sqlsrv_php_type.typeinfo.type == SQLSRV_PHPTYPE_INVALID ) { + // If the php type was not specified set the php type to be the default type. + if (sqlsrv_php_type.typeinfo.type == SQLSRV_PHPTYPE_INVALID) { + SQLSRV_ASSERT(stmt->current_meta_data.size() > field_index, "core_sqlsrv_get_field - meta data vector not in sync" ); + sql_field_type = stmt->current_meta_data[field_index]->field_type; + if (stmt->current_meta_data[field_index]->field_precision > 0) { + sql_field_len = stmt->current_meta_data[field_index]->field_precision; + } + else { + sql_field_len = stmt->current_meta_data[field_index]->field_size; + } - // Get the SQL type of the field. - core::SQLColAttributeW( stmt, field_index + 1, SQL_DESC_CONCISE_TYPE, NULL, 0, NULL, &sql_field_type TSRMLS_CC ); + // Get the corresponding php type from the sql type. + sqlsrv_php_type = stmt->sql_type_to_php_type(static_cast(sql_field_type), static_cast(sql_field_len), prefer_string); + } - // Get the length of the field. - core::SQLColAttributeW( stmt, field_index + 1, SQL_DESC_LENGTH, NULL, 0, NULL, &sql_field_len TSRMLS_CC ); + // Verify that we have an acceptable type to convert. + CHECK_CUSTOM_ERROR( !is_valid_sqlsrv_phptype( sqlsrv_php_type ), stmt, SQLSRV_ERROR_INVALID_TYPE ) { + throw core::CoreException(); + } - // Get the corresponding php type from the sql type. - sqlsrv_php_type = stmt->sql_type_to_php_type( static_cast( sql_field_type ), static_cast( sql_field_len ), prefer_string ); - } + if( sqlsrv_php_type_out != NULL ) + *sqlsrv_php_type_out = static_cast( sqlsrv_php_type.typeinfo.type ); - // Verify that we have an acceptable type to convert. - CHECK_CUSTOM_ERROR( !is_valid_sqlsrv_phptype( sqlsrv_php_type ), stmt, SQLSRV_ERROR_INVALID_TYPE ) { - throw core::CoreException(); - } + // Retrieve the data + core_get_field_common( stmt, field_index, sqlsrv_php_type, field_value, field_len TSRMLS_CC ); - if( sqlsrv_php_type_out != NULL ) - *sqlsrv_php_type_out = static_cast( sqlsrv_php_type.typeinfo.type ); + // if the user wants us to cache the field, we'll do it + if( cache_field ) { + field_cache cache( field_value, *field_len, sqlsrv_php_type ); + core::sqlsrv_zend_hash_index_update_mem( *stmt, Z_ARRVAL( stmt->field_cache ), field_index, &cache, sizeof(field_cache) TSRMLS_CC ); + } + } - // Retrieve the data - core_get_field_common( stmt, field_index, sqlsrv_php_type, field_value, field_len TSRMLS_CC ); - - // if the user wants us to cache the field, we'll do it - if( cache_field ) { - field_cache cache( field_value, *field_len, sqlsrv_php_type ); - core::sqlsrv_zend_hash_index_update_mem( *stmt, Z_ARRVAL( stmt->field_cache ), field_index, &cache, sizeof(field_cache) TSRMLS_CC ); - } - } - - catch( core::CoreException& e ) { - throw e; - } + catch( core::CoreException& e ) { + throw e; + } } // core_sqlsrv_has_any_result @@ -1253,6 +1272,27 @@ void core_sqlsrv_set_query_timeout( _Inout_ sqlsrv_stmt* stmt, _In_ long timeout } } +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_DECIMAL_PLACES) { + 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->decimal_places = static_cast(decimal_places); + } + catch( core::CoreException& ) { + throw; + } +} + void core_sqlsrv_set_send_at_exec( _Inout_ sqlsrv_stmt* stmt, _In_ zval* value_z TSRMLS_DC ) { TSRMLS_C; @@ -1293,31 +1333,36 @@ bool core_sqlsrv_send_stream_packet( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) php_stream* param_stream = NULL; core::sqlsrv_php_stream_from_zval_no_verify( *stmt, param_stream, stmt->current_stream.stream_z TSRMLS_CC ); - // if we're at the end, then release our current parameter - if( php_stream_eof( param_stream )) { - // if no data was actually sent prior, then send a NULL - if( stmt->current_stream_read == 0 ) { - // send an empty string, which is what a 0 length does. - char buff[1]; // temp storage to hand to SQLPutData - core::SQLPutData( stmt, buff, 0 TSRMLS_CC ); + // if we're at the end, then reset both current_stream and current_stream_read + if (php_stream_eof(param_stream)) { + // yet return to the very beginning of param_stream since SQLParamData() may ask for the same data again + int ret = php_stream_seek(param_stream, 0, SEEK_SET); + if (ret != 0) { + LOG(SEV_ERROR, "PHP stream: stream seek failed."); + throw core::CoreException(); } - stmt->current_stream = sqlsrv_stream( NULL, SQLSRV_ENCODING_CHAR ); + stmt->current_stream = sqlsrv_stream(NULL, SQLSRV_ENCODING_CHAR); stmt->current_stream_read = 0; } // 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] = {'\0'}; - std::size_t buffer_size = sizeof( buffer ) - 3; // -3 to preserve enough space for a cut off UTF-8 character + 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 ); - if (read > UINT_MAX) - { - LOG(SEV_ERROR, "PHP stream: buffer length exceeded."); - throw core::CoreException(); - } + if (read > UINT_MAX) + { + LOG(SEV_ERROR, "PHP stream: buffer length exceeded."); + throw core::CoreException(); + } stmt->current_stream_read += static_cast( read ); - if( read > 0 ) { + if (read == 0) { + // send an empty string, which is what a 0 length does. + char buff[1]; // temp storage to hand to SQLPutData + core::SQLPutData(stmt, buff, 0 TSRMLS_CC); + } + else if (read > 0) { // if this is a UTF-8 stream, then we will use the UTF-8 encoding to determine if we're in the middle of a character // then read in the appropriate number more bytes and then retest the string. This way we try at most to convert it // twice. @@ -1329,8 +1374,8 @@ bool core_sqlsrv_send_stream_packet( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) // expansion of 2x the UTF-8 size. 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 + DWORD last_error_code = ERROR_SUCCESS; + // buffer_size is the # of wchars. Since it set to stmt->param_buffer_size / 2, this is accurate #ifndef _WIN32 int wsize = SystemLocale::ToUtf16Strict( stmt->current_stream.encoding, buffer, static_cast(read), wbuffer, wbuffer_size, &last_error_code ); #else @@ -1338,7 +1383,7 @@ bool core_sqlsrv_send_stream_packet( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) last_error_code = GetLastError(); #endif // !_WIN32 - if( wsize == 0 && last_error_code == ERROR_NO_UNICODE_TRANSLATION ) { + if( wsize == 0 && last_error_code == ERROR_NO_UNICODE_TRANSLATION ) { // this will calculate how many bytes were cut off from the last UTF-8 character and read that many more // in, then reattempt the conversion. If it fails the second time, then an error is returned. @@ -1415,6 +1460,21 @@ 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 ) +{ + 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 // that will alter the statement and cancel any retrieval of data from a stream. void close_active_stream( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) @@ -1441,7 +1501,7 @@ void close_active_stream( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) namespace { -bool is_streamable_type( _In_ SQLLEN sql_type ) +bool is_streamable_type( _In_ SQLSMALLINT sql_type ) { switch( sql_type ) { case SQL_CHAR: @@ -1460,6 +1520,25 @@ bool is_streamable_type( _In_ SQLLEN sql_type ) return false; } +bool is_a_numeric_type(_In_ SQLSMALLINT sql_type) +{ + switch (sql_type) { + case SQL_BIGINT: + case SQL_BIT: + case SQL_INTEGER: + case SQL_SMALLINT: + case SQL_TINYINT: + case SQL_FLOAT: + case SQL_DOUBLE: + case SQL_REAL: + case SQL_DECIMAL: + case SQL_NUMERIC: + return true; + } + + return false; +} + void calc_string_size( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT field_index, _In_ SQLLEN sql_type, _Inout_ SQLLEN& size TSRMLS_DC ) { try { @@ -1693,12 +1772,10 @@ void core_get_field_common( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT field_i { php_stream* stream = NULL; sqlsrv_stream* ss = NULL; - SQLLEN sql_type; + SQLSMALLINT sql_type; - SQLRETURN r = SQLColAttributeW( stmt->handle(), field_index + 1, SQL_DESC_TYPE, NULL, 0, NULL, &sql_type ); - CHECK_SQL_ERROR_OR_WARNING( r, stmt ) { - throw core::CoreException(); - } + SQLSRV_ASSERT(stmt->current_meta_data.size() > field_index, "core_get_field_common - meta data vector not in sync" ); + sql_type = stmt->current_meta_data[field_index]->field_type; CHECK_CUSTOM_ERROR( !is_streamable_type( sql_type ), stmt, SQLSRV_ERROR_STREAMABLE_TYPES_ONLY ) { throw core::CoreException(); @@ -1796,23 +1873,26 @@ bool convert_input_param_to_utf16( _In_ zval* input_param_z, _Inout_ zval* conve std::size_t buffer_len = Z_STRLEN_P( input_param_z ); int wchar_size; - if (buffer_len > INT_MAX) - { - LOG(SEV_ERROR, "Convert input parameter to utf16: buffer length exceeded."); - throw core::CoreException(); - } + if (buffer_len > INT_MAX) + { + LOG(SEV_ERROR, "Convert input parameter to utf16: buffer length exceeded."); + throw core::CoreException(); + } // if the string is empty, then just return that the conversion succeeded as // MultiByteToWideChar will "fail" on an empty string. if( buffer_len == 0 ) { - core::sqlsrv_zval_stringl( converted_param_z, "", 0 ); + core::sqlsrv_zval_stringl( converted_param_z, "", 0 ); return true; } - // if the parameter is an input parameter, calc the size of the necessary buffer from the length of the string #ifndef _WIN32 - wchar_size = SystemLocale::ToUtf16Strict( CP_UTF8, reinterpret_cast( buffer ), static_cast( buffer_len ), NULL, 0 ); + // Declare wchar_size to be the largest possible number of UTF-16 characters after + // conversion, to avoid the performance penalty of calling ToUtf16 + wchar_size = buffer_len; #else + // Calculate the size of the necessary buffer from the length of the string - + // no performance penalty because MultiByteToWidechar is highly optimised wchar_size = MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, reinterpret_cast( buffer ), static_cast( buffer_len ), NULL, 0 ); #endif // !_WIN32 @@ -1824,17 +1904,18 @@ bool convert_input_param_to_utf16( _In_ zval* input_param_z, _Inout_ zval* conve wbuffer = reinterpret_cast( sqlsrv_malloc( (wchar_size + 1) * sizeof( SQLWCHAR ) )); // convert the utf-8 string to a wchar string in the new buffer #ifndef _WIN32 - int r = SystemLocale::ToUtf16Strict( CP_UTF8, reinterpret_cast( buffer ), static_cast( buffer_len ), wbuffer, wchar_size ); + int rc = SystemLocale::ToUtf16Strict( CP_UTF8, reinterpret_cast( buffer ), static_cast( buffer_len ), wbuffer, wchar_size ); #else - int r = MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, reinterpret_cast( buffer ), static_cast( buffer_len ), wbuffer, wchar_size ); + int rc = MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, reinterpret_cast( buffer ), static_cast( buffer_len ), wbuffer, wchar_size ); #endif // !_WIN32 // if there was a problem converting the string, then free the memory and return false - if( r == 0 ) { + if( rc == 0 ) { return false; } + wchar_size = rc; // 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(); @@ -1918,7 +1999,7 @@ void default_sql_type( _Inout_ sqlsrv_stmt* stmt, _In_opt_ SQLULEN paramno, _In_ _Out_ SQLSMALLINT& sql_type TSRMLS_DC ) { sql_type = SQL_UNKNOWN_TYPE; - int php_type = Z_TYPE_P(param_z); + int php_type = Z_TYPE_P(param_z); switch( php_type ) { case IS_NULL: @@ -2058,9 +2139,146 @@ void field_cache_dtor( _Inout_ zval* data_z ) { sqlsrv_free( cache->value ); } - sqlsrv_free( cache ); + sqlsrv_free( cache ); } +// 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_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: 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 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('.'); + + // The decimal dot is not found, simply return + if (pos == std::string::npos) { + return; + } + + SQLSMALLINT num_decimals = decimals_places; + if (num_decimals > field_scale) { + num_decimals = field_scale; + } + + // We want the rounding to be consistent with php number_format(), http://php.net/manual/en/function.number-format.php + // as well as SQL Server Management studio, such that the least significant digit will be rounded up if it is + // followed by 5 or above. + + bool isNegative = false; + + // If negative, remove the minus sign for now so as not to complicate the rounding process + if (str[0] == '-') { + isNegative = true; + std::ostringstream oss; + oss << str.substr(1); + str = oss.str(); + pos = str.find_first_of('.'); + } + + // Adds the leading zero if not exists + if (pos == 0) { + std::ostringstream oss; + oss << '0' << str; + str = oss.str(); + pos++; + } + + 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 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()) { + 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); + } + } + + size_t len = str.length(); + str.copy(field_value, len); + field_value[len] = '\0'; + *field_len = len; +} // To be called after all results are processed. ODBC and SQL Server do not guarantee that all output // parameters will be present until all results are processed (since output parameters can depend on results @@ -2074,13 +2292,13 @@ void finalize_output_parameters( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) return; HashTable* params_ht = Z_ARRVAL( stmt->output_params ); - zend_ulong index = -1; - zend_string* key = NULL; - void* output_param_temp = NULL; + zend_ulong index = -1; + zend_string* key = NULL; + void* output_param_temp = NULL; - ZEND_HASH_FOREACH_KEY_PTR( params_ht, index, key, output_param_temp ) { - sqlsrv_output_param* output_param = static_cast( output_param_temp ); - zval* value_z = Z_REFVAL_P( output_param->param_z ); + ZEND_HASH_FOREACH_KEY_PTR( params_ht, index, key, output_param_temp ) { + sqlsrv_output_param* output_param = static_cast( output_param_temp ); + zval* value_z = Z_REFVAL_P( output_param->param_z ); switch( Z_TYPE_P( value_z )) { case IS_STRING: { @@ -2127,22 +2345,40 @@ void finalize_output_parameters( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) str_len = output_param->original_buffer_len - null_size; } - // if it's not in the 8 bit encodings, then it's in UTF-16 - if( output_param->encoding != SQLSRV_ENCODING_CHAR && output_param->encoding != SQLSRV_ENCODING_BINARY ) { - bool converted = convert_zval_string_from_utf16(output_param->encoding, value_z, str_len); - CHECK_CUSTOM_ERROR( !converted, stmt, SQLSRV_ERROR_OUTPUT_PARAM_ENCODING_TRANSLATE, get_last_error_message()) { - throw core::CoreException(); - } - } - else if( output_param->encoding == SQLSRV_ENCODING_BINARY && str_len < output_param->original_buffer_len ) { + if (output_param->encoding == SQLSRV_ENCODING_BINARY) { // 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'; + if (str_len < output_param->original_buffer_len) { + str[str_len] = '\0'; + } core::sqlsrv_zval_stringl(value_z, str, str_len); } else { - core::sqlsrv_zval_stringl(value_z, str, str_len); + param_meta_data metaData = output_param->getMetaData(); + + if (output_param->encoding != SQLSRV_ENCODING_CHAR) { + char* outString = NULL; + SQLLEN outLen = 0; + bool result = convert_string_from_utf16(output_param->encoding, reinterpret_cast(str), int(str_len / sizeof(SQLWCHAR)), &outString, outLen ); + CHECK_CUSTOM_ERROR(!result, stmt, SQLSRV_ERROR_OUTPUT_PARAM_ENCODING_TRANSLATE, get_last_error_message()) { + throw core::CoreException(); + } + + 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->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); + } } } break; @@ -2183,7 +2419,7 @@ void finalize_output_parameters( _Inout_ sqlsrv_stmt* stmt TSRMLS_DC ) DIE( "Illegal or unknown output parameter type. This should have been caught in core_sqlsrv_bind_parameter." ); break; } - value_z = NULL; + value_z = NULL; } ZEND_HASH_FOREACH_END(); // empty the hash table since it's been processed @@ -2196,7 +2432,7 @@ void get_field_as_string( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT field_ind { SQLRETURN r; SQLSMALLINT c_type; - SQLLEN sql_field_type = 0; + SQLSMALLINT sql_field_type = 0; SQLSMALLINT extra = 0; SQLLEN field_len_temp = 0; SQLLEN sql_display_size = 0; @@ -2208,9 +2444,30 @@ void get_field_as_string( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT field_ind DEBUG_SQLSRV_ASSERT( sqlsrv_php_type.typeinfo.type == SQLSRV_PHPTYPE_STRING, "Type should be SQLSRV_PHPTYPE_STRING in get_field_as_string" ); + col_cache* cached = NULL; + if ( NULL != ( cached = static_cast< col_cache* >( zend_hash_index_find_ptr( Z_ARRVAL( stmt->col_cache ), static_cast< zend_ulong >( field_index ))))) { + sql_field_type = cached->sql_type; + sql_display_size = cached->display_size; + } + else { + SQLSRV_ASSERT(stmt->current_meta_data.size() > field_index, "get_field_as_string - meta data vector not in sync" ); + sql_field_type = stmt->current_meta_data[field_index]->field_type; + + // Calculate the field size. + calc_string_size( stmt, field_index, sql_field_type, sql_display_size TSRMLS_CC ); + + col_cache cache( sql_field_type, sql_display_size ); + core::sqlsrv_zend_hash_index_update_mem( *stmt, Z_ARRVAL( stmt->col_cache ), field_index, &cache, sizeof( col_cache ) TSRMLS_CC ); + } + + // Determine the correct encoding if( sqlsrv_php_type.typeinfo.encoding == SQLSRV_ENCODING_DEFAULT ) { sqlsrv_php_type.typeinfo.encoding = stmt->conn->encoding(); } + // For numbers, no need to convert + if (is_a_numeric_type(sql_field_type)) { + sqlsrv_php_type.typeinfo.encoding = SQLSRV_ENCODING_CHAR; + } // Set the C type and account for null characters at the end of the data. switch( sqlsrv_php_type.typeinfo.encoding ) { @@ -2228,22 +2485,6 @@ void get_field_as_string( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT field_ind break; } - col_cache* cached = NULL; - if ( NULL != ( cached = static_cast< col_cache* >( zend_hash_index_find_ptr( Z_ARRVAL( stmt->col_cache ), static_cast< zend_ulong >( field_index ))))) { - sql_field_type = cached->sql_type; - sql_display_size = cached->display_size; - } - else { - // Get the SQL type of the field. unixODBC 2.3.1 requires wide calls to support pooling - core::SQLColAttributeW( stmt, field_index + 1, SQL_DESC_CONCISE_TYPE, NULL, 0, NULL, &sql_field_type TSRMLS_CC ); - - // Calculate the field size. - calc_string_size( stmt, field_index, sql_field_type, sql_display_size TSRMLS_CC ); - - col_cache cache( sql_field_type, sql_display_size ); - core::sqlsrv_zend_hash_index_update_mem( *stmt, Z_ARRVAL( stmt->col_cache ), field_index, &cache, sizeof( col_cache ) TSRMLS_CC ); - } - // if this is a large type, then read the first few bytes to get the actual length from SQLGetData if( sql_display_size == 0 || sql_display_size == INT_MAX || sql_display_size == INT_MAX >> 1 || sql_display_size == UINT_MAX - 1 ) { @@ -2402,6 +2643,12 @@ void get_field_as_string( _Inout_ sqlsrv_stmt* stmt, _In_ SQLUSMALLINT field_ind throw core::CoreException(); } } + + 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 ) else { @@ -2569,24 +2816,24 @@ void resize_output_buffer_if_necessary( _Inout_ sqlsrv_stmt* stmt, _Inout_ zval* // allocate enough space to ALWAYS include the NULL regardless of the type being retrieved since // we set the last byte(s) to be NULL to avoid the debug build warning from the Zend engine about // not having a NULL terminator on a string. - zend_string* param_z_string = zend_string_realloc( Z_STR_P(param_z), expected_len, 0 ); + zend_string* param_z_string = zend_string_realloc( Z_STR_P(param_z), expected_len, 0 ); // A zval string len doesn't include the null. This calculates the length it should be // regardless of whether the ODBC type contains the NULL or not. // null terminate the string to avoid a warning in debug PHP builds - ZSTR_VAL(param_z_string)[without_null_len] = '\0'; - ZVAL_NEW_STR(param_z, param_z_string); + ZSTR_VAL(param_z_string)[without_null_len] = '\0'; + ZVAL_NEW_STR(param_z, param_z_string); - // buffer_len is the length passed to SQLBindParameter. It must contain the space for NULL in the - // buffer when retrieving anything but SQLSRV_ENC_BINARY/SQL_C_BINARY - buffer_len = Z_STRLEN_P(param_z) - buffer_null_extra; + // buffer_len is the length passed to SQLBindParameter. It must contain the space for NULL in the + // buffer when retrieving anything but SQLSRV_ENC_BINARY/SQL_C_BINARY + buffer_len = Z_STRLEN_P(param_z) - buffer_null_extra; - // Zend string length doesn't include the null terminator - ZSTR_LEN(Z_STR_P(param_z)) -= elem_size; + // Zend string length doesn't include the null terminator + ZSTR_LEN(Z_STR_P(param_z)) -= elem_size; } - buffer = Z_STRVAL_P(param_z); + buffer = Z_STRVAL_P(param_z); // 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, @@ -2770,7 +3017,7 @@ void sqlsrv_output_param_dtor( _Inout_ zval* data ) { sqlsrv_output_param *output_param = static_cast( Z_PTR_P( data )); zval_ptr_dtor( output_param->param_z ); // undo the reference to the string we will no longer hold - sqlsrv_free( output_param ); + sqlsrv_free( output_param ); } // called by Zend for each stream in the sqlsrv_stmt::param_streams hash table when it is cleaned/destroyed @@ -2778,7 +3025,7 @@ void sqlsrv_stream_dtor( _Inout_ zval* data ) { sqlsrv_stream* stream_encoding = static_cast( Z_PTR_P( data )); zval_ptr_dtor( stream_encoding->stream_z ); // undo the reference to the stream we will no longer hold - sqlsrv_free( stream_encoding ); + sqlsrv_free( stream_encoding ); } } diff --git a/source/shared/core_stream.cpp b/source/shared/core_stream.cpp index e4e9e485..826fcf2e 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License diff --git a/source/shared/core_util.cpp b/source/shared/core_util.cpp index ca097a24..4aa2b37f 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -91,25 +91,6 @@ bool convert_string_from_utf16_inplace( _In_ SQLSRV_ENCODING encoding, _Inout_up return result; } -bool convert_zval_string_from_utf16( _In_ SQLSRV_ENCODING encoding, _Inout_ zval* value_z, _Inout_ SQLLEN& len) -{ - char* string = Z_STRVAL_P(value_z); - - if( validate_string(string, len)) { - return true; - } - - char* outString = NULL; - SQLLEN outLen = 0; - bool result = convert_string_from_utf16( encoding, reinterpret_cast(string), int(len / sizeof(SQLWCHAR)), &outString, outLen ); - if( result ) { - core::sqlsrv_zval_stringl( value_z, outString, outLen ); - sqlsrv_free( outString ); - len = outLen; - } - return result; -} - bool validate_string( _In_ char* string, _In_ SQLLEN& len ) { SQLSRV_ASSERT(string != NULL, "String must be specified"); @@ -146,10 +127,13 @@ bool convert_string_from_utf16( _In_ SQLSRV_ENCODING encoding, _In_reads_bytes_( flags = WC_ERR_INVALID_CHARS; } - // calculate the number of characters needed #ifndef _WIN32 - cchOutLen = SystemLocale::FromUtf16Strict( encoding, inString, cchInLen, NULL, 0 ); + // Allocate enough space to hold the largest possible number of bytes for UTF-8 conversion + // instead of calling FromUtf16, for performance reasons + cchOutLen = 4*cchInLen; #else + // Calculate the number of output bytes required - no performance hit here because + // WideCharToMultiByte is highly optimised cchOutLen = WideCharToMultiByte( encoding, flags, inString, cchInLen, NULL, 0, NULL, NULL ); @@ -161,9 +145,10 @@ bool convert_string_from_utf16( _In_ SQLSRV_ENCODING encoding, _In_reads_bytes_( // Create a buffer to fit the encoded string char* newString = reinterpret_cast( sqlsrv_malloc( cchOutLen + 1 /* NULL char*/ )); + memset(newString, '\0', cchOutLen+1); #ifndef _WIN32 - int rc = SystemLocale::FromUtf16( encoding, inString, cchInLen, newString, static_cast(cchOutLen)); + int rc = SystemLocale::FromUtf16Strict( encoding, inString, cchInLen, newString, static_cast(cchOutLen)); #else int rc = WideCharToMultiByte( encoding, flags, inString, cchInLen, newString, static_cast(cchOutLen), NULL, NULL ); #endif // !_WIN32 @@ -172,9 +157,13 @@ bool convert_string_from_utf16( _In_ SQLSRV_ENCODING encoding, _In_reads_bytes_( sqlsrv_free( newString ); return false; } + char* newString2 = reinterpret_cast( sqlsrv_malloc( rc + 1 /* NULL char*/ )); + memset(newString2, '\0', rc+1); + memcpy_s(newString2, rc, newString, rc); + sqlsrv_free( newString ); - *outString = newString; - newString[cchOutLen] = '\0'; // null terminate the encoded string + *outString = newString2; + cchOutLen = rc; return true; } diff --git a/source/shared/globalization.h b/source/shared/globalization.h index 98619d61..f3545de2 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -261,6 +261,8 @@ class EncodingConverter return 0; } } + //if a shift sequence is encountered, we need to advance output buffer + iconv_ret = iconv( m_pCvtCache->GetIConv(), NULL, NULL, &dest.m_pBytes, &dest.m_nBytesLeft ); } return cchDest - (dest.m_nBytesLeft / sizeof(DestType)); diff --git a/source/shared/interlockedatomic.h b/source/shared/interlockedatomic.h index b8c04643..953c2580 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 6977ff22..ba5087b5 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 6aa43fb0..76e2eda8 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 79bd860e..6328f1fb 100644 --- a/source/shared/localization.hpp +++ b/source/shared/localization.hpp @@ -3,7 +3,7 @@ // // Contents: Contains portable classes for localization // -// Microsoft Drivers 5.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -169,8 +169,14 @@ public: static size_t FromUtf16Strict(UINT destCodePage, const WCHAR * src, SSIZE_T cchSrc, __out_ecount_opt(cchDest) char * dest, size_t cchDest, bool * pHasDataLoss = NULL, DWORD * pErrorCode = NULL); + // CP1252 to UTF16 conversion which does not involve iconv + static size_t CP1252ToUtf16( const char *src, SSIZE_T cchSrc, WCHAR *dest, size_t cchDest, DWORD *pErrorCode ); - + // UTF8/16 conversion which does not involve iconv + static size_t Utf8To16( const char *src, SSIZE_T cchSrc, WCHAR *dest, size_t cchDest, DWORD *pErrorCode ); + static size_t Utf8From16( const WCHAR *src, SSIZE_T cchSrc, char *dest, size_t cchDest, DWORD *pErrorCode ); + static size_t Utf8To16Strict( const char *src, SSIZE_T cchSrc, WCHAR *dest, size_t cchDest, DWORD *pErrorCode ); + static size_t Utf8From16Strict( const WCHAR *src, SSIZE_T cchSrc, char *dest, size_t cchDest, DWORD *pErrorCode ); // ----------------------------------------------------------------------- // Public Member Functions diff --git a/source/shared/localizationimpl.cpp b/source/shared/localizationimpl.cpp index 669462ab..38ee64b7 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -336,9 +336,300 @@ const SystemLocale & SystemLocale::Singleton() return s_Default; } + +// Convert CP1252 to UTF-16 without requiring iconv or taking a lock. +// This is trivial because, except for the 80-9F range, CP1252 bytes +// directly map to the corresponding UTF-16 codepoint. +size_t SystemLocale::CP1252ToUtf16( const char *src, SSIZE_T cchSrc, WCHAR *dest, size_t cchDest, DWORD *pErrorCode ) +{ + const static WCHAR s_1252Map[] = + { + 0x20AC, 0x003F, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x003F, 0x017D, 0x003F, + 0x003F, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x003F, 0x017E, 0x0178 + }; + const unsigned char *usrc = reinterpret_cast(src); + const unsigned char *srcEnd = usrc + cchSrc; + const WCHAR *destEnd = dest + cchDest; + + while(usrc < srcEnd && dest < destEnd) + { + DWORD ucode = *usrc++; + *dest++ = (ucode <= 127 || ucode >= 160) ? ucode : s_1252Map[ucode - 128]; + } + pErrorCode && (*pErrorCode = (dest == destEnd && usrc != srcEnd) ? ERROR_INSUFFICIENT_BUFFER : ERROR_SUCCESS); + return cchDest - (destEnd - dest); +} + +// Convert UTF-8 to UTF-16 without requiring iconv or taking a lock. +// 0abcdefg -> 0abcdefg 00000000 +// 110abcde 10fghijk -> defghijk 00000abc +// 1110abcd 10efghij 10klmnop -> ijklmnop abcdefgh +// 11110abc 10defghi 10jklmno 10pqrstu -> cdfghijk 110110ab nopqrstu 11011lm +size_t SystemLocale::Utf8To16( const char *src, SSIZE_T cchSrc, WCHAR *dest, size_t cchDest, DWORD *pErrorCode ) +{ + const unsigned char *usrc = reinterpret_cast(src); + const unsigned char *srcEnd = usrc + cchSrc; + const WCHAR *destEnd = dest + cchDest; + DWORD dummyError; + if (!pErrorCode) + { + pErrorCode = &dummyError; + } + *pErrorCode = 0; + + while(usrc < srcEnd && dest < destEnd) + { + DWORD ucode = *usrc++; + if(ucode <= 127) // Most common case for ASCII + { + *dest++ = ucode; + } + else if(ucode < 0xC0) // unexpected trailing byte 10xxxxxx + { + goto Invalid; + } + else if(ucode < 0xE0) // 110abcde 10fghijk + { + if (usrc >= srcEnd || *usrc < 0x80 || *usrc > 0xBF || + (*dest = (ucode & 0x1F)<<6 | (*usrc++ & 0x3F)) < 0x80) + { + *dest = 0xFFFD; + } + dest++; + } + else if(ucode < 0xF0) // 1110abcd 10efghij 10klmnop + { + if (usrc >= srcEnd) + { + goto Invalid; + } + DWORD c1 = *usrc; + if (c1 < 0x80 || c1 > 0xBF) + { + goto Invalid; + } + usrc++; + if (usrc >= srcEnd) + { + goto Invalid; + } + DWORD c2 = *usrc; + if (c2 < 0x80 || c2 > 0xBF) + { + goto Invalid; + } + usrc++; + ucode = (ucode&15)<<12 | (c1&0x3F)<<6 | (c2&0x3F); + if (ucode < 0x800 || ucode >= 0xD800 && ucode <= 0xDFFF) + { + goto Invalid; + } + *dest++ = ucode; + } + else if(ucode < 0xF8) // 11110abc 10defghi 10jklmno 10pqrstu + { + if (usrc >= srcEnd) + { + goto Invalid; + } + DWORD c1 = *usrc; + if (c1 < 0x80 || c1 > 0xBF) + { + goto Invalid; + } + usrc++; + if (usrc >= srcEnd) + { + goto Invalid; + } + DWORD c2 = *usrc; + if (c2 < 0x80 || c2 > 0xBF) + { + goto Invalid; + } + usrc++; + if (usrc >= srcEnd) + { + goto Invalid; + } + DWORD c3 = *usrc; + if (c3 < 0x80 || c3 > 0xBF) + { + goto Invalid; + } + usrc++; + ucode = (ucode&7)<<18 | (c1&0x3F)<<12 | (c2&0x3F)<<6 | (c3&0x3F); + + if (ucode < 0x10000 // overlong encoding + || ucode > 0x10FFFF // exceeds Unicode range + || ucode >= 0xD800 && ucode <= 0xDFFF) // surrogate pairs + { + goto Invalid; + } + if (dest >= destEnd - 1) + { + *pErrorCode = ERROR_INSUFFICIENT_BUFFER; + return cchDest - (destEnd - dest); + } + ucode -= 0x10000; + // Lead surrogate + *dest++ = 0xD800 + (ucode >> 10); + // Trail surrogate + *dest++ = 0xDC00 + (ucode & 0x3FF); + } + else // invalid + { + Invalid: + *dest++ = 0xFFFD; + } + } + if (!*pErrorCode) + { + *pErrorCode = (dest == destEnd && usrc != srcEnd) ? ERROR_INSUFFICIENT_BUFFER : ERROR_SUCCESS; + } + return cchDest - (destEnd - dest); +} + +size_t SystemLocale::Utf8To16Strict( const char *src, SSIZE_T cchSrc, WCHAR *dest, size_t cchDest, DWORD *pErrorCode ) +{ + const unsigned char *usrc = reinterpret_cast(src); + const unsigned char *srcEnd = usrc + cchSrc; + const WCHAR *destEnd = dest + cchDest; + DWORD dummyError; + if (!pErrorCode) + { + pErrorCode = &dummyError; + } + *pErrorCode = 0; + + while(usrc < srcEnd && dest < destEnd) + { + DWORD ucode = *usrc++; + if(ucode <= 127) // Most common case for ASCII + { + *dest++ = ucode; + } + else if(ucode < 0xC0) // unexpected trailing byte 10xxxxxx + { + goto Invalid; + } + else if(ucode < 0xE0) // 110abcde 10fghijk + { + if (usrc >= srcEnd || *usrc < 0x80 || *usrc > 0xBF || + (*dest = (ucode & 0x1F)<<6 | (*usrc++ & 0x3F)) < 0x80) + { + goto Invalid; + } + dest++; + } + else if(ucode < 0xF0) // 1110abcd 10efghij 10klmnop + { + if (usrc >= srcEnd) + { + goto Invalid; + } + DWORD c1 = *usrc; + if (c1 < 0x80 || c1 > 0xBF) + { + goto Invalid; + } + usrc++; + if (usrc >= srcEnd) + { + goto Invalid; + } + DWORD c2 = *usrc; + if (c2 < 0x80 || c2 > 0xBF) + { + goto Invalid; + } + usrc++; + ucode = (ucode&15)<<12 | (c1&0x3F)<<6 | (c2&0x3F); + if (ucode < 0x800 || ucode >= 0xD800 && ucode <= 0xDFFF) + { + goto Invalid; + } + *dest++ = ucode; + } + else if(ucode < 0xF8) // 11110abc 10defghi 10jklmno 10pqrstu + { + if (usrc >= srcEnd) + { + goto Invalid; + } + DWORD c1 = *usrc; + if (c1 < 0x80 || c1 > 0xBF) + { + goto Invalid; + } + usrc++; + if (usrc >= srcEnd) + { + goto Invalid; + } + DWORD c2 = *usrc; + if (c2 < 0x80 || c2 > 0xBF) + { + goto Invalid; + } + usrc++; + if (usrc >= srcEnd) + { + goto Invalid; + } + DWORD c3 = *usrc; + if (c3 < 0x80 || c3 > 0xBF) + { + goto Invalid; + } + usrc++; + ucode = (ucode&7)<<18 | (c1&0x3F)<<12 | (c2&0x3F)<<6 | (c3&0x3F); + + if (ucode < 0x10000 // overlong encoding + || ucode > 0x10FFFF // exceeds Unicode range + || ucode >= 0xD800 && ucode <= 0xDFFF) // surrogate pairs + { + goto Invalid; + } + if (dest >= destEnd - 1) + { + *pErrorCode = ERROR_INSUFFICIENT_BUFFER; + return cchDest - (destEnd - dest); + } + ucode -= 0x10000; + // Lead surrogate + *dest++ = 0xD800 + (ucode >> 10); + // Trail surrogate + *dest++ = 0xDC00 + (ucode & 0x3FF); + } + else // invalid + { + Invalid: + *pErrorCode = ERROR_NO_UNICODE_TRANSLATION; + return 0 ; + } + } + if (!*pErrorCode) + { + *pErrorCode = (dest == destEnd && usrc != srcEnd) ? ERROR_INSUFFICIENT_BUFFER : ERROR_SUCCESS; + } + return cchDest - (destEnd - dest); +} + size_t SystemLocale::ToUtf16( UINT srcCodePage, const char * src, SSIZE_T cchSrc, WCHAR * dest, size_t cchDest, DWORD * pErrorCode ) { srcCodePage = ExpandSpecialCP( srcCodePage ); + if ( dest ) + { + if ( srcCodePage == CP_UTF8 ) + { + return SystemLocale::Utf8To16( src, cchSrc < 0 ? (1+strlen(src)) : cchSrc, dest, cchDest, pErrorCode ); + } + else if ( srcCodePage == 1252 ) + { + return SystemLocale::CP1252ToUtf16( src, cchSrc < 0 ? (1+strlen(src)) : cchSrc, dest, cchDest, pErrorCode ); + } + } EncodingConverter cvt( CP_UTF16, srcCodePage ); if ( !cvt.Initialize() ) { @@ -354,6 +645,17 @@ size_t SystemLocale::ToUtf16( UINT srcCodePage, const char * src, SSIZE_T cchSrc size_t SystemLocale::ToUtf16Strict( UINT srcCodePage, const char * src, SSIZE_T cchSrc, WCHAR * dest, size_t cchDest, DWORD * pErrorCode ) { srcCodePage = ExpandSpecialCP( srcCodePage ); + if ( dest ) + { + if ( srcCodePage == CP_UTF8 ) + { + return SystemLocale::Utf8To16Strict( src, cchSrc < 0 ? (1+strlen(src)) : cchSrc, dest, cchDest, pErrorCode ); + } + else if ( srcCodePage == 1252 ) + { + return SystemLocale::CP1252ToUtf16( src, cchSrc < 0 ? (1+strlen(src)) : cchSrc, dest, cchDest, pErrorCode ); + } + } EncodingConverter cvt( CP_UTF16, srcCodePage ); if ( !cvt.Initialize() ) { @@ -366,9 +668,282 @@ size_t SystemLocale::ToUtf16Strict( UINT srcCodePage, const char * src, SSIZE_T return cvt.Convert( dest, cchDest, src, cchSrcActual, true, &hasLoss, pErrorCode ); } +size_t SystemLocale::Utf8From16( const WCHAR *src, SSIZE_T cchSrc, char *dest, size_t cchDest, DWORD *pErrorCode ) +{ + const WCHAR *srcEnd = src + cchSrc; + char *destEnd = dest + cchDest; + DWORD dummyError; + if (!pErrorCode) + { + pErrorCode = &dummyError; + } + *pErrorCode = 0; + + // null dest is a special mode to calculate the output size required. + if (!dest) + { + size_t cbOut = 0; + while (src < srcEnd) + { + DWORD wch = *src++; + if (wch < 128) // most common case. + { + cbOut++; + } + else if (wch < 0x800) // 127 to 2047: 2 bytes + { + cbOut += 2; + } + else if (wch < 0xD800 || wch > 0xDFFF) // 2048 to 55295 and 57344 to 65535: 3 bytes + { + cbOut += 3; + } + else if (wch < 0xDC00) // 65536 to end of Unicode: 4 bytes + { + if (src >= srcEnd) + { + cbOut += 3; // lone surrogate at end + } + else if (*src < 0xDC00 || *src > 0xDFFF) + { + cbOut += 3; // low surrogate not followed by high + } + else + { + cbOut += 4; + } + } + else // unexpected trail surrogate + { + cbOut += 3; + } + } + return cbOut; + } + while ( src < srcEnd && dest < destEnd ) + { + DWORD wch = *src++; + if (wch < 128) // most common case. + { + *dest++ = wch; + } + else if (wch < 0x800) // 127 to 2047: 2 bytes + { + if (destEnd - dest < 2) + { + *pErrorCode = ERROR_INSUFFICIENT_BUFFER; + return 0; + } + *dest++ = 0xC0 | (wch >> 6); + *dest++ = 0x80 | (wch & 0x3F); + } + else if (wch < 0xD800 || wch > 0xDFFF) // 2048 to 55295 and 57344 to 65535: 3 bytes + { + if (destEnd - dest < 3) + { + *pErrorCode = ERROR_INSUFFICIENT_BUFFER; + return 0; + } + *dest++ = 0xE0 | (wch >> 12); + *dest++ = 0x80 | (wch >> 6)&0x3F; + *dest++ = 0x80 | (wch &0x3F); + } + else if (wch < 0xDC00) // 65536 to end of Unicode: 4 bytes + { + if (src >= srcEnd) + { + *pErrorCode = ERROR_NO_UNICODE_TRANSLATION; // lone surrogate at end + if (destEnd - dest < 3) + { + *pErrorCode = ERROR_INSUFFICIENT_BUFFER; + return 0; + } + *dest++ = 0xEF; + *dest++ = 0xBF; + *dest++ = 0xBD; + continue; + } + if (*src < 0xDC00 || *src > 0xDFFF) + { + // low surrogate not followed by high + if (destEnd - dest < 3) + { + *pErrorCode = ERROR_INSUFFICIENT_BUFFER; + return 0; + } + *dest++ = 0xEF; + *dest++ = 0xBF; + *dest++ = 0xBD; + continue; + } + wch = 0x10000 + ((wch - 0xD800)<<10) + *src++ - 0xDC00; + if (destEnd - dest < 4) + { + *pErrorCode = ERROR_INSUFFICIENT_BUFFER; + return 0; + } + *dest++ = 0xF0 | (wch >> 18); + *dest++ = 0x80 | (wch >>12)&0x3F; + *dest++ = 0x80 | (wch >> 6)&0x3F; + *dest++ = 0x80 | wch&0x3F; + } + else // unexpected trail surrogate + { + *pErrorCode = ERROR_NO_UNICODE_TRANSLATION; // lone surrogate at end + if (destEnd - dest < 3) + { + *pErrorCode = ERROR_INSUFFICIENT_BUFFER; + return 0; + } + *dest++ = 0xEF; + *dest++ = 0xBF; + *dest++ = 0xBD; + } + } + if (!*pErrorCode) + { + *pErrorCode = (dest == destEnd && src != srcEnd) ? ERROR_INSUFFICIENT_BUFFER : ERROR_SUCCESS; + } + return *pErrorCode == ERROR_INSUFFICIENT_BUFFER ? 0 : cchDest - (destEnd - dest); +} + +size_t SystemLocale::Utf8From16Strict( const WCHAR *src, SSIZE_T cchSrc, char *dest, size_t cchDest, DWORD *pErrorCode ) +{ + const WCHAR *srcEnd = src + cchSrc; + char *destEnd = dest + cchDest; + DWORD dummyError; + if (!pErrorCode) + { + pErrorCode = &dummyError; + } + *pErrorCode = 0; + + // null dest is a special mode to calculate the output size required. + if (!dest) + { + size_t cbOut = 0; + while (src < srcEnd) + { + DWORD wch = *src++; + if (wch < 128) // most common case. + { + cbOut++; + } + else if (wch < 0x800) // 127 to 2047: 2 bytes + { + cbOut += 2; + } + else if (wch < 0xD800 || wch > 0xDFFF) // 2048 to 55295 and 57344 to 65535: 3 bytes + { + cbOut += 3; + } + else if (wch < 0xDC00) // 65536 to end of Unicode: 4 bytes + { + if (src >= srcEnd) + { + cbOut += 3; // lone surrogate at end + } + else if (*src < 0xDC00 || *src > 0xDFFF) + { + cbOut += 3; // low surrogate not followed by high + } + else + { + cbOut += 4; + } + } + else // unexpected trail surrogate + { + cbOut += 3; + } + } + return cbOut; + } + while ( src < srcEnd && dest < destEnd ) + { + DWORD wch = *src++; + if (wch < 128) // most common case. + { + *dest++ = wch; + } + else if (wch < 0x800) // 127 to 2047: 2 bytes + { + if (destEnd - dest < 2) + { + *pErrorCode = ERROR_INSUFFICIENT_BUFFER; + return 0; + } + *dest++ = 0xC0 | (wch >> 6); + *dest++ = 0x80 | (wch & 0x3F); + } + else if (wch < 0xD800 || wch > 0xDFFF) // 2048 to 55295 and 57344 to 65535: 3 bytes + { + if (destEnd - dest < 3) + { + *pErrorCode = ERROR_INSUFFICIENT_BUFFER; + return 0; + } + *dest++ = 0xE0 | (wch >> 12); + *dest++ = 0x80 | (wch >> 6)&0x3F; + *dest++ = 0x80 | (wch &0x3F); + } + else if (wch < 0xDC00) // 65536 to end of Unicode: 4 bytes + { + if (src >= srcEnd) + { + *pErrorCode = ERROR_NO_UNICODE_TRANSLATION; // lone surrogate at end + if (destEnd - dest < 3) + { + *pErrorCode = ERROR_INSUFFICIENT_BUFFER; + } + + return 0; + } + if (*src < 0xDC00 || *src > 0xDFFF) + { + *pErrorCode = ERROR_NO_UNICODE_TRANSLATION; // low surrogate not followed by high + if (destEnd - dest < 3) + { + *pErrorCode = ERROR_INSUFFICIENT_BUFFER; + } + return 0; + } + wch = 0x10000 + ((wch - 0xD800)<<10) + *src++ - 0xDC00; + if (destEnd - dest < 4) + { + *pErrorCode = ERROR_INSUFFICIENT_BUFFER; + return 0; + } + *dest++ = 0xF0 | (wch >> 18); + *dest++ = 0x80 | (wch >>12)&0x3F; + *dest++ = 0x80 | (wch >> 6)&0x3F; + *dest++ = 0x80 | wch&0x3F; + } + else // unexpected trail surrogate + { + *pErrorCode = ERROR_NO_UNICODE_TRANSLATION; // lone surrogate at end + if (destEnd - dest < 3) + { + *pErrorCode = ERROR_INSUFFICIENT_BUFFER; + } + return 0; + } + } + if (!*pErrorCode) + { + *pErrorCode = (dest == destEnd && src != srcEnd) ? ERROR_INSUFFICIENT_BUFFER : ERROR_SUCCESS; + } + return *pErrorCode == ERROR_INSUFFICIENT_BUFFER ? 0 : cchDest - (destEnd - dest); +} + size_t SystemLocale::FromUtf16( UINT destCodePage, const WCHAR * src, SSIZE_T cchSrc, char * dest, size_t cchDest, bool * pHasDataLoss, DWORD * pErrorCode ) { destCodePage = ExpandSpecialCP( destCodePage ); + if ( destCodePage == CP_UTF8 ) + { + pHasDataLoss && (*pHasDataLoss = 0); + return SystemLocale::Utf8From16( src, cchSrc < 0 ? 1+mplat_wcslen(src) : cchSrc, dest, cchDest, pErrorCode ); + } EncodingConverter cvt( destCodePage, CP_UTF16 ); if ( !cvt.Initialize() ) { @@ -384,6 +959,11 @@ size_t SystemLocale::FromUtf16( UINT destCodePage, const WCHAR * src, SSIZE_T cc size_t SystemLocale::FromUtf16Strict(UINT destCodePage, const WCHAR * src, SSIZE_T cchSrc, char * dest, size_t cchDest, bool * pHasDataLoss, DWORD * pErrorCode) { destCodePage = ExpandSpecialCP(destCodePage); + if ( destCodePage == CP_UTF8 ) + { + pHasDataLoss && (*pHasDataLoss = 0); + return SystemLocale::Utf8From16Strict( src, cchSrc < 0 ? 1+mplat_wcslen(src) : cchSrc, dest, cchDest, pErrorCode ); + } EncodingConverter cvt(destCodePage, CP_UTF16); if (!cvt.Initialize()) { diff --git a/source/shared/msodbcsql.h b/source/shared/msodbcsql.h index f4912b11..b440a95a 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 8d5b785c..b000b640 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 574dc51a..d035e366 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 0ad9dcd1..256fb51d 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -26,7 +26,7 @@ // Increase Minor with backward compatible new functionalities and API changes. // Increase Patch for backward compatible fixes. #define SQLVERSION_MAJOR 5 -#define SQLVERSION_MINOR 4 +#define SQLVERSION_MINOR 5 #define SQLVERSION_PATCH 0 #define SQLVERSION_BUILD 0 diff --git a/source/shared/xplat.h b/source/shared/xplat.h index 8e113a5c..bb4888ea 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 03706dd3..571c62b2 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 a5bdf641..88a97baa 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 27426310..7bdac15e 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 c0e4d3af..5af9e7cd 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.4 for PHP for SQL Server +dnl Microsoft Drivers 5.5 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 b6c2b1b1..dc9f0b5f 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -36,11 +36,18 @@ if( PHP_SQLSRV != "no" ) { ADD_FLAG( "CFLAGS_SQLSRV", "/GS" ); ADD_FLAG( "CFLAGS_SQLSRV", "/Zi" ); if (VCVERS >= 1913) { + ADD_FLAG("LDFLAGS_SQLSRV", "/d2:-guardspecload"); ADD_FLAG("CFLAGS_SQLSRV", "/Qspectre"); - } + } else if (VCVERS == 1900) { + var subver1900 = probe_binary(PHP_CL).substr(6); + if (subver1900 >= 24241) { + ADD_FLAG("LDFLAGS_SQLSRV", "/d2:-guardspecload"); + 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 { WARNING("sqlsrv not enabled; libraries and headers not found"); - } + } } diff --git a/source/sqlsrv/conn.cpp b/source/sqlsrv/conn.cpp index dcfc755e..1de0c6b6 100644 --- a/source/sqlsrv/conn.cpp +++ b/source/sqlsrv/conn.cpp @@ -3,7 +3,7 @@ // // Contents: Routines that use connection handles // -// Microsoft Drivers 5.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -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 ) @@ -174,6 +213,8 @@ namespace SSStmtOptionNames { const char SCROLLABLE[] = "Scrollable"; 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 { @@ -191,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"; @@ -216,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 @@ -250,6 +295,18 @@ const stmt_option SS_STMT_OPTS[] = { SQLSRV_STMT_OPTION_DATE_AS_STRING, std::unique_ptr( new stmt_option_date_as_string ) }, + { + SSStmtOptionNames::FORMAT_DECIMALS, + sizeof( SSStmtOptionNames::FORMAT_DECIMALS ), + 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{} }, }; @@ -508,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/init.cpp b/source/sqlsrv/init.cpp index 45dfb0e5..9079ac75 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 1816942a..f60c6c84 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -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 3bbd4af6..1f0357ac 100644 --- a/source/sqlsrv/stmt.cpp +++ b/source/sqlsrv/stmt.cpp @@ -3,7 +3,7 @@ // // Contents: Routines that use statement handles // -// Microsoft Drivers 5.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -91,7 +91,7 @@ const char SS_SQLSRV_WARNING_PARAM_VAR_NOT_REF[] = "Variable parameter %d not pa /* internal functions */ void convert_to_zval( _Inout_ sqlsrv_stmt* stmt, _In_ SQLSRV_PHPTYPE sqlsrv_php_type, _In_opt_ void* in_val, _In_ SQLLEN field_len, _Inout_ zval& out_zval ); - +SQLSMALLINT get_resultset_meta_data(_Inout_ sqlsrv_stmt* stmt); void fetch_fields_common( _Inout_ ss_sqlsrv_stmt* stmt, _In_ zend_long fetch_type, _Out_ zval& fields, _In_ bool allow_empty_field_names TSRMLS_DC ); bool determine_column_size_or_precision( sqlsrv_stmt const* stmt, _In_ sqlsrv_sqltype sqlsrv_type, _Inout_ SQLULEN* column_size, @@ -110,6 +110,15 @@ bool verify_and_set_encoding( _In_ const char* encoding_string, _Inout_ sqlsrv_p } +// internal helper function to free meta data structures allocated +void meta_data_free( _Inout_ field_meta_data* meta ) +{ + if( meta->field_name ) { + meta->field_name.reset(); + } + sqlsrv_free( meta ); +} + // query options for cursor types namespace SSCursorTypes { @@ -130,13 +139,18 @@ 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 ) { + std::for_each(current_meta_data.begin(), current_meta_data.end(), meta_data_free); + current_meta_data.clear(); + if( fetch_field_names != NULL ) { for( int i=0; i < fetch_fields_count; ++i ) { @@ -459,27 +473,24 @@ PHP_FUNCTION( sqlsrv_field_metadata ) try { - // get the number of fields in the resultset - num_cols = core::SQLNumResultCols( stmt TSRMLS_CC ); + // get the number of fields in the resultset and its metadata if not exists + SQLSMALLINT num_cols = get_resultset_meta_data(stmt); zval result_meta_data; ZVAL_UNDEF( &result_meta_data ); core::sqlsrv_array_init( *stmt, &result_meta_data TSRMLS_CC ); for( SQLSMALLINT f = 0; f < num_cols; ++f ) { - - sqlsrv_malloc_auto_ptr core_meta_data; - core_meta_data = core_sqlsrv_field_metadata( stmt, f TSRMLS_CC ); - + field_meta_data* core_meta_data = stmt->current_meta_data[f]; + // initialize the array zval field_array; ZVAL_UNDEF( &field_array ); core::sqlsrv_array_init( *stmt, &field_array TSRMLS_CC ); - core::sqlsrv_add_assoc_string( *stmt, &field_array, FieldMetaData::NAME, - reinterpret_cast( core_meta_data->field_name.get() ), 0 TSRMLS_CC ); - - core_meta_data->field_name.transferred(); + // add the field name to the associative array but keep a copy + core::sqlsrv_add_assoc_string(*stmt, &field_array, FieldMetaData::NAME, + reinterpret_cast(core_meta_data->field_name.get()), 1 TSRMLS_CC); core::sqlsrv_add_assoc_long( *stmt, &field_array, FieldMetaData::TYPE, core_meta_data->field_type TSRMLS_CC ); @@ -519,9 +530,6 @@ PHP_FUNCTION( sqlsrv_field_metadata ) // add this field's meta data to the result set meta data core::sqlsrv_add_next_index_zval( *stmt, &result_meta_data, &field_array TSRMLS_CC ); - - // always good to call destructor for allocations done through placement new operator. - core_meta_data->~field_meta_data(); } // return our built collection and transfer ownership @@ -567,6 +575,10 @@ PHP_FUNCTION( sqlsrv_next_result ) core_sqlsrv_next_result( stmt TSRMLS_CC, true ); + // clear the current meta data since the new result will generate new meta data + std::for_each(stmt->current_meta_data.begin(), stmt->current_meta_data.end(), meta_data_free); + stmt->current_meta_data.clear(); + if( stmt->past_next_result_end ) { RETURN_NULL(); @@ -1084,7 +1096,7 @@ PHP_FUNCTION( sqlsrv_get_field ) try { // validate that the field index is within range - int num_cols = core::SQLNumResultCols( stmt TSRMLS_CC ); + SQLSMALLINT num_cols = get_resultset_meta_data(stmt); if( field_index < 0 || field_index >= num_cols ) { THROW_SS_ERROR( stmt, SS_SQLSRV_ERROR_INVALID_FUNCTION_PARAMETER, _FN_ ); @@ -1622,10 +1634,13 @@ sqlsrv_phptype determine_sqlsrv_php_type( _In_ ss_sqlsrv_stmt const* stmt, _In_ switch( sql_type ) { case SQL_BIGINT: - case SQL_CHAR: case SQL_DECIMAL: - case SQL_GUID: case SQL_NUMERIC: + sqlsrv_phptype.typeinfo.type = SQLSRV_PHPTYPE_STRING; + sqlsrv_phptype.typeinfo.encoding = SQLSRV_ENCODING_CHAR; + break; + case SQL_CHAR: + case SQL_GUID: case SQL_WCHAR: sqlsrv_phptype.typeinfo.type = SQLSRV_PHPTYPE_STRING; sqlsrv_phptype.typeinfo.encoding = stmt->encoding(); @@ -1647,6 +1662,7 @@ sqlsrv_phptype determine_sqlsrv_php_type( _In_ ss_sqlsrv_stmt const* stmt, _In_ case SQL_SMALLINT: case SQL_TINYINT: sqlsrv_phptype.typeinfo.type = SQLSRV_PHPTYPE_INT; + sqlsrv_phptype.typeinfo.encoding = SQLSRV_ENCODING_CHAR; break; case SQL_BINARY: case SQL_LONGVARBINARY: @@ -1676,6 +1692,7 @@ sqlsrv_phptype determine_sqlsrv_php_type( _In_ ss_sqlsrv_stmt const* stmt, _In_ case SQL_FLOAT: case SQL_REAL: sqlsrv_phptype.typeinfo.type = SQLSRV_PHPTYPE_FLOAT; + sqlsrv_phptype.typeinfo.encoding = SQLSRV_ENCODING_CHAR; break; case SQL_TYPE_DATE: case SQL_SS_TIMESTAMPOFFSET: @@ -1759,6 +1776,37 @@ void determine_stmt_has_rows( _Inout_ ss_sqlsrv_stmt* stmt TSRMLS_DC ) } } +SQLSMALLINT get_resultset_meta_data(_Inout_ sqlsrv_stmt * stmt) +{ + // get the numer of columns in the result set + SQLSMALLINT num_cols = -1; + + num_cols = stmt->current_meta_data.size(); + bool getMetaData = false; + + if (num_cols == 0) { + getMetaData = true; + num_cols = core::SQLNumResultCols(stmt TSRMLS_CC); + } + + try { + if (getMetaData) { + for (int i = 0; i < num_cols; i++) { + sqlsrv_malloc_auto_ptr core_meta_data; + core_meta_data = core_sqlsrv_field_metadata(stmt, i TSRMLS_CC); + stmt->current_meta_data.push_back(core_meta_data.get()); + core_meta_data.transferred(); + } + } + } catch( core::CoreException& ) { + throw; + } + + SQLSRV_ASSERT(num_cols > 0 && stmt->current_meta_data.size() == num_cols, "Meta data vector out of sync" ); + + return num_cols; +} + void fetch_fields_common( _Inout_ ss_sqlsrv_stmt* stmt, _In_ zend_long fetch_type, _Out_ zval& fields, _In_ bool allow_empty_field_names TSRMLS_DC ) { @@ -1772,40 +1820,25 @@ void fetch_fields_common( _Inout_ ss_sqlsrv_stmt* stmt, _In_ zend_long fetch_typ throw ss::SSException(); } - // get the numer of columns in the result set - SQLSMALLINT num_cols = core::SQLNumResultCols(stmt TSRMLS_CC); + // get the numer of columns in the result set and its metadata if not exists + SQLSMALLINT num_cols = get_resultset_meta_data(stmt); // if this is the first fetch in a new result set, then get the field names and // store them off for successive fetches. - if(( fetch_type & SQLSRV_FETCH_ASSOC ) && stmt->fetch_field_names == NULL ) { + if ((fetch_type & SQLSRV_FETCH_ASSOC) && stmt->fetch_field_names == NULL) { SQLLEN field_name_len = 0; - SQLSMALLINT field_name_len_w = 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 ))); - SQLSRV_ENCODING encoding = (( stmt->encoding() == SQLSRV_ENCODING_DEFAULT ) ? stmt->conn->encoding() : stmt->encoding()); - for( int i = 0; i < num_cols; ++i ) { - - core::SQLColAttributeW ( stmt, i + 1, SQL_DESC_NAME, field_name_w, ( SS_MAXCOLNAMELEN + 1 ) * 2, &field_name_len_w, NULL TSRMLS_CC ); - - //Conversion function expects size in characters - field_name_len_w = field_name_len_w / sizeof ( SQLWCHAR ); - bool converted = convert_string_from_utf16( encoding, field_name_w, - field_name_len_w, ( char** ) &field_name, field_name_len ); - - CHECK_CUSTOM_ERROR( !converted, stmt, SQLSRV_ERROR_FIELD_ENCODING_TRANSLATE, get_last_error_message() ) { - throw core::CoreException(); - } - - field_names[i].name = static_cast( sqlsrv_malloc( field_name_len, sizeof( char ), 1 )); - memcpy_s(( void* )field_names[i].name, ( field_name_len * sizeof( char )) , ( void* ) field_name, field_name_len ); - field_names[i].name[field_name_len] = '\0'; // null terminate the field name since SQLColAttribute doesn't. - field_names[i].len = field_name_len + 1; - field_name.reset(); + field_names = static_cast(sqlsrv_malloc(num_cols * sizeof(sqlsrv_fetch_field_name))); + for (int i = 0; i < num_cols; ++i) { + // The meta data field name is already null-terminated, and the field name len is correct. + field_name_len = stmt->current_meta_data[i]->field_name_len; + field_names[i].name = static_cast(sqlsrv_malloc(field_name_len, sizeof(char), 1)); + memcpy_s((void*)field_names[i].name, (field_name_len * sizeof(char)), (void*)stmt->current_meta_data[i]->field_name, field_name_len); + field_names[i].name[field_name_len] = '\0'; // null terminate the field name after the memcpy + field_names[i].len = field_name_len; // field_name_len should not need to include the null char } - + stmt->fetch_field_names = field_names; stmt->fetch_fields_count = num_cols; field_names.transferred(); @@ -1840,12 +1873,12 @@ void fetch_fields_common( _Inout_ ss_sqlsrv_stmt* stmt, _In_ zend_long fetch_typ if( fetch_type & SQLSRV_FETCH_ASSOC ) { - CHECK_CUSTOM_WARNING_AS_ERROR(( stmt->fetch_field_names[i].len == 1 && !allow_empty_field_names ), stmt, + CHECK_CUSTOM_WARNING_AS_ERROR(( stmt->fetch_field_names[i].len == 0 && !allow_empty_field_names ), stmt, SS_SQLSRV_WARNING_FIELD_NAME_EMPTY) { throw ss::SSException(); } - if( stmt->fetch_field_names[i].len > 1 || allow_empty_field_names ) { + if( stmt->fetch_field_names[i].len > 0 || 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 d70a93a9..88eefb55 100644 --- a/source/sqlsrv/template.rc +++ b/source/sqlsrv/template.rc @@ -3,7 +3,7 @@ // // Contents: Version resource // -// Microsoft Drivers 5.4 for PHP for SQL Server +// Microsoft Drivers 5.5 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 aab5e2eb..d4be03f5 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.4 for PHP for SQL Server +// Microsoft Drivers 5.5 for PHP for SQL Server // Copyright(c) Microsoft Corporation // All rights reserved. // MIT License @@ -428,6 +428,10 @@ ss_error SS_ERRORS[] = { SQLSRV_ERROR_EMPTY_ACCESS_TOKEN, { IMSSP, (SQLCHAR*) "The Azure AD Access Token is empty. Expected a byte string.", -116, false} }, + { + 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} + }, // terminate the list of errors/warnings { UINT_MAX, {} } diff --git a/test/functional/pdo_sqlsrv/MsData_PDO_AllTypes.inc b/test/functional/pdo_sqlsrv/MsData_PDO_AllTypes.inc index 14f89a1a..2fe6d98a 100644 --- a/test/functional/pdo_sqlsrv/MsData_PDO_AllTypes.inc +++ b/test/functional/pdo_sqlsrv/MsData_PDO_AllTypes.inc @@ -12,7 +12,7 @@ $int_col = array(1, 2); $bin = fopen('php://memory', 'a'); -fwrite($bin, '00'); +fwrite($bin, hex2bin('6162636465')); // 'abcde' rewind($bin); $binary_col = array($bin, $bin); diff --git a/test/functional/pdo_sqlsrv/PDO81_MemoryCheck.phpt b/test/functional/pdo_sqlsrv/PDO81_MemoryCheck.phpt index 8cc64838..9fc7cd95 100644 --- a/test/functional/pdo_sqlsrv/PDO81_MemoryCheck.phpt +++ b/test/functional/pdo_sqlsrv/PDO81_MemoryCheck.phpt @@ -6,7 +6,7 @@ emalloc (which only allocate memory in the memory space allocated for the PHP pr --ENV-- PHPT_EXEC=true --SKIPIF-- - + --FILE-- + --FILE-- + --FILE-- +--FILE-- +prepare($query); + $stmt->bindParam(1, $bin, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY); + $stmt->bindParam(2, $bin, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY); + $stmt->bindParam(3, $bin, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY); + + $stmt->execute(); + fclose($bin); + + $bin2 = fopen('php://memory', 'a'); + fwrite($bin2, $inputs[1]); // 'ABC' will be 0x414243 in hex + rewind($bin2); + + $stmt->bindParam(1, $bin2, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY); + $stmt->bindParam(2, $bin2, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY); + $stmt->bindParam(3, $bin2, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY); + + $stmt->execute(); + fclose($bin2); + + // Verify the data by fetching and comparing against the inputs + $query = "SELECT * FROM $tableName"; + $stmt = $conn->query($query); + $rowset = $stmt->fetchAll(); + + for ($i = 0; $i < 2; $i++) { + for ($j = 0; $j < 3; $j++) { + $str = $rowset[$i][$j]; + $len = strlen($str); + $failed = false; + + if ($j == 0) { + // binary fields have fixed size, unlike varbinary ones + if ($len !== $size || trim($str) !== $inputs[$i]) { + $failed = true; + } + } else { + if ($len !== strlen($inputs[$i]) || $str !== $inputs[$i]) { + $failed = true; + } + } + + if ($failed) { + $row = $i + 1; + $col = $j + 1; + echo "Unexpected value returned from row $row and column $col: \n"; + var_dump($str); + } + } + } + + dropTable($conn, $tableName); + unset($stmt); + unset($conn); + + echo "Done\n"; +} catch (PDOException $e) { + var_dump($e); + exit; +} +?> +--EXPECT-- +Done diff --git a/test/functional/pdo_sqlsrv/pdostatement_fetchAll.phpt b/test/functional/pdo_sqlsrv/pdostatement_fetchAll.phpt index dc7ccae64c4d9fda3c8e9e985b30d2227ec19ae5..62bc542d8820bf95e3b41f4271db38eefba6a94f 100644 GIT binary patch delta 139 zcmX@w!}z#|al;Nt*2JXbl+?-ldBizQH5HV=yv=td1(*@s$sc7T5WLO2vZwhF+{t&e okt8So&{o%io1?^~00hxS=CQVRU}kYiQD$Dc23)~rdmT0@00+P+bpQYW delta 128 zcmaFd!+5lZal;NtRs#bD28PM|dBizQH5HV=yv=td1(+2KfLtXm1t5qvG>Eme12c +--FILE-- +getMessage(), $expected) === false) { + print_r($exception->getMessage()); + echo "\n"; + } +} + +function testErrorCases($conn) +{ + $expected = 'Expected an integer to specify number of decimals to format the output values of decimal data types'; + $query = "SELECT 0.0001"; + + try { + $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) { + checkException($e, $expected); + } + + try { + $options = array(PDO::SQLSRV_ATTR_DECIMAL_PLACES => 0.9); + $stmt = $conn->prepare($query, $options); + } catch (PdoException $e) { + checkException($e, $expected); + } + + try { + $options = array(PDO::SQLSRV_ATTR_DECIMAL_PLACES => true); + $stmt = $conn->prepare($query, $options); + } catch (PdoException $e) { + checkException($e, $expected); + } +} + +function compareNumbers($actual, $input, $column, $fieldScale, $format = true) +{ + $matched = false; + if ($actual === $input) { + $matched = true; + trace("Matched: $actual, $input\n"); + } else { + // 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: "); + $expected = str_replace('0.', '.', $expected); + } + } + trace("With number_format: $actual, $expected\n"); + if ($actual === $expected) { + $matched = true; + } else { + echo "For $column ($fieldScale): expected $expected ($input) but the value is $actual\n"; + } + } + return $matched; +} + +function testNoOption($conn, $tableName, $inputs, $columns) +{ + // Without the statement option, should return decimal values as they are + $query = "SELECT * FROM $tableName"; + $stmt = $conn->query($query); + + // Compare values + $results = $stmt->fetch(PDO::FETCH_NUM); + trace("\ntestNoOption:\n"); + for ($i = 0; $i < count($inputs); $i++) { + compareNumbers($results[$i], $inputs[$i], $columns[$i], $i, false); + } +} + +function testStmtOption($conn, $tableName, $inputs, $columns, $decimalPlaces, $withBuffer) +{ + // 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_DECIMAL_PLACES => $decimalPlaces); + } else { + $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: $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); + } +} + +function getOutputParam($conn, $storedProcName, $inputValue, $prec, $scale, $inout) +{ + $outString = ''; + $numDigits = 2; + + $outSql = getCallProcSqlPlaceholders($storedProcName, 1); + + $options = array(PDO::SQLSRV_ATTR_DECIMAL_PLACES => $numDigits); + $stmt = $conn->prepare($outSql, $options); + + $len = 1024; + if ($inout) { + $paramType = PDO::PARAM_STR | PDO::PARAM_INPUT_OUTPUT; + + // For inout parameters the input type should match the output one + $outString = '0.0'; + } else { + $paramType = PDO::PARAM_STR; + } + + $stmt->bindParam(1, $outString, $paramType, $len); + $stmt->execute(); + + // The output param value should be unaffected by the attr + // PDO::SQLSRV_ATTR_DECIMAL_PLACES. Without ColumnEncryption, the + // output param is treated as a regular string (not a decimal), so + // no missing leading zeroes. + // 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); + } else { + trace("\ngetOutputParam ($inout) without AE:\n"); + $column = 'outputParam'; + compareNumbers($outString, $inputValue, $column, $scale); + } +} + +function testOutputParam($conn, $tableName, $inputs, $columns, $dataTypes, $inout = false) +{ + for ($i = 0, $p = 3; $i < count($columns); $i++, $p++) { + // Create the stored procedure first + $storedProcName = "spFormatDecimals" . $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 + getOutputParam($conn, $storedProcName, $inputs[$i], $p, $i, $inout); + + dropProc($conn, $storedProcName); + } +} + +try { + // This helper method sets PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION + $conn = connect(); + + // Test some error conditions + testErrorCases($conn); + + // Create the test table of decimal / numeric data columns + $tableName = 'pdoFormatDecimals'; + + $columns = array('c1', 'c2', 'c3', 'c4', 'c5', 'c6'); + $dataTypes = array('decimal(3,0)', 'decimal(4,1)', 'decimal(5,2)', 'numeric(6,3)', 'numeric(7,4)', 'numeric(8, 5)'); + + $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); + + // Generate random input values based on precision and scale + trace("\nGenerating random input values: \n"); + $values = array(); + $max = 1; + for ($s = 0, $p = 3; $s < count($columns); $s++, $p++) { + // First get a random number + $n = rand(1, 6); + $neg = ($n % 2 == 0) ? -1 : 1; + + // $n1, a tiny number, which may or may not be negative, + $n1 = rand(0, 5) * $neg; + + if ($s > 0) { + $max *= 10; + $n2 = rand(0, $max); + $number = sprintf("%d.%d", $n1, $n2); + } else { + $number = sprintf("%d", $n1); + } + + trace("$s: $number\n"); + array_push($values, $number); + } + + $query = "INSERT INTO $tableName VALUES(?, ?, ?, ?, ?, ?)"; + $stmt = $conn->prepare($query); + for ($i = 0; $i < count($columns); $i++) { + $stmt->bindParam($i+1, $values[$i]); + } + $stmt->execute(); + + 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); + + testStmtOption($conn, $tableName, $values, $columns, 2, false); + testStmtOption($conn, $tableName, $values, $columns, 2, true); + + // Test output parameters + testOutputParam($conn, $tableName, $values, $columns, $dataTypes); + testOutputParam($conn, $tableName, $values, $columns, $dataTypes, true); + + dropTable($conn, $tableName); + echo "Done\n"; + + unset($stmt); + unset($conn); +} catch (PdoException $e) { + echo $e->getMessage() . PHP_EOL; +} +?> +--EXPECT-- +Done 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 00000000..f7618fe0 --- /dev/null +++ b/test/functional/pdo_sqlsrv/pdostatement_format_money_scales.phpt @@ -0,0 +1,162 @@ +--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 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/pdo_sqlsrv/pdostatement_format_money_types.phpt b/test/functional/pdo_sqlsrv/pdostatement_format_money_types.phpt new file mode 100644 index 00000000..c02d634a --- /dev/null +++ b/test/functional/pdo_sqlsrv/pdostatement_format_money_types.phpt @@ -0,0 +1,244 @@ +--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/pdo_sqlsrv/pdostatement_nextRowset.phpt b/test/functional/pdo_sqlsrv/pdostatement_nextRowset.phpt index 339880bc800bb4a44bf279f260aa22f0b8f210a8..f235ed94b1d2ef00f861553e6b56a7b1c0d6496e 100644 GIT binary patch delta 156 zcmaDJ+#0f>hnY1oDLEx|@W#uh4dyCBx1^_>EEg1j+ delta 112 zcmZn-c^hndyDfPsNw@ + --FILE-- + --FILE-- + --FILE-- $azureUsername, "PWD"=>$azurePassword, - "Authentication"=>'ActiveDirectoryPassword', "TrustServerCertificate"=>true ); + "Authentication"=>'ActiveDirectoryPassword', "TrustServerCertificate"=>false ); $conn = sqlsrv_connect( $azureServer, $connectionInfo ); if( $conn === false ) diff --git a/test/functional/sqlsrv/sqlsrv_param_empty_binary.phpt b/test/functional/sqlsrv/sqlsrv_param_empty_binary.phpt new file mode 100644 index 00000000..8ddff7fb --- /dev/null +++ b/test/functional/sqlsrv/sqlsrv_param_empty_binary.phpt @@ -0,0 +1,105 @@ +--TEST-- +Test for inserting empty strings and non-empty ones into binary types +--DESCRIPTION-- +Test for inserting empty strings and non-empty ones into binary types +Related to GitHub PR 865 - verify that the same binary data can be reused rather +than flushed after the first use +--SKIPIF-- + +--FILE-- + $inputs[0], "VarBinaryCol" => $inputs[1], "VarBinaryMaxCol" => $inputs[2]), $r, AE\INSERT_PREPARE_PARAMS); + + +$inputs = array(new AE\BindParamOption($inputValues[1], + null, + "SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_BINARY)", + "SQLSRV_SQLTYPE_BINARY($size)"), + new AE\BindParamOption($inputValues[1], + null, + "SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_BINARY)", + "SQLSRV_SQLTYPE_VARBINARY($size)"), + new AE\BindParamOption($inputValues[1], + null, + "SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_BINARY)", + "SQLSRV_SQLTYPE_VARBINARY('max')")); +$r; +$stmt = AE\insertRow($conn, $tableName, array("BinaryCol" => $inputs[0], "VarBinaryCol" => $inputs[1], "VarBinaryMaxCol" => $inputs[2]), $r, AE\INSERT_PREPARE_PARAMS); + +// Verify the data by fetching and comparing against the inputs +$query = "SELECT * FROM $tableName"; +$stmt = sqlsrv_query($conn, $query); +if (!$stmt) { + fatalError("Failed to retrieve data from $tableName"); +} + +for ($i = 0; $i < 2; $i++) { + $rowNum = $i + 1; + $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); + if (!$row) { + fatalError("Failed in sqlsrv_fetch_array for row $rowNum"); + } + + for ($j = 0; $j < 3; $j++) { + $str = $row[$j]; + $len = strlen($str); + $failed = false; + + if ($j == 0) { + // binary fields have fixed size, unlike varbinary ones + if ($len !== $size || trim($str) !== $inputValues[$i]) { + $failed = true; + } + } else { + $inputLen = strlen($inputValues[$i]); + if ($len !== $inputLen || $str !== $inputValues[$i]) { + $failed = true; + } + } + + if ($failed) { + $colNum = $j + 1; + echo "Unexpected value returned from row $rowNum and column $colNum: \n"; + var_dump($str); + } + } +} + +dropTable($conn, $tableName); + +sqlsrv_free_stmt($stmt); +sqlsrv_close($conn); + +echo "Done\n"; + +?> +--EXPECT-- +Done diff --git a/test/functional/sqlsrv/sqlsrv_statement_format_decimals.phpt b/test/functional/sqlsrv/sqlsrv_statement_format_decimals.phpt new file mode 100644 index 00000000..a2faf7cf --- /dev/null +++ b/test/functional/sqlsrv/sqlsrv_statement_format_decimals.phpt @@ -0,0 +1,288 @@ +--TEST-- +Test connection and statement attributes for formatting decimal and numeric data (feature request issue 415) +--DESCRIPTION-- +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 operations like insertion or update. +--ENV-- +PHPT_EXEC=true +--SKIPIF-- + +--FILE-- + 1.5); + $stmt = sqlsrv_query($conn, $query, array(), $options); + if ($stmt) { + fatalError("Case 1: expected query to fail!!"); + } else { + $error = sqlsrv_errors()[0]['message']; + if (strpos($error, $message) === false) { + print_r(sqlsrv_errors()); + } + } + + $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']; + if (strpos($error, $message) === false) { + print_r(sqlsrv_errors()); + } + } +} + +function testNoOption($conn, $tableName, $inputs, $columns, $exec) +{ + // This should return decimal values as they are + $query = "SELECT * FROM $tableName"; + if ($exec) { + $stmt = sqlsrv_query($conn, $query); + } else { + $stmt = sqlsrv_prepare($conn, $query); + sqlsrv_execute($stmt); + } + + // 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, false); + } +} + +function testStmtOption($conn, $tableName, $inputs, $columns, $decimalPlaces, $withBuffer) +{ + // Decimal values should NOT be affected by the statement + // option DecimalPlaces + $query = "SELECT * FROM $tableName"; + if ($withBuffer){ + $options = array('Scrollable' => 'buffered', 'DecimalPlaces' => $decimalPlaces); + } else { + $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); + + if (sqlsrv_fetch($stmt) === false) { + fatalError("Failed in retrieving data\n"); + } + for ($i = 0; $i < $size; $i++) { + $field = sqlsrv_get_field($stmt, $i); // Expect a string + compareNumbers($field, $inputs[$i], $columns[$i], $i, true); + } +} + +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, + // 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()) { + $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; + $outString = '0.0'; + } + + $outSql = AE\getCallProcSqlPlaceholders($storedProcName, 1); + $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"); + } + + // Verify value of output param + $column = 'outputParam'; + 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('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, true); + sqlsrv_free_stmt($stmt); + } +} + +function testOutputParam($conn, $tableName, $inputs, $columns, $dataTypes, $inout = false) +{ + for ($i = 0, $p = 3; $i < count($columns); $i++, $p++) { + // Create the stored procedure first + $storedProcName = "spFormatDecimals" . $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 + getOutputParam($conn, $storedProcName, $inputs[$i], $p, $i, $i > 2, $inout); + + dropProc($conn, $storedProcName); + } +} + +set_time_limit(0); +sqlsrv_configure('WarningsReturnAsErrors', 1); + +$conn = AE\connect(); +if (!$conn) { + fatalError("Could not connect.\n"); +} + +// Test error conditions +testErrorCases($conn); + +// Create the test table of decimal / numeric data columns +$tableName = 'sqlsrvFormatDecimals'; + +$columns = array('c1', 'c2', 'c3', 'c4', 'c5', 'c6'); +$dataTypes = array('decimal(3,0)', 'decimal(4,1)', 'decimal(5,2)', 'numeric(6,3)', 'numeric(7,4)', 'numeric(8, 5)'); + +$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); + +// Generate random input values based on precision and scale +$values = array(); +$max2 = 1; +for ($s = 0, $p = 3; $s < count($columns); $s++, $p++) { + // First get a random number + $n = rand(1, 6); + $neg = ($n % 2 == 0) ? -1 : 1; + + // $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); + $number = sprintf("%d.%d", $n1, $n2); + } else { + $number = sprintf("%d", $n1); + } + + array_push($values, $number); +} + +// Insert data values as strings +$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) { + var_dump($values); + fatalError("Failed to insert data.\n"); +} +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); + +testStmtOption($conn, $tableName, $values, $columns, 2, false); +testStmtOption($conn, $tableName, $values, $columns, 2, true); + +// Test output parameters +testOutputParam($conn, $tableName, $values, $columns, $dataTypes); +testOutputParam($conn, $tableName, $values, $columns, $dataTypes, true); + +dropTable($conn, $tableName); +sqlsrv_close($conn); + +echo "Done\n"; +?> +--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 00000000..f6b3e753 --- /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 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 00000000..ac2c1cd0 --- /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 diff --git a/test/functional/sqlsrv/test_largeData.phpt b/test/functional/sqlsrv/test_largeData.phpt index 5f1969ae..e282df2a 100644 --- a/test/functional/sqlsrv/test_largeData.phpt +++ b/test/functional/sqlsrv/test_largeData.phpt @@ -42,6 +42,12 @@ class my_stream { function stream_seek($offset, $whence) { + // For the purpose of this test only support SEEK_SET to $offset 0 + if ($whence == SEEK_SET && $offset == 0) { + $this->total_read = $offset; + return true; + } + return false; } }