2016-01-03 05:48:37 +05:30
|
|
|
<?php
|
2024-12-07 04:59:15 +05:30
|
|
|
declare(strict_types=1);
|
|
|
|
|
2016-01-03 05:48:37 +05:30
|
|
|
namespace console\db;
|
|
|
|
|
2024-12-07 04:59:15 +05:30
|
|
|
use yii\db\Exception;
|
2016-01-03 05:48:37 +05:30
|
|
|
use yii\db\Migration as YiiMigration;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @property string $tableOptions
|
2024-12-02 15:40:55 +05:30
|
|
|
* @method \SamIT\Yii2\MariaDb\ColumnSchemaBuilder json()
|
2016-01-03 05:48:37 +05:30
|
|
|
*/
|
|
|
|
class Migration extends YiiMigration {
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
public function getTableOptions(string $engine = 'InnoDB'): string {
|
2016-01-03 05:48:37 +05:30
|
|
|
$tableOptions = null;
|
|
|
|
if ($this->db->driverName === 'mysql') {
|
2017-12-23 03:02:36 +05:30
|
|
|
$tableOptions = 'CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE=' . $engine;
|
2016-01-03 05:48:37 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
return $tableOptions;
|
|
|
|
}
|
|
|
|
|
2024-12-07 04:59:15 +05:30
|
|
|
/**
|
|
|
|
* @param array<string|\yii\db\ColumnSchemaBuilder>|null $columns
|
|
|
|
*/
|
2024-12-02 15:40:55 +05:30
|
|
|
public function createTable($table, $columns, $options = null): void {
|
2016-08-21 03:54:23 +05:30
|
|
|
if ($options === null) {
|
|
|
|
$options = $this->getTableOptions();
|
|
|
|
}
|
|
|
|
|
|
|
|
parent::createTable($table, $columns, $options);
|
|
|
|
}
|
|
|
|
|
2018-07-07 17:31:18 +05:30
|
|
|
protected function primary(string ...$columns): string {
|
|
|
|
foreach ($columns as &$column) {
|
|
|
|
$column = $this->db->quoteColumnName($column);
|
2016-02-14 23:20:10 +05:30
|
|
|
}
|
|
|
|
|
2018-07-07 17:31:18 +05:30
|
|
|
return ' PRIMARY KEY (' . implode(', ', $columns) . ') ';
|
2016-02-14 23:20:10 +05:30
|
|
|
}
|
|
|
|
|
2024-12-07 04:59:15 +05:30
|
|
|
protected function getPrimaryKeyType(string $table, bool $nullable = false): string {
|
|
|
|
$primaryKeys = $this->db->getTableSchema($table)->primaryKey;
|
|
|
|
if (count($primaryKeys) === 0) {
|
|
|
|
throw new Exception("The table \"{$table}\" have no primary keys.");
|
|
|
|
}
|
|
|
|
|
|
|
|
if (count($primaryKeys) > 1) {
|
|
|
|
throw new Exception("The table \"{$table}\" have more than one primary key.");
|
|
|
|
}
|
|
|
|
|
|
|
|
return $this->getColumnType($table, $primaryKeys[0], $nullable);
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function getColumnType(string $table, string $column, bool $nullable = false): string {
|
|
|
|
return $this->db->getTableSchema($table)->getColumn($column)->dbType . ($nullable ? '' : ' NOT NULL');
|
|
|
|
}
|
|
|
|
|
2016-01-03 05:48:37 +05:30
|
|
|
}
|