Exemple #1
0
    def __init__(self,
                 connection: Connection,
                 id: str,
                 project_id: str,
                 shortcut_info_flag: Union[
                     ShortcutInfoFlags,
                     int] = ShortcutInfoFlags.DssDossierShortcutInfoTOC):
        """Initialize the Shortcut object and populate it with I-Server data.

        Args:
            connection: MicroStrategy connection object returned
                by `connection.Connection()`.
            id: Shortcut ID
            project_id: ID of the project that the shortcut is in
            shortcut_info_flag: flag indicating what information about shortcut
                should be loaded
        """
        if id is None or project_id is None:
            raise AttributeError(
                "Please specify 'id' and 'project_id' parameters in the constructor."
            )
        else:
            super().__init__(connection=connection,
                             object_id=id,
                             project_id=project_id,
                             shortcut_info_flag=get_enum_val(
                                 shortcut_info_flag, ShortcutInfoFlags))
    def lock(self, lock_type: Union[str, "SchemaLockType"]) -> bool:
        """Lock the schema. After successfully locking the schema its
        `lock_type` property is updated.

        Args:
            lock_type: (string or object): Type of lock which will be placed on
                the schema.

        Returns:
            `True` when schema was successfully locked or schema has already
            been locked. `False` when procedure of locking schema failed.

        Raises:
            `TypeError` if `lock_type` is neither a string nor
            a `SchemaLockType`.
            `ValueError` if `lock_type` is specified as a string which is not
            a proper value of enum `SchemaLockType`.
        """
        lock_type = get_enum_val(lock_type, SchemaLockType)

        if self.lock_type != SchemaLockType.UNLOCKED:
            logger.info('Schema is already locked.')
            return True

        res = schema.lock_schema(self.connection, lock_type, self.project_id)
        if res.ok:
            self.get_lock_status()
            return True
        return False
Exemple #3
0
    def __init__(self, type: Union["ConstantType", str], value: str):
        """Constant parameter for predicate.

        Args:
            type (enum): type of constant. Possible values are defined in enum
                `ConstantType`.
            value (str): value of constant.
        """
        super().__init__()
        self.constant = {"type": get_enum_val(type, ConstantType), "value": value}
Exemple #4
0
def merge_id_and_type(object_id: str,
                      object_type: Union["ObjectTypes", "ObjectSubTypes", int],
                      error_msg: Optional[str] = None) -> str:
    if not object_id or not object_type:
        exception_handler(msg=error_msg
                          or "Please provide both `id` and `type`.",
                          exception_type=AttributeError)
    object_id = get_objects_id(object_id, type(object_id))
    object_type = get_enum_val(object_type, type(object_type)) if isinstance(
        object_type, Enum) else object_type
    return f'{object_id};{object_type}'
    def reload(self,
               update_types: Optional[Union[List[Union[str,
                                                       "SchemaUpdateType"]],
                                            Union[str,
                                                  "SchemaUpdateType"]]] = None,
               respond_async: bool = True) -> Optional["SchemaTask"]:
        """Reload (update) the schema. This operation can be performed
        asynchronously. In that case the task is created and it is saved in
        property `tasks` to help tracking its status.

        Args:
            update_types (optional, list or object or string): Field with update
                type(s). Values in this field can be of type `string` or
                `SchemaUpdateType` or be a list of those types. This field can
                contain empty, any of the following options, or all of them:
                - `table_key`: Use this option if you changed the key structure
                  of a table.
                - `entry_level`: Use this option if you changed the level at
                  which a fact is stored.
                - `logical_size`: Use this option to recalculate logical table
                  sizes and override any modifications you made to logical table
                  sizes.
                - `clear_element_cache`: Use this option to clear up the
                  attribute element cache saved on the Intelligence Server.
            respond_async (optional, bool): When `True` reload is performed
                asynchronously. Otherwise it is performed synchronously. Default
                value is `True`.

        Returns:
            When `respond_async` is set to `True` then `SchemaTask` object with
            all details about the task of reloading schema is returned.
            Otherwise `None` is returned.

        Raises:
            `TypeError` if any value in `update_types` is neither a string nor
            a `SchemaUpdateType`.
            `ValueError` if any value in `update_types` is specified as a string
            which is not a proper value of enum `SchemaUpdateType`.
        """
        if not update_types:
            update_types = []
        elif not isinstance(update_types, list):
            update_types = [update_types]
        update_types = [
            get_enum_val(t, SchemaUpdateType) for t in update_types
        ]

        res = schema.reload_schema(self.connection, self.project_id,
                                   update_types, respond_async)
        if res.ok and respond_async:
            return self._save_task(res.json())
Exemple #6
0
def get_shortcuts(connection: Connection,
                  project_id: str,
                  shortcut_ids: List[str],
                  shortcut_info_flag: Union[
                      ShortcutInfoFlags,
                      int] = ShortcutInfoFlags.DssDossierShortcutInfoDefault,
                  to_dictionary: bool = False,
                  limit: Optional[int] = None,
                  **filters) -> Union[List[dict], List[Shortcut]]:
    """Retrieve information about specific published shortcuts
    in specific project.

    Args:
        shortcut_ids: ids of target shortcuts
        project_id: id of project that the shortcuts are in
        shortcut_info_flag: a single ShortcutInfoFlags that describes what
          exact info are to be fetched
        to_dictionary: parameter describing output format
        limit (int): limit the number of elements returned. If `None` (default),
            all objects are returned.
    Return:
        list of dictionaries or Shortcut objects,
          depending on `to_dictionary` parameter
    """

    shortcuts = fetch_objects(
        connection=connection,
        api=browsing.get_shortcuts,
        dict_unpack_value="shortcuts",
        limit=limit,
        filters=filters,
        body=[{
            "projectId": project_id,
            "shortcutIds": shortcut_ids
        }],
        shortcut_info_flag=get_enum_val(shortcut_info_flag, ShortcutInfoFlags),
    )

    if to_dictionary:
        return shortcuts
    else:
        return [
            Shortcut.from_dict(source=short, connection=connection)
            for short in shortcuts
        ]
Exemple #7
0
    def create(cls,
               connection: "Connection",
               name: str,
               device_type: Union[DeviceType, str],
               transmitter: Union[Transmitter, str],
               device_properties: Union[dict, Dictable],
               description: str = None) -> "Device":
        """Create a new device.

        Args:
            connection: MicroStrategy connection object returned by
                `connection.Connection()`
            name: device object name
            device_type: type of the device
            transmitter: Transmitter object
            description: device object description
            device_properties: properties of the device
        Returns:
            Device object.
        """
        device_type = get_enum_val(device_type, DeviceType)
        device_properties = device_properties.to_dict() if isinstance(
            device_properties, Dictable) else device_properties
        transmitter_id = get_objects_id(transmitter, Transmitter)
        body = {
            "name": name,
            "description": description,
            "deviceType": device_type,
            "transmitter": {
                "id": transmitter_id,
            },
            "deviceProperties": {
                device_type: device_properties
            }
        }
        body = delete_none_values(body)
        response = devices.create_device(connection, body).json()
        if config.verbose:
            logger.info(
                f"Successfully created device named: '{name}' with ID: '{response['id']}'."
            )
        return cls.from_dict(source=response, connection=connection)
    def create(
        cls,
        connection: "Connection",
        name: str,
        delivery_type: Union[str, TransmitterDeliveryType],
        description: Optional[str] = None,
        email_transmitter_properties: Optional[Union[
            dict, EmailTransmitterProperties]] = None
    ) -> "Transmitter":
        """Create transmitter.

        Args:
            connection: MicroStrategy connection object returned by
                `connection.Connection()`.
            delivery_type: type of the transmitter
            name (str): transmitter's name
            description (str): transmitter's description
            email_transmitter_properties (dict or object): properties specific
                to email transmitter. In transmitter with type `email` those
                properties must be provided. Otherwise they cannot be provided.

        Returns:
            `Transmitter` object
        """
        delivery_type = get_enum_val(delivery_type, TransmitterDeliveryType)
        email_transmitter_properties = email_transmitter_properties.to_dict(
        ) if isinstance(
            email_transmitter_properties,
            EmailTransmitterProperties) else email_transmitter_properties
        body = {
            'name': name,
            'description': description,
            'deliveryType': delivery_type,
            'emailTransmitterProperties': email_transmitter_properties
        }

        res = transmitters.create_transmitter(connection, body).json()
        if config.verbose:
            logger.info(
                f"Successfully created transmitter named: '{res.get('name')}' "
                f"with ID: '{res.get('id')}'")
        return cls.from_dict(res, connection)
Exemple #9
0
    def create(
            cls,
            connection: "Connection",
            name: str,
            description: Optional[str] = None,
            acg: Optional[int] = None,
            execution_mode: Union[str, ExecutionMode] = None,
            max_cancel_attempt_time: Optional[int] = None,
            max_query_exe_time: Optional[int] = None,
            max_connection_attempt_time: Optional[int] = None,
            connection_lifetime: Optional[int] = None,
            connection_idle_timeout: Optional[int] = None,
            char_encoding_windows: Union[str, CharEncoding] = None,
            char_encoding_unix: Union[str, CharEncoding] = None,
            table_prefix: Optional[str] = None,
            connection_string: Optional[str] = None,
            parameterized_queries: Optional[bool] = None,
            extended_fetch: Optional[bool] = None,
            datasource_login: Union[DatasourceLogin, str, None] = None,
            database_type: Optional[str] = None,
            database_version: Optional[str] = None,
            driver_type: Union[str, DriverType] = None,
            oauth_parameter: Optional[str] = None) -> "DatasourceConnection":
        """Create a new datasource connection on the I-Server.

        Args:
            connection: MicroStrategy connection object returned by
                `connection.Connection()`.
            name: Unique datasource connection name.
            description: Datasource connection description.
            acg: Object access rights. It's a bit vector where bits are defined
                at [EnumDSSXMLAccessRightFlags].
            execution_mode: ExecutionMode Enum specifying how SQL statements
                will be executed on a physical database connection made.
            max_cancel_attempt_time: Number of seconds before being timed out
                when attempting to make a connection.
            max_query_exe_time: Number of seconds during which a query must be
                executed before being timed out.
            max_connection_attempt_time: Number of seconds connection attempts
                to be made before timing out.
            connection_lifetime: Number of seconds of the connection lifetime.
            connection_idle_timeout: Number of seconds before being timed out
                when the connection is idle.
            char_encoding_windows: CharEncoding Enum specifying the encoding
                across connection for Windows drivers.
            char_encoding_unix: CharEncoding Enum specifying the encoding across
                connection for Unix drivers.
            table_prefix: String prefixed to the names of all temporary tables
                created by the Query Engine for this connection during report
                execution with this string.
            connection_string: Database connection string.
            parameterized_queries: Specifies whether parameterized queries are
                enabled.
            extended_fetch: Specifies whether or not to use the extended fetch
                ODBC call to retrieve data from the database connection.
            driver_type: DriverType Enum specifying Driver used for database
                connection.
            oauth_parameter: Used for authentication with oAuth.
            datasource_login: `DatasourceLogin` object or ID
            database_type: Database type
            database_version: Database version

        Returns:
            DatasourceConnection object.
        """
        login_id = get_objects_id(datasource_login, DatasourceLogin)

        body = {
            "name":
            name,
            "description":
            description,
            "acg":
            acg,
            "executionMode":
            get_enum_val(execution_mode, ExecutionMode),
            "maxCancelAttemptTime":
            max_cancel_attempt_time,
            "maxQueryExeTime":
            max_query_exe_time,
            "maxConnectionAttemptTime":
            max_connection_attempt_time,
            "connectionLifetime":
            connection_lifetime,
            "connectionIdleTimeout":
            connection_idle_timeout,
            "charEncodingWindows":
            get_enum_val(char_encoding_windows, CharEncoding),
            "charEncodingUnix":
            get_enum_val(char_encoding_unix, CharEncoding),
            "tablePrefix":
            table_prefix,
            "connectionString":
            connection_string,
            "parameterizedQueries":
            parameterized_queries,
            "extendedFetch":
            extended_fetch,
            "database": {
                "login": {
                    "id": login_id
                },
                "type": database_type,
                "version": database_version
            },
            "driverType":
            get_enum_val(driver_type, DriverType),
            "oauthParameter":
            oauth_parameter
        }
        body = helper.delete_none_values(body)
        response = datasources.create_datasource_connection(connection,
                                                            body).json()
        if config.verbose:
            logger.info(
                f"Successfully created datasource connection named: '{response.get('name')}' "
                f"with ID: '{response.get('id')}'")
        return cls.from_dict(source=response, connection=connection)
Exemple #10
0
    def create(
        cls,
        connection: "Connection",
        name: str,
        dbms: Union[Dbms, str],
        description: Optional[str] = None,
        datasource_type: Optional[Union[str, DatasourceType]] = None,
        table_prefix: Optional[str] = None,
        odbc_version: Optional[str] = None,
        intermediate_store_db_name: Optional[str] = None,
        intermediate_store_table_space_name: Optional[str] = None,
        datasource_connection: Union[str, DatasourceConnection, None] = None,
        database_type: str = None,
        database_version: str = None,
        primary_datasource: Union[str, "DatasourceInstance", None] = None,
        data_mart_datasource: Union[str, "DatasourceInstance", None] = None
    ) -> Optional["DatasourceInstance"]:
        """Create a new DatasourceInstance object on I-Server.

        Args:
            connection: MicroStrategy connection object returned by
                `connection.Connection()`.
            name: Datasource name
            dbms: The database management system (DBMS) object or id
            description: Datasource description
            datasource_type: DatasourceType Enum (reserved, normal, data_import,
                data_import_primary)
            table_prefix: Table prefix
            odbc_version: Odbc version ENUM (version3x, version2x)
            intermediate_store_db_name: Intermediate store DBName
            intermediate_store_table_space_name: intermediate store table space
                name
            datasource_connection: `DatasourceConnection` object or ID
            database_type: Database type
            database_version: Database version
            primary_datasource: `DatasourceInstance` object or ID
            data_mart_datasource: `DatasourceInstance` object or ID

        Returns:
            DatasourceInstance object.
        """
        dbms_id = get_objects_id(dbms, Dbms)
        connection_id = get_objects_id(datasource_connection,
                                       DatasourceConnection)
        primary_datasource_id = get_objects_id(primary_datasource, cls)
        data_mart_datasource_id = get_objects_id(data_mart_datasource, cls)
        database = {
            "type": database_type,
            "version": database_version,
            "connection": {
                "id": connection_id
            }
        }
        if primary_datasource_id:
            database["primaryDatasource"] = {"id": primary_datasource_id}
        if data_mart_datasource_id:
            database["dataMartDatasource"] = {"id": data_mart_datasource_id}

        body = {
            "name": name,
            "database": database,
            "description": description,
            "datasourceType": get_enum_val(datasource_type, DatasourceType),
            "tablePrefix": table_prefix,
            "odbcVersion": odbc_version,
            "intermediateStoreDbName": intermediate_store_db_name,
            "intermediateStoreTableSpaceName":
            intermediate_store_table_space_name,
            "dbms": {
                "id": dbms_id
            }
        }
        body = helper.delete_none_values(body)
        response = datasources.create_datasource_instance(connection,
                                                          body).json()
        if config.verbose:
            logger.info(
                f"Successfully created datasource instance named: '{response.get('name')}' "
                f"with ID: '{response.get('id')}'")
        return cls.from_dict(source=response, connection=connection)
Exemple #11
0
    def create(
        cls,
        connection: Connection,
        name: str,
        schedule_type: Union[ScheduleType, str],
        start_date: Union[str, datetime],
        description: Optional[str] = None,
        stop_date: Optional[Union[str, datetime]] = None,
        event_id: Optional[str] = None,
        time: Optional[ScheduleTime] = None,
        recurrence_pattern: Optional[Union[ScheduleEnums.RecurrencePattern,
                                           str]] = None,
        execution_pattern: Optional[Union[ScheduleEnums.ExecutionPattern,
                                          str]] = None,
        execution_time: Optional[str] = None,
        start_time: Optional[str] = None,
        stop_time: Optional[str] = None,
        execution_repeat_interval: Optional[int] = None,
        daily_pattern: Optional[Union[ScheduleEnums.DailyPattern, str]] = None,
        repeat_interval: Optional[int] = None,
        days_of_week: Optional[Union[List[ScheduleEnums.DaysOfWeek],
                                     List[str]]] = None,
        day: Optional[int] = None,
        month: Optional[int] = None,
        week_offset: Optional[Union[ScheduleEnums.WeekOffset, str]] = None,
        day_of_week: Optional[Union[ScheduleEnums.DaysOfWeek, str]] = None,
        weekday_off_set: Optional[str] = None,
        days_of_month: Optional[List[str]] = None,
        monthly_pattern: Optional[Union[ScheduleEnums.MonthlyPattern,
                                        str]] = None,
        yearly_pattern: Optional[Union[ScheduleEnums.YearlyPattern,
                                       str]] = None):
        """Create a Schedule using provided parameters as data.

        Args:
            recurrence_pattern (ScheduleEnums.RecurrencePattern, optional):
                The recurrence pattern of the schedule. Possible values are
                DAILY, WEEKLY, MONTHLY, YEARLY. Defaults to None.
            execution_pattern (ScheduleEnums.ExecutionPattern, optional):
                The execution pattern of the schedule. Possible values are ONCE,
                REPEAT. Defaults to None.
            execution_time (str, optional):
                The execution time of the execution day, if execution_pattern
                is ONCE. Format should be HH:mm:ss. Defaults to None.
            start_time (str, optional):
                The start time of the execution day, if execution_pattern is
                REPEAT. Format should be HH:mm:ss. Defaults to None.
            stop_time (str, optional):
                The stop time of the execution day, if execution_pattern is
                REPEAT.Format should be HH:mm:ss. Defaults to None.
            execution_repeat_interval (int, optional):
                The repeat interval of minutes of the execution day, if
                execution_pattern is REPEAT. Defaults to None.
            daily_pattern (ScheduleEnums.DailyPattern, optional):
                The daily recurrence pattern of the schedule. Possible values
                are DAY, WEEKDAY. Defaults to None.
            repeat_interval (int, optional):
                The repeat interval of days of daily schedule, if daily_pattern
                is DAY. Defaults to None.
            day (int, optional):
                The day in month of monthly schedule, if monthly_pattern is DAY
                or, The day in month of yearly schedule, if yearly_pattern is
                DAY. Defaults to None.
            month (int, optional):
                The month in year of yearly schedule. Defaults to None.
            week_offset (ScheduleEnums.WeekOffset, optional):
                The week offset in month of monthly schedule, if monthly_pattern
                is DAY_OF_WEEK or, The week offset in year of yearly schedule,
                if yearly_pattern is DAY_OF_WEEK. Possible values are FIRST,
                SECOND, THIRD, FOURTH, LAST. Defaults to None.
            day_of_week (ScheduleEnums.DaysOfWeek, optional):
                The days of week of weekly schedule or, The day of week in month
                of monthly schedule, if monthly_pattern is DAY_OF_WEEK or, The
                day of week in year of yearly schedule, if yearly_pattern is
                DAY_OF_WEEK. Possible values are: MONDAY, TUESDAY, WEDNESDAY,
                THURSDAY, FRIDAY, SATURDAY, SUNDAY. Defaults to None.
            weekday_offset (ScheduleEnums.WeekdayOffset, optional):
                The weekday offset in month of monthly schedule, if
                monthly_pattern is WEEKDAY. Defaults to None.
            days_of_month (List[str], optional):
                The days of month of monthly schedule, if monthly_pattern is
                DAYS_OF_MONTH. Must be provided as a list of one or more
                stringified digits (from '1' to '31'). Defaults to None.
            monthly_pattern (ScheduleEnums.MonthlyPattern, optional):
                The monthly recurrence pattern of the schedule. Possible values
                are: DAY, DAY_OF_WEEK, WEEKDAY, LAST_DAY, DAYS_OF_MONTH.
                Defaults to None.
            yearly_pattern (ScheduleEnums.YearlyPattern, optional):
                The yearly recurrence pattern of the schedule. Possible values
                are DAY, DAY_OF_WEEK. Defaults to None.
        Returns:
            Schedule object with provided parameters.
        """
        time_kwargs = {
            key: val
            for key, val in locals().items()
            if val is not None and key not in [
                'event_id', 'connection', 'description', 'name',
                'schedule_type', 'start_date', 'stop_date', 'time', 'self',
                'cls'
            ]
        }
        # Event based or Time based logic
        if schedule_type == cls.ScheduleType.EVENT_BASED:
            execution_details = {'type': 'event', 'content': {'id': event_id}}
        elif schedule_type == cls.ScheduleType.TIME_BASED:
            if time is None:
                time = ScheduleTime.from_details(**time_kwargs)
            execution_details = {'type': 'time', 'content': time.to_dict()}

        # Datetime dates to string format conversion
        start_date = map_datetime_to_str(name='start_date',
                                         date=start_date,
                                         string_to_date_map=cls._FROM_DICT_MAP)
        stop_date = map_datetime_to_str(name='stop_date',
                                        date=stop_date,
                                        string_to_date_map=cls._FROM_DICT_MAP)

        # Create body and send request
        body = {
            'name': name,
            'description': description,
            'schedule_type': get_enum_val(schedule_type, cls.ScheduleType),
            'start_date': start_date,
            'stop_date': stop_date,
            execution_details['type']: execution_details['content']
        }
        body = helper.delete_none_values(body)
        body = helper.snake_to_camel(body)
        # Response is already unpacked in wrapper
        response = schedules.create_schedule(connection, body)
        response = response.json()
        if config.verbose:
            logger.info(f"Created schedule '{name}' with ID: {response['id']}")
        return Schedule.from_dict(source=response, connection=connection)