Skip to content
robotslackerPublic

About

Duckdb Postgres Proxy. (A postgres jdbc server with duckdb backend)

Topics

Resources

Stars

16 stars

Watchers

1 watching

Forks

Repository files navigation

RobotSlacker
Figure 1. RobotSlacker

SlackerDB (DuckDB Postgres proxy)

What is SlackerDB?

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.

Capabilities

  • 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 SESSION reach the statement that is actually running.

  • High‑Performance Bulk Transfer – PostgreSQL COPY … FROM STDIN and COPY … TO STDOUT in 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.

Use Cases

  • 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 .duckdb file 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.

Usage

Build from source:

    # 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

How to develop in an offline environment

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

Start db server

    java -jar dbserver/target/slackerdb-dbserver-0.2.2-standalone.jar start

Stop db server

    java -jar dbserver/target/slackerdb-dbserver-0.2.2-standalone.jar stop

Check db status

    java -jar dbserver/target/slackerdb-dbserver-0.2.2-standalone.jar status

Start db proxy

    java -jar dbproxy/target/slackerdb-dbproxy-0.2.2-standalone.jar start

Stop db proxy

    java -jar dbproxy/target/slackerdb-dbproxy-0.2.2-standalone.jar stop

Check proxy status

    java -jar dbproxy/target/slackerdb-dbproxy-0.2.2-standalone.jar status

Server configuration file template

# 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=

Proxy configuration file template

# 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.

Service Discovery

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 advertise_address=<group>:<port>

A multicast group within a subnet

dbserver advertise_nic=<name or local IP>

Empty selects the first usable network interface

dbproxy listener_address=<group>:<port>

Must match the dbserver advertise_address exactly

Multi-instance Management

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_x set to 0 (or omitted) means "let the proxy pick a free port": the real port is written into instance.conf and is available afterwards from list, GET /admin/databases/<alias> or the create response. port_x=-1 disables the management port of that instance.

  • An instance always lives in <data_dir>/<alias> and instance.conf is 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 pid and log are followed everywhere: probing reads the pid file named by pid= (renamed or absolute paths are fine), and GET /admin/databases/<alias>/logs tails the file(s) named by log= (CONSOLE entries are skipped, ${data} is substituted with the database name). Nothing assumes the default instance.pid / logs/server.log. logfile is dbserver’s alias for log; it is normalized to log on create (an explicit log wins), so instance.conf never contains both keys with an ambiguous winner.

  • --name is shorthand for data; when both are given, --data wins.

  • For create, --conf still means the proxy client config (used to locate the proxy); every other --key value describes 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=true is passed, the launch overrides it with --daemon false (bin/start-daemon can still be used for a manual background start).

Command Description

dbproxy create --alias sales [--name sales] [--start false] [--<conf_key> <value> …​]

Create an instance and start it by default

dbproxy resume --alias sales

Start a stopped instance

dbproxy shutdown --alias sales

Graceful stop (data and directory are kept)

dbproxy restart --alias sales

Stop, then start again

dbproxy destroy --alias sales

Stop and delete the entire instance directory

dbproxy list [--json]

List the live state of all instances

dbproxy status

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 under data_dir (managed by the proxy); external = backends registered through multicast. The state and the SOURCE column in list distinguish them. External backends only forward data: start/shutdown/restart/destroy return 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 stop stops only the proxy; instances keep running.

  • No automatic recovery: restarting the proxy does not start any instance.

  • Destroy only removes the instance directory: destroy deletes <data_dir>/<alias>. If the instance’s data_dir points 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/stop in the instance directory directly; every status query re-probes the instance (/health + pid + command-line validation), so manual starts and stops are recognized correctly.

Proxy HTTP API

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

/status, /capabilities

The proxy itself

2

/admin/databases/**

The proxy’s instance management

3

/<alias>/**

The management port of that alias (HTTP passthrough)

4

/<alias>/aichat

/aichat of that alias (WebSocket pipe)

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 bind and 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.

GET /status

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
    }
  ]
}
  • backends contains only externally registered (multicast-discovered) forward mappings; state is always UNKNOWN because the proxy cannot probe them further. backendCount is its length.

  • databases is the unified view: both management (instances scanned under data_dir) and external (multicast-registered backends) appear here. Field meanings are in "Backend object" below.

  • The proxy itself has no /health endpoint (/health is the dbserver liveness probe); monitor the proxy through /status.

GET /capabilities

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 }
}
  • apiVersion and contracts.managementApi are the management API contract version (currently 1), not the product version; the product version is in proxy.version.

  • provisioning.enabled mirrors instanceManagementEnabled: it is false when data_dir is not configured, and write operations against managed instances then return 503.

  • managementForwarding.prefixMode=alias describes the /<alias>/** forwarding rule.

The /admin/databases family
Method Path Description

GET

/admin/databases

List every backend plus the instance root

GET

/admin/databases/<alias>

One backend (managed instances include conf)

POST

/admin/databases

Create an instance

POST

/admin/databases/<alias>/start

Start an instance

POST

/admin/databases/<alias>/shutdown

Gracefully stop an instance

POST

/admin/databases/<alias>/restart

Stop, then start again

DELETE

/admin/databases/<alias>

Stop and delete the instance directory

GET

/admin/databases/<alias>/logs

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.

GET /admin/databases

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

alias

string

Alias, also the routing key

source

string

management (an instance under data_dir) or external (a multicast-registered backend)

manageable

boolean

Whether lifecycle operations are allowed; only management is true

name

string

Database name (the data value of the instance configuration)

state

string

RUNNING, DEGRADED, STOPPED or UNKNOWN; transient STARTING / STOPPING may also appear in lists

pid

number/null

Instance process id verified through its command line; null for external backends and stopped instances

pgPort

number

Data port

mgmtPort

number

Management port; -1 when the instance has no management port

health

string

UP, DOWN, TIMEOUT or UNKNOWN

uptimeSeconds

number/null

Process uptime; null when it cannot be determined

error

string/null

Why the backend cannot be routed or its state cannot be determined

dir

string/null

Managed instance directory; null for external backends

target

string/null

host:port of an external backend; null for managed instances

When instanceManagementEnabled=false, storage.dataDir is null and databases contains only external backends. A failure to scan the instance directory returns a 500 envelope.

GET /admin/databases/<alias>

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.

POST /admin/databases

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

alias

yes

Directory name / routing key, lowercased, pattern [a-z][a-z0-9_-]{0,62}; a reserved or existing alias returns 409

name

no

Database name, defaults to alias, pattern [A-Za-z][A-Za-z0-9_-]{0,62}

start

no

Whether to start right after creation, default true

conf

no

dbserver settings written into instance.conf; every key can be overridden (ports, log, data path, pid, bind, advertise_address, access_mode, plugin parameters, …​)

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.

POST /admin/databases/<alias>/start|shutdown|restart

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 /health to report UP; 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 already STOPPED instance 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.

DELETE /admin/databases/<alias>

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.

GET /admin/databases/<alias>/logs

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>).

Example:
GET /admin/databases/sales/logs?lines=100

An external backend returns 409; a missing instance returns 404; a non-integer lines returns 400.

Prefix forwarding /<alias>/**

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=50 is forwarded to http://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, …​) and Host, 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, /viewlog or /backup have 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

{"retCode":404,"retMsg":"Database [x] does not exist."}

503

The instance exists but cannot be forwarded to (e.g. STOPPED)

{"retCode":503,"retMsg":"…​","alias":"x","state":"STOPPED"}

504

The instance management port timed out

{"retCode":504,"retMsg":"…​"}

502

Connection failure or interrupted request

{"retCode":502,"retMsg":"…​"}

Example:
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.

WebSocket /<alias>/aichat

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 1011 and 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, 1006 and 1015 are never sent to the peer as-is (they become 1000).

Other WebSocket endpoints (for example /sql/ws of the SQL REPL) are not proxied yet; connect to the instance management port directly.

Misc
  • 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 500 with the plain text Internal Server Error.

Complete example:
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"

JDBC Support

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.

Unix Domain Socket (UDS) Support

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.
Server Configuration

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.

JDBC Connection via UDS

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

Example 1: Standard JDBC

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..

Connect, create a table, insert, and query
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 and export with CopyManager
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);
        }
    }
}

Performance Tuning

  • Where objective conditions allow, use COPY for import and export whenever possible; it is much faster than plain SELECT and INSERT.

HTTP Management Services

  • 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 example GET /sales/status); see Proxy HTTP API for the forwarding rules.

/backup (POST)

Performs a synchronous database backup. The backup file is saved in the backup/ directory as {backupTag}.db.

Request body (JSON):
{
  "backupTag": "mybackup"
}
Response example (success):
{
  "retCode": 0,
  "retMsg": "Successful."
}
/backups (POST/GET)

Asynchronous backup tasks, for callers that need progress and a downloadable result.

  • POST /backups with {"backupTag":"mybackup"} returns 202 and {"id":"…​","status":"RUNNING"}.

  • GET /backups lists known tasks.

  • GET /backups/{id} returns the task status (RUNNING, COMPLETED, FAILED).

  • GET /backups/{id}/download downloads a completed backup file.

/logfile (GET)

Returns the configured server log as plain text.

Query parameters:
  • lines (optional) – return only the last N lines (max 10000). Without it the whole file is returned.

Example:
GET /logfile?lines=500
/download (GET)

Downloads a file from the server’s directory.

Query parameters:
  • filename (required) – path to the file.

Example:
GET /download?filename=logs/slackerdb.log

The endpoint supports Range requests for partial downloads.

/upload (POST)

Uploads a file to the server’s uploads/ directory.

Query parameters:
  • filename (required) – target file path.

Form data:
  • file (required) – the file to upload.

Example using curl:
curl -X POST -F "file=@local.txt" "http://localhost:8080/upload?filename=uploads/remote.txt"
Response:
"uploaded: uploads/remote.txt"
/viewLog (GET)

Retrieves the last N lines of a log file.

Query parameters:
  • filename (required) – path to the log file.

  • lines (optional) – number of lines to return (default 100, max 10000).

Example:
GET /viewLog?filename=logs/slackerdb.log&lines=50
Response (JSON array of strings):
[
  "2025-12-04 10:00:00 INFO  Server started",
  "2025-12-04 10:00:01 INFO  Listening on port 8080"
]
/status (GET)

Returns comprehensive server status information, including server details, database metrics, configuration parameters, usage statistics, installed extensions, and active sessions.

Example:
GET /status
Response (abbreviated):
{
  "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": []
}

PL/SQL Support

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.

Running a block

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.

Typical examples

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).

What is supported
Area Supported

Declaration

DECLARE variables with INTEGER/SMALLINT/BIGINT/DECIMAL(p,s)/REAL/DOUBLE/VARCHAR(n)/CHAR(n)/TEXT/BOOLEAN/DATE/TIME/TIMESTAMP [WITH TIME ZONE]/INTERVAL, NOT NULL, defaults, and CURSOR name [(params)] IS <query>

Assignment

x := expr; and LET x = expr;

Conditionals

IF / ELSIF / ELSE / END IF (also ELSEIF, ENDIF, ==, !=, &&, !)

Loops

LOOP, WHILE cond LOOP, FOR i IN [REVERSE] a..b LOOP (inclusive), FOR i IN [v1, v2] LOOP, EXIT [WHEN cond], CONTINUE [WHEN cond], labelled loops

Cursors

OPEN / FETCH …​ INTO / CLOSE, %FOUND, %NOTFOUND, %ROWCOUNT, %ISOPEN

Queries

SELECT …​ INTO v1[, v2] (exactly one row), any DuckDB SQL statement, :name bind variables in SQL text

Dynamic SQL

EXECUTE IMMEDIATE <SQL text> [INTO targets…​] [USING values…​]: the SQL text is evaluated at run time (build it with ||), placeholders may be ? / :1 / :name, and USING binds them in order of appearance; without INTO the result set is discarded by default, but the data service API captures the last dynamic query without INTO and returns it as the response; with INTO single-row semantics apply (NO_DATA_FOUND / TOO_MANY_ROWS / 24000), and a placeholder/USING count mismatch raises 07001

Exceptions

EXCEPTION WHEN NO_DATA_FOUND / TOO_MANY_ROWS / ZERO_DIVIDE / OTHERS / <custom> THEN, RAISE, RAISE name, re-raise inside a handler, nested blocks (legacy EXCEPTION: = WHEN OTHERS)

Expressions

Arithmetic, || concatenation, comparisons, IS [NOT] NULL, LIKE, IN, BETWEEN, CASE, logical AND/OR/NOT with short-circuit, and any DuckDB function

Semantics worth knowing
  • Variables start as NULL (not 0).

  • FOR i IN 1..5 iterates 1,2,3,4,5 (both bounds inclusive); FOR i IN 5..1 iterates 0 times; FOR i IN REVERSE 5..1 iterates 5,4,3,2,1.

  • EXIT leaves only the innermost loop; EXIT label leaves the named loop.

  • SELECT …​ INTO with 0 rows raises NO_DATA_FOUND, with more than one row TOO_MANY_ROWS — it never silently picks a row.

  • :name inside 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, so WHEN ZERO_DIVIDE works.

  • A block itself does not return a result set; the data service API captures the last EXECUTE IMMEDIATE query without INTO, 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.

Error codes
SQLSTATE Meaning

42601

Syntax or semantic error (unknown variable/cursor, duplicate declaration, unsupported type) — reported with line:column

P0002 / P0003

NO_DATA_FOUND / TOO_MANY_ROWS

22012

ZERO_DIVIDE

22001 / 22003 / 22P02 / 22007 / 42804

String too long / numeric out of range / bad numeric text / bad datetime / datatype mismatch

24000

Invalid cursor state; INTO target count mismatch

P0001

User RAISE

57014

Canceled by CancelRequest / KILL SESSION (long PL/SQL loops are interruptible)

54000

Statement budget exceeded (possible infinite loop)

Client notes

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 (preferQueryMode=simple, psql)

DO ...

OK

OK

bare ...

OK

OK

unwrapped DECLARE …​ END;

split by the driver — use DO $$ instead

OK

Types and implicit conversion

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 22003

string → numeric/date/time/timestamp

OK when the text parses as that literal, otherwise 22P02 (or 22007 for datetime)

numeric/date/time/timestamp → string

OK (standard text form)

string → VARCHAR(n)/CHAR(n) when longer than n

22001 — never silently truncated

anything involving BOOLEAN (except NULL)

42804 — use an explicit function or CAST

anything else

42804

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).

Loop boundaries
Form Iterations

FOR i IN 1..1

1 (i = 1)

FOR i IN 1..5

5 — both bounds inclusive

FOR i IN 1..0, FOR i IN 5..1

0

FOR i IN REVERSE 5..1

5 → 5,4,3,2,1

FOR i IN REVERSE 1..5

0

FOR i IN -3..-1

3 → -3,-2,-1

FOR i IN [v1, v2, v3]

one iteration per list element (compatibility form)

WHILE NULL LOOP

0 (NULL counts as false)

LOOP that never exits

stopped by the statement budget → 54000

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;
Expression semantics
  • Precedence, high to low: * → unary - / NOT → / % → + - → || → comparisons (= <> < ⇐ > >=, IS [NOT] NULL, LIKE, IN, BETWEEN) → AND → OR.

  • NULL in a condition counts as false; AND/OR short-circuit, so false AND (1/0 = 1) is fine.

  • || is string concatenation (SQL semantics) — write OR for 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.func are accepted).

Compatibility aliases kept from earlier versions:

Alias Equivalent

LET x = e

x := e

PASS

NULL;

BREAK

EXIT

== != && !

= <> AND NOT

ELSEIF / ENDIF

ELSIF / END IF

EXCEPTION: + statements

EXCEPTION WHEN OTHERS THEN

FOR :i IN 1 TO 5

FOR i IN 1..5

FOR i IN [v1, v2]

list iteration

%notfound, %found, %rowcount, %isopen

case-insensitive cursor attributes

Cursor state machine
State \ operation OPEN FETCH CLOSE %ISOPEN %FOUND %NOTFOUND %ROWCOUNT

Closed (declared, not opened)

OK

24000

24000

false

24000

24000

24000

Open, rows available

24000

OK, count+1

OK

true

true

false

n

Open, no rows

24000

OK → EOF, notFound=true

OK

true

false

true

0

Open, after EOF

24000

OK (stays EOF, variables keep their values)

OK

true

false

true

n

Closed after fetching

OK

24000

24000

false

24000

24000

24000

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.

Statement routing
  • Wrappers: DO … , DO $tag$ … $tag$, bare … , or an unwrapped DECLARE … 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: CommandComplete reports DO. Use DESCRIBE-visible statements (ordinary queries) or write into tables for output.

  • In the extended protocol a PL/SQL portal is described as NoData and bound without parameters.

Limitations and known gaps

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 / %NOTFOUND applied 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 ZONE keeps the backend representation; values are not normalised to UTC.

  • A block that fails does not roll back by itself — issue ROLLBACK in an EXCEPTION handler or from the client, exactly as with PostgreSQL DO.

Connection Pool

  • 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 backendSysConnection and closes it at session end, so it does not consume the pool’s max_connections. At most repl_max_connections sessions may exist; excess sessions are rejected immediately with Too much connections.

Data Service

  • 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

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

/api/login

Response example:

Success response (200)

  {
    "retCode": 0,
    "token": “yJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9”,
    "retMsg": "Login successful."
  }
user logout

User logout

Attribute Value

Protocol

HTTP

Method

POST

Path

/api/logout

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

set context

Attribute Value

Protocol

HTTP

Method

POST

Path

/api/setContext

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."
  }
removeContext

remove context

Attribute Value

Protocol

HTTP

Method

POST

Path

/api/removeContext

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."
  }
registerService

register a service

Attribute Value

Protocol

HTTP

Method

POST

Path

/api/registerService

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 (<category>.service, services without a category go to uncategorized.service).

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 WHERE + ORDER BY + LIMIT/OFFSET. Invalid expressions are rejected at registration

description

description

snapshotLimit

how long the query result will be cached (optional), for example 3 hours / 30 minutes / 45 seconds; default empty (0), i.e. no caching

maxExecutionTime

maximum execution time for this service’s queries (optional, milliseconds). Unset = inherit the server max_execution_time; 0 = explicitly unlimited; negative or non-integer values are rejected

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.

unRegisterService

unregister a service

Attribute Value

Protocol

HTTP

Method

POST

Path

/api/unRegisterService

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."
  }
listRegisteredService

list all service

Attribute Value

Protocol

HTTP

Method

GET

Path

/api/listRegisteredService

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 to data_service_schema (a single file, or one <category>.service file per category when it is a directory);

  • /api/loadRegisterService - loads definitions from the request body (a single object or an array).

/api/{apiVersion}/{apiName}

API query

Attribute Value

Protocol

HTTP

Method

POST or GET

Path

/api/{apiVersion}/{apiName}

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 (service-level result-set filtering)

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, optional ESCAPE)

  • 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; trim removes leading/trailing ASCII spaces only, and length counts Unicode code points for strings and elements for lists

  • sorting: ORDER BY col [ASC|DESC] [NULLS FIRST|LAST], …​ (defaults to ASC and NULLS LAST; as in DuckDB, NULLS LAST does not flip with direction)

  • paging: LIMIT n, LIMIT ALL, OFFSET n (filter/sort first, then OFFSET, then LIMIT)

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.

Result value types

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 (2026-10-09, 12:34:56)

TIMESTAMP

ISO-8601 string without zone (2026-10-09T12:34:56)

TIMESTAMP WITH TIME ZONE

ISO-8601 string with offset (2026-10-09T20:34:56+08:00)

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.

MCP Server

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.

Protocol surface
Item Behaviour

Transport

Streamable HTTP: every message is a POST to /mcp (/jsonrpc is kept as a compatibility alias).

Sessions

None at the protocol level. The initialize handshake and Mcp-Session-Id were removed in 2026-07-28. Every request carries its protocol version and client capabilities in params._meta (io.modelcontextprotocol/protocolVersion, …​/clientCapabilities). A version mismatch returns UnsupportedProtocolVersionError (-32020).

server/discover

Implemented, as the specification requires. Advertises supported protocol versions, capabilities, server identity and usage instructions. Sent as a normal POST.

GET requests

Answer 405 Method Not Allowed (with Allow: POST). The specification removed the GET endpoint, and installed clients probe it to decide whether an SSE stream is offered — 405 is the documented "none available" answer, so this keeps older SDK clients connecting cleanly.

Result envelope

Every result carries resultType (complete or input_required).

Caching

tools/list, prompts/list, resources/list, resources/read and resources/templates/list carry ttlMs and cacheScope.

tools/list

Deterministic (sorted by name) so client-side caches and LLM prompt caches stay effective.

Removed methods

ping and logging/setLevel answer with an explicit "removed in 2026-07-28" error rather than being silently accepted. The GET /sse endpoint is gone; log level is per-request via _meta.

Built-in tools
Tool Description

open_session

Opens a stateful SQL session and returns a server-minted handle. Pass that handle to run_sql to keep temporary tables, transactions and session settings across calls. Sessions expire when idle and are closed by close_session.

close_session

Closes a session and releases its connection immediately.

run_sql

Executes SQL (all rows by default) and can cap the result with max_rows. The optional maxExecutionTime (milliseconds, 0 = no limit) overrides the server timeout for this call only. The result also carries read_only, statement_type (query/update) and elapsed_ms.

list_tables

Lists tables and views as a tables array of {schema, name, type}, optionally filtered by schema.

describe_table

Column definitions (name, type, nullable, default) for one table or view, as a columns result grid plus the resolved schema/table.

sample_rows

A small sample of real values from a table.

list_services

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 slackerdb://services, because not every MCP client consumes resources.

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).

Execution policy
  • Permissions follow the server. MCP is an internal tool and no longer adds a read-only restriction; run_sql can execute read and write statements, and the final permissions come from the server’s access_mode. open_session(read_only) is kept only for compatibility with older clients and no longer has any effect.

  • Returned rows. run_sql returns all rows by default; max_rows can cap the result, and 0 or a negative value means unlimited. truncated is true only 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_sql accepts an optional maxExecutionTime (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.

Resources and prompts
URI / name Content

slackerdb://schema/tables

Every table and view with schema and type.

slackerdb://schema/table/{table}

Column definitions for one table (resource template).

slackerdb://services

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.

answer_with_services (prompt)

A service-first answering policy that can be handed to the model.

Configuration

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.service

A 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.

Connecting an MCP client (DeepSeek Harness example)

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.

MCP Tool administration

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.

registerMCPTool

Register an MCP tool.

Attribute Value

Protocol

HTTP

Method

POST

Path

/mcp/registerMCPTool

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 mcp_config may omit it when it declares a handler)

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"
  }
unregisterMCPTool

Unregister an MCP tool.

Attribute Value

Protocol

HTTP

Method

POST

Path

/mcp/unregisterMCPTool

request body:

Attribute Value

name

tool name (required)

Request example:

  {
    "name": "queryDatabase"
  }

Response example:

Success response (200)

  {
    "retCode": 0,
    "retMsg": "Tool unregistered successfully"
  }
loadMCPTool

Load MCP tool definitions from JSON.

Attribute Value

Protocol

HTTP

Method

POST

Path

/mcp/loadMCPTool

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"
  }
saveMCPTool

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

/mcp/saveMCPTool

Response example:

Success response (200)

  {
    "retCode": 0,
    "retMsg": "Tools saved successfully",
    "savedPath": "/path/to/config/file"
  }
dumpMCPTool

Dump MCP tool definitions as JSON for download.

Attribute Value

Protocol

HTTP

Method

POST

Path

/mcp/dumpMCPTool

Response: JSON file download with Content-Disposition header.

MCP Resource

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.

registerMCPResource

Register an MCP resource.

Attribute Value

Protocol

HTTP

Method

POST

Path

/mcp/registerMCPResource

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"
  }
unregisterMCPResource

Unregister an MCP resource.

Attribute Value

Protocol

HTTP

Method

POST

Path

/mcp/unregisterMCPResource

request body:

Attribute Value

name

resource name (required)

Request example:

  {
    "name": "customerData"
  }

Response example:

Success response (200)

  {
    "retCode": 0,
    "retMsg": "Resource unregistered successfully"
  }
loadMCPResource

Load MCP resource definitions from JSON.

Attribute Value

Protocol

HTTP

Method

POST

Path

/mcp/loadMCPResource

request body: JSON array of resource definitions or a single resource definition object.

Response example:

Success response (200)

  {
    "retCode": 0,
    "retMsg": "Resources loaded successfully"
  }
saveMCPResource

Save MCP resource definitions to configuration file.

Attribute Value

Protocol

HTTP

Method

POST

Path

/mcp/saveMCPSource

Response example:

Success response (200)

  {
    "retCode": 0,
    "retMsg": "Resources saved successfully",
    "savedPath": "/path/to/config/file"
  }
dumpMCPResource

Dump MCP resource definitions as JSON for download.

Attribute Value

Protocol

HTTP

Method

POST

Path

/mcp/dumpMCPSource

Response: JSON file download with Content-Disposition header.

MCP Service

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.

registerMCPService

Register an MCP service.

Attribute Value

Protocol

HTTP

Method

POST

Path

/mcp/registerMCPService

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"
  }
unregisterMCPService

Unregister an MCP service.

Attribute Value

Protocol

HTTP

Method

POST

Path

/mcp/unregisterMCPService

request body:

Attribute Value

name

service name (required)

Request example:

  {
    "name": "queryCustomer"
  }

Response example:

Success response (200)

  {
    "retCode": 0,
    "retMsg": "Service unregistered successfully"
  }
loadMCPService

Load MCP service definitions from JSON.

Attribute Value

Protocol

HTTP

Method

POST

Path

/mcp/loadMCPService

request body: JSON array of service definitions or a single service definition object.

Response example:

Success response (200)

  {
    "retCode": 0,
    "retMsg": "Services loaded successfully"
  }
saveMCPService

Save MCP service definitions to configuration file.

Attribute Value

Protocol

HTTP

Method

POST

Path

/mcp/saveMCPService

Response example:

Success response (200)

  {
    "retCode": 0,
    "retMsg": "Services saved successfully",
    "savedPath": "/path/to/config/file"
  }
dumpMCPService

Dump MCP service definitions as JSON for download.

Attribute Value

Protocol

HTTP

Method

POST

Path

/mcp/dumpMCPService

Response: JSON file download with Content-Disposition header.

SQL REPL Server

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.

WebSocket Endpoint

Connect to the WebSocket endpoint:

Attribute Value

Protocol

WebSocket (ws:// or wss://)

Path

/sql/ws

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.

Session Management

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 close message (the session id stops being valid immediately);

  • when the connection that created them disappears - detected by a 10-second heartbeat, because the WebSocket onClose callback is not delivered by the Jetty/Javalin combination in use;

  • when a session stays idle (no start/exec/fetch/cancel) for longer than client_timeout seconds (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"}.

Execute SQL (async)

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 unwrapped DECLARE …​ 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 fetch pages through, otherwise the affected-row count of the script’s DML statements is reported as updateCount. 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).

Fetch Results

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 no rows / hasMore yet);

  • error — execution failed: {"status": "error", "error": "<message>"};

  • completed with a result set — columns, rows, hasMore and fetched; keep calling fetch while hasMore is true;

  • completed without a result set (INSERT/UPDATE/DDL) — {"status": "completed", "updateCount": <n>}, with no rows;

  • idle — the task has finished and its result set/statement have been closed (all rows consumed); a later fetch answers with this status.

You can send multiple fetch messages until hasMore becomes false. Each call returns the next page of rows.

Cancel Task

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.

Close Session

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.

Example Workflow (using JavaScript/Node.js)
  1. Connect to WebSocket endpoint:

    const WebSocket = require('ws');
    const ws = new WebSocket('ws://localhost:8080/sql/ws');
  2. Create a session:

    ws.send(JSON.stringify({
      id: "1",
      type: "start",
      data: {}
    }));
  3. Execute a long query:

    ws.send(JSON.stringify({
      id: "2",
      type: "exec",
      data: {
        sessionId: "session-123",
        sql: "SELECT * FROM huge_table",
        fetchSize: 500
      }
    }));
  4. Fetch first page:

    ws.send(JSON.stringify({
      id: "3",
      type: "fetch",
      data: {
        sessionId: "session-123",
        taskId: "abc123",
        maxRows: 100
      }
    }));
  5. Fetch subsequent pages until hasMore becomes false.

  6. Optionally cancel (only sessionId is read — it cancels the session’s current task):

    ws.send(JSON.stringify({
      id: "4",
      type: "cancel",
      data: {
        sessionId: "session-123"
      }
    }));
  7. 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.

Embed the db server in your code

  // 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.

Embed the db proxy in your code

    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);
    }

Data Security

Based on DuckDB’s secure encryption mechanism, we support data encryption.

To use this feature, you need to:

  1. Set the parameter data_encrypt to true.

  2. Set the database key through any of the following three methods:

    1. Environment variable: SLACKERDB_<dbName>_KEY (where <dbName> is replaced with the name of your database instance).

    2. Java property: Specify it when starting the program as -DSLACKERDB_<dbName>_KEY=…​.

    3. After startup, specify it via the statement: ALTER DATABASE <dbName> SET Encrypt Key <key>.

dbcli (command line client)

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 ; or with / alone on a line; Ctrl-C cancels a running statement

Result checks

--ref compares this run with a reference file; _assert and _compare inside a script

HTTP calls

_api calls REST APIs; status/headers/JSON values are available as API.* for assertions/chaining

Control flow

_if/_elseif/_else/_endif, _loop/_endloop, _loop break / continue; one progress line per iteration

Connection

_connect takes the short form, jdbc:slackerdb:// and any other jdbc:<scheme>: URL; _load jdbcdriver loads a driver at runtime

Session persistence

_session keeps/switches connections

Task orchestration

_job concurrent jobs; _ssh/SFTP, _host

Remote access

_ssh/SFTP, _host

System commands

_host

Output

_set controls echo/summaries/result sets; table/vertical/csv; _spool to a file

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.

dbcli connected and running select 42

Known Issues

1. User and password authorization

We do not support user password authentication; these two options are kept only for compatibility.
You can fill in anything; they have no effect.

2. Limited support for duckdb datatype

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 STDIN into BIGNUM: DuckDB’s JDBC appender has no BIGNUM C API type (unsupported C API type: 35), so SlackerDB cannot support it yet.

  • COPY …​ FROM STDIN into BIT, INTERVAL, TIME_NS, or VARIANT: same missing appender type, so they are rejected too.

  • COPY …​ TO STDOUT (FORMAT binary) for INTERVAL, BIT, TIME_NS, BIGNUM, VARIANT, and nested LIST/ARRAY/STRUCT/MAP/UNION: these have no PostgreSQL binary representation in the encoder, so the statement is rejected with 0A000 before any data is sent. Use CSV or text format for such queries.

3. postgresql-fdw

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_name and client_encoding in the startup packet; GSSENCRequest is answered with N.

  • 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), PortalSuspended paging, 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 without WITH HOLD are dropped when the transaction ends, as in PostgreSQL; WITH HOLD cursors survive COMMIT and are materialised in memory to do so. Only forward directions are supported: BACKWARD / ABSOLUTE / RELATIVE explicitly return 0A000, because a DuckDB JDBC result set cannot scroll backwards.

  • Transactions: BEGIN / START TRANSACTION [ISOLATION LEVEL …​] really open a DuckDB transaction, and COMMIT / COMMIT TRANSACTION / END / ROLLBACK / ABORT end it (a COMMIT inside a failed transaction rolls back, as in PostgreSQL; COMMIT with no transaction in progress only raises a NOTICE). Isolation levels: READ ONLY is passed through and enforced by DuckDB, READ COMMITTED / REPEATABLE READ are treated as satisfied, SERIALIZABLE / DEFERRABLE are accepted with a NOTICE saying they are not enforced. SET TRANSACTION …​ is accepted inside a transaction block (with a NOTICE) and rejected with 25P01 outside one.

  • SET <PostgreSQL-only parameter> (for example statement_timeout, lock_timeout, server_version_num) is accepted, remembered per session and answered with a NOTICE saying 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) / 8192 and SELECT reltuples, relkind FROM pg_catalog.pg_class WHERE oid = …) by translating the regclass cast into a real OID lookup, and serves the row sample through a cursor. relpages comes from DuckDB’s own estimated_size, so it stays 0 for small tables.

  • Errors follow the protocol: after an extended-protocol error the backend discards messages until Sync; Describe/Close of an unknown statement or portal return 26000/34000; a malformed Bind message returns 08P01.

Not implemented yet

  • SAVEPOINT / RELEASE SAVEPOINT / ROLLBACK TO SAVEPOINT: DuckDB has no subtransactions, so these fail predictably. In particular ROLLBACK TO SAVEPOINT does not roll back the whole transaction. Consequence for the FDW: postgres_fdw emits SAVEPOINT sN whenever a remote statement runs inside a local subtransaction, so foreign tables cannot be used inside a subtransaction (an explicit SAVEPOINT, or a PL/pgSQL EXCEPTION block), 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_fdw pushes the locking clause to the remote, and DuckDB rejects it (Parser Error: SELECT locking clause is not supported!), so such queries fail. ctid matters only if you declare OPTIONS (rowid 'ctid') on a foreign table; ordinary UPDATE/DELETE works without a remote key — the FDW does not need a transaction id (ctid).

  • SELECT …​ FOR UPDATE / FOR SHARE (DuckDB has no row locks), and UPDATE/DELETE …​ WHERE ctid = $1 (DuckDB has no ctid).

  • IMPORT FOREIGN SCHEMA only works with import_collate 'false' (pg_collation.collnamespace is not exposed); column defaults are not imported because pg_get_expr is 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:

  • dbname is the instance name the server was started with (--data fdwdb), not a PostgreSQL-style database name.

  • import_collate is an option of IMPORT FOREIGN SCHEMA, not of CREATE SERVER; PostgreSQL rejects it in the server options (invalid option "import_collate").

  • Keep use_remote_estimate off: it makes postgres_fdw parse PostgreSQL’s EXPLAIN (cost=…​ rows=…​ width=…​) text, which DuckDB does not produce.

Plugin System

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.

Plugin Mechanism Overview

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 Plugin class and implements the IDBPluginContext interface. 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 DBPluginFactory to 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 IDBPluginContext and, if so, injects the DBPluginContext.

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.

How to Write a Plugin

The following steps are based on the plugin‑example module and demonstrate how to write a SlackerDB plugin.

1. Create a Maven Project

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).

2. Implement the Plugin Main Class

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
}
3. Configure the Plugin Descriptor File

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=*
4. Build the Plugin

Package the plugin with Maven:

mvn clean package

The resulting JAR file (e.g., myplugin‑1.0.0.jar) should contain the plugin class and the plugin.properties file.

5. Deploy the Plugin

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.

6. Start the Server

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).

Plugin Notes
  • Logging – Plugins can output logs via getLogger(); the log level is controlled by the server’s log_level configuration.

  • 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/load only 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/stop and /plugin/unload yourself, replace the JAR, then call /plugin/load and /plugin/start.

  • Route limitation – Because /plugin/unload is 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 returns 500 Internal Server Error.

Module Structure

The plugin‑example module contains the following key components:

  • The main plugin class – extends DBPlugin and 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.properties file that defines the plugin’s metadata.

  • The Maven build – configuration with a dependency on slackerdb‑plugin.

PluginExample Class Overview

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);
    }
}
Key Features Demonstrated
  1. Resource Access – Shows how to obtain database connections, loggers, and Javalin application instances via getDbConnection(), getLogger(), and getJavalinApp().

  2. Lifecycle Management – Implements all lifecycle methods (onStart, onStop, onDelete) and their corresponding hook methods (beforeStart, afterStart, etc).

  3. Debug Mode – Includes a standAloneInstance() method that lets the plugin run without the PF4J framework.

Building and Running the Example
  1. Build the plugin:

    cd plugin-example
    mvn clean package

    The resulting JAR file (plugin‑example‑0.2.2.jar) will be placed in the target directory.

  2. Deploy to a SlackerDB server:

    • Copy the JAR file to the server’s plugin directory (configured via plugins_dir parameter).

    • Start the server; the plugin will be loaded automatically.

    • Check server logs for plugin loading messages.

  3. Run in debug mode:

    cd plugin-example
    mvn compile exec:java -Dexec.mainClass="org.slackerdb.pluginExample.SimplePluginRunner"

    This executes the SimplePluginRunner class, which demonstrates how to run the plugin without a full SlackerDB server.

Customizing the Example

To create your own plugin based on this example:

  1. Rename the package and class – Change org.slackerdb.pluginExample to your own package name.

  2. Update plugin.properties – Modify plugin.id, plugin.class, and plugin.version accordingly.

  3. Implement business logic – Uncomment the resource acquisition code in onStart() and add your custom functionality.

  4. Add dependencies – Update pom.xml with any additional libraries your plugin requires.

  5. Test thoroughly – Use debug mode for testing before deploying to a production server.

Plugin Descriptor File

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.id is the unique plugin identifier and is read from plugin.properties by PF4J (in practice the JAR filename does not have to match it, though keeping them consistent is recommended for clarity).

  • plugin.class must be the fully qualified name of the plugin main class.

  • plugin.version follows semantic versioning.

  • plugin.requires specifies plugin dependencies (* means no specific dependency).

Plugin Debugging

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();
    }
}

Job Scheduler (built-in capability, config keys plugin-scheduler.*)

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.projectHome missing: the capability does not exist — no /scheduler/* routes, no tables, no Quartz, /capabilities.features.etl=false, and /status.scheduler explains why;

  • Configured but unusable (directory missing, hop.runScript pointing 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.runScript is not a prerequisite: without it the scheduler still runs, only HOP tasks are unavailable (SHELL is unaffected). If it is set, it must be valid;

  • Directories are never created automatically: home and projectHome must already exist.

Quick Start
  1. 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.javaHome may 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.

  2. Enable the capability: set home / projectHome in the server configuration file (plugins_dir is 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
  3. Prepare a template: create a directory named after the template under data/scheduler/projects/ (see the next section).

  4. 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"
Preparing a Project Template

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 pipelines

The 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

taskScript

For HOP tasks: the .hwf/.hpl file name; for SHELL tasks: the command line; for DBCLI tasks: the dbcli script file (relative to this run’s flow/<projectType>, or an absolute path)

taskScriptType

HOP (default) / SHELL / DBCLI

taskRunPolicy

RUN_ONCE run once (default) / CRONTAB on a cron schedule / INTERVAL at a fixed interval

taskCrontabExpr

Quartz cron (6 or 7 fields, e.g. 0 1/2 * * * ? *); validate it with the describeCrontabExpr endpoint

taskInterval

Interval in seconds for INTERVAL

taskTimeout

Timeout in seconds, 0 means unlimited; on timeout the task (including its child processes) is terminated

taskGroup / taskStartupOrder

Grouping and order inside a group; groups declares the order of the groups

taskMandatory

Mandatory task: if it fails the instance is marked failed and later stages are not started

taskParallelPolicy

Re-entrancy policy: PARALLEL / SERIAL_DISCARD skip this fire / SERIAL_DELAY, SERIAL_CATCHUP queue it

taskFailPolicy

CONTINUE (default) / STOP pause the task on failure / RETRY retry (with taskRetryTimes, taskRetryInterval)

taskEnabled

Whether the task is enabled, default true

variables

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.

DBCLI tasks

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: taskScript is resolved against this run’s flow/<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 --port must be enabled; with port=-1 a DBCLI task fails with a clear message. Override with plugin-scheduler.dbcli.connect=jdbc:slackerdb://host:port/db when needed; a _connect inside 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 n changes 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 1 at the top of the script.

Variables: Passing Connection Information to HOP

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:

  1. data/scheduler/variables.properties (global)

  2. template directory proj1/conf/variables.properties

  3. the configJson field of the create-instance request

  4. the variables object 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).

Instance and Task Lifecycle
Operation Description

Create instance

Creates an isolated run directory (runs/<runId>/) from the template and loads its task list

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.

API Reference
Endpoint Description

GET /scheduler/status

Scheduler status

GET /scheduler/project/list, GET /scheduler/project/{projectType}

Template list / template details (including the parsed task list and warnings)

POST /scheduler/run/create

Create an instance

GET /scheduler/run/list, GET /scheduler/run/{runId}

Instance list / details

POST /scheduler/run/{runId}/start|stop|abort|drop

Start / stop / abort / drop an instance

POST /scheduler/run/{runId}/task/schedule

Schedule a single task

POST /scheduler/run/{runId}/task/start|stop|abort

Start / pause / abort a single task

GET /scheduler/run/{runId}/task/list

Task list: state, next fire time, last result, whether it is running

GET /scheduler/run/{runId}/task/history

Execution history

GET /scheduler/run/{runId}/log?taskName=&tail=200

Read task logs; without taskName it lists the log files

GET /scheduler/run/{runId}/variables?taskName=

Show variables (secrets masked)

GET /scheduler/describeCrontabExpr?expr=

Validate a cron expression and return the next 5 fire times

Notes
  • 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-run process (--project-locations, --environments, --in-memory). It therefore no longer depends on the hop-config.json it maintains in the run directory: parallel tasks cannot lose each other’s environment, a read-only hop-config.json is supported, and a failed hop-config.json update only logs a warning. Set plugin-scheduler.hop.inMemoryProject=false only 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=65001 and appends -Dfile.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8 to HOP_OPTIONS, so Chinese task names/values no longer garble the task log on Windows. SHELL output 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.json declares "parentProjectName": "default", a default/ project must exist under the template root and its own parentProjectName must be empty (a parent project is optional — in that case leave parentProjectName empty in the template itself); metadata/workflow-run-configuration/local.json must exist (it corresponds to the default runconfig local)

  • Termination is best-effort: timeouts and aborts terminate hop-run and 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

Plugin Management API

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.
/plugin/load (POST)

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.

Request body (JSON):
{
  "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 via plugins_dir); if plugins_dir is empty, a simple filename fails. A full path is loaded directly from that location and does not require plugins_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 in plugins_dir.

Response example (success):
{
  "retCode": 0,
  "retMsg": "Plugin loaded successfully",
  "pluginId": "myplugin"
}
Response example (error):
{
  "retCode": -1,
  "retMsg": "Plugin file does not exist: /path/to/plugins/myplugin.jar"
}
/plugin/unload (POST)

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.

Request body (JSON):
{
  "plugid": "myplugin"
}
Response example (success):
{
  "retCode": 0,
  "retMsg": "Plugin unloaded successfully"
}
/plugin/start (POST)

Starts a loaded plugin. The plugin’s start() method will be called, which triggers the plugin’s lifecycle hooks (beforeStart(), onStart(), afterStart()).

Request body (JSON):
{
  "plugid": "myplugin"
}
Response example (success):
{
  "retCode": 0,
  "retMsg": "Plugin started successfully"
}
/plugin/stop (POST)

Stops a running plugin. The plugin’s stop() method will be called, which triggers the plugin’s lifecycle hooks (beforeStop(), onStop(), afterStop()).

Request body (JSON):
{
  "plugid": "myplugin"
}
Response example (success):
{
  "retCode": 0,
  "retMsg": "Plugin stopped successfully"
}
/plugin/list (GET)

Lists all currently loaded plugins with their details.

Response example:
{
  "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.

Notes

  1. Thread safety – The plugin instance is a singleton during the server’s lifetime; ensure that methods like onStart() are thread‑safe.

  2. Resource management – Database connections obtained via getDbConnection() must be managed by the plugin itself; close them proactively.

  3. Dependency conflicts – Avoid introducing library versions that conflict with server dependencies; it is recommended to use the provided scope for libraries already provided by the server.

  4. Performance impact – Plugin execution consumes server resources; avoid performing long‑blocking operations in plugins.

Roadmap

  • dbdesk – planned… a web-based management console and application platform for datasets, dashboards, and data portals.

  • dbInstall – planned… a graphical deployment wizard.

…

About

Duckdb Postgres Proxy. (A postgres jdbc server with duckdb backend)

Topics

Resources

Stars

16 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages