-
-
Notifications
You must be signed in to change notification settings - Fork 168
Expand file tree
/
Copy pathreconcile-vote-counts.ts
More file actions
333 lines (295 loc) · 9.22 KB
/
reconcile-vote-counts.ts
File metadata and controls
333 lines (295 loc) · 9.22 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/**
* Vote Count Reconciliation Script
*
* This script verifies that denormalized vote counts match actual vote records
* and fixes any discrepancies. Database triggers should keep counts in sync,
* but this script provides a safety net for edge cases.
*
* Run with: npx tsx scripts/reconcile-vote-counts.ts
* Dry run: npx tsx scripts/reconcile-vote-counts.ts --dry-run
*/
import { db } from "@/server/db";
import { posts, comments, post_votes, comment_votes } from "@/server/db/schema";
import { eq, sql } from "drizzle-orm";
const isDryRun = process.argv.includes("--dry-run");
interface VoteDiscrepancy {
id: string;
type: "post" | "comment";
storedUpvotes: number;
actualUpvotes: number;
storedDownvotes: number;
actualDownvotes: number;
}
async function reconcilePostVotes(): Promise<{
checked: number;
fixed: number;
discrepancies: VoteDiscrepancy[];
}> {
console.log("Checking post vote counts...");
// Get actual vote counts from post_votes table
const actualCounts = await db
.select({
postId: post_votes.postId,
upvotes: sql<number>`COUNT(*) FILTER (WHERE ${post_votes.voteType} = 'up')::int`,
downvotes: sql<number>`COUNT(*) FILTER (WHERE ${post_votes.voteType} = 'down')::int`,
})
.from(post_votes)
.groupBy(post_votes.postId);
// Create a map for quick lookup
const actualCountsMap = new Map(
actualCounts.map((c) => [
c.postId,
{ upvotes: c.upvotes, downvotes: c.downvotes },
]),
);
// Get all posts with their stored counts
const allPosts = await db
.select({
id: posts.id,
upvotesCount: posts.upvotesCount,
downvotesCount: posts.downvotesCount,
})
.from(posts);
const discrepancies: VoteDiscrepancy[] = [];
let fixed = 0;
for (const post of allPosts) {
const actual = actualCountsMap.get(post.id) || { upvotes: 0, downvotes: 0 };
if (
post.upvotesCount !== actual.upvotes ||
post.downvotesCount !== actual.downvotes
) {
discrepancies.push({
id: post.id,
type: "post",
storedUpvotes: post.upvotesCount,
actualUpvotes: actual.upvotes,
storedDownvotes: post.downvotesCount,
actualDownvotes: actual.downvotes,
});
if (!isDryRun) {
await db
.update(posts)
.set({
upvotesCount: actual.upvotes,
downvotesCount: actual.downvotes,
})
.where(eq(posts.id, post.id));
fixed++;
}
}
}
return { checked: allPosts.length, fixed, discrepancies };
}
async function reconcileCommentVotes(): Promise<{
checked: number;
fixed: number;
discrepancies: VoteDiscrepancy[];
}> {
console.log("Checking comment vote counts...");
// Get actual vote counts from comment_votes table
const actualCounts = await db
.select({
commentId: comment_votes.commentId,
upvotes: sql<number>`COUNT(*) FILTER (WHERE ${comment_votes.voteType} = 'up')::int`,
downvotes: sql<number>`COUNT(*) FILTER (WHERE ${comment_votes.voteType} = 'down')::int`,
})
.from(comment_votes)
.groupBy(comment_votes.commentId);
// Create a map for quick lookup
const actualCountsMap = new Map(
actualCounts.map((c) => [
c.commentId,
{ upvotes: c.upvotes, downvotes: c.downvotes },
]),
);
// Get all comments with their stored counts
const allComments = await db
.select({
id: comments.id,
upvotesCount: comments.upvotesCount,
downvotesCount: comments.downvotesCount,
})
.from(comments);
const discrepancies: VoteDiscrepancy[] = [];
let fixed = 0;
for (const comment of allComments) {
const actual = actualCountsMap.get(comment.id) || {
upvotes: 0,
downvotes: 0,
};
if (
comment.upvotesCount !== actual.upvotes ||
comment.downvotesCount !== actual.downvotes
) {
discrepancies.push({
id: comment.id,
type: "comment",
storedUpvotes: comment.upvotesCount,
actualUpvotes: actual.upvotes,
storedDownvotes: comment.downvotesCount,
actualDownvotes: actual.downvotes,
});
if (!isDryRun) {
await db
.update(comments)
.set({
upvotesCount: actual.upvotes,
downvotesCount: actual.downvotes,
})
.where(eq(comments.id, comment.id));
fixed++;
}
}
}
return { checked: allComments.length, fixed, discrepancies };
}
async function reconcileCommentCounts(): Promise<{
checked: number;
fixed: number;
discrepancies: Array<{
postId: string;
storedCount: number;
actualCount: number;
}>;
}> {
console.log("Checking post comment counts...");
// Get actual comment counts (excluding soft-deleted comments)
const actualCounts = await db
.select({
postId: comments.postId,
count: sql<number>`COUNT(*)::int`,
})
.from(comments)
.where(sql`${comments.deletedAt} IS NULL`)
.groupBy(comments.postId);
// Create a map for quick lookup
const actualCountsMap = new Map(actualCounts.map((c) => [c.postId, c.count]));
// Get all posts with their stored comment counts
const allPosts = await db
.select({
id: posts.id,
commentsCount: posts.commentsCount,
})
.from(posts);
const discrepancies: Array<{
postId: string;
storedCount: number;
actualCount: number;
}> = [];
let fixed = 0;
for (const post of allPosts) {
const actualCount = actualCountsMap.get(post.id) || 0;
if (post.commentsCount !== actualCount) {
discrepancies.push({
postId: post.id,
storedCount: post.commentsCount,
actualCount,
});
if (!isDryRun) {
await db
.update(posts)
.set({ commentsCount: actualCount })
.where(eq(posts.id, post.id));
fixed++;
}
}
}
return { checked: allPosts.length, fixed, discrepancies };
}
async function main() {
console.log("=== Vote Count Reconciliation ===");
console.log(
`Mode: ${isDryRun ? "DRY RUN (no changes will be made)" : "LIVE"}\n`,
);
try {
// Reconcile post votes
const postResult = await reconcilePostVotes();
console.log(`\nPosts checked: ${postResult.checked}`);
console.log(
`Post vote discrepancies found: ${postResult.discrepancies.length}`,
);
if (postResult.discrepancies.length > 0) {
console.log("Post discrepancies:");
for (const d of postResult.discrepancies.slice(0, 10)) {
console.log(
` ${d.id}: stored(${d.storedUpvotes}/${d.storedDownvotes}) vs actual(${d.actualUpvotes}/${d.actualDownvotes})`,
);
}
if (postResult.discrepancies.length > 10) {
console.log(` ... and ${postResult.discrepancies.length - 10} more`);
}
if (!isDryRun) {
console.log(`Fixed: ${postResult.fixed}`);
}
}
// Reconcile comment votes
const commentResult = await reconcileCommentVotes();
console.log(`\nComments checked: ${commentResult.checked}`);
console.log(
`Comment vote discrepancies found: ${commentResult.discrepancies.length}`,
);
if (commentResult.discrepancies.length > 0) {
console.log("Comment discrepancies:");
for (const d of commentResult.discrepancies.slice(0, 10)) {
console.log(
` ${d.id}: stored(${d.storedUpvotes}/${d.storedDownvotes}) vs actual(${d.actualUpvotes}/${d.actualDownvotes})`,
);
}
if (commentResult.discrepancies.length > 10) {
console.log(
` ... and ${commentResult.discrepancies.length - 10} more`,
);
}
if (!isDryRun) {
console.log(`Fixed: ${commentResult.fixed}`);
}
}
// Reconcile comment counts
const commentCountResult = await reconcileCommentCounts();
console.log(
`\nPosts checked for comment counts: ${commentCountResult.checked}`,
);
console.log(
`Comment count discrepancies found: ${commentCountResult.discrepancies.length}`,
);
if (commentCountResult.discrepancies.length > 0) {
console.log("Comment count discrepancies:");
for (const d of commentCountResult.discrepancies.slice(0, 10)) {
console.log(
` ${d.postId}: stored(${d.storedCount}) vs actual(${d.actualCount})`,
);
}
if (commentCountResult.discrepancies.length > 10) {
console.log(
` ... and ${commentCountResult.discrepancies.length - 10} more`,
);
}
if (!isDryRun) {
console.log(`Fixed: ${commentCountResult.fixed}`);
}
}
// Summary
console.log("\n=== Summary ===");
const totalDiscrepancies =
postResult.discrepancies.length +
commentResult.discrepancies.length +
commentCountResult.discrepancies.length;
if (totalDiscrepancies === 0) {
console.log("All vote counts are in sync!");
} else {
console.log(`Total discrepancies: ${totalDiscrepancies}`);
if (isDryRun) {
console.log("\nRun without --dry-run to fix these discrepancies.");
} else {
const totalFixed =
postResult.fixed + commentResult.fixed + commentCountResult.fixed;
console.log(`Total fixed: ${totalFixed}`);
}
}
process.exit(0);
} catch (error) {
console.error("Error during reconciliation:", error);
process.exit(1);
}
}
main();