PSA/ee/server/migrations/citus/20250805000013_distribute_time_billing_tables.cjs
Hermes 284313f908
Some checks are pending
Bidi Control Character Guard / bidi-control-guard (push) Waiting to run
Circular Dependency Check / Check for new circular dependencies (push) Waiting to run
Citus Migration Smoke / Combined migrations on single-node Citus (push) Waiting to run
E2E Fresh Install Tests / fresh-install-e2e (push) Waiting to run
ext-v2 guardrails / Run ext-v2 guard and ESLint (push) Waiting to run
Integration Tests / Check for relevant changes (push) Waiting to run
Integration Tests / ${{ (github.event_name == 'schedule' || github.event.inputs.suite == 'full') && 'Full integration suite' || 'Tier-1 integration subset' }} (push) Blocked by required conditions
Mobile checks / Mobile lint + typecheck (push) Waiting to run
Mobile checks / Mobile unit tests (push) Waiting to run
Mobile checks / Mobile dependency audit (report) (push) Waiting to run
Mobile checks / Mobile reproducibility checks (push) Waiting to run
Secrets guard (env backups) / Ensure no tracked env backup files (push) Waiting to run
Temporal Readiness / fast-readiness (push) Waiting to run
Temporal Readiness / docker-parity (push) Waiting to run
TypeScript Type Check / Nx affected typecheck (push) Waiting to run
Unit Tests / Skipped-test budget (push) Waiting to run
Unit Tests / Nx affected unit tests (push) Waiting to run
Unit Tests / Server unit coverage (informational) (push) Waiting to run
Validate Tenant Management Schema / Check for relevant changes (push) Waiting to run
Validate Tenant Management Schema / Validate Tenant Management Schema (push) Blocked by required conditions
EE Workflows Build Guard / ee-workflows-build-guard (push) Waiting to run
Initial import of AlgaPSA codebase from PSA server
Excluded: .git, node_modules, secrets/, compose.env, assemblyscript tgz

Source: /opt/alga-psa on psa.joliet.tech
2026-06-22 16:12:17 -05:00

171 lines
5.1 KiB
JavaScript

/**
* Distribute time tracking and billing related tables
*/
const {
dropAndCaptureForeignKeys,
recreateForeignKeys
} = require('./utils/foreign_key_manager.cjs');
exports.config = { transaction: false };
exports.up = async function(knex) {
// Check if Citus is enabled
const citusEnabled = await knex.raw(`
SELECT EXISTS (
SELECT 1 FROM pg_extension WHERE extname = 'citus'
) as enabled
`);
if (!citusEnabled.rows[0].enabled) {
console.log('Citus not enabled, skipping table distribution');
return;
}
console.log('Distributing time tracking and billing tables...');
const tables = [
'billing_plans',
// 'bucket_plans', // Table was dropped in migration 20250403170555
'bucket_usage',
'time_sheets',
'time_periods',
'tenant_time_period_settings'
];
for (const table of tables) {
try {
console.log(`\nProcessing ${table}...`);
// Check if already distributed
const isDistributed = await knex.raw(`
SELECT EXISTS (
SELECT 1 FROM pg_dist_partition
WHERE logicalrelid = '${table}'::regclass
) as distributed
`);
if (isDistributed.rows[0].distributed) {
console.log(` ${table} already distributed`);
continue;
}
// Step 1: Capture and drop foreign key constraints
console.log(` Capturing and dropping foreign key constraints for ${table}...`);
const capturedFKs = await dropAndCaptureForeignKeys(knex, table);
// Step 2: Drop unique constraints with CASCADE
console.log(` Dropping unique constraints for ${table}...`);
const uniqueConstraints = await knex.raw(`
SELECT conname
FROM pg_constraint
WHERE conrelid = '${table}'::regclass
AND contype = 'u'
`);
for (const constraint of uniqueConstraints.rows) {
try {
await knex.raw(`ALTER TABLE ${table} DROP CONSTRAINT ${constraint.conname} CASCADE`);
console.log(` ✓ Dropped constraint: ${constraint.conname} with CASCADE`);
} catch (e) {
console.log(` - Could not drop ${constraint.conname}: ${e.message}`);
}
}
// Step 2b: Drop check constraints
console.log(` Dropping check constraints for ${table}...`);
const checkConstraints = await knex.raw(`
SELECT conname
FROM pg_constraint
WHERE conrelid = '${table}'::regclass
AND contype = 'c'
AND conname NOT LIKE '%_not_null'
`);
for (const constraint of checkConstraints.rows) {
try {
await knex.raw(`ALTER TABLE ${table} DROP CONSTRAINT ${constraint.conname} CASCADE`);
console.log(` ✓ Dropped check constraint: ${constraint.conname}`);
} catch (e) {
console.log(` - Could not drop check ${constraint.conname}: ${e.message}`);
}
}
// Step 3: Drop triggers if any
console.log(` Dropping triggers for ${table}...`);
const triggers = await knex.raw(`
SELECT tgname
FROM pg_trigger
WHERE tgrelid = '${table}'::regclass
AND tgisinternal = false
`);
for (const trigger of triggers.rows) {
try {
await knex.raw(`DROP TRIGGER IF EXISTS ${trigger.tgname} ON ${table}`);
console.log(` ✓ Dropped trigger: ${trigger.tgname}`);
} catch (e) {
console.log(` - Could not drop trigger ${trigger.tgname}: ${e.message}`);
}
}
// Step 4: Distribute the table
console.log(` Distributing ${table}...`);
await knex.raw(`SELECT create_distributed_table('${table}', 'tenant', colocate_with => 'tenants')`);
console.log(` ✓ Distributed ${table}`);
// Recreate foreign keys for this table
console.log(` Recreating foreign keys for ${table}...`);
await recreateForeignKeys(knex, table, capturedFKs);
} catch (error) {
console.error(` ✗ Failed to distribute ${table}: ${error.message}`);
throw error;
}
}
console.log('\n✓ All tables distributed successfully');
};
exports.down = async function(knex) {
const citusEnabled = await knex.raw(`
SELECT EXISTS (
SELECT 1 FROM pg_extension WHERE extname = 'citus'
) as enabled
`);
if (!citusEnabled.rows[0].enabled) {
return;
}
console.log('Undistributing time tracking and billing tables...');
const tables = [
'tenant_time_period_settings',
'time_periods',
'time_sheets',
'bucket_usage',
// 'bucket_plans', // Removed
'billing_plans'
];
for (const table of tables) {
try {
const isDistributed = await knex.raw(`
SELECT EXISTS (
SELECT 1 FROM pg_dist_partition
WHERE logicalrelid = '${table}'::regclass
) as distributed
`);
if (isDistributed.rows[0].distributed) {
await knex.raw(`SELECT undistribute_table('${table}')`);
console.log(` ✓ Undistributed ${table}`);
}
} catch (error) {
console.error(` ✗ Failed to undistribute ${table}: ${error.message}`);
}
}
};