Esempio n. 1
0
def output_design():
    import eralchemy
    from magnet import Base
    eralchemy.render_er(Base, "er.png")
    markdown = get_table_define_as_markdown(Base)
    with open("tables.md", mode='w') as f:
        f.write(markdown)
Esempio n. 2
0
def main(argv=None):
    usage = """Data Model ERD Generator

    Generates an entity relationship diagram for the data model specified. If
    passing a custom URL, the data model returned must be in the JSON format
    defined by the chop-dbhi/data-models package. The generated diagram is
    saved to the named output file.

    Usage: erd.py [options] <model> <version> <outfile>

    Options:
        -h --help            Show this screen.
        -u URL --url=URL     Retrieve model JSON from this URL instead of the
                             default or environment-variable-passed URL.

    """  # noqa

    from docopt import docopt

    # Ignore command name if called from command line.
    argv = argv or sys.argv[1:]

    args = docopt(usage, argv=argv, version=__version__)

    url = args['--url'] or get_url(args['<model>'], args['<version>'])
    model_json = requests.get(url).json()

    metadata = MetaData()
    make_model(model_json, metadata)

    render_er(metadata, args['<outfile>'])
Esempio n. 3
0
def main():
    """entry point of the whole application, equivalent to django's manage.py"""
    args = docopt(__doc__)
    setproctitle('socialite')

    # setup logging
    level_name = os.environ.get('DEBUG', 'INFO')
    level = getattr(logging, level_name)
    daiquiri.setup(level=level, outputs=('stderr', ))

    if args.get('web'):
        loop = asyncio.get_event_loop()
        app = create_app(loop)
        web.run_app(app, host='127.0.0.1', port=8000)
    elif args.get('init'):
        loop = asyncio.get_event_loop()
        loop.run_until_complete(init(settings))
    elif args.get('database') and args.get('migrate'):
        directory = Path(__file__) / '..' / 'migrations'
        directory = directory.resolve()
        directory = str(directory)
        yoyo([
            '--no-config-file',
            '-b',
            'apply',
            '--database',
            settings.DSN,
            directory,
        ])
    elif args.get('database') and args.get('diagram'):
        render_er(settings.DSN, 'socialite-diagram.png')
    else:
        print('Use --help to know more')
Esempio n. 4
0
def create_table(engine):
    event.listen(
        Base.metadata, "before_create", DDL(f"CREATE SCHEMA IF NOT EXISTS {SCHEMA}")
    )
    Base.metadata.create_all(engine)

    render_er(os.environ.get("CONNECTION_STRING"), "static/drugbank_schema.png")
Esempio n. 5
0
def create_with_eralchemy(image_path: Path):
    # SEE https://github.com/Alexis-benoist/eralchemy

    from eralchemy import render_er

    for ext in (".png", ".svg"):
        render_er(metadata, str(image_path.with_suffix(ext)))
Esempio n. 6
0
    def save_layout(self, filename: str):
        """
        Save the layout of the database to file.

        Args:
            filename (str): Filetypes are png, dot, er (markdown), and pdf.
        """
        from eralchemy import render_er

        render_er(self.metadata, filename)
Esempio n. 7
0
def erd():
    """ Create an ERD of the current data model """
    import os
    from eralchemy import render_er
    from dataservice.api.participant.models import Participant

    if not os.path.isdir('docs'):
        os.mkdir('docs')

    render_er(Participant, os.path.join('docs', 'erd.png'))
Esempio n. 8
0
def main():
    database_config = read_config(database_config_template(),
                                  filter_section='sqlalchemy')
    setup_db(database_config)

    render_er(
        "{}://{}:{}@{}:{}/{}".format(database_config['drivername'],
                                     database_config['username'],
                                     database_config['password'],
                                     database_config['host'],
                                     database_config['port'],
                                     database_config['database']),
        os.path.join('..', '_static', 'img', 'schema_db.png'))
Esempio n. 9
0
def drawerd(image_name, publish):
    """
        Generates ERD in /temp/<image_name>
    """
    # TODO : add publishing functionality once GCP access is setup
    from eralchemy import render_er

    pathlib.Path("temp").mkdir(parents=True, exist_ok=True)
    render_er(db.Model, os.path.join("temp", image_name))
    print(
        f"Diagram created : {os.path.join(os.path.curdir, 'temp', image_name)}"
    )
    if publish:
        upload_blob("<your_bucket_goes_here>", f"temp/{image_name}", "erd.png")
Esempio n. 10
0
def main(argv=sys.argv):
    if len(argv) < 3:
        usage(argv)
    config_uri = argv[1]
    output_file = argv[2]
    options = parse_vars(argv[3:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)
    
    durl = os.environ.get("DATABASE_URL") #heroku
    if durl:
        settings['sqlalchemy.url']=durl
        
    from eralchemy import render_er
    ## Draw from SQLAlchemy base
    render_er(settings.get("sqlalchemy.url"), output_file)
Esempio n. 11
0
class Planetas(Base):
    __tablename__ = 'planetas'
    # Here we define columns for the table address.
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    diameter = Column(String(250)
    population = Column(String(250), nullable=False)
    terrain = Column(String(250), nullable=False)
  
class User(Base):
    __tablename__ = 'user'
    # Here we define columns for the table address.
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)
    mail= Column(String(250), nullable=False)
    password = Column(String(250), nullable=False)

class Favoritos(Base):
    __tablename__ = 'planetas'
    # Here we define columns for the table address.
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    user_id = Column(String(250)
    planeta_id = Column(String(250), nullable=False)
    persona_id = Column(String(250), nullable=False)
    

    def to_dict(self):
        return {}

## Draw from SQLAlchemy base
render_er(Base, 'diagram.png')
Esempio n. 12
0
    def erd(self, line, cell=''):
        '''Format.'''

        parser = ArgumentParser()
        parser.add_argument('-o', '--output_type', default='svg')
        parser.add_argument('-f', '--filestub', default='erd_from_db')
        parser.add_argument('-c', '--connection_string', default=None)
        parser.add_argument('-i', '--include_tables', default=None)
        parser.add_argument('-x', '--exclude_tables', default=None)

        args = parser.parse_args(shlex.split(line))

        if args.connection_string is None: return
        fname = '{}.{}'.format(args.filestub, args.output_type)

        include_tables = [i for i in reader([args.include_tables])
                          ][0] if args.include_tables is not None else None
        exclude_tables = [i for i in reader([args.exclude_tables])
                          ][0] if args.exclude_tables is not None else None
        retval = render_er(args.connection_string,
                           fname,
                           include_tables=include_tables,
                           exclude_tables=exclude_tables)
        #return SVG(filename=fname)
        #retval is a graphviz object with a _repr_svg_() method
        return retval
Esempio n. 13
0
def er(directory):
    """Generate entity-relation diagrams for each package."""
    try:
        import eralchemy
    except ImportError:
        click.echo('Can not import eralchemy. Try `pip install eralchemy`.')
        return sys.exit(1)

    os.makedirs(directory, exist_ok=True)
    it = tqdm(sorted(MANAGERS.items()), leave=False)
    for name, manager_cls in it:
        base = getattr(manager_cls, '_base', None)
        if base is None:
            it.write(f'{name} does not have a SQLAlchemy base')
            continue
        it.write(f'generating for {name}')
        eralchemy.render_er(base, os.path.join(directory, f'{name}_erd.png'))
Esempio n. 14
0
def write(model, model_version, output, service):
    """Generate entity relationship diagram for the data model specified.

    Arguments:
      model          Model to generate DDL for.
      model_version  Model version to generate DDL for.
      output         Output file for ERD.
      service        Base URL of the data models service to use.

    Raises:
        ImportError, if erlalchemy cannot be imported
    """  # noqa

    metadata = MetaData()
    model_json = get_model_json(model, model_version, service)
    make_model(model_json, metadata)

    from eralchemy import render_er

    render_er(metadata, output)
Esempio n. 15
0
def erd(config_name=None, filepath=None):
    """
    Generate an entity relationship diagram from the database

    :param config_name: a dict key which specifies which Config class to select
    in config.config dict. The Config class encapsulates all db parameters such
    as user, pw, host, port, and name of the db. See config.py for more info.
    :param filepath: Path to output ERD file
    """
    config = _select_config(config_name)

    doc_dir = os.path.join(os.path.dirname(ROOT_DIR), 'docs')
    if not filepath:
        filepath = os.path.join(doc_dir, 'erd.png')

    # Draw from database
    print(f'Generating ERD for {config.PG_HOST}/{config.PG_NAME} ...')
    render_er(config.SQLALCHEMY_DATABASE_URI, filepath)

    print(f'Entity relationship diagram generated: {filepath}')
Esempio n. 16
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--out", help="output pdf file.")
    args = parser.parse_args()

    os.getcwd()
    current = datetime.now(tz=JST())
    if args.out is None:
        out_target = "%s/eralchemy/%s-%s.pdf" % (
            os.getcwd(), db_name, current.strftime("%Y-%m-%d_%H%M%S"))
    else:
        out_target = args.out

    df = open("exclude.yml", "r+")
    excludes = " ".join(yaml.load(df)['exclude_tables'])
    connect_url = "postgresql+psycopg2://%s:%s@%s:%s/%s" % (
        db_user, db_password, db_host, db_port, db_name)

    logger.info("start : %s ---> %s" % (connect_url, out_target))

    render_er(connect_url, out_target, exclude=excludes)
Esempio n. 17
0
def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)

    settings = get_appsettings(config_uri, options=options)
    # passwords_config_path = helpers.get_passwords_config_path(global_config['__file__'])
    passwords_config_path = helpers.get_passwords_config_path(config_uri)
    if os.path.isfile(passwords_config_path):
        passwords_settings = helpers.load_config(passwords_config_path)
        settings = helpers.dicts_merge(passwords_settings.get('app:main', {}),
                                       settings)

    # sql_engine = engine_from_config(settings, 'sqlalchemy.')
    # # DBSession.configure(bind=engine)
    # Base.metadata.bind = sql_engine
    erd_file_path = path.realpath(
        path.join(server_path, '..', 'dia', erd_file_name))
    eralchemy.render_er(Base, erd_file_path)
    print('file generated. see "' + erd_file_path + '"')
Esempio n. 18
0

class Edge(Base):
    __tablename__ = 'edge'

    lower_id = Column(Integer, ForeignKey('node.node_id'), primary_key=True)

    higher_id = Column(Integer, ForeignKey('node.node_id'), primary_key=True)

    lower_node = relationship(Node,
                              primaryjoin=lower_id == Node.node_id,
                              backref='lower_edges')
    higher_node = relationship(Node,
                               primaryjoin=higher_id == Node.node_id,
                               backref='higher_edges')

    # here we have lower.node_id <= higher.node_id
    def __init__(self, n1, n2):
        if n1.node_id < n2.node_id:
            self.lower_node = n1
            self.higher_node = n2
        else:
            self.lower_node = n2
            self.higher_node = n1


if __name__ == '__main__':
    render_er(Base, 'graph.png')
    render_er(Base, 'graph.dot')
    render_er(Base, 'graph.pdf')
Esempio n. 19
0
    user = relationship(User)


class Comments(Base):
    __tablename__ = 'comments'
    id = Column(Integer, unique=True, primary_key=True)
    text = Column(String)
    user_id = Column(Integer, ForeignKey("user.id"))
    post_id = Column(Integer, ForeignKey("post.id"))
    user = relationship(User)
    post = relationship(Post)


class Followers(Base):
    __tablename__ = 'followers'
    id = Column(Integer, unique=True, primary_key=True)
    user_id = Column(Integer, ForeignKey("user.id"))
    follower_by = Column(Integer, ForeignKey("user.id"))
    user = relationship(User)

    def to_dict(self):
        return {}


## Draw from SQLAlchemy base
try:
    result = render_er(Base, 'diagram.png')
    print("Success! Check the diagram.png file")
except Exception as e:
    print("There was a problem genering the diagram")
    raise e
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from eralchemy import render_er

Base = declarative_base()

class Person(Base):
    __tablename__ = 'person'
    # Here we define columns for the table person
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

class Address(Base):
    __tablename__ = 'address'
    # Here we define columns for the table address.
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    street_name = Column(String(250))
    street_number = Column(String(250))
    post_code = Column(String(250), nullable=False)
    person_id = Column(Integer, ForeignKey('person.id'))
    person = relationship(Person)

    def to_dict(self):
        return {}

## Draw from SQLAlchemy base
render_er(Base, 'diagram.png')
Esempio n. 21
0
            "text": self.text,
            "icon": self.icon,
            "like": self.like,
        }


class Direct(Base):
    __tablename__ = 'direct'
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('user.id'))
    messege_id = Column(Integer, ForeignKey('messege.id'))# tabla no existe
    userOtro_id = Column(Integer, ForeignKey('userOtro.id'))# tabla no existe
    photo_id = Column(Integer, ForeignKey('photo.id'))# tabla no existe
    text = Column(String(250), nullable=False)
    icon = Column(String(250), nullable=False)

    def serialize(self): 
        return {
            "id": self.id,
            "user_id": self.user_id,
            "messege_id": self.messege_id,
            "userOtro_id": self.userOtro_id,
            "photo_id": self.photo_id,
            "text": self.text,
            "icon": self.icon
        }


## Draw from SQLAlchemy base
render_er(Base, 'diagramUML.png')
Esempio n. 22
0
class Edge(Base):
    __tablename__ = 'edge'

    lower_id = Column(Integer,
                        ForeignKey('node.node_id'),
                        primary_key=True)

    higher_id = Column(Integer,
                        ForeignKey('node.node_id'),
                        primary_key=True)

    lower_node = relationship(Node,
                                primaryjoin=lower_id==Node.node_id,
                                backref='lower_edges')
    higher_node = relationship(Node,
                                primaryjoin=higher_id==Node.node_id,
                                backref='higher_edges')

    # here we have lower.node_id <= higher.node_id
    def __init__(self, n1, n2):
        if n1.node_id < n2.node_id:
            self.lower_node = n1
            self.higher_node = n2
        else:
            self.lower_node = n2
            self.higher_node = n1


render_er(Base, 'graph.png')
Esempio n. 23
0
                     ForeignKey(Post.id, ondelete='CASCADE'),
                     nullable=False)

    parent_id = Column(Integer,
                       ForeignKey("comments.id", ondelete='CASCADE'))

    comment = Column(UnicodeText)
    date_created = Column(DateTime, default=datetime.utcnow)
    score = Column(Integer, default=1)
    votes = Column(Text)

    author = relation(User, innerjoin=True, lazy="joined")

    post = relation(Post, innerjoin=True, lazy="joined")

    parent = relation('Comment', remote_side=[id])


class Tag(Base):
    __tablename__ = "tags"

    id = Column(Integer, primary_key=True)
    slug = Column(Unicode(80), unique=True)

    _name = Column("name", Unicode(80), unique=True)


if __name__ == '__main__':
    from eralchemy import render_er
    render_er(Base, 'newsmeme.pdf')
Esempio n. 24
0
# -*- coding: 850 -*-
from eralchemy import render_er
import getpass
import psycopg2

salida = False

while not salida :
   print 'Entre las credenciales del servidor--->'
   servidor = raw_input("Entre servidor : ")
   puerto = raw_input("Entre el puerto : ")
   basedatos = raw_input("Entre el la base de datos: ")
   usuario = raw_input("Entre el usuario: ")
   contrasena = getpass.getpass('Password')
   try:
       cadena = 'postgresql+psycopg2://'+usuario+':'+contrasena+'@'+servidor+':'+puerto+'/'+basedatos
       render_er(cadena, 'salida.png')
       print 'El modelo se encuentra en el archivo salida.png'
       salida=True
   except Exception, e:
       print u'Verifique los parametros de conexión'
       print str(e)
Esempio n. 25
0
    lower_id = Column(Integer,
                      ForeignKey('node.node_id'),
                      primary_key=True)

    higher_id = Column(Integer,
                       ForeignKey('node.node_id'),
                       primary_key=True)

    lower_node = relationship(Node,
                              primaryjoin=lower_id == Node.node_id,
                              backref='lower_edges')
    higher_node = relationship(Node,
                               primaryjoin=higher_id == Node.node_id,
                               backref='higher_edges')

    # here we have lower.node_id <= higher.node_id
    def __init__(self, n1, n2):
        if n1.node_id < n2.node_id:
            self.lower_node = n1
            self.higher_node = n2
        else:
            self.lower_node = n2
            self.higher_node = n1


if __name__ == '__main__':
    render_er(Base, 'graph.png')
    render_er(Base, 'graph.dot')
    render_er(Base, 'graph.pdf')
if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description='SAP Ariba ER Diagram generator')

    parser.add_argument('--document_type',
                        type=str,
                        default='',
                        help='Example value: S4ApprovalFlowFact')

    args = parser.parse_args()

    er_markdown = ""

    if args.document_type != "":
        er_markdown = generate_er_markdown(
            document_type_entities(args.document_type))
    else:
        er_markdown = generate_er_markdown()

    # Generate output file name
    document_filename = "_" + args.document_type if args.document_type != "" else ""
    er_markdown_filename = f"analytical_reporting{document_filename}"

    # Store Entity Relationship markdown
    with open(er_markdown_filename + ".er", "w") as f:
        f.write(er_markdown)

    ## Draw from Entity Relationship markdown to PDF
    render_er(er_markdown_filename + ".er", er_markdown_filename + ".pdf")
Esempio n. 27
0
def get_tables():
    return query_db("SELECT name FROM sqlite_master WHERE type='table'")

def get_table_content(t):
    header = [c[1] for c in query_db("PRAGMA table_info('" + t + "')")]
    content = query_db("SELECT * FROM " + t + " LIMIT 10")
    return [header] + content

def get_table_numbers(t):
    return query_db("SELECT count(*) FROM " + t, one=True)[0]

# init

DB_NAME = get_db_name()
print 'Database:', DB_NAME
render_er('sqlite:///' + DB_NAME, 'static/schema.png')

# routes

@app.route('/')
def root():
    return app.send_static_file('index.html')

@app.route('/overview/')
def overview():
    tables = [{"name": t[0], "records": 0} for t in get_tables()]
    for i in range(len(tables)):
        tables[i]["records"] = get_table_numbers(tables[i]["name"])
    return jsonify(results=tables)

@app.route('/tables/')
from eralchemy import render_er
from db.config import Config
import os.path

image_path = os.path.dirname(__file__)+'/../db/docs/'
## Draw from SQLAlchemy base
render_er(Config.SQLALCHEMY_DATABASE_URI, image_path+'erd_from_sqlalchemy.png')
Esempio n. 29
0
def example():
    render_er(Base, 'simple.png')
    render_er(Base, 'simple.dot')
    render_er(Base, 'simple.pdf')
    render_er(Base, 'simple.er')
Esempio n. 30
0
# ERAlchemy
# Github: https://github.com/Alexis-benoist/eralchemy
# Pypi: https://pypi.org/project/ERAlchemy/
import os
import sys
sys.path.append(os.getcwd())

from eralchemy import render_er
from app.core.config import settings

# Draw from database
render_er(settings.SQLALCHEMY_DATABASE_URI,
          'docs/schemas/entity-relation_diagram.png')
Esempio n. 31
0
__author__ = 'anthony'
# -*- coding: 850 -*-
from eralchemy import render_er
import getpass
import psycopg2

salida = False

while not salida:
    print('Entre las credenciales del servidor--->')
    servidor = raw_input("localhost")
    puerto = raw_input("5433")
    basedatos = raw_input("EjemploBaseInsti")
    usuario = raw_input("postgres")
    contrasena = getpass.getpass('Holapostgres')
    try:
        cadena = 'postgresql+psycopg2://' + usuario + ':' + contrasena + '@' + servidor + ':' + puerto + '/' + basedatos
        render_er(cadena, 'salida.png')
        print('El modelo se encuentra en el archivo EjemploBase.png')
        salida = True
    except Exception as e:
        print('Verifique los parametros de conexión')
        print(str(e))
Esempio n. 32
0
                )
                conn = engine.connect()
                conn.execute("commit")
                try:
                    conn.execute("create database tmp")
                except:
                    conn.execute("drop database tmp")
                    conn.execute("create database tmp")

                engine = create_engine(
                    "mysql+mysqlconnector://<username>:<password>@localhost/tmp?charset=utf8"
                )
                conn = engine.connect()
                import_sql(conn, commands[1])
                render_er(
                    "mysql+mysqlconnector://root:qqwe@localhost/tmp?charset=utf8",
                    'erd_from_sqlite.png')
                conn.execute("drop database tmp")
                conn.close()
                image = Image.open('erd_from_sqlite.png')
                image.show()
            else:
                print('\nInvalid Path\n')

        elif (commands[0] == 'query'):
            if not dbms:
                print('\nthere is no database yet\n')
            elif (commands[1] == '-e'):
                ###
                query_db = deepcopy(dbms[0])
                ###
Esempio n. 33
0
def main():
    output = (current_dir /
              "../doc/img/postgres-database-models.svg").resolve()
    render_er(metadata, str(output))
Esempio n. 34
0
from eralchemy import render_er
import re
import os

def find_filepath_from_directory(directory, filename):
    regex = re.compile(r'(%s)$' % filename)
    for root, dirs, files in os.walk(directory):
        for file in files:
            if regex.match(file):
                return os.path.join(root, file)


def_file_path = find_filepath_from_directory('.', 'table_definition.er')
def_file_directory = os.path.dirname(def_file_path)
render_er(def_file_path, os.path.join(def_file_directory, "table_definition.png"))

Esempio n. 35
0
#"edited": "2014-12-20T21:26:24.783000Z",
#"url": "http://swapi.dev/api/starships/9/"
#}


class Username(Base):
    __tablename__ = 'username'
    id = Column(Integer, primary_key=True)
    username = Column(String(50), unique=True, nullable=False)
    email = Column(String(100), unique=True, nullable=False)

    def to_dict(self):
        return {}


class Favorites(Base):
    __tablename__ = 'favorites'
    user_id = Column(Integer, ForeignKey(Username.id))
    id = Column(Integer, primary_key=True)
    name = Column(String(60))
    planet_name = Column(String(60), ForeignKey(Planet.name))
    person_name = Column(String(60), ForeignKey(Character.name))
    startship = Column(String(60), ForeignKey(StartShip.name))

    def to_dict(self):
        return {}


## Draw from SQLAlchemy base
render_er(Base, 'diagram.png')
Esempio n. 36
0
def dump_schema(outf):
    from wikiparse.db.tables import metadata
    from eralchemy import render_er

    render_er(metadata, outf)