-- Renumber existing low order numbers to start at 1000, then seed the sequence.
DO $$
DECLARE
  seq_name text;
  seed bigint;
  r record;
  i integer := 0;
BEGIN
  -- Move current numbers out of the way to avoid unique collisions
  UPDATE "Order" SET number = number + 1000000 WHERE number < 1000;

  -- Assign contiguous numbers from 1000 for any that were shifted
  FOR r IN
    SELECT id FROM "Order" WHERE number >= 1000000 ORDER BY number ASC
  LOOP
    UPDATE "Order" SET number = 1000 + i WHERE id = r.id;
    i := i + 1;
  END LOOP;

  seq_name := pg_get_serial_sequence('"Order"', 'number');
  IF seq_name IS NULL THEN
    RAISE EXCEPTION 'Order.number sequence not found';
  END IF;

  SELECT GREATEST(999, COALESCE(MAX(number), 999)) INTO seed FROM "Order";
  PERFORM setval(seq_name, seed, true);
END $$;
