CREATE OR REPLACE FUNCTION microsharding_schema_name_create_tmp_(
  fmt text
) RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
  m text[];
  prefix text;
  width text;
  suffix text;
BEGIN
  fmt := COALESCE(trim(fmt), '');
  IF fmt <> '' OR NOT EXISTS (
    SELECT 1 FROM pg_proc
    WHERE
      proname = 'microsharding_schema_name_'
      AND pronamespace = current_schema()::regnamespace
  ) THEN
    fmt := CASE WHEN fmt = '' THEN 'sh%04d' ELSE fmt END;
    EXECUTE format(
      $format$
      CREATE OR REPLACE FUNCTION microsharding_schema_name_(shard integer) RETURNS text
        LANGUAGE sql
        SET search_path FROM CURRENT
        AS $func$SELECT microsharding_fmt_(%L, $1)$func$
      $format$,
      fmt
    );
  END IF;
END;
$$;

\set PG_MICROSHARDING_SCHEMA_NAME_FMT `echo "$PG_MICROSHARDING_SCHEMA_NAME_FMT"`
SELECT microsharding_schema_name_create_tmp_(:'PG_MICROSHARDING_SCHEMA_NAME_FMT');

DROP FUNCTION microsharding_schema_name_create_tmp_(text);

COMMENT ON FUNCTION microsharding_schema_name_(integer)
  IS 'Builds the shard schema name from shard number.';
