Skip to content

Commit ddcc6c2

Browse files
authored
feat(database): Supports CSV import and semantic layer analysis (#183)
* feat(csv): 支持 CSV 导入及语义层分析 (#165) - 区分 CSV 托管来源与 JDBC 引擎,复用 MySQL 数据源和分析链路 - 增加上传预览、字段类型确认、异步批量导入及原子语义发布 - 支持失败重试、删除补偿、任务恢复和过期文件清理 - 在查询及元数据入口校验表归属和就绪状态,沿用角色表权限 - 增加前端 CSV 分析空间、MySQL 5.7 兼容迁移及 Docker 配置说明 验证: - 后端主代码及既有测试编译通过,Checkstyle 和本次 Java 改动的 Spotless 检查通过 - 前端类型检查、生产构建及本次改动的 ESLint 检查通过 - MySQL 8.0 独立临时库验证导入、精确聚合、权限隔离、失败重试和删除 - 迁移脚本重复执行通过,未新增或执行单测,仅同步既有测试构造依赖 - MySQL 5.7 尚未实机验证;启用步骤见 docs/csv-import.md Refs #165 * fix(csv): harden import concurrency and lifecycle handling Preserve the application executor and align schema inference with empty-value handling. Isolate import attempts, bind retries to the submitting user, and guard publishing, deletion, and orphan cleanup against stale workers. Validate metric table references before deletion, share semantic conversion, and ignore stale upload and pagination responses. Make concurrent confirmations idempotent and return HTTP 413 for oversized multipart uploads. Document dedicated CSV database setup and upgrade requirements. Verified with 57 live integration checks and a successful backend build. * refactor(csv): clarify service boundaries and add domain error codes Extract shared datasource validation and inject the CSV executor by name. Generate preview metadata mappings with MapStruct while keeping task lifecycle initialization in the service. Remove the exception factory from the schema converter and introduce CSV-specific error codes through the existing exception handling flow. Document error codes and HTTP status mappings. Validated with a successful backend build and 24 temporary Spring context checks. * refactor(csv): share date validation and clarify worker workflows Centralize date parsing, the default timezone, and MySQL date range validation. Reuse these rules in CSV inference and conversion, the date tool, and agent prompts. Extract physical naming rules, organize worker execution and cleanup into focused methods, and tighten frontend column and task status types. Validated backend and frontend builds, lint, 9 existing date tool tests, 34 date and naming checks, 24 Spring context checks, and 47 live API checks. * refactor(csv): isolate editor state and streamline import completion Move shared table and column snapshots into model.bo and update semantic sync consumers. Deep-clone dialog input to keep nested edits independent of the parent list. Persist the final row count and DATA_READY state in one guarded update. Reuse UTF-8 byte counts from record validation when sizing import batches. Validated backend and frontend builds, lint, the existing semantic sync test, and focused checks for editor isolation, stale attempts, atomic completion, and byte limits. * refactor(csv): reuse domain enums and improve failure diagnostics Rename shared schema snapshots with the Bo suffix and use MapStruct for mechanical metadata mappings while keeping business defaults in services. Reuse existing datasource enums and retain contextual asynchronous failure diagnostics before compensation. * fix * fix(csv): preserve edits and synchronize import lifecycle Separate upload forms and cleanup responsibilities, reuse JSON utilities, and preserve local date and time values. Keep cleanup failures polling, serialize deletion and reference writes, and protect semantic refreshes from concurrent publication. * fix(csv): harden validation and datasource management Accept Tab delimiters and reject cross-database metric references. Add datasource-aware semantic navigation and isolate state when switching sources. Remove the single-datasource chat selector, clear CSV configuration defaults, and update portable setup documentation.
1 parent 8eb0e87 commit ddcc6c2

83 files changed

Lines changed: 4227 additions & 318 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.gitignore‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,3 +111,6 @@ yarn-integrity
111111

112112
application-dev.properties
113113
agents
114+
115+
# Local CSV uploaded source files
116+
/data-agent-backend/.local/

‎data-agent-backend/pom.xml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,11 @@
9393
</dependencyManagement>
9494

9595
<dependencies>
96+
<dependency>
97+
<groupId>org.apache.commons</groupId>
98+
<artifactId>commons-csv</artifactId>
99+
<version>1.14.1</version>
100+
</dependency>
96101
<dependency>
97102
<groupId>org.springframework.boot</groupId>
98103
<artifactId>spring-boot-starter-web</artifactId>

‎data-agent-backend/src/main/java/io/github/malonetalk/agent/AgentService.java‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -52,11 +52,11 @@
5252
import io.github.malonetalk.service.DatasourceService;
5353
import io.github.malonetalk.service.PermissionService;
5454
import io.github.malonetalk.service.SessionDatasourceService;
55+
import io.github.malonetalk.utils.DateTimeUtils;
5556
import io.opentelemetry.context.Context;
5657
import io.opentelemetry.instrumentation.reactor.v3_1.ContextPropagationOperator;
5758
import jakarta.annotation.PostConstruct;
5859
import java.time.LocalDate;
59-
import java.time.ZoneId;
6060
import java.util.ArrayList;
6161
import java.util.List;
6262
import java.util.Objects;
@@ -74,8 +74,6 @@
7474
@RequiredArgsConstructor
7575
public class AgentService {
7676

77-
private static final ZoneId DEFAULT_ZONE = ZoneId.of("Asia/Shanghai");
78-
7977
private final ModelFactory modelFactory;
8078
private final List<DataAgentTool> allToolBeans;
8179
private final ModelProperties modelProperties;
@@ -296,7 +294,7 @@ private ReActAgent createAgent(ToolCallContext toolCallContext) {
296294
}
297295

298296
private String systemPrompt() {
299-
LocalDate today = LocalDate.now(DEFAULT_ZONE);
297+
LocalDate today = LocalDate.now(DateTimeUtils.DEFAULT_ZONE);
300298
return """
301299
你是一个数据助手,可以帮助用户查询数据库中的数据。
302300
当前时区是 Asia/Shanghai。

‎data-agent-backend/src/main/java/io/github/malonetalk/agent/datasource/SchemaReader.java‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@
2222
import io.github.malonetalk.exception.BusinessException;
2323
import io.github.malonetalk.exception.ErrorCode;
2424
import io.github.malonetalk.model.converter.JdbcColumnMetadataConverter;
25+
import io.github.malonetalk.model.po.CsvImportPo;
2526
import io.github.malonetalk.model.po.DatasourcePo;
27+
import io.github.malonetalk.service.csv.CsvAccessService;
2628
import io.github.malonetalk.utils.SemanticUtils;
2729
import java.sql.Connection;
2830
import java.sql.DatabaseMetaData;
@@ -48,12 +50,14 @@ public class SchemaReader {
4850

4951
private final DynamicDataSourceManager dynamicDataSourceManager;
5052
private final JdbcColumnMetadataConverter columnMetadataConverter;
53+
private final CsvAccessService csvAccess;
5154

5255
public List<PhysicalTableInfo> getTables(DatasourcePo datasource) {
5356
javax.sql.DataSource ds = dynamicDataSourceManager.getOrCreateDataSource(datasource);
5457

5558
try (Connection conn = ds.getConnection()) {
56-
return getTables(conn);
59+
var ready = csvAccess.readyFilter(datasource);
60+
return getTables(conn).stream().filter(table -> ready.test(table.tableName())).toList();
5761
} catch (SQLException e) {
5862
log.error("Failed to read tables: {}", e.getMessage(), e);
5963
throw BusinessException.of(
@@ -64,6 +68,17 @@ public List<PhysicalTableInfo> getTables(DatasourcePo datasource) {
6468
}
6569

6670
public List<PhysicalColumnInfo> getTableSchema(DatasourcePo datasource, String tableName) {
71+
csvAccess.requireReady(datasource, tableName);
72+
return readTableSchema(datasource, tableName);
73+
}
74+
75+
public List<PhysicalColumnInfo> getImportTableSchema(
76+
DatasourcePo datasource, CsvImportPo task) {
77+
csvAccess.requireImportTable(datasource, task);
78+
return readTableSchema(datasource, task.getPhysicalTableName());
79+
}
80+
81+
private List<PhysicalColumnInfo> readTableSchema(DatasourcePo datasource, String tableName) {
6782
javax.sql.DataSource ds = dynamicDataSourceManager.getOrCreateDataSource(datasource);
6883

6984
try (Connection conn = ds.getConnection()) {
@@ -86,7 +101,9 @@ public Map<String, Set<String>> getTableColumnNames(
86101
return Map.of();
87102
}
88103
Map<String, Set<String>> columnNamesByTable = new LinkedHashMap<>();
104+
var ready = csvAccess.readyFilter(datasource);
89105
for (String tableName : tableNames) {
106+
if (!ready.test(tableName)) continue;
90107
columnNamesByTable.putIfAbsent(tableName, new LinkedHashSet<>());
91108
}
92109

‎data-agent-backend/src/main/java/io/github/malonetalk/agent/tools/impls/DateInfoTool.java‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
import io.github.malonetalk.agent.tools.ToolResultBoConverter;
2727
import io.github.malonetalk.exception.ExceptionResponseMapper;
2828
import io.github.malonetalk.model.bo.ToolResultBo;
29+
import io.github.malonetalk.utils.DateTimeUtils;
2930
import java.io.IOException;
3031
import java.net.URI;
3132
import java.net.http.HttpClient;
@@ -52,7 +53,6 @@
5253
@AllArgsConstructor(access = AccessLevel.PRIVATE)
5354
public class DateInfoTool implements DataAgentTool {
5455

55-
private static final String DEFAULT_TIMEZONE = "Asia/Shanghai";
5656
private static final String HOLIDAY_API_BASE_URL = "https://timor.tech/api/holiday/info";
5757

5858
private final ObjectMapper objectMapper;
@@ -122,10 +122,12 @@ public ToolResultBo getDateInfo(
122122

123123
DateInfo resolve(String startDateText, String endDateText, String timezoneText) {
124124
ZoneId zoneId =
125-
ZoneId.of(StringUtils.hasText(timezoneText) ? timezoneText : DEFAULT_TIMEZONE);
125+
StringUtils.hasText(timezoneText)
126+
? ZoneId.of(timezoneText)
127+
: DateTimeUtils.DEFAULT_ZONE;
126128
LocalDate startDate =
127129
StringUtils.hasText(startDateText)
128-
? LocalDate.parse(startDateText)
130+
? DateTimeUtils.parseDate(startDateText)
129131
: LocalDate.now(clock.withZone(zoneId));
130132
Optional<HolidayApiResponse> holidayApiResponse = queryHolidayApi(startDate);
131133
HolidayDetail holiday = holidayApiResponse.map(HolidayApiResponse::holiday).orElse(null);
@@ -144,7 +146,7 @@ DateInfo resolve(String startDateText, String endDateText, String timezoneText)
144146
.holidayDataAvailable(holidayApiResponse.isPresent())
145147
.dateDiff(
146148
StringUtils.hasText(endDateText)
147-
? resolveDateDiff(startDate, LocalDate.parse(endDateText))
149+
? resolveDateDiff(startDate, DateTimeUtils.parseDate(endDateText))
148150
: null)
149151
.build();
150152
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/*
2+
* Copyright (C) 2026 github.com/MaloneTalk
3+
*
4+
* This program is free software: you can redistribute it and/or modify
5+
* it under the terms of the GNU Affero General Public License as
6+
* published by the Free Software Foundation, either version 3 of the
7+
* License, or any later version.
8+
*
9+
* This program is distributed in the hope that it will be useful,
10+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
* GNU Affero General Public License for more details.
13+
*
14+
* You should have received a copy of the GNU Affero General Public License
15+
* along with this program. If not, see <https://www.gnu.org/licenses/>.
16+
* limitations under the License.
17+
*/
18+
package io.github.malonetalk.common;
19+
20+
/** Shared CSV limits keep request validation, file parsing and schema conversion consistent. */
21+
public final class CsvLimits {
22+
public static final int MAX_COLUMNS = 100;
23+
public static final int MAX_NAME_LENGTH = 200;
24+
25+
private CsvLimits() {}
26+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
* Copyright (C) 2026 github.com/MaloneTalk
3+
*
4+
* This program is free software: you can redistribute it and/or modify
5+
* it under the terms of the GNU Affero General Public License as
6+
* published by the Free Software Foundation, either version 3 of the
7+
* License, or any later version.
8+
*
9+
* This program is distributed in the hope that it will be useful,
10+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
* GNU Affero General Public License for more details.
13+
*
14+
* You should have received a copy of the GNU Affero General Public License
15+
* along with this program. If not, see <https://www.gnu.org/licenses/>.
16+
* limitations under the License.
17+
*/
18+
package io.github.malonetalk.config;
19+
20+
import java.nio.file.Path;
21+
import lombok.Data;
22+
import org.springframework.boot.context.properties.ConfigurationProperties;
23+
import org.springframework.context.annotation.Bean;
24+
import org.springframework.context.annotation.Configuration;
25+
import org.springframework.scheduling.annotation.EnableScheduling;
26+
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
27+
28+
@Data
29+
@Configuration
30+
@EnableScheduling
31+
@ConfigurationProperties(prefix = "csv-import")
32+
public class CsvImportConfig {
33+
private Integer datasourceId = 0;
34+
private Path directory = Path.of(System.getProperty("java.io.tmpdir"), "data-agent-csv");
35+
private String writerUrl = "";
36+
private String writerUsername = "";
37+
private String writerPassword = "";
38+
39+
// Keep Boot's applicationTaskExecutor available for MVC/SSE.
40+
@Bean(value = "csvImportExecutor", defaultCandidate = false)
41+
public ThreadPoolTaskExecutor csvImportExecutor() {
42+
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
43+
executor.setCorePoolSize(2);
44+
executor.setMaxPoolSize(2);
45+
executor.setQueueCapacity(0);
46+
executor.setThreadNamePrefix("csv-import-");
47+
executor.setWaitForTasksToCompleteOnShutdown(true);
48+
executor.setAwaitTerminationSeconds(40);
49+
return executor;
50+
}
51+
}
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
/*
2+
* Copyright (C) 2026 github.com/MaloneTalk
3+
*
4+
* This program is free software: you can redistribute it and/or modify
5+
* it under the terms of the GNU Affero General Public License as
6+
* published by the Free Software Foundation, either version 3 of the
7+
* License, or any later version.
8+
*
9+
* This program is distributed in the hope that it will be useful,
10+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
* GNU Affero General Public License for more details.
13+
*
14+
* You should have received a copy of the GNU Affero General Public License
15+
* along with this program. If not, see <https://www.gnu.org/licenses/>.
16+
* limitations under the License.
17+
*/
18+
package io.github.malonetalk.controller;
19+
20+
import io.github.malonetalk.annotation.RequirePermission;
21+
import io.github.malonetalk.enums.PermissionEnum;
22+
import io.github.malonetalk.model.dto.CsvImportConfirmDto;
23+
import io.github.malonetalk.model.dto.CsvParseOptions;
24+
import io.github.malonetalk.model.vo.BooleanVo;
25+
import io.github.malonetalk.model.vo.CsvImportPageVo;
26+
import io.github.malonetalk.model.vo.CsvImportVo;
27+
import io.github.malonetalk.service.csv.CsvImportService;
28+
import jakarta.validation.Valid;
29+
import lombok.RequiredArgsConstructor;
30+
import org.springframework.http.HttpStatus;
31+
import org.springframework.web.bind.annotation.DeleteMapping;
32+
import org.springframework.web.bind.annotation.GetMapping;
33+
import org.springframework.web.bind.annotation.PathVariable;
34+
import org.springframework.web.bind.annotation.PostMapping;
35+
import org.springframework.web.bind.annotation.PutMapping;
36+
import org.springframework.web.bind.annotation.RequestBody;
37+
import org.springframework.web.bind.annotation.RequestMapping;
38+
import org.springframework.web.bind.annotation.RequestParam;
39+
import org.springframework.web.bind.annotation.ResponseStatus;
40+
import org.springframework.web.bind.annotation.RestController;
41+
import org.springframework.web.multipart.MultipartFile;
42+
43+
@RestController
44+
@RequestMapping("/api/csv-imports")
45+
@RequiredArgsConstructor
46+
public class CsvImportController {
47+
private final CsvImportService service;
48+
49+
@PostMapping("/preview")
50+
@RequirePermission(PermissionEnum.DATA_CSV_IMPORT)
51+
public CsvImportVo preview(
52+
@RequestParam MultipartFile file,
53+
@RequestParam(defaultValue = "UTF-8") String encoding,
54+
@RequestParam(defaultValue = ",") String delimiter,
55+
@RequestParam(defaultValue = "true") boolean header,
56+
@RequestParam(defaultValue = "true") boolean emptyAsNull)
57+
throws Exception {
58+
return service.preview(
59+
file,
60+
CsvParseOptions.builder()
61+
.encoding(encoding)
62+
.delimiter(delimiter)
63+
.header(header)
64+
.emptyAsNull(emptyAsNull)
65+
.build());
66+
}
67+
68+
@PutMapping("/{id}/preview")
69+
@RequirePermission(PermissionEnum.DATA_CSV_IMPORT)
70+
public CsvImportVo repreview(
71+
@PathVariable String id, @Valid @RequestBody CsvParseOptions options) throws Exception {
72+
return service.repreview(id, options);
73+
}
74+
75+
@PostMapping("/{id}/confirm")
76+
@ResponseStatus(HttpStatus.ACCEPTED)
77+
@RequirePermission({PermissionEnum.DATA_CSV_IMPORT, PermissionEnum.SEMANTIC_TABLE_SYNC})
78+
public CsvImportVo confirm(
79+
@PathVariable String id, @Valid @RequestBody CsvImportConfirmDto request) {
80+
return service.confirm(id, request);
81+
}
82+
83+
@GetMapping("/{id}")
84+
@RequirePermission(
85+
value = {
86+
PermissionEnum.DATA_CSV_IMPORT,
87+
PermissionEnum.DATA_CSV_DELETE,
88+
PermissionEnum.DATA_DATASOURCE_READ
89+
},
90+
anyOf = true)
91+
public CsvImportVo get(@PathVariable String id) {
92+
return service.get(id);
93+
}
94+
95+
@GetMapping
96+
@RequirePermission(
97+
value = {
98+
PermissionEnum.DATA_CSV_IMPORT,
99+
PermissionEnum.DATA_CSV_DELETE,
100+
PermissionEnum.DATA_DATASOURCE_READ
101+
},
102+
anyOf = true)
103+
public CsvImportPageVo list(
104+
@RequestParam(defaultValue = "1") int page,
105+
@RequestParam(defaultValue = "10") int pageSize) {
106+
return service.list(page, pageSize);
107+
}
108+
109+
@PostMapping("/{id}/sync")
110+
@ResponseStatus(HttpStatus.ACCEPTED)
111+
@RequirePermission({PermissionEnum.DATA_CSV_IMPORT, PermissionEnum.SEMANTIC_TABLE_SYNC})
112+
public BooleanVo sync(@PathVariable String id) {
113+
service.retrySync(id);
114+
return BooleanVo.TRUE;
115+
}
116+
117+
@DeleteMapping("/{id}")
118+
@RequirePermission(PermissionEnum.DATA_CSV_DELETE)
119+
public BooleanVo delete(@PathVariable String id) throws Exception {
120+
service.delete(id);
121+
return BooleanVo.TRUE;
122+
}
123+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
* Copyright (C) 2026 github.com/MaloneTalk
3+
*
4+
* This program is free software: you can redistribute it and/or modify
5+
* it under the terms of the GNU Affero General Public License as
6+
* published by the Free Software Foundation, either version 3 of the
7+
* License, or any later version.
8+
*
9+
* This program is distributed in the hope that it will be useful,
10+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
* GNU Affero General Public License for more details.
13+
*
14+
* You should have received a copy of the GNU Affero General Public License
15+
* along with this program. If not, see <https://www.gnu.org/licenses/>.
16+
* limitations under the License.
17+
*/
18+
package io.github.malonetalk.enums;
19+
20+
public enum CsvImportStatus {
21+
PREVIEWED,
22+
QUEUED,
23+
IMPORTING,
24+
DATA_READY,
25+
SYNCING,
26+
READY,
27+
IMPORT_FAILED,
28+
SYNC_FAILED,
29+
CLEANING,
30+
CLEANUP_FAILED,
31+
DELETING,
32+
DELETE_FAILED,
33+
EXPIRED
34+
}

0 commit comments

Comments
 (0)