文章首发在个人博客
分析
通常来说,在需求分析阶段会确定数据库表中的字段,同时也普遍存在一种需求,那就是表中的字段除了常见的以外,还存在一些不确定的字段。譬如电商系统,有一个 products 表保存商品记录,然而各行各业的商品信息不一样,不可能因为某一行业商品特有的属性而在表中添加一个字段。面对这样的需求,如何设计数据库呢?
对策
文中提出来的解决方案的前提是系统所用的数据库支持 hash 数据类型,其中 PostgreSQL 支持 Hstore ,正好是我们需要的数据类型。所以前提是使用了 PostgreSQL 作为系统数据库在本文的讨论中才适用。
具体的实现思路细节是采用 Ruby on Rails 框架,不熟悉在 Rails 使用 psql 特性的读者可以先看看这篇文章 Active Record and PostgreSQL 。
在 Rails 的 ActiveRecord 中,使用 serialize 能够把 hash, json, array 类型的数据以 text 数据类型保存在数据库中。但是这种方式不能查询保存在数据库之前 hash json array 的原数据。ActiveRecord Base。PostgreSQL hstore 能补充这个短板。
Active Record can serialize any object in text columns using YAML. To do so, you must specify this with a call to the class method serialize. This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work.
Po