-- groups

CREATE TABLE
	groups(
		"id" SERIAL,
		"name" VARCHAR(63) NOT NULL,
		"label" VARCHAR(63) NOT NULL,
		UNIQUE ("name"),
		UNIQUE ("id")
	)
;

INSERT INTO
	groups("name","label")
	SELECT
		DISTINCT group_name,
		''
	FROM
		member_groups
;

UPDATE
	groups
SET
	label = name
;


-- invitations

CREATE TABLE
	invitations(
		"id" SERIAL,
		"key" VARCHAR(63) NOT NULL,
		"expiry" INTEGER,
		"name_changeable" BOOLEAN NOT NULL,
		"name_value" VARCHAR(63) NOT NULL,
		"label_changeable" BOOLEAN NOT NULL,
		"label_value" VARCHAR(63) NOT NULL,
		"email_address_changeable" BOOLEAN NOT NULL,
		"email_address_value" VARCHAR(63),
		"groups_changeable" BOOLEAN NOT NULL,
		UNIQUE ("key"),
		UNIQUE ("id")
	)
;


-- invitation_groups

CREATE TABLE
	invitation_groups(
		"invitation_id" INTEGER NOT NULL,
		"group_id" INTEGER NOT NULL,
		"_dummy" BOOLEAN,
		FOREIGN KEY ("invitation_id") REFERENCES "invitations"("id"),
		FOREIGN KEY ("group_id") REFERENCES "groups"("id"),
		UNIQUE ("invitation_id","group_id")
	)
;


-- name_indices

DROP TABLE name_indices;


-- members

ALTER TABLE members DROP CONSTRAINT members_name_real_value_name_real_index_key;
ALTER TABLE members ADD COLUMN "label" VARCHAR(63);
UPDATE members SET label = name;
ALTER TABLE members ALTER COLUMN "label" SET NOT NULL;
ALTER TABLE members RENAME COLUMN "name_real_value" TO "name";
ALTER TABLE members RENAME COLUMN "email_address_private" TO "email_address";
ALTER TABLE members DROP COLUMN "membership_number";
ALTER TABLE members DROP COLUMN "name_real_index";
ALTER TABLE members DROP COLUMN "registered";
ALTER TABLE members DROP COLUMN "email_use_veiled_address";
ALTER TABLE members DROP COLUMN "email_use_nominal_address";
ALTER TABLE members DROP COLUMN "email_redirect_to_private_address";
ALTER TABLE members DROP COLUMN "email_allow_sending";
ALTER TABLE members ADD CONSTRAINT "members_name_key" UNIQUE ("name");



-- member_groups

ALTER TABLE member_groups DROP CONSTRAINT member_groups_member_id_group_name_key;
ALTER TABLE member_groups ADD COLUMN group_id INTEGER;
UPDATE member_groups AS x SET group_id = (SELECT y.id FROM groups AS y WHERE y.name = x.group_name);
ALTER TABLE member_groups ALTER COLUMN group_id SET NOT NULL;
ALTER TABLE member_groups ADD CONSTRAINT "member_groups_group_id_fkey" FOREIGN KEY ("group_id") REFERENCES groups(id);
ALTER TABLE member_groups ADD CONSTRAINT "member_groups_member_id_group_id_key" UNIQUE ("member_id","group_id");
ALTER TABLE member_groups DROP COLUMN group_name;


-- revision

UPDATE _meta SET revision = 'r7';
