Download the PHP package methorz/swift-db without Composer
On this page you can find all versions of the php package methorz/swift-db. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download methorz/swift-db
More information about methorz/swift-db
Files in methorz/swift-db
Package swift-db
Short Description High-performance MySQL database layer with bulk operations, PDO-based
License MIT
Informations about the package swift-db
MethorZ SwiftDb
High-performance MySQL database layer with bulk operations, built on PDO.
Features
- High Performance: Direct PDO with no abstraction overhead
- Bulk Operations: Multi-row INSERT, INSERT...ON DUPLICATE KEY UPDATE
- Entity Pattern: Clean entity classes with dirty tracking
- Repository Pattern: Type-safe repositories with query builder
- MySQL Optimized: Designed specifically for MySQL
- Deadlock Handling: Automatic retry with exponential backoff
- Connection Management: Master/slave support, reconnection handling
- Query Logging: Built-in debugging and monitoring
Installation
Quick Start
Configuration
Define an Entity
Define a Repository
Basic Usage
Pagination
Bulk Operations
Transactions
Optimistic Locking
Performance Tips
- Use bulk operations for multiple inserts/updates
- Use dirty tracking - only changed fields are updated
- Batch your queries - use
findMany()instead of multiplefind()calls - Use the query builder for complex queries instead of multiple simple queries
- Enable the mapping cache in production for faster hydration
- Use convenience methods -
whereBetween()generates more efficient SQL than two separatewhere()calls, andorWhereLike()is clearer thanorWhere('col', 'LIKE', '?')
Development
Quick Start
Docker Setup
The package includes a Docker setup for running integration tests with a real MySQL database.
Test Structure
Makefile Commands
| Command | Description |
|---|---|
make start |
Start Docker containers |
make stop |
Stop Docker containers |
make test |
Run all tests |
make test-unit |
Run unit tests only |
make test-integration |
Run integration tests |
make quality |
Run CS fix, CS check, and PHPStan |
make cs-check |
Check code style |
make cs-fix |
Fix code style |
make analyze |
Run PHPStan |
make shell |
Open PHP shell |
make db-shell |
Open MySQL shell |
API Reference
AbstractEntity
Base class for all entities.
| Method | Description |
|---|---|
getId(): mixed |
Get primary key value |
setId(mixed $id): void |
Set primary key value |
hydrate(array $data): void |
Populate entity from database row |
extract(): array |
Extract entity data for persistence |
isDirty(): bool |
Check if entity has unsaved changes |
getDirtyFields(): array |
Get only changed fields |
markPersisted(): void |
Mark entity as saved |
getColumnMapping(): array |
Define property-to-column mapping |
getPrimaryKeyColumn(): string |
Get primary key column name |
AbstractRepository
Base class for all repositories.
| Method | Description |
|---|---|
find(mixed $id): ?T |
Find by primary key |
findOrFail(mixed $id): T |
Find or throw exception |
findMany(array $ids): array |
Find multiple by IDs |
findAll(): array |
Find all records |
save(EntityInterface $entity): void |
Insert or update entity |
delete(EntityInterface $entity): bool |
Delete entity |
deleteById(mixed $id): bool |
Delete by primary key |
create(): T |
Create new entity instance |
count(): int |
Count all records |
query(): QueryBuilder |
Create query builder |
paginate(int $perPage, int $page): PaginatedResult |
Paginate all records |
bulkInsert(int $batchSize): BulkInsert |
Create bulk insert operation |
bulkUpsert(int $batchSize): BulkUpsert |
Create bulk upsert operation |
beginTransaction(): void |
Start transaction |
commit(): void |
Commit transaction |
rollback(): void |
Rollback transaction |
transaction(callable $callback): mixed |
Execute in transaction |
QueryBuilder
Fluent query builder for MySQL with Laravel-style syntax.
Basic Methods
| Method | Description |
|---|---|
table(string $table): self |
Set table name |
from(string $table): self |
Alias for table() |
select(array\|string $columns): self |
Set columns to select |
addSelect(string ...$columns): self |
Add columns |
selectSub(Closure $callback, string $as): self |
Add subquery column |
selectRaw(string $expression): self |
Add raw select |
distinct(): self |
Select distinct rows |
WHERE Clauses (Laravel-style)
| Method | Description |
|---|---|
where($column, $value) |
Implicit '=' operator |
where($column, $operator, $value) |
Explicit operator |
where(['col' => $val, ...]) |
Array of conditions |
where(Closure $callback) |
Nested conditions |
orWhere(...) |
OR variant of where() |
whereColumn($first, $second) |
Compare two columns |
orWhereColumn(...) |
OR variant of whereColumn() |
whereIn($column, $values\|Closure) |
IN clause or subquery |
orWhereIn($column, $values\|Closure) |
OR WHERE IN |
whereNotIn($column, $values\|Closure) |
NOT IN clause |
orWhereNotIn($column, $values\|Closure) |
OR WHERE NOT IN |
whereNull($column) |
IS NULL |
orWhereNull($column) |
OR WHERE IS NULL |
whereNotNull($column) |
IS NOT NULL |
orWhereNotNull($column) |
OR WHERE IS NOT NULL |
whereBetween($column, $min, $max) |
BETWEEN |
orWhereBetween($column, $min, $max) |
OR WHERE BETWEEN |
whereNotBetween($column, $min, $max) |
NOT BETWEEN |
orWhereNotBetween($column, $min, $max) |
OR WHERE NOT BETWEEN |
whereLike($column, $pattern) |
LIKE pattern |
orWhereLike($column, $pattern) |
OR WHERE LIKE |
whereExists(Closure $callback) |
EXISTS subquery |
orWhereExists(Closure $callback) |
OR WHERE EXISTS |
whereNotExists(Closure $callback) |
NOT EXISTS |
orWhereNotExists(Closure $callback) |
OR WHERE NOT EXISTS |
whereRaw($sql, $bindings) |
Raw WHERE clause |
orWhereRaw($sql, $bindings) |
OR raw WHERE clause |
JOINs (with closure support)
| Method | Description |
|---|---|
join($table, $first, $second) |
INNER JOIN (implicit '=') |
join($table, $first, $op, $second) |
INNER JOIN with operator |
join($table, Closure $callback) |
Complex join conditions |
leftJoin(...) |
LEFT JOIN variants |
rightJoin(...) |
RIGHT JOIN variants |
Ordering & Grouping
| Method | Description |
|---|---|
orderBy($column, $direction) |
ORDER BY |
orderBy(['col' => 'dir', ...]) |
Multiple columns |
orderByAsc($column) |
ORDER BY ASC |
orderByDesc($column) |
ORDER BY DESC |
groupBy($columns) |
GROUP BY |
limit($n) / take($n) |
Set LIMIT |
offset($n) / skip($n) |
Set OFFSET |
Unions
| Method | Description |
|---|---|
union(QueryBuilder $query) |
UNION |
unionAll(QueryBuilder $query) |
UNION ALL |
Conditional Building
| Method | Description |
|---|---|
when($condition, Closure $callback, ?Closure $default) |
Apply if truthy |
unless($condition, Closure $callback) |
Apply if falsy |
tap(Closure $callback) |
Execute side effect |
Execution
| Method | Description |
|---|---|
get(): array |
Get all rows |
first(): ?array |
Get first row |
count(): int |
COUNT query |
exists(): bool |
Check existence |
doesntExist(): bool |
Check non-existence |
update(array $values): int |
UPDATE query |
delete(): int |
DELETE query |
insert(array $values): bool |
INSERT query |
toSql(): string |
Get SQL string |
getBindings(): array |
Get bindings |
paginate(int $perPage, int $page): PaginatedResult |
Paginate results |
Query Builder Examples
PaginatedResult
Paginated result set implementing Countable and IteratorAggregate.
| Property/Method | Description |
|---|---|
$items |
Array of result rows |
$total |
Total record count |
$perPage |
Items per page |
$currentPage |
Current page number |
lastPage(): int |
Calculate last page number |
hasMorePages(): bool |
Check if more pages exist |
hasPreviousPage(): bool |
Check if previous page exists |
isEmpty(): bool |
Check if result is empty |
isNotEmpty(): bool |
Check if result has items |
firstItem(): ?int |
Get first item index (1-based) |
lastItem(): ?int |
Get last item index (1-based) |
Connection
Database connection wrapper with lazy initialization and automatic reconnection.
| Method | Description |
|---|---|
getPdo(): PDO |
Get underlying PDO (lazy-init) |
prepare(string $sql): PDOStatement |
Prepare statement with reconnect |
query(string $sql): PDOStatement |
Execute raw query with reconnect |
execute(string $sql, array $params): int |
Execute and return affected rows |
fetchOne(string $sql, array $params): ?array |
Fetch single row or null |
fetchAll(string $sql, array $params): array |
Fetch all matching rows |
beginTransaction(): bool |
Start transaction |
commit(): bool |
Commit transaction |
rollback(): bool |
Rollback transaction |
inTransaction(): bool |
Check if in transaction |
lastInsertId(?string $name): string\|false |
Get last insert ID |
executeWithReconnect(callable $op): mixed |
Run operation with auto-reconnect |
isConnected(): bool |
Check if connected |
connect(): void |
Establish connection |
disconnect(): void |
Close connection |
reconnect(): void |
Disconnect and reconnect |
BulkInsert
High-performance multi-row INSERT.
| Method | Description |
|---|---|
add(array\|EntityInterface $row): self |
Add row or entity to batch |
addMany(array $rows): self |
Add multiple rows |
flush(): int |
Execute and return affected rows |
ignore(bool $ignore = true): self |
Use INSERT IGNORE |
getTotalAffected(): int |
Get total rows affected |
getPendingCount(): int |
Get pending (unflushed) row count |
Batch size is set via the constructor (default: 1000). Auto-flushes when batch is full.
BulkUpsert
INSERT ... ON DUPLICATE KEY UPDATE (extends BulkInsert).
| Method | Description |
|---|---|
onDuplicateKeyUpdate(array $columns): self |
Set columns to update |
updateColumn(string $col, string $expr): self |
Custom update expression |
incrementOnDuplicate(string $column): self |
Increment column on duplicate |
touchUpdatedOnDuplicate(string $col): self |
Update timestamp on duplicate |
| (inherits all BulkInsert methods) |
IdentityMap (Optional)
Caches loaded entities to prevent duplicate instances.
| Method | Description |
|---|---|
get(string $class, int\|string $id): ?T |
Get cached entity |
set(string $class, int\|string $id, EntityInterface $entity): void |
Cache entity |
has(string $class, int\|string $id): bool |
Check if cached |
remove(string $class, int\|string $id): void |
Remove from cache |
clear(?string $class): void |
Clear cache (all or by class) |
getStats(): array |
Get hit/miss statistics |
JoinClause
Helper class for building complex JOIN conditions (used with closure joins).
| Method | Description |
|---|---|
on($first, $second) |
Add ON condition (column = column) |
on($first, $operator, $second) |
Add ON condition with operator |
orOn($first, $second) |
Add OR ON condition |
where($column, $value) |
Add WHERE condition (column = value) |
where($column, $operator, $value) |
Add WHERE condition with operator |
orWhere(...) |
Add OR WHERE condition |
whereNull($column) |
Add WHERE IS NULL |
whereNotNull($column) |
Add WHERE IS NOT NULL |
Example:
QueryLogger
Debug and monitor query execution.
| Method | Description |
|---|---|
enable(): void |
Enable logging |
disable(): void |
Disable logging |
isEnabled(): bool |
Check if enabled |
log(string $sql, array $params, float $duration): void |
Log a query |
getQueries(): array |
Get all logged queries |
getQueryCount(): int |
Get total query count |
getTotalTime(): float |
Get total execution time (seconds) |
getSlowestQuery(): ?array |
Get the slowest query |
getSlowQueries(float $threshold): array |
Get queries slower than threshold |
getSummary(): array |
Get statistics summary |
clear(): void |
Clear logged queries |
Example:
MappingCache
OPcache-friendly cache for entity column mappings (production optimization).
| Method | Description |
|---|---|
getMapping(string $entityClass): array |
Get cached mapping for entity class |
clear(): void |
Clear all cached mappings |
clearFor(string $entityClass): void |
Clear mapping for specific class |
Example:
Traits
| Trait | Properties | Description |
|---|---|---|
TimestampsTrait |
createdAt, updatedAt |
Auto-managed timestamps |
UuidTrait |
uuid |
UUID v7 generation |
VersionTrait |
version |
Optimistic locking |
Exceptions
| Exception | HTTP Code | Description |
|---|---|---|
DatabaseException |
500 | Base exception |
ConnectionException |
500 | Connection failures |
QueryException |
500 | Query execution errors |
EntityException |
500 | Entity-related errors |
DeadlockException |
500 | MySQL deadlock detected |
DuplicateEntryException |
409 | Unique constraint violation |
OptimisticLockException |
409 | Version mismatch |
Requirements
- PHP 8.3 or 8.4
- PDO with MySQL driver
- MySQL 8.0+
- Docker (for integration tests)
Contributing
See CONTRIBUTING.md for development guidelines.
License
MIT
All versions of swift-db with dependencies
ext-pdo Version *
ext-pdo_mysql Version *
psr/container Version ^2.0
psr/log Version ^3.0
ramsey/uuid Version ^4.7