-
Notifications
You must be signed in to change notification settings - Fork 137
feat(diagnostic): превышение длины ключа индекса для файловой ИБ (#3986) #4292
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
erprivalov
wants to merge
1
commit into
1c-syntax:develop
Choose a base branch
from
erprivalov:feature/Issue-3986
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| # Превышена максимальная длина ключа индекса (FileDbIndexKeyLengthExceeded) | ||
|
|
||
| <!-- Блоки выше заполняются автоматически, не трогать --> | ||
| ## Описание диагностики | ||
|
|
||
| # Превышена максимальная длина ключа индекса (FileDbIndexKeyLengthExceeded) | ||
|
|
||
| <!-- Блоки выше заполняются автоматически, не трогать --> | ||
| ## Описание | ||
| <!-- Описание диагностики заполняется вручную. Необходимо понятным языком описать смысл и схему работу --> | ||
| Правило проверяет физический размер индексов в регистрах сведений (`InformationRegister`) | ||
| и регистрах расчета (`CalculationRegister`). | ||
| Если суммарный размер полей в индексе превышает лимиты СУБД, платформа 1С не сможет выполнить реструктуризацию, | ||
| и обновление конфигурации завершится ошибкой. | ||
|
|
||
| Проверка выполняется по двум направлениям: | ||
| 1. Основной индекс регистра (`ByDims`): состоит из всех измерений регистра. | ||
| Если регистр периодический, к размеру автоматически добавляется 8 байт на системное поле `Период`. | ||
| 2. Индивидуальные индексы полей: проверяются для любых измерений или реквизитов, | ||
| у которых свойство «Индексировать» установлено в значение, отличное от `Не индексировать` (`None`/`DONT_INDEX`). | ||
|
|
||
| Размер каждого типа поля рассчитывается кодом анализатора следующим образом: | ||
| * Строка (`String`): `Длина` * 3 + 2 байт (неограниченная строка считается как 9999 байт). | ||
| * Число (`Number`): (`Длина разрядов` / 2) + 1 байт. | ||
| * Дата (`Date`): 8 байт. | ||
| * Булево (`Boolean`): 1 байт. | ||
| * Любая ссылка (`Single Ref`): 16 байт. | ||
| * Составной тип (`Composite`): 1 байт (маркер) | ||
| + сумма максимальных длин выбранных примитивных типов | ||
| + 20 байт (если в составной тип включена хотя бы одна ссылка). | ||
|
|
||
| Параметры настройки: `checkMode` — режим проверки лимитов. | ||
|
|
||
| Допустимые значения: | ||
| * `ALL` (проверять все лимиты, по умолчанию) | ||
| * `FILE` (проверять только лимит файловой базы — 1920 байт) | ||
| * `MSSQL` (проверять только лимит MS SQL — 900 байт) | ||
|
|
||
| ## Примеры | ||
| <!-- В данном разделе приводятся примеры, на которые диагностика срабатывает, а также можно привести пример, как можно исправить ситуацию --> | ||
| Неправильно: | ||
|
|
||
| Создан периодический регистр сведений. Режим проверки установлен в `MSSQL` (лимит 900 байт) или `ALL`. | ||
| * Измерение `Организация` — тип `СправочникСсылка.Организации` (16 байт) | ||
| * Измерение `КомментарийКЗаписи` — тип `Строка(300)` (300 * 3 + 2 = 902 байта) | ||
|
|
||
| ```bsl | ||
| // Расчет индекса ByDims для этого регистра: | ||
| // Поле "Период" (8) + Организация (16) + КомментарийКЗаписи (902) = 926 байт. | ||
| // Результат: Правило выдаст ошибку превышения лимита MSSQL (926 > 900 байт). | ||
| ``` | ||
| Аналогично ошибка возникнет, если для обычного реквизита регистра с типом `Строка(400)` | ||
| включить свойство `Индексировать`: | ||
|
|
||
| ```bsl | ||
| // Индивидуальный индекс реквизита: 400 * 3 + 2 = 1202 байта. | ||
| // Результат: Ошибка превышения лимита MSSQL (1202 > 900 байт). | ||
| ``` | ||
|
|
||
| Правильно: | ||
|
|
||
| Длинные строковые данные вынесены из измерений в ресурсы или реквизиты без индексирования, | ||
| а длины ключевых строк оптимизированы. | ||
| * Измерение `Организация` — тип `СправочникСсылка.Организации` (16 байт) | ||
| * Измерение `КодИдентификатор` — тип `Строка(50)` (50 * 3 + 2 = 152 байта) | ||
| * Ресурс `КомментарийКЗаписи` — тип `Строка(300)` (не входит в состав индекса) | ||
|
|
||
| ```bsl | ||
| // Общий размер ключа ByDims: 8 (Период) + 16 (Организация) + 152 (КороткийКод) = 176 байт. | ||
| // Размер ключа находится в пределах нормы для любой СУБД. Замечаний нет. | ||
| ``` | ||
|
|
||
| ## Источники | ||
| <!-- Необходимо указывать ссылки на все источники, из которых почерпнута информация для создания диагностики --> | ||
| Источники: | ||
| * [Стандарт: Влияние ограничений длины ключа индексов на проектирование объектов метаданных](https://its.1c.ru/db/metod8dev/content/1828/hdoc) | ||
| * [Стандарт: Индексы таблиц базы данных](https://its.1c.ru/db/content/metod8dev/src/admins/i8101798.htm) | ||
| * [Стандарт: Несоответствие индексов и условий запроса](https://its.1c.ru/db/content/v8std/src/300/200/i8100652.htm) | ||
|
|
||
| Полезная информация: | ||
| * [В облачке: Длина ключа индекса превышает максимально допустимую](https://voblachke.ru/blog/dlina-kljucha-indeksa-prevyshaet-maksimalno-dopustimuju/) | ||
| * [Mista: Длина ключа индекса превышает максимально допустимую](https://www.mista.ru/topic/866818) | ||
| * [Infostart: Ошибка превышения максимальной длины ключа индекса](https://forum.infostart.ru/forum9/topic122084/) | ||
| * [Документация BSL LS: Структура диагностики, назначение и содержимое файлов](https://1c-syntax.github.io/bsl-language-server/contributing/DiagnosticStructure/) | ||
| <!-- Примеры источников | ||
|
|
||
| * Источник: [Стандарт: Тексты модулей](https://its.1c.ru/db/v8std#content:456:hdoc) | ||
| * Полезная информация: [Отказ от использования модальных окон](https://its.1c.ru/db/metod8dev#content:5272:hdoc) | ||
| * Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) --> | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| # Index key length limit exceeded (FileDbIndexKeyLengthExceeded) | ||
|
|
||
| <!-- Блоки выше заполняются автоматически, не трогать --> | ||
| ## Description | ||
| <!-- Описание диагностики заполняется вручную. Необходимо понятным языком описать смысл и схему работу --> | ||
| The rule checks the physical size of indexes in information registers (`InformationRegister`) | ||
| and calculation registers (`CalculationRegister`). | ||
| If the total size of fields in the index exceeds the DBMS limits, the 1C platform will not be able to perform restructuring, | ||
| and the configuration update will fail with an error. | ||
|
|
||
| The check is performed in two areas: | ||
| 1. Main register index (`ByDims`): consists of all register dimensions. | ||
| If the register is periodic, 8 bytes are automatically added to the size for the system `Period` field. | ||
| 2. Individual field indexes: checked for any dimensions or attributes | ||
| whose `Index` property is set to a value other than `Don't index` (`None`/`DONT_INDEX`). | ||
|
|
||
| The size of each field type is calculated by the analyzer code as follows: | ||
|
|
||
| * String (`String`): `Length` * 3 + 2 bytes (unlimited string is considered as 9999 bytes). | ||
| * Number (`Number`): (`Total digits` / 2) + 1 bytes. | ||
| * Date (`Date`): 8 bytes. | ||
| * Boolean (`Boolean`): 1 byte. | ||
| * Any reference (`Single Ref`): 16 bytes. | ||
| * Composite type (`Composite`): 1 byte (marker) | ||
| + sum of maximum lengths of the selected primitive types | ||
| + 20 bytes (if at least one reference is included in the composite type). | ||
|
|
||
| Configuration parameters: `checkMode` — limit validation mode. | ||
|
|
||
| Allowed values: | ||
| * `ALL` (check all limits, default) | ||
| * `FILE` (check only the file database limit — 1920 bytes) | ||
| * `MSSQL` (check only the MS SQL limit — 900 bytes) | ||
|
|
||
| ## Examples | ||
| <!-- В данном разделе приводятся примеры, на которые диагностика срабатывает, а также можно привести пример, как можно исправить ситуацию --> | ||
| Incorrect: | ||
| A periodic information register is created. The check mode is set to MSSQL (900 bytes limit) or ALL. | ||
| * Dimension `Company` — type `CatalogRef.Companies` (16 bytes) | ||
| * Dimension `RecordComment` — type `String(300)` (300 * 3 + 2 = 902 bytes) | ||
|
|
||
| ```bsl | ||
| // ByDims index calculation for this register: | ||
| // "Period" field (8) + Company (16) + RecordComment (902) = 926 bytes. | ||
| // Result: The rule will report an error exceeding the MSSQL limit (926 > 900 bytes). | ||
| ``` | ||
| Similarly, an error will occur if the Index property is enabled for a regular register attribute of type `String(400)`: | ||
| ```bsl | ||
| // Individual attribute index: 400 * 3 + 2 = 1202 bytes. | ||
| // Result: Error exceeding the MSSQL limit (1202 > 900 bytes). | ||
| ``` | ||
| Correct: | ||
|
|
||
| Long string data is moved from dimensions to resources or attributes without indexing, | ||
| and key string lengths are optimized. | ||
| * Dimension `Company` — type `CatalogRef.Companies` (16 bytes) | ||
| * Dimension `IdentifierCode` — type `String(50)` (50 * 3 + 2 = 152 bytes) | ||
| * Resource `RecordComment` — type `String(300)` (not included in the index) | ||
|
|
||
| ```bsl | ||
| // Total ByDims key size: 8 (Period) + 16 (Company) + 152 (ShortCode) = 176 bytes. | ||
| // The key size is within the norm for any DBMS. No warnings. | ||
| ``` | ||
| ## Sources | ||
| <!-- Необходимо указывать ссылки на все источники, из которых почерпнута информация для создания диагностики --> | ||
| Sources: | ||
| * [Methodological support: Influence of index key length limitations on designing metadata objects](https://its.1c.ru/db/metod8dev/content/1828/hdoc) | ||
| * [Methodological support: Database table indexes](https://its.1c.ru/db/content/metod8dev/src/admins/i8101798.htm) | ||
| * [Standard: Mismatch between indexes and query conditions](https://its.1c.ru/db/content/v8std/src/300/200/i8100652.htm) | ||
|
|
||
| Useful information: | ||
|
|
||
| * [V oblachke: Index key length exceeds the maximum allowable limit](https://voblachke.ru/blog/dlina-kljucha-indeksa-prevyshaet-maksimalno-dopustimuju/) | ||
| * [Mista: Index key length exceeds the maximum allowable limit](https://www.mista.ru/topic/866818) | ||
| * [Infostart: Maximum index key length exceeded error](https://forum.infostart.ru/forum9/topic122084/) | ||
| * [BSL LS Documentation: Diagnostic structure, purpose and file contents](https://1c-syntax.github.io/bsl-language-server/contributing/DiagnosticStructure/) | ||
|
|
||
| <!-- Примеры источников | ||
|
|
||
| * Источник: [Стандарт: Тексты модулей](https://its.1c.ru/db/v8std#content:456:hdoc) | ||
| * Полезная информация: [Отказ от использования модальных окон](https://its.1c.ru/db/metod8dev#content:5272:hdoc) | ||
| * Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) --> |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Remove the duplicate diagnostic heading.
The same H1 appears at Line [1] and Line [6], and markdownlint reports MD024. Keep only the generated heading or rename the second heading so the documentation passes lint.
🧰 Tools
🪛 markdownlint-cli2 (0.23.0)
[warning] 6-6: Multiple headings with the same content
(MD024, no-duplicate-heading)
🤖 Prompt for AI Agents
Source: Linters/SAST tools