chore: Аннотации к типам

This commit is contained in:
origami11@yandex.ru 2025-10-23 11:24:33 +03:00
parent e5713e9015
commit 530a3b931d
22 changed files with 388 additions and 131 deletions

View file

@ -17,9 +17,15 @@ class Manager
$this->db = $db;
}
public function executeAction(array $action, $db_file = "")
/**
* Выполняет действие
* @param array $action
* @param string $db_file
* @throws Exception
*/
public function executeAction(array $action, $db_file = ""): void
{
switch($action["type"]) {
switch ($action["type"]) {
case "dropTable":
$this->dropTableQuery($action["table_name"], true);
break;
@ -56,59 +62,85 @@ class Manager
break;
default:
throw new Exception("unknown action ". $action["type"] . PHP_EOL);
throw new Exception("unknown action " . $action["type"] . PHP_EOL);
}
}
//Дропает и создаёт SQL VIEW
public function recreateView($viewName, $selectStatement)
/**
* Дропает и создаёт SQL VIEW
* @param string $viewName
* @param string $selectStatement
*/
public function recreateView($viewName, $selectStatement): void
{
$this->db->query("DROP VIEW ".$viewName);
$this->db->query("CREATE VIEW ".$viewName." AS ".$selectStatement);
$this->db->query("DROP VIEW " . $viewName);
$this->db->query("CREATE VIEW " . $viewName . " AS " . $selectStatement);
}
public function dropTableQuery($table, $cascade=false)
/**
* Дропает таблицу
* @param string $table
* @param bool $cascade
*/
public function dropTableQuery($table, $cascade = false): void
{
$statement = "DROP TABLE IF EXISTS ".$table;
if ($this->db->isPostgres()&&$cascade) {
$statement = "DROP TABLE IF EXISTS " . $table;
if ($this->db->isPostgres() && $cascade) {
$statement .= " CASCADE";
}
$this->db->query($statement);
}
public function alterReference($table, $column, $refTable, $refColumn)
/**
* Добавляет ссылку на другую таблицу
* @param string $table
* @param string $column
* @param string $refTable
* @param string $refColumn
*/
public function alterReference($table, $column, $refTable, $refColumn): void
{
$this->db->query("ALTER TABLE ".$table." ADD CONSTRAINT ".$table."_".$column."fk"." FOREIGN KEY (".$column.") REFERENCES ".$refTable." (".$refColumn.")");
$this->db->query("ALTER TABLE " . $table . " ADD CONSTRAINT " . $table . "_" . $column . "fk" . " FOREIGN KEY (" . $column . ") REFERENCES " . $refTable . " (" . $refColumn . ") ON DELETE CASCADE ON UPDATE CASCADE");
}
//Извлечение информации о полях таблицы
/**
* Извлечение информации о полях таблицы
* @param string $table
* @return array{type:string,not_null:bool,constraint:?string}[]|null
*/
public function tableInfo($table)
{
$pg = $this->db->isPostgres();
if ($pg) {
throw new Exception("Not implemented for postgres");
} else {
$results = $this->db->fetchAllArray("PRAGMA table_info(".$table.");");
$results = $this->db->fetchAllArray("PRAGMA table_info(" . $table . ");");
if (empty($results)) {
return null;
}
$fields = [];
foreach ($results as $result) {
$fields[$result["name"]] = [
"type"=> $result["type"],
"not_null"=> boolval($result["notnull"]),
"constraint"=> ((bool) $result["pk"]) ? "PRIMARY KEY" : null
"type" => $result["type"],
"not_null" => boolval($result["notnull"]),
"constraint" => ((bool) $result["pk"]) ? "PRIMARY KEY" : null
];
}
return $fields;
}
}
public function renameColumn($table, $old_name, $new_name)
/**
* Переименование столбца в таблице
* @param string $table
* @param string $old_name
* @param string $new_name
*/
public function renameColumn($table, $old_name, $new_name): void
{
$pg = $this->db->isPostgres();
if ($pg) {
$this->db->query("ALTER TABLE ".$table." RENAME COLUMN ".$old_name." TO ".$new_name);
$this->db->query("ALTER TABLE " . $table . " RENAME COLUMN " . $old_name . " TO " . $new_name);
} else {
$tmp_table = "tmp_" . $table;
$this->dropTableQuery($tmp_table);
@ -120,7 +152,7 @@ class Manager
$data = $this->dumpTable($table);
$this->db->query("ALTER TABLE ".$table." RENAME TO ".$tmp_table.";");
$this->db->query("ALTER TABLE " . $table . " RENAME TO " . $tmp_table . ";");
$table_info[$new_name] = $table_info[$old_name];
unset($table_info[$old_name]);
$this->createTableQuery($table, $table_info, null);
@ -135,41 +167,63 @@ class Manager
}
}
//Обновление ключа serial после ручной вставки
public function updateSerial($table, $column)
/**
* Обновление ключа serial после ручной вставки
* @param string $table
* @param string $column
*/
public function updateSerial($table, $column): void
{
$this->db->query("SELECT setval(pg_get_serial_sequence('".$table."', '".$column."'), coalesce(max(".$column."),0) + 1, false) FROM ".$table);
$this->db->query("SELECT setval(pg_get_serial_sequence('" . $table . "', '" . $column . "'), coalesce(max(" . $column . "),0) + 1, false) FROM " . $table);
}
/**
* Возвращает определение столбца
* @param string $name
* @param array $data
* @param bool $pg
* @return string
*/
public function columnDefinition($name, $data, $pg)
{
$constraint = isset($data['constraint']) ? " ".$data['constraint'] : "";
$constraint = isset($data['constraint']) ? " " . $data['constraint'] : "";
$references = "";
if (isset($data['references'])) {
$references = " REFERENCES " . $data['references']['refTable'] . '(' .$data['references']['refColumn'] . ')';
$references = " REFERENCES " . $data['references']['refTable'] . '(' . $data['references']['refColumn'] . ')';
}
if (isset($data["not_null"]) && $data["not_null"]) {
$constraint .=" NOT NULL";
$constraint .= " NOT NULL";
}
$type = $data['type'];
if (!$pg) {
if (strtolower($type)=="serial") {
if (strtolower($type) == "serial") {
$type = "integer";
}
//if (strtolower($type)=="boolean")
// $type = "integer";
}
return $name." ".$type.$references.$constraint;
return $name . " " . $type . $references . $constraint;
}
public function addColumn($table_name, $column_name, $field)
/**
* Добавляет столбец в таблицу
* @param string $table_name
* @param string $column_name
* @param array $field
*/
public function addColumn($table_name, $column_name, $field): void
{
$pg = $this->db->isPostgres();
$q = "ALTER TABLE ".$table_name." ADD COLUMN ".
$this->columnDefinition($column_name, $field, $pg);
$q = "ALTER TABLE " . $table_name . " ADD COLUMN " .
$this->columnDefinition($column_name, $field, $pg);
$this->db->query($q);
}
/**
* Возвращает определение ограничения
* @param array{fields: string[], type: string} $c
* @return string
*/
public function getConstraintDef(array $c)
{
if ($c['type'] == 'unique') {
@ -178,7 +232,14 @@ class Manager
return "";
}
//CreateTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']])
/**
* Создает таблицу
* @example createTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']])
* @param string $table
* @param array $fields
* @param array|string|null $constraints
*/
public function createTableQuery($table, $fields, $constraints)
{
$pg = $this->db->isPostgres();
@ -198,12 +259,17 @@ class Manager
$this->db->query($statement);
}
/**
* Возвращает дамп таблицы
* @param string $table_name
* @return array
*/
public function dumpTable($table_name)
{
$pg = $this->db->isPostgres();
$result = [];
$data = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";");
$data = $this->db->fetchAllArray("SELECT * FROM " . $table_name . ";");
if (!$pg) {
$table_fields = $this->tableInfo($table_name);
@ -220,14 +286,18 @@ class Manager
}
foreach ($data as $r) {
$result[] = [
"type" => "insert",
"table_name" => $table_name,
"values" => $r
"type" => "insert",
"table_name" => $table_name,
"values" => $r
];
}
return $result;
}
/**
* Возвращает все имена таблиц
* @return array
*/
public function getAllTableNames()
{
$result = [];
@ -243,6 +313,10 @@ class Manager
return $result;
}
/**
* Возвращает дамп всех таблиц
* @return array
*/
public function dumpInserts()
{
$table_names = $this->getAllTableNames();