{"record":{"id":"19d4c760ecd22ade","repo":"iflytek/astron-agent","slug":"database-import-failed","errorCode":"DATABASE_IMPORT_FAILED","errorMessage":"importTableData partial failures: {}","messagePattern":"importTableData partial failures: (.+?)","errorType":"exception","errorClass":"BusinessException","httpStatus":null,"severity":"error","filePath":"console/backend/toolkit/src/main/java/com/iflytek/astron/console/toolkit/service/database/DatabaseService.java","lineNumber":945,"sourceCode":"                                sql,\n                                UserInfoManagerHandler.getUserId(),\n                                SpaceInfoUtil.getSpaceId(),\n                                dbInfo.getDbId(),\n                                DBOperateEnum.INSERT.getCode(),\n                                execDev);\n                    });\n\n            // 3) Summary\n            if (!summary.errors.isEmpty()) {\n                // Record the first 10 failed examples\n                StringBuilder sb = new StringBuilder();\n                sb.append(\"导入部分失败：success=\")\n                        .append(summary.success)\n                        .append(\", failed=\")\n                        .append(summary.failed)\n                        .append(\". 失败样例：\");\n                summary.errors.stream().limit(10).forEach(err -> sb.append(\"\\n#\").append(err.index).append(\" : \").append(err.message));\n                log.warn(\"importTableData partial failures: {}\", sb);\n                throw new BusinessException(ResponseEnum.DATABASE_IMPORT_FAILED);\n            }\n        } catch (Exception ex) {\n            log.error(\"import data failed, tbId={}, execDev={}, fileName={}\", tbId, execDev, file.getOriginalFilename(), ex);\n            throw new BusinessException(ResponseEnum.DATABASE_IMPORT_FAILED);\n        }\n    }\n\n    @Transactional\n    public void copyTable(Long tbId) {\n        try {\n            DbTable dbTable = dbTableMapper.selectById(tbId);\n            // Unify and standardize the copy names, and avoid illegal characters\n            String tableName = NamePolicy.copyName(dbTable.getName());\n\n            // build DDL CREATE TABLE new AS SELECT * FROM old\n            DbTableDto dbTableDto = new DbTableDto();\n            dbTableDto.setName(tableName);","sourceCodeStart":927,"sourceCodeEnd":963,"githubUrl":"https://github.com/iflytek/astron-agent/blob/5e758547a83371a5a4b29dadf4ac03e8dd527635/console/backend/toolkit/src/main/java/com/iflytek/astron/console/toolkit/service/database/DatabaseService.java#L927-L963","documentation":"DatabaseService.importTableData imports rows from an uploaded file into a database table. When some rows fail (summary.failed > 0) it builds a diagnostic message with up to 10 failed-row samples, logs it as a warning, and throws BusinessException(DATABASE_IMPORT_FAILED). Any other exception during import is caught, logged, and also converted to DATABASE_IMPORT_FAILED.","triggerScenarios":"Batch insert where one or more rows violate the target schema: type mismatch, constraint/PK violation, null in NOT NULL column, value out of range, string too long, or an SQL error mid-import (connection loss, permission denied).","commonSituations":"Excel/CSV upload with malformed cells (text in numeric columns, wrong date formats); file encoding mismatch causing garbage values; table schema changed after the file was exported; importing into the wrong database type (MySQL vs PostgreSQL dialect differences).","solutions":["Read the logged '导入部分失败' summary with failed-row samples (index + message) and fix those specific rows in the source file.","Validate the file's columns against the current table schema (types, NOT NULL, lengths) before re-uploading.","Check date/number formats in the file match the table column expectations and locale.","Verify the file encoding (UTF-8 vs GBK) matches what the parser expects to avoid corrupted values.","If the whole import fails (log line 'import data failed'), check the full exception for SQL/connection errors and database permissions."],"exampleFix":"// before\n// CSV cell: created_at = \"2026/9/12\" while column expects 'yyyy-MM-dd HH:mm:ss'\n\n// after\n// normalize dates in the file or during row conversion\nLocalDateTime dt = LocalDate.parse(raw, DateTimeFormatter.ofPattern(\"yyyy/M/d\")).atStartOfDay();","handlingStrategy":"validation","validationCode":"// validate the file rows against the table schema before import\nrows.forEach((row, i) => {\n  schema.columns.forEach((c) => {\n    const v = row[c.name];\n    if (c.notNull && (v == null || v === '')) throw new Error(`Row ${i}: ${c.name} is required`);\n    if (v != null && c.type === 'number' && isNaN(Number(v))) throw new Error(`Row ${i}: ${c.name} must be numeric`);\n  });\n});","typeGuard":null,"tryCatchPattern":"try {\n  await dbService.importTableData(tbId, file);\n} catch (e) {\n  if (e.code === 'DATABASE_IMPORT_FAILED') {\n    // server log 'importTableData partial failures' lists failing row indexes/messages\n    console.error('Import failed: fix flagged rows in the source file, then re-upload');\n  } else throw e;\n}","preventionTips":["Dry-run validation of each row against the current table schema before writing.","Normalize dates/numbers/encodings (UTF-8) in the upload pipeline.","Re-validate files against the schema after any table DDL change.","Import in batches with per-row error capture rather than failing the whole batch silently."],"tags":["database","import","data-validation","batch-insert"],"backgroundTag":"database-write-failed","analyzedSha":"5e758547a83371a5a4b29dadf4ac03e8dd527635","analyzedAt":"2026-09-12T08:03:51.356Z","contentChangedAt":"2026-09-12T08:03:51.356Z","schemaVersion":2},"datasetVersion":"2026-09-15T23:17:13.987Z"}