BEGIN;

ALTER TABLE project_flock_kandangs
    DROP COLUMN IF EXISTS period;

ALTER TABLE project_flocks
    ADD COLUMN IF NOT EXISTS period INT NOT NULL DEFAULT 0;

CREATE UNIQUE INDEX IF NOT EXISTS project_flocks_base_period_unique
    ON project_flocks (
        LOWER(TRIM(regexp_replace(flock_name, '\\s+\\d+(\\s+\\d+)*$', '', 'g'))),
        period
    )
    WHERE deleted_at IS NULL;

COMMIT;
