Files
rmser/migrations/20250127000000_add_order_to_draft_invoice_items.sql

20 lines
1.0 KiB
SQL
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

-- Добавляем колонку order в таблицу draft_invoice_items
-- Миграция для добавления поля сортировки позиций в черновике накладной
-- Добавляем колонку order со значением по умолчанию 0
ALTER TABLE draft_invoice_items ADD COLUMN "order" INTEGER NOT NULL DEFAULT 0;
-- Инициализируем значения order для существующих записей
-- Сортируем по created_at для сохранения текущего порядка
WITH ordered_items AS (
SELECT id, ROW_NUMBER() OVER (PARTITION BY draft_id ORDER BY created_at ASC) as row_num
FROM draft_invoice_items
)
UPDATE draft_invoice_items
SET "order" = ordered_items.row_num
FROM ordered_items
WHERE draft_invoice_items.id = ordered_items.id;
-- Создаем индекс для оптимизации сортировки
CREATE INDEX idx_draft_items_order ON draft_invoice_items(draft_id, "order");