comment table class

This commit is contained in:
Jan-Niclas Loosen 2025-02-03 14:31:13 +01:00
parent bc1844dfb9
commit d634d16eab
3 changed files with 18 additions and 12 deletions

View File

@ -35,6 +35,11 @@ class Database implements interfaces\DatabaseHelper
// TODO: Implement makeUpdate() method.
}
/**
* Adds the WordPress database prefix to table names if not already present.
* @param string ...$tableName Array of table names to process
* @return void
*/
public static function standardizeTableNames(string &...$tableName): void {
global $wpdb;
$dbPrefix = $wpdb->prefix;

View File

@ -25,6 +25,7 @@ class Table implements TableBlueprint
protected CollationTypes $collation = CollationTypes::UTF8_GENERAL_CI;
public function __construct(string $tableName) {
Database::standardizeTableNames($tableName);
$this->tableName = $tableName;
}
@ -87,43 +88,43 @@ class Table implements TableBlueprint
return $this;
}
/**
* Constructs a SQL string for creating a table with columns and constraints.
*/
public function toSql(): string {
$sql = "CREATE TABLE `{$this->tableName}` (\n";
if (!empty($this->primaryKey)) {
$sql .= " `{$this->primaryKey['colName']}` {$this->primaryKey['colType']->value}";
if ($this->primaryKey['autoincrement'])
$sql .= " AUTO_INCREMENT";
$sql .= " NOT NULL,\n";
}
// Add primary key constraint if present
if (!empty($this->primaryKey))
$sql .= " PRIMARY KEY (`{$this->primaryKey['colName']}`),\n";
foreach ($this->columns as $column) {
if ($column['colName'] !== $this->primaryKey['colName']) {
// Add row with constraints and default values
$sql .= " `{$column['colName']}` {$column['colType']->value}";
// Handle nulls, uniqueness, and defaults
if (!$column['nullable'])
$sql .= " NOT NULL";
if ($column['unique'])
$sql .= " UNIQUE";
if ($column['defaultVal'] !== null) {
$default = is_string($column['defaultVal']) ? "'{$column['defaultVal']}'" : $column['defaultVal'];
$sql .= " DEFAULT $default";
}
// Add column reference
$sql .= ",\n";
}
}
if (!empty($this->primaryKey))
$sql .= " PRIMARY KEY (`{$this->primaryKey['colName']}`),\n";
// Add secondary constraints if present
foreach ($this->foreignKeys as $foreignKey) {
$sql .= " FOREIGN KEY (`{$foreignKey['colName']}`) REFERENCES `{$foreignKey['tableName']}` (`{$foreignKey['colName']}`)";
$sql .= " ON DELETE {$foreignKey['onDelete']->type()} ON UPDATE {$foreignKey['onUpdate']->type()},\n";
}
// Close the SQL string and add constraints
$sql = rtrim($sql, ",\n") . "\n";
$sql .= ") ENGINE={$this->engine->type()} CHARSET={$this->charset->type()} COLLATE={$this->collation->type()};";

View File

@ -51,7 +51,7 @@ interface TableBlueprint
public function collation(CollationTypes $collation): TableBlueprint;
/**
* Executes the blueprint.
* Creates the blueprinted table.
* @return void
*/
public function create(): void;