calc migration
This commit is contained in:
@@ -0,0 +1,44 @@
|
|||||||
|
import { Migration } from '@mikro-orm/migrations';
|
||||||
|
|
||||||
|
export class Migration20260218114512_orderCalc extends Migration {
|
||||||
|
|
||||||
|
override async up(): Promise<void> {
|
||||||
|
this.addSql(`
|
||||||
|
CREATE OR REPLACE FUNCTION update_order_paid_amount()
|
||||||
|
RETURNS TRIGGER AS $$
|
||||||
|
BEGIN
|
||||||
|
UPDATE orders o
|
||||||
|
SET paid_amount = (
|
||||||
|
SELECT COALESCE(SUM(p.amount), 0)
|
||||||
|
FROM payments p
|
||||||
|
WHERE p.order_id = COALESCE(NEW.order_id, OLD.order_id)
|
||||||
|
AND p.status = 'Paid'
|
||||||
|
)
|
||||||
|
WHERE o.id = COALESCE(NEW.order_id, OLD.order_id);
|
||||||
|
|
||||||
|
RETURN NULL;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
`);
|
||||||
|
|
||||||
|
this.addSql(`
|
||||||
|
CREATE TRIGGER trg_update_order_paid_amount
|
||||||
|
AFTER INSERT OR UPDATE OR DELETE
|
||||||
|
ON payments
|
||||||
|
FOR EACH ROW
|
||||||
|
EXECUTE FUNCTION update_order_paid_amount();
|
||||||
|
`);
|
||||||
|
|
||||||
|
this.addSql(`
|
||||||
|
CREATE INDEX idx_payments_order_status
|
||||||
|
ON payments(order_id, status);
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
override async down(): Promise<void> {
|
||||||
|
this.addSql(`DROP TRIGGER IF EXISTS trg_update_order_paid_amount ON payments;`);
|
||||||
|
this.addSql(`DROP FUNCTION IF EXISTS update_order_paid_amount;`);
|
||||||
|
this.addSql(`DROP INDEX IF EXISTS idx_payments_order_status;`);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -25,6 +25,7 @@
|
|||||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||||
"test:e2e": "jest --config ./test/jest-e2e.json",
|
"test:e2e": "jest --config ./test/jest-e2e.json",
|
||||||
"migration:create": "npx mikro-orm migration:create --config ./src/config/mikro-orm.config.dev.ts",
|
"migration:create": "npx mikro-orm migration:create --config ./src/config/mikro-orm.config.dev.ts",
|
||||||
|
"migration:blank": "npx mikro-orm migration:create --blank --config ./src/config/mikro-orm.config.dev.ts",
|
||||||
"migration:up": "npx mikro-orm migration:up --config ./src/config/mikro-orm.config.dev.ts",
|
"migration:up": "npx mikro-orm migration:up --config ./src/config/mikro-orm.config.dev.ts",
|
||||||
"migration:down": "npx mikro-orm migration:down --config ./src/config/mikro-orm.config.dev.ts",
|
"migration:down": "npx mikro-orm migration:down --config ./src/config/mikro-orm.config.dev.ts",
|
||||||
"migration:list": "npx mikro-orm migration:list --config ./src/config/mikro-orm.config.dev.ts",
|
"migration:list": "npx mikro-orm migration:list --config ./src/config/mikro-orm.config.dev.ts",
|
||||||
|
|||||||
Reference in New Issue
Block a user