203

HTTP code 203: Non-Authoritative Information

Curious First

(first_last.rb) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
ActiveRecord::Schema.define do
  drop_table :records if table_exists? :records
  create_table :records do |t|
    t.timestamps
  end
end

class Record < ActiveRecord::Base
end

class CuriousFirstTest < MiniTest::Unit::TestCase
  def test_first_last
    r = Record.create
    Record.create
    r.touch
    assert_equal 2, Record.count
    assert Record.first != Record.last, 'The first of 2 records is also the last!'
  end
end

What are we doing here? We create two records, touching first (this updates the record timestamps), and making sure that the first record is not the same as the last one. Perfectly valid assumption, that almost works.

The test succeeds on SQLite and MySQL (latter - with various engines), but fails on PostgreSQL.

Is it a database fault? Not really. Rails (before 4.0) used a strange asymmetric approach: #last (when statement do not have any explicit order) adds ordering by primary key, but #first does not add anything, thus using default database ordering. No database actually guarantees what is implicit order, but there is still some consistency: at least in simple cases, MySQL always maintains primary key order, but PostgreSQL places most recently modified records at the end.

Bug? I’d say yes, but… This is not the bug that is going to be fixed. Apparently there are developers “in the wild” that managed to rely on this behavior. Thus – this behavior was effectively declared “a feature, not a bug”

Comments