Skip to content

Commit

Permalink
Fixed error when no rows are found, added more verbose logging
Browse files Browse the repository at this point in the history
  • Loading branch information
cmraible committed Jul 25, 2024
1 parent 374d36e commit f4981c3
Showing 1 changed file with 37 additions and 29 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,38 +10,46 @@ module.exports = createTransactionalMigration(
async function up(knex) {
// Backfill missing offer redemptions
// Select all subscriptions that have an `offer_id` but don't have a matching row in the `offer_redemptions` table
const result = await knex.raw(`
SELECT
mscs.id AS subscription_id,
mscs.offer_id,
mscs.start_date AS created_at,
m.id AS member_id
FROM
members_stripe_customers_subscriptions mscs
JOIN
members_stripe_customers msc ON mscs.customer_id = msc.customer_id
JOIN
members m ON msc.member_id = m.id
LEFT JOIN
offer_redemptions r ON r.subscription_id = mscs.id
WHERE
mscs.offer_id IS NOT NULL and r.id IS NULL;
`);
const rows = result[0];
if (rows.length > 0) {
// Generate IDs for each row
const offerRedemptions = rows.map((row) => {
return {
id: new ObjectID().toHexString(),
...row
};
});
// Bulk insert rows into the offer_redemptions table
await knex.batchInsert('offer_redemptions', offerRedemptions, 1000);
try {
logging.info('Selecting subscriptions that need offer redemptions backfilled');
const result = await knex.raw(`
SELECT
mscs.id AS subscription_id,
mscs.offer_id,
mscs.start_date AS created_at,
m.id AS member_id
FROM
members_stripe_customers_subscriptions mscs
JOIN
members_stripe_customers msc ON mscs.customer_id = msc.customer_id
JOIN
members m ON msc.member_id = m.id
LEFT JOIN
offer_redemptions r ON r.subscription_id = mscs.id
WHERE
mscs.offer_id IS NOT NULL and r.id IS NULL;
`);
const rows = result && result[0];
if (rows && rows.length > 0) {
logging.info(`Backfilling ${rows.length} offer redemptions`);
// Generate IDs for each row
const offerRedemptions = rows.map((row) => {
return {
id: new ObjectID().toHexString(),
...row
};
});
// Bulk insert rows into the offer_redemptions table
await knex.batchInsert('offer_redemptions', offerRedemptions, 1000);
} else {
logging.info('No offer redemptions to backfill');
}
} catch (error) {
logging.error(`Error backfilling offer redemptions: ${error.message}`);
}
},
async function down() {
// We don't want to un-backfill data, so do nothing here.
logging.warn('No rollback for migration');
logging.warn('No rollback for this migration to prevent data loss');
}
);

0 comments on commit f4981c3

Please sign in to comment.