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()
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()
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 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
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)
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()
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()
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())
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
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()
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()
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()
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()
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)
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()
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
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()
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(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(),
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?"
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?')
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?'
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
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
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()
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
def __init__(self, resource_type): ''' Constructor @see: nublic_resource.Provider.__init__ ''' Provider.__init__(self, resource_type) setup_all(create_tables=True)
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()
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()
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()
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)
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()
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()
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()
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()
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()
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()
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)]
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)
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)
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()
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!")
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
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.')
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)
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())
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.'
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()
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
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()
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()
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)