This commit is contained in:
2025-08-19 23:38:52 +03:00
parent 5074629e40
commit cc3b1ef41b
8 changed files with 189 additions and 157 deletions

View File

@@ -11,6 +11,7 @@
use goodboyalex\php_db_components_pack\enums\DBDriver;
use goodboyalex\php_db_components_pack\enums\DBOperation;
use goodboyalex\php_db_components_pack\interfaces\IDBItem;
use goodboyalex\php_db_components_pack\models\DBItemProperty;
use PDO;
/**
@@ -36,7 +37,7 @@
public function Insert (string $table, IDBItem $row): mixed
{
// Подготавливаю запрос
[$sql, $params] = $this->PrepareInsertSQL($table, $row);
[$sql, $params, $primaryKeyValue] = $this->PrepareInsertSQL($table, $row);
// Выполняю запрос
$count = $this->Execute($sql, $params);
@@ -48,7 +49,7 @@
// Задаю переменную для последнего id
$lastId = match ($this->Config->Driver) {
DBDriver::MSSQL => $this->DataBaseHandle->query('SELECT SCOPE_IDENTITY()')->fetchColumn(),
DBDriver::MSSQL => $this->Query('SELECT SCOPE_IDENTITY() AS last_inserted_id;')['last_inserted_id'],
DBDriver::MySQL, DBDriver::SQLite => $this->DataBaseHandle->lastInsertId(),
DBDriver::PostgreSQL, DBDriver::OracleDB => $this->DataBaseHandle->lastInsertId('sequence_name')
};
@@ -58,6 +59,11 @@
// - то вывожу просто true
$lastId = true;
// Если id не генерировался
if ($lastId === null)
// - то вывожу -1
$lastId = $primaryKeyValue !== "NULL" ? $primaryKeyValue : true;
// Вывожу последний id
return $lastId;
}
@@ -106,12 +112,35 @@
* @param string $table Имя таблицы.
* @param IDBItem $row Элемент.
*
* @return Tuple Возвращает [запрос, параметры запроса].
* @return Tuple Возвращает [запрос, параметры запроса, значение первичного ключа].
*/
private function PrepareInsertSQL (string $table, IDBItem $row): Tuple
{
// Подготавливаю массив параметров
$params = $this->PrepareParamsArray(source: $row, operation: DBOperation::Insert);
$params = [];
// Получаю массив свойств
$properties = self::GetProperties($row, DBOperation::Insert);
/**
* Для каждого свойства...
*
* @var DBItemProperty $property Свойство.
*/
foreach ($properties as $property) {
// - пропускаю игнорируемые поля
if ($property->IsIgnored)
continue;
// - получаю значение имени поля
$fieldName = $property->Column->Name;
// - преобразую тип
$value = call_user_func($property->ConvertToDB, $property->Value);
// - добавляю в массив
$params[$fieldName] = $value;
}
// Получаю ключи параметров
$keys = array_keys($params);
@@ -140,10 +169,26 @@
// Значения sql запроса
$sql_values = implode(', ', $keys_values);
// Подготавливаю имя таблицы
$table = $this->PrepareTableName($table);
// Создаю запрос
$sql = "INSERT INTO $this->DBSignOpen$table$this->DBSignClose ($sql_keys) VALUES ($sql_values);";
$sql = "INSERT INTO $table ($sql_keys) VALUES ($sql_values);";
/**
* Получаю первичный ключ таблицы.
*
* @var false|DBItemProperty $key Первичный ключ таблицы.
*/
$key = $properties->GetRow(
selectCondition: fn (DBItemProperty $property): bool => $property->Column->IsPrimaryKey
);
// Передаю первичный ключ в переменную
$pKey = $key === false ? 'NULL' : $key->Value ?? "NULL";
// Возвращаю результат
return new Tuple($sql, $params);
return new Tuple($sql, $params, $pKey);
}
}