@univerjs-pro/collaboration-database-postgres 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,61 @@
1
- # Temporary Holding Version
1
+ # @univerjs-pro/collaboration-database-postgres
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ English | [简体中文](./README.zh-CN.md)
4
+
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
+
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
+
9
+ ## Create the Adapter
10
+
11
+ ```bash
12
+ pnpm add \
13
+ @univerjs-pro/collaboration-service \
14
+ @univerjs-pro/collaboration-database-postgres \
15
+ pg
16
+ ```
17
+
18
+ The application owns the connection pool. `create` initializes the schema in an empty database and verifies an existing one:
19
+
20
+ ```ts
21
+ import { PostgresDatabaseAdapter } from '@univerjs-pro/collaboration-database-postgres';
22
+ import { UniverCollabService } from '@univerjs-pro/collaboration-service';
23
+ import { Pool } from 'pg';
24
+
25
+ const pool = new Pool({ connectionString: process.env.DATABASE_URL });
26
+ const database = await PostgresDatabaseAdapter.create({ pool });
27
+ const service = new UniverCollabService({ dbAdapter: database });
28
+
29
+ await service.dispose();
30
+ await pool.end();
31
+ ```
32
+
33
+ Pass the Adapter to `UniverCollabService` as `dbAdapter`. Dispose the Service first, then end the pool.
34
+
35
+ ## PostgreSQL behavior
36
+
37
+ - Tables live in the `collaboration` schema: `units`, `snapshots`, `changesets`, `sheet_blocks` and `schema_versions`. Protocol objects are stored as MessagePack `BYTEA` payloads.
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 }`.
@@ -0,0 +1,61 @@
1
+ # @univerjs-pro/collaboration-database-postgres
2
+
3
+ [English](./README.md) | [简体中文](./README.zh-CN.md)
4
+
5
+ 基于 [node-postgres](https://node-postgres.com/) 的 PostgreSQL `IDatabaseAdapter`,单节点部署和多个协同节点共用一个数据库都适用。要求 Node.js 22 及以上、PostgreSQL 13 及以上。
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
+
9
+ ## 创建 Adapter
10
+
11
+ ```bash
12
+ pnpm add \
13
+ @univerjs-pro/collaboration-service \
14
+ @univerjs-pro/collaboration-database-postgres \
15
+ pg
16
+ ```
17
+
18
+ 连接池由应用持有。`create` 为空数据库初始化 schema,已有 schema 时只做校验:
19
+
20
+ ```ts
21
+ import { PostgresDatabaseAdapter } from '@univerjs-pro/collaboration-database-postgres';
22
+ import { UniverCollabService } from '@univerjs-pro/collaboration-service';
23
+ import { Pool } from 'pg';
24
+
25
+ const pool = new Pool({ connectionString: process.env.DATABASE_URL });
26
+ const database = await PostgresDatabaseAdapter.create({ pool });
27
+ const service = new UniverCollabService({ dbAdapter: database });
28
+
29
+ await service.dispose();
30
+ await pool.end();
31
+ ```
32
+
33
+ 将 Adapter 作为 `dbAdapter` 传给 `UniverCollabService`。先释放 Service,再关闭连接池。
34
+
35
+ ## PostgreSQL 行为
36
+
37
+ - 表位于 `collaboration` schema 中:`units`、`snapshots`、`changesets`、`sheet_blocks` 和
38
+ `schema_versions`;协议对象以 MessagePack `BYTEA` 保存。
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 ADDED
@@ -0,0 +1,175 @@
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`,`
44
+ SELECT unit_id AS "unitID", type, head_revision AS "headRevision",
45
+ creator_id AS "creatorID", created_at_ms AS "createdAt", metadata
46
+ FROM collaboration.units
47
+ WHERE unit_id = $1 AND deleted_status IS NULL
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`,`
49
+ SELECT s.payload
50
+ FROM collaboration.snapshots s
51
+ JOIN collaboration.units u USING (unit_id)
52
+ WHERE u.unit_id = $1 AND u.deleted_status IS NULL
53
+ ORDER BY s.revision DESC
54
+ LIMIT 1
55
+ `,[t]):await this._query(`get_snapshot_at_revision`,`
56
+ SELECT s.payload
57
+ FROM collaboration.snapshots s
58
+ JOIN collaboration.units u USING (unit_id)
59
+ WHERE u.unit_id = $1 AND u.deleted_status IS NULL AND s.revision <= $2
60
+ ORDER BY s.revision DESC
61
+ LIMIT 1
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`,`
63
+ SELECT s.unit_id AS "unitID", u.type, s.revision AS rev
64
+ FROM collaboration.snapshots s
65
+ JOIN collaboration.units u USING (unit_id)
66
+ WHERE u.unit_id = $1 AND u.deleted_status IS NULL
67
+ ORDER BY s.revision DESC
68
+ LIMIT 1
69
+ `,[t]):await this._query(`get_snapshot_info_at_revision`,`
70
+ SELECT s.unit_id AS "unitID", u.type, s.revision AS rev
71
+ FROM collaboration.snapshots s
72
+ JOIN collaboration.units u USING (unit_id)
73
+ WHERE u.unit_id = $1 AND u.deleted_status IS NULL AND s.revision <= $2
74
+ ORDER BY s.revision DESC
75
+ LIMIT 1
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`,`
77
+ SELECT c.payload, c.metadata
78
+ FROM collaboration.units u
79
+ LEFT JOIN collaboration.changesets c ON c.unit_id = u.unit_id AND c.revision > $2
80
+ WHERE u.unit_id = $1 AND u.deleted_status IS NULL
81
+ ORDER BY c.revision
82
+ `,[t,r.from]):await this._query(`get_changesets_in_range`,`
83
+ SELECT c.payload, c.metadata
84
+ FROM collaboration.units u
85
+ LEFT JOIN collaboration.changesets c
86
+ ON c.unit_id = u.unit_id AND c.revision > $2 AND c.revision <= $3
87
+ WHERE u.unit_id = $1 AND u.deleted_status IS NULL
88
+ ORDER BY c.revision
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`,`
90
+ SELECT b.payload
91
+ FROM collaboration.sheet_blocks b
92
+ JOIN collaboration.units u USING (unit_id)
93
+ WHERE u.unit_id = $1 AND u.deleted_status IS NULL AND b.block_id = $2
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`,`
95
+ WITH created AS (
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)
98
+ ON CONFLICT (unit_id) DO NOTHING
99
+ RETURNING unit_id
100
+ ), saved_blocks AS (
101
+ INSERT INTO collaboration.sheet_blocks (unit_id, block_id, payload)
102
+ SELECT u.unit_id, b.id, b.payload
103
+ FROM created u
104
+ CROSS JOIN unnest($4::text[], $5::bytea[]) AS b(id, payload)
105
+ )
106
+ INSERT INTO collaboration.snapshots (unit_id, revision, payload)
107
+ SELECT unit_id, 1, $3 FROM created
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`,`
109
+ WITH updated_unit AS (
110
+ UPDATE collaboration.units
111
+ SET head_revision = $2, metadata = $8::jsonb
112
+ WHERE unit_id = $1 AND deleted_status IS NULL AND head_revision = $2::integer - 1
113
+ RETURNING unit_id, head_revision
114
+ )
115
+ INSERT INTO collaboration.changesets
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`,`
120
+ WITH locked_unit AS MATERIALIZED (
121
+ SELECT unit_id, type, head_revision, deleted_status
122
+ FROM collaboration.units
123
+ WHERE unit_id = $1
124
+ FOR UPDATE
125
+ ), valid_unit AS (
126
+ SELECT unit_id FROM locked_unit
127
+ WHERE deleted_status IS NULL AND type = $2 AND $3::integer BETWEEN 1 AND head_revision
128
+ ), saved_blocks AS (
129
+ INSERT INTO collaboration.sheet_blocks (unit_id, block_id, payload)
130
+ SELECT u.unit_id, b.id, b.payload
131
+ FROM valid_unit u
132
+ CROSS JOIN unnest($5::text[], $6::bytea[]) AS b(id, payload)
133
+ ON CONFLICT (unit_id, block_id) DO NOTHING
134
+ ), saved_snapshot AS (
135
+ INSERT INTO collaboration.snapshots (unit_id, revision, payload)
136
+ SELECT unit_id, $3, $4 FROM valid_unit
137
+ ON CONFLICT (unit_id, revision) DO UPDATE SET payload = excluded.payload
138
+ RETURNING revision
139
+ )
140
+ SELECT deleted_status AS "deletedStatus", EXISTS (SELECT 1 FROM saved_snapshot) AS saved
141
+ FROM locked_unit
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`,`
143
+ WITH deleted_units AS (
144
+ UPDATE collaboration.units
145
+ SET deleted_at_ms = $2, deleted_status = 'hard', metadata = '{}'::jsonb
146
+ WHERE unit_id = ANY($1::text[]) AND deleted_status IS DISTINCT FROM 'hard'
147
+ RETURNING unit_id
148
+ ), removed_snapshots AS (
149
+ DELETE FROM collaboration.snapshots WHERE unit_id IN (SELECT unit_id FROM deleted_units)
150
+ ), removed_blocks AS (
151
+ DELETE FROM collaboration.sheet_blocks WHERE unit_id IN (SELECT unit_id FROM deleted_units)
152
+ )
153
+ DELETE FROM collaboration.changesets WHERE unit_id IN (SELECT unit_id FROM deleted_units)
154
+ `,[r,a],e):await this._query(`soft_delete_units`,`
155
+ UPDATE collaboration.units
156
+ SET deleted_at_ms = $2, deleted_status = 'soft'
157
+ WHERE unit_id = ANY($1::text[]) AND deleted_status IS NULL
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`,`
159
+ UPDATE collaboration.units SET deleted_at_ms = NULL, deleted_status = NULL
160
+ WHERE unit_id = ANY($1::text[]) AND deleted_status = 'soft'
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
+ SELECT unit_id AS "unitID", type, head_revision AS "headRevision",
163
+ creator_id AS "creatorID", created_at_ms AS "createdAt", metadata, deleted_status AS "deletedStatus"
164
+ FROM collaboration.units
165
+ WHERE unit_id = ANY($1::text[])
166
+ ORDER BY unit_id
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})}_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;
@@ -0,0 +1,77 @@
1
+ import { Pool } from "pg";
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
+
5
+ // src/postgres-database-adapter.d.ts
6
+ /** @public */
7
+ interface PostgresDatabaseAdapterOptions {
8
+ /** Connection pool owned by the application; the adapter never ends it. */
9
+ readonly pool: Pool;
10
+ }
11
+ /**
12
+ * PostgreSQL implementation of the collaboration persistence contract, built on `node-postgres`.
13
+ * Protocol objects are stored as MessagePack `BYTEA` payloads.
14
+ *
15
+ * Create instances with {@link PostgresDatabaseAdapter.create}, which initializes an empty
16
+ * `collaboration` schema and rejects one whose core version differs from the one this adapter writes.
17
+ * @public
18
+ */
19
+ declare class PostgresDatabaseAdapter implements IDatabaseAdapter {
20
+ private readonly _pool;
21
+ private readonly _encoder;
22
+ private readonly _decoder;
23
+ private constructor();
24
+ /** Initializes or verifies the schema, then returns a ready adapter. */
25
+ static create(options: PostgresDatabaseAdapterOptions): Promise<PostgresDatabaseAdapter>;
26
+ getUnit(_ctx: DatabaseContext, unitID: string): Promise<UnitRecord | null>;
27
+ /** Reads the latest snapshot, optionally bounded by the specified revision. */
28
+ getSnapshot(_ctx: DatabaseContext, unitID: string, options?: {
29
+ readonly revision?: number;
30
+ }): Promise<ISnapshot | null>;
31
+ /** Reads snapshot info with the same selection rules as getSnapshot, without decoding the payload. */
32
+ getSnapshotInfo(_ctx: DatabaseContext, unitID: string, options?: {
33
+ readonly revision?: number;
34
+ }): Promise<SnapshotInfo | null>;
35
+ /** Reads changesets in (from, to], ordered by revision. */
36
+ getChangesets(_ctx: DatabaseContext, unitID: string, range: {
37
+ readonly from: number;
38
+ readonly to?: number;
39
+ }): Promise<readonly ChangesetRecord[] | null>;
40
+ getSheetBlock(_ctx: DatabaseContext, unitID: string, blockID: string): Promise<ISheetBlock | null>;
41
+ /** Atomically creates a Unit at revision 1 with its snapshot and blocks; an existing active Unit returns its record. */
42
+ createUnit(_ctx: DatabaseContext, input: CreateUnitDatabaseInput): Promise<CreateUnitDatabaseResult>;
43
+ /** Confirms the changeset when the stored head equals `revision - 1`; otherwise reports the actual head. */
44
+ commitChangeset(ctx: SubmitDatabaseContext, input: CommitChangesetInput): Promise<CommitChangesetResult>;
45
+ /** Publishes a snapshot together with the blocks it references. */
46
+ saveSnapshot(_ctx: DatabaseContext, input: SaveSnapshotInput): Promise<void>;
47
+ /** Deletes the whole batch or fails it; hard deletion keeps the Unit row as a permanent marker. */
48
+ deleteUnits(_ctx: DatabaseContext, input: DeleteUnitsDatabaseInput): Promise<DeleteUnitsDatabaseResult>;
49
+ /** Recovers the whole batch or fails it; hard-deleted IDs cannot be recovered. */
50
+ recoverUnits(_ctx: DatabaseContext, input: RecoverUnitsDatabaseInput): Promise<RecoverUnitsDatabaseResult>;
51
+ private _initializeSchema;
52
+ private _lockUnits;
53
+ private _query;
54
+ private _decodeChangeset;
55
+ private _encode;
56
+ private _decode;
57
+ private _missingBlocks;
58
+ private _encodeBlocks;
59
+ }
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 ADDED
@@ -0,0 +1,5 @@
1
+ import cjsModule from "./index.cjs";
2
+ const facadeExport0 = cjsModule["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
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@univerjs-pro/collaboration-database-postgres",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "PostgreSQL IDatabaseAdapter for Univer Collaboration built on node-postgres",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/dream-num/univer-collaboration-sdk-community.git",
7
+ "directory": "packages/collaboration-database-postgres"
8
+ },
9
+ "license": "Apache-2.0",
10
+ "type": "module",
11
+ "engines": {
12
+ "node": ">=22"
13
+ },
14
+ "version": "1.5.2",
15
+ "main": "./dist/index.cjs",
16
+ "module": "./dist/index.mjs",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.mjs",
22
+ "require": "./dist/index.cjs"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "dependencies": {
29
+ "@msgpack/msgpack": "^3.1.3"
30
+ },
31
+ "peerDependencies": {
32
+ "@univerjs-pro/collaboration-service": "1.5.2",
33
+ "@univerjs/protocol": "1.5.2",
34
+ "pg": "^8.11.0"
35
+ }
6
36
  }