bitrix-sprint-migration
Covers Bitrix module sprint.migration — Version migrations, HelperManager (Iblock/Hlblock/Option/Agent/…), builders (run), CLI migrate.php (add/ls/up/down/redo/mark), configs migrations.*.php, restartable batches, exchange dirs. Use when creating or applying DB/schema/content mig
Install
npx skills add https://github.com/bxmaximum/bitrix-framework-skills/tree/main/skills/bitrix-sprint-migration
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install bxmaximum-bitrix-framework-skills@llmmart
git clone https://github.com/bxmaximum/bitrix-framework-skills.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole bxmaximum/bitrix-framework-skills collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
Bitrix sprint.migration
Module sprint.migration (Composer: andreyryabin/sprint.migration) stores
schema/content changes as PHP classes under VCS and applies them on each copy
of the project via CLI or admin UI.
Install location (either is valid; resolve before calling CLI):
| Path | Typical when |
|---|---|
/local/modules/sprint.migration/ |
Composer / marketplace into local |
/bitrix/modules/sprint.migration/ |
Marketplace / copy into kernel modules |
Below, {module} means that resolved directory. Do not edit module
source. Write only migration files and optional configs (usually under
php_interface/).
Progressive disclosure: open only the rule files that match the task.
How to use
- Confirm the module is installed (
Loader::includeModule('sprint.migration')). - Identify the layer (CLI/config vs writing a Version vs helpers/builders).
- Open the matching
rules/*.mdbelow. - Prefer helpers/
save*APIs over raw Bitrix API when they cover the entity. - For domain ORM/data updates without builders — use D7/
Resultinsideup(), still as aVersionclass.
Official wiki: https://github.com/andreyryabin/sprint.migration/wiki
Defaults (override via migrations.*.php / module options)
| Item | Default |
|---|---|
| Migration dir | {local\|bitrix}/php_interface/migrations (local wins if present) |
| Versions table | sprint_migration_versions |
| Class prefix | Version + timestamp YmdHis (name must contain a valid timestamp) |
| Extend class | Sprint\Migration\Version |
| CLI entry | php {module}/tools/migrate.php |
| Extra configs | {local\|bitrix}/php_interface/migrations.<name>.php → dir migrations.<name>, table sprint_migration_<name> |
Choose a rule file
When to read rules/cli-config.md
Read when the task involves:
- Running CLI (
add,ls,up,down,redo,mark,run,config) - Naming versions / timestamps
- Multiple configs (
--config,migrations.*.php) - Admin UI vs console auth user
When to read rules/writing.md
Read when the task involves:
- Authoring
Version(up/down) - Idempotent
save*vsadd*IfNotExists - Output (
outSuccess/outError), returnfalseon failure - Dependencies (
checkRequiredVersions) - Restartable long migrations
- Exchange files / large data sets
- Hand-written data migrations (ORM / SQL)
When to read rules/helpers-builders.md
Read when the task involves:
- Choosing a Helper (
Iblock(),Hlblock(), …) - Choosing a Builder (
run IblockBuilder, …) - Export-from-admin → commit generated PHP
When to read rules/checklist.md
Read before finishing or reviewing a migration change:
- Safety / anti-patterns
- Apply / verify checklist
Related skills
| Need | Skill |
|---|---|
| Iblock domain model | bitrix-iblocks |
| Highloadblock CRUD | bitrix-highloadblock |
| Raw SQL / DDL outside helpers | bitrix-database |
| Module install SQL (not sprint) | bitrix-modules |
| Agents registration | bitrix-background-jobs |
| Options / storage choice | bitrix-storage |
Checklist
- Opened only the rule file(s) needed for this task.
- Migration files live under the configured
migration_dir(not in the module). - Did not modify sprint.migration module source.
- Applied
upon a local/dev copy when verifying the change.
Files (bitrix-framework-skills)
-
rules
-
checklist.md 2.6 KB
# Safety and finish checklist ## Safety rules - Write migrations under configured `migration_dir` only — never patch `sprint.migration` module source for product needs. - Treat `up`/`down` as **production-capable**: they may alter schema and data. - Do not embed secrets, tokens, or personal dumps in migration files or exchange dirs. - Prefer identifying records by stable business keys (CODE, XML_ID), not by IDs copied from a local DB. - Avoid `delete` / mass `down` on shared environments unless explicitly requested. - `mark --as=installed` skips code execution — use only to align status after a known manual change, never as a substitute for a failed `up`. - Applying migrations on production requires explicit human approval; do not treat a successful local `up` as permission to change production. ## Anti-patterns | Anti-pattern | Do instead | | --- | --- | | Hand-editing installed migration that already ran on other copies | Add a **new** migration | | Hard-coded element/section IDs from local DB | Resolve by CODE/XML_ID via helpers | | Non-idempotent `add` that fails on second env | `save*` / `*IfNotExists` | | Empty `description` | Write a clear one-line purpose | | Giant irreversible data wipe in `down` “for symmetry” | Document one-way `down()` or omit | | Committing builder output without review | Diff-check generated arrays/files | | Using migrations for runtime business logic | Put logic in module services; migration only bootstraps/schema | ## Author checklist - [ ] Created via `add` or a builder (valid class name + timestamp). - [ ] `namespace Sprint\Migration;` and class name = file name. - [ ] `$description` filled. - [ ] `up()` is idempotent or safe to run once per environment. - [ ] `down()` implemented or explicitly documented as one-way. - [ ] Helpers used where available; modules `includeModule`'d for custom code. - [ ] No secrets; no `/bitrix/` edits. - [ ] Exchange files (if any) committed alongside the Version when required. ## Verify checklist - [ ] `ls --new` shows the migration before apply (or expected status). - [ ] `up` (or `up VersionName`) succeeds on a local/dev copy. - [ ] Spot-check admin / ORM / page that depends on the change. - [ ] If `down` is supported, `redo VersionName` once on a disposable copy. - [ ] Status in `ls` is `installed` after success. ## Review focus - Destructive deletes without filters or backups. - Reliance on environment-specific IDs. - Missing module checks before using custom classes. - Silent failures (`Result` ignored, no `outError` / `return false`). - Schema drift: `addIfNotExists` where an update (`save*`) was required. -
cli-config.md 4 KB
# CLI and config ## Resolve module path The module may be installed in **either** place: 1. `/local/modules/sprint.migration/` — prefer this if `include.php` exists there 2. `/bitrix/modules/sprint.migration/` — fallback ```bash # from document root if [ -f local/modules/sprint.migration/tools/migrate.php ]; then MIGRATE=local/modules/sprint.migration/tools/migrate.php else MIGRATE=bitrix/modules/sprint.migration/tools/migrate.php fi php "$MIGRATE" <command> [args] [options] ``` In docs below, **`{migrate}`** = that `tools/migrate.php` path. Optional thin wrapper in project root (e.g. `bin/migrate`) that sets `DOCUMENT_ROOT` and requires `{module}/tools/migrate.php`. Symfony: `php bin/console sprint:migration` when the SprintMigration bundle / console command is registered. CLI refuses non-CLI SAPI. It bootstraps Bitrix via `prolog_before.php`. ## Essential commands Full list: module files `commands.txt` (RU) / `commands-en.txt` under `{module}/`. | Command | Purpose | | --- | --- | | `add [desc] [name]` | Scaffold blank migration (`--desc`, `--name`) | | `ls` | List (`--new`, `--installed`, `--search=`, `--tag=`) | | `up` / `up [version]` | Apply all new or one version (`--search=`, `--add-tag=`) | | `down` / `down [version]` | Rollback | | `redo [version]` | `down` then `up` for one version | | `run [builder]` | Interactive/export builder (admin-oriented; CLI supported) | | `mark [version\|new\|installed\|unknown] --as=installed\|new` | Change status **without** running code | | `delete …` | Remove migration records/files (destructive — confirm intent) | | `config` | Show active config; `--config=[name]` switches config | Examples (after resolving `$MIGRATE` / `{migrate}`): ```bash php "$MIGRATE" add "Add news iblock" NewsIblock php "$MIGRATE" ls --new php "$MIGRATE" up php "$MIGRATE" up Version20240722144938 php "$MIGRATE" down Version20240722144938 php "$MIGRATE" redo Version20240722144938 php "$MIGRATE" mark Version20240722144938 --as=installed php "$MIGRATE" --config=shop up ``` Prefer **`add`** (or admin builders) over inventing filenames by hand. Hand-copied classes often break timestamp/name validation. ## Version naming - Must be a valid PHP class name: `^[a-zA-Z_][a-zA-Z0-9_]*$`. - Must contain a timestamp matching config `version_timestamp_format` (default `YmdHis`, pattern like `20\d{12}`). - Default template: `#NAME##TIMESTAMP#` → e.g. `Version20260720113800` or `NewsIblock20260720113800`. - Class name **equals** file basename without `.php`. - Namespace: `Sprint\Migration`. ## Configs Default config is built-in (empty overrides → module defaults). Additional configs: files in php_interface (`local/php_interface` if that directory exists, else `bitrix/php_interface`): ``` {php_interface}/migrations.<name>.php ``` Must `return` an array. Typical keys: ```php <?php return [ 'title' => 'Shop migrations', // path relative to docroot unless migration_dir_absolute is set 'migration_dir' => '/local/php_interface/migrations.shop', 'migration_table' => 'sprint_migration_shop', 'version_prefix' => 'Version', 'exchange_dir' => '/local/php_interface/migrations.shop', // 'console_user' => 'admin' | false | 'login:someuser', // 'migration_extend_class' => 'Version', // 'version_builders' => [...], ]; ``` Use `/bitrix/php_interface/...` in `migration_dir` / `exchange_dir` when the project has no `local/php_interface`. Custom config directories can also be registered via module event `OnSearchConfigFiles` (returns a directory path with `migrations.*.php` files). Show / switch: `config`, `--config=[name]`. ## Console user and events Defaults (unless overridden): - `console_user` = `admin` (migrations run as that user in CLI). - `console_auth_events_disable` = `true` (auth events skipped in console). Set `console_user` to `false` to run without authorizing a user when the change must not depend on admin context. ## Admin UI Module admin page can create migrations, run builders, and apply `up`/`down`. Same files and status table as CLI. Prefer CLI in automation scripts. -
helpers-builders.md 4.1 KB
# Helpers and builders Access helpers from any `Version`: ```php $helper = $this->getHelperManager(); $helper->Iblock()->saveIblock([...]); ``` A helper throws `HelperException` if its Bitrix module is not installed/enabled. ## Helper map | Call | Covers | Typical methods | | --- | --- | --- | | `Iblock()` | Iblock types, iblocks, fields, properties, sections, elements, permissions | `saveIblockType`, `saveIblock`, `saveProperty`, `saveSection`, `saveElement`, `deleteIblockIfExists` | | `Hlblock()` | Highload blocks, UF fields, elements, permissions | `saveHlblock`, `saveField`, `saveElementByXmlId`, `deleteHlblock` | | `UserTypeEntity()` | User fields (HL / user / other `ENTITY_ID`) | `saveUserTypeEntity`, `addUserTypeEntitiesIfNotExists`, `deleteUserTypeEntitiesIfExists` | | `UserGroup()` | Groups | `saveGroup`, `deleteGroup` | | `User()` | Users (rare in migrations) | helper methods on user entity | | `Agent()` | Agents | `saveAgent`, `deleteAgent` | | `Option()` | `COption` / module options | `saveOption`, `deleteOption` | | `Event()` | Mail events / templates | `saveEvent`, `saveEventType` | | `Form()` | Web forms | form export/save helpers | | `Forum()` / `Blog()` / `Vote()` / `Subscribe()` | Corresponding modules | module-specific `save*` | | `Site()` / `Lang()` / `Culture()` | Sites, languages, cultures | `saveSite`, language helpers | | `UserOptions()` | User / grid options | export/save UI options | | `Sql()` | Controlled SQL helpers | use sparingly; prefer ORM | | `Medialib()` / `MedialibExchange()` | Media library | collections/items | | `IblockExchange()` / `HlblockExchange()` | Exchange-backed element sync | used with exchange dirs | | `OrderProperties()` / `SaleDiscount()` / `DeliveryService()` | Sale-related | when `sale` is present | | `Task()` / `Text()` | Tasks / text utilities | niche | For iblock/HL **domain semantics** beyond migration helpers, also open `bitrix-iblocks` / `bitrix-highloadblock`. ## Method naming cheatsheet - **`save*`** — upsert to match exported/desired state (best default for schema). - **`add*IfNotExists`** — create once; will not update drifted fields. - **`*IfExists`** — safe get/delete when absence is OK. - Identify entities by **CODE / XML_ID / NAME**, not by numeric ID from another environment. ## Builders (`run`) Builders generate a migration (and often exchange files) from the current DB state. Prefer them for large iblock/HL/option exports instead of hand-writing arrays. ```bash # {migrate} = local/... or bitrix/.../tools/migrate.php — see rules/cli-config.md php "$MIGRATE" run IblockBuilder ``` Default builder keys (config `version_builders`): | Builder key | Use for | | --- | --- | | `BlankBuilder` | Empty `Version` stub | | `IblockBuilder` | Iblock structure | | `IblockPropertyBuilder` / `IblockPropertyDeleteBuilder` | Properties | | `IblockCategoryBuilder` | Sections | | `IblockElementsBuilder` | Elements (+ exchange) | | `IblockDeleteBuilder` | Delete iblock migration | | `HlblockBuilder` / `HlblockElementsBuilder` | HL structure / elements | | `UserTypeEntitiesBuilder` | UF entities | | `UserGroupBuilder` | Groups | | `AgentBuilder` | Agents | | `OptionBuilder` | Options | | `EventBuilder` | Mail events | | `FormBuilder` / `ForumBuilder` / `VoteBuilder` / `SubscribeBuilder` | Module entities | | `UserOptionsBuilder` | Admin UI options | | `LanguageBuilder` | Languages | | `OrderPropertiesBuilder` / `SaleDiscountBuilder` | Sale | | `MedialibElementsBuilder` | Media library | | `CacheCleanerBuilder` | Cache clean step | | `MarkerBuilder` / `TransferBuilder` | Tagging / transfer between configs | After a builder run: review the generated PHP, commit migration (+ exchange dir if present), then `up` on other environments. ## Examples in the module Read-only references under `{module}` (do not copy into product blindly): - `{module}/examples/*.php` - `{module}/templates/*.php` ## Extending helpers `HelperManager::registerHelper($name, $class)` registers a custom helper class extending `Sprint\Migration\Helper`. Use only when a project maintains a shared base migration layer; otherwise keep domain logic in services called from `up()`. -
writing.md 5.1 KB
# Writing Version migrations ## Skeleton ```php <?php namespace Sprint\Migration; class Version20260720120000 extends Version { protected $author = ''; protected $description = 'Short human summary of the change'; protected $moduleVersion = '5.13.0'; // module version that generated the file (informational) public function up() { $helper = $this->getHelperManager(); // apply changes } public function down() { $helper = $this->getHelperManager(); // reverse changes when safe/possible } } ``` Scaffold via CLI `add` or admin builder — then fill `up`/`down`. ## Contract of `up` / `down` | Return / behavior | Meaning | | --- | --- | | `void` / `true` / no return | Success (default) | | `false` | Failure — migration stays not installed | | Throw `HelperException` / `MigrationException` | Failure with message | | Throw `RestartException` (via `$this->restart*`) | Pause and resume (long jobs) | Use `$this->outSuccess()`, `$this->outError()`, `$this->outWarning()`, `$this->outProgress($msg, $val, $total)` for operator-visible logs. ## Prefer idempotent helpers Naming convention in helpers: | Pattern | Behavior | | --- | --- | | `saveX(...)` | Create or update to match given fields (preferred for schema) | | `addXIfNotExists(...)` | Create only if missing | | `deleteXIfExists(...)` | Delete only if present | | `getXIfExists(...)` | Fetch or throw / fail clearly | Example (iblock): ```php public function up() { $helper = $this->getHelperManager(); $helper->Iblock()->saveIblockType([ 'ID' => 'content', 'LANG' => [ 'ru' => [ 'NAME' => 'Контент', 'SECTION_NAME' => 'Разделы', 'ELEMENT_NAME' => 'Элементы', ], ], ]); $iblockId = $helper->Iblock()->saveIblock([ 'NAME' => 'Новости', 'CODE' => 'content_news', 'LID' => ['s1'], 'IBLOCK_TYPE_ID' => 'content', ]); $helper->Iblock()->saveProperty($iblockId, [ 'NAME' => 'Ссылка', 'CODE' => 'LINK', ]); } public function down() { $this->getHelperManager()->Iblock()->deleteIblockIfExists('content_news'); } ``` ## Dependencies between migrations ```php public function up() { $this->checkRequiredVersions([ 'Version20260101120000', OtherMigration::class, ]); // ... } ``` `$requiredVersions` property is **deprecated** — use `checkRequiredVersions()`. ## Restartable (batch) migrations For large loops, use restart helpers so CLI/admin can continue without timeout: ```php public function up() { $items = $this->loadItems(); // or from exchange $this->restartIterator('items', $items, function (array $row) { // process one row $this->outProgress('rows', /* current */, count($this->loadItems())); }); } ``` Also available: `restartOnce($name, $callback)`, `restartWhile($name, $callback)`. Storage of restart params is managed by the module between invocations. ## Exchange / files next to a version Large exported data (elements, files) lives under: `{exchange_dir}/{VersionName}_files/` Access via `$this->getExchangeManager()`. Prefer builders (`IblockElementsBuilder`, `HlblockElementsBuilder`, …) over hand-rolling exchange format. Do not commit secrets or huge binary dumps without an explicit project policy. ## Hand-written data migrations When helpers do not cover the entity (custom ORM tablet, business data): 1. `Loader::includeModule('vendor.module')` first; fail with `outError` + `return false` if missing. 2. Prefer D7 ORM / ServiceLocator services over classic API. 3. Check `Result::isSuccess()`; aggregate errors with `outError`. 4. Keep migrations **deterministic** and **re-runnable** where possible (match by business key / XML_ID / CODE, not by auto-increment ID). 5. Cast IDs and codes strictly (`(int)`, whitelist filters). ```php public function up() { if (!\Bitrix\Main\Loader::includeModule('vendor.module')) { $this->outError('Module vendor.module is not installed'); return false; } $result = \Vendor\Module\Entity\ItemTable::add([/* ... */]); if (!$result->isSuccess()) { $this->outError(implode('; ', $result->getErrorMessages())); return false; } $this->outSuccess('Item created'); } ``` Raw SQL: only when ORM/helpers cannot express the change — see `bitrix-database`. Escape via `SqlHelper`; wrap multi-step DDL/DML in a transaction when safe. ## `down()` policy - Schema created in `up` → delete/revert in `down` when practical. - One-way data fixes (external registry sync, irreversible transforms) → empty `down()` with a short comment why rollback is impossible. - Never invent destructive `down()` that drops production data “for symmetry” without an explicit requirement. ## What not to put in migrations - Secrets, tokens, `.env` values, private keys. - Hard-coded absolute host paths of a single developer machine. - Edits to `/bitrix/` core files. - Non-deterministic “random” seeds that break replay on another copy.
-
-
SKILL.md 3.9 KB
--- name: bitrix-sprint-migration description: >- Covers Bitrix module sprint.migration — Version migrations, HelperManager (Iblock/Hlblock/Option/Agent/…), builders (run), CLI migrate.php (add/ls/up/down/redo/mark), configs migrations.*.php, restartable batches, exchange dirs. Use when creating or applying DB/schema/content migrations, exporting iblock/HL/options via builders, or debugging migration state. Key terms — sprint.migration, Version, up/down, HelperManager, saveIblock, saveHlblock, migrate.php, version builders, migration_dir. --- # Bitrix sprint.migration Module **`sprint.migration`** (Composer: `andreyryabin/sprint.migration`) stores schema/content changes as PHP classes under VCS and applies them on each copy of the project via CLI or admin UI. Install location (either is valid; resolve before calling CLI): | Path | Typical when | | --- | --- | | `/local/modules/sprint.migration/` | Composer / marketplace into `local` | | `/bitrix/modules/sprint.migration/` | Marketplace / copy into kernel modules | Below, **`{module}`** means that resolved directory. Do **not** edit module source. Write only migration files and optional configs (usually under `php_interface/`). Progressive disclosure: open **only** the rule files that match the task. ## How to use 1. Confirm the module is installed (`Loader::includeModule('sprint.migration')`). 2. Identify the layer (CLI/config vs writing a Version vs helpers/builders). 3. Open the matching `rules/*.md` below. 4. Prefer helpers/`save*` APIs over raw Bitrix API when they cover the entity. 5. For domain ORM/data updates without builders — use D7/`Result` inside `up()`, still as a `Version` class. Official wiki: https://github.com/andreyryabin/sprint.migration/wiki ## Defaults (override via `migrations.*.php` / module options) | Item | Default | | --- | --- | | Migration dir | `{local\|bitrix}/php_interface/migrations` (`local` wins if present) | | Versions table | `sprint_migration_versions` | | Class prefix | `Version` + timestamp `YmdHis` (name must contain a valid timestamp) | | Extend class | `Sprint\Migration\Version` | | CLI entry | `php {module}/tools/migrate.php` | | Extra configs | `{local\|bitrix}/php_interface/migrations.<name>.php` → dir `migrations.<name>`, table `sprint_migration_<name>` | ## Choose a rule file ### When to read `rules/cli-config.md` Read when the task involves: - Running CLI (`add`, `ls`, `up`, `down`, `redo`, `mark`, `run`, `config`) - Naming versions / timestamps - Multiple configs (`--config`, `migrations.*.php`) - Admin UI vs console auth user ### When to read `rules/writing.md` Read when the task involves: - Authoring `Version` (`up` / `down`) - Idempotent `save*` vs `add*IfNotExists` - Output (`outSuccess` / `outError`), return `false` on failure - Dependencies (`checkRequiredVersions`) - Restartable long migrations - Exchange files / large data sets - Hand-written data migrations (ORM / SQL) ### When to read `rules/helpers-builders.md` Read when the task involves: - Choosing a Helper (`Iblock()`, `Hlblock()`, …) - Choosing a Builder (`run IblockBuilder`, …) - Export-from-admin → commit generated PHP ### When to read `rules/checklist.md` Read before finishing or reviewing a migration change: - Safety / anti-patterns - Apply / verify checklist ## Related skills | Need | Skill | | --- | --- | | Iblock domain model | `bitrix-iblocks` | | Highloadblock CRUD | `bitrix-highloadblock` | | Raw SQL / DDL outside helpers | `bitrix-database` | | Module install SQL (not sprint) | `bitrix-modules` | | Agents registration | `bitrix-background-jobs` | | Options / storage choice | `bitrix-storage` | ## Checklist - [ ] Opened only the rule file(s) needed for this task. - [ ] Migration files live under the configured `migration_dir` (not in the module). - [ ] Did not modify sprint.migration module source. - [ ] Applied `up` on a local/dev copy when verifying the change.
Comments (0)
Sign in to join the conversation.
Reviews (0)
No reviews yet.
No comments yet.