PHPackages                             jardisport/dbquery - 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. jardisport/dbquery

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

jardisport/dbquery
==================

Fluent SQL query builder interfaces for dialect-aware SELECT, INSERT, UPDATE, and DELETE

v1.0.0(2mo ago)0116↓50%2proprietaryPHPPHP &gt;=8.2CI passing

Since Mar 17Pushed 2mo agoCompare

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

READMEChangelog (1)Dependencies (4)Versions (6)Used By (2)

DbQuery - Database Query Builder Interfaces
===========================================

[](#dbquery---database-query-builder-interfaces)

[![Build Status](https://github.com/JardisPort/dbquery/actions/workflows/ci.yml/badge.svg)](https://github.com/JardisPort/dbquery/actions/workflows/ci.yml/badge.svg)[![License: MIT](https://camo.githubusercontent.com/08cef40a9105b6526ca22088bc514fbfdbc9aac1ddbf8d4e6c750e3a88a44dca/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d626c75652e737667)](LICENSE)[![PHP Version](https://camo.githubusercontent.com/c5e8da782b1a0673c08b4f474108036d2cc973470eed2d5d89d48e8c8475eee6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e322d626c75652e737667)](https://www.php.net/)[![PHPStan Level](https://camo.githubusercontent.com/da248cac2cd550c5338b7bb389aa607444a2caaebcff4973edc1b153132ec1bd/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d4c6576656c253230382d737563636573732e737667)](phpstan.neon)[![PSR-4](https://camo.githubusercontent.com/52bb6536eb4261a007095d48b1b40fcf8bf357a0649865230901e12746a7fe80/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6175746f6c6f61642d5053522d2d342d626c75652e737667)](https://www.php-fig.org/psr/psr-4/)[![PSR-12](https://camo.githubusercontent.com/31c439b05fb5c48dbfede00334441d62e75bd1e94cc1e9406e47664fbb11f18f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f64652532307374796c652d5053522d2d31322d6f72616e67652e737667)](phpcs.xml)

A comprehensive set of **interface-only** database query builder contracts for domain-driven design. This library provides the blueprints for building type-safe, fluent SQL query builders - you implement the interfaces according to your specific needs.

> **Note**: This is an interface library only. It contains no implementations, just contracts that define how query builders should work.

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

[](#installation)

```
composer require jardisport/dbquery
```

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

[](#requirements)

- PHP &gt;= 8.2
- PDO extension

Why Use This Library?
---------------------

[](#why-use-this-library)

DbQuery provides a clean, professional foundation for building your own query builders:

- **Interface-First Design**: Define contracts before implementation, enabling flexible architecture
- **Domain-Driven Design**: Follows SOLID principles with interface segregation
- **Multi-Dialect Support**: Design for MySQL, PostgreSQL, and SQLite from the start
- **Type Safety**: Leverage PHP 8.2+ type system for compile-time safety
- **Production-Ready Standards**: PHPStan level 8, PSR-12 compliant, fully documented

Key Features
------------

[](#key-features)

- **Fluent Interface Pattern**: Chainable methods for intuitive, readable query building
- **Comprehensive Query Support**: SELECT, INSERT, UPDATE, DELETE with full feature sets
- **Advanced SQL Features**:
    - Common Table Expressions (CTEs), including recursive CTEs
    - Window functions with PARTITION BY and custom framing
    - JSON path extraction and contains operations
    - Subqueries in SELECT, WHERE, JOIN, and INSERT...SELECT
    - Upsert operations with conflict resolution
- **Prepared Statements**: Built-in parameter binding for SQL injection prevention
- **Clean Architecture**: Small, focused interfaces composed into larger ones

Architecture
------------

[](#architecture)

### Interface Hierarchy

[](#interface-hierarchy)

The library uses **Interface Segregation Principle** - small, focused interfaces that compose into larger ones:

#### Core Query Builders

[](#core-query-builders)

These extend multiple feature interfaces to provide complete query building capabilities:

- **`DbQueryBuilderInterface`** - SELECT queries

    - Extends: `DbWhereConditionInterface`, `DbJoinInterface`, `DbQueryExistsInterface`, `DbOrderLimitInterface`, `DbSqlGeneratorInterface`
    - Methods: `select()`, `from()`, `selectWindow()`, `with()`, `withRecursive()`, `union()`, `groupBy()`, `having()`
- **`DbInsertBuilderInterface`** - INSERT operations

    - Extends: `DbSqlGeneratorInterface`
    - Methods: `insert()`, `into()`, `fields()`, `values()`, `onConflict()`, `doUpdate()`, `doNothing()`
- **`DbUpdateBuilderInterface`** - UPDATE operations

    - Extends: `DbWhereConditionInterface`, `DbQueryExistsInterface`, `DbJoinInterface`, `DbOrderLimitInterface`, `DbSqlGeneratorInterface`
    - Methods: `update()`, `table()`, `set()`
- **`DbDeleteBuilderInterface`** - DELETE operations

    - Extends: `DbWhereConditionInterface`, `DbQueryExistsInterface`, `DbJoinInterface`, `DbOrderLimitInterface`, `DbSqlGeneratorInterface`
    - Methods: `delete()`, `from()`

#### Feature Interfaces

[](#feature-interfaces)

Mix-in interfaces for specific capabilities:

- **`DbWhereConditionInterface`** - WHERE clause building with AND/OR logic
- **`DbQueryConditionBuilderInterface`** - Standard comparison operators
- **`DbComparisonOperatorsInterface`** - Common operators (equals, greater, like, in, between, etc.)
- **`DbQueryJsonConditionBuilderInterface`** - JSON operations (extract, contains)
- **`DbQueryExistsInterface`** - EXISTS and NOT EXISTS subqueries
- **`DbJoinInterface`** - INNER and LEFT JOIN operations
- **`DbOrderLimitInterface`** - ORDER BY, LIMIT, OFFSET clauses
- **`DbWindowBuilderInterface`** - Window function specifications

#### Result Interfaces

[](#result-interfaces)

- **`QueryResultInterface`** - Result of a SELECT query: `fetchAll()`, `fetchOne()`, `rowCount()`
- **`ExecuteResultInterface`** - Result of a DML operation (INSERT/UPDATE/DELETE): `affectedRows()`, `lastInsertId()`

#### Supporting Interfaces

[](#supporting-interfaces)

- **`DbSqlGeneratorInterface`** - Generate SQL with dialect parameter ('mysql', 'pgsql', 'sqlite')
- **`DbPreparedQueryInterface`** - Prepared query result with SQL and parameter bindings
- **`ExpressionInterface`** - Raw SQL expressions for special cases

Usage Examples
--------------

[](#usage-examples)

> **Remember**: These are interface definitions. The examples show how code would look when using implementations of these interfaces.

### Basic SELECT Query

[](#basic-select-query)

```
// Build a query with conditions and ordering
$query = $builder
    ->select('id, name, email')
    ->from('users')
    ->where('status')->equals('active')
    ->and('age')->greater(18)
    ->orderBy('name', 'ASC')
    ->limit(10);

// Generate prepared statement for MySQL
$prepared = $query->sql('mysql', true);
// Returns DbPreparedQueryInterface with SQL and bindings
```

### INSERT with Upsert (Conflict Resolution)

[](#insert-with-upsert-conflict-resolution)

```
// INSERT with ON CONFLICT handling (PostgreSQL style)
$insert = $builder
    ->insert()
    ->into('users')
    ->fields('email', 'name', 'status')
    ->values('john@example.com', 'John Doe', 'active')
    ->onConflict('email')
    ->doUpdate(['name' => 'John Doe', 'status' => 'active']);

$prepared = $insert->sql('pgsql', true);
```

### UPDATE with JOIN

[](#update-with-join)

```
// Update based on joined table data
$update = $builder
    ->update()
    ->table('users', 'u')
    ->innerJoin('orders', 'orders.user_id = u.id', 'o')
    ->set('u.last_order_date', new Expression('MAX(o.created_at)'))
    ->where('o.status')->equals('completed');

$prepared = $update->sql('mysql', true);
```

### Common Table Expressions (CTEs)

[](#common-table-expressions-ctes)

```
// Regular CTE
$query = $builder
    ->with('active_users', $subquery)  // $subquery is DbQueryBuilderInterface
    ->select('*')
    ->from('active_users')
    ->where('registration_date')->greater('2024-01-01');

// Recursive CTE for hierarchical data
$query = $builder
    ->withRecursive('hierarchy', $anchorQuery, $recursiveQuery)
    ->select('*')
    ->from('hierarchy');

$prepared = $query->sql('pgsql', true);
```

### Window Functions

[](#window-functions)

```
// Partition data and apply window functions
$query = $builder
    ->select('id, name, department, salary')
    ->selectWindow('ROW_NUMBER', 'row_num')
        ->partitionBy('department')
        ->windowOrderBy('salary', 'DESC')
        ->endWindow()
    ->selectWindow('AVG', 'dept_avg_salary')
        ->windowFunction('salary')
        ->partitionBy('department')
        ->endWindow()
    ->from('employees');

$prepared = $query->sql('mysql', true);
```

### JSON Operations

[](#json-operations)

```
// Query JSON columns
$query = $builder
    ->select('*')
    ->from('users')
    ->whereJson('metadata')->extract('$.role')->equals('admin')
    ->andJson('settings')->contains('notifications', '$.features');

$prepared = $query->sql('mysql', true);
```

### Complex Query with Subqueries

[](#complex-query-with-subqueries)

```
// Subquery in SELECT
$avgSalarySubquery = $builder
    ->select('AVG(salary)')
    ->from('employees', 'e2')
    ->where('e2.department')->equalsColumn('e1.department');

$query = $builder
    ->select('e1.name, e1.salary')
    ->selectSubquery($avgSalarySubquery, 'dept_avg')
    ->from('employees', 'e1')
    ->where('e1.salary')->greater($avgSalarySubquery);

$prepared = $query->sql('mysql', true);
```

Development
-----------

[](#development)

This project uses Docker for all development tasks. See [CLAUDE.md](.claude/CLAUDE.md) for comprehensive development documentation.

### Quick Start

[](#quick-start)

```
# Install dependencies
make install

# Run coding standards check
make phpcs

# Run static analysis
make phpstan

# Update dependencies
make update
```

### Code Quality

[](#code-quality)

- **Standards**: PSR-12 with 120 character line limit
- **Static Analysis**: PHPStan level 8 (strictest)
- **Pre-commit Hooks**: Automatically enforces coding standards and branch naming conventions
- **CI/CD**: GitHub Actions runs PHPCS and PHPStan on all PRs

### Branch Naming Convention

[](#branch-naming-convention)

Branches must follow the pattern: `feature/123456_description`, `fix/1234567_description`, or `hotfix/123456_description`

### Docker Environment

[](#docker-environment)

All commands run through Docker Compose - never run PHP commands directly on the host:

```
make shell      # Open interactive shell in container
make remove     # Clean up Docker environment
```

All interfaces must include:

- `declare(strict_types=1);` declaration
- Comprehensive PHPDoc comments with examples
- Full type declarations for all parameters and return types

License
-------

[](#license)

MIT License - see [LICENSE](LICENSE) file for details

Authors
-------

[](#authors)

**Jardis Core Development**

- Email:
- GitHub: [@JardisPort](https://github.com/JardisPort)

Support
-------

[](#support)

- **Issues**:
- **Email**:

**Built with ❤️ by Jardis Core Development**

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance88

Actively maintained with recent releases

Popularity14

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity50

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

Total

2

Last Release

62d ago

### Community

Maintainers

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

---

Top Contributors

[![Headgent](https://avatars.githubusercontent.com/u/245725954?v=4)](https://github.com/Headgent "Headgent (1 commits)")

---

Tags

interfacesdatabasequerydddHeadgentJardisPort

###  Code Quality

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/jardisport-dbquery/health.svg)

```
[![Health](https://phpackages.com/badges/jardisport-dbquery/health.svg)](https://phpackages.com/packages/jardisport-dbquery)
```

###  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)[envms/fluentpdo

FluentPDO is a quick and light PHP library for rapid query building. It features a smart join builder, which automatically creates table joins.

925511.7k13](/packages/envms-fluentpdo)[bvanhoekelen/performance

PHP performance tool analyser your script on time, memory usage and db query. Support Laravel and Composer for web, web console and command line interfaces.

521774.3k4](/packages/bvanhoekelen-performance)[tpetry/laravel-query-expressions

Database-independent Query Expressions as a replacement to DB::raw calls

357436.5k2](/packages/tpetry-laravel-query-expressions)[clancats/hydrahon

Fast &amp; standalone PHP MySQL Query Builder library.

281205.5k5](/packages/clancats-hydrahon)[illuminated/db-profiler

Database Profiler for Laravel Web and Console Applications.

168237.4k](/packages/illuminated-db-profiler)

PHPackages © 2026

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