From 43dccb1ba26a6fa02e890599bc2985778bbcf5ea Mon Sep 17 00:00:00 2001 From: Mira Paulik Date: Mon, 29 Feb 2016 15:54:52 +0100 Subject: [PATCH] SqlsrvDriver::getInsertId() last inserted id is from last statement instead of last inserted row regardless of the table that produced the value --- src/Dibi/Drivers/SqlsrvDriver.php | 2 +- tests/dibi/Sqlsrv.insert.phpt | 28 ++++++++++++++++++++++++++++ tests/dibi/data/sqlsrv.insert.sql | 5 +++++ 3 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 tests/dibi/Sqlsrv.insert.phpt create mode 100644 tests/dibi/data/sqlsrv.insert.sql diff --git a/src/Dibi/Drivers/SqlsrvDriver.php b/src/Dibi/Drivers/SqlsrvDriver.php index 108b6ff3..69f18356 100644 --- a/src/Dibi/Drivers/SqlsrvDriver.php +++ b/src/Dibi/Drivers/SqlsrvDriver.php @@ -141,7 +141,7 @@ class SqlsrvDriver implements Dibi\Driver, Dibi\ResultDriver */ public function getInsertId($sequence) { - $res = sqlsrv_query($this->connection, 'SELECT @@IDENTITY'); + $res = sqlsrv_query($this->connection, 'SELECT SCOPE_IDENTITY()'); if (is_resource($res)) { $row = sqlsrv_fetch_array($res, SQLSRV_FETCH_NUMERIC); return $row[0]; diff --git a/tests/dibi/Sqlsrv.insert.phpt b/tests/dibi/Sqlsrv.insert.phpt new file mode 100644 index 00000000..8520a3d2 --- /dev/null +++ b/tests/dibi/Sqlsrv.insert.phpt @@ -0,0 +1,28 @@ +loadFile(__DIR__ . "/data/sqlsrv.insert.sql"); + +for ($i = 1; $i <= 5; $i++) { + $conn->query('INSERT INTO %n DEFAULT VALUES', 'aaa'); + Assert::equal($i, $conn->getInsertId()); +} + +$conn->query('INSERT INTO %n DEFAULT VALUES', 'aab'); +Assert::equal(1, $conn->getInsertId()); + +$conn->query( + 'CREATE TRIGGER %n ON %n AFTER INSERT AS INSERT INTO %n DEFAULT VALUES', + 'UpdAAB', 'aab', 'aaa' +); + +$conn->query('INSERT INTO %n DEFAULT VALUES', 'aab'); +Assert::equal(2, $conn->getInsertId()); diff --git a/tests/dibi/data/sqlsrv.insert.sql b/tests/dibi/data/sqlsrv.insert.sql new file mode 100644 index 00000000..8ce36823 --- /dev/null +++ b/tests/dibi/data/sqlsrv.insert.sql @@ -0,0 +1,5 @@ +IF OBJECT_ID('aaa', 'U') IS NOT NULL DROP TABLE aaa; +IF OBJECT_ID('aab', 'U') IS NOT NULL DROP TABLE aab; + +CREATE TABLE aaa ( [id] int NOT NULL IDENTITY PRIMARY KEY ) +CREATE TABLE aab ( [id] int NOT NULL IDENTITY PRIMARY KEY )