- Created separate MoneyFlix project directory - Copied Node.js redirector from production server - Added CRM PHP code (Redirects module, Core classes, Config, Routes, Views) - Created comprehensive documentation (README_MONEYFLIX.md) - Added sync script to keep CRM code updated (sync-from-crm.sh) - Configured .gitignore for Node.js and PHP - Set up proper project structure for multi-client isolation This separates MoneyFlix from the main CRM to avoid confusion between different client systems and provides a dedicated environment for MoneyFlix-specific development and maintenance.
1552 lines
46 KiB
PHP
1552 lines
46 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
namespace App\Core\Database;
|
||
|
||
use App\Core\DatabaseManager;
|
||
use App\Core\ErrorReporter;
|
||
use App\Core\Logger;
|
||
|
||
class SchemaBuilder
|
||
{
|
||
private DatabaseManager $db;
|
||
private Logger $logger;
|
||
private array $currentStructure = [];
|
||
private array $currentIndexes = [];
|
||
private array $desiredStructure = [];
|
||
private array $changes = [];
|
||
|
||
public function __construct()
|
||
{
|
||
$this->db = DatabaseManager::getInstance();
|
||
$this->logger = new Logger();
|
||
}
|
||
|
||
/**
|
||
* Define a table structure using fluent interface
|
||
*/
|
||
public function table(string $tableName): TableBuilder
|
||
{
|
||
return new TableBuilder($tableName, $this);
|
||
}
|
||
|
||
/**
|
||
* Get current table structure from database
|
||
* Uses information_schema for consistent field names
|
||
*/
|
||
public function getCurrentStructure(string $tableName): array
|
||
{
|
||
if (isset($this->currentStructure[$tableName])) {
|
||
return $this->currentStructure[$tableName];
|
||
}
|
||
|
||
try {
|
||
$result = $this->db->fetchAll("
|
||
SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY, COLUMN_DEFAULT, EXTRA
|
||
FROM information_schema.COLUMNS
|
||
WHERE TABLE_NAME = ? AND TABLE_SCHEMA = DATABASE()
|
||
ORDER BY ORDINAL_POSITION
|
||
", [$tableName]);
|
||
|
||
$structure = [];
|
||
|
||
foreach ($result as $column) {
|
||
$structure[$column['COLUMN_NAME']] = [
|
||
'type' => $column['COLUMN_TYPE'],
|
||
'null' => $column['IS_NULLABLE'] === 'YES',
|
||
'key' => $column['COLUMN_KEY'],
|
||
'default' => $column['COLUMN_DEFAULT'],
|
||
'extra' => $column['EXTRA']
|
||
];
|
||
}
|
||
|
||
$this->currentStructure[$tableName] = $structure;
|
||
return $structure;
|
||
} catch (\Exception $e) {
|
||
// Table doesn't exist
|
||
return [];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Get current table indexes from database
|
||
*/
|
||
public function getCurrentIndexes(string $tableName): array
|
||
{
|
||
if (isset($this->currentIndexes[$tableName])) {
|
||
return $this->currentIndexes[$tableName];
|
||
}
|
||
|
||
try {
|
||
$result = $this->db->fetchAll("
|
||
SELECT
|
||
INDEX_NAME,
|
||
COLUMN_NAME,
|
||
NON_UNIQUE,
|
||
SEQ_IN_INDEX,
|
||
CARDINALITY,
|
||
SUB_PART,
|
||
PACKED,
|
||
NULLABLE,
|
||
INDEX_TYPE,
|
||
COMMENT
|
||
FROM information_schema.STATISTICS
|
||
WHERE TABLE_NAME = ? AND TABLE_SCHEMA = DATABASE()
|
||
ORDER BY INDEX_NAME, SEQ_IN_INDEX
|
||
", [$tableName]);
|
||
|
||
$indexes = [];
|
||
|
||
foreach ($result as $index) {
|
||
$indexName = $index['INDEX_NAME'];
|
||
|
||
if (!isset($indexes[$indexName])) {
|
||
$indexes[$indexName] = [
|
||
'name' => $indexName,
|
||
'columns' => [],
|
||
'unique' => $index['NON_UNIQUE'] == 0,
|
||
'type' => $index['INDEX_TYPE'],
|
||
'comment' => $index['COMMENT']
|
||
];
|
||
}
|
||
|
||
$indexes[$indexName]['columns'][] = [
|
||
'name' => $index['COLUMN_NAME'],
|
||
'sub_part' => $index['SUB_PART'],
|
||
'nullable' => $index['NULLABLE']
|
||
];
|
||
}
|
||
|
||
$this->currentIndexes[$tableName] = $indexes;
|
||
return $indexes;
|
||
} catch (\Exception $e) {
|
||
// Table doesn't exist
|
||
return [];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Compare current and desired structure and generate changes
|
||
* INTELLIGENT MIGRATION SYSTEM - Only applies necessary changes
|
||
*/
|
||
public function compareStructures(string $tableName, array $desiredColumns, array $desiredIndexes = []): array
|
||
{
|
||
$current = $this->getCurrentStructure($tableName);
|
||
$currentIndexes = $this->getCurrentIndexes($tableName);
|
||
|
||
$changes = [
|
||
'create_table' => empty($current),
|
||
'add_columns' => [],
|
||
'modify_columns' => [],
|
||
'drop_columns' => [], // DISABLED for safety - never drop columns automatically
|
||
'add_indexes' => [],
|
||
'drop_indexes' => [], // DISABLED for safety - never drop indexes automatically
|
||
'desired_columns' => $desiredColumns,
|
||
'desired_indexes' => $desiredIndexes
|
||
];
|
||
|
||
$this->logger->info("🔍 Comparing table structure: $tableName");
|
||
|
||
if (empty($current)) {
|
||
// Table doesn't exist, create it
|
||
$this->logger->info("📋 Table $tableName doesn't exist - will create");
|
||
return $changes;
|
||
}
|
||
|
||
// Check for columns to add or modify
|
||
foreach ($desiredColumns as $columnName => $columnDef) {
|
||
if (!isset($current[$columnName])) {
|
||
$changes['add_columns'][$columnName] = $columnDef;
|
||
$this->logger->info("➕ Will add column: $columnName");
|
||
} else {
|
||
$currentCol = $current[$columnName];
|
||
if ($this->columnsDiffer($currentCol, $columnDef)) {
|
||
$changes['modify_columns'][$columnName] = $columnDef;
|
||
$this->logger->info("🔄 Will modify column: $columnName");
|
||
}
|
||
}
|
||
}
|
||
|
||
// Check for columns to drop (DISABLED for safety)
|
||
// foreach ($current as $columnName => $columnDef) {
|
||
// if (!isset($desiredColumns[$columnName])) {
|
||
// $changes['drop_columns'][] = $columnName;
|
||
// }
|
||
// }
|
||
|
||
// Compare indexes
|
||
$this->compareIndexes($tableName, $currentIndexes, $desiredIndexes, $changes);
|
||
|
||
return $changes;
|
||
}
|
||
|
||
/**
|
||
* Compare current and desired indexes
|
||
*/
|
||
private function compareIndexes(string $tableName, array $currentIndexes, array $desiredIndexes, array &$changes): void
|
||
{
|
||
foreach ($desiredIndexes as $indexDef) {
|
||
// Check if it's a PRIMARY KEY
|
||
if (stripos($indexDef, 'PRIMARY KEY') !== false) {
|
||
// Check if PRIMARY KEY already exists
|
||
$exists = $this->db->fetch("
|
||
SELECT COUNT(*) as count
|
||
FROM information_schema.KEY_COLUMN_USAGE
|
||
WHERE TABLE_SCHEMA = DATABASE()
|
||
AND TABLE_NAME = ?
|
||
AND CONSTRAINT_NAME = 'PRIMARY'
|
||
", [$tableName]);
|
||
|
||
if (($exists['count'] ?? 0) === 0) {
|
||
$changes['add_indexes'][] = $indexDef;
|
||
$this->logger->info("➕ Will add PRIMARY KEY");
|
||
} else {
|
||
$this->logger->info("✅ PRIMARY KEY already exists");
|
||
}
|
||
} else {
|
||
// Extract index name from definition for non-PRIMARY indexes
|
||
if (preg_match('/`([^`]+)`/', $indexDef, $matches)) {
|
||
$indexName = $matches[1];
|
||
|
||
// Check if index exists
|
||
$exists = $this->db->fetch("
|
||
SELECT COUNT(*) as count
|
||
FROM information_schema.STATISTICS
|
||
WHERE TABLE_SCHEMA = DATABASE()
|
||
AND TABLE_NAME = ?
|
||
AND INDEX_NAME = ?
|
||
", [$tableName, $indexName]);
|
||
|
||
if (($exists['count'] ?? 0) === 0) {
|
||
$changes['add_indexes'][] = $indexDef;
|
||
$this->logger->info("➕ Will add index: $indexName");
|
||
} else {
|
||
$this->logger->info("✅ Index already exists: $indexName");
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Check if two column definitions are different
|
||
* Uses direct field comparison from information_schema
|
||
*/
|
||
private function columnsDiffer(array $current, array $desired): bool
|
||
{
|
||
// Normalize types for comparison
|
||
$currentType = $this->normalizeType($current['type']);
|
||
$desiredType = $this->normalizeType($desired['type']);
|
||
|
||
if ($currentType !== $desiredType) {
|
||
return true;
|
||
}
|
||
|
||
// Direct null comparison
|
||
$currentNull = $current['null'] === true;
|
||
$desiredNull = $desired['null'];
|
||
|
||
if ($currentNull !== $desiredNull) {
|
||
return true;
|
||
}
|
||
|
||
// Normalize default values for comparison
|
||
$currentDefault = $this->normalizeDefault($current['default']);
|
||
$desiredDefault = $this->normalizeDefault($desired['default']);
|
||
|
||
if ($currentDefault !== $desiredDefault) {
|
||
return true;
|
||
}
|
||
|
||
// Direct extra comparison
|
||
if ($current['extra'] !== $desired['extra']) {
|
||
return true;
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
/**
|
||
* Normalize MySQL type for comparison
|
||
*/
|
||
private function normalizeType(string $type): string
|
||
{
|
||
// Convert to uppercase and remove length specifications for comparison
|
||
$type = strtoupper(trim($type));
|
||
|
||
// Remove length specifications like (11), (255), etc.
|
||
$type = preg_replace('/\(\d+\)/', '', $type);
|
||
|
||
// Normalize common variations
|
||
$type = str_replace('INTEGER', 'INT', $type);
|
||
$type = str_replace('CHARACTER VARYING', 'VARCHAR', $type);
|
||
|
||
return trim($type);
|
||
}
|
||
|
||
/**
|
||
* Normalize default values for comparison
|
||
*/
|
||
private function normalizeDefault($default): string
|
||
{
|
||
if ($default === null) {
|
||
return 'NULL';
|
||
}
|
||
|
||
// Convert to string and normalize
|
||
$default = (string)$default;
|
||
|
||
// Normalize common default values
|
||
if ($default === '1' || $default === 1) {
|
||
return '1';
|
||
}
|
||
|
||
if ($default === '0' || $default === 0) {
|
||
return '0';
|
||
}
|
||
|
||
if (strtoupper($default) === 'CURRENT_TIMESTAMP') {
|
||
return 'CURRENT_TIMESTAMP';
|
||
}
|
||
|
||
return $default;
|
||
}
|
||
|
||
/**
|
||
* Apply changes to database
|
||
* INTELLIGENT MIGRATION - Only applies necessary changes
|
||
*/
|
||
public function applyChanges(string $tableName, array $changes): bool
|
||
{
|
||
try {
|
||
$this->logger->info("🚀 Applying changes to table: $tableName");
|
||
|
||
if ($changes['create_table']) {
|
||
$indexes = $changes['desired_indexes'] ?? [];
|
||
$result = $this->createTable($tableName, $changes['desired_columns'], $indexes);
|
||
return $result;
|
||
}
|
||
|
||
// Add new columns
|
||
foreach ($changes['add_columns'] as $columnName => $columnDef) {
|
||
$this->addColumn($tableName, $columnName, $columnDef);
|
||
}
|
||
|
||
// Modify existing columns
|
||
foreach ($changes['modify_columns'] as $columnName => $columnDef) {
|
||
$this->modifyColumn($tableName, $columnName, $columnDef);
|
||
}
|
||
|
||
// Add missing indexes
|
||
foreach ($changes['add_indexes'] as $indexDef) {
|
||
$this->addIndex($tableName, $indexDef);
|
||
}
|
||
|
||
// Validate structure after changes
|
||
$this->validateTableStructure($tableName, $changes['desired_columns'], $changes['desired_indexes'] ?? []);
|
||
|
||
$this->logger->info("✅ Successfully applied changes to table: $tableName");
|
||
return true;
|
||
} catch (\Exception $e) {
|
||
$this->logger->error("❌ Failed to apply changes to table $tableName: " . $e->getMessage());
|
||
ErrorReporter::report($e, ['context' => 'schema_builder_apply_changes', 'table' => $tableName]);
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Create new table with intelligent validation
|
||
*/
|
||
private function createTable(string $tableName, array $columns, array $indexes = []): bool
|
||
{
|
||
$this->logger->info("🏗️ Creating table: $tableName");
|
||
|
||
$sql = "CREATE TABLE `$tableName` (\n";
|
||
$columnDefs = [];
|
||
|
||
foreach ($columns as $columnName => $columnDef) {
|
||
$columnDefs[] = $this->buildColumnDefinition($columnName, $columnDef);
|
||
}
|
||
|
||
// Add indexes
|
||
if (!empty($indexes)) {
|
||
$columnDefs = array_merge($columnDefs, $indexes);
|
||
}
|
||
|
||
// Ensure PRIMARY KEY for AUTO_INCREMENT columns
|
||
$hasPrimaryKey = false;
|
||
foreach ($indexes as $indexDef) {
|
||
if (stripos($indexDef, 'PRIMARY KEY') !== false) {
|
||
$hasPrimaryKey = true;
|
||
break;
|
||
}
|
||
}
|
||
|
||
if (!$hasPrimaryKey) {
|
||
foreach ($columns as $columnName => $columnDef) {
|
||
if (strpos($columnDef['extra'], 'auto_increment') !== false || $columnName === 'id') {
|
||
$columnDefs[] = "PRIMARY KEY (`$columnName`)";
|
||
$this->logger->info("🔑 Adding PRIMARY KEY for AUTO_INCREMENT column: $columnName");
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
$sql .= implode(",\n", $columnDefs);
|
||
$sql .= "\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
|
||
|
||
$this->logger->info("🔍 SQL gerado para criação da tabela $tableName:");
|
||
$this->logger->info($sql);
|
||
|
||
try {
|
||
$this->db->query($sql);
|
||
|
||
// Validate and fix structure after creation
|
||
$this->validateAndFixTableStructure($tableName, $columns, $indexes);
|
||
|
||
$this->logger->info("✅ Successfully created table: $tableName");
|
||
return true;
|
||
} catch (\Exception $e) {
|
||
$this->logger->error("❌ Failed to create table $tableName: " . $e->getMessage());
|
||
throw $e;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Validate and fix table structure after creation/modification
|
||
*/
|
||
private function validateAndFixTableStructure(string $tableName, array $columns, array $indexes): void
|
||
{
|
||
$this->logger->info("🔍 Validating table structure: $tableName");
|
||
|
||
// Ensure PRIMARY KEY exists
|
||
$this->ensurePrimaryKey($tableName, $columns);
|
||
|
||
// Ensure all indexes were created
|
||
$this->ensureIndexes($tableName, $indexes);
|
||
|
||
// Validate column types
|
||
$this->validateColumnTypes($tableName, $columns);
|
||
|
||
$this->logger->info("✅ Table structure validation completed: $tableName");
|
||
}
|
||
|
||
/**
|
||
* Ensure table has PRIMARY KEY
|
||
*/
|
||
private function ensurePrimaryKey(string $tableName, array $columns): void
|
||
{
|
||
// Check if PRIMARY KEY already exists
|
||
$hasPrimaryKey = $this->db->fetch("
|
||
SELECT COUNT(*) as count
|
||
FROM information_schema.KEY_COLUMN_USAGE
|
||
WHERE TABLE_SCHEMA = DATABASE()
|
||
AND TABLE_NAME = ?
|
||
AND CONSTRAINT_NAME = 'PRIMARY'
|
||
", [$tableName]);
|
||
|
||
if (($hasPrimaryKey['count'] ?? 0) === 0) {
|
||
// Look for ID column with AUTO_INCREMENT
|
||
foreach ($columns as $columnName => $columnDef) {
|
||
if (strpos($columnDef['extra'], 'AUTO_INCREMENT') !== false || $columnName === 'id') {
|
||
$sql = "ALTER TABLE `$tableName` ADD PRIMARY KEY (`$columnName`)";
|
||
try {
|
||
$this->db->query($sql);
|
||
$this->logger->info("🔑 Added PRIMARY KEY to column: $columnName");
|
||
break;
|
||
} catch (\Exception $e) {
|
||
// Ignore if already exists
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Ensure all indexes were created
|
||
*/
|
||
private function ensureIndexes(string $tableName, array $indexes): void
|
||
{
|
||
foreach ($indexes as $indexDef) {
|
||
// Extract index name from definition
|
||
if (preg_match('/`([^`]+)`/', $indexDef, $matches)) {
|
||
$indexName = $matches[1];
|
||
|
||
// Check if index exists
|
||
$exists = $this->db->fetch("
|
||
SELECT COUNT(*) as count
|
||
FROM information_schema.STATISTICS
|
||
WHERE TABLE_SCHEMA = DATABASE()
|
||
AND TABLE_NAME = ?
|
||
AND INDEX_NAME = ?
|
||
", [$tableName, $indexName]);
|
||
|
||
if (($exists['count'] ?? 0) === 0) {
|
||
// Create index if it doesn't exist
|
||
$sql = "ALTER TABLE `$tableName` ADD $indexDef";
|
||
try {
|
||
$this->db->query($sql);
|
||
$this->logger->info("📊 Added index: $indexName");
|
||
} catch (\Exception $e) {
|
||
// Ignore if already exists or conflict
|
||
$this->logger->warning("⚠️ Could not add index $indexName: " . $e->getMessage());
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Validate column types are correct
|
||
*/
|
||
private function validateColumnTypes(string $tableName, array $desiredColumns): void
|
||
{
|
||
$currentStructure = $this->getCurrentStructure($tableName);
|
||
|
||
foreach ($desiredColumns as $columnName => $desiredDef) {
|
||
if (isset($currentStructure[$columnName])) {
|
||
$currentDef = $currentStructure[$columnName];
|
||
|
||
if ($this->columnsDiffer($currentDef, $desiredDef)) {
|
||
// Fix type automatically
|
||
try {
|
||
$this->modifyColumn($tableName, $columnName, $desiredDef);
|
||
$this->logger->info("🔧 Fixed column type: $columnName");
|
||
} catch (\Exception $e) {
|
||
// Ignore if can't modify (e.g., foreign keys)
|
||
$this->logger->warning("⚠️ Could not fix column $columnName: " . $e->getMessage());
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Add new column
|
||
*/
|
||
public function addColumn(string $tableName, string $columnName, array $columnDef): void
|
||
{
|
||
$columnDefinition = $this->buildColumnDefinitionWithoutName($columnDef);
|
||
$sql = "ALTER TABLE `$tableName` ADD COLUMN `$columnName` $columnDefinition";
|
||
|
||
try {
|
||
$this->db->query($sql);
|
||
$this->logger->info("➕ Added column: $tableName.$columnName");
|
||
} catch (\Exception $e) {
|
||
$this->logger->error("❌ Failed to add column $tableName.$columnName: " . $e->getMessage());
|
||
throw $e;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Modify existing column
|
||
*/
|
||
public function modifyColumn(string $tableName, string $columnName, array $columnDef): void
|
||
{
|
||
$columnDefinition = $this->buildColumnDefinitionWithoutName($columnDef);
|
||
$sql = "ALTER TABLE `$tableName` MODIFY COLUMN `$columnName` $columnDefinition";
|
||
|
||
try {
|
||
$this->db->query($sql);
|
||
$this->logger->info("🔄 Modified column: $tableName.$columnName");
|
||
} catch (\Exception $e) {
|
||
$this->logger->error("❌ Failed to modify column $tableName.$columnName: " . $e->getMessage());
|
||
throw $e;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Add index to table
|
||
*/
|
||
public function addIndex(string $tableName, string $indexDef): void
|
||
{
|
||
$sql = "ALTER TABLE `$tableName` ADD $indexDef";
|
||
|
||
try {
|
||
$this->db->query($sql);
|
||
$this->logger->info("📊 Added index to table: $tableName");
|
||
} catch (\Exception $e) {
|
||
$this->logger->error("❌ Failed to add index to table $tableName: " . $e->getMessage());
|
||
throw $e;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Drop column (DISABLED for safety)
|
||
*/
|
||
public function dropColumn(string $tableName, string $columnName): void
|
||
{
|
||
// DISABLED for safety - never drop columns automatically
|
||
$this->logger->warning("🚫 Column drop disabled for safety: $tableName.$columnName");
|
||
return;
|
||
|
||
// $sql = "ALTER TABLE `$tableName` DROP COLUMN `$columnName`";
|
||
// $this->db->query($sql);
|
||
}
|
||
|
||
/**
|
||
* Build column definition with name
|
||
*/
|
||
private function buildColumnDefinition(string $columnName, array $columnDef): string
|
||
{
|
||
$def = "`$columnName` " . $this->buildColumnDefinitionWithoutName($columnDef);
|
||
return $def;
|
||
}
|
||
|
||
/**
|
||
* Build column definition without name
|
||
*/
|
||
private function buildColumnDefinitionWithoutName(array $columnDef): string
|
||
{
|
||
$def = $columnDef['type'];
|
||
|
||
if (!$columnDef['null']) {
|
||
$def .= ' NOT NULL';
|
||
} else {
|
||
$def .= ' NULL';
|
||
}
|
||
|
||
if ($columnDef['default'] !== null) {
|
||
if ($columnDef['default'] === 'CURRENT_TIMESTAMP') {
|
||
$def .= " DEFAULT CURRENT_TIMESTAMP";
|
||
} elseif (is_string($columnDef['default'])) {
|
||
$def .= " DEFAULT '" . addslashes($columnDef['default']) . "'";
|
||
} else {
|
||
$def .= " DEFAULT " . $columnDef['default'];
|
||
}
|
||
}
|
||
|
||
if (!empty($columnDef['extra'])) {
|
||
$def .= ' ' . $columnDef['extra'];
|
||
}
|
||
|
||
return $def;
|
||
}
|
||
|
||
/**
|
||
* Validate table structure after changes
|
||
*/
|
||
private function validateTableStructure(string $tableName, array $desiredColumns, array $desiredIndexes): void
|
||
{
|
||
$this->logger->info("🔍 Validating table structure after changes: $tableName");
|
||
|
||
// Verify all columns exist
|
||
$currentStructure = $this->getCurrentStructure($tableName);
|
||
foreach ($desiredColumns as $columnName => $columnDef) {
|
||
if (!isset($currentStructure[$columnName])) {
|
||
throw new \Exception("Column $columnName was not created in table $tableName");
|
||
}
|
||
}
|
||
|
||
// Verify all indexes exist
|
||
foreach ($desiredIndexes as $indexDef) {
|
||
if (preg_match('/`([^`]+)`/', $indexDef, $matches)) {
|
||
$indexName = $matches[1];
|
||
$exists = $this->db->fetch("
|
||
SELECT COUNT(*) as count
|
||
FROM information_schema.STATISTICS
|
||
WHERE TABLE_SCHEMA = DATABASE()
|
||
AND TABLE_NAME = ?
|
||
AND INDEX_NAME = ?
|
||
", [$tableName, $indexName]);
|
||
|
||
if (($exists['count'] ?? 0) === 0) {
|
||
$this->logger->warning("⚠️ Index $indexName was not created in table $tableName");
|
||
}
|
||
}
|
||
}
|
||
|
||
$this->logger->info("✅ Table structure validation passed: $tableName");
|
||
}
|
||
|
||
/**
|
||
* Check if table exists
|
||
*/
|
||
public function tableExists(string $tableName): bool
|
||
{
|
||
try {
|
||
$result = $this->db->fetch("
|
||
SELECT COUNT(*) as count
|
||
FROM information_schema.TABLES
|
||
WHERE TABLE_SCHEMA = DATABASE()
|
||
AND TABLE_NAME = ?
|
||
", [$tableName]);
|
||
|
||
return ($result['count'] ?? 0) > 0;
|
||
} catch (\Exception $e) {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Get all tables in database
|
||
*/
|
||
public function getTables(): array
|
||
{
|
||
try {
|
||
$result = $this->db->fetchAll("
|
||
SELECT TABLE_NAME
|
||
FROM information_schema.TABLES
|
||
WHERE TABLE_SCHEMA = DATABASE()
|
||
ORDER BY TABLE_NAME
|
||
");
|
||
|
||
return array_column($result, 'TABLE_NAME');
|
||
} catch (\Exception $e) {
|
||
return [];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Get database name
|
||
*/
|
||
private function getDatabaseName(): string
|
||
{
|
||
try {
|
||
$result = $this->db->fetch("SELECT DATABASE() as db_name");
|
||
return $result['db_name'] ?? '';
|
||
} catch (\Exception $e) {
|
||
return '';
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Create trigger
|
||
*/
|
||
public function createTrigger(string $triggerName, string $tableName, string $timing, string $event, string $body): void
|
||
{
|
||
$sql = "CREATE TRIGGER `$triggerName` $timing $event ON `$tableName` FOR EACH ROW $body";
|
||
$this->db->query($sql);
|
||
}
|
||
|
||
/**
|
||
* Drop trigger
|
||
*/
|
||
public function dropTrigger(string $triggerName): void
|
||
{
|
||
$sql = "DROP TRIGGER IF EXISTS `$triggerName`";
|
||
$this->db->query($sql);
|
||
}
|
||
|
||
/**
|
||
* Check if trigger exists
|
||
*/
|
||
public function triggerExists(string $triggerName): bool
|
||
{
|
||
try {
|
||
$result = $this->db->fetch("
|
||
SELECT COUNT(*) as count
|
||
FROM information_schema.TRIGGERS
|
||
WHERE TRIGGER_SCHEMA = DATABASE()
|
||
AND TRIGGER_NAME = ?
|
||
", [$triggerName]);
|
||
|
||
return ($result['count'] ?? 0) > 0;
|
||
} catch (\Exception $e) {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Get table triggers
|
||
*/
|
||
public function getTableTriggers(string $tableName): array
|
||
{
|
||
try {
|
||
$result = $this->db->fetchAll("
|
||
SELECT TRIGGER_NAME, EVENT_MANIPULATION, EVENT_OBJECT_TABLE, ACTION_TIMING, ACTION_STATEMENT
|
||
FROM information_schema.TRIGGERS
|
||
WHERE TRIGGER_SCHEMA = DATABASE()
|
||
AND EVENT_OBJECT_TABLE = ?
|
||
ORDER BY TRIGGER_NAME
|
||
", [$tableName]);
|
||
|
||
return $result;
|
||
} catch (\Exception $e) {
|
||
return [];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Get all triggers
|
||
*/
|
||
public function getAllTriggers(): array
|
||
{
|
||
try {
|
||
$result = $this->db->fetchAll("
|
||
SELECT TRIGGER_NAME, EVENT_MANIPULATION, EVENT_OBJECT_TABLE, ACTION_TIMING, ACTION_STATEMENT
|
||
FROM information_schema.TRIGGERS
|
||
WHERE TRIGGER_SCHEMA = DATABASE()
|
||
ORDER BY TRIGGER_NAME
|
||
");
|
||
|
||
return $result;
|
||
} catch (\Exception $e) {
|
||
return [];
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Fluent interface for defining table structure
|
||
*/
|
||
class TableBuilder
|
||
{
|
||
private string $tableName;
|
||
private SchemaBuilder $schemaBuilder;
|
||
private array $columns = [];
|
||
private array $indexes = [];
|
||
|
||
public function __construct(string $tableName, SchemaBuilder $schemaBuilder)
|
||
{
|
||
$this->tableName = $tableName;
|
||
$this->schemaBuilder = $schemaBuilder;
|
||
}
|
||
|
||
/**
|
||
* Define INT column (4 bytes, -2147483648 to 2147483647)
|
||
* Note: Display width (length) is deprecated in MySQL 8.0+
|
||
*/
|
||
public function integer(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'INT',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Define BIGINT column (8 bytes, -9223372036854775808 to 9223372036854775807)
|
||
* Use unsigned() for positive values only (0 to 18446744073709551615)
|
||
*/
|
||
public function bigInteger(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'BIGINT',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Make column UNSIGNED (for positive values only, doubles the range)
|
||
* Best practice for AUTO_INCREMENT and foreign keys
|
||
*/
|
||
public function unsigned(): self
|
||
{
|
||
$lastColumn = array_key_last($this->columns);
|
||
if ($lastColumn && isset($this->columns[$lastColumn]['type'])) {
|
||
$currentType = $this->columns[$lastColumn]['type'];
|
||
if (!str_contains($currentType, 'UNSIGNED')) {
|
||
$this->columns[$lastColumn]['type'] = $currentType . ' UNSIGNED';
|
||
}
|
||
}
|
||
return $this;
|
||
}
|
||
|
||
public function smallInteger(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'SMALLINT',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Define TINYINT column (1 byte, -128 to 127, or 0 to 255 if UNSIGNED)
|
||
* Perfect for status fields: 0=disabled, 1=active, -1=deleted
|
||
*/
|
||
public function tinyInteger(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'TINYINT',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function mediumInteger(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'MEDIUMINT',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Define VARCHAR column (variable length string)
|
||
* Best practice: Don't blindly use 255, use reasonable limits
|
||
* For IDs, codes, etc. consider CHARACTER SET ascii for better performance
|
||
*/
|
||
public function string(string $columnName, int $length = 255): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => "VARCHAR($length)",
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Define CUID column (Collision-resistant Unique ID)
|
||
* Fixed length 32 characters, CHARACTER SET ascii for optimal performance
|
||
*/
|
||
public function cuid(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'VARCHAR(32) CHARACTER SET ascii',
|
||
'null' => false,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function char(string $columnName, int $length = 1): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => "CHAR($length)",
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function text(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'TEXT',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function mediumText(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'MEDIUMTEXT',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function longText(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'LONGTEXT',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function tinyText(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'TINYTEXT',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Define DECIMAL column (exact numeric, perfect for money)
|
||
* Precision: total digits, Scale: digits after decimal point
|
||
* Example: DECIMAL(15,2) for money (up to 999,999,999,999.99)
|
||
*/
|
||
public function decimal(string $columnName, int $precision = 10, int $scale = 2): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => "DECIMAL($precision,$scale)",
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function float(string $columnName, int $precision = 10, int $scale = 2): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => "FLOAT($precision,$scale)",
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function double(string $columnName, int $precision = 10, int $scale = 2): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => "DOUBLE($precision,$scale)",
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function real(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'REAL',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function timestamp(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'TIMESTAMP',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function datetime(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'DATETIME',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function date(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'DATE',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function time(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'TIME',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function year(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'YEAR',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Define ENUM column (up to 255 values = 1 byte, up to 65535 = 2 bytes)
|
||
* Best practice: Use for small, fixed sets of values
|
||
* Consider TINYINT for status fields (0=disabled, 1=active, -1=deleted)
|
||
* Avoid nullable ENUMs - use 'unknown' or 'N/A' as first option instead
|
||
*/
|
||
public function enum(string $columnName, array $values): self
|
||
{
|
||
$valuesList = "'" . implode("','", $values) . "'";
|
||
$this->columns[$columnName] = [
|
||
'type' => "ENUM($valuesList)",
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function set(string $columnName, array $values): self
|
||
{
|
||
$valuesList = "'" . implode("','", $values) . "'";
|
||
$this->columns[$columnName] = [
|
||
'type' => "SET($valuesList)",
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function json(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'JSON',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Define BOOLEAN column (MySQL synonym for TINYINT)
|
||
* Best practice: Use TINYINT UNSIGNED NOT NULL DEFAULT 0/1
|
||
* Values: 0 = FALSE, 1 = TRUE, any other value = TRUE
|
||
*/
|
||
public function boolean(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'TINYINT UNSIGNED',
|
||
'null' => false,
|
||
'default' => 0,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function bit(string $columnName, int $length = 1): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => "BIT($length)",
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function binary(string $columnName, int $length = 255): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => "BINARY($length)",
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function varbinary(string $columnName, int $length = 255): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => "VARBINARY($length)",
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function blob(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'BLOB',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function tinyBlob(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'TINYBLOB',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function mediumBlob(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'MEDIUMBLOB',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function longBlob(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'LONGBLOB',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function geometry(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'GEOMETRY',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function point(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'POINT',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function linestring(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'LINESTRING',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function polygon(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'POLYGON',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function multipoint(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'MULTIPOINT',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function multilinestring(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'MULTILINESTRING',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function multipolygon(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'MULTIPOLYGON',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function geometrycollection(string $columnName): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'GEOMETRYCOLLECTION',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
public function notNull(): self
|
||
{
|
||
$lastColumn = array_key_last($this->columns);
|
||
if ($lastColumn) {
|
||
$this->columns[$lastColumn]['null'] = false;
|
||
}
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Set column as nullable (explicit)
|
||
*/
|
||
public function nullable(): self
|
||
{
|
||
$lastColumn = array_key_last($this->columns);
|
||
if ($lastColumn) {
|
||
$this->columns[$lastColumn]['null'] = true;
|
||
}
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Set default value
|
||
*/
|
||
public function default($value): self
|
||
{
|
||
$lastColumn = array_key_last($this->columns);
|
||
if ($lastColumn) {
|
||
$this->columns[$lastColumn]['default'] = $value;
|
||
}
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Set auto increment
|
||
*/
|
||
public function autoIncrement(): self
|
||
{
|
||
$lastColumn = array_key_last($this->columns);
|
||
if ($lastColumn) {
|
||
$this->columns[$lastColumn]['extra'] = 'AUTO_INCREMENT';
|
||
}
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Add primary key
|
||
*/
|
||
public function primaryKey(string $columnName): self
|
||
{
|
||
$this->indexes[] = "PRIMARY KEY (`$columnName`)";
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Add unique key
|
||
*/
|
||
public function unique(string $columnName): self
|
||
{
|
||
$this->indexes[] = "UNIQUE KEY `uk_$columnName` (`$columnName`)";
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Add composite unique constraint
|
||
*/
|
||
public function uniqueComposite(string $indexName, array $columns): self
|
||
{
|
||
$columnsList = implode(', ', array_map(fn($col) => "`$col`", $columns));
|
||
$this->indexes[] = "UNIQUE KEY `$indexName` ($columnsList)";
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Add index - supports both string and array of columns
|
||
*/
|
||
public function index($columnName): self
|
||
{
|
||
if (is_array($columnName)) {
|
||
// For arrays, create individual indexes for each column
|
||
foreach ($columnName as $column) {
|
||
$this->indexes[] = "KEY `idx_$column` (`$column`)";
|
||
}
|
||
} else {
|
||
// For strings, create single index
|
||
$this->indexes[] = "KEY `idx_$columnName` (`$columnName`)";
|
||
}
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Add composite index (multiple columns in one index)
|
||
*/
|
||
public function compositeIndex(array $columnNames, ?string $indexName = null): self
|
||
{
|
||
$indexName = $indexName ?: 'idx_' . implode('_', $columnNames);
|
||
$columns = implode('`, `', $columnNames);
|
||
$this->indexes[] = "KEY `$indexName` (`$columns`)";
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Define email column (VARCHAR with reasonable length)
|
||
*/
|
||
public function email(string $columnName = 'email'): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'VARCHAR(320)', // RFC 5321 max length
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Define URL column (VARCHAR with reasonable length)
|
||
*/
|
||
public function url(string $columnName, int $length = 2048): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => "VARCHAR($length)",
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Define phone number column (VARCHAR for international support)
|
||
*/
|
||
public function phone(string $columnName = 'phone'): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'VARCHAR(20) CHARACTER SET ascii',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Define postal code column (VARCHAR to preserve leading zeros)
|
||
*/
|
||
public function postalCode(string $columnName = 'postal_code'): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'VARCHAR(20) CHARACTER SET ascii',
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Define IPv4/IPv6 address column (VARCHAR for readability)
|
||
* Use INET_ATON()/INET_NTOA() for IPv4 integer storage if needed
|
||
*/
|
||
public function ipAddress(string $columnName = 'ip_address'): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'VARCHAR(39) CHARACTER SET ascii', // IPv6 max length
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Define status column using TINYINT (recommended over ENUM)
|
||
* Standard: 0=disabled, 1=active, -1=deleted
|
||
*/
|
||
public function status(string $columnName = 'status'): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => 'TINYINT',
|
||
'null' => false,
|
||
'default' => 1,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Define money column using DECIMAL(15,2)
|
||
* Precision 15 allows up to 999,999,999,999.99
|
||
*/
|
||
public function money(string $columnName, int $precision = 15, int $scale = 2): self
|
||
{
|
||
$this->columns[$columnName] = [
|
||
'type' => "DECIMAL($precision,$scale)",
|
||
'null' => true,
|
||
'default' => null,
|
||
'extra' => ''
|
||
];
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* Apply the table structure
|
||
*/
|
||
public function apply(): bool
|
||
{
|
||
try {
|
||
$changes = $this->schemaBuilder->compareStructures($this->tableName, $this->columns, $this->indexes);
|
||
|
||
if ($changes['create_table']) {
|
||
$changes['desired_columns'] = $this->columns;
|
||
$changes['desired_indexes'] = $this->indexes;
|
||
}
|
||
|
||
$result = $this->schemaBuilder->applyChanges($this->tableName, $changes);
|
||
|
||
return $result;
|
||
} catch (\Exception $e) {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Get the defined columns
|
||
*/
|
||
public function getColumns(): array
|
||
{
|
||
return $this->columns;
|
||
}
|
||
|
||
/**
|
||
* Get the defined indexes
|
||
*/
|
||
public function getIndexes(): array
|
||
{
|
||
return $this->indexes;
|
||
}
|
||
|
||
/**
|
||
* Add comment to the last defined column
|
||
*/
|
||
public function comment(string $comment): self
|
||
{
|
||
if (!empty($this->columns)) {
|
||
$lastColumnName = array_key_last($this->columns);
|
||
$this->columns[$lastColumnName]['comment'] = $comment;
|
||
}
|
||
return $this;
|
||
}
|
||
} |