Repository navigation
多数据库抽象架构:统一 mysql(jdbc) 扩展模块各组件的方言设计(agentscope-extensions-mysql -> agentscope-extensions-jdbc) - #2759
Conversation
New agentscope-extensions-jdbc module with unified multi-database dialect abstraction. The dialect layer provides: - JdbcStoreDialect: KV store SQL (abstract: createTable, upsert; default: insert, casUpdate, select, delete, search, likeEscape) - AgentStateStoreDialect: session state SQL (abstract: createSessions, upsertState, checkTableExists; default: insertState, selectState, selectList, deleteByKey, deleteSession, maxIndex, exists, listSessionIds, quoteIdentifier, createDatabase=null, fullTableRef) - SnapshotStoreDialect: snapshot SQL (abstract: upsertSnapshot; default: blobType, createTable, selectSnapshot, existsSnapshot) - JdbcDialect: aggregate interface extending all three + lockStrategy default + static from(DataSource) auto-detection - SandboxLockStrategy + TableBasedLockStrategy: portable fallback - MysqlLockStrategy: MySQL GET_LOCK/RELEASE_LOCK native strategy Database implementations: - PostgresDialect: ANSI baseline (~0 divergences) - MysqlDialect: LONGTEXT/ENGINE=InnoDB, ON DUPLICATE KEY, backtick quoting, CREATE DATABASE, GET_LOCK (~5 divergences) - H2Dialect: CLOB types, ON CONFLICT (H2 2.x) (~1 divergence) - SqliteDialect: TEXT/INTEGER types, sqlite_master (~3 divergences)
Four database-agnostic component classes with zero inline SQL: - JdbcStore (implements BaseStore): KV store with CAS, namespace encoding, hash-based change detection, pagination search - JdbcAgentStateStore (implements AgentStateStore): session state with incremental list storage, hash-based change detection, transaction-managed writes - JdbcRemoteSnapshotClient + JdbcSnapshotSpec: BLOB-backed snapshot upload/download/exists - JdbcSandboxExecutionGuard: delegates to dialect's SandboxLockStrategy JdbcDistributedStore facade auto-detects dialect via JdbcDialect.from() and assembles all four components.
…ore @deprecated Add @deprecated(since="2.1", forRemoval=true) to both facade classes with Javadoc pointing users to JdbcDistributedStore in the new agentscope-extensions-jdbc module. No business logic changes — the deprecated modules remain fully functional during the transition period.
Three test layers: - Unit tests (32): dialect SQL generation for all 4 databases, cross-dialect default inheritance verification, JdbcDialect.from() auto-detection with mocked DatabaseMetaData (MySQL/PG/H2/SQLite/unknown/blank/null paths) - H2 integration tests (35): full CRUD/CAS/search for JdbcStore, state CRUD + list incremental append + hash-based rewrite for JdbcAgentStateStore, BLOB upload/download for snapshot client, thread mutual exclusion for sandbox guard, end-to-end facade integration - Testcontainers tests (8, -Pintegration): MySQL + PostgreSQL containers validating real-database UPSERT, CAS, BLOB/BYTEA, and dialect detection H2Dialect updated to use MERGE INTO for all UPSERT operations — H2 does not support ON CONFLICT DO UPDATE in standard mode. Test isolation fixed with unique UUID-suffixed database names per test invocation.
Documents the four-layer architecture, database capability matrix (KV store, state store, snapshot, distributed lock per database), quick-start guide, how to add a new database dialect, and migration table from deprecated modules.
…g license headers - Add agentscope-extensions-jdbc dependency to agentscope-all so it is shaded into the uber-jar (required by check-shade-and-bom-sync.sh) - Add agentscope-extensions-jdbc to agentscope-bom for version management - Add Apache-2.0 license headers to dialect package-info.java files to pass license-eye header check
The '<-' arrows in the dialect ASCII diagram were parsed by javadoc doclint as malformed HTML tags, failing the maven-javadoc-plugin:jar goal. Escape them as <- which renders identically in <pre> blocks.
AgentScopeJavaBot
left a comment
There was a problem hiding this comment.
🤖 AI Review
This PR introduces a well-architected multi-database JDBC dialect abstraction layer (agentscope-extensions-jdbc) that replaces the deprecated MySQL-only and PostgreSQL-only extension modules. The design follows a clean four-layer architecture: Facade → Component → Dialect → Vendor, with zero inline SQL in the component layer and JDK SPI-based dialect auto-detection. The code quality is generally high — clean separation of concerns, thorough Javadoc, good test structure for H2 integration, and proper deprecation of the old modules. However, there are several areas that need attention: inconsistent error handling in schema initialization, redundant DDL execution from accessor methods, a memory risk in snapshot uploads, a hash-collision risk in MySQL lock name truncation, and notable test coverage gaps.
… DDL as List<String> Stream snapshot uploads via setBinaryStream, hash long MySQL lock names with SHA-256, cache distributed-store components, add/emit secondary indexes per table, and unify xxxCreateTableSql into List<String>-returning xxxCreateTableDdls.
70cca18 to
f90a9e4
Compare
| public class JdbcAgentStateStore implements AgentStateStore { | ||
|
|
There was a problem hiding this comment.
AgentStateStore 乐观并发未实现(功能回退):
被废弃的 MysqlAgentStateStore 和 PostgresAgentStateStore 重写了 supportsVersioning()、getVersioned() 和 saveIfVersion(),并在 sessions 表中使用了 version 列。此类继承了默认的空操作实现,因此 ReActAgent(在 ReActAgent.java:374,557,567,614 调用 saveIfVersion)静默降级为“最后写入者胜”策略,丧失了针对并发 Agent 状态更新的 CAS 保护。此外,所有四种方言的 sessionStateCreateTableDdls() 都缺少 version 列。为了实现功能对齐,需要在方言 DDL 中添加 version BIGINT NOT NULL DEFAULT 0 列,并重写 supportsVersioning()→true、getVersioned() 和 saveIfVersion()。
| public class PostgresDialect extends AbstractJdbcDialect { | ||
|
|
There was a problem hiding this comment.
PostgreSQL 咨询锁未实现(性能回退):
被废弃的 PostgresSandboxExecutionGuard 使用了原生的 pg_try_advisory_lock / pg_advisory_unlock(连接绑定、无轮询、无额外表)。PostgresDialect 没有重写 tryEnter,并继承了 AbstractJdbcDialect 中的基于表的锁机制,该机制需要为每个实例创建一个 distributed_locks 表并轮询(50ms–1000ms 退避)。
| } | ||
| } | ||
|
|
||
| private void createTablesIfNeeded(AbstractJdbcDialect dialect) { |
There was a problem hiding this comment.
MySQL createDatabaseIfNotExist 未实现(操作缺失):
被废弃的 MysqlAgentStateStore 在创建表之前会调用 createDatabaseIfNotExist()(执行 CREATE DATABASE IF NOT EXISTS)。此构建器的 createTablesIfNeeded() 仅执行表 DDL。在全新的 MySQL 部署中(数据库尚不存在),CREATE TABLE 将会失败并提示“Unknown database”。考虑在 AbstractJdbcDialect 中添加一个可选的 createDatabaseDdls() 方法(默认返回空列表,并在 MysqlDialect 中重写),并在 createTablesIfNeeded 之前执行它。
There was a problem hiding this comment.
关于jdbc模块review指出的【 createDatabaseIfNotExist 未实现(操作缺失)】,这确实是个有效的问题 —— 全新部署时库不存在会直接报 Unknown database 失败。
这个问题经过再三思考后,关于“框架是否自动建库”,结论是倾向不做,理由如下:
1、职责归属:库名已在 JDBC URL 中,“建库” 应是开发者最基本的工作,不属于也不应作为运行时职责。
2、权限问题:建库需要实例级权限,生产环境账号通常没有。框架静默建库会导致“开发机能跑、生产上失败”。
3、维边界:charset/collation 等一次性决策、RDS 等平台管控场景,旧模块硬编码 agentscope 库名的模式也不值得延续,框架只聚焦于 Datasource 对象锚定的数据库连接是更合适的。
故本次模块改造后,数据库的创建交还给开发者。
…stgreSQL advisory lock - Add version BIGINT column to sessions table across MySQL, PostgreSQL, H2, SQLite, with UPSERT version self-increment. - Implement supportsVersioning()/getVersioned()/saveIfVersion() in JdbcAgentStateStore for compare-and-swap state updates. - Override PostgresDialect.tryEnter to use pg_try_advisory_lock/pg_advisory_unlock instead of the portable table-based lock. - Extract null-safe closeConnection/closeStatement/closeResultSet helpers into AbstractJdbcDialect for vendor dialects.
…eat/jdbc-dialect-module
|
@xzxiaoshan 请问后续会支持国产数据库的方言吗,比如达梦、高斯这些? |
会,必须会。 这个模块的重构,重构就是为了更好更方便的数据库扩展。 可以留下大家需要的国产数据库需求优先级留言。 |
|
高斯、达梦、OceanBase。oracle也需要 |
完成 ISSUE #2503