Пример #1
0
def write_uml():
    # lets find all the mappers in our model
    mappers = []
    for attr in dir(base):
        if attr[0] == '_': continue
        try:
            cls = getattr(base, attr)
            mappers.append(class_mapper(cls))
        except:
            pass

    graph_out1 = create_uml_graph(
        mappers,
        show_operations=False,  # not necessary in this case
        show_multiplicity_one=
        True,  # some people like to see the ones, some don't
        show_attributes=True,
        show_inherited=True,
    )
    with open('schema_uml.txt', 'w', encoding='utf-8') as f:
        f.write(str(graph_out1))

    graph_out = create_schema_graph(
        metadata=MetaData(
            "postgresql://*****:*****@localhost:6532/fastapi"),
        show_datatypes=False,  # can get large with datatypes
        show_indexes=False,  # ditto for indexes
        rankdir='LR',  # From left to right (LR), top to bottom (TB)
        concentrate=True,  # Don't try to join the relation lines together,
    )
    with open('schema_schema.txt', 'w', encoding='utf-8') as f:
        f.write(str(graph_out))
Пример #2
0
def make_graph(mappers):
    # pass them to the function and set some formatting options
    graph = create_uml_graph(mappers,
        show_operations=True, # not necessary in this case
        show_multiplicity_one=True # some people like to see the ones, some don't
    )
    return graph
Пример #3
0
    def _draw_uml_class_diagram(self):
        # lets find all the mappers in our model
        try:
            from sqlalchemy_schemadisplay import create_uml_graph  # pylint:disable=import-outside-toplevel
        except ImportError:
            print(
                'Please install sqlalchemy_schemadisplay with "pip install sqlalchemy_schemadisplay"'
            )
            sys.exit(1)
        mappers = []
        for attr in dir(models):
            if attr[0] == '_':
                continue
            try:
                cls = getattr(models, attr)
                mappers.append(class_mapper(cls))
            except Exception as ex:
                print(ex)

        # pass them to the function and set some formatting options
        graph = create_uml_graph(
            mappers,
            show_operations=False,  # not necessary in this case
            show_multiplicity_one=
            False,  # some people like to see the ones, some don't
            # show_attributes=False,  # Uncomment to don't show fields, only model names
        )
        graph.write_png('uml_schema.png')  # write out the file
        print("Graph written to fle uml_schema.png")
    def _draw_uml_class_diagram(self):
        # lets find all the mappers in our model
        mappers = []
        for attr in dir(models):
            if attr[0] == '_':
                continue
            try:
                cls = getattr(models, attr)
                mappers.append(class_mapper(cls))
            except:
                pass

        # pass them to the function and set some formatting options
        graph = create_uml_graph(
            mappers,
            show_operations=False,  # not necessary in this case
            show_multiplicity_one=
            False,  # some people like to see the ones, some don't
            # show_attributes=False,  # Uncomment to don't show fields, only model names
        )
        graph.write_png('uml_schema.png')  # write out the file
        print("Graph written to fle uml_schema.png")


# I'm Py3
Пример #5
0
def make_graph(mappers):
    # pass them to the function and set some formatting options
    graph = create_uml_graph(mappers,
        show_operations=True, # not necessary in this case
        show_multiplicity_one=True # some people like to see the ones, some don't
    )
    return graph
Пример #6
0
def uml_graph(db):
    """Generate a UML diagram from the models."""
    import sqlalchemy_schemadisplay as sasd

    graph = sasd.create_uml_graph(mappers(Spam, Feed, FeedSet),
                                  show_operations=False,
                                  show_multiplicity_one=True)
    graph.write_png('uml_graph.png')  # write out the file
Пример #7
0
def build_uml(file='schema.png'):
    '''write model relation graph to schema.png'''
    from sqlalchemy_schemadisplay import create_uml_graph
    from sqlalchemy.orm import class_mapper

    mappers = []
    for attr in dir(model):
        if attr[0] == '_': continue
        try:
            cls = getattr(model, attr)
            mappers.append(class_mapper(cls))
        except:
            pass
    create_uml_graph(
        mappers,
        show_operations=False,
        show_multiplicity_one=
        False  # some people like to see the ones, some don't
    ).write_png(file)
Пример #8
0
def uml_graph(db):
    """Generate a UML diagram from the models."""
    import sqlalchemy_schemadisplay as sasd

    graph = sasd.create_uml_graph(
        mappers(User, Organization, Schema, JsonObject, License),
        show_operations=False,
        show_multiplicity_one=True,
    )
    graph.write_png("uml_graph.png")  # write out the file
Пример #9
0
def make_graph(target_name, generate_dot=False):
    from assembl.models import Base
    mappers = [cls.__mapper__ for cls in Base.get_subclasses()]

    graph = create_uml_graph(mappers,
                             show_operations=False,
                             show_multiplicity_one=False)

    if generate_dot:
        graph.write_dot(target_name + '.dot')
    graph.write_svg(target_name + '.svg')
Пример #10
0
def generate_uml_graph(package, output):
    mappers = []
    for module in sorted(load_all_modules(package), key=lambda m: m.__name__):
        for attr in dir(module):
            if not attr.startswith('_'):
                try:
                    mappers.append(class_mapper(getattr(module, attr)))
                except Exception as e:
                    print(str(e))

    graph = create_uml_graph(mappers, show_operations=False, show_multiplicity_one=False)
    graph.write_png(output)
Пример #11
0
def make_graph(target_name, generate_dot=False):
    from assembl.models import Base
    mappers = [cls.__mapper__ for cls in Base.get_subclasses()]

    graph = create_uml_graph(
        mappers,
        show_operations=False,
        show_multiplicity_one=False)

    if generate_dot:
        graph.write_dot(target_name + '.dot')
    graph.write_svg(target_name + '.svg')
Пример #12
0
def uml_graph(db):
    """Generate a UML diagram from the models."""
    import sqlalchemy_schemadisplay as sasd

    graph = sasd.create_uml_graph(
        mappers(
            Client,
            Stats,
        ),
        show_operations=False,
        show_multiplicity_one=True,
    )
    graph.write_png("uml_graph.png")  # write out the file
Пример #13
0
def uml_graph(db):
    """Generate a UML diagram from the models."""
    import sqlalchemy_schemadisplay as sasd

    graph = sasd.create_uml_graph(
                        mappers(User, Shelter, Section, Property,
                                Category, Attribute, Value,
                                Page, Translation,
                                ShelterPicture, ShelterDocument,
                                AttributePicture),
                        show_operations=False,
                        show_multiplicity_one=True
    )
    graph.write_png('uml_graph.png') # write out the file
def test_relation(Base):
    class Foo(Base):
        __tablename__ = 'foo'
        id = Column(types.Integer, primary_key=True)
    class Bar(Base):
        __tablename__ = 'bar'
        id = Column(types.Integer, primary_key=True)
        foo_id = Column(types.Integer, ForeignKey(Foo.id))
    Foo.bars = relationship(Bar)
    graph = sasd.create_uml_graph(mappers(Foo, Bar))
    assert sorted(graph.obj_dict['nodes'].keys()) == ['"Bar"', '"Foo"']
    assert '+id : Integer' in graph.obj_dict['nodes']['"Foo"'][0]['attributes']['label']
    assert '+foo_id : Integer' in graph.obj_dict['nodes']['"Bar"'][0]['attributes']['label']
    assert 'edges' in graph.obj_dict
    assert ('"Foo"', '"Bar"') in graph.obj_dict['edges']
    assert graph.obj_dict['edges'][('"Foo"', '"Bar"')][0]['attributes']['headlabel'] == '+bars *'
def test_relation(Base):
    class Foo(Base):
        __tablename__ = 'foo'
        id = Column(types.Integer, primary_key=True)
    class Bar(Base):
        __tablename__ = 'bar'
        id = Column(types.Integer, primary_key=True)
        foo_id = Column(types.Integer, ForeignKey(Foo.id))
    Foo.bars = relationship(Bar)
    graph = sasd.create_uml_graph(mappers(Foo, Bar))
    assert sorted(graph.obj_dict['nodes'].keys()) == ['"Bar"', '"Foo"']
    assert '+id : Integer' in graph.obj_dict['nodes']['"Foo"'][0]['attributes']['label']
    assert '+foo_id : Integer' in graph.obj_dict['nodes']['"Bar"'][0]['attributes']['label']
    assert 'edges' in graph.obj_dict
    assert ('"Foo"', '"Bar"') in graph.obj_dict['edges']
    assert graph.obj_dict['edges'][('"Foo"', '"Bar"')][0]['attributes']['headlabel'] == '+bars *'
Пример #16
0
def write_uml():
  # lets find all the mappers in our model
  mappers = []
  for attr in dir(Base):
      if attr[0] == '_': continue
      try:
          cls = getattr(Base, attr)
          mappers.append(class_mapper(cls))
      except:
          pass

  # pass them to the function and set some formatting options
  graph = create_uml_graph(mappers,
      show_operations=False, # not necessary in this case
      show_multiplicity_one=False # some people like to see the ones, some don't
  )
  graph.write_png('/home/hdeeken/umlschema.png') # write out the file
Пример #17
0
def create_uml_pic(store: bool = False, dev: bool = False):
    print("CREATING UML CODE DIAGRAM ...")
    print("Finding all the relevant mappers in our model...")
    mappers = []
    # map comparable names to model classes. We compare without "_" and in lowercase.
    # Note: This relies on model classes and their tables having the same name,
    #       ignoring capitalization and underscores.
    relevant_models = {}
    for module in RELEVANT_MODULES:
        relevant_models.update(
            {
                mname.lower(): mclass
                for mname, mclass in inspect.getmembers(
                    import_module(f"flexmeasures.data.models.{module}")
                )
                if inspect.isclass(mclass) and issubclass(mclass, flexmeasures_db.Model)
            }
        )
    relevant_tables = RELEVANT_TABLES
    if dev:
        relevant_tables += RELEVANT_TABLES_DEV
    else:
        relevant_tables += LEGACY_TABLES
    if DEBUG:
        print(f"Relevant tables: {relevant_tables}")
        print(f"Relevant models: {relevant_models}")
    matched_models = {
        m: c for (m, c) in relevant_models.items() if c.__tablename__ in relevant_tables
    }
    for model_name, model_class in matched_models.items():
        if DEBUG:
            print(f"Loading class {model_class.__name__} ...")
        mappers.append(class_mapper(model_class))

    print("Creating diagram ...")
    kwargs = dict(
        show_operations=False,  # not necessary in this case
        show_multiplicity_one=False,  # some people like to see the ones, some don't
    )
    print("Creating the pydot graph object...")
    graph = create_uml_graph(mappers, **kwargs)
    if store:
        print("Storing as image (uml_diagram.png) ...")
        graph.write_png("uml_diagram.png")  # write out the file
    else:
        show_image(graph, fb_viewer_command=FALLBACK_VIEWER_CMD)
Пример #18
0
def model_to_uml(module):
    """

    :param module:
    :return:
    """
    mappers = []
    models = importlib.import_module(module)

    for attr in dir(models):
        if attr[0] == "_":
            continue
        try:
            cls = getattr(models, attr)
            mappers.append(class_mapper(cls))
        except SQLAlchemyError:
            pass

    return create_uml_graph(mappers, show_operations=False)
Пример #19
0
    def render_schema(self):
        """
            Отрисовка структуры схемы БД.
            Записывает построенный график в фаил.
            
            :return: None
        """
        from sqlalchemy_schemadisplay import create_uml_graph, create_schema_graph
        from sqlalchemy.orm import class_mapper
    
        log.info("Формирование списка таблиц.")

        mappers = []
        for schema_name in dir(Schema):
            if schema_name[0] == '_':
                continue
                
            if schema_name in ['Base', 'log']:
                continue

            schema_class = getattr(Schema, schema_name)
            
            if hasattr(schema_class, "__tablename__"):
                log.debug("    Анализ схемы: {}".format(schema_name))
                
                mappers.append(class_mapper(schema_class))
       
        log.info("Формирование окружения GraphViz.")
        
        graph = create_uml_graph(
            mappers,
            show_inherited=False,
            show_operations=False,
            show_datatypes=False,
            show_multiplicity_one=False
        )

        log.info("Формирование графика.")
        graph.write_png(self.path_graph)

        log.info("Формирование графика завершено.")
Пример #20
0
    def _draw_uml_class_diagram(self):
        # lets find all the mappers in our model
        mappers = []
        for attr in dir(models):
            if attr[0] == '_':
                continue
            try:
                cls = getattr(models, attr)
                mappers.append(class_mapper(cls))
            except:
                pass

        # pass them to the function and set some formatting options
        graph = create_uml_graph(
            mappers,
            show_operations=False,  # not necessary in this case
            show_multiplicity_one=False,  # some people like to see the ones, some don't
            # show_attributes=False,  # Uncomment to don't show fields, only model names
        )
        graph.write_png('uml_schema.png')  # write out the file
        print("Graph written to fle uml_schema.png")
Пример #21
0
def uml_graph(db):
    """Generate a UML diagram from the models."""
    import sqlalchemy_schemadisplay as sasd

    graph = sasd.create_uml_graph(
        mappers(
            User,
            Tag,
            Project,
            Code,
            License,
            Organization,
            Release,
            CVE,
            Icon,
            Language,
            Submission,
            Feed,
            News,
        ),
        show_operations=False,
        show_multiplicity_one=True,
    )
    graph.write_png("uml_graph.png")  # write out the file
Пример #22
0
def schemadraw(**args):
    try:
        from sqlalchemy_schemadisplay import create_uml_graph
    except ImportError:
        log.critical("You must install sqlalchemy_schemadisplay\n$pip install sqlalchemy_schemadisplay")
        sys.exit(1)


    # lets find all the mappers in our model
    mappers = []
    for attr in dir(model):
        if attr[0] == '_': continue
        try:
            cls = getattr(model, attr)
            mappers.append(class_mapper(cls))
        except:
            pass

    # pass them to the function and set some formatting options
    graph = create_uml_graph(mappers,
        show_operations=False, # not necessary in this case
        show_multiplicity_one=False # some people like to see the ones, some don't
    )
    graph.write_png('./doc/DevOps/dbschema.png') # write out the file
Пример #23
0
from sqlalchemy_schemadisplay import create_uml_graph, create_schema_graph
from sqlalchemy.orm import class_mapper
from sqlalchemy.orm.exc import UnmappedClassError
from inyoka.core.api import db, ctx, IResource
from inyoka.utils import flatten_iterator

models = list(
    flatten_iterator(
        x.models for x in ctx.get_implementations(IResource, instances=True)))

# lets find all the mappers in our model
mappers = []
tables = []
for model in models:
    try:
        mappers.append(class_mapper(model))
        tables.extend(mappers[-1].tables)
    except UnmappedClassError:
        continue

# pass them to the function and set some formatting options
uml = create_uml_graph(
    mappers,
    show_operations=False,  # not necessary in this case
    show_multiplicity_one=False  # some people like to see the ones, some don't
)
uml.write_png('uml.png')  # write out the file

schema = create_schema_graph(list(set(tables)))
schema.write_png('schema.png')
# create a diagram of all tables

graph = create_schema_graph(
    metadata=model.meta.data,
    show_datatypes=True,
    show_indexes=False,
    rankdir='LR',
    concentrate=False   # Don't try to join the relation lines together
)

graph.write_gif('adhocracy-tables.gif')


# create an uml diagramm of all mapped classes

mappers = []
for attr in dir(model):
    if attr[0] == '_':
        continue
    try:
        cls = getattr(model, attr)
        mappers.append(class_mapper(cls))
    except:
        pass

graph = create_uml_graph(mappers,
                         show_operations=False,
                         show_multiplicity_one=True)

graph.write_gif('adhocracy-classes.gif')
Пример #25
0
    sqlitedb = os.path.join(gxy_root, 'database/universe.sqlite')
    # Try to build a representation of what's in the sqlite database
    if os.path.exists(sqlitedb):
        graph = create_schema_graph(metadata=MetaData('sqlite:///' + sqlitedb),
                                    show_datatypes=False,
                                    show_indexes=False,
                                    rankdir='LR',
                                    concentrate=False)
        print(f"Writing galaxy_universe.png, built from {sqlitedb}")
        graph.write_png('galaxy_universe.png')
    else:
        print(f"No sqlitedb available at {sqlitedb}, skipping rendering")

    # Build UML graph from loaded mapper
    mappers = []
    for attr in dir(model):
        if attr[0] == '_':
            continue
        try:
            cls = getattr(model, attr)
            mappers.append(class_mapper(cls))
        except Exception:
            pass

    graph = create_uml_graph(
        mappers,
        show_operations=False,
    )
    print("Writing galaxy_uml.png")
    graph.write_png('galaxy_uml.png')  # write out the file
        concentrate=False)  # no joins of tables together
    graph.write_png(output)


def generate_uml_graph(package, output):
    mappers = []
    for module in sorted(load_all_modules(package), key=lambda m: m.__name__):
        for attr in dir(module):
            if not attr.startswith('_'):
                try:
                    mappers.append(class_mapper(getattr(module, attr)))
                except Exception, e:
                    print str(e)

    graph = create_uml_graph(mappers,
                             show_operations=False,
                             show_multiplicity_one=False)
    graph.write_png(output)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    uml = parser.add_argument_group('UML')
    uml.add_argument('-p', '--package', help='database connection uri')
    uml.add_argument('-u', '--uml_output', help='uml diagram output path')

    schema = parser.add_argument_group('SCHEMA')
    schema.add_argument('-c',
                        '--create',
                        help='first create the database from the package')
def plain_result(mapper, **kw):
    return parse_graph(sasd.create_uml_graph(mapper, **kw))
Пример #28
0
from model import models
from sqlalchemy_schemadisplay import create_uml_graph
from sqlalchemy.orm import class_mapper

# lets find all the mappers in our model
mappers = []
for attr in dir(models):
    if attr[0] == '_': continue
    try:
        cls = getattr(models, attr)
        mappers.append(class_mapper(cls))
    except:
        pass

# pass them to the function and set some formatting options
graph = create_uml_graph(mappers,
    show_operations=False,  # not necessary in this case
    show_multiplicity_one=True,  # some people like to see the ones, some don't
    font='Calibri'
)
graph.write('schema.svg',format='svg') # write out the file
def plain_result(mapper, **kw):
    return parse_graph(sasd.create_uml_graph(mapper, **kw))