K.4. Дополнительные модули #
K.4.1. Встроенные модули по умолчанию #
Чтобы обеспечить поддержку решений 1C, дистрибутив Postgres Pro содержит следующие встроенные модули, которые включены по умолчанию и не требуют дополнительной настройки:
fasttrun — предоставляет транзакционно-небезопасную функцию для усечения временных таблиц, предотвращающую увеличение размера
pg_class.fulleq — предоставляет дополнительный оператор равенства для совместимости с Microsoft SQL Server.
mchar — предоставляет дополнительные типы данных
MCHARиMVARCHARдля совместимости с Microsoft SQL Server.
K.4.2. pg_trgm_mchar #
pg_trgm_mchar — расширение Postgres Pro, которое обеспечивает быстрый поиск схожих строк типов mchar и mvarchar на основе триграмм. Эти типы данных часто используются для решений 1C.
Чтобы включить поддержку поиска на основе триграмм для этих типов данных, установите pg_trgm_mchar с параметром CASCADE:
CREATE EXTENSION pg_trgm_mchar CASCADE;
Эта команда автоматически устанавливает все необходимые зависимости и включает поиск на основе триграмм для mchar и mvarchar. Это может быть особенно полезно для ускорения обработки динамических списков в решениях 1C.
K.4.3. dbcopies_decoding #
dbcopies_decoding — модуль 1C для обновления копий баз данных, который включён по умолчанию. Для использования механизма логической репликации этого модуля установите для параметра wal_level значение logical.
За более подробной информацией об этом модуле обратитесь в поддержку 1C.
K.4.4. plantuner #
Модуль plantuner позволяет оптимизировать планы выполнения запросов. Чтобы настроить его для решений 1C, выполните следующее:
Добавьте имя библиотеки в переменную
shared_preload_librariesв файлеpostgresql.conf.shared_preload_libraries = 'plantuner'
Установите для параметра
plantuner.fix_empty_tableзначениеonдля улучшения планирования запросов с недавно созданными пустыми таблицами.plantuner.fix_empty_table = on
K.4.5. online_analyze #
Модуль online_analyze предоставляет набор функций, которые немедленно обновляют статистику для задействованных таблиц после операций INSERT, UPDATE, DELETE, SELECT INTO или COPY.
Примечание
Для версий 1C:Enterprise 8.3.13 и выше необязательно использовать модуль online_analyze. 1C:Enterprise автоматически выполняет команду ANALYZE после каждой вставки во временную таблицу.
Однако включение online_analyze может быть полезным для более старых версий 1C:Enterprise или в особых случаях, например, если фоновые изменения не обеспечивают ожидаемые результаты или оптимизатор часто ошибается в оценке количества строк.
Следующая инструкция полезна, только если вы решите использовать этот модуль.
Чтобы настроить этот модуль, выполните шаги ниже.
Добавьте имя библиотеки в переменную
shared_preload_librariesв файлеpostgresql.conf.shared_preload_libraries = 'online_analyze'
Включите этот модуль.
online_analyze.enable = on
Укажите минимальное число изменений строк, после которого может начаться немедленный анализ.
online_analyze.threshold = 50
Укажите процент от размера таблицы, при котором начнётся немедленный анализ.
online_analyze.scale_factor = 0.1
Выполняйте команду
ANALYZEбезVERBOSE.online_analyze.verbose = off
Включите немедленный анализ для временных таблиц.
online_analyze.table_type = 'temporary'
Укажите минимальный интервал времени между вызовами
ANALYZEдля каждой таблицы, в миллисекундах.online_analyze.min_interval = 10000
K.4.6. auto_dump #
Расширение auto_dump предназначено для сбора данных по длительным и проблемным запросам и последующего воспроизведения этих запросов с целью устранения неполадок.
Чтобы включить и настроить это расширение, выполните следующие действия:
Добавьте
auto_dumpв параметр shared_preload_libraries в файлеpostgresql.conf.shared_preload_libraries = 'auto_dump'
Включите расширение:
auto_dump.enable = on
Перед использованием расширения задайте другие обязательные параметры конфигурации и перезапустите сервер баз данных, чтобы изменения вступили в силу.
K.4.7. Использование pg_hint_plan для 1С #
Модуль pg_hint_plan позволяет управлять планами выполнения запросов с помощью указаний для планировщика. За подробной информацией об установке и поддерживаемых типах указаний pg_hint_plan обратитесь к документации модуля.
Чтобы использовать pg_hint_plan для решений 1C, необходимо установить параметр pg_hint_plan.hints_anywhere в значение on. Это позволит планировщику считывать указания из любой части запроса. Сами указания должны задаваться в комментарии особого вида, который начинается с символов /*+ и заканчивается символами */. Такой комментарий следует добавлять в предложение WHERE в следующем формате:
WHERE ... AND '1' != '/*+ указание */'
Следующий пример демонстрирует запрос с указанием SeqScan:
SELECT
Спр.Ссылка,
Спр.Наименование
FROM
Справочник.Номенклатура КАК Спр
WHERE
Спр.ПометкаУдаления = ЛОЖЬ
AND
'1' != '/*+ SeqScan(t1) */'K.4.8. Помощь в планировании запросов #
Следующие модули предоставляют функциональность, аналогичную возможностям Microsoft SQL Server. Они помогают улучшить планирование и выполнение запросов, а также упрощают миграцию решений 1C на Postgres Pro.
aqo — расширение для оптимизации запросов на основе машинного обучения, которое улучшает оценку количества строк и качество планов выполнения для сложных запросов. Это может быть особенно полезно для нагрузок типа 1C с большим количеством отчётных и аналитических запросов. Данная функциональность аналогична Adaptive Query Processing (AQP) в Microsoft SQL Server.
pgpro_multiplan— расширение, которое позволяет сохранять планы выполнения запросов и использовать их при последующем выполнении тех же запросов, что помогает избежать повторной оптимизации идентичных запросов. Можно также использовать это расширение, чтобы фиксировать определённый план выполнения, если выбранный планировщиком план по каким-то причинам не подходит. Эта функциональность аналогична возможности заморозки планов в Microsoft SQL Server.
K.4. Additional Modules #
K.4.1. Built-In Default Modules #
To provide support for 1C solutions, the Postgres Pro distribution includes the following built-in modules that are enabled by default and do not require additional configuration:
fasttrun — provides a transaction-unsafe function to truncate temporary tables without growing the size of
pg_class.fulleq — provides an additional equivalence operator for compatibility with Microsoft SQL Server.
mchar — provides additional
MCHARandMVARCHARdata types for compatibility with Microsoft SQL Server.
K.4.2. pg_trgm_mchar #
pg_trgm_mchar is a Postgres Pro extension that allows fast trigram-based search for similar mchar and mvarchar strings. These data types are commonly used by 1C solutions.
To enable trigram‑based search support for these data types, install pg_trgm_mchar with the CASCADE option:
CREATE EXTENSION pg_trgm_mchar CASCADE;
This command automatically installs all required dependencies and enables trigram‑based search for mchar and mvarchar. This may be particularly useful for speeding up processing of dynamic lists in 1C solutions.
K.4.3. dbcopies_decoding #
dbcopies_decoding is a 1C module for updating database copies, which is enabled by default. To use the logical replication mechanism of this module, set the wal_level parameter to logical.
For more information about this module, contact 1C support.
K.4.4. plantuner #
The plantuner module allows optimizing query execution plans. To configure it for 1C solutions, do the following:
Add the library name to the
shared_preload_librariesvariable in thepostgresql.conffile.shared_preload_libraries = 'plantuner'
Set the
plantuner.fix_empty_tableparameter toonto improve planning for recently created empty tables.plantuner.fix_empty_table = on
K.4.5. online_analyze #
The online_analyze module provides a set of features that immediately update statistics after INSERT, UPDATE, DELETE, SELECT INTO, or COPY operations for the affected tables.
Note
For 1C:Enterprise versions 8.3.13 and later, using the online_analyze module is not necessary. This is because 1C:Enterprise automatically performs ANALYZE after each insert into a temporary table.
However, enabling online_analyze may still be useful for older versions of 1C:Enterprise or in specific cases, for example, when background updates do not provide the desired result or if the optimizer frequently fails to estimate the row count.
The instruction below is relevant only if you decide to use the module.
To configure this module, follow the steps below.
Add the library name to the
shared_preload_librariesvariable in thepostgresql.conffile.shared_preload_libraries = 'online_analyze'
Enable this module.
online_analyze.enable = on
Specify the minimum number of row updates before starting online analysis.
online_analyze.threshold = 50
Specify the fraction of the table size to start online analysis.
online_analyze.scale_factor = 0.1
Execute the
ANALYZEcommand withoutVERBOSE.online_analyze.verbose = off
Enable online analysis for temporary tables.
online_analyze.table_type = 'temporary'
Specify the minimum time interval between
ANALYZEcalls per table, in milliseconds.online_analyze.min_interval = 10000
K.4.6. auto_dump #
The auto_dump extension is designed to collect data on long-running and problematic queries and to further reproduce these problems for troubleshooting.
To enable and configure this extension, do the following:
Add
auto_dumpto the shared_preload_libraries parameter in thepostgresql.conffile:shared_preload_libraries = 'auto_dump'
Enable the extension:
auto_dump.enable = on
Before using the extension, set other required configuration parameters and restart the database server for the changes to take effect.
K.4.7. Using pg_hint_plan in 1C #
The pg_hint_plan module allows managing query execution plans by providing hints to the planner. For information about installation and supported hints of pg_hint_plan, refer to its documentation.
To use pg_hint_plan in 1C solutions, it is required to set the pg_hint_plan.hints_anywhere parameter to on to read hints from anywhere in a query. Hints should be specified in the special comment that begins with /*+ and ends with */. This comment should be added to the WHERE clause using the following syntax:
WHERE ... AND '1' != '/*+ your_hint */'
The following example shows a sample query with the SeqScan hint:
SELECT * FROM t1 WHERE t1.id = 1 AND '1' != '/*+ SeqScan(t1) */';
K.4.8. Query Planning Assistance #
The following modules provide functionality similar to Microsoft SQL Server features. They can help improve query planning and execution as well as simplify the migration of 1C solutions to Postgres Pro.
aqo — a machine learning-based query optimization extension that improves cardinality estimation and execution plan quality for complex queries, which can be especially useful for 1C workloads with intensive reporting and analytical queries. This functionality is similar to Adaptive Query Processing (AQP) in Microsoft SQL Server.
pgpro_multiplan — an extension that allows saving query execution plans and reuse them for subsequent executions of the same queries, avoiding repeated optimization. It can also lock a specific execution plan if the plan chosen by the planner does not suit your needs, which is similar to the plan-freezing functionality available in Microsoft SQL Server.