Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

2.2 KB
Raw Blame
-- Fix a read-then-write race in get_next_sequence: two concurrent callers both
-- read the same "next", both wrote the same absolute value, and both returned
-- the same sequence number. The atomic UPDATE ... RETURNING takes the row lock
-- first, so a concurrent caller blocks and then reads the committed value.
CREATE OR REPLACE FUNCTION get_next_sequence(
  sequence_name text,
  company_id text
)
RETURNS text
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
  v_prefix text;
  v_suffix text;
  v_next_value integer;
  v_size integer;
  v_next_sequence text;
  v_derived_prefix text;
  v_derived_suffix text;
BEGIN
  IF session_user = 'authenticator' THEN
    IF NOT (has_role('employee', company_id) OR has_valid_api_key_for_company(company_id)) THEN
      RAISE EXCEPTION 'Insufficient permissions';
    END IF;
  END IF;

  UPDATE sequence
  SET next = next + step,
      "updatedBy" = 'system'
  WHERE "table" = sequence_name
  AND "companyId" = company_id
  RETURNING next, prefix, suffix, size
  INTO v_next_value, v_prefix, v_suffix, v_size;

  IF NOT FOUND THEN
    RAISE EXCEPTION 'Sequence not found for table % and company %', sequence_name, company_id;
  END IF;

  -- Format sequence number
  v_next_sequence := lpad(v_next_value::text, COALESCE(v_size, 4), '0');

  -- Interpolate date variables in prefix/suffix
  v_derived_prefix := COALESCE(v_prefix, '');
  v_derived_prefix := replace(v_derived_prefix, '%{yyyy}', to_char(current_date, 'YYYY'));
  v_derived_prefix := replace(v_derived_prefix, '%{yy}', to_char(current_date, 'YY'));
  v_derived_prefix := replace(v_derived_prefix, '%{mm}', to_char(current_date, 'MM'));
  v_derived_prefix := replace(v_derived_prefix, '%{dd}', to_char(current_date, 'DD'));

  v_derived_suffix := COALESCE(v_suffix, '');
  v_derived_suffix := replace(v_derived_suffix, '%{yyyy}', to_char(current_date, 'YYYY'));
  v_derived_suffix := replace(v_derived_suffix, '%{yy}', to_char(current_date, 'YY'));
  v_derived_suffix := replace(v_derived_suffix, '%{mm}', to_char(current_date, 'MM'));
  v_derived_suffix := replace(v_derived_suffix, '%{dd}', to_char(current_date, 'DD'));

  RETURN v_derived_prefix || v_next_sequence || v_derived_suffix;
END;
$$;