|
| 1 | +DO $$ |
| 2 | +DECLARE |
| 3 | + chunk_size INTEGER := 1000; |
| 4 | + start_id INTEGER := 1; -- Starting ID |
| 5 | + end_id INTEGER; -- Will be set dynamically |
| 6 | + current_id INTEGER; |
| 7 | + sleep_interval FLOAT := 1; -- Sleep duration in seconds |
| 8 | + missing_records_exist BOOLEAN; |
| 9 | +BEGIN |
| 10 | + -- Get the maximum ID from the Booking table |
| 11 | + SELECT COALESCE(MAX(id), 0) INTO end_id FROM "Booking"; |
| 12 | + |
| 13 | + FOR current_id IN SELECT * FROM generate_series(start_id, end_id, chunk_size) |
| 14 | + LOOP |
| 15 | + -- Check if there are any Booking records that don't exist in BookingDenormalized |
| 16 | + SELECT EXISTS ( |
| 17 | + SELECT 1 |
| 18 | + FROM "Booking" b |
| 19 | + LEFT JOIN "BookingDenormalized" bd ON b.id = bd.id |
| 20 | + WHERE b.id BETWEEN current_id AND current_id + chunk_size - 1 |
| 21 | + AND bd.id IS NULL |
| 22 | + ) INTO missing_records_exist; |
| 23 | + |
| 24 | + -- Only proceed with INSERT if there are actually missing records |
| 25 | + IF missing_records_exist THEN |
| 26 | + INSERT INTO "BookingDenormalized" ( |
| 27 | + id, uid, "eventTypeId", title, description, "startTime", "endTime", |
| 28 | + "createdAt", "updatedAt", location, paid, status, rescheduled, |
| 29 | + "userId", "teamId", "eventLength", "eventParentId", "userEmail", |
| 30 | + "userUsername", "ratingFeedback", rating, "noShowHost", |
| 31 | + "isTeamBooking" |
| 32 | + ) |
| 33 | + SELECT |
| 34 | + b.id, b.uid, b."eventTypeId", b.title, b.description, |
| 35 | + b."startTime", b."endTime", b."createdAt", b."updatedAt", |
| 36 | + b.location, b.paid, b.status, b.rescheduled, b."userId", |
| 37 | + et."teamId", et.length as "eventLength", |
| 38 | + et."parentId" as "eventParentId", u.email as "userEmail", |
| 39 | + u.username as "userUsername", b."ratingFeedback", b.rating, |
| 40 | + b."noShowHost", |
| 41 | + COALESCE(et."teamId", 0) > 0 as "isTeamBooking" |
| 42 | + FROM "Booking" b |
| 43 | + LEFT JOIN "EventType" et ON b."eventTypeId" = et.id |
| 44 | + LEFT JOIN "users" u ON u.id = b."userId" |
| 45 | + WHERE b.id BETWEEN current_id AND current_id + chunk_size - 1 |
| 46 | + AND NOT EXISTS ( |
| 47 | + SELECT 1 FROM "BookingDenormalized" bd WHERE bd.id = b.id |
| 48 | + ) |
| 49 | + ON CONFLICT (id) DO NOTHING; |
| 50 | + END IF; |
| 51 | + |
| 52 | + PERFORM pg_sleep(sleep_interval); -- Using the declared sleep_interval |
| 53 | + END LOOP; |
| 54 | +END $$; |
0 commit comments