Ejemplo n.º 1
0
    def setUp(self):
        import elixir as el
        import transaction
        el.metadata = sa.MetaData('sqlite:///:memory:')

        class DBTestCls1(el.Entity):
            name = el.Field(el.String)
        class DBTestCls2(el.Entity):
            id = el.Field(el.String, primary_key=True)
        class DBTestCls3(el.Entity):
            id1 = el.Field(el.Integer, primary_key=True)
            id2 = el.Field(el.Integer, primary_key=True)
        
        self.DBTestCls1 = DBTestCls1
        self.DBTestCls2 = DBTestCls2
        self.DBTestCls3 = DBTestCls3
    
        el.setup_all()
        el.metadata.create_all()

        self.DBTestCls1(id=1)
        self.DBTestCls2(id='bob')
        transaction.commit()

        testapi.setup()
Ejemplo n.º 2
0
 def setup_model():
     from sqlalchemy.orm import configure_mappers
     from camelot.core.sql import metadata
     metadata.bind = settings.ENGINE()
     import camelot.model.party
     import camelot.model.authentication
     import camelot.model.i18n
     import camelot.model.fixture
     import camelot.model.memento
     import camelot_example.model
     #
     # setup_all is only needed for those models that rely on elixir
     #
     from elixir import setup_all
     setup_all()
     #
     # create the tables for all models, configure mappers first, to make
     # sure all deferred properties have been handled, as those could
     # create tables or columns
     #
     configure_mappers()
     metadata.create_all()
     from camelot.model.authentication import update_last_login
     update_last_login()
     #
     # Load sample data with the fixure mechanism
     #
     from camelot_example.fixtures import load_movie_fixtures
     load_movie_fixtures()
     #
     # setup the views
     #
     from camelot_example.view import setup_views
     setup_views()
Ejemplo n.º 3
0
 def __init__(self, filename):
     db_url = 'sqlite:///' + filename
     metadata.bind = db_url
     #metadata.bind.echo = True
     setup_all()
     if not os.path.exists(filename):
         create_all()
Ejemplo n.º 4
0
def updateEntry(job):
    """
    Fetch the existing entry for job and update it.
    """
    # Define the database connection.
    elixir.metadata.bind = DATABASE_CONNECTION_STR
    elixir.metadata.bind.echo = False
    elixir.setup_all()

    # Fix timestamps.
    _convertTimeStamps(job)

    # Update the old entry. Remember that the information on the number of job
    # instances is only available to the prepare_job hook. This means that we
    # should not update entry.Instances.
    entry = Blackboard.query.filter_by(GlobalJobId=job.GlobalJobId).one()
    modified = 0

    attrs = _get_job_attrs_for_db(job)
    for key in attrs.keys():
        if(key == "Instances"):
            # Never update Instances.
            continue

        # _get_job_attrs_for_db garantees that we are only seeing attributes
        # which are in the table definition.
        if(attrs[key] != getattr(entry, key)):
            setattr(entry, key, attrs[key])
            modified += 1
    if(modified):
        elixir.session.commit()
    return
Ejemplo n.º 5
0
 def __getattr__(self, name):
     elixir.setup_all()
     #FIXME: it's possible to get an infinite loop here if setup_all doesn't
     #remove the triggers for this entity. This can happen if the entity is
     #not in the `entities` list for some reason.
     proxied_attr = getattr(self.class_, self.attrname)
     return getattr(proxied_attr, name)
Ejemplo n.º 6
0
 def __init__(self, filename):
     db_url = 'sqlite:///' + filename
     metadata.bind = db_url
     #metadata.bind.echo = True
     setup_all()
     if not os.path.exists(filename):
         create_all()
    def setup_database():
        init_model(engine)
        teardownDatabase()
        elixir.setup_all(True)
        # Creating users

        user = User()
        user.user_name = compat.u('rms')
        user.password = compat.u('freedom')
        DBSession.add(user)

        user = User()
        user.user_name = compat.u('linus')
        user.password = compat.u('linux')
        DBSession.add(user)

        user = User()
        user.user_name = compat.u('sballmer')
        user.password = compat.u('developers')
        DBSession.add(user)

        # Plus a couple of users without groups
        user = User()
        user.user_name = compat.u('guido')
        user.password = compat.u('phytonic')
        DBSession.add(user)

        user = User()
        user.user_name = compat.u('rasmus')
        user.password = compat.u('php')
        DBSession.add(user)

        DBSession.commit()
Ejemplo n.º 8
0
def setup_model():
    import camelot.model
    from elixir import setup_all
    import model
    setup_all(create_tables=True)
    from camelot.model.authentication import updateLastLogin
    updateLastLogin()
Ejemplo n.º 9
0
def fetchData(username, dataset, mindate=None, maxdate=None, exitcode=0,
              status='Exited', keys=KEYS):
    """
    Do what I say :-) But remove None values.
    """
    # Define the database connection.
    elixir.metadata.bind = DATABASE_CONNECTION_STR
    elixir.session.configure(bind=elixir.metadata.bind)
    elixir.metadata.bind.echo = False
    elixir.setup_all()

    fields = [getattr(Blackboard, k) for k in keys]

    query = elixir.session.query(*fields)

    query = query.filter_by(Owner=unicode(username))
    query = query.filter_by(Dataset=unicode(dataset))
    query = query.filter_by(ExitCode=exitcode)
    query = query.filter_by(JobState=unicode(status))
    if(mindate is not None):
        query = query.filter(Blackboard.JobStartDate>=mindate)
    if(maxdate is not None):
        query = query.filter(Blackboard.JobStartDate<=maxdate)
    query = query.order_by(desc(Blackboard.JobStartDate))
    return(query.all())
Ejemplo n.º 10
0
def updateEntry(job):
    """
    Fetch the existing entry for job and update it.
    """
    # Define the database connection.
    elixir.metadata.bind = DATABASE_CONNECTION_STR
    elixir.metadata.bind.echo = False
    elixir.setup_all()

    # Fix timestamps.
    _convertTimeStamps(job)

    # Update the old entry. Remember that the information on the number of job
    # instances is only available to the prepare_job hook. This means that we
    # should not update entry.Instances.
    entry = Blackboard.query.filter_by(GlobalJobId=job.GlobalJobId).one()
    modified = 0

    attrs = _get_job_attrs_for_db(job)
    for key in attrs.keys():
        if (key == "Instances"):
            # Never update Instances.
            continue

        # _get_job_attrs_for_db garantees that we are only seeing attributes
        # which are in the table definition.
        if (attrs[key] != getattr(entry, key)):
            setattr(entry, key, attrs[key])
            modified += 1
    if (modified):
        elixir.session.commit()
    return
Ejemplo n.º 11
0
def initDB(drop=False):

    from elixir import metadata, setup_all, drop_all, create_all
    from genericpath import exists
    from os import makedirs
    from posixpath import expanduser

    DB_NAME = "stockflow.sqlite"
    log = logging.getLogger(__name__)
    log.info("Inicializando o Core")
    dbpath = expanduser("~/.stockflow/")
    if not exists(dbpath):
        try:
            makedirs(dbpath)
        except OSError:
            log.warning("Nao foi possivel criar os diretorios, \
                usando o home do usuário.")
            dbpath = expanduser("~")

    metadata.bind = "".join(("sqlite:///", dbpath, DB_NAME))
    metadata.bind.echo = False

    setup_all()
    if(drop):
        drop_all()


    if not exists("".join((dbpath, DB_NAME))) or drop:
        log.debug("Criando tabelas...")
        create_all()
Ejemplo n.º 12
0
def setup_model():
    import camelot.model
    import example.model
    from elixir import setup_all
    from camelot.model.authentication import updateLastLogin
    setup_all(create_tables=True)
    updateLastLogin()
Ejemplo n.º 13
0
def setup():
    """ Setup the database and create the tables that don't exists yet """
    from elixir import setup_all, create_all
    from couchpotato import get_engine

    setup_all()
    create_all(get_engine())
Ejemplo n.º 14
0
def setup_database():
    init_model(engine)
    teardownDatabase()
    elixir.setup_all(True)
    # Creating users

    user = User()
    user.user_name = u'rms'
    user.password = u'freedom'
    DBSession.save(user)

    user = User()
    user.user_name = u'linus'
    user.password = u'linux'
    DBSession.save(user)

    user = User()
    user.user_name = u'sballmer'
    user.password = u'developers'
    DBSession.save(user)

    # Plus a couple of users without groups
    user = User()
    user.user_name = u'guido'
    user.password = u'phytonic'
    DBSession.save(user)

    user = User()
    user.user_name = u'rasmus'
    user.password = u'php'
    DBSession.save(user)

    DBSession.commit()
    def setup_database():
        init_model(engine)
        teardownDatabase()
        elixir.setup_all(True)
        # Creating users

        user = User()
        user.user_name = compat.u('rms')
        user.password = compat.u('freedom')
        DBSession.add(user)

        user = User()
        user.user_name = compat.u('linus')
        user.password = compat.u('linux')
        DBSession.add(user)

        user = User()
        user.user_name = compat.u('sballmer')
        user.password = compat.u('developers')
        DBSession.add(user)

        # Plus a couple of users without groups
        user = User()
        user.user_name = compat.u('guido')
        user.password = compat.u('phytonic')
        DBSession.add(user)

        user = User()
        user.user_name = compat.u('rasmus')
        user.password = compat.u('php')
        DBSession.add(user)

        DBSession.commit()
Ejemplo n.º 16
0
 def __getattr__(self, name):
     elixir.setup_all()
     #FIXME: it's possible to get an infinite loop here if setup_all doesn't
     #remove the triggers for this entity. This can happen if the entity is
     #not in the `entities` list for some reason.
     proxied_attr = getattr(self.class_, self.attrname)
     return getattr(proxied_attr, name)
Ejemplo n.º 17
0
def run_scan_setup(cam_index=0):
    setup_all(True)

    cam = cv.CreateCameraCapture(cam_index)
    scan_card.setup_windows()

    # main loop
    run = True
    while run:
        # for now, name the next box as the largest integer box name, +1
        current_max_box = session.query(func.max(sqlalchemy.cast(InvCard.box, sqlalchemy.Integer))).first()[0]
        if current_max_box is None:
            # if there is no current box, just start at 1
            next_box = 1
        else:
            next_box = current_max_box + 1

        print "box to scan[%02d]: " % next_box,
        answer = ("%s" % raw_input().rstrip())
        if answer != '' and answer != 'q':
            next_box = answer
            capture_box(cam, next_box)
        if answer == 'q':
            run = False
            run_match()
Ejemplo n.º 18
0
def initialize(dbname='SmartCommunity', db_hostname="localhost", setup=True):
    cengine = create_engine('mysql://*****:*****@' + db_hostname + '/' +
                            dbname,
                            pool_recycle=7200)
    metadata.bind = cengine
    metadata.bind.echo = True
    setup_all(setup)
Ejemplo n.º 19
0
def setup_model():
    #import camelot.model
    from elixir import setup_all
    import model
    setup_all(create_tables=True)
    from camelot.model.authentication import updateLastLogin
    updateLastLogin()
Ejemplo n.º 20
0
 def setup_model():
     from sqlalchemy.orm import configure_mappers
     from camelot.core.sql import metadata
     metadata.bind = settings.ENGINE()
     import camelot.model.party
     import camelot.model.authentication
     import camelot.model.i18n
     import camelot.model.fixture
     import camelot.model.memento
     import camelot_example.model
     #
     # setup_all is only needed for those models that rely on elixir
     #
     from elixir import setup_all
     setup_all()
     #
     # create the tables for all models, configure mappers first, to make
     # sure all deferred properties have been handled, as those could
     # create tables or columns
     #
     configure_mappers()
     metadata.create_all()
     from camelot.model.authentication import update_last_login
     update_last_login()
     # 
     # Load sample data with the fixure mechanism
     #
     from camelot_example.fixtures import load_movie_fixtures
     load_movie_fixtures()
     #
     # setup the views
     #
     from camelot_example.view import setup_views
     setup_views()
Ejemplo n.º 21
0
    def create_storage(self):

        try:
            server = DatabaseServer(self.server_config)
        except:
            logger.log_error(
                'Cannot connect to the database server that the services database is hosted on %s.'
                % self.server_config.database_name)
            raise

        if not server.has_database(self.server_config.database_name):
            server.create_database(self.server_config.database_name)

        try:
            services_db = server.get_database(self.server_config.database_name)
        except:
            logger.log_error('Cannot connect to a services database on %s.' %
                             server.get_connection_string(scrub=True))
            raise

        metadata.bind = services_db.engine
        setup_all()
        create_all()

        return services_db
Ejemplo n.º 22
0
    def setUp(self):
        import elixir as el
        self.session = el.session = tws.transactional_session()
        el.metadata = sa.MetaData('sqlite:///:memory:')

        class DBTestCls1(el.Entity):
            name = el.Field(el.String)
            some_number = el.Field(el.Integer, default=2)

        class DBTestCls2(el.Entity):
            nick = el.Field(el.String)
            other_id = el.Field(el.Integer, colname='other')
            other = el.ManyToOne(DBTestCls1,
                                 field=other_id,
                                 backref='others')

        self.DBTestCls1 = DBTestCls1
        self.DBTestCls2 = DBTestCls2

        el.setup_all()
        el.metadata.create_all()
        foo = self.DBTestCls1(id=1, name='foo')
        bob = self.DBTestCls2(id=1, nick='bob', other=foo)
        george = self.DBTestCls2(id=2, nick='george')

        testapi.setup()
Ejemplo n.º 23
0
def setup():
    """Setup the database and create the tables that don't exists yet"""
    from elixir import setup_all, create_all
    from couchpotato import get_engine

    setup_all()
    create_all(get_engine())
def setup_database():
    init_model(engine)
    teardownDatabase()
    elixir.setup_all(True)
    # Creating users

    user = User()
    user.user_name = u'rms'
    user.password = u'freedom'
    DBSession.save(user)

    user = User()
    user.user_name = u'linus'
    user.password = u'linux'
    DBSession.save(user)

    user = User()
    user.user_name = u'sballmer'
    user.password = u'developers'
    DBSession.save(user)

    # Plus a couple of users without groups
    user = User()
    user.user_name = u'guido'
    user.password = u'phytonic'
    DBSession.save(user)

    user = User()
    user.user_name = u'rasmus'
    user.password = u'php'
    DBSession.save(user)

    DBSession.commit()
Ejemplo n.º 25
0
	def setup(self, create_tables=True):
		"""
		2008-10-09
			add option create_tables
		2008-08-26
		"""
		from elixir import setup_all
		setup_all(create_tables=create_tables)	#create_tables=True causes setup_all to call elixir.create_all(),
Ejemplo n.º 26
0
 def openDB(self, dbfilename):
     try:
         self.name = dbfilename
         metadata.bind = "sqlite:///" + dbfilename
         # 		metadata.bind.echo = True									# uncomment to see detailed database logs
         setup_all()
     except:
         print "[-] Could not open database file. Is the file corrupted?"
Ejemplo n.º 27
0
 def openDB(self, dbfilename):
     try:
         self.name = dbfilename
         metadata.bind = 'sqlite:///'+dbfilename
         #metadata.bind.echo = True                                   # uncomment to see detailed database logs
         setup_all()
     except:
         logging.error('[-] Could not open database file. Is the file corrupted?')
Ejemplo n.º 28
0
 def openDB(self, dbfilename):
     try:
         self.name = dbfilename
         metadata.bind = 'sqlite:///' + dbfilename
         #		metadata.bind.echo = True									# uncomment to see detailed database logs
         setup_all()
     except:
         print '[-] Could not open database file. Is the file corrupted?'
Ejemplo n.º 29
0
    def setupDB(self):  
        """Initialize/read database on disk"""
#        self.db = SqlSoup(SQLITE + PATH_TO_RES + KANJIDIC2) 
        setup_all()
        if not os.path.exists(PATH_TO_RES + DBNAME):
            create_all()
             
        session.bind = metadata.bind
Ejemplo n.º 30
0
Archivo: db.py Proyecto: Xifax/suzu
 def setupDB(self):  
     """Initialize/read database on disk"""
     self.db = SqlSoup(SQLITE + PATH_TO_RES + KANJIDIC2)     #TODO: add check up
     setup_all()
     if not os.path.exists(PATH_TO_RES + DBNAME):
         create_all()
          
     session.bind = metadata.bind
Ejemplo n.º 31
0
def init_db(db):
    ''' Initializes the database.'''
    print "binding db.."
    metadata.bind = db
    # from: http://stackoverflow.com/questions/7004169/why-does-elixir-sqlalchemys-session-bind-get-set-to-none-within-threads
    #session.configure(bind=metadata.bind)
    #metadata.bind.echo = True
    setup_all()
Ejemplo n.º 32
0
    def __init__(self):
        super(DatabaseHandler, self).__init__()

        self._fallback_handler = logging.StreamHandler()

        # Connect to the database. The connection is closed in self.close()
        elixir.setup_all()
        return
Ejemplo n.º 33
0
 def __init__(self, resource_type):
     '''
     Constructor
     
     @see:  nublic_resource.Provider.__init__
     '''
     Provider.__init__(self, resource_type)
     setup_all(create_tables=True)
Ejemplo n.º 34
0
	def setup(self, create_tables=True):
		"""
		2008-10-09
			add option create_tables
		2008-08-26
		"""
		from elixir import setup_all
		setup_all(create_tables=create_tables)	#create_tables=True causes setup_all to call elixir.create_all(), which in turn calls metadata.create_all()
Ejemplo n.º 35
0
def setup_model():
    #import camelot.model
    from elixir import setup_all
    import model
    print 'Testing...'
    print 'model.metadata: ', model.__metadata__

    setup_all(create_tables=False)
    print 'Original Tables:'
#    for table in model.__metadata__.sorted_tables:
#        print str(table)
    tables_to_drop = ([
        'address',
#        'authentication_mechanism',
#        'authentication_mechanism_username',
        'batch_job',
        'batch_job_type',
        'contact_mechanism',
        'fixture',
        'fixture_version',
        'geographic_boundary',
        'geographic_boundary_city',
        'geographic_boundary_country',
        'memento',
        'memento_create',
        'memento_delete',
        'memento_update',
        'organization',
        'party',
        'party_address',
        'party_address_role_type',
        'party_authentication',
        'party_contact_mechanism',
        'party_relationship',
        'party_relationship_dir',
        'party_relationship_empl',
        'party_relationship_shares',
        'party_relationship_suppl',
        'party_representor',
        'party_status',
        'party_status_type',
        'person',
        'synchronizedable',
        'synchronized',
        'synchronizedable_to_synchronized',
#        'translation',
        ])
    for table in model.__metadata__.sorted_tables:
        if str(table) in tables_to_drop:
            model.__metadata__.remove(table)
    setup_all(create_tables=True)
#    print
#    print 'Reduced Tables'
#    for table in model.__metadata__.sorted_tables:
#        print str(table)
       
    from camelot.model.authentication import updateLastLogin
    updateLastLogin()
Ejemplo n.º 36
0
def setup_model():
    #import camelot.model
    from elixir import setup_all
    import model
    print 'Testing...'
    print 'model.metadata: ', model.__metadata__

    setup_all(create_tables=False)
    print 'Original Tables:'
    #    for table in model.__metadata__.sorted_tables:
    #        print str(table)
    tables_to_drop = ([
        'address',
        #        'authentication_mechanism',
        #        'authentication_mechanism_username',
        'batch_job',
        'batch_job_type',
        'contact_mechanism',
        'fixture',
        'fixture_version',
        'geographic_boundary',
        'geographic_boundary_city',
        'geographic_boundary_country',
        'memento',
        'memento_create',
        'memento_delete',
        'memento_update',
        'organization',
        'party',
        'party_address',
        'party_address_role_type',
        'party_authentication',
        'party_contact_mechanism',
        'party_relationship',
        'party_relationship_dir',
        'party_relationship_empl',
        'party_relationship_shares',
        'party_relationship_suppl',
        'party_representor',
        'party_status',
        'party_status_type',
        'person',
        'synchronizedable',
        'synchronized',
        'synchronizedable_to_synchronized',
        #        'translation',
    ])
    for table in model.__metadata__.sorted_tables:
        if str(table) in tables_to_drop:
            model.__metadata__.remove(table)
    setup_all(create_tables=True)
    #    print
    #    print 'Reduced Tables'
    #    for table in model.__metadata__.sorted_tables:
    #        print str(table)

    from camelot.model.authentication import updateLastLogin
    updateLastLogin()
Ejemplo n.º 37
0
def setup_model():
    """This function will be called at application startup, it is used to setup
    the model"""
    import camelot.model
    from elixir import setup_all
    import canasta.model
    import canasta.view
    setup_all(create_tables=True)
    canasta.view.setup_views()
Ejemplo n.º 38
0
def gjms_config():
    """ Setup backend config """
    form = gjms.backend.forms.config(flask.request.form)

    if flask.request.method == "POST":
        if form.validate_on_submit():
            parser.set("gjms", "label", form.label.data)
            parser.set("gjms", "manager", form.manager.data)
            parser.set("gjms", "manager_email", form.m_email.data)
            parser.set("gjms", "theme_voting", form.v_theme.data)
            parser.set("gjms", "game_ratings", form.ratings.data)
            parser.set("gjms", "game_comments", form.comments.data)

            parser.set("gjms", "database_engine", form.engine.data)
            parser.set("gjms", "database_host", form.host.data)
            parser.set("gjms", "database_port", form.port.data)
            parser.set("gjms", "database_user", form.user.data)
            parser.set("gjms", "database_password", form.password.data)
            parser.set("gjms", "database", form.db.data)

            if form.engine.data == "sqlite":
                db_url = "sqlite:///%s?check_same_thread=False" % form.host.data
            elif form.engine.data != "sqlite" and form.port.data == "":
                db_url = "%s://%s:%s@%s/%s" % (form.engine.data, form.user.data, form.password.data, form.host.data, form.db.data)
            else:
                db_url = "%s://%s:%s@%s:%s/%s" % (form.engine.data, form.user.data, form.password.data, form.host.data, form.port.data, form.db.data)

            gjms.util.database.setup(db_url)
            elixir.setup_all()
            elixir.create_all()

            parser.set("gjms", "db_url", db_url)
            parser.set("gjms", "database_setup", True)

            cfgfile = open(os.path.abspath(os.path.dirname(__file__)+"/../gjms.cfg"), "w")
            gjms.config.parser.write(cfgfile)

            flask.flash(u"Settings saved!", "success")
        else:
            flask.flash(u"Woops! That didn't work. Check below for details.", "error")
    else:
        form.label.data = parser.get("gjms", "label")
        form.manager.data = parser.get("gjms", "manager")
        form.m_email.data = parser.get("gjms", "manager_email")
        form.v_theme.data = parser.getboolean("gjms", "theme_voting")
        form.ratings.data = parser.getboolean("gjms", "game_ratings")
        form.comments.data = parser.getboolean("gjms", "game_comments")

        form.engine.data = parser.get("gjms", "database_engine")
        form.host.data = parser.get("gjms", "database_host")
        form.port.data = parser.get("gjms", "database_port")
        form.user.data = parser.get("gjms", "database_user")
        form.password.data = parser.get("gjms", "database_password")
        form.db.data = parser.get("gjms", "database")

    system = gjms.core.system.get(1)
    return flask.render_template("backend/config.html", form=form, time=datetime, system=system, config=parser, users=gjms.core.users, events=gjms.core.events, games=gjms.core.games, platforms=gjms.core.platforms, ratings=gjms.core.ratings)
Ejemplo n.º 39
0
def init_db(path=paths['freq_db']):
    """
    Initialize specified DB.
    In case no DB file exists, it will be created.
    """
    metadata.bind = "sqlite:///" + path
    setup_all()
    if not os.path.exists(path):
        create_all()
Ejemplo n.º 40
0
def create_new_database():
    # Read schema and create entities
    setup_all()
    
    # Drop all the existing database. Warning!!
    metadata.drop_all()
    
    # Issue the commands to the local database
    create_all()
Ejemplo n.º 41
0
def setup_session(inventory_dbname=None, scanned_images_dbname=None):
    #create engine
    elixir.metadata.bind = 'sqlite://'
    b = elixir.metadata.bind
    if inventory_dbname is not None:
        b.execute("attach database ? as inventory", inventory_dbname)
    if scanned_images_dbname is not None:
        b.execute("attach database ? as scanned_images", scanned_images_dbname)
    elixir.setup_all()
Ejemplo n.º 42
0
def setup_models():
    from elixir import metadata, setup_all
    from cdpc.config import DATABASE_URI
    import cdpc.app.common.models
    import cdpc.app.usuarios.models
    import cdpc.app.projetos.models
    metadata.bind = DATABASE_URI
    metadata.bind.echo = True
    setup_all()
Ejemplo n.º 43
0
def init_db(path = paths['freq_db']):
    """
    Initialize specified DB.
    In case no DB file exists, it will be created.
    """
    metadata.bind = "sqlite:///" + path
    setup_all()
    if not os.path.exists(path):
        create_all()
Ejemplo n.º 44
0
def setup_db(meta):
    datafile = params['DB_FILE']
    print "Using database : %s " % datafile
    meta.bind = "sqlite:///"+datafile

    meta.bind.echo = True
    meta.bind.echo = False

    elixir.setup_all()
Ejemplo n.º 45
0
def _test():
    import random
    from elixir import session, metadata, setup_all, create_all
    connection_line = 'sqlite:///:memory:'
    metadata.bind = connection_line

    setup_all()
    create_all()

    [iHS('snp_%s' % i, ) for i in xrange(10)]
Ejemplo n.º 46
0
def getMaxClusterId():
    # Define the database connection.
    elixir.metadata.bind = DATABASE_CONNECTION_STR
    elixir.metadata.bind.echo = False
    elixir.setup_all()

    entry = elixir.session.query(func.max(Blackboard.ClusterId)).one()
    if (entry and len(entry) == 1 and entry[0] is not None):
        return (entry[0])
    return (0)
Ejemplo n.º 47
0
def getMaxClusterId():
    # Define the database connection.
    elixir.metadata.bind = DATABASE_CONNECTION_STR
    elixir.metadata.bind.echo = False
    elixir.setup_all()

    entry = elixir.session.query(func.max(Blackboard.ClusterId)).one()
    if(entry and len(entry) == 1 and entry[0] is not None):
        return(entry[0])
    return(0)
Ejemplo n.º 48
0
 def test_insertALotOfIndividual(self):
     """Tests the insertion of a lot of individuals
     """
     session.commit()
     setup_all()
     individuals = [Individual('Ind' + str(i+1)) for i in range(100)]    #TODO: use an higher value
     
     session.commit()
     for ind in individuals: 
         ind.delete()
Ejemplo n.º 49
0
def choose_db(db):
    """
    Remap active DB.
    """
    global active_db
    if os.path.exists(dbs[db]):
        metadata.bind = "sqlite:///" + dbs[db]
        setup_all()
        active_db = db
    else:
        raise NoDbException("Specified db does not exist!")
Ejemplo n.º 50
0
Archivo: DAO.py Proyecto: joubu/CDL
 def init(cls):
     """
     Initialisation de la bdd
     Création si besoin des tables
     """
     setup_all()
     create_all()
     config = cls.config()
     if not config:
         config = cls.reload_config()
     return config
Ejemplo n.º 51
0
 def __init__(self, dbfilename):
     if not os.path.exists(os.path.dirname(dbfilename)):
         os.makedirs(os.path.dirname(dbfilename))
     try:
         self.name = dbfilename
         metadata.bind = 'sqlite:///' + dbfilename
         #metadata.bind.echo = True                                   # uncomment to see detailed database logs
         setup_all()
         create_all()
     except:
         logging.error('[-] Could not create database. Please try again.')
Ejemplo n.º 52
0
Archivo: db.py Proyecto: nsi-iff/pyOLS
 def reset(self):
     """ Clean out and reset the database.
     > db.connect(...)
     > db.create()
     ... add things ...
     > db.reset()
     The db is now at the state it was when create() was called. """
     # Probably only useful during testing...
     objectstore.clear()
     drop_all()
     setup_all(create_tables=True)
Ejemplo n.º 53
0
def getEntry(globalJobId):
    """
    Retrieve a single blackboard entry given its GlobalJobId `globalJobId`.
    """
    # Define the database connection.
    elixir.metadata.bind = DATABASE_CONNECTION_STR
    elixir.metadata.bind.echo = False
    elixir.setup_all()

    query = Blackboard.query.filter_by(GlobalJobId=globalJobId)
    return (query.one())
Ejemplo n.º 54
0
 def __init__(self, dbfilename):
     try:
         self.name = dbfilename
         self.dbsemaphore = QSemaphore(
             1)  # to control concurrent write access to db
         metadata.bind = 'sqlite:///' + dbfilename
         #		metadata.bind.echo = True									# uncomment to see detailed database logs
         setup_all()
         create_all()
     except:
         print '[-] Could not create database. Please try again.'
Ejemplo n.º 55
0
def upgrade():
    # Add column
    op.add_column('board', sa.Column('is_template', sa.Boolean, default=False))

    # Setup models
    elixir.metadata.bind = op.get_bind()
    elixir.setup_all()

    # Create default template
    create_template_empty()
    create_template_todo()
Ejemplo n.º 56
0
Archivo: db.py Proyecto: nsi-iff/pyOLS
 def connect(self, dbString, debug=False):
     """ Connect to the database described by 'dbString'.
         Debug enables verbose SQL debugging.
         It is (probably) an error to `connect()` twice. """
     # In practice, dbString will probably be sqlite:///path/to/db
     self._dbString = dbString
     self._debug = debug
     self._txn = None
     metadata.bind = dbString
     metadata.bind.echo = debug
     setup_all()
     self.connected = True
Ejemplo n.º 57
0
def set_metadata(metadata, database_uri, database_debug, engine_settings):
    """Activate the metadatas (bind them to a database engine)

    In:
      - ``metadata`` -- the metadatas
      - ``database_uri`` -- connection string for the database engine
      - ``database_debug`` -- debug mode for the database engine
      - ``engine_settings`` -- dedicated parameters for the used database engine
    """
    if not metadata.bind:
        metadata.bind = _engines.setdefault(database_uri, sqlalchemy.engine_from_config(engine_settings, '', echo=database_debug, url=database_uri))
        setup_all()
Ejemplo n.º 58
0
    def setUp(self):
        if not e:
            self.skipTest("'elixir' is not available")

        e.setup_all()
        e.create_all()

        self.movie_alias = pyamf.register_class(Movie, 'movie')
        self.genre_alias = pyamf.register_class(Genre, 'genre')
        self.director_alias = pyamf.register_class(Director, 'director')

        self.create_movie_data()
Ejemplo n.º 59
0
def init_model(junk=None):
    # Connect.
    new_engine()

    # Import models.
    import_models()

    # Setup elixir entities.
    setup_all()

    # Bind session to the engine.
    Session.configure(bind=_engine)