Skip to content
Database

pg_repack:物理存储优化与维护

pg_repack 是一个 PostgreSQL 扩展,用于清理表和索引的膨胀,并可选择性地恢复聚簇索引的物理顺序。与 CLUSTER 和 VACUUM FULL 不同,pg_repack 可以“在线”运行,不会对处理的表加独占锁,从而不会阻塞正在进行的数据库操作。pg_repack 的效率与直接使用 CLUSTER 相当。

pg_repack 提供了以下方法来优化物理存储:

🌐 pg_repack provides the following methods to optimize physical storage:

  • 在线聚类:以非阻塞方式按聚类索引排序表格数据
  • 按指定列对表格数据排序
  • 在线 VACUUM FULL:以非阻塞方式只整理行
  • 只重建或移动表的索引

pg_repack 有两个部分,一个是数据库扩展,另一个是用于控制它的客户端命令行工具。

🌐 pg_repack has 2 components, the database extension and a client-side CLI to control it.

要求 #

🌐 Requirements

  • 目标表必须有一个主键,或者在非空列上有一个唯一的总索引。
  • 执行全表重打包需要的可用磁盘空间大约是目标表及其索引的两倍。

pg_repack 默认需要 Postgres 超级用户角色。Supabase 平台上的用户无法获得该角色。要避免这个要求,可以在每个 pg_repack CLI 命令上使用 -k--no-superuser-check 标志。

🌐 pg_repack requires the Postgres superuser role by default. That role is not available to users on the Supabase platform. To avoid that requirement, use the -k or --no-superuser-check flags on every pg_repack CLI command.

pg_repack 第一个完全支持非超级用户重打包的版本是 1.5.2。你可以使用以下方法查看你在 Supabase 实例上安装的版本

🌐 The first version of pg_repack with full support for non-superuser repacking is 1.5.2. You can check the version installed on your Supabase instance using

1
select default_version
2
from pg_available_extensions
3
where name = 'pg_repack';

如果没有 pg_repack,或者版本低于 1.5.2,请升级到最新版本的 Supabase 以获得访问权限。

🌐 If pg_repack is not present, or the version is < 1.5.2, upgrade to the latest version of Supabase to gain access.

用法 #

🌐 Usage

启用扩展 #

🌐 Enable the extension

先在 Supabase 仪表板中启用扩展,然后开始使用 pg_repack。

🌐 Get started with pg_repack by enabling the extension in the Supabase Dashboard.

  1. 在仪表板中转到数据库页面。
  2. 点击侧边栏的 扩展
  3. 搜索“pg_repack”并启用该扩展。

安装命令行工具 #

🌐 Install the CLI

从 pg_repack 文档中选择一个选项来安装客户端 CLI

🌐 Select an option from the pg_repack docs to install the client CLI.

语法 #

🌐 Syntax

所有 pg_repack 命令都应该包含 -k 标志,以跳过客户端的超级用户检查。

🌐 All pg_repack commands should include the -k flag to skip the client-side superuser check.

1
pg_repack -k [OPTION]... [DBNAME]

示例 #

🌐 Example

在数据库 postgres 中,对表 public.foopublic.bar 执行在线 VACUUM FULL 操作:

🌐 Perform an online VACUUM FULL on the tables public.foo and public.bar in the database postgres:

1
pg_repack -k -h db.<PROJECT_REF>.supabase.co -p 5432 -U postgres -d postgres --no-order --table public.foo --table public.bar

查看官方 pg_repack 文档以获取完整的选项列表。

🌐 See the official pg_repack documentation for the full list of options.

限制 #

🌐 Limitations

  • pg_repack 无法重组临时表。
  • pg_repack 不能按 GiST 索引对表进行聚簇。
  • 在 pg_repack 工作时,你不能对目标表执行 DDL 命令,除了 VACUUM 或 ANALYZE。pg_repack 会对目标表持有一个 ACCESS SHARE 锁来强制这个限制。

资源 #

🌐 Resources