Set up databases using create_all().

    :param eng: The sqlalchemy engine to use.
    :param list modules: A list of modules with models inside.
    :param list models:  A list of models to setup.
499189
def setup_database(eng, modules=None, models=None):
    
    if modules is not None:
        for modu in modules:
            for m in modu.__all__:
                getattr(modu, m).metadata.create_all(eng)
    if models is not None:
        for mod in models:
            mod.metadata.create_all(eng)
1315811
def create_db(app, appbuilder):
    
    from flask_appbuilder.models.sqla import Base

    _appbuilder = import_application(app, appbuilder)
    engine = _appbuilder.get_session.get_bind(mapper=None, clause=None)
    Base.metadata.create_all(engine)
    click.echo(click.style("DB objects created", fg="green"))
216083
def init_db(uri, base, **kwargs):
    
    engine = create_engine(uri, **kwargs)
    base.metadata.create_all(engine)
    return engine
244967
def create_db():
    "  "

    from ..ext import db
    db.create_all()

    # Evolution support
    from flask import current_app
    from flaskext.evolution import db as evolution_db
    evolution_db.init_app(current_app)
    evolution_db.create_all()

    print "Database created successfuly"
771626
def _set_all_tables(self, schema, **kwargs):
        
        with self.transaction(**kwargs) as connection:
            kwargs['connection'] = connection
            # go through and make sure all foreign key referenced tables exist
            for field_name, field_val in schema.fields.items():
                s = field_val.schema
                if s:
                    self._set_all_tables(s, **kwargs)

            # now that we know all fk tables exist, create this table
            self.set_table(schema, **kwargs)

        return True
1096016
def _list_tables_model(self, prefix='', project=None):
    
    tset = set()

    if prefix.startswith(TEMP_TABLE_PREFIX):
        prefix = TEMP_TABLE_MODEL_PREFIX + prefix[len(TEMP_TABLE_PREFIX):]
        it = self.list_tables(project=project, prefix=prefix)
    else:
        it = self.list_tables(project=project, prefix=TABLE_MODEL_PREFIX + prefix)
        if TEMP_TABLE_PREFIX.startswith(prefix):
            new_iter = self.list_tables(project=project, prefix=TEMP_TABLE_MODEL_PREFIX)
            it = itertools.chain(it, new_iter)

    for table in it:
        if TABLE_MODEL_SEPARATOR not in table.name:
            continue
        if not table.name.startswith(TEMP_TABLE_MODEL_PREFIX) and not table.name.startswith(TABLE_MODEL_PREFIX):
            continue
        model_name, _ = table.name.rsplit(TABLE_MODEL_SEPARATOR, 1)
        if model_name.startswith(TEMP_TABLE_MODEL_PREFIX):
            model_name = TEMP_TABLE_PREFIX + model_name[len(TEMP_TABLE_MODEL_PREFIX):]
        else:
            model_name = model_name[len(TABLE_MODEL_PREFIX):]
        if model_name not in tset:
            tset.add(model_name)
            yield TablesModelObject(_odps=self, name=model_name, project=project)
762749
def init():
    
    global _users, _names
    _configure_app(app)
    _users, _names = _init_login_manager(app)
    _configure_logger()
    init_scheduler(app.config.get('SQLALCHEMY_DATABASE_URI'))
    db.init(app.config.get('SQLALCHEMY_DATABASE_URI'))
357875
def init_db(self):
    '''
    '''

    # The user can provide a custom string
    if self.database is None:
        self.logger.error("You must provide a database url, exiting.")
        sys.exit(1)

    self.engine = create_engine(self.database, convert_unicode=True)
    self.session = scoped_session(sessionmaker(autocommit=False,
                                               autoflush=False,
                                               bind=self.engine))

    # Database Setup
    Base.query = self.session.query_property()

    # import all modules here that might define models so that
    # they will be registered properly on the metadata.  Otherwise
    # you will have to import them first before calling init_db()
    import expfactory.database.models
    self.Base = Base
    self.Base.metadata.create_all(bind=self.engine)
706055
def from_list(cls, database, key, data, clear=False):
        
        arr = cls(database, key)
        if clear:
            arr.clear()
        arr.extend(data)
        return arr
887223
def execute_project_models_sql_scripts(force_update=False):
    
    # TODO: Remove except and use ignore_conflicts
    # on bulk_create when django 2.2. is released
    with open(MODEL_FILE, "r") as file_content:
        query = file_content.read()
        db = db_connector()
        query_result = db.execute_pandas_sql_query(query)
        db.close()
        try:
            projects = Project.objects.bulk_create(
                (Project(**vals) for vals in query_result.to_dict("records")),
                # ignore_conflicts=True available on django 2.2.
            )
            indicators = [FinancialIndicator(project=p) for p in projects]
            FinancialIndicator.objects.bulk_create(indicators)
        except IntegrityError:
            # happens when there are duplicated projects
            LOG("Projects bulk_create failed, creating one by one...")
            with transaction.atomic():
                if force_update:
                    for item in query_result.to_dict("records"):
                        p, _ = Project.objects.update_or_create(**item)
                        FinancialIndicator.objects.update_or_create(project=p)
                else:

                    for item in query_result.to_dict("records"):
                        p, _ = Project.objects.get_or_create(**item)
                        FinancialIndicator.objects.update_or_create(project=p)
197726
def create(self, request, *args, **kwargs):
        
        return self.list(request, *args, **kwargs)
932710
def _dbsetup(self):
        
        self._dbconn = sqlite3.connect(self._db_file)
        # Create table for multiplicons
        sql = '''CREATE TABLE multiplicons
                 (id, genome_x, list_x, parent, genome_y, list_y, level,
                  number_of_anchorpoints, profile_length, begin_x, end_x,
                  begin_y, end_y, is_redundant)'''
        self._dbconn.execute(sql)
        # Create table for multiplicons ('order' appears to be reserved)
        sql = '''CREATE TABLE segments
                 (id, multiplicon, genome, list, first, last, ord)'''
        self._dbconn.execute(sql)
        self._dbconn.commit()
1314872
def create_app():
    
    
    # Setup Flask app and app.config
    app = Flask(__name__)
    app.config.from_object(__name__+'.ConfigClass')

    # Initialize Flask extensions
    db = SQLAlchemy(app)                            # Initialize Flask-SQLAlchemy

    # Define the User data-model. Make sure to add flask_user UserMixin !!!
    class User(db.Model, UserMixin):
        __tablename__ = 'users'
        id = db.Column(db.Integer, primary_key=True)

        # User authentication information
        username = db.Column(db.String(50, collation='NOCASE'), nullable=False, unique=True)
        password = db.Column(db.String(255), nullable=False, server_default='')

        # User information
        active = db.Column('is_active', db.Boolean(), nullable=False, server_default='0')
        first_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')
        last_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')

        # Relationship
        user_emails = db.relationship('UserEmail')


    # Define UserEmail DataModel.
    class UserEmail(db.Model):
        __tablename__ = 'user_emails'
        id = db.Column(db.Integer, primary_key=True)
        user_id = db.Column(db.Integer, db.ForeignKey('users.id'))

        # User email information
        email = db.Column(db.String(255, collation='NOCASE'), nullable=False, unique=True)
        email_confirmed_at = db.Column(db.DateTime())
        is_primary = db.Column(db.Boolean(), nullable=False, default=False)

        # Relationship
        user = db.relationship('User', uselist=False)


    # Create all database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db, User, UserEmailClass=UserEmail)        # Register the User data-model
    user_manager = UserManager(db_adapter, app)     # Initialize Flask-User

    # The Home page is accessible to anyone
    @app.route('/')
    def home_page():
        return render_template_string("""
            {% extends "flask_user_layout.html" %}
            {% block content %}
                <h2>Home page</h2>
                <p>This page can be accessed by anyone.</p><br/>
                <p><a href={{ url_for('home_page') }}>Home page</a> (anyone)</p>
                <p><a href={{ url_for('member_page') }}>Members page</a> (login required)</p>
            {% endblock %}
            """)

    # The Members page is only accessible to authenticated users
    @app.route('/members')
    @login_required                                 # Use of @login_required decorator
    def member_page():
        return render_template_string("""
            {% extends "flask_user_layout.html" %}
            {% block content %}
                <h2>Members page</h2>
                <p>This page can only be accessed by authenticated users.</p><br/>
                <p><a href={{ url_for('home_page') }}>Home page</a> (anyone)</p>
                <p><a href={{ url_for('member_page') }}>Members page</a> (login required)</p>
            {% endblock %}
            """)

    return app
1322482
def list_():  # pylint: disable=redefined-builtin
    
    load_dbenv_if_not_loaded(
    )  # Important to load the dbenv in the last moment

    from aiida.orm.querybuilder import QueryBuilder
    from aiida.orm import DataFactory
    MultiplyParameters = DataFactory('phtools.factors')

    qb = QueryBuilder()
    qb.append(MultiplyParameters)
    results = qb.all()

    s = ""
    for result in results:
        obj = result[0]
        s += "{}, pk: {}\n".format(str(obj), obj.pk)
    sys.stdout.write(s)
594625
def create(self, data, fields=[], models={}):
        '''
        
        '''
        if not fields: fields = self.fields
        if not models and hasattr(self, 'models'): models = self.models
        for field in fields:
            setattr(self,field,None)
        if not data: return None
        for k, v in data.iteritems():
            if type(v) in (str, unicode):
                v = v.strip()
            if models and k in models:
                if type(v) == dict:
                    lists = []
                    for k2, v2 in v.iteritems():
                        if type(v2) == list:
                            for d in v2:
                                model = models[k]()
                                lists.append(model.create(d))
                    if not lists:
                        model = models[k]()
                        v = model.create(v)
                    else:
                        v = lists
                else:
                    model = models[k]()
                    v = model.create(v)
            setattr(self,k,v)
        return self
184477
def _set_module_names_for_sphinx(modules: List, new_name: str):
    
    for obj in modules:
        obj.__module__ = new_name
467142
def _expose_models(cls):
        
        if db._IS_OK_:
            register_models(**{m.__name__: m
                               for m in db.Model.__subclasses__()
                               if not hasattr(models, m.__name__)})