# 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>
完結。