CREATE OR REPLACE FUNCTION microsharding_fmt_(
  fmt text,
  arg integer
) RETURNS text
LANGUAGE plpgsql
SET search_path FROM CURRENT
AS $$
DECLARE
  m text[];
  prefix text;
  width text;
  suffix text;
BEGIN
  m := regexp_match(fmt, '^([^%]*)%(0[0-9]+)?d([^%]*)$');
  IF m IS NULL THEN
    RAISE EXCEPTION 'Invalid format specifier: "%" (valid examples: "sh%%04d", "some_%%d", "some%%04d_my")', fmt;
  END IF;
  prefix := m[1];
  width := m[2];
  suffix := m[3];
  IF COALESCE(width, '') = '' THEN
    RETURN prefix || arg || suffix;
  ELSE
    RETURN prefix || lpad(arg::text, width::integer, '0') || suffix;
  END IF;
END;
$$;

COMMENT ON FUNCTION microsharding_fmt_(text, integer)
  IS 'A poor man''s sprintf() implementation limited to only one integer substitution.';
