# PostgreSQL storage for Pi Durable

## Schema setup

Export the adapter's tables, sequence, and enums from a schema file that Drizzle Kit
loads, such as `database/pi-schema.ts`. The export names below also let you use
Drizzle's relational queries.

```ts
import { createCentralPiSchemas } from 'central-pi-durable/schema'

export const {
  central_pi_conversations: conversations,
  central_pi_entries: entries,
  central_pi_tasks: tasks,
  central_pi_submissions: submissions,
  central_pi_documents: documents,
  central_pi_document_revisions: document_revisions,
  central_pi_record_ids: record_ids,
  central_pi_id_counters: id_counters,
  central_pi_commit_seq,
  central_pi_record_type,
  central_pi_document_revision_kind
} = createCentralPiSchemas().schemas
```

Include that file in your Drizzle Kit `schema` paths. Generate and apply your
application's migration before opening the first harness.

## Open a harness

Pass your application's Drizzle database to `centralDB`. For a writable harness,
use a connection on which the adapter can commit its own transactions.

```ts
import { Harness } from '@earendil-works/pi-durable'
import { centralDB, CentralStorage } from 'central-pi-durable'

const storage = new CentralStorage(centralDB(db), 'research')
const harness = await Harness.open(storage, { models, registry, env }, context)
```

The instance ID (`research`) identifies one harness's records. Give each independent
harness its own ID and reuse it on reopen. An ID must be well-formed Unicode
without NUL. Open only one writable harness per instance. Finish pending work
and call `await harness.close(context)` before closing the database client.

The table prefix defaults to `central_pi`. For a separate set of tables, pass the
same prefix to `createCentralPiSchemas(prefix)` and `centralDB(db, prefix)`, and
use that prefix in the schema file's destructuring keys.

## Query records with Drizzle

If your application reads the tables directly, filter by `instance_id`. For
queries with related records, register the relations when creating the Drizzle
database. This example reads the entries stored under each conversation.

```ts
import { buildCentralPiRelations } from 'central-pi-durable/relations'
import { defineRelations } from 'drizzle-orm'
import { drizzle } from 'drizzle-orm/node-postgres'
import * as schema from './database/pi-schema.js'

const relations = defineRelations(schema, buildCentralPiRelations)
const db = drizzle({ connection: connectionString, relations })

const conversations = await db.query.conversations.findMany({
  where: { instance_id: 'research' },
  with: { entries: true }
})
```

Use the storage API for fork-visible entries or for a document's value at a
point in its history. Rewindable documents support past reads. Current-only
documents support current reads.

## IDs and commits

Each instance reserves 42 record IDs at a time. Unused IDs stay reserved across
restarts, so gaps are normal. To change the reservation size, pass
`{ idSlotSize: 100 }` as the third argument to `CentralStorage`.

A commit processes batches in order and returns `{ kind: 'stored', stored }`
when all batches succeed. If a batch is refused, the result is
`{ kind: 'refused', stored, refused }`, where `stored` counts the earlier
batches that committed and `refused` gives the reason. Storage acknowledges
each accepted batch after commit. A database error rolls back the transaction.
[Commit validation](validation.md)
