rails/rails — pull request #5153 by mhfs (2012-02-24 14:15:24+00:00)
Title: Made `first` finder consistent between MySQL and PostgreSQL

Hi,

When you do a call to `first` the generated SQL is this:

```ruby
> User.first
User Load (35.2ms) SELECT "users".* FROM "users" LIMIT 1
```

However, PostgreSQL changes the 'default order' of the records when you perform an update as you can observe in this example:

```sql
# CREATE TABLE users (id serial, name varchar(40));
# INSERT INTO users (name) VALUES ('John');
# INSERT INTO users (name) VALUES ('Michael');
# SELECT * FROM users;
id | name
----+---------------
1 | John
2 | Michael

# SELECT "users".* FROM "users" LIMIT 1;
id | name
----+------
1 | John

# UPDATE users SET name = 'Modified John' WHERE id = 1;
# SELECT * FROM users;
id | name
----+---------------
2 | Michael
1 | Modified John

# SELECT "users".* FROM "users" LIMIT 1;
id | name
----+---------
2 | Michael
```

So I made a change so that all `first` calls gains a default order clause:

```ruby
> User.first
User Load (3.1ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
```

If an order clause is already chained, nothing is added:

```ruby
> User.order(:name).first
User Load (75.1ms) SELECT "users".* FROM "users" ORDER BY name LIMIT 1
```
I'm not particularly confortable changing the global behavior for a PostgreSQL specific fix but I think an adapter check wouldn't make sense in this area of the code. What do you think?

If accepted I'd be happy to backport the fix to previous versions.

Cheers!