From cd46cafa49dcf8c197bc55e19e3ff6157e227ec8 Mon Sep 17 00:00:00 2001 From: SupunKavinda Date: Tue, 14 Mar 2023 11:09:56 +0100 Subject: [PATCH] insert row order fix --- src/Clickhouse.php | 6 +++++- tests/InsertTest.php | 32 +++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/Clickhouse.php b/src/Clickhouse.php index 71abf5c..367a2c8 100644 --- a/src/Clickhouse.php +++ b/src/Clickhouse.php @@ -73,7 +73,9 @@ public function pingThrow() : void public function insert(string $table, array $columns, array ...$rows) : mixed { - $columnNames = implode(', ', array_keys($columns)); + $columnNames = array_keys($columns); + sort($columnNames); + $columnNames = implode(',', $columnNames); $bindings = []; $placeholders = []; @@ -90,6 +92,8 @@ public function insert(string $table, array $columns, array ...$rows) : mixed ); } + ksort($row); + foreach ($row as $columnName => $value) { $key = 'r' . $i . '_' . $columnName; $bindings[$key] = $value; diff --git a/tests/InsertTest.php b/tests/InsertTest.php index e1e8670..4ce2555 100644 --- a/tests/InsertTest.php +++ b/tests/InsertTest.php @@ -92,4 +92,34 @@ ] ); -})->throws(ClickhouseException::class, 'Expected 4 columns, got 3'); \ No newline at end of file +})->throws(ClickhouseException::class, 'Expected 4 columns, got 3'); + +# bug +it('inserts correctly when the row key order is different', function() { + + addUsersTable(); + + $clickhouse = test()->clickhouse; + + $clickhouse->insert('users', + [ + 'id' => 'UInt32', + 'created_at' => 'DateTime', + 'name' => 'String', + 'age' => 'UInt8', + ], + [ + 'age' => 10, + 'created_at' => '2021-01-01 00:00:00', + 'name' => 'John', + 'id' => 1 + ] + ); + + $response = $clickhouse->select('SELECT * FROM users'); + $row = $response->first(); + + expect($row['id'])->toBe(1) + ->and($row['age'])->toBe(10); + +}); \ No newline at end of file