DO $$ 
    BEGIN
          IF EXISTS (SELECT "Id" FROM public."Versions" WHERE "Build">=1765) THEN
		RETURN;
          END IF;
        BEGIN
        CREATE TABLE public."EmailMessages"
(
    "Id" bigserial, 
    "Subject" character varying(4000) NULL, 
    "From" character varying(1024) NULL, 
    "To" text NULL, 
    "Cc" text NULL, 
    "Bcc" text NULL, 
    "Body" text NULL,
    "HtmlBody" text NULL,
    "FolderId" BIGINT NOT NULL,
    "ExternalId" character varying(64) NOT NULL, 
    "WasRead" boolean DEFAULT false,
    "WasSent" boolean DEFAULT false,
    "WasReplied" boolean DEFAULT false,
    "HasAttachments" boolean DEFAULT false,
    "IsDeleted" boolean DEFAULT false,
    "OwnerId" BIGINT NOT NULL,
    "ParentId" BIGINT NULL,
    "HasChildren" boolean DEFAULT false,
    "Size" BIGINT NOT NULL,
    "Date" timestamp NULL,
    "Timestamp" timestamp without time zone DEFAULT timezone('utc', now())  NOT NULL, 
    "Important" boolean DEFAULT false,
    CONSTRAINT "PK_EmailMessages" PRIMARY KEY("ExternalId", "FolderId")
);
CREATE INDEX "IDX_EmailMessages_ParentId"
    ON public."EmailMessages" USING btree
    ("ParentId" ASC NULLS LAST,"Id" ASC NULLS LAST)
    TABLESPACE pg_default; 

CREATE INDEX "IDX_EmailMessages_FolderId"
    ON public."EmailMessages" USING btree
    ("FolderId" ASC NULLS LAST,"Size" ASC NULLS LAST)
    TABLESPACE pg_default;  

CREATE INDEX "IDX_EmailMessages_Id"
    ON public."EmailMessages" USING btree
    ("Id" ASC NULLS LAST)
    TABLESPACE pg_default;  

CREATE INDEX "IDX_EmailMessages_WasReplied"
    ON public."EmailMessages" USING btree
    ("WasReplied" ASC NULLS LAST)
    TABLESPACE pg_default;  

CREATE INDEX "IDX_EmailMessages_OwnerId"
    ON public."EmailMessages" USING btree
    ("OwnerId" ASC NULLS LAST)
    TABLESPACE pg_default;  
        EXCEPTION
            WHEN duplicate_table THEN RAISE NOTICE 'Create table <EmailMessages>.';
        END;
    END;
$$


