|
| 1 | +:sectnums: |
| 2 | +:sectnumlevels: 5 |
| 3 | + |
| 4 | += pg_readonly |
| 5 | + |
| 6 | +== 概述 |
| 7 | +pg_readonly 是一个能够将所有 PostgreSQL 的数据库设为只读的插件。 |
| 8 | + |
| 9 | +pg_readonly 没有特定的GUC参数,它依靠内存中的全局标志来管理只读状态,并提供了SQL函数来设置或者查询全局标志。 |
| 10 | +这个全局标志是集群级别的,集群中的数据库要么全部是只读的,要么全部是可读可写的。 |
| 11 | + |
| 12 | +只读模式通过过滤SQL语句实现。 |
| 13 | +[literal] |
| 14 | +---- |
| 15 | +允许不包含有写动作函数的SELECT语句; |
| 16 | +DML (INSERT, UPDATE, DELETE) 和 DDL 语句包括 TRUNCATE 完全不允许; |
| 17 | +DCL 语句 GRANT 与 REVOKE 也是禁止的; |
| 18 | +---- |
| 19 | + |
| 20 | +== 安装 |
| 21 | + |
| 22 | +[TIP] |
| 23 | +源码安装环境为 Ubuntu 24.04(x86_64),环境中已经安装了IvorySQL,安装路径为/path-to/ivorysql |
| 24 | + |
| 25 | +=== 源码安装 |
| 26 | + |
| 27 | +[literal] |
| 28 | +---- |
| 29 | +# 从 https://github.com/pierreforstmann/pg_readonly/releases/tag/1.0.6 下载 1.0.6 的源码包 1.0.6.tar.gz |
| 30 | +tar xvf 1.0.6.tar.gz |
| 31 | +cd pg_readonly-1.0.6 |
| 32 | +
|
| 33 | +# 编译安装 |
| 34 | +make PG_CONFIF=/path-to/ivorysql/bin/pg_config |
| 35 | +make PG_CONFIF=/path-to/ivorysql/bin/pg_config install |
| 36 | +---- |
| 37 | + |
| 38 | +=== 配置预加载库 |
| 39 | +修改 data 目录中的 ivorysql.conf 文件,向 shared_preload_libraries 中追加 pg_readonly。 |
| 40 | +shared_preload_libraries = 'pg_readonly' |
| 41 | + |
| 42 | +== 创建Extension并确认pg_readonly版本 |
| 43 | + |
| 44 | +psql 连接到数据库,执行如下命令: |
| 45 | +[literal] |
| 46 | +---- |
| 47 | +ivorysql=# CREATE EXTENSION pg_readonly; |
| 48 | +CREATE EXTENSION |
| 49 | +
|
| 50 | +ivorysql=# SELECT * FROM pg_available_extensions WHERE name = 'pg_readonly'; |
| 51 | + name | default_version | installed_version | location | comment |
| 52 | +-------------+-----------------+-------------------+----------+---------------------------- |
| 53 | + pg_readonly | 1.0.6 | 1.0.6 | $system | cluster database read only |
| 54 | +(1 row) |
| 55 | +---- |
| 56 | + |
| 57 | +== 使用 |
| 58 | + |
| 59 | +=== 检查单个函数 |
| 60 | + |
| 61 | +[literal] |
| 62 | +---- |
| 63 | +-- 查询当前集群只读状态 |
| 64 | +select get_cluster_readonly(); |
| 65 | + get_cluster_readonly |
| 66 | +---------------------- |
| 67 | + f |
| 68 | +(1 row) |
| 69 | + |
| 70 | +-- 设置当前集群为只读 |
| 71 | +select set_cluster_readonly(); |
| 72 | + set_cluster_readonly |
| 73 | +---------------------- |
| 74 | + t |
| 75 | +(1 row) |
| 76 | +
|
| 77 | +-- 只读的集群只允许 SELECT 语句 |
| 78 | +select * from t; |
| 79 | + x | y |
| 80 | +---+--- |
| 81 | +(0 rows) |
| 82 | +
|
| 83 | +update t set x=33 where y='abc'; |
| 84 | +ERROR: cannot execute UPDATE in a read-only transaction |
| 85 | +
|
| 86 | +select 1 into tmp; |
| 87 | +ERROR: cannot execute UPDATE in a read-only transaction |
| 88 | +
|
| 89 | +create table tmp(c text); |
| 90 | +ERROR: cannot execute UPDATE in a read-only transaction |
| 91 | +---- |
| 92 | + |
| 93 | +更多详细使用方法和高级特性,请参阅 https://github.com/pierreforstmann/pg_readonly 。 |
| 94 | + |
0 commit comments