diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml index b0477a7..3d2177b 100644 --- a/.github/workflows/php.yml +++ b/.github/workflows/php.yml @@ -12,18 +12,19 @@ permissions: jobs: verify: - name: PHP ${{ matrix.php }} + name: PHP ${{ matrix.php }} / dependencies ${{ matrix.dependencies }} runs-on: ubuntu-24.04 strategy: fail-fast: false matrix: php: ['8.2', '8.5'] + dependencies: ['latest', 'lowest'] steps: - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Set up PHP - uses: shivammathur/setup-php@v2 + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0 with: php-version: ${{ matrix.php }} extensions: curl, intl, mbstring, pdo_sqlite @@ -31,11 +32,19 @@ jobs: github-token: ${{ secrets.GITHUB_TOKEN }} coverage: none - - name: Validate Composer manifest and lock - run: composer validate --no-check-publish --no-interaction + - name: Validate Composer manifest + run: composer validate --strict --no-check-publish --no-interaction - - name: Install locked dependencies - run: composer install --prefer-dist --no-interaction --no-progress --no-scripts + - name: Install dependencies + run: | + if [[ "${{ matrix.dependencies }}" == "lowest" ]]; then + composer update --prefer-lowest --prefer-stable --prefer-dist --no-interaction --no-progress --no-scripts + else + composer update --prefer-dist --no-interaction --no-progress --no-scripts + fi + + - name: Audit dependencies + run: composer audit --no-interaction - name: Check PHP syntax run: find . -path './vendor' -prune -o -path './.git' -prune -o -name '*.php' -type f -print0 | xargs -0 -n1 php -l diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b9ab6b..99f6040 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,10 +26,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 --- -## [Unreleased] +## [2.0.0] - Unreleased -### Planned -- Performance optimizations -- Connection pooling improvements -- Advanced query logging +### Changed +- Require Triangle Engine 9 and Localzet Server 7. +- Upgrade Illuminate Database, Events, and Pagination to 12.x. +- Require Symfony VarDumper 7.4 and PHP 8.2 or newer. + +### Removed +- Drop compatibility with Triangle Engine 8 and earlier. + +### Tests +- Add a SQLite integration check for Engine 9 bootstrap and Eloquent model reads/writes. diff --git a/README.md b/README.md index 0d25f52..ce4d94e 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,115 @@ -

- -

- -

- - Скачивания - - - Коммиты - - - Версия - - - Версия PHP - - - Лицензия - -

+# Triangle Database + +Triangle Database connects [Illuminate Database](https://laravel.com/docs/database) to applications running on Triangle Engine 9 and Localzet Server 7. It boots Eloquent and the query builder, registers database connections from the Engine configuration, and wires pagination to the current request. + +This branch prepares the next major release, `2.x`. The published `1.x` line targets older Engine versions. Until `2.x` is released, install this branch only when you intend to test the Engine 9 migration. + +## Compatibility + +| Component | Supported version | +| --- | --- | +| PHP | 8.2 or newer | +| Triangle Engine | 9.x | +| Localzet Server | 7.x, provided by Triangle Engine | +| Illuminate Database, Events, Pagination | 12.x | +| Symfony VarDumper | 7.4.x | + +Engine 8 and earlier are not supported by this branch. A project migrating from the published 1.x line should upgrade its Triangle components together and review its dependency lock before deployment. + +## Install + +After the 2.x release is published: + +```sh +composer require triangle/database:^2.0 +``` + +During development, use the repository branch or a local Composer path repository. Do not assume the Packagist 1.x release contains Engine 9 support. + +## Configure a connection + +Triangle Engine loads `config/database.php` during application startup. The package includes a configuration template with SQLite, MySQL, PostgreSQL, SQL Server, and MongoDB examples. Keep credentials in environment variables and enable only the drivers and PHP extensions used by the application. + +For example, select a MySQL connection in `.env`: + +```dotenv +DB_CONNECTION=mysql +DB_HOST=127.0.0.1 +DB_PORT=3306 +DB_DATABASE=app +DB_USERNAME=app +DB_PASSWORD=change-me +``` + +`DB_PASSWORD` is a placeholder; provide the real value through the deployment environment or a secret store. Do not commit credentials. + +The package registers the selected default connection and each configured named connection. `persistent` defaults to `true`. When Engine starts the package with a Server instance, it schedules a MySQL keepalive query every 55 seconds. Set `persistent` to `false` when that behavior is not wanted. The manager and its connections are process-local; multiple Server workers each hold their own database manager. + +## Use Eloquent and the query builder + +Extend the package model to define an application model: + +```php +create(['name' => 'Ada']); +$found = User::query()->where('id', $user->id)->first(); + +$rows = \Triangle\Database\Manager::table('users') + ->where('name', 'Ada') + ->get(); +``` + +The package's `Model` extends Eloquent's model. `Manager` extends Illuminate's Capsule manager, so its connection, schema, and query-builder entry points follow Illuminate's APIs. For raw SQL, pass values through bindings; do not interpolate user input into a query string. + +## Pagination and application startup + +Engine loads `Triangle\Database\Bootstrap` through the component lifecycle. The bootstrap is a no-op when no database connections are configured. Otherwise it configures Capsule, boots Eloquent, and sets page, path, query-string, and cursor resolvers from the current Triangle request. + +Use Illuminate's `paginate`, `simplePaginate`, or `cursorPaginate` methods from the request handler. Pagination resolvers are process-wide callbacks, so call them while handling a request rather than retaining request data in long-lived application state. + +The package exposes Illuminate's schema builder but does not provide a separate migration CLI or run schema changes automatically. Manage migrations through the application's chosen deployment process. + +## Drivers and extensions + +Database driver availability depends on the installed PHP extensions and PDO drivers. SQLite is used by the package integration test. MySQL, PostgreSQL, and SQL Server require their corresponding PDO extensions. MongoDB is optional and uses an installed compatible MongoDB integration when available; MongoDB support is not covered by the local SQLite test. + +## Verify locally + +```sh +composer install --no-interaction +composer validate --strict --no-check-publish +composer test +``` + +The integration test boots Engine 9 against an in-memory SQLite database, creates a table, and verifies an Eloquent insert and read. GitHub Actions runs the checks on PHP 8.2 and 8.5 with both the lowest supported and latest allowed dependency versions. The workflow resolves dependencies from `composer.json` because this library does not commit a lock file. It does not test external database services or production credentials. + +## Security and operations + +- Use least-privilege database accounts and restrict database network access to application hosts. +- Keep connection secrets out of source control, logs, and exception responses. +- Prefer parameterized query-builder and Eloquent APIs. Bind every value passed to raw SQL. +- Set connection timeouts and TLS options in the driver configuration required by the deployment. +- Treat the 55-second MySQL keepalive as a connection-liveness mechanism, not as a pool, retry policy, or availability guarantee. +- Back up and migrate schemas through the deployment process; this component does not perform automatic migrations. + +## License + +AGPL-3.0-or-later. See [`LICENSE`](LICENSE). + +Copyright © 2016-2026 [Localzet Group](https://www.localzet.com/). All rights reserved. diff --git a/README.ru.md b/README.ru.md new file mode 100644 index 0000000..9831ce6 --- /dev/null +++ b/README.ru.md @@ -0,0 +1,115 @@ +# Triangle Database + +Triangle Database подключает [Illuminate Database](https://laravel.com/docs/database) к приложениям на Triangle Engine 9 и Localzet Server 7. Компонент запускает Eloquent и query builder, регистрирует соединения из конфигурации Engine и связывает пагинацию с текущим запросом. + +Эта ветка готовит следующую основную версию `2.x`. Опубликованная линия `1.x` рассчитана на более старые версии Engine. До выпуска `2.x` устанавливайте эту ветку только для проверки миграции на Engine 9. + +## Совместимость + +| Компонент | Поддерживаемая версия | +| --- | --- | +| PHP | 8.2 или новее | +| Triangle Engine | 9.x | +| Localzet Server | 7.x, устанавливается через Triangle Engine | +| Illuminate Database, Events, Pagination | 12.x | +| Symfony VarDumper | 7.4.x | + +Engine 8 и более ранние версии эта ветка не поддерживает. При переходе с опубликованной линии 1.x обновляйте компоненты Triangle согласованно и проверяйте lock-файл до выкладки. + +## Установка + +После публикации версии 2.x: + +```sh +composer require triangle/database:^2.0 +``` + +Во время разработки подключайте ветку репозитория или локальный Composer path repository. Не считайте, что опубликованный пакет 1.x уже поддерживает Engine 9. + +## Настройка соединения + +Triangle Engine загружает `config/database.php` при запуске приложения. В комплекте есть шаблон конфигурации с примерами для SQLite, MySQL, PostgreSQL, SQL Server и MongoDB. Храните реквизиты подключения в переменных окружения и включайте только используемые драйверы и PHP-расширения. + +Например, выберите MySQL в `.env`: + +```dotenv +DB_CONNECTION=mysql +DB_HOST=127.0.0.1 +DB_PORT=3306 +DB_DATABASE=app +DB_USERNAME=app +DB_PASSWORD=change-me +``` + +`DB_PASSWORD` — пример. Передавайте реальное значение через окружение развёртывания или хранилище секретов. Не коммитьте реквизиты подключения. + +Компонент регистрирует выбранное соединение по умолчанию и все именованные соединения из конфигурации. По умолчанию `persistent` равно `true`. Если Engine запускает компонент с экземпляром Server, он добавляет MySQL keepalive-запрос каждые 55 секунд. Установите `persistent` в `false`, если это поведение не требуется. Менеджер и его соединения локальны для процесса: у каждого worker свой менеджер базы данных. + +## Eloquent и query builder + +Создайте модель приложения на основе модели компонента: + +```php +create(['name' => 'Ada']); +$found = User::query()->where('id', $user->id)->first(); + +$rows = \Triangle\Database\Manager::table('users') + ->where('name', 'Ada') + ->get(); +``` + +`Model` компонента наследует модель Eloquent. `Manager` наследует Capsule Manager, поэтому методы соединений, схем и query builder соответствуют API Illuminate. Для raw SQL передавайте значения отдельными binding-параметрами; не вставляйте пользовательский ввод в SQL-строку. + +## Пагинация и запуск приложения + +Engine загружает `Triangle\Database\Bootstrap` в рамках жизненного цикла компонента. Bootstrap ничего не делает, если соединения не настроены. В противном случае он настраивает Capsule, запускает Eloquent и задаёт резолверы страницы, пути, query string и cursor на основе текущего запроса Triangle. + +В обработчике запроса используйте методы Illuminate `paginate`, `simplePaginate` или `cursorPaginate`. Резолверы пагинации — callback-и на весь процесс, поэтому обращайтесь к ним при обработке запроса и не сохраняйте данные запроса в долгоживущем состоянии приложения. + +Компонент предоставляет schema builder Illuminate, но не добавляет отдельную CLI-команду миграций и не меняет схему автоматически. Выполняйте миграции в выбранном процессе развёртывания. + +## Драйверы и расширения + +Доступность драйверов зависит от установленных PHP-расширений и PDO-драйверов. Интеграционный тест компонента использует SQLite в памяти. Для MySQL, PostgreSQL и SQL Server нужны соответствующие PDO-расширения. MongoDB подключается через совместимую установленную интеграцию, если она доступна; локальный тест SQLite не проверяет MongoDB. + +## Локальная проверка + +```sh +composer install --no-interaction +composer validate --strict --no-check-publish +composer test +``` + +Интеграционный тест запускает Engine 9 с SQLite в памяти, создаёт таблицу и проверяет запись и чтение через Eloquent. GitHub Actions проверяет PHP 8.2 и 8.5 на минимальных поддерживаемых и последних допустимых зависимостях. Workflow разрешает версии из `composer.json`, поскольку библиотека не хранит lock-файл. Внешние базы данных и production-реквизиты в CI не используются. + +## Безопасность и эксплуатация + +- Используйте отдельные учётные записи БД с минимально необходимыми правами и ограничивайте сетевой доступ к базе. +- Не храните секреты подключения в исходниках, логах и ответах с исключениями. +- Отдавайте предпочтение Eloquent и query builder с параметрами. Для raw SQL связывайте каждое значение через bindings. +- Настраивайте таймауты соединения и TLS-параметры согласно требованиям драйвера и окружения. +- MySQL keepalive с интервалом 55 секунд проверяет жизнеспособность соединения, но не является пулом, политикой повторов или гарантией доступности. +- Резервное копирование и изменение схемы выполняйте в процессе развёртывания; компонент не запускает миграции автоматически. + +## Лицензия + +AGPL-3.0-or-later. Текст лицензии находится в [`LICENSE`](LICENSE). + +Copyright © 2016-2026 [Localzet Group](https://www.localzet.com/). All rights reserved. diff --git a/composer.json b/composer.json index 9e38eaa..70db400 100644 --- a/composer.json +++ b/composer.json @@ -20,6 +20,9 @@ "email": "support@localzet.com", "source": "https://github.com/Triangle-org/Database" }, + "scripts": { + "test": "php tests/bootstrap.php" + }, "autoload": { "psr-4": { "Triangle\\": "", @@ -28,17 +31,11 @@ }, "require": { "php": "^8.2", - "triangle/engine": "^8.1", - "illuminate/database": "^11.19", - "illuminate/pagination": "^11.19", - "illuminate/events": "^11.19", - "symfony/var-dumper": "^7.1" - }, - "conflict": { - "illuminate/database": ">=12.0", - "illuminate/pagination": ">=12.0", - "illuminate/events": ">=12.0", - "symfony/var-dumper": ">=8.0" + "triangle/engine": "^9.0", + "illuminate/database": "^12.0", + "illuminate/pagination": "^12.0", + "illuminate/events": "^12.0", + "symfony/var-dumper": "^7.4" }, "suggest": { "mongodb/laravel-mongodb": "For MongoDB Driver" diff --git a/src/Bootstrap.php b/src/Bootstrap.php index 0c6db6c..9e9de7d 100644 --- a/src/Bootstrap.php +++ b/src/Bootstrap.php @@ -5,7 +5,8 @@ * @link https://github.com/Triangle-org/Database * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2024 Triangle Framework Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 * * This program is free software: you can redistribute it and/or modify diff --git a/src/Config/database.php b/src/Config/database.php index 589dd06..1ebc6d3 100644 --- a/src/Config/database.php +++ b/src/Config/database.php @@ -1,5 +1,13 @@ + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * @license AGPL-3.0-or-later + */ + return [ 'default' => env('DB_CONNECTION', 'mysql'), 'connections' => [ diff --git a/src/Install.php b/src/Install.php index 6dd9990..11426b1 100644 --- a/src/Install.php +++ b/src/Install.php @@ -5,7 +5,8 @@ * @link https://github.com/Triangle-org/Database * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2024 Triangle Framework Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 * * This program is free software: you can redistribute it and/or modify diff --git a/src/Manager.php b/src/Manager.php index b150dcd..2f56706 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -5,7 +5,8 @@ * @link https://github.com/Triangle-org/Database * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2024 Triangle Framework Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 * * This program is free software: you can redistribute it and/or modify diff --git a/src/Model.php b/src/Model.php index 3e65b96..5b4bd84 100644 --- a/src/Model.php +++ b/src/Model.php @@ -5,7 +5,8 @@ * @link https://github.com/Triangle-org/Database * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2024 Triangle Framework Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 * * This program is free software: you can redistribute it and/or modify diff --git a/tests/bootstrap.php b/tests/bootstrap.php new file mode 100644 index 0000000..a5843b7 --- /dev/null +++ b/tests/bootstrap.php @@ -0,0 +1,67 @@ + + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * @license AGPL-3.0-or-later + */ + +require dirname(__DIR__) . '/vendor/autoload.php'; + +use Illuminate\Container\Container as IlluminateContainer; +use Illuminate\Database\Schema\Blueprint; +use Triangle\Database\Bootstrap; +use Triangle\Database\Manager; +use Triangle\Database\Model; +use Triangle\Engine\Config; + +function expect(bool $condition, string $message): void +{ + if (!$condition) { + throw new RuntimeException($message); + } +} + +$container = new IlluminateContainer(); +IlluminateContainer::setInstance($container); + +Config::clear(); +Config::set([ + 'container' => $container, + 'database' => [ + 'default' => 'sqlite', + 'persistent' => false, + 'connections' => [ + 'sqlite' => [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + ], + ], + ], +]); + +Bootstrap::start(); + +Manager::schema()->create('entries', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('name'); +}); + +$model = new class extends Model { + protected $table = 'entries'; + + protected $fillable = ['name']; + + public $timestamps = false; +}; + +$model->newQuery()->create(['name' => 'Engine 9']); +$entry = $model->newQuery()->first(); + +expect($entry !== null, 'The SQLite row was not loaded.'); +expect($entry->name === 'Engine 9', 'The model returned an unexpected value.'); + +echo "ENGINE9_SQLITE_BOOTSTRAP=ok\n";