zed/crates/collab/migrations/20240730014107_add_billing_customer.sql
Marshall Bowers 28c14cdee4
collab: Add separate billing_customers table (#15457)
This PR adds a new `billing_customers` table to hold the billing
customers.

Previously we were storing both the `stripe_customer_id` and
`stripe_subscription_id` in the `billable_subscriptions` table. However,
this creates problems when we need to correlate subscription events back
to the subscription record, as we don't know the user that the Stripe
event corresponds to.

By moving the `stripe_customer_id` to a separate table we can create the
Stripe customer earlier in the flow—before we create the Stripe Checkout
session—and associate that customer with a user. This way when we
receive events down the line we can use the Stripe customer ID to
correlate it back to the user.

We're doing some destructive actions to the `billing_subscriptions`
table, but this is fine, as we haven't started using them yet.

Release Notes:

- N/A
2024-07-29 22:48:21 -04:00

18 lines
1 KiB
SQL

CREATE TABLE IF NOT EXISTS billing_customers (
id SERIAL PRIMARY KEY,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT now(),
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
stripe_customer_id TEXT NOT NULL
);
CREATE UNIQUE INDEX "uix_billing_customers_on_user_id" ON billing_customers (user_id);
CREATE UNIQUE INDEX "uix_billing_customers_on_stripe_customer_id" ON billing_customers (stripe_customer_id);
-- Make `billing_subscriptions` reference `billing_customers` instead of having its
-- own `user_id` and `stripe_customer_id`.
DROP INDEX IF EXISTS "ix_billing_subscriptions_on_user_id";
DROP INDEX IF EXISTS "ix_billing_subscriptions_on_stripe_customer_id";
ALTER TABLE billing_subscriptions DROP COLUMN user_id;
ALTER TABLE billing_subscriptions DROP COLUMN stripe_customer_id;
ALTER TABLE billing_subscriptions ADD COLUMN billing_customer_id INTEGER NOT NULL REFERENCES billing_customers (id) ON DELETE CASCADE;
CREATE INDEX "ix_billing_subscriptions_on_billing_customer_id" ON billing_subscriptions (billing_customer_id);