\set ON_ERROR_STOP on

-- Remove artifacts of the previous unfuccessful runs (if any).
DO $$
BEGIN
  DROP TABLE IF EXISTS test_microsharding0001.tbl1;
  SET search_path TO test_microsharding;
  PERFORM microsharding_debug_fdw_drop('test_microsharding_fdw');
  PERFORM microsharding_ensure_absent(0, 1000);
  SET search_path TO public;
  DROP SCHEMA test_microsharding CASCADE;
EXCEPTION
  WHEN OTHERS THEN -- skip
END
$$;

BEGIN;

CREATE EXTENSION IF NOT EXISTS postgres_fdw;
CREATE EXTENSION IF NOT EXISTS dblink;

CREATE SCHEMA test_microsharding;
\set ON_ERROR_STOP on

\setenv PG_MICROSHARDING_SCHEMA_NAME_FMT 'test_microsharding%04d'
\ir ../pg-microsharding-up.sql

CREATE FUNCTION expect(sql text, exp text, msg text) RETURNS void LANGUAGE plpgsql AS $$
DECLARE
  got text;
BEGIN
  EXECUTE sql INTO got;
  IF got IS DISTINCT FROM exp THEN
    RAISE EXCEPTION 'Expectation failed (%): expected %, got %', msg, exp, got;
  END IF;
END;
$$;

CREATE FUNCTION expect_raise(sql text, exp text, msg text) RETURNS void LANGUAGE plpgsql AS $$
DECLARE
  got text;
BEGIN
  BEGIN
    EXECUTE sql INTO got;
    RAISE EXCEPTION 'Expected to raise an exception (%)', msg;
  EXCEPTION
    WHEN OTHERS THEN
      GET STACKED DIAGNOSTICS got = MESSAGE_TEXT;
      IF got NOT LIKE exp THEN
        RAISE EXCEPTION 'Expected exception matching "%", got "%"', exp, got;
      END IF;
  END;
END;
$$;
