StellarWP DB is a WordPress database wrapper and query builder library that provides a fluent interface for constructing and executing database queries. It's built on top of WordPress's $wpdb global and adds a modern, chainable API with proper error handling.
Key Features:
- Fluent query builder interface
- SQL injection protection via WordPress's prepared statements
- Support for complex queries (joins, unions, subqueries, etc.)
- Meta table abstractions for WordPress-style data
- Error handling with exceptions
- Full compatibility with
$wpdbmethods
-
DB (
src/DB/DB.php)- Static facade/decorator for
$wpdb - Entry point for creating query builders via
DB::table() - Provides static methods that wrap
$wpdbmethods with error checking - Throws
DatabaseQueryExceptionon SQL errors
- Static facade/decorator for
-
QueryBuilder (
src/DB/QueryBuilder/QueryBuilder.php)- Main query building class
- Uses traits to organize functionality:
Aggregate- COUNT, SUM, AVG, MIN, MAX operationsCRUD- INSERT, UPDATE, DELETE, UPSERT operationsFromClause- FROM table handlingWhereClause- WHERE conditionsJoinClause- JOIN operationsSelectStatement- SELECT column handlingMetaQuery- WordPress meta table helpers- And more...
-
Config (
src/DB/Config.php)- Configuration management
- Allows setting custom exception classes
- Hook prefix configuration for WordPress integration
/home/matt/git/db/
├── src/DB/ # Main source code
│ ├── Config.php # Configuration class
│ ├── DB.php # Main DB facade
│ ├── Database/ # Database-specific classes
│ │ ├── Actions/ # Database actions (e.g., EnableBigSqlSelects)
│ │ ├── Exceptions/ # Custom exceptions
│ │ └── Provider.php # Service provider
│ └── QueryBuilder/ # Query builder components
│ ├── Clauses/ # SQL clause representations
│ ├── Concerns/ # Traits for QueryBuilder
│ ├── Types/ # Type definitions (JoinType, Operator, etc.)
│ ├── QueryBuilder.php # Main query builder
│ ├── JoinQueryBuilder.php
│ └── WhereQueryBuilder.php
├── tests/ # Test suite
│ ├── wpunit/ # WordPress unit tests
│ └── _support/ # Test support classes
├── .github/workflows/ # GitHub Actions CI/CD
├── composer.json # PHP dependencies
├── phpstan.neon.dist # PHPStan configuration
└── README.md # Documentation
# Run static analysis with PHPStan
composer test:analysisThe project uses Codeception with WordPress testing framework (wp-browser) and a tool called "slic" for managing the test environment:
# Run tests using slic (see .github/workflows/tests-php.yml)
${SLIC_BIN} run wpunit --ext DotReporterPHPStan is configured at level 5 with WordPress-specific rules:
- Configuration:
phpstan.neon.dist - Includes WordPress stubs via
szepeviktor/phpstan-wordpress - Analyzes only the
src/directory
- Root namespace:
StellarWP\DB - Follow PSR-4 autoloading standard
- Tests use
StellarWP\DB\Testsnamespace
- All table names are automatically prefixed with
$wpdb->prefix - Use
DB::raw()to bypass automatic prefixing - Methods match
$wpdbsignatures where applicable
- SQL errors throw
DatabaseQueryExceptionby default - Custom exception classes can be configured via
Config::setDatabaseQueryException() - All database operations should be wrapped in try-catch blocks in production code
// Basic query
DB::table('posts')
->select('ID', 'post_title')
->where('post_status', 'publish')
->orderBy('post_date', 'DESC')
->limit(10)
->getAll();
// Complex query with joins and meta
DB::table('posts', 'p')
->select(['p.ID', 'id'], ['p.post_title', 'title'])
->attachMeta('postmeta', 'p.ID', 'post_id',
['_thumbnail_id', 'thumbnailId'],
['_custom_field', 'customValue']
)
->leftJoin('term_relationships', 'p.ID', 'tr.object_id', 'tr')
->where('p.post_type', 'post')
->where('p.post_status', 'publish')
->getAll();The library is designed to be included via Strauss for namespace isolation in WordPress plugins. The README examples assume a namespace prefix like Boom\Shakalaka\.
- Requires WordPress with
$wpdbglobal - Compatible with WordPress coding standards
- Follows WordPress database structure conventions (posts, postmeta, etc.)
- Queries are not executed until terminal methods are called (
get(),getAll(),count(), etc.) - Use
attachMeta()for efficient meta queries instead of multiple joins - The library generates SQL using WordPress's
prepare()method for security
- Added
DB::generate_results()andDB::generate_col()for handling large result sets with bounded queries - PHP 8.1 compatibility improvements
- Better type safety in docblocks
-
Tests (
.github/workflows/tests-php.yml)- Runs on every push
- Uses
stellarwp/slicfor test environment setup - Executes wpunit test suite
-
Static Analysis (
.github/workflows/static-analysis.yml)- Runs on every push
- PHP 8.0 environment
- Executes PHPStan via
composer test:analysis
- Create a new trait in
src/DB/QueryBuilder/Concerns/ - Add the trait to the
QueryBuilderclass - Implement the SQL generation method (e.g.,
getYourFeatureSQL()) - Add it to the
getSQL()method if needed - Write tests in
tests/wpunit/QueryBuilder/
// Get the generated SQL without executing
$sql = DB::table('posts')
->where('post_status', 'publish')
->getSQL();
// Use wpdb's last_query after execution
$results = DB::table('posts')->getAll();
$lastQuery = $wpdb->last_query;The library provides special handling for WordPress meta tables:
attachMeta()- Efficiently join and select meta valuesconfigureMetaTable()- Customize meta table column names- Automatic LEFT JOIN generation for each meta key
- Support for multiple meta values with the same key