通知短信+运营短信,5秒速达,支持群发助手一键发送🚀高效触达和通知客户 广告
# 12. 表的继承和分区之 pg\_partman #### 1. 介绍 在这一篇文章[PostgreSQL的表的继承和分区之介绍(一)](http://www.rails365.net/articles/2015-10-09-postgresql-de-biao-de-ji-cheng-he-fen-qu-zhi-jie-shao-yi)介绍了表的继承和分区的概念以及如何使用的方法。 首先是分区建立在继承的基础上,先创建母表,通过约束条件创建子表,再通过创建触发器保证数据能插入到相应的子表中。这一切都是需要我们手动来创建的。 而[pg\_partman](https://github.com/keithf4/pg_partman)把这一些手动的过程全封装到函数中,通过函数的调用即可方便创建与维护,并且避免了手工创建引入错误。 #### 2. 安装 下载源代码安装。 ``` git clone git@github.com:keithf4/pg_partman.git cd pg_partman make install ``` 进入psql安装pg\_partman扩展。 ``` CREATE SCHEMA partman; CREATE EXTENSION pg_partman SCHEMA partman; ``` #### 3. 使用 设置partman为当前的表搜索路径。 ``` set search_path to partman; ``` 先创建一张母表。 ``` CREATE schema test; CREATE TABLE test.part_test (col1 serial, col2 text, col3 timestamptz NOT NULL DEFAULT now()); ``` 这张表很简单,只有三列,最后一列是时间。 ``` SELECT partman.create_parent('test.part_test', 'col3', 'time', 'daily'); ``` 我们先来查看创建成功后结果,使用下面的命令。 ``` partman=# \d+ test.part_test ``` 结果是: ``` Table "test.part_test" Column | Type | Modifiers | Storage | Stats target | Description --------+--------------------------+---------------------------------------------------------------+----------+--------------+------------- col1 | integer | not null default nextval('test.part_test_col1_seq'::regclass) | plain | | col2 | text | | extended | | col3 | timestamp with time zone | not null default now() | plain | | Triggers: part_test_part_trig BEFORE INSERT ON test.part_test FOR EACH ROW EXECUTE PROCEDURE test.part_test_part_trig_func() Child tables: test.part_test_p2015_10_10, test.part_test_p2015_10_11, test.part_test_p2015_10_12, test.part_test_p2015_10_13, test.part_test_p2015_10_14, test.part_test_p2015_10_15, test.part_test_p2015_10_16, test.part_test_p2015_10_17, test.part_test_p2015_10_18 ``` 由上可知,总共创建了一个叫part\_test\_part\_trig\_func的触发器和九张子表(part\_test\_p2015\_10\_11到part\_test\_p2015\_10\_18)。 可以用下面的命令来查看触发器part\_test\_part\_trig\_func的内容。 ``` partman=# select prosrc from pg_proc where proname='part_test_part_trig_func'; ``` 今天的时间是: ``` ➜ rails365 git:(master) date Wed Oct 14 21:46:30 HKT 2015 ``` 也就是14号之前有四张表,14号之后有四张表。 当然这些规则可以由我们自己自定义的,只要我们熟悉了create\_parent的用法就可以。 在上面的例子中。 ``` SELECT partman.create_parent('test.part_test', 'col3', 'time', 'daily'); ``` create\_parent的第一个参数接的是母表的名称,第二个接的是要分区的列的名称,第三个表示按照时间来分区,第四表示是按照时间上的每天来分区。这也解释了为什么会出现上面的按时间顺序命名的分区表的情况。 关于pg\_partman的更多内容可以查看官方的这篇文档[pg\_partman.md](https://github.com/keithf4/pg_partman/blob/master/doc/pg_partman.md)。 关于pg\_partman的更多示例可以查看官方的这篇文档[pg\_partman\_howto.md](https://github.com/keithf4/pg_partman/blob/master/doc/pg_partman_howto.md)。 另外,ruby也有相关的分区工具,就是用ruby来生成分区的指令。<https://github.com/ankane/pgslice> 完结。