これはPGroonga 2.X用のドキュメントです。古いPGroongaを使っているならPGroonga 1.xのドキュメントを見てください。

pgroonga_set_writable関数

概要

pgroonga_set_writable関数はPGroongaのデータを変更できるかどうか設定します。通常、この設定をする必要はありません。

この関数を使うことでオンラインバックアップを実現できます。この使い方をする場合は以下の条件を満たす必要があります。

構文

この関数の構文は次の通りです。

bool pgroonga_set_writable(new_writable)

new_writablebool型の値です。trueは変更可能でfalseは変更不可能という意味です。

変更する前は変更可能だったかどうかを返します。

使い方

サンプルスキーマとデータは次の通りです。

SET pgroonga.enable_wal = yes;

CREATE TABLE memos (
  content text
);

CREATE INDEX pgroonga_memos_index
          ON memos
       USING pgroonga (content);

INSERT INTO memos VALUES ('PGroonga (PostgreSQL+Groonga) is great!');

pgroonga_writable関数にfalseを渡した後はPGroongaのインデックスを変更できません。

SELECT pgroonga_set_writable(false);
--  pgroonga_set_writable 
-- -----------------------
--  t
-- (1 row)
INSERT INTO memos VALUES ('Groonga is great!');
-- ERROR:  pgroonga: can't insert a record while pgroonga.writable is false
SELECT pgroonga_set_writable(true);
--  pgroonga_set_writable 
-- -----------------------
--  f
-- (1 row)
INSERT INTO memos VALUES ('Groonga is great!');
-- INSERT 0 1

オンラインバックアップ

この関数を使うことでオンラインバックアップを実現できます。この使い方をする場合は以下の条件を満たす必要があります。

次の設定をpostgresql.confに追加します。

pgroonga.enable_wal = yes

オートバキュームを無効にします。

CREATE TABLE memos (
  content text
) WITH (autovacuum_enabled = false);

CREATE INDEX pgroonga_memos_index
          ON memos
       USING pgroonga (content);

データを変更した後は同一セッション内でSELECT pgroonga_command('io_flush', ARRAY['only_opened', 'yes'])を呼びます。

INSERT INTO memos VALUES ('PGroonga (PostgreSQL+Groonga) is great!');
SELECT pgroonga_command('io_flush', ARRAY['only_opened', 'yes']);

バックアップ作成前に手動でVACUUMを実行することを推奨します。

VACUUM ANALYZE memos;
SELECT pgroonga_command('io_flush', ARRAY['only_opened', 'yes']);

バックアップ作成前にPGroongaのデータを変更できないようにします。

SELECT pgroonga_set_writable(false);
SELECT pgroonga_command('io_flush', ARRAY['only_opened', 'yes']);

これでPostgreSQLを止めずにバックアップを作成できます。

db_name="YOUR_DB_NAME"

# Detect database information
db_oid=$(psql \
  --dbname ${db_name} \
  --no-psqlrc \
  --no-align \
  --tuples-only \
  -c "SELECT datid FROM pg_stat_database WHERE datname = '${db_name}'")
data_dir=$(psql \
  --dbname ${db_name} \
  --no-psqlrc \
  --no-align \
  --tuples-only \
  -c "SHOW data_directory")

# Define directories
db_dir=${data_dir}/base/${db_oid}
backup_dir=${data_dir}/../../backup

# Create backup directory
mkdir -p ${backup_dir}

# Create backup
rsync -a --include '/pgrn*' --exclude '*' --delete ${db_dir}/ ${backup_dir}/

PGroongaのWALを削除することを推奨します。pgroonga_wal_truncate関数は変更不可のときでも実行できます。

SELECT pgroonga_wal_truncate();
SELECT pgroonga_command('io_flush', ARRAY['only_opened', 'yes']);

If you truncate PGroonga's WAL, you must create backup again with the above shell script. The process will be fast because rsync copies only different data.

PGroongaのデータを変更可能に戻します。

SELECT pgroonga_set_writable(true);
SELECT pgroonga_command('io_flush', ARRAY['only_opened', 'yes']);

参考