import type { PluginId } from './identity.js'; import { OwnerScopedResourceHost, qualifyOwnedResourceName, } from './owner-scoped-resource-host.js'; import { createRootPrivateToken, createToken, scopeSetupFinalizer } from './token.js'; import { PluginStateStore, type PersistentStatePort } from './persistent-state.js'; import { generationAdmissionBinder, generationAdmissionSource, type GenerationAdmissionGate } from './admission.js'; import { OwnerOperation } from './owner-operation.js'; export interface DatabaseHostSelection { where(query: Record): DatabaseHostSelection; orderBy(field: string, direction?: 'ASC' | 'DESC'): DatabaseHostSelection; limit(count: number): DatabaseHostSelection; then[], TResult2 = never>( onfulfilled?: ((value: Record[]) => TResult1 | PromiseLike) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike) | null, ): Promise; } /** Fixed-table read-only grouped aggregates; no SQL, joins or table selection. */ export interface DatabaseHostAggregation extends PromiseLike[]> { min(field: string, alias?: string): DatabaseHostAggregation; max(field: string, alias?: string): DatabaseHostAggregation; groupBy(...fields: string[]): DatabaseHostAggregation; where(query: Record): DatabaseHostAggregation; } /** * select() 需要显式列名:'*' 在 SQL 方言里会被当成字面列名(no such column: "*"), * 类型层直接拒绝;运行时另有可读报错兜底(见 Host 实现)。 */ type SelectFields = { [K in keyof Fields]: Fields[K] extends '*' ? never : Fields[K]; }; /** * Minimal model surface shared by lottery / rss / group-suite memory stores * and the Host-backed `@zhin.js/database` adapter. */ export interface DatabaseHostModel { /** Optional SQL capability; lightweight and transaction models may omit it. */ aggregate?(): DatabaseHostAggregation; select(...fields: SelectFields): DatabaseHostSelection; insert(row: Record): Promise; delete(): { where(query: Record): Promise }; update(patch: Record): { where(query: Record): Promise; }; /** * DB 侧计数(聚合下推,避免为计数整表加载)。 * 可选:轻量 test/memory host 可不实现,调用方降级为 select 计数。 */ count?(where?: Record): Promise; } /** Callback-scoped transaction models; no raw SQL or administration access. */ export interface DatabaseHostTransaction { model(name: string): DatabaseHostModel; } export type DatabaseHostType = 'related' | 'document' | 'keyvalue'; export interface DatabaseHostTable { readonly name: string; readonly columns?: Readonly>; /** A physical table no code declared (created from the Console or left by a removed plugin). */ readonly discovered?: boolean; } /** Explicit, additive upgrades applied before SQL models become available. */ export interface DatabaseTableOptions { /** Names from this table's definition. Existing columns and data remain untouched. */ readonly addColumns?: readonly string[]; } export interface DatabaseHostSelectResult { readonly rows: readonly unknown[]; readonly total: number; readonly page: number; readonly pageSize: number; /** The ordering the Host applied (absent: unordered, or a Host without server-side sort). */ readonly orderBy?: DatabaseHostOrderBy; } /** Server-side ordering of a Console `db:select`. */ export interface DatabaseHostOrderBy { readonly column: string; readonly direction: 'asc' | 'desc'; } /** * What the Console database port supports beyond the base CRUD surface; a Host that reports no * capabilities supports none of these (older Hosts), and the Console falls back accordingly. */ export interface DatabaseHostConsoleCapabilities { /** `db:select` honours `orderBy` across the whole table. */ readonly sort: boolean; /** `where` operators `db:select` accepts per column (`$eq`, `$ne`, `$gt`, …). */ readonly filterOperators: readonly string[]; /** `db:query` (read-only) and `db:execute` (write); both need `ops.database.schema`. */ readonly sql: boolean; /** `db:schema:*` structured schema editor. */ readonly schema: boolean; /** Why `sql` / `schema` are unavailable (non-relational dialect; also repeats `sqlReason`). */ readonly reason?: string; /** * Why raw SQL (`sql`) is off while the schema editor may still work: no restricted account on * PostgreSQL / MySQL (`zhin db console-role`), a failed account probe, or a server that reads * SQL text differently from the Console (ADR 0059 §4). */ readonly sqlReason?: string; /** * Machine-readable kind of `sqlReason`: `console-role-missing` (no `database.console`), * `console-role-invalid` (the account cannot log in or holds too much), `text-compatibility` * (the server reads SQL text differently), `sqlite-isolation` (in-memory SQLite). */ readonly sqlReasonCode?: 'console-role-missing' | 'console-role-invalid' | 'text-compatibility' | 'sqlite-isolation'; /** * What keeps raw SQL away from the gateway's data (ADR 0059): `separate-store` (SQLite — the * accounts are in `.zhin/gateway.db`, which this connection cannot ATTACH) or * `restricted-credential` (PostgreSQL / MySQL — raw SQL logs in as a restricted account). */ readonly sqlIsolation?: 'separate-store' | 'restricted-credential'; } export interface DatabaseHostQueryResult { readonly columns: readonly string[]; readonly rows: readonly Record[]; readonly rowCount: number; /** More rows existed than the cap; only the first `rows.length` are returned. */ readonly truncated: boolean; readonly durationMs: number; } export interface DatabaseHostExecuteResult { readonly statements: readonly { readonly sql: string; /** Rows changed (DML) when the driver reports it. */ readonly affected?: number; /** Rows returned (statements with a result set). */ readonly rows?: number; }[]; /** True when the run was rolled back on purpose (`dryRun`). */ readonly dryRun: boolean; /** The dry run could not be rolled back safely for these statements, so it did not run them. */ readonly estimateUnavailable?: boolean; readonly durationMs: number; } export type DatabaseHostColumnType = 'text' | 'integer' | 'bigint' | 'float' | 'boolean' | 'date' | 'json'; export interface DatabaseHostColumnSpec { readonly name: string; readonly type: DatabaseHostColumnType; readonly nullable?: boolean; readonly default?: string | number | boolean | null; readonly primary?: boolean; readonly autoIncrement?: boolean; readonly unique?: boolean; readonly length?: number; } export type DatabaseHostSchemaChange = | { readonly kind: 'create-table'; readonly table: string; readonly columns: readonly DatabaseHostColumnSpec[] } | { readonly kind: 'add-column'; readonly table: string; readonly column: DatabaseHostColumnSpec } | { readonly kind: 'rename-column'; readonly table: string; readonly column: string; readonly to: string } | { readonly kind: 'drop-column'; readonly table: string; readonly column: string } | { readonly kind: 'alter-column'; readonly table: string; readonly column: string; readonly type?: DatabaseHostColumnType; readonly nullable?: boolean; readonly default?: string | number | boolean | null; readonly dropDefault?: boolean; } | { readonly kind: 'create-index'; readonly table: string; readonly name: string; readonly columns: readonly string[]; readonly unique?: boolean } | { readonly kind: 'drop-index'; readonly table: string; readonly name: string }; export interface DatabaseHostSchemaPlan { readonly change: DatabaseHostSchemaChange; /** The exact DDL `applySchema` runs. */ readonly statements: readonly string[]; /** Loses data or an object: apply needs `confirm`. */ readonly destructive: boolean; /** Name the operator must type to apply a destructive change. */ readonly confirm?: string; /** Stable warning codes (`data_loss`, `type_change_may_fail`, …). */ readonly warnings: readonly string[]; } export interface DatabaseHostTableSchema { readonly table: string; readonly columns: readonly { readonly name: string; /** Zhin column type (best effort for physical types). */ readonly type: string; readonly nativeType: string; readonly nullable: boolean; readonly primary: boolean; readonly defaultSql?: string; }[]; readonly indexes: readonly { readonly name: string; readonly columns: readonly string[]; readonly unique: boolean; readonly primary: boolean; }[]; } /** Root-only database administration surface used by Console RPC. */ export interface DatabaseHostConsole { info(): { readonly dialect: string; readonly type: DatabaseHostType; readonly tables: readonly string[]; readonly connected: boolean; readonly capabilities?: DatabaseHostConsoleCapabilities; }; tables(): readonly DatabaseHostTable[]; select( table: string, page: number, pageSize: number, where?: Record, orderBy?: DatabaseHostOrderBy, ): Promise; /** One read statement (`ops.database.schema`) in a read-only transaction, capped at `maxRows`. */ query?(sql: string, options?: { readonly maxRows?: number; readonly timeoutMs?: number }): Promise; /** SQL text with literal values replaced by `'…'` (audit log), lexed by the dialect. */ redactSql?(sql: string): string; /** Write statements (`ops.database.schema`); `dryRun` runs them in a transaction and rolls back. */ execute?(sql: string, options?: { readonly dryRun?: boolean; readonly timeoutMs?: number }): Promise; describe?(table: string): Promise; previewSchema?(change: unknown): Promise; /** Re-plans `change` and runs it; destructive plans need `confirm` equal to `plan.confirm`. */ applySchema?(change: unknown, confirm?: string): Promise; insert(table: string, row: Record): Promise; update( table: string, row: Record, where: Record, ): Promise; delete(table: string, where: Record): Promise; dropTable(table: string): Promise; kvGet(table: string, key: string): Promise; kvSet(table: string, key: string, value: unknown, ttl?: number): Promise; kvDelete(table: string, key: string): Promise; kvEntries(table: string): Promise; } /** * Thin Host Resource for Plugin Runtime persistence. * Plugins call `define` during `setup()`; Host starts the dialect on generation * `activateNext` so models are available before commands / cron run. */ export interface DatabaseHost { /** Small-object persistence with database-level compare-and-swap. */ readonly state?: PersistentStatePort; readonly dialect: string; readonly started: boolean; /** Register a table schema before `start` (column defs match `@zhin.js/database`). */ define(name: string, definition: Record, options?: DatabaseTableOptions): void; /** Names of tables registered via `define` (Console `db:tables`). */ tables(): readonly string[]; models: { get(name: string): DatabaseHostModel | undefined; }; /** Atomic SQL operations. The callback must await all operations before returning. */ transaction?(callback: (transaction: DatabaseHostTransaction) => Promise): Promise; /** Root-only management port; absent on lightweight test/memory hosts. */ readonly console?: DatabaseHostConsole; /** * Raw `@zhin.js/database` registry (full `create` / `select` API). * Available after `start()` — used by Agent Host ADR 0009 persistence. */ getRawDatabase(): { models?: Map } | undefined; start(): Promise; stop(): Promise; } /** * Persistence surface visible to a plugin. Names are logical to the owner; * the Runtime maps them to private physical table names before they reach the * process-wide DatabaseHost. */ /** * Maps a plugin's logical resource name to its process-wide physical name. * Every owner, including the root plugin, uses the same private namespace. */ export function qualifyPluginResourceName(owner: PluginId, name: string): string { return qualifyOwnedResourceName(owner, name); } /** Owner-bound persistence facade without Console administration or raw DB access. */ export class PluginDatabaseHost extends OwnerScopedResourceHost { readonly models: { get(name: string): DatabaseHostModel | undefined }; readonly #host: DatabaseHost; readonly #admission?: GenerationAdmissionGate; readonly #operation: OwnerOperation; constructor(owner: PluginId, host: DatabaseHost, admission?: GenerationAdmissionGate) { super(owner); this.#host = host; this.#admission = admission; this.#operation = new OwnerOperation(admission, 'Database'); this.models = Object.freeze({ get: (name: string) => this.#operation.setup(() => { const model = this.#host.models.get(this.qualify(name)); return model ? this.#bindModel(model) : undefined; }) }); } get state(): PluginStateStore { if (!this.#host.state) throw new Error('Persistent state requires a configured database with atomic state support'); return new PluginStateStore(super.owner, this.#host.state, undefined, this.#admission); } /** @internal Bound by generation publication, never a plugin authoring operation. */ [generationAdmissionBinder](gate: GenerationAdmissionGate): PluginDatabaseHost { const facade = new PluginDatabaseHost(super.owner, this.#host, gate); facade[scopeSetupFinalizer](); return facade; } /** @internal Scope-owned declaration window. */ [scopeSetupFinalizer](): void { this.#operation.endSetup(); } /** @internal Admission source collected by the Runtime. */ get [generationAdmissionSource](): readonly GenerationAdmissionGate[] { return this.#admission ? [this.#admission] : []; } get dialect(): string { return this.#host.dialect; } get started(): boolean { return this.#host.started; } define(name: string, definition: Record, options?: DatabaseTableOptions): void { this.#operation.setup(() => options === undefined ? this.#host.define(this.qualify(name), definition) : this.#host.define(this.qualify(name), definition, options)); } tables(): readonly string[] { return this.#operation.setup(() => Object.freeze(this.#host.tables().flatMap((name) => { const logical = this.unqualify(name); return logical === undefined ? [] : [logical]; }))); } async transaction(callback: (transaction: DatabaseHostTransaction) => Promise): Promise { if (!this.#host.transaction) throw new Error('Database Host does not support transactions'); return this.#execute(() => this.#host.transaction!(async transaction => { let active = true; const requireActive = () => { if (!active) throw new Error('Database transaction is already closed'); }; try { return await callback(Object.freeze({ model: (name: string) => { requireActive(); // Reuse the ordinary facade so qualification and generation checks stay identical. const model = transaction.model(this.qualify(name)); const guarded = guardTransactionModel(model, requireActive); return this.#bindModel(guarded); } })); } finally { active = false; } })); } #bindSelection(selection: DatabaseHostSelection): DatabaseHostSelection { const modify = (operation: () => DatabaseHostSelection): DatabaseHostSelection => this.#operation.setup(() => { const next = operation(); return next === selection ? chain : this.#bindSelection(next); }); const chain: DatabaseHostSelection = { where: (query) => modify(() => selection.where(query)), orderBy: (field, direction) => modify(() => selection.orderBy(field, direction)), limit: (count) => modify(() => selection.limit(count)), then: (fulfilled, rejected) => this.#execute(() => Promise.resolve(selection)).then(fulfilled, rejected), }; return Object.freeze(chain); } #bindAggregation(aggregation: DatabaseHostAggregation): DatabaseHostAggregation { const modify = (operation: () => DatabaseHostAggregation): DatabaseHostAggregation => this.#operation.setup(() => { const next = operation(); return next === aggregation ? chain : this.#bindAggregation(next); }); const chain: DatabaseHostAggregation = { min: (field, alias) => modify(() => aggregation.min(field, alias)), max: (field, alias) => modify(() => aggregation.max(field, alias)), groupBy: (...fields) => modify(() => aggregation.groupBy(...fields)), where: query => modify(() => aggregation.where(query)), then: (fulfilled, rejected) => this.#execute(() => Promise.resolve(aggregation)).then(fulfilled, rejected), }; return Object.freeze(chain); } #bindModel(model: DatabaseHostModel): DatabaseHostModel { const count = model.count?.bind(model), aggregate = model.aggregate?.bind(model); return Object.freeze({ select: (...fields: SelectFields) => this.#operation.setup(() => this.#bindSelection(model.select(...fields))), insert: (row) => this.#execute(() => model.insert(row)), delete: () => this.#operation.setup(() => Object.freeze({ where: (query: Record) => this.#execute(() => model.delete().where(query)), })), update: (patch) => this.#operation.setup(() => Object.freeze({ where: (query: Record) => this.#execute(() => model.update(patch).where(query)), })), ...(count ? { count: (query?: Record) => this.#execute(() => count(query)) } : {}), ...(aggregate ? { aggregate: () => this.#operation.setup(() => this.#bindAggregation(aggregate())) } : {}), } satisfies DatabaseHostModel); } async #execute(operation: () => Promise): Promise { return this.#operation.run(operation); } } /** A saved query/model cannot escape the callback and reuse the transaction. */ export function guardTransactionModel(model: DatabaseHostModel, check: () => void): DatabaseHostModel { const selection = (source: DatabaseHostSelection): DatabaseHostSelection => ({ where(query) { check(); return selection(source.where(query)); }, orderBy(field, direction) { check(); return selection(source.orderBy(field, direction)); }, limit(count) { check(); return selection(source.limit(count)); }, then(resolve, reject) { return Promise.resolve().then(() => { check(); return source; }).then(resolve, reject); }, }); const aggregation = (source: DatabaseHostAggregation): DatabaseHostAggregation => ({ min(field, alias) { check(); return aggregation(source.min(field, alias)); }, max(field, alias) { check(); return aggregation(source.max(field, alias)); }, groupBy(...fields) { check(); return aggregation(source.groupBy(...fields)); }, where(query) { check(); return aggregation(source.where(query)); }, then(resolve, reject) { return Promise.resolve().then(() => { check(); return source; }).then(resolve, reject); }, }); return { select: (...fields: SelectFields) => { check(); return selection(model.select(...fields)); }, ...(model.aggregate ? { aggregate: () => { check(); return aggregation(model.aggregate!()); } } : {}), insert: async row => { check(); return model.insert(row); }, update: patch => { check(); return { where: async query => { check(); return model.update(patch).where(query); } }; }, delete: () => { check(); return { where: async query => { check(); return model.delete().where(query); } }; }, }; } /** * Plugin-facing scoped persistence token. Runtime replaces this binding for * every Plugin Scope; plugin code must never receive the process-wide host. * The owner encoding keeps `root/a` and `root/a/b` disjoint, so a parent * facade cannot accidentally enumerate a descendant's tables. */ /** @public Plugin-facing database facade bound to the current owner. */ export const databaseHostToken = createToken( 'zhin.database.host', 'Plugin Runtime scoped database host', ); /** Root-only process host for CLI composition and Console administration. */ export const databaseRootHostToken = createRootPrivateToken( 'zhin.database.root-host', 'Plugin Runtime root database host', );