页面优化 数据采集

This commit is contained in:
lmy
2026-10-23 15:16:27 +08:00
parent a68f27f7f2
commit 20660da286
13 changed files with 425 additions and 88 deletions
+5
View File
@@ -63,6 +63,11 @@
<artifactId>postgresql</artifactId> <artifactId>postgresql</artifactId>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 连接池 --> <!-- 连接池 -->
<dependency> <dependency>
@@ -30,6 +30,20 @@ public class CollectController {
return Result.success(collectService.createTask(task)); return Result.success(collectService.createTask(task));
} }
@Operation(summary = "修改采集任务")
@PutMapping("/task/{id}")
public Result<Void> updateTask(@PathVariable Long id, @RequestBody CollectTask task) {
collectService.updateTask(id, task);
return Result.success();
}
@Operation(summary = "删除采集任务")
@DeleteMapping("/task/{id}")
public Result<Void> removeTask(@PathVariable Long id) {
collectService.removeTask(id);
return Result.success();
}
@Operation(summary = "测试来源库连接,并查看表字段如何写入版本资源表") @Operation(summary = "测试来源库连接,并查看表字段如何写入版本资源表")
@PostMapping("/preview") @PostMapping("/preview")
public Result<CollectTableVO> preview(@RequestBody CollectTask source) { public Result<CollectTableVO> preview(@RequestBody CollectTask source) {
@@ -0,0 +1,27 @@
package com.banben.modules.collect.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 版本资源表字段与来源列的对照。
*/
@Data
@Schema(description = "版本资源字段对照")
public class CollectFieldCompareVO {
@Schema(description = "version_resource 字段名")
private String targetField;
@Schema(description = "字段中文名")
private String targetLabel;
@Schema(description = "是否为必备字段")
private boolean required;
@Schema(description = "对应的来源列名,没有则为空")
private String sourceColumn;
@Schema(description = "来源表是否有列对应到该字段")
private boolean matched;
}
@@ -21,4 +21,7 @@ public class CollectTableVO {
@Schema(description = "列与版本资源字段的对应关系") @Schema(description = "列与版本资源字段的对应关系")
private List<CollectColumnVO> columns = new ArrayList<>(); private List<CollectColumnVO> columns = new ArrayList<>();
@Schema(description = "版本资源表字段与来源列的对照")
private List<CollectFieldCompareVO> compares = new ArrayList<>();
} }
@@ -36,7 +36,10 @@ public class CollectTask implements Serializable {
@Schema(description = "数据库地址,如 10.1.1.14") @Schema(description = "数据库地址,如 10.1.1.14")
private String dbHost; private String dbHost;
@Schema(description = "数据库端口,瀚高默认 5866,PostgreSQL 默认 5432") @Schema(description = "来源数据库类型:MYSQL 或 POSTGRESQL(瀚高走 PostgreSQL 协议)")
private String dbType;
@Schema(description = "数据库端口。MySQL 常用 3306,PostgreSQL 常用 5432,瀚高常用 5866")
private Integer dbPort; private Integer dbPort;
@Schema(description = "数据库名") @Schema(description = "数据库名")
@@ -16,6 +16,16 @@ public interface CollectService extends IService<CollectTask> {
*/ */
Long createTask(CollectTask task); Long createTask(CollectTask task);
/**
* 修改采集任务的连接信息。密码留空则保持原密码。
*/
void updateTask(Long id, CollectTask task);
/**
* 删除采集任务。
*/
void removeTask(Long id);
/** /**
* 执行采集任务,返回执行后的任务(含采集条数和结果说明)。 * 执行采集任务,返回执行后的任务(含采集条数和结果说明)。
*/ */
@@ -50,7 +50,7 @@ public class CollectServiceImpl extends ServiceImpl<CollectTaskMapper, CollectTa
.collect(Collectors.toMap(c -> c.sourceType().toUpperCase(), Function.identity(), (a, b) -> a)); .collect(Collectors.toMap(c -> c.sourceType().toUpperCase(), Function.identity(), (a, b) -> a));
} }
/** 创建任务:初始状态 PENDING、已采集量 0,目标量缺省为 20 万条。 */ /** 创建任务:初始状态 PENDING、已采集量 0。来源表至少要有一列能写入版本资源表。 */
@Override @Override
public Long createTask(CollectTask task) { public Long createTask(CollectTask task) {
task.setId(null); task.setId(null);
@@ -59,15 +59,78 @@ public class CollectServiceImpl extends ServiceImpl<CollectTaskMapper, CollectTa
if (task.getTargetCount() == null) { if (task.getTargetCount() == null) {
task.setTargetCount(200000); task.setTargetCount(200000);
} }
ensureMapped(task);
this.save(task); this.save(task);
return task.getId(); return task.getId();
} }
@Override
public void updateTask(Long id, CollectTask task) {
CollectTask stored = requireTask(id);
if ("RUNNING".equals(stored.getStatus())) {
throw new BusinessException("任务正在执行,不能修改");
}
stored.setLibraryCode(task.getLibraryCode());
stored.setLibraryName(task.getLibraryName());
stored.setSourceType(task.getSourceType() == null ? "DB" : task.getSourceType());
stored.setDbHost(task.getDbHost());
stored.setDbType(task.getDbType());
stored.setDbPort(task.getDbPort());
stored.setDbName(task.getDbName());
stored.setDbUsername(task.getDbUsername());
stored.setSourceTable(task.getSourceTable());
if (task.getDbPassword() != null && !task.getDbPassword().isBlank()) {
stored.setDbPassword(task.getDbPassword());
}
ensureMapped(stored);
this.updateById(stored);
}
@Override
public void removeTask(Long id) {
CollectTask stored = requireTask(id);
if ("RUNNING".equals(stored.getStatus())) {
throw new BusinessException("任务正在执行,不能删除");
}
this.removeById(id);
}
@Override @Override
public CollectTableVO previewSource(CollectTask source) { public CollectTableVO previewSource(CollectTask source) {
fillPassword(source);
return dbTableCollector.preview(source); return dbTableCollector.preview(source);
} }
private CollectTask requireTask(Long id) {
CollectTask stored = this.getById(id);
if (stored == null) {
throw new BusinessException("采集任务不存在");
}
return stored;
}
/** 编辑时密码留空,沿用已保存的密码再去测试连接。 */
private void fillPassword(CollectTask source) {
if (source.getDbPassword() != null && !source.getDbPassword().isBlank()) {
return;
}
if (source.getId() == null) {
return;
}
CollectTask stored = this.getById(source.getId());
if (stored != null) {
source.setDbPassword(stored.getDbPassword());
}
}
private void ensureMapped(CollectTask task) {
CollectTableVO preview = previewSource(task);
boolean matched = preview.getColumns().stream().anyMatch(column -> column.getTargetField() != null);
if (!matched) {
throw new BusinessException("来源表至少要有一列能对应到版本资源表");
}
}
@Override @Override
public CollectTask startTask(Long taskId) { public CollectTask startTask(Long taskId) {
CollectTask task = this.getById(taskId); CollectTask task = this.getById(taskId);
@@ -3,6 +3,7 @@ package com.banben.modules.collect.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.banben.common.BusinessException; import com.banben.common.BusinessException;
import com.banben.modules.collect.dto.CollectColumnVO; import com.banben.modules.collect.dto.CollectColumnVO;
import com.banben.modules.collect.dto.CollectFieldCompareVO;
import com.banben.modules.collect.dto.CollectTableVO; import com.banben.modules.collect.dto.CollectTableVO;
import com.banben.modules.collect.entity.CollectTask; import com.banben.modules.collect.entity.CollectTask;
import com.banben.modules.collect.service.Collector; import com.banben.modules.collect.service.Collector;
@@ -44,6 +45,12 @@ public class DbTableCollector implements Collector {
private static final DateTimeFormatter DAY = DateTimeFormatter.ofPattern("yyyyMMdd"); private static final DateTimeFormatter DAY = DateTimeFormatter.ofPattern("yyyyMMdd");
private static final int MAX_ROWS = 200000; private static final int MAX_ROWS = 200000;
/** 写入 version_resource 时建议具备的字段。正题名未对应则该行无法入库。 */
private static final List<String> REQUIRED_FIELDS = List.of(
"title", "processNo", "clcCode", "keywords", "summary", "publishYear", "processDate",
"contentForm", "mediaType", "format", "language", "fulltextUrl"
);
private static final Map<String, String> FIELD_BY_COLUMN = new HashMap<>(); private static final Map<String, String> FIELD_BY_COLUMN = new HashMap<>();
private static final Map<String, String> FIELD_LABEL = new LinkedHashMap<>(); private static final Map<String, String> FIELD_LABEL = new LinkedHashMap<>();
private static final Map<String, BiConsumer<VersionResource, String>> SETTERS = new HashMap<>(); private static final Map<String, BiConsumer<VersionResource, String>> SETTERS = new HashMap<>();
@@ -151,13 +158,14 @@ public class DbTableCollector implements Collector {
* 用页面填写的地址、账号和表名连接来源库,返回行数以及列如何写入版本资源表。 * 用页面填写的地址、账号和表名连接来源库,返回行数以及列如何写入版本资源表。
*/ */
public CollectTableVO preview(CollectTask task) { public CollectTableVO preview(CollectTask task) {
String[] qualified = qualify(task.getSourceTable()); String[] qualified = qualify(task);
try (Connection connection = openConnection(task)) { try (Connection connection = openConnection(task)) {
ensureTable(connection, qualified[0], qualified[1]); qualified[1] = canonicalTable(connection, qualified[0], qualified[1], mysql(task));
CollectTableVO table = new CollectTableVO(); CollectTableVO table = new CollectTableVO();
table.setTableName(qualified[0] + "." + qualified[1]); table.setTableName(qualified[0] + "." + qualified[1]);
table.setRowCount(countRows(connection, qualified[0], qualified[1])); table.setRowCount(countRows(connection, qualified[0], qualified[1], mysql(task)));
table.setColumns(readColumns(connection, qualified[0], qualified[1])); table.setColumns(readColumns(connection, qualified[0], qualified[1]));
table.setCompares(buildCompares(table.getColumns()));
return table; return table;
} catch (SQLException e) { } catch (SQLException e) {
throw new BusinessException(sqlMessage(e)); throw new BusinessException(sqlMessage(e));
@@ -166,12 +174,16 @@ public class DbTableCollector implements Collector {
@Override @Override
public int collect(CollectTask task) { public int collect(CollectTask task) {
String[] qualified = qualify(task.getSourceTable()); String[] qualified = qualify(task);
int limit = task.getTargetCount() == null ? MAX_ROWS : Math.min(Math.max(task.getTargetCount(), 1), MAX_ROWS); int limit = task.getTargetCount() == null ? MAX_ROWS : Math.min(Math.max(task.getTargetCount(), 1), MAX_ROWS);
List<Map<String, Object>> rows; List<Map<String, Object>> rows;
try (Connection connection = openConnection(task)) { try (Connection connection = openConnection(task)) {
ensureTable(connection, qualified[0], qualified[1]); qualified[1] = canonicalTable(connection, qualified[0], qualified[1], mysql(task));
rows = readRows(connection, qualified[0], qualified[1], limit); List<CollectColumnVO> columns = readColumns(connection, qualified[0], qualified[1]);
if (columns.stream().noneMatch(column -> column.getTargetField() != null)) {
throw new BusinessException("来源表至少要有一列能对应到版本资源表,无法写入");
}
rows = readRows(connection, qualified[0], qualified[1], limit, mysql(task));
} catch (SQLException e) { } catch (SQLException e) {
throw new BusinessException(sqlMessage(e)); throw new BusinessException(sqlMessage(e));
} }
@@ -260,7 +272,11 @@ public class DbTableCollector implements Collector {
if (blank(task.getDbPassword())) { if (blank(task.getDbPassword())) {
throw new BusinessException("请填写数据库密码"); throw new BusinessException("请填写数据库密码");
} }
String url = "jdbc:postgresql://" + task.getDbHost().trim() + ":" + port + "/" String url = mysql(task)
? "jdbc:mysql://" + task.getDbHost().trim() + ":" + port + "/" + task.getDbName().trim()
+ "?connectTimeout=8000&socketTimeout=30000&useSSL=false&allowPublicKeyRetrieval=true"
+ "&characterEncoding=utf8&serverTimezone=Asia/Shanghai"
: "jdbc:postgresql://" + task.getDbHost().trim() + ":" + port + "/"
+ task.getDbName().trim() + "?connectTimeout=8&socketTimeout=30"; + task.getDbName().trim() + "?connectTimeout=8&socketTimeout=30";
Properties properties = new Properties(); Properties properties = new Properties();
properties.setProperty("user", task.getDbUsername().trim()); properties.setProperty("user", task.getDbUsername().trim());
@@ -272,47 +288,87 @@ public class DbTableCollector implements Collector {
} }
} }
private String[] qualify(String raw) { /**
if (blank(raw)) { * 按页面选择的数据库类型决定驱动。未填写类型的旧任务仍按 3306 识别为 MySQL。
*/
private boolean mysql(CollectTask task) {
String type = task.getDbType() == null ? "" : task.getDbType().trim().toUpperCase(Locale.ROOT);
if ("MYSQL".equals(type)) {
return true;
}
if ("POSTGRESQL".equals(type) || "HIGHGO".equals(type)) {
return false;
}
if (type.isEmpty()) {
return task.getDbPort() != null && task.getDbPort() == 3306;
}
throw new BusinessException("数据库类型只支持 MySQL 或 PostgreSQL");
}
private String[] qualify(CollectTask task) {
if (blank(task.getSourceTable())) {
throw new BusinessException("请填写要采集的表名"); throw new BusinessException("请填写要采集的表名");
} }
String[] parts = raw.trim().split("\\."); String[] parts = task.getSourceTable().trim().split("\\.");
if (parts.length > 2) { if (parts.length > 2) {
throw new BusinessException("表名格式应为表名,或模式名.表名"); throw new BusinessException("表名格式应为表名,或模式名.表名");
} }
String schema = parts.length == 2 ? parts[0] : "public"; boolean mysql = mysql(task);
String schema = parts.length == 2 ? parts[0] : (mysql ? task.getDbName().trim() : "public");
String table = parts.length == 2 ? parts[1] : parts[0]; String table = parts.length == 2 ? parts[1] : parts[0];
if (!schema.matches("[A-Za-z_][A-Za-z0-9_]*") || !table.matches("[A-Za-z_][A-Za-z0-9_]*")) { if (!schema.matches("[A-Za-z_][A-Za-z0-9_]*") || !table.matches("[A-Za-z_][A-Za-z0-9_]*")) {
throw new BusinessException("表名只能包含字母、数字和下划线"); throw new BusinessException("表名只能包含字母、数字和下划线");
} }
return new String[]{schema.toLowerCase(Locale.ROOT), table.toLowerCase(Locale.ROOT)}; if (!mysql) {
schema = schema.toLowerCase(Locale.ROOT);
table = table.toLowerCase(Locale.ROOT);
}
return new String[]{schema, table};
} }
private void ensureTable(Connection connection, String schema, String table) throws SQLException { private String canonicalTable(Connection connection, String schema, String table, boolean mysql) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(""" String sql = mysql
SELECT COUNT(*) FROM information_schema.tables ? """
SELECT table_name FROM information_schema.tables
WHERE table_schema = ? AND LOWER(table_name) = LOWER(?)
"""
: """
SELECT table_name FROM information_schema.tables
WHERE table_schema = ? AND table_name = ? WHERE table_schema = ? AND table_name = ?
""")) { """;
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, schema); statement.setString(1, schema);
statement.setString(2, table); statement.setString(2, table);
try (ResultSet resultSet = statement.executeQuery()) { try (ResultSet resultSet = statement.executeQuery()) {
resultSet.next(); String found = null;
if (resultSet.getInt(1) == 0) { while (resultSet.next()) {
String name = resultSet.getString(1);
if (name.equals(table)) {
return name;
}
found = name;
}
if (found == null) {
throw new BusinessException("来源库中不存在表:" + schema + "." + table); throw new BusinessException("来源库中不存在表:" + schema + "." + table);
} }
return found;
} }
} }
} }
private long countRows(Connection connection, String schema, String table) throws SQLException { private long countRows(Connection connection, String schema, String table, boolean mysql) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement( try (PreparedStatement statement = connection.prepareStatement(
"SELECT COUNT(*) FROM \"" + schema + "\".\"" + table + "\""); "SELECT COUNT(*) FROM " + quote(schema, mysql) + "." + quote(table, mysql));
ResultSet resultSet = statement.executeQuery()) { ResultSet resultSet = statement.executeQuery()) {
resultSet.next(); resultSet.next();
return resultSet.getLong(1); return resultSet.getLong(1);
} }
} }
private String quote(String identifier, boolean mysql) {
return mysql ? "`" + identifier + "`" : "\"" + identifier + "\"";
}
private List<CollectColumnVO> readColumns(Connection connection, String schema, String table) throws SQLException { private List<CollectColumnVO> readColumns(Connection connection, String schema, String table) throws SQLException {
List<CollectColumnVO> columns = new ArrayList<>(); List<CollectColumnVO> columns = new ArrayList<>();
try (PreparedStatement statement = connection.prepareStatement(""" try (PreparedStatement statement = connection.prepareStatement("""
@@ -337,11 +393,11 @@ public class DbTableCollector implements Collector {
return columns; return columns;
} }
private List<Map<String, Object>> readRows(Connection connection, String schema, String table, int limit) private List<Map<String, Object>> readRows(Connection connection, String schema, String table, int limit,
throws SQLException { boolean mysql) throws SQLException {
List<Map<String, Object>> rows = new ArrayList<>(); List<Map<String, Object>> rows = new ArrayList<>();
try (PreparedStatement statement = connection.prepareStatement( try (PreparedStatement statement = connection.prepareStatement(
"SELECT * FROM \"" + schema + "\".\"" + table + "\" LIMIT " + limit); "SELECT * FROM " + quote(schema, mysql) + "." + quote(table, mysql) + " LIMIT " + limit);
ResultSet resultSet = statement.executeQuery()) { ResultSet resultSet = statement.executeQuery()) {
ResultSetMetaData meta = resultSet.getMetaData(); ResultSetMetaData meta = resultSet.getMetaData();
while (resultSet.next()) { while (resultSet.next()) {
@@ -358,13 +414,14 @@ public class DbTableCollector implements Collector {
private String sqlMessage(SQLException exception) { private String sqlMessage(SQLException exception) {
String message = exception.getMessage() == null ? "" : exception.getMessage(); String message = exception.getMessage() == null ? "" : exception.getMessage();
String lower = message.toLowerCase(Locale.ROOT); String lower = message.toLowerCase(Locale.ROOT);
if (lower.contains("password authentication failed") || lower.contains("authentication failed")) { if (lower.contains("password authentication failed") || lower.contains("authentication failed")
|| lower.contains("access denied")) {
return "数据库用户名或密码错误"; return "数据库用户名或密码错误";
} }
if (lower.contains("does not exist") && lower.contains("database")) { if ((lower.contains("does not exist") && lower.contains("database")) || lower.contains("unknown database")) {
return "数据库不存在"; return "数据库不存在";
} }
if (lower.contains("connection refused")) { if (lower.contains("connection refused") || lower.contains("communications link failure")) {
return "连接被拒绝,请检查数据库地址和端口"; return "连接被拒绝,请检查数据库地址和端口";
} }
if (lower.contains("timeout") || lower.contains("timed out")) { if (lower.contains("timeout") || lower.contains("timed out")) {
@@ -377,6 +434,37 @@ public class DbTableCollector implements Collector {
return brief.isEmpty() ? "连接数据库失败" : "连接数据库失败:" + brief; return brief.isEmpty() ? "连接数据库失败" : "连接数据库失败:" + brief;
} }
private List<CollectFieldCompareVO> buildCompares(List<CollectColumnVO> columns) {
Map<String, String> sourceByField = new LinkedHashMap<>();
for (CollectColumnVO column : columns) {
if (column.getTargetField() != null) {
sourceByField.putIfAbsent(column.getTargetField(), column.getColumnName());
}
}
List<CollectFieldCompareVO> compares = new ArrayList<>();
Set<String> seen = new HashSet<>();
for (String field : REQUIRED_FIELDS) {
compares.add(compareItem(field, true, sourceByField));
seen.add(field);
}
for (String field : FIELD_LABEL.keySet()) {
if (!seen.contains(field)) {
compares.add(compareItem(field, false, sourceByField));
}
}
return compares;
}
private CollectFieldCompareVO compareItem(String field, boolean required, Map<String, String> sourceByField) {
CollectFieldCompareVO item = new CollectFieldCompareVO();
item.setTargetField(field);
item.setTargetLabel(FIELD_LABEL.get(field));
item.setRequired(required);
item.setSourceColumn(sourceByField.get(field));
item.setMatched(item.getSourceColumn() != null);
return item;
}
private Set<String> loadProcessNos() { private Set<String> loadProcessNos() {
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>(); LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
query.select(VersionResource::getProcessNo).isNotNull(VersionResource::getProcessNo); query.select(VersionResource::getProcessNo).isNotNull(VersionResource::getProcessNo);
@@ -18,7 +18,7 @@ import java.util.List;
/** /**
* 数据治理接口。 * 数据治理接口。
* *
* <p>对应「数据治理」四动作:聚同、优化、提示、提纯。</p> * <p>对应「数据治理」:聚同、优化、提示、提纯。</p>
* <ul> * <ul>
* <li>优化:整合聚同文献的不同描述元数据,生成质量更高、要素更完整的元数据。</li> * <li>优化:整合聚同文献的不同描述元数据,生成质量更高、要素更完整的元数据。</li>
* <li>提示:生成疑似同一文献提示清单、疑似元数据错漏提示清单。</li> * <li>提示:生成疑似同一文献提示清单、疑似元数据错漏提示清单。</li>
@@ -0,0 +1,4 @@
-- 采集任务记录来源库类型,连接时按类型选择驱动。
ALTER TABLE collect_task ADD COLUMN IF NOT EXISTS db_type VARCHAR(32);
COMMENT ON COLUMN collect_task.db_type IS '来源数据库类型:MYSQL 或 POSTGRESQL';
@@ -53,6 +53,7 @@ CREATE TABLE IF NOT EXISTS collect_task
library_name VARCHAR(256), -- 单位名称 library_name VARCHAR(256), -- 单位名称
source_type VARCHAR(64), -- 数据源类型:MARC/EXCEL/DB/API source_type VARCHAR(64), -- 数据源类型:MARC/EXCEL/DB/API
db_host VARCHAR(256), -- 来源库地址 db_host VARCHAR(256), -- 来源库地址
db_type VARCHAR(32), -- 来源库类型:MYSQL / POSTGRESQL
db_port INTEGER, -- 来源库端口 db_port INTEGER, -- 来源库端口
db_name VARCHAR(128), -- 来源库名 db_name VARCHAR(128), -- 来源库名
db_username VARCHAR(128), -- 来源库用户名 db_username VARCHAR(128), -- 来源库用户名
+21
View File
@@ -6,6 +6,8 @@ export interface CollectTask {
libraryName?: string libraryName?: string
sourceType?: string sourceType?: string
dbHost?: string dbHost?: string
/** MYSQL 或 POSTGRESQL */
dbType?: string
dbPort?: number dbPort?: number
dbName?: string dbName?: string
dbUsername?: string dbUsername?: string
@@ -27,10 +29,19 @@ export interface CollectColumn {
targetLabel?: string targetLabel?: string
} }
export interface CollectFieldCompare {
targetField: string
targetLabel: string
required: boolean
sourceColumn?: string
matched: boolean
}
export interface CollectTable { export interface CollectTable {
tableName: string tableName: string
rowCount: number rowCount: number
columns: CollectColumn[] columns: CollectColumn[]
compares: CollectFieldCompare[]
} }
/** 创建采集任务 */ /** 创建采集任务 */
@@ -38,6 +49,16 @@ export function createCollectTask(data: CollectTask) {
return request.post<never, number>('/collect/task', data) return request.post<never, number>('/collect/task', data)
} }
/** 修改采集任务。密码留空则不修改 */
export function updateCollectTask(id: number, data: CollectTask) {
return request.put<never, void>(`/collect/task/${id}`, data)
}
/** 删除采集任务 */
export function removeCollectTask(id: number) {
return request.delete<never, void>(`/collect/task/${id}`)
}
/** 执行采集任务 */ /** 执行采集任务 */
export function startCollectTask(id: number) { export function startCollectTask(id: number) {
return request.post<never, CollectTask>(`/collect/task/${id}/start`) return request.post<never, CollectTask>(`/collect/task/${id}/start`)
+157 -59
View File
@@ -1,11 +1,13 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue' import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus' import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { import {
createCollectTask, createCollectTask,
listCollectTasks, listCollectTasks,
previewCollectSource, previewCollectSource,
removeCollectTask,
startCollectTask, startCollectTask,
updateCollectTask,
type CollectTable, type CollectTable,
type CollectTask type CollectTask
} from '@/api/collect' } from '@/api/collect'
@@ -23,22 +25,29 @@ const form = reactive<CollectTask>({
libraryName: '', libraryName: '',
sourceType: 'DB', sourceType: 'DB',
dbHost: '', dbHost: '',
dbType: 'POSTGRESQL',
dbPort: 5432, dbPort: 5432,
dbName: '', dbName: '',
dbUsername: '', dbUsername: '',
dbPassword: '', dbPassword: '',
sourceTable: '', sourceTable: ''
targetCount: 200000
}) })
const rules: FormRules = { const rules: FormRules = {
libraryCode: [{ required: true, message: '请输入单位编码', trigger: 'blur' }], libraryCode: [{ required: true, message: '请输入单位编码', trigger: 'blur' }],
libraryName: [{ required: true, message: '请输入单位名称', trigger: 'blur' }], libraryName: [{ required: true, message: '请输入单位名称', trigger: 'blur' }],
dbHost: [{ required: true, message: '请输入数据库地址', trigger: 'blur' }], dbHost: [{ required: true, message: '请输入数据库地址', trigger: 'blur' }],
dbType: [{ required: true, message: '请选择数据库类型', trigger: 'change' }],
dbPort: [{ required: true, message: '请输入端口', trigger: 'blur' }], dbPort: [{ required: true, message: '请输入端口', trigger: 'blur' }],
dbName: [{ required: true, message: '请输入数据库名', trigger: 'blur' }], dbName: [{ required: true, message: '请输入数据库名', trigger: 'blur' }],
dbUsername: [{ required: true, message: '请输入用户名', trigger: 'blur' }], dbUsername: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
dbPassword: [{ required: true, message: '请输入密码', trigger: 'blur' }], dbPassword: [{
validator: (_rule, value, callback) => {
if (!form.id && !value) callback(new Error('请输入密码'))
else callback()
},
trigger: 'blur'
}],
sourceTable: [{ required: true, message: '请输入表名', trigger: 'blur' }] sourceTable: [{ required: true, message: '请输入表名', trigger: 'blur' }]
} }
@@ -46,6 +55,7 @@ const mappedColumns = computed(() => (preview.value?.columns || []).filter((item
const unmappedColumns = computed(() => const unmappedColumns = computed(() =>
(preview.value?.columns || []).filter((item) => !item.targetField).map((item) => item.columnName) (preview.value?.columns || []).filter((item) => !item.targetField).map((item) => item.columnName)
) )
const missingRequired = computed(() => (preview.value?.compares || []).filter((item) => item.required && !item.matched))
async function fetchList() { async function fetchList() {
loading.value = true loading.value = true
@@ -61,18 +71,51 @@ function openCreate() {
form.libraryName = '' form.libraryName = ''
form.sourceType = 'DB' form.sourceType = 'DB'
form.dbHost = '' form.dbHost = ''
form.dbType = 'POSTGRESQL'
form.dbPort = 5432 form.dbPort = 5432
form.dbName = '' form.dbName = ''
form.dbUsername = '' form.dbUsername = ''
form.dbPassword = '' form.dbPassword = ''
form.sourceTable = '' form.sourceTable = ''
form.targetCount = 200000 form.id = undefined
preview.value = null preview.value = null
dialogVisible.value = true dialogVisible.value = true
} }
function openEdit(row: CollectTask) {
form.id = row.id
form.libraryCode = row.libraryCode
form.libraryName = row.libraryName || ''
form.sourceType = 'DB'
form.dbHost = row.dbHost || ''
form.dbType = row.dbType || 'POSTGRESQL'
form.dbPort = row.dbPort || 5432
form.dbName = row.dbName || ''
form.dbUsername = row.dbUsername || ''
form.dbPassword = ''
form.sourceTable = row.sourceTable || ''
preview.value = null
dialogVisible.value = true
}
const dbTypeOptions = [
{ value: 'POSTGRESQL', label: 'PostgreSQL / 瀚高', port: 5432 },
{ value: 'MYSQL', label: 'MySQL', port: 3306 }
]
function dbTypeLabel(type?: string) {
return dbTypeOptions.find((item) => item.value === type)?.label || type || '-'
}
function onDbTypeChange(value: string) {
const found = dbTypeOptions.find((item) => item.value === value)
if (found) {
form.dbPort = found.port
}
}
async function handlePreview() { async function handlePreview() {
await formRef.value?.validateField(['dbHost', 'dbPort', 'dbName', 'dbUsername', 'dbPassword', 'sourceTable']) await formRef.value?.validateField(['dbHost', 'dbType', 'dbPort', 'dbName', 'dbUsername', 'dbPassword', 'sourceTable'])
previewing.value = true previewing.value = true
preview.value = null preview.value = null
try { try {
@@ -83,15 +126,39 @@ async function handlePreview() {
} }
} }
async function handleCreate() { async function handleSave() {
await formRef.value?.validate() await formRef.value?.validate()
if (!preview.value) {
ElMessage.warning('请先测试连接,查看字段对比')
return
}
if (!mappedColumns.value.length) {
ElMessage.error('来源表至少要有一列对应到版本资源表')
return
}
form.sourceType = 'DB' form.sourceType = 'DB'
await createCollectTask(form) if (form.id) {
ElMessage.success('采集任务已创建,可在列表中执行') await updateCollectTask(form.id, form)
ElMessage.success('采集任务已更新')
} else {
await createCollectTask(form)
ElMessage.success('采集任务已创建,可在列表中执行')
}
dialogVisible.value = false dialogVisible.value = false
fetchList() fetchList()
} }
async function handleRemove(row: CollectTask) {
try {
await ElMessageBox.confirm(`确认删除采集任务「${row.libraryName || row.libraryCode}」?`, '提示', { type: 'warning' })
} catch {
return
}
await removeCollectTask(row.id as number)
ElMessage.success('已删除')
fetchList()
}
async function handleStart(row: CollectTask) { async function handleStart(row: CollectTask) {
startingId.value = row.id as number startingId.value = row.id as number
try { try {
@@ -107,13 +174,6 @@ async function handleStart(row: CollectTask) {
} }
} }
function wrotePercent(row: CollectTask) {
const target = Number(row.targetCount) || 0
const got = Number(row.collectedCount) || 0
if (target <= 0) return '0%'
return `${Math.min(100, Math.round((got / target) * 100))}%`
}
function statusTag(status?: string) { function statusTag(status?: string) {
if (status === 'SUCCESS') return 'success' if (status === 'SUCCESS') return 'success'
if (status === 'RUNNING') return 'warning' if (status === 'RUNNING') return 'warning'
@@ -133,11 +193,11 @@ onMounted(fetchList)
<div class="page-card"> <div class="page-card">
<div class="head"> <div class="head">
<h3 class="page-title">数据采集</h3> <h3 class="page-title">数据采集</h3>
<el-button type="primary" @click="openCreate">新建采集任务</el-button> <el-button type="primary" @click="openCreate">新增</el-button>
</div> </div>
<el-alert <el-alert
title="填写来源数据库的地址、用户名、密码和表名。测试连接后可看到每列写入版本资源表的哪个字段;执行后按这些字段入库。" title="采集结果全部写入版本资源表。测试连接后对照必备字段;来源表至少要有一列能对应,才能保存并执行。"
type="info" type="info"
:closable="false" :closable="false"
class="mb-16" class="mb-16"
@@ -146,18 +206,14 @@ onMounted(fetchList)
<el-table v-loading="loading" :data="list" border stripe> <el-table v-loading="loading" :data="list" border stripe>
<el-table-column prop="libraryCode" label="单位编码" width="110" /> <el-table-column prop="libraryCode" label="单位编码" width="110" />
<el-table-column prop="libraryName" label="单位名称" min-width="140" /> <el-table-column prop="libraryName" label="单位名称" min-width="140" />
<el-table-column label="数据库类型" width="160" show-overflow-tooltip>
<template #default="{ row }">{{ dbTypeLabel(row.dbType) }}</template>
</el-table-column>
<el-table-column label="来源库 / 表" min-width="240" show-overflow-tooltip> <el-table-column label="来源库 / 表" min-width="240" show-overflow-tooltip>
<template #default="{ row }">{{ sourceText(row) }}</template> <template #default="{ row }">{{ sourceText(row) }}</template>
</el-table-column> </el-table-column>
<el-table-column prop="dbUsername" label="用户名" width="110" /> <el-table-column prop="dbUsername" label="用户名" width="110" />
<el-table-column label="本次写入" width="120"> <el-table-column prop="collectedCount" label="本次写入" width="100" />
<template #default="{ row }">
<div class="wrote">
<span>{{ row.collectedCount ?? 0 }}</span>
<i class="wrote-bar"><b :style="{ width: wrotePercent(row) }" /></i>
</div>
</template>
</el-table-column>
<el-table-column label="状态" width="110"> <el-table-column label="状态" width="110">
<template #default="{ row }"> <template #default="{ row }">
<el-tag :type="statusTag(row.status)" size="small">{{ row.status }}</el-tag> <el-tag :type="statusTag(row.status)" size="small">{{ row.status }}</el-tag>
@@ -165,7 +221,7 @@ onMounted(fetchList)
</el-table-column> </el-table-column>
<el-table-column prop="message" label="结果" min-width="240" show-overflow-tooltip /> <el-table-column prop="message" label="结果" min-width="240" show-overflow-tooltip />
<el-table-column prop="createTime" label="创建时间" width="170" /> <el-table-column prop="createTime" label="创建时间" width="170" />
<el-table-column label="操作" width="110" fixed="right"> <el-table-column label="操作" width="200" fixed="right">
<template #default="{ row }"> <template #default="{ row }">
<el-button <el-button
link link
@@ -177,12 +233,29 @@ onMounted(fetchList)
> >
执行 执行
</el-button> </el-button>
<el-button link type="primary" size="small" :disabled="row.status === 'RUNNING'" @click="openEdit(row)">
编辑
</el-button>
<el-button link type="danger" size="small" :disabled="row.status === 'RUNNING'" @click="handleRemove(row)">
删除
</el-button>
</template> </template>
</el-table-column> </el-table-column>
</el-table> </el-table>
<el-dialog v-model="dialogVisible" title="新建采集任务" width="720px"> <el-dialog
v-model="dialogVisible"
class="collect-task-dialog"
:title="form.id ? '编辑采集任务' : '新建采集任务'"
width="880px"
top="6vh"
>
<el-form ref="formRef" :model="form" :rules="rules" label-width="110px"> <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
<el-form-item label="数据库类型" prop="dbType">
<el-select v-model="form.dbType" style="width: 100%" @change="onDbTypeChange">
<el-option v-for="item in dbTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
</el-select>
</el-form-item>
<el-row :gutter="12"> <el-row :gutter="12">
<el-col :span="16"> <el-col :span="16">
<el-form-item label="数据库地址" prop="dbHost"> <el-form-item label="数据库地址" prop="dbHost">
@@ -192,6 +265,7 @@ onMounted(fetchList)
<el-col :span="8"> <el-col :span="8">
<el-form-item label="端口" prop="dbPort" label-width="60px"> <el-form-item label="端口" prop="dbPort" label-width="60px">
<el-input-number v-model="form.dbPort" :min="1" :max="65535" controls-position="right" style="width: 100%" /> <el-input-number v-model="form.dbPort" :min="1" :max="65535" controls-position="right" style="width: 100%" />
<p class="port-tip">切换类型会填入常用端口,仍可改成实际端口</p>
</el-form-item> </el-form-item>
</el-col> </el-col>
</el-row> </el-row>
@@ -206,7 +280,12 @@ onMounted(fetchList)
</el-col> </el-col>
<el-col :span="12"> <el-col :span="12">
<el-form-item label="密码" prop="dbPassword" label-width="60px"> <el-form-item label="密码" prop="dbPassword" label-width="60px">
<el-input v-model="form.dbPassword" type="password" show-password placeholder="数据库密码" /> <el-input
v-model="form.dbPassword"
type="password"
show-password
:placeholder="form.id ? '不修改请留空' : '数据库密码'"
/>
</el-form-item> </el-form-item>
</el-col> </el-col>
</el-row> </el-row>
@@ -216,14 +295,33 @@ onMounted(fetchList)
<el-form-item> <el-form-item>
<el-button :loading="previewing" @click="handlePreview">测试连接并查看字段</el-button> <el-button :loading="previewing" @click="handlePreview">测试连接并查看字段</el-button>
</el-form-item> </el-form-item>
<el-form-item v-if="preview" label="字段对应"> <el-form-item v-if="preview" label="字段对比">
<div class="map-box"> <div class="map-box">
<p class="unmap">{{ preview.tableName }} 共 {{ preview.rowCount }} 条。同名或常见别名会写入版本资源表。</p> <p class="unmap">
<el-tag v-for="col in mappedColumns" :key="col.columnName" size="small" class="map-tag"> {{ preview.tableName }} 共 {{ preview.rowCount }} 条,写入版本资源表。
{{ col.columnName }} → {{ col.targetLabel }} 已对应 {{ mappedColumns.length }} 列,必备未对应 {{ missingRequired.length }} 项。
</el-tag> </p>
<p v-if="unmappedColumns.length" class="unmap">不写入:{{ unmappedColumns.join('、') }}</p> <el-table :data="preview.compares" size="small" border max-height="320">
<p v-if="!mappedColumns.length" class="unmap">这张表没有能对应到版本资源字段的列。</p> <el-table-column prop="targetLabel" label="版本资源字段" width="150" />
<el-table-column label="要求" width="80">
<template #default="{ row }">
<el-tag :type="row.required ? 'warning' : 'info'" size="small">{{ row.required ? '必备' : '可选' }}</el-tag>
</template>
</el-table-column>
<el-table-column label="来源字段" min-width="160" show-overflow-tooltip>
<template #default="{ row }">{{ row.sourceColumn || '—' }}</template>
</el-table-column>
<el-table-column label="对应" width="90">
<template #default="{ row }">
<span :class="row.matched ? 'ok' : 'miss'">{{ row.matched ? '已对应' : '未对应' }}</span>
</template>
</el-table-column>
</el-table>
<p v-if="missingRequired.length" class="unmap">
未对应的必备字段:{{ missingRequired.map((item) => item.targetLabel).join('、') }}。没有正题名的记录不会入库。
</p>
<p v-if="unmappedColumns.length" class="unmap">来源表中不写入的列:{{ unmappedColumns.join('、') }}</p>
<p v-if="!mappedColumns.length" class="miss">这张表没有能对应到版本资源表的列,不能保存。</p>
</div> </div>
</el-form-item> </el-form-item>
<el-form-item label="单位编码" prop="libraryCode"> <el-form-item label="单位编码" prop="libraryCode">
@@ -232,13 +330,10 @@ onMounted(fetchList)
<el-form-item label="单位名称" prop="libraryName"> <el-form-item label="单位名称" prop="libraryName">
<el-input v-model="form.libraryName" placeholder="如 陆军步兵学院图书馆" /> <el-input v-model="form.libraryName" placeholder="如 陆军步兵学院图书馆" />
</el-form-item> </el-form-item>
<el-form-item label="目标采集量">
<el-input-number v-model="form.targetCount" :min="1" :step="1000" style="width: 100%" />
</el-form-item>
</el-form> </el-form>
<template #footer> <template #footer>
<el-button @click="dialogVisible = false">取消</el-button> <el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="handleCreate">创建</el-button> <el-button type="primary" @click="handleSave">{{ form.id ? '保存' : '创建' }}</el-button>
</template> </template>
</el-dialog> </el-dialog>
</div> </div>
@@ -256,34 +351,37 @@ onMounted(fetchList)
line-height: 1.8; line-height: 1.8;
} }
.map-tag {
margin: 0 8px 8px 0;
}
.unmap { .unmap {
margin: 0 0 8px; margin: 0 0 8px;
color: var(--text-muted); color: var(--text-muted);
font-size: 12px; font-size: 12px;
} }
.wrote { .port-tip {
display: flex; margin: 4px 0 0;
flex-direction: column; font-size: 12px;
gap: 4px; line-height: 1.4;
font-variant-numeric: tabular-nums; color: var(--text-muted);
} }
.wrote-bar { .ok {
display: block; color: var(--brand-primary-deep);
height: 3px;
background: var(--brand-light);
border-radius: 2px;
overflow: hidden;
} }
.wrote-bar b { .miss {
display: block; color: var(--el-color-danger);
height: 100%; }
background: linear-gradient(90deg, var(--brand-primary-deep), var(--brand-gold)); </style>
<style>
.collect-task-dialog.el-dialog {
max-height: 88vh;
display: flex;
flex-direction: column;
margin-bottom: 4vh;
}
.collect-task-dialog .el-dialog__body {
overflow: auto;
} }
</style> </style>