PHPackages                             illusiard/yii2-db-toolkit - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. illusiard/yii2-db-toolkit

ActiveYii2-extension[Database &amp; ORM](/categories/database)

illusiard/yii2-db-toolkit
=========================

Yii2 DB toolkit

v0.2.0(2mo ago)03BSD-3-ClausePHPPHP &gt;=8.1

Since Feb 15Pushed 2mo agoCompare

[ Source](https://github.com/Illusiard/yii2-db-toolkit)[ Packagist](https://packagist.org/packages/illusiard/yii2-db-toolkit)[ RSS](/packages/illusiard-yii2-db-toolkit/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (3)Versions (3)Used By (0)

illusiard/yii2-db-toolkit
=========================

[](#illusiardyii2-db-toolkit)

Yii2 DB toolkit — набор инфраструктурных утилит для работы с БД на уровне миграций и DDL.

Пакет даёт синтаксический и архитектурный сахар для создания таблиц, индексов и внешних ключей, а также небольшие вспомогательные инструменты для унификации миграций между PostgreSQL и MySQL. Использование позволяет просто заводить новые таблицы, получая единую стилистику, на которую можно опираться при дальнейшем проектировании.

What's included
---------------

[](#whats-included)

- `CreateTable` — базовый класс миграции для создания таблиц:

    - автоматические дефолтные колонки: `id`, `created_at`, `updated_at`, `is_active` (можно отключать через `false`)
    - декларативное описание индексов и внешних ключей
    - автоматическое создание индекса под каждый внешний ключ
    - `onDelete` / `onUpdate` для FK (с валидацией значений)
    - авто-создание FK-колонки при отсутствии в `getColumns()`
- `ForeignKeyDTO` — DTO для применения FK внутри `CreateTable`
- `BaseDictionaryCreateTableMigration` — базовая миграция “таблица-справочник”:

    - колонки: `code`, `name`, `description`
    - unique индекс на `code`
- `SchemaIntrospector` (read-only) — библиотечная интроспекция схемы БД:

    - DTO: `SchemaDTO`, `TableDTO`, `ColumnDTO`, `IndexDTO`, `ForeignKeyDTO`
    - сбор таблиц/PK/columns/indexes/foreignKeys/comments
    - поддержка SQLite (`PRAGMA`) и общая ветка для остальных драйверов
- Функции-утилиты:

    - генерация имён idx/fk
    - нормализация конфигов
    - дефолтные поля
    - (опционально) провайдеры/разделение логики по драйверу (PG/MySQL)

What's NOT included
-------------------

[](#whats-not-included)

- сущности / ActiveRecord
- meta-layer BES

Requirements
------------

[](#requirements)

- PHP &gt;= 8.1
- yiisoft/yii2 ^2.0.49

Installation
------------

[](#installation)

```
composer require illusiard/yii2-db-toolkit
```

Quick start
-----------

[](#quick-start)

### CreateTable

[](#createtable)

Создайте миграцию, унаследовавшись от `CreateTable`:

```
use illusiard\dbtoolkit\CreateTable;

final class m240101_000001_create_post_table extends CreateTable
{
    public function getTableName(): string
    {
        return 'post';
    }

    public function getColumns(): array
    {
        return [
            'title' => $this->string(255)->notNull()->comment('Заголовок'),
            'body' => $this->text()->null()->comment('Текст'),
        ];
    }

    public function getIndexes(): array
    {
        return [
            ['title'],
        ];
    }

    public function getForeignKeys(): array
    {
        return [
            'user_id' => ['user', 'id', 'onDelete' => 'RESTRICT', 'onUpdate' => 'CASCADE'],
        ];
    }
}
```

### Disabling default columns

[](#disabling-default-columns)

Любую дефолтную колонку можно отключить, вернув `false` по соответствующему ключу:

```
public function getColumns(): array
{
    return [
        'id' => false,
        'created_at' => false,
        'updated_at' => false,
        'is_active' => false,

        'code' => $this->string(64)->notNull()->comment('Код'),
    ];
}
```

### BaseDictionaryCreateTableMigration

[](#basedictionarycreatetablemigration)

Отдельно выделен класс для создания таблиц-словарей.

```
use illusiard\dbtoolkit\BaseDictionaryCreateTableMigration;

final class m240101_000002_create_country_dict extends BaseDictionaryCreateTableMigration
{
    public function getTableName(): string
    {
        return 'dict_country';
    }
}
```

### SchemaIntrospector (read-only)

[](#schemaintrospector-read-only)

Интроспекция работает с любым `yii\db\Connection`:

```
use illusiard\dbtoolkit\schema\SchemaIntrospector;

$introspector = new SchemaIntrospector($db);

$schema = $introspector->introspectSchema();
$table = $introspector->introspectTable('post');
```

Формат данных для endpoint-слоя:

- `SchemaDTO::toArray()` -&gt; `{tables:[...], driver, serverVersion?}`
- `TableDTO::toDetailsArray()` -&gt; `table`, `primaryKey`, `columns`, `indexes`, `foreignKeys`

### Schema tooling

[](#schema-tooling)

Для схемного синка доступны четыре шага:

1. `SchemaIntrospector`: `Connection -> SchemaDTO` (текущая схема)
2. `SchemaParser`: `array -> SchemaDTO` (желаемая схема)
3. `SchemaDiffService`: `current + desired -> SchemaDiffResult` (actions в безопасном порядке)
4. `MigrationGeneratorService`: `SchemaDiffResult -> MigrationCodeResult` (php-код миграции)

Минимальный пример desired schema:

```
$desired = [
    'tables' => [
        [
            'name' => 'post',
            'columns' => [
                ['name' => 'id', 'type' => 'integer', 'allowNull' => false],
                ['name' => 'status', 'type' => 'string(32)', 'defaultValue' => 'draft'],
            ],
            'indexes' => [
                ['columns' => ['status'], 'unique' => false],
            ],
            'foreignKeys' => [
                [
                    'columns' => 'tenant_id,author_id',
                    'refTable' => 'author',
                    'refColumns' => ['tenant_id', 'id'],
                    'onDelete' => 'CASCADE',
                    'onUpdate' => 'NO ACTION',
                ],
            ],
        ],
    ],
];
```

Ошибки endpoint-слоя (например в BES) остаются на стороне контроллера:

- несуществующая таблица: `404 {error:{type:"not_found",table:"..."}}`
- невалидное имя таблицы: `400 {error:{type:"bad_request",...}}`

Tests
-----

[](#tests)

Есть unit-тесты (SQLite in-memory) и интеграционные тесты (реальные БД в Docker).

### Launching the database

[](#launching-the-database)

```
docker compose up -d
```

### Environment variables

[](#environment-variables)

Пример `.env` (используется тестами):

- `DB_DRIVER=pgsql` или `DB_DRIVER=mysql`
- `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER`, `DB_PASS`

### Running tests

[](#running-tests)

Unit (SQLite in-memory):

```
vendor/bin/phpunit tests/Unit
```

PostgreSQL:

```
export $(cat .env | xargs)
DB_DRIVER=pgsql vendor/bin/phpunit
```

MySQL:

```
export $(cat .env | xargs)
DB_DRIVER=mysql vendor/bin/phpunit
```

LICENCE
-------

[](#licence)

BSD-3-Clause

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance83

Actively maintained with recent releases

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity34

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~6 days

Total

2

Last Release

86d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/514a2bdbd1dfc61512460d4026da34187fb5e20e69be3ada0a8594b593dd269a?d=identicon)[Illusiard](/maintainers/Illusiard)

---

Top Contributors

[![Illusiard](https://avatars.githubusercontent.com/u/27963611?v=4)](https://github.com/Illusiard "Illusiard (10 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/illusiard-yii2-db-toolkit/health.svg)

```
[![Health](https://phpackages.com/badges/illusiard-yii2-db-toolkit/health.svg)](https://phpackages.com/packages/illusiard-yii2-db-toolkit)
```

###  Alternatives

[yii2tech/illuminate

Yii2 to Laravel Migration Package

11315.1k](/packages/yii2tech-illuminate)[mootensai/yii2-relation-trait

Yii 2 Models load with relation, &amp; transaction save with relation

47220.3k9](/packages/mootensai-yii2-relation-trait)[nhkey/yii2-activerecord-history

Storage history of changes to ActiveRecord

46143.4k1](/packages/nhkey-yii2-activerecord-history)[dmstr/yii2-db

Database extensions

19618.8k6](/packages/dmstr-yii2-db)[urbanindo/yii2-dynamodb

DynamoDB extensions for Yii2

1471.4k](/packages/urbanindo-yii2-dynamodb)[spanjeta/yii2-backup

Database Backup and Restore functionality

285.0k1](/packages/spanjeta-yii2-backup)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
