WorkerSQL PHP SDK
WorkerSQL PHP SDK
Section titled “WorkerSQL PHP SDK”A PHP SDK for WorkerSQL - bringing MySQL-compatible database operations to the edge with Cloudflare Workers.
Features
Section titled “Features”- 🚀 Edge-Native: Run SQL queries at the edge for ultra-low latency
- 🔒 Secure: Built-in SQL injection prevention and schema validation
- 📊 MySQL Compatible: Familiar SQL syntax with MySQL compatibility
- 🔁 Automatic Retries: Exponential backoff retry logic for transient failures
- 📝 PSR-4 Compliant: Modern PHP with autoloading
- 🧪 Well Tested: Comprehensive test coverage with PHPUnit
- 📚 Well Documented: Complete API documentation and examples
Installation
Section titled “Installation”composer require workersql/php-sdk
Quick Start
Section titled “Quick Start”Using DSN String
Section titled “Using DSN String”<?php
require 'vendor/autoload.php';
use WorkerSQL\Client;
// Connect using DSN
// Execute a query$result = $client->query('SELECT * FROM users WHERE id = ?', [1]);print_r($result['data']);
// Close the connection$client->close();
Using Configuration Array
Section titled “Using Configuration Array”<?php
use WorkerSQL\Client;
$client = new Client([ 'host' => 'api.workersql.com', 'port' => 443, 'database' => 'mydb', 'username' => 'myuser', 'password' => 'mypass', 'api_key' => 'your-api-key', 'ssl' => true,]);
// Execute queries$users = $client->query('SELECT * FROM users');print_r($users['data']);
$client->close();
DSN Format
Section titled “DSN Format”The DSN (Data Source Name) follows this format:
workersql://[username[:password]@]host[:port][/database][?param1=value1¶m2=value2]
DSN Parameters
Section titled “DSN Parameters”apiKey
: API authentication keyssl
: Enable/disable SSL (default: true)timeout
: Request timeout in milliseconds (default: 30000)retryAttempts
: Number of retry attempts (default: 3)
DSN Examples
Section titled “DSN Examples”workersql://user:[email protected]/mydb?apiKey=abc123workersql://api.workersql.com/mydb?apiKey=abc123&retryAttempts=5workersql://localhost:8787/test?ssl=false&apiKey=dev-key
Configuration Options
Section titled “Configuration Options”$client = new Client([ // Connection details 'host' => 'api.workersql.com', 'port' => 443, 'username' => 'myuser', 'password' => 'mypass', 'database' => 'mydb',
// API configuration 'api_endpoint' => 'https://api.workersql.com/v1', // Auto-constructed if not provided 'api_key' => 'your-api-key',
// Connection options 'ssl' => true, 'timeout' => 30000, // milliseconds
// Retry configuration 'retry_attempts' => 3, 'retry_delay' => 1.0, // seconds]);
API Reference
Section titled “API Reference”Client
Section titled “Client”query(string $sql, array $params = [], ?array $options = null): array
Section titled “query(string $sql, array $params = [], ?array $options = null): array”Execute a single SQL query.
$result = $client->query( 'SELECT * FROM users WHERE age > ?', [18], ['timeout' => 5000]);
print_r($result['data']); // Query resultsprint_r($result['rowCount']); // Number of rowsprint_r($result['cached']); // Whether result was cached
batchQuery(array $queries, ?array $options = null): array
Section titled “batchQuery(array $queries, ?array $options = null): array”Execute multiple queries in batch.
$results = $client->batchQuery([ ['sql' => 'INSERT INTO users (name, email) VALUES (?, ?)', 'params' => ['John', '[email protected]']], ['sql' => 'INSERT INTO users (name, email) VALUES (?, ?)', 'params' => ['Jane', '[email protected]']]], [ 'transaction' => true, 'stopOnError' => true]);
healthCheck(): array
Section titled “healthCheck(): array”Check service health.
$health = $client->healthCheck();print_r($health['status']); // 'healthy' | 'degraded' | 'unhealthy'
close(): void
Section titled “close(): void”Close the client connection.
$client->close();
Error Handling
Section titled “Error Handling”The SDK provides detailed error information through the ValidationException
class:
use WorkerSQL\Client;use WorkerSQL\ValidationException;
try { $result = $client->query('SELECT * FROM users');} catch (ValidationException $e) { echo 'Error code: ' . $e->getCode() . PHP_EOL; echo 'Error message: ' . $e->getMessage() . PHP_EOL; print_r($e->getDetails());}
Error Codes
Section titled “Error Codes”INVALID_QUERY
: SQL syntax or validation errorCONNECTION_ERROR
: Network or connection failureTIMEOUT_ERROR
: Operation timed outAUTH_ERROR
: Authentication failedPERMISSION_ERROR
: Insufficient permissionsRESOURCE_LIMIT
: Resource limit exceededINTERNAL_ERROR
: Internal server error
Automatic Retries
Section titled “Automatic Retries”The SDK automatically retries failed requests with exponential backoff:
$client = new Client([ 'host' => 'api.workersql.com', 'database' => 'mydb', 'api_key' => 'your-key', 'retry_attempts' => 5, // Retry up to 5 times 'retry_delay' => 1.0 // Start with 1 second delay]);
// Automatically retries on transient errors:// - CONNECTION_ERROR// - TIMEOUT_ERROR// - RESOURCE_LIMIT// - Network errors (connection refused, timeout, etc.)
Prepared Statements
Section titled “Prepared Statements”The SDK uses parameterized queries to prevent SQL injection:
// ✅ Safe - uses prepared statements$result = $client->query( 'SELECT * FROM users WHERE email = ? AND status = ?',);
// ❌ Unsafe - don't concatenate user input// $result = $client->query("SELECT * FROM users WHERE email = '{$userEmail}'");
Examples
Section titled “Examples”Basic CRUD Operations
Section titled “Basic CRUD Operations”// Create$insert = $client->query( 'INSERT INTO users (name, email) VALUES (?, ?)',);print_r($insert['data']);
// Read$users = $client->query('SELECT * FROM users WHERE id = ?', [1]);print_r($users['data'][0]);
// Update
// Delete$client->query('DELETE FROM users WHERE id = ?', [1]);
Batch Operations
Section titled “Batch Operations”$queries = [ ['sql' => 'INSERT INTO logs (message) VALUES (?)', 'params' => ['Log 1']], ['sql' => 'INSERT INTO logs (message) VALUES (?)', 'params' => ['Log 2']], ['sql' => 'INSERT INTO logs (message) VALUES (?)', 'params' => ['Log 3']]];
$results = $client->batchQuery($queries, [ 'transaction' => false, 'stopOnError' => false]);
$successCount = count(array_filter($results['results'], fn($r) => $r['success']));echo "{$successCount} queries succeeded" . PHP_EOL;
Development
Section titled “Development”# Install dependenciescomposer install
# Run testscomposer test
# Run static analysiscomposer phpstan
# Check code stylecomposer cs:check
# Fix code stylecomposer cs:fix
Requirements
Section titled “Requirements”- PHP 7.4 or higher
- ext-json
- Guzzle HTTP client
Contributing
Section titled “Contributing”Contributions are welcome! Please see CONTRIBUTING.md for details.
License
Section titled “License”Apache-2.0 - see LICENSE for details.
Support
Section titled “Support”- Documentation: https://docs.workersql.com
- GitHub Issues: https://github.com/healthfees-org/workersql/issues
- Community Forum: https://community.workersql.com
Changelog
Section titled “Changelog”See CHANGELOG.md for version history and release notes.