@spear340000/adapter-postgres 0.1.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 +66 -0
- package/dist/index.d.mts +81 -0
- package/dist/index.d.ts +81 -0
- package/dist/index.js +236 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +234 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +55 -0
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
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# @spear340000/adapter-postgres
|
|
2
|
+
|
|
3
|
+
RouteFlow 공식 지원 PostgreSQL 어댑터.
|
|
4
|
+
|
|
5
|
+
기존 REST 엔드포인트 작성 방식은 유지하면서, PostgreSQL 변경이 생기면 해당 live 엔드포인트를 구독 중인 클라이언트에게 최신 결과를 자동 푸시하는 흐름에 연결됩니다.
|
|
6
|
+
|
|
7
|
+
`LISTEN/NOTIFY` 기반으로 DB 변경을 감지합니다.
|
|
8
|
+
|
|
9
|
+
## 설치
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pnpm add @spear340000/adapter-postgres pg
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## 사용법
|
|
16
|
+
|
|
17
|
+
```typescript
|
|
18
|
+
import { createApp } from '@spear340000/core'
|
|
19
|
+
import { PostgresAdapter } from '@spear340000/adapter-postgres'
|
|
20
|
+
|
|
21
|
+
const app = createApp({
|
|
22
|
+
adapter: new PostgresAdapter({
|
|
23
|
+
connectionString: process.env.DATABASE_URL,
|
|
24
|
+
}),
|
|
25
|
+
port: 3000,
|
|
26
|
+
})
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
이 어댑터는 `@Reactive({ watch: 'table' })`로 선언한 엔드포인트와 연결되어, 테이블 변경 시 해당 엔드포인트 결과를 다시 계산하게 만듭니다.
|
|
30
|
+
|
|
31
|
+
## 동작 원리
|
|
32
|
+
|
|
33
|
+
1. `connect()` 시 전용 `pg.Client`로 연결 후 공유 트리거 함수 설치
|
|
34
|
+
2. `onChange(table, cb)` 호출 시 해당 테이블에 `AFTER INSERT OR UPDATE OR DELETE` 트리거 자동 설치
|
|
35
|
+
3. 변경 발생 → 트리거가 `pg_notify('reactive_api_changes', payload)` 호출
|
|
36
|
+
4. LISTEN 커넥션이 페이로드를 수신 → `ChangeEvent`로 변환 → 콜백 호출
|
|
37
|
+
5. `disconnect()` 시 모든 트리거와 함수 자동 제거
|
|
38
|
+
|
|
39
|
+
## 포지션
|
|
40
|
+
|
|
41
|
+
- 상태: `official`
|
|
42
|
+
- 권장 대상: PostgreSQL 기반 서비스
|
|
43
|
+
- 연결 방식: 네이티브 DB 변경 감지
|
|
44
|
+
|
|
45
|
+
## 옵션
|
|
46
|
+
|
|
47
|
+
```typescript
|
|
48
|
+
new PostgresAdapter({
|
|
49
|
+
connectionString: 'postgresql://user:pass@localhost:5432/mydb',
|
|
50
|
+
schema: 'public', // 기본값
|
|
51
|
+
triggerPrefix: 'reactive_api', // 기본값
|
|
52
|
+
})
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## 주의사항
|
|
56
|
+
|
|
57
|
+
- **8KB 제한**: PostgreSQL `NOTIFY` 페이로드는 8000바이트 미만이어야 합니다. 큰 행은 `newRow/oldRow`가 `null`로 전달됩니다. 필요 시 `event.newRow === null` 검사 후 재조회하세요.
|
|
58
|
+
- **전용 커넥션**: LISTEN을 위해 별도 `pg.Client`를 유지합니다. 애플리케이션의 커넥션 풀과 별개입니다.
|
|
59
|
+
- **트리거 권한**: 어댑터를 실행하는 DB 유저에게 해당 테이블에 트리거를 생성할 권한이 필요합니다.
|
|
60
|
+
|
|
61
|
+
## 통합 테스트
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
POSTGRES_TEST_URL=postgresql://user:pass@localhost:5432/testdb \
|
|
65
|
+
pnpm test:integration
|
|
66
|
+
```
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { DatabaseAdapter, ChangeEvent } from '@spear340000/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Configuration options for PostgresAdapter.
|
|
5
|
+
*/
|
|
6
|
+
interface PostgresAdapterOptions {
|
|
7
|
+
/**
|
|
8
|
+
* PostgreSQL connection string.
|
|
9
|
+
* e.g. 'postgresql://user:password@localhost:5432/dbname'
|
|
10
|
+
*/
|
|
11
|
+
connectionString: string;
|
|
12
|
+
/**
|
|
13
|
+
* Schema to install trigger functions in.
|
|
14
|
+
* Defaults to 'public'.
|
|
15
|
+
*/
|
|
16
|
+
schema?: string;
|
|
17
|
+
/**
|
|
18
|
+
* Name prefix for generated trigger functions and triggers.
|
|
19
|
+
* Defaults to 'reactive_api'.
|
|
20
|
+
*/
|
|
21
|
+
triggerPrefix?: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The raw JSON payload delivered by the PostgreSQL NOTIFY.
|
|
25
|
+
* Must stay in sync with the trigger function SQL in trigger-sql.ts.
|
|
26
|
+
*/
|
|
27
|
+
interface NotifyPayload {
|
|
28
|
+
table: string;
|
|
29
|
+
operation: 'INSERT' | 'UPDATE' | 'DELETE';
|
|
30
|
+
new_row: Record<string, unknown> | null;
|
|
31
|
+
old_row: Record<string, unknown> | null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* PostgreSQL database adapter for RouteFlow.
|
|
36
|
+
*
|
|
37
|
+
* Uses a dedicated `pg.Client` (not a pool) for LISTEN so the connection
|
|
38
|
+
* stays open and notifications are never missed. A separate pool/client
|
|
39
|
+
* can still be used by the application for regular queries.
|
|
40
|
+
*
|
|
41
|
+
* Change detection mechanism:
|
|
42
|
+
* - On `onChange(table)`: installs a per-table AFTER INSERT/UPDATE/DELETE trigger
|
|
43
|
+
* that calls `pg_notify` with a JSON payload.
|
|
44
|
+
* - A single LISTEN connection subscribes to one shared channel for all tables.
|
|
45
|
+
* - Payloads > 7900 bytes are sent without row data (`_truncated: true`);
|
|
46
|
+
* subscribers receive a ChangeEvent with `newRow: null` / `oldRow: null`.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* ```ts
|
|
50
|
+
* const adapter = new PostgresAdapter({
|
|
51
|
+
* connectionString: process.env.DATABASE_URL,
|
|
52
|
+
* })
|
|
53
|
+
* await adapter.connect()
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
declare class PostgresAdapter implements DatabaseAdapter {
|
|
57
|
+
private listenClient;
|
|
58
|
+
private readonly schema;
|
|
59
|
+
private readonly prefix;
|
|
60
|
+
private readonly connectionString;
|
|
61
|
+
/** table → Set<callback> */
|
|
62
|
+
private readonly listeners;
|
|
63
|
+
/** Tables for which a trigger has already been installed */
|
|
64
|
+
private readonly installedTriggers;
|
|
65
|
+
constructor(options: PostgresAdapterOptions);
|
|
66
|
+
/** Connect the LISTEN client and install the shared trigger function. */
|
|
67
|
+
connect(): Promise<void>;
|
|
68
|
+
/** Disconnect the LISTEN client and optionally clean up triggers. */
|
|
69
|
+
disconnect(): Promise<void>;
|
|
70
|
+
/**
|
|
71
|
+
* Register a callback for changes on `table`.
|
|
72
|
+
* Installs a PostgreSQL trigger on first registration for this table.
|
|
73
|
+
*
|
|
74
|
+
* @returns An unsubscribe function.
|
|
75
|
+
*/
|
|
76
|
+
onChange(table: string, callback: (event: ChangeEvent) => void): () => void;
|
|
77
|
+
private ensureTriggerInstalled;
|
|
78
|
+
private handleNotification;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export { type NotifyPayload, PostgresAdapter, type PostgresAdapterOptions };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { DatabaseAdapter, ChangeEvent } from '@spear340000/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Configuration options for PostgresAdapter.
|
|
5
|
+
*/
|
|
6
|
+
interface PostgresAdapterOptions {
|
|
7
|
+
/**
|
|
8
|
+
* PostgreSQL connection string.
|
|
9
|
+
* e.g. 'postgresql://user:password@localhost:5432/dbname'
|
|
10
|
+
*/
|
|
11
|
+
connectionString: string;
|
|
12
|
+
/**
|
|
13
|
+
* Schema to install trigger functions in.
|
|
14
|
+
* Defaults to 'public'.
|
|
15
|
+
*/
|
|
16
|
+
schema?: string;
|
|
17
|
+
/**
|
|
18
|
+
* Name prefix for generated trigger functions and triggers.
|
|
19
|
+
* Defaults to 'reactive_api'.
|
|
20
|
+
*/
|
|
21
|
+
triggerPrefix?: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The raw JSON payload delivered by the PostgreSQL NOTIFY.
|
|
25
|
+
* Must stay in sync with the trigger function SQL in trigger-sql.ts.
|
|
26
|
+
*/
|
|
27
|
+
interface NotifyPayload {
|
|
28
|
+
table: string;
|
|
29
|
+
operation: 'INSERT' | 'UPDATE' | 'DELETE';
|
|
30
|
+
new_row: Record<string, unknown> | null;
|
|
31
|
+
old_row: Record<string, unknown> | null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* PostgreSQL database adapter for RouteFlow.
|
|
36
|
+
*
|
|
37
|
+
* Uses a dedicated `pg.Client` (not a pool) for LISTEN so the connection
|
|
38
|
+
* stays open and notifications are never missed. A separate pool/client
|
|
39
|
+
* can still be used by the application for regular queries.
|
|
40
|
+
*
|
|
41
|
+
* Change detection mechanism:
|
|
42
|
+
* - On `onChange(table)`: installs a per-table AFTER INSERT/UPDATE/DELETE trigger
|
|
43
|
+
* that calls `pg_notify` with a JSON payload.
|
|
44
|
+
* - A single LISTEN connection subscribes to one shared channel for all tables.
|
|
45
|
+
* - Payloads > 7900 bytes are sent without row data (`_truncated: true`);
|
|
46
|
+
* subscribers receive a ChangeEvent with `newRow: null` / `oldRow: null`.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* ```ts
|
|
50
|
+
* const adapter = new PostgresAdapter({
|
|
51
|
+
* connectionString: process.env.DATABASE_URL,
|
|
52
|
+
* })
|
|
53
|
+
* await adapter.connect()
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
declare class PostgresAdapter implements DatabaseAdapter {
|
|
57
|
+
private listenClient;
|
|
58
|
+
private readonly schema;
|
|
59
|
+
private readonly prefix;
|
|
60
|
+
private readonly connectionString;
|
|
61
|
+
/** table → Set<callback> */
|
|
62
|
+
private readonly listeners;
|
|
63
|
+
/** Tables for which a trigger has already been installed */
|
|
64
|
+
private readonly installedTriggers;
|
|
65
|
+
constructor(options: PostgresAdapterOptions);
|
|
66
|
+
/** Connect the LISTEN client and install the shared trigger function. */
|
|
67
|
+
connect(): Promise<void>;
|
|
68
|
+
/** Disconnect the LISTEN client and optionally clean up triggers. */
|
|
69
|
+
disconnect(): Promise<void>;
|
|
70
|
+
/**
|
|
71
|
+
* Register a callback for changes on `table`.
|
|
72
|
+
* Installs a PostgreSQL trigger on first registration for this table.
|
|
73
|
+
*
|
|
74
|
+
* @returns An unsubscribe function.
|
|
75
|
+
*/
|
|
76
|
+
onChange(table: string, callback: (event: ChangeEvent) => void): () => void;
|
|
77
|
+
private ensureTriggerInstalled;
|
|
78
|
+
private handleNotification;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export { type NotifyPayload, PostgresAdapter, type PostgresAdapterOptions };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var pg = require('pg');
|
|
4
|
+
var core = require('@spear340000/core');
|
|
5
|
+
|
|
6
|
+
// src/postgres-adapter.ts
|
|
7
|
+
|
|
8
|
+
// src/trigger-sql.ts
|
|
9
|
+
function notifyChannel(prefix) {
|
|
10
|
+
return `${prefix}_changes`;
|
|
11
|
+
}
|
|
12
|
+
function createTriggerFunctionSQL(schema, prefix) {
|
|
13
|
+
const fnName = `${schema}.${prefix}_notify_changes`;
|
|
14
|
+
const channel = notifyChannel(prefix);
|
|
15
|
+
return `
|
|
16
|
+
CREATE OR REPLACE FUNCTION ${fnName}()
|
|
17
|
+
RETURNS trigger
|
|
18
|
+
LANGUAGE plpgsql
|
|
19
|
+
AS $$
|
|
20
|
+
DECLARE
|
|
21
|
+
payload TEXT;
|
|
22
|
+
new_row JSON;
|
|
23
|
+
old_row JSON;
|
|
24
|
+
BEGIN
|
|
25
|
+
IF (TG_OP = 'DELETE') THEN
|
|
26
|
+
new_row := NULL;
|
|
27
|
+
old_row := row_to_json(OLD);
|
|
28
|
+
ELSIF (TG_OP = 'INSERT') THEN
|
|
29
|
+
new_row := row_to_json(NEW);
|
|
30
|
+
old_row := NULL;
|
|
31
|
+
ELSE
|
|
32
|
+
new_row := row_to_json(NEW);
|
|
33
|
+
old_row := row_to_json(OLD);
|
|
34
|
+
END IF;
|
|
35
|
+
|
|
36
|
+
payload := json_build_object(
|
|
37
|
+
'table', TG_TABLE_NAME,
|
|
38
|
+
'operation', TG_OP,
|
|
39
|
+
'new_row', new_row,
|
|
40
|
+
'old_row', old_row
|
|
41
|
+
)::text;
|
|
42
|
+
|
|
43
|
+
-- Truncate gracefully if payload exceeds pg's 8000-byte NOTIFY limit
|
|
44
|
+
IF octet_length(payload) > 7900 THEN
|
|
45
|
+
payload := json_build_object(
|
|
46
|
+
'table', TG_TABLE_NAME,
|
|
47
|
+
'operation', TG_OP,
|
|
48
|
+
'new_row', NULL,
|
|
49
|
+
'old_row', NULL,
|
|
50
|
+
'_truncated', true
|
|
51
|
+
)::text;
|
|
52
|
+
END IF;
|
|
53
|
+
|
|
54
|
+
PERFORM pg_notify('${channel}', payload);
|
|
55
|
+
RETURN COALESCE(NEW, OLD);
|
|
56
|
+
END;
|
|
57
|
+
$$;
|
|
58
|
+
`.trim();
|
|
59
|
+
}
|
|
60
|
+
function createTableTriggerSQL(schema, prefix, table) {
|
|
61
|
+
const triggerName = `${prefix}_notify_${table}`;
|
|
62
|
+
const fnName = `${schema}.${prefix}_notify_changes`;
|
|
63
|
+
return `
|
|
64
|
+
DO $$
|
|
65
|
+
BEGIN
|
|
66
|
+
IF NOT EXISTS (
|
|
67
|
+
SELECT 1 FROM pg_trigger
|
|
68
|
+
WHERE tgname = '${triggerName}'
|
|
69
|
+
AND tgrelid = '${schema}.${table}'::regclass
|
|
70
|
+
) THEN
|
|
71
|
+
CREATE TRIGGER ${triggerName}
|
|
72
|
+
AFTER INSERT OR UPDATE OR DELETE ON ${schema}.${table}
|
|
73
|
+
FOR EACH ROW EXECUTE FUNCTION ${fnName}();
|
|
74
|
+
END IF;
|
|
75
|
+
END;
|
|
76
|
+
$$;
|
|
77
|
+
`.trim();
|
|
78
|
+
}
|
|
79
|
+
function dropTableTriggerSQL(schema, prefix, table) {
|
|
80
|
+
const triggerName = `${prefix}_notify_${table}`;
|
|
81
|
+
return `DROP TRIGGER IF EXISTS ${triggerName} ON ${schema}.${table};`;
|
|
82
|
+
}
|
|
83
|
+
function dropTriggerFunctionSQL(schema, prefix) {
|
|
84
|
+
return `DROP FUNCTION IF EXISTS ${schema}.${prefix}_notify_changes();`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// src/postgres-adapter.ts
|
|
88
|
+
var PostgresAdapter = class {
|
|
89
|
+
listenClient = null;
|
|
90
|
+
schema;
|
|
91
|
+
prefix;
|
|
92
|
+
connectionString;
|
|
93
|
+
/** table → Set<callback> */
|
|
94
|
+
listeners = /* @__PURE__ */ new Map();
|
|
95
|
+
/** Tables for which a trigger has already been installed */
|
|
96
|
+
installedTriggers = /* @__PURE__ */ new Set();
|
|
97
|
+
constructor(options) {
|
|
98
|
+
this.connectionString = options.connectionString;
|
|
99
|
+
this.schema = options.schema ?? "public";
|
|
100
|
+
this.prefix = options.triggerPrefix ?? "reactive_api";
|
|
101
|
+
}
|
|
102
|
+
// ---------------------------------------------------------------------------
|
|
103
|
+
// DatabaseAdapter interface
|
|
104
|
+
// ---------------------------------------------------------------------------
|
|
105
|
+
/** Connect the LISTEN client and install the shared trigger function. */
|
|
106
|
+
async connect() {
|
|
107
|
+
if (this.listenClient) return;
|
|
108
|
+
const client = new pg.Client({ connectionString: this.connectionString });
|
|
109
|
+
try {
|
|
110
|
+
await client.connect();
|
|
111
|
+
} catch (err) {
|
|
112
|
+
throw new core.ReactiveApiError(
|
|
113
|
+
"POSTGRES_CONNECT_FAILED",
|
|
114
|
+
`Failed to connect to PostgreSQL: ${errorMessage(err)}`
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
await client.query(createTriggerFunctionSQL(this.schema, this.prefix));
|
|
119
|
+
} catch (err) {
|
|
120
|
+
await client.end().catch(() => void 0);
|
|
121
|
+
throw new core.ReactiveApiError(
|
|
122
|
+
"POSTGRES_TRIGGER_FUNCTION_FAILED",
|
|
123
|
+
`Failed to install trigger function: ${errorMessage(err)}`
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
const channel = notifyChannel(this.prefix);
|
|
127
|
+
await client.query(`LISTEN "${channel}"`);
|
|
128
|
+
client.on("notification", (msg) => {
|
|
129
|
+
if (msg.channel !== channel || !msg.payload) return;
|
|
130
|
+
this.handleNotification(msg.payload);
|
|
131
|
+
});
|
|
132
|
+
client.on("error", (err) => {
|
|
133
|
+
console.error("[RouteFlow/postgres] LISTEN client error:", err.message);
|
|
134
|
+
});
|
|
135
|
+
this.listenClient = client;
|
|
136
|
+
}
|
|
137
|
+
/** Disconnect the LISTEN client and optionally clean up triggers. */
|
|
138
|
+
async disconnect() {
|
|
139
|
+
if (!this.listenClient) return;
|
|
140
|
+
const client = this.listenClient;
|
|
141
|
+
this.listenClient = null;
|
|
142
|
+
for (const table of this.installedTriggers) {
|
|
143
|
+
await client.query(dropTableTriggerSQL(this.schema, this.prefix, table)).catch(() => void 0);
|
|
144
|
+
}
|
|
145
|
+
this.installedTriggers.clear();
|
|
146
|
+
await client.query(dropTriggerFunctionSQL(this.schema, this.prefix)).catch(() => void 0);
|
|
147
|
+
await client.end().catch(() => void 0);
|
|
148
|
+
this.listeners.clear();
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Register a callback for changes on `table`.
|
|
152
|
+
* Installs a PostgreSQL trigger on first registration for this table.
|
|
153
|
+
*
|
|
154
|
+
* @returns An unsubscribe function.
|
|
155
|
+
*/
|
|
156
|
+
onChange(table, callback) {
|
|
157
|
+
if (!this.listeners.has(table)) {
|
|
158
|
+
this.listeners.set(table, /* @__PURE__ */ new Set());
|
|
159
|
+
}
|
|
160
|
+
this.listeners.get(table).add(callback);
|
|
161
|
+
this.ensureTriggerInstalled(table).catch((err) => {
|
|
162
|
+
console.error(
|
|
163
|
+
`[RouteFlow/postgres] Failed to install trigger for table "${table}":`,
|
|
164
|
+
errorMessage(err)
|
|
165
|
+
);
|
|
166
|
+
});
|
|
167
|
+
return () => {
|
|
168
|
+
this.listeners.get(table)?.delete(callback);
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
// ---------------------------------------------------------------------------
|
|
172
|
+
// Private helpers
|
|
173
|
+
// ---------------------------------------------------------------------------
|
|
174
|
+
async ensureTriggerInstalled(table) {
|
|
175
|
+
if (this.installedTriggers.has(table)) return;
|
|
176
|
+
if (!this.listenClient) return;
|
|
177
|
+
try {
|
|
178
|
+
await this.listenClient.query(
|
|
179
|
+
createTableTriggerSQL(this.schema, this.prefix, table)
|
|
180
|
+
);
|
|
181
|
+
this.installedTriggers.add(table);
|
|
182
|
+
} catch (err) {
|
|
183
|
+
if (err instanceof pg.DatabaseError) {
|
|
184
|
+
throw new core.ReactiveApiError(
|
|
185
|
+
"POSTGRES_TRIGGER_INSTALL_FAILED",
|
|
186
|
+
`Failed to install trigger on "${table}": ${err.message}`
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
throw err;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
handleNotification(rawPayload) {
|
|
193
|
+
let payload;
|
|
194
|
+
try {
|
|
195
|
+
payload = JSON.parse(rawPayload);
|
|
196
|
+
} catch {
|
|
197
|
+
console.error("[RouteFlow/postgres] Malformed NOTIFY payload:", rawPayload);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
if (!isNotifyPayload(payload)) {
|
|
201
|
+
console.error("[RouteFlow/postgres] Unexpected payload shape:", payload);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
const event = {
|
|
205
|
+
table: payload.table,
|
|
206
|
+
operation: payload.operation,
|
|
207
|
+
newRow: payload.new_row,
|
|
208
|
+
oldRow: payload.old_row,
|
|
209
|
+
timestamp: Date.now()
|
|
210
|
+
};
|
|
211
|
+
const callbacks = this.listeners.get(payload.table);
|
|
212
|
+
if (!callbacks) return;
|
|
213
|
+
for (const cb of callbacks) {
|
|
214
|
+
try {
|
|
215
|
+
cb(event);
|
|
216
|
+
} catch (err) {
|
|
217
|
+
console.error(
|
|
218
|
+
`[RouteFlow/postgres] Listener error on table "${payload.table}":`,
|
|
219
|
+
errorMessage(err)
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
function isNotifyPayload(value) {
|
|
226
|
+
if (typeof value !== "object" || value === null) return false;
|
|
227
|
+
const v = value;
|
|
228
|
+
return typeof v["table"] === "string" && (v["operation"] === "INSERT" || v["operation"] === "UPDATE" || v["operation"] === "DELETE");
|
|
229
|
+
}
|
|
230
|
+
function errorMessage(err) {
|
|
231
|
+
return err instanceof Error ? err.message : String(err);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
exports.PostgresAdapter = PostgresAdapter;
|
|
235
|
+
//# sourceMappingURL=index.js.map
|
|
236
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/trigger-sql.ts","../src/postgres-adapter.ts"],"names":["Client","ReactiveApiError","DatabaseError"],"mappings":";;;;;;;;AAmBO,SAAS,cAAc,MAAA,EAAwB;AACpD,EAAA,OAAO,GAAG,MAAM,CAAA,QAAA,CAAA;AAClB;AAMO,SAAS,wBAAA,CAAyB,QAAgB,MAAA,EAAwB;AAC/E,EAAA,MAAM,MAAA,GAAS,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,MAAM,CAAA,eAAA,CAAA;AAClC,EAAA,MAAM,OAAA,GAAU,cAAc,MAAM,CAAA;AAEpC,EAAA,OAAO;AAAA,2BAAA,EACoB,MAAM,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA,qBAAA,EAsCZ,OAAO,CAAA;AAAA;AAAA;AAAA;AAAA,CAAA,CAI5B,IAAA,EAAK;AACP;AAOO,SAAS,qBAAA,CACd,MAAA,EACA,MAAA,EACA,KAAA,EACQ;AACR,EAAA,MAAM,WAAA,GAAc,CAAA,EAAG,MAAM,CAAA,QAAA,EAAW,KAAK,CAAA,CAAA;AAC7C,EAAA,MAAM,MAAA,GAAS,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,MAAM,CAAA,eAAA,CAAA;AAElC,EAAA,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAA,EAKa,WAAW,CAAA;AAAA,qBAAA,EACV,MAAM,IAAI,KAAK,CAAA;AAAA;AAAA,mBAAA,EAEjB,WAAW;AAAA,wCAAA,EACU,MAAM,IAAI,KA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AA;AAAI,KACtB;AAEA,IAAA,MAAM,SAAA,GAAY,IAAA,CAAK,SAAA,CAAU,GAAA,CAAI,QAAQ,KAAK,CAAA;AAClD,IAAA,IAAI,CAAC,SAAA,EAAW;AAEhB,IAAA,KAAA,MAAW,MAAM,SAAA,EAAW;AAC1B,MAAA,IAAI;AACF,QAAA,EAAA,CAAG,KAAK,CAAA;AAAA,MACV,SAAS,GAAA,EAAK;AACZ,QAAA,OAAA,CAAQ,KAAA;AAAA,UACN,CAAA,8CAAA,EAAiD,QAAQ,KAAK,CAAA,EAAA,CAAA;AAAA,UAC9D,aAAa,GAAG;AAAA,SAClB;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAMA,SAAS,gBAAgB,KAAA,EAAwC;AAC/D,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,MAAM,OAAO,KAAA;AACxD,EAAA,MAAM,CAAA,GAAI,KAAA;AACV,EAAA,OACE,OAAO,CAAA,CAAE,OAAO,CAAA,KAAM,aACrB,CAAA,CAAE,WAAW,CAAA,KAAM,QAAA,IAAY,EAAE,WAAW,CAAA,KAAM,QAAA,IAAY,CAAA,CAAE,WAAW,CAAA,KAAM,QAAA,CAAA;AAEtF;AAEA,SAAS,aAAa,GAAA,EAAsB;AAC1C,EAAA,OAAO,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AACxD","file":"index.js","sourcesContent":["/**\n * Generates the SQL that installs a per-table NOTIFY trigger.\n *\n * Strategy:\n * - One shared trigger function per (schema, prefix) pair — handles all tables.\n * - One trigger per table that calls that function.\n *\n * Payload sent via NOTIFY (channel = triggerPrefix):\n * ```json\n * { \"table\": \"orders\", \"operation\": \"INSERT\", \"new_row\": {...}, \"old_row\": null }\n * ```\n *\n * IMPORTANT: PostgreSQL NOTIFY payloads are limited to 8000 bytes.\n * For larger rows the payload is truncated and only the primary-key columns\n * are guaranteed to be present. Callers that need the full row should\n * re-query after receiving the event.\n */\n\n/** Channel name used for LISTEN/NOTIFY — one shared channel for all tables. */\nexport function notifyChannel(prefix: string): string {\n return `${prefix}_changes`\n}\n\n/**\n * SQL to create (or replace) the shared trigger function.\n * The function encodes NEW/OLD as JSON and notifies the channel.\n */\nexport function createTriggerFunctionSQL(schema: string, prefix: string): string {\n const fnName = `${schema}.${prefix}_notify_changes`\n const channel = notifyChannel(prefix)\n\n return `\nCREATE OR REPLACE FUNCTION ${fnName}()\nRETURNS trigger\nLANGUAGE plpgsql\nAS $$\nDECLARE\n payload TEXT;\n new_row JSON;\n old_row JSON;\nBEGIN\n IF (TG_OP = 'DELETE') THEN\n new_row := NULL;\n old_row := row_to_json(OLD);\n ELSIF (TG_OP = 'INSERT') THEN\n new_row := row_to_json(NEW);\n old_row := NULL;\n ELSE\n new_row := row_to_json(NEW);\n old_row := row_to_json(OLD);\n END IF;\n\n payload := json_build_object(\n 'table', TG_TABLE_NAME,\n 'operation', TG_OP,\n 'new_row', new_row,\n 'old_row', old_row\n )::text;\n\n -- Truncate gracefully if payload exceeds pg's 8000-byte NOTIFY limit\n IF octet_length(payload) > 7900 THEN\n payload := json_build_object(\n 'table', TG_TABLE_NAME,\n 'operation', TG_OP,\n 'new_row', NULL,\n 'old_row', NULL,\n '_truncated', true\n )::text;\n END IF;\n\n PERFORM pg_notify('${channel}', payload);\n RETURN COALESCE(NEW, OLD);\nEND;\n$$;\n`.trim()\n}\n\n/**\n * SQL to attach the trigger to a specific table.\n * Idempotent — uses CREATE OR REPLACE (Postgres 14+).\n * Falls back to DROP + CREATE for older versions.\n */\nexport function createTableTriggerSQL(\n schema: string,\n prefix: string,\n table: string,\n): string {\n const triggerName = `${prefix}_notify_${table}`\n const fnName = `${schema}.${prefix}_notify_changes`\n\n return `\nDO $$\nBEGIN\n IF NOT EXISTS (\n SELECT 1 FROM pg_trigger\n WHERE tgname = '${triggerName}'\n AND tgrelid = '${schema}.${table}'::regclass\n ) THEN\n CREATE TRIGGER ${triggerName}\n AFTER INSERT OR UPDATE OR DELETE ON ${schema}.${table}\n FOR EACH ROW EXECUTE FUNCTION ${fnName}();\n END IF;\nEND;\n$$;\n`.trim()\n}\n\n/**\n * SQL to drop the trigger from a table (used on disconnect/cleanup).\n */\nexport function dropTableTriggerSQL(\n schema: string,\n prefix: string,\n table: string,\n): string {\n const triggerName = `${prefix}_notify_${table}`\n return `DROP TRIGGER IF EXISTS ${triggerName} ON ${schema}.${table};`\n}\n\n/**\n * SQL to drop the shared trigger function (used on full adapter teardown).\n */\nexport function dropTriggerFunctionSQL(schema: string, prefix: string): string {\n return `DROP FUNCTION IF EXISTS ${schema}.${prefix}_notify_changes();`\n}\n","import { Client, DatabaseError } from 'pg'\nimport type { ChangeEvent, DatabaseAdapter } from '@spear340000/core'\nimport { ReactiveApiError } from '@spear340000/core'\nimport type { NotifyPayload, PostgresAdapterOptions } from './types.js'\nimport {\n notifyChannel,\n createTriggerFunctionSQL,\n createTableTriggerSQL,\n dropTableTriggerSQL,\n dropTriggerFunctionSQL,\n} from './trigger-sql.js'\n\n/**\n * PostgreSQL database adapter for RouteFlow.\n *\n * Uses a dedicated `pg.Client` (not a pool) for LISTEN so the connection\n * stays open and notifications are never missed. A separate pool/client\n * can still be used by the application for regular queries.\n *\n * Change detection mechanism:\n * - On `onChange(table)`: installs a per-table AFTER INSERT/UPDATE/DELETE trigger\n * that calls `pg_notify` with a JSON payload.\n * - A single LISTEN connection subscribes to one shared channel for all tables.\n * - Payloads > 7900 bytes are sent without row data (`_truncated: true`);\n * subscribers receive a ChangeEvent with `newRow: null` / `oldRow: null`.\n *\n * @example\n * ```ts\n * const adapter = new PostgresAdapter({\n * connectionString: process.env.DATABASE_URL,\n * })\n * await adapter.connect()\n * ```\n */\nexport class PostgresAdapter implements DatabaseAdapter {\n private listenClient: Client | null = null\n private readonly schema: string\n private readonly prefix: string\n private readonly connectionString: string\n\n /** table → Set<callback> */\n private readonly listeners: Map<string, Set<(event: ChangeEvent) => void>> = new Map()\n /** Tables for which a trigger has already been installed */\n private readonly installedTriggers: Set<string> = new Set()\n\n constructor(options: PostgresAdapterOptions) {\n this.connectionString = options.connectionString\n this.schema = options.schema ?? 'public'\n this.prefix = options.triggerPrefix ?? 'reactive_api'\n }\n\n // ---------------------------------------------------------------------------\n // DatabaseAdapter interface\n // ---------------------------------------------------------------------------\n\n /** Connect the LISTEN client and install the shared trigger function. */\n async connect(): Promise<void> {\n if (this.listenClient) return\n\n const client = new Client({ connectionString: this.connectionString })\n try {\n await client.connect()\n } catch (err) {\n throw new ReactiveApiError(\n 'POSTGRES_CONNECT_FAILED',\n `Failed to connect to PostgreSQL: ${errorMessage(err)}`,\n )\n }\n\n // Install (or replace) the shared trigger function once per connection\n try {\n await client.query(createTriggerFunctionSQL(this.schema, this.prefix))\n } catch (err) {\n await client.end().catch(() => undefined)\n throw new ReactiveApiError(\n 'POSTGRES_TRIGGER_FUNCTION_FAILED',\n `Failed to install trigger function: ${errorMessage(err)}`,\n )\n }\n\n // Start listening on the shared channel\n const channel = notifyChannel(this.prefix)\n await client.query(`LISTEN \"${channel}\"`)\n\n client.on('notification', (msg) => {\n if (msg.channel !== channel || !msg.payload) return\n this.handleNotification(msg.payload)\n })\n\n client.on('error', (err) => {\n // Log but don't crash — the adapter becomes unavailable; the app can\n // call disconnect() + connect() to recover.\n console.error('[RouteFlow/postgres] LISTEN client error:', err.message)\n })\n\n this.listenClient = client\n }\n\n /** Disconnect the LISTEN client and optionally clean up triggers. */\n async disconnect(): Promise<void> {\n if (!this.listenClient) return\n\n const client = this.listenClient\n this.listenClient = null\n\n // Remove all installed table triggers and the shared function\n for (const table of this.installedTriggers) {\n await client\n .query(dropTableTriggerSQL(this.schema, this.prefix, table))\n .catch(() => undefined)\n }\n this.installedTriggers.clear()\n\n await client\n .query(dropTriggerFunctionSQL(this.schema, this.prefix))\n .catch(() => undefined)\n\n await client.end().catch(() => undefined)\n this.listeners.clear()\n }\n\n /**\n * Register a callback for changes on `table`.\n * Installs a PostgreSQL trigger on first registration for this table.\n *\n * @returns An unsubscribe function.\n */\n onChange(table: string, callback: (event: ChangeEvent) => void): () => void {\n if (!this.listeners.has(table)) {\n this.listeners.set(table, new Set())\n }\n this.listeners.get(table)!.add(callback)\n\n // Install trigger asynchronously; errors are surfaced to the console\n // rather than throwing so registration can happen before connect().\n this.ensureTriggerInstalled(table).catch((err) => {\n console.error(\n `[RouteFlow/postgres] Failed to install trigger for table \"${table}\":`,\n errorMessage(err),\n )\n })\n\n return () => {\n this.listeners.get(table)?.delete(callback)\n }\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private async ensureTriggerInstalled(table: string): Promise<void> {\n if (this.installedTriggers.has(table)) return\n if (!this.listenClient) return // will be retried via connect() flow\n\n try {\n await this.listenClient.query(\n createTableTriggerSQL(this.schema, this.prefix, table),\n )\n this.installedTriggers.add(table)\n } catch (err) {\n if (err instanceof DatabaseError) {\n throw new ReactiveApiError(\n 'POSTGRES_TRIGGER_INSTALL_FAILED',\n `Failed to install trigger on \"${table}\": ${err.message}`,\n )\n }\n throw err\n }\n }\n\n private handleNotification(rawPayload: string): void {\n let payload: unknown\n try {\n payload = JSON.parse(rawPayload)\n } catch {\n console.error('[RouteFlow/postgres] Malformed NOTIFY payload:', rawPayload)\n return\n }\n\n if (!isNotifyPayload(payload)) {\n console.error('[RouteFlow/postgres] Unexpected payload shape:', payload)\n return\n }\n\n const event: ChangeEvent = {\n table: payload.table,\n operation: payload.operation,\n newRow: payload.new_row,\n oldRow: payload.old_row,\n timestamp: Date.now(),\n }\n\n const callbacks = this.listeners.get(payload.table)\n if (!callbacks) return\n\n for (const cb of callbacks) {\n try {\n cb(event)\n } catch (err) {\n console.error(\n `[RouteFlow/postgres] Listener error on table \"${payload.table}\":`,\n errorMessage(err),\n )\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Type guards / utilities\n// ---------------------------------------------------------------------------\n\nfunction isNotifyPayload(value: unknown): value is NotifyPayload {\n if (typeof value !== 'object' || value === null) return false\n const v = value as Record<string, unknown>\n return (\n typeof v['table'] === 'string' &&\n (v['operation'] === 'INSERT' || v['operation'] === 'UPDATE' || v['operation'] === 'DELETE')\n )\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n"]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { Client, DatabaseError } from 'pg';
|
|
2
|
+
import { ReactiveApiError } from '@spear340000/core';
|
|
3
|
+
|
|
4
|
+
// src/postgres-adapter.ts
|
|
5
|
+
|
|
6
|
+
// src/trigger-sql.ts
|
|
7
|
+
function notifyChannel(prefix) {
|
|
8
|
+
return `${prefix}_changes`;
|
|
9
|
+
}
|
|
10
|
+
function createTriggerFunctionSQL(schema, prefix) {
|
|
11
|
+
const fnName = `${schema}.${prefix}_notify_changes`;
|
|
12
|
+
const channel = notifyChannel(prefix);
|
|
13
|
+
return `
|
|
14
|
+
CREATE OR REPLACE FUNCTION ${fnName}()
|
|
15
|
+
RETURNS trigger
|
|
16
|
+
LANGUAGE plpgsql
|
|
17
|
+
AS $$
|
|
18
|
+
DECLARE
|
|
19
|
+
payload TEXT;
|
|
20
|
+
new_row JSON;
|
|
21
|
+
old_row JSON;
|
|
22
|
+
BEGIN
|
|
23
|
+
IF (TG_OP = 'DELETE') THEN
|
|
24
|
+
new_row := NULL;
|
|
25
|
+
old_row := row_to_json(OLD);
|
|
26
|
+
ELSIF (TG_OP = 'INSERT') THEN
|
|
27
|
+
new_row := row_to_json(NEW);
|
|
28
|
+
old_row := NULL;
|
|
29
|
+
ELSE
|
|
30
|
+
new_row := row_to_json(NEW);
|
|
31
|
+
old_row := row_to_json(OLD);
|
|
32
|
+
END IF;
|
|
33
|
+
|
|
34
|
+
payload := json_build_object(
|
|
35
|
+
'table', TG_TABLE_NAME,
|
|
36
|
+
'operation', TG_OP,
|
|
37
|
+
'new_row', new_row,
|
|
38
|
+
'old_row', old_row
|
|
39
|
+
)::text;
|
|
40
|
+
|
|
41
|
+
-- Truncate gracefully if payload exceeds pg's 8000-byte NOTIFY limit
|
|
42
|
+
IF octet_length(payload) > 7900 THEN
|
|
43
|
+
payload := json_build_object(
|
|
44
|
+
'table', TG_TABLE_NAME,
|
|
45
|
+
'operation', TG_OP,
|
|
46
|
+
'new_row', NULL,
|
|
47
|
+
'old_row', NULL,
|
|
48
|
+
'_truncated', true
|
|
49
|
+
)::text;
|
|
50
|
+
END IF;
|
|
51
|
+
|
|
52
|
+
PERFORM pg_notify('${channel}', payload);
|
|
53
|
+
RETURN COALESCE(NEW, OLD);
|
|
54
|
+
END;
|
|
55
|
+
$$;
|
|
56
|
+
`.trim();
|
|
57
|
+
}
|
|
58
|
+
function createTableTriggerSQL(schema, prefix, table) {
|
|
59
|
+
const triggerName = `${prefix}_notify_${table}`;
|
|
60
|
+
const fnName = `${schema}.${prefix}_notify_changes`;
|
|
61
|
+
return `
|
|
62
|
+
DO $$
|
|
63
|
+
BEGIN
|
|
64
|
+
IF NOT EXISTS (
|
|
65
|
+
SELECT 1 FROM pg_trigger
|
|
66
|
+
WHERE tgname = '${triggerName}'
|
|
67
|
+
AND tgrelid = '${schema}.${table}'::regclass
|
|
68
|
+
) THEN
|
|
69
|
+
CREATE TRIGGER ${triggerName}
|
|
70
|
+
AFTER INSERT OR UPDATE OR DELETE ON ${schema}.${table}
|
|
71
|
+
FOR EACH ROW EXECUTE FUNCTION ${fnName}();
|
|
72
|
+
END IF;
|
|
73
|
+
END;
|
|
74
|
+
$$;
|
|
75
|
+
`.trim();
|
|
76
|
+
}
|
|
77
|
+
function dropTableTriggerSQL(schema, prefix, table) {
|
|
78
|
+
const triggerName = `${prefix}_notify_${table}`;
|
|
79
|
+
return `DROP TRIGGER IF EXISTS ${triggerName} ON ${schema}.${table};`;
|
|
80
|
+
}
|
|
81
|
+
function dropTriggerFunctionSQL(schema, prefix) {
|
|
82
|
+
return `DROP FUNCTION IF EXISTS ${schema}.${prefix}_notify_changes();`;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// src/postgres-adapter.ts
|
|
86
|
+
var PostgresAdapter = class {
|
|
87
|
+
listenClient = null;
|
|
88
|
+
schema;
|
|
89
|
+
prefix;
|
|
90
|
+
connectionString;
|
|
91
|
+
/** table → Set<callback> */
|
|
92
|
+
listeners = /* @__PURE__ */ new Map();
|
|
93
|
+
/** Tables for which a trigger has already been installed */
|
|
94
|
+
installedTriggers = /* @__PURE__ */ new Set();
|
|
95
|
+
constructor(options) {
|
|
96
|
+
this.connectionString = options.connectionString;
|
|
97
|
+
this.schema = options.schema ?? "public";
|
|
98
|
+
this.prefix = options.triggerPrefix ?? "reactive_api";
|
|
99
|
+
}
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
// DatabaseAdapter interface
|
|
102
|
+
// ---------------------------------------------------------------------------
|
|
103
|
+
/** Connect the LISTEN client and install the shared trigger function. */
|
|
104
|
+
async connect() {
|
|
105
|
+
if (this.listenClient) return;
|
|
106
|
+
const client = new Client({ connectionString: this.connectionString });
|
|
107
|
+
try {
|
|
108
|
+
await client.connect();
|
|
109
|
+
} catch (err) {
|
|
110
|
+
throw new ReactiveApiError(
|
|
111
|
+
"POSTGRES_CONNECT_FAILED",
|
|
112
|
+
`Failed to connect to PostgreSQL: ${errorMessage(err)}`
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
try {
|
|
116
|
+
await client.query(createTriggerFunctionSQL(this.schema, this.prefix));
|
|
117
|
+
} catch (err) {
|
|
118
|
+
await client.end().catch(() => void 0);
|
|
119
|
+
throw new ReactiveApiError(
|
|
120
|
+
"POSTGRES_TRIGGER_FUNCTION_FAILED",
|
|
121
|
+
`Failed to install trigger function: ${errorMessage(err)}`
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
const channel = notifyChannel(this.prefix);
|
|
125
|
+
await client.query(`LISTEN "${channel}"`);
|
|
126
|
+
client.on("notification", (msg) => {
|
|
127
|
+
if (msg.channel !== channel || !msg.payload) return;
|
|
128
|
+
this.handleNotification(msg.payload);
|
|
129
|
+
});
|
|
130
|
+
client.on("error", (err) => {
|
|
131
|
+
console.error("[RouteFlow/postgres] LISTEN client error:", err.message);
|
|
132
|
+
});
|
|
133
|
+
this.listenClient = client;
|
|
134
|
+
}
|
|
135
|
+
/** Disconnect the LISTEN client and optionally clean up triggers. */
|
|
136
|
+
async disconnect() {
|
|
137
|
+
if (!this.listenClient) return;
|
|
138
|
+
const client = this.listenClient;
|
|
139
|
+
this.listenClient = null;
|
|
140
|
+
for (const table of this.installedTriggers) {
|
|
141
|
+
await client.query(dropTableTriggerSQL(this.schema, this.prefix, table)).catch(() => void 0);
|
|
142
|
+
}
|
|
143
|
+
this.installedTriggers.clear();
|
|
144
|
+
await client.query(dropTriggerFunctionSQL(this.schema, this.prefix)).catch(() => void 0);
|
|
145
|
+
await client.end().catch(() => void 0);
|
|
146
|
+
this.listeners.clear();
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Register a callback for changes on `table`.
|
|
150
|
+
* Installs a PostgreSQL trigger on first registration for this table.
|
|
151
|
+
*
|
|
152
|
+
* @returns An unsubscribe function.
|
|
153
|
+
*/
|
|
154
|
+
onChange(table, callback) {
|
|
155
|
+
if (!this.listeners.has(table)) {
|
|
156
|
+
this.listeners.set(table, /* @__PURE__ */ new Set());
|
|
157
|
+
}
|
|
158
|
+
this.listeners.get(table).add(callback);
|
|
159
|
+
this.ensureTriggerInstalled(table).catch((err) => {
|
|
160
|
+
console.error(
|
|
161
|
+
`[RouteFlow/postgres] Failed to install trigger for table "${table}":`,
|
|
162
|
+
errorMessage(err)
|
|
163
|
+
);
|
|
164
|
+
});
|
|
165
|
+
return () => {
|
|
166
|
+
this.listeners.get(table)?.delete(callback);
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
// ---------------------------------------------------------------------------
|
|
170
|
+
// Private helpers
|
|
171
|
+
// ---------------------------------------------------------------------------
|
|
172
|
+
async ensureTriggerInstalled(table) {
|
|
173
|
+
if (this.installedTriggers.has(table)) return;
|
|
174
|
+
if (!this.listenClient) return;
|
|
175
|
+
try {
|
|
176
|
+
await this.listenClient.query(
|
|
177
|
+
createTableTriggerSQL(this.schema, this.prefix, table)
|
|
178
|
+
);
|
|
179
|
+
this.installedTriggers.add(table);
|
|
180
|
+
} catch (err) {
|
|
181
|
+
if (err instanceof DatabaseError) {
|
|
182
|
+
throw new ReactiveApiError(
|
|
183
|
+
"POSTGRES_TRIGGER_INSTALL_FAILED",
|
|
184
|
+
`Failed to install trigger on "${table}": ${err.message}`
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
throw err;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
handleNotification(rawPayload) {
|
|
191
|
+
let payload;
|
|
192
|
+
try {
|
|
193
|
+
payload = JSON.parse(rawPayload);
|
|
194
|
+
} catch {
|
|
195
|
+
console.error("[RouteFlow/postgres] Malformed NOTIFY payload:", rawPayload);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (!isNotifyPayload(payload)) {
|
|
199
|
+
console.error("[RouteFlow/postgres] Unexpected payload shape:", payload);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
const event = {
|
|
203
|
+
table: payload.table,
|
|
204
|
+
operation: payload.operation,
|
|
205
|
+
newRow: payload.new_row,
|
|
206
|
+
oldRow: payload.old_row,
|
|
207
|
+
timestamp: Date.now()
|
|
208
|
+
};
|
|
209
|
+
const callbacks = this.listeners.get(payload.table);
|
|
210
|
+
if (!callbacks) return;
|
|
211
|
+
for (const cb of callbacks) {
|
|
212
|
+
try {
|
|
213
|
+
cb(event);
|
|
214
|
+
} catch (err) {
|
|
215
|
+
console.error(
|
|
216
|
+
`[RouteFlow/postgres] Listener error on table "${payload.table}":`,
|
|
217
|
+
errorMessage(err)
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
function isNotifyPayload(value) {
|
|
224
|
+
if (typeof value !== "object" || value === null) return false;
|
|
225
|
+
const v = value;
|
|
226
|
+
return typeof v["table"] === "string" && (v["operation"] === "INSERT" || v["operation"] === "UPDATE" || v["operation"] === "DELETE");
|
|
227
|
+
}
|
|
228
|
+
function errorMessage(err) {
|
|
229
|
+
return err instanceof Error ? err.message : String(err);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export { PostgresAdapter };
|
|
233
|
+
//# sourceMappingURL=index.mjs.map
|
|
234
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/trigger-sql.ts","../src/postgres-adapter.ts"],"names":[],"mappings":";;;;;;AAmBO,SAAS,cAAc,MAAA,EAAwB;AACpD,EAAA,OAAO,GAAG,MAAM,CAAA,QAAA,CAAA;AAClB;AAMO,SAAS,wBAAA,CAAyB,QAAgB,MAAA,EAAwB;AAC/E,EAAA,MAAM,MAAA,GAAS,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,MAAM,CAAA,eAAA,CAAA;AAClC,EAAA,MAAM,OAAA,GAAU,cAAc,MAAM,CAAA;AAEpC,EAAA,OAAO;AAAA,2BAAA,EACoB,MAAM,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA,qBAAA,EAsCZ,OAAO,CAAA;AAAA;AAAA;AAAA;AAAA,CAAA,CAI5B,IAAA,EAAK;AACP;AAOO,SAAS,qBAAA,CACd,MAAA,EACA,MAAA,EACA,KAAA,EACQ;AACR,EAAA,MAAM,WAAA,GAAc,CAAA,EAAG,MAAM,CAAA,QAAA,EAAW,KAAK,CAAA,CAAA;AAC7C,EAAA,MAA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OAAO,CAAA;AACvE,MAAA;AAAA,IACF;AAEA,IAAA,MAAM,KAAA,GAAqB;AAAA,MACzB,OAAO,OAAA,CAAQ,KAAA;AAAA,MACf,WAAW,OAAA,CAAQ,SAAA;AAAA,MACnB,QAAQ,OAAA,CAAQ,OAAA;AAAA,MAChB,QAAQ,OAAA,CAAQ,OAAA;AAAA,MAChB,SAAA,EAAW,KAAK,GAAA;AAAI,KACtB;AAEA,IAAA,MAAM,SAAA,GAAY,IAAA,CAAK,SAAA,CAAU,GAAA,CAAI,QAAQ,KAAK,CAAA;AAClD,IAAA,IAAI,CAAC,SAAA,EAAW;AAEhB,IAAA,KAAA,MAAW,MAAM,SAAA,EAAW;AAC1B,MAAA,IAAI;AACF,QAAA,EAAA,CAAG,KAAK,CAAA;AAAA,MACV,SAAS,GAAA,EAAK;AACZ,QAAA,OAAA,CAAQ,KAAA;AAAA,UACN,CAAA,8CAAA,EAAiD,QAAQ,KAAK,CAAA,EAAA,CAAA;AAAA,UAC9D,aAAa,GAAG;AAAA,SAClB;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAMA,SAAS,gBAAgB,KAAA,EAAwC;AAC/D,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,MAAM,OAAO,KAAA;AACxD,EAAA,MAAM,CAAA,GAAI,KAAA;AACV,EAAA,OACE,OAAO,CAAA,CAAE,OAAO,CAAA,KAAM,aACrB,CAAA,CAAE,WAAW,CAAA,KAAM,QAAA,IAAY,EAAE,WAAW,CAAA,KAAM,QAAA,IAAY,CAAA,CAAE,WAAW,CAAA,KAAM,QAAA,CAAA;AAEtF;AAEA,SAAS,aAAa,GAAA,EAAsB;AAC1C,EAAA,OAAO,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AACxD","file":"index.mjs","sourcesContent":["/**\n * Generates the SQL that installs a per-table NOTIFY trigger.\n *\n * Strategy:\n * - One shared trigger function per (schema, prefix) pair — handles all tables.\n * - One trigger per table that calls that function.\n *\n * Payload sent via NOTIFY (channel = triggerPrefix):\n * ```json\n * { \"table\": \"orders\", \"operation\": \"INSERT\", \"new_row\": {...}, \"old_row\": null }\n * ```\n *\n * IMPORTANT: PostgreSQL NOTIFY payloads are limited to 8000 bytes.\n * For larger rows the payload is truncated and only the primary-key columns\n * are guaranteed to be present. Callers that need the full row should\n * re-query after receiving the event.\n */\n\n/** Channel name used for LISTEN/NOTIFY — one shared channel for all tables. */\nexport function notifyChannel(prefix: string): string {\n return `${prefix}_changes`\n}\n\n/**\n * SQL to create (or replace) the shared trigger function.\n * The function encodes NEW/OLD as JSON and notifies the channel.\n */\nexport function createTriggerFunctionSQL(schema: string, prefix: string): string {\n const fnName = `${schema}.${prefix}_notify_changes`\n const channel = notifyChannel(prefix)\n\n return `\nCREATE OR REPLACE FUNCTION ${fnName}()\nRETURNS trigger\nLANGUAGE plpgsql\nAS $$\nDECLARE\n payload TEXT;\n new_row JSON;\n old_row JSON;\nBEGIN\n IF (TG_OP = 'DELETE') THEN\n new_row := NULL;\n old_row := row_to_json(OLD);\n ELSIF (TG_OP = 'INSERT') THEN\n new_row := row_to_json(NEW);\n old_row := NULL;\n ELSE\n new_row := row_to_json(NEW);\n old_row := row_to_json(OLD);\n END IF;\n\n payload := json_build_object(\n 'table', TG_TABLE_NAME,\n 'operation', TG_OP,\n 'new_row', new_row,\n 'old_row', old_row\n )::text;\n\n -- Truncate gracefully if payload exceeds pg's 8000-byte NOTIFY limit\n IF octet_length(payload) > 7900 THEN\n payload := json_build_object(\n 'table', TG_TABLE_NAME,\n 'operation', TG_OP,\n 'new_row', NULL,\n 'old_row', NULL,\n '_truncated', true\n )::text;\n END IF;\n\n PERFORM pg_notify('${channel}', payload);\n RETURN COALESCE(NEW, OLD);\nEND;\n$$;\n`.trim()\n}\n\n/**\n * SQL to attach the trigger to a specific table.\n * Idempotent — uses CREATE OR REPLACE (Postgres 14+).\n * Falls back to DROP + CREATE for older versions.\n */\nexport function createTableTriggerSQL(\n schema: string,\n prefix: string,\n table: string,\n): string {\n const triggerName = `${prefix}_notify_${table}`\n const fnName = `${schema}.${prefix}_notify_changes`\n\n return `\nDO $$\nBEGIN\n IF NOT EXISTS (\n SELECT 1 FROM pg_trigger\n WHERE tgname = '${triggerName}'\n AND tgrelid = '${schema}.${table}'::regclass\n ) THEN\n CREATE TRIGGER ${triggerName}\n AFTER INSERT OR UPDATE OR DELETE ON ${schema}.${table}\n FOR EACH ROW EXECUTE FUNCTION ${fnName}();\n END IF;\nEND;\n$$;\n`.trim()\n}\n\n/**\n * SQL to drop the trigger from a table (used on disconnect/cleanup).\n */\nexport function dropTableTriggerSQL(\n schema: string,\n prefix: string,\n table: string,\n): string {\n const triggerName = `${prefix}_notify_${table}`\n return `DROP TRIGGER IF EXISTS ${triggerName} ON ${schema}.${table};`\n}\n\n/**\n * SQL to drop the shared trigger function (used on full adapter teardown).\n */\nexport function dropTriggerFunctionSQL(schema: string, prefix: string): string {\n return `DROP FUNCTION IF EXISTS ${schema}.${prefix}_notify_changes();`\n}\n","import { Client, DatabaseError } from 'pg'\nimport type { ChangeEvent, DatabaseAdapter } from '@spear340000/core'\nimport { ReactiveApiError } from '@spear340000/core'\nimport type { NotifyPayload, PostgresAdapterOptions } from './types.js'\nimport {\n notifyChannel,\n createTriggerFunctionSQL,\n createTableTriggerSQL,\n dropTableTriggerSQL,\n dropTriggerFunctionSQL,\n} from './trigger-sql.js'\n\n/**\n * PostgreSQL database adapter for RouteFlow.\n *\n * Uses a dedicated `pg.Client` (not a pool) for LISTEN so the connection\n * stays open and notifications are never missed. A separate pool/client\n * can still be used by the application for regular queries.\n *\n * Change detection mechanism:\n * - On `onChange(table)`: installs a per-table AFTER INSERT/UPDATE/DELETE trigger\n * that calls `pg_notify` with a JSON payload.\n * - A single LISTEN connection subscribes to one shared channel for all tables.\n * - Payloads > 7900 bytes are sent without row data (`_truncated: true`);\n * subscribers receive a ChangeEvent with `newRow: null` / `oldRow: null`.\n *\n * @example\n * ```ts\n * const adapter = new PostgresAdapter({\n * connectionString: process.env.DATABASE_URL,\n * })\n * await adapter.connect()\n * ```\n */\nexport class PostgresAdapter implements DatabaseAdapter {\n private listenClient: Client | null = null\n private readonly schema: string\n private readonly prefix: string\n private readonly connectionString: string\n\n /** table → Set<callback> */\n private readonly listeners: Map<string, Set<(event: ChangeEvent) => void>> = new Map()\n /** Tables for which a trigger has already been installed */\n private readonly installedTriggers: Set<string> = new Set()\n\n constructor(options: PostgresAdapterOptions) {\n this.connectionString = options.connectionString\n this.schema = options.schema ?? 'public'\n this.prefix = options.triggerPrefix ?? 'reactive_api'\n }\n\n // ---------------------------------------------------------------------------\n // DatabaseAdapter interface\n // ---------------------------------------------------------------------------\n\n /** Connect the LISTEN client and install the shared trigger function. */\n async connect(): Promise<void> {\n if (this.listenClient) return\n\n const client = new Client({ connectionString: this.connectionString })\n try {\n await client.connect()\n } catch (err) {\n throw new ReactiveApiError(\n 'POSTGRES_CONNECT_FAILED',\n `Failed to connect to PostgreSQL: ${errorMessage(err)}`,\n )\n }\n\n // Install (or replace) the shared trigger function once per connection\n try {\n await client.query(createTriggerFunctionSQL(this.schema, this.prefix))\n } catch (err) {\n await client.end().catch(() => undefined)\n throw new ReactiveApiError(\n 'POSTGRES_TRIGGER_FUNCTION_FAILED',\n `Failed to install trigger function: ${errorMessage(err)}`,\n )\n }\n\n // Start listening on the shared channel\n const channel = notifyChannel(this.prefix)\n await client.query(`LISTEN \"${channel}\"`)\n\n client.on('notification', (msg) => {\n if (msg.channel !== channel || !msg.payload) return\n this.handleNotification(msg.payload)\n })\n\n client.on('error', (err) => {\n // Log but don't crash — the adapter becomes unavailable; the app can\n // call disconnect() + connect() to recover.\n console.error('[RouteFlow/postgres] LISTEN client error:', err.message)\n })\n\n this.listenClient = client\n }\n\n /** Disconnect the LISTEN client and optionally clean up triggers. */\n async disconnect(): Promise<void> {\n if (!this.listenClient) return\n\n const client = this.listenClient\n this.listenClient = null\n\n // Remove all installed table triggers and the shared function\n for (const table of this.installedTriggers) {\n await client\n .query(dropTableTriggerSQL(this.schema, this.prefix, table))\n .catch(() => undefined)\n }\n this.installedTriggers.clear()\n\n await client\n .query(dropTriggerFunctionSQL(this.schema, this.prefix))\n .catch(() => undefined)\n\n await client.end().catch(() => undefined)\n this.listeners.clear()\n }\n\n /**\n * Register a callback for changes on `table`.\n * Installs a PostgreSQL trigger on first registration for this table.\n *\n * @returns An unsubscribe function.\n */\n onChange(table: string, callback: (event: ChangeEvent) => void): () => void {\n if (!this.listeners.has(table)) {\n this.listeners.set(table, new Set())\n }\n this.listeners.get(table)!.add(callback)\n\n // Install trigger asynchronously; errors are surfaced to the console\n // rather than throwing so registration can happen before connect().\n this.ensureTriggerInstalled(table).catch((err) => {\n console.error(\n `[RouteFlow/postgres] Failed to install trigger for table \"${table}\":`,\n errorMessage(err),\n )\n })\n\n return () => {\n this.listeners.get(table)?.delete(callback)\n }\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private async ensureTriggerInstalled(table: string): Promise<void> {\n if (this.installedTriggers.has(table)) return\n if (!this.listenClient) return // will be retried via connect() flow\n\n try {\n await this.listenClient.query(\n createTableTriggerSQL(this.schema, this.prefix, table),\n )\n this.installedTriggers.add(table)\n } catch (err) {\n if (err instanceof DatabaseError) {\n throw new ReactiveApiError(\n 'POSTGRES_TRIGGER_INSTALL_FAILED',\n `Failed to install trigger on \"${table}\": ${err.message}`,\n )\n }\n throw err\n }\n }\n\n private handleNotification(rawPayload: string): void {\n let payload: unknown\n try {\n payload = JSON.parse(rawPayload)\n } catch {\n console.error('[RouteFlow/postgres] Malformed NOTIFY payload:', rawPayload)\n return\n }\n\n if (!isNotifyPayload(payload)) {\n console.error('[RouteFlow/postgres] Unexpected payload shape:', payload)\n return\n }\n\n const event: ChangeEvent = {\n table: payload.table,\n operation: payload.operation,\n newRow: payload.new_row,\n oldRow: payload.old_row,\n timestamp: Date.now(),\n }\n\n const callbacks = this.listeners.get(payload.table)\n if (!callbacks) return\n\n for (const cb of callbacks) {\n try {\n cb(event)\n } catch (err) {\n console.error(\n `[RouteFlow/postgres] Listener error on table \"${payload.table}\":`,\n errorMessage(err),\n )\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Type guards / utilities\n// ---------------------------------------------------------------------------\n\nfunction isNotifyPayload(value: unknown): value is NotifyPayload {\n if (typeof value !== 'object' || value === null) return false\n const v = value as Record<string, unknown>\n return (\n typeof v['table'] === 'string' &&\n (v['operation'] === 'INSERT' || v['operation'] === 'UPDATE' || v['operation'] === 'DELETE')\n )\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@spear340000/adapter-postgres",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "PostgreSQL adapter for RouteFlow — LISTEN/NOTIFY based change streaming",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/spear34000/RouteFlow.git"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/spear34000/RouteFlow#readme",
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/spear34000/RouteFlow/issues"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"routeflow",
|
|
16
|
+
"postgres",
|
|
17
|
+
"postgresql",
|
|
18
|
+
"realtime",
|
|
19
|
+
"cdc"
|
|
20
|
+
],
|
|
21
|
+
"main": "./dist/index.js",
|
|
22
|
+
"module": "./dist/index.mjs",
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"README.md"
|
|
27
|
+
],
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"import": "./dist/index.mjs",
|
|
32
|
+
"require": "./dist/index.js"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"pg": "^8.13.3",
|
|
40
|
+
"@spear340000/core": "0.1.0"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@types/node": "^20.0.0",
|
|
44
|
+
"@types/pg": "^8.11.10",
|
|
45
|
+
"tsup": "^8.0.0",
|
|
46
|
+
"typescript": "^5.4.0",
|
|
47
|
+
"vitest": "^1.6.0"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "tsup",
|
|
51
|
+
"test": "vitest run",
|
|
52
|
+
"test:integration": "vitest run --config vitest.integration.config.ts",
|
|
53
|
+
"dev": "tsup --watch"
|
|
54
|
+
}
|
|
55
|
+
}
|