表空間:字面上理解就是表存儲的物理空間,其實包括數據庫的表、索引、序列等。
可以將表空間創建在服務器的不同分區,這樣做的好處有:
一、如果初始化集群所在分區已經用光,可以方便的其他分區上創建表空間已達到擴容的目的。
二、對於頻繁訪問的數據可以存儲在性能較高、較快的磁盤分區上,而不常用的數據存儲在便宜的較慢的磁盤分區上。
語法:
postgres=# \h create tablespace
Command: CREATE TABLESPACE
Description: define a new tablespace
Syntax:
CREATE TABLESPACE tablespace_name
[ OWNER user_name ]
LOCATION 'directory'
[ WITH ( tablespace_option = value [, ... ] ) ]
用戶必須有表空間所在目錄訪問權限,所以在創建表空間之前需要在對應分區下創建相應的目錄,並為其分配權限。
[root@localhost ~]# mkdir /usr/local/pgdata
[root@localhost ~]# chown postgres:postgres /usr/local/pgdata/
創建表空間示例:
postgres=# create tablespace tbs_test owner postgres location '/usr/local/pgdata'; CREATE TABLESPACE
創建表空間成功后,可在數據庫集群目錄下看到一個新增的目錄pg_tblspc下有一個連接文件51276,指向到/usr/local/pgdata下
[root@localhost ~]# ll /mnt/syncdata/pgsql941/data/pg_tblspc/ total 0 lrwxrwxrwx. 1 postgres postgres 17 Aug 30 02:06 51276 -> /usr/local/pgdata
[root@localhost ~]# ll /usr/local/pgdata/ total 4 drwx------. 2 postgres postgres 4096 Aug 30 02:06 PG_9.4_201409291
在此表空間內創建表:
postgres=# create table test(a int) tablespace tbs_test; CREATE TABLE
現在在表空間目錄下就會新增一個test表對應的文件:
[root@localhost ~]# ll /usr/local/pgdata/PG_9.4_201409291/13003/51277
-rw-------. 1 postgres postgres 0 Aug 30 02:15 /usr/local/pgdata/PG_9.4_201409291/13003/51277
其中51277對應的是test表的relfilenode,13003是數據庫postgres的oid。
postgres=# select oid,datname from pg_database where datname = 'postgres'; oid | datname -------+---------- 13003 | postgres (1 row) postgres=# select relname,relfilenode from pg_class where relname='test'; relname | relfilenode ---------+------------- test | 51277 (1 row)
刪除表空間:
postgres=# \h drop tablespace
Command: DROP TABLESPACE
Description: remove a tablespace
Syntax:
DROP TABLESPACE [ IF EXISTS ] name
刪除表空間前必須要刪除該表空間下的所有數據庫對象,否則無法刪除。
如:
postgres=# drop tablespace if exists tbs_test; ERROR: tablespace "tbs_test" is not empty
刪除剛才在此表空間創建的表test,然后再刪除表空間。
postgres=# drop table if exists test; DROP TABLE postgres=# drop tablespace if exists tbs_test; DROP TABLESPACE