
DO $$ 
DECLARE _path character varying(256) = 'patch-2024-11-02-Groups';

    BEGIN
         IF EXISTS (SELECT "Id" FROM public."Versions" WHERE "Build">=14592) THEN
		RETURN;
          END IF;
 

	IF EXISTS (SELECT "Id" FROM public."Versions" WHERE "Path"=_path) THEN
		RETURN;
	END IF;


        BEGIN
  

		DROP TABLE public."Groups";
		
		CREATE TABLE public."Groups" (
    			"Id" bigserial ,
   			 "Name" character varying(400) NOT NULL,
    			"EntityType" integer NOT NULL,
    			"CustomerId" integer NOT NULL,
    			"OwnerId" bigint NOT NULL,
    			"Color" character varying(10),
    			"ParentId" bigint,
    			"CreatedAt" timestamp without time zone DEFAULT timezone('utc', now())  NOT NULL,
    			CONSTRAINT "Groups_pkey" PRIMARY KEY ("EntityType","CustomerId", "Name")

		); 

  
		CREATE INDEX IF NOT EXISTS "IDX_Groups-Id-OwnerId-ParentId"
    		ON public."Groups" USING btree
    		("Id" ASC NULLS LAST, "OwnerId" ASC NULLS LAST, "ParentId" ASC NULLS LAST)
    		TABLESPACE pg_default;

		CREATE INDEX IF NOT EXISTS "IDX_Groups-CustomerId-EntityType"
   		 ON public."Groups" USING btree
    		("CustomerId" ASC NULLS LAST, "EntityType" ASC NULLS LAST)
    		TABLESPACE pg_default;
 			INSERT INTO public."Versions" ("Path", "Build") VALUES (_path, 0);
  
		EXCEPTION
		WHEN OTHERS THEN RAISE NOTICE '[ERR] patch-2024-11-02-Groups: %', SQLERRM;
        END;
    END;
$$
