fhwang.net

Lafcadio 0.9.3: PostgreSQL support, eager loading, more

The newest development release of Lafcadio, 0.9.3, now supports PostgreSQL, adds eager loading, and has a few more additions.

As always, odd-numbered releases should be considered beta. If you want to play it safe, use 0.8.3 instead.

PostgreSQL support

Lafcadio now supports PostgreSQL. Activating is a simple matter of setting ‘dbtype’ in LafcadioConfig:

LafcadioConfig.set_values(
  'dbuser' => 'testuser', 'dbpassword' => 'password',
  'dbname' => 'test_db', 'dbhost' => 'localhost', 'dbtype' => 'Pg'
)

Everything else—single-row retrieval, transactions, query inference, order and limit clauses—works transparently across both MySQL and PostgreSQL.

Eager loading

To prevent excessive selects, you can now use eager loading to load across associations with one select statement:

all_invoices = Invoice.all( :include => :client )
# Knows Client information without incurring another select
all_invoices.first.client.name

MockObjectStore handles transactions

Transaction support was previously added, in 0.9.0, but I forgot to add transaction support to the MockObjectStore. Now that the MockObjectStore mimics the database, you can test transaction-dependent logic in-memory, within having a real database installed.

For example, below is a (somewhat stupid) method that uses transactions, with a test-case using the in-memory MockObjectStore:

def transfer_money( from_account, to_account, tr_amount )
  object_store = Lafcadio::ObjectStore.get_object_store
  object_store.transaction do |tr|
    from_account.update!(
      'amount' => from_account.amount - tr_amount
    )
    to_account.update!( 'amount' => to_account.amount + tr_amount )
    tr.rollback if from_account.amount < 0
  end
end

class TestTransferMoney < Test::Unit::TestCase
  def test_rollback_if_less_than_zero
    mock_object_store = MockObjectStore.new
    ObjectStore.set_object_store mock_object_store
    from_account = Account.new( 'amount' => 100.0 ).commit
    to_account = Account.new( 'amount' => 0.0 ).commit
    transfer_money( from_account, to_account, 200.0 )
    from_account_prime = Account[from_account.pk_id]
    assert_equal( 100.0, from_account_prime.amount )
  end
end

Commits and rollbacks work for the test code, even if you don’t have a database installed.

blog comments powered by Disqus
Tagged: ruby

« Previous post

Next post »