Active record pattern
Encyclopedia
In software engineering
, the active record pattern is an architectural pattern
found in software that stores its data in relational database
s. It was named by Martin Fowler
in his 2003 book Patterns of Enterprise Application Architecture. The interface to such an object would include functions such as Insert, Update, and Delete, plus properties that correspond more or less directly to the columns in the underlying database table.
Active record is an approach to accessing data in a database
. A database table or view
is wrapped into a class
. Thus, an object
instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save. Any object loaded gets its information from the database. When an object is updated the corresponding row in the table is also updated. The wrapper class implements accessor methods
or properties for each column in the table or view.
This pattern is commonly used by object persistence tools, and in object-relational mapping
. Typically, foreign key
relationships will be exposed as an object instance of the appropriate type via a property.
s for many programming environments. For example, if in a database there is a table
part = new Part
part.name = "Sample part"
part.price = 123.45
part.save
will create a new row in the
command
Conversely, the class can be used to query the database:
b = Part.find_first("name", "gearbox")
This will create a new
has an open source implementation of the Active Record pattern.
The ColdFusion on Wheels
framework has an implementation of the Active Record pattern. It is open source and has the added advantage of requiring no complex configuration.
framework is available in the Castle Project
. It represents a row in the database with an Active Record instance, and the static methods act on all rows. It is free
, open source software that is distributed under the Apache 2.0 License
. It uses NHibernate
, but you do not need to write XML
mapping.
The SubSonic (software)
project implements the Active Record pattern which is loosely based on how Active Record works on Ruby on Rails
.
The nHydrate
ORM tool also implements the Active Record pattern in its data access layer (DAL). Though the framework provides much more functionality and other implemented patterns, Active Record is the heart of its DAL. It is also open source and has the added advantage of requiring no complex configuration.
open-source frameworks bundle their own ORM implementing the Active Record pattern, including Kohana
, Doctrine
(Before version 2), Propel
, CakePHP
, Yii
and SilverStripe
.
Most implementations support relationships, behaviors, validation, serialization and support for multiple adapters.
The framework CodeIgniter has a query builder it calls "ActiveRecord", but which doesn't implement the ActiveRecord pattern. Instead it implements what the user guide refers to as a modified version of the pattern. The ActiveRecord functionality in CodeIgniter can be achieved by using either CodeIgniter DataMapper library or CodeIgniter Gas ORM library.
library ActiveRecord implements the object-relational mapping
(ORM) design pattern. It creates a persistable
domain model from business objects and database tables, where logic and data are presented as a unified package. ActiveRecord adds inheritance
and associations
to the pattern above, solving two substantial limitations of that pattern. A set of macros acts as a domain language for the latter, and the Single Table Inheritance
pattern is integrated for the former; thus, ActiveRecord increases the functionality of the active record pattern approach to database interaction. ActiveRecord is the default model component of the Model-view-controller
web-application framework Ruby on Rails
, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson
, and has been improved upon by a number of contributors.
Other, less popular ORMs have been released since ActiveRecord first took the stage. Gems like DataMapper
and Sequel show major improvements over the original ActiveRecord framework. As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 will be independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.
. ActiveJDBC
is an implementation of Active Record design pattern inspired by Ruby on Rails
ActiveRecord. ActiveJDBC is lightweight, fast, small and does not require any configuration.
Another library implementing the Active record pattern is jOOQ (for Java Object Oriented Querying)
. It combines active records with source code generation
and a querying DSL similar to SQL
allowing for retrieving active records using complex SQL statements.
(e.g., ActiveJS's Active Record), Perl
(Class::DBI), ActionScript
and Python
.
is often at odds with the concept of separation of concerns
. Generally speaking, patterns that favor separation of concerns are more suitable to isolated unit tests while patterns that favor encapsulation have easier to use APIs. Active Record heavily favors encapsulation to the point where testing without a database is quite difficult.
The negative effects on testability in the Active Record pattern can be minimized by using mocking or dependency injection
frameworks to substitute the real data tier with a simulated one.
Software engineering
Software Engineering is the application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software, and the study of these approaches; that is, the application of engineering to software...
, the active record pattern is an architectural pattern
Architectural pattern (computer science)
An architectural pattern in software is a standard design in the field of software architecture. The concept of a software architectural pattern has a broader scope than the concept of a software design pattern...
found in software that stores its data in relational database
Relational database
A relational database is a database that conforms to relational model theory. The software used in a relational database is called a relational database management system . Colloquial use of the term "relational database" may refer to the RDBMS software, or the relational database itself...
s. It was named by Martin Fowler
Martin Fowler
-Online presentations:* at RailsConf 2006* at JAOO 2006* at QCon London 2007 * at QCon London 2008 * at ThoughtWorks Quarterly Technology Briefing, October 2008...
in his 2003 book Patterns of Enterprise Application Architecture. The interface to such an object would include functions such as Insert, Update, and Delete, plus properties that correspond more or less directly to the columns in the underlying database table.
Active record is an approach to accessing data in a database
Database
A database is an organized collection of data for one or more purposes, usually in digital form. The data are typically organized to model relevant aspects of reality , in a way that supports processes requiring this information...
. A database table or view
View (database)
In database theory, a view consists of a stored query accessible as a virtual table in a relational database or a set of documents in a document-oriented database composed of the result set of a query or map and reduce functions...
is wrapped into a class
Class (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...
. Thus, an object
Object (computer science)
In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...
instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save. Any object loaded gets its information from the database. When an object is updated the corresponding row in the table is also updated. The wrapper class implements accessor methods
Method (computer programming)
In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...
or properties for each column in the table or view.
This pattern is commonly used by object persistence tools, and in object-relational mapping
Object-relational mapping
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a "virtual object database" that can be used from within the programming language...
. Typically, foreign key
Foreign key
In the context of relational databases, a foreign key is a referential constraint between two tables.A foreign key is a field in a relational table that matches a candidate key of another table...
relationships will be exposed as an object instance of the appropriate type via a property.
Implementations
Implementations of the concept can be found in various frameworkSoftware framework
In computer programming, a software framework is an abstraction in which software providing generic functionality can be selectively changed by user code, thus providing application specific software...
s for many programming environments. For example, if in a database there is a table
parts
with columns name
(string type) and price
(number type), and the Active Record pattern is implemented in the class Part
, the pseudo-codepart = new Part
part.name = "Sample part"
part.price = 123.45
part.save
will create a new row in the
parts
table with the given values, and is roughly equivalent to the SQLSQL
SQL is a programming language designed for managing data in relational database management systems ....
command
Conversely, the class can be used to query the database:
b = Part.find_first("name", "gearbox")
This will create a new
Part
object based on the first matching row from the parts
table whose name
column has the value "gearbox". The SQL command used might be similar to the following, depending on the SQL implementation details of the database:ColdFusion
ColdFusionColdFusion
In computing, ColdFusion is the name of a commercial rapid application development platform invented by Jeremy and JJ Allaire in 1995. ColdFusion was originally designed to make it easier to connect simple HTML pages to a database, by version 2 it had...
has an open source implementation of the Active Record pattern.
The ColdFusion on Wheels
ColdFusion on Wheels
ColdFusion on Wheels is an open source web application framework designed for applications written in ColdFusion Markup Language. Its name is often shortened to CFWheels or Wheels....
framework has an implementation of the Active Record pattern. It is open source and has the added advantage of requiring no complex configuration.
Microsoft .NET
An implementation for the Microsoft .NET.NET Framework
The .NET Framework is a software framework that runs primarily on Microsoft Windows. It includes a large library and supports several programming languages which allows language interoperability...
framework is available in the Castle Project
Castle Project
The Castle Project is an open source application framework for the .NET platform.- History :The project was founded by Hamilton Verissimo de Oliveira , who was a member of the Apache Avalon and the Apache Excalibur projects...
. It represents a row in the database with an Active Record instance, and the static methods act on all rows. It is free
Free software
Free software, software libre or libre software is software that can be used, studied, and modified without restriction, and which can be copied and redistributed in modified or unmodified form either without restriction, or with restrictions that only ensure that further recipients can also do...
, open source software that is distributed under the Apache 2.0 License
Apache License
The Apache License is a copyfree free software license authored by the Apache Software Foundation . The Apache License requires preservation of the copyright notice and disclaimer....
. It uses NHibernate
NHibernate
- External links :*** *NuGet...
, but you do not need to write XML
XML
Extensible Markup Language is a set of rules for encoding documents in machine-readable form. It is defined in the XML 1.0 Specification produced by the W3C, and several other related specifications, all gratis open standards....
mapping.
The SubSonic (software)
Subsonic (software)
SubSonic is an open source object-relational mapper for Microsoft .NET Framework maintained by Rob Conery. The current version is , released in July 2009.- Supported databases :SubSonic 3.0 supports databases that can be used through System.Data.Common:...
project implements the Active Record pattern which is loosely based on how Active Record works on Ruby on Rails
Ruby on Rails
Ruby on Rails, often shortened to Rails or RoR, is an open source web application framework for the Ruby programming language.-History:...
.
The nHydrate
Nhydrate
nHydrate is an object-relational mapping solution for the Microsoft .NET platform providing a framework for a relational database to be mapped to .NET objects...
ORM tool also implements the Active Record pattern in its data access layer (DAL). Though the framework provides much more functionality and other implemented patterns, Active Record is the heart of its DAL. It is also open source and has the added advantage of requiring no complex configuration.
PHP
Several PHPPHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...
open-source frameworks bundle their own ORM implementing the Active Record pattern, including Kohana
Kohana Framework
Kohana PHP is an HMVC PHP5 framework that provides a rich set of components for quickly building robust and dynamic web applications. It is a relatively lesser known framework when compared to other, such as CakePHP or CodeIgniter, and has a small "strong but elite" community...
, Doctrine
Doctrine (PHP)
See also DataEase, whose query language is also called DQL.Doctrine is an object-relational mapper for PHP that provides persistence for PHP objects. It sits on top of a database abstraction layer...
(Before version 2), Propel
Propel (PHP)
Propel is a free, open-source object-relational mapping toolkit written in PHP. It is also an integral part of the PHP framework Symfony and was the default ORM up to, and including version 1.2.- History :...
, CakePHP
CakePHP
CakePHP is an open source web application framework for producing web applications. It is written in PHP, modeled after the concepts of Ruby on Rails, and distributed under the MIT License.-History:...
, Yii
Yii
Yii is an open source, object-oriented, high-performance component-based PHP web application framework. Yii is pronounced as "Yee" or [ji:] and it's an acronym for "Yes It Is!".- History :...
and SilverStripe
SilverStripe
SilverStripe is a free and open source content management system for creating and maintaining websites. It provides an out of the box web-based administration panel that enables users to make modifications to parts of the website, which includes a WYSIWYG website editor...
.
Most implementations support relationships, behaviors, validation, serialization and support for multiple adapters.
The framework CodeIgniter has a query builder it calls "ActiveRecord", but which doesn't implement the ActiveRecord pattern. Instead it implements what the user guide refers to as a modified version of the pattern. The ActiveRecord functionality in CodeIgniter can be achieved by using either CodeIgniter DataMapper library or CodeIgniter Gas ORM library.
Ruby
The RubyRuby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...
library ActiveRecord implements the object-relational mapping
Object-relational mapping
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a "virtual object database" that can be used from within the programming language...
(ORM) design pattern. It creates a persistable
Persistence (computer science)
Persistence in computer science refers to the characteristic of state that outlives the process that created it. Without this capability, state would only exist in RAM, and would be lost when this RAM loses power, such as a computer shutdown....
domain model from business objects and database tables, where logic and data are presented as a unified package. ActiveRecord adds inheritance
Inheritance (computer science)
In object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...
and associations
Association (object-oriented programming)
In object-oriented programming, association defines a relationship between classes of objects that allows one object instance to cause another to perform an action on its behalf...
to the pattern above, solving two substantial limitations of that pattern. A set of macros acts as a domain language for the latter, and the Single Table Inheritance
Single Table Inheritance
Single table inheritance is a way to emulate object-oriented inheritance in a relational database. When mapping from a database table to an object in an object-oriented language, a field in the database identifies what class in the hierarchy the object belongs to. In Ruby on Rails the field in...
pattern is integrated for the former; thus, ActiveRecord increases the functionality of the active record pattern approach to database interaction. ActiveRecord is the default model component of the Model-view-controller
Model-view-controller
Model–view–controller is a software architecture, currently considered an architectural pattern used in software engineering. The pattern isolates "domain logic" from the user interface , permitting independent development, testing and maintenance of each .Model View Controller...
web-application framework Ruby on Rails
Ruby on Rails
Ruby on Rails, often shortened to Rails or RoR, is an open source web application framework for the Ruby programming language.-History:...
, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson
David Heinemeier Hansson
David Heinemeier Hansson is a Danish programmer and the creator of the popular Ruby on Rails web development framework and the Instiki wiki...
, and has been improved upon by a number of contributors.
Other, less popular ORMs have been released since ActiveRecord first took the stage. Gems like DataMapper
Datamapper
Datamapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails' ActiveRecord library.Some features of Datamapper:...
and Sequel show major improvements over the original ActiveRecord framework. As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 will be independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.
Java
The Java language has a new library called ActiveJDBCActiveJDBC
ActiveJDBC is a Java implementation of the Active Record design pattern developed by Igor Polevoy. It was inspired by ActiveRecord ORM from Ruby on Rails. It is based on a set of conventions and does not require configuration.- Writing models :...
. ActiveJDBC
ActiveJDBC
ActiveJDBC is a Java implementation of the Active Record design pattern developed by Igor Polevoy. It was inspired by ActiveRecord ORM from Ruby on Rails. It is based on a set of conventions and does not require configuration.- Writing models :...
is an implementation of Active Record design pattern inspired by Ruby on Rails
Ruby on Rails
Ruby on Rails, often shortened to Rails or RoR, is an open source web application framework for the Ruby programming language.-History:...
ActiveRecord. ActiveJDBC is lightweight, fast, small and does not require any configuration.
Another library implementing the Active record pattern is jOOQ (for Java Object Oriented Querying)
Java Object Oriented Querying
jOOQ stands for Java Object Oriented Querying. It is a very light database mapping library in Java. Its purpose is to be both relational and object oriented by providing a Domain-specific language to construct queries from classes generated from a database schema...
. It combines active records with source code generation
Automatic programming
In computer science, the term automatic programming identifies a type of computer programming in which some mechanism generates a computer program to allow human programmers to write the code at a higher abstraction level....
and a querying DSL similar to SQL
SQL
SQL is a programming language designed for managing data in relational database management systems ....
allowing for retrieving active records using complex SQL statements.
Other languages
There are several open source implementations of the Active Record pattern in other languages, including JavaScriptJavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....
(e.g., ActiveJS's Active Record), Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
(Class::DBI), ActionScript
ActionScript
ActionScript is an object-oriented language originally developed by Macromedia Inc. . It is a dialect of ECMAScript , and is used primarily for the development of websites and software targeting the Adobe Flash Player platform, used on Web pages in the form of...
and Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
.
Testability
In OOP the concept of encapsulationEncapsulation (object-oriented programming)
In a programming language encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof:* A language mechanism for restricting access to some of the object's components....
is often at odds with the concept of separation of concerns
Separation of concerns
In computer science, separation of concerns is the process of separating a computer program into distinct features that overlap in functionality as little as possible. A concern is any piece of interest or focus in a program. Typically, concerns are synonymous with features or behaviors...
. Generally speaking, patterns that favor separation of concerns are more suitable to isolated unit tests while patterns that favor encapsulation have easier to use APIs. Active Record heavily favors encapsulation to the point where testing without a database is quite difficult.
The negative effects on testability in the Active Record pattern can be minimized by using mocking or dependency injection
Dependency injection
Dependency injection is a design pattern in object-oriented computer programming whose purpose is to improve testability of, and simplify deployment of components in very large software systems....
frameworks to substitute the real data tier with a simulated one.