{"id":46,"date":"2007-10-04T20:07:53","date_gmt":"2007-10-05T02:07:53","guid":{"rendered":"http:\/\/www.pervasivecode.com\/blog\/2007\/10\/04\/activerecord-the-visual-basic-of-object-relational-mappers\/"},"modified":"2007-10-04T20:07:53","modified_gmt":"2007-10-05T02:07:53","slug":"activerecord-the-visual-basic-of-object-relational-mappers","status":"publish","type":"post","link":"http:\/\/www.pervasivecode.com\/blog\/2007\/10\/04\/activerecord-the-visual-basic-of-object-relational-mappers\/","title":{"rendered":"ActiveRecord: the Visual Basic of Object Relational Mappers"},"content":{"rendered":"<p>I&#8217;ve been working with Ruby on Rails intensively for several months, and I&#8217;ve finally found a place where Rails can&#8217;t readily be extended to do what I want. It&#8217;s ActiveRecord, which is probably the most controversial part of Rails.<\/p>\n<p>I&#8217;m reminded of a <a href=\"http:\/\/en.wikipedia.org\/wiki\/James_Gosling\">James Gosling<\/a> quote disparaging Microsoft tools, particularly Visual Basic: &#8220;The easy stuff is easy, but the hard stuff is impossible.&#8221; There&#8217;s a parallel between VB and Rails in this instance, in that <em>if you only let yourself use the high level tools<\/em>, the hard stuff is impossible, but the designers specifically tell you to do the hard stuff using a lower level toolset. The controversy that surrounds &#8220;X can&#8217;t do everything, therefore it sucks&#8221; should really be focusing on the feasibility of going through that trapdoor to do things &#8220;the hard way&#8221;. This is what <a href=\"http:\/\/en.wikipedia.org\/wiki\/Borland_Delphi\">Delphi<\/a> did, which is why so many folks chose it over VB; it made the hard stuff easier.<\/p>\n<p><!--more--><\/p>\n<p>Here&#8217;s the task I need to accomplish, for which ActiveRecord is not well suited: complex queries involving SQL functions and multiple-table joins. I want to join a few tables together, order by a SQL function, include with each result row the result of a SQL function that operates on each row, and have all that come back as a graph of high-level objects.<\/p>\n<p>Despite my attempts to use plugins, extend and\/or fix bugs in those plugins, and to dig through the ActiveRecord source to figure out what the documentation won&#8217;t tell me, I was unable to get it to work. Most of the parts of what I wanted was possible: acts_as_tsearch cleverly weaves SQL functions into a high-level ActiveRecord::Base.find calls; paginating_find provides a very convenient pagination API on top of ActiveRecord::Base.find, and ActiveRecord includes some clever association tricks such as automatic many-to-many relationships (has_and_belongs_to_many), eager loading of associated records using a join (via the :include option to ActiveRecord::Base.find), and a fairly low-level :joins option that lets you add tables to a &#8216;find&#8217; query which can be used in your :conditions. Problem is, they don&#8217;t all work together in a fancy way.<\/p>\n<p>Really, the issue in this case is related to the design choices that went into ActiveRecord.<\/p>\n<p>Some ORMs (object-relational mappers) are designed in a modular fashion: there is a part that helps you describe the relationships between your model objects, a part that helps you construct queries, and a part that does the storage and retrieval. Sometimes there&#8217;s another part that uses your description of object relationships to create an empty database with the appropriate data model, or that looks at an existing database and creates an object model that matches it. Sometimes there&#8217;s an import\/export tool for bulk data loading or dumping as well.<\/p>\n<p>ActiveRecord has the first three functions integrated (which has benefits and drawbacks compared to a more modular approach), has a very isolated schema manipulation module, and has a somewhat isolated data loader tool.<\/p>\n<p>The relationships are explicitly declared in source code using associations: has_one, has_many, belongs_to, and has_and_belongs_to_many. These are pretty fancy and provide some convenience features that make the associations appear as object collections, such that changing the collection and saving it turns into insert\/delete\/update activity in the database.<\/p>\n<p>Query construction is basically tied to the objects themselves, in a way that greatly simplifies star-join queries, but which handles only the simplest joins across multiple tables, and is barely able to handle self-referential joins at all. So, you can easily load an object (or group of similar objects) and associated objects, but OLAP-style queries (&#8220;what are the top 5 states where customers are located who have bought classical CDs within 2 weeks of their release using American Express and had them shipped as gifts via UPS 3-day Select?&#8221;) are impossible. Oddly, views, functions, and stored procedures could bridge the gap between real-world data models and ActiveRecord&#8217;s limited set of association types, but they are not supported either.<\/p>\n<p>The storage and retrieval code is inseparable from the query code, and so it is not possible to examine and modify the final SQL before it is executed, nor is it possible to provide an arbitrary query and have the results be parsed into an object graph based on the associations you have defined. The code that would allow these features appears to exist and be sufficiently well designed to allow this with a fairly small amount of changes to ActiveRecord. However, it is currently (as of Rails 1.2.3, which is the current release) not part of the documented API and is declared private.<\/p>\n<p>There is a limited facility for constructing simple objects from arbitrary SQL, in find_by_sql. This loses essentially all of the high level functionality of the find method; most notably, it isn&#8217;t possible to use find_by_sql results to instantiate an object graph, rather than a flat array of objects (similar to the eager loading feature in the regular find method).<\/p>\n<p>ActiveRecord has fairly good high-level schema creation functionality (&#8220;migrations&#8221;). Though it lacks concepts for all but the basic database objects, support can be added for <a href=\"http:\/\/www.redhillonrails.org\/#foreign_key_migrations\">foreign key constraints<\/a> (I kid you not, they aren&#8217;t supported by Rails itself!) and <a href=\"http:\/\/activewarehouse.rubyforge.org\/rails_sql_views\/\">views<\/a>. There&#8217;s also a simple way to execute arbitrary SQL. Migrations aren&#8217;t technically that amazing, but rather they&#8217;re a helpful organizational approach to what can be a really hairy problem: defining a schema and then applying changes to live databases while keeping track of what changes you&#8217;ve already applied.<\/p>\n<p>Finally, there is a test data loading facility called Fixtures. The common opinion of Fixtures seems to be that they are broken by design and should be avoided. The main issue I&#8217;ve found with them is that the implementation ignores the kind of database design elements that any book on SQL would recommend, such as foreign keys and check constraints. I managed to circumvent this with a combination of a plugin and some customization, described in detail in my previous post, <a href=\"http:\/\/www.pervasivecode.com\/blog\/2007\/08\/02\/rails-fixtures-the-test-db-and-testunit\/\">Rails, Fixtures, the Test DB, and Test::Unit<\/a>. With those changes, all test fixture data is preloaded in the right order (so constraints aren&#8217;t violated) before any tests run, and any data alterations within tests are rolled back automatically by Rails.<\/p>\n<p>A secondary issue with Fixtures is that they go directly from YAML text files to SQL INSERT statements, bypassing the ActiveRecord Model classes. ActiveRecord does pretty much rule out any fancy mapping between database tables and objects, so that&#8217;s not a problem, but this model-skipping fixture loading implementation means that any code in your model object (validations, before_save filters, etc.) <i>will not be executed<\/i> when loading fixtures. So fixtures do not work well with the otherwise pervasive Rails design rule of &#8220;put all the intelligence in the application&#8221;.<\/p>\n<p>Still, despite the commonly-held disdain for using fixtures at all, I find that they can be tamed. In fact I&#8217;ve even created a base data facility for loading the fundamental data set that needs to be in the live database (e.g. initial admin user info). My approach is basically to alter fixture behavior to treat it as essentially a bulk data loading tool, and to do the extra housekeeping after loading to make up for the fact that the ActiveRecord model code was bypassed.<\/p>\n<p>As far as I know, there is no bulk data dumping functionality in Rails.<\/p>\n<p>So, to summarize, of the five main ORM features, here&#8217;s how ActiveRecord stacks up:<\/p>\n<ol>\n<li><b>Describing Relationships<\/b>: Easy to understand and use, with lots of slick functionality<\/li>\n<li><b>Querying<\/b>: Easy to understand and use, but limited to simple join structures, and not possible to customize query building or rewrite SQL before execution<\/li>\n<li><b>Storage and Retrieval<\/b>: Very easy to use, but only within the limits of the query builder&#8217;s features<\/li>\n<li><b>Schema manipulation<\/b>: Easy to understand and use; limited in functionality but readily extensible; solid third party plugins are available for missing schema objects<\/li>\n<li><b>Bulk Loading and Dumping<\/b>: Loading is badly designed and implemented, but fixable with some effort; dumping is not offered<\/li>\n<\/ol>\n<p>Okay, so it definitely makes the easy stuff easy. But what about the rest?<\/p>\n<p>As I observed before, ActiveRecord is not designed as a set of modules that you use to assemble a solution that fits your needs. That&#8217;s more of the Java approach to design, and it trades flexibility for convenience. It can be a major pain to assemble a working system out of all of those abstract Java APIs, which are sometimes so comically over-<a href=\"http:\/\/en.wikipedia.org\/wiki\/Design_Patterns\">pattern<\/a>ized as to draw mockery such as the hilarious &#8220;Are Javalanders Happy?&#8221; code snippet from <a href=\"http:\/\/steve-yegge.blogspot.com\/2006\/03\/execution-in-kingdom-of-nouns.html\">Execution in the Kingdom of Nouns<\/a>.  Rails makes the opposite trade-off: sacrifice flexibility and gain a very approachable API.<\/p>\n<p>Unfortunately, the Java approach (too abstract to readily use, but extremely flexible) is easily wrapped with a simpler, more convenient, less customizable API. The Rails approach isn&#8217;t internally componentized (have a look at ActiveRecord&#8217;s activerecord\/base.rb source file in its 2,165-line glory, almost all of which is one class), so if you want to fiddle with its internal behavior, you can&#8217;t. So with Rails, it&#8217;s all or nothing: high level slickness for simple requirements, or hand-written SQL and hand-coded results mapping for your complex requirements.<\/p>\n<p>As I said at the beginning, though, the key question is not how comprehensive the high level feature set is. More important is the question of how painful things are when you drop down to a lower level for a greater degree of control.<\/p>\n<p>It would be nice if there were a middle level of complexity, between the high-level &#8216;find&#8217; method and &#8216;has_xxx&#8217; associations, and raw SQL. There isn&#8217;t. I think that the reason there isn&#8217;t one is that there is still a persistent belief among many Rails core team members and community members that databases should be stupid: just a persistent hash. Once upon a time I worked that way myself: I didn&#8217;t have access to or skill with a SQL RDBMS, and so I solved all of my persistence problems with DBM files, which (using Perl&#8217;s Tie::Hash class) are conceptually just persistent hashtables. miniSQL was little more than a SQL query parser on top of that sort of storage engine, and MySQL originally was pretty similar. But big databases have all sorts of useful features that address complicated persistence requirements in a fairly elegant way.<\/p>\n<p>Given that Ruby fans like the idea of domain specific languages, which let you work in a super high level language customized to the problem domain, it&#8217;s surprising that Rails groupthink is that SQL is bad. It&#8217;s actually a very high level language, and allows a well written database to do some pretty amazing optimization on the fly because it provides a strong layer of abstraction between what you requested and how the storage engine provides it.<\/p>\n<p>No, it&#8217;s not dynamic, nor is it pure relational perfection, but it&#8217;s pretty darn good. Pre- and post-event validations and arbitrary callbacks to user-specified code, functions providing behavior on top of data&#8230; these are all things that Ruby and Rails fans hold in high regard when provided by Ruby and Rails, but which are considered a bad idea at the database layer. As I discussed at length in <a href=\"http:\/\/www.pervasivecode.com\/blog\/2007\/08\/02\/rails-and-the-notion-of-stupid-databases-being-a-good-idea\/\">Rails and the notion of Stupid Databases Being a Good Idea<\/a>, this is a philosophy rooted in <a href=\"http:\/\/c2.com\/cgi\/wiki?DontRepeatYourself\">DRY<\/a>, but it has some major flaws.<\/p>\n<p>Mainly, there is the issue that some things <i>must<\/i> be done in the data tier, and trying to put them in the application tier doesn&#8217;t work. The best example that comes to mind is full text search. Satisfying queries is the database&#8217;s job, period. It&#8217;s just hideously slow to try and do an inner join in the application across a network link to a database. If you find yourself doing this, that&#8217;s a pretty good sign that your architecture is broken. But some queries are too complicated for ActiveRecord, so sometimes you must choose between a series of high level queries whose results are intersected in application code (easy to understand, but extremely inefficient), or hand coded SQL.<\/p>\n<p>Well, SQL is fast and is a high level domain-specific language, so it isn&#8217;t actually a bad tool for the job. The problem is that this approach (the trapdoor to the lower level API) is regarded differently by different people. Some see it as a common and reasonable approach to complex requirements; others see it as a bad evil scary thing that should be avoided at all costs, a <a href=\"http:\/\/gilesbowkett.blogspot.com\/2007\/05\/evan-weavers-railsconf-presentation.html\">kludge and a design mistake<\/a>.<\/p>\n<p>As a result, the low level option in Rails is anemic. It&#8217;s there, but you&#8217;re not supposed to use it. <a href=\"http:\/\/rlucas.net\/blog\/bugfix\/ruby_active_record_makes_raw_sql_a_royal_pain.html\">Ruby&#8217;s ActiveRecord Makes Dropping to Raw SQL a Royal Pain (Probably on Purpose)<\/a> notes that there are no bind variables allowed in ActiveRecord. You may be saying, &#8220;No, wait a minute, I&#8217;ve used them, that can&#8217;t be right.&#8221; That&#8217;s what I thought. Look at the source; the bind variable functionality is actually a high level feature built on top of drivers that don&#8217;t have that feature. Whatever you did at the high level, it&#8217;s going to the driver as a single string. Okay, it&#8217;s nice that they added that feature, especially since it provides a single point of testing and verification for safe escaping. But that functionality (in sanitize_sql) is <i>not part of the public API<\/i>. Fortunately <a href=\"http:\/\/rlucas.net\/blog\/bugfix\/ruby_active_record_makes_raw_sql_a_royal_pain.html\">that same article<\/a> provides a workaround that makes sanitize_sql accessible, so you can use bind variables in your hand coded SQL code, and pretend that the driver supports them. But that&#8217;s not likely to work forever.<\/p>\n<p>The key problem with ActiveRecord is its least common denominator feature set, based around the least featureful of all popular SQL databases: MySQL. Years ago, MySQL AB (the vendor of the MySQL database) took a strong philosophical stand against pretty much any advanced database features (which their product lacked, and which competing products had), but lately they&#8217;ve softened and added those features that they claimed nobody really needed. In the meantime, Rails has been designed with minimal expectations for database sophistication; therefore, the limited functionality of ActiveRecord is fairly complete, assuming you&#8217;re using a database with similarly limited functionality.<\/p>\n<p>Triggers, stored procedures, functions, data integrity constraints, nested transactions, and views are all examples of unsupported database functionality. Try and use them via ActiveRecord&#8217;s high level API, and you will quickly see how fragile and inflexible ActiveRecord really is. If you shouldn&#8217;t need those features in your database, then you shouldn&#8217;t need anything that ActiveRecord doesn&#8217;t already provide, so it shouldn&#8217;t matter that you can&#8217;t extend ActiveRecord.<\/p>\n<p>Truly, these are features that you need only in a few small cases in your application, so looking at individual queries they&#8217;re needed rarely (which is not the same thing as &#8220;never&#8221;). But looking at whether you need one or more of them in a given <i>application<\/i>, they&#8217;re needed <i>more often than not<\/i>. The pain of using hand coded SQL makes this worse: some tricky things could be done either using a view or stored procedure, or using a really slick dynamic SQL statement. Making all of those options painful means that even a clever developer can&#8217;t use anything in their bag of tricks to craft an elegant solution.<\/p>\n<p>Unfortunately, non-trivial web applications need things like full text search, complex associations between persistent objects, non-trival summary information about associated objects, and complex reports, and ActiveRecord fails at all of these. These are not just things that big dumb ancient companies that like using Object COBOL think they need; Amazon and eBay need them too.<\/p>\n<p>The <a href=\"http:\/\/code.google.com\/p\/acts-as-tsearch\/\">acts_as_tsearch<\/a> plugin is a good case study of ActiveRecord&#8217;s design flaws. <a href=\"http:\/\/www.sai.msu.su\/~megera\/postgres\/gist\/tsearch\/V2\/\">TSearch2<\/a> is the standard PostgreSQL full text search engine, and it&#8217;s pretty good in my opinion. It&#8217;s also pretty straightforward to use. Unfortunately for developers using Rails, TSearch2 uses SQL functions (mainly <code>to_tsquery<\/code> and <code>rank_cd<\/code>). The acts_as_tsearch plugin tries to inject SQL into ActiveRecord&#8217;s queries via the high-level <code>find<\/code> interface, but ultimately fails as soon as you use the :joins or :include options. The problem is that ActiveRecord has a very simplistic idea of how queries and joins work, and so if you need to inject SQL functions to get the job done (as is necessary in TSearch2 queries), too bad. (See also issues <a href=\"http:\/\/code.google.com\/p\/acts-as-tsearch\/issues\/detail?id=7\">7<\/a> and <a href=\"http:\/\/code.google.com\/p\/acts-as-tsearch\/issues\/detail?id=8\">8<\/a> in acts_as_tsearch, in which I describe and attempt to clean up the mess that results when you use find_by_tsearch in non-trivial ways.)<\/p>\n<p>A fellow Rails developer asked me in all seriousness why I wasn&#8217;t abandoning the full text search functionality of TSearch2 and just using a completely separate, redundant database product designed exclusively for full text search. Seriously, that is considered the &#8220;easy&#8221; approach: one database for full text search, and another for ACID\/OLTP\/CRUD. Honestly if I were going to go down that road I would try hard to just abandon the SQL RDMBS and put everything in the other database, since Lucene and its imitators are capable of far more than just find-text-in-document queries. The pain of duplicating everything, using two query languages, two document representations (in addition to the object representation in Ruby) and writing application-tier query correlation makes the double-DB approach seem very unwise.<\/p>\n<p>It makes far more sense to me to use the SQL RDMBS&#8217;s full text search facility, even if there&#8217;s a 2x or 3x read performance penalty, because the conceptual simplicity of having one powerful storage tier (instead of two halves cobbled together) eliminates a ton of ugliness in the application, and the SQL RDBMS is going to get clustered for reads anyway. Nevertheless, even if I&#8217;m wrong about this case (putting search in the SQL RDBMS instead of in a separate server), there are other cases for needing a smart database that gives you exactly the results you need and lets you push data logic into the data tier.<\/p>\n<p>So, what do I suggest? Abandon Rails? Nope. I still like Ruby a lot, and find Rails very useful. I just think that ActiveRecord needs to support the low-level and middle-level abstractions better.<\/p>\n<p>Specifically, supporting bind variables (either by exposing that sanitize_sql function, or better yet by making drivers and connection adapters support bind variables for real) would make the <code>find_by_sql<\/code>, <code>select_all<\/code>, and <code>exec<\/code> approaches to low-level SQL query execution less painful.<\/p>\n<p>More difficult, and substantially more valuable, would be refactoring ActiveRecord::Base to split it up in the way I described above: association descriptions and unmarshalling code separate from query building code separate from SQL execution and result retrieval code. All of this could remain hidden for most users under the same old slick high-level API, but for advanced requirements, the ability to fiddle with the SQL and still use the built in high-level unmarshalling code to create object graphs from flat result sets would be very powerful, and useful. <\/p>\n<p>I looked at one alternative to ActiveRecord, called <a href=\"http:\/\/sequel.rubyforge.org\/\">Sequel<\/a>, which overlaps with ActiveRecord only partially. It is a query builder and lazy result proxy, which is actually what I thought ActiveRecord would do when I first started working with Rails. The proxy design means that you can either keep adding constraints or start fetching results, from the same Dataset class. This seems like a pretty good approach, though I haven&#8217;t really looked closely to make sure it would fit what ActiveRecord needs.<\/p>\n<p>What Sequel lacks, though, is the unmarshalling side: turning a 2-dimensional (rows of columns) result set into a complex object graph (customers with orders with order lines with products from suppliers stored in warehouses), with user-controlled eager or lazy loading behavior. Ruby is well-suited to a design that would allow user-specified code (i.e., a block) to decompose each row into the object graph associated with that row, leaving the remaining associations on those objects to be lazily provided via future queries.<\/p>\n<p>So, I think there is hope for ActiveRecord, definitely. I considered the idea of rolling a minimal Hibernate clone, or some other sort of challenger to ActiveRecord, but I don&#8217;t that ActiveRecord is broken beyond repair. I think the shortest path to a badass Ruby ORM is through improvements (refactoring and abstraction) to ActiveRecord.<\/p>\n<p>So, if you&#8217;ve read this far, you probably care about these issues. Here&#8217;s my call to action: Please help me make ActiveRecord less like VB and more like Delphi. Who else is interested in helping me with this effort? Are there alternatives that I&#8217;ve missed, or components that could be integrated into ActiveRecord to make it better?<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I&#8217;ve been working with Ruby on Rails intensively for several months, and I&#8217;ve finally found a place where Rails can&#8217;t readily be extended to do what I want. It&#8217;s ActiveRecord, which is probably the most controversial part of Rails. I&#8217;m reminded of a James Gosling quote disparaging Microsoft tools, particularly Visual Basic: &#8220;The easy stuff &hellip; <a href=\"http:\/\/www.pervasivecode.com\/blog\/2007\/10\/04\/activerecord-the-visual-basic-of-object-relational-mappers\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;ActiveRecord: the Visual Basic of Object Relational Mappers&#8221;<\/span><\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6,16,17,27,28,19,26,20,18],"tags":[],"class_list":["post-46","post","type-post","status-publish","format-standard","hentry","category-architecture","category-articles","category-databases","category-java","category-perl","category-postgresql","category-ruby","category-ruby-on-rails","category-sql"],"_links":{"self":[{"href":"http:\/\/www.pervasivecode.com\/blog\/wp-json\/wp\/v2\/posts\/46"}],"collection":[{"href":"http:\/\/www.pervasivecode.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.pervasivecode.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.pervasivecode.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/www.pervasivecode.com\/blog\/wp-json\/wp\/v2\/comments?post=46"}],"version-history":[{"count":0,"href":"http:\/\/www.pervasivecode.com\/blog\/wp-json\/wp\/v2\/posts\/46\/revisions"}],"wp:attachment":[{"href":"http:\/\/www.pervasivecode.com\/blog\/wp-json\/wp\/v2\/media?parent=46"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.pervasivecode.com\/blog\/wp-json\/wp\/v2\/categories?post=46"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.pervasivecode.com\/blog\/wp-json\/wp\/v2\/tags?post=46"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}