|
| 1 | +import { sql } from '@silverhand/slonik'; |
| 2 | + |
| 3 | +import type { AlterationScript } from '../lib/types/alteration.js'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Remove foreign key constraint from daily_active_users table to allow |
| 7 | + * historical billing data to persist even after tenant deletion. |
| 8 | + * This supports the MAU-based billing system requirements. |
| 9 | + * |
| 10 | + * Index optimizations: |
| 11 | + * 1. Removes redundant (tenant_id, id) index (id is already primary key) |
| 12 | + * 2. Adds optimized index (tenant_id, date, user_id) for aggregation queries |
| 13 | + * 3. Replaces problematic partial index with BRIN index |
| 14 | + */ |
| 15 | + |
| 16 | +const alteration: AlterationScript = { |
| 17 | + up: async (pool) => { |
| 18 | + // Drop the existing foreign key constraint |
| 19 | + await pool.query(sql` |
| 20 | + alter table daily_active_users |
| 21 | + drop constraint if exists daily_active_users_tenant_id_fkey |
| 22 | + `); |
| 23 | + |
| 24 | + // Remove the redundant (tenant_id, id) index since id is already primary key |
| 25 | + await pool.query(sql` |
| 26 | + drop index if exists daily_active_users__id |
| 27 | + `); |
| 28 | + |
| 29 | + // Add optimized index for aggregation queries with better write performance |
| 30 | + await pool.query(sql` |
| 31 | + create index daily_active_users__tenant_date_user |
| 32 | + on daily_active_users (tenant_id, date, user_id) |
| 33 | + `); |
| 34 | + |
| 35 | + // Add BRIN index for time-series date range queries |
| 36 | + // Optimized for sequential data insertion and range scans (date >= ?) |
| 37 | + await pool.query(sql` |
| 38 | + create index daily_active_users__date_brin |
| 39 | + on daily_active_users using brin (date) |
| 40 | + `); |
| 41 | + }, |
| 42 | + |
| 43 | + down: async (pool) => { |
| 44 | + // Drop the new indexes we created |
| 45 | + await pool.query(sql` |
| 46 | + drop index if exists daily_active_users__date_brin |
| 47 | + `); |
| 48 | + |
| 49 | + await pool.query(sql` |
| 50 | + drop index if exists daily_active_users__tenant_date_user |
| 51 | + `); |
| 52 | + |
| 53 | + // Recreate the original redundant index |
| 54 | + await pool.query(sql` |
| 55 | + create index daily_active_users__id |
| 56 | + on daily_active_users (tenant_id, id) |
| 57 | + `); |
| 58 | + |
| 59 | + // Recreate the foreign key constraint |
| 60 | + await pool.query(sql` |
| 61 | + alter table daily_active_users |
| 62 | + add constraint daily_active_users_tenant_id_fkey |
| 63 | + foreign key (tenant_id) references tenants(id) |
| 64 | + on update cascade on delete cascade |
| 65 | + `); |
| 66 | + }, |
| 67 | +}; |
| 68 | + |
| 69 | +export default alteration; |
0 commit comments