@univerjs-pro/collaboration-database-postgres 0.0.0-stage → 1.4.0
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 +201 -0
- package/README.md +35 -2
- package/README.zh-CN.md +37 -0
- package/dist/index.cjs +168 -0
- package/dist/index.d.ts +60 -0
- package/dist/index.mjs +3 -0
- package/package.json +33 -3
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,36 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @univerjs-pro/collaboration-database-postgres
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
## Create the Adapter
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add \
|
|
11
|
+
@univerjs-pro/collaboration-service \
|
|
12
|
+
@univerjs-pro/collaboration-database-postgres \
|
|
13
|
+
pg
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
The application owns the connection pool. `create` initializes the schema in an empty database and verifies an existing one:
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { PostgresDatabaseAdapter } from '@univerjs-pro/collaboration-database-postgres';
|
|
20
|
+
import { UniverCollabService } from '@univerjs-pro/collaboration-service';
|
|
21
|
+
import { Pool } from 'pg';
|
|
22
|
+
|
|
23
|
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
|
24
|
+
const database = await PostgresDatabaseAdapter.create({ pool });
|
|
25
|
+
const service = new UniverCollabService({ dbAdapter: database });
|
|
26
|
+
|
|
27
|
+
await service.dispose();
|
|
28
|
+
await pool.end();
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Pass the Adapter to `UniverCollabService` as `dbAdapter`. Dispose the Service first, then end the pool.
|
|
32
|
+
|
|
33
|
+
## PostgreSQL behavior
|
|
34
|
+
|
|
35
|
+
- 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.
|
package/README.zh-CN.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
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
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add \
|
|
11
|
+
@univerjs-pro/collaboration-service \
|
|
12
|
+
@univerjs-pro/collaboration-database-postgres \
|
|
13
|
+
pg
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
连接池由应用持有。`create` 为空数据库初始化 schema,已有 schema 时只做校验:
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { PostgresDatabaseAdapter } from '@univerjs-pro/collaboration-database-postgres';
|
|
20
|
+
import { UniverCollabService } from '@univerjs-pro/collaboration-service';
|
|
21
|
+
import { Pool } from 'pg';
|
|
22
|
+
|
|
23
|
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
|
24
|
+
const database = await PostgresDatabaseAdapter.create({ pool });
|
|
25
|
+
const service = new UniverCollabService({ dbAdapter: database });
|
|
26
|
+
|
|
27
|
+
await service.dispose();
|
|
28
|
+
await pool.end();
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
将 Adapter 作为 `dbAdapter` 传给 `UniverCollabService`。先释放 Service,再关闭连接池。
|
|
32
|
+
|
|
33
|
+
## PostgreSQL 行为
|
|
34
|
+
|
|
35
|
+
- 表位于 `collaboration` schema 中:`units`、`snapshots`、`changesets`、`sheet_blocks` 和
|
|
36
|
+
`schema_versions`;协议对象以 MessagePack `BYTEA` 保存。
|
|
37
|
+
- `schema_versions` 记录 `('core', 1)`,按组件与其他协同 Adapter 共用。`create` 打开这个核心版本的 schema,迁移作为独立步骤显式执行。
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
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`,`
|
|
2
|
+
SELECT unit_id AS "unitID", type, head_revision AS "headRevision",
|
|
3
|
+
creator_id AS "creatorID", created_at_ms AS "createdAt"
|
|
4
|
+
FROM collaboration.units
|
|
5
|
+
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`,`
|
|
7
|
+
SELECT s.payload
|
|
8
|
+
FROM collaboration.snapshots s
|
|
9
|
+
JOIN collaboration.units u USING (unit_id)
|
|
10
|
+
WHERE u.unit_id = $1 AND u.deleted_status IS NULL
|
|
11
|
+
ORDER BY s.revision DESC
|
|
12
|
+
LIMIT 1
|
|
13
|
+
`,[t]):await this._query(`get_snapshot_at_revision`,`
|
|
14
|
+
SELECT s.payload
|
|
15
|
+
FROM collaboration.snapshots s
|
|
16
|
+
JOIN collaboration.units u USING (unit_id)
|
|
17
|
+
WHERE u.unit_id = $1 AND u.deleted_status IS NULL AND s.revision <= $2
|
|
18
|
+
ORDER BY s.revision DESC
|
|
19
|
+
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`,`
|
|
21
|
+
SELECT s.unit_id AS "unitID", u.type, s.revision AS rev
|
|
22
|
+
FROM collaboration.snapshots s
|
|
23
|
+
JOIN collaboration.units u USING (unit_id)
|
|
24
|
+
WHERE u.unit_id = $1 AND u.deleted_status IS NULL
|
|
25
|
+
ORDER BY s.revision DESC
|
|
26
|
+
LIMIT 1
|
|
27
|
+
`,[t]):await this._query(`get_snapshot_info_at_revision`,`
|
|
28
|
+
SELECT s.unit_id AS "unitID", u.type, s.revision AS rev
|
|
29
|
+
FROM collaboration.snapshots s
|
|
30
|
+
JOIN collaboration.units u USING (unit_id)
|
|
31
|
+
WHERE u.unit_id = $1 AND u.deleted_status IS NULL AND s.revision <= $2
|
|
32
|
+
ORDER BY s.revision DESC
|
|
33
|
+
LIMIT 1
|
|
34
|
+
`,[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
|
|
36
|
+
FROM collaboration.units u
|
|
37
|
+
LEFT JOIN collaboration.changesets c ON c.unit_id = u.unit_id AND c.revision > $2
|
|
38
|
+
WHERE u.unit_id = $1 AND u.deleted_status IS NULL
|
|
39
|
+
ORDER BY c.revision
|
|
40
|
+
`,[t,r.from]):await this._query(`get_changesets_in_range`,`
|
|
41
|
+
SELECT c.payload
|
|
42
|
+
FROM collaboration.units u
|
|
43
|
+
LEFT JOIN collaboration.changesets c
|
|
44
|
+
ON c.unit_id = u.unit_id AND c.revision > $2 AND c.revision <= $3
|
|
45
|
+
WHERE u.unit_id = $1 AND u.deleted_status IS NULL
|
|
46
|
+
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`,`
|
|
48
|
+
SELECT b.payload
|
|
49
|
+
FROM collaboration.sheet_blocks b
|
|
50
|
+
JOIN collaboration.units u USING (unit_id)
|
|
51
|
+
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`,`
|
|
53
|
+
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)
|
|
56
|
+
ON CONFLICT (unit_id) DO NOTHING
|
|
57
|
+
RETURNING unit_id
|
|
58
|
+
), saved_blocks AS (
|
|
59
|
+
INSERT INTO collaboration.sheet_blocks (unit_id, block_id, payload)
|
|
60
|
+
SELECT u.unit_id, b.id, b.payload
|
|
61
|
+
FROM created u
|
|
62
|
+
CROSS JOIN unnest($4::text[], $5::bytea[]) AS b(id, payload)
|
|
63
|
+
)
|
|
64
|
+
INSERT INTO collaboration.snapshots (unit_id, revision, payload)
|
|
65
|
+
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`,`
|
|
67
|
+
WITH updated_unit AS (
|
|
68
|
+
UPDATE collaboration.units
|
|
69
|
+
SET head_revision = $2
|
|
70
|
+
WHERE unit_id = $1 AND deleted_status IS NULL AND head_revision = $2::integer - 1
|
|
71
|
+
RETURNING unit_id, head_revision
|
|
72
|
+
)
|
|
73
|
+
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`,`
|
|
78
|
+
WITH locked_unit AS MATERIALIZED (
|
|
79
|
+
SELECT unit_id, type, head_revision, deleted_status
|
|
80
|
+
FROM collaboration.units
|
|
81
|
+
WHERE unit_id = $1
|
|
82
|
+
FOR UPDATE
|
|
83
|
+
), valid_unit AS (
|
|
84
|
+
SELECT unit_id FROM locked_unit
|
|
85
|
+
WHERE deleted_status IS NULL AND type = $2 AND $3::integer BETWEEN 1 AND head_revision
|
|
86
|
+
), saved_blocks AS (
|
|
87
|
+
INSERT INTO collaboration.sheet_blocks (unit_id, block_id, payload)
|
|
88
|
+
SELECT u.unit_id, b.id, b.payload
|
|
89
|
+
FROM valid_unit u
|
|
90
|
+
CROSS JOIN unnest($5::text[], $6::bytea[]) AS b(id, payload)
|
|
91
|
+
ON CONFLICT (unit_id, block_id) DO UPDATE SET payload = excluded.payload
|
|
92
|
+
), saved_snapshot AS (
|
|
93
|
+
INSERT INTO collaboration.snapshots (unit_id, revision, payload)
|
|
94
|
+
SELECT unit_id, $3, $4 FROM valid_unit
|
|
95
|
+
ON CONFLICT (unit_id, revision) DO UPDATE SET payload = excluded.payload
|
|
96
|
+
RETURNING revision
|
|
97
|
+
)
|
|
98
|
+
SELECT deleted_status AS "deletedStatus", EXISTS (SELECT 1 FROM saved_snapshot) AS saved
|
|
99
|
+
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`,`
|
|
101
|
+
WITH deleted_units AS (
|
|
102
|
+
UPDATE collaboration.units
|
|
103
|
+
SET deleted_at_ms = $2, deleted_status = 'hard'
|
|
104
|
+
WHERE unit_id = ANY($1::text[]) AND deleted_status IS DISTINCT FROM 'hard'
|
|
105
|
+
RETURNING unit_id
|
|
106
|
+
), removed_snapshots AS (
|
|
107
|
+
DELETE FROM collaboration.snapshots WHERE unit_id IN (SELECT unit_id FROM deleted_units)
|
|
108
|
+
), removed_blocks AS (
|
|
109
|
+
DELETE FROM collaboration.sheet_blocks WHERE unit_id IN (SELECT unit_id FROM deleted_units)
|
|
110
|
+
)
|
|
111
|
+
DELETE FROM collaboration.changesets WHERE unit_id IN (SELECT unit_id FROM deleted_units)
|
|
112
|
+
`,[r,a],e):await this._query(`soft_delete_units`,`
|
|
113
|
+
UPDATE collaboration.units
|
|
114
|
+
SET deleted_at_ms = $2, deleted_status = 'soft'
|
|
115
|
+
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`,`
|
|
117
|
+
UPDATE collaboration.units SET deleted_at_ms = NULL, deleted_status = NULL
|
|
118
|
+
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`,`
|
|
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"
|
|
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})}_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;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
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";
|
|
4
|
+
|
|
5
|
+
//#region src/postgres-database-adapter.d.ts
|
|
6
|
+
interface PostgresDatabaseAdapterOptions {
|
|
7
|
+
/** Connection pool owned by the application; the adapter never ends it. */
|
|
8
|
+
readonly pool: Pool;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* PostgreSQL implementation of the collaboration persistence contract, built on `node-postgres`.
|
|
12
|
+
* Protocol objects are stored as MessagePack `BYTEA` payloads.
|
|
13
|
+
*
|
|
14
|
+
* Create instances with {@link PostgresDatabaseAdapter.create}, which initializes an empty
|
|
15
|
+
* `collaboration` schema and rejects one whose core version differs from the one this adapter writes.
|
|
16
|
+
*/
|
|
17
|
+
declare class PostgresDatabaseAdapter implements IDatabaseAdapter {
|
|
18
|
+
private readonly _pool;
|
|
19
|
+
private readonly _encoder;
|
|
20
|
+
private readonly _decoder;
|
|
21
|
+
private constructor();
|
|
22
|
+
/** Initializes or verifies the schema, then returns a ready adapter. */
|
|
23
|
+
static create(options: PostgresDatabaseAdapterOptions): Promise<PostgresDatabaseAdapter>;
|
|
24
|
+
getUnit(_ctx: DatabaseContext, unitID: string): Promise<UnitRecord | null>;
|
|
25
|
+
/** Reads the latest snapshot, optionally bounded by the specified revision. */
|
|
26
|
+
getSnapshot(_ctx: DatabaseContext, unitID: string, options?: {
|
|
27
|
+
readonly revision?: number;
|
|
28
|
+
}): Promise<ISnapshot | null>;
|
|
29
|
+
/** Reads metadata with the same selection rules as getSnapshot, without decoding the payload. */
|
|
30
|
+
getSnapshotInfo(_ctx: DatabaseContext, unitID: string, options?: {
|
|
31
|
+
readonly revision?: number;
|
|
32
|
+
}): Promise<SnapshotInfo | null>;
|
|
33
|
+
/** Reads changesets in (from, to], ordered by revision. */
|
|
34
|
+
getChangesets(_ctx: DatabaseContext, unitID: string, range: {
|
|
35
|
+
readonly from: number;
|
|
36
|
+
readonly to?: number;
|
|
37
|
+
}): Promise<readonly IChangeset[] | null>;
|
|
38
|
+
getSheetBlock(_ctx: DatabaseContext, unitID: string, blockID: string): Promise<ISheetBlock | null>;
|
|
39
|
+
/** Atomically creates a Unit at revision 1 with its snapshot and blocks; an existing active Unit returns its record. */
|
|
40
|
+
createUnit(_ctx: DatabaseContext, input: CreateUnitDatabaseInput): Promise<CreateUnitDatabaseResult>;
|
|
41
|
+
/** Confirms the changeset when the stored head equals `revision - 1`; otherwise reports the actual head. */
|
|
42
|
+
commitChangeset(ctx: SubmitDatabaseContext, input: CommitChangesetInput): Promise<CommitChangesetResult>;
|
|
43
|
+
/** Publishes a snapshot together with the blocks it references. */
|
|
44
|
+
saveSnapshot(_ctx: DatabaseContext, input: SaveSnapshotInput): Promise<void>;
|
|
45
|
+
/** Deletes the whole batch or fails it; hard deletion keeps the Unit row as a permanent marker. */
|
|
46
|
+
deleteUnits(_ctx: DatabaseContext, input: DeleteUnitsDatabaseInput): Promise<DeleteUnitsDatabaseResult>;
|
|
47
|
+
/** Recovers the whole batch or fails it; hard-deleted IDs cannot be recovered. */
|
|
48
|
+
recoverUnits(_ctx: DatabaseContext, input: RecoverUnitsDatabaseInput): Promise<RecoverUnitsDatabaseResult>;
|
|
49
|
+
private _initializeSchema;
|
|
50
|
+
private _readSchemaVersion;
|
|
51
|
+
private _createSchema;
|
|
52
|
+
private _transaction;
|
|
53
|
+
private _lockUnits;
|
|
54
|
+
private _query;
|
|
55
|
+
private _encode;
|
|
56
|
+
private _decode;
|
|
57
|
+
private _encodeBlocks;
|
|
58
|
+
}
|
|
59
|
+
//#endregion
|
|
60
|
+
export { PostgresDatabaseAdapter, type PostgresDatabaseAdapterOptions };
|
package/dist/index.mjs
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@univerjs-pro/collaboration-database-postgres",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
|
|
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.4.0",
|
|
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.4.0",
|
|
33
|
+
"@univerjs/protocol": "1.4.0",
|
|
34
|
+
"pg": "^8.11.0"
|
|
35
|
+
}
|
|
6
36
|
}
|