-
-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathpostgresql.ts
More file actions
249 lines (232 loc) · 6.92 KB
/
postgresql.ts
File metadata and controls
249 lines (232 loc) · 6.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import type {
DatabaseChangeListener,
DatabaseExecuteCommand,
DatabasePersisterConfig,
PersistedStore,
Persister,
PersisterListener,
Persists,
} from '../../../@types/persisters/index.d.ts';
import {arrayJoin, arrayMap} from '../../../common/array.ts';
import {collHas, collValues} from '../../../common/coll.ts';
import {getHash} from '../../../common/hash.ts';
import {
jsonParse,
jsonString,
jsonStringWithUndefined,
} from '../../../common/json.ts';
import {mapGet} from '../../../common/map.ts';
import {ifNotUndefined, promiseAll} from '../../../common/other.ts';
import {
EMPTY_STRING,
TINYBASE,
TRUE,
strMatch,
strReplace,
} from '../../../common/strings.ts';
import {
CREATE,
CREATE_TABLE,
DELETE,
FUNCTION,
INSERT,
OR_REPLACE,
SELECT,
TABLE_NAME_PLACEHOLDER,
UPDATE,
WHERE,
escapeId,
escapeIds,
getPlaceholders,
getWrappedCommand,
} from './common.ts';
import {DefaultedTabularConfig, getConfigStructures} from './config.ts';
import {createJsonPersister} from './json.ts';
import {createTabularPersister} from './tabular.ts';
const TABLE_CREATED = 'c';
const DATA_CHANGED = 'd';
const EVENT_REGEX = /^([cd]:)(.+)/;
export const createCustomPostgreSqlPersister = <
ListenerHandle,
Persist extends Persists = Persists.StoreOnly,
>(
store: PersistedStore<Persist>,
configOrStoreTableName: DatabasePersisterConfig | string | undefined,
rawExecuteCommand: DatabaseExecuteCommand,
addChangeListener: (
channel: string,
listener: DatabaseChangeListener,
) => Promise<ListenerHandle>,
delChangeListener: (listenerHandle: ListenerHandle) => Promise<void>,
onSqlCommand: ((sql: string, params?: any[]) => void) | undefined,
onIgnoredError: ((error: any) => void) | undefined,
destroy: () => void,
persist: Persist,
thing: any,
getThing = 'getDb',
): Persister<Persist> => {
type Handles = [listenerHandle: ListenerHandle, functionNames: string[]];
const executeCommand = getWrappedCommand(rawExecuteCommand, onSqlCommand);
const [isJson, , defaultedConfig, managedTableNamesSet] = getConfigStructures(
configOrStoreTableName,
);
const configHash =
EMPTY_STRING + getHash(jsonStringWithUndefined(defaultedConfig));
const channel = TINYBASE + '_' + configHash;
const createFunction = async (
name: string,
body: string,
returnPrefix = '',
declarations = '',
): Promise<string> => {
const escapedFunctionName = escapeIds(TINYBASE, name, configHash);
await executeCommand(
CREATE +
OR_REPLACE +
FUNCTION +
escapedFunctionName +
`()RETURNS ${returnPrefix}trigger ` +
`AS $$ ${declarations}BEGIN ${body}END;$$ LANGUAGE plpgsql;`,
);
return escapedFunctionName;
};
const createTrigger = async (
prefix: string,
escapedTriggerName: string,
body: string,
escapedFunctionName: string,
): Promise<string> => {
await executeCommand(
CREATE +
prefix +
'TRIGGER' +
escapedTriggerName +
body +
'EXECUTE ' +
FUNCTION +
escapedFunctionName +
`()`,
);
return escapedTriggerName;
};
const notify = (message: string) =>
`PERFORM pg_notify('${channel}',${message});`;
const when = (tableName: string, newOrOldOrBoth: 0 | 1 | 2): string =>
isJson
? TRUE
: newOrOldOrBoth === 2
? when(tableName, 0) + ' OR ' + when(tableName, 1)
: strReplace(
mapGet(
(defaultedConfig as DefaultedTabularConfig)[0],
tableName,
)?.[2] ?? TRUE,
TABLE_NAME_PLACEHOLDER,
newOrOldOrBoth == 0 ? 'NEW' : 'OLD',
);
const addDataChangedTriggers = (
tableName: string,
dataChangedFunction: string,
) =>
promiseAll(
arrayMap([INSERT, DELETE, UPDATE], (action, newOrOldOrBoth) =>
createTrigger(
OR_REPLACE,
escapeIds(TINYBASE, DATA_CHANGED, configHash, tableName, action),
`AFTER ${action} ON${escapeId(tableName)}FOR EACH ROW WHEN(${when(
tableName,
newOrOldOrBoth as 0 | 1 | 2,
)})`,
dataChangedFunction,
),
),
);
const addPersisterListener = async (
listener: PersisterListener<Persist>,
): Promise<Handles> => {
const tableCreatedFunctionName = await createFunction(
TABLE_CREATED,
// eslint-disable-next-line max-len
`FOR row IN SELECT object_identity FROM pg_event_trigger_ddl_commands()${WHERE} command_tag='${CREATE_TABLE}' LOOP ${notify(`'c:'||SPLIT_PART(row.object_identity,'.',2)`)}END LOOP;`,
'event_',
'DECLARE row record;',
);
await createTrigger(
'EVENT ',
escapeIds(TINYBASE, TABLE_CREATED, configHash),
`ON ddl_command_end WHEN TAG IN('${CREATE_TABLE}')`,
tableCreatedFunctionName,
);
const dataChangedFunctionName = await createFunction(
DATA_CHANGED,
notify(`'d:'||TG_TABLE_NAME`) + `RETURN NULL;`,
);
await promiseAll(
arrayMap(collValues(managedTableNamesSet), async (tableName) => {
await executeCommand(
CREATE_TABLE +
` IF NOT EXISTS${escapeId(tableName)}("_id"text PRIMARY KEY)`,
);
return await addDataChangedTriggers(tableName, dataChangedFunctionName);
}),
);
const listenerHandle = await addChangeListener(
channel,
(prefixAndTableName) =>
ifNotUndefined(
strMatch(prefixAndTableName, EVENT_REGEX),
async ([, eventType, tableName]) => {
if (collHas(managedTableNamesSet, tableName)) {
if (eventType == 'c:') {
await addDataChangedTriggers(
tableName,
dataChangedFunctionName,
);
}
listener();
}
},
),
);
return [
listenerHandle,
[tableCreatedFunctionName, dataChangedFunctionName],
];
};
const delPersisterListener = async ([
listenerHandle,
functionNames,
]: Handles) => {
delChangeListener(listenerHandle);
await executeCommand(
`DROP FUNCTION IF EXISTS${arrayJoin(functionNames, ',')}CASCADE`,
);
};
return (isJson ? createJsonPersister : createTabularPersister)(
store,
executeCommand,
addPersisterListener,
delPersisterListener,
onIgnoredError,
destroy,
persist,
defaultedConfig as any,
collValues(managedTableNamesSet),
async (
executeCommand: DatabaseExecuteCommand,
managedTableNames: string[],
): Promise<any[]> =>
await executeCommand(
SELECT +
// eslint-disable-next-line max-len
` table_name tn,column_name cn FROM information_schema.columns ${WHERE} table_schema='public'AND table_name IN(${getPlaceholders(managedTableNames)})`,
managedTableNames,
),
thing,
getThing,
'text',
undefined,
(cellOrValue) => jsonString(cellOrValue),
(field) => jsonParse(field as string),
);
};