分享

实战演练:PostgreSQL在线扩容

 数据和云 2020-07-01

墨墨导读:最近被问到PG在线扩容的问题,本文整理了整个过程,之前写过一篇文章,供大家参考:《PosgreSQL三种表空间使用方式》https://www./db/14119

1. 查看表空间

postgres=# \db+                                  List of tablespaces    Name    |  Owner   | Location | Access privileges | Options |  Size   | Description ------------+----------+----------+-------------------+---------+---------+------------- pg_default | postgres |          |                   |         | 1088 MB |  pg_global  | postgres |          |                   |         | 2167 kB | (2 rows)


可以看到这里没有自定义表空间,默认使用pg_default 表空间

2. 创建演示数据库和用户

使用新的数据库app,并且owner为app用户来进行演示

postgres=# create user app password'XXX';CREATE ROLEpostgres=# create database app owner app;CREATE DATABASEpostgres=# \c app appYou are now connected to database "app" as user "app".app=> create schema app authorization app;CREATE SCHEMAapp=> create table public.t1(id int);CREATE TABLEapp=> create table app.t2(id int);CREATE TABLE


3. 新建表空间

创建表空间需要超级用户权限

$ mkdir tblspace_new
app=# CREATE TABLESPACE tbl_app OWNER app LOCATION '/home/postgres/tblspace_new';CREATE TABLESPACE


4. 数据库app使用新表空间作为默认表空间

app=# \c app appYou are now connected to database "app" as user "app".app=> alter database app set default_tablespace to tbl_app;
退出psql再重新连接app=> create table public.t3(id int);CREATE TABLEapp=> create table app.t4(id int);CREATE TABLEapp=> select pg_relation_filepath('t3'); pg_relation_filepath ------------------------------------------------ pg_tblspc/356916/PG_12_201909212/356883/356935(1 row)
app=> select pg_relation_filepath('app.t4'); pg_relation_filepath ------------------------------------------------ pg_tblspc/356916/PG_12_201909212/356883/356938(1 row)
app=> select oid,spcname from pg_tablespace ; oid | spcname --------+------------ 1663 | pg_default 1664 | pg_global 356916 | tbl_app(3 rows)

可以看到在app数据库下新建的表默认变到tbl_app表空间下,即oid为356916。


5. 修改用户app默认表空间为tbl_app

先恢复下上面的配置

drop table public.t3;drop table app.t4;alter database app set default_tablespace to default;
app=# \c app appapp=> alter user app set default_tablespace to tbl_app;


退出psql再重新连接

app=> create table public.t5(id int);CREATE TABLEapp=> create table app.t6(id int);CREATE TABLEapp=> select pg_relation_filepath('t5');              pg_relation_filepath              ------------------------------------------------ pg_tblspc/356916/PG_12_201909212/356883/356959(1 row)
app=> select pg_relation_filepath('app.t6'); pg_relation_filepath ------------------------------------------------ pg_tblspc/356916/PG_12_201909212/356883/356962(1 row)


可以看到用户app新建的表默认变到tbl_app表空间下,其他用户不受影响。


6. 总结

  • 如果要迁移数据表的表空间,会锁表,要注意对业务的影响。
  • 新建表修改database级别或者user级别(一般还是database级别)的默认表空间,只需配置一次,原有的数据表存储不改变,这种方式是推荐的。


墨天轮原文链接:https://www./db/26082(复制到浏览器中打开或者点击“阅读原文”)

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多