debug: добавлена детальная отладка импорта CSV
- Добавлено логирование парсинга CSV на фронтенде - Добавлено логирование отправляемых данных - Добавлено детальное логирование в PHP бэкенде (каждая строка импорта) - Улучшена обработка ошибок с выводом подробной информации - Добавлен вывод SQL запросов при ошибках
This commit is contained in:
@@ -241,6 +241,11 @@ class DataService
|
||||
|
||||
public function insertMultipleRows(string $schema, string $table, array $rows, array $columns): array
|
||||
{
|
||||
error_log("=== НАЧАЛО ИМПОРТА CSV ===");
|
||||
error_log("Schema: $schema, Table: $table");
|
||||
error_log("Количество строк для импорта: " . count($rows));
|
||||
error_log("Структура первой строки: " . json_encode($rows[0] ?? []));
|
||||
|
||||
if (empty($rows)) {
|
||||
return ['inserted' => 0, 'errors' => 0, 'message' => 'No rows provided'];
|
||||
}
|
||||
@@ -255,6 +260,8 @@ public function insertMultipleRows(string $schema, string $table, array $rows, a
|
||||
$name = $c['COLUMN_NAME'];
|
||||
$extra = $c['EXTRA'] ?? '';
|
||||
|
||||
error_log("Столбец: $name, Extra: $extra, Nullable: " . ($c['IS_NULLABLE'] ? 'YES' : 'NO') . ", Default: " . ($c['COLUMN_DEFAULT'] ?? 'NULL'));
|
||||
|
||||
// Пропускаем только auto_increment поля
|
||||
if (!str_contains($extra, 'auto_increment')) {
|
||||
$validColumns[$name] = [
|
||||
@@ -262,13 +269,20 @@ public function insertMultipleRows(string $schema, string $table, array $rows, a
|
||||
'has_default' => !empty($c['COLUMN_DEFAULT']) || $c['COLUMN_DEFAULT'] === '0',
|
||||
'default' => $c['COLUMN_DEFAULT'] ?? null
|
||||
];
|
||||
} else {
|
||||
error_log("Пропускаем auto_increment столбец: $name");
|
||||
}
|
||||
}
|
||||
|
||||
error_log("Валидные столбцы для импорта: " . json_encode(array_keys($validColumns)));
|
||||
|
||||
$this->pdo->beginTransaction();
|
||||
|
||||
try {
|
||||
foreach ($rows as $index => $row) {
|
||||
error_log("\n--- Обработка строки " . ($index + 1) . " ---");
|
||||
error_log("Данные строки: " . json_encode($row));
|
||||
|
||||
try {
|
||||
$insertCols = [];
|
||||
$placeholders = [];
|
||||
@@ -281,22 +295,28 @@ public function insertMultipleRows(string $schema, string $table, array $rows, a
|
||||
// Если столбец есть в CSV строке
|
||||
if (array_key_exists($name, $row)) {
|
||||
$value = $row[$name];
|
||||
error_log(" Столбец '$name' найден в CSV: '$value'");
|
||||
|
||||
// ✅ Обрабатываем "NULL" как NULL
|
||||
if (in_array($value, ['NULL', 'null', ''], true)) {
|
||||
error_log(" Преобразуем '$value' в NULL");
|
||||
$value = null;
|
||||
}
|
||||
} else {
|
||||
error_log(" Столбец '$name' НЕ найден в CSV");
|
||||
// ✅ Столбца нет в CSV - устанавливаем NULL или пропускаем
|
||||
// Если поле имеет значение по умолчанию - пропускаем (БД сама подставит)
|
||||
if ($info['has_default']) {
|
||||
error_log(" Пропускаем (есть default): " . $info['default']);
|
||||
continue;
|
||||
}
|
||||
// Если поле nullable - ставим NULL
|
||||
if ($info['nullable']) {
|
||||
error_log(" Устанавливаем NULL (nullable)");
|
||||
$value = null;
|
||||
} else {
|
||||
// Поле обязательное и нет дефолта - ошибка
|
||||
error_log(" ОШИБКА: обязательное поле без значения");
|
||||
throw new \PDOException("Missing required field: $name");
|
||||
}
|
||||
}
|
||||
@@ -304,9 +324,11 @@ public function insertMultipleRows(string $schema, string $table, array $rows, a
|
||||
$insertCols[] = "`$name`";
|
||||
$placeholders[] = ":$name";
|
||||
$params[":$name"] = $value;
|
||||
error_log(" Добавлено в INSERT: '$name' = " . ($value === null ? 'NULL' : "'$value'"));
|
||||
}
|
||||
|
||||
if (empty($insertCols)) {
|
||||
error_log("Нет столбцов для вставки, пропускаем строку");
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -317,18 +339,28 @@ public function insertMultipleRows(string $schema, string $table, array $rows, a
|
||||
implode(',', $placeholders)
|
||||
);
|
||||
|
||||
error_log("SQL: $sql");
|
||||
error_log("Параметры: " . json_encode($params));
|
||||
|
||||
$stmt = $this->pdo->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
$inserted++;
|
||||
error_log("✓ Строка успешно вставлена, ID: " . $this->pdo->lastInsertId());
|
||||
} catch (\PDOException $e) {
|
||||
$errors++;
|
||||
$errorMessages[] = "Строка " . ($index + 1) . ": " . $this->formatPDOError($e, $schema, $table);
|
||||
$errorMsg = "Строка " . ($index + 1) . ": " . $this->formatPDOError($e, $schema, $table);
|
||||
error_log("✗ ОШИБКА при вставке строки " . ($index + 1) . ": " . $e->getMessage());
|
||||
error_log(" SQL Code: " . $e->getCode());
|
||||
error_log(" SQL State: " . ($e->errorInfo[0] ?? 'unknown'));
|
||||
$errorMessages[] = $errorMsg;
|
||||
}
|
||||
}
|
||||
|
||||
$this->pdo->commit();
|
||||
error_log("=== ИМПОРТ ЗАВЕРШЁН: вставлено=$inserted, ошибок=$errors ===");
|
||||
} catch (\Exception $e) {
|
||||
$this->pdo->rollBack();
|
||||
error_log("=== КРИТИЧЕСКАЯ ОШИБКА ИМПОРТА: " . $e->getMessage() . " ===");
|
||||
throw new \RuntimeException('Import failed: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user