@univerjs-pro/collaboration-database-postgres 1.4.0 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,6 +4,8 @@ English | [简体中文](./README.zh-CN.md)
4
4
 
5
5
  A PostgreSQL `IDatabaseAdapter` built on [node-postgres](https://node-postgres.com/). It serves a single node and several collaboration nodes sharing one database alike. Requires Node.js 22 or later and PostgreSQL 13 or later.
6
6
 
7
+ This Adapter keeps everything in PostgreSQL, including Sheet blocks, the cell data that makes up nearly all of a large workbook. [`@univerjs-pro/collaboration-database-postgres-s3`](../collaboration-database-postgres-s3/README.md) stores the blocks in an S3-compatible bucket and is the recommended Adapter where object storage is available; its README explains what blocks are and what moving them changes.
8
+
7
9
  ## Create the Adapter
8
10
 
9
11
  ```bash
@@ -33,4 +35,27 @@ Pass the Adapter to `UniverCollabService` as `dbAdapter`. Dispose the Service fi
33
35
  ## PostgreSQL behavior
34
36
 
35
37
  - Tables live in the `collaboration` schema: `units`, `snapshots`, `changesets`, `sheet_blocks` and `schema_versions`. Protocol objects are stored as MessagePack `BYTEA` payloads.
36
- - `schema_versions` records `('core', 1)` and is shared by component with the other collaboration adapters. `create` opens a schema of this core version and leaves migration to an explicit step.
38
+ - `schema_versions` records `('core', 2)` and is shared by component with the other collaboration adapters. `create` opens a schema of this core version and leaves migration to an explicit step.
39
+
40
+ ## Application metadata
41
+
42
+ `UnitRecord.metadata` and `ChangesetRecord.metadata` use `Record<string, unknown>` and must contain
43
+ JSON values. Creation stores `record.metadata`; `getUnit()` and `getChangesets()` return the saved values.
44
+ `commitChangeset()` requires complete `unitMetadata` and `changeset.metadata` and saves both atomically
45
+ with the new head. The Service prepares the metadata defaults and drafts before each commit.
46
+ Snapshot saves leave metadata unchanged.
47
+
48
+ ## Migrations
49
+
50
+ Stop writers and back up the database using your PostgreSQL backup procedure. Before creating the
51
+ Adapter, pass the application-owned pool to `migratePostgresCore`:
52
+
53
+ ```ts
54
+ import { migratePostgresCore } from '@univerjs-pro/collaboration-database-postgres';
55
+
56
+ const result = await migratePostgresCore({ pool });
57
+ // { from: 1, to: 2 }
58
+ ```
59
+
60
+ The v1 to v2 upgrade initializes existing Unit and changeset metadata to `{}`. If the upgrade fails,
61
+ the transaction rolls back and you can retry. A current database returns `{ from: 2, to: 2 }`.
package/README.zh-CN.md CHANGED
@@ -4,6 +4,8 @@
4
4
 
5
5
  基于 [node-postgres](https://node-postgres.com/) 的 PostgreSQL `IDatabaseAdapter`,单节点部署和多个协同节点共用一个数据库都适用。要求 Node.js 22 及以上、PostgreSQL 13 及以上。
6
6
 
7
+ 这个 Adapter 把全部数据放在 PostgreSQL 中,包括 Sheet block,也就是占大型工作簿绝大部分体积的单元格数据。[`@univerjs-pro/collaboration-database-postgres-s3`](../collaboration-database-postgres-s3/README.zh-CN.md) 把 block 存放在 S3 兼容存储桶中,有对象存储时推荐使用;它的 README 说明了 block 是什么,以及外置之后的变化。
8
+
7
9
  ## 创建 Adapter
8
10
 
9
11
  ```bash
@@ -34,4 +36,26 @@ await pool.end();
34
36
 
35
37
  - 表位于 `collaboration` schema 中:`units`、`snapshots`、`changesets`、`sheet_blocks` 和
36
38
  `schema_versions`;协议对象以 MessagePack `BYTEA` 保存。
37
- - `schema_versions` 记录 `('core', 1)`,按组件与其他协同 Adapter 共用。`create` 打开这个核心版本的 schema,迁移作为独立步骤显式执行。
39
+ - `schema_versions` 记录 `('core', 2)`,按组件与其他协同 Adapter 共用。`create` 打开这个核心版本的 schema,迁移作为独立步骤显式执行。
40
+
41
+ ## 应用元数据
42
+
43
+ `UnitRecord.metadata` 和 `ChangesetRecord.metadata` 使用 `Record<string, unknown>`,只接受 JSON 值。
44
+ 创建时保存 `record.metadata`,通过 `getUnit()` 和 `getChangesets()` 读取已保存的值。
45
+ `commitChangeset()` 必须接收完整的 `unitMetadata` 和 `changeset.metadata`,并与新 head
46
+ 原子保存。metadata 的默认值和草稿由 Service 在每次提交前统一准备。保存 snapshot 不修改 metadata。
47
+
48
+ ## 迁移
49
+
50
+ 停止写入,按部署环境的 PostgreSQL 备份流程备份数据库。在创建 Adapter 前,将应用的连接池传给
51
+ `migratePostgresCore`:
52
+
53
+ ```ts
54
+ import { migratePostgresCore } from '@univerjs-pro/collaboration-database-postgres';
55
+
56
+ const result = await migratePostgresCore({ pool });
57
+ // { from: 1, to: 2 }
58
+ ```
59
+
60
+ v1 升至 v2 时,已有 Unit 和 changeset 的 metadata 初始化为 `{}`。升级失败时事务回滚,修复原因后
61
+ 可重试。已是当前版本时返回 `{ from: 2, to: 2 }`。
package/dist/index.cjs CHANGED
@@ -1,9 +1,51 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("node:buffer"),t=require("@msgpack/msgpack"),n=require("@univerjs-pro/collaboration-service");var r=`core`,i=1,a=1668246636,o=class o{_pool;_encoder=new t.Encoder({ignoreUndefined:!0});_decoder=new t.Decoder;constructor(e){this._pool=e}static async create(e){let t=new o(e.pool);return await t._initializeSchema(),t}async getUnit(e,t){let{rows:n}=await this._query(`get_unit`,`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("node:buffer"),t=require("@msgpack/msgpack"),n=require("@univerjs-pro/collaboration-service");var r=`core`,i=1668246636;async function a(e){let{rows:t}=await e.query(`SELECT version FROM collaboration.schema_versions WHERE component = $1`,[r]);return t[0]?.version}var o=`
2
+ CREATE SCHEMA IF NOT EXISTS collaboration;
3
+ CREATE TABLE IF NOT EXISTS collaboration.schema_versions (
4
+ component TEXT PRIMARY KEY,
5
+ version INTEGER NOT NULL CHECK (version >= 1)
6
+ );
7
+ `,s=`
8
+ CREATE TABLE collaboration.units (
9
+ unit_id TEXT PRIMARY KEY,
10
+ type INTEGER NOT NULL,
11
+ head_revision INTEGER NOT NULL CHECK (head_revision >= 1),
12
+ creator_id TEXT NOT NULL,
13
+ created_at_ms BIGINT NOT NULL,
14
+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
15
+ deleted_at_ms BIGINT,
16
+ deleted_status TEXT CHECK (deleted_status IN ('soft', 'hard')),
17
+ CHECK ((deleted_status IS NULL) = (deleted_at_ms IS NULL))
18
+ );
19
+ CREATE TABLE collaboration.snapshots (
20
+ unit_id TEXT NOT NULL REFERENCES collaboration.units(unit_id) ON DELETE CASCADE,
21
+ revision INTEGER NOT NULL CHECK (revision >= 1),
22
+ payload BYTEA NOT NULL,
23
+ PRIMARY KEY (unit_id, revision)
24
+ );
25
+ CREATE TABLE collaboration.changesets (
26
+ unit_id TEXT NOT NULL REFERENCES collaboration.units(unit_id) ON DELETE CASCADE,
27
+ revision INTEGER NOT NULL CHECK (revision >= 2),
28
+ base_revision INTEGER NOT NULL CHECK (base_revision >= 1),
29
+ sid TEXT NOT NULL,
30
+ req_id INTEGER NOT NULL CHECK (req_id >= 1),
31
+ created_at_ms BIGINT NOT NULL,
32
+ payload BYTEA NOT NULL,
33
+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
34
+ PRIMARY KEY (unit_id, revision),
35
+ UNIQUE (unit_id, sid, req_id)
36
+ );
37
+ CREATE TABLE collaboration.sheet_blocks (
38
+ unit_id TEXT NOT NULL REFERENCES collaboration.units(unit_id) ON DELETE CASCADE,
39
+ block_id TEXT NOT NULL,
40
+ payload BYTEA NOT NULL,
41
+ PRIMARY KEY (unit_id, block_id)
42
+ );
43
+ `;async function c(e,t){let n=await e.connect(),r;try{await n.query(`BEGIN`);let e=await t(n);return await n.query(`COMMIT`),e}catch(e){try{await n.query(`ROLLBACK`)}catch(e){r=e instanceof Error?e:Error(`Rollback failed`)}throw e}finally{n.release(r)}}var l=class l{_pool;_encoder=new t.Encoder({ignoreUndefined:!0});_decoder=new t.Decoder;constructor(e){this._pool=e}static async create(e){let t=new l(e.pool);return await t._initializeSchema(),t}async getUnit(e,t){let{rows:n}=await this._query(`get_unit`,`
2
44
  SELECT unit_id AS "unitID", type, head_revision AS "headRevision",
3
- creator_id AS "creatorID", created_at_ms AS "createdAt"
45
+ creator_id AS "creatorID", created_at_ms AS "createdAt", metadata
4
46
  FROM collaboration.units
5
47
  WHERE unit_id = $1 AND deleted_status IS NULL
6
- `,[t]);return n[0]?u(n[0]):null}async getSnapshot(e,t,n){let r=c(n?.revision),{rows:i}=r===void 0?await this._query(`get_snapshot`,`
48
+ `,[t]);return n[0]?p(n[0]):null}async getSnapshot(e,t,n){let r=d(n?.revision),{rows:i}=r===void 0?await this._query(`get_snapshot`,`
7
49
  SELECT s.payload
8
50
  FROM collaboration.snapshots s
9
51
  JOIN collaboration.units u USING (unit_id)
@@ -17,7 +59,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require
17
59
  WHERE u.unit_id = $1 AND u.deleted_status IS NULL AND s.revision <= $2
18
60
  ORDER BY s.revision DESC
19
61
  LIMIT 1
20
- `,[t,r]);return i[0]?this._decode(i[0].payload):null}async getSnapshotInfo(e,t,n){let r=c(n?.revision),{rows:i}=r===void 0?await this._query(`get_snapshot_info`,`
62
+ `,[t,r]);return i[0]?this._decode(i[0].payload):null}async getSnapshotInfo(e,t,n){let r=d(n?.revision),{rows:i}=r===void 0?await this._query(`get_snapshot_info`,`
21
63
  SELECT s.unit_id AS "unitID", u.type, s.revision AS rev
22
64
  FROM collaboration.snapshots s
23
65
  JOIN collaboration.units u USING (unit_id)
@@ -32,27 +74,27 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require
32
74
  ORDER BY s.revision DESC
33
75
  LIMIT 1
34
76
  `,[t,r]),a=i[0];return a?{unitID:a.unitID,type:a.type,rev:a.rev}:null}async getChangesets(e,t,r){if(r.from<0||r.to!==void 0&&r.to<0)throw new n.CollabError(`INVALID_REQUEST`,`Changeset range revisions cannot be negative`);let{rows:i}=r.to===void 0?await this._query(`get_changesets`,`
35
- SELECT c.payload
77
+ SELECT c.payload, c.metadata
36
78
  FROM collaboration.units u
37
79
  LEFT JOIN collaboration.changesets c ON c.unit_id = u.unit_id AND c.revision > $2
38
80
  WHERE u.unit_id = $1 AND u.deleted_status IS NULL
39
81
  ORDER BY c.revision
40
82
  `,[t,r.from]):await this._query(`get_changesets_in_range`,`
41
- SELECT c.payload
83
+ SELECT c.payload, c.metadata
42
84
  FROM collaboration.units u
43
85
  LEFT JOIN collaboration.changesets c
44
86
  ON c.unit_id = u.unit_id AND c.revision > $2 AND c.revision <= $3
45
87
  WHERE u.unit_id = $1 AND u.deleted_status IS NULL
46
88
  ORDER BY c.revision
47
- `,[t,r.from,r.to]);if(i.length===0)return null;let a=[];for(let e of i)e.payload!==null&&a.push(this._decode(e.payload));return a}async getSheetBlock(e,t,n){let{rows:r}=await this._query(`get_sheet_block`,`
89
+ `,[t,r.from,r.to]);if(i.length===0)return null;let a=[];for(let e of i)e.payload!==null&&a.push(this._decodeChangeset(e.payload,e.metadata));return a}async getSheetBlock(e,t,n){let{rows:r}=await this._query(`get_sheet_block`,`
48
90
  SELECT b.payload
49
91
  FROM collaboration.sheet_blocks b
50
92
  JOIN collaboration.units u USING (unit_id)
51
93
  WHERE u.unit_id = $1 AND u.deleted_status IS NULL AND b.block_id = $2
52
- `,[t,n]);return r[0]?this._decode(r[0].payload):null}async createUnit(e,t){s(t);let{record:r,snapshot:i,sheetBlocks:a=[]}=t,o=this._encodeBlocks(a);return this._transaction(async e=>{if((await this._query(`create_unit`,`
94
+ `,[t,n]);return r[0]?this._decode(r[0].payload):null}async createUnit(e,t){u(t);let r=JSON.stringify(t.record.metadata),{record:i,snapshot:a,sheetBlocks:o=[]}=t,s=this._encodeBlocks(o);return c(this._pool,async e=>{if((await this._query(`create_unit`,`
53
95
  WITH created AS (
54
- INSERT INTO collaboration.units (unit_id, type, head_revision, creator_id, created_at_ms)
55
- VALUES ($1, $2, 1, $6, $7)
96
+ INSERT INTO collaboration.units (unit_id, type, head_revision, creator_id, created_at_ms, metadata)
97
+ VALUES ($1, $2, 1, $6, $7, $8::jsonb)
56
98
  ON CONFLICT (unit_id) DO NOTHING
57
99
  RETURNING unit_id
58
100
  ), saved_blocks AS (
@@ -63,18 +105,18 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require
63
105
  )
64
106
  INSERT INTO collaboration.snapshots (unit_id, revision, payload)
65
107
  SELECT unit_id, 1, $3 FROM created
66
- `,[r.unitID,r.type,this._encode(i),o.ids,o.payloads,r.creatorID,r.createdAt],e)).rowCount)return{status:`created`,record:{...r}};let[t]=await this._lockUnits(e,[r.unitID]);if(!t||t.deletedStatus!==null)throw new n.CollabError(`INVALID_REQUEST`,`A deleted unit ID cannot be reused`);return{status:`already-exists`,record:u(t)}})}async commitChangeset(e,t){let{changeset:r}=t,i=Date.now(),a={...r,createTime:Math.floor(i/1e3)};if((await this._query(`commit_changeset`,`
108
+ `,[i.unitID,i.type,this._encode(a),s.ids,s.payloads,i.creatorID,i.createdAt,r],e)).rowCount)return{status:`created`,record:{...i,metadata:JSON.parse(r)}};let[t]=await this._lockUnits(e,[i.unitID]);if(!t||t.deletedStatus!==null)throw new n.CollabError(`INVALID_REQUEST`,`A deleted unit ID cannot be reused`);return{status:`already-exists`,record:p(t)}})}async commitChangeset(e,t){let{changeset:r}=t,i=Date.now(),{metadata:a,...o}=r,s=this._encode({...o,createTime:Math.floor(i/1e3)}),c=await this._query(`commit_changeset`,`
67
109
  WITH updated_unit AS (
68
110
  UPDATE collaboration.units
69
- SET head_revision = $2
111
+ SET head_revision = $2, metadata = $8::jsonb
70
112
  WHERE unit_id = $1 AND deleted_status IS NULL AND head_revision = $2::integer - 1
71
113
  RETURNING unit_id, head_revision
72
114
  )
73
115
  INSERT INTO collaboration.changesets
74
- (unit_id, revision, base_revision, sid, req_id, created_at_ms, payload)
75
- SELECT unit_id, head_revision, $3, $4, $5, $6, $7 FROM updated_unit
76
- RETURNING revision
77
- `,[r.unitID,r.revision,r.baseRev,r.sid,r.reqId,i,this._encode(a)])).rowCount)return{status:`committed`,changeset:a,headRevision:r.revision};let o=await this.getUnit(e,r.unitID);if(!o)throw new n.CollabError(`UNIT_NOT_FOUND`,`Unit is not active`);return{status:`revision-mismatch`,actualHeadRevision:o.headRevision}}async saveSnapshot(e,t){let{snapshot:r,sheetBlocks:i=[]}=t,a=this._encodeBlocks(i),{rows:o}=await this._query(`save_snapshot`,`
116
+ (unit_id, revision, base_revision, sid, req_id, created_at_ms, payload, metadata)
117
+ SELECT unit_id, head_revision, $3, $4, $5, $6, $7, $9::jsonb FROM updated_unit
118
+ RETURNING metadata
119
+ `,[r.unitID,r.revision,r.baseRev,r.sid,r.reqId,i,s,JSON.stringify(t.unitMetadata),JSON.stringify(a)]);if(c.rowCount)return{status:`committed`,changeset:this._decodeChangeset(s,c.rows[0].metadata),headRevision:r.revision};let l=await this.getUnit(e,r.unitID);if(!l)throw new n.CollabError(`UNIT_NOT_FOUND`,`Unit is not active`);return{status:`revision-mismatch`,actualHeadRevision:l.headRevision}}async saveSnapshot(e,t){let{snapshot:r,sheetBlocks:i=[]}=t,a=this._encodeBlocks(await this._missingBlocks(r.unitID,i)),{rows:o}=await this._query(`save_snapshot`,`
78
120
  WITH locked_unit AS MATERIALIZED (
79
121
  SELECT unit_id, type, head_revision, deleted_status
80
122
  FROM collaboration.units
@@ -88,7 +130,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require
88
130
  SELECT u.unit_id, b.id, b.payload
89
131
  FROM valid_unit u
90
132
  CROSS JOIN unnest($5::text[], $6::bytea[]) AS b(id, payload)
91
- ON CONFLICT (unit_id, block_id) DO UPDATE SET payload = excluded.payload
133
+ ON CONFLICT (unit_id, block_id) DO NOTHING
92
134
  ), saved_snapshot AS (
93
135
  INSERT INTO collaboration.snapshots (unit_id, revision, payload)
94
136
  SELECT unit_id, $3, $4 FROM valid_unit
@@ -97,10 +139,10 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require
97
139
  )
98
140
  SELECT deleted_status AS "deletedStatus", EXISTS (SELECT 1 FROM saved_snapshot) AS saved
99
141
  FROM locked_unit
100
- `,[r.unitID,r.type,r.rev,this._encode(r),a.ids,a.payloads]),s=o[0];if(!s||s.deletedStatus!==null)throw new n.CollabError(`UNIT_NOT_FOUND`,`Unit is not active`);if(!s.saved)throw new n.CollabError(`INVALID_REQUEST`,`Snapshot does not match the stored unit head`)}async deleteUnits(e,t){let{unitIDs:r}=t;return r.length===0?{units:[]}:this._transaction(async e=>{let i=(await this._lockUnits(e,r)).map(e=>{if(!e||e.deletedStatus===`hard`&&!t.hardDelete)throw new n.CollabError(`UNIT_NOT_FOUND`,`Cannot delete a missing unit`);return{unitID:e.unitID,status:t.hardDelete?e.deletedStatus===`hard`?`already-hard-deleted`:`hard-deleted`:e.deletedStatus===`soft`?`already-soft-deleted`:`soft-deleted`}}),a=Date.now();return t.hardDelete?await this._query(`hard_delete_units`,`
142
+ `,[r.unitID,r.type,r.rev,this._encode(r),a.ids,a.payloads]),s=o[0];if(!s||s.deletedStatus!==null)throw new n.CollabError(`UNIT_NOT_FOUND`,`Unit is not active`);if(!s.saved)throw new n.CollabError(`INVALID_REQUEST`,`Snapshot does not match the stored unit head`)}async deleteUnits(e,t){let{unitIDs:r}=t;return r.length===0?{units:[]}:c(this._pool,async e=>{let i=(await this._lockUnits(e,r)).map(e=>{if(!e||e.deletedStatus===`hard`&&!t.hardDelete)throw new n.CollabError(`UNIT_NOT_FOUND`,`Cannot delete a missing unit`);return{unitID:e.unitID,status:t.hardDelete?e.deletedStatus===`hard`?`already-hard-deleted`:`hard-deleted`:e.deletedStatus===`soft`?`already-soft-deleted`:`soft-deleted`}}),a=Date.now();return t.hardDelete?await this._query(`hard_delete_units`,`
101
143
  WITH deleted_units AS (
102
144
  UPDATE collaboration.units
103
- SET deleted_at_ms = $2, deleted_status = 'hard'
145
+ SET deleted_at_ms = $2, deleted_status = 'hard', metadata = '{}'::jsonb
104
146
  WHERE unit_id = ANY($1::text[]) AND deleted_status IS DISTINCT FROM 'hard'
105
147
  RETURNING unit_id
106
148
  ), removed_snapshots AS (
@@ -113,56 +155,21 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require
113
155
  UPDATE collaboration.units
114
156
  SET deleted_at_ms = $2, deleted_status = 'soft'
115
157
  WHERE unit_id = ANY($1::text[]) AND deleted_status IS NULL
116
- `,[r,a],e),{units:i}})}async recoverUnits(e,t){let{unitIDs:r}=t;return r.length===0?{units:[]}:this._transaction(async e=>{let t=(await this._lockUnits(e,r)).map(e=>{if(!e)throw new n.CollabError(`UNIT_NOT_FOUND`,`Cannot recover a missing unit`);if(e.deletedStatus===`hard`)throw new n.CollabError(`INVALID_REQUEST`,`A hard-deleted unit cannot be recovered`);return{unitID:e.unitID,status:e.deletedStatus===`soft`?`recovered`:`already-active`}});return await this._query(`recover_units`,`
158
+ `,[r,a],e),{units:i}})}async recoverUnits(e,t){let{unitIDs:r}=t;return r.length===0?{units:[]}:c(this._pool,async e=>{let t=(await this._lockUnits(e,r)).map(e=>{if(!e)throw new n.CollabError(`UNIT_NOT_FOUND`,`Cannot recover a missing unit`);if(e.deletedStatus===`hard`)throw new n.CollabError(`INVALID_REQUEST`,`A hard-deleted unit cannot be recovered`);return{unitID:e.unitID,status:e.deletedStatus===`soft`?`recovered`:`already-active`}});return await this._query(`recover_units`,`
117
159
  UPDATE collaboration.units SET deleted_at_ms = NULL, deleted_status = NULL
118
160
  WHERE unit_id = ANY($1::text[]) AND deleted_status = 'soft'
119
- `,[r],e),{units:t}})}async _initializeSchema(){await this._transaction(async e=>{await e.query(`SELECT pg_advisory_xact_lock($1)`,[a]),await e.query(`
120
- CREATE SCHEMA IF NOT EXISTS collaboration;
121
- CREATE TABLE IF NOT EXISTS collaboration.schema_versions (
122
- component TEXT PRIMARY KEY,
123
- version INTEGER NOT NULL CHECK (version >= 1)
124
- );
125
- `);let t=await this._readSchemaVersion(e);if(t!==i){if(t!==void 0)throw l(t);await this._createSchema(e)}})}async _readSchemaVersion(e){let{rows:t}=await e.query(`SELECT version FROM collaboration.schema_versions WHERE component = $1`,[r]);return t[0]?.version}async _createSchema(e){await e.query(`
126
- CREATE TABLE collaboration.units (
127
- unit_id TEXT PRIMARY KEY,
128
- type INTEGER NOT NULL,
129
- head_revision INTEGER NOT NULL CHECK (head_revision >= 1),
130
- creator_id TEXT NOT NULL,
131
- created_at_ms BIGINT NOT NULL,
132
- deleted_at_ms BIGINT,
133
- deleted_status TEXT CHECK (deleted_status IN ('soft', 'hard')),
134
- CHECK ((deleted_status IS NULL) = (deleted_at_ms IS NULL))
135
- );
136
- CREATE TABLE collaboration.snapshots (
137
- unit_id TEXT NOT NULL REFERENCES collaboration.units(unit_id) ON DELETE CASCADE,
138
- revision INTEGER NOT NULL CHECK (revision >= 1),
139
- payload BYTEA NOT NULL,
140
- PRIMARY KEY (unit_id, revision)
141
- );
142
- CREATE TABLE collaboration.changesets (
143
- unit_id TEXT NOT NULL REFERENCES collaboration.units(unit_id) ON DELETE CASCADE,
144
- revision INTEGER NOT NULL CHECK (revision >= 2),
145
- base_revision INTEGER NOT NULL CHECK (base_revision >= 1),
146
- sid TEXT NOT NULL,
147
- req_id INTEGER NOT NULL CHECK (req_id >= 1),
148
- created_at_ms BIGINT NOT NULL,
149
- payload BYTEA NOT NULL,
150
- PRIMARY KEY (unit_id, revision),
151
- UNIQUE (unit_id, sid, req_id)
152
- );
153
- CREATE TABLE collaboration.sheet_blocks (
154
- unit_id TEXT NOT NULL REFERENCES collaboration.units(unit_id) ON DELETE CASCADE,
155
- block_id TEXT NOT NULL,
156
- payload BYTEA NOT NULL,
157
- PRIMARY KEY (unit_id, block_id)
158
- );
159
- INSERT INTO collaboration.schema_versions (component, version)
160
- VALUES ('${r}', ${i});
161
- `)}async _transaction(e){let t=await this._pool.connect(),n;try{await t.query(`BEGIN`);let n=await e(t);return await t.query(`COMMIT`),n}catch(e){try{await t.query(`ROLLBACK`)}catch(e){n=e instanceof Error?e:Error(`Rollback failed`)}throw e}finally{t.release(n)}}async _lockUnits(e,t){let{rows:n}=await this._query(`lock_units`,`
161
+ `,[r],e),{units:t}})}async _initializeSchema(){await c(this._pool,async e=>{await e.query(`SELECT pg_advisory_xact_lock($1)`,[i]),await e.query(o);let t=await a(e);if(t!==2){if(t!==void 0)throw f(t);await e.query(s),await e.query(`INSERT INTO collaboration.schema_versions (component, version) VALUES ($1, $2)`,[r,2])}})}async _lockUnits(e,t){let{rows:n}=await this._query(`lock_units`,`
162
162
  SELECT unit_id AS "unitID", type, head_revision AS "headRevision",
163
- creator_id AS "creatorID", created_at_ms AS "createdAt", deleted_status AS "deletedStatus"
163
+ creator_id AS "creatorID", created_at_ms AS "createdAt", metadata, deleted_status AS "deletedStatus"
164
164
  FROM collaboration.units
165
165
  WHERE unit_id = ANY($1::text[])
166
166
  ORDER BY unit_id
167
167
  FOR UPDATE
168
- `,[t],e),r=new Map(n.map(e=>[e.unitID,e]));return t.map(e=>r.get(e))}_query(e,t,n,r){return(r??this._pool).query({name:e,text:t,values:n})}_encode(t){let n=this._encoder.encode(t);return e.Buffer.from(n.buffer,n.byteOffset,n.byteLength)}_decode(e){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return this._decoder.decode(t)}_encodeBlocks(e){let t=[],n=[],r=new Map(e.map(e=>[e.id,e]));for(let e of r.values())t.push(e.id),n.push(this._encode(e));return{ids:t,payloads:n}}};function s({record:e,snapshot:t}){if(e.headRevision!==1||t.rev!==1||t.unitID!==e.unitID||t.type!==e.type)throw new n.CollabError(`INVALID_REQUEST`,`Initial record and snapshot must match at revision 1`);if(typeof e.creatorID!=`string`||e.creatorID.length===0||!Number.isSafeInteger(e.createdAt)||e.createdAt<0)throw new n.CollabError(`INVALID_REQUEST`,`Unit creation requires creatorID and createdAt in Unix milliseconds`)}function c(e){if(e!==void 0&&e<0)throw new n.CollabError(`INVALID_REQUEST`,`Snapshot revision cannot be negative`);return e}function l(e){return new n.CollabError(`INTERNAL_ERROR`,`Core schema version ${e} is not supported by this adapter (expected ${i}); migrate the database explicitly first`)}function u(e){return{unitID:e.unitID,type:e.type,headRevision:e.headRevision,creatorID:e.creatorID,createdAt:Number(e.createdAt)}}exports.PostgresDatabaseAdapter=o;
168
+ `,[t],e),r=new Map(n.map(e=>[e.unitID,e]));return t.map(e=>r.get(e))}_query(e,t,n,r){return(r??this._pool).query({name:e,text:t,values:n})}_decodeChangeset(e,t){return{...this._decode(e),metadata:t}}_encode(t){let n=this._encoder.encode(t);return e.Buffer.from(n.buffer,n.byteOffset,n.byteLength)}_decode(e){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return this._decoder.decode(t)}async _missingBlocks(e,t){if(t.length===0)return t;let{rows:n}=await this._query(`get_stored_sheet_block_ids`,`
169
+ SELECT block_id AS "blockID"
170
+ FROM collaboration.sheet_blocks
171
+ WHERE unit_id = $1 AND block_id = ANY($2::text[])
172
+ `,[e,t.map(e=>e.id)]);if(n.length===0)return t;let r=new Set(n.map(e=>e.blockID));return t.filter(e=>!r.has(e.id))}_encodeBlocks(e){let t=[],n=[],r=new Map(e.map(e=>[e.id,e]));for(let e of r.values())t.push(e.id),n.push(this._encode(e));return{ids:t,payloads:n}}};function u({record:e,snapshot:t}){if(e.headRevision!==1||t.rev!==1||t.unitID!==e.unitID||t.type!==e.type)throw new n.CollabError(`INVALID_REQUEST`,`Initial record and snapshot must match at revision 1`);if(typeof e.creatorID!=`string`||e.creatorID.length===0||!Number.isSafeInteger(e.createdAt)||e.createdAt<0)throw new n.CollabError(`INVALID_REQUEST`,`Unit creation requires creatorID and createdAt in Unix milliseconds`)}function d(e){if(e!==void 0&&e<0)throw new n.CollabError(`INVALID_REQUEST`,`Snapshot revision cannot be negative`);return e}function f(e){return new n.CollabError(`INTERNAL_ERROR`,`Core schema version ${e} is not supported by this adapter (expected 2); ${e<2?`run migratePostgresCore first`:`upgrade the adapter`}`)}function p(e){return{unitID:e.unitID,type:e.type,headRevision:e.headRevision,creatorID:e.creatorID,createdAt:Number(e.createdAt),metadata:e.metadata}}function m(e,t){return c(e.pool,async e=>{await e.query(`SELECT pg_advisory_xact_lock($1)`,[i]);let r=await a(e);if(r===void 0)throw new n.CollabError(`INVALID_REQUEST`,`The database has no PostgreSQL core schema version to migrate from`);return t(e,r)})}function h(e){return m(e,g)}async function g(e,t){if(t!==1)throw new n.CollabError(`INVALID_REQUEST`,`PostgreSQL core v1-to-v2 migration requires schema version 1`);if(await e.query(`
173
+ ALTER TABLE collaboration.units ADD COLUMN metadata JSONB NOT NULL DEFAULT '{}'::jsonb;
174
+ ALTER TABLE collaboration.changesets ADD COLUMN metadata JSONB NOT NULL DEFAULT '{}'::jsonb;
175
+ `),(await e.query(`UPDATE collaboration.schema_versions SET version = 2 WHERE component = 'core' AND version = 1`)).rowCount!==1)throw new n.CollabError(`INVALID_REQUEST`,`Failed to publish PostgreSQL core schema version 2`)}function _(e){return m(e,async(e,t)=>{if(t===2)return{from:t,to:t};if(t>2)throw new n.CollabError(`INVALID_REQUEST`,`Core schema version ${t} is newer than this package supports (2)`);return await g(e,t),{from:t,to:2}})}exports.PostgresDatabaseAdapter=l,exports.migratePostgresCore=_,exports.migratePostgresCoreV1ToV2=h;
package/dist/index.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import { Pool } from "pg";
2
- import { CommitChangesetInput, CommitChangesetResult, CreateUnitDatabaseInput, CreateUnitDatabaseResult, DatabaseContext, DeleteUnitsDatabaseInput, DeleteUnitsDatabaseResult, IDatabaseAdapter, RecoverUnitsDatabaseInput, RecoverUnitsDatabaseResult, SaveSnapshotInput, SnapshotInfo, SubmitDatabaseContext, UnitRecord } from "@univerjs-pro/collaboration-service";
3
- import { IChangeset, ISheetBlock, ISnapshot } from "@univerjs/protocol";
2
+ import { ChangesetRecord, CommitChangesetInput, CommitChangesetResult, CreateUnitDatabaseInput, CreateUnitDatabaseResult, DatabaseContext, DeleteUnitsDatabaseInput, DeleteUnitsDatabaseResult, IDatabaseAdapter, RecoverUnitsDatabaseInput, RecoverUnitsDatabaseResult, SaveSnapshotInput, SnapshotInfo, SubmitDatabaseContext, UnitRecord } from "@univerjs-pro/collaboration-service";
3
+ import { ISheetBlock, ISnapshot } from "@univerjs/protocol";
4
4
 
5
- //#region src/postgres-database-adapter.d.ts
5
+ // src/postgres-database-adapter.d.ts
6
+ /** @public */
6
7
  interface PostgresDatabaseAdapterOptions {
7
8
  /** Connection pool owned by the application; the adapter never ends it. */
8
9
  readonly pool: Pool;
@@ -13,6 +14,7 @@ interface PostgresDatabaseAdapterOptions {
13
14
  *
14
15
  * Create instances with {@link PostgresDatabaseAdapter.create}, which initializes an empty
15
16
  * `collaboration` schema and rejects one whose core version differs from the one this adapter writes.
17
+ * @public
16
18
  */
17
19
  declare class PostgresDatabaseAdapter implements IDatabaseAdapter {
18
20
  private readonly _pool;
@@ -26,7 +28,7 @@ declare class PostgresDatabaseAdapter implements IDatabaseAdapter {
26
28
  getSnapshot(_ctx: DatabaseContext, unitID: string, options?: {
27
29
  readonly revision?: number;
28
30
  }): Promise<ISnapshot | null>;
29
- /** Reads metadata with the same selection rules as getSnapshot, without decoding the payload. */
31
+ /** Reads snapshot info with the same selection rules as getSnapshot, without decoding the payload. */
30
32
  getSnapshotInfo(_ctx: DatabaseContext, unitID: string, options?: {
31
33
  readonly revision?: number;
32
34
  }): Promise<SnapshotInfo | null>;
@@ -34,7 +36,7 @@ declare class PostgresDatabaseAdapter implements IDatabaseAdapter {
34
36
  getChangesets(_ctx: DatabaseContext, unitID: string, range: {
35
37
  readonly from: number;
36
38
  readonly to?: number;
37
- }): Promise<readonly IChangeset[] | null>;
39
+ }): Promise<readonly ChangesetRecord[] | null>;
38
40
  getSheetBlock(_ctx: DatabaseContext, unitID: string, blockID: string): Promise<ISheetBlock | null>;
39
41
  /** Atomically creates a Unit at revision 1 with its snapshot and blocks; an existing active Unit returns its record. */
40
42
  createUnit(_ctx: DatabaseContext, input: CreateUnitDatabaseInput): Promise<CreateUnitDatabaseResult>;
@@ -47,14 +49,29 @@ declare class PostgresDatabaseAdapter implements IDatabaseAdapter {
47
49
  /** Recovers the whole batch or fails it; hard-deleted IDs cannot be recovered. */
48
50
  recoverUnits(_ctx: DatabaseContext, input: RecoverUnitsDatabaseInput): Promise<RecoverUnitsDatabaseResult>;
49
51
  private _initializeSchema;
50
- private _readSchemaVersion;
51
- private _createSchema;
52
- private _transaction;
53
52
  private _lockUnits;
54
53
  private _query;
54
+ private _decodeChangeset;
55
55
  private _encode;
56
56
  private _decode;
57
+ private _missingBlocks;
57
58
  private _encodeBlocks;
58
59
  }
59
- //#endregion
60
- export { PostgresDatabaseAdapter, type PostgresDatabaseAdapterOptions };
60
+ /** Core schema versions before and after migration. @public */
61
+ interface PostgresCoreMigrationResult {
62
+ readonly from: number;
63
+ readonly to: number;
64
+ }
65
+ /**
66
+ * Upgrades an existing PostgreSQL core schema to the version this package writes.
67
+ * Stop writers and arrange a database backup first. A current schema is left unchanged.
68
+ * @public
69
+ */
70
+ declare function migratePostgresCore(options: PostgresDatabaseAdapterOptions): Promise<PostgresCoreMigrationResult>;
71
+ /**
72
+ * Upgrades PostgreSQL core v1 to v2, adding empty metadata to existing Units and changesets.
73
+ * Requires core v1. Stop writers and back up the database before calling.
74
+ * @public
75
+ */
76
+ declare function migratePostgresCoreV1ToV2(options: PostgresDatabaseAdapterOptions): Promise<void>;
77
+ export { type PostgresCoreMigrationResult, PostgresDatabaseAdapter, type PostgresDatabaseAdapterOptions, migratePostgresCore, migratePostgresCoreV1ToV2 };
package/dist/index.mjs CHANGED
@@ -1,3 +1,5 @@
1
1
  import cjsModule from "./index.cjs";
2
2
  const facadeExport0 = cjsModule["PostgresDatabaseAdapter"];
3
- export { facadeExport0 as PostgresDatabaseAdapter };
3
+ const facadeExport1 = cjsModule["migratePostgresCore"];
4
+ const facadeExport2 = cjsModule["migratePostgresCoreV1ToV2"];
5
+ export { facadeExport0 as PostgresDatabaseAdapter, facadeExport1 as migratePostgresCore, facadeExport2 as migratePostgresCoreV1ToV2 };
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "engines": {
12
12
  "node": ">=22"
13
13
  },
14
- "version": "1.4.0",
14
+ "version": "1.5.2",
15
15
  "main": "./dist/index.cjs",
16
16
  "module": "./dist/index.mjs",
17
17
  "types": "./dist/index.d.ts",
@@ -29,8 +29,8 @@
29
29
  "@msgpack/msgpack": "^3.1.3"
30
30
  },
31
31
  "peerDependencies": {
32
- "@univerjs-pro/collaboration-service": "1.4.0",
33
- "@univerjs/protocol": "1.4.0",
32
+ "@univerjs-pro/collaboration-service": "1.5.2",
33
+ "@univerjs/protocol": "1.5.2",
34
34
  "pg": "^8.11.0"
35
35
  }
36
36
  }