PHPackages                             codemonster-ru/database - 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. codemonster-ru/database

ActiveLibrary[Database &amp; ORM](/categories/database)

codemonster-ru/database
=======================

Lightweight, framework-agnostic database layer with PDO connections, fluent Query Builder, Schema Builder, and full migration system.

v2.0.0(4mo ago)0811MITPHPPHP &gt;=8.2CI passing

Since Dec 7Pushed 4mo agoCompare

[ Source](https://github.com/codemonster-ru/database)[ Packagist](https://packagist.org/packages/codemonster-ru/database)[ Docs](https://github.com/codemonster-ru/database)[ RSS](/packages/codemonster-ru-database/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (9)Dependencies (1)Versions (10)Used By (1)

codemonster-ru/database
=======================

[](#codemonster-rudatabase)

[![Latest Version on Packagist](https://camo.githubusercontent.com/4baec3d7303e17f3bc7191880f62aea5acee51b211146e4e34c012dd0017b972/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636f64656d6f6e737465722d72752f64617461626173652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/codemonster-ru/database)[![Total Downloads](https://camo.githubusercontent.com/e47896b5591a1643ce23051f450e13cfff04539d443745783b43004e3731f4a5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f636f64656d6f6e737465722d72752f64617461626173652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/codemonster-ru/database)[![License](https://camo.githubusercontent.com/e1b9cee2ee32da9e5aa0bd30052c217bcd79bc95832b532ea9088ef03a75c970/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f636f64656d6f6e737465722d72752f64617461626173652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/codemonster-ru/database)[![Tests](https://github.com/codemonster-ru/database/actions/workflows/tests.yml/badge.svg)](https://github.com/codemonster-ru/database/actions/workflows/tests.yml)

A lightweight, framework-agnostic database layer for PHP.
Part of the Codemonster ecosystem — but works fully standalone.

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

[](#installation)

```
composer require codemonster-ru/database
```

Usage
-----

[](#usage)

### 1. Database Manager

[](#1-database-manager)

```
use Codemonster\Database\DatabaseManager;

$manager = new DatabaseManager([
    'default' => 'mysql', // name of the default connection
    'connections' => [
        'mysql' => [
            'driver'   => 'mysql',
            'host'     => '127.0.0.1',
            'port'     => 3306,
            'database' => 'test',
            'username' => 'root',
            'password' => '',
            'charset'  => 'utf8mb4',
        ],
    ],
]);

$db = $manager->connection(); // default connection
```

You can define multiple connections and select them by name:

```
$manager = new DatabaseManager([
    'default' => 'mysql',
    'connections' => [
        'mysql' => [
            'driver'   => 'mysql',
            'host'     => '127.0.0.1',
            'port'     => 3306,
            'database' => 'app',
            'username' => 'root',
            'password' => '',
        ],
        'sqlite' => [
            'driver'   => 'sqlite',
            'database' => __DIR__ . '/database.sqlite',
        ],
    ],
]);

$mysql  = $manager->connection();          // default (mysql)
$sqlite = $manager->connection('sqlite');  // explicit connection
```

- For **MySQL/MariaDB** use `driver => 'mysql'`.
- For **SQLite** use `driver => 'sqlite'` and only `database` is required (file path or `:memory:`).
- Other PDO drivers can be wired via `driver` + DSN-compatible options; the query layer is driver-agnostic, while the schema builder is primarily tuned for MySQL-like syntax and SQLite.

### 2. Query Builder

[](#2-query-builder)

#### SELECT

[](#select)

```
$users = $db->table('users')
    ->select('id', 'name', 'email')
    ->where('active', 1)
    ->orderBy('created_at', 'desc')
    ->limit(10)
    ->get();
```

#### SELECT with aliases

[](#select-with-aliases)

```
$rows = $db->table('users')
    ->select('users.name label', 'COUNT(*) total')
    ->groupBy('users.name')
    ->get();
```

#### INSERT

[](#insert)

```
$db->table('users')->insert([
    'name'  => 'Vasya',
    'email' => 'test@example.com',
]);

$id = $db->table('ideas')->insertGetId([
    'title' => 'New idea',
]);
```

#### UPDATE

[](#update)

```
$db->table('users')
    ->where('id', 5)
    ->update([
        'active'     => 0,
        'updated_at' => date('Y-m-d H:i:s'),
    ]);
```

#### DELETE

[](#delete)

```
$db->table('sessions')
    ->where('user_id', 10)
    ->delete();
```

#### Debug SQL

[](#debug-sql)

```
[$sql, $bindings] = $db->table('users')
    ->where('active', 1)
    ->toSql();

// $sql      = 'SELECT * FROM `users` WHERE `active` = ?'
// $bindings = [1]
```

#### Raw expressions

[](#raw-expressions)

```
$db->table('users')
    ->selectRaw('COUNT(*) as total')
    ->whereRaw('JSON_VALID(metadata)')
    ->orderByRaw('FIELD(status, "new", "approved", "archived")')
    ->get();
```

#### Join support

[](#join-support)

```
$db->table('orders')
    ->join('users', 'users.id', '=', 'orders.user_id')
    ->leftJoin('payments', function ($join) {
        $join->on('payments.order_id', '=', 'orders.id')
             ->where('payments.status', 'paid');
    })
    ->get();
```

#### Group By / Having

[](#group-by--having)

```
$db->table('orders')
    ->selectRaw('status, COUNT(*) as total')
    ->groupBy('status')
    ->having('total', '>', 10)
    ->get();
```

#### Aggregates

[](#aggregates)

```
$count = $db->table('users')->count();
$sum   = $db->table('orders')->sum('amount');
$avg   = $db->table('ratings')->avg('score');
$min   = $db->table('logs')->min('id');
$max   = $db->table('visits')->max('duration');
```

#### Exists

[](#exists)

```
$exists = $db->table('users')
    ->where('email', 'test@example.com')
    ->exists();
```

#### Value / Pluck

[](#value--pluck)

```
$email = $db->table('users')
    ->where('id', 1)
    ->value('email');

$names = $db->table('users')->pluck('name');
$pairs = $db->table('users')->pluck('email', 'id'); // [id => email]

// Aliases are supported:
// $db->table('users')->pluck('users.name label', 'users.id key');
// $db->table('users')->value('COUNT(*) total');
```

#### Value / Pluck with aliases

[](#value--pluck-with-aliases)

```
$pairs = $db->table('users')
    ->pluck('users.name label', 'users.id key'); // [id => name]

$total = $db->table('users')->value('COUNT(*) total');
```

#### Pagination

[](#pagination)

```
$currentPage = 1;

$page = $db->table('posts')->simplePaginate(20, $currentPage);

// $page = [
//     'data'        => [...],
//     'per_page'    => 20,
//     'current_page'=> 1,
//     'next_page'   => 2,
//     'prev_page'   => null,
// ];
```

#### Empty whereIn / whereNotIn

[](#empty-wherein--wherenotin)

```
$db->table('users')
    ->setEmptyWhereInBehavior(\Codemonster\Database\Query\QueryBuilder::EMPTY_CONDITION_EXCEPTION)
    ->whereIn('id', []);
```

Available behaviors:

- `EMPTY_CONDITION_NONE` (default for `whereIn`) -&gt; executes `0 = 1`
- `EMPTY_CONDITION_ALL` (default for `whereNotIn`) -&gt; executes `1 = 1`
- `EMPTY_CONDITION_EXCEPTION` -&gt; throws `InvalidArgumentException`

You can override `whereNotIn` separately:

```
$db->table('users')
    ->setEmptyWhereNotInBehavior(\Codemonster\Database\Query\QueryBuilder::EMPTY_CONDITION_NONE)
    ->whereNotIn('id', []);
```

### 3. Transactions

[](#3-transactions)

```
$db->transaction(function ($db) {
    $db->table('users')->insert([
        'name'  => 'New user',
        'email' => 'user@example.com',
    ]);

    $db->table('logs')->insert([
        'message' => 'User created',
    ]);
});
```

### 4. Global Helpers (with `codemonster-ru/support`)

[](#4-global-helpers-with-codemonster-rusupport)

If you also install [`codemonster-ru/support`](https://packagist.org/packages/codemonster-ru/support)and register bindings in your container, you can use global helpers:

```
db();                 // returns default ConnectionInterface
db('sqlite');         // specific connection
schema();             // schema builder for default connection
transaction(fn() =>   // convenience wrapper
    db()->table('logs')->insert(['message' => 'ok'])
);
```

Helpers are thin wrappers around `DatabaseManager` and the connection’s `schema()` / `transaction()` methods.

Schema Builder
--------------

[](#schema-builder)

The package includes a lightweight schema builder.

> **Note:** The schema grammar is focused on MySQL/MariaDB and SQLite.
> For other PDO drivers, the query builder will work, but schema operations may not be fully supported.

### Creating a table

[](#creating-a-table)

```
use Codemonster\Database\Schema\Blueprint;

// You can also use Schema::forConnection($db) if you need a schema instance directly.
$db->schema()->create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->boolean('active')->default(1);
    $table->timestamps();
});
```

### Modifying a table

[](#modifying-a-table)

```
$db->schema()->table('users', function (Blueprint $table) {
    $table->string('avatar')->nullable();
    $table->integer('age')->default(0);
});
```

### SQLite notes

[](#sqlite-notes)

- SQLite supports `ALTER TABLE` only for a subset of operations; some drop operations are ignored.
- Foreign keys are emitted inline during `CREATE TABLE`.

### Dropping a table

[](#dropping-a-table)

```
$db->schema()->drop('users');

// or:
$db->schema()->dropIfExists('users');
```

Supported Column Types
----------------------

[](#supported-column-types)

- Integers: `id`, `integer`, `bigInteger`, `mediumInteger`, `smallInteger`, `tinyInteger`
- Floats: `decimal`, `double`, `float`
- Text: `string`, `char`, `text`, `mediumText`, `longText`
- Boolean: `boolean`
- JSON: `json`
- Dates &amp; time: `date`, `datetime`, `timestamp`, `time`, `year`
- UUID: `uuid`
- Indexes: `index`, `unique`, `primary`
- Foreign keys with `foreign()` / `references()` / `on()` and `onDelete()` / `onUpdate()` helpers

Migrations
----------

[](#migrations)

The package includes a migration system (designed to be used via the CLI).

- `migrate`
- `migrate:rollback`
- `migrate:status`
- `make:migration`
- `seed`
- `make:seed`

### Example migration

[](#example-migration)

```
use Codemonster\Database\Migrations\Migration;
use Codemonster\Database\Schema\Blueprint;

return new class extends Migration {
    public function up(): void
    {
        schema()->create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
        });
    }

    public function down(): void
    {
        schema()->drop('posts');
    }
};
```

Seeders
-------

[](#seeders)

The package includes a lightweight seeding system (via the CLI).

### Example seeder

[](#example-seeder)

```
use Codemonster\Database\Seeders\Seeder;

return new class extends Seeder {
    public function run(): void
    {
        db()->table('users')->insert([
            'name' => 'Admin',
            'email' => 'admin@example.com',
        ]);
    }
};
```

ORM (ActiveRecord / Eloquent‑style)
-----------------------------------

[](#orm-activerecord--eloquentstyle)

**Since 1.3.0**, the package includes a complete ORM layer:

- `Model`
- `ModelQuery`
- `ModelCollection`
- Lazy &amp; eager loading
- `$fillable`, `$guarded`, `$hidden`
- Attribute casting (`int`, `json`, `datetime`, etc.)
- `created_at` / `updated_at`
- `SoftDeletes`

### Example model

[](#example-model)

```
use Codemonster\Database\ORM\Model;

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

    protected array $fillable = ['name', 'email', 'password'];

    protected array $hidden = ['password'];

    protected array $casts = [
        'created_at' => 'datetime',
    ];
}
```

### Fetching models

[](#fetching-models)

```
$user = User::find(1);

$active = User::query()
    ->where('active', 1)
    ->orderBy('id')
    ->get();
```

### Creating / updating / deleting

[](#creating--updating--deleting)

```
User::create([
    'name' => 'John',
    'email' => 'john@example.com',
]);

$user->email = 'new@example.com';
$user->save();

$user->delete();
```

Relationships
-------------

[](#relationships)

Available relations:

- `HasOne`
- `HasMany`
- `BelongsTo`
- `BelongsToMany`

### Example

[](#example)

```
class User extends Model {
    public function posts() {
        return $this->hasMany(Post::class);
    }
}

class Post extends Model {
    public function author() {
        return $this->belongsTo(User::class, 'user_id');
    }
}
```

### Lazy loading

[](#lazy-loading)

```
$user->posts;
```

### Eager loading

[](#eager-loading)

```
$user->load('posts');
```

Soft Deletes
------------

[](#soft-deletes)

```
use Codemonster\Database\Traits\SoftDeletes;

class User extends Model {
    use SoftDeletes;
}
```

- `$user->delete()` → sets `deleted_at`
- `$user->restore()`
- `User::onlyTrashed()`
- `User::withTrashed()`

CLI Tool
--------

[](#cli-tool)

A standalone CLI ships with the package:

```
vendor/bin/database
```

### Running migrations

[](#running-migrations)

```
vendor/bin/database migrate
```

### Rollback

[](#rollback)

```
vendor/bin/database migrate:rollback
```

### Status

[](#status)

```
vendor/bin/database migrate:status
```

### Wipe database

[](#wipe-database)

```
vendor/bin/database db:wipe
```

Force wipe without confirmation:

```
vendor/bin/database db:wipe --force
```

### Clean database data (keep migrations table)

[](#clean-database-data-keep-migrations-table)

```
vendor/bin/database db:truncate
```

Force clean without confirmation:

```
vendor/bin/database db:truncate --force
```

### Create a migration

[](#create-a-migration)

```
vendor/bin/database make:migration CreatePostsTable
```

Migration names must be CamelCase using only Latin letters (e.g., `CreateUsersTable`). Names that include other symbols or casing styles are rejected.

Default migrations directory:

```
./database/migrations

```

You can override paths via the migration kernel/path resolver:

```
$kernel->getPathResolver()->addPath('/path/to/migrations');
```

### Running seeders

[](#running-seeders)

```
vendor/bin/database seed
```

### Create a seeder

[](#create-a-seeder)

```
vendor/bin/database make:seed UsersSeeder
```

Seed names must be CamelCase using only Latin letters (e.g., `UsersSeeder`). Names that include other symbols or casing styles are rejected.

Default seeds directory:

```
./database/seeds

```

You can override paths via the seed kernel/path resolver:

```
$kernel->getSeedPathResolver()->addPath('/path/to/seeds');
```

Tests
-----

[](#tests)

```
composer test
```

Author
------

[](#author)

[**Kirill Kolesnikov**](https://github.com/KolesnikovKirill)

License
-------

[](#license)

[MIT](https://github.com/codemonster-ru/database/blob/main/LICENSE)

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance74

Regular maintenance activity

Popularity9

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 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 ~1 days

Total

9

Last Release

147d ago

Major Versions

v1.6.0 → v2.0.02025-12-22

### Community

Maintainers

![](https://www.gravatar.com/avatar/a22c460130c82eca5da633a388faa81adf7e63558a2ae1e34441e6624ec2ad15?d=identicon)[KolesnikovKirill](/maintainers/KolesnikovKirill)

---

Top Contributors

[![KolesnikovKirill](https://avatars.githubusercontent.com/u/33142935?v=4)](https://github.com/KolesnikovKirill "KolesnikovKirill (20 commits)")

---

Tags

codemonsterdatabasedb-layerlightweightmysqlpdophp-databasequeryquery-buildersqlschemadatabasemysqlsqlpdoquerymigrationsquery builderframework agnosticphp-databaseDB layerdatabase-managercodemonstermigration-runnerorm-like

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/codemonster-ru-database/health.svg)

```
[![Health](https://phpackages.com/badges/codemonster-ru-database/health.svg)](https://phpackages.com/packages/codemonster-ru-database)
```

###  Alternatives

[aura/sqlquery

Object-oriented query builders for MySQL, Postgres, SQLite, and SQLServer; can be used with any database connection library.

4572.9M34](/packages/aura-sqlquery)[tommyknocker/pdo-database-class

Framework-agnostic PHP database library with unified API for MySQL, MariaDB, PostgreSQL, SQLite, MSSQL, and Oracle. Query Builder, caching, sharding, window functions, CTEs, JSON, migrations, ActiveRecord, CLI tools, AI-powered analysis. Zero external dependencies.

845.7k](/packages/tommyknocker-pdo-database-class)[opis/database

A database abstraction layer over PDO, that provides a powerful and intuitive query builder, bundled with an easy to use schema builder

10184.2k3](/packages/opis-database)[atlas/query

Object-oriented query builders and performers for MySQL, Postgres, SQLite, and SQLServer.

41249.0k7](/packages/atlas-query)[aura/sqlschema

Provides facilities to read table names and table columns from a database using PDO.

41234.1k4](/packages/aura-sqlschema)[codesvault/howdy-qb

Mysql Query Builder for WordPress

371.2k1](/packages/codesvault-howdy-qb)

PHPackages © 2026

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