2 November 2011
By: Tomas Malmsten

Choosing between table mappers or DeclerativeBase when working with SQLAlchemy

I have recently been looking how to create a clean Domain Driven Design architecture using SQLAlchemy and specifically how to map domain classes to tables. This post will discuss the two techniques available and why to choose one over the other.

Lets start with looking at the two strategies available. SQLAlchemy offers a [Data Mapper(http://martinfowler.com/eaaCatalog/dataMapper) out of the box. It is also possible to use an Active Record approach by using the Declarative Base ORM extension.

The Active Record approach is a very attractive way of working. It adds metadata to the domain objects that tells the engine how to save them to the database. It's quick and easy to use and avoids extra classes or configurations that handles the database mapping. It's a perfect fit for most web applications. The main drawback is that storage logic is tightly coupled with the domain objects. This can make the domain difficult to work with over time. It also means that any changes required in storage logic will force changes into the domain breaking the Single Responsibility Principle. Active Record will also prove very costly if the project finds that a change of storage technology would be beneficial. A not to unlikely event with such a variation in industry strength storage technologies available.

Data Mappers provides high decoupling by keeping all meta data for mapping objects to tables separate from the domain. The mapping can be placed in its own module which makes it easy to divide the domain into coherent modules with no need to cater for storage concerns. It also makes it easy to model more advanced relational concepts in a large database. Since it allows for complete separation of concerns for domain and data access it is also easy to change or swap out the data storage technology completely without any needs to change the domain. It does however increase the complexity of the application since it adds an extra module/package.

If the project in question is going to use a clean implementation of Domain Driven Design only the Data Mapper works. It is also the only possible choice if it is likely that the project will be changing storage technology.

If, however, the project is a traditional web application with a domain model that is simple or close to non-existing then Active Record is a good choice. It will provide more speed of development. Making a clear distinction between domain logic tests and data access tests will make it easier to later extract data access out into Data Mappers if needed.

Tags: DDD Tidy Code ORM Design Patterns