SlackerDB is a Java‑based service layer that puts DuckDB on the network. It speaks the PostgreSQL wire protocol, so standard PostgreSQL JDBC clients connect without any special driver; it also lets multiple clients share the same DuckDB database — something a single‑process DuckDB cannot do. On top of that, it provides a bulk COPY channel for importing and exporting data, and a registered‑SQL layer that turns queries into cacheable HTTP endpoints.
It runs either as a standalone server (dbserver, dbproxy) or embedded directly in a Java application.
-
PostgreSQL Wire Protocol – Standard PostgreSQL clients connect as‑is: JDBC, ODBC, libpq, psql, Python.
-
PostgreSQL Data Dictionary Compatibility – Emulates the data dictionary that database tools need to access, such as DBeaver, postgres_fdw, and psql; under these tools SlackerDB looks just like a PostgreSQL database.
-
Multi‑Session Access – One DuckDB database served to many concurrent client sessions, with a connection pool, per‑session state, and SQL executed off the network I/O threads.
-
Query Cancellation – Client‑side cancellation and
KILL SESSIONreach the statement that is actually running. -
High‑Performance Bulk Transfer – PostgreSQL
COPY … FROM STDINandCOPY … TO STDOUTin CSV and BINARY form, including exporting a subset of columns (something PostgreSQL does not support today). -
Registered SQL Services – Register parameterized SQL as named HTTP endpoints at runtime, with result caching, service versioning, and per‑service search paths.
-
Server Management APIs – Status and metrics, database backup, log viewing, and file upload/download on the management port.
-
Asynchronous SQL over WebSocket – Execute SQL asynchronously and page through results, for queries too large or too slow for a single request.
-
Embeddable Design – Run as a standalone process, or embed in Java code; multiple instances can run side by side on different ports.
-
Plugin System – Extensible PF4J‑based plugin framework for custom functionality, HTTP endpoints, and background tasks, with runtime load/start/stop/unload.
-
Data Encryption – Leverages DuckDB’s native encryption for data‑at‑rest protection.
-
Command‑Line Access – A custom psql‑like client that supports batch SQL scripts and interactive SQL, plus complex concurrent job coordination and SQL result comparison.
-
Job Orchestration – Uses plugin capabilities to provide HOP‑based job orchestration for scheduled workflow execution.
-
Console Access – In progress. Will provide a complete browser‑based graphical workbench.
-
Database Proxy – Manages multiple database instances through a proxy and connects to different instances through a unified port.
-
Analytical Application Backends – Serve as the data engine for BI tools, dashboards, and reporting applications that support PostgreSQL connections.
-
Shared Internal Datasets – Want DuckDB’s analytical performance and strong SQL capabilities, but need network access and do not want the analysis process to be a black box. Load an existing
.duckdbfile once and let several teams and tools query it concurrently without moving or re‑platforming the data. -
Embedded Service in Java – Provide a networked analytical store inside a Java application and expose a data access point.
# Before building, make sure the following are installed and directly available on `PATH`:
# 1: JDK 21
# 2: Maven 3.9.16
# 3: Node v24 (web console only; ignore it if you do not need the console)
# All of them must be directly accessible from `PATH`.
# Download source code
git clone ...
# compile it
cd slackerdb
mvn clean compile package -DskipTests
# All compiled results will be placed in the dist directory:
# slackerdb-dist_0.2.2.zip
# distribution package - standalone jar packages,
# default configuration files and start/stop scripts.
# slackerdb-src_0.2.2.zip
# source package - the complete multi-module Maven project, the same
# content a shallow clone would give you (no git history, no build
# output). Unzip it and run the very same maven command inside to
# rebuild everything from source.
# slackerdb-docs_0.2.2.zip (only when built with -Ppdf)
# PDF documentation - README.pdf and README-CN.pdf at the top level,
# the dbcli manual (README.pdf / README-CN.pdf) under dbcli/.
# PDF documentation is not built by default, and it is not packed into the
# distribution package either: the PDFs ship in slackerdb-docs_0.2.2.zip.
# To generate them, add -Ppdf:
# mvn -Ppdf clean compile package -DskipTests
# To rebuild only the documentation, build the docs module on its own:
# that writes dist/slackerdb-docs_0.2.2.zip and leaves the release
# packages untouched.
# mvn -Ppdf -pl docs package
On a machine with network access, install the plugin once and generate offline/javarepo and
offline/npmrepo:
mvn -f offline-package-maven-plugin/pom.xml install
mvn -Poffline-package validate
The command also writes offline/javarepo.zip and offline/npmrepo.zip, and removes the
uncompressed javarepo/ and npmrepo/ directories. Copy those two zips to the offline
machine and unzip them into the same directory.
When regenerating, npm packages are taken from existing local caches first (the previous
offline/npmrepo, NPM_CONFIG_CACHE, and the machine-wide cache reported by
npm config get cache). Only packages that no local cache contains are fetched from the npm
registry. Add -Doffline.npm.cache.dirs=<dir> (comma or semicolon separated) for extra cache
directories.
javarepo does not only contain the jars that end up on the classpath: it carries the complete
POM descriptor closure (parent POMs, imported BOMs, and every candidate dependency version Maven
reads while collecting, including the ones dropped by nearest-wins mediation). An offline build
therefore never degrades to [WARNING] The POM for … is missing, no dependency information
available; if a required POM cannot be packaged, the collection fails instead of shipping an
incomplete package. Unpack javarepo.zip and re-check the closure on the generating machine
with mvn -o -N org.robotslacker.tools:offline-package-maven-plugin:1.0.0:verify.
The jars of the losing candidate versions are packaged as well (offline.candidate.jars, on by
default, about 25 MB). Maven never resolves them for this reactor, but they keep the repository
usable if a module POM is edited offline or another resolution order picks such a version. Use
-Doffline.candidate.jars=false to skip them.
mvn clean does not delete offline/: the offline package is also the -Dmaven.repo.local.tail
repository of the offline build, so cleaning it would delete the repository the build depends on.
Regenerating replaces the directory by itself (offline-package:collect stages the new package
and swaps it in).
Before building, make sure the required JDK, Maven, and Node are installed and available on PATH.
On the offline machine, use the packaged Maven repository (first unzip javarepo.zip and
npmrepo.zip under <offline>):
Run the following commands to complete the build:
mvn -o -Dmaven.repo.local.tail=<offline>/javarepo clean package -pl !dbdesk -am
# or
NPM_CONFIG_CACHE=<offline>/npmrepo NPM_CONFIG_OFFLINE=true mvn -o -Dmaven.repo.local=/tmp/m2 -Dmaven.repo.local.tail=<offline>/javarepo package
# Database name. Empty means the built-in memory database (named memory, nothing written # to disk); the management API and internal tables such as sysaux live in it. data= # Path where data files are saved # ":memory:" indicates in-memory mode (data will be lost after restart) # ":ducklake:" indicates DuckLake mode (requires ducklake_meta below, ducklake_path optional) data_dir=:memory: # DuckLake metadata connection # Format: user/password@host:port/database (a DuckDB/SQLite metadata file path also works) # Required when data_dir=:ducklake:, ignored otherwise ducklake_meta= # DuckLake data path # Filesystem path or s3 path (e.g., s3://my-bucket/my-data/) # Optional when data_dir=:ducklake: (DuckLake uses its default location when empty) # Ignored otherwise ducklake_path= # Temporary files directory during operations # Disk mode: Defaults to data_dir if not specified # Memory mode: Defaults to system temp directory if not specified # Recommended: Use high-performance storage for temp_dir temp_dir= # Directory for extension plugins # Default: $HOME/.duckdb/extensions extension_dir= # Directory for custom plugins # Default: None plugins_dir= # Run as background daemon (true/false) # Command line notes: `--daemon true|false`; a bare `--daemon` means true. # An explicit `--daemon` on the command line overrides this setting. # Only the `start` subcommand supports daemon mode. daemon= # PID file location # - Locks exclusively during server operation # - Startup aborts if file is locked by another process # - No file created if not configured, and no lock. pid= # Log output destinations (comma-separated) # "CONSOLE" for stdout, file paths for file logging log=CONSOLE,logs/slackerdb.log # Log verbosity level log_level=INFO # Main service port # 0 = random port assignment # -1 = disable network interface # Default: 0 (disabled) port= # Used to indicate whether data encryption is enabled. # If enabled, a key must be provided before accessing the database. # default: false data_encrypt=false # Management API port # 0 = random port assignment # -1 = disable interface (default) port_x= # Network binding address bind=0.0.0.0 # Client connection idle timeout (seconds) client_timeout=600 # Multicast service discovery: the group this server announces itself to. # Format: <group>:<port> (IPv6 groups must be bracketed: [ff02::1]:46666) # IPv4 groups must be inside 224.0.0.0/4; 224.0.0.0/24 is reserved and rejected. # Default: service discovery is disabled. advertise_address= # Local network interface used to send the multicast announcement. # Accepts an interface name (eth0, Ethernet) or a local IPv4 address; leaving it empty # selects the first usable interface automatically. # Ignored when advertise_address is empty. advertise_nic= # Database opening mode. # Default: READ_WRITE access_mode=READ_WRITE # Maximum concurrent connections # Default: 256 max_connections= # Maximum concurrent SQL REPL sessions # Each session holds one private connection outside the pool; when the limit # is reached, new sessions are rejected immediately with "Too much connections." # Default: 64 repl_max_connections=64 # Maximum worker threads # Default: CPU core count max_workers= # Business processing threads (executes SQL off the Netty I/O threads) # Default: -1 = follow max_connections (one business thread per session) # 0 = disabled (run SQL on the I/O threads; a slow query will block other # connections sharing the same I/O thread) # >0 = explicit thread count # Note: connections sharing one business thread still queue behind each other. # The number of connections affected by a slow query is about # (connections / business_threads - 1), so keep this close to the number of # concurrently active sessions. business_threads= # Database engine threads # Default: 80% of total system memory (GB) / 10 (minimum 1) # Recommendation: adjust based on workload threads= # Memory usage limit. Accepts an absolute size (K/M/G suffix) or a percentage # of total system memory, for example 60%. # Default: 80% of total system memory # -1 = unlimited (memory mode only) memory_limit= # Maximum execution time per query in milliseconds (0 = no limit). # Applied as the DuckDB GLOBAL setting; a data service definition or the # maxExecutionTime request header can override it per query. The server's # backend connection, init/startup scripts and internal maintenance are exempt. max_execution_time= # Database template file template= # Initialization script(s) # Executes only on first launch # Accepts: .sql file or directory init_script= # Startup script(s) # Executes on every launch # Accepts: .sql file or directory startup_script= # System locale # Default: OS setting locale= # SQL command history # ON = enable tracking # OFF = disable (default) sql_history=OFF # Minimum idle connections in pool connection_pool_minimum_idle=3 # Maximum idle connections in pool connection_pool_maximum_idle=10 # Connection lifetime (milliseconds) connection_pool_maximum_lifecycle_time=900000 # Query result cache configuration (in bytes) # - Only caches API request results (JDBC queries unaffected) # - Default: 1GB (1073741824 bytes) # - Set to 0 to disable caching query_result_cache_size= # Data service history # ON = enable tracking # OFF = disable (default) data_service_history= # Data service schema initialization file/path # - Accepts: # * JSON file path (single schema) # * Directory path (loads all *.service files) # - Schema files should contain service definitions in JSON format data_service_schema= # MCP definitions loaded at startup # - Accepts: # * JSON file path (single config) # * Directory path (loads all *.mcp and *.service files, in name order) # - Each tool entry may set "handler": "builtin:<name>" to bind to a real implementation # (run_sql, list_tables, describe_table, sample_rows, list_services, # open_session, close_session). # Without "handler" the tool only echoes its arguments. # Built-in tool names are reserved: a declared tool may not reuse one. # Default: empty (no MCP definitions; the built-in tools are always available) mcp_config= # MCP LLM server configuration # Format: <service>:<ip>:<port>:<model> # Example: openai:api.openai.com:443:gpt-4 # Default: empty (no LLM server configuration) mcp_llm_server= # MCP LLM API key for services that require authentication # Required for OpenAI API and optional for other services # Example: sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # Default: empty (no API key) mcp_llm_key= # Unix Domain Socket file path # Used for UDS (Unix Domain Socket) connections instead of TCP # Default: empty (UDS disabled, use TCP) # Note: Only supported on Linux/macOS. Ignored on Windows. socket= # Quack remote server address # Format: IP:PORT (e.g., 0.0.0.0:9494) # Default: none (Quack disabled) quack_addr= # Quack authentication token # - Minimum 4 characters # - Default: empty (a random token is generated; it is logged and shown by the # status command) quack_token=
# PID file location # - Locks exclusively during server operation # - Startup aborts if file is locked by another process # - No file created if not configured, and no lock. pid= # Log output destinations (comma-separated) # "CONSOLE" for stdout, file paths for file logging log=CONSOLE,logs/slackerdb-proxy.log # Log level log_level=INFO # Run as background daemon (true/false) # Command line notes: `--daemon true|false`; a bare `--daemon` means true. # An explicit `--daemon` on the command line overrides this setting. # Only the `start` subcommand supports daemon mode. daemon= # Main service port # 0 = random port assignment # -1 = disable network interface # Default: 0 (random port) port=0 # Management API port # 0 = random port assignment (default) # -1 = disable interface port_x=0 # Network binding address bind=0.0.0.0 # Multicast service discovery: the group this proxy listens to. # Format: <group>:<port> (IPv6 groups must be bracketed: [ff02::1]:46666) # No default: leaving it empty disables discovery # Must match the dbserver's advertise_address exactly listener_address= # Root directory for managed database instances. Each subdirectory is one instance; its name is the alias. # Empty = instance management disabled # See the "Multi-instance management" section below. data_dir= # File-name pattern of the dbserver runtime jar, searched in the proxy directory, jlib, etc. # Example: slackerdb-dbserver-*-standalone.jar # No default: when empty, creating new instances is refused (existing instances still work). dbserver_jar= # Client connection idle timeout (seconds) client_timeout=600 # Maximum worker threads # Default: CPU core count max_workers= # Business processing threads (executes SQL off the Netty I/O threads) # Default: -1 = follow max_connections (one business thread per session) # 0 = disabled (run SQL on the I/O threads); >0 = explicit thread count business_threads= # Database engine threads # Default: 80% of total system memory (GB) / 10 (minimum 1) # Recommendation: adjust based on workload threads= # Memory usage limit. Accepts an absolute size (K/M/G suffix) or a percentage # of total system memory, for example 60%. # Default: 80% of total system memory # -1 = unlimited (memory mode only) memory_limit= # Maximum execution time per query in milliseconds (0 = no limit). # Applied as the DuckDB GLOBAL setting; a data service definition or the # maxExecutionTime request header can override it per query. The server's # backend connection, init/startup scripts and internal maintenance are exempt. max_execution_time= # System locale # Default: OS setting locale=
Note: All parameters are optional.
You can keep only the parameters you need to modify.
For parameters that are not configured, default values will be used.
UDP multicast discovery: dbserver periodically announces "I am here" to a multicast group; the proxy joins the same group and maintains the alias-to-backend map from those announcements.
| Module | Description |
|---|---|
dbserver |
A multicast group within a subnet |
dbserver |
Empty selects the first usable network interface |
dbproxy |
Must match the dbserver |
With data_dir configured, the proxy can manage multiple database instances on the local machine: each instance is a separate dbserver process.
Creating an instance also requires dbserver_jar (the file-name pattern of the dbserver runtime jar,
for example slackerdb-dbserver-*-standalone.jar). It has no default: without it create returns 503,
while existing instances can still be listed, stopped and destroyed.
instances/
sales/ # directory name = alias (database in the connection string)
instance.conf # single source of truth: database name, both ports, pid, log paths
bin/start.sh|bat # foreground start
bin/start-daemon.sh|bat # background start
bin/stop.sh|bat # graceful stop (PG port management frame)
bin/status.sh|bat
data/sales.db
logs/server.log # dbserver log (default; log= may point elsewhere)
logs/console.log # child process stdout/stderr
instance.pid # default pid file (pid= may use another name)
An alias and a database name may differ (--name sets the database name; it defaults to the alias). Aliases are unique; creating a duplicate returns 409.
create accepts any dbserver setting as a --key value pair: ports, log, data path, pid, bind, multicast
registration, access mode, plugin parameters, and so on are all owned by the user. The proxy only fills in the
settings the user did not mention and does not judge the values — a port conflict, an unwritable directory or an
invalid value shows up as a dbserver startup error. CLI values travel over the admin channel (the ! frame on the
PG port) and therefore cannot contain spaces; the HTTP API has no such restriction.
dbproxy create --alias sales --conf dbproxy.conf \
--port 15433 --port_x 15434 --log logs/sales.log --data_dir /data/sales
-
port/port_xset to0(or omitted) means "let the proxy pick a free port": the real port is written intoinstance.confand is available afterwards fromlist,GET /admin/databases/<alias>or the create response.port_x=-1disables the management port of that instance. -
An instance always lives in
<data_dir>/<alias>andinstance.confis written there; every other setting (data,data_dir,pid,log,bind,advertise_address,access_mode,max_connections,<pluginId>.<param>, …) is copied into that file verbatim. Relative paths resolve against the instance directory, because the dbserver is started with it as its working directory. -
The configured
pidandlogare followed everywhere: probing reads the pid file named bypid=(renamed or absolute paths are fine), andGET /admin/databases/<alias>/logstails the file(s) named bylog=(CONSOLEentries are skipped,${data}is substituted with the database name). Nothing assumes the defaultinstance.pid/logs/server.log.logfileis dbserver’s alias forlog; it is normalized tologon create (an explicitlogwins), soinstance.confnever contains both keys with an ambiguous winner. -
--nameis shorthand fordata; when both are given,--datawins. -
For
create,--confstill means the proxy client config (used to locate the proxy); every other--key valuedescribes the new instance, e.g.dbproxy create --alias sales --conf dbproxy.conf --port 15433. -
Proxy-managed processes always run in the foreground: even if
daemon=trueis passed, the launch overrides it with--daemon false(bin/start-daemoncan still be used for a manual background start).
| Command | Description |
|---|---|
|
Create an instance and start it by default |
|
Start a stopped instance |
|
Graceful stop (data and directory are kept) |
|
Stop, then start again |
|
Stop and delete the entire instance directory |
|
List the live state of all instances |
|
Proxy status plus the instance table |
The full HTTP contract of the management port (proxy status, instance management, /<alias>/** prefix forwarding and WebSocket) is described in the next section, Proxy HTTP API.
Behavior:
-
Two kinds of backends:
management= instances discovered underdata_dir(managed by the proxy);external= backends registered through multicast. The state and theSOURCEcolumn inlistdistinguish them. External backends only forward data:start/shutdown/restart/destroyreturn 409 and never appear in the instance directory. -
Internal aliases win conflicts: when an instance with the same name exists under
data_dir, external announcements are discarded and an existing external entry with the same name is removed immediately. -
No cascade:
dbproxy stopstops only the proxy; instances keep running. -
No automatic recovery: restarting the proxy does not start any instance.
-
Destroy only removes the instance directory:
destroydeletes<data_dir>/<alias>. If the instance’sdata_dirpoints outside that directory, it is ignored (the data is kept; clean it up yourself if needed). -
Proxy bypass is allowed: run
bin/start-daemon/bin/stopin the instance directory directly; every status query re-probes the instance (/health+ pid + command-line validation), so manual starts and stops are recognized correctly.
The proxy management port (config port_x, CLI --portX) serves three kinds of requests: the proxy’s own status, lifecycle management for managed instances, and transparent forwarding of /<alias>/ to that instance’s management port.
port_x=0 (the default) assigns a random port; the actual value is in the startup log. port_x=-1 disables the management port, and every endpoint in this section becomes unavailable.
The management port is API-only**: the proxy serves no HTML/Web UI of its own (dbdesk is the UI).
| Priority | Path | Target |
|---|---|---|
1 |
|
The proxy itself |
2 |
|
The proxy’s instance management |
3 |
|
The management port of that alias (HTTP passthrough) |
4 |
|
|
Priority follows registration order, so /admin/** is never treated as an alias. Only the first path segment is the alias; the rest of the path (including the query string) is appended to the target URL unchanged.
admin, status, capabilities and health are reserved names and cannot be used for instances.
General conventions
-
Errors produced by the proxy itself use a JSON envelope:
{"retCode": <HTTP status>, "retMsg": "<reason>"}. A successfully forwarded response keeps the instance’s status code, headers and body without rewrapping; the envelope is only generated when forwarding fails. -
The management port has no authentication or authorization. Restrict it with
bindand never expose it to an untrusted network. -
CORS is enabled by default (any origin), so browser consoles can call it directly.
-
Responses generated by the proxy are UTF-8 JSON (except the per-instance log endpoint, which returns
text/plain); forwarded responses keep the instance’s content type, which may be anything, including binary.
The proxy’s own status plus every currently registered backend. It uses the latest scan snapshot and does not force a re-probe, so it is cheap.
{
"role": "proxy",
"version": "0.2.2",
"pid": 12345,
"uptimeSeconds": 3600,
"managementPort": 18080,
"pgPort": 15432,
"instanceManagementEnabled": true,
"backends": [
{ "alias": "erp", "target": "http://10.0.0.8:18080", "state": "UNKNOWN" }
],
"backendCount": 1,
"databases": [
{
"alias": "erp",
"source": "external",
"manageable": false,
"name": "erp",
"state": "RUNNING",
"pid": null,
"pgPort": 5432,
"mgmtPort": 18080,
"health": "UNKNOWN",
"uptimeSeconds": null,
"error": null,
"dir": null,
"target": "10.0.0.8:5432"
},
{
"alias": "sales",
"source": "management",
"manageable": true,
"name": "sales",
"state": "RUNNING",
"pid": 23456,
"pgPort": 42001,
"mgmtPort": 42002,
"health": "UP",
"uptimeSeconds": 1200,
"error": null,
"dir": "/data/instances/sales",
"target": null
}
]
}-
backendscontains only externally registered (multicast-discovered) forward mappings;stateis alwaysUNKNOWNbecause the proxy cannot probe them further.backendCountis its length. -
databasesis the unified view: bothmanagement(instances scanned underdata_dir) andexternal(multicast-registered backends) appear here. Field meanings are in "Backend object" below. -
The proxy itself has no
/healthendpoint (/healthis the dbserver liveness probe); monitor the proxy through/status.
Declares the management API contract version and the proxy’s capabilities so clients can discover which endpoints to call.
{
"apiVersion": 1,
"proxy": { "version": "0.2.2", "pid": 12345 },
"ports": { "pg": 15432, "management": 18080, "managementEnabled": true },
"managementForwarding": { "enabled": true, "prefixMode": "alias" },
"provisioning": {
"enabled": true,
"mode": "process",
"adminBase": "/admin",
"features": ["list", "detail", "create", "start", "shutdown", "restart", "destroy", "logs"],
"backendSources": ["management", "external"]
},
"contracts": { "managementApi": 1 }
}-
apiVersionandcontracts.managementApiare the management API contract version (currently1), not the product version; the product version is inproxy.version. -
provisioning.enabledmirrorsinstanceManagementEnabled: it isfalsewhendata_diris not configured, and write operations against managed instances then return 503. -
managementForwarding.prefixMode=aliasdescribes the/<alias>/**forwarding rule.
| Method | Path | Description |
|---|---|---|
GET |
|
List every backend plus the instance root |
GET |
|
One backend (managed instances include |
POST |
|
Create an instance |
POST |
|
Start an instance |
POST |
|
Gracefully stop an instance |
POST |
|
Stop, then start again |
DELETE |
|
Stop and delete the instance directory |
GET |
|
Tail the instance log (plain text) |
Every endpoint except the list requires the alias to exist; otherwise it returns 404. Lifecycle failures return 400/409/500/504 depending on the cause, still using the retCode/retMsg envelope.
Lists backends. The optional query parameter probe (default true) controls forced re-probing: probe=false uses the latest scan snapshot (at most about 5 seconds old), which suits frequent polling.
{
"instanceManagementEnabled": true,
"storage": { "dataDir": "/data/instances" },
"databases": [
{
"alias": "sales",
"source": "management",
"manageable": true,
"name": "sales",
"state": "RUNNING",
"pid": 23456,
"pgPort": 42001,
"mgmtPort": 42002,
"health": "UP",
"uptimeSeconds": 1200,
"error": null,
"dir": "/data/instances/sales",
"target": null
}
]
}Backend object:
| Field | Type | Description |
|---|---|---|
|
string |
Alias, also the routing key |
|
string |
|
|
boolean |
Whether lifecycle operations are allowed; only |
|
string |
Database name (the |
|
string |
|
|
number/null |
Instance process id verified through its command line; |
|
number |
Data port |
|
number |
Management port; |
|
string |
|
|
number/null |
Process uptime; |
|
string/null |
Why the backend cannot be routed or its state cannot be determined |
|
string/null |
Managed instance directory; |
|
string/null |
|
When instanceManagementEnabled=false, storage.dataDir is null and databases contains only external backends. A failure to scan the instance directory returns a 500 envelope.
Returns one backend. Managed instances additionally carry conf (the lowercase key/value view of instance.conf); external backends only have address information. Managed instances are returned from the latest scan snapshot without a forced re-probe; use the list endpoint when the freshest state matters.
{
"alias": "sales",
"source": "management",
"manageable": true,
"name": "sales",
"state": "RUNNING",
"pid": 23456,
"pgPort": 42001,
"mgmtPort": 42002,
"health": "UP",
"uptimeSeconds": 1200,
"error": null,
"dir": "/data/instances/sales",
"target": null,
"conf": {
"data": "sales",
"data_dir": "data",
"port": "42001",
"port_x": "42002",
"pid": "instance.pid",
"log": "logs/server.log",
"bind": "127.0.0.1",
"daemon": "false",
"advertise_address": "",
"access_mode": "READ_WRITE"
}
}If the alias is neither a managed instance nor an external registration, the endpoint returns 404.
Creates an instance directory and, by default, starts it immediately.
{
"alias": "sales",
"name": "sales",
"start": true,
"conf": {
"port": 0,
"port_x": 0,
"log": "logs/sales.log",
"access_mode": "READ_ONLY"
}
}| Field | Required | Description |
|---|---|---|
|
yes |
Directory name / routing key, lowercased, pattern |
|
no |
Database name, defaults to |
|
no |
Whether to start right after creation, default |
|
no |
dbserver settings written into |
conf key rules: standard keys match [a-z][a-z0-9_]*; plugin parameters use <pluginId>.<paramName> (case is
preserved). Values must be single-line. The proxy does not validate the values; a bad setting fails at dbserver startup.
port / port_x set to 0 (or omitted) makes the proxy allocate a free port; the real port is written into
instance.conf and returned by the response and by later queries. port_x=-1 disables that instance’s management port.
Success returns 201 with the instance object (including conf and the real ports). If start=true and the start fails, the instance directory is kept and the response carries the start failure status; retMsg explains that it was created but failed to start, and why.
None of the three endpoints accepts a request body. Success returns 200 with the instance object (including conf).
-
start: waits up to 30 seconds for the instance/healthto reportUP; 409 if already running, 504 on timeout. -
shutdown: sends the PG-port stop frame and waits up to 20 seconds; if the process is still alive it sends SIGTERM to this instance’s process and waits 5 more seconds. An alreadySTOPPEDinstance returns 200 directly; an external backend or an unusable port returns 409; a process that still will not stop returns 500. -
restart:shutdown+start; for a stopped instance this is equivalent to a plain start.
Stops the instance if it is running and deletes the whole instance directory, returning:
{ "alias": "sales", "destroyed": true }Only <data_dir>/<alias> itself is deleted. If the instance’s data_dir points outside that directory, it is
ignored (the data is kept).
An external backend returns 409 (forward only, not manageable); a missing directory returns 404; a pid that is still alive but cannot be verified as this instance, or an instance that is still running, returns 409.
Returns the tail of the instance log as text/plain. The query parameter lines defaults to 200 and is capped at 5000.
The body contains the last N lines of the dbserver log file(s) named by log= in instance.conf (default
logs/server.log; comma-separated targets are all included, CONSOLE entries and missing files are skipped),
then the last min(N, 50) lines of logs/console.log, then the last 4 lines of logs/launch.log; each section
starts with a ---- <file> (last K lines) ---- separator. When none of the files exists, the body is
(no log file at <files>).
GET /admin/databases/sales/logs?lines=100
An external backend returns 409; a missing instance returns 404; a non-integer lines returns 400.
Every request outside /status, /capabilities and /admin/** is resolved by its first path segment and forwarded to that instance’s management port. GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS share one implementation.
-
The path after the first segment and the query string are preserved verbatim:
/sales/logfile?lines=50is forwarded tohttp://127.0.0.1:42002/logfile?lines=50. -
Request headers are forwarded as-is except hop-by-hop headers (
Connection,Keep-Alive,Upgrade,Transfer-Encoding, …) andHost,Content-Length,Expect; request and response bodies are streamed, so large uploads and downloads work. -
Redirects are not followed: a 302 from the instance is returned to the caller unchanged.
-
The overall timeout is 15 seconds. Requests whose path contains
/download,/upload,/logfile,/viewlogor/backuphave no overall timeout, only the 5-second connect timeout. -
The instance’s status code, headers and body are passed through unchanged; HEAD, 204 and 304 have no body.
On failure the proxy returns a JSON envelope:
| Status | Situation | Body |
|---|---|---|
404 |
Unknown alias |
|
503 |
The instance exists but cannot be forwarded to (e.g. |
|
504 |
The instance management port timed out |
|
502 |
Connection failure or interrupted request |
|
curl http://127.0.0.1:18080/sales/status
curl "http://127.0.0.1:18080/sales/logfile?lines=50"
curl -X POST http://127.0.0.1:18080/sales/api/registerService \
-H "Content-Type: application/json" -d '{"serviceName":"demo"}'The endpoints of the instance management port itself (/status, /health, /logfile, /backup, /api/…, /mcp, …) are described in "HTTP Management Services" and related sections; the proxy only adds the alias prefix and forwards.
Only the single management WebSocket endpoint of dbserver is proxied today, at the fixed path /<alias>/aichat (a query string may follow).
const ws = new WebSocket('ws://127.0.0.1:18080/sales/aichat');-
If the alias does not exist, the instance is not running, or its management port is disabled, the socket is closed immediately after the handshake with code
1011and a reason. -
Text and binary frames are forwarded in both directions; fragmented messages are aggregated before forwarding.
-
Messages that arrive before the upstream connection is ready are queued and flushed in order once it connects.
-
Close codes are normalized: reserved codes such as
1005,1006and1015are never sent to the peer as-is (they become1000).
Other WebSocket endpoints (for example /sql/ws of the SQL REPL) are not proxied yet; connect to the instance management port directly.
-
GET /: returns a 404 JSON body suggesting/<database>/<path>or/admin/**. -
An unmatched route returns the JSON envelope
{"retCode":404,"retMsg":"Nothing is served at […]."}; a body already written by the forwarding layer is preserved. -
An uncaught exception returns
500with the plain textInternal Server Error.
BASE=http://127.0.0.1:18080
curl $BASE/status
curl $BASE/capabilities
curl "$BASE/admin/databases?probe=false"
curl $BASE/admin/databases/sales
curl -X POST $BASE/admin/databases \
-H "Content-Type: application/json" \
-d '{"alias":"sales"}'
curl -X POST $BASE/admin/databases/sales/start
curl -X POST $BASE/admin/databases/sales/restart
curl -X POST $BASE/admin/databases/sales/shutdown
curl "$BASE/admin/databases/sales/logs?lines=100"
curl -X DELETE $BASE/admin/databases/sales
curl "$BASE/sales/logfile?lines=20"SlackerDB provides full PostgreSQL wire protocol compatibility, allowing you to connect using standard JDBC drivers. This enables you to use any PostgreSQL‑compatible JDBC client.
PostgreSQL JDBC Driver
You can use the standard PostgreSQL JDBC driver (org.postgresql.Driver) with the connection URL format jdbc:postgresql://host:port/database. This is useful when you want to reuse existing PostgreSQL tooling.
SlackerDB JDBC Driver
For better integration and additional features, use the native SlackerDB JDBC driver (org.slackerdb.jdbc.Driver). The connection URL format is jdbc:slackerdb://host:port/database. This driver is included in the distribution.
The slackerdb-dbdriver driver stays on Java 17 bytecode, so JDK 17 applications can load it directly; the server, proxy and dbcli artifacts require Java 21.
Connection Examples
// PostgreSQL JDBC driver String url = "jdbc:postgresql://127.0.0.1:3175/db1"; Connection conn = DriverManager.getConnection(url, "main", ""); conn.setAutoCommit(false); // SlackerDB JDBC driver String url = "jdbc:slackerdb://127.0.0.1:3175/db1"; Connection conn = DriverManager.getConnection(url, "main", ""); conn.setAutoCommit(false);
Tool Integration
You can connect to SlackerDB from the DBeaver IDE database tool.
You can connect to SlackerDB from the PostgreSQL psql command line.
We cannot exhaustively verify other tools.
Use PostgreSQL driver
Download postgresql server and connect database like a pg.
Use custom driver
Since native Postgres clients often use some data dictionary information
that duckdb doesn’t have,
You can create a generic JDBC driver with the following settings:
Dbeaver:
Database -> Driver Manager -> New
Database type: generic database.
Class name: org.slackerdb.jdbc.Driver
URL template: jdbc:slackerdb://{host}:{port}/[{database}]
ODBC and Python SlackerDB also supports ODBC and Python connections via the same PostgreSQL wire protocol. Refer to the respective client documentation for setup details.
SlackerDB supports Unix Domain Socket (UDS) connections for local inter-process communication. UDS provides lower latency and higher throughput compared to TCP loopback connections, making it ideal for local client-server communication on the same machine.
|
Note
|
UDS is only supported on Linux and macOS. On Windows, the socket parameter is ignored and a log message is printed.
|
You can enable UDS by setting the socket parameter in the server configuration file:
# dbserver/conf/dbserver.conf socket=/tmp/.s.slackerdb.4309
Alternatively, use the --socket command-line parameter:
java -jar dbserver/target/slackerdb-dbserver-0.2.2-standalone.jar start --socket /tmp/.s.slackerdb.4309
When socket is configured, the server listens on both the TCP port and the UDS socket simultaneously. Clients can connect via either method.
To connect to SlackerDB via UDS using the SlackerDB JDBC driver, use the jdbc:slackerdb:// protocol with the socketFactory and socketFactoryArg connection parameters:
// SlackerDB JDBC driver with UDS
String url = "jdbc:slackerdb:///mem";
Properties props = new Properties();
props.setProperty("user", "");
props.setProperty("password", "");
props.setProperty("socketFactory",
"org.slackerdb.jdbc.UnixDomainSocketFactory");
props.setProperty("socketFactoryArg", "/tmp/.s.slackerdb.4309");
Connection conn = DriverManager.getConnection(url, props);
conn.setAutoCommit(false);
The UnixDomainSocketFactory class is included in the SlackerDB JDBC driver and uses Java’s built-in UnixDomainSocketAddress API to establish UDS connections.
Key points:
* The socketFactory parameter must be set to org.slackerdb.jdbc.UnixDomainSocketFactory
* The socketFactoryArg parameter specifies the UDS socket file path
* The jdbc:slackerdb:// protocol is used (not jdbc:postgresql://)
* The host portion of the URL is ignored when using UDS; use ///database format
The examples below use the SlackerDB JDBC driver bundled with the distribution
(org.slackerdb.jdbc.Driver). With the standard PostgreSQL JDBC driver, change the URL to
jdbc:postgresql://… and replace the org.slackerdb.jdbc. CopyManager / BaseConnection
packages with org.postgresql..
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) throws Exception {
Class.forName("org.slackerdb.jdbc.Driver");
String url = "jdbc:slackerdb://127.0.0.1:3175/db1";
try (Connection conn = DriverManager.getConnection(url, "main", "");
Statement stmt = conn.createStatement()) {
stmt.execute("CREATE TABLE IF NOT EXISTS demo(id INTEGER, name VARCHAR)");
stmt.executeUpdate("INSERT INTO demo VALUES (1, 'Alice'), (2, 'Bob')");
try (ResultSet rs = stmt.executeQuery(
"SELECT id, name FROM demo ORDER BY id")) {
while (rs.next()) {
System.out.println(rs.getInt("id") + "\t" + rs.getString("name"));
}
}
}
}
}import java.io.StringReader;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import org.slackerdb.jdbc.copy.CopyManager;
import org.slackerdb.jdbc.core.BaseConnection;
public class CopyDemo {
public static void main(String[] args) throws Exception {
Class.forName("org.slackerdb.jdbc.Driver");
String url = "jdbc:slackerdb://127.0.0.1:3175/db1";
try (Connection conn = DriverManager.getConnection(url, "main", "")) {
CopyManager copy = new CopyManager((BaseConnection) conn);
long imported = copy.copyIn(
"COPY demo (id, name) FROM STDIN WITH (FORMAT csv)",
new StringReader("3,Carol\n4,Dave\n"));
StringWriter out = new StringWriter();
long exported = copy.copyOut(
"COPY demo TO STDOUT WITH (FORMAT csv)", out);
System.out.println("imported=" + imported + ", exported=" + exported);
System.out.println(out);
}
}
}-
Where objective conditions allow, use COPY for import and export whenever possible; it is much faster than plain SELECT and INSERT.
-
The following HTTP endpoints provide basic management functions such as backup, file upload/download, log viewing, and status monitoring. They are available when the management port (
port_x) is enabled. These endpoints belong to the dbserver management port; when going through the proxy, prefix the path with/<alias>(for exampleGET /sales/status); see Proxy HTTP API for the forwarding rules.
Performs a synchronous database backup. The backup file is saved in the backup/ directory as {backupTag}.db.
{
"backupTag": "mybackup"
}{
"retCode": 0,
"retMsg": "Successful."
}Asynchronous backup tasks, for callers that need progress and a downloadable result.
-
POST /backupswith{"backupTag":"mybackup"}returns202and{"id":"…","status":"RUNNING"}. -
GET /backupslists known tasks. -
GET /backups/{id}returns the task status (RUNNING,COMPLETED,FAILED). -
GET /backups/{id}/downloaddownloads a completed backup file.
Returns the configured server log as plain text.
-
lines(optional) – return only the last N lines (max 10000). Without it the whole file is returned.
GET /logfile?lines=500
Downloads a file from the server’s directory.
-
filename(required) – path to the file.
GET /download?filename=logs/slackerdb.log
The endpoint supports Range requests for partial downloads.
Uploads a file to the server’s uploads/ directory.
-
filename(required) – target file path.
-
file(required) – the file to upload.
curl -X POST -F "file=@local.txt" "http://localhost:8080/upload?filename=uploads/remote.txt""uploaded: uploads/remote.txt"Retrieves the last N lines of a log file.
-
filename(required) – path to the log file. -
lines(optional) – number of lines to return (default 100, max 10000).
GET /viewLog?filename=logs/slackerdb.log&lines=50
[
"2025-12-04 10:00:00 INFO Server started",
"2025-12-04 10:00:01 INFO Listening on port 8080"
]Returns comprehensive server status information, including server details, database metrics, configuration parameters, usage statistics, installed extensions, and active sessions.
GET /status
{
"server": {
"status": "RUNNING",
"version": "0.2.2",
"build": "2025-12-04 10:00:00.000 UTC",
"pid": 12345,
"now": "2025-12-04 15:20:00",
"bootTime": "2025-12-04 10:00:00",
"runTime": "5 hours, 20 minutes, 0 seconds"
},
"database": {
"version": "v1.0.0",
"size": "1.2 GB",
"memoryUsage": "256 MB",
"walSize": "0 B"
},
"parameters": {},
"usage": {},
"extensions": [],
"sessions": []
}SlackerDB ships a PL/SQL engine for anonymous blocks: declare variables, branch, loop, iterate cursors, fetch into variables and handle exceptions — all on top of DuckDB.
Wrap the block in DO ... (PostgreSQL style) and send it like any other statement:
DO $$
DECLARE
CURSOR cur IS SELECT id, name FROM users WHERE active = true;
v_id BIGINT;
v_name TEXT;
total INTEGER := 0;
BEGIN
OPEN cur;
LOOP
FETCH cur INTO v_id, v_name;
EXIT WHEN cur%NOTFOUND;
IF v_name IS NULL THEN
CONTINUE;
ELSIF length(v_name) > 20 THEN
UPDATE users SET name = substr(:v_name, 1, 20) WHERE id = :v_id;
ELSE
INSERT INTO audit(user_id, note) VALUES (:v_id, 'ok: ' || :v_name);
END IF;
total := total + 1;
EXIT WHEN total >= 1000;
END LOOP;
CLOSE cur;
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO audit(user_id, note) VALUES (NULL, 'no rows');
WHEN OTHERS THEN
ROLLBACK;
RAISE;
END;
$$;Supported wrappers: DO ... , DO $tag$ … $tag$, bare ... , and unwrapped
DECLARE … BEGIN … END; scripts (the latter needs a client that does not split statements —
see Client notes below). One query string may contain several statements; they run in order.
The four blocks below are self-contained: each one creates its own tables, so you can paste any
of them into a client and run it as is. Two conventions to keep in mind: in the structural part
(IF, WHILE, FETCH INTO, assignments) variables can be written bare; while variables inside
embedded SQL must be written as :name (bind parameters).
Variables, IF/ELSIF branching and a WHILE loop:
DO $$
DECLARE
i INTEGER := 1;
total INTEGER := 0;
BEGIN
CREATE OR REPLACE TABLE demo_numbers(n INTEGER, kind TEXT);
WHILE i <= 6 LOOP
IF i % 2 = 0 THEN
INSERT INTO demo_numbers VALUES (:i, 'even');
ELSIF i % 3 = 0 THEN
INSERT INTO demo_numbers VALUES (:i, 'multiple of 3');
ELSE
INSERT INTO demo_numbers VALUES (:i, 'other');
END IF;
total := total + i;
i := i + 1;
END LOOP;
INSERT INTO demo_numbers VALUES (:total, 'sum');
END;
$$;Result: demo_numbers holds six classified rows (other / even / multiple of 3) plus the
summary row (21, 'sum').
Walking a cursor with %NOTFOUND, plus an exception handler:
DO $$
DECLARE
CURSOR cur IS SELECT id, name FROM demo_emp ORDER BY id;
v_id INTEGER;
v_name TEXT;
v_total INTEGER := 0;
BEGIN
CREATE OR REPLACE TABLE demo_emp(id INTEGER, name TEXT);
INSERT INTO demo_emp VALUES (1, 'alice'), (2, 'bob'), (3, 'carol');
CREATE OR REPLACE TABLE demo_audit(id INTEGER, note TEXT);
OPEN cur;
LOOP
FETCH cur INTO v_id, v_name;
EXIT WHEN cur%NOTFOUND;
IF v_name IS NULL THEN
CONTINUE;
END IF;
INSERT INTO demo_audit VALUES (:v_id, 'ok: ' || :v_name);
v_total := v_total + 1;
END LOOP;
CLOSE cur;
INSERT INTO demo_audit VALUES (0, 'count = ' || CAST(:v_total AS TEXT));
EXCEPTION
WHEN OTHERS THEN
INSERT INTO demo_audit VALUES (-1, 'failed');
END;
$$;Result: demo_audit receives three ok: <name> rows for ids 1/2/3, plus (0, 'count = 3').
SELECT … INTO with an exception handler that branches on the error code:
DO $$
DECLARE
v_name TEXT;
v_cnt INTEGER;
BEGIN
CREATE OR REPLACE TABLE demo_dept(id INTEGER, name TEXT);
INSERT INTO demo_dept VALUES (1, 'sales'), (2, 'hr');
SELECT count(*) INTO v_cnt FROM demo_dept;
BEGIN
SELECT name INTO v_name FROM demo_dept WHERE id = 99;
EXCEPTION
WHEN NO_DATA_FOUND THEN
v_name := '(not found)';
WHEN TOO_MANY_ROWS THEN
v_name := '(too many rows)';
END;
CREATE OR REPLACE TABLE demo_result(cnt INTEGER, name TEXT);
INSERT INTO demo_result VALUES (:v_cnt, :v_name);
END;
$$;Result: demo_result holds (2, '(not found)') — when the query matches no row, SELECT INTO
raises NO_DATA_FOUND, which the inner block catches.
Dynamic SQL: EXECUTE IMMEDIATE with USING and INTO:
DO $$
DECLARE
v_table TEXT := 'demo_dyn';
v_id INTEGER := 7;
v_cnt INTEGER;
BEGIN
EXECUTE IMMEDIATE 'CREATE OR REPLACE TABLE ' || v_table || '(id INTEGER)';
EXECUTE IMMEDIATE 'INSERT INTO ' || v_table || ' VALUES (?)' USING v_id;
EXECUTE IMMEDIATE 'SELECT count(*) FROM ' || v_table INTO v_cnt;
EXECUTE IMMEDIATE 'INSERT INTO ' || v_table || ' VALUES (?)' USING v_cnt * 10;
END;
$$;Result: demo_dyn holds the two rows 7 and 10; USING values bind to the placeholders in the
order they appear (?, :1 and :name all work, and :name also resolves from the current scope
when there is no USING clause).
| Area | Supported |
|---|---|
Declaration |
|
Assignment |
|
Conditionals |
|
Loops |
|
Cursors |
|
Queries |
|
Dynamic SQL |
|
Exceptions |
|
Expressions |
Arithmetic, |
-
Variables start as
NULL(not0). -
FOR i IN 1..5iterates 1,2,3,4,5 (both bounds inclusive);FOR i IN 5..1iterates 0 times;FOR i IN REVERSE 5..1iterates 5,4,3,2,1. -
EXITleaves only the innermost loop;EXIT labelleaves the named loop. -
SELECT … INTOwith 0 rows raisesNO_DATA_FOUND, with more than one rowTOO_MANY_ROWS— it never silently picks a row. -
:nameinside string literals is not substituted ('Hello :name'is literal text; use||). -
Expressions are evaluated with bind parameters — values are never spliced into SQL text.
-
Division by zero raises
ZERO_DIVIDE, soWHEN ZERO_DIVIDEworks. -
A block itself does not return a result set; the data service API captures the last
EXECUTE IMMEDIATEquery withoutINTO, while PG wire / SQL REPL still do not. In all other cases, write results to tables. -
Runaway loops are stopped by a statement budget (200000 statements) →
54000.
| SQLSTATE | Meaning |
|---|---|
|
Syntax or semantic error (unknown variable/cursor, duplicate declaration, unsupported type) — reported with |
|
|
|
|
|
String too long / numeric out of range / bad numeric text / bad datetime / datatype mismatch |
|
Invalid cursor state; |
|
User |
|
Canceled by |
|
Statement budget exceeded (possible infinite loop) |
A PL/SQL block must reach the server unsplit. SlackerDB’s own JDBC driver splits statements on
top-level semicolons in the extended protocol; it understands dollar quoting, so DO ... is
sent as one statement while an unwrapped DECLARE … END; block is not.
| Block form | Extended protocol (default) |
|---|---|
Simple query protocol ( |
|
OK |
OK |
bare |
OK |
OK |
unwrapped |
split by the driver — use |
OK |
Variables are typed at declaration. Every assignment converts the value to the declared type with these rules:
| Source → target | Result |
|---|---|
NULL → any |
OK (stays NULL) |
between numeric types |
OK; widening is lossless, narrowing rounds half-up, overflow raises |
string → numeric/date/time/timestamp |
OK when the text parses as that literal, otherwise |
numeric/date/time/timestamp → string |
OK (standard text form) |
string → |
|
anything involving |
|
anything else |
|
Identifiers are case-insensitive and folded to lower case unless quoted ("Mixed" keeps its case).
An uninitialised variable is NULL; NOT NULL declarations reject NULL assignment (22004).
| Form | Iterations |
|---|---|
|
1 (i = 1) |
|
5 — both bounds inclusive |
|
0 |
|
5 → 5,4,3,2,1 |
|
0 |
|
3 → -3,-2,-1 |
|
one iteration per list element (compatibility form) |
|
0 (NULL counts as false) |
|
stopped by the statement budget → |
The loop variable is implicit, read-only, and invisible outside the loop. EXIT / CONTINUE
affect only the innermost loop; EXIT name leaves the loop that carries that label:
<<outer_loop>>
LOOP
...
EXIT outer_loop WHEN done = 1;
END LOOP outer_loop;-
Precedence, high to low:
*→ unary-/NOT→/ %→+ -→||→ comparisons (= <> < ⇐ > >=,IS [NOT] NULL,LIKE,IN,BETWEEN) →AND→OR. -
NULLin a condition counts as false;AND/ORshort-circuit, sofalse AND (1/0 = 1)is fine. -
||is string concatenation (SQL semantics) — writeORfor logical or. -
Every variable value is passed as a bind parameter; values are never spliced into SQL text.
-
Function calls are delegated to DuckDB, so any DuckDB scalar function works (qualified names such as
schema.funcare accepted).
Compatibility aliases kept from earlier versions:
| Alias | Equivalent |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
list iteration |
|
case-insensitive cursor attributes |
| State \ operation | OPEN | FETCH | CLOSE | %ISOPEN |
%FOUND |
%NOTFOUND |
%ROWCOUNT |
|---|---|---|---|---|---|---|---|
Closed (declared, not opened) |
OK |
|
|
false |
|
|
|
Open, rows available |
|
OK, count+1 |
OK |
true |
true |
false |
n |
Open, no rows |
|
OK → EOF, notFound=true |
OK |
true |
false |
true |
0 |
Open, after EOF |
|
OK (stays EOF, variables keep their values) |
OK |
true |
false |
true |
n |
Closed after fetching |
OK |
|
|
false |
|
|
|
A cursor opened in a block is closed automatically when that block ends (including on the exception
path); CLOSE followed by OPEN is allowed and resets %ROWCOUNT.
-
Wrappers:
DO …,DO $tag$ … $tag$, bare…, or an unwrappedDECLARE … END;script. -
Dollar quoting follows PostgreSQL: there are no escapes inside, the matching tag ends the string — use another tag (
$body$ … $body$) when the body itself must contain$$. -
In the simple query protocol one query string may contain several statements separated by semicolons; they run in order and each returns its own
CommandComplete(and result set). -
A PL/SQL block itself returns no rows:
CommandCompletereportsDO. UseDESCRIBE-visible statements (ordinary queries) or write into tables for output. -
In the extended protocol a PL/SQL portal is described as
NoDataand bound without parameters.
Stored procedures, functions, triggers, packages, records/%ROWTYPE, collections, cursor FOR
loops and GOTO are not supported. Unsupported constructs fail with an explicit error instead
of being silently ignored.
-
%FOUND/%NOTFOUNDapplied to a name that is not a cursor is not rejected at compile time. -
Division by zero is detected when the divisor can be resolved locally (literal, variable, cursor attribute); a divisor computed by a query keeps the backend behaviour (
Infinity). -
TIMESTAMP WITH TIME ZONEkeeps the backend representation; values are not normalised to UTC. -
A block that fails does not roll back by itself — issue
ROLLBACKin anEXCEPTIONhandler or from the client, exactly as with PostgreSQLDO.
-
Data service API: uses the main pool.
-
MCP: uses the main pool and shares its connection limit with the data service API.
-
PostgreSQL-protocol clients (dbcli/psql/JDBC): use the main pool.
-
Management definitions and portal access records: use the main pool.
-
SQL REPL: does not use the pool. Each session duplicates
backendSysConnectionand closes it at session end, so it does not consume the pool’smax_connections. At mostrepl_max_connectionssessions may exist; excess sessions are rejected immediately withToo much connections.
-
Data service work with port_x, please make sure you have enabled it in server configuration or from command parameter. It’s important to note that we have no consider on data security. This means data services must work in a trusted environment.
User login (note: this is optional). After success, a token will be
provided.
Context operations or SQL access that requires context variables will
require token.
If your program does not involve context feature, you can ignore this
login.
Put it simplify, the token is currently used as the user ID.
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
Response example:
Success response (200)
{
"retCode": 0,
"token": “yJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9”,
"retMsg": "Login successful."
}
User logout
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
headers:
| Attribute | Value |
|---|---|
Authorization |
NzJjYjE3NmQtN2Y2ZC00OWMyLWIwODAtYTU1MDE3YzVmZDU1 |
The token information here is obtained when call /login in earlier
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Successful."
}
set context
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
headers:
| Attribute | Value |
|---|---|
Authorization |
NzJjYjE3NmQtN2Y2ZC00OWMyLWIwODAtYTU1MDE3YzVmZDU1 |
The token information here is obtained when call /login in earlier
request body:
| Attribute | Value |
|---|---|
key1 |
value1 |
key2 |
value2 |
… |
… |
keyx |
valuex |
You can set one or more key-value pairs at once, or you can set multiple key-value pairs by calling setContext multiple times.
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Successful."
}
remove context
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
headers:
| Attribute | Value |
|---|---|
Authorization |
NzJjYjE3NmQtN2Y2ZC00OWMyLWIwODAtYTU1MDE3YzVmZDU1 |
The token information here is obtained when call /login in earlier
request body:
| Attribute | Value |
|---|---|
removedKeyList |
[key1,key2, ….] |
You can remove one or more key-value pairs at once, or you can remove multiple key-value pairs by calling removeContext multiple times.
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Successful."
}
register a service
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
request body:
| Attribute | Value |
|---|---|
serviceName |
service name |
serviceVersion |
service version |
serviceType |
service type, GET/POST |
category |
Optional. Grouping label; when services are saved into a directory it becomes the file name
( |
searchPath |
sql default search path, Optional parameter |
sql |
SQL statement, can contain such ${var1} variable information |
filter |
Optional result-set filter expression. Configured at registration time and applied
automatically on every call; syntax is close to SQL |
description |
description |
snapshotLimit |
how long the query result will be cached (optional), for example |
maxExecutionTime |
maximum execution time for this service’s queries (optional, milliseconds).
Unset = inherit the server |
parameter |
parameter default value when query api not provide parameter value |
snapshotLimit format: 3 hours / 30 minutes / 45 seconds maxExecutionTime format: integer milliseconds (for example 30000 = 30 seconds)
Request example:
{
"serviceName": "queryTest1",
"serviceVersion": "1.0",
"serviceType": "GET",
"sql": "SELECT 1"
}
Request example (PL/SQL; the last SELECT provides the result):
{
"serviceName": "queryTest3",
"serviceVersion": "1.0",
"serviceType": "GET",
"sql": "DO $$ BEGIN NULL; END; $$; SELECT 1 AS ok;"
}
A standalone PL/SQL block returns no data; only a trailing SELECT produces a result set.
Request example (with a service-level filter):
{
"serviceName": "paidOrders",
"serviceVersion": "1.0",
"serviceType": "GET",
"sql": "SELECT * FROM orders",
"filter": "status IN ('paid','shipped') ORDER BY created_at DESC LIMIT 100"
}
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Successful."
}
Registering a service name + version that is already registered is rejected with
retCode = -1 and retMsg = "Rejected. [<name>#<version>] is already registered.".
There is no "update" semantic: unregister first (/api/unRegisterService) and register again.
unregister a service
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
request body:
| Attribute | Value |
|---|---|
serviceName |
service name |
serviceVersion |
service version |
serviceType |
service type, GET/POST |
Request example:
{
"serviceName": "queryTest1",
"serviceVersion": "1.0",
"serviceType": "GET"
}
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Successful."
}
list all service
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
GET |
Path |
|
Response example:
Success response (200)
[
{
"serviceName" : "Query1",
"serviceVersion" : "1.0",
"serviceType" : "GET",
"category" : "test",
"searchPath" : "main",
"sql" : "SELECT 1",
"description" : "NO DESCRIPTION.",
"snapshotLimit" : "0 seconds",
"parameter" : {}
}
]
The response is a bare JSON array of service definitions (no retCode wrapper):
each item contains serviceName, serviceVersion, serviceType, category,
searchPath, sql, description, snapshotLimit and parameter (plus filter when
the service defines one).
Related management endpoints (all POST, empty body):
-
/api/dumpRegisteredService- same array, returned as a JSON attachment; -
/api/downloadRegisteredService- same payload (for download clients); -
/api/saveRegisterService- writes the current definitions back todata_service_schema(a single file, or one<category>.servicefile per category when it is a directory); -
/api/loadRegisterService- loads definitions from the request body (a single object or an array).
API query
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST or GET |
Path |
|
headers:
| Attribute | Value |
|---|---|
Authorization |
NzJjYjE3NmQtN2Y2ZC00OWMyLWIwODAtYTU1MDE3YzVmZDU1 |
snapshotLimit |
Optional. used to overwrite service definition. 0 means no result cache |
maxExecutionTime |
Optional. overrides the service definition and the server GLOBAL setting, in milliseconds; 0 means no limit for this query |
The token information here is obtained when call /login.
The token is optional, if you use context in your sql statement, you
must set it.
snapshotLimit format: 3 hours / 30 minutes / 45 seconds
maxExecutionTime precedence: request header > service definition > server max_execution_time.
On timeout the response keeps the normal failure shape (retCode = -1 with
retMsg = "INTERRUPT Error: Query exceeded maximum execution time").
GET Request example:
GET /api/1.0/queryApi?context1=xxx&context2=yyy
POST Request example:
POST /api/1.0/queryApi
{
"context1": "xxx",
"context2": "yyy",
}
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Successful.",
"description": "test 1",
"cached": false,
"timestamp": 17777700,
"data":
{
"columnNames":["col1","col2","col3"],
"columnTypes":["INTEGER","INTEGER","VARCHAR"],
"dataset":[[1,2,"中国"]]
}
}
Requesting a service that is not registered answers HTTP 404 with
{"retCode": 404, "retMsg": "GET /api/1.0/xxx is not registered."}.
${var} placeholders are always validated: when a placeholder has no value
(no request parameter, no default in parameters, no token/context variable),
the request is rejected with retCode = -1 and
retMsg = "Missing required parameters: <names>" - the SQL is never executed with a
literal ${var} left inside it.
When a cached entry expires, concurrent requests do not all hit the database: for the
same content (same service and parameters) exactly one request refreshes the result
while the others wait for that refresh and then return the refreshed result (cached
stays true). So an expiring snapshotLimit never turns into a burst of backend
queries. A waiter that has waited longer than 30 seconds falls back to querying directly
so a request is never blocked indefinitely.
filter is part of the service definition: set it in /api/registerService (or in a
.service file) and every call to /api/{apiVersion}/{apiName} applies it automatically.
Callers do not send a filter parameter.
It is evaluated in memory on the server after the SQL has run and before the response is written: it never rewrites the SQL and never causes another database query. Supported clauses are similar to SQL:
-
comparisons:
=,!=(<>),>,>=,<,⇐ -
sets:
IN,NOT IN -
patterns:
LIKE,NOT LIKE(%any length,_one character, optionalESCAPE) -
logic:
AND,OR,NOT, parentheses -
NULL:
IS NULL,IS NOT NULL(SQL three-valued logic; comparing with NULL yields UNKNOWN) -
functions:
lower(s),upper(s),trim(s),length(s|list), nestable;trimremoves leading/trailing ASCII spaces only, andlengthcounts Unicode code points for strings and elements for lists -
sorting:
ORDER BY col [ASC|DESC] [NULLS FIRST|LAST], …(defaults toASCandNULLS LAST; as in DuckDB,NULLS LASTdoes not flip with direction) -
paging:
LIMIT n,LIMIT ALL,OFFSET n(filter/sort first, thenOFFSET, thenLIMIT)
Strings use single quotes and an embedded quote is doubled ('it''s').
Registration example:
POST /api/registerService
{
"serviceName": "paidOrders",
"serviceVersion": "1.0",
"serviceType": "GET",
"sql": "SELECT * FROM orders",
"filter": "status IN ('paid','shipped') AND length(name) > 2 ORDER BY created_at DESC LIMIT 100"
}
After that, GET /api/1.0/paidOrders returns the filtered result with no extra parameters.
Registration validation: invalid expressions are rejected when registering
(retCode = -1, retMsg starts with Rejected. Invalid filter: `); definitions loaded from
a `.service file are skipped with a warning. Errors that depend on result columns
(unknown/ambiguous columns, type mismatches) are returned at request time with
retCode = -1 and a retMsg starting with `Invalid filter: ` (HTTP status stays 200).
Cache: the cache holds the unfiltered result; the filter is applied per response.
Services that share the same SQL and searchPath but differ only in filter therefore
share one cached snapshot and cause only one database query (while snapshotLimit is
valid); cached keeps its meaning. Re-registering with a different filter does not
invalidate the raw cache. The cache key contains searchPath plus the parameter-substituted
SQL, not the service name/version or the filter.
Non-result statements: UPDATE/INSERT/DELETE/DDL statements have no result set, so a
configured filter is ignored at runtime.
Limits: only whitelisted functions; no BETWEEN, ILIKE, arithmetic or subqueries;
filter columns must be present in the result set; a column whose name is a keyword must be
quoted (for example "limit"); paging order is unstable without ORDER BY; filtering
happens after materialisation and does not reduce database work.
Both the HTTP data service and the SQL REPL return the same JSON representations, so a client never needs driver-specific knowledge:
| Value type | JSON representation |
|---|---|
INTEGER/BIGINT/HUGEINT/DECIMAL/DOUBLE |
number |
VARCHAR/UUID/INTERVAL |
string |
BOOLEAN |
true/false |
DATE/TIME |
ISO-8601 string ( |
TIMESTAMP |
ISO-8601 string without zone ( |
TIMESTAMP WITH TIME ZONE |
ISO-8601 string with offset ( |
BLOB |
Base64 string |
LIST/ARRAY |
JSON array |
STRUCT |
JSON object keyed by field name |
MAP |
JSON object |
JSON |
the JSON value itself (not a string-escaped copy, not driver internals) |
NULL |
null |
A result set is materialised into a single response: the data service API has no cursor/streaming variant, so very large results are bounded by memory.
SlackerDB runs a Model Context Protocol (MCP) server on the management port, so AI assistants and other MCP clients can inspect and query the database.
The implementation targets the 2026-07-28 revision of the specification and also accepts earlier
revisions (dual-era support), because installed clients lag the spec.
| Item | Behaviour |
|---|---|
Transport |
Streamable HTTP: every message is a |
Sessions |
None at the protocol level. The |
|
Implemented, as the specification requires. Advertises supported protocol versions,
capabilities, server identity and usage instructions. Sent as a normal |
GET requests |
Answer |
Result envelope |
Every result carries |
Caching |
|
|
Deterministic (sorted by name) so client-side caches and LLM prompt caches stay effective. |
Removed methods |
|
| Tool | Description |
|---|---|
|
Opens a stateful SQL session and returns a server-minted handle. Pass that handle to
|
|
Closes a session and releases its connection immediately. |
|
Executes SQL (all rows by default) and can cap the result with |
|
Lists tables and views as a |
|
Column definitions (name, type, nullable, default) for one table or view, as a |
|
A small sample of real values from a table. |
|
The registered data services (see Data Service), so an agent prefers curated, cached,
versioned services over ad-hoc SQL. Each entry carries the endpoint and its parameters; service SQL text is
deliberately not exposed. The same list is also available as the resource |
Because protocol-level sessions no longer exist, cross-call state is expressed the way the specification prescribes: as an explicit handle passed as an ordinary tool argument (the specification’s own guidance names "a database transaction" as the motivating case).
-
Permissions follow the server. MCP is an internal tool and no longer adds a read-only restriction;
run_sqlcan execute read and write statements, and the final permissions come from the server’saccess_mode.open_session(read_only)is kept only for compatibility with older clients and no longer has any effect. -
Returned rows.
run_sqlreturns all rows by default;max_rowscan cap the result, and0or a negative value means unlimited.truncatedistrueonly when a positive cap was set and rows were actually cut off. -
Statement timeout. Queries follow the server’s
max_execution_time(GLOBAL) by default;run_sqlaccepts an optionalmaxExecutionTime(milliseconds,0= no limit) that overrides it for this call only and restores the session value afterwards. -
Same execution path as everything else. Tool calls take connections from the ordinary dbserver pool, so the connection cap and session handling apply to agents exactly as they do to other clients.
| URI / name | Content |
|---|---|
|
Every table and view with schema and type. |
|
Column definitions for one table (resource template). |
|
The registered data services (see Data Service), so an agent prefers curated, cached, versioned services over ad-hoc SQL. Service SQL text is deliberately not exposed. |
|
A service-first answering policy that can be handed to the model. |
Definitions can be loaded at startup from mcp_config (a single JSON file, or a directory of .mcp /
.service files):
mcp_config=conf/mcp_config_example.serviceA tool entry may bind to a built-in implementation instead of being an echo stub:
{
"name": "query",
"description": "Execute SQL",
"handler": "builtin:run_sql"
}Recognised builtin: handlers are run_sql, list_tables, describe_table, sample_rows,
list_services, open_session and close_session; the legacy aliases query, sql, runquery,
tables, show_tables, describe and sample are mapped onto them.
conf/mcp_config_example.service in the distribution is a working sample of that shape: an echo stub, two
bindings to built-in tools under custom names (top_tables → list_tables, peek_rows → sample_rows)
and one static resource. The built-in tools themselves are always present and never need to be declared. A
handler entry needs no inputSchema of its own: the built-in’s real schema (including outputSchema) is
used instead, so a declaration cannot drift from the implementation.
Two rules apply to those names. A name a built-in tool already uses is reserved: such a declaration is
skipped while loading, /mcp/registerMCPTool and the single-object form of /mcp/loadMCPTool reject it with
retCode = -1, and the array form of /mcp/loadMCPTool skips that entry (tools/list would otherwise
advertise two tools with the same name, and calls would always reach the built-in). And the binding survives a
round trip: saveMCPTool / dumpMCPTool write
"handler": "builtin:<name>" back into the file, so saving and restarting keeps a tool bound to its real
implementation instead of degrading it to an echo stub.
The optional mcp_llm_server / mcp_llm_key settings enable the private /aichat WebSocket endpoint,
which routes natural-language questions to registered data services (<service>:<ip>:<port>:<model>;
ollama and openai are supported). It is independent of the MCP protocol surface.
The endpoint lives on the management port, so the management interface must be enabled (port_x /
--portx; the default -1 disables it) and the port has to be explicit — leaving it empty assigns a random
port that a client configuration cannot address.
1. Start the server with MCP enabled.
java -jar slackerdb-dbserver-0.2.2-standalone.jar --conf conf/dbserver.conf \
--port 15432 --portx 18080 start--mcp-config is deliberately left out here: it is optional, the built-in tools exist without it, and it only
declares your own extra tools and resources (see the mcp_config setting above).
2. Point the client at http://<host>:18080/mcp using the Streamable HTTP transport. For the DeepSeek
Harness, add one row to the profile patch ($DSH_HOME/profiles/<profile>/cordis.patch.yml):
- insert:
- id: mcp-slacker
name: '@deepseek-ai/dsh-mcp-client'
config:
serverName: slacker
transport: streamable-http
url: 'http://127.0.0.1:18080/mcp'Use a unique serverName per server; the namespace is local configuration and never taken from the
server’s advertised name.
3. Verify by asking a question in the client. Server tools reach the model as
mcp__<serverName>__<tool>, and naming the tool is the most reliable form:
Run SELECT 42 AS answer with mcp__slacker__run_sql and tell me the result.The model calls mcp__slacker__run_sql and gets back rows = [[42]]. Naming no tool also works
("query SELECT 42 AS answer with SlackerDB’s MCP tools"), but naming it makes the hit certain.
The endpoints in this section register and manage MCP tool definitions at runtime. They are administration operations used by scripts and administrative clients, and are not part of the MCP protocol surface described under MCP Server.
Register an MCP tool.
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
request body:
| Attribute | Value |
|---|---|
name |
tool name (required). A name a built-in tool already uses is rejected. |
description |
tool description (required) |
inputSchema |
JSON Schema of the arguments (required here; a definition loaded from |
category |
tool category (optional); used as the file name when definitions are saved into a directory |
A tool registered here is an echo stub: it carries no handler, so calling it returns its arguments. Tools
bound to real implementations come from mcp_config.
Request example:
{
"name": "queryDatabase",
"description": "Echo the request back, for connectivity checks",
"category": "database",
"inputSchema": {
"type": "object",
"properties": {"sql": {"type": "string"}},
"required": ["sql"]
}
}
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Tool registered successfully"
}
Unregister an MCP tool.
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
request body:
| Attribute | Value |
|---|---|
name |
tool name (required) |
Request example:
{
"name": "queryDatabase"
}
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Tool unregistered successfully"
}
Load MCP tool definitions from JSON.
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
request body: JSON array of tool definitions or a single tool definition object. A definition whose name a
built-in tool already uses is skipped in the array form, and rejected with retCode = -1 in the single-object
form.
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Tools loaded successfully"
}
Save MCP tool definitions to configuration file.
Tools bound to a built-in implementation are written back with their "handler": "builtin:<name>", so loading
the saved file restores the binding instead of turning the tool into an echo stub.
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Tools saved successfully",
"savedPath": "/path/to/config/file"
}
MCP (Model Context Protocol) Resource provides a way to register, manage, and access resources through the MCP protocol. These resources can be used by AI assistants and other clients that support MCP to access data, files, or other resources.
Register an MCP resource.
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
request body:
| Attribute | Value |
|---|---|
name |
resource name (required) |
type |
resource type (required, e.g., "file", "database", "api") |
description |
resource description (required) |
uri |
resource URI or path (required) |
metadata |
additional metadata (optional object) |
access_method |
access method (optional, e.g., "read", "write", "both") |
Request example:
{
"name": "customerData",
"type": "database",
"description": "Customer database table",
"uri": "duckdb://localhost/customers",
"metadata": {
"schema": "public",
"table": "customers"
},
"access_method": "read"
}
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Resource registered successfully"
}
Unregister an MCP resource.
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
request body:
| Attribute | Value |
|---|---|
name |
resource name (required) |
Request example:
{
"name": "customerData"
}
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Resource unregistered successfully"
}
Load MCP resource definitions from JSON.
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
request body: JSON array of resource definitions or a single resource definition object.
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Resources loaded successfully"
}
Save MCP resource definitions to configuration file.
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Resources saved successfully",
"savedPath": "/path/to/config/file"
}
MCP (Model Context Protocol) Service provides a way to register, manage, and invoke services through the MCP protocol. These services can be used by AI assistants and other clients that support MCP.
Register an MCP service.
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
request body:
| Attribute | Value |
|---|---|
name |
service name (required) |
apiName |
API name (required) |
version |
service version (required) |
method |
service method, GET/POST (required) |
description |
service description (required) |
category |
service category (optional) |
capabilities |
list of capabilities (optional array) |
use_cases |
list of use cases (optional array) |
parameters |
list of parameters (optional array of objects with name, type, required, description) |
examples |
list of examples (optional array of objects with user_query, parameters) |
Request example:
{
"name": "queryCustomer",
"apiName": "queryCustomer",
"version": "1.0",
"method": "GET",
"description": "Query customer information",
"category": "database",
"capabilities": ["query", "filter"],
"use_cases": ["customer lookup", "data analysis"],
"parameters": [
{
"name": "customer_id",
"type": "integer",
"required": true,
"description": "Customer ID to query"
}
],
"examples": [
{
"user_query": "Get customer with ID 123",
"parameters": {"customer_id": 123}
}
]
}
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Service registered successfully"
}
Unregister an MCP service.
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
request body:
| Attribute | Value |
|---|---|
name |
service name (required) |
Request example:
{
"name": "queryCustomer"
}
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Service unregistered successfully"
}
Load MCP service definitions from JSON.
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
request body: JSON array of service definitions or a single service definition object.
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Services loaded successfully"
}
Save MCP service definitions to configuration file.
| Attribute | Value |
|---|---|
Protocol |
HTTP |
Method |
POST |
Path |
|
Response example:
Success response (200)
{
"retCode": 0,
"retMsg": "Services saved successfully",
"savedPath": "/path/to/config/file"
}
SQL REPL Server provides an asynchronous WebSocket interface for executing SQL queries and fetching results in pages. It is useful for long-running queries where you want to avoid blocking the client, and aligns with the MCP (Model Context Protocol) philosophy of using WebSocket for bidirectional communication.
To use it, ensure the management port (port_x) is enabled in server configuration.
Connect to the WebSocket endpoint:
| Attribute | Value |
|---|---|
Protocol |
WebSocket (ws:// or wss://) |
Path |
|
Once connected, you can send JSON messages with the following general format:
{
"id": "unique-request-id", // used to match responses, echoed back unchanged
"type": "message-type", // one of: start, exec, fetch, cancel, close
"data": { ... } // payload specific to the message type; defaults to {}
}
The server replies with the same three fields: id, type (same as the request) and data.
There is no retCode / retMsg — success or failure is reported by data.status.
When a message fails validation or refers to an unknown session, the server replies with an error
object that carries neither id nor type:
{ "error": "Field 'sessionId' must be a string" }
Validation errors you may see: Field 'id' must be a string, Field 'type' must be a string,
Field 'data' must be an object, Unknown type: <type>, Field 'sessionId' must be a string,
Field 'sql' must be a string, Field 'fetchSize' must be a number,
Field 'maxRows' must be a number, Field 'maxRows' must be a positive number,
Field 'maxExecutionTime' must be a non-negative integer (milliseconds),
Invalid session, Invalid taskId, Another SQL is already running.
maxRows is the number of rows the API returns per call (page size), not a database query limit, and must be
positive.
A session is created by sending a start message. The server returns a sessionId that must be included in subsequent messages for the same session.
A session owns its own backend connection. Sessions are released in three ways:
-
explicitly, with a
closemessage (the session id stops being valid immediately); -
when the connection that created them disappears - detected by a 10-second heartbeat, because the WebSocket
onClosecallback is not delivered by the Jetty/Javalin combination in use; -
when a session stays idle (no
start/exec/fetch/cancel) for longer thanclient_timeoutseconds (default 600). Sessions with a running task are never collected this way.
A session that is still running a task is not collected by the idle rule.
Start message:
{
"id": "1",
"type": "start",
"data": {}
}
Response:
{
"id": "1",
"type": "start",
"data": { "sessionId": "session-123" }
}
All further messages for this session must include "sessionId": "session-123" in their data field.
A session owns its own backend connection and can run one task at a time; sending exec while a
task is still running answers {"error": "Another SQL is already running"}.
Submits a SQL statement for asynchronous execution. Returns a task ID that can be used to fetch results later.
Message:
{
"id": "2",
"type": "exec",
"data": {
"sessionId": "session-123",
"sql": "SELECT * FROM large_table",
"fetchSize": 100, // optional, default 100; applied to the underlying Statement
"maxExecutionTime": 30000 // optional, milliseconds for this execution; 0 = no limit; omit = session/GLOBAL
}
}
Response (returned as soon as the task is accepted, while it is still running):
{
"id": "2",
"type": "exec",
"data": {
"taskId": "550e8400-e29b-41d4-a716-446655440000",
"status": "running",
"maxExecutionTime": 30000 // the effective value; echoes the session value when the field is omitted
}
}
maxExecutionTime applies to this task only: the server sets the session value before executing and
restores the previous value when the task ends (success, failure, timeout or cancel), so it never leaks
into later exec calls on the same session. Precedence: exec.data.maxExecutionTime >
client SET SESSION max_execution_time > server max_execution_time (GLOBAL). The field must be a
non-negative integer number of milliseconds; negative, fractional or non-numeric values are
rejected (see the validation error list above).
If the SQL fails while executing, the task status becomes error and fetch reports it as
data.status = "error" with the message in data.error (the exec response itself only means the
task was accepted).
exec accepts the same SQL as the PostgreSQL wire protocol, including:
-
PL/SQL anonymous blocks -
DO ..., bare...and unwrappedDECLARE … BEGIN … END;scripts, executed by the same engine the PG path uses; -
multi-statement scripts - every statement is executed in order; if the last statement returns a result set, that result set is the one
fetchpages through, otherwise the affected-row count of the script’s DML statements is reported asupdateCount. Earlier result sets are discarded, so a script is not a way to get several result sets.
Result values use the representations listed in Result value types above (ISO-8601 dates/times, Base64 BLOBs, JSON arrays for LIST, JSON objects for STRUCT/MAP).
Retrieves a page of results for a given task ID. The endpoint returns a fixed number of rows (up to fetchSize specified in execute) and indicates whether more rows are available.
Message:
{
"id": "3",
"type": "fetch",
"data": {
"sessionId": "session-123",
"taskId": "550e8400-e29b-41d4-a716-446655440000",
"maxRows": 100 // optional, overrides the default page size
}
}
Response:
{
"id": "3",
"type": "fetch",
"data": {
"status": "completed",
"columns": ["id", "name"],
"rows": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
],
"hasMore": false, // true while there are more rows
"fetched": 2 // rows read so far for this task
}
}
The values of data.status and the payload that comes with them:
-
running— the task is still executing; the payload is only{"status": "running"}(there are norows/hasMoreyet); -
error— execution failed:{"status": "error", "error": "<message>"}; -
completedwith a result set —columns,rows,hasMoreandfetched; keep callingfetchwhilehasMoreis true; -
completedwithout a result set (INSERT/UPDATE/DDL) —{"status": "completed", "updateCount": <n>}, with norows; -
idle— the task has finished and its result set/statement have been closed (all rows consumed); a laterfetchanswers with this status.
You can send multiple fetch messages until hasMore becomes false. Each call returns the next page of rows.
Cancels the task that is currently running in the session. Only sessionId is read — taskId is
ignored (a session has at most one running task): the server interrupts the executing thread and
calls Statement.cancel().
Message:
{
"id": "4",
"type": "cancel",
"data": {
"sessionId": "session-123"
}
}
Response:
{
"id": "4",
"type": "cancel",
"data": {
"status": "canceled", // "no-running-statement" when there was nothing to cancel
"detail": "statement canceled"
}
}
When status is canceled, detail is either "future canceled" (the executing thread was
interrupted) or "statement canceled" (the running statement was cancelled); when there was nothing
to cancel, status is no-running-statement and detail is an empty string. A successful cancel
resets the task, so a later fetch with the old taskId answers Invalid taskId.
Closes the session and releases all associated resources (including any pending tasks).
Message:
{
"id": "5",
"type": "close",
"data": {
"sessionId": "session-123"
}
}
Response:
{
"id": "5",
"type": "close",
"data": {
"status": "closed"
}
}
After closing, the session ID is no longer valid.
-
Connect to WebSocket endpoint:
const WebSocket = require('ws'); const ws = new WebSocket('ws://localhost:8080/sql/ws');
-
Create a session:
ws.send(JSON.stringify({ id: "1", type: "start", data: {} }));
-
Execute a long query:
ws.send(JSON.stringify({ id: "2", type: "exec", data: { sessionId: "session-123", sql: "SELECT * FROM huge_table", fetchSize: 500 } }));
-
Fetch first page:
ws.send(JSON.stringify({ id: "3", type: "fetch", data: { sessionId: "session-123", taskId: "abc123", maxRows: 100 } }));
-
Fetch subsequent pages until
hasMorebecomes false. -
Optionally cancel (only
sessionIdis read — it cancels the session’s current task):ws.send(JSON.stringify({ id: "4", type: "cancel", data: { sessionId: "session-123" } }));
-
Close the session when done:
ws.send(JSON.stringify({ id: "5", type: "close", data: { sessionId: "session-123" } }));
Note: The examples above assume you handle incoming messages asynchronously. In a real client you would match responses by their id.
// create configuration, and update as your need
ServerConfiguration serverConfiguration = new ServerConfiguration();
serverConfiguration.setPort(4309);
serverConfiguration.setData("data1");
// init database
DBInstance dbInstance = new DBInstance(serverConfiguration);
// startup database
dbInstance.start();
// shutdown database
dbInstance.stop();
// We currently supports starting multiple instances running at the same time.
// But each instance must have his own port and instance name.
ServerConfiguration proxyConfiguration = new ServerConfiguration();
proxyConfiguration.setPort(dbPort);
ProxyInstance proxyInstance = new ProxyInstance(proxyConfiguration);
proxyInstance.start();
// Waiting for server ready
while (!proxyInstance.instanceState.equalsIgnoreCase("RUNNING")) {
Sleeper.sleep(1000);
}
Based on DuckDB’s secure encryption mechanism, we support data encryption.
To use this feature, you need to:
-
Set the parameter data_encrypt to true.
-
Set the database key through any of the following three methods:
-
Environment variable: SLACKERDB_<dbName>_KEY (where <dbName> is replaced with the name of your database instance).
-
Java property: Specify it when starting the program as -DSLACKERDB_<dbName>_KEY=….
-
After startup, specify it via the statement: ALTER DATABASE <dbName> SET Encrypt Key <key>.
-
The distribution also ships a command line client, dbcli (Java 21+): connect interactively to write SQL, or
run scripts in CI/batch and verify their output. It is jlib/slackerdb-dbcli-<version>-standalone.jar and is
started with bin/dbcli.bat / bin/dbcli.sh.
| Feature | Description |
|---|---|
SQL client |
interactive console plus batch scripts; statements end with |
Result checks |
|
HTTP calls |
|
Control flow |
|
Connection |
|
Session persistence |
|
Task orchestration |
|
Remote access |
|
System commands |
|
Output |
|
dbcli # interactive console dbcli --execute script.sql # run a script dbcli --execute script.sql --logfile run.log --ref golden.ref # run and compare with a reference dbcli --home_dir code --work_dir /tmp/work --output_dir out --execute script.sql # explicit dirs
Full usage: dbcli/README.adoc.
We do not support user password authentication; these two options are kept only for compatibility.
You can fill in anything; they have no effect.
Only some DuckDB data types are supported, mainly simple types such as int, number, double, varchar, … Complex types are either still under development or cannot be represented in the PG protocol (blob, list, map…); they are rejected with an explicit error rather than silently converted.
Upstream blockers as of duckdb_jdbc 2.0.1.0 (DuckDB is expected to be upgraded soon; we will follow):
-
COPY … FROM STDINintoBIGNUM: DuckDB’s JDBC appender has no BIGNUM C API type (unsupported C API type: 35), so SlackerDB cannot support it yet. -
COPY … FROM STDINintoBIT,INTERVAL,TIME_NS, orVARIANT: same missing appender type, so they are rejected too. -
COPY … TO STDOUT (FORMAT binary)forINTERVAL,BIT,TIME_NS,BIGNUM,VARIANT, and nestedLIST/ARRAY/STRUCT/MAP/UNION: these have no PostgreSQL binary representation in the encoder, so the statement is rejected with0A000before any data is sent. Use CSV or text format for such queries.
SlackerDB speaks the PostgreSQL wire protocol, so postgres_fdw can attach a SlackerDB
instance as a foreign server. The protocol layer handles the FDW’s session and statement
traffic, including the cursor-based data path it uses to read rows.
Statements PostgreSQL 17’s postgres_fdw actually sends, and where we stand:
Supported
-
Connection setup:
SET search_path,SET timezone,SET datestyle,SET intervalstyle,SET extra_float_digits;application_nameandclient_encodingin the startup packet;GSSENCRequestis answered withN. -
Extended protocol: Parse / Bind / Describe / Execute / Close / Sync / Flush — named and unnamed statements and portals, per-column result-format negotiation (the
Int16[R]list in Bind is honoured, text or binary),PortalSuspendedpaging,RETURNING,DEALLOCATE ALL/DEALLOCATE <name>,RESET ALL,DISCARD ALL. -
Cursors:
DECLARE … CURSOR [WITH HOLD] FOR,FETCH(NEXT/FORWARD n/ALL/ bare count),MOVE,CLOSE [ALL]— on both the simple and the extended protocol path. Cursors withoutWITH HOLDare dropped when the transaction ends, as in PostgreSQL;WITH HOLDcursors surviveCOMMITand are materialised in memory to do so. Only forward directions are supported:BACKWARD/ABSOLUTE/RELATIVEexplicitly return0A000, because a DuckDB JDBC result set cannot scroll backwards. -
Transactions:
BEGIN/START TRANSACTION [ISOLATION LEVEL …]really open a DuckDB transaction, andCOMMIT/COMMIT TRANSACTION/END/ROLLBACK/ABORTend it (aCOMMITinside a failed transaction rolls back, as in PostgreSQL;COMMITwith no transaction in progress only raises aNOTICE). Isolation levels:READ ONLYis passed through and enforced by DuckDB,READ COMMITTED/REPEATABLE READare treated as satisfied,SERIALIZABLE/DEFERRABLEare accepted with aNOTICEsaying they are not enforced.SET TRANSACTION …is accepted inside a transaction block (with aNOTICE) and rejected with25P01outside one. -
SET <PostgreSQL-only parameter>(for examplestatement_timeout,lock_timeout,server_version_num) is accepted, remembered per session and answered with aNOTICEsaying it has no effect; DuckDB’s own parameters still pass through. -
ANALYZE <foreign table>works: SlackDB answers both statements PostgreSQL sends for it (SELECT pg_catalog.pg_relation_size('schema.table'::pg_catalog.regclass) / 8192andSELECT reltuples, relkind FROM pg_catalog.pg_class WHERE oid = …) by translating theregclasscast into a real OID lookup, and serves the row sample through a cursor.relpagescomes from DuckDB’s ownestimated_size, so it stays 0 for small tables. -
Errors follow the protocol: after an extended-protocol error the backend discards messages until
Sync;Describe/Closeof an unknown statement or portal return26000/34000; a malformed Bind message returns08P01.
Not implemented yet
-
SAVEPOINT/RELEASE SAVEPOINT/ROLLBACK TO SAVEPOINT: DuckDB has no subtransactions, so these fail predictably. In particularROLLBACK TO SAVEPOINTdoes not roll back the whole transaction. Consequence for the FDW:postgres_fdwemitsSAVEPOINT sNwhenever a remote statement runs inside a local subtransaction, so foreign tables cannot be used inside a subtransaction (an explicitSAVEPOINT, or a PL/pgSQLEXCEPTIONblock), and the failure additionally leaves that foreign server’s connection unusable for the rest of the transaction (connection to server "sdb" cannot be used due to abort cleanup failure). -
SELECT … FOR UPDATE/FOR SHARE:postgres_fdwpushes the locking clause to the remote, and DuckDB rejects it (Parser Error: SELECT locking clause is not supported!), so such queries fail.ctidmatters only if you declareOPTIONS (rowid 'ctid')on a foreign table; ordinaryUPDATE/DELETEworks without a remote key — the FDW does not need a transaction id (ctid). -
SELECT … FOR UPDATE/FOR SHARE(DuckDB has no row locks), andUPDATE/DELETE … WHERE ctid = $1(DuckDB has noctid). -
IMPORT FOREIGN SCHEMAonly works withimport_collate 'false'(pg_collation.collnamespaceis not exposed); column defaults are not imported becausepg_get_expris unavailable.
Example
CREATE EXTENSION postgres_fdw;
CREATE SERVER sdb FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host '127.0.0.1', port '15499', dbname 'fdwdb',
use_remote_estimate 'false');
CREATE USER MAPPING FOR CURRENT_USER SERVER sdb OPTIONS (user 'main', password 'main');
CREATE FOREIGN TABLE orders (id integer, amount numeric(38,4))
SERVER sdb OPTIONS (schema_name 'main', table_name 'orders');
-- IMPORT FOREIGN SCHEMA can also import the tables directly (requires import_collate 'false')
IMPORT FOREIGN SCHEMA "main" FROM SERVER sdb INTO public
OPTIONS (import_collate 'false');Other limitations:
-
dbnameis the instance name the server was started with (--data fdwdb), not a PostgreSQL-style database name. -
import_collateis an option ofIMPORT FOREIGN SCHEMA, not ofCREATE SERVER; PostgreSQL rejects it in the server options (invalid option "import_collate"). -
Keep
use_remote_estimateoff: it makespostgres_fdwparse PostgreSQL’sEXPLAIN (cost=… rows=… width=…)text, which DuckDB does not produce.
SlackerDB provides a PF4J‑based plugin framework that allows developers to extend the database server’s functionality. Plugins can access database connections, loggers, and the Javalin web application instance, enabling them to register custom HTTP endpoints, execute background tasks, or integrate external services.
The plugin system is built on top of PF4J (Plugin Framework for Java) and is customized to provide database‑specific context. The core components are:
-
DBPlugin – Abstract plugin base class that extends PF4J’s
Pluginclass and implements theIDBPluginContextinterface. Plugins must extend this class and implement lifecycle methods. -
DBPluginContext – Plugin context object that contains a database connection, a logger, and the Javalin application instance. The plugin manager injects this context before the plugin starts.
-
DBPluginManager – Custom plugin manager responsible for loading, starting, stopping, and unloading plugins. It uses a custom
DBPluginFactoryto ensure the context is automatically injected when a plugin is created. -
DBPluginFactory – Custom plugin factory that, after creating a plugin instance, checks whether the plugin implements
IDBPluginContextand, if so, injects theDBPluginContext.
Plugin lifecycle:
1. Startup scan – When the server starts, it scans the configured plugin directory (plugins_dir), loads all JARs that conform to the PF4J specification, and starts them automatically.
2. Runtime load – The management endpoint POST /plugin/load can load a new plugin without restarting the server. It only loads the plugin and does not start it; call /plugin/start afterwards.
3. Create – The plugin instance is created via DBPluginFactory, and the DBPluginContext is injected.
4. Start – The plugin’s start() method is called, which executes beforeStart(), onStart(), and afterStart() in order.
5. Run – The plugin executes its custom logic in onStart(), e.g., registering Javalin routes, initializing database tables, etc.
6. Stop – Stop the plugin via /plugin/stop; /plugin/unload stops it first; shutting down the server also stops plugins that are running. Stopping executes beforeStop(), onStop(), and afterStop().
7. Unload – Unload the plugin via /plugin/unload. Unloading stops the plugin and releases the PF4J class loader, but does not delete the JAR and does not call delete().
Plugins loaded at runtime are not persisted: after a restart, only JARs present in plugins_dir are scanned and started again.
Plugins can access the following resources:
* Database connection – Obtain a new connection to the backend database via getDbConnection() (created via DuckDBConnection.duplicate()).
* Logger – Obtain a configured SLF4J logger via getLogger().
* Web application instance – Obtain the Javalin application instance via getJavalinApp(), which can be used to register HTTP routes and middleware.
The following steps are based on the plugin‑example module and demonstrate how to write a SlackerDB plugin.
The plugin project needs to depend on the slackerdb‑plugin module. Add the following dependency to your pom.xml:
<dependency>
<groupId>org.slackerdb</groupId>
<artifactId>slackerdb-plugin</artifactId>
<version>0.2.2</version>
<scope>provided</scope>
</dependency>The PF4J core library is also required (usually already a transitive dependency of slackerdb‑plugin).
Create a class that extends DBPlugin and implements the necessary lifecycle methods. Example:
package org.slackerdb.myplugin;
import io.javalin.Javalin;
import org.pf4j.PluginWrapper;
import org.slackerdb.plugin.DBPlugin;
import org.slf4j.Logger;
import java.sql.Connection;
import java.sql.SQLException;
public class MyPlugin extends DBPlugin {
private Connection conn;
private Javalin app;
private Logger logger;
public MyPlugin(PluginWrapper wrapper) {
super(wrapper);
}
@Override
protected void onStart() {
// Obtain resources
try {
this.conn = getDbConnection();
} catch (SQLException e) {
// Handle exception
}
this.logger = getLogger();
this.app = getJavalinApp();
// Register a custom HTTP endpoint
app.get("/myplugin/hello", ctx -> ctx.result("Hello from MyPlugin!"));
// Initialize a database table
try (var stmt = conn.createStatement()) {
stmt.execute("CREATE TABLE IF NOT EXISTS myplugin_data (id INTEGER, name VARCHAR)");
} catch (SQLException e) {
logger.error("Failed to create table", e);
}
logger.info("MyPlugin started successfully");
}
@Override
protected void onStop() {
// Clean up resources
if (conn != null) {
try { conn.close(); } catch (SQLException ignored) {}
}
logger.info("MyPlugin stopped");
}
// Optional: override other lifecycle hook methods
// beforeStart, afterStart, beforeStop, afterStop, beforeDelete, afterDelete
}Create a plugin.properties file in the src/main/resources directory with the following content:
# Plugin unique identifier, must match the plugin JAR filename (without extension)
plugin.id=myplugin
# Fully qualified name of the plugin main class, must extend org.slackerdb.plugin.DBPlugin
plugin.class=org.slackerdb.myplugin.MyPlugin
# Plugin version number, follows semantic versioning
plugin.version=1.0.0
# Plugin dependency requirement, * means no specific dependency
plugin.requires=*Package the plugin with Maven:
mvn clean packageThe resulting JAR file (e.g., myplugin‑1.0.0.jar) should contain the plugin class and the plugin.properties file.
Place the plugin JAR file into the SlackerDB server’s plugin directory (specified by the server’s plugins_dir parameter). The default is empty, so no plugin directory is scanned; configure it explicitly and make sure the directory exists and the server can read it.
Start the SlackerDB server; the plugin will be loaded and started automatically. Check the server logs to confirm successful plugin loading:
[SERVER][PLUGIN ] Load plugin [myplugin] ...
[SERVER][PLUGIN ] start plugin [myplugin] ...If the plugin registered an HTTP endpoint, you can access it at http://localhost:<port_x>/myplugin/hello (assuming the management port port_x is enabled).
-
Logging – Plugins can output logs via
getLogger(); the log level is controlled by the server’slog_levelconfiguration. -
Error handling – Exceptions in a plugin’s startup lifecycle methods are caught and wrapped as
RuntimeException, causing the plugin to fail to start. Error messages are recorded in the server log. -
Runtime management – Plugins can be managed through the management endpoints
/plugin/load,/plugin/unload,/plugin/start, and/plugin/stop;/plugin/loadonly loads a plugin and does not start it automatically. -
Plugin updates – The server does not watch JAR files or automatically hot‑replace loaded plugins. To update a plugin, call
/plugin/stopand/plugin/unloadyourself, replace the JAR, then call/plugin/loadand/plugin/start. -
Route limitation – Because
/plugin/unloadis a fully trusted mechanism, it does not unregister routes that the plugin has already registered with Javalin. Unless the plugin removes them in its own unload logic, accessing the old paths after unload usually returns500 Internal Server Error.
The plugin‑example module contains the following key components:
-
The main plugin class – extends
DBPluginand implements all lifecycle methods. Its full source is reproduced in this section. -
A debug mode – demonstrates how to execute a plugin without the full PF4J framework.
-
The plugin descriptor – a
plugin.propertiesfile that defines the plugin’s metadata. -
The Maven build – configuration with a dependency on
slackerdb‑plugin.
The PluginExample class extends DBPlugin and provides implementations for all lifecycle methods:
public class PluginExample extends DBPlugin {
private Connection conn;
private Javalin app = null;
private Logger logger = null;
public PluginExample(PluginWrapper wrapper) {
super(wrapper);
}
@Override
protected void onStart() {
// Example: Obtain plugin resources
// try {
// this.conn = getDbConnection();
// } catch (SQLException ignored) {}
// this.logger = getLogger();
// this.app = getJavalinApp();
// Add plugin startup logic here
}
protected void onStop() {
// Clean up resources
}
protected void onDelete() {
// Permanent cleanup operations
}
// Lifecycle hook methods: beforeStart, afterStart, beforeStop, afterStop,
// beforeDelete, afterDelete
// Debug mode support
public static PluginExample standAloneInstance() throws Exception {
return DBPlugin.Standalone.createInstance(PluginExample.class);
}
}-
Resource Access – Shows how to obtain database connections, loggers, and Javalin application instances via
getDbConnection(),getLogger(), andgetJavalinApp(). -
Lifecycle Management – Implements all lifecycle methods (
onStart,onStop,onDelete) and their corresponding hook methods (beforeStart,afterStart, etc). -
Debug Mode – Includes a
standAloneInstance()method that lets the plugin run without the PF4J framework.
-
Build the plugin:
cd plugin-example mvn clean packageThe resulting JAR file (
plugin‑example‑0.2.2.jar) will be placed in thetargetdirectory. -
Deploy to a SlackerDB server:
-
Copy the JAR file to the server’s plugin directory (configured via
plugins_dirparameter). -
Start the server; the plugin will be loaded automatically.
-
Check server logs for plugin loading messages.
-
-
Run in debug mode:
cd plugin-example mvn compile exec:java -Dexec.mainClass="org.slackerdb.pluginExample.SimplePluginRunner"
This executes the
SimplePluginRunnerclass, which demonstrates how to run the plugin without a full SlackerDB server.
To create your own plugin based on this example:
-
Rename the package and class – Change
org.slackerdb.pluginExampleto your own package name. -
Update plugin.properties – Modify
plugin.id,plugin.class, andplugin.versionaccordingly. -
Implement business logic – Uncomment the resource acquisition code in
onStart()and add your custom functionality. -
Add dependencies – Update
pom.xmlwith any additional libraries your plugin requires. -
Test thoroughly – Use debug mode for testing before deploying to a production server.
The src/main/resources/plugin.properties file contains the plugin metadata:
plugin.id=plugin-example
plugin.class=org.slackerdb.pluginExample.PluginExample
plugin.version=0.2.2
plugin.requires=*-
plugin.idis the unique plugin identifier and is read fromplugin.propertiesby PF4J (in practice the JAR filename does not have to match it, though keeping them consistent is recommended for clarity). -
plugin.classmust be the fully qualified name of the plugin main class. -
plugin.versionfollows semantic versioning. -
plugin.requiresspecifies plugin dependencies (*means no specific dependency).
In addition to the standard PF4J‑based plugin loading mechanism, SlackerDB provides a debug mode that allows plugins to be executed directly without the full PF4J framework. This is useful for testing, debugging, or embedding plugin logic in custom applications.
Debug mode works by:
1. Creating a plugin instance via the standAloneInstance() method (available in plugins that extend DBPlugin)
2. Manually constructing a DBPluginContext with the required resources (database connection, logger, Javalin app)
3. Injecting the context into the plugin via setDBPluginContext()
4. Calling the plugin’s lifecycle methods (start(), stop()) directly
The plugin-example module includes a SimplePluginRunner class that demonstrates how to run a plugin in debug mode. Here’s a simplified version:
package org.slackerdb.pluginExample;
import io.javalin.Javalin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slackerdb.plugin.DBPluginContext;
import java.sql.Connection;
import java.sql.DriverManager;
public class SimplePluginRunner {
public static void main(String[] args) throws Exception {
// 1. Create database connection
Connection conn = DriverManager.getConnection("jdbc:duckdb:memory:");
// 2. Create Javalin app instance
Javalin javalin = Javalin.create();
// 3. Create logger
Logger pluginLogger = LoggerFactory.getLogger(PluginExample.class);
// 4. Create and configure DBPluginContext
DBPluginContext ctx = new DBPluginContext();
ctx.setDbBackendConn(conn);
ctx.setLogger(pluginLogger);
ctx.setJavalin(javalin);
// 5. Create plugin instance via debug mode
PluginExample plugin = PluginExample.standAloneInstance();
// 6. Inject context
plugin.setDBPluginContext(ctx);
// 7. Start the plugin
plugin.start();
// 8. (Optional) Wait and then stop
Thread.sleep(1000);
plugin.stop();
// 9. Clean up resources
conn.close();
}
}SlackerDB ships a built-in job scheduler that runs HOP workflows or scripts on a schedule, driven by project templates.
Typical usage: put a HOP project (.hwf/.hpl files, including the steps that execute SQL) into a "project template",
create an instance and bring it online with one call — the scheduler first runs the one-off initialization tasks
in order, then automatically runs the main flow on its cron schedule, recording logs and history for every run.
When is it available? Entirely configuration-driven — no plugin directory involved:
-
Management port disabled (
port_x=-1): none of the management capabilities, including the scheduler, exist; -
Management port enabled but
plugin-scheduler.home/plugin-scheduler.projectHomemissing: the capability does not exist — no/scheduler/*routes, no tables, no Quartz,/capabilities.features.etl=false, and/status.schedulerexplains why; -
Configured but unusable (directory missing,
hop.runScriptpointing nowhere, …): startup is refused, and a failed startup rolls back the listeners/thread pools that were already started; -
Read-only instance (
access_mode=READ_ONLY): no capability, and the configuration is not validated (creating the metadata tables cannot work anyway); -
plugin-scheduler.hop.runScriptis not a prerequisite: without it the scheduler still runs, only HOP tasks are unavailable (SHELLis unaffected). If it is set, it must be valid; -
Directories are never created automatically:
homeandprojectHomemust already exist.
-
Prepare HOP: the distribution does not bundle HOP. Prepare a HOP 2.20+ distribution and note the path of
hop-run.bat/hop-run.sh. HOP 2.20 requires JDK 21.plugin-scheduler.hop.javaHomemay be left empty; when empty, the JDK running dbserver (java.home) is used — usually the same JDK 21 that started the server. Set it only when a separate JDK is required. -
Enable the capability: set
home/projectHomein the server configuration file (plugins_diris no longer needed):plugin-scheduler.home=data/scheduler plugin-scheduler.projectHome=data/scheduler/projects plugin-scheduler.hop.runScript=D:/hop/hop-run.bat # Optional; leave empty (or remove this line) to use the current JDK # plugin-scheduler.hop.javaHome=D:/jdk21 # Optional; default true (HOP 2.20+). Set false only for HOP 2.19 or older # plugin-scheduler.hop.inMemoryProject=true
-
Prepare a template: create a directory named after the template under
data/scheduler/projects/(see the next section). -
Create and start an instance (
<management port>is the server’s management port):# Create an instance: projectType is the template directory name curl -X POST http://127.0.0.1:<management port>/scheduler/run/create \ -H "Content-Type: application/json" \ -d '{"projectType":"proj1"}' # Start it (orchestrated in template order: one-off tasks first, then periodic ones) curl -X POST http://127.0.0.1:<management port>/scheduler/run/<runId>/start # Check task status and the next fire time curl http://127.0.0.1:<management port>/scheduler/run/<runId>/task/list # Read the tail of a task log curl "http://127.0.0.1:<management port>/scheduler/run/<runId>/log?taskName=main&tail=200"
Each template is a directory whose name is the template name (projectType).
The template directory itself is the HOP project directory:
data/scheduler/projects/ ← template root (projectHome)
├── default/ ← HOP "parent project" (optional, shared configuration)
│ ├── project-config.json
│ └── metadata/
└── proj1/ ← template name, also the HOP project directory
├── conf/
│ ├── defaultSchedulerTask.json ← task list
│ └── variables.properties ← variables (optional, see next section)
├── project-config.json ← HOP project configuration
├── metadata/ ← HOP metadata (database connections, run configurations)
├── sql/ ← SQL scripts referenced by the workflows
└── *.hwf / *.hpl ← workflows and pipelinesThe task list conf/defaultSchedulerTask.json is keyed by task name:
{
"groups": ["SETUP_GROUP", "MAIN_GROUP"],
"setup": {
"taskScript": "setup.hwf",
"taskRunPolicy": "RUN_ONCE",
"taskTimeout": 600,
"taskGroup": "SETUP_GROUP",
"taskMandatory": true
},
"main": {
"taskScript": "main.hwf",
"taskRunPolicy": "CRONTAB",
"taskCrontabExpr": "0 1/2 * * * ? *",
"taskParallelPolicy": "SERIAL_DISCARD",
"taskFailPolicy": "CONTINUE",
"taskTimeout": 600,
"taskGroup": "MAIN_GROUP"
}
}| Field | Description |
|---|---|
|
For |
|
|
|
|
|
Quartz cron (6 or 7 fields, e.g. |
|
Interval in seconds for |
|
Timeout in seconds, 0 means unlimited; on timeout the task (including its child processes) is terminated |
|
Grouping and order inside a group; |
|
Mandatory task: if it fails the instance is marked failed and later stages are not started |
|
Re-entrancy policy: |
|
|
|
Whether the task is enabled, default |
|
Task-specific variables (optional) |
The task list may also be placed at the template root (projects/conf/defaultSchedulerTask.json) and shared by all
templates; a missing task list is not an error — the instance simply has no pre-configured tasks. Tasks can also be
supplied directly through the tasks parameter of the create-instance endpoint.
The field set above applies to both entry points (template list and the inline tasks[] of
POST /scheduler/run/create). Inline tasks are validated before anything is created: taskScriptType only accepts
HOP/SHELL/DBCLI (default HOP), and policies, taskRetryTimes/taskRetryInterval, taskMandatory and
variables (flat scalar values only) are checked too — unknown field names are rejected as well. Any invalid
entry yields 400 with a problems array and no instance directory or run record is created. In a template list an
unknown field only produces a warning (loading is not blocked).
The same applies to the top level of the create-instance request: only projectType / configJson / runId /
tasks are accepted and tasks must be an array; an unknown top-level field (e.g. task instead of tasks) yields
400 instead of silently falling back to the template task list.
With taskScriptType=DBCLI the scheduler runs a dbcli script in-process: exactly the same execution path as
dbcli --execute <file> (same statement splitting, _SET/_WHENEVER/_START/_ASSERT semantics and output
format) — no separate dbcli process is spawned.
-
Script location:
taskScriptis resolved against this run’sflow/<projectType>(where the project template was copied), or may be an absolute path; -
Connection: the script connects back to this instance’s data service port as an ordinary client (
jdbc:slackerdb://<host>:<port>/<database>), so--portmust be enabled; withport=-1a DBCLI task fails with a clear message. Override withplugin-scheduler.dbcli.connect=jdbc:slackerdb://host:port/dbwhen needed; a_connectinside the script still wins; -
Variables: scheduler variables (framework + the three business layers) are available as
${NAME}; -
Timeout / abort: the stop signal makes the script stop before the next statement and cancels the running SQL;
-
Exit code: dbcli semantics — only an explicit
_EXIT n/_WHENEVER ERROR EXIT nchanges it; SQL errors inside the script are only counted (the task log mentions them) and do not fail the task. To fail on SQL errors, put_WHENEVER ERROR EXIT 1at the top of the script.
Both the ${XXX} placeholders inside HOP workflows and the HOP connection metadata (${HOST}, ${PORT}, … in
metadata/rdbms/*.json) are resolved from these variables. They can be defined in four places; later ones win:
-
data/scheduler/variables.properties(global) -
template directory
proj1/conf/variables.properties -
the
configJsonfield of the create-instance request -
the
variablesobject of a specific task in the task list
DB_HOST=10.0.0.5
DB_PORT=5432
DB_USER=main
DB_PASSWORD=******A variable value may reference other variables, for example TEST_CODE=${RUN_ID} (built-in variables such as
RUN_ID, PROJECT_TYPE and TASK_NAME are available). The built-in variables are PROJECT_HOME, RUN_HOME,
RUN_ID, PROJECT_TYPE, TASK_NAME, LOG_DIR and AUDIT_DIR.
GET /scheduler/run/{runId}/variables shows the currently effective values (secrets are masked).
| Operation | Description |
|---|---|
Create instance |
Creates an isolated run directory ( |
Start |
Orchestrates by group and order: runs one-off tasks one after another, then activates that group’s periodic tasks |
Stop |
Pauses all tasks (definitions are kept, the instance can be started again) |
Abort |
Interrupts running tasks and pauses everything |
Drop |
Deletes the instance, its task definitions and its run directory |
After a server restart |
Instances are put into the "stopped" state; one-off tasks are not re-run automatically — start the instance manually to resume |
Individual tasks can also be scheduled, started, paused and aborted on their own.
Logs and history: every run writes to runs/<runId>/logs/<taskName>.log and is recorded in the history, which can be
queried through the API; expired history rows and log files are cleaned up automatically after the configured number of days.
| Endpoint | Description |
|---|---|
|
Scheduler status |
|
Template list / template details (including the parsed task list and warnings) |
|
Create an instance |
|
Instance list / details |
|
Start / stop / abort / drop an instance |
|
Schedule a single task |
|
Start / pause / abort a single task |
|
Task list: state, next fire time, last result, whether it is running |
|
Execution history |
|
Read task logs; without |
|
Show variables (secrets masked) |
|
Validate a cron expression and return the next 5 fire times |
-
HOP is not bundled with the distribution; provide a HOP 2.20+ distribution and configure
plugin-scheduler.hop.runScript. HOP runs as a separate process, so no JVM parameters of the database server need to be changed. -
Since HOP 2.20 the scheduler registers its project and lifecycle environment inside each
hop-runprocess (--project-locations,--environments,--in-memory). It therefore no longer depends on thehop-config.jsonit maintains in the run directory: parallel tasks cannot lose each other’s environment, a read-onlyhop-config.jsonis supported, and a failedhop-config.jsonupdate only logs a warning. Setplugin-scheduler.hop.inMemoryProject=falseonly to fall back to the old behaviour on HOP 2.19 or older. -
HOP output is decoded as UTF-8: the scheduler exports
HOP_WINDOWS_SHELL_ENCODING=65001and appends-Dfile.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8toHOP_OPTIONS, so Chinese task names/values no longer garble the task log on Windows.SHELLoutput still uses the platform encoding. -
The HOP project must satisfy the following (the scheduler self-checks this when an instance is created and warns): if the template’s
project-config.jsondeclares"parentProjectName": "default", adefault/project must exist under the template root and its ownparentProjectNamemust be empty (a parent project is optional — in that case leaveparentProjectNameempty in the template itself);metadata/workflow-run-configuration/local.jsonmust exist (it corresponds to the default runconfiglocal) -
Termination is best-effort: timeouts and aborts terminate
hop-runand its child processes, but long-running transactions inside HOP are not guaranteed to roll back immediately -
Single-node scheduling only; multiple nodes are not supported
-
The scheduler has no built-in authentication — expose the management port only on trusted networks
SlackerDB provides a set of HTTP endpoints for managing plugins at runtime. These endpoints allow you to load, unload, start, stop, and list plugins without restarting the server. All endpoints return JSON responses with a standard format: {"retCode": 0/-1, "retMsg": "message"}.
|
Note
|
Business failures on these endpoints usually still return HTTP 200 with retCode=-1; callers must check retCode, not only the HTTP status code.
|
Loads a JAR from the plugin directory or a specified path. After loading, the plugin is in the RESOLVED state and is not started automatically; call /plugin/start afterwards.
{
"filename": "myplugin.jar"
}-
filename– Plugin JAR filename (e.g., "myplugin.jar") or full path to the JAR file. If a simple filename is provided, it is loaded from the server’s plugin directory (configured viaplugins_dir); ifplugins_diris empty, a simple filename fails. A full path is loaded directly from that location and does not requireplugins_dir. -
Plugins loaded at runtime are not written to configuration and are not copied into
plugins_dir; whether they can be loaded after a restart depends on whether the JAR is still inplugins_dir.
{
"retCode": 0,
"retMsg": "Plugin loaded successfully",
"pluginId": "myplugin"
}{
"retCode": -1,
"retMsg": "Plugin file does not exist: /path/to/plugins/myplugin.jar"
}Stops and unloads a previously loaded plugin. If the plugin is running, it is stopped first.
-
Unloading releases the PF4J class loader, but does not delete the JAR and does not call
delete()/onDelete(). -
Unloading does not unregister routes that the plugin has already registered with Javalin. After unload, accessing the old paths usually returns
500 Internal Server Error, and may continue to return old plugin results; when updating a route-based plugin or when a complete cleanup is required, restart the server.
{
"plugid": "myplugin"
}{
"retCode": 0,
"retMsg": "Plugin unloaded successfully"
}Starts a loaded plugin. The plugin’s start() method will be called, which triggers the plugin’s lifecycle hooks (beforeStart(), onStart(), afterStart()).
{
"plugid": "myplugin"
}{
"retCode": 0,
"retMsg": "Plugin started successfully"
}Stops a running plugin. The plugin’s stop() method will be called, which triggers the plugin’s lifecycle hooks (beforeStop(), onStop(), afterStop()).
{
"plugid": "myplugin"
}{
"retCode": 0,
"retMsg": "Plugin stopped successfully"
}Lists all currently loaded plugins with their details.
{
"retCode": 0,
"retMsg": "Success",
"plugins": [
{
"pluginId": "myplugin",
"version": "1.0.0",
"state": "STARTED",
"file": "/path/to/plugins/myplugin.jar",
"description": "My example plugin",
"mountTime": 1761520800000,
"mountTimeFormatted": "2026-10-27 10:00:00"
},
{
"pluginId": "anotherplugin",
"version": "2.0.0",
"state": "STOPPED",
"file": "/path/to/plugins/anotherplugin.jar",
"description": "Another plugin",
"mountTime": 0,
"mountTimeFormatted": ""
}
]
}The state field uses PF4J state values: CREATED, DISABLED, RESOLVED, STARTED, STOPPED, FAILED, UNLOADED.
/plugin/list lists only currently loaded plugins, so UNLOADED is normally not visible; pluginState is not the real field name.
-
Thread safety – The plugin instance is a singleton during the server’s lifetime; ensure that methods like
onStart()are thread‑safe. -
Resource management – Database connections obtained via
getDbConnection()must be managed by the plugin itself; close them proactively. -
Dependency conflicts – Avoid introducing library versions that conflict with server dependencies; it is recommended to use the
providedscope for libraries already provided by the server. -
Performance impact – Plugin execution consumes server resources; avoid performing long‑blocking operations in plugins.

