-- create a tablespace we can use
CREATE TABLESPACE testspace LOCATION '@testtablespace@';

-- try setting and resetting some properties for the new tablespace
ALTER TABLESPACE testspace SET (random_page_cost = 1.0);
ALTER TABLESPACE testspace SET (some_nonexistent_parameter = true);  -- fail
ALTER TABLESPACE testspace RESET (random_page_cost = 2.0); -- fail
ALTER TABLESPACE testspace RESET (random_page_cost, seq_page_cost); -- ok

-- create a schema we can use
CREATE SCHEMA testschema;

-- try a table
CREATE TABLE testschema.foo (i int) TABLESPACE testspace;
SELECT relname, spcname FROM pg_catalog.pg_tablespace t, pg_catalog.pg_class c
    where c.reltablespace = t.oid AND c.relname = 'foo';

INSERT INTO testschema.foo VALUES(1);
INSERT INTO testschema.foo VALUES(2);

-- tables from dynamic sources
CREATE TABLE testschema.asselect TABLESPACE testspace AS SELECT 1;
SELECT relname, spcname FROM pg_catalog.pg_tablespace t, pg_catalog.pg_class c
    where c.reltablespace = t.oid AND c.relname = 'asselect';

PREPARE selectsource(int) AS SELECT $1;
CREATE TABLE testschema.asexecute TABLESPACE testspace
    AS EXECUTE selectsource(2);
SELECT relname, spcname FROM pg_catalog.pg_tablespace t, pg_catalog.pg_class c
    where c.reltablespace = t.oid AND c.relname = 'asexecute';

-- index
CREATE INDEX foo_idx on testschema.foo(i) TABLESPACE testspace;
SELECT relname, spcname FROM pg_catalog.pg_tablespace t, pg_catalog.pg_class c
    where c.reltablespace = t.oid AND c.relname = 'foo_idx';

-- let's try moving a table from one place to another
CREATE TABLE testschema.atable AS VALUES (1), (2);
CREATE UNIQUE INDEX anindex ON testschema.atable(column1);

ALTER TABLE testschema.atable SET TABLESPACE testspace;
ALTER INDEX testschema.anindex SET TABLESPACE testspace;

INSERT INTO testschema.atable VALUES(3);	-- ok
INSERT INTO testschema.atable VALUES(1);	-- fail (checks index)
SELECT COUNT(*) FROM testschema.atable;		-- checks heap

-- Will fail with bad path
CREATE TABLESPACE badspace LOCATION '/no/such/location';

-- No such tablespace
CREATE TABLE bar (i int) TABLESPACE nosuchspace;

-- Fail, not empty
DROP TABLESPACE testspace;

DROP SCHEMA testschema CASCADE;

-- Should succeed
DROP TABLESPACE testspace;
