Skip to main content

Built and signed on GitHub Actions

Works with
This package works with DenoIt is unknown whether this package works with Cloudflare Workers, Node.js, Bun, Browsers
It is unknown whether this package works with Cloudflare Workers
It is unknown whether this package works with Node.js
This package works with Deno
It is unknown whether this package works with Bun
It is unknown whether this package works with Browsers
•JSR Score100%•
License
Apache-2.0
•
Downloads292/wk
•
Publisheda day ago (0.0.10)

The database integration layer for NetScript: one provider-agnostic adapter contract plus Prisma v7 driver adapters for PostgreSQL, SQL Server, and MySQL, with connection-string helpers, JSON extensions, and OpenTelemetry tracing.

@netscript/database

JSR CI Docs

The database integration layer for NetScript: one provider-agnostic adapter contract plus Prisma v7 driver adapters for PostgreSQL, SQL Server, and MySQL, with connection-string helpers, JSON extensions, and OpenTelemetry tracing.

Running Prisma on Deno means picking a driver adapter per backend, wiring its lifecycle, and re-solving the same JSON-serialization and tracing questions in every service. @netscript/database answers them once: a DatabaseAdapter contract that every backend implements identically, factories that wrap the official Prisma v7 driver adapters, and helpers for the plumbing around them — building and parsing connection strings, serializing JSON fields across SQL backends, and emitting Prisma OpenTelemetry spans.

The package owns the reusable integration layer only. Your data model, migrations, and generated Prisma client stay in the application or plugin that owns them — the adapter takes the client you built and manages connect, health, and disconnect around it.

Why teams use it

  • One contract, four providers — DatabaseAdapter and DatabaseAdapterFactory define a single connect / disconnect / health-check / raw-query interface across postgres, mssql, mysql, and sqlite, so call sites never branch on the backend.
  • Prisma v7 driver adapters included — createPostgresAdapter at @netscript/database/adapters/postgres, with SQL Server and MySQL siblings behind their own sub-paths, wrap the official Prisma driver adapters and hand them to Prisma Client via getDriverAdapter().
  • Focused sub-path exports — a Postgres-only consumer never pulls the SQL Server or MySQL drivers into its module graph; each backend lives behind its own export.
  • Connection-string helpers — buildPostgresConnectionString, buildMssqlConnectionString, and parseConnectionString assemble and parse provider URLs from typed parts instead of string concatenation.
  • JSON fields and tracing solved once — registerJsonFields / jsonUtils handle JSON serialization uniformly across SQL backends, and enableInstrumentation turns on Prisma OpenTelemetry spans when OTEL_DENO=true.
  • Contract tests included — runDatabaseAdapterContract and createMockDatabaseAdapter from @netscript/database/testing prove a custom adapter against the same contract the first-party adapters pass.

Install

deno add jsr:@netscript/database@<version>

Pin <version> to match your installed CLI; bare jsr:@netscript/* specifiers do not resolve on the pre-release line.

Quick example

Prerequisites: a running PostgreSQL server and a generated Prisma client for your schema — the adapter wraps the client you supply; it does not generate one.

import { createPostgresAdapter } from '@netscript/database/adapters/postgres';

// In your app this is the generated client:
//   import { PrismaClient } from './generated/client/mod.ts';
declare const PrismaClient: new (options: { adapter: unknown }) => {
  $connect(): Promise<void>;
  $disconnect(): Promise<void>;
  $queryRaw: unknown;
  $queryRawUnsafe: unknown;
  $executeRaw: unknown;
  $executeRawUnsafe: unknown;
};

const adapter = createPostgresAdapter({
  connectionString: 'postgresql://app:secret@localhost:5432/app',
});

const prisma = new PrismaClient({ adapter: adapter.getDriverAdapter() });
adapter.setClient(prisma);

await adapter.connect();
const healthy = await adapter.healthCheck();
await adapter.disconnect();

In a scaffolded NetScript project, netscript db init generates this wiring for you — the manual form above is for custom hosts and tests.

Normalize PostgreSQL connection strings

Both PostgreSQL URI schemes pass through unchanged, including TLS query parameters. For Npgsql key/value strings, use the Postgres adapter helper before constructing a client:

import { normalizePostgresConnectionString } from '@netscript/database/connection-strings/postgres';

const url = normalizePostgresConnectionString(
  'Host=localhost;Database=app;Username=app;Password=secret;SSL Mode=VerifyFull',
);
// postgres://app:secret@localhost:5432/app?sslmode=verify-full

The helper maps Disable, Prefer, Require, VerifyCA, and VerifyFull to their PostgreSQL sslmode values. The libpq spellings verify-ca and verify-full are also accepted, and all mode values are case-insensitive. Decimal ports are canonicalized (Port=05432 becomes :5432). Credentials and database names are percent-encoded. Quoted values may contain semicolons and equals signs, and doubled quotes escape the enclosing quote. Missing endpoint and credential fields use the scaffold defaults: localhost:5432, database/user postgres, and an empty password. Omitting SSL Mode leaves the driver's TLS defaults in effect.

Repeated keys are refused, including case variants, aliases (such as Host/Server, Database/DB, Username/User ID/UID, Password/Pwd, and SSL Mode/SslMode), and identical repeated values. They throw PostgresConnectionStringError with reason duplicate-key and the canonical lowercase key (for example, sslmode), before an option can overwrite an earlier setting.

Unsupported keys (including certificate options), unsupported values (including SSL Mode=Allow), and malformed input also throw PostgresConnectionStringError. Their reasons are unsupported-key, unsupported-value, and invalid-format; the optional key identifies the refused option. Messages never include option values or credentials. The scaffolded Postgres module and Prisma config use generated inline code from this same helper, with no runtime package import in Prisma config. The scaffold wrapper trims environment values before calling the helper.

Public surface

Entry What it gives you
. The DatabaseAdapter contract, createPostgresAdapter, connection-string helpers, jsonUtils
./ports Contract types only (DatabaseAdapter, DatabaseAdapterFactory, provider and status types)
./adapters/postgres PostgresAdapter over the official Prisma pg driver adapter
./adapters/mssql SQL Server adapter over the official Prisma mssql driver adapter
./adapters/mysql MySQL/MariaDB adapter over @netscript/prisma-adapter-mysql
./extensions JSON field registry and serialization utilities
./tracing enableInstrumentation for Prisma OpenTelemetry spans
./commands Bound command port, logical rows, store errors and true callback-client boundary
./commands/postgres createPostgresCommandStore and createPostgresCommandOutboxRelayStore over the consumer-owned schema and callback bridge
./testing runDatabaseAdapterContract, createMockDatabaseAdapter

The always-current symbol list is deno doc jsr:@netscript/database@<version> (pin <version> on the pre-release line, as above).

Docs

Compatibility

Designed for Deno with Prisma v7 driver adapters; database connections need --allow-net (plus --allow-env for environment-based configuration). Tracing activates only when OTEL_DENO=true.

License

Apache-2.0 — see LICENSE. Published to JSR with cryptographically verified provenance.

Command persistence contracts

@netscript/database/commands owns CommandStorePort<TTx> and CommandTransaction<TTx>, capability declarations, transaction requests and logical receipt/audit/outbox rows. A provider constructs all delegates from the actual transaction callback. Root lifecycle and nested transaction methods stay outside the business handle. The boundary invokes work once; a busy claim requires rollback before an error surfaces. A capability declaration validates and freezes metadata; it cannot certify an adapter's physical guarantees. This contract subpath requires no permissions.

CommandStoreError and CommandStoreFailure provide database-owned bounded provider failure classification. Adapters classify acquisition, driver and boundary failures themselves; driver codes/messages stay solely in the trusted cause. The service translates this class and preserves arbitrary callback business errors. busy remains a terminal receipt-claim result requiring rollback, rather than a retry of the transaction callback.

True callback client and schema ownership

withTransaction(root, work) preserves a separate callback type through TransactionClientPort<TTx>. Bind Prisma through its actual callback; never assert a root client into the business handle. Consumers generate CommandTransactionClient = Omit<Prisma.TransactionClient, '$transaction' | '$connect' | '$disconnect' | '$on' | '$use' | '$extends'>.

The reviewed schema, migration and bridge samples in tests/fixtures/command-store/ show the consumer-owned receipt unique key, completion check, audit fields and initial outbox lease fields. Generate a Prisma client and bind the callback explicitly. Apply the migration through the application's normal review workflow. CLI generation is deferred to RFC 0003 stage 8; importing the framework never creates tables or runs a migration.

PostgreSQL command store

Import createPostgresCommandStore from @netscript/database/commands/postgres, pass the consumer's generated callback bridge, and configure transactionTimeoutMs. The store supports PostgreSQL ReadCommitted, ReadUncommitted (PostgreSQL treats it as ReadCommitted), RepeatableRead and Serializable. Receipt wait is an integer from 1 to 60,000 milliseconds; zero would disable PostgreSQL lock_timeout and is refused. The timeout is finite and cancellation is cooperative.

Claims use the reviewed unique key with INSERT ... ON CONFLICT DO NOTHING RETURNING, then one indexed winner select. Successful claims restore the previous transaction-local lock timeout. A lock timeout produces terminal busy, rolls back the complete callback, and forbids subsequent side-record calls. Serialization/deadlock errors are retryable provider failures; the callback is never retried automatically. Each owned receipt must complete before commit. All audit/outbox SQL derives from the callback client; root business/lifecycle operations are refused.

Prisma currently exposes nested transactions on its callback proxy. The consumer bridge sample hides root operations at runtime as well as in the generated alias. It preserves model delegates and uses the actual provider transaction for every side record. Table mappings match the reviewed sample migration; explicit mapping changes require a reviewed adapter/bridge migration.

bash .llm/tools/command-postgres-conformance.sh runs the native generated-client provider gate with an isolated temporary Unix socket. The dedicated CI workflow uses Deno 2.9.8. A suite skipped without provider configuration never certifies PostgreSQL support. No database credentials, connection addresses or operational evidence belong in the public run artifacts.

PostgreSQL command outbox relay

createPostgresCommandOutboxRelayStore from @netscript/database/commands/postgres binds the same true generated callback bridge, with an explicit finite transaction timeout. CommandOutboxRelayStore from @netscript/database/commands is raw storage: it owns bounded due-row claims, live generation/expiry fencing, retry/terminal retention, and one atomic publication plus normalized acceptance write. It imports no queue, service or worker package and runs no migration on construction or invocation.

Apply the reviewed tests/fixtures/command-store/relay-acceptance-migration.sql through your consumer's migration workflow when upgrading the C3 table. The complete schema/migration fixture already contains paired acceptanceIdentity/acceptedAt columns. Claims require an explicit clock instant, opaque fresh claimToken, 1–64 rows and a 1–60,000 millisecond lease. Publication and release compare row identity, current token, unexpired lease, unpublished and nonterminal state. Release's now is the actual current instant, distinct from retryAt. Retry clears ownership and advances availability; terminal retains the row; neither changes message ID or dedupe key. Worker receipts persist only normalized identity/time, never raw transport responses.

The generic relay acknowledges after the sink's documented acceptance boundary. A crash after acceptance and before settlement redelivers the same stable key. A lease expiration fences settlement even if nobody has claimed the row again. Consumer operations must remain idempotent; this is at-least-once delivery. The native PostgreSQL gate runs both command-store and relay-store generated-client conformance and owns its provider cleanup. Supplied provider operations need consumer-owned network permissions; framework construction needs none.

Outbox maintenance

The PostgreSQL relay store also exposes pruneSettled({ now, limit, completedRetentionDays, afterId }). The default window is seven days and a page examines/deletes at most 100 primary-key rows, including retained rows. Persist nextAfterId until the sweep finishes. Only expired published/terminal rows with no lease are deleted, with eligibility rechecked at deletion. The saga plugin installs the outbox schema and SQL CHECK sidecar; normal migration tooling appends pending SQL before deploying. For atomic saga keys, compose createPrismaSagaCommandRetention from the saga stores subpath. See the outbox reference.

Examples

Basic Usage with Adapters

import { createPostgresAdapter } from '@netscript/database/adapters/postgres';
import { createMssqlAdapter } from '@netscript/database/adapters/mssql';
import { PrismaClient } from '@database';

declare const pgUrl: string;
declare const mssqlUrl: string;

// PostgreSQL
const pgAdapter = createPostgresAdapter({ connectionString: pgUrl });
const pgClient = new PrismaClient({ adapter: pgAdapter.getDriverAdapter() });

// SQL Server
const mssqlAdapter = createMssqlAdapter({ connectionString: mssqlUrl });
const mssqlClient = new PrismaClient({ adapter: mssqlAdapter.getDriverAdapter() });
Built and signed on
GitHub Actions