Merge pull request #590 from yitam/sqlsrvBuffer

Refactor sqlsrv tests with buffer or cursor
This commit is contained in:
Jenny Tam 2017-11-15 11:02:59 -08:00 committed by GitHub
commit 04a1637f22
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
27 changed files with 1062 additions and 1204 deletions

View file

@ -1,7 +1,9 @@
--TEST-- --TEST--
scrollable results with no rows. scrollable results with no rows.
--DESCRIPTION--
this test is very similar to test_scrollable.phpt... might consider removing this test as a duplicate
--SKIPIF-- --SKIPIF--
<?php require('skipif.inc'); ?> <?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
sqlsrv_configure('WarningsReturnAsErrors', 0); sqlsrv_configure('WarningsReturnAsErrors', 0);
@ -9,23 +11,42 @@ scrollable results with no rows.
require_once('MsCommon.inc'); require_once('MsCommon.inc');
$conn = connect(); $conn = AE\connect();
if ($conn === false) { $tableName = 'ScrollTest';
die(print_r(sqlsrv_errors(), true));
}
$stmt = sqlsrv_query($conn, "IF OBJECT_ID('ScrollTest', 'U') IS NOT NULL DROP TABLE ScrollTest"); $columns = array(new AE\ColumnMeta('int', 'id'),
if ($stmt !== false) { new AE\ColumnMeta('char(10)', 'value'));
sqlsrv_free_stmt($stmt); $stmt = AE\createTable($conn, $tableName, $columns);
} if (!$stmt) {
fatalError("Failed to create table for the test]n");
$stmt = sqlsrv_query($conn, "CREATE TABLE ScrollTest (id int, value char(10))");
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
} }
sqlsrv_free_stmt($stmt); sqlsrv_free_stmt($stmt);
// Always Encrypted feature only supports SQLSRV_CURSOR_FORWARD or
// SQLSRV_CURSOR_CLIENT_BUFFERED
$query = "SELECT * FROM $tableName";
if (AE\isColEncrypted()) {
$options = array('Scrollable' => SQLSRV_CURSOR_FORWARD);
} else {
$options = array('Scrollable' => 'static');
}
$stmt = sqlsrv_query($conn, "SELECT * FROM ScrollTest", array(), array( "Scrollable" => 'static' )); $stmt = sqlsrv_query($conn, $query, array(), $options);
$rows = sqlsrv_has_rows($stmt);
if ($rows != false) {
fatalError("Should be no rows present");
};
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
$row = sqlsrv_fetch_array($stmt);
print_r($row);
if ($row === false) {
print_r(sqlsrv_errors(), true);
}
$stmt = sqlsrv_query($conn, $query);
$rows = sqlsrv_has_rows($stmt); $rows = sqlsrv_has_rows($stmt);
if ($rows != false) { if ($rows != false) {
fatalError("Should be no rows present"); fatalError("Should be no rows present");
@ -40,23 +61,7 @@ scrollable results with no rows.
print_r(sqlsrv_errors(), true); print_r(sqlsrv_errors(), true);
} }
$stmt = sqlsrv_query($conn, "SELECT * FROM ScrollTest"); dropTable($conn, $tableName);
$rows = sqlsrv_has_rows($stmt);
if ($rows != false) {
fatalError("Should be no rows present");
};
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
$row = sqlsrv_fetch_array($stmt);
print_r($row);
if ($row === false) {
print_r(sqlsrv_errors(), true);
}
$stmt = sqlsrv_query($conn, "DROP TABLE ScrollTest");
echo "Test succeeded.\n"; echo "Test succeeded.\n";
?> ?>

View file

@ -1,25 +0,0 @@
<?php
function getKSPpath()
{
$name = 'myKSP';
$dir_name = realpath(dirname(__FILE__));
$ksp = $dir_name . DIRECTORY_SEPARATOR . $name;
if ( strtoupper( substr( php_uname( 's' ), 0, 3 ) ) == 'WIN' ) {
$arch = 'x64';
if ( PHP_INT_SIZE == 4 ) // running 32 bit
$arch = '';
$ksp .= $arch . '.dll';
}
else
$ksp .= '.so';
return $ksp;
}
$ksp_name = 'MyCustomKSPName';
$encrypt_key = 'LPKCWVD07N3RG98J0MBLG4H2';
$ksp_test_table = 'CustomKSPTestTable';
?>

View file

@ -22,6 +22,9 @@ const INSERT_PREPARE = 2;
const INSERT_QUERY_PARAMS = 3; const INSERT_QUERY_PARAMS = 3;
const INSERT_PREPARE_PARAMS = 4; const INSERT_PREPARE_PARAMS = 4;
const KSP_NAME = 'MyCustomKSPName';
const ENCRYPT_KEY = 'LPKCWVD07N3RG98J0MBLG4H2';
const KSP_TEST_TABLE = 'CustomKSPTestTable';
/** /**
* class for encapsulating column metadata needed for creating a table * class for encapsulating column metadata needed for creating a table
@ -71,10 +74,10 @@ class ColumnMeta
// https://docs.microsoft.com/en-us/sql/relational-databases/security/encryption/always-encrypted-database-engine // https://docs.microsoft.com/en-us/sql/relational-databases/security/encryption/always-encrypted-database-engine
$unsupported = array("xml", "timestamp", "image", "ntext", "text", "sql_variant", "hierarchyid", "geography", "geometry", "alias"); $unsupported = array("xml", "timestamp", "image", "ntext", "text", "sql_variant", "hierarchyid", "geography", "geometry", "alias");
if (stripos($this->options, "identity") !== false) { if (stripos($this->options, "identity") !== false) {
$this->encryptable = false; $this->encryptable = false;
} elseif (in_array($this->dataType, $unsupported)) { } elseif (in_array(strtolower($this->dataType), $unsupported)) {
$this->encryptable = false; $this->encryptable = false;
} else { } else {
$this->encryptable = true; $this->encryptable = true;
@ -210,6 +213,29 @@ function getCekName()
return $cekName; return $cekName;
} }
/**
* @return the path to the KSP dll/so file
*/
function getKSPpath()
{
$name = 'myKSP';
$dir_name = realpath(dirname(__FILE__));
$ksp = $dir_name . DIRECTORY_SEPARATOR . $name;
if (strtoupper(substr(php_uname('s'), 0, 3)) == 'WIN') {
$arch = 'x64';
if (PHP_INT_SIZE == 4) {
// running 32 bit
$arch = '';
}
$ksp .= $arch . '.dll';
} else {
$ksp .= '.so';
}
return $ksp;
}
/** /**
* @return string default column name when a name is not provided in the ColumnMeta class * @return string default column name when a name is not provided in the ColumnMeta class
*/ */
@ -346,11 +372,10 @@ function connect($options = array(), $disableCE = false)
$connectionOptions = array_merge($connectionOptions, array("ColumnEncryption" => "Enabled")); $connectionOptions = array_merge($connectionOptions, array("ColumnEncryption" => "Enabled"));
} }
if ($keystore == "ksp") { if ($keystore == "ksp") {
require('AE_Ksp.inc');
$ksp_path = getKSPPath(); $ksp_path = getKSPPath();
$ksp_options = array("CEKeystoreProvider"=>$ksp_path, $ksp_options = array("CEKeystoreProvider"=>$ksp_path,
"CEKeystoreName"=>$ksp_name, "CEKeystoreName"=>KSP_NAME,
"CEKeystoreEncryptKey"=>$encrypt_key); "CEKeystoreEncryptKey"=>ENCRYPT_KEY);
$connectionOptions = array_merge($connectionOptions, $ksp_options); $connectionOptions = array_merge($connectionOptions, $ksp_options);
} }
} }
@ -419,19 +444,20 @@ function insertRow($conn, $tbname, $inputs, &$r = null, $api = INSERT_QUERY)
array_push($params, $inputs[$key]); array_push($params, $inputs[$key]);
} }
} }
// use prepare for inserts when AE is enabled // use prepare for inserts when AE is enabled
if (isColEncrypted() || $api == INSERT_PREPARE_PARAMS) { if (isColEncrypted() || $api == INSERT_PREPARE_PARAMS) {
$stmt = sqlsrv_prepare($conn, $insertSql, $params); $stmt = sqlsrv_prepare($conn, $insertSql, $params);
if ($stmt) { if ($stmt) {
$r = sqlsrv_execute($stmt); $r = sqlsrv_execute($stmt);
} else { } else {
fatalError("insertRow: failed to prepare insert query!"); fatalError("insertRow: failed to prepare insert query!");
} }
} else { } else {
$stmt = sqlsrv_query($conn, $insertSql, $params); $stmt = sqlsrv_query($conn, $insertSql, $params);
} }
} }
return $stmt; return $stmt;
} }
@ -454,10 +480,11 @@ function selectFromTable($conn, $tbname, $conds = null, $values = null)
* @param resource $conn : connection resource * @param resource $conn : connection resource
* @param string $sql : T-SQL query * @param string $sql : T-SQL query
* @param string $conds : string of condition(s) possibly with placeholders, null by default * @param string $conds : string of condition(s) possibly with placeholders, null by default
* @param array $values : array of parameters, null by default * @param array $values : array of parameters for placeholders in $conds, null by default
* @param array $options : array of query options, null by default
* @return resource sqlsrv statement upon success or false otherwise * @return resource sqlsrv statement upon success or false otherwise
*/ */
function executeQuery($conn, $sql, $conds = null, $values = null) function executeQuery($conn, $sql, $conds = null, $values = null, $options = null)
{ {
if (!isColEncrypted()) { if (!isColEncrypted()) {
// if not encrypted replace placeholders ('?') with values, if array not empty // if not encrypted replace placeholders ('?') with values, if array not empty
@ -475,17 +502,19 @@ function executeQuery($conn, $sql, $conds = null, $values = null)
$sql = $sql . " WHERE $clause "; $sql = $sql . " WHERE $clause ";
} elseif (!empty($conds)) { } elseif (!empty($conds)) {
$sql = $sql . " WHERE $conds "; $sql = $sql . " WHERE $conds ";
} }
$stmt = sqlsrv_query($conn, $sql);
$stmt = sqlsrv_query($conn, $sql, null, $options);
} else { } else {
// with AE enabled, use sqlsrv_prepare() in case there are // with AE enabled, use sqlsrv_prepare() in case there are
// fields with unlimited size // fields with unlimited size
if (empty($conds) || empty($values)) { if (empty($conds)) {
$stmt = sqlsrv_prepare($conn, $sql); $stmt = sqlsrv_prepare($conn, $sql, null, $options);
} else { } else {
$sql = $sql . " WHERE $conds "; $sql = $sql . " WHERE $conds ";
$stmt = sqlsrv_prepare($conn, $sql, $values); // pass $values to sqlsrv_prepare whether the array is null, empty or filled
} $stmt = sqlsrv_prepare($conn, $sql, $values, $options);
}
if ($stmt) { if ($stmt) {
$r = sqlsrv_execute($stmt); $r = sqlsrv_execute($stmt);
if (!$r) { if (!$r) {
@ -649,13 +678,12 @@ function insertTestRow($conn, $tbname, $index)
echo("Invalid row index $index for test data!\n"); echo("Invalid row index $index for test data!\n");
return false; return false;
} }
// get array of input values // get array of input values
$inputArray = getInsertArray($index); $inputArray = getInsertArray($index);
if (empty($inputArray)) { if (empty($inputArray)) {
fatalError("getInsertSqlComplete: inputs for inserting a row cannot be empty"); fatalError("getInsertSqlComplete: inputs for inserting a row cannot be empty");
} }
$result = null; $result = null;
if (isColEncrypted()) { if (isColEncrypted()) {
$stmt = insertRow($conn, $tbname, $inputArray, $result); $stmt = insertRow($conn, $tbname, $inputArray, $result);
@ -667,14 +695,14 @@ function insertTestRow($conn, $tbname, $index)
$col = 1; $col = 1;
foreach ($inputArray as $key => $value) { foreach ($inputArray as $key => $value) {
$colStr .= $key . ", "; $colStr .= $key . ", ";
if (is_array($value)) { if (is_array($value)) {
$value = $value[0]; $value = $value[0];
// this might be an input to a decimal, a numeric or a binary field // this might be an input to a decimal, a numeric or a binary field
if (isBinary($col)) { if (isBinary($col)) {
$value = "0x" . $value; // annotate the input string as a hex string $value = "0x" . $value; // annotate the input string as a hex string
} }
} }
if (is_null($value)) { if (is_null($value)) {
$valStr .= "null, "; $valStr .= "null, ";
} elseif (is_string($value) && !isBinary($col)) { } elseif (is_string($value) && !isBinary($col)) {

View file

@ -1,23 +1,17 @@
<?php <?php
if(! extension_loaded( "sqlsrv" ) ) if (!extension_loaded("sqlsrv"))
die( "skip extension not loaded" ); die("skip extension not loaded");
require_once( 'MsSetup.inc' ); require_once('MsCommon.inc');
if ($keystore != 'ksp') if ($keystore != AE\KEYSTORE_KSP)
die ( 'skip - this test requires a custom keystore provider.' ); die('skip - this test requires a custom keystore provider.');
require_once( 'MsCommon.inc' ); $conn = AE\connect();
if (! $conn) {
$conn = Connect(); echo("Error: could not connect during SKIPIF!");
if( ! $conn ) } elseif (AE\isColEncrypted() && !AE\isQualified($conn)) {
{ die("skip - AE feature not supported in the current environment.");
echo( "Error: could not connect during SKIPIF!" );
} }
else if(! IsAEQualified( $conn ) )
{
die( "skip - AE feature not supported in the current environment." );
}
?> ?>

View file

@ -1,46 +1,80 @@
--TEST-- --TEST--
Read, Update, Insert from a SQLSRV stream with buffered query Read, Update, Insert from a SQLSRV stream with buffered query
--SKIPIF-- --SKIPIF--
<?php require('skipif.inc'); ?> <?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
require_once('MsCommon.inc'); require_once('MsCommon.inc');
$conn = connect(); function insertOneRow($conn, $tableName)
if (!$conn) { {
fatalError("Could not connect"); $result = null;
if (AE\isColEncrypted()) {
$data = array("Field2" => "This is field 2.",
"Field3" => array("010203", null, SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_CHAR), SQLSRV_SQLTYPE_IMAGE),
"Field4" => "This is field 4.",
"Field5" => array("040506", null, SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_CHAR), SQLSRV_SQLTYPE_VARBINARY('max')),
"Field6" => "This is field 6.",
"Field7" => "This is field 7.");
$query = AE\getInsertSqlPlaceholders($tableName, $data);
$stmt = sqlsrv_prepare($conn, $query, array_values($data), array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED));
} else {
$query = "INSERT INTO $tableName ([Field2], [Field3], [Field4], [Field5], [Field6], [Field7]) VALUES ('This is field 2.', 0x010203, 'This is field 4.', 0x040506, 'This is field 6.', 'This is field 7.' )";
$stmt = sqlsrv_prepare($conn, $query, array(), array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED));
}
if (!$stmt) {
fatalError("insertOneRow: query could not be prepared.\n");
}
$result = sqlsrv_execute($stmt);
if ($result === false) {
fatalError("insertOneRow: failed to insert data!\n");
}
return $stmt;
} }
$query = "IF OBJECT_ID('PhpCustomerTable', 'U') IS NOT NULL DROP TABLE [PhpCustomerTable]"; function updateRow($conn, $tableName, $updateField, $params)
$stmt = sqlsrv_prepare($conn, $query, array(), array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED)); {
$condField = 'Field7';
$condition = 'This is field 7.';
if (AE\isColEncrypted()) {
$query = "UPDATE $tableName SET $updateField=? WHERE $condField = ?";
array_push($params, array($condition, SQLSRV_PARAM_IN, null, SQLSRV_SQLTYPE_NVARCHAR('max')));
} else {
$query = "UPDATE $tableName SET $updateField=? WHERE $condField = '$condition'";
}
$stmt = sqlsrv_prepare($conn, $query, $params, array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED));
if (!$stmt) {
fatalError("updateRow: query could not be prepared.\n");
}
$result = sqlsrv_execute($stmt);
if ($result === false) {
fatalError("updateRow: failed to update $updateField!\n");
}
sqlsrv_free_stmt($stmt);
}
$conn = AE\connect();
$tableName = 'PhpCustomerTable';
// Create the test table and insert one row
$columns = array(new AE\ColumnMeta('int', 'Id', 'NOT NULL Identity (100,2) PRIMARY KEY'),
new AE\ColumnMeta('text', 'Field2'),
new AE\ColumnMeta('image', 'Field3'),
new AE\ColumnMeta('ntext', 'Field4'),
new AE\ColumnMeta('varbinary(max)', 'Field5'),
new AE\ColumnMeta('varchar(max)', 'Field6'),
new AE\ColumnMeta('nvarchar(max)', 'Field7'));
$stmt = AE\createTable($conn, $tableName, $columns);
if (!$stmt) { if (!$stmt) {
echo "Statement could not be prepared.\n"; fatalError("Failed to create table for the test\n");
die(print_r(sqlsrv_errors(), true));
} }
$stmt = insertOneRow($conn, $tableName);
sqlsrv_execute($stmt);
$query = "CREATE TABLE [PhpCustomerTable] ([Id] int NOT NULL Identity (100,2) PRIMARY KEY, [Field2] text, [Field3] image, [Field4] ntext, [Field5] varbinary(max), [Field6] varchar(max), [Field7] nvarchar(max))";
$stmt = sqlsrv_prepare($conn, $query, array(), array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED));
if (!$stmt) {
echo "Statement could not be prepared.\n";
die(print_r(sqlsrv_errors(), true));
}
sqlsrv_execute($stmt);
$query = "INSERT [PhpCustomerTable] ([Field2], [Field3], [Field4], [Field5], [Field6], [Field7]) VALUES ('This is field 2.', 0x010203, 'This is field 4.', 0x040506, 'This is field 6.', 'This is field 7.' )";
$stmt = sqlsrv_prepare($conn, $query, array(), array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED));
if (!$stmt) {
echo "Statement could not be prepared.\n";
die(print_r(sqlsrv_errors(), true));
}
sqlsrv_execute($stmt);
$f2 = fopen('php://memory', 'a'); $f2 = fopen('php://memory', 'a');
fwrite($f2, 'Update field 2.'); fwrite($f2, 'Update field 2.');
@ -61,88 +95,27 @@ $f7 = fopen('php://memory', 'a');
fwrite($f7, 'Update field 7.'); fwrite($f7, 'Update field 7.');
rewind($f7); rewind($f7);
// Update data in the table
$query = "UPDATE [PhpCustomerTable] SET [Field2]=? WHERE [Field7]='This is field 7.'";
$params = array(array(&$f2, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_CHAR), SQLSRV_SQLTYPE_TEXT)); $params = array(array(&$f2, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_CHAR), SQLSRV_SQLTYPE_TEXT));
$stmt = sqlsrv_prepare($conn, $query, $params, array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED)); updateRow($conn, $tableName, 'Field2', $params);
if (!$stmt) {
echo "Statement could not be prepared.\n";
die(print_r(sqlsrv_errors(), true));
}
sqlsrv_execute($stmt);
sqlsrv_free_stmt($stmt);
$query = "UPDATE [PhpCustomerTable] SET [Field3]=? WHERE [Field7]='This is field 7.'";
$params = array(array(&$f3, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY), SQLSRV_SQLTYPE_IMAGE)); $params = array(array(&$f3, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY), SQLSRV_SQLTYPE_IMAGE));
$stmt = sqlsrv_prepare($conn, $query, $params, array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED)); updateRow($conn, $tableName, 'Field3', $params);
if (!$stmt) {
echo "Statement could not be prepared.\n";
die(print_r(sqlsrv_errors(), true));
}
sqlsrv_execute($stmt);
sqlsrv_free_stmt($stmt);
$query = "UPDATE [PhpCustomerTable] SET [Field4]=? WHERE [Field7]='This is field 7.'";
$params = array(array(&$f4, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_CHAR), SQLSRV_SQLTYPE_NTEXT)); $params = array(array(&$f4, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_CHAR), SQLSRV_SQLTYPE_NTEXT));
$stmt = sqlsrv_prepare($conn, $query, $params, array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED)); updateRow($conn, $tableName, 'Field4', $params);
if (!$stmt) {
echo "Statement could not be prepared.\n";
die(print_r(sqlsrv_errors(), true));
}
sqlsrv_execute($stmt);
sqlsrv_free_stmt($stmt);
$query = "UPDATE [PhpCustomerTable] SET [Field5]=? WHERE [Field7]='This is field 7.'";
$params = array(array(&$f5, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY), SQLSRV_SQLTYPE_VARBINARY('max'))); $params = array(array(&$f5, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY), SQLSRV_SQLTYPE_VARBINARY('max')));
$stmt = sqlsrv_prepare($conn, $query, $params, array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED)); updateRow($conn, $tableName, 'Field5', $params);
if (!$stmt) {
echo "Statement could not be prepared.\n";
die(print_r(sqlsrv_errors(), true));
}
sqlsrv_execute($stmt);
sqlsrv_free_stmt($stmt);
$query = "UPDATE [PhpCustomerTable] SET [Field6]=? WHERE [Field7]='This is field 7.'";
$params = array(array(&$f6, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_CHAR), SQLSRV_SQLTYPE_VARCHAR('MAX'))); $params = array(array(&$f6, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_CHAR), SQLSRV_SQLTYPE_VARCHAR('MAX')));
$stmt = sqlsrv_prepare($conn, $query, $params, array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED)); updateRow($conn, $tableName, 'Field6', $params);
if (!$stmt) {
echo "Statement could not be prepared.\n";
die(print_r(sqlsrv_errors(), true));
}
sqlsrv_execute($stmt);
sqlsrv_free_stmt($stmt);
$query = "UPDATE [PhpCustomerTable] SET [Field7]=? WHERE [Field7]='This is field 7.'";
$params = array(array(&$f7, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_CHAR), SQLSRV_SQLTYPE_NVARCHAR('MAX'))); $params = array(array(&$f7, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_CHAR), SQLSRV_SQLTYPE_NVARCHAR('MAX')));
$stmt = sqlsrv_prepare($conn, $query, $params, array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED)); updateRow($conn, $tableName, 'Field7', $params);
if (!$stmt) { // Fetch data from the table
echo "Statement could not be prepared.\n"; $stmt = AE\executeQueryEx($conn, "SELECT * FROM [PhpCustomerTable]", array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED));
die(print_r(sqlsrv_errors(), true));
}
sqlsrv_execute($stmt);
sqlsrv_free_stmt($stmt);
$stmt = sqlsrv_query($conn, "SELECT * FROM [PhpCustomerTable]", array(), array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED));
if (!$stmt) {
echo "Statement could not be prepared.\n";
die(print_r(sqlsrv_errors(), true));
}
sqlsrv_fetch($stmt); sqlsrv_fetch($stmt);
$field = sqlsrv_get_field($stmt, 0, SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_CHAR)); $field = sqlsrv_get_field($stmt, 0, SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_CHAR));
@ -195,7 +168,7 @@ if (!$field) {
print("$field\n"); print("$field\n");
} }
sqlsrv_query($conn, "DROP TABLE [PhpCustomerTable]"); dropTable($conn, $tableName);
sqlsrv_free_stmt($stmt); sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); sqlsrv_close($conn);

View file

@ -1,40 +1,33 @@
--TEST-- --TEST--
Fetch array of extended ASCII data using a scrollable buffered cursor Fetch array of extended ASCII data using a scrollable buffered cursor
--SKIPIF-- --SKIPIF--
<?php require('skipif.inc'); ?> <?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
require_once("MsCommon.inc"); require_once('MsCommon.inc');
// Connect // Connect
$conn = connect(array( 'CharacterSet'=>'UTF-8' )); $conn = AE\connect(array('CharacterSet'=>'UTF-8'));
if (!$conn) {
die(print_r(sqlsrv_errors(), true));
}
// Create table // Create table
$tableName = '#exAsciiTest'; $tableName = 'exAsciiTest';
$query = "CREATE TABLE $tableName (ID CHAR(10))"; $columns = array(new AE\ColumnMeta('CHAR(10)', 'ID'));
$stmt = sqlsrv_query($conn, $query); AE\createTable($conn, $tableName, $columns);
// Insert data // Insert data
$query = "INSERT INTO $tableName VALUES ('Aå_Ð×Æ×Ø_B')"; $res = null;
$stmt = sqlsrv_query($conn, $query); $stmt = AE\insertRow($conn, $tableName, array('ID' => 'Aå_Ð×Æ×Ø_B'));
if (! $stmt) {
die(print_r(sqlsrv_errors(), true));
}
// Fetch data // Fetch data
$query = "SELECT * FROM $tableName"; $query = "SELECT * FROM $tableName";
$stmt = sqlsrv_query($conn, $query, [], array("Scrollable"=>"buffered")); $stmt = sqlsrv_query($conn, $query, [], array("Scrollable"=>"buffered"));
if (! $stmt) {
die(print_r(sqlsrv_errors(), true));
}
// Fetch // Fetch
$row = sqlsrv_fetch_array($stmt); $row = sqlsrv_fetch_array($stmt);
var_dump($row); var_dump($row);
dropTable($conn, $tableName);
// Close connection // Close connection
sqlsrv_free_stmt($stmt); sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); sqlsrv_close($conn);

View file

@ -4,46 +4,31 @@ Fetch data from a prepopulated test table given a custom keystore provider
<?php require('skipif_not_ksp.inc'); ?> <?php require('skipif_not_ksp.inc'); ?>
--FILE-- --FILE--
<?php <?php
sqlsrv_configure( 'WarningsReturnAsErrors', 1 ); sqlsrv_configure('WarningsReturnAsErrors', 1);
sqlsrv_configure( 'LogSeverity', SQLSRV_LOG_SEVERITY_ALL ); sqlsrv_configure('LogSeverity', SQLSRV_LOG_SEVERITY_ALL);
require( 'MsSetup.inc' ); require_once('MsHelper.inc');
require( 'AE_Ksp.inc' ); $conn = AE\connect(array('ReturnDatesAsStrings'=>true));
if ($conn === false) {
$ksp_path = getKSPpath();
$connectionInfo = array( "Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd,
"ColumnEncryption"=>"enabled",
"CEKeystoreProvider"=>$ksp_path,
"CEKeystoreName"=>$ksp_name,
"CEKeystoreEncryptKey"=>$encrypt_key,
'ReturnDatesAsStrings'=>true);
$conn = sqlsrv_connect( $server, $connectionInfo );
if( $conn === false )
{
echo "Failed to connect.\n"; echo "Failed to connect.\n";
print_r( sqlsrv_errors() ); print_r(sqlsrv_errors());
} } else {
else
{
echo "Connected successfully with ColumnEncryption enabled.\n"; echo "Connected successfully with ColumnEncryption enabled.\n";
} }
$ksp_test_table = AE\KSP_TEST_TABLE;
$tsql = "SELECT * FROM $ksp_test_table"; $tsql = "SELECT * FROM $ksp_test_table";
$stmt = sqlsrv_prepare($conn, $tsql); $stmt = sqlsrv_prepare($conn, $tsql);
if (! sqlsrv_execute($stmt) ) if (!sqlsrv_execute($stmt)) {
{
echo "Failed to fetch data.\n"; echo "Failed to fetch data.\n";
print_r( sqlsrv_errors() ); print_r(sqlsrv_errors());
} }
// fetch data // fetch data
while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC )) while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)) {
{
echo "c1=" . $row[0] . "\tc2=" . $row[1] . "\tc3=" . $row[2] . "\tc4=" . $row[3] . "\n" ; echo "c1=" . $row[0] . "\tc2=" . $row[1] . "\tc3=" . $row[2] . "\tc4=" . $row[3] . "\n" ;
} }
sqlsrv_free_stmt($stmt); sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); sqlsrv_close($conn);
@ -61,4 +46,4 @@ c1=67 c2=Sample data 6 for column 2 c3=ghi c4=2017-08-16
c1=78 c2=Sample data 7 for column 2 c3=hij c4=2017-08-17 c1=78 c2=Sample data 7 for column 2 c3=hij c4=2017-08-17
c1=89 c2=Sample data 8 for column 2 c3=ijk c4=2017-08-18 c1=89 c2=Sample data 8 for column 2 c3=ijk c4=2017-08-18
c1=100 c2=Sample data 9 for column 2 c3=jkl c4=2017-08-19 c1=100 c2=Sample data 9 for column 2 c3=jkl c4=2017-08-19
Done Done

View file

@ -4,50 +4,34 @@ Fetch encrypted data from a prepopulated test table given a custom keystore prov
<?php require('skipif_not_ksp.inc'); ?> <?php require('skipif_not_ksp.inc'); ?>
--FILE-- --FILE--
<?php <?php
sqlsrv_configure( 'WarningsReturnAsErrors', 1 ); sqlsrv_configure('WarningsReturnAsErrors', 1);
sqlsrv_configure( 'LogSeverity', SQLSRV_LOG_SEVERITY_ALL ); sqlsrv_configure('LogSeverity', SQLSRV_LOG_SEVERITY_ALL);
require( 'MsSetup.inc' ); require_once('MsHelper.inc');
require( 'AE_Ksp.inc' ); $conn = AE\connect(array('ReturnDatesAsStrings'=>true));
if ($conn === false) {
$ksp_path = getKSPpath(); fatalError("Failed to connect.\n");
} else {
$connectionInfo = array( "Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd,
"CEKeystoreProvider"=>$ksp_path,
"CEKeystoreName"=>$ksp_name,
"CEKeystoreEncryptKey"=>$encrypt_key,
'ReturnDatesAsStrings'=>true);
$conn = sqlsrv_connect( $server, $connectionInfo );
if( $conn === false )
{
echo "Failed to connect.\n";
print_r( sqlsrv_errors() );
}
else
{
echo "Connected successfully with ColumnEncryption disabled.\n"; echo "Connected successfully with ColumnEncryption disabled.\n";
} }
$ksp_test_table = AE\KSP_TEST_TABLE;
$tsql = "SELECT * FROM $ksp_test_table"; $tsql = "SELECT * FROM $ksp_test_table";
$stmt = sqlsrv_prepare($conn, $tsql); $stmt = sqlsrv_prepare($conn, $tsql);
if (! sqlsrv_execute($stmt) ) if (!sqlsrv_execute($stmt)) {
{ fatalError("Failed to fetch data.\n");
echo "Failed to fetch data.\n";
print_r( sqlsrv_errors() );
} }
// fetch data // fetch data
while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC )) while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)) {
{
// all columns should return binary data except the first column // all columns should return binary data except the first column
echo "c1=" . $row[0]; echo "c1=" . $row[0];
echo "\tc2=" . bin2hex($row[1]); echo "\tc2=" . bin2hex($row[1]);
echo "\tc3=" . bin2hex($row[2]); echo "\tc3=" . bin2hex($row[2]);
echo "\tc4=" . bin2hex($row[3]); echo "\tc4=" . bin2hex($row[3]);
echo "\n" ; echo "\n" ;
} }
sqlsrv_free_stmt($stmt); sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); sqlsrv_close($conn);

View file

@ -5,91 +5,88 @@ Connect using a custom keystore provider with some required inputs missing
--FILE-- --FILE--
<?php <?php
function connect( $server, $connectionInfo ) function connect($server, $connectionInfo)
{ {
$conn = sqlsrv_connect( $server, $connectionInfo ); $conn = sqlsrv_connect($server, $connectionInfo);
if( $conn === false ) if ($conn === false) {
{
echo "Failed to connect.\n"; echo "Failed to connect.\n";
$errors = sqlsrv_errors(); $errors = sqlsrv_errors();
foreach ( $errors[0] as $key => $error ) foreach ($errors[0] as $key => $error) {
{ if(is_string($key)) {
if( is_string( $key ) )
echo "[$key] => $error\n"; echo "[$key] => $error\n";
}
} }
echo "\n"; echo "\n";
} } else {
else
{
echo "Connected successfully with ColumnEncryption enabled.\n"; echo "Connected successfully with ColumnEncryption enabled.\n";
} }
return $conn; return $conn;
} }
sqlsrv_configure( 'LogSeverity', SQLSRV_LOG_SEVERITY_ALL );
require( 'MsSetup.inc' ); sqlsrv_configure('LogSeverity', SQLSRV_LOG_SEVERITY_ALL);
require( 'AE_Ksp.inc' );
$ksp_path = getKSPpath();
echo("Connecting... with column encryption\n"); require_once('MsHelper.inc');
$connectionInfo = array( "Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd, $ksp_path = AE\getKSPpath();
"ColumnEncryption"=>"enabled"); $ksp_name = AE\KSP_NAME;
$encrypt_key = AE\ENCRYPT_KEY;
connect( $server, $connectionInfo ); echo "Connecting... with column encryption\n";
$connectionInfo = array("Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd,
echo("Connecting... with an invalid input to CEKeystoreProvider\n"); "ColumnEncryption"=>"enabled");
$connectionInfo = array( "Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd,
"ColumnEncryption"=>"enabled",
"CEKeystoreProvider"=>1);
connect( $server, $connectionInfo ); connect($server, $connectionInfo);
echo("Connecting... with an empty path\n"); echo "Connecting... with an invalid input to CEKeystoreProvider\n";
$connectionInfo = array( "Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd, $connectionInfo = array("Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd,
"ColumnEncryption"=>"enabled", "ColumnEncryption"=>"enabled",
"CEKeystoreProvider"=>"", "CEKeystoreProvider"=>1);
"CEKeystoreName"=>$ksp_name,
"CEKeystoreEncryptKey"=>$encrypt_key);
connect( $server, $connectionInfo ); connect($server, $connectionInfo);
echo("Connecting... without a name\n");
$connectionInfo = array( "Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd,
"ColumnEncryption"=>"enabled",
"CEKeystoreProvider"=>$ksp_path,
"CEKeystoreEncryptKey"=>$encrypt_key);
connect( $server, $connectionInfo ); echo "Connecting... with an empty path\n";
$connectionInfo = array("Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd,
"ColumnEncryption"=>"enabled",
"CEKeystoreProvider"=>"",
"CEKeystoreName"=>$ksp_name,
"CEKeystoreEncryptKey"=>$encrypt_key);
echo("Connecting... with an empty name\n"); connect($server, $connectionInfo);
$connectionInfo = array( "Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd,
"ColumnEncryption"=>"enabled",
"CEKeystoreProvider"=>$ksp_path,
"CEKeystoreName"=>"",
"CEKeystoreEncryptKey"=>$encrypt_key);
connect( $server, $connectionInfo ); echo "Connecting... without a name\n";
$connectionInfo = array("Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd,
"ColumnEncryption"=>"enabled",
"CEKeystoreProvider"=>$ksp_path,
"CEKeystoreEncryptKey"=>$encrypt_key);
echo("Connecting... without a key\n"); connect($server, $connectionInfo);
$connectionInfo = array( "Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd,
"ColumnEncryption"=>"enabled", echo "Connecting... with an empty name\n";
"CEKeystoreProvider"=>$ksp_path, $connectionInfo = array("Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd,
"CEKeystoreName"=>$ksp_name); "ColumnEncryption"=>"enabled",
"CEKeystoreProvider"=>$ksp_path,
connect( $server, $connectionInfo ); "CEKeystoreName"=>"",
"CEKeystoreEncryptKey"=>$encrypt_key);
connect($server, $connectionInfo);
echo "Connecting... without a key\n";
$connectionInfo = array("Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd,
"ColumnEncryption"=>"enabled",
"CEKeystoreProvider"=>$ksp_path,
"CEKeystoreName"=>$ksp_name);
connect($server, $connectionInfo);
echo "Connecting... with all required inputs\n";
$connectionInfo = array("Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd,
"ColumnEncryption"=>"enabled",
"CEKeystoreProvider"=>$ksp_path,
"CEKeystoreName"=>$ksp_name,
"CEKeystoreEncryptKey"=>$encrypt_key);
connect($server, $connectionInfo);
echo("Connecting... with all required inputs\n");
$connectionInfo = array( "Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd,
"ColumnEncryption"=>"enabled",
"CEKeystoreProvider"=>$ksp_path,
"CEKeystoreName"=>$ksp_name,
"CEKeystoreEncryptKey"=>$encrypt_key);
connect( $server, $connectionInfo );
echo "Done\n"; echo "Done\n";
?> ?>
--EXPECT-- --EXPECT--

View file

@ -4,205 +4,168 @@ Test simple insert, fetch and update with ColumnEncryption enabled and a custome
<?php require('skipif_not_ksp.inc'); ?> <?php require('skipif_not_ksp.inc'); ?>
--FILE-- --FILE--
<?php <?php
function CreatePatientsTable() function createPatientsTable()
{ {
global $conn; global $conn;
$tablename = 'Patients'; $tableName = 'Patients';
$stmt = sqlsrv_query( $conn, "IF OBJECT_ID('$tablename', 'U') IS NOT NULL DROP TABLE $tablename" );
sqlsrv_free_stmt( $stmt );
$tsql = "CREATE TABLE $tablename ( $columns = array(new AE\ColumnMeta('int', 'PatientId', 'IDENTITY(1,1) NOT NULL'),
[PatientId] [int] IDENTITY(1,1) NOT NULL, new AE\ColumnMeta('char(11)', 'SSN'),
[SSN] [char](11) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = CustomCEK, ENCRYPTION_TYPE = Deterministic, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NOT NULL, new AE\ColumnMeta('nvarchar(50)', 'FirstName'),
[FirstName] [nvarchar](50) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = CustomCEK, ENCRYPTION_TYPE = Deterministic, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NULL, new AE\ColumnMeta('nvarchar(50)', 'LastName'),
[LastName] [nvarchar](50) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = CustomCEK, ENCRYPTION_TYPE = Deterministic, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NULL, new AE\ColumnMeta('date', 'BirthDate'));
[BirthDate] [date] ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = CustomCEK, ENCRYPTION_TYPE = Randomized, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NOT NULL)"; $stmt = AE\createTable($conn, $tableName, $columns);
if (!$stmt) {
$stmt = sqlsrv_query( $conn, $tsql ); fatalError("Failed to create test table!\n");
if (! $stmt )
{
echo "Failed to create test table!\n";
die( print_r( sqlsrv_errors(), true ));
} }
return $tablename; return $tableName;
} }
function InsertData($ssn, $fname, $lname, $date) function insertData($ssn, $fname, $lname, $date)
{ {
global $conn, $tablename; global $conn, $tableName;
$params = array( $params = array(
array($ssn, null, null, SQLSRV_SQLTYPE_CHAR(11)), array($fname, null, null, SQLSRV_SQLTYPE_NVARCHAR(50)), array($lname, null, null, SQLSRV_SQLTYPE_NVARCHAR(50)), array($date, null, null, SQLSRV_SQLTYPE_DATE) array($ssn, null, null, SQLSRV_SQLTYPE_CHAR(11)), array($fname, null, null, SQLSRV_SQLTYPE_NVARCHAR(50)), array($lname, null, null, SQLSRV_SQLTYPE_NVARCHAR(50)), array($date, null, null, SQLSRV_SQLTYPE_DATE)
); );
$tsql = "INSERT INTO $tablename (SSN, FirstName, LastName, BirthDate) VALUES (?, ?, ?, ?)"; $tsql = "INSERT INTO $tableName (SSN, FirstName, LastName, BirthDate) VALUES (?, ?, ?, ?)";
if (! $stmt = sqlsrv_prepare($conn, $tsql, $params)) if (! $stmt = sqlsrv_prepare($conn, $tsql, $params)) {
{ fatalError("Failed to prepare statement.\n");
echo "Failed to prepare statement.\n";
print_r( sqlsrv_errors() );
} }
if (! sqlsrv_execute($stmt)) if (! sqlsrv_execute($stmt)) {
{ fatalError("Failed to insert a new record.\n");
echo "Failed to insert a new record.\n";
print_r( sqlsrv_errors() );
} }
} }
function SelectData()
{
global $conn, $tablename;
$stmt = sqlsrv_query($conn, "SELECT * FROM $tablename");
while ($obj = sqlsrv_fetch_object( $stmt )) function selectData()
{ {
global $conn, $tableName;
$stmt = sqlsrv_query($conn, "SELECT * FROM $tableName");
while ($obj = sqlsrv_fetch_object($stmt)) {
echo $obj->PatientId . "\n"; echo $obj->PatientId . "\n";
echo $obj->SSN . "\n"; echo $obj->SSN . "\n";
echo $obj->FirstName . "\n"; echo $obj->FirstName . "\n";
echo $obj->LastName . "\n"; echo $obj->LastName . "\n";
echo $obj->BirthDate . "\n\n"; echo $obj->BirthDate . "\n\n";
} }
} }
function SelectDataBuffered() function selectDataBuffered()
{ {
global $conn, $tablename; global $conn, $tableName;
$stmt = sqlsrv_query($conn, "SELECT * FROM $tablename", array(), array("Scrollable"=>"buffered")); $stmt = sqlsrv_query($conn, "SELECT * FROM $tableName", array(), array("Scrollable"=>"buffered"));
$row_count = sqlsrv_num_rows($stmt); $row_count = sqlsrv_num_rows($stmt);
echo "\nRow count for result set is $row_count\n"; echo "\nRow count for result set is $row_count\n";
echo "First record=>\t"; echo "First record=>\t";
$row = sqlsrv_fetch($stmt, SQLSRV_SCROLL_FIRST); $row = sqlsrv_fetch($stmt, SQLSRV_SCROLL_FIRST);
$SSN = sqlsrv_get_field( $stmt, 1); $SSN = sqlsrv_get_field($stmt, 1);
echo "SSN = $SSN \n"; echo "SSN = $SSN\n";
echo "Next record=>\t"; echo "Next record=>\t";
$row = sqlsrv_fetch($stmt, SQLSRV_SCROLL_NEXT); $row = sqlsrv_fetch($stmt, SQLSRV_SCROLL_NEXT);
$BirthDate = sqlsrv_get_field( $stmt, 4); $BirthDate = sqlsrv_get_field($stmt, 4);
echo "BirthDate = $BirthDate \n"; echo "BirthDate = $BirthDate\n";
echo "Last record=>\t"; echo "Last record=>\t";
$row = sqlsrv_fetch($stmt, SQLSRV_SCROLL_LAST); $row = sqlsrv_fetch($stmt, SQLSRV_SCROLL_LAST);
$LastName = sqlsrv_get_field( $stmt, 3); $LastName = sqlsrv_get_field($stmt, 3);
echo "LastName = $LastName \n"; echo "LastName = $LastName\n";
} }
sqlsrv_configure( 'WarningsReturnAsErrors', 1 );
sqlsrv_configure( 'LogSeverity', SQLSRV_LOG_SEVERITY_ALL );
require_once( 'MsSetup.inc' ); sqlsrv_configure('WarningsReturnAsErrors', 1);
require_once( 'AE_Ksp.inc' ); sqlsrv_configure('LogSeverity', SQLSRV_LOG_SEVERITY_ALL);
$ksp_path = getKSPpath(); require_once('MsHelper.inc');
$conn = AE\connect(array('ReturnDatesAsStrings'=>true));
$connectionInfo = array( "Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd, if ($conn === false) {
"ReturnDatesAsStrings"=>true, "ColumnEncryption"=>'Enabled', fatalError( "Failed to connect.\n");
"CEKeystoreProvider"=>$ksp_path, } else {
"CEKeystoreName"=>$ksp_name,
"CEKeystoreEncryptKey"=>$encrypt_key);
$conn = sqlsrv_connect( $server, $connectionInfo );
if( $conn === false )
{
echo "Failed to connect.\n";
print_r( sqlsrv_errors() );
}
else
{
echo "Connected successfully with ColumnEncryption enabled.\n"; echo "Connected successfully with ColumnEncryption enabled.\n";
} }
$tablename = CreatePatientsTable(); $tableName = createPatientsTable();
InsertData('748-68-0245', 'Jeannette', 'McDonald', '2002-11-28'); insertData('748-68-0245', 'Jeannette', 'McDonald', '2002-11-28');
InsertData('795-73-9838', 'John', 'Doe', '2001-05-29'); insertData('795-73-9838', 'John', 'Doe', '2001-05-29');
InsertData('456-12-5486', 'Jonathan', 'Wong', '1999-12-20'); insertData('456-12-5486', 'Jonathan', 'Wong', '1999-12-20');
InsertData('156-45-5486', 'Marianne', 'Smith', '1997-03-04'); insertData('156-45-5486', 'Marianne', 'Smith', '1997-03-04');
SelectData(); selectData();
/////////////////////////////////////////// ///////////////////////////////////////////
echo "Update Patient Jonathan Wong...\n"; echo "Update Patient Jonathan Wong...\n";
$params = array(array('1999-12-31', null, null, SQLSRV_SQLTYPE_DATE), array('Chang', null, null, SQLSRV_SQLTYPE_NVARCHAR(50)), array('456-12-5486', null, null, SQLSRV_SQLTYPE_CHAR(11))); $params = array(array('1999-12-31', null, null, SQLSRV_SQLTYPE_DATE),
array('Chang', null, null, SQLSRV_SQLTYPE_NVARCHAR(50)),
$tsql = "UPDATE Patients SET BirthDate = ?, LastName = ? WHERE SSN = ?"; array('456-12-5486', null, null, SQLSRV_SQLTYPE_CHAR(11)));
$tsql = "UPDATE $tableName SET BirthDate = ?, LastName = ? WHERE SSN = ?";
$stmt = sqlsrv_query($conn, $tsql, $params); $stmt = sqlsrv_query($conn, $tsql, $params);
if (! $stmt) if (!$stmt) {
{ fatalError("Failed to update record\n");
echo "Failed to update record\n";
print_r( sqlsrv_errors() );
} }
echo "Update his birthdate too...\n"; echo "Update his birthdate too...\n";
$params = array(array('456-12-5486', null, null, SQLSRV_SQLTYPE_CHAR(11))); $params = array(array('456-12-5486', null, null, SQLSRV_SQLTYPE_CHAR(11)));
$tsql = "SELECT SSN, FirstName, LastName, BirthDate FROM Patients WHERE SSN = ?"; $tsql = "SELECT SSN, FirstName, LastName, BirthDate FROM $tableName WHERE SSN = ?";
$stmt = sqlsrv_query($conn, $tsql, $params); $stmt = sqlsrv_query($conn, $tsql, $params);
if (! $stmt) if (!$stmt) {
{ fatalError("Failed to select with a WHERE clause\n");
echo "Failed to select with a WHERE clause\n"; } else {
print_r( sqlsrv_errors() ); $obj = sqlsrv_fetch_object($stmt);
} echo "BirthDate updated for $obj->FirstName:\n";
else
{
$obj = sqlsrv_fetch_object( $stmt );
echo "BirthDate updated for $obj->FirstName:\n";
echo $obj->SSN . "\n"; echo $obj->SSN . "\n";
echo $obj->FirstName . "\n"; echo $obj->FirstName . "\n";
echo $obj->LastName . "\n"; echo $obj->LastName . "\n";
echo $obj->BirthDate . "\n\n"; echo $obj->BirthDate . "\n\n";
} }
/////////////////////////////////////////// ///////////////////////////////////////////
$procName = '#phpAEProc1'; $procName = '#phpAEProc1';
$spArgs = "@p1 INT, @p2 DATE OUTPUT"; $spArgs = "@p1 INT, @p2 DATE OUTPUT";
$spCode = "SET @p2 = ( SELECT [BirthDate] FROM Patients WHERE [PatientId] = @p1 )"; $spCode = "SET @p2 = (SELECT [BirthDate] FROM $tableName WHERE [PatientId] = @p1)";
$stmt = sqlsrv_query($conn, "CREATE PROC [$procName] ($spArgs) AS BEGIN $spCode END"); $stmt = sqlsrv_query($conn, "CREATE PROC [$procName] ($spArgs) AS BEGIN $spCode END");
sqlsrv_free_stmt($stmt); sqlsrv_free_stmt($stmt);
$callResult = '1900-01-01'; $callResult = '1900-01-01';
//when binding parameter using sqlsrv_query in a column encryption enabled connection, need to provide the sql_type in all parameters //when binding parameter using sqlsrv_query in a column encryption enabled connection, need to provide the sql_type in all parameters
$params = array( array( 1, SQLSRV_PARAM_IN, null, SQLSRV_SQLTYPE_INT ), array( &$callResult, SQLSRV_PARAM_OUT, null, SQLSRV_SQLTYPE_DATE)); $params = array(array(1, SQLSRV_PARAM_IN, null, SQLSRV_SQLTYPE_INT),
array(&$callResult, SQLSRV_PARAM_OUT, null, SQLSRV_SQLTYPE_DATE));
$callArgs = "?, ?"; $callArgs = "?, ?";
$stmt = sqlsrv_query($conn, "{ CALL [$procName] ($callArgs)}", $params); $stmt = sqlsrv_query($conn, "{ CALL [$procName] ($callArgs)}", $params);
if (! $stmt ) if (!$stmt) {
{ print_r(sqlsrv_errors());
print_r( sqlsrv_errors() ); } else {
}
else
{
echo "BirthDate for the first record is: $callResult\n"; echo "BirthDate for the first record is: $callResult\n";
} }
/////////////////////////////////////////// ///////////////////////////////////////////
$procName = '#phpAEProc2'; $procName = '#phpAEProc2';
$spArgs = "@p1 INT, @p2 CHAR(11) OUTPUT"; $spArgs = "@p1 INT, @p2 CHAR(11) OUTPUT";
$spCode = "SET @p2 = ( SELECT [SSN] FROM Patients WHERE [PatientId] = @p1 )"; $spCode = "SET @p2 = (SELECT [SSN] FROM $tableName WHERE [PatientId] = @p1)";
$stmt = sqlsrv_query($conn, "CREATE PROC [$procName] ($spArgs) AS BEGIN $spCode END"); $stmt = sqlsrv_query($conn, "CREATE PROC [$procName] ($spArgs) AS BEGIN $spCode END");
sqlsrv_free_stmt($stmt); sqlsrv_free_stmt($stmt);
$callResult = '000-00-0000'; $callResult = '000-00-0000';
//when binding parameter using sqlsrv_query in a column encryption enabled connection, need to provide the sql_type in all parameters // when binding parameter using sqlsrv_query in a column encryption enabled connection,
$params = array( array( 1, SQLSRV_PARAM_IN, null, SQLSRV_SQLTYPE_INT ), array( &$callResult, SQLSRV_PARAM_OUT, null, SQLSRV_SQLTYPE_CHAR(11))); // need to provide the sql_type in all parameters
$params = array(array(1, SQLSRV_PARAM_IN, null, SQLSRV_SQLTYPE_INT),
array(&$callResult, SQLSRV_PARAM_OUT, null, SQLSRV_SQLTYPE_CHAR(11)));
$callArgs = "?, ?"; $callArgs = "?, ?";
$stmt = sqlsrv_query($conn, "{ CALL [$procName] ($callArgs)}", $params); $stmt = sqlsrv_query($conn, "{ CALL [$procName] ($callArgs)}", $params);
if (! $stmt ) if (!$stmt) {
{ print_r(sqlsrv_errors());
print_r( sqlsrv_errors() ); } else {
}
else
{
echo "SSN for the first record is: $callResult\n"; echo "SSN for the first record is: $callResult\n";
} }
SelectDataBuffered(); selectDataBuffered();
echo "\nDone\n"; echo "\nDone\n";
?> ?>
--EXPECT-- --EXPECT--
@ -243,8 +206,8 @@ BirthDate for the first record is: 2002-11-28
SSN for the first record is: 748-68-0245 SSN for the first record is: 748-68-0245
Row count for result set is 4 Row count for result set is 4
First record=> SSN = 748-68-0245 First record=> SSN = 748-68-0245
Next record=> BirthDate = 2001-05-29 Next record=> BirthDate = 2001-05-29
Last record=> LastName = Smith Last record=> LastName = Smith
Done Done

View file

@ -1,118 +1,96 @@
--TEST-- --TEST--
Test using sqlserv_query for binding parameters with ColumnEncryption enabled and a custome keystore provider Test using sqlsrv_query for binding parameters with column encryption and a custom keystore provider
--SKIPIF-- --SKIPIF--
<?php require('skipif_not_ksp.inc'); ?> <?php require('skipif_not_ksp.inc'); ?>
--FILE-- --FILE--
<?php <?php
function CreatePatientsTable() function createPatientsTable()
{ {
global $conn; global $conn;
$tablename = 'Patients'; $tableName = 'Patients';
$stmt = sqlsrv_query( $conn, "IF OBJECT_ID('$tablename', 'U') IS NOT NULL DROP TABLE $tablename" );
sqlsrv_free_stmt( $stmt );
$tsql = "CREATE TABLE $tablename ( $columns = array(new AE\ColumnMeta('int', 'PatientId', 'IDENTITY(1,1) NOT NULL'),
[PatientId] [int] IDENTITY(1,1) NOT NULL, new AE\ColumnMeta('char(11)', 'SSN'),
[SSN] [char](11) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = CustomCEK, ENCRYPTION_TYPE = Deterministic, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NOT NULL, new AE\ColumnMeta('nvarchar(50)', 'FirstName'),
[FirstName] [nvarchar](50) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = CustomCEK, ENCRYPTION_TYPE = Deterministic, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NULL, new AE\ColumnMeta('nvarchar(50)', 'LastName'),
[LastName] [nvarchar](50) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = CustomCEK, ENCRYPTION_TYPE = Deterministic, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NULL, new AE\ColumnMeta('date', 'BirthDate'));
[BirthDate] [date] ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = CustomCEK, ENCRYPTION_TYPE = Randomized, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NOT NULL)"; $stmt = AE\createTable($conn, $tableName, $columns);
if (!$stmt) {
$stmt = sqlsrv_query( $conn, $tsql ); fatalError("Failed to create test table!\n");
if (! $stmt )
{
echo "Failed to create test table!\n";
die( print_r( sqlsrv_errors(), true ));
} }
return $tableName;
return $tablename;
} }
function SelectData()
{
global $conn, $tablename;
$stmt = sqlsrv_query($conn, "SELECT * FROM $tablename");
while ($obj = sqlsrv_fetch_object( $stmt )) function selectData()
{ {
global $conn, $tableName;
$stmt = sqlsrv_query($conn, "SELECT * FROM $tableName");
while ($obj = sqlsrv_fetch_object($stmt)) {
echo $obj->PatientId . "\n"; echo $obj->PatientId . "\n";
echo $obj->SSN . "\n"; echo $obj->SSN . "\n";
echo $obj->FirstName . "\n"; echo $obj->FirstName . "\n";
echo $obj->LastName . "\n"; echo $obj->LastName . "\n";
echo $obj->BirthDate . "\n\n"; echo $obj->BirthDate . "\n\n";
}
}
function PrintError()
{
$errors = sqlsrv_errors();
foreach ( $errors as $error )
{
echo " SQLSTATE: " . $error['SQLSTATE'] . "\n";
echo " code: " . $error['code'] . "\n";
echo " message: " . $error['message'] . "\n\n";
} }
} }
sqlsrv_configure( 'WarningsReturnAsErrors', 1 );
sqlsrv_configure( 'LogSeverity', SQLSRV_LOG_SEVERITY_ALL );
require_once( 'MsSetup.inc' ); function printError()
require_once( 'AE_Ksp.inc' );
$ksp_path = getKSPpath();
$connectionInfo = array( "Database"=>$databaseName, "UID"=>$uid, "PWD"=>$pwd,
"ReturnDatesAsStrings"=>true, "ColumnEncryption"=>'Enabled',
"CEKeystoreProvider"=>$ksp_path,
"CEKeystoreName"=>$ksp_name,
"CEKeystoreEncryptKey"=>$encrypt_key);
$conn = sqlsrv_connect( $server, $connectionInfo );
if( $conn === false )
{ {
echo "Failed to connect.\n"; $errors = sqlsrv_errors();
PrintError(); foreach ($errors as $error) {
echo " SQLSTATE: " . $error['SQLSTATE'] . "\n";
echo " code: " . $error['code'] . "\n";
echo " message: " . $error['message'] . "\n\n";
}
} }
else
{ sqlsrv_configure('WarningsReturnAsErrors', 1);
sqlsrv_configure('LogSeverity', SQLSRV_LOG_SEVERITY_ALL);
require_once('MsHelper.inc');
$conn = AE\connect(array('ReturnDatesAsStrings'=>true));
if ($conn === false) {
echo "Failed to connect.\n";
printError();
} else {
echo "Connected successfully with ColumnEncryption enabled.\n\n"; echo "Connected successfully with ColumnEncryption enabled.\n\n";
} }
$tablename = CreatePatientsTable(); $tableName = createPatientsTable();
$tsql = "INSERT INTO $tablename (SSN, FirstName, LastName, BirthDate) VALUES (?, ?, ?, ?)"; $tsql = "INSERT INTO $tableName (SSN, FirstName, LastName, BirthDate) VALUES (?, ?, ?, ?)";
$inputs = array( '748-68-0245', 'Jeannette', 'McDonald', '2002-11-28' ); $inputs = array('748-68-0245', 'Jeannette', 'McDonald', '2002-11-28');
//expects an error in Column Encryption enabled connection // expects an error in Column Encryption enabled connection
print_r( "Using sqlsrv_query and binding parameters with literal values:\n" ); print_r("Using sqlsrv_query and binding parameters with literal values:\n");
$stmt = sqlsrv_query( $conn, $tsql, $inputs ); $stmt = sqlsrv_query($conn, $tsql, $inputs);
if ( !$stmt) if (!$stmt) {
PrintError(); printError();
}
//expects an error in Column Encryption enabled connection
print_r( "Using sqlsrv_query and binding parameters with parameter arrays and no sqltypes provided:\n" ); // expects an error in Column Encryption enabled connection
$stmt = sqlsrv_query( $conn, $tsql, array( array( $inputs[0], SQLSRV_PARAM_IN ), print_r("Using sqlsrv_query and binding parameters with parameter arrays and no sqltypes provided:\n");
array( $inputs[1], SQLSRV_PARAM_IN ), $stmt = sqlsrv_query($conn, $tsql, array(array($inputs[0], SQLSRV_PARAM_IN),
array( $inputs[2], SQLSRV_PARAM_IN ), array($inputs[1], SQLSRV_PARAM_IN),
array( $inputs[3], SQLSRV_PARAM_IN ))); array($inputs[2], SQLSRV_PARAM_IN),
if ( !$stmt) array($inputs[3], SQLSRV_PARAM_IN)));
PrintError(); if (!$stmt) {
printError();
//no error is expected }
print_r( "Using sqlsrv_query and binding parameters with parameter arrays and sqltypes provided:\n" ); // no error is expected
$stmt = sqlsrv_query( $conn, $tsql, array( array( $inputs[0], null, null, SQLSRV_SQLTYPE_CHAR(11) ), print_r("Using sqlsrv_query and binding parameters with parameter arrays and sqltypes provided:\n");
array( $inputs[1], null, null, SQLSRV_SQLTYPE_NVARCHAR(50) ), $stmt = sqlsrv_query($conn, $tsql, array(array($inputs[0], null, null, SQLSRV_SQLTYPE_CHAR(11)),
array( $inputs[2], null, null, SQLSRV_SQLTYPE_NVARCHAR(50) ), array($inputs[1], null, null, SQLSRV_SQLTYPE_NVARCHAR(50)),
array( $inputs[3], null, null, SQLSRV_SQLTYPE_DATE ) )); array($inputs[2], null, null, SQLSRV_SQLTYPE_NVARCHAR(50)),
if ( !$stmt) array($inputs[3], null, null, SQLSRV_SQLTYPE_DATE)));
PrintError(); if (!$stmt) {
printError();
SelectData(); }
selectData();
echo "Done\n"; echo "Done\n";
?> ?>
--EXPECT-- --EXPECT--

View file

@ -1,24 +1,27 @@
--TEST-- --TEST--
Test with static cursor and select different rows in some random order Test with static cursor and select different rows in some random order
--SKIPIF--
<?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
require_once('MsCommon.inc'); require_once('MsCommon.inc');
function FetchRow_Query($conn) function fetchRowQuery($conn)
{ {
$tableName = GetTempTableName(); $tableName = 'testScrollCursor';
$stmt = sqlsrv_query($conn, "CREATE TABLE $tableName ([c1_int] int, [c2_varchar] varchar(10))"); $columns = array(new AE\ColumnMeta('int', 'c1_int'),
sqlsrv_free_stmt($stmt); new AE\ColumnMeta('varchar(10)', 'c2_varchar'));
AE\createTable($conn, $tableName, $columns);
// insert data // insert data
$numRows = 10; $numRows = 10;
InsertData($conn, $tableName, $numRows); insertData($conn, $tableName, $numRows);
// select table // select table
$stmt = sqlsrv_query($conn, "SELECT * FROM $tableName", array(), array('Scrollable' => 'static')); $stmt = sqlsrv_query($conn, "SELECT * FROM $tableName", array(), array('Scrollable' => 'static'));
HasRows($stmt); hasRows($stmt);
$numRowsFetched = 0; $numRowsFetched = 0;
while ($obj = sqlsrv_fetch_object($stmt)) { while ($obj = sqlsrv_fetch_object($stmt)) {
echo $obj->c1_int . ", " . $obj->c2_varchar . "\n"; echo $obj->c1_int . ", " . $obj->c2_varchar . "\n";
@ -29,25 +32,27 @@ function FetchRow_Query($conn)
echo "Number of rows fetched $numRowsFetched is wrong! Expected $numRows\n"; echo "Number of rows fetched $numRowsFetched is wrong! Expected $numRows\n";
} }
GetFirstRow($stmt); getFirstRow($stmt);
GetNextRow($stmt); getNextRow($stmt);
GetLastRow($stmt); getLastRow($stmt);
GetPriorRow($stmt); getPriorRow($stmt);
GetAbsoluteRow($stmt, 7); getAbsoluteRow($stmt, 7);
GetAbsoluteRow($stmt, 2); getAbsoluteRow($stmt, 2);
GetRelativeRow($stmt, 3); getRelativeRow($stmt, 3);
GetPriorRow($stmt); getPriorRow($stmt);
GetRelativeRow($stmt, -4); getRelativeRow($stmt, -4);
GetAbsoluteRow($stmt, 0); getAbsoluteRow($stmt, 0);
GetNextRow($stmt); getNextRow($stmt);
GetRelativeRow($stmt, 5); getRelativeRow($stmt, 5);
GetAbsoluteRow($stmt, -1); getAbsoluteRow($stmt, -1);
GetNextRow($stmt); getNextRow($stmt);
GetLastRow($stmt); getLastRow($stmt);
GetRelativeRow($stmt, 1); getRelativeRow($stmt, 1);
dropTable($conn, $tableName);
} }
function InsertData($conn, $tableName, $numRows) function insertData($conn, $tableName, $numRows)
{ {
$stmt = sqlsrv_prepare($conn, "INSERT INTO $tableName (c1_int, c2_varchar) VALUES (?, ?)", array(&$v1, &$v2)); $stmt = sqlsrv_prepare($conn, "INSERT INTO $tableName (c1_int, c2_varchar) VALUES (?, ?)", array(&$v1, &$v2));
@ -59,7 +64,7 @@ function InsertData($conn, $tableName, $numRows)
} }
} }
function GetFirstRow($stmt) function getFirstRow($stmt)
{ {
echo "\nfirst row: "; echo "\nfirst row: ";
$result = sqlsrv_fetch($stmt, SQLSRV_SCROLL_FIRST); $result = sqlsrv_fetch($stmt, SQLSRV_SCROLL_FIRST);
@ -70,7 +75,7 @@ function GetFirstRow($stmt)
} }
} }
function GetNextRow($stmt) function getNextRow($stmt)
{ {
echo "\nnext row: "; echo "\nnext row: ";
$result = sqlsrv_fetch($stmt, SQLSRV_SCROLL_NEXT); $result = sqlsrv_fetch($stmt, SQLSRV_SCROLL_NEXT);
@ -81,7 +86,7 @@ function GetNextRow($stmt)
} }
} }
function GetPriorRow($stmt) function getPriorRow($stmt)
{ {
echo "\nprior row: "; echo "\nprior row: ";
$obj = sqlsrv_fetch_object($stmt, null, null, SQLSRV_SCROLL_PRIOR); $obj = sqlsrv_fetch_object($stmt, null, null, SQLSRV_SCROLL_PRIOR);
@ -90,7 +95,7 @@ function GetPriorRow($stmt)
} }
} }
function GetLastRow($stmt) function getLastRow($stmt)
{ {
echo "\nlast row: "; echo "\nlast row: ";
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC, SQLSRV_SCROLL_LAST); $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC, SQLSRV_SCROLL_LAST);
@ -99,7 +104,7 @@ function GetLastRow($stmt)
} }
} }
function GetRelativeRow($stmt, $offset) function getRelativeRow($stmt, $offset)
{ {
echo "\nrow $offset from the current row: "; echo "\nrow $offset from the current row: ";
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_RELATIVE, $offset); $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_RELATIVE, $offset);
@ -108,7 +113,7 @@ function GetRelativeRow($stmt, $offset)
} }
} }
function GetAbsoluteRow($stmt, $offset) function getAbsoluteRow($stmt, $offset)
{ {
echo "\nabsolute row with offset $offset: "; echo "\nabsolute row with offset $offset: ";
$obj = sqlsrv_fetch_object($stmt, null, null, SQLSRV_SCROLL_ABSOLUTE, $offset); $obj = sqlsrv_fetch_object($stmt, null, null, SQLSRV_SCROLL_ABSOLUTE, $offset);
@ -117,7 +122,7 @@ function GetAbsoluteRow($stmt, $offset)
} }
} }
function HasRows($stmt) function hasRows($stmt)
{ {
$rows = sqlsrv_has_rows($stmt); $rows = sqlsrv_has_rows($stmt);
if ($rows != true) { if ($rows != true) {
@ -125,36 +130,18 @@ function HasRows($stmt)
} }
} }
//-------------------------------------------------------------------- set_time_limit(0);
// RunTest sqlsrv_configure('WarningsReturnAsErrors', 1);
//
//--------------------------------------------------------------------
function RunTest()
{
startTest("sqlsrv_fetch_cursor_static_scroll");
try {
set_time_limit(0);
sqlsrv_configure('WarningsReturnAsErrors', 1);
echo "\nTest begins...\n"; echo "\nTest begins...\n";
// Connect // Connect
$conn = connect(); $conn = AE\connect();
if (!$conn) { fetchRowQuery($conn);
fatalError("Could not connect.\n");
}
FetchRow_Query($conn); sqlsrv_close($conn);
echo "\nDone\n";
sqlsrv_close($conn); endTest("sqlsrv_fetch_cursor_static_scroll");
} catch (Exception $e) {
echo $e->getMessage();
}
echo "\nDone\n";
endTest("sqlsrv_fetch_cursor_static_scroll");
}
RunTest();
?> ?>
--EXPECT-- --EXPECT--

View file

@ -1,25 +1,28 @@
--TEST-- --TEST--
Test various cursor types and whether they reflect changes in the database Test various cursor types and whether they reflect changes in the database
--SKIPIF--
<?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
require_once('MsCommon.inc'); require_once('MsCommon.inc');
function Fetch_WithCursor($conn, $cursorType) function fetchWithCursor($conn, $cursorType)
{ {
$tableName = GetTempTableName(); $tableName = "table_$cursorType";
$stmt = sqlsrv_query($conn, "CREATE TABLE $tableName ([c1_int] int, [c2_char] char(10))");
sqlsrv_free_stmt($stmt);
$columns = array(new AE\ColumnMeta('int', 'c1_int'),
new AE\ColumnMeta('char(10)', 'c2_char'));
$stmt = AE\createTable($conn, $tableName, $columns);
// insert four rows // insert four rows
$numRows = 4; $numRows = 4;
InsertData($conn, $tableName, 0, $numRows); insertData($conn, $tableName, 0, $numRows);
// select table // select table
$stmt = sqlsrv_prepare($conn, "SELECT * FROM $tableName", array(), array('Scrollable' => $cursorType)); $stmt = sqlsrv_prepare($conn, "SELECT * FROM $tableName", array(), array('Scrollable' => $cursorType));
sqlsrv_execute($stmt); sqlsrv_execute($stmt);
GetNumRows($stmt, $cursorType); getNumRows($stmt, $cursorType);
$numRowsFetched = 0; $numRowsFetched = 0;
while ($obj = sqlsrv_fetch_object($stmt)) { while ($obj = sqlsrv_fetch_object($stmt)) {
echo $obj->c1_int . "\n"; echo $obj->c1_int . "\n";
@ -30,10 +33,12 @@ function Fetch_WithCursor($conn, $cursorType)
echo "Number of rows fetched $numRowsFetched is wrong! Expected $numRows\n"; echo "Number of rows fetched $numRowsFetched is wrong! Expected $numRows\n";
} }
DeleteThenFetchLastRow($conn, $stmt, $tableName, 4); deleteThenFetchLastRow($conn, $stmt, $tableName, 4);
dropTable($conn, $tableName);
} }
function InsertData($conn, $tableName, $start, $count) function insertData($conn, $tableName, $start, $count)
{ {
$stmt = sqlsrv_prepare($conn, "INSERT INTO $tableName (c1_int, c2_char) VALUES (?, ?)", array(&$v1, &$v2)); $stmt = sqlsrv_prepare($conn, "INSERT INTO $tableName (c1_int, c2_char) VALUES (?, ?)", array(&$v1, &$v2));
@ -46,13 +51,10 @@ function InsertData($conn, $tableName, $start, $count)
} }
} }
function DeleteThenFetchLastRow($conn, $stmt, $tableName, $id) function deleteThenFetchLastRow($conn, $stmt, $tableName, $id)
{ {
echo "\nNow delete the last row then try to fetch it...\n"; echo "\nNow delete the last row then try to fetch it...\n";
$stmt2 = sqlsrv_query($conn, "DELETE FROM $tableName WHERE [c1_int] = 4"); $stmt2 = AE\executeQuery($conn, "DELETE FROM $tableName", "[c1_int] = ?", array(4));
if ($stmt2 !== false) {
sqlsrv_free_stmt($stmt2);
}
$result = sqlsrv_fetch($stmt, SQLSRV_SCROLL_LAST); $result = sqlsrv_fetch($stmt, SQLSRV_SCROLL_LAST);
if ($result) { if ($result) {
@ -65,7 +67,7 @@ function DeleteThenFetchLastRow($conn, $stmt, $tableName, $id)
} }
} }
function GetNumRows($stmt, $cursorType) function getNumRows($stmt, $cursorType)
{ {
$expectedToFail = false; $expectedToFail = false;
if ($cursorType == SQLSRV_CURSOR_FORWARD || $cursorType == SQLSRV_CURSOR_DYNAMIC) { if ($cursorType == SQLSRV_CURSOR_FORWARD || $cursorType == SQLSRV_CURSOR_DYNAMIC) {
@ -89,48 +91,31 @@ function GetNumRows($stmt, $cursorType)
} }
} }
//-------------------------------------------------------------------- try {
// RunTest set_time_limit(0);
// sqlsrv_configure('WarningsReturnAsErrors', 1);
//--------------------------------------------------------------------
function RunTest()
{
startTest("sqlsrv_fetch_cursor_types");
try {
set_time_limit(0);
sqlsrv_configure('WarningsReturnAsErrors', 1);
echo "\nTest begins...\n"; // Connect
$conn = AE\connect();
// Connect echo "\nUsing SQLSRV_CURSOR_FORWARD...\n";
$conn = connect(); fetchWithCursor($conn, SQLSRV_CURSOR_FORWARD);
if (!$conn) { echo "\nUsing SQLSRV_CURSOR_DYNAMIC...\n";
fatalError("Could not connect.\n"); fetchWithCursor($conn, SQLSRV_CURSOR_DYNAMIC);
} echo "\nUsing SQLSRV_CURSOR_KEYSET...\n";
fetchWithCursor($conn, SQLSRV_CURSOR_KEYSET);
echo "\nUsing SQLSRV_CURSOR_STATIC...\n";
fetchWithCursor($conn, SQLSRV_CURSOR_STATIC);
echo "\nUsing SQLSRV_CURSOR_FORWARD...\n"; sqlsrv_close($conn);
Fetch_WithCursor($conn, SQLSRV_CURSOR_FORWARD); } catch (Exception $e) {
echo "\nUsing SQLSRV_CURSOR_DYNAMIC...\n"; echo $e->getMessage();
Fetch_WithCursor($conn, SQLSRV_CURSOR_DYNAMIC);
echo "\nUsing SQLSRV_CURSOR_KEYSET...\n";
Fetch_WithCursor($conn, SQLSRV_CURSOR_KEYSET);
echo "\nUsing SQLSRV_CURSOR_STATIC...\n";
Fetch_WithCursor($conn, SQLSRV_CURSOR_STATIC);
sqlsrv_close($conn);
} catch (Exception $e) {
echo $e->getMessage();
}
echo "\nDone\n";
endTest("sqlsrv_fetch_cursor_types");
} }
echo "\nDone\n";
RunTest(); endTest("sqlsrv_fetch_cursor_types");
?> ?>
--EXPECT-- --EXPECT--

Test begins...
Using SQLSRV_CURSOR_FORWARD... Using SQLSRV_CURSOR_FORWARD...
Error occurred in sqlsrv_num_rows, which is expected Error occurred in sqlsrv_num_rows, which is expected

View file

@ -1,26 +1,23 @@
--TEST-- --TEST--
Fetch missing row Fetch missing row
--SKIPIF--
<?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
require_once('MsCommon.inc'); require_once('MsCommon.inc');
function MissingRow_Fetch() function missingRowFetch()
{ {
set_time_limit(0); set_time_limit(0);
sqlsrv_configure('WarningsReturnAsErrors', 1); sqlsrv_configure('WarningsReturnAsErrors', 1);
// Connect // Connect
$conn = connect(); $conn = AE\connect();
if (!$conn) { $tableName = 'missingRow';
fatalError("Could not connect.\n");
}
$tableName = GetTempTableName(); AE\createTestTable($conn, $tableName);
$stmt = sqlsrv_query($conn, "CREATE TABLE $tableName ([c1_int] int, [c2_tinyint] tinyint, [c3_smallint] smallint, [c4_bigint] bigint, [c5_bit] bit, [c6_float] float, [c7_real] real, [c8_decimal] decimal(28,4), [c9_numeric] numeric(32,4), [c10_money] money, [c11_smallmoney] smallmoney, [c12_char] char(512), [c13_varchar] varchar(512), [c14_varchar_max] varchar(max), [c15_nchar] nchar(512), [c16_nvarchar] nvarchar(512), [c17_nvarchar_max] nvarchar(max), [c18_text] text, [c19_ntext] ntext, [c20_binary] binary(512), [c21_varbinary] varbinary(512), [c22_varbinary_max] varbinary(max), [c23_image] image, [c24_uniqueidentifier] uniqueidentifier, [c25_datetime] datetime, [c26_smalldatetime] smalldatetime, [c27_timestamp] timestamp, [c28_xml] xml, [c29_time] time, [c30_date] date, [c31_datetime2] datetime2, [c32_datetimeoffset] datetimeoffset)"); $stmt = AE\selectFromTable($conn, $tableName);
sqlsrv_free_stmt($stmt);
$stmt = sqlsrv_query($conn, "SELECT * FROM $tableName");
$result1 = sqlsrv_fetch($stmt); $result1 = sqlsrv_fetch($stmt);
$result2 = sqlsrv_fetch($stmt); $result2 = sqlsrv_fetch($stmt);
@ -33,32 +30,18 @@ function MissingRow_Fetch()
$value3 = $e['SQLSTATE']; $value3 = $e['SQLSTATE'];
print "$value3\n"; print "$value3\n";
dropTable($conn, $tableName);
sqlsrv_free_stmt($stmt); sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); sqlsrv_close($conn);
} }
function Repro() missingRowFetch();
{ endTest("sqlsrv_fetch_missing_row");
startTest("sqlsrv_fetch_missing_row");
echo "\nTest begins...\n";
try {
MissingRow_Fetch();
} catch (Exception $e) {
echo $e->getMessage();
}
echo "\nDone\n";
endTest("sqlsrv_fetch_missing_row");
}
Repro();
?> ?>
--EXPECT-- --EXPECT--

Test begins...
There are no more rows in the active result set. Since this result set is not scrollable, no more data may be retrieved. There are no more rows in the active result set. Since this result set is not scrollable, no more data may be retrieved.
-22 -22
IMSSP IMSSP
Done
Test "sqlsrv_fetch_missing_row" completed successfully. Test "sqlsrv_fetch_missing_row" completed successfully.

View file

@ -1,7 +1,7 @@
--TEST-- --TEST--
Test for fetch_object Test for fetch_object
--SKIPIF-- --SKIPIF--
<?php require('skipif.inc'); ?> <?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
@ -41,28 +41,22 @@ class foo_noargs
} // end class foo_noargs } // end class foo_noargs
sqlsrv_configure( 'WarningsReturnAsErrors', 0 ); sqlsrv_configure( 'WarningsReturnAsErrors', 0 );
require( 'MsCommon.inc' ); require_once('MsCommon.inc');
$conn = Connect(); $conn = AE\connect();
if( $conn === false ) { $tableName = 'test_params';
die( print_r( sqlsrv_errors(), true )); $columns = array(new AE\ColumnMeta('tinyint', 'id'),
} new AE\ColumnMeta('char(10)', 'name'),
new AE\ColumnMeta('float', 'double'),
$stmt = sqlsrv_prepare( $conn, "IF OBJECT_ID('test_params', 'U') IS NOT NULL DROP TABLE test_params" ); new AE\ColumnMeta('varchar(max)', 'stuff'));
sqlsrv_execute( $stmt ); AE\createTable($conn, $tableName, $columns);
sqlsrv_free_stmt( $stmt );
$stmt = sqlsrv_prepare( $conn, "CREATE TABLE test_params (id tinyint, name char(10), [double] float, stuff varchar(max))" );
sqlsrv_execute( $stmt );
sqlsrv_free_stmt( $stmt );
$f1 = 1; $f1 = 1;
$f2 = "testtestte"; $f2 = "testtestte";
$f3 = 12.0; $f3 = 12.0;
$f4 = fopen( "data://text/plain,This%20is%20some%20text%20meant%20to%20test%20binding%20parameters%20to%20streams", "r" ); $f4 = fopen( "data://text/plain,This%20is%20some%20text%20meant%20to%20test%20binding%20parameters%20to%20streams", "r" );
$stmt = sqlsrv_prepare( $conn, "INSERT INTO test_params (id, name, [double], stuff) VALUES (?, ?, ?, ?)", array( &$f1, "testtestte", &$f3, &$f4 )); //, $stmt = sqlsrv_prepare( $conn, "INSERT INTO $tableName (id, name, [double], stuff) VALUES (?, ?, ?, ?)", array( &$f1, "testtestte", &$f3, &$f4 ));
//~ array( SQLSRV_SQLTYPE_INTEGER, SQLSRV_SQLTYPE_CHAR(10), SQLSRV_SQLTYPE_DOUBLE, SQLSRV_SQLTYPE_VARBINARY(4000)));
if( !$stmt ) { if( !$stmt ) {
var_dump( sqlsrv_errors() ); var_dump( sqlsrv_errors() );
die( "sqlsrv_prepare failed." ); die( "sqlsrv_prepare failed." );
@ -147,7 +141,7 @@ if( !is_null( $success )) {
sqlsrv_free_stmt( $stmt ); sqlsrv_free_stmt( $stmt );
$stmt = sqlsrv_prepare( $conn, "SELECT id, [double], name, stuff FROM test_params" ); $stmt = sqlsrv_prepare( $conn, "SELECT id, [double], name, stuff FROM $tableName" );
$success = sqlsrv_execute( $stmt ); $success = sqlsrv_execute( $stmt );
if( !$success ) { if( !$success ) {
var_dump( sqlsrv_errors() ); var_dump( sqlsrv_errors() );
@ -239,7 +233,7 @@ else {
print_r( $obj ); print_r( $obj );
} }
sqlsrv_query( $conn, "DROP TABLE test_params" ); dropTable($conn, $tableName);
sqlsrv_free_stmt( $stmt ); sqlsrv_free_stmt( $stmt );
sqlsrv_close( $conn ); sqlsrv_close( $conn );

View file

@ -1,7 +1,7 @@
--TEST-- --TEST--
Test for fetch_object Test for fetch_object
--SKIPIF-- --SKIPIF--
<?php require('skipif.inc'); ?> <?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
@ -41,29 +41,22 @@ class foo_noargs
} // end class foo_noargs } // end class foo_noargs
sqlsrv_configure( 'WarningsReturnAsErrors', 0 ); sqlsrv_configure( 'WarningsReturnAsErrors', 0 );
require_once('MsCommon.inc');
require( 'MsCommon.inc' ); $conn = AE\connect();
$tableName = 'test_params';
$conn = Connect(); $columns = array(new AE\ColumnMeta('tinyint', 'id'),
if( $conn === false ) { new AE\ColumnMeta('char(10)', 'name'),
die( print_r( sqlsrv_errors(), true )); new AE\ColumnMeta('float', 'double'),
} new AE\ColumnMeta('varchar(max)', 'stuff'));
AE\createTable($conn, $tableName, $columns);
$stmt = sqlsrv_prepare( $conn, "IF OBJECT_ID('test_params', 'U') IS NOT NULL DROP TABLE test_params" );
sqlsrv_execute( $stmt );
sqlsrv_free_stmt( $stmt );
$stmt = sqlsrv_prepare( $conn, "CREATE TABLE test_params (id tinyint, name char(10), [double] float, stuff varchar(max))" );
sqlsrv_execute( $stmt );
sqlsrv_free_stmt( $stmt );
$f1 = 1; $f1 = 1;
$f2 = "testtestte"; $f2 = "testtestte";
$f3 = 12.0; $f3 = 12.0;
$f4 = fopen( "data://text/plain,This%20is%20some%20text%20meant%20to%20test%20binding%20parameters%20to%20streams", "r" ); $f4 = fopen( "data://text/plain,This%20is%20some%20text%20meant%20to%20test%20binding%20parameters%20to%20streams", "r" );
$stmt = sqlsrv_prepare( $conn, "INSERT INTO test_params (id, name, [double], stuff) VALUES (?, ?, ?, ?)", array( &$f1, "testtestte", &$f3, &$f4 )); //, $stmt = sqlsrv_prepare( $conn, "INSERT INTO $tableName (id, name, [double], stuff) VALUES (?, ?, ?, ?)", array( &$f1, "testtestte", &$f3, &$f4 ));
//~ array( SQLSRV_SQLTYPE_INTEGER, SQLSRV_SQLTYPE_CHAR(10), SQLSRV_SQLTYPE_DOUBLE, SQLSRV_SQLTYPE_VARBINARY(4000)));
if( !$stmt ) { if( !$stmt ) {
var_dump( sqlsrv_errors() ); var_dump( sqlsrv_errors() );
die( "sqlsrv_prepare failed." ); die( "sqlsrv_prepare failed." );
@ -85,7 +78,7 @@ if( !is_null( $success )) {
$f1 = 2; $f1 = 2;
$f3 = 13.0; $f3 = 13.0;
$f4 = fopen( "data://text/plain,This%20is%20some%20more%20text%20meant%20to%20test%20binding%20parameters%20to%20streams", "r" ); $f4 = fopen( "data://text/plain,This%20is%20some%20more%20text%20meant%20to%20test%20binding%20parameters%20to%20streams", "r" );
$stmt2 = sqlsrv_prepare( $conn, "INSERT INTO test_params (id, name, [double], stuff) VALUES (?, ?, ?, ?)", array( &$f1, "testtestte", &$f3, &$f4 )); $stmt2 = sqlsrv_prepare( $conn, "INSERT INTO $tableName (id, name, [double], stuff) VALUES (?, ?, ?, ?)", array( &$f1, "testtestte", &$f3, &$f4 ));
$success = sqlsrv_execute( $stmt2 ); $success = sqlsrv_execute( $stmt2 );
if( !$success ) { if( !$success ) {
var_dump( sqlsrv_errors() ); var_dump( sqlsrv_errors() );
@ -102,7 +95,7 @@ if( !is_null( $success )) {
$f1 = 3; $f1 = 3;
$f3 = 14.0; $f3 = 14.0;
$f4 = fopen( "data://text/plain,This%20is%20some%20more%20text%20meant%20to%20test%20binding%20parameters%20to%20streams", "r" ); $f4 = fopen( "data://text/plain,This%20is%20some%20more%20text%20meant%20to%20test%20binding%20parameters%20to%20streams", "r" );
$stmt3 = sqlsrv_prepare( $conn, "INSERT INTO test_params (id, name, [double], stuff) VALUES (?, ?, ?, ?)", array( &$f1, "testtestte", &$f3, &$f4 )); $stmt3 = sqlsrv_prepare( $conn, "INSERT INTO $tableName (id, name, [double], stuff) VALUES (?, ?, ?, ?)", array( &$f1, "testtestte", &$f3, &$f4 ));
$success = sqlsrv_execute( $stmt3 ); $success = sqlsrv_execute( $stmt3 );
if( !$success ) { if( !$success ) {
var_dump( sqlsrv_errors() ); var_dump( sqlsrv_errors() );
@ -119,7 +112,7 @@ if( !is_null( $success )) {
$f1 = 4; $f1 = 4;
$f3 = 15.0; $f3 = 15.0;
$f4 = fopen( "data://text/plain,This%20is%20some%20more%20text%20meant%20to%20test%20binding%20parameters%20to%20streams", "r" ); $f4 = fopen( "data://text/plain,This%20is%20some%20more%20text%20meant%20to%20test%20binding%20parameters%20to%20streams", "r" );
$stmt4 = sqlsrv_prepare( $conn, "INSERT INTO test_params (id, name, [double], stuff) VALUES (?, ?, ?, ?)", array( &$f1, "testtestte", &$f3, &$f4 )); $stmt4 = sqlsrv_prepare( $conn, "INSERT INTO $tableName (id, name, [double], stuff) VALUES (?, ?, ?, ?)", array( &$f1, "testtestte", &$f3, &$f4 ));
$success = sqlsrv_execute( $stmt4 ); $success = sqlsrv_execute( $stmt4 );
if( !$success ) { if( !$success ) {
var_dump( sqlsrv_errors() ); var_dump( sqlsrv_errors() );
@ -136,7 +129,7 @@ if( !is_null( $success )) {
$f1 = 5; $f1 = 5;
$f3 = 16.0; $f3 = 16.0;
$f4 = fopen( "data://text/plain,This%20is%20some%20more%20text%20meant%20to%20test%20binding%20parameters%20to%20streams", "r" ); $f4 = fopen( "data://text/plain,This%20is%20some%20more%20text%20meant%20to%20test%20binding%20parameters%20to%20streams", "r" );
$stmt5 = sqlsrv_prepare( $conn, "INSERT INTO test_params (id, name, [double], stuff) VALUES (?, ?, ?, ?)", array( &$f1, "testtestte", &$f3, &$f4 )); $stmt5 = sqlsrv_prepare( $conn, "INSERT INTO $tableName (id, name, [double], stuff) VALUES (?, ?, ?, ?)", array( &$f1, "testtestte", &$f3, &$f4 ));
$success = sqlsrv_execute( $stmt5 ); $success = sqlsrv_execute( $stmt5 );
if( !$success ) { if( !$success ) {
var_dump( sqlsrv_errors() ); var_dump( sqlsrv_errors() );
@ -152,7 +145,7 @@ if( !is_null( $success )) {
sqlsrv_free_stmt( $stmt ); sqlsrv_free_stmt( $stmt );
$stmt = sqlsrv_prepare( $conn, "SELECT id, [double], name, stuff FROM test_params" ); $stmt = sqlsrv_prepare( $conn, "SELECT id, [double], name, stuff FROM $tableName" );
$success = sqlsrv_execute( $stmt ); $success = sqlsrv_execute( $stmt );
if( !$success ) { if( !$success ) {
var_dump( sqlsrv_errors() ); var_dump( sqlsrv_errors() );
@ -244,7 +237,7 @@ else {
print_r( $obj ); print_r( $obj );
} }
sqlsrv_query( $conn, "DROP TABLE test_params" ); dropTable($conn, $tableName);
sqlsrv_free_stmt( $stmt ); sqlsrv_free_stmt( $stmt );
sqlsrv_close( $conn ); sqlsrv_close( $conn );

View file

@ -1,7 +1,7 @@
--TEST-- --TEST--
Test for fetch_object with Unicode column name Test for fetch_object with Unicode column name
--SKIPIF-- --SKIPIF--
<?php require('skipif.inc'); ?> <?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
@ -41,28 +41,23 @@ class foo_noargs
} // end class foo_noargs } // end class foo_noargs
sqlsrv_configure('WarningsReturnAsErrors', 0); sqlsrv_configure('WarningsReturnAsErrors', 0);
//sqlsrv_configure( 'LogSeverity', SQLSRV_LOG_SEVERITY_ALL );
//sqlsrv_configure( 'LogSubsystems', SQLSRV_LOG_SYSTEM_ALL );
require_once('MsCommon.inc'); require_once('MsCommon.inc');
$conn = connect(array( 'CharacterSet'=>'UTF-8' )); $conn = AE\connect(array( 'CharacterSet'=>'UTF-8' ));
$tableName = 'test_params';
$stmt = sqlsrv_prepare($conn, "IF OBJECT_ID('test_params', 'U') IS NOT NULL DROP TABLE test_params"); $columns = array(new AE\ColumnMeta('tinyint', 'id'),
sqlsrv_execute($stmt); new AE\ColumnMeta('char(10)', '吉安而來'),
sqlsrv_free_stmt($stmt); new AE\ColumnMeta('float', '此是後話Κοντάוְאַתָּה第十四章BiałopioБунтевсемужирафиtest是أي بزمام الإنذارהნომინავიiałopioБунтевсемужирафиtest父親回衙 汗流如雨 吉安而來. 關雎 誨€¥É§é'),
new AE\ColumnMeta('varchar(max)', 'stuff'));
$stmt = sqlsrv_prepare($conn, "CREATE TABLE test_params (id tinyint, 吉安而來 char(10), [此是後話Κοντάוְאַתָּה第十四章BiałopioБунтевсемужирафиtest是أي بزمام الإنذارהნომინავიiałopioБунтевсемужирафиtest父親回衙 汗流如雨 吉安而來. 關雎 誨€¥É§é] float, stuff varchar(max))"); AE\createTable($conn, $tableName, $columns);
sqlsrv_execute($stmt);
sqlsrv_free_stmt($stmt);
$f1 = 1; $f1 = 1;
$f2 = "testtestte"; $f2 = "testtestte";
$f3 = 12.0; $f3 = 12.0;
$f4 = fopen("data://text/plain,This%20is%20some%20text%20meant%20to%20test%20binding%20parameters%20to%20streams", "r"); $f4 = fopen("data://text/plain,This%20is%20some%20text%20meant%20to%20test%20binding%20parameters%20to%20streams", "r");
$stmt = sqlsrv_prepare($conn, "INSERT INTO test_params (id, 吉安而來, [此是後話Κοντάוְאַתָּה第十四章BiałopioБунтевсемужирафиtest是أي بزمام الإنذارהნომინავიiałopioБунтевсемужирафиtest父親回衙 汗流如雨 吉安而來. 關雎 誨€¥É§é], stuff) VALUES (?, ?, ?, ?)", array( &$f1, "testtestte", &$f3, &$f4 )); //, $stmt = sqlsrv_prepare($conn, "INSERT INTO $tableName (id, 吉安而來, [此是後話Κοντάוְאַתָּה第十四章BiałopioБунтевсемужирафиtest是أي بزمام الإنذارהნომინავიiałopioБунтевсемужирафиtest父親回衙 汗流如雨 吉安而來. 關雎 誨€¥É§é], stuff) VALUES (?, ?, ?, ?)", array( &$f1, "testtestte", &$f3, &$f4 ));
//~ array( SQLSRV_SQLTYPE_INTEGER, SQLSRV_SQLTYPE_CHAR(10), SQLSRV_SQLTYPE_此是後話Κοντάוְאַתָּה第十四章BiałopioБунтевсемужирафиtest是أي بزمام الإنذارהნომინავიiałopioБунтевсемужирафиtest父親回衙 汗流如雨 吉安而來. 關雎 誨€¥É§é, SQLSRV_SQLTYPE_VARBINARY(4000)));
if (!$stmt) { if (!$stmt) {
var_dump(sqlsrv_errors()); var_dump(sqlsrv_errors());
die("sqlsrv_prepare failed."); die("sqlsrv_prepare failed.");
@ -147,7 +142,7 @@ if (!is_null($success)) {
sqlsrv_free_stmt($stmt); sqlsrv_free_stmt($stmt);
$stmt = sqlsrv_prepare($conn, "SELECT id, [此是後話Κοντάוְאַתָּה第十四章BiałopioБунтевсемужирафиtest是أي بزمام الإنذارהნომინავიiałopioБунтевсемужирафиtest父親回衙 汗流如雨 吉安而來. 關雎 誨€¥É§é], 吉安而來, stuff FROM test_params"); $stmt = sqlsrv_prepare($conn, "SELECT id, [此是後話Κοντάוְאַתָּה第十四章BiałopioБунтевсемужирафиtest是أي بزمام الإنذارהნომინავიiałopioБунтевсемужирафиtest父親回衙 汗流如雨 吉安而來. 關雎 誨€¥É§é], 吉安而來, stuff FROM $tableName");
$success = sqlsrv_execute($stmt); $success = sqlsrv_execute($stmt);
if (!$success) { if (!$success) {
var_dump(sqlsrv_errors()); var_dump(sqlsrv_errors());
@ -234,6 +229,11 @@ if (is_null($obj)) {
print_r($obj); print_r($obj);
} }
dropTable($conn, $tableName);
sqlsrv_free_stmt( $stmt );
sqlsrv_close( $conn );
?> ?>
--EXPECTREGEX-- --EXPECTREGEX--
Fetch a stdClass object \(1\) Fetch a stdClass object \(1\)

View file

@ -1,10 +1,11 @@
--TEST-- --TEST--
sqlsrv_fetch_object() into a class with Unicode column name sqlsrv_fetch_object() into a class with Unicode column name
--SKIPIF-- --SKIPIF--
<?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
/* Define the Product class. */ // Define the Product class
class Product class Product
{ {
public function __construct($ID, $UID) public function __construct($ID, $UID)
@ -56,72 +57,153 @@ class Sample extends Product
} }
} }
function getInputData1($inputs)
{
return array('ID' => $inputs[0],
'личное_имя'=> $inputs[1],
'SafetyStockLevel' => $inputs[2],
'StockedQty' => $inputs[3],
'UnitPrice' => $inputs[4],
'DueDate' => $inputs[5],
'Color' => $inputs[6]);
}
function getInputData2($inputs)
{
return array('SerialNumber' => $inputs[0],
'Code'=> $inputs[1]);
}
require_once('MsCommon.inc'); require_once('MsCommon.inc');
$tableName = "UnicodeColNameTest"; $conn = AE\connect(array('CharacterSet'=>'UTF-8'));
include 'MsSetup.inc';
$conn = connect(array( 'CharacterSet'=>'UTF-8' ));
$tableName = "UnicodeColNameTest";
// Create table Purchasing // Create table Purchasing
$tableName1 = "Purchasing"; $tableName1 = "Purchasing";
$tableName2 = "Country"; $tableName2 = "Country";
dropTable($conn, $tableName1);
dropTable($conn, $tableName2); $columns = array(new AE\ColumnMeta('CHAR(4)', 'ID'),
$sql = "create table $tableName1 (ID CHAR(4), личное_имя VARCHAR(128), SafetyStockLevel SMALLINT, new AE\ColumnMeta('VARCHAR(128)', 'личное_имя'),
StockedQty INT, UnitPrice FLOAT, DueDate datetime, Color VARCHAR(20))"; new AE\ColumnMeta('SMALLINT', 'SafetyStockLevel'),
sqlsrv_query($conn, $sql) ?: die(print_r(sqlsrv_errors(), true)); new AE\ColumnMeta('INT', 'StockedQty'),
new AE\ColumnMeta('FLOAT', 'UnitPrice'),
new AE\ColumnMeta('datetime', 'DueDate'),
new AE\ColumnMeta('VARCHAR(20)', 'Color'));
AE\createTable($conn, $tableName1, $columns);
// Insert data // Insert data
$sql = "INSERT INTO $tableName1 VALUES if (AE\isColEncrypted()) {
('P001','Pencil 2B','102','24','0.24','2016-02-01','Red'), $sql = "INSERT INTO $tableName1 VALUES
('P002','Notepad','102','12','3.87', '2016-02-21',Null), (?, ?, ?, ?, ?, ?, ?),
('P001','Mirror 2\"','652','3','15.99', '2016-02-01',NULL), (?, ?, ?, ?, ?, ?, ?),
('P003','USB connector','1652','31','9.99','2016-02-01',NULL)"; (?, ?, ?, ?, ?, ?, ?),
sqlsrv_query($conn, $sql) ?: die(print_r(sqlsrv_errors(), true)); (?, ?, ?, ?, ?, ?, ?)";
$stmt = sqlsrv_query($conn, $sql, array(array('P001', null, null, SQLSRV_SQLTYPE_CHAR(4)),
// Create table Country array('Pencil 2B', null, null, SQLSRV_SQLTYPE_VARCHAR(128)),
$sql = "create table $tableName2 (SerialNumber CHAR(4), Code VARCHAR(2))"; array('102', null, null, SQLSRV_SQLTYPE_SMALLINT),
sqlsrv_query($conn, $sql) ?: die(print_r(sqlsrv_errors(), true)); array('24', null, null, SQLSRV_SQLTYPE_INT),
array('0.24', null, null, SQLSRV_SQLTYPE_FLOAT),
// Insert data array('2016-02-01', null, null, SQLSRV_SQLTYPE_DATETIME),
$sql = "INSERT INTO $tableName2 VALUES ('P001','FR'),('P002','UK'),('P003','DE')"; array('Red', null, null, SQLSRV_SQLTYPE_VARCHAR(20)),
sqlsrv_query($conn, $sql) ?: die(print_r(sqlsrv_errors(), true)); array('P002', null, null, SQLSRV_SQLTYPE_CHAR(4)),
array('Notepad', null, null, SQLSRV_SQLTYPE_VARCHAR(128)),
/* Define the query. */ array('102', null, null, SQLSRV_SQLTYPE_SMALLINT),
$sql = "SELECT личное_имя, SafetyStockLevel, StockedQty, UnitPrice, Color, Code array('12', null, null, SQLSRV_SQLTYPE_INT),
FROM $tableName1 AS Purchasing array('3.87', null, null, SQLSRV_SQLTYPE_FLOAT),
JOIN $tableName2 AS Country array('2016-02-21', null, null, SQLSRV_SQLTYPE_DATETIME),
ON Purchasing.ID = Country.SerialNumber array(null, null, null, SQLSRV_SQLTYPE_VARCHAR(20)),
WHERE Purchasing.StockedQty < ? array('P001', null, null, SQLSRV_SQLTYPE_CHAR(4)),
AND Purchasing.UnitPrice < ? array('Mirror 2\"', null, null, SQLSRV_SQLTYPE_VARCHAR(128)),
AND Purchasing.DueDate= ?"; array('652', null, null, SQLSRV_SQLTYPE_SMALLINT),
array('3', null, null, SQLSRV_SQLTYPE_INT),
/* Set the parameter values. */ array('15.99', null, null, SQLSRV_SQLTYPE_FLOAT),
$params = array(100, '10.5', '2016-02-01'); array('2016-02-01', null, null, SQLSRV_SQLTYPE_DATETIME),
array(null, null, null, SQLSRV_SQLTYPE_VARCHAR(20)),
/* Execute the query. */ array('P003', null, null, SQLSRV_SQLTYPE_CHAR(4)),
$stmt = sqlsrv_query($conn, $sql, $params, array("Scrollable"=>"static")); //, array("Scrollable"=>"buffered") array('USB connector', null, null, SQLSRV_SQLTYPE_VARCHAR(128)),
array('1652', null, null, SQLSRV_SQLTYPE_SMALLINT),
array('31', null, null, SQLSRV_SQLTYPE_INT),
array('9.99', null, null, SQLSRV_SQLTYPE_FLOAT),
array('2016-02-01', null, null, SQLSRV_SQLTYPE_DATETIME),
array(null, null, null, SQLSRV_SQLTYPE_VARCHAR(20))));
} else {
$sql = "INSERT INTO $tableName1 VALUES
('P001', 'Pencil 2B', '102', '24', '0.24', '2016-02-01', 'Red'),
('P002', 'Notepad', '102', '12', '3.87', '2016-02-21', Null),
('P001', 'Mirror 2\"', '652', '3', '15.99', '2016-02-01', NULL),
('P003', 'USB connector', '1652', '31', '9.99', '2016-02-01', NULL)";
$stmt = sqlsrv_query($conn, $sql);
}
if (!$stmt) { if (!$stmt) {
echo "Error in statement execution.\n"; fatalError("Failed to insert test data into $tableName1\n");
die(print_r(sqlsrv_errors(), true));
} }
// Iterate through the result set. // Create table Country
// $product is an instance of the Product class. $columns = array(new AE\ColumnMeta('CHAR(4)', 'SerialNumber'),
$i=0; $hasNext = true; new AE\ColumnMeta('VARCHAR(2)', 'Code'));
AE\createTable($conn, $tableName2, $columns);
// Insert data
if (AE\isColEncrypted()) {
$sql = "INSERT INTO $tableName2 VALUES (?, ?), (?, ?), (?, ?)";
$stmt = sqlsrv_query($conn, $sql, array(array('P001', null, null, SQLSRV_SQLTYPE_CHAR(4)),
array('FR', null, null, SQLSRV_SQLTYPE_VARCHAR(2)),
array('P002', null, null, SQLSRV_SQLTYPE_CHAR(4)),
array('UK', null, null, SQLSRV_SQLTYPE_VARCHAR(2)),
array('P003', null, null, SQLSRV_SQLTYPE_CHAR(4)),
array('DE', null, null, SQLSRV_SQLTYPE_VARCHAR(2))));
} else {
$sql = "INSERT INTO $tableName2 VALUES ('P001', 'FR'), ('P002', 'UK'), ('P003', 'DE')";
$stmt = sqlsrv_query($conn, $sql);
}
if (!$stmt) {
fatalError("Failed to insert test data into $tableName2\n");
}
// With AE enabled, we cannot do comparisons with encrypted columns
// Also, only forward cursor or client buffer is supported
if (AE\isColEncrypted()) {
$sql = "SELECT личное_имя, SafetyStockLevel, StockedQty, UnitPrice, Color, Code
FROM $tableName1 AS Purchasing
JOIN $tableName2 AS Country
ON Purchasing.ID = Country.SerialNumber
WHERE Purchasing.личное_имя != ?
AND Purchasing.StockedQty != ?
AND Purchasing.DueDate= ?";
$params = array('Notepad', 3, '2016-02-01');
$stmt = sqlsrv_prepare($conn, $sql, $params, array("Scrollable"=>"buffered"));
if ($stmt) {
$res = sqlsrv_execute($stmt);
if (!$res) {
fatalError("Error in statement execution.\n");
}
} else {
fatalError("Error in preparing statement.\n");
}
} else {
$sql = "SELECT личное_имя, SafetyStockLevel, StockedQty, UnitPrice, Color, Code
FROM $tableName1 AS Purchasing
JOIN $tableName2 AS Country
ON Purchasing.ID = Country.SerialNumber
WHERE Purchasing.StockedQty < ?
AND Purchasing.UnitPrice < ?
AND Purchasing.DueDate= ?";
$params = array(100, '10.5', '2016-02-01');
$stmt = sqlsrv_query($conn, $sql, $params, array("Scrollable"=>"static"));
if (!$stmt) {
fatalError("Error in statement execution.\n");
}
}
// Iterate through the result set
// $product is an instance of the Product class
$i=0;
$hasNext = true;
while ($hasNext) { while ($hasNext) {
$sample = sqlsrv_fetch_object($stmt, "Sample", array($i+1000), SQLSRV_SCROLL_ABSOLUTE, $i); $sample = sqlsrv_fetch_object($stmt, "Sample", array($i+1000), SQLSRV_SCROLL_ABSOLUTE, $i);
// DEBUG: uncomment to see the SQL_SERVER ERROR
// if(!$sample) die( print_r( sqlsrv_errors(), true));
if (!$sample) { if (!$sample) {
$hasNext = false; $hasNext = false;
} else { } else {
@ -130,12 +212,10 @@ while ($hasNext) {
} }
} }
// DROP database dropTable($conn, $tableName1);
// $stmt = sqlsrv_query($conn,"DROP DATABASE ". $dbName); dropTable($conn, $tableName2);
//echo $dbName;
dropTable($conn, $tableName1); // Free statement and connection resources
dropTable($conn, $tableName2);
// Free statement and connection resources.s
sqlsrv_free_stmt($stmt); sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); sqlsrv_close($conn);

View file

@ -1,30 +1,30 @@
--TEST-- --TEST--
Test sqlsrv_num_rows method. Test sqlsrv_num_rows method.
--SKIPIF-- --SKIPIF--
<?php require('skipif.inc'); ?> <?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
sqlsrv_configure('WarningsReturnAsErrors', 0); sqlsrv_configure('WarningsReturnAsErrors', 0);
sqlsrv_configure('LogSeverity', SQLSRV_LOG_SEVERITY_ALL); sqlsrv_configure('LogSeverity', SQLSRV_LOG_SEVERITY_ALL);
require_once('MsCommon.inc'); require_once('MsCommon.inc');
$conn = connect(); $conn = AE\connect();
$tableName = 'testNumRows';
if (!$conn) { $columns = array(new AE\ColumnMeta('int', 'id', 'identity'),
fatalError("Failed to connect."); new AE\ColumnMeta('nvarchar(100)', 'c1'));
AE\createTable($conn, $tableName, $columns);
$stmt = AE\insertRow($conn, $tableName, array("c1" => 'TEST'));
// Always Encrypted feature only supports SQLSRV_CURSOR_FORWARD or
// SQLSRV_CURSOR_CLIENT_BUFFERED
if (AE\isColEncrypted()) {
$options = array('Scrollable' => SQLSRV_CURSOR_CLIENT_BUFFERED);
} else {
$options = array('Scrollable' => SQLSRV_CURSOR_KEYSET);
} }
$stmt = sqlsrv_query($conn, "SELECT * FROM $tableName", array(), $options);
dropTable($conn, 'utf16invalid');
$stmt = sqlsrv_query($conn, "CREATE TABLE utf16invalid (id int identity, c1 nvarchar(100))");
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
$stmt = sqlsrv_query($conn, "INSERT INTO utf16invalid (c1) VALUES ('TEST')");
if ($stmt === false) {
die(print_r(sqlsrv_errors()));
}
$stmt = sqlsrv_query($conn, "SELECT * FROM utf16invalid", array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET ));
$row_nums = sqlsrv_num_rows($stmt); $row_nums = sqlsrv_num_rows($stmt);
echo $row_nums; echo $row_nums;

View file

@ -1,30 +1,27 @@
--TEST-- --TEST--
sqlsrv_fetch_array() using a scrollable cursor sqlsrv_fetch_array() using a scrollable cursor
--SKIPIF-- --SKIPIF--
<?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
require_once('MsCommon.inc');
require_once("MsCommon.inc");
// connect // connect
$conn = connect(); $conn = AE\connect();
if (!$conn) { $tableName = 'test012';
fatalError("Connection could not be established.\n");
}
$tableName = GetTempTableName();
// Create table // Create table
$query = "CREATE TABLE $tableName (ID VARCHAR(10))"; $columns = array(new AE\ColumnMeta('VARCHAR(10)', 'ID'));
$stmt = sqlsrv_query($conn, $query); AE\createTable($conn, $tableName, $columns);
$query = "INSERT INTO $tableName VALUES ('1998.1'),('-2004'),('2016'),('4.2EUR')"; AE\insertRow($conn, $tableName, array("ID" => '1998.1'));
$stmt = sqlsrv_query($conn, $query) ?: die(print_r(sqlsrv_errors(), true)); AE\insertRow($conn, $tableName, array("ID" => '-2004'));
AE\insertRow($conn, $tableName, array("ID" => '2016'));
AE\insertRow($conn, $tableName, array("ID" => '4.2EUR'));
// Fetch data // Fetch data
$query = "SELECT ID FROM $tableName"; $query = "SELECT ID FROM $tableName";
$stmt = sqlsrv_query($conn, $query, [], array("Scrollable"=>"buffered")) $stmt = AE\executeQueryEx($conn, $query, array("Scrollable"=>"buffered"));
?: die(print_r(sqlsrv_errors(), true));
// Fetch first row // Fetch first row
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_NEXT); $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_NEXT);
@ -38,6 +35,8 @@ echo $row['ID']."\n";
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_LAST); $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_LAST);
echo $row['ID']."\n"; echo $row['ID']."\n";
dropTable($conn, $tableName);
sqlsrv_free_stmt($stmt); sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); sqlsrv_close($conn);
print "Done" print "Done"

View file

@ -5,30 +5,27 @@ This test calls sqlsrv_has_rows multiple times. Previously, multiple calls
with a forward cursor would advance the cursor. Subsequent fetch calls with a forward cursor would advance the cursor. Subsequent fetch calls
would then fail. would then fail.
--SKIPIF-- --SKIPIF--
<?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
require_once('MsCommon.inc');
require_once("MsCommon.inc");
// connect // connect
$conn = connect(); $conn = AE\connect();
if (!$conn) { $tableName = 'test037';
fatalError("Connection could not be established.\n");
}
$tableName = GetTempTableName();
// Create table // Create table
$query = "CREATE TABLE $tableName (ID VARCHAR(10))"; $columns = array(new AE\ColumnMeta('VARCHAR(10)', 'ID'));
$stmt = sqlsrv_query($conn, $query); AE\createTable($conn, $tableName, $columns);
$query = "INSERT INTO $tableName VALUES ('1998.1'),('-2004'),('2016'),('4.2EUR')"; AE\insertRow($conn, $tableName, array("ID" => '1998.1'));
$stmt = sqlsrv_query($conn, $query) ?: die(print_r(sqlsrv_errors(), true)); AE\insertRow($conn, $tableName, array("ID" => '-2004'));
AE\insertRow($conn, $tableName, array("ID" => '2016'));
AE\insertRow($conn, $tableName, array("ID" => '4.2EUR'));
// Fetch data using forward only cursor // Fetch data using forward only cursor
$query = "SELECT ID FROM $tableName"; $query = "SELECT ID FROM $tableName";
$stmt = sqlsrv_query($conn, $query) $stmt = AE\executeQuery($conn, $query);
?: die(print_r(sqlsrv_errors(), true));
// repeated calls should return true and fetch should work. // repeated calls should return true and fetch should work.
echo "Has Rows?" . (sqlsrv_has_rows($stmt) ? " Yes!" : " NO!") . "\n"; echo "Has Rows?" . (sqlsrv_has_rows($stmt) ? " Yes!" : " NO!") . "\n";
@ -43,8 +40,7 @@ if (sqlsrv_has_rows($stmt)) {
} }
// Fetch data using a scrollable cursor // Fetch data using a scrollable cursor
$stmt = sqlsrv_query($conn, $query, [], array("Scrollable"=>"buffered")) $stmt = sqlsrv_query($conn, $query, [], array("Scrollable"=>"buffered"));
?: die(print_r(sqlsrv_errors(), true));
echo "Has Rows?" . (sqlsrv_has_rows($stmt) ? " Yes!" : " NO!") . "\n"; echo "Has Rows?" . (sqlsrv_has_rows($stmt) ? " Yes!" : " NO!") . "\n";
echo "Has Rows?" . (sqlsrv_has_rows($stmt) ? " Yes!" : " NO!") . "\n"; echo "Has Rows?" . (sqlsrv_has_rows($stmt) ? " Yes!" : " NO!") . "\n";
@ -57,22 +53,21 @@ if (sqlsrv_has_rows($stmt)) {
} }
} }
$query = "SELECT ID FROM $tableName where ID='nomatch'"; // $query = "SELECT ID FROM $tableName where ID='nomatch'";
$stmt = sqlsrv_query($conn, $query) $stmt = AE\executeQuery($conn, $query, "ID = ?", array('nomatch'));
?: die(print_r(sqlsrv_errors(), true));
// repeated calls should return false if there are no rows. // repeated calls should return false if there are no rows.
echo "Has Rows?" . (sqlsrv_has_rows($stmt) ? " Yes!" : " NO!") . "\n"; echo "Has Rows?" . (sqlsrv_has_rows($stmt) ? " Yes!" : " NO!") . "\n";
echo "Has Rows?" . (sqlsrv_has_rows($stmt) ? " Yes!" : " NO!") . "\n"; echo "Has Rows?" . (sqlsrv_has_rows($stmt) ? " Yes!" : " NO!") . "\n";
// Fetch data using a scrollable cursor // Fetch data using a scrollable cursor
$stmt = sqlsrv_query($conn, $query, [], array("Scrollable"=>"buffered")) $stmt = AE\executeQuery($conn, $query, "ID = ?", array('nomatch'), array("Scrollable"=>"buffered"));
?: die(print_r(sqlsrv_errors(), true));
// repeated calls should return false if there are no rows. // repeated calls should return false if there are no rows.
echo "Has Rows?" . (sqlsrv_has_rows($stmt) ? " Yes!" : " NO!") . "\n"; echo "Has Rows?" . (sqlsrv_has_rows($stmt) ? " Yes!" : " NO!") . "\n";
echo "Has Rows?" . (sqlsrv_has_rows($stmt) ? " Yes!" : " NO!") . "\n"; echo "Has Rows?" . (sqlsrv_has_rows($stmt) ? " Yes!" : " NO!") . "\n";
dropTable($conn, $tableName);
sqlsrv_free_stmt($stmt); sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); sqlsrv_close($conn);

View file

@ -1,38 +1,27 @@
--TEST-- --TEST--
GitHub issue #69 - fetching an empty nvarchar using client buffer GitHub issue #69 - fetching an empty nvarchar using client buffer
--SKIPIF-- --SKIPIF--
<?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
function print_errors() require_once('MsCommon.inc');
{
die( print_r( sqlsrv_errors(), true));
}
function test() // Connect
{ $conn = AE\connect();
require_once("MsCommon.inc");
// Connect
$conn = Connect();
if( !$conn ) { print_errors(); }
$sql = "EXEC dbo.sp_executesql
N'DECLARE @x nvarchar(max)
SET @x = '''' -- empty string
SELECT @x AS [Empty_Nvarchar_Max]'";
$stmt = sqlsrv_query($conn, $sql, [], ["Scrollable" => 'buffered']); $sql = "EXEC dbo.sp_executesql
if (! $stmt) { print_errors(); } N'DECLARE @x nvarchar(max)
SET @x = '''' -- empty string
SELECT @x AS [Empty_Nvarchar_Max]'";
$return = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC); $stmt = AE\executeQueryEx($conn, $sql, ["Scrollable" => 'buffered']);
print_r($return);
$return = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
// Free the statement and connection resources. print_r($return);
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn); // Free the statement and connection resources.
} sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
test();
print "Done"; print "Done";
?> ?>

View file

@ -1,61 +1,53 @@
--TEST-- --TEST--
sqlsrv_fetch() with SQLSRV_SCROLL_ABSOLUTE using out of range offset sqlsrv_fetch() with SQLSRV_SCROLL_ABSOLUTE using out of range offset
--SKIPIF-- --SKIPIF--
<?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
require_once('MsCommon.inc');
function test() // connect
{ $conn = AE\connect();
require_once("MsCommon.inc");
// connect // Prepare the statement
$conn = connect(); $sql = "select * from cd_info";
if (!$conn) { $stmt = sqlsrv_prepare($conn, $sql, array(), array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED));
printErrors("Connection could not be established.\n"); if ($stmt === false) {
} printErrors();
}
sqlsrv_execute($stmt);
// Prepare the statement // Get row count
$sql = "select * from cd_info"; $row_count = sqlsrv_num_rows($stmt);
$stmt = sqlsrv_prepare($conn, $sql, array(), array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED)); if ($row_count == 0) {
if ($stmt === false) { printErrors("There should be at least one row!\n");
printErrors();
}
sqlsrv_execute($stmt);
// Get row count
$row_count = sqlsrv_num_rows($stmt);
if ($row_count == 0) {
printErrors("There should be at least one row!\n");
}
sqlsrv_execute($stmt);
$row = sqlsrv_fetch($stmt, SQLSRV_SCROLL_FIRST);
$field = sqlsrv_get_field($stmt, 0);
if (! $field) {
printErrors();
}
$row = sqlsrv_fetch($stmt, SQLSRV_SCROLL_LAST);
$field = sqlsrv_get_field($stmt, 0);
if (! $field) {
printErrors();
}
// this should return false
$row = sqlsrv_fetch($stmt, SQLSRV_SCROLL_ABSOLUTE, $row_count);
if ($row) {
printErrors("This should return false!");
}
$field = sqlsrv_get_field($stmt, 0);
if ($field !== false) {
printErrors("This should have resulted in error!");
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
} }
test(); sqlsrv_execute($stmt);
$row = sqlsrv_fetch($stmt, SQLSRV_SCROLL_FIRST);
$field = sqlsrv_get_field($stmt, 0);
if (! $field) {
printErrors();
}
$row = sqlsrv_fetch($stmt, SQLSRV_SCROLL_LAST);
$field = sqlsrv_get_field($stmt, 0);
if (! $field) {
printErrors();
}
// this should return false
$row = sqlsrv_fetch($stmt, SQLSRV_SCROLL_ABSOLUTE, $row_count);
if ($row) {
printErrors("This should return false!");
}
$field = sqlsrv_get_field($stmt, 0);
if ($field !== false) {
printErrors("This should have resulted in error!");
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
print "Done"; print "Done";
?> ?>

View file

@ -1,10 +1,11 @@
--TEST-- --TEST--
sqlsrv_has_rows() using a forward and scrollable cursor sqlsrv_has_rows() using a forward and scrollable cursor
--SKIPIF-- --SKIPIF--
<?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
require_once("MsCommon.inc"); require_once('MsCommon.inc');
function fetchData($conn, $table, $size) function fetchData($conn, $table, $size)
{ {
@ -27,21 +28,26 @@ function fetchData($conn, $table, $size)
} }
// connect // connect
$conn = connect(); $conn = AE\connect();
if (!$conn) {
printErrors("Connection could not be established.\n");
}
$tableName1 = GetTempTableName('php_test_table_1'); $tableName1 = 'php_test_table_1';
$tableName2 = GetTempTableName('php_test_table_2'); $tableName2 = 'php_test_table_2';
// Create table // Create tables
$stmt = sqlsrv_query($conn, "CREATE TABLE $tableName1 ([c1_int] int, [c2_varchar_max] varchar(max))"); $columns = array(new AE\ColumnMeta('int', 'c1_int'),
$stmt = sqlsrv_query($conn, "CREATE TABLE $tableName2 ([c1_int] int, [c2_varchar_1036] varchar(1036))"); new AE\ColumnMeta('varchar(max)', 'c2_varchar_max'));
$stmt = AE\createTable($conn, $tableName1, $columns);
unset($columns);
$columns = array(new AE\ColumnMeta('int', 'c1_int'),
new AE\ColumnMeta('varchar(1036)', 'c2_varchar_1036'));
$stmt = AE\createTable($conn, $tableName2, $columns);
// insert > 1KB into c2_varchar_max & c2_varchar_1036 (1036 characters). // insert > 1KB into c2_varchar_max & c2_varchar_1036 (1036 characters).
$stmt = sqlsrv_query($conn, "INSERT INTO $tableName1 (c1_int, c2_varchar_max) VALUES (1, 'This is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a test')"); $longString = 'This is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a test';
$stmt = sqlsrv_query($conn, "INSERT INTO $tableName2 (c1_int, c2_varchar_1036) VALUES (1, 'This is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a testThis is a test')");
$stmt = AE\insertRow($conn, $tableName1, array('c1_int' => 1, 'c2_varchar_max' => $longString));
$stmt = AE\insertRow($conn, $tableName2, array('c1_int' => 1, 'c2_varchar_1036' => $longString));
// set client buffer size to 0KB returns false // set client buffer size to 0KB returns false
$ret = sqlsrv_configure('ClientBufferMaxKBSize', 0); $ret = sqlsrv_configure('ClientBufferMaxKBSize', 0);

View file

@ -3,16 +3,28 @@ Read numeric types from SQLSRV with buffered query.
--DESCRIPTION-- --DESCRIPTION--
Test numeric conversion (number to string, string to number) functionality for buffered queries with SQLSRV. Test numeric conversion (number to string, string to number) functionality for buffered queries with SQLSRV.
--SKIPIF-- --SKIPIF--
<?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
require_once("MsCommon.inc"); function getInputData($inputs)
{
$conn = connect(array("CharacterSet"=>"utf-8")); return array('a' => $inputs[0],
if (!$conn) { 'neg_a'=> $inputs[1],
printErrors("Connection could not be established.\n"); 'b' => $inputs[2],
'neg_b' => $inputs[3],
'c' => $inputs[4],
'neg_c' => $inputs[5],
'zero' => $inputs[6],
'zerof' => $inputs[7],
'zerod' => $inputs[8]);
} }
require_once('MsCommon.inc');
$conn = AE\connect(array("CharacterSet"=>"utf-8"));
$tableName = 'test230';
$sample = 1234567890.1234; $sample = 1234567890.1234;
$sample1 = -1234567890.1234; $sample1 = -1234567890.1234;
$sample2 = 1; $sample2 = 1;
@ -20,34 +32,35 @@ $sample3 = -1;
$sample4 = 0.5; $sample4 = 0.5;
$sample5 = -0.55; $sample5 = -0.55;
$query = 'CREATE TABLE #TESTTABLE (a float(53), neg_a float(53), b int, neg_b int, c decimal(16, 6), neg_c decimal(16, 6), zero int, zerof float(53), zerod decimal(16,6))';
// Create table // Create table
$stmt = sqlsrv_query($conn, $query); $columns = array(new AE\ColumnMeta('float(53)', 'a'),
if ($stmt === false) { new AE\ColumnMeta('float(53)', 'neg_a'),
die(print_r(sqlsrv_errors(), true)); new AE\ColumnMeta('int', 'b'),
} new AE\ColumnMeta('int', 'neg_b'),
new AE\ColumnMeta('decimal(16, 6)', 'c'),
new AE\ColumnMeta('decimal(16, 6)', 'neg_c'),
new AE\ColumnMeta('int', 'zero'),
new AE\ColumnMeta('float(53)', 'zerof'),
new AE\ColumnMeta('decimal(16, 6)', 'zerod'));
AE\createTable($conn, $tableName, $columns);
$query = 'INSERT INTO #TESTTABLE (a, neg_a, b, neg_b, c, neg_c, zero, zerof, zerod) VALUES(?, ?, ?, ?, ?, ?, 0, 0, 0)'; $res = null;
$params = array($sample, $sample1, $sample2, $sample3, $sample4, $sample5); $params = array($sample, $sample1, $sample2, $sample3, $sample4, $sample5, 0, 0, 0);
$data = getInputData($params);
$stmt = sqlsrv_query($conn, $query, $params); $stmt = AE\insertRow($conn, $tableName, $data, $res, AE\INSERT_QUERY_PARAMS);
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
$params = array($sample4, $sample5, 100000, -1234567, $sample, $sample1);
$stmt = sqlsrv_query($conn, $query, $params);
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
$query = 'SELECT TOP 2 * FROM #TESTTABLE';
$stmt = sqlsrv_query($conn, $query, array(), array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED));
if (!$stmt) { if (!$stmt) {
echo "Statement could not be prepared.\n"; fatalError("Failed to insert into $tableName!");
die(print_r(sqlsrv_errors(), true));
} }
sqlsrv_execute($stmt);
$params = array($sample4, $sample5, 100000, -1234567, $sample, $sample1, 0, 0, 0);
$data = getInputData($params);
$stmt = AE\insertRow($conn, $tableName, $data, $res, AE\INSERT_QUERY_PARAMS);
if (!$stmt) {
fatalError("Failed to insert into $tableName!");
}
$query = "SELECT TOP 2 * FROM $tableName";
$stmt = sqlsrv_query($conn, $query, array(), array("Scrollable"=>SQLSRV_CURSOR_CLIENT_BUFFERED));
$array = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC); $array = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC);
var_dump($array); var_dump($array);
@ -73,6 +86,8 @@ for ($i = 0; $i < $rowcount; $i++) {
} }
} }
dropTable($conn, $tableName);
sqlsrv_free_stmt($stmt); sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); sqlsrv_close($conn);

View file

@ -3,12 +3,13 @@ GitHub issue #330 - get numrow of null buffered result set
--DESCRIPTION-- --DESCRIPTION--
A variation of the example in GitHub issue 330. A -1 value returned as numrow of a null buffered result set. A variation of the example in GitHub issue 330. A -1 value returned as numrow of a null buffered result set.
--SKIPIF-- --SKIPIF--
<?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
require_once("MsCommon.inc"); require_once('MsCommon.inc');
// connect // connect
$conn = connect() ?: fatalError("Failed to connect"); $conn = AE\connect();
$stmt = sqlsrv_query($conn, "IF EXISTS (SELECT * FROM [sys].[objects] WHERE (name LIKE 'non_existent_table_name%') AND type in (N'U')) $stmt = sqlsrv_query($conn, "IF EXISTS (SELECT * FROM [sys].[objects] WHERE (name LIKE 'non_existent_table_name%') AND type in (N'U'))
BEGIN BEGIN

View file

@ -1,249 +1,213 @@
--TEST-- --TEST--
scrollable result sets. scrollable result sets.
--SKIPIF-- --SKIPIF--
<?php require('skipif.inc'); ?> <?php require('skipif_versions_old.inc'); ?>
--FILE-- --FILE--
<?php <?php
sqlsrv_configure( 'WarningsReturnAsErrors', false ); sqlsrv_configure('WarningsReturnAsErrors', false);
sqlsrv_configure( 'LogSeverity', SQLSRV_LOG_SEVERITY_ALL ); sqlsrv_configure('LogSeverity', SQLSRV_LOG_SEVERITY_ALL);
require( 'MsCommon.inc' ); require_once('MsCommon.inc');
$conn = Connect(); function hasRows($stmt, $expectedFail)
if( $conn === false ) { {
die( print_r( sqlsrv_errors(), true )); $rows = sqlsrv_has_rows($stmt);
} if ($expectedFail) {
if ($rows == true) {
$stmt = sqlsrv_query( $conn, "IF OBJECT_ID('ScrollTest', 'U') IS NOT NULL DROP TABLE ScrollTest" ); die("Shouldn't have rows");
if( $stmt !== false ) { sqlsrv_free_stmt( $stmt ); } }
} else {
$stmt = sqlsrv_query( $conn, "CREATE TABLE ScrollTest (id int, value char(10))" ); if ($rows != true) {
if( $stmt === false ) { die("Should have rows");
die( print_r( sqlsrv_errors(), true )); }
}
$rows = sqlsrv_has_rows( $stmt );
if( $rows == true ) {
die( "Shouldn't have rows" );
}
sqlsrv_free_stmt( $stmt );
$stmt = sqlsrv_query( $conn, "INSERT INTO ScrollTest (id, value) VALUES(?,?)", array( 1, "Row 1" ));
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true ));
}
$rows = sqlsrv_has_rows( $stmt );
if( $rows == true ) {
die( "Shouldn't have rows" );
}
$stmt = sqlsrv_query( $conn, "INSERT INTO ScrollTest (id, value) VALUES(?,?)", array( 2, "Row 2" ));
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true ));
}
$rows = sqlsrv_has_rows( $stmt );
if( $rows == true ) {
die( "Shouldn't have rows" );
}
$stmt = sqlsrv_query( $conn, "INSERT INTO ScrollTest (id, value) VALUES(?,?)", array( 3, "Row 3" ));
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true ));
}
$rows = sqlsrv_has_rows( $stmt );
if( $rows == true ) {
die( "Shouldn't have rows" );
}
$stmt = sqlsrv_query( $conn, "INSERT INTO ScrollTest (id, value) VALUES(?,?)", array( 4, "Row 4" ));
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true ));
}
$rows = sqlsrv_has_rows( $stmt );
if( $rows == true ) {
die( "Shouldn't have rows" );
}
$stmt = sqlsrv_query( $conn, "SELECT * FROM ScrollTest", array(), array( "Scrollable" => 'static' ));
$result = sqlsrv_fetch( $stmt, SQLSRV_SCROLL_ABSOLUTE, 4 );
if( $result !== null ) {
die( "Should have failed with an invalid row number" );
}
$rows = sqlsrv_has_rows( $stmt );
if( $rows != true ) {
die( "Should have rows" );
}
print_r( sqlsrv_errors() );
$result = sqlsrv_fetch( $stmt, SQLSRV_SCROLL_ABSOLUTE, -1 );
if( $result !== null ) {
die( "Should have failed with an invalid row number" );
}
print_r( sqlsrv_errors() );
$rows = sqlsrv_rows_affected( $stmt );
print_r( sqlsrv_errors() );
$rows = sqlsrv_num_rows( $stmt );
echo "Query returned $rows rows\n";
$row = 3;
$result = sqlsrv_fetch( $stmt, SQLSRV_SCROLL_ABSOLUTE, $row );
do {
$result = sqlsrv_fetch( $stmt, SQLSRV_SCROLL_ABSOLUTE, $row );
if( $result === false ) {
die( print_r( sqlsrv_errors(), true ));
} }
$field1 = sqlsrv_get_field( $stmt, 0 );
$field2 = sqlsrv_get_field( $stmt, 1 );
echo "$field1 $field2\n";
$row = $row - 1;
} while( $row >= 0 );
sqlsrv_free_stmt( $stmt );
$stmt = sqlsrv_query( $conn, "SELECT * FROM ScrollTest", array(), array( "Scrollable" => SQLSRV_CURSOR_FORWARD ));
$rows = sqlsrv_has_rows( $stmt );
if( $rows != true ) {
die( "Should have rows" );
} }
$row_count = 0;
while( $row = sqlsrv_fetch( $stmt )) { function countRows($stmt, $numRows, $cursorType, $initialCount = 0)
{
$row_count = $initialCount;
while ($row = sqlsrv_fetch($stmt)) {
++$row_count; ++$row_count;
} }
if( $row === false ) { if($row === false) {
die( print_r( sqlsrv_errors(), true )); die(print_r(sqlsrv_errors(), true));
} }
echo "$row_count rows retrieved on the forward only cursor\n"; if ($row_count != $numRows) {
sqlsrv_free_stmt( $stmt ); echo "ERROR: $row_count rows retrieved on the $cursorType cursor\n";
}
$stmt = sqlsrv_query( $conn, "SELECT * FROM ScrollTest", array(), array( "Scrollable" => 'static' ));
$rows = sqlsrv_has_rows( $stmt );
if( $rows != true ) {
die( "Should have rows" );
}
$row_count = 0;
while( $row = sqlsrv_fetch( $stmt )) {
++$row_count;
}
if( $row === false ) {
die( print_r( sqlsrv_errors(), true ));
}
echo "$row_count rows retrieved on the static cursor\n";
sqlsrv_free_stmt( $stmt );
$stmt = sqlsrv_query( $conn, "SELECT * FROM ScrollTest", array(), array( "Scrollable" => 'dynamic' ));
sqlsrv_fetch( $stmt );
sqlsrv_fetch( $stmt );
$stmt2 = sqlsrv_query( $conn, "INSERT INTO ScrollTest (id, value) VALUES(?,?)", array( 5, "Row 5" ));
if( $stmt2 === false ) {
die( print_r( sqlsrv_errors(), true ));
}
$stmt2 = sqlsrv_query( $conn, "INSERT INTO ScrollTest (id, value) VALUES(?,?)", array( 6, "Row 6" ));
if( $stmt2 === false ) {
die( print_r( sqlsrv_errors(), true ));
} }
$row_count = 2; // for the two fetches above function insertOneRow($conn, $tableName, $idx, $expectedFail)
while( sqlsrv_fetch( $stmt )) { {
++$row_count; $res = null;
} $stmt = AE\insertRow($conn, $tableName, array('id' => $idx, 'value' => 'Row ' . $idx), $res, AE\INSERT_QUERY_PARAMS);
echo "$row_count rows retrieved on the dynamic cursor\n";
sqlsrv_free_stmt( $stmt );
if (!$stmt || $res === false) {
$stmt = sqlsrv_query( $conn, "SELECT * FROM ScrollTest", array(), array( "Scrollable" => SQLSRV_CURSOR_STATIC )); fatalError("failed to insert row $idx!\n");
$row_count = sqlsrv_num_rows( $stmt ); }
if( $row_count != 6 ) { hasRows($stmt, $expectedFail);
die( "sqlsrv_num_rows should have returned 6 rows in the static cursor\n" ); sqlsrv_free_stmt($stmt);
}
$row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_ABSOLUTE, -1 );
if( $row !== null ) {
die( "sqlsrv_fetch_array should have returned null\n" );
} }
$row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_ABSOLUTE, 6 ); $conn = AE\connect();
if( $row !== null ) { $tableName = 'ScrollTest';
die( "sqlsrv_fetch_array should have returned null\n" ); $numRows = 4;
$columns = array(new AE\ColumnMeta('int', 'id'),
new AE\ColumnMeta('char(10)', 'value'));
$stmt = AE\createTable($conn, $tableName, $columns);
$rows = sqlsrv_has_rows($stmt);
if($rows == true) {
die("Shouldn't have rows");
}
sqlsrv_free_stmt($stmt);
for ($i = 1; $i <= $numRows; $i++) {
insertOneRow($conn, $tableName, $i, true);
} }
$stmt = sqlsrv_query( $conn, "SELECT * FROM ScrollTest", array(), array( "Scrollable" => SQLSRV_CURSOR_DYNAMIC )); // Always Encrypted feature only supports SQLSRV_CURSOR_FORWARD, so skip the rest of the test
// when AE is enabled
// https://github.com/Microsoft/msphpsql/wiki/Features#aelimitation
$query = "SELECT * FROM $tableName";
$options = array('Scrollable' => SQLSRV_CURSOR_FORWARD);
$stmt = sqlsrv_query($conn, $query, array(), $options);
$result = sqlsrv_num_rows( $stmt ); hasRows($stmt, false);
if( $result !== false ) { countRows($stmt, $numRows, 'forward only');
die( "sqlsrv_num_rows should have failed for a dynamic cursor." ); sqlsrv_free_stmt($stmt);
}
sqlsrv_fetch( $stmt );
sqlsrv_fetch( $stmt );
$stmt2 = sqlsrv_query( $conn, "DELETE FROM ScrollTest WHERE id = 2" ); if (! AE\isColEncrypted()) {
if( $stmt2 === false ) { $options = array('Scrollable' => 'static');
die( print_r( sqlsrv_errors(), true )); $stmt = sqlsrv_query($conn, $query, array(), $options);
}
$row = sqlsrv_get_field( $stmt, 0 ); $result = sqlsrv_fetch($stmt, SQLSRV_SCROLL_ABSOLUTE, 4);
if( $row !== false ) { if($result !== null) {
die( "Should have returned false retrieving a field deleted by another query\n" ); die("Should have failed with an invalid row number");
} }
echo "sqlsrv_get_field returned false when retrieving a field deleted by another query\n"; hasRows($stmt, false);
print_r( sqlsrv_errors() ); // this is empty
print_r(sqlsrv_errors());
$result = sqlsrv_fetch($stmt, SQLSRV_SCROLL_ABSOLUTE, -1);
if($result !== null) {
die("Should have failed with an invalid row number");
}
// this is empty
print_r(sqlsrv_errors());
// verify the sqlsrv_fetch_object is working // expected an error here
$obj = sqlsrv_fetch_object( $stmt, null, array(null), SQLSRV_SCROLL_LAST, 1 ); $rows = sqlsrv_rows_affected($stmt);
$message = !empty(sqlsrv_errors()) ? sqlsrv_errors()[0]['message'] : '';
$expected = 'This function only works with statements that are not scrollable.';
if (strcmp($message, $expected)) {
echo "Expected this error message: \'$expected\'\nbut it is: \'$message\'\n";
}
if( $obj === false ) { $rows = sqlsrv_num_rows($stmt);
if ($rows != $numRows) {
echo "Error: Query returned $rows rows\n";
}
print_r( sqlsrv_errors() ); $row = 3;
$result = sqlsrv_fetch($stmt, SQLSRV_SCROLL_ABSOLUTE, $row);
do {
$result = sqlsrv_fetch($stmt, SQLSRV_SCROLL_ABSOLUTE, $row);
if($result === false) {
die(print_r(sqlsrv_errors(), true));
}
$field1 = sqlsrv_get_field($stmt, 0);
$field2 = sqlsrv_get_field($stmt, 1);
$idx = $row + 1;
if ($field1 != $idx || trim($field2) != "Row $idx")
echo "Field values unexpected $field1 $field2!\n";
$row = $row - 1;
} while($row >= 0);
sqlsrv_free_stmt($stmt);
$options = array('Scrollable' => 'static');
$stmt = sqlsrv_query($conn, $query, array(), $options);
hasRows($stmt, false);
countRows($stmt, $numRows, 'static');
sqlsrv_free_stmt($stmt);
$options = array('Scrollable' => 'dynamic');
$stmt = sqlsrv_query($conn, $query, array(), $options);
sqlsrv_fetch($stmt);
sqlsrv_fetch($stmt);
insertOneRow($conn, $tableName, 5, true);
insertOneRow($conn, $tableName, 6, true);
$numRows = 6;
// to account for the two fetches above
countRows($stmt, $numRows, 'dynamic', 2);
sqlsrv_free_stmt($stmt);
$options = array('Scrollable' => SQLSRV_CURSOR_STATIC);
$stmt = sqlsrv_query($conn, $query, array(), $options);
$row_count = sqlsrv_num_rows($stmt);
if($row_count != $numRows) {
die("sqlsrv_num_rows should have returned 6 rows in the static cursor\n");
}
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_ABSOLUTE, -1);
if($row !== null) {
die("sqlsrv_fetch_array should have returned null\n");
}
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_ABSOLUTE, 6);
if($row !== null) {
die("sqlsrv_fetch_array should have returned null\n");
}
$options = array('Scrollable' => SQLSRV_CURSOR_DYNAMIC);
$stmt = sqlsrv_query($conn, $query, array(), $options);
$result = sqlsrv_num_rows($stmt);
if($result !== false) {
die("sqlsrv_num_rows should have failed for a dynamic cursor.");
}
sqlsrv_fetch($stmt);
sqlsrv_fetch($stmt);
$stmt2 = sqlsrv_query($conn, "DELETE FROM ScrollTest WHERE id = 2");
if($stmt2 === false) {
die(print_r(sqlsrv_errors(), true));
}
$row = sqlsrv_get_field($stmt, 0);
if($row !== false) {
die("sqlsrv_get_field should have returned false retrieving a field deleted by another query");
}
$error = sqlsrv_errors()[0];
$message = $error['message'];
$sqlstate = $error['SQLSTATE'];
if (strcmp($sqlstate, 'HY109') || strpos($message, 'Invalid cursor position') === false) {
die("Unexpected SQL state $sqlstate or error \'$message\'");
}
// verify the sqlsrv_fetch_object is working
$obj = sqlsrv_fetch_object($stmt, null, array(null), SQLSRV_SCROLL_LAST, 1);
if($obj === false) {
print_r(sqlsrv_errors());
} else {
if ($obj->id != $numRows || trim($obj->value) != "Row $numRows")
echo "Field values unexpected $obj->id $obj->value!\n";
}
sqlsrv_free_stmt($stmt);
} }
print_r( $obj );
dropTable($conn, $tableName);
sqlsrv_query( $conn, "DROP TABLE ScrollTest" ); sqlsrv_close($conn);
sqlsrv_free_stmt( $stmt );
sqlsrv_close( $conn );
echo "Test succeeded.\n"; echo "Test succeeded.\n";
?> ?>
--EXPECTREGEX-- --EXPECT--
Array Test succeeded.
\(
\[0\] => Array
\(
\[0\] => IMSSP
\[SQLSTATE\] => IMSSP
\[1\] => \-51
\[code\] => \-51
\[2\] => This function only works with statements that are not scrollable\.
\[message\] => This function only works with statements that are not scrollable\.
\)
\)
Query returned 4 rows
4 Row 4
3 Row 3
2 Row 2
1 Row 1
4 rows retrieved on the forward only cursor
4 rows retrieved on the static cursor
6 rows retrieved on the dynamic cursor
sqlsrv_get_field returned false when retrieving a field deleted by another query
Array
\(
\[0\] => Array
\(
\[0\] => HY109
\[SQLSTATE\] => HY109
\[1\] => 0
\[code\] => 0
\[2\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Invalid cursor position
\[message\] => \[Microsoft\]\[ODBC Driver 1[1-9] for SQL Server\]Invalid cursor position
\)
\)
stdClass Object
\(
\[id\] => 6
\[value\] => Row 6
\)
Test succeeded\.