Database Adapters
Understand the collaboration persistence contract and choose between Memory, SQLite, PostgreSQL, and custom Database Adapters.
A Database Adapter persists the core collaboration data that Collaboration Service manages. The Service owns the Unit, OT, and revision semantics, and the Adapter turns those semantics into atomic storage operations that are safe to retry. To connect a database that is not covered by the built-in Adapters, implement IDatabaseAdapter and satisfy its complete behavioral contract.
Database Adapters are open source under Apache-2.0. The source code is available in univer-collaboration-sdk-community, and the packages use the same names and versions as every other package.
Verify persistence
Stop Quick Start and run pnpm example:database-adapter from the repository root. Open http://127.0.0.1:3010/?unit=persistent-sheet, change a cell, and confirm the change in a second browser. Then stop the server, run the same command again, and reopen the same URL. The value should still be present.
The example server stores data in examples/database-adapter/.data/collaboration.sqlite.
What an adapter stores
The Adapter stores three kinds of data for each collaborative document (Unit).
- The Unit record stores the document ID, type, creator, creation time, and current revision (
headRevision). When the Adapter commits a change, it saves the changeset and updates the revision in the same operation. The application can useUnitRecord.metadatato store and maintain its own document fields, such as the document name (name), the last editor’s ID (lastEditorID), and the last modification time (lastModifiedAt). - Snapshots capture the document content at a particular revision. To read a specific revision, the Service can load the latest snapshot at or before that revision and replay the changes up to the requested revision. For spreadsheets, the Adapter also stores the data blocks referenced by the snapshot.
- Changesets group the operations in each submission. The Adapter stores changesets in revision order and preserves the submission identifiers
sidandreqIdso the Service can recognize a client retry and avoid applying the same edit twice.1 The application can useChangesetRecord.metadatato store its own information about a submission, such as the source of the edit (source) or a related business operation ID (operationId).
For details on setting metadata during creation and submission, see Middleware and Events.
Soft deletion preserves this data so editing can resume after recovery. After permanent deletion, the document data is inaccessible and the document ID cannot be reused.
The application manages users, roles, and access permissions. History, Thread Comment, and Worktree each use a separate Adapter interface.
Adapter read and write requirements
A custom IDatabaseAdapter must meet the following requirements for each operation.
| Operation | Requirement |
|---|---|
| Create a Unit | Save the Unit record (including its metadata), the initial snapshot, and its Sheet blocks atomically so they become readable together. |
| Commit a changeset | Commit only if the Unit’s current revision matches the expected revision (CAS)2. In one atomic write, save the changeset with its metadata, replace the Unit metadata in full, and increment the revision by one. On a mismatch, return the current revision without writing any data. |
| Read changesets | Return the changesets in the requested range in ascending revision order, with no gaps. Preserve each changeset’s original sid and reqId so the Service can recognize duplicate submissions for the same Unit. |
| Save a snapshot | When the snapshot becomes readable, every Sheet block it references must also be readable. |
| Delete or recover Units | Apply the operation to the entire batch. If any item fails, leave the whole batch unchanged. |
Memory adapter
@univerjs-pro/collaboration-database-memory runs inside the Node.js process. It is suitable for:
- unit and integration tests
- temporary development environments
- quick checks of custom Middleware or Client assembly
import { MemoryDatabaseAdapter } from "@univerjs-pro/collaboration-database-memory";import { UniverCollabService } from "@univerjs-pro/collaboration-service";const database = new MemoryDatabaseAdapter();const service = new UniverCollabService({ dbAdapter: database });The Memory Adapter follows the same revision, CAS, and idempotency contract as the persistent implementations. Its data exists only in the current Node.js process and is lost when that process exits.
SQLite adapter
@univerjs-pro/collaboration-database-sqlite stores data in a SQLite file. It is suitable for development, testing, local applications, and small-scale use.
import { mkdir } from "node:fs/promises";import { SQLiteDatabaseAdapter } from "@univerjs-pro/collaboration-database-sqlite";import { UniverCollabService } from "@univerjs-pro/collaboration-service";await mkdir("./data", { recursive: true });const database = new SQLiteDatabaseAdapter({ filename: "./data/collaboration.sqlite", busyTimeoutMs: 5_000,});const service = new UniverCollabService({ dbAdapter: database });It initializes the schema when the database is empty and only verifies the schema when it already exists. The file location, the backup method, and any other SQLite settings are decided by the application.
PostgreSQL adapter
@univerjs-pro/collaboration-database-postgres stores all core collaboration data in PostgreSQL, including the cell data blocks referenced by Sheet snapshots. Multiple collaboration nodes can share the same database.
import { PostgresDatabaseAdapter } from "@univerjs-pro/collaboration-database-postgres";import { UniverCollabService } from "@univerjs-pro/collaboration-service";import { Pool } from "pg";const pool = new Pool({ connectionString: process.env.DATABASE_URL });const database = await PostgresDatabaseAdapter.create({ pool });const service = new UniverCollabService({ dbAdapter: database });The application owns the pool and closes it after disposing the Service. create() initializes the collaboration schema in an empty database and only verifies an existing schema.
If S3-compatible object storage is available, we recommend the PostgreSQL + S3 Adapter to keep the database and its backups smaller.
PostgreSQL + S3 adapter
@univerjs-pro/collaboration-database-postgres-s3 stores Sheet cell data blocks in an S3-compatible bucket. PostgreSQL holds the Units, changesets, snapshot records, and block references.
Cell data makes up most of a large workbook’s snapshot. Storing these blocks in S3 keeps the PostgreSQL database and its backups smaller. As workbooks grow, block storage can scale independently of the database.
Set DATABASE_URL to the database connection string, S3_REGION to the bucket’s region, and S3_BUCKET to the name of an existing bucket.
import { S3Client } from "@aws-sdk/client-s3";import { PostgresS3DatabaseAdapter } from "@univerjs-pro/collaboration-database-postgres-s3";import { UniverCollabService } from "@univerjs-pro/collaboration-service";import { Pool } from "pg";const pool = new Pool({ connectionString: process.env.DATABASE_URL });const client = new S3Client({ region: process.env.S3_REGION });const database = await PostgresS3DatabaseAdapter.create({ pool, s3: { client, bucket: process.env.S3_BUCKET! },});const service = new UniverCollabService({ dbAdapter: database });Custom database adapters
A custom Adapter is usually appropriate in the following cases:
- the application already uses MySQL or another business database
- collaboration submissions must use database mechanisms that the application owns
- operational or compliance requirements exceed the scope of the built-in Adapters
Implement IDatabaseAdapter and inject it into the Service in the same way as a built-in Adapter:
const database = new ApplicationCollaborationDatabase({ pool });const service = new UniverCollabService({ dbAdapter: database });The Service does not depend on a specific database, but it cannot add transactions, CAS, or deduplication to a custom implementation. The Adapter must implement the complete contract using the capabilities that its database provides. The built-in implementations in the community repository apply the same contract to different databases and serve as references.
How to store business data
Use metadata for information attached to a document or changeset. The application can set these fields when it creates a document or submits a changeset, and the built-in Adapters save them together with the collaboration data. See Middleware and Events.
Use Middleware or Events to write to separate business tables. To audit an attempted operation, write to an audit table in Middleware. To update a business table after a successful commit, listen for changesetCommitted. By default, these writes run outside the collaboration transaction. A revision conflict can cause commit-stage Middleware to run again, so a retry must not create a duplicate record. Events are delivered within the process on a best-effort basis. Use them for data the application can backfill or rebuild.
Use a custom Database Adapter when the application needs its own database and schema, or when business and collaboration data must be written in one transaction. When calling the Service, the application can pass context such as a business operation ID in customData. The Adapter can then read the fields it needs from ctx.customData and decide which tables to update. For example, commitChangeset() can use the operation ID to update the corresponding business record in the same transaction that saves the changeset.
customData is scoped to the current call. Built-in Adapters do not persist its fields automatically, and they do not use them to write to business tables.
Storage for extension modules
Extension modules such as History, Thread Comment, Worktree, and File each define an independent Database Adapter interface. Their Adapters can share one database or use separate storage. A single custom implementation can also provide several Adapter interfaces and be injected into the corresponding Services.
Because these Adapter interfaces are independent, the SDK does not provide cross-module transactions by default. Even when several modules share a database, the application owns the cross-module consistency strategy.
Choosing an adapter
| Adapter | Best fit | Main constraint |
|---|---|---|
| Memory | Tests, examples, temporary development | Data is lost when the process exits |
| SQLite | Development, testing, local applications, small-scale use | Single-file database with application-owned settings |
| PostgreSQL + S3 | PostgreSQL applications with object storage, especially for large workbooks | Manage both the database and bucket. Without S3-compatible storage, use the PostgreSQL Adapter. |
| Custom | Existing databases or custom business-data integration | The application must implement and verify the complete contract |
The application owns every injected Adapter. Dispose the Service before disposing the Adapter:
await service.dispose();await database.dispose();See the runnable Database Adapter example for a side-by-side reference.
Footnotes
-
Idempotency lets the same submission be retried without applying its edits twice. Keep its submission identifier unchanged on retry; sending the same payload with a new identifier is a new submission. ↩
-
Compare-and-swap (CAS) updates a value only if its current value still matches the expected one. Here, checking the head revision and writing the next state must be atomic, so two concurrent submissions cannot both claim the same revision. ↩
How is this guide?