Skip to content

Commit 7431282

Browse files
authored
Refactor/code refactor (#181)
* fix: scope SQL column permissions and reuse shared API requests * refactor: separate relation queries and provenance construction * refactor: simplify semantic pages and modernize datasource persistence * fix: escape JDBC metadata patterns and detect SQL truncation accurately * refactor: remove circular dependency between user and permission services * fix: preserve physical names and update references when renaming domains * fix: correct CSV exports, SQL lineage, and user editing * refactor: extract JDBC CSV value conversion * refactor: extract history, metric, provenance, and metadata converters * refactor: split chat, user management, and semantic sync logic Extract datasource selection and user dialogs into Vue components, and share semantic sync diff calculation between sync and refresh flows. Adapt existing tests without adding new test cases. * Update SqlQueryScope.java * fix: resolve parenthesized column projections in SQL scopes
1 parent ccbc0d4 commit 7431282

85 files changed

Lines changed: 2962 additions & 1958 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.

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

Lines changed: 3 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -17,28 +17,23 @@
1717
*/
1818
package io.github.malonetalk.agent;
1919

20-
import io.agentscope.core.message.ContentBlock;
2120
import io.agentscope.core.message.Msg;
2221
import io.agentscope.core.message.MsgRole;
2322
import io.agentscope.core.message.TextBlock;
2423
import io.agentscope.core.message.ThinkingBlock;
25-
import io.agentscope.core.message.ToolResultBlock;
26-
import io.agentscope.core.message.ToolUseBlock;
2724
import io.agentscope.core.session.Session;
2825
import io.agentscope.core.session.mysql.MysqlSession;
2926
import io.agentscope.core.state.SessionKey;
3027
import io.agentscope.core.state.SimpleSessionKey;
3128
import io.github.malonetalk.agent.provenance.AnswerProvenanceService;
32-
import io.github.malonetalk.convertor.handler.ToolResultHandler;
33-
import io.github.malonetalk.dto.ChatStreamEvent;
3429
import io.github.malonetalk.dto.SessionDatasourceBinding;
3530
import io.github.malonetalk.dto.SessionInfo;
3631
import io.github.malonetalk.dto.TurnItem;
37-
import io.github.malonetalk.enums.ChatStreamEventType;
3832
import io.github.malonetalk.exception.BusinessException;
3933
import io.github.malonetalk.exception.ErrorCode;
4034
import io.github.malonetalk.mapper.SessionDatasourceMapper;
4135
import io.github.malonetalk.mapper.UserSessionMapper;
36+
import io.github.malonetalk.model.converter.SessionHistoryConverter;
4237
import java.sql.Connection;
4338
import java.sql.PreparedStatement;
4439
import java.sql.ResultSet;
@@ -68,6 +63,7 @@ public class SessionService {
6863
private final SessionDatasourceMapper sessionDatasourceMapper;
6964
private final UserSessionMapper userSessionMapper;
7065
private final AnswerProvenanceService answerProvenanceService;
66+
private final SessionHistoryConverter sessionHistoryConverter;
7167

7268
@Getter(lazy = true)
7369
private final MysqlSession session =
@@ -119,7 +115,7 @@ public List<Msg> getSessionDebug(String sessionId, Integer userId) {
119115

120116
public List<TurnItem> getSessionHistory(String sessionId, Integer userId) {
121117
requireOwnership(userId, sessionId);
122-
return buildTurnItems(loadMessages(sessionId));
118+
return sessionHistoryConverter.convert(loadMessages(sessionId));
123119
}
124120

125121
private List<Msg> loadMessages(String sessionId) {
@@ -139,109 +135,6 @@ public Optional<String> getLatestUserMessageId(String sessionId) {
139135
return Optional.empty();
140136
}
141137

142-
private List<TurnItem> buildTurnItems(List<Msg> messages) {
143-
List<TurnItem> turns = new ArrayList<>();
144-
List<ContentBlock> agentBlocks = null;
145-
146-
for (Msg msg : messages) {
147-
boolean isUser = msg.getRole() == MsgRole.USER;
148-
if (isUser) {
149-
if (agentBlocks != null) {
150-
turns.add(buildAgentTurn(agentBlocks));
151-
agentBlocks = null;
152-
}
153-
String text =
154-
msg.getContent().stream()
155-
.filter(block -> block instanceof TextBlock)
156-
.map(block -> ((TextBlock) block).getText())
157-
.filter(t -> t != null && !t.isEmpty())
158-
.collect(Collectors.joining());
159-
turns.add(new TurnItem(MsgRole.USER.name(), text, List.of()));
160-
} else {
161-
if (agentBlocks == null) {
162-
agentBlocks = new ArrayList<>();
163-
}
164-
agentBlocks.addAll(msg.getContent());
165-
}
166-
}
167-
if (agentBlocks != null) {
168-
turns.add(buildAgentTurn(agentBlocks));
169-
}
170-
171-
return turns;
172-
}
173-
174-
private TurnItem buildAgentTurn(List<ContentBlock> blocks) {
175-
StringBuilder content = new StringBuilder();
176-
List<ChatStreamEvent> traceSteps = new ArrayList<>();
177-
178-
for (ContentBlock block : blocks) {
179-
if (block instanceof TextBlock tb) {
180-
appendText(content, tb);
181-
} else if (block instanceof ThinkingBlock tb) {
182-
appendThinking(traceSteps, tb);
183-
} else if (block instanceof ToolUseBlock tub) {
184-
appendToolCall(traceSteps, tub);
185-
} else if (block instanceof ToolResultBlock trb) {
186-
appendToolResult(traceSteps, trb);
187-
}
188-
}
189-
190-
return new TurnItem(MsgRole.ASSISTANT.name(), content.toString(), traceSteps);
191-
}
192-
193-
private void appendText(StringBuilder content, TextBlock tb) {
194-
String text = tb.getText();
195-
if (text != null && !text.isEmpty()) {
196-
content.append(text);
197-
}
198-
}
199-
200-
private void appendThinking(List<ChatStreamEvent> traceSteps, ThinkingBlock tb) {
201-
String thinking = tb.getThinking();
202-
if (thinking == null || thinking.isEmpty()) {
203-
return;
204-
}
205-
int lastIdx = traceSteps.size() - 1;
206-
if (lastIdx >= 0 && traceSteps.get(lastIdx).type() == ChatStreamEventType.THINKING) {
207-
String merged =
208-
(traceSteps.get(lastIdx).content() != null
209-
? traceSteps.get(lastIdx).content()
210-
: "")
211-
+ thinking;
212-
traceSteps.set(lastIdx, thinkingEvent(merged));
213-
} else {
214-
traceSteps.add(thinkingEvent(thinking));
215-
}
216-
}
217-
218-
private void appendToolCall(List<ChatStreamEvent> traceSteps, ToolUseBlock tub) {
219-
traceSteps.add(
220-
ChatStreamEvent.builder()
221-
.type(ChatStreamEventType.TOOL_CALL)
222-
.toolCall(
223-
new ChatStreamEvent.ToolCallInfo(
224-
tub.getId(), tub.getName(), tub.getInput()))
225-
.build());
226-
}
227-
228-
private void appendToolResult(List<ChatStreamEvent> traceSteps, ToolResultBlock trb) {
229-
String outputText =
230-
trb.getOutput().stream()
231-
.filter(b -> b instanceof TextBlock)
232-
.map(b -> ((TextBlock) b).getText())
233-
.filter(t -> t != null && !t.isEmpty())
234-
.collect(Collectors.joining("\n"));
235-
traceSteps.add(ToolResultHandler.defaultHandle(trb, outputText, null, false));
236-
}
237-
238-
private static ChatStreamEvent thinkingEvent(String thinking) {
239-
return ChatStreamEvent.builder()
240-
.type(ChatStreamEventType.THINKING)
241-
.content(thinking)
242-
.build();
243-
}
244-
245138
@Transactional
246139
public void clearSession(String sessionId, Integer userId) {
247140
requireOwnership(userId, sessionId);

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

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@
1919

2020
import com.zaxxer.hikari.HikariConfig;
2121
import com.zaxxer.hikari.HikariDataSource;
22-
import io.github.malonetalk.entity.Datasource;
2322
import io.github.malonetalk.exception.BusinessException;
2423
import io.github.malonetalk.exception.ErrorCode;
24+
import io.github.malonetalk.model.po.DatasourcePo;
2525
import io.opentelemetry.instrumentation.jdbc.datasource.JdbcTelemetry;
2626
import jakarta.annotation.PreDestroy;
2727
import java.util.concurrent.ConcurrentHashMap;
@@ -45,14 +45,14 @@ public class DynamicDataSourceManager {
4545
new ConcurrentHashMap<>();
4646
private final JdbcTelemetry jdbcTelemetry;
4747

48-
public DataSource getOrCreateDataSource(Datasource datasource) {
48+
public DataSource getOrCreateDataSource(DatasourcePo datasource) {
4949
HikariDataSource pool =
5050
dataSourcePool.computeIfAbsent(
5151
datasource.getId(), id -> createDataSource(datasource));
5252
return jdbcTelemetry.wrap(pool);
5353
}
5454

55-
private HikariDataSource createDataSource(Datasource datasource) {
55+
private HikariDataSource createDataSource(DatasourcePo datasource) {
5656
DataSourceType type =
5757
DataSourceType.fromCode(datasource.getType())
5858
.orElseThrow(
@@ -112,7 +112,7 @@ private RuntimeException translateInitializationFailure(
112112
}
113113

114114
private static HikariConfig getHikariConfig(
115-
Datasource datasource, String jdbcUrl, DataSourceType type) {
115+
DatasourcePo datasource, String jdbcUrl, DataSourceType type) {
116116
HikariConfig config = new HikariConfig();
117117
config.setJdbcUrl(jdbcUrl);
118118
config.setUsername(datasource.getUsername());
@@ -129,7 +129,7 @@ private static HikariConfig getHikariConfig(
129129
return config;
130130
}
131131

132-
private String resolveJdbcUrl(Datasource datasource, DataSourceType type) {
132+
private String resolveJdbcUrl(DatasourcePo datasource, DataSourceType type) {
133133
if (datasource.getConnectionUrl() != null && !datasource.getConnectionUrl().isBlank()) {
134134
return datasource.getConnectionUrl();
135135
}

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

Lines changed: 37 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,10 @@
1919

2020
import io.github.malonetalk.dto.datasource.PhysicalColumnInfo;
2121
import io.github.malonetalk.dto.datasource.PhysicalTableInfo;
22-
import io.github.malonetalk.entity.Datasource;
2322
import io.github.malonetalk.exception.BusinessException;
2423
import io.github.malonetalk.exception.ErrorCode;
24+
import io.github.malonetalk.model.converter.JdbcColumnMetadataConverter;
25+
import io.github.malonetalk.model.po.DatasourcePo;
2526
import io.github.malonetalk.utils.SemanticUtils;
2627
import java.sql.Connection;
2728
import java.sql.DatabaseMetaData;
@@ -33,6 +34,7 @@
3334
import java.util.LinkedHashSet;
3435
import java.util.List;
3536
import java.util.Map;
37+
import java.util.Optional;
3638
import java.util.Set;
3739
import java.util.TreeMap;
3840
import lombok.AllArgsConstructor;
@@ -45,8 +47,9 @@
4547
public class SchemaReader {
4648

4749
private final DynamicDataSourceManager dynamicDataSourceManager;
50+
private final JdbcColumnMetadataConverter columnMetadataConverter;
4851

49-
public List<PhysicalTableInfo> getTables(Datasource datasource) {
52+
public List<PhysicalTableInfo> getTables(DatasourcePo datasource) {
5053
javax.sql.DataSource ds = dynamicDataSourceManager.getOrCreateDataSource(datasource);
5154

5255
try (Connection conn = ds.getConnection()) {
@@ -60,7 +63,7 @@ public List<PhysicalTableInfo> getTables(Datasource datasource) {
6063
}
6164
}
6265

63-
public List<PhysicalColumnInfo> getTableSchema(Datasource datasource, String tableName) {
66+
public List<PhysicalColumnInfo> getTableSchema(DatasourcePo datasource, String tableName) {
6467
javax.sql.DataSource ds = dynamicDataSourceManager.getOrCreateDataSource(datasource);
6568

6669
try (Connection conn = ds.getConnection()) {
@@ -78,7 +81,7 @@ public List<PhysicalColumnInfo> getTableSchema(Datasource datasource, String tab
7881
}
7982

8083
public Map<String, Set<String>> getTableColumnNames(
81-
Datasource datasource, Collection<String> tableNames) {
84+
DatasourcePo datasource, Collection<String> tableNames) {
8285
if (tableNames == null || tableNames.isEmpty()) {
8386
return Map.of();
8487
}
@@ -92,7 +95,8 @@ public Map<String, Set<String>> getTableColumnNames(
9295
try (Connection conn = ds.getConnection()) {
9396
DatabaseMetaData metaData = conn.getMetaData();
9497
try (ResultSet rs =
95-
metaData.getColumns(conn.getCatalog(), conn.getSchema(), "%", null)) {
98+
metaData.getColumns(
99+
conn.getCatalog(), schemaPattern(conn).orElse(null), "%", null)) {
96100
while (rs.next()) {
97101
Set<String> columnNames = columnNamesByTable.get(rs.getString("TABLE_NAME"));
98102
if (columnNames != null) {
@@ -116,7 +120,10 @@ private List<PhysicalTableInfo> getTables(Connection conn) throws SQLException {
116120

117121
try (ResultSet rs =
118122
metaData.getTables(
119-
conn.getCatalog(), conn.getSchema(), "%", new String[] {"TABLE"})) {
123+
conn.getCatalog(),
124+
schemaPattern(conn).orElse(null),
125+
"%",
126+
new String[] {"TABLE"})) {
120127
while (rs.next()) {
121128
tables.add(
122129
new PhysicalTableInfo(rs.getString("TABLE_NAME"), rs.getString("REMARKS")));
@@ -190,36 +197,37 @@ private List<PhysicalColumnInfo> getColumns(
190197
DatabaseMetaData metaData = conn.getMetaData();
191198

192199
try (ResultSet rs =
193-
metaData.getColumns(conn.getCatalog(), conn.getSchema(), tableName, null)) {
200+
metaData.getColumns(
201+
conn.getCatalog(),
202+
schemaPattern(conn).orElse(null),
203+
escapeMetadataPattern(tableName, metaData.getSearchStringEscape()),
204+
null)) {
194205
while (rs.next()) {
195-
String columnName = rs.getString("COLUMN_NAME");
196-
String typeName = rs.getString("TYPE_NAME");
197-
int columnSize = rs.getInt("COLUMN_SIZE");
198-
int decimalDigits = rs.getInt("DECIMAL_DIGITS");
199-
String nullableStr = rs.getString("IS_NULLABLE");
200-
boolean nullable = "YES".equalsIgnoreCase(nullableStr);
201-
String defaultValue = rs.getString("COLUMN_DEF");
202-
String remarks = rs.getString("REMARKS");
203-
String normalizedColumnName = normalizeColumnName(columnName);
204-
boolean isPk = primaryKeys.contains(normalizedColumnName);
205-
206-
columns.add(
207-
new PhysicalColumnInfo(
208-
columnName,
209-
typeName,
210-
columnSize,
211-
decimalDigits,
212-
nullable,
213-
defaultValue,
214-
isPk,
215-
remarks,
216-
indexesByColumn.getOrDefault(normalizedColumnName, List.of())));
206+
if (!tableName.equals(rs.getString("TABLE_NAME"))) {
207+
continue;
208+
}
209+
columns.add(columnMetadataConverter.convert(rs, primaryKeys, indexesByColumn));
217210
}
218211
}
219212

220213
return columns;
221214
}
222215

216+
private Optional<String> schemaPattern(Connection conn) throws SQLException {
217+
String escape = conn.getMetaData().getSearchStringEscape();
218+
return Optional.ofNullable(conn.getSchema())
219+
.map(schema -> escapeMetadataPattern(schema, escape));
220+
}
221+
222+
private static String escapeMetadataPattern(String name, String escape) {
223+
if (escape == null || escape.isEmpty()) {
224+
return name;
225+
}
226+
return name.replace(escape, escape + escape)
227+
.replace("_", escape + "_")
228+
.replace("%", escape + "%");
229+
}
230+
223231
private static String normalizeColumnName(String columnName) {
224232
return SemanticUtils.normalizeObjectName(
225233
columnName, "Missing column name while reading schema.");

0 commit comments

Comments
 (0)