예제 #1
0
    def update(
        cls, model: Model, properties: Dict[str, Any], commit: bool = True
    ) -> Model:
        """
        create a report schedule and nested recipients
        :raises: DAOCreateFailedError
        """

        try:
            for key, value in properties.items():
                if key != "recipients":
                    setattr(model, key, value)
            if "recipients" in properties:
                recipients = properties["recipients"]
                model.recipients = [
                    ReportRecipients(
                        type=recipient["type"],
                        recipient_config_json=json.dumps(
                            recipient["recipient_config_json"]
                        ),
                        report_schedule=model,
                    )
                    for recipient in recipients
                ]
            db.session.merge(model)
            if commit:
                db.session.commit()
            return model
        except SQLAlchemyError as ex:
            db.session.rollback()
            raise DAOCreateFailedError(str(ex)) from ex
예제 #2
0
def import_simple_obj(session: Session, i_obj: Model,
                      lookup_obj: Callable[[Session, Model], Model]) -> Model:
    make_transient(i_obj)
    i_obj.id = None
    i_obj.table = None

    # find if the column was already imported
    existing_column = lookup_obj(session, i_obj)
    i_obj.table = None
    if existing_column:
        existing_column.override(i_obj)
        session.flush()
        return existing_column

    session.add(i_obj)
    session.flush()
    return i_obj
예제 #3
0
 def set_owners(instance: Model, owners: List[int]):
     owner_objs = list()
     if g.user.id not in owners:
         owners.append(g.user.id)
     for owner_id in owners:
         user = current_app.appbuilder.get_session.query(
             current_app.appbuilder.sm.user_model).get(owner_id)
         owner_objs.append(user)
     instance.owners = owner_objs
예제 #4
0
 def set_owners(instance: Model, owners: List[int]) -> None:
     owner_objs = []
     user_id = get_user_id()
     if user_id and user_id not in owners:
         owners.append(user_id)
     for owner_id in owners:
         user = current_app.appbuilder.get_session.query(
             current_app.appbuilder.sm.user_model).get(owner_id)
         owner_objs.append(user)
     instance.owners = owner_objs
예제 #5
0
def import_datasource(
    session: Session,
    i_datasource: Model,
    lookup_database: Callable[[Model], Model],
    lookup_datasource: Callable[[Model], Model],
    import_time: Optional[int] = None,
) -> int:
    """Imports the datasource from the object to the database.

     Metrics and columns and datasource will be overrided if exists.
     This function can be used to import/export datasources between multiple
     superset instances. Audit metadata isn't copies over.
    """
    make_transient(i_datasource)
    logger.info("Started import of the datasource: %s", i_datasource.to_json())

    i_datasource.id = None
    i_datasource.database_id = lookup_database(i_datasource).id
    i_datasource.alter_params(import_time=import_time)

    # override the datasource
    datasource = lookup_datasource(i_datasource)

    if datasource:
        datasource.override(i_datasource)
        session.flush()
    else:
        datasource = i_datasource.copy()
        session.add(datasource)
        session.flush()

    for metric in i_datasource.metrics:
        new_m = metric.copy()
        new_m.table_id = datasource.id
        logger.info(
            "Importing metric %s from the datasource: %s",
            new_m.to_json(),
            i_datasource.full_name,
        )
        imported_m = i_datasource.metric_class.import_obj(new_m)
        if imported_m.metric_name not in [
                m.metric_name for m in datasource.metrics
        ]:
            datasource.metrics.append(imported_m)

    for column in i_datasource.columns:
        new_c = column.copy()
        new_c.table_id = datasource.id
        logger.info(
            "Importing column %s from the datasource: %s",
            new_c.to_json(),
            i_datasource.full_name,
        )
        imported_c = i_datasource.column_class.import_obj(new_c)
        if imported_c.column_name not in [
                c.column_name for c in datasource.columns
        ]:
            datasource.columns.append(imported_c)
    session.flush()
    return datasource.id
예제 #6
0
 def _get_related_filter(self, datamodel: Model, column_name: str,
                         value: str) -> Filters:
     filter_field = self.related_field_filters.get(column_name)
     if isinstance(filter_field, str):
         filter_field = RelatedFieldFilter(cast(str, filter_field),
                                           FilterStartsWith)
     filter_field = cast(RelatedFieldFilter, filter_field)
     search_columns = [filter_field.field_name] if filter_field else None
     filters = datamodel.get_filters(search_columns)
     base_filters = self.filter_rel_fields.get(column_name)
     if base_filters:
         filters.add_filter_list(base_filters)
     if value and filter_field:
         filters.add_filter(filter_field.field_name,
                            filter_field.filter_class, value)
     return filters
예제 #7
0
def clone_model(
    target: Model, ignore: Optional[List[str]] = None, **kwargs: Any
) -> Model:
    """
    Clone a SQLAlchemy model.
    """
    ignore = ignore or []

    table = target.__table__
    data = {
        attr: getattr(target, attr)
        for attr in table.columns.keys()
        if attr not in table.primary_key.columns.keys() and attr not in ignore
    }
    data.update(kwargs)

    return target.__class__(**data)
예제 #8
0
def clone_model(
    target: Model,
    ignore: Optional[List[str]] = None,
    keep_relations: Optional[List[str]] = None,
    **kwargs: Any,
) -> Model:
    """
    Clone a SQLAlchemy model. By default will only clone naive column attributes.
    To include relationship attributes, use `keep_relations`.
    """
    ignore = ignore or []

    table = target.__table__
    primary_keys = table.primary_key.columns.keys()
    data = {
        attr: getattr(target, attr)
        for attr in list(table.columns.keys()) + (keep_relations or [])
        if attr not in primary_keys and attr not in ignore
    }
    data.update(kwargs)

    return target.__class__(**data)
예제 #9
0
 def to_model(self, model: Model, dto, is_update: bool = False):
     model.user_id = dto['user_id']
     return self.model_factory.create_or_update(model, dto, is_update)