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
Table of Contents
Properties
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
$logtext
public
string
$logtext
= ''
$db
protected
PDO
$db
$dryRun
protected
bool
$dryRun
= false
$logFile
protected
string|null
$logFile
= null
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
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
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
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:
- Validates file existence and readability
- Reads entire file content into memory
- Parses SQL using smartSplit() method
- Executes each statement individually
- Logs all operations with detailed status
- 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
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
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
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
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
Return values
bool —True if the quote is escaped, false otherwise