Develop, package, or fix OntoPlato data adapter implementations under the plugin architecture (Java SPI, API version manifest, isolated plugin subdirectories, DSL read/write contracts, vector attributes, and contract tests). Use only when adding a new engine type or fixing an adapter; configuring an already supported database does not require this skill.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Ontoplato Adapter Builder?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/ontomato-ai-ontoplato-adapter-builder)
---
name: ontoplato-adapter-builder
description: Develop, package, or fix OntoPlato data adapter implementations under the plugin architecture (Java SPI, API version manifest, isolated plugin subdirectories, DSL read/write contracts, vector attributes, and contract tests). Use only when adding a new engine type or fixing an adapter; configuring an already supported database does not require this skill.
compatibility: Requires Java 21+, Maven, an OntoPlato source workspace (or locally installed io.ontomato:data-engine-core and io.ontomato:data-adapter-test-support artifacts), and access to a target test engine.
---
# Adapter Builder
Use this skill to develop or fix a data source adapter for OntoPlato so ontology objects, relationships, and DSL read/write contracts run reliably on the target engine. If you only need to connect an already supported database type, configure it through the Data Adapters settings page or configuration API instead of writing a new adapter.
## Non-negotiable rules
1. **Never silently drop, ignore, or truncate any DSL construct.** Render it faithfully or throw a located `DslContractViolationException`. A query that drops an unsupported filter returns a plausible-looking wrong answer.
2. **Keep the planner adapter-agnostic.** Never encode adapter capability differences in prompts; enforce differences inside the adapter (by throwing) or declare them to the test suite via capabilities.
3. **Compiling is not done.** The shared contract suite `AbstractDataAdapterTest` must pass against a real engine, with Surefire counts (`tests run / failures / errors / skipped`) and an explanation for every skip.
4. **Ship a standalone plugin subdirectory; never modify product module lists.** Package external adapters as an independent `<name>/` subdirectory (containing the adapter plugin JAR and its required JDBC driver JARs), deploy it under `backend_data/adapters/<name>/` (`/deploy/adapters/<name>/` in containers), and restart `datarag`. Do not edit product POMs or build scripts, and do not use the retired `backend_data/drivers/` directory.
5. **Read-only adapters must explicitly reject writes.** Every unsupported write method must throw `UnsupportedDataAdapterOperationException`; never leave a no-op that reports success.
## 1. Plugin architecture, layout, and boundaries
### Built-in adapters vs. external plugins
The OntoPlato monorepo ships open-source core adapters and M3 using the exact same standard Java SPI discovery mechanism as external plugins:
- **Built-in adapters** (`packages/data-adapters/`): `postgresql`, `mysql`, `sqlserver`, `gaussdb`, `duckdb`, `neo4j`, `elasticsearch` (serves both `elasticsearch` and `opensearch`), `mongodb`, `clickhouse`, `arangodb`, and `m3`.
- **External standalone plugins** (such as DM/Dameng, DB2, and Oracle in the official public plugin repository [`ontomato-ai/ontoplato-plugins`](https://github.com/ontomato-ai/ontoplato-plugins), or customer-specific data sources): maintained and built outside the product repository and dropped in as `<name>/` plugin subdirectories without modifying product code.
### Standalone plugin project and manifest contract
Build external adapters as standalone Maven projects (see the bundled self-contained [Plugin Contract and Interface Signatures](references/plugin-contract.md) for directory layout, dependency versions, required vs. default `DataAdapter` methods, and `DataAdapterPluginLoader` signatures). Third-party plugins should use their own vendor Java package (for example `com.example.adapter.<name>`) rather than occupying `io.ontomato.dataengine.dataAdapter`, as long as `META-INF/services/io.ontomato.dataengine.dataAdapter.DataAdapterProvider` lists the provider's FQCN:
```text
adapter-<name>/
├── pom.xml
└── src/
├── main/
│ ├── java/<vendor-package>/
│ │ ├── <Engine>Adapter.java
│ │ └── <Engine>AdapterProvider.java
│ └── resources/META-INF/services/
│ └── io.ontomato.dataengine.dataAdapter.DataAdapterProvider
└── test/java/<vendor-package>/
├── <Engine>AdapterTest.java
└── <Engine>AdapterProviderTest.java
```
Packaging and dependency requirements:
- **Compile and test dependencies**: depend on `io.ontomato:data-engine-core` with `<scope>provided</scope>` (runtime already supplies `com.alibaba.fastjson2:fastjson2:2.0.57` and `org.slf4j:slf4j-api` aligned with Spring Boot `3.5.0`; declare them `provided` and never bundle `data-engine-core`, `fastjson2`, or `slf4j` into the plugin directory). Running `AbstractDataAdapterTest` requires **`io.ontomato:data-adapter-test-support`** with `<scope>test</scope>` (that abstract test class is not inside `data-engine-core`; if `data-adapter-test-support` is absent in an isolated workspace, verify SPI, manifest gating, and `DataAdapterPluginLoader` using [Plugin Contract and Interface Signatures](references/plugin-contract.md) and explicitly report that the shared contract suite has not yet been run).
- **Allowed product classes**: use only `DataAdapterProvider`, `DataAdapter`, `DataAdapterConnection`, `DataAdapterConnectionField`, `DataAdapterPluginApi`, `DslExecutionMode`, `DslRowLimit`, `DslGrammarValidator`, `SqlDslChecks`, `LikePattern`, `DslContractViolationException`, `UnsupportedDataAdapterOperationException`, `ConfigurationProblem`, `SandboxDataAdapter`, `SandboxTarget`, `SandboxCapability`, `JdbcSandboxArtifacts`, `KeyFieldGraphContract`, `OntologyRelation`, `DataRagConfig`, `BusinessConfig`, `VectorResourceDao`, `UserDataPermission`, `DslUtil` (`getPrimaryKey`, `parseVectorAttr`, `setConditionTimeColumnToCorrectFormat`), and runtime-provided `com.alibaba.fastjson2.*` and `org.slf4j.*`. Never depend on `service.*`, `controller.*`, other `dao.*`, or Spring container beans.
- **Plugin API version manifest header**: plugins target `io.ontomato.dataengine.dataAdapter.DataAdapterPluginApi.VERSION` (currently **`1`**) rather than product patch versions. Configure `maven-jar-plugin` in `pom.xml` to write `META-INF/MANIFEST.MF`:
```xml
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestEntries>
<OntoPlato-Adapter-Api-Version>1</OntoPlato-Adapter-Api-Version>
</manifestEntries>
</archive>
</configuration>
</plugin>
```
### Runtime plugin subdirectories and classloader isolation
On startup, `datarag` scans `adapters/` under its working directory (host path `backend_data/adapters/`, mounted at `/deploy/adapters/` in containers; overridable via `ONTOMATO_ADAPTER_PLUGINS_DIR` or `-Dontomato.adapters.dir`):
```text
backend_data/adapters/
└── <name>/
├── ontoplato-adapter-<name>-api1.jar
└── <vendor-jdbc-driver>.jar
```
- **Co-locate JDBC drivers in the same subdirectory**: give each plugin its own subdirectory containing the adapter JAR, its JDBC driver JAR(s), and any private dependencies. Keep signed vendor JDBC drivers as separate JARs — never shade/repack them into the plugin JAR. Loose JARs at the root of `adapters/` are ignored with a warning log.
- **Version check before bytecode load**: `DataAdapterPluginLoader` verifies `OntoPlato-Adapter-Api-Version` from the ZIP manifest before loading any classes. For valid subdirectories it creates an isolated `URLClassLoader` and initializes any `java.sql.Driver` shipped inside that subdirectory so standard `DriverManager.getConnection(...)` works cleanly without cross-plugin interference.
- **Fault isolation**: missing/mismatched API versions, load errors, or colliding `type()` values skip only that plugin and log the directory name, JAR name, and exact reason while the engine starts normally. Runtime requests targeting that adapter type return an explicit "adapter not installed or plugin API version mismatch" error.
- **Install / uninstall**: add or delete the `<name>/` subdirectory and restart `datarag`.
## 2. Java SPI provider (`DataAdapterProvider`) and configuration metadata
Both built-in and external adapters register via standard Java SPI: **never annotate with Spring `@Component`** or inject Spring beans; providers must have a `public` no-argument constructor.
List each fully qualified provider class name (one per line) in `src/main/resources/META-INF/services/io.ontomato.dataengine.dataAdapter.DataAdapterProvider`:
```text
io.ontomato.dataengine.dataAdapter.FooAdapterProvider
```
```java
public class FooAdapterProvider implements DataAdapterProvider {
@Override public String type() { return "foo"; }
@Override public String label() { return "FooDB"; }
@Override public boolean requiresJoinFields() { return true; }
@Override public List<String> connectionFields() {
return List.of("url", "user", "password");
}
@Override public Map<String, String> connectionExamples() {
return Map.of("url", "jdbc:foo://db.example.com:5432/app", "user", "reader");
}
@Override public DataAdapter create(DataAdapterConnection connection,
DataRagConfig config, Map<String, Object> jsonRule) {
return new FooAdapter(connection, jsonRule);
}
}
```
Contract details:
- `type()` is a stable lowercase persisted identifier; never rename it after release. Multiple `type()` values may share one adapter implementation (such as `elasticsearch` and `opensearch`).
- `requiresJoinFields()` returns `true` when relations join via `fromField`/`toField` (relational and search engines) and `false` for native relationship-edge graph engines (such as Neo4j).
- `connectionFields()` and `connectionFieldDefinitions()`: any custom field keys are supported (not restricted to the original four). The default `connectionFieldDefinitions()` derives `DataAdapterConnectionField` descriptors from `connectionFields()` and `connectionExamples()` and automatically marks secret-looking names via `DataAdapterConnectionField.isSecretName(name)` for masking. Override `connectionFieldDefinitions()` when custom labels, `required` flags, or `fullWidth` layout are needed — never add adapter-specific frontend branches.
- `connectionExamples()` must contain realistic placeholders only (use `*.example.com` or `192.0.2.x`; never real credentials or internal hostnames).
- `create(...)` must pass the caller's real `jsonRule` to the adapter; never cache adapters by connection or substitute an empty rule. Override `create(BusinessConfig, ...)` only for multi-source composite adapters.
### Connection test response shape
The settings and connection-test panel is entirely metadata-driven (no frontend changes required). `testConnection()` (implemented by `DataAdapterConnectionTester` for JDBC; overridden by non-JDBC adapters) is validated strictly by `dataAdapterTestResultSchema` and must return one of two shapes:
- **Catalog sources (JDBC, graph)**: `kind: "catalog"` with `elapsedMs`, `databaseProduct`, `databaseVersion`, `driverName`, `driverVersion`, `catalog`, `schema`, and `tables: [{name, type}]`.
- **Search sources (Elasticsearch / OpenSearch)**: `kind: "search"` with `elapsedMs`, `databaseProduct`, `databaseVersion` (nullable), `clusterName` (nullable), and `indices: [...]` (omitting `driverName`, `catalog`, `schema`, and `tables`).
## 3. Read path contract (DSL execution and limits)
### Request and response envelopes
- `executeDsl(queryJson, sessionId, mode, generatedMqls)` receives `queryJson` as a JSON **array** of DSL documents (use index `0`) rooted at `answer.steps`:
- `objects[]` carries `class` (the resolved physical name on the read path), `variable` (alias), `idx` (endpoint index for relations), and `conditions.properties`.
- `relationship[]` carries `from`/`to` (`idx` indices, not class names) and a `type` array (first item is the relation name; graph engines support `["*"]`). Omitting `relationship` means a single-object query.
- Two-step queries: `steps[0]` filters and projects; `steps[1]` aggregates, sorts, or limits over step 0's projected columns (SQL wraps step 0 in a subquery, Neo4j bridges with `WITH` -> `RETURN`, ES materializes and streams aggregations).
- **Append native queries**: append every generated SQL/Cypher/query JSON string to `generatedMqls`.
- **Response shape**: JSON array `[{ "answer": [...], "mqls": [...], "truncated"?: true, "rowLimit"?: 20000, "truncationHint"?: "..." }]`, serialized with `WriteMapNullValue` so null columns are preserved.
- **Error boundary**: `executeDsl()` throws on failure (always rethrow `DslContractViolationException` before any generic `catch`); `query()` catches execution failure and returns `{ error }` in the map instead of throwing. Keep these two paths distinct.
### Conditions, projections, and row limits
- **Condition tree**: supports arbitrary `and`/`or`/`not` nesting and operators `=`, `!=`, `<`, `<=`, `>`, `>=`, `in`, `not_in`, `between`, `like` (on the read path, wrap values without wildcards in `%...%` and handle escaping via `LikePattern`), `is_null`, `is_not_null`, and `text`. Unsupported constructs or type-mismatched operators must throw `DslContractViolationException` with `Code` and `dslPath`.
- **Output clauses**: supports `fields` (`as`, aggregates `count`/`sum`/`avg`/`min`/`max`, `distinct`), `group_by` (with `having`), `sort`, and `limit` (`count`/`offset`).
- **Default row limit (`DslRowLimit`)**: applies only to the terminal step. When `limit` is omitted, probe with `cap + 1` using `DslRowLimit.defaultRowLimit()` (default `20000`); if more than `cap` rows arrive, trim the probe row and report `truncated: true`, `rowLimit`, and `truncationHint`. An explicit `limit` is not truncation.
- **Time conditions**: `timeConditionsAsEpochMillis()` defaults to `false` (pass literal values verbatim for native column comparison); override to `true` (and `timeConditionZone()` if needed) only when the backing store requires epoch milliseconds (such as M3).
## 4. Write path, sandbox, and vector attribute contracts
### `jsonRule` and namespace semantics
- `jsonRule` holds `classDef` (`className` is the bare class name; `attrs[]` holds `name`, `type`, `primaryKey`, `enable`) and `relationship_rule` (`fromclass`, `toclass`, plus `fromField`/`toField` for key-field engines). Read paths use physical names; write paths must look up `classDef` by bare class name.
- **Namespace is a table/collection name prefix, not a database schema**: `createNamespace` is usually a no-op for relational, search, and graph engines; `truncateNamespace` and `dropNamespace` enumerate tables in the current schema whose lowercase name starts with the lowercase namespace prefix and delete rows or drop tables (alias `TABLE_NAME` to lowercase `table_name` for MySQL/SQL Server `information_schema` queries).
- **Type mapping**: map `varchar`, `text`, `int`, `long`, `double`, `date`, `timestamp`, and `vector` according to the engine dialect (relational engines always store `vector` as a text column: PostgreSQL `text`, MySQL `longtext`, SQL Server `nvarchar(max)`, DuckDB `varchar`).
- **Object and edge CRUD**:
- `createClass` skips attributes with `enable == false` or unsupported types.
- `insertObjects` writes only enabled supported attributes, rejects missing/null primary keys, escapes single quotes, and formats dates/timestamps as `yyyy-MM-dd` / `yyyy-MM-dd HH:mm:ss`.
- `updateObjects` rejects primary key updates and unknown fields; `deleteObjects` with an empty condition clears the class.
- `createEdge` / `deleteEdge`: key-field engines update the `fromField` side; graph engines create/delete native edges.
- **Sandbox write actions (optional)**: adapters supporting Action sandbox trials implement `forSandbox(SandboxTarget)`, `supportsSandbox()`, `sandboxClassName`, and `sandboxObjectId`; override `requiresSandboxEdgeResource`, `sandboxEdgeArtifact`, and `dropRecordedResource` when a relationship requires its own physical resource (such as default `n:n` join tables or ArangoDB native edge collections).
### Vector attribute contract (including `name`)
- Vector attributes are stored in a text column as a JSON array string:
```json
[{"path": "...", "text": "...", "name": "original-filename.pdf"}]
```
where `name` stores the original filename (omitted when none was saved).
- `DataAdapter` has **no** `appendVector`/`updateVector`/`deleteVector` methods (the service layer coordinates those with normal `updateObjects`/`deleteObjects` and the vector store). Adapters implement only `queryVectorAttr(classDef, attrName, objectId)`:
- Parse the stored column with `DslUtil.parseVectorAttr(value)` into a `JSONArray` (empty array when null or blank);
- Throw `IllegalArgumentException` when the target `objectId` does not exist.
## 5. Non-JDBC engine notes
- **Elasticsearch / OpenSearch**: share one adapter implementation with dialect differences encapsulated in `EsDialect` (PIT open/close paths, ID key, tiebreaker). Deep pagination must use PIT + `search_after` (never `from`/`size`, which hits `index.max_result_window`). Cache `_shard_doc` capability per cluster URL + dialect and fall back to a `keyword` primary key when `_shard_doc` is missing. Push small-side `terms` into joins first, cap materialization with `ontomato.es.maxMaterialize` (default 100000), always close PITs in `finally`, and return `kind: "search"` from `testConnection()`.
- **Neo4j**: `openConnection()` throws unsupported; `testConnection()` runs `RETURN 1` and `CALL db.labels()` and returns `kind: "catalog"`. Classes map to node labels and relations map to directed edges; support multi-type `-[:a|b]->`, wildcard `["*"]` -> `-[]->`, `max_hops = -1` capped at `10`, two-step `WITH` -> `RETURN` pipelines, and `ontomato.neo4j.maxMaterialize`. Capabilities: `FULL - JDBC_CONNECTION + RELATIONSHIP_EDGES`.
- **M3**: non-JDBC timeseries/graph engine with `timeConditionsAsEpochMillis() = true`, capabilities `FULL - JDBC_CONNECTION - EDGE_CRUD`, and `sourceRendersTimeseries() = true` in tests.
## 6. Contract test suite and build commands
### Shared contract suite (`AbstractDataAdapterTest`)
Every adapter needs at least two test classes:
1. **`<Engine>AdapterProviderTest`**: pins `type()`, `label()`, `requiresJoinFields()`, `connectionFields()`/`connectionFieldDefinitions()`, `connectionExamples()`, and verifies SPI loading via `ServiceLoader`.
2. **`<Engine>AdapterTest extends AbstractDataAdapterTest`**: runs the shared contract suite against a real engine, supplemented with protocol, dialect, and scale-boundary tests.
Fixture and hook rules:
- `namespace()` must be unique per test instance (e.g. `"it_" + System.nanoTime() + "_"`); mirror `PostgreAdapterTest`'s `classDef()`, `testObjects()`, and `graphSeed()` fixture values.
- **Enable capabilities only after tests turn green**: never declare a `DataAdapterCapability` whose test group has not passed on a real engine. Missing Docker or external test URLs must skip via assumptions rather than fail.
- **Read-only relational adapters**: because `READ_QUERY` calls write-based `seedGraph()` by default, pre-seed tables outside the adapter and override `seedGraph()` and `dropGraph()`.
- **Non-JDBC adapters**: override `selectAll()` and `countRows()` using the engine's native read API.
### OntoPlato monorepo build and test commands
Use `./mvnw` from the repository root, and **never run unfiltered `-am test`** (which would execute upstream database/model integration tests):
```bash
# 1. Install core contract and test-support artifacts locally (once before external plugin builds)
./mvnw -B -ntp -pl packages/data-engine-core,packages/data-adapter-test-support -am -DskipTests install
# 2. Build the data-engine reactor (includes built-in adapters and m3)
./mvnw -B -ntp -pl apps/data-engine -am -DskipTests package
# 3. Run a targeted built-in adapter test class or method
./mvnw -B -ntp -pl packages/data-adapters/postgresql -am test \
-Dtest=PostgreAdapterTest -Dsurefire.failIfNoSpecifiedTests=false
# 4. Run targeted m3 adapter tests
./mvnw -B -ntp -pl packages/data-adapters/m3 -am test \
-Dtest=M3AdapterTest -Dsurefire.failIfNoSpecifiedTests=false
# 5. Test and package an external standalone plugin project (producing a JAR with OntoPlato-Adapter-Api-Version)
mvn -B -ntp test -Dtest=FooAdapterTest
mvn -B -ntp package -DskipTests
```
External test engine overrides use `ONTOMATO_TEST_<ENGINE>_URL`, `_USER`, and `_PASSWORD` (`PG`, `MYSQL`, `MSSQL`, `NEO4J`, `ES`, plus `ONTOMATO_TEST_ES_DIALECT=opensearch` for OpenSearch). Run `rm -rf target` after deleting or moving test classes so stale `.class` files are removed.
## 7. Pre-delivery review gates
Verify every gate before submitting or shipping an adapter plugin:
- [ ] **SPI & manifest complete**: `META-INF/services/io.ontomato.dataengine.dataAdapter.DataAdapterProvider` is present with no Spring `@Component`; `META-INF/MANIFEST.MF` declares `OntoPlato-Adapter-Api-Version: 1`.
- [ ] **Plugin subdirectory layout**: delivered as `<name>/` (adapter JAR + unshaded JDBC driver JAR), with no bundled `data-engine-core`, `fastjson2`, or `slf4j`, and no edits to product POMs.
- [ ] **No silent degradation**: every unsupported DSL construct, operator, and read-only write method explicitly throws `DslContractViolationException` or `UnsupportedDataAdapterOperationException`.
- [ ] **Critical boundaries verified**: `DslRowLimit` `cap+1` truncation probe, `queryVectorAttr` (including `name` field parsing and `IllegalArgumentException` on missing object), and strict `catalog` / `search` `testConnection()` schema.
- [ ] **Real-engine evidence recorded**: attach engine version and Surefire XML counts (`run / failures / errors / skipped` with skip reasons), and clean up temporary namespaces and containers afterward.
- [ ] **Public repository hygiene**: no real credentials, private/RFC1918 IPs, internal hostnames, or customer identifiers in code, examples, or tests.