﻿CREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" (
    "MigrationId" character varying(150) NOT NULL,
    "ProductVersion" character varying(32) NOT NULL,
    CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY ("MigrationId")
);

START TRANSACTION;


DO $EF$
BEGIN
    IF NOT EXISTS(SELECT 1 FROM "__EFMigrationsHistory" WHERE "MigrationId" = '20240817153531_Initial') THEN
    CREATE TABLE "Users" (
        "Id" text NOT NULL,
        CONSTRAINT "PK_Users" PRIMARY KEY ("Id")
    );
    END IF;
END $EF$;

DO $EF$
BEGIN
    IF NOT EXISTS(SELECT 1 FROM "__EFMigrationsHistory" WHERE "MigrationId" = '20240817153531_Initial') THEN
    CREATE TABLE "Cars" (
        "Id" uuid NOT NULL,
        "Name" character varying(50) NOT NULL,
        "UserId" text NOT NULL,
        CONSTRAINT "PK_Cars" PRIMARY KEY ("Id"),
        CONSTRAINT "FK_Cars_Users_UserId" FOREIGN KEY ("UserId") REFERENCES "Users" ("Id") ON DELETE CASCADE
    );
    END IF;
END $EF$;

DO $EF$
BEGIN
    IF NOT EXISTS(SELECT 1 FROM "__EFMigrationsHistory" WHERE "MigrationId" = '20240817153531_Initial') THEN
    CREATE TABLE "Consumption" (
        "Id" uuid NOT NULL,
        "DateTime" timestamp with time zone NOT NULL,
        "Distance" double precision NOT NULL,
        "Amount" double precision NOT NULL,
        "IgnoreInCalculation" boolean NOT NULL,
        "CarId" uuid NOT NULL,
        CONSTRAINT "PK_Consumption" PRIMARY KEY ("Id"),
        CONSTRAINT "FK_Consumption_Cars_CarId" FOREIGN KEY ("CarId") REFERENCES "Cars" ("Id") ON DELETE CASCADE
    );
    END IF;
END $EF$;

DO $EF$
BEGIN
    IF NOT EXISTS(SELECT 1 FROM "__EFMigrationsHistory" WHERE "MigrationId" = '20240817153531_Initial') THEN
    CREATE INDEX "IX_Cars_UserId" ON "Cars" ("UserId");
    END IF;
END $EF$;

DO $EF$
BEGIN
    IF NOT EXISTS(SELECT 1 FROM "__EFMigrationsHistory" WHERE "MigrationId" = '20240817153531_Initial') THEN
    CREATE INDEX "IX_Consumption_CarId" ON "Consumption" ("CarId");
    END IF;
END $EF$;

DO $EF$
BEGIN
    IF NOT EXISTS(SELECT 1 FROM "__EFMigrationsHistory" WHERE "MigrationId" = '20240817153531_Initial') THEN
    INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
    VALUES ('20240817153531_Initial', '8.0.8');
    END IF;
END $EF$;
COMMIT;

