@openpeepshq/core 0.1.32 → 0.1.34
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/dist/accessTokens/helpers.d.ts +2 -2
- package/dist/accessTokens/tokens.js +14 -7
- package/dist/accounts/mutations.d.ts +2 -2
- package/dist/accounts/mutations.js +33 -35
- package/dist/analytics/cache.js +12 -7
- package/dist/analytics/compile.js +16 -10
- package/dist/analytics/pdfReport.d.ts +1 -0
- package/dist/analytics/pdfReport.js +5 -4
- package/dist/analytics/privacy.d.ts +18 -0
- package/dist/analytics/privacy.js +10 -0
- package/dist/analytics/read.js +75 -19
- package/dist/analytics/report.d.ts +21 -1
- package/dist/analytics/report.js +9 -2
- package/dist/backups/index.js +78 -15
- package/dist/backups/metadata.d.ts +8 -2
- package/dist/backups/metadata.js +6 -2
- package/dist/config/defaults/capabilities.js +13 -2
- package/dist/config/defaults/community.js +7 -9
- package/dist/config/defaults/core.d.ts +1 -1
- package/dist/config/defaults/core.js +3 -0
- package/dist/config/defaults/db.d.ts +0 -2
- package/dist/config/defaults/db.js +0 -2
- package/dist/config/index.d.ts +25 -3
- package/dist/config/index.js +7 -1
- package/dist/db/helpers.d.ts +7 -28
- package/dist/db/helpers.js +30 -152
- package/dist/db/index.d.ts +3 -1
- package/dist/db/index.js +5 -0
- package/dist/db/init.js +2 -2
- package/dist/db/migration/importCollections.d.ts +15 -10
- package/dist/db/migration/importCollections.js +121 -155
- package/dist/db/migration/shared.d.ts +2 -37
- package/dist/db/migration/shared.js +2 -59
- package/dist/db/pg/client.js +4 -0
- package/dist/db/pg/collections.d.ts +2 -2
- package/dist/db/pg/collections.js +2 -2
- package/dist/db/pg/filters/edges.d.ts +1 -1
- package/dist/db/pg/filters/edges.js +1 -1
- package/dist/db/pg/filters/posts.d.ts +11 -0
- package/dist/db/pg/filters/posts.js +37 -3
- package/dist/db/pg/filters/profiles.d.ts +1 -0
- package/dist/db/pg/filters/profiles.js +2 -1
- package/dist/db/pg/map/filters.js +37 -2
- package/dist/db/pg/map/mutations.js +13 -8
- package/dist/db/pg/map/registry.d.ts +5 -0
- package/dist/db/pg/map/registry.js +64 -24
- package/dist/db/pg/map/relations.d.ts +1 -1
- package/dist/db/pg/map/relations.js +98 -46
- package/dist/db/pg/migrate.d.ts +22 -0
- package/dist/db/pg/migrate.js +88 -2
- package/dist/db/pg/queries/activity.js +3 -3
- package/dist/db/pg/queries/sorts.d.ts +1 -0
- package/dist/db/pg/queries/sorts.js +4 -0
- package/dist/db/pg/schema/documents.d.ts +422 -41
- package/dist/db/pg/schema/documents.js +43 -9
- package/dist/db/pg/schema/edges.d.ts +117 -7
- package/dist/db/pg/schema/edges.js +4 -2
- package/dist/db/pg/schema/index.d.ts +505 -15
- package/dist/db/pg/sql/0007_shallow_oracle.sql +3 -0
- package/dist/db/pg/sql/0008_group_owner_roles.sql +31 -0
- package/dist/db/pg/sql/0009_event_occurrences.sql +26 -0
- package/dist/db/pg/sql/0010_user_group_membership_roles.sql +16 -0
- package/dist/db/pg/sql/0011_drop_data_migrations.sql +1 -0
- package/dist/db/pg/sql/0012_posts_last_activity_at.sql +5 -0
- package/dist/db/pg/sql/0013_add_blocks_edge.sql +12 -0
- package/dist/db/pg/sql/0014_federation_datamodel.sql +59 -0
- package/dist/db/pg/sql/0015_profile_hashtags.sql +12 -0
- package/dist/db/pg/sql/meta/{0006_snapshot.json → 0015_snapshot.json} +393 -39
- package/dist/db/pg/sql/meta/_journal.json +64 -1
- package/dist/db/replaceOrigin.js +6 -0
- package/dist/db/types.d.ts +0 -4
- package/dist/email/render.js +11 -3
- package/dist/events/index.d.ts +6 -1
- package/dist/events/index.js +55 -33
- package/dist/federation/activities.d.ts +17 -0
- package/dist/federation/activities.js +26 -0
- package/dist/federation/identity.d.ts +16 -0
- package/dist/federation/identity.js +52 -0
- package/dist/federation/index.d.ts +4 -0
- package/dist/federation/index.js +3 -0
- package/dist/federation/profiles.d.ts +3 -0
- package/dist/federation/profiles.js +14 -0
- package/dist/groups/finders.d.ts +3 -2
- package/dist/groups/helpers.d.ts +24 -6
- package/dist/groups/mapping.d.ts +6 -4
- package/dist/groups/mapping.js +2 -2
- package/dist/groups/mutations.js +1 -1
- package/dist/hashtags/finders.d.ts +6 -3
- package/dist/hashtags/finders.js +2 -0
- package/dist/hashtags/helpers.d.ts +8 -0
- package/dist/hashtags/helpers.js +4 -0
- package/dist/hashtags/index.d.ts +2 -0
- package/dist/hashtags/index.js +2 -0
- package/dist/hashtags/mutations.d.ts +3 -0
- package/dist/hashtags/mutations.js +13 -1
- package/dist/i18n/index.d.ts +1 -1
- package/dist/i18n/index.js +3 -1
- package/dist/i18n/pluginLocales.d.ts +6 -0
- package/dist/i18n/pluginLocales.js +15 -0
- package/dist/inviteLinks/helpers.d.ts +4 -4
- package/dist/jams/cache.d.ts +1 -1
- package/dist/jams/cache.js +2 -1
- package/dist/jams/export.d.ts +19 -0
- package/dist/jams/export.js +60 -0
- package/dist/jams/finders.d.ts +2 -1
- package/dist/jams/finders.js +18 -7
- package/dist/jams/health.d.ts +8 -0
- package/dist/jams/health.js +46 -0
- package/dist/jams/helpers.d.ts +6 -2
- package/dist/jams/index.d.ts +6 -3
- package/dist/jams/index.js +41 -27
- package/dist/jams/jobs.js +1 -1
- package/dist/jams/livekit.d.ts +93 -10
- package/dist/jams/livekit.js +151 -52
- package/dist/jams/mapping.d.ts +17 -7
- package/dist/jams/mutations.d.ts +3 -1
- package/dist/jams/recording.d.ts +10 -0
- package/dist/jams/recording.js +32 -0
- package/dist/jams/rtmp.d.ts +5 -0
- package/dist/jams/rtmp.js +8 -0
- package/dist/jams/token.d.ts +15 -3
- package/dist/jams/token.js +30 -16
- package/dist/jams/waitingRoom.d.ts +6 -6
- package/dist/jams/waitingRoom.js +24 -23
- package/dist/jobs/index.d.ts +1 -0
- package/dist/jobs/index.js +6 -1
- package/dist/jobs/jobDetail.js +1 -6
- package/dist/media/index.d.ts +1 -1
- package/dist/media/index.js +23 -8
- package/dist/media/processing.js +18 -7
- package/dist/notifications/defaultNotifications/follow/index.js +2 -2
- package/dist/notifications/defaultNotifications/groupMemberJoined/index.js +3 -1
- package/dist/notifications/defaultNotifications/groupMemberLeft/index.js +3 -1
- package/dist/notifications/defaultNotifications/index.js +4 -0
- package/dist/notifications/defaultNotifications/newGroupPost/index.js +12 -6
- package/dist/notifications/defaultNotifications/pollEnded/index.d.ts +19 -0
- package/dist/notifications/defaultNotifications/pollEnded/index.js +39 -0
- package/dist/notifications/defaultNotifications/pollEnded/recipients.d.ts +3 -0
- package/dist/notifications/defaultNotifications/pollEnded/recipients.js +18 -0
- package/dist/notifications/defaultNotifications/rsvp/index.d.ts +6 -1
- package/dist/notifications/defaultNotifications/rsvp/index.js +7 -0
- package/dist/notifications/defaultNotifications/rsvpCanceled/index.d.ts +24 -0
- package/dist/notifications/defaultNotifications/rsvpCanceled/index.js +75 -0
- package/dist/notifications/defaultNotifications/rsvpCanceled/recipients.d.ts +4 -0
- package/dist/notifications/defaultNotifications/rsvpCanceled/recipients.js +11 -0
- package/dist/notifications/helpers.js +6 -2
- package/dist/notifications/jobs.js +3 -1
- package/dist/notifications/mutations.js +4 -0
- package/dist/notifications/push.js +11 -4
- package/dist/plugins/helpers.d.ts +1 -0
- package/dist/plugins/helpers.js +1 -8
- package/dist/plugins/index.d.ts +5 -0
- package/dist/plugins/index.js +78 -5
- package/dist/plugins/install.d.ts +39 -0
- package/dist/plugins/install.js +455 -0
- package/dist/plugins/pluginAuth.d.ts +1 -1
- package/dist/plugins/pluginAuth.js +10 -6
- package/dist/plugins/state.d.ts +4 -0
- package/dist/plugins/state.js +29 -0
- package/dist/posts/activity.d.ts +9 -0
- package/dist/posts/activity.js +35 -0
- package/dist/posts/contextClosure.d.ts +1 -9
- package/dist/posts/contextClosure.js +15 -44
- package/dist/posts/conversationQueries.d.ts +7 -0
- package/dist/posts/conversationQueries.js +76 -2
- package/dist/posts/eventAgenda.d.ts +166 -0
- package/dist/posts/eventAgenda.js +126 -0
- package/dist/posts/eventOccurrenceJobs.d.ts +4 -0
- package/dist/posts/eventOccurrenceJobs.js +28 -0
- package/dist/posts/eventOccurrences.d.ts +10 -0
- package/dist/posts/eventOccurrences.js +61 -0
- package/dist/posts/finders.d.ts +47 -16
- package/dist/posts/finders.js +93 -62
- package/dist/posts/helpers/filters.js +14 -9
- package/dist/posts/helpers/index.d.ts +129 -30
- package/dist/posts/helpers/index.js +66 -33
- package/dist/posts/index.d.ts +7 -1
- package/dist/posts/index.js +7 -1
- package/dist/posts/mapping.d.ts +491 -13
- package/dist/posts/mapping.js +45 -10
- package/dist/posts/mutations.d.ts +441 -4
- package/dist/posts/mutations.js +177 -43
- package/dist/posts/pollEnd.d.ts +3 -0
- package/dist/posts/pollEnd.js +7 -0
- package/dist/posts/pollEndJobs.d.ts +8 -0
- package/dist/posts/pollEndJobs.js +49 -0
- package/dist/posts/replyClosure.d.ts +10 -0
- package/dist/posts/replyClosure.js +43 -0
- package/dist/posts/rsvpConfirmationEmail.js +14 -15
- package/dist/posts/threadPreview.d.ts +8 -0
- package/dist/posts/threadPreview.js +44 -0
- package/dist/posts/unseenCounts.d.ts +2 -0
- package/dist/posts/unseenCounts.js +28 -8
- package/dist/profileSettings/cache.js +22 -5
- package/dist/profileSettings/mapping.d.ts +2 -0
- package/dist/profiles/activityQueries.d.ts +5 -0
- package/dist/profiles/activityQueries.js +85 -0
- package/dist/profiles/activitySummary.d.ts +3 -0
- package/dist/profiles/activitySummary.js +87 -0
- package/dist/profiles/blocks.d.ts +12 -0
- package/dist/profiles/blocks.js +73 -0
- package/dist/profiles/cache.d.ts +4 -1
- package/dist/profiles/cache.js +28 -7
- package/dist/profiles/finders.d.ts +2 -1
- package/dist/profiles/finders.js +8 -3
- package/dist/profiles/helpers.d.ts +7 -5
- package/dist/profiles/index.d.ts +3 -1
- package/dist/profiles/index.js +3 -1
- package/dist/profiles/mapping.d.ts +10 -5
- package/dist/profiles/mapping.js +13 -1
- package/dist/profiles/mutations.d.ts +8 -4
- package/dist/profiles/mutations.js +42 -15
- package/dist/pushSubscriptions/helpers.d.ts +2 -2
- package/dist/pushSubscriptions/mutations.js +13 -1
- package/dist/redis/connection.d.ts +2 -0
- package/dist/redis/connection.js +25 -6
- package/dist/reports/helpers.d.ts +6 -6
- package/dist/roles/index.d.ts +1 -1
- package/dist/roles/index.js +1 -1
- package/dist/roles/mapping.d.ts +1 -0
- package/dist/roles/mutations.js +86 -3
- package/dist/search/mapping.d.ts +1 -1
- package/dist/search/mapping.js +6 -2
- package/dist/server/index.d.ts +19 -1
- package/dist/server/index.js +37 -18
- package/dist/server/stablePublicServerInfo.d.ts +17 -0
- package/dist/server/stablePublicServerInfo.js +37 -0
- package/dist/server/status.d.ts +25 -0
- package/dist/server/status.js +98 -0
- package/dist/stats/finders.d.ts +1 -16131
- package/dist/stats/finders.js +9 -5
- package/dist/stats/mapping.d.ts +21 -1
- package/dist/stats/mapping.js +0 -3
- package/package.json +6 -12
- package/dist/db/arango.d.ts +0 -2
- package/dist/db/arango.js +0 -110
- package/dist/db/migration/autoMigrate.d.ts +0 -2
- package/dist/db/migration/autoMigrate.js +0 -111
- package/dist/db/migration/cli.d.ts +0 -1
- package/dist/db/migration/cli.js +0 -56
- package/dist/db/migration/detect.d.ts +0 -6
- package/dist/db/migration/detect.js +0 -87
- package/dist/db/migration/exportArango.d.ts +0 -4
- package/dist/db/migration/exportArango.js +0 -80
- package/dist/db/migration/importPostgres.d.ts +0 -3
- package/dist/db/migration/importPostgres.js +0 -18
- package/dist/db/migration/transform.d.ts +0 -18
- package/dist/db/migration/transform.js +0 -209
- package/dist/db/migration/validate.d.ts +0 -18
- package/dist/db/migration/validate.js +0 -69
- package/dist/db/pg/sql/meta/0000_snapshot.json +0 -3380
- package/dist/db/pg/sql/meta/0004_snapshot.json +0 -4114
- package/dist/db/pg/sql/meta/0005_snapshot.json +0 -4179
- package/dist/mastodon/index.d.ts +0 -4
- package/dist/mastodon/index.js +0 -51
- package/dist/mastodon/types.d.ts +0 -7579
- package/dist/mastodon/types.js +0 -523
- package/dist/mastodon/typescript.d.ts +0 -1578
- package/dist/mastodon/typescript.js +0 -1
- package/dist/roles/defaults.d.ts +0 -2
- package/dist/roles/defaults.js +0 -94
package/dist/db/helpers.js
CHANGED
|
@@ -1,152 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { collectionElement, query, literal, } from '@openpeepshq/arango-querybuilder';
|
|
1
|
+
import { parseFeedCursor } from '@openpeepshq/common';
|
|
2
|
+
import { and, eq } from 'drizzle-orm';
|
|
4
3
|
import { deleteEdge as deletePgEdge, insertEdge } from './pg/helpers.js';
|
|
5
4
|
import { asTable, edgeRegistry } from './pg/map/registry.js';
|
|
6
5
|
import { nowIso } from './pg/mappers.js';
|
|
7
|
-
import {
|
|
8
|
-
import { documentKeyAfter, documentKeyBefore } from './pg/filters/index.js';
|
|
6
|
+
import { documentKeyAfter, documentKeyBefore, postFilters } from './pg/filters/index.js';
|
|
9
7
|
import { sorts } from './pg/queries/index.js';
|
|
10
|
-
import { asyncFilter } from '@openpeepshq/common/lib';
|
|
11
|
-
import { logger } from '../log/index.js';
|
|
12
|
-
const log = logger('openpeeps:db');
|
|
13
|
-
const collectionName = (collectionOrName) => typeof collectionOrName === 'string'
|
|
14
|
-
? collectionOrName
|
|
15
|
-
: collectionOrName.name;
|
|
16
|
-
export const addModificationDates = async (collection) => {
|
|
17
|
-
await collection.properties({
|
|
18
|
-
computedValues: [
|
|
19
|
-
{
|
|
20
|
-
name: 'createdAt',
|
|
21
|
-
expression: 'RETURN DATE_ISO8601(DATE_NOW())',
|
|
22
|
-
computeOn: ['insert'],
|
|
23
|
-
overwrite: false,
|
|
24
|
-
failOnWarning: false,
|
|
25
|
-
keepNull: true,
|
|
26
|
-
},
|
|
27
|
-
{
|
|
28
|
-
name: 'updatedAt',
|
|
29
|
-
expression: 'RETURN DATE_ISO8601(DATE_NOW())',
|
|
30
|
-
computeOn: ['update', 'replace', 'insert'],
|
|
31
|
-
overwrite: false,
|
|
32
|
-
failOnWarning: false,
|
|
33
|
-
keepNull: true,
|
|
34
|
-
},
|
|
35
|
-
],
|
|
36
|
-
});
|
|
37
|
-
};
|
|
38
|
-
export const addIndices = async (collection, indices) => {
|
|
39
|
-
for (const index of indices) {
|
|
40
|
-
if (!index.name) {
|
|
41
|
-
return;
|
|
42
|
-
}
|
|
43
|
-
try {
|
|
44
|
-
log.info('ensuring index', index.name);
|
|
45
|
-
await collection.ensureIndex(index);
|
|
46
|
-
}
|
|
47
|
-
catch (error) {
|
|
48
|
-
const message = error.message;
|
|
49
|
-
if (message.includes('duplicate value')) {
|
|
50
|
-
log.info('index already exists', index.name);
|
|
51
|
-
log.info('dropping and recreating...');
|
|
52
|
-
await collection.dropIndex(index.name);
|
|
53
|
-
await collection.ensureIndex(index);
|
|
54
|
-
log.info('index recreated');
|
|
55
|
-
}
|
|
56
|
-
else {
|
|
57
|
-
log.error('error ensuring index', index.name, message);
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
};
|
|
62
|
-
export const ensureIndexedCollection = async (db, collectionInfo) => {
|
|
63
|
-
var _a;
|
|
64
|
-
const maybeCollection = db.collection(collectionInfo.name);
|
|
65
|
-
const collection = (await maybeCollection.exists())
|
|
66
|
-
? maybeCollection
|
|
67
|
-
: collectionInfo.edge
|
|
68
|
-
? await db.createEdgeCollection(collectionInfo.name)
|
|
69
|
-
: await db.createCollection(collectionInfo.name);
|
|
70
|
-
await addModificationDates(collection);
|
|
71
|
-
await addIndices(collection, ((_a = collectionInfo.indices) !== null && _a !== void 0 ? _a : []));
|
|
72
|
-
return collection;
|
|
73
|
-
};
|
|
74
|
-
const isEqualView = (viewInfo1, viewInfo2) => viewInfo1.indexes.length === viewInfo2.indexes.length &&
|
|
75
|
-
viewInfo1.indexes.every((index1) => viewInfo2.indexes.find((index2) => index1.collection === index2.collection &&
|
|
76
|
-
index1.index === index2.index)) &&
|
|
77
|
-
viewInfo2.indexes.every((index2) => viewInfo1.indexes.find((index1) => index1.collection === index2.collection &&
|
|
78
|
-
index1.index === index2.index));
|
|
79
|
-
export const ensureView = async (db, viewInfo) => {
|
|
80
|
-
const view = db.view(viewInfo.name);
|
|
81
|
-
if (await view.exists()) {
|
|
82
|
-
const viewData = await view.properties();
|
|
83
|
-
if (viewData.type === 'search-alias' && isEqualView(viewData, viewInfo)) {
|
|
84
|
-
return view;
|
|
85
|
-
}
|
|
86
|
-
else {
|
|
87
|
-
await view.drop();
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
await view.create(viewInfo);
|
|
91
|
-
};
|
|
92
|
-
const replaceEdgeDefinition = (db) => (edgeDefinition) => db
|
|
93
|
-
.listGraphs()
|
|
94
|
-
.then((graphInfos) => graphInfos.map((gi) => gi.edgeDefinitions).flat())
|
|
95
|
-
.then((edgeDefinitions) => edgeDefinitions.find((ed) => ed.collection === edgeDefinition.collection) || edgeDefinition);
|
|
96
|
-
export const ensureGraph = async (db, name, edgeDefinitions) => {
|
|
97
|
-
const replacedEdgeDefinitions = await Promise.all(edgeDefinitions.map(replaceEdgeDefinition(db)));
|
|
98
|
-
const graph = db.graph(name);
|
|
99
|
-
if (await graph.exists()) {
|
|
100
|
-
const edgeDefinitionsToAdd = await asyncFilter(replacedEdgeDefinitions, (ed) => graph
|
|
101
|
-
.listEdgeCollections()
|
|
102
|
-
.then((ecs) => !ecs.includes(collectionName(ed.collection))));
|
|
103
|
-
const edgeDefinitionsToRemove = await graph
|
|
104
|
-
.listEdgeCollections()
|
|
105
|
-
.then((ecs) => ecs.filter((ec) => !replacedEdgeDefinitions
|
|
106
|
-
.map((ed) => collectionName(ed.collection))
|
|
107
|
-
.includes(ec)));
|
|
108
|
-
for (const edgeDefinition of edgeDefinitionsToAdd) {
|
|
109
|
-
await graph.addEdgeDefinition(edgeDefinition);
|
|
110
|
-
}
|
|
111
|
-
for (const edgeDefinitionCollectionName of edgeDefinitionsToRemove) {
|
|
112
|
-
await graph.removeEdgeDefinition(edgeDefinitionCollectionName);
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
else {
|
|
116
|
-
return await db.createGraph(name, replacedEdgeDefinitions);
|
|
117
|
-
}
|
|
118
|
-
return graph;
|
|
119
|
-
};
|
|
120
|
-
export const ensureFunction = async (db, { name, dbFunction }) => {
|
|
121
|
-
console.log('--------------------------------');
|
|
122
|
-
console.log('ensureFunction', name);
|
|
123
|
-
console.log('--------------------------------');
|
|
124
|
-
console.log(dbFunction.toString());
|
|
125
|
-
console.log('--------------------------------');
|
|
126
|
-
db.createUserFunction(`ALLPEEP::${name}`, dbFunction.toString(), true);
|
|
127
|
-
};
|
|
128
|
-
const setId = (document) => (Object.assign(Object.assign({}, document), { id: document._key }));
|
|
129
|
-
export const createEdge = async (collection, document) => {
|
|
130
|
-
var _a;
|
|
131
|
-
const data = Object.assign(Object.assign({}, document), { _key: (_a = document.id) !== null && _a !== void 0 ? _a : uuidv7() });
|
|
132
|
-
const createdEdge = (await collection.save(data, { returnNew: true })).new;
|
|
133
|
-
if (createdEdge) {
|
|
134
|
-
return setId(createdEdge);
|
|
135
|
-
}
|
|
136
|
-
else {
|
|
137
|
-
throw Error(`Edge in collection ${collection.name} could not be created.`);
|
|
138
|
-
}
|
|
139
|
-
};
|
|
140
|
-
export const updateEdge = async (collection, documentKey, document) => (await collection.update(documentKey, document, { returnNew: true })).new;
|
|
141
|
-
export const deleteEdge = async (collection, documentKey) => await collection.remove(documentKey);
|
|
142
|
-
export const findOneBy = (db, collectionInfo) => (filter) => query().collection(collectionInfo.name).filter(filter).first(db);
|
|
143
|
-
export const edgeCollections = async (database) => database
|
|
144
|
-
.collections()
|
|
145
|
-
.then((collections) => asyncFilter(collections, async (c) => c.properties().then((p) => p.type === CollectionType.EDGE_COLLECTION)));
|
|
146
|
-
const getEdge = async (db, collection, from, to) => findOneBy(db, collection)({
|
|
147
|
-
name: literal(collectionElement(collection)),
|
|
148
|
-
matches: { _from: from, _to: to },
|
|
149
|
-
});
|
|
150
8
|
const getPgEdge = async (db, edgeCollectionName, fromId, toId) => {
|
|
151
9
|
const edgeConfig = edgeRegistry[edgeCollectionName];
|
|
152
10
|
if (!edgeConfig) {
|
|
@@ -171,14 +29,14 @@ export const connector = (fromCollectionInfo, toCollectionInfo, edgeCollectionIn
|
|
|
171
29
|
const id = await insertEdge(db, edgeConfig.table, from.id, to.id, data);
|
|
172
30
|
return Object.assign(Object.assign({}, data), { id, _from: `${fromCollectionInfo.name}/${from.id}`, _to: `${toCollectionInfo.name}/${to.id}` });
|
|
173
31
|
};
|
|
174
|
-
export const disconnector = (
|
|
32
|
+
export const disconnector = (_fromCollectionInfo, _toCollectionInfo, edgeCollectionInfo) => async (db, from, to) => {
|
|
175
33
|
const edgeConfig = edgeRegistry[edgeCollectionInfo.name];
|
|
176
34
|
if (!edgeConfig) {
|
|
177
35
|
throw new Error(`Unknown edge collection: ${edgeCollectionInfo.name}`);
|
|
178
36
|
}
|
|
179
37
|
await deletePgEdge(db, edgeConfig.table, from.id, to.id);
|
|
180
38
|
};
|
|
181
|
-
export const connectionUpdater = (
|
|
39
|
+
export const connectionUpdater = (_fromCollectionInfo, _toCollectionInfo, edgeCollectionInfo) => async (db, from, to, data) => {
|
|
182
40
|
const edgeConfig = edgeRegistry[edgeCollectionInfo.name];
|
|
183
41
|
if (!edgeConfig) {
|
|
184
42
|
throw new Error(`Unknown edge collection: ${edgeCollectionInfo.name}`);
|
|
@@ -203,19 +61,39 @@ export const addQuerySort = (mapping, sort) => ((sort === null || sort === void
|
|
|
203
61
|
export const sortNewestFirst = (mapping) => mapping.sort(sorts.idDesc);
|
|
204
62
|
export const sortOldestFirst = (mapping) => mapping.sort(sorts.idAsc);
|
|
205
63
|
export const addStartLimit = (mapping, start, limit = 100) => filterBefore(sortNewestFirst(mapping.limit(limit)), start);
|
|
206
|
-
export const addStart = (mapping, start) => filterBefore(sortNewestFirst(mapping), start);
|
|
64
|
+
export const addStart = (mapping, start) => { var _a; return filterBefore(sortNewestFirst(mapping), (_a = parseFeedCursor(start)) === null || _a === void 0 ? void 0 : _a.id); };
|
|
65
|
+
export const addActivityStart = (mapping, start) => {
|
|
66
|
+
const sorted = mapping.sort(sorts.lastActivityDesc);
|
|
67
|
+
const cursor = parseFeedCursor(start);
|
|
68
|
+
if (!cursor)
|
|
69
|
+
return sorted;
|
|
70
|
+
return sorted.filter(postFilters.afterActivity(cursor));
|
|
71
|
+
};
|
|
207
72
|
const buildLimit = (limit, offset) => limit && offset ? [offset, limit] : limit;
|
|
73
|
+
/**
|
|
74
|
+
* Ceiling on base rows read for one page, as a multiple of the page size. A
|
|
75
|
+
* post-filter that rejects everything would otherwise walk (and hydrate) the
|
|
76
|
+
* whole collection before returning an empty page.
|
|
77
|
+
*/
|
|
78
|
+
const MAX_SCAN_FACTOR = 10;
|
|
208
79
|
export const filterAndTransform = async (queryResult, db, options) => {
|
|
209
|
-
const { filter = (
|
|
80
|
+
const { filter = () => true, transform = async (i) => i, limit = 100, offset = 0, } = options;
|
|
210
81
|
const result = [];
|
|
82
|
+
const maxScan = limit * MAX_SCAN_FACTOR;
|
|
83
|
+
let scanned = 0;
|
|
211
84
|
let pageOffset = 0;
|
|
212
|
-
while (result.length < limit) {
|
|
213
|
-
const
|
|
85
|
+
while (result.length < limit && scanned < maxScan) {
|
|
86
|
+
const shortfall = limit - result.length;
|
|
87
|
+
// Transform is the expensive part, so read only what the page still needs
|
|
88
|
+
// until a page proves the filter is dropping rows; then over-fetch to
|
|
89
|
+
// converge without a round trip per remaining row.
|
|
90
|
+
const nextPageLength = Math.min(pageOffset === 0 ? shortfall : shortfall * 2, maxScan - scanned);
|
|
214
91
|
const list = await queryResult
|
|
215
92
|
.limit(buildLimit(nextPageLength, offset + pageOffset))
|
|
216
93
|
.all(db);
|
|
217
94
|
const filteredList = await Promise.all(list.map(transform)).then((items) => items.filter(filter));
|
|
218
|
-
result.push(...filteredList.slice(0,
|
|
95
|
+
result.push(...filteredList.slice(0, shortfall));
|
|
96
|
+
scanned += list.length;
|
|
219
97
|
if (list.length < nextPageLength) {
|
|
220
98
|
break;
|
|
221
99
|
}
|
package/dist/db/index.d.ts
CHANGED
|
@@ -5,9 +5,11 @@ export * from './explorer';
|
|
|
5
5
|
export { map } from './pg/map';
|
|
6
6
|
export { collectionInfos } from './pg/collections';
|
|
7
7
|
export type { CollectionInfoKey } from './pg/collections';
|
|
8
|
-
export type
|
|
8
|
+
export { closePostgres, type PgDb } from './pg/client';
|
|
9
9
|
export type { PgFilter, SqlFilter } from './pg/map/queryTypes';
|
|
10
10
|
export { combine, createdAtBetween, documentKeyAfter, documentKeyBefore, edgeFilters, eventTimeFilters, groupFilters, isSqlFilter, notificationFilters, pgSql, postFilters, profileFilters, } from './pg/filters';
|
|
11
11
|
export { computedFields, sorts } from './pg/queries';
|
|
12
12
|
export declare const allpeepDb: () => Promise<OpenpeepsDatabase>;
|
|
13
|
+
/** Clear the cached DB after `closePostgres()` so the next call re-inits. */
|
|
14
|
+
export declare const resetAllpeepDb: () => void;
|
|
13
15
|
export declare const database: () => Promise<PgDb>;
|
package/dist/db/index.js
CHANGED
|
@@ -3,6 +3,7 @@ export { empty } from './examples.js';
|
|
|
3
3
|
export * from './explorer/index.js';
|
|
4
4
|
export { map } from './pg/map/index.js';
|
|
5
5
|
export { collectionInfos } from './pg/collections.js';
|
|
6
|
+
export { closePostgres } from './pg/client.js';
|
|
6
7
|
export { combine, createdAtBetween, documentKeyAfter, documentKeyBefore, edgeFilters, eventTimeFilters, groupFilters, isSqlFilter, notificationFilters, pgSql, postFilters, profileFilters, } from './pg/filters/index.js';
|
|
7
8
|
export { computedFields, sorts } from './pg/queries/index.js';
|
|
8
9
|
let dbPromise;
|
|
@@ -12,4 +13,8 @@ export const allpeepDb = () => {
|
|
|
12
13
|
}
|
|
13
14
|
return dbPromise;
|
|
14
15
|
};
|
|
16
|
+
/** Clear the cached DB after `closePostgres()` so the next call re-inits. */
|
|
17
|
+
export const resetAllpeepDb = () => {
|
|
18
|
+
dbPromise = undefined;
|
|
19
|
+
};
|
|
15
20
|
export const database = () => allpeepDb().then(({ db }) => db);
|
package/dist/db/init.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { logger } from '../log/index.js';
|
|
2
|
-
import { maybeAutoMigrateFromArango } from './migration/autoMigrate.js';
|
|
3
2
|
import { initPostgres } from './pg/client.js';
|
|
3
|
+
import { backfillLocalFederationIdentities } from '../federation/identity.js';
|
|
4
4
|
const log = logger('openpeeps:db');
|
|
5
5
|
export const initDb = async () => {
|
|
6
6
|
log.info('Initializing Postgres');
|
|
7
7
|
const db = await initPostgres();
|
|
8
|
-
await
|
|
8
|
+
await backfillLocalFederationIdentities();
|
|
9
9
|
return { db };
|
|
10
10
|
};
|
|
@@ -1,18 +1,23 @@
|
|
|
1
|
-
|
|
2
|
-
/** Arango exports can contain duplicate _key lines; keep the last row per id. */
|
|
1
|
+
/** Keep the last row per id when a JSONL file repeats keys. */
|
|
3
2
|
export declare const dedupeRowsById: <T extends Record<string, unknown>>(rows: T[]) => T[];
|
|
4
3
|
export declare const collectionJsonlPath: (collectionsDir: string, collection: string) => string;
|
|
5
4
|
export declare const truncateAllTables: () => Promise<void>;
|
|
6
5
|
export declare const isUuid: (value: unknown) => value is string;
|
|
7
|
-
/** Collapse empty / duplicate hashtag names onto one row (unique on name). */
|
|
8
|
-
export declare const prepareHashtagRows: (rows: Record<string, unknown>[], context: ImportContext) => Record<string, unknown>[];
|
|
9
|
-
export declare const importArangoCollection: (collection: string, collectionsDir: string, context?: ImportContext) => Promise<number>;
|
|
10
6
|
export declare const importPostgresRowCollection: (collection: string, collectionsDir: string) => Promise<number>;
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
7
|
+
/** Legacy reactions rows become append-only reaction entries. */
|
|
8
|
+
export declare const wrapReactionEntryBody: (body: Record<string, unknown> | null | undefined) => {
|
|
9
|
+
type: "reaction";
|
|
10
|
+
data: {
|
|
11
|
+
reaction: string;
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
/** Older dumps may still have reactions.jsonl; store them as entries. */
|
|
15
|
+
export declare const importLegacyReactionsAsEntries: (collectionsDir: string) => Promise<number>;
|
|
16
|
+
export type PlaceholderColumn = {
|
|
17
|
+
table: string;
|
|
18
|
+
column: string;
|
|
19
|
+
};
|
|
20
|
+
export declare const importAllPostgresCollections: (collectionsDir: string, schemaVersionFromBackup?: string) => Promise<{
|
|
16
21
|
imported: Record<string, number>;
|
|
17
22
|
total: number;
|
|
18
23
|
}>;
|
|
@@ -2,16 +2,26 @@ import { randomUUID } from 'node:crypto';
|
|
|
2
2
|
import { appendFile, access } from 'node:fs/promises';
|
|
3
3
|
import { constants } from 'node:fs';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
|
-
import { getTableName, sql } from 'drizzle-orm';
|
|
5
|
+
import { getTableColumns, getTableName, sql } from 'drizzle-orm';
|
|
6
6
|
import { logger } from '../../log/index.js';
|
|
7
7
|
import { pgDb } from '../pg/client.js';
|
|
8
|
-
import { runMigrations } from '../pg/migrate.js';
|
|
9
|
-
import { documentRegistry, edgeRegistry, getTableForCollection, } from '../pg/map/registry.js';
|
|
10
|
-
import { arangoDocToDocumentRow, arangoDocToEdgeRow, buildPostCreatorIdByPostId, isEdgeCollection, normalizeImportId, } from './transform.js';
|
|
8
|
+
import { resetAndMigrateToSchemaVersion, resolveRestoreSchemaVersion, runMigrations, } from '../pg/migrate.js';
|
|
9
|
+
import { documentRegistry, edgeRegistry, getTableForCollection, isEdgeCollection, } from '../pg/map/registry.js';
|
|
11
10
|
import { BATCH_SIZE, DOCUMENT_IMPORT_ORDER, EDGE_IMPORT_ORDER, readJsonl, } from './shared.js';
|
|
12
11
|
const log = logger('core:db:import');
|
|
12
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
13
|
+
const normalizeImportId = (value) => {
|
|
14
|
+
if (typeof value !== 'string') {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
const trimmed = value.trim();
|
|
18
|
+
if (!trimmed) {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
return UUID_RE.test(trimmed) ? trimmed.toLowerCase() : trimmed;
|
|
22
|
+
};
|
|
13
23
|
const rowDedupeKey = (row) => { var _a; return normalizeImportId((_a = row.id) !== null && _a !== void 0 ? _a : row.key); };
|
|
14
|
-
/**
|
|
24
|
+
/** Keep the last row per id when a JSONL file repeats keys. */
|
|
15
25
|
export const dedupeRowsById = (rows) => {
|
|
16
26
|
const byKey = new Map();
|
|
17
27
|
const withoutKey = [];
|
|
@@ -49,13 +59,7 @@ export const truncateAllTables = async () => {
|
|
|
49
59
|
}
|
|
50
60
|
await db.execute(sql.raw(`TRUNCATE TABLE ${existing.map((name) => `"${name}"`).join(', ')} RESTART IDENTITY CASCADE`));
|
|
51
61
|
};
|
|
52
|
-
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
53
62
|
export const isUuid = (value) => typeof value === 'string' && UUID_RE.test(value);
|
|
54
|
-
/**
|
|
55
|
-
* Edge `id` columns are uuid. Legacy Arango edge `_key`s are sometimes numeric
|
|
56
|
-
* (or otherwise non-UUID); replace those so the insert does not fail. Document
|
|
57
|
-
* collections are left alone (`data_migrations.id` is text, not uuid).
|
|
58
|
-
*/
|
|
59
63
|
const ensureEdgeUuidId = (collection, row) => {
|
|
60
64
|
var _a;
|
|
61
65
|
if (!isEdgeCollection(collection)) {
|
|
@@ -69,78 +73,7 @@ const ensureEdgeUuidId = (collection, row) => {
|
|
|
69
73
|
log.warn('Replaced non-UUID %s edge id %s with %s', collection, String(row.id), next.id);
|
|
70
74
|
return next;
|
|
71
75
|
};
|
|
72
|
-
const
|
|
73
|
-
if (collection === 'posts' && !row.creatorId) {
|
|
74
|
-
log.warn('Skipping post %s: missing creatorId', row.id);
|
|
75
|
-
return false;
|
|
76
|
-
}
|
|
77
|
-
if (collection === 'jamEvents' && !row.postId) {
|
|
78
|
-
log.warn('Skipping jam event %s: missing postId', row.id);
|
|
79
|
-
return false;
|
|
80
|
-
}
|
|
81
|
-
if (collection === 'profileSettings' && !row.profileId) {
|
|
82
|
-
log.warn('Skipping profile settings %s: missing profileId', row.id);
|
|
83
|
-
return false;
|
|
84
|
-
}
|
|
85
|
-
return true;
|
|
86
|
-
};
|
|
87
|
-
/** Collapse empty / duplicate hashtag names onto one row (unique on name). */
|
|
88
|
-
export const prepareHashtagRows = (rows, context) => {
|
|
89
|
-
var _a;
|
|
90
|
-
const remap = (_a = context.hashtagIdRemap) !== null && _a !== void 0 ? _a : new Map();
|
|
91
|
-
context.hashtagIdRemap = remap;
|
|
92
|
-
const byName = new Map();
|
|
93
|
-
const prepared = [];
|
|
94
|
-
for (const row of rows) {
|
|
95
|
-
const id = typeof row.id === 'string' ? row.id : undefined;
|
|
96
|
-
const name = typeof row.name === 'string' ? row.name.trim().toLowerCase() : '';
|
|
97
|
-
if (!name) {
|
|
98
|
-
if (id)
|
|
99
|
-
remap.set(id, '');
|
|
100
|
-
log.warn('Skipping hashtag %s: empty name', id !== null && id !== void 0 ? id : '(no id)');
|
|
101
|
-
continue;
|
|
102
|
-
}
|
|
103
|
-
row.name = name;
|
|
104
|
-
const existing = byName.get(name);
|
|
105
|
-
if (existing) {
|
|
106
|
-
const keptId = typeof existing.id === 'string' ? existing.id : '';
|
|
107
|
-
if (id)
|
|
108
|
-
remap.set(id, keptId);
|
|
109
|
-
log.warn('Skipping duplicate hashtag name "%s" (id %s → %s)', name, id, keptId || '(unknown)');
|
|
110
|
-
continue;
|
|
111
|
-
}
|
|
112
|
-
byName.set(name, row);
|
|
113
|
-
prepared.push(row);
|
|
114
|
-
}
|
|
115
|
-
return prepared;
|
|
116
|
-
};
|
|
117
|
-
const applyHashtagEdgeRemap = (collection, rows, context) => {
|
|
118
|
-
var _a;
|
|
119
|
-
if (collection !== 'postHashtags' || !((_a = context.hashtagIdRemap) === null || _a === void 0 ? void 0 : _a.size)) {
|
|
120
|
-
return rows;
|
|
121
|
-
}
|
|
122
|
-
const remap = context.hashtagIdRemap;
|
|
123
|
-
const out = [];
|
|
124
|
-
let dropped = 0;
|
|
125
|
-
for (const row of rows) {
|
|
126
|
-
const toId = typeof row.toId === 'string' ? row.toId : undefined;
|
|
127
|
-
if (!toId || !remap.has(toId)) {
|
|
128
|
-
out.push(row);
|
|
129
|
-
continue;
|
|
130
|
-
}
|
|
131
|
-
const mapped = remap.get(toId);
|
|
132
|
-
if (!mapped) {
|
|
133
|
-
dropped += 1;
|
|
134
|
-
continue;
|
|
135
|
-
}
|
|
136
|
-
out.push(Object.assign(Object.assign({}, row), { toId: mapped }));
|
|
137
|
-
}
|
|
138
|
-
if (dropped > 0) {
|
|
139
|
-
log.warn('Dropped %d postHashtags edge(s) pointing at skipped hashtags', dropped);
|
|
140
|
-
}
|
|
141
|
-
return out;
|
|
142
|
-
};
|
|
143
|
-
export const importArangoCollection = async (collection, collectionsDir, context = {}) => {
|
|
76
|
+
export const importPostgresRowCollection = async (collection, collectionsDir) => {
|
|
144
77
|
if (!isKnownCollection(collection)) {
|
|
145
78
|
return 0;
|
|
146
79
|
}
|
|
@@ -151,106 +84,134 @@ export const importArangoCollection = async (collection, collectionsDir, context
|
|
|
151
84
|
catch (_a) {
|
|
152
85
|
return 0;
|
|
153
86
|
}
|
|
154
|
-
const
|
|
155
|
-
if (
|
|
87
|
+
const mapped = await readJsonl(filePath);
|
|
88
|
+
if (mapped.length === 0) {
|
|
156
89
|
return 0;
|
|
157
90
|
}
|
|
91
|
+
const withValidIds = mapped.map((row) => ensureEdgeUuidId(collection, row));
|
|
92
|
+
const rows = dedupeRowsById(withValidIds);
|
|
93
|
+
if (rows.length < mapped.length) {
|
|
94
|
+
log.warn('Dropped %d duplicate row(s) while importing %s', mapped.length - rows.length, collection);
|
|
95
|
+
}
|
|
158
96
|
const table = getTableForCollection(collection);
|
|
159
97
|
const db = pgDb();
|
|
160
|
-
let mapped = docs.map((doc) => isEdgeCollection(collection)
|
|
161
|
-
? arangoDocToEdgeRow(collection, doc)
|
|
162
|
-
: arangoDocToDocumentRow(collection, doc, context));
|
|
163
|
-
if (collection === 'hashtags') {
|
|
164
|
-
mapped = prepareHashtagRows(mapped, context);
|
|
165
|
-
}
|
|
166
|
-
else {
|
|
167
|
-
mapped = mapped.filter((row) => documentRowIsImportable(collection, row));
|
|
168
|
-
}
|
|
169
|
-
mapped = applyHashtagEdgeRemap(collection, mapped, context);
|
|
170
|
-
mapped = mapped.map((row) => ensureEdgeUuidId(collection, row));
|
|
171
|
-
const beforeDedupe = mapped.length;
|
|
172
|
-
const rows = dedupeRowsById(mapped);
|
|
173
|
-
if (rows.length < beforeDedupe) {
|
|
174
|
-
log.warn('Dropped %d duplicate row(s) while importing %s (e.g. remapped config keys or duplicate _key)', beforeDedupe - rows.length, collection);
|
|
175
|
-
}
|
|
176
|
-
if (rows.length === 0) {
|
|
177
|
-
return 0;
|
|
178
|
-
}
|
|
179
98
|
let imported = 0;
|
|
180
99
|
for (let offset = 0; offset < rows.length; offset += BATCH_SIZE) {
|
|
181
100
|
const batch = rows.slice(offset, offset + BATCH_SIZE);
|
|
182
|
-
|
|
183
|
-
await db.insert(table).values(batch);
|
|
184
|
-
}
|
|
185
|
-
catch (err) {
|
|
186
|
-
const cause = err && typeof err === 'object' && 'cause' in err
|
|
187
|
-
? err.cause
|
|
188
|
-
: undefined;
|
|
189
|
-
const detail = cause instanceof Error
|
|
190
|
-
? cause.message
|
|
191
|
-
: err instanceof Error
|
|
192
|
-
? err.message
|
|
193
|
-
: String(err);
|
|
194
|
-
throw new Error(`Failed importing ${collection} batch at offset ${offset} (${batch.length} rows): ${detail}`);
|
|
195
|
-
}
|
|
101
|
+
await db.insert(table).values(batch);
|
|
196
102
|
imported += batch.length;
|
|
197
103
|
}
|
|
198
|
-
log.info('Imported %d rows into %s from
|
|
104
|
+
log.info('Imported %d rows into %s from Postgres JSONL', imported, collection);
|
|
199
105
|
return imported;
|
|
200
106
|
};
|
|
201
|
-
|
|
202
|
-
|
|
107
|
+
/** Legacy reactions rows become append-only reaction entries. */
|
|
108
|
+
export const wrapReactionEntryBody = (body) => {
|
|
109
|
+
var _a;
|
|
110
|
+
if ((body === null || body === void 0 ? void 0 : body.type) === 'reaction') {
|
|
111
|
+
const reaction = typeof ((_a = body.data) === null || _a === void 0 ? void 0 : _a.reaction) ===
|
|
112
|
+
'string'
|
|
113
|
+
? body.data.reaction
|
|
114
|
+
: typeof body.reaction === 'string'
|
|
115
|
+
? body.reaction
|
|
116
|
+
: '👍';
|
|
117
|
+
return { type: 'reaction', data: { reaction } };
|
|
118
|
+
}
|
|
119
|
+
const reaction = typeof (body === null || body === void 0 ? void 0 : body.reaction) === 'string' ? body.reaction : '👍';
|
|
120
|
+
return { type: 'reaction', data: { reaction } };
|
|
121
|
+
};
|
|
122
|
+
const insertEntryRows = async (rows) => {
|
|
123
|
+
if (rows.length === 0)
|
|
203
124
|
return 0;
|
|
125
|
+
const table = getTableForCollection('entries');
|
|
126
|
+
const db = pgDb();
|
|
127
|
+
let imported = 0;
|
|
128
|
+
for (let offset = 0; offset < rows.length; offset += BATCH_SIZE) {
|
|
129
|
+
const batch = rows.slice(offset, offset + BATCH_SIZE);
|
|
130
|
+
await db.insert(table).values(batch);
|
|
131
|
+
imported += batch.length;
|
|
204
132
|
}
|
|
205
|
-
|
|
133
|
+
return imported;
|
|
134
|
+
};
|
|
135
|
+
/** Older dumps may still have reactions.jsonl; store them as entries. */
|
|
136
|
+
export const importLegacyReactionsAsEntries = async (collectionsDir) => {
|
|
137
|
+
const filePath = collectionJsonlPath(collectionsDir, 'reactions');
|
|
206
138
|
try {
|
|
207
139
|
await access(filePath, constants.F_OK);
|
|
208
140
|
}
|
|
209
141
|
catch (_a) {
|
|
210
142
|
return 0;
|
|
211
143
|
}
|
|
212
|
-
const
|
|
213
|
-
if (
|
|
144
|
+
const docs = await readJsonl(filePath);
|
|
145
|
+
if (docs.length === 0) {
|
|
214
146
|
return 0;
|
|
215
147
|
}
|
|
216
|
-
const
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
const
|
|
222
|
-
|
|
223
|
-
let imported = 0;
|
|
224
|
-
for (let offset = 0; offset < rows.length; offset += BATCH_SIZE) {
|
|
225
|
-
const batch = rows.slice(offset, offset + BATCH_SIZE);
|
|
226
|
-
await db.insert(table).values(batch);
|
|
227
|
-
imported += batch.length;
|
|
228
|
-
}
|
|
229
|
-
log.info('Imported %d rows into %s from Postgres JSONL', imported, collection);
|
|
148
|
+
const mapped = docs.map((doc) => {
|
|
149
|
+
var _a;
|
|
150
|
+
return ensureEdgeUuidId('entries', Object.assign(Object.assign({}, doc), { body: wrapReactionEntryBody((_a = doc.body) !== null && _a !== void 0 ? _a : doc) }));
|
|
151
|
+
});
|
|
152
|
+
const rows = dedupeRowsById(mapped);
|
|
153
|
+
const imported = await insertEntryRows(rows);
|
|
154
|
+
log.info('Imported %d legacy reactions as entries', imported);
|
|
230
155
|
return imported;
|
|
231
156
|
};
|
|
232
157
|
const sumImported = (imported) => Object.values(imported).reduce((sum, count) => sum + count, 0);
|
|
233
|
-
|
|
234
|
-
await
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
158
|
+
const liveColumnNames = async (table) => {
|
|
159
|
+
const result = await pgDb().execute(sql `SELECT column_name FROM information_schema.columns
|
|
160
|
+
WHERE table_schema = 'public' AND table_name = ${table}`);
|
|
161
|
+
return new Set(result.rows.map((row) => row.column_name));
|
|
162
|
+
};
|
|
163
|
+
/**
|
|
164
|
+
* A restore loads rows at an older schema version, but Drizzle names every
|
|
165
|
+
* column of the current table objects in its INSERT, so a column a later
|
|
166
|
+
* migration adds (e.g. `search_vector` in 0001) breaks the load. Add those as
|
|
167
|
+
* nullable placeholders and drop them again before migrating forward, so the
|
|
168
|
+
* migration still creates them itself and runs its backfill.
|
|
169
|
+
*/
|
|
170
|
+
const addPlaceholderColumns = async () => {
|
|
171
|
+
const db = pgDb();
|
|
172
|
+
const added = [];
|
|
173
|
+
for (const collection of [...DOCUMENT_IMPORT_ORDER, ...EDGE_IMPORT_ORDER]) {
|
|
174
|
+
const table = getTableForCollection(collection);
|
|
175
|
+
const tableName = getTableName(table);
|
|
176
|
+
const live = await liveColumnNames(tableName);
|
|
177
|
+
if (live.size === 0) {
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
for (const column of Object.values(getTableColumns(table))) {
|
|
181
|
+
if (live.has(column.name)) {
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
await db.execute(sql.raw(`ALTER TABLE "${tableName}" ADD COLUMN "${column.name}" ${column.getSQLType()}`));
|
|
185
|
+
added.push({ table: tableName, column: column.name });
|
|
186
|
+
}
|
|
243
187
|
}
|
|
244
|
-
|
|
245
|
-
|
|
188
|
+
if (added.length > 0) {
|
|
189
|
+
log.info('Added %d placeholder column(s) for the restore: %s', added.length, added.map(({ table, column }) => `${table}.${column}`).join(', '));
|
|
246
190
|
}
|
|
247
|
-
|
|
248
|
-
log.info('Arango JSONL import complete: %d rows across %d collections', total, Object.keys(imported).filter((key) => imported[key] > 0).length);
|
|
249
|
-
return { imported, total };
|
|
191
|
+
return added;
|
|
250
192
|
};
|
|
251
|
-
|
|
252
|
-
|
|
193
|
+
const dropPlaceholderColumns = async (columns) => {
|
|
194
|
+
for (const { table, column } of columns) {
|
|
195
|
+
await pgDb().execute(sql.raw(`ALTER TABLE "${table}" DROP COLUMN IF EXISTS "${column}"`));
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
const backfillFederationIdentities = async () => {
|
|
199
|
+
const { backfillLocalFederationIdentities } = await import('../../federation/identity.js');
|
|
200
|
+
await backfillLocalFederationIdentities();
|
|
201
|
+
};
|
|
202
|
+
const prepareSchemaForRestore = async (schemaVersionFromBackup) => {
|
|
203
|
+
const schemaVersion = resolveRestoreSchemaVersion(schemaVersionFromBackup);
|
|
204
|
+
log.info('Preparing postgres restore at schema %s', schemaVersion);
|
|
205
|
+
await resetAndMigrateToSchemaVersion(schemaVersion);
|
|
206
|
+
// 0006 added a unique (from_id, to_id) on post_seen; that was wrong for
|
|
207
|
+
// impressions. Drop it before import so pre-0007 backups with duplicate
|
|
208
|
+
// view rows can restore. 0007 (and later) drop it permanently.
|
|
209
|
+
await pgDb().execute(sql.raw('DROP INDEX IF EXISTS "post_seen_from_to_unique"'));
|
|
253
210
|
await truncateAllTables();
|
|
211
|
+
return addPlaceholderColumns();
|
|
212
|
+
};
|
|
213
|
+
export const importAllPostgresCollections = async (collectionsDir, schemaVersionFromBackup) => {
|
|
214
|
+
const placeholders = await prepareSchemaForRestore(schemaVersionFromBackup);
|
|
254
215
|
const imported = {};
|
|
255
216
|
for (const collection of DOCUMENT_IMPORT_ORDER) {
|
|
256
217
|
imported[collection] = await importPostgresRowCollection(collection, collectionsDir);
|
|
@@ -258,6 +219,11 @@ export const importAllPostgresCollections = async (collectionsDir) => {
|
|
|
258
219
|
for (const collection of EDGE_IMPORT_ORDER) {
|
|
259
220
|
imported[collection] = await importPostgresRowCollection(collection, collectionsDir);
|
|
260
221
|
}
|
|
222
|
+
imported.reactions = await importLegacyReactionsAsEntries(collectionsDir);
|
|
223
|
+
log.info('Postgres rows loaded; ensuring schema is at latest');
|
|
224
|
+
await dropPlaceholderColumns(placeholders);
|
|
225
|
+
await runMigrations();
|
|
226
|
+
await backfillFederationIdentities();
|
|
261
227
|
const total = sumImported(imported);
|
|
262
228
|
log.info('Postgres JSONL import complete: %d rows across %d collections', total, Object.keys(imported).filter((key) => imported[key] > 0).length);
|
|
263
229
|
return { imported, total };
|