Primordyx Framework Documentation

SqlProcessor
in package

Class SqlProcessor

Advanced SQL processor for the Primordyx framework. This class provides robust functionality for parsing and executing SQL from files or strings with comprehensive error handling, dry-run capabilities, and intelligent SQL statement parsing.

Features:

  • Smart SQL parsing that respects quoted strings and comments
  • Dry-run mode for testing without actual execution
  • Comprehensive logging with timestamps
  • Execute SQL from files, wildcards, or strings
  • Event-driven error handling via EventManager

The SQL parser handles:

  • Single-line comments (-- comment)
  • Multi-line comments (/* comment */)
  • Quoted strings with proper escaping
  • Multiple SQL statements separated by semicolons

Usage Examples:

// Simple usage with default connection
$processor = new SqlProcessor();
$processor->run('/app/database/migrations/001_create_users.sql');

// Run multiple files with wildcard
$processor = new SqlProcessor();
$processor->runAll('/app/migrations/*.sql');

// Execute SQL string directly
$sql = "CREATE TABLE users (id INT PRIMARY KEY); CREATE INDEX idx_users ON users(id);";
$processor->runSqlString($sql);

// Custom PDO connection with dry run
$pdo = new PDO($dsn, $user, $pass);
$processor = new SqlProcessor($pdo);
$processor->dryRun(true)
          ->logTo('/tmp/test.log')
          ->run('/app/migrations/test.sql');

// Error handling
$result = $processor->run('/app/migrations/001_create_tables.sql');
if (!$result) {
    // Error was fired via EventManager
    echo "Migration failed - check events\n";
}
Tags
since
1.0.0
see
EventManager

For error event handling

see
ConnectionManager

For database connection handling

Table of Contents

Properties

$logtext  : string
$db  : PDO
$dryRun  : bool
$logFile  : string|null

Methods

__construct()  : mixed
SqlProcessor constructor.
dryRun()  : static
Enables or disables dry run mode.
logTo()  : static
Configures logging output to a specified file.
run()  : bool
Loads and executes SQL statements from a specific file.
runAll()  : bool
Loads and executes all SQL files matching a wildcard pattern.
runSqlString()  : bool
Executes SQL statements from a string.
log()  : void
Internal logging method.
smartSplit()  : array<string|int, mixed>
Parses SQL content into individual executable statements.
isQuoteEscaped()  : bool
Checks if a quote at the given position is escaped by backslashes.

Properties

Methods

__construct()

SqlProcessor constructor.

public __construct([PDO|null $db = null ]) : mixed

Initializes the SqlProcessor with optional PDO connection.

Parameters
$db : PDO|null = null

Optional PDO database connection instance. If null, uses ConnectionManager::getHandle() default connection.

Tags
throws
RuntimeException

If ConnectionManager fails to provide a valid PDO connection

since
2.0.0
example
// Use default connection
$processor = new SqlProcessor();

// Custom PDO connection
$pdo = new PDO($dsn, $user, $pass);
$processor = new SqlProcessor($pdo);

dryRun()

Enables or disables dry run mode.

public dryRun([bool $toggle = true ]) : static

When dry run mode is enabled, SQL statements are parsed, validated, and logged but not actually executed against the database. This is invaluable for testing migration scripts, debugging SQL syntax, or previewing changes before applying them to production databases.

In dry run mode:

  • SQL files are still parsed and validated
  • All statements are logged with [DRY RUN] prefix
  • No actual database modifications occur
  • Syntax errors are still detected and reported
  • Execution flow remains identical to live runs
Parameters
$toggle : bool = true

Set to true to enable dry run mode, false to disable. Default behavior is live execution (false).

Tags
since
1.0.0
example
$processor = new SqlProcessor();

// Test migration before applying
$processor->dryRun(true)
          ->run('/app/migrations/001_create_tables.sql');

// Apply for real
$processor->dryRun(false)
          ->run('/app/migrations/001_create_tables.sql');
Return values
static

Returns self for method chaining

logTo()

Configures logging output to a specified file.

public logTo(string $filePath) : static

When a log file is configured, all SQL processing operations are logged with timestamps, including SQL statements executed, errors encountered, and execution status. This provides an audit trail and debugging information for SQL operations.

The log file is created if it doesn't exist and all entries are appended to preserve execution history.

Log Format:

  • [YYYY-MM-DD HH:MM:SS] Message content
  • Includes file paths, execution status, and SQL content
  • Error logs include file names, line numbers, and details
Parameters
$filePath : string

Full absolute path to the log file. Directory must be writable by the web server. File will be created if it doesn't exist. All log entries are appended (not overwritten).

Tags
since
1.0.0
example
$processor = new SqlProcessor();

// Basic logging
$processor->logTo('/var/log/sql_processor.log');

// Method chaining with timestamped log files
$logFile = '/tmp/sql_' . date('Y-m-d_H-i-s') . '.log';
$processor->logTo($logFile)
          ->dryRun(true)
          ->runAll('/app/migrations/*.sql');
Return values
static

Returns self for method chaining

run()

Loads and executes SQL statements from a specific file.

public run(string $filepath) : bool

This method reads the specified SQL file, parses it into executable statements using intelligent parsing that respects SQL syntax rules, and executes each statement against the database (unless in dry run mode).

Processing Pipeline:

  1. Validates file existence and readability
  2. Reads entire file content into memory
  3. Parses SQL using smartSplit() method
  4. Executes each statement individually
  5. Logs all operations with detailed status
  6. Fires events on errors via EventManager
Parameters
$filepath : string

Absolute path to the SQL file to execute. Must be readable and contain valid SQL statements.

Tags
since
2.0.0
example
$processor = new SqlProcessor();

// Run a single SQL file
$success = $processor->run('/app/migrations/001_create_users.sql');

// Run with dry run and logging
$success = $processor->dryRun(true)
                     ->logTo('/tmp/test.log')
                     ->run('/app/migrations/002_add_indexes.sql');

if (!$success) {
    // Handle error - event was fired
}
Return values
bool

True if execution was successful, false if errors occurred

runAll()

Loads and executes all SQL files matching a wildcard pattern.

public runAll(string $pattern) : bool

Performs batch execution of SQL files matching the provided pattern. Files are processed in alphabetical/lexicographic order, which allows for sequential numbering schemes (001_file.sql, 002_file.sql, etc.) to control execution order.

Parameters
$pattern : string

Wildcard pattern for SQL files (e.g., '/app/migrations/*.sql') Must be an absolute path with wildcard.

Tags
since
2.0.0
example
$processor = new SqlProcessor();

// Run all SQL files in a directory
$success = $processor->runAll('/app/migrations/*.sql');

// Run specific pattern with logging
$success = $processor->logTo('/tmp/batch.log')
                     ->runAll('/app/migrations/2025_*.sql');

// Dry run test
$success = $processor->dryRun(true)
                     ->runAll('/app/migrations/rollback_*.sql');
Return values
bool

True if all files executed successfully, false if any errors occurred

runSqlString()

Executes SQL statements from a string.

public runSqlString(string $sql) : bool

This method takes a string containing SQL statements, parses it using the same intelligent parsing as file-based execution, and executes each statement against the database (unless in dry run mode).

Parameters
$sql : string

SQL statements to execute. Multiple statements should be separated by semicolons.

Tags
since
2.0.0
example
$processor = new SqlProcessor();

// Execute single statement
$sql = "CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(100))";
$success = $processor->runSqlString($sql);

// Execute multiple statements
$sql = "
    CREATE TABLE posts (id INT PRIMARY KEY, title VARCHAR(200));
    CREATE INDEX idx_posts_title ON posts(title);
    INSERT INTO posts (id, title) VALUES (1, 'First Post');
";
$success = $processor->runSqlString($sql);

// Dry run test
$success = $processor->dryRun(true)
                     ->logTo('/tmp/sql_test.log')
                     ->runSqlString($sql);
Return values
bool

True if execution was successful, false if errors occurred

log()

Internal logging method.

protected log(string $message) : void

Handles both file-based logging and internal log text accumulation. All log entries are timestamped for accurate audit trails.

Parameters
$message : string

Message to log

smartSplit()

Parses SQL content into individual executable statements.

protected smartSplit(string $sql) : array<string|int, mixed>

This method intelligently splits SQL content on semicolons while respecting SQL syntax rules for quoted strings and comments. This prevents improper splitting of statements that contain semicolons within string literals or comment blocks.

Parsing Rules:

  • Splits on semicolons not inside quoted strings
  • Ignores content within single-line comments (-- comment)
  • Ignores content within multi-line comments (/* comment */)
  • Respects both single and double quoted strings
  • Handles escaped quotes within strings
  • Handles escaped backslashes
  • Removes empty statements after splitting
Parameters
$sql : string

Raw SQL content to parse

Tags
since
1.0.0
version
2.1.0

Fixed escaped quote handling

Return values
array<string|int, mixed>

List of individual SQL statements ready for execution

isQuoteEscaped()

Checks if a quote at the given position is escaped by backslashes.

private isQuoteEscaped(string $sql, int $quotePos) : bool

This method counts the number of consecutive backslashes immediately before the quote. If there's an odd number of backslashes, the quote is escaped. If there's an even number (including zero), the quote is not escaped.

Examples:

  • 'don't' -> quote at position of ' is escaped (1 backslash = odd)
  • 'path\' -> quote would not be escaped (2 backslashes = even)
  • 'say \' -> quote is escaped (3 backslashes = odd)
Parameters
$sql : string

The full SQL string

$quotePos : int

Position of the quote character to check

Tags
since
2.1.0
Return values
bool

True if the quote is escaped, false otherwise


        
On this page

Search results