Skip to content

Commit 77b3c29

Browse files
claudepieterbeulque
authored andcommitted
Add data backfill for discount_applied_at
Populates discount_applied_at for existing subscriptions by finding the first order that used each subscription's current discount.
1 parent 07b1a56 commit 77b3c29

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

server/migrations/versions/2026-01-06-1200_add_discount_applied_at_to_subscriptions.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,28 @@ def upgrade() -> None:
2424
sa.Column("discount_applied_at", sa.TIMESTAMP(timezone=True), nullable=True),
2525
)
2626

27+
# Backfill discount_applied_at for existing subscriptions with discounts
28+
# by finding the first order that used the discount
29+
op.execute(
30+
"""
31+
UPDATE subscriptions s
32+
SET discount_applied_at = o.created_at
33+
FROM (
34+
SELECT DISTINCT ON (o.subscription_id, o.discount_id)
35+
o.subscription_id,
36+
o.discount_id,
37+
o.created_at
38+
FROM orders o
39+
WHERE o.subscription_id IS NOT NULL
40+
AND o.discount_id IS NOT NULL
41+
AND o.deleted_at IS NULL
42+
ORDER BY o.subscription_id, o.discount_id, o.created_at ASC
43+
) o
44+
WHERE s.id = o.subscription_id
45+
AND s.discount_id = o.discount_id
46+
"""
47+
)
48+
2749

2850
def downgrade() -> None:
2951
op.drop_column("subscriptions", "discount_applied_at")

0 commit comments

Comments
 (0)