Skip to content

Commit cc89cda

Browse files
Fix for negative number handling (DECIMAL -51.1234 could not read). (#80)
* Fix for negative number handling (DECIMAL -51.1234 could not read). This seems to fix it. Inspired by fengxiangyun/mysql-replication@a9da836
1 parent 1cab85f commit cc89cda

File tree

2 files changed

+12
-11
lines changed

2 files changed

+12
-11
lines changed

src/MySQLReplication/BinaryDataReader/BinaryDataReader.php

+8-9
Original file line numberDiff line numberDiff line change
@@ -229,28 +229,27 @@ public function readIntBeBySize(int $size): int
229229

230230
public function readInt8(): int
231231
{
232-
return unpack('c', $this->read(self::UNSIGNED_CHAR_LENGTH))[1];
232+
$re = unpack('c', $this->read(self::UNSIGNED_CHAR_LENGTH))[1];
233+
return $re >= 0x80 ? $re - 0x100 : $re;
233234
}
234235

235236
public function readInt16Be(): int
236237
{
237-
return unpack('n', $this->read(self::UNSIGNED_SHORT_LENGTH))[1];
238+
$re = unpack('n', $this->read(self::UNSIGNED_SHORT_LENGTH))[1];
239+
return $re >= 0x8000 ? $re - 0x10000 : $re;
238240
}
239241

240242
public function readInt24Be(): int
241243
{
242244
$data = unpack('C3', $this->read(self::UNSIGNED_INT24_LENGTH));
243-
$res = ($data[1] << 16) | ($data[2] << 8) | $data[3];
244-
if ($res >= 0x800000) {
245-
$res -= 0x1000000;
246-
}
247-
248-
return $res;
245+
$re = ($data[1] << 16) | ($data[2] << 8) | $data[3];
246+
return $re >= 0x800000 ? $re - 0x1000000 : $re;
249247
}
250248

251249
public function readInt32Be(): int
252250
{
253-
return unpack('i', strrev($this->read(self::UNSIGNED_INT32_LENGTH)))[1];
251+
$re = unpack('N', $this->read(self::UNSIGNED_INT32_LENGTH))[1];
252+
return $re >= 0x80000000 ? $re - 0x100000000 : $re;
254253
}
255254

256255
public function readInt40Be(): int

tests/Integration/TypesTest.php

+4-2
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,14 @@ public function shouldBeDecimalLongValues2(): void
5656
*/
5757
public function shouldBeDecimalNegativeValues(): void
5858
{
59-
$create_query = 'CREATE TABLE test (test DECIMAL(20,10))';
60-
$insert_query = 'INSERT INTO test VALUES(-42000.123456)';
59+
$create_query = 'CREATE TABLE test (test DECIMAL(20,10), test2 DECIMAL(11,4), test3 DECIMAL(40,30))';
60+
$insert_query = 'INSERT INTO test VALUES(-42000.123456, -51.1234, -51.123456789098765432123456789)';
6161

6262
$event = $this->createAndInsertValue($create_query, $insert_query);
6363

6464
self::assertEquals('-42000.1234560000', $event->getValues()[0]['test']);
65+
self::assertEquals('-51.1234', $event->getValues()[0]['test2']);
66+
self::assertEquals('-51.123456789098765432123456789000', $event->getValues()[0]['test3']);
6567
}
6668

6769
/**

0 commit comments

Comments
 (0)