diff --git a/src/Database/Table/SqlBuilder.php b/src/Database/Table/SqlBuilder.php index 178f00ce7..e11576bfa 100644 --- a/src/Database/Table/SqlBuilder.php +++ b/src/Database/Table/SqlBuilder.php @@ -124,6 +124,13 @@ public function buildDeleteQuery() */ public function buildSelectQuery($columns = NULL) { + if (!$this->order && ($this->limit !== NULL || $this->offset)) { + $this->order = array_map( + function ($col) { return "$this->tableName.$col"; }, + (array) $this->conventions->getPrimary($this->tableName) + ); + } + $queryCondition = $this->buildConditions(); $queryEnd = $this->buildQueryEnd(); diff --git a/tests/Database/Table/Table.limit.phpt b/tests/Database/Table/Table.limit.phpt index 8e6457c1a..87ba1f4f8 100644 --- a/tests/Database/Table/Table.limit.phpt +++ b/tests/Database/Table/Table.limit.phpt @@ -13,12 +13,12 @@ Nette\Database\Helpers::loadFromFile($connection, __DIR__ . "/../files/{$driverN Assert::same( - reformat('SELECT * FROM [author] LIMIT 2'), + reformat('SELECT * FROM [author] ORDER BY [author].[id] LIMIT 2'), $context->table('author')->limit(2)->getSql() ); Assert::same( - reformat('SELECT * FROM [author] LIMIT 2 OFFSET 10'), + reformat('SELECT * FROM [author] ORDER BY [author].[id] LIMIT 2 OFFSET 10'), $context->table('author')->limit(2, 10)->getSql() ); @@ -28,24 +28,24 @@ Assert::same( ); Assert::same( - reformat('SELECT * FROM [author] LIMIT 10'), + reformat('SELECT * FROM [author] ORDER BY [author].[id] LIMIT 10'), $context->table('author')->page(1, 10)->getSql() ); Assert::same( - reformat('SELECT * FROM [author] LIMIT 0'), + reformat('SELECT * FROM [author] ORDER BY [author].[id] LIMIT 0'), $context->table('author')->page(0, 10, $count)->getSql() ); Assert::same(1, $count); Assert::same( - reformat('SELECT * FROM [author] LIMIT 10 OFFSET 10'), + reformat('SELECT * FROM [author] ORDER BY [author].[id] LIMIT 10 OFFSET 10'), $context->table('author')->page(2, 10, $count)->getSql() ); Assert::same(1, $count); Assert::same( - reformat('SELECT * FROM [author] LIMIT 2 OFFSET 2'), + reformat('SELECT * FROM [author] ORDER BY [author].[id] LIMIT 2 OFFSET 2'), $context->table('author')->page(2, 2, $count)->getSql() ); Assert::same(2, $count); diff --git a/tests/Database/Table/bugs/bug1356.phpt b/tests/Database/Table/bugs/bug1356.phpt index 6d81fbe75..00f96cdc2 100644 --- a/tests/Database/Table/bugs/bug1356.phpt +++ b/tests/Database/Table/bugs/bug1356.phpt @@ -24,4 +24,4 @@ foreach ($books as $book) { $book->title; } -Assert::same(reformat('SELECT * FROM [book] LIMIT 1'), $books->getSql()); +Assert::same(reformat('SELECT * FROM [book] ORDER BY [book].[id] LIMIT 1'), $books->getSql());