Runsqlfile Documentation
Run SQL File Controller Documentation
File: /controllers/runsqlfile.php
Purpose: Executes SQL commands and scripts for database administration and maintenance tasks
Last Updated: December 21, 2024
Total Functions: 1
Lines of Code: ~110
---
๐ Overview
The Run SQL File Controller provides database administration capabilities by allowing direct execution of SQL commands and scripts. It serves as a utility controller for:
- โข Direct SQL command execution
- โข Database maintenance scripts
- โข Schema updates and modifications
- โข Data import/export operations
- โข Administrative database tasks
- โข SQL file processing and validation
- โข Comment filtering and cleanup
- โข Multi-statement execution handling
Primary Functions
- โ Execute raw SQL commands directly on database
- โ Process SQL files with multiple statements
- โ Filter out SQL comments automatically
- โ Handle multi-line SQL scripts
- โ Provide command execution feedback
- โ Support administrative database operations
- โ Safe SQL parsing and validation
- โ Error handling for SQL execution
Related Controllers
- โข Database Maintenance Scripts - Schema updates
- โข Import/Export Controllers - Data migration
- โข Administrative Tools - System maintenance
---
๐๏ธ Database Tables
No Direct Table Operations
This controller operates at the SQL execution level and can interact with any database table depending on the SQL commands provided.
Potential Target Tables
| Category | Tables | Operations | |
|---|---|---|---|
| **Schema Changes** | Any table | CREATE, ALTER, DROP statements | |
| **Data Operations** | Any table | INSERT, UPDATE, DELETE, SELECT | |
| **Index Management** | System tables | CREATE/DROP INDEX statements | |
| **User Management** | User tables | GRANT, REVOKE permissions | |
| **Maintenance** | All tables | OPTIMIZE, REPAIR, ANALYZE |
๐ Key Functions
1. Default Action - SQL Upload Interface
Location: Lines 35-42
Purpose: Display the SQL file upload and execution interface
Process Flow:
1. Check user authentication
2. Display header template
3. Show SQL upload form
4. Set script flag for interface
5. Display footer template
Interface Configuration:
$smarty->display("runsqlfileview/uploadfiles.html");
$smarty->assign("runsqlfilescript", 1);
---
2. run_sql_file() - SQL Command Processor
Location: Lines 73-108
Purpose: Parse and execute SQL commands from user input
Function Signature:
function run_sql_file()
Process Flow:
1. Extract SQL commands from POST data
2. Remove comments and empty lines
3. Split commands by semicolon delimiter
4. Execute each command individually
5. Track success and failure counts
6. Return execution statistics
Comment Removal Logic:
$lines = explode("\n", $commands);
$commands = '';
foreach ($lines as $line) {
$line = trim($line);
if ($line && !strpos($line, '--')) {
$commands .= $line . "\n";
}
}
Command Splitting:
// Convert to array by semicolon delimiter
$commands = explode(";", $commands);
Execution Loop:
$total = $success = 0;
foreach ($commands as $command) {
if (trim($command)) {
$storeExt->run($command);
}
}
Return Statistics:
return array(
"success" => $success,
"total" => $total
);
---
๐ Workflows
Workflow 1: SQL Command Execution
---
๐ URL Routes & Actions
| URL Parameter | Function Called | Description | |
|---|---|---|---|
| `do=` (empty) | Default action | Display SQL upload interface | |
| `do=addfiles` | `run_sql_file()` | Execute SQL commands | |
| `do=sucess` | Success page | Display success confirmation | |
| `do=error` | Error page | Display error message |
SQL Execution (do=addfiles):
- โข
sql- SQL commands string (POST data)
Input Format
SQL Commands:
-- Comments are automatically filtered out
CREATE TABLE test (id INT PRIMARY KEY);
INSERT INTO test (id) VALUES (1);
UPDATE test SET id = 2 WHERE id = 1;
DROP TABLE test;
Multi-line Support:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO users (username, email) VALUES
('admin', 'admin@example.com'),
('user1', 'user1@example.com');
---
๐งฎ Calculation Methods
Comment Detection
// Simple comment detection
if ($line && !strpos($line, '--')) {
// Line is not a comment
}
Command Counting
// Statistics tracking (currently not implemented)
$total = $success = 0;
foreach ($commands as $command) {
if (trim($command)) {
$total++; // Should be incremented
try {
$storeExt->run($command);
$success++; // Should be incremented on success
} catch (Exception $e) {
// Handle error
}
}
}
Command Validation
// Check for non-empty commands
if (trim($command)) {
// Command has content, safe to execute
}
---
๐ Security & Permissions
โ ๏ธ CRITICAL SECURITY WARNING โ ๏ธ
This controller presents EXTREMELY HIGH security risks:
1. Direct SQL Execution: Allows arbitrary SQL command execution
2. No Input Validation: No filtering of dangerous SQL commands
3. Full Database Access: Can access/modify any database table
4. Data Loss Risk: Can execute DROP, DELETE, TRUNCATE commands
5. Privilege Escalation: May allow unauthorized database operations
Authentication Requirements
include_once("../public/authentication.php");
Missing Security Controls
No Command Filtering:
// DANGEROUS: No validation of SQL commands
$commands = $_POST['sql']; // Direct use of user input
No Operation Restrictions:
// MISSING: Should restrict dangerous operations
$allowedOperations = ['SELECT', 'INSERT', 'UPDATE'];
// Should validate against allowed operations
No SQL Injection Protection:
// MISSING: Should sanitize input
// Should use parameterized queries where possible
Recommended Security Improvements
1. Command Whitelist:
function validateSQLCommand($command) {
$dangerous = ['DROP', 'DELETE', 'TRUNCATE', 'ALTER', 'GRANT', 'REVOKE'];
$cmd_upper = strtoupper(trim($command));
foreach ($dangerous as $danger) {
if (strpos($cmd_upper, $danger) === 0) {
throw new Exception("Dangerous command not allowed: $danger");
}
}
}
2. User Permission Checks:
// Should verify user has SQL execution permissions
if (!$_SESSION['user_can_execute_sql']) {
die('Insufficient permissions');
}
3. Audit Logging:
// Should log all SQL executions
logSQLExecution($_SESSION['userid'], $command, $result);
---
๐ Performance Considerations
Database Impact
- โข High Risk: Direct database operations can impact performance
- โข Transaction Control: No automatic transaction wrapping
- โข Resource Usage: Large SQL files may consume significant resources
Memory Usage
- โข String Processing: Large SQL content held in memory
- โข Command Splitting: Creates arrays of commands in memory
Execution Time
- โข No Timeout Control: Long-running SQL may timeout
- โข Sequential Execution: Commands executed one by one
Recommended Improvements
// Add transaction control
$storeExt->beginTransaction();
try {
foreach ($commands as $command) {
$storeExt->run($command);
}
$storeExt->commit();
} catch (Exception $e) {
$storeExt->rollback();
throw $e;
}
---
๐ Common Issues & Troubleshooting
1. Incomplete Statistics
Issue: Success/total counts not properly tracked
Cause: Statistics variables not incremented
Fix:
$total = $success = 0;
foreach ($commands as $command) {
if (trim($command)) {
$total++;
try {
$storeExt->run($command);
$success++;
} catch (Exception $e) {
// Log error but continue
error_log("SQL Error: " . $e->getMessage());
}
}
}
2. Comment Detection Issues
Issue: Comments not properly filtered
Cause: Simple strpos() check insufficient
Improved Detection:
foreach ($lines as $line) {
$line = trim($line);
// Better comment detection
if ($line && !preg_match('/^\s*--/', $line) && $line !== '') {
$commands .= $line . "\n";
}
}
3. SQL Parsing Problems
Issue: Complex SQL statements broken by semicolon split
Cause: Semicolons within strings or functions
Better Parsing:
// Would need proper SQL parser for complex statements
// Current simple split may break on:
// INSERT INTO table VALUES ('data;with;semicolons');
4. Error Handling Missing
Issue: SQL errors not properly reported
Cause: No try-catch around execution
Improved Error Handling:
foreach ($commands as $command) {
if (trim($command)) {
try {
$storeExt->run($command);
$success++;
} catch (Exception $e) {
$errors[] = "Command failed: " . $command . " - " . $e->getMessage();
}
$total++;
}
}
---
๐งช Testing Scenarios
โ ๏ธ DANGER: Test in Development Environment Only โ ๏ธ
Test Case 1: Basic Command Execution
-- Test simple commands
SELECT COUNT(*) FROM user;
Test Case 2: Comment Filtering
-- This is a comment
SELECT 1; -- This should work
-- SELECT 2; This should be filtered
Test Case 3: Multi-Statement Execution
CREATE TEMPORARY TABLE test_temp (id INT);
INSERT INTO test_temp VALUES (1);
SELECT * FROM test_temp;
DROP TABLE test_temp;
Test Case 4: Error Handling
-- This should cause an error
SELECT * FROM nonexistent_table;
SELECT 1; -- This should still execute
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข Database Security Guidelines - Security best practices
- โข SQL Injection Prevention - Security measures
- โข Database Administration - Admin procedures
---
โ ๏ธ SECURITY RECOMMENDATIONS
Immediate Actions Required:
1. Restrict Access: Limit to super-admin users only
2. Add Command Validation: Implement SQL command whitelist
3. Add Audit Logging: Log all SQL executions
4. Implement Safeguards: Prevent dangerous operations
5. Consider Removal: Evaluate if this functionality is necessary
Alternative Approaches:
- โข Use proper database migration tools
- โข Implement specific admin functions instead of raw SQL
- โข Use database admin tools (phpMyAdmin, Adminer) for maintenance
---
Documented By: AI Assistant
Review Status: โ Complete โ ๏ธ SECURITY CRITICAL
Next Review: Immediate security audit required