Skip to content

Releases: tommyknocker/pdo-database-class

v2.11.2

06 Dec 18:03

Choose a tag to compare

Release v2.11.2

This release extends the TUI Dashboard with 4 new panes, adds powerful table search and seed generation commands, and includes numerous bug fixes and improvements.

🎉 Major Features

Extended TUI Dashboard with Dual-Screen Support

The dashboard now includes 8 panes across 2 screens with full keyboard navigation:

  • Schema Browser - Browse database tables, view columns, indexes, and foreign keys
  • Migration Manager - List migrations with status, view file content with syntax highlighting, apply/rollback actions
  • Server Variables - View and search server configuration variables across all dialects
  • SQL Scratchpad - Interactive SQL query editor with autocomplete and query history

Navigate between screens with Tab/arrows, use keys 1-8 to jump to any pane, and activate global search with '/' key.

New Commands

Table Search (pdodb table search <table>)

  • Search values across all columns in a table
  • Support for JSON and array column search across all dialects
  • Options: --column, --limit, --json, --format

Seed Generate (pdodb seed generate <table>)

  • Extract data from database and generate seed files
  • Flexible filtering, sorting, and selective column export
  • Options: --limit, --where, --order-by, --exclude, --include, --format, --chunk-size, --preserve-ids, --skip-timestamps

🔧 Improvements

  • Enhanced IDE autocompletion for schema() method in migrations
  • New EnvConfigLoader class for better environment variable isolation
  • Centered pane titles and compact UI to fit 80x24 terminal
  • Optimized imports across 74 files

🐛 Bug Fixes

TUI Dashboard

  • Fixed connection count discrepancy in Connection Pool pane
  • Fixed Server Metrics pane showing incorrect Uptime and connection metrics
  • Fixed flickering in Active Queries pane in fullscreen mode
  • Fixed right border being overwritten by content
  • Fixed arrow key navigation (2-character escape sequences)
  • Fixed SQL Scratchpad autocomplete positioning and screen refresh
  • Fixed ESC key handling to exit fullscreen mode

Database Dialects

  • Fixed MySQL/MariaDB connection count calculation
  • Fixed MySQL/MariaDB uptime retrieval from SHOW VARIABLES
  • Fixed Oracle connection details display (added support for 'sid' and 'schema' keys)
  • Improved ServerMetricsPane metric labels for clarity

Code Quality

  • Fixed PHPStan errors in SeedCommand and SeedDataGenerator
  • Fixed event dispatcher state leakage in tests
  • Fixed Oracle tests failing due to environment variable pollution
  • Fixed CacheManager reflection issues with typed properties

📊 Test Coverage

  • Code coverage increased from ~65% to ~67% (Lines: 18519/27596)
  • Added comprehensive tests for Oracle classes, UI panes, and CLI commands
  • Total: 3806 tests, 12180 assertions

📝 Full Changelog

See CHANGELOG.md for complete list of changes.

🔗 Links

v2.11.1

02 Dec 18:38

Choose a tag to compare

Release v2.11.1

🎉 Major Features

🖥️ Interactive TUI Dashboard

Real-time database monitoring with a beautiful full-screen terminal interface! Monitor active queries, connection pool, cache statistics, and server metrics in real-time.

Features:

  • Monitor active queries with full query text, execution time, user, and database
  • Kill long-running queries with a single keystroke
  • Keyboard navigation with pane switching, scrolling, and fullscreen mode
  • Real-time refresh with configurable intervals (realtime, 0.5s, 1s, 2s, 5s)
  • Color-coded metrics for performance visualization

Launch: pdodb ui

🚀 Code Generation Command

New pdodb generate command with multiple subcommands for rapid development:

  • pdodb generate api - Generate API controller classes
  • pdodb generate tests - Generate test files
  • pdodb generate dto - Generate Data Transfer Object classes
  • pdodb generate enum - Generate enum classes
  • pdodb generate docs - Generate documentation files
  • pdodb generate model - Generate ActiveRecord model classes
  • pdodb generate repository - Generate repository classes
  • pdodb generate service - Generate service classes

⚡ Benchmark Command

Comprehensive performance testing tools:

  • pdodb benchmark query - Benchmark SQL query performance
  • pdodb benchmark crud - Benchmark CRUD operations
  • pdodb benchmark load - Load testing with multiple connections
  • pdodb benchmark profile - Query profiling with detailed statistics
  • pdodb benchmark compare - Compare query performance

✨ New Features

  • Version Command - pdodb version and --version / -v flag support
  • Index Suggestion - pdodb table suggest-indexes <table> to optimize database performance
  • Oracle Helpers - New Db::toTs(), Db::toDate(), and Db::toChar() functions
  • IDE Autocompletion - Enhanced autocompletion for Model::find() method
  • CLI Improvements - "Did you mean?" command suggestions for typos
  • Event System - Added missing events for better monitoring and auditing

🔧 Improvements

  • All generated namespaces are now automatically converted to lowercase for consistency

🐛 Bug Fixes

  • Fixed loading .env file before checking PDODB_DRIVER in connection list command
  • Fixed parsing command line options without equals sign (--option=value and --option value)
  • Fixed Oracle type helpers example and PHPStan errors
  • Fixed benchmark command tests to use correct path to pdodb binary
  • Added warning when --query is not specified for benchmark compare command
  • Improved test reliability: skip user creation tests when privileges are missing

📚 Documentation

  • Improved IDE autocompletion documentation
  • Clarified PHPStan ignore comments in PdoDb::fromEnv method

🧪 Tests

  • Added comprehensive tests for Oracle-specific helpers and exception handling
  • Improved benchmark command tests with better error handling

Full Changelog: v2.11.0...v2.11.1

v2.11.0

28 Nov 18:14

Choose a tag to compare

🚀 Release v2.11.0 - Oracle Database Support & Major Enhancements

Release Date: November 28, 2025

This release introduces full Oracle Database support along with significant improvements to the CLI tools, environment configuration, and overall code quality.

🎉 Major Features

🗄️ Oracle Database Support

Complete Oracle Database (OCI driver) implementation with:

  • Full query builder support for all Oracle features
  • Oracle-specific data types and functions
  • CLOB handling for large text fields
  • Support for recursive CTEs, window functions, and advanced Oracle features
  • normalize_row_keys option for automatic column name normalization
  • Comprehensive examples and test coverage
  • CI integration in GitHub Actions

🔧 New Methods & Features

  • PdoDb::fromEnv() - Unified .env file support for easy database connection
  • PHP Extension Validation - Automatic validation with helpful error messages
  • Connection Management CLI - New pdodb connection commands
  • Database Seeds - New pdodb seed functionality
  • Enhanced Dump Command - Compression, auto-naming, and backup rotation
  • Table Management - New count and sample commands

📊 Test Coverage

Extended test coverage to 74%+ with comprehensive tests for:

  • All CLI commands
  • DDL builders for all dialects
  • Code generators (Repository, Service, Migration)
  • Cache and connection management
  • Edge cases and error handling

🔄 Improvements

Oracle Compatibility

  • Improved support for TRUE/FALSE, CAST, GREATEST, LEAST functions
  • Enhanced REGEXP_MATCH, COALESCE, and NULLIF support
  • Better CLOB handling in various operations
  • Cursor pagination support
  • Improved date handling in INSERT ALL statements

Code Quality

  • Removed dialect-specific logic from general classes
  • Moved dialect-specific logic to dialect implementations
  • Improved code organization and maintainability

🐛 Bug Fixes

  • Fixed Oracle CI in GitHub Actions (Instant Client installation, extension compilation)
  • Fixed Oracle CLI examples (environment variable propagation)
  • Fixed Oracle examples (recursive CTEs, window functions, JSON basics)
  • Fixed Memcached adapter creation
  • Fixed foreign key constraint handling in DDL examples
  • Fixed PHPStan errors

📚 Documentation

  • Added Oracle Database installation instructions
  • Fixed all documentation links
  • Created bidirectional links between documentation and examples
  • Updated README.md for better readability
  • Added bash completion installation instructions

🔗 Links

📦 Installation

composer require tommyknocker/pdo-database-class:^2.11.0

⚡ Migration Guide

No breaking changes! This is a backward-compatible release. You can safely update from v2.10.x.

For Oracle support, make sure you have:


Thank you for using PDOdb! 🎊

v2.10.3

21 Nov 14:06

Choose a tag to compare

Release v2.10.3

Release Date: November 21, 2025

🎉 Major Features

Project Initialization Wizard (pdodb init)

The fastest way to get started with PDOdb! Interactive wizard for quick project setup:

  • Interactive configuration wizard for database connection settings
  • Support for MySQL, PostgreSQL, SQLite, and MSSQL (SQLSRV) drivers
  • Configuration file generation (.env or config/db.php)
  • Automatic directory structure creation
  • Cache dependency validation with helpful warnings

Repository and Service Generators

  • pdodb repository make <name> - Generate repository classes
  • pdodb service make <name> - Generate service classes with dependency injection
  • Automatic primary key detection

Database Monitoring (pdodb monitor)

Monitor your database performance:

  • pdodb monitor queries - Show active queries
  • pdodb monitor connections - Show active connections
  • pdodb monitor slow [threshold] - Show slow queries
  • Cross-dialect support (MySQL, MariaDB, PostgreSQL, MSSQL, SQLite)

Migration Dry-Run Improvements

pdodb migrate up --dry-run now shows actual SQL queries that would be executed, not just comments!

Cache Management Enhancements

  • pdodb cache invalidate <pattern> - Invalidate cache entries by pattern
  • Persistent cache statistics with atomic operations
  • Universal cache type detection for all PSR-16 implementations

🔧 Improvements

  • Architecture Refactoring: Moved dialect-specific logic to dialect implementations (Open/Closed Principle)
  • MSSQL Driver Standardization: Removed mssql alias, use only sqlsrv everywhere
  • Dialect-Specific DDL Query Builders: Full support for MySQL, PostgreSQL, MSSQL, and SQLite specific types
  • Bash Completion Script: Tab completion for all pdodb CLI commands
  • CLI Version Auto-Detection: Automatically detects version from git tags

🐛 Bug Fixes

  • Fixed Redis connection error handling in CacheFactory
  • Fixed MSSQL monitoring example in GitHub Actions
  • Fixed configuration parameter normalization (database vs dbname)
  • Fixed duplicate default values in CLI prompts

📊 Quality Metrics

  • All tests passing: 2491 tests, 8468 assertions across all dialects
  • Code quality: PHPStan level 9, PHP-CS-Fixer compliant
  • Backward compatibility: 100% maintained (except removed mssql alias)

📚 Documentation

  • Updated README with pdodb init as the fastest way to start
  • Updated examples to use sqlsrv instead of mssql
  • Added comprehensive changelog entry

🔗 Links


Installation:

composer require tommyknocker/pdodb

Quick Start:

vendor/bin/pdodb init

v2.10.2

18 Nov 14:37

Choose a tag to compare

Release v2.10.2

Release Date: November 18, 2025

🎉 Major Features

Database Dump and Restore

Complete database backup and restore functionality with cross-dialect support:

  • Full database or table-specific dumps
  • Schema-only and data-only modes
  • Automatic DROP TABLE IF EXISTS (configurable)
  • Restore from SQL dump files with confirmation prompts

Table Management

Comprehensive table operations via CLI:

  • Create, drop, rename, truncate tables
  • Column management (add, alter, drop)
  • Index management (list, add, drop)
  • Multiple output formats (table, JSON, YAML)

Database & User Management

Full database and user administration:

  • Database operations (create, drop, list, info)
  • User management with privilege grants/revokes
  • Cross-dialect support (MySQL, MariaDB, PostgreSQL, MSSQL)
  • Interactive prompts for better UX

✨ Enhancements

Query Command

  • explain - Show query execution plans
  • format - Pretty-print SQL queries
  • validate - Validate SQL syntax

Model Generator

  • --force option for overwriting without prompts
  • --namespace option for custom namespaces
  • Better connection handling

Migration Command

  • --dry-run and --pretend options
  • --force option to skip confirmations
  • Improved confirmation prompts

Global CLI Options

  • --help - Show help (global and per-command)
  • --connection=<name> - Select named connection
  • --config=<path> - Custom config file path
  • --env=<path> - Custom .env file path

🔧 Improvements

SQL Formatter

  • Enhanced tokenization and whitespace handling
  • Multi-word keyword recognition
  • Consistent keyword uppercasing
  • Better formatting with proper line breaks

Architecture

  • Dialect classes split into components (SqlFormatter, DmlBuilder, DdlBuilder)
  • Reorganized into subdirectories for better organization
  • Replaced magic strings with QueryConstants class

Error Handling

  • User-friendly error messages instead of fatal errors
  • Typo detection with helpful suggestions
  • Better exception handling throughout CLI

🐛 Bug Fixes

  • Fixed configuration loading order
  • Improved CI/CD environment variable support
  • Fixed MariaDB examples in GitHub Actions
  • Restored MariaDB LAG/LEAD default value handling
  • Fixed CLI prompts display timing
  • Improved table listing robustness

📊 Quality Metrics

  • Tests: 2390 tests, 8016 assertions
  • Coverage: Increased CLI integration test coverage
  • Code Quality: PHPStan level 8, PSR-12 compliant
  • Compatibility: 100% backward compatible

📚 Documentation

All new features are fully documented in:

  • CLI Tools documentation
  • README.md
  • Inline code documentation

Full Changelog: v2.10.1...v2.10.2

v2.10.1

11 Nov 09:47

Choose a tag to compare

🚀 PDOdb v2.10.1 - CLI Tools & Enhanced Developer Experience

We're excited to announce v2.10.1, a release focused on developer productivity with a complete command-line interface and enhanced documentation!

🎯 What's New

✨ CLI Tools - Unified Command Structure

PDOdb now includes a comprehensive CLI toolkit accessible via vendor/bin/pdodb:

📦 Migration Management (pdodb migrate)

pdodb migrate create create_users_table  # Generate new migration
pdodb migrate up                         # Apply pending migrations
pdodb migrate down                       # Rollback last migration
pdodb migrate to 20251101120000         # Migrate to specific version
pdodb migrate history                    # View migration history
pdodb migrate new                        # List pending migrations

🏗️ Model Generator (pdodb model make)

Auto-generate ActiveRecord models from existing database tables:

pdodb model make User                    # Auto-detect table name
pdodb model make User users              # Specify table name
pdodb model make User users app/Models   # Custom output path

Features:

  • Automatic table name detection from model name
  • Primary key and foreign key detection
  • Relationship definitions generation
  • Type-aware attribute generation

🔍 Schema Inspector (pdodb schema inspect)

Inspect your database structure with multiple output formats:

pdodb schema inspect                     # List all tables
pdodb schema inspect users               # Detailed table info
pdodb schema inspect users --format=json # JSON output
pdodb schema inspect users --format=yaml # YAML output

🧪 Interactive Query Tester (pdodb query test)

REPL for testing SQL queries interactively:

pdodb query test                         # Interactive mode
pdodb query test "SELECT * FROM users"   # Single query

📚 Enhanced Developer Experience

PHPDoc Improvements

Comprehensive inline documentation with examples, warnings, and best practices:

  • @example tags with usage examples for 10+ key methods
  • @warning tags for dialect-specific differences
  • @note tags for additional context
  • @see tags linking to full documentation

Enhanced documentation for:

  • insertFrom(), merge(), getColumn(), paginate()
  • withRecursive(), createIndex(), groupBy()
  • case(), relations(), and more

Migration System Improvements

  • Automatic project root detection
  • .env file configuration support
  • Better error messages
  • Fixed rollback sequence logic

API Enhancements

  • getColumn('name') - Extract specific column by name
  • Db::as() - Alias helper to reduce Db::raw() usage
  • Db::add() - Addition helper for mathematical operations
  • ColumnSchema::char() - CHAR type support

🔧 Improvements

  • CLI Tools Architecture - Unified Yii2-inspired command structure
  • Code Quality - Test coverage increased from 79.79% to 80.25%
  • Cross-Dialect Compatibility - Better MSSQL reserved word handling
  • Type Safety - Enhanced PHPStan compatibility

🐛 Fixes

  • Fixed migration path resolution for Composer installations
  • Improved identifier quoting in CASE statements for MSSQL
  • Fixed GROUP BY with qualified identifiers and JOIN aliases
  • Corrected migration version detection after rollback

📊 Technical Details

  • All tests passing: 2052+ tests across all dialects
  • CLI Tools: Fully tested with comprehensive coverage
  • PHPStan Level 8: Zero errors maintained
  • PSR-12: All code compliant
  • 100% backward compatible

📖 Documentation

🎉 Get Started

composer require tommyknocker/pdo-database-class:^2.10.1

Then try the CLI tools:

vendor/bin/pdodb --help

Full Changelog: v2.10.0...v2.10.1

v2.10.0

09 Nov 18:39

Choose a tag to compare

🎉 Release v2.10.0 - MSSQL Support & Architecture Improvements

We're excited to announce v2.10.0, a major release that adds full Microsoft SQL Server (MSSQL) support as the fifth database dialect, along with significant architecture improvements and example enhancements.

🚀 What's New

✨ MSSQL (Microsoft SQL Server) Support

PDOdb now supports 5 database dialects: SQLite, MySQL, MariaDB, PostgreSQL, and Microsoft SQL Server!

  • Complete MSSQL dialect implementation with comprehensive SQL Server-specific features
  • 732+ new tests across 28 test suites covering all MSSQL functionality
  • GitHub Actions CI integration with dedicated MSSQL testing job
  • All 64 examples now work perfectly on MSSQL (64/64 passing ✅)
  • Custom REGEXP support using PATINDEX for pattern matching
  • Cross-dialect compatibility - all helper functions work consistently across all five dialects

MSSQL-Specific Features

  • LATERAL JOIN → Automatic conversion to CROSS APPLY/OUTER APPLY
  • MERGE statements → Native UPSERT operations
  • Window functions → Full SQL Server window function support
  • JSON operations → Complete JSON support using SQL Server JSON functions
  • Type casting → Safe type conversion using TRY_CAST
  • String functions → Dialect-specific implementations (LEN vs LENGTH, CEILING vs CEIL)
  • Boolean typesBIT type with proper 0/1 handling
  • Identity columnsIDENTITY(1,1) support for auto-incrementing keys

🏗️ Architecture Improvements

Major Refactoring Following SOLID Principles

We've moved all dialect-specific logic from general classes into dialect implementations, following the Open/Closed Principle:

  • 20+ new DialectInterface methods for better abstraction:

    • formatLateralJoin(), needsColumnQualificationInUpdateSet()
    • executeExplainAnalyze(), getBooleanType(), getTimestampType()
    • isNoFieldsError(), appendLimitOffset()
    • formatGreatest(), formatLeast(), buildDropTableIfExistsSql()
    • And many more...
  • No more dialect checks in general classes - No more if ($driver === 'sqlsrv') scattered throughout the codebase

  • Better separation of concerns - Each dialect handles its own specific requirements

📚 Example Improvements

  • Refactored examples - Removed Db::raw() calls with dialect-specific SQL
  • Library helpers usage - Examples now use library helpers exclusively (Db::length(), Db::position(), Db::greatest(), etc.)
  • Schema Builder usage - Examples use Schema Builder for DDL operations where possible
  • Better educational value - Examples demonstrate proper library usage patterns

🐛 Bug Fixes

  • PostgreSQL - Fixed DROP TABLE CASCADE for foreign key constraints
  • MSSQL - Fixed type compatibility issues in GREATEST/LEAST functions
  • MSSQL - Proper boolean handling (TRUE/FALSE → 1/0 for BIT type)
  • MSSQL - Fixed string function conversions (LENGTH → LEN, SUBSTRING syntax)
  • MSSQL - Proper LIMIT/OFFSET syntax (OFFSET ... FETCH NEXT ... ROWS ONLY)
  • MSSQL - Proper error handling for "contains no fields" errors
  • All dialects - All examples now work correctly on all five dialects

📊 Statistics

  • Tests: 2052 tests, 7097 assertions (+732 tests, +2239 assertions from v2.9.3)
  • Examples: 320/320 passing (64 files × 5 dialects)
    • SQLite: 64/64 ✅
    • MySQL: 64/64 ✅
    • MariaDB: 64/64 ✅
    • PostgreSQL: 64/64 ✅
    • MSSQL: 64/64 ✅ (NEW!)

🔄 Migration Guide

No breaking changes! This release maintains 100% backward compatibility. All existing code continues to work without modifications.

🙏 Thank You

Thank you to everyone who contributed to this release! Your feedback and contributions make PDOdb better with every release.


Full Changelog: v2.9.3...v2.10.0

v2.9.3

09 Nov 06:19

Choose a tag to compare

Release v2.9.3

🎉 Major feature release with Regular Expression Helpers, Plugin System, Advanced DML Operations, and significant documentation improvements!

🚀 New Features

Regular Expression Helpers

  • Cross-database regex support with unified API (Db::regexpMatch(), Db::regexpReplace(), Db::regexpExtract())
  • Automatic SQLite registration via PDO::sqliteCreateFunction() if REGEXP extension is not available
  • Configuration option enable_regexp for SQLite (default: true)
  • Full support across MySQL, MariaDB, PostgreSQL, and SQLite

JSON Modification Helpers

  • Db::jsonSet() - Set JSON values at specific paths (supports nested paths)
  • Db::jsonRemove() - Remove JSON keys or array elements
  • Db::jsonReplace() - Replace existing JSON values
  • Proper MariaDB compatibility handling

Plugin System

  • AbstractPlugin class for extending PdoDb functionality
  • PdoDb::registerPlugin() method
  • Support for registering macros, scopes, and event listeners
  • Complete documentation and examples

Advanced DML Operations

  • JOIN Support for UPDATE and DELETE - Update/delete tables based on JOIN conditions
  • INSERT ... SELECT - Bulk insert from query results via QueryBuilder::insertFrom()
  • Cross-dialect support for all operations

Transaction Management

  • Savepoints and Nested Transactions - Advanced transaction control
  • Rollback to specific savepoints without affecting outer transactions

SQLite Enhancements

  • DEFAULT Helper Support - Db::default() now works on SQLite (auto-converted to NULL)
  • String Function Emulation - REPEAT(), REVERSE(), LPAD(), RPAD() automatically registered

Enhanced EXPLAIN Analysis

  • Additional performance metrics
  • Improved query optimization suggestions
  • Enhanced parsing for all dialects

📝 Documentation Improvements

  • Major README overhaul:
    • Reorganized feature list into logical categories
    • Added "Why PDOdb?" section with value proposition
    • Added "5-Minute Tutorial" for quick onboarding
    • Added FAQ section (10 common questions)
    • Added Migration Guide (Raw PDO, Eloquent, Doctrine, Yii2)
    • Simplified Quick Example (basic CRUD with SQLite)
  • Updated Examples section with current structure
  • Replaced chained where() with andWhere() for better clarity

🔧 Changes

  • Examples Directory Reorganization - Improved structure for better navigation
  • Code Quality Improvements - Namespace refactoring, better code organization, PSR-12 compliance

🐛 Fixes

  • Composer Description - Shortened for better Packagist display

📊 Technical Details

  • All tests passing - Comprehensive test coverage including new regex, JSON, and SQLite emulation tests
  • PHPStan Level 8 - Zero errors across entire codebase
  • PHP-CS-Fixer - All code complies with PSR-12 standards
  • 100% backward compatibility - All existing code continues to work
  • All examples verified - Updated and verified on all dialects (MySQL, MariaDB, PostgreSQL, SQLite)

📚 Documentation & Examples

  • Complete documentation for all new features
  • Comprehensive examples in examples/ directory
  • Plugin development guide
  • Transaction management guide with savepoints

🔗 Links


Installation:

composer require tommyknocker/pdo-database-class:^2.9.3

Upgrade from v2.9.2:
No breaking changes - safe to upgrade! 🎉

v2.9.2

06 Nov 03:33

Choose a tag to compare

🚀 Release v2.9.2

This release introduces Sharding support, QueryBuilder Macros, and Enhanced WHERE Condition Methods - three major features that significantly expand the library's capabilities.

✨ What's New

🗄️ Sharding Support

Horizontal partitioning across multiple databases with automatic query routing!

  • Three sharding strategies: Range, Hash, and Modulo
  • Unified connection pool: Reuses existing connections via useConnections()
  • Automatic query routing: Routes queries to the correct shard based on shard key
  • Fluent API: $db->shard('table')->shardKey('id')->strategy('range')->useConnections([...])->register()
// Configure sharding
$db->shard('users')
    ->shardKey('user_id')
    ->strategy('range')
    ->ranges([
        'shard1' => [0, 1000],
        'shard2' => [1001, 2000],
    ])
    ->useConnections(['shard1', 'shard2'])
    ->register();

// Automatic routing - queries go to correct shard
$user = $db->find()
    ->from('users')
    ->where('user_id', 500)
    ->getOne(); // Automatically routed to shard1

📚 Documentation | 📖 Examples

🔧 QueryBuilder Macros

Extend QueryBuilder with your own custom methods!

// Register a macro
QueryBuilder::macro('activeUsers', function() {
    return $this->where('status', 'active')
                ->where('deleted_at', null);
});

// Use it anywhere
$activeUsers = $db->find()
    ->from('users')
    ->activeUsers()
    ->get();

📚 Documentation | 📖 Examples

🎯 Enhanced WHERE Condition Methods

27 new fluent methods for common WHERE patterns - no more helper functions needed!

// Null checks
->whereNull('deleted_at')
->whereNotNull('email')

// Range checks
->whereBetween('age', 18, 65)
->whereNotBetween('score', 0, 50)

// Column comparisons
->whereColumn('updated_at', '>', 'created_at')

// AND/OR variants for all methods
->andWhereNull('deleted_at')
->orWhereBetween('age', 18, 65)

📚 Documentation

🔄 Improvements

  • Fluent Interface: All interfaces now return static instead of self for better inheritance support
  • Composer Metadata: Updated description and added 17 new keywords for better discoverability
  • Connection Management: Added PdoDb::getConnection() method to retrieve connections from pool

📊 Technical Details

  • All tests passing: Comprehensive test coverage with new sharding, macro, and WHERE condition tests
  • PHPStan Level 8: Zero errors across entire codebase
  • PHP-CS-Fixer: All code complies with PSR-12 standards
  • 100% backward compatible: All existing code continues to work unchanged

📦 Installation

composer require tommyknocker/pdo-database-class:^2.9.2

📚 Resources


Full Changelog: v2.9.1...v2.9.2

v2.9.1

04 Nov 05:10

Choose a tag to compare

Release 2.9.1 - Enhanced Error Diagnostics & ActiveRecord Improvements

Release Date: November 4, 2025

🎉 What's New

This release introduces Enhanced Error Diagnostics (roadmap item 1.1), significant ActiveRecord relationship improvements, and several developer experience enhancements.

✨ Major Features

Enhanced Error Diagnostics

  • QueryDebugger class - Centralized debugging utilities for parameter sanitization and context formatting
  • QueryException enhancements - Now includes queryContext property with complete query builder state
  • Automatic context capture - Query context automatically captured and included in exceptions
  • Parameter sanitization - Sensitive data (passwords, tokens, API keys) automatically masked in error messages
  • Comprehensive documentation - New error-diagnostics.md guide with practical examples

ActiveRecord Relationship Enhancements

  • Many-to-many relationships - New viaTable() and via() methods for junction table relationships
  • Yii2-like syntax - Support for Yii2-style relationship definitions for easier migration
  • Enhanced relationship documentation and examples

QueryBuilder Convenience Methods

  • first() - Get first row from query result
  • last() - Get last row from query result
  • index() - Index query results by a specific column

CLI Migration Tool

  • Yii2-style migration command-line tool
  • Create, run, and rollback migrations via command line
  • Yii2-compatible migration workflow

📚 Documentation Improvements

  • MariaDB configuration examples - Complete setup guide in Getting Started documentation
  • MariaDB connection examples - Step-by-step connection guide in first-connection.md
  • Complete MariaDB setup guide for new users

🔄 Changes

  • Fulltext search helper - Renamed Db::fulltextMatch() to Db::match() for clarity
  • Composer script namespacing - All scripts now use pdodb: prefix
  • PdoDb scope methods - Renamed for better readability

🐛 Fixes

  • Fixed fatal error in LoadBalancerTests by implementing missing setTempQueryContext() method
  • Fixed all PHPStan type errors
  • Resolved all PHP-CS-Fixer code style issues

📊 Technical Details

  • All tests passing - Comprehensive test coverage with improved ActiveQuery, EagerLoader, and CacheManager tests
  • PHPStan Level 8 - Zero errors across entire codebase
  • PHP-CS-Fixer - All code complies with PSR-12 standards
  • 100% backward compatible - All existing code continues to work
  • Code quality - Follows KISS, SOLID, DRY, YAGNI principles

📖 Documentation

🔗 Links

📦 Installation

composer require tommyknocker/pdo-database-class:^2.9.1

Thank you for using PDOdb! 🚀