Skip to content

Latest commit

 

History

History
832 lines (657 loc) · 23.2 KB

File metadata and controls

832 lines (657 loc) · 23.2 KB

Configuration

Database connection configuration for MySQL, MariaDB, PostgreSQL, SQLite, Microsoft SQL Server (MSSQL), and Oracle Database.

MySQL Configuration

Basic Configuration

use tommyknocker\pdodb\PdoDb;

$db = new PdoDb('mysql', [
    'host' => '127.0.0.1',
    'username' => 'testuser',
    'password' => 'testpass',
    'dbname' => 'testdb'
]);

Full Configuration Options

$db = new PdoDb('mysql', [
    // Connection options
    'pdo'         => null,                 // Optional: Existing PDO object
    'host'        => '127.0.0.1',          // Required: MySQL host
    'username'    => 'testuser',           // Required: MySQL username
    'password'    => 'testpass',           // Required: MySQL password
    'dbname'      => 'testdb',             // Required: Database name
    'port'        => 3306,                 // Optional: MySQL port (default: 3306)
    'prefix'      => 'my_',                // Optional: Table prefix (e.g. 'wp_')
    'charset'     => 'utf8mb4',            // Optional: Connection charset
    
    // Advanced options
    'unix_socket' => '/var/run/mysqld/mysqld.sock', // Optional: Unix socket path
    'sslca'       => '/path/ca.pem',       // Optional: SSL CA certificate
    'sslcert'     => '/path/client-cert.pem', // Optional: SSL client certificate
    'sslkey'      => '/path/client-key.pem',  // Optional: SSL client key
    'compress'    => true                  // Optional: Enable protocol compression
]);

Using Existing PDO Connection

$pdo = new PDO(
    'mysql:host=localhost;dbname=testdb',
    'user',
    'pass'
);

$db = new PdoDb('mysql', [
    'pdo' => $pdo,
    'prefix' => 'wp_'
]);

MariaDB Configuration

MariaDB uses the same driver as MySQL ('mysql') and shares the same configuration options. MariaDB is fully supported as a separate dialect with optimized SQL generation.

Basic Configuration

use tommyknocker\pdodb\PdoDb;

$db = new PdoDb('mysql', [
    'host' => '127.0.0.1',
    'username' => 'testuser',
    'password' => 'testpass',
    'dbname' => 'testdb'
]);

Full Configuration Options

$db = new PdoDb('mysql', [
    // Connection options
    'pdo'         => null,                 // Optional: Existing PDO object
    'host'        => '127.0.0.1',          // Required: MariaDB host
    'username'    => 'testuser',           // Required: MariaDB username
    'password'    => 'testpass',           // Required: MariaDB password
    'dbname'      => 'testdb',             // Required: Database name
    'port'        => 3306,                 // Optional: MariaDB port (default: 3306)
    'prefix'      => 'my_',                // Optional: Table prefix (e.g. 'wp_')
    'charset'     => 'utf8mb4',            // Optional: Connection charset
    
    // Advanced options
    'unix_socket' => '/var/run/mysqld/mysqld.sock', // Optional: Unix socket path
    'sslca'       => '/path/ca.pem',       // Optional: SSL CA certificate
    'sslcert'     => '/path/client-cert.pem', // Optional: SSL client certificate
    'sslkey'      => '/path/client-key.pem',  // Optional: SSL client key
    'compress'    => true                  // Optional: Enable protocol compression
]);

Using Existing PDO Connection

$pdo = new PDO(
    'mysql:host=localhost;dbname=testdb',
    'user',
    'pass'
);

$db = new PdoDb('mysql', [
    'pdo' => $pdo,
    'prefix' => 'app_'
]);

Note: MariaDB uses the same driver name ('mysql') as MySQL, but PDOdb automatically detects MariaDB and uses the MariaDB dialect for optimized SQL generation.

PostgreSQL Configuration

Basic Configuration

use tommyknocker\pdodb\PdoDb;

$db = new PdoDb('pgsql', [
    'host' => '127.0.0.1',
    'username' => 'testuser',
    'password' => 'testpass',
    'dbname' => 'testdb'
]);

Full Configuration Options

$db = new PdoDb('pgsql', [
    // Connection options
    'pdo'              => null,            // Optional: Existing PDO object
    'host'             => '127.0.0.1',     // Required: PostgreSQL host
    'username'         => 'testuser',      // Required: PostgreSQL username
    'password'         => 'testpass',       // Required: PostgreSQL password
    'dbname'           => 'testdb',        // Required: Database name
    'port'             => 5432,            // Optional: PostgreSQL port (default: 5432)
    'prefix'           => 'pg_',           // Optional: Table prefix
    
    // Advanced options
    'options'          => '--client_encoding=UTF8', // Optional: Extra options
    'sslmode'          => 'require',       // Optional: SSL mode (disable, allow, prefer, require, verify-ca, verify-full)
    'sslkey'           => '/path/client.key',   // Optional: SSL private key
    'sslcert'          => '/path/client.crt',   // Optional: SSL client certificate
    'sslrootcert'      => '/path/ca.crt',       // Optional: SSL root certificate
    'application_name' => 'MyApp',         // Optional: Application name (visible in pg_stat_activity)
    'connect_timeout'  => 5,               // Optional: Connection timeout in seconds
    'hostaddr'         => '192.168.1.10',  // Optional: Direct IP address (bypasses DNS)
    'service'          => 'myservice',     // Optional: Service name from pg_service.conf
    'target_session_attrs' => 'read-write' // Optional: For clusters (any, read-write)
]);

SQLite Configuration

Basic Configuration

use tommyknocker\pdodb\PdoDb;

// In-memory database
$db = new PdoDb('sqlite', [
    'path' => ':memory:'
]);

// File-based database
$db = new PdoDb('sqlite', [
    'path' => '/path/to/database.sqlite'
]);

Full Configuration Options

$db = new PdoDb('sqlite', [
    // Connection options
    'pdo'         => null,                       // Optional: Existing PDO object
    'path'        => '/path/to/database.sqlite', // Required: Path to SQLite file
                                                 // Use ':memory:' for in-memory database
    'prefix'      => 'sq_',                      // Optional: Table prefix
    'mode'        => 'rwc',                      // Optional: Open mode (ro, rw, rwc, memory)
    'cache'       => 'shared',                   // Optional: Cache mode (shared, private)
    'enable_regexp' => true                     // Optional: Enable REGEXP functions (default: true)
                                                 // Automatically registers REGEXP, regexp_replace, regexp_extract
]);

SQLite Open Modes

  • ro - Read-only access
  • rw - Read/write access
  • rwc - Read/write/create if not exists (default)
  • memory - In-memory database

PDO Options

You can pass additional PDO options when creating a connection:

use tommyknocker\pdodb\PdoDb;

$pdoOptions = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false,
];

$db = new PdoDb('mysql', [
    'host' => 'localhost',
    'username' => 'user',
    'password' => 'pass',
    'dbname' => 'testdb'
], $pdoOptions);

Recommended PDO Options

$pdoOptions = [
    // Error handling
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    
    // Fetch mode
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    
    // Disable emulated prepares for better performance and security
    PDO::ATTR_EMULATE_PREPARES => false,
    
    // Use persistent connections (optional, be careful with this)
    // PDO::ATTR_PERSISTENT => true,
    
    // Connection timeout (MySQL only)
    // PDO::ATTR_TIMEOUT => 5
];

$db = new PdoDb('mysql', $config, $pdoOptions);

Prepared Statement Pool

Enable automatic prepared statement caching for better performance:

use tommyknocker\pdodb\PdoDb;

$db = new PdoDb('mysql', [
    'host' => 'localhost',
    'username' => 'user',
    'password' => 'pass',
    'dbname' => 'mydb',
    'stmt_pool' => [
        'enabled' => true,      // Enable statement pooling
        'capacity' => 256       // Maximum cached statements (default: 256)
    ]
]);

See: Connection Management - Prepared Statement Pool for detailed documentation.

Connection Pooling

You can manage multiple database connections:

use tommyknocker\pdodb\PdoDb;

// Initialize without a default connection
$db = new PdoDb();

// Add MySQL connection
$db->addConnection('mysql_main', [
    'driver' => 'mysql',
    'host' => 'mysql.server.com',
    'username' => 'user',
    'password' => 'pass',
    'dbname' => 'main_db'
]);

// Add PostgreSQL connection
$db->addConnection('pgsql_analytics', [
    'driver' => 'pgsql',
    'host' => 'postgres.server.com',
    'username' => 'analyst',
    'password' => 'pass',
    'dbname' => 'analytics'
]);

// Switch between connections
$users = $db->connection('mysql_main')->find()->from('users')->get();
$stats = $db->connection('pgsql_analytics')->find()->from('stats')->get();

Using .env Files

PDOdb supports loading configuration from .env files using the PdoDb::fromEnv() static method. This provides a convenient way to manage database configuration without hardcoding credentials.

Basic Usage

Create a .env file in your project root:

PDODB_DRIVER=mysql
PDODB_HOST=localhost
PDODB_PORT=3306
PDODB_DATABASE=testdb
PDODB_USERNAME=testuser
PDODB_PASSWORD=testpass
PDODB_CHARSET=utf8mb4

Then load the configuration:

use tommyknocker\pdodb\PdoDb;

// Load from .env file in current directory
$db = PdoDb::fromEnv();

// Or specify a custom .env file path
$db = PdoDb::fromEnv('/path/to/.env.local');

Environment Variables

The following environment variables are supported in .env files:

Variable Required Description Example
PDODB_DRIVER Yes Database driver name mysql, pgsql, sqlite, sqlsrv, oci
PDODB_HOST Yes* Database host localhost, 127.0.0.1
PDODB_PORT No Database port 3306, 5432, 1433, 1521
PDODB_DATABASE Yes* Database name testdb, mydb
PDODB_USERNAME Yes* Database username testuser, root
PDODB_PASSWORD No Database password secret123
PDODB_CHARSET No Connection charset utf8mb4, UTF8
PDODB_PATH Yes* SQLite database path :memory:, /path/to/db.sqlite

* Required for most databases, except SQLite which only requires PDODB_DRIVER and PDODB_PATH.

.env File Format

The .env file supports:

  • Key-value pairs: KEY=value
  • Comments: Lines starting with # are ignored
  • Quoted values: Both single and double quotes are supported and automatically removed
  • Empty lines: Ignored

Example .env file:

# Database Configuration
PDODB_DRIVER=mysql
PDODB_HOST=localhost
PDODB_PORT=3306
PDODB_DATABASE=testdb

# Credentials
PDODB_USERNAME=testuser
PDODB_PASSWORD="secret123"
PDODB_CHARSET=utf8mb4

Custom .env File Path

You can specify a custom path to the .env file:

$db = PdoDb::fromEnv('/path/to/.env.production');

Or set the PDODB_ENV_PATH environment variable:

export PDODB_ENV_PATH=/path/to/.env.production
php your-script.php

With PDO Options, Logger, and Cache

You can pass additional options to fromEnv():

use Psr\Log\NullLogger;
use tommyknocker\pdodb\cache\CacheFactory;

$pdoOptions = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
];

$logger = new NullLogger();
$cache = CacheFactory::create(['type' => 'array', 'enabled' => true]);

$db = PdoDb::fromEnv(
    null,           // Use default .env path
    $pdoOptions,    // PDO options
    $logger,        // Logger instance
    $cache          // Cache instance
);

Error Handling

If PDODB_DRIVER is not set in the .env file, fromEnv() will throw an InvalidArgumentException:

try {
    $db = PdoDb::fromEnv();
} catch (InvalidArgumentException $e) {
    echo "Error: " . $e->getMessage();
    // Error: PDODB_DRIVER not set in .env file
}

For non-SQLite databases, if required variables (PDODB_DATABASE, PDODB_USERNAME) are missing, an exception will be thrown:

try {
    $db = PdoDb::fromEnv();
} catch (InvalidArgumentException $e) {
    echo "Error: " . $e->getMessage();
    // Error: PDODB_DATABASE and PDODB_USERNAME must be set in .env file for driver: mysql
}

Environment-Based Configuration (Alternative)

You can also use environment variables directly without .env files:

// config.php
return [
    'host' => getenv('DB_HOST') ?: 'localhost',
    'username' => getenv('DB_USERNAME') ?: 'root',
    'password' => getenv('DB_PASSWORD') ?: '',
    'dbname' => getenv('DB_NAME') ?: 'testdb',
    'charset' => getenv('DB_CHARSET') ?: 'utf8mb4'
];

// Usage
$db = new PdoDb('mysql', require 'config.php');

SSL/TLS Configuration

MySQL SSL

$db = new PdoDb('mysql', [
    'host' => 'mysql.example.com',
    'username' => 'user',
    'password' => 'pass',
    'dbname' => 'mydb',
    'sslcert' => '/path/to/client-cert.pem',
    'sslkey' => '/path/to/client-key.pem',
    'sslca' => '/path/to/ca.pem'
]);

PostgreSQL SSL

$db = new PdoDb('pgsql', [
    'host' => 'postgres.example.com',
    'username' => 'user',
    'password' => 'pass',
    'dbname' => 'mydb',
    'sslmode' => 'require',
    'sslcert' => '/path/to/client.crt',
    'sslkey' => '/path/to/client.key',
    'sslrootcert' => '/path/to/ca.crt'
]);

Microsoft SQL Server (MSSQL) Configuration

Basic Configuration

use tommyknocker\pdodb\PdoDb;

$db = new PdoDb('sqlsrv', [
    'host' => 'localhost',
    'username' => 'testuser',
    'password' => 'testpass',
    'dbname' => 'testdb'
]);

Full Configuration Options

$db = new PdoDb('sqlsrv', [
    // Connection options
    'pdo'                    => null,            // Optional: Existing PDO object
    'host'                   => 'localhost',     // Required: SQL Server host
    'username'               => 'testuser',      // Required: SQL Server username
    'password'               => 'testpass',      // Required: SQL Server password
    'dbname'                 => 'testdb',        // Required: Database name
    'port'                   => 1433,            // Optional: SQL Server port (default: 1433)
    'prefix'                 => 'mssql_',        // Optional: Table prefix
    
    // SSL/TLS options
    'trust_server_certificate' => true,          // Optional: Trust server certificate (default: true)
                                                  // Set to false for production with valid certificates
    'encrypt'                => true,            // Optional: Enable encryption (default: true)
]);

Using Existing PDO Connection

$pdo = new PDO(
    'sqlsrv:Server=localhost,1433;Database=testdb;TrustServerCertificate=yes;Encrypt=yes',
    'user',
    'pass'
);

$db = new PdoDb('sqlsrv', [
    'pdo' => $pdo,
    'prefix' => 'app_'
]);

MSSQL SSL Configuration

For self-signed certificates (development/testing):

$db = new PdoDb('sqlsrv', [
    'host' => 'localhost',
    'username' => 'user',
    'password' => 'pass',
    'dbname' => 'mydb',
    'trust_server_certificate' => true,  // Trust self-signed certificates
    'encrypt' => true                     // Enable encryption
]);

For production with valid certificates:

$db = new PdoDb('sqlsrv', [
    'host' => 'sqlserver.example.com',
    'username' => 'user',
    'password' => 'pass',
    'dbname' => 'mydb',
    'trust_server_certificate' => false,  // Require valid certificate
    'encrypt' => true                     // Enable encryption
]);

Note: MSSQL uses the sqlsrv driver name. The Microsoft ODBC Driver for SQL Server must be installed, and the PHP sqlsrv extension must be enabled.

Oracle Database Configuration

Basic Configuration

use tommyknocker\pdodb\PdoDb;

$db = new PdoDb('oci', [
    'host' => 'localhost',
    'port' => 1521,
    'username' => 'testuser',
    'password' => 'testpass',
    'service_name' => 'XEPDB1', // Oracle service name (or use 'sid' for SID)
    'charset' => 'UTF8'
]);

Full Configuration Options

$db = new PdoDb('oci', [
    // Connection options
    'pdo'          => null,            // Optional: Existing PDO object
    'host'         => 'localhost',     // Required: Oracle host
    'port'         => 1521,            // Optional: Oracle port (default: 1521)
    'username'     => 'testuser',      // Required: Oracle username
    'password'     => 'testpass',       // Required: Oracle password
    'service_name' => 'XEPDB1',        // Required: Oracle service name (preferred)
    // OR use 'sid' instead of 'service_name' for SID-based connections
    'sid'          => 'XE',            // Optional: Oracle SID (alternative to service_name)
    'dbname'       => 'XEPDB1',        // Optional: Fallback to dbname if service_name/sid not provided
    'prefix'       => 'app_',          // Optional: Table prefix
    'charset'      => 'UTF8',          // Optional: Connection charset (default: UTF8)
]);

Using Service Name (Recommended)

Oracle 12c+ uses service names for Pluggable Databases (PDBs):

$db = new PdoDb('oci', [
    'host' => 'localhost',
    'port' => 1521,
    'username' => 'testuser',
    'password' => 'testpass',
    'service_name' => 'XEPDB1' // Pluggable Database service name
]);

Using SID (Legacy)

For older Oracle installations or non-CDB databases:

$db = new PdoDb('oci', [
    'host' => 'localhost',
    'port' => 1521,
    'username' => 'testuser',
    'password' => 'testpass',
    'sid' => 'XE' // Oracle SID
]);

Using Existing PDO Connection

$pdo = new PDO(
    'oci:dbname=//localhost:1521/XEPDB1',
    'user',
    'pass'
);

$db = new PdoDb('oci', [
    'pdo' => $pdo,
    'prefix' => 'app_'
]);

Environment Variables

Oracle configuration via environment variables:

export PDODB_DRIVER=oci
export PDODB_HOST=localhost
export PDODB_PORT=1521
export PDODB_USERNAME=testuser
export PDODB_PASSWORD=testpass
export PDODB_SERVICE_NAME=XEPDB1
export PDODB_CHARSET=UTF8
export PDODB_PREFIX=app_

Note: Oracle uses the oci driver name. The PHP pdo_oci extension must be installed and enabled. Oracle Database 12c+ is recommended for full feature support (JSON operations, LATERAL JOINs, etc.).

Environment Variables Reference

All database dialects support configuration via .env file or environment variables. The following variables are available:

Common Variables (All Dialects)

Variable Description Required Default
PDODB_DRIVER Database driver (mysql, mariadb, pgsql, sqlite, sqlsrv, oci) Yes -
PDODB_HOST Database host Yes* localhost
PDODB_PORT Database port No Driver default
PDODB_DATABASE Database name Yes* -
PDODB_USERNAME Database username Yes* -
PDODB_PASSWORD Database password Yes* -
PDODB_CHARSET Connection charset No Driver default
PDODB_PREFIX Table prefix No Empty

* Not required for SQLite

MySQL/MariaDB Specific Variables

Variable Description Type Default
PDODB_UNIX_SOCKET Unix socket path String -
PDODB_SSLCA SSL CA certificate path String -
PDODB_SSLCERT SSL client certificate path String -
PDODB_SSLKEY SSL client key path String -
PDODB_COMPRESS Enable protocol compression Boolean false

Example:

PDODB_DRIVER=mysql
PDODB_HOST=localhost
PDODB_DATABASE=mydb
PDODB_USERNAME=user
PDODB_PASSWORD=pass
PDODB_PREFIX=wp_
PDODB_UNIX_SOCKET=/var/run/mysqld/mysqld.sock
PDODB_SSLCA=/path/ca.pem
PDODB_SSLCERT=/path/client-cert.pem
PDODB_SSLKEY=/path/client-key.pem
PDODB_COMPRESS=true

PostgreSQL Specific Variables

Variable Description Type Default
PDODB_SSLMODE SSL mode (disable, allow, prefer, require, verify-ca, verify-full) String -
PDODB_SSLKEY SSL private key path String -
PDODB_SSLCERT SSL client certificate path String -
PDODB_SSLROOTCERT SSL root certificate path String -
PDODB_APPLICATION_NAME Application name (visible in pg_stat_activity) String -
PDODB_CONNECT_TIMEOUT Connection timeout in seconds Integer -
PDODB_HOSTADDR Direct IP address (bypasses DNS) String -
PDODB_SERVICE Service name from pg_service.conf String -
PDODB_TARGET_SESSION_ATTRS Target session attributes (any, read-write) String -
PDODB_OPTIONS Extra connection options String -

Example:

PDODB_DRIVER=pgsql
PDODB_HOST=localhost
PDODB_DATABASE=mydb
PDODB_USERNAME=user
PDODB_PASSWORD=pass
PDODB_PREFIX=app_
PDODB_SSLMODE=require
PDODB_SSLCERT=/path/client.crt
PDODB_SSLKEY=/path/client.key
PDODB_SSLROOTCERT=/path/ca.crt
PDODB_APPLICATION_NAME=MyApp
PDODB_CONNECT_TIMEOUT=5

SQLite Specific Variables

Variable Description Type Default
PDODB_PATH Path to SQLite file (use :memory: for in-memory) String ./database.sqlite
PDODB_MODE Open mode (ro, rw, rwc, memory) String rwc
PDODB_CACHE Cache mode (shared, private) String -
PDODB_ENABLE_REGEXP Enable REGEXP functions Boolean true

Example:

PDODB_DRIVER=sqlite
PDODB_PATH=:memory:
PDODB_PREFIX=test_
PDODB_MODE=rwc
PDODB_CACHE=shared
PDODB_ENABLE_REGEXP=true

MSSQL Specific Variables

Variable Description Type Default
PDODB_TRUST_SERVER_CERTIFICATE Trust server certificate Boolean true
PDODB_ENCRYPT Enable encryption Boolean true

Example:

PDODB_DRIVER=sqlsrv
PDODB_HOST=localhost
PDODB_DATABASE=mydb
PDODB_USERNAME=user
PDODB_PASSWORD=pass
PDODB_PREFIX=mssql_
PDODB_TRUST_SERVER_CERTIFICATE=true
PDODB_ENCRYPT=true

Oracle Specific Variables

Variable Description Type Default
PDODB_SERVICE_NAME Oracle service name (preferred for 12c+) String -
PDODB_SID Oracle SID (alternative to service_name) String -

Note: Use PDODB_SERVICE_NAME for Oracle 12c+ Pluggable Databases (PDBs), or PDODB_SID for older installations.

Example:

PDODB_DRIVER=oci
PDODB_HOST=localhost
PDODB_PORT=1521
PDODB_USERNAME=testuser
PDODB_PASSWORD=testpass
PDODB_SERVICE_NAME=XEPDB1
PDODB_CHARSET=UTF8
PDODB_PREFIX=app_

Using .env File

Create a .env file in your project root:

# .env
PDODB_DRIVER=mysql
PDODB_HOST=localhost
PDODB_DATABASE=mydb
PDODB_USERNAME=user
PDODB_PASSWORD=pass
PDODB_PREFIX=app_
PDODB_CHARSET=utf8mb4

Then use PdoDb::fromEnv():

use tommyknocker\pdodb\PdoDb;

// Load from .env file in current directory
$db = PdoDb::fromEnv();

// Or specify custom path
$db = PdoDb::fromEnv('/path/to/.env.local');

Boolean Values

Boolean environment variables accept the following values:

  • true, 1, yes, ontrue
  • false, 0, no, offfalse

Examples:

PDODB_COMPRESS=true
PDODB_ENABLE_REGEXP=1
PDODB_TRUST_SERVER_CERTIFICATE=yes
PDODB_ENCRYPT=false

Next Steps