CREATE TABLE permission.api_key_permissions
(
    Id           SERIAL PRIMARY KEY,
    ApiKeyId     INT         NOT NULL REFERENCES administration.api_keys (Id) ON DELETE CASCADE,
    PermissionId INT         NOT NULL REFERENCES permission.permissions (Id) ON DELETE CASCADE,

    -- for history
    Deleted      BOOLEAN     NOT NULL DEFAULT FALSE,
    EditorId     INT         NULL REFERENCES administration.users (Id),
    CreatedUtc   timestamptz NOT NULL DEFAULT NOW(),
    UpdatedUtc   timestamptz NOT NULL DEFAULT NOW(),
    CONSTRAINT UQ_ApiKeyPermission UNIQUE (ApiKeyId, PermissionId)
);

CREATE TABLE permission.api_key_permissions_history
(
    LIKE permission.api_key_permissions
);

CREATE TRIGGER versioning_trigger
    BEFORE INSERT OR UPDATE OR DELETE
    ON permission.api_key_permissions
    FOR EACH ROW
EXECUTE PROCEDURE public.history_trigger_function();