Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions .github/workflows/php.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,39 @@ 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
tools: composer:v2
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
Expand Down
16 changes: 11 additions & 5 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

136 changes: 115 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,115 @@
<p align="center"><a href="https://www.localzet.com" target="_blank">
<img src="https://static.zorin.space/media/logos/LocalzetGroup.png" width="400">
</a></p>

<p align="center">
<a href="https://packagist.org/packages/triangle/database">
<img src="https://img.shields.io/packagist/dt/triangle/database?label=%D0%A1%D0%BA%D0%B0%D1%87%D0%B8%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F" alt="Скачивания">
</a>
<a href="https://github.com/Triangle-org/Database">
<img src="https://img.shields.io/github/commit-activity/t/Triangle-org/Database?label=%D0%9A%D0%BE%D0%BC%D0%BC%D0%B8%D1%82%D1%8B" alt="Коммиты">
</a>
<a href="https://packagist.org/packages/triangle/database">
<img src="https://img.shields.io/packagist/v/triangle/database?label=%D0%92%D0%B5%D1%80%D1%81%D0%B8%D1%8F" alt="Версия">
</a>
<a href="https://packagist.org/packages/triangle/database">
<img src="https://img.shields.io/packagist/dependency-v/triangle/database/php?label=PHP" alt="Версия PHP">
</a>
<a href="https://github.com/Triangle-org/Database">
<img src="https://img.shields.io/github/license/Triangle-org/Database?label=%D0%9B%D0%B8%D1%86%D0%B5%D0%BD%D0%B7%D0%B8%D1%8F" alt="Лицензия">
</a>
</p>
# 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
<?php

use Triangle\Database\Model;

final class User extends Model
{
protected $table = 'users';

protected $fillable = ['name'];

public $timestamps = false;
}
```

Then use the standard Illuminate APIs:

```php
$user = User::query()->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.
115 changes: 115 additions & 0 deletions README.ru.md
Original file line number Diff line number Diff line change
@@ -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
<?php

use Triangle\Database\Model;

final class User extends Model
{
protected $table = 'users';

protected $fillable = ['name'];

public $timestamps = false;
}
```

Затем используйте стандартный API Illuminate:

```php
$user = User::query()->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.
19 changes: 8 additions & 11 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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\\": "",
Expand All @@ -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"
Expand Down
3 changes: 2 additions & 1 deletion src/Bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
* @link https://github.com/Triangle-org/Database
*
* @author Ivan Zorin <creator@localzet.com>
* @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
Expand Down
8 changes: 8 additions & 0 deletions src/Config/database.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
<?php

/**
* @package Triangle Database Component
* @link https://github.com/Triangle-org/Database
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license AGPL-3.0-or-later
*/

return [
'default' => env('DB_CONNECTION', 'mysql'),
'connections' => [
Expand Down
3 changes: 2 additions & 1 deletion src/Install.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
* @link https://github.com/Triangle-org/Database
*
* @author Ivan Zorin <creator@localzet.com>
* @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
Expand Down
Loading