9.1. Функции для распределённой системы #
Postgres Pro Shardman предоставляет ряд функций для распределённой системы. Они позволяют работать с узлами кластера, управлять сегментированными таблицами и распространять выполнение запросов.
Обратите внимание, что данные функции работают только в распределённых системах. Все функции в других разделах данной главы работают в обычных нераспределённых системах.
-
shardman.broadcast_all_sql(#statementtext) Выполняет
операторв каждой группе репликации.Предупреждение
Функция
shardman.broadcast_all_sqlне может выполняться рекурсивно. Попытка это сделать приводит к ошибке «Command execution must be initiated by coordinator» (Выполнение команды должно инициироваться координатором).-
shardman.broadcast_query(#statementtext) Действует аналогично shardman.broadcast_all_sql, а также возвращает результаты исполняемого
выраженияSQL.Можно задать необязательный параметр
include_rgid, тогда в результирующих кортежах будет номер узла, из которого получен кортеж.Пример с отключённым параметром
include_rgid:SELECT shardman.broadcast_query('SELECT relname FROM pg_class WHERE relkind=''f'''); broadcast_query ----------------- (t_1_fdw) (t_2_fdw) (t_0_fdw) (t_2_fdw) (t_0_fdw) (t_1_fdw) (6 rows)Пример с включённым параметром
include_rgid:SELECT shardman.broadcast_query('SELECT relname FROM pg_class WHERE relkind=''f''', include_rgid => true); broadcast_query ----------------- (1,t_1_fdw) (1,t_2_fdw) (2,t_0_fdw) (2,t_2_fdw) (3,t_0_fdw) (3,t_1_fdw) (6 rows)-
shardman.broadcast_sql(#statementtext) Выполняет
операторв каждой группе репликации, кроме текущей.Предупреждение
Функция
shardman.broadcast_sqlне может выполняться рекурсивно. Попытка это сделать приводит к ошибке «Command execution must be initiated by coordinator» (Выполнение команды должно быть инициироваться координатором).-
shardman.get_partition_for_value(#relidoid,valvariadic "any") →shardman.get_partition_for_value_type(local_nspnametext,local_relnametext,remote_nspnametext,remote_relnametext) Выясняет, к какой секции сегментированной таблицы с OID
relidпринадлежитval. Функция определяет секцию для любого значенияval, даже если оно не существует в указанной сегментированной таблице. Возвращает ошибку, если сегментированная таблица с OIDrelidне существует. Возвращает имя локальной схемы и имена отношений. Если значение принадлежит секции, хранящейся в другой группе репликации, также возвращает удалённую схему и имя отношения.Пример:
select * from shardman.get_partition_for_value('pgbench_branches'::regclass, 20); local_nspname | local_relname | remote_nspname | remote_relname --------------+-------------------------+----------------+--------------------- public | pgbench_branches_17_fdw | public | pgbench_branches_17-
shardman.get_topology()# Получает информацию о топологии кластера от shardmand. За подробной информацией о формате данных топологии кластера обратитесь к представлению shardman.topology.
-
shardman.global_analyze()# Выполняет последовательный анализ сегментированных и реплицированных таблиц всего кластера. Сначала эта функция выполняет
ANALYZEдля всех локальных секций сегментированных таблиц на каждом узле, а затем отправляет эту статистику на другие узлы. Затем она выбирает один узел для каждой реплицированной таблицы и запускаетANALYZEэтой таблицы на выбранном узле. Собранная статистика транслируется на все остальные узлы кластера. Обратите внимание, что реплицированные таблицы анализируются только один раз, в отличие от сценария запускаANALYZEна каждом узле.Пример:
select shardman.global_analyze();
В итоге статистика собирается для всех секций реплицированной таблицы, кроме статистики для секционированной таблицы.
-
shardman.global_analyze_async(#forceboolean,manage_txnboolean) Параллельно производит анализ сегментированных и глобальных таблиц по всему кластеру. В отличие от shardman.global_analyze такая процедура выполняется командой
ANALYZEна всех локальных секциях сегментированных таблиц одновременно на всех узлах. Кроме того, при этом секции не блокируются до конца операции.Параметр
forceзадаёт частоту выполнения командыANALYZEэтой процедурой. При значенииtrue(по умолчанию) командаANALYZEвыполняется всегда. При значенииfalseво избежание частых вызовов командыANALYZEиспользуются autovacuum_analyze_threshold и autovacuum_analyze_scale_factor.Параметр
manage_txnопределяет способ обработки операцийCOMMITпо завершении командыANALYZE. При значенииtrue(по умолчанию)COMMITвыполняется по завершении командыANALYZEдля каждой сегментированной или глобальной таблицы. При значенииfalseCOMMITне выполняется.Пример:
CALL shardman.global_analyze_async(force="false",manage_txn="true");
-
shardman.attach_subpart(#relidregclass,snumint,partition_boundtext[]) Присоединяет ранее отсоединённую подсекцию с номером
snumк локально секционированной таблицеrelidв качестве секции для указанных значений в диапазонеpartition_bound. Все таблицы подсекции и сторонние таблицы уже должны существовать. Параметрpartition_bound— это пара нижней и верхней границ секции. Если и нижняя, и верхняя границы равны NULL, подсекция присоединятся как стандартная.Операция выполняется на уровне кластера.
Пример:
select shardman.attach_subpart('pgbench_history'::regclass, 1,$${'2021-01-01 00:00', '2022-01-01 00:00'}$$);-
shardman.create_subpart(#relidregclass,snumint,partition_boundtext[]) Создаёт подсекцию с номером
snumдля локально секционированной таблицыrelidв качестве секции для значений в диапазонеpartition_bound. Параметрpartition_bound— это пара нижней и верхней границ секции. Если и нижняя, и верхняя границы равны NULL, подсекция создаётся как стандартная. Если номер подсекции не указан, он будет выбран в качестве следующего доступного номера секции.Операция выполняется на уровне кластера.
Примеры:
select shardman.create_subpart('pgbench_history'::regclass, 1, $${'2021-01-01 00:00', '2022-01-01 00:00'}$$); select shardman.create_subpart('pgbench_history'::regclass, partition_bound:=$${'2022-01-01 00:00', '2023-01-01 00:00'}$$);-
shardman.detach_subpart(#relidregclass,snumint) Отсоединяет подсекцию с номером
snumот локально секционированной таблицыrelid. Номер секции можно определить из представленияshardman.subparts.Операция выполняется на уровне кластера.
Пример:
select shardman.detach_subpart('pgbench_history'::regclass, 1);-
shardman.drop_subpart(#relidregclass,snumint) Удаляет подсекцию с номером
snumиз локально секционированной таблицыrelid. Номер секции можно определить из представленияshardman.subparts.Операция выполняется на уровне кластера.
Пример:
select shardman.drop_subpart('pgbench_history'::regclass, 1);-
shardman.am_coordinator()# Проверяет, является ли текущий сеанс координатором запроса. Данная проверка позволят избежать случаев повторного срабатывание триггеров управляемых таблиц, когда триггер срабатывает сначала в координаторе запроса, а потом на удалённых узлах при изменении данных.
SELECT shardman.am_coordinator(); am_coordinator ---------------- t (1 row)
Пример проверки триггерной функцией координатора запросов:
CREATE OR REPLACE FUNCTION trg_func() RETURNS TRIGGER AS $$ BEGIN IF NOT shardman.am_coordinator() THEN -- exit on non coordinator RETURN NEW; END IF; -- execute only by coordinator RAISE WARNING 'Trigger fired!'; END $$ LANGUAGE plpgsql;
9.1. Functions for Distributed System #
Postgres Pro Shardman provides a set of functions intended for a distributed system. These functions allow you to operate with cluster nodes, manage sharded tables, and broadcast query execution.
Note these functions only apply to the distributed systems. All functions in other sections of this chapter apply to regular non-distributed systems.
-
shardman.broadcast_all_sql(#statementtext) Executes
statementon every replication group.Warning
The
shardman.broadcast_all_sqlfunction cannot be executed recursively. An attempt to do so results in an error “Command execution must be initiated by coordinator”.-
shardman.broadcast_query(#statementtext) Functions as shardman.broadcast_all_sql and returns an executed SQL
statementresults.You may optionally set
include_rgidtotrue, then the resulting tuples will have a number of the node the tuple originated from.Example with
include_rgidset tofalse:select shardman.broadcast_query('SELECT relname from pg_class where relkind=''f'''); broadcast_query ----------------- (t_1_fdw) (t_2_fdw) (t_0_fdw) (t_2_fdw) (t_0_fdw) (t_1_fdw) (6 rows)Example with
include_rgidset totrue:select shardman.broadcast_query('SELECT relname from pg_class where relkind=''f''', include_rgid => true); broadcast_query ----------------- (1,t_1_fdw) (1,t_2_fdw) (2,t_0_fdw) (2,t_2_fdw) (3,t_0_fdw) (3,t_1_fdw) (6 rows)-
shardman.broadcast_sql(#statementtext) Executes
statementon every replication group but the current one.Warning
The
shardman.broadcast_sqlfunction cannot be executed recursively. An attempt to do so results in an error “Command execution must be initiated by coordinator”.-
shardman.get_partition_for_value(#relidoid,valvariadic "any") →shardman.get_partition_for_value_type(local_nspnametext,local_relnametext,remote_nspnametext,remote_relnametext) Finds out which partition of a sharded table with oid
relidthevalbelongs to. The function determines the partition for anyvaleven if it does not exist in the sharded table. Returns an error if the sharded table with oidreliddoes not exist. Returns the local schema name and relation names. If the value belongs to a partition stored in another replication group, also returns the remote schema and relation name.Example:
select * from shardman.get_partition_for_value('pgbench_branches'::regclass, 20); local_nspname | local_relname | remote_nspname | remote_relname --------------+-------------------------+----------------+--------------------- public | pgbench_branches_17_fdw | public | pgbench_branches_17-
shardman.get_topology()# Retrieves information about the cluster topology from shardmand. For more information about the cluster topology data format, see the shardman.topology view.
-
shardman.global_analyze()# Performs cluster-wide analysis of sharded and replicated tables. First, this function executes
ANALYZEon all local partitions of sharded tables on each node, then sends this statistics to other nodes. Next, it selects one node per replicated table and runsANALYZEof this table on the selected node. Gathered statistics is broadcast to all other nodes in the cluster. Note that replicated tables are only analysed once, unlike if you runANALYZEon each node.Example:
select shardman.global_analyze();
It results in the statistics gathered for all partitions and the replicated table, except for the statistics for the partitioned table.pg_class
-
shardman.global_analyze_async(#forceboolean,manage_txnboolean) Performs cluster-wide analysis of sharded and global tables in parallel. Unlike shardman.global_analyze, this procedure executes
ANALYZEon all local partitions of sharded tables on all nodes simultaneously. Also, the procedure does not keep partitions locked until the end of the operation.The
forceparameter determines how often the procedure executesANALYZE. Iftrue(default), the procedure always executesANALYZE. Iffalse, the procedure uses autovacuum_analyze_threshold and autovacuum_analyze_scale_factor to prevent frequentANALYZEcalls.The
manage_txnparameter determines the wayCOMMIToperations are processed after executingANALYZE. Iftrue(default), aCOMMITis performed after executingANALYZEon each sharded or global table. Iffalse, noCOMMIToperations are performed.Example:
CALL shardman.global_analyze_async(force="false",manage_txn="true");
-
shardman.attach_subpart(#relidregclass,snumint,partition_boundtext[]) Attaches a previously detached subpartition number
snumto a locally-partitioned tablerelidas a partition for the values withinpartition_bound. All subpartition tables and foreign tables should already exist. Thepartition_boundparameter is a pair of lower and upper bounds for the partition. If lower and upper bounds are both NULL, the subpartition is attached as the default one.The operation is performed cluster-wide.
Example:
select shardman.attach_subpart('pgbench_history'::regclass, 1,$${'2021-01-01 00:00', '2022-01-01 00:00'}$$);-
shardman.create_subpart(#relidregclass,snumint,partition_boundtext[]) Creates a subpartition number
snumfor a locally-partitioned tablerelidas a partition for the values withinpartition_bound. Thepartition_boundparameter is a pair of lower and upper bounds for the partition. If lower and upper bounds are both NULL, the subpartition is created as the default one. If the subpartition number is not specified, it will be selected as the next available partition number.The operation is performed cluster-wide.
Examples:
select shardman.create_subpart('pgbench_history'::regclass, 1, $${'2021-01-01 00:00', '2022-01-01 00:00'}$$); select shardman.create_subpart('pgbench_history'::regclass, partition_bound:=$${'2022-01-01 00:00', '2023-01-01 00:00'}$$);-
shardman.detach_subpart(#relidregclass,snumint) Detaches a subpartition number
snumfrom a locally-partitioned tablerelid. The partition number can be determined from theshardman.subpartsview.The operation is performed cluster-wide.
Example:
select shardman.detach_subpart('pgbench_history'::regclass, 1);-
shardman.drop_subpart(#relidregclass,snumint) Drops subpartition number
snumfrom locally-partitioned tablerelid. Partition number can be determined from theshardman.subpartsview.The operation is performed cluster-wide.
Example:
select shardman.drop_subpart('pgbench_history'::regclass, 1);-
shardman.am_coordinator()# Returns whether the current session is the query coordinator. This check allows avoiding cases where managed table triggers fire twice, first on the query coordinator, then on the remote nodes when data is modified.
SELECT shardman.am_coordinator(); am_coordinator ---------------- t (1 row)
Example of the trigger function checking the query coordinator:
CREATE OR REPLACE FUNCTION trg_func() RETURNS TRIGGER AS $$ BEGIN IF NOT shardman.am_coordinator() THEN -- exit on non coordinator RETURN NEW; END IF; -- execute only by coordinator RAISE WARNING 'Trigger fired!'; END $$ LANGUAGE plpgsql;