PostgreSQL 教程: 移动表空间

四月 20, 2024

摘要:在本教程中,您将学习如何在 PostgreSQL 中移动表空间。

介绍

表空间旨在允许 PostgreSQL 实例分布到多个存储设备上。创建表空间时,会在集群数据目录的 pg_tblspc 目录中,创建一个指向新创建的表空间目录的符号链接。

遗憾的是,尽管有一个命令可以在表空间之间移动表和索引,但没有命令将表空间移动到不同的目录。但是,从 PostgreSQL 9.2 开始,移动表空间的过程非常简单:

  1. 记录要移动的表空间的 oid
  2. 关闭 PostgreSQL 实例
  3. 在同一文件系统中移动表空间目录,或者移动到其他文件系统中
  4. 将表示已移动的表空间的 oid 符号链接,更新到新的表空间目录位置
  5. 重新启动服务器

示例

下面是一个移动表空间的示例。

首先,我们需要为表空间创建一个空目录:

$ mkdir /data/pgsql/test_tblspc

第二步,使用一个超级用户连接到数据库,基于该目录创建一个表空间:

CREATE TABLESPACE test_tblspc LOCATION '/data/pgsql/test_tblspc';

CREATE TABLE test_table (x int) TABLESPACE test_tblspc;

INSERT INTO test_table VALUES (1);

SELECT oid, * FROM pg_tablespace;
  oid  |   spcname   | spcowner | spcacl | spcoptions
-------+-------------+----------+--------+------------
  1663 | pg_default  |       10 |        |
  1664 | pg_global   |       10 |        |
 16385 | test_tblspc |       10 |        |

SELECT pg_tablespace_location(16385);
 pg_tablespace_location
-------------------------
 /data/pgsql/test_tblspc

第三步,关闭 PostgreSQL 实例,并移动表空间目录:

$ pg_ctl stop

$ mv /data/pgsql/test_tblspc /data/pgsql/test2_tblspc/

$ cd $PGDATA/pg_tblspc/

$ ls -l
lrwxrwxrwx 1 postgres postgres 23 Sep  5 22:20 16385 -> /data/pgsql/test_tblspc

$ ln -fs /data/pgsql/test2_tblspc 16385

$ ls -l
lrwxrwxrwx 1 root root 24 Sep  5 22:25 16385 -> /data/pgsql/test2_tblspc

$ pg_ctl start

最后,我们可以验证下表数据,并确认新的表空间位置:

SELECT * FROM test_table;
 x
---
 1

SELECT pg_tablespace_location(16385);
  pg_tablespace_location
--------------------------
 /data/pgsql/test2_tblspc