def setup():
    global memconn, realconn, sqlhub
    if not env_supports.sqlobject:
        raise SkipTest
        
    from sqlobject import connectionForURI, sqlhub
    
    realconn = connectionForURI(conf.HEAVY_DSN)
    memconn = connectionForURI("sqlite:/:memory:")
Exemple #2
0
 def connection(self):
     config = self.config()
     if config is not None:
         assert config.get('database'), (
             "No database variable found in config file %s"
             % self.options.config_file)
         return sqlobject.connectionForURI(config['database'])
     elif getattr(self.options, 'connection_uri', None):
         return sqlobject.connectionForURI(self.options.connection_uri)
     else:
         return None
Exemple #3
0
 def connection(self):
     config = self.config()
     if config is not None:
         assert config.get('database'), (
             "No database variable found in config file %s" %
             self.options.config_file)
         return sqlobject.connectionForURI(config['database'])
     elif getattr(self.options, 'connection_uri', None):
         return sqlobject.connectionForURI(self.options.connection_uri)
     else:
         return None
def establish_connection():
    """ Connect to the database """
    res_dict = config_parser_result()
    conn = None
    if res_dict[save_type_key] == "mysql":
        connection_str = "mysql://*****:*****@127.0.0.1/testdb"
        conn = sqlobject.connectionForURI(connection_str)
    elif res_dict[save_type_key] == "sqll":
        connection_str = "sqlite:" + os.path.abspath("mdata.db")
        conn = sqlobject.connectionForURI(connection_str)
    elif res_dict[save_type_key] == "psql":
        connection_str = "mysql://*****:*****@127.0.0.1/sammy"
        conn = sqlobject.connectionForURI(connection_str)
    return conn
Exemple #5
0
def main(repos, revision):
    """
    Main function.
    """

    import pysvn
    import os.path

    client = pysvn.Client()
    diff = client.diff_summarize(
        repos,
        revision1=pysvn.Revision(pysvn.opt_revision_kind.number, revision - 1),
        revision2=pysvn.Revision(pysvn.opt_revision_kind.number, revision))

    conn = sqlobject.connectionForURI(DATABASE_URI)
    sqlobject.sqlhub.processConnection = conn
    #PythonScore.createTable()

    func = lambda f: os.path.splitext(f.path)[-1] == ".py"
    for entry in filter(func, diff):
        path = os.path.join(repos, entry.path)
        score, old_score, credit = process_file(path)

        info = client.info(path)

        PythonScore(username=info['commit_author'],
                    pathname=path,
                    revision="1",
                    score=score,
                    old_score=old_score,
                    credit=credit)
Exemple #6
0
def create(path, dbName = 'scenarios.db', debug = False):
    if isConnected():
        disconnect()

    campaignConfigurationPath = os.path.join(os.path.abspath(path), 'campaignConfiguration.py')
    if not os.path.exists(campaignConfigurationPath):
        raise 'File campaignConfiguration.py does not exist in path %s.' % path
    campaignConfiguration = imp.load_module('foo',
                                            file(campaignConfigurationPath),
                                            'foo', ('.py', 'r', imp.PY_SOURCE))

    dbPath = os.path.join(os.path.abspath(path), dbName)
    if os.path.exists(dbPath):
        raise 'Database already exists!'
    __Vars.dbPath = dbPath

    connectionString = 'sqlite:' + dbPath + '?timeout=1000000'
    __Vars.connection = sqlobject.connectionForURI(connectionString)
    sqlobject.sqlhub.processConnection = __Vars.connection

    __accessDB(__setPragma, __Vars.connection)

    for parameter in campaignConfiguration.parameters:
        Scenario.Scenario.sqlmeta.addColumn(parameter)

    Scenario.Scenario.createTable()
    Scenario.Scenario._connection.debug = debug
    Parameters.createTable()

    campaignConfiguration.createCampaign()

    Parameters(campaign = campaignConfiguration.parameters)

    if debug:
        print 'Database %s successfully created.' % dbPath
Exemple #7
0
def addParametersTable(path, dbName = 'scenarios.db', debug = False):
    if isConnected():
        disconnect()

    campaignConfigurationPath = os.path.join(os.path.abspath(path), 'campaignConfiguration.py')
    if not os.path.exists(campaignConfigurationPath):
        raise 'File campaignConfiguration.py does not exist in path %s.' % path
    campaignConfiguration = imp.load_module('foo',
                                            file(campaignConfigurationPath),
                                            'foo', ('.py', 'r', imp.PY_SOURCE))

    dbPath = os.path.join(os.path.abspath(path), dbName)
    if not os.path.exists(dbPath):
        raise 'Database not found!'
    __Vars.dbPath = dbPath

    connectionString = 'sqlite:' + dbPath
    __Vars.connection = sqlobject.connectionForURI(connectionString)

    curs = __Vars.connection.getConnection().cursor()
    curs.execute('PRAGMA synchronous = OFF')  # SQLite specific
    curs.close()

    sqlobject.sqlhub.processConnection = __Vars.connection

    for parameter in campaignConfiguration.parameters:
        Scenario.Scenario.sqlmeta.addColumn(parameter)

    Scenario.Scenario._connection.debug = debug
    Parameters.createTable()
    Parameters(campaign = campaignConfiguration.parameters)

    if debug:
        print 'Parameters table successfully added to %s.' % dbPath
Exemple #8
0
def connect(path, dbName = 'scenarios.db', debug = False):
    dbPath = os.path.join(os.path.abspath(path), dbName)

    if isConnected():
        if dbPath == __Vars.dbPath:
            return
        else:
            disconnect()

    if not os.path.exists(dbPath):
        raise 'Database not found!'
    __Vars.dbPath = dbPath

    connectionString = 'sqlite:' + dbPath + '?timeout=1000000'
    __Vars.connection = sqlobject.connectionForURI(connectionString)
    sqlobject.sqlhub.processConnection = __Vars.connection

    __accessDB(__setPragma, __Vars.connection)

    Scenario.Scenario._connection.debug = debug

    parameters = Parameters.get(1)
    for parameter in parameters.campaign:
        Scenario.Scenario.sqlmeta.addColumn(parameter)

    if debug:
        print 'Connection to database %s established.' % dbPath
Exemple #9
0
def getDB():
    global connection
    if connection is not None:
        return connection

    connection = sqlobject.connectionForURI(settings.Connection_String)
    return connection
Exemple #10
0
def initdb(config):
    dbfile = os.path.abspath(config.get("app", "db_params"))
    conn = connectionForURI("%s:%s" % (config.get("app", "db_type"), dbfile))
    sqlhub.processConnection = conn
    Message.createTable(ifNotExists=True)
    ModemLog.createTable(ifNotExists=True)
    MessageState.createTable(ifNotExists=True)
Exemple #11
0
	def _sqliteCreateDB(self, dbpath, model):
		model = models.Model()
		'''
		Creates/syncs an sqlite DB at location dbpath.
		Requires python 2.5 for sqlite3 module.
		'''
		try:
			import sqlobject
		except Exception:
			print 'Python sqlite import failed.'
			return False
		if os.path.exists(dbpath):
			os.remove(dbpath)
		print 'Attempting connection to', dbpath + '...'
		connectionpath = 'sqlite://' + dbpath
		connection = sqlobject.connectionForURI(connectionpath)
		sqlobject.sqlhub.processConnection = connection
		transaction = connection.transaction()
		print 'Vars:', dir(model)
		for table in dir(model): #FIXME: is there a better way to do this?
			if table[0] == '_':
				continue
			Table = getattr(model, table)
			Table.createTable()
		transaction.commit(close = True)
		return dbpath
 def __init__(self, appcfg_file):
     self.__paths = Path
     self.__pluginlist = PluginList
     #REVIEW: Is this the best way to tackle this?:
     # http://sqlobject.org/SQLObject.html#declaring-a-connection
     if platform == "win32":
         appcfg_file = appcfg_file.replace("\\", "/")
         appcfg_file = appcfg_file.replace(r"\\", r"/")
         (drive, filepath) = path.splitdrive(appcfg_file)
         uri = "sqlite:/"
         if drive == '':
             appcfg_file = path.abspath(filepath)
             if path.isfile(appcfg_file):
                 (drive, filepath) = path.splitdrive(appcfg_file)
         if ":" in drive:
             uri = uri + "".join([drive.replace(":", "|"), filepath])
         else:
             uri = uri + appcfg_file
     else:
         uri = uri + appcfg_file
     print uri
     self.__app_cfg_db = connectionForURI(uri)
     self.__paths.setConnection(self.__app_cfg_db)
     self.__paths.createTable(ifNotExists=True)
     self.__pluginlist.setConnection(self.__app_cfg_db)
     self.__pluginlist.createTable(ifNotExists=True)
Exemple #13
0
 def __init__(self):
     """ Create table on load if table doesnt exist """
     self.logger = logging.getLogger('htpc.settings')
     self.logger.debug('Connecting to database: ' + htpc.DB)
     sqlhub.processConnection = connectionForURI('sqlite:' + htpc.DB)
     Setting.createTable(ifNotExists=True)
     self.updatebl()
Exemple #14
0
def open_pki(fname):
    cnx = "sqlite://" + os.path.realpath(fname)
    sqlhub.processConnection = connectionForURI(cnx)
    m = Meta.select()[0]
    if m.version != DBVERSION:
        raise Exception("bad db version (got %i, expected %i)" %
                        (m.version, DBVERSION))
    def get(self):
        import sys
        from sqlobject import SQLObject, StringCol, ForeignKey, connectionForURI, sqlhub
        if 'bae' in sys.modules:
            from bae.core import const
            connection_string = 'mysql://%s:%s@%s:%s/NtwLDxlnbZIsMEPsgrFH?charset=utf8' % (
                const.MYSQL_USER, const.MYSQL_PASS, const.MYSQL_HOST,
                const.MYSQL_PORT)
        else:
            connection_string = 'sqlite:d:/weicbd_db.sqlite3'
        connection = connectionForURI(connection_string)
        sqlhub.processConnection = connection

        class Person(SQLObject):
            firstName = StringCol()
            middleInitial = StringCol(length=1, default=None)
            lastName = StringCol()

        class Address(SQLObject):
            street = StringCol()
            city = StringCol()
            state = StringCol(length=2)
            zip = StringCol(length=9)
            person = ForeignKey('Person')

        Address.createTable(ifNotExists=True)
Exemple #16
0
def open_db(db_uri=None):
    if db_uri is None:
        db_uri = get_config().get('database', 'URI') or find_sqlite_dburi()

    if '://' not in db_uri:
        db_uri = 'sqlite://' + os.path.abspath(db_uri).replace(os.sep, '/')

    sqlhub.processConnection = connection = connectionForURI(db_uri)

    if connection.dbName == 'sqlite':

        def lower(s):
            if isinstance(s, string_type):
                return s.lower()
            return s

        sqlite = connection.module

        class MLConnection(sqlite.Connection):
            def __init__(self, *args, **kwargs):
                super(MLConnection, self).__init__(*args, **kwargs)
                self.create_function('lower', 1, lower)

        # This hack must be done at the very beginning, before the first query
        connection._connOptions['factory'] = MLConnection

        # Speedup SQLite connection
        connection.query("PRAGMA synchronous=OFF")
        connection.query("PRAGMA count_changes=OFF")
        connection.query("PRAGMA journal_mode=MEMORY")
        connection.query("PRAGMA temp_store=MEMORY")
Exemple #17
0
def getDB():
    global connection
    if connection is not None:
        return connection

    connection = sqlobject.connectionForURI(settings.Connection_String)
    return connection
Exemple #18
0
def main():
    sqlhub.processConnection = connectionForURI('sqlite:/:memory:')
    SERVER='kirsikka'
    DOMAIN='mirror.kapsi.fi'
    Usage.createTable()
    for i in Usage.select():
        print unicode(i)
Exemple #19
0
def connectDatabase(dbFileName, createIfNeeded=True):
    """Connect to database and create it if needed
    @param dbFileName: path to database file
    @type dbFileName: str
    @param createIfNeeded: Indicate if database must be created if it does not exists (default True)
    @type createIfNeeded: bool"""

    dbFileName=os.path.abspath(dbFileName)

    if sys.platform == 'win32':
        connectionString = 'sqlite:/'+ dbFileName[0] +'|' + dbFileName[2:]
    else:
        connectionString = 'sqlite:' + dbFileName
        
    connection = connectionForURI(connectionString)
    sqlhub.processConnection = connection

    if not os.path.exists(dbFileName):
        if createIfNeeded:
            print "Creating database"
            createTables()
            # Set database version according to current yokadi release
            Config(name=DB_VERSION_KEY, value=str(DB_VERSION), system=True, desc="Database schema release number")
        else:
            print "Database file (%s) does not exist or is not readable. Exiting" % dbFileName
            sys.exit(1)

    # Check version
    version = getVersion()
    if version != DB_VERSION:
        tui.error("Your database version is %d but Yokadi wants version %d." \
            % (version, DB_VERSION))
        print "Please, run the %s/update.py script to migrate your database prior to running Yokadi" % \
                os.path.abspath(utils.shareDirPath())
        sys.exit(1)
Exemple #20
0
 def __init__(self):
     """ Create table on load if table doesnt exist """
     self.logger = logging.getLogger('htpc.settings')
     self.logger.debug('Connecting to database: ' + htpc.DB)
     sqlhub.processConnection = connectionForURI('sqlite:' + htpc.DB)
     Setting.createTable(ifNotExists=True)
     self.updatebl()
Exemple #21
0
def import_site(xml_root,
                site_name,
                dump_date,
                site_desc,
                site_key,
                site_base_url,
                answer_yes=False):
    print('Using the XML root path: ' + xml_root + '\n')

    if not os.path.exists(xml_root):
        print('The given XML root path does not exist.')
        sys.exit(1)

    # connect to the database
    print('Connecting to the Stackdump database...')
    conn_str = settings.DATABASE_CONN_STR
    sqlhub.processConnection = connectionForURI(conn_str)
    print('Connected.\n')

    # connect to solr
    print('Connecting to solr...')
    solr = Solr(settings.SOLR_URL, assume_clean=True)
    # pysolr doesn't try to connect until a request is made, so we'll make a ping request
    try:
        solr._send_request('GET', 'admin/ping')
    except socket.error, e:
        print('Failed to connect to solr - error was: %s' % str(e))
        print('Aborting.')
        sys.exit(2)
def SQLObject():
    from sqlobject import sqlhub, connectionForURI, SQLObject, StringCol, IntCol

    sqlhub.processConnection = connectionForURI('sqlite:/:memory:')

    class Person(SQLObject):
        name = StringCol()
        gender = StringCol(length=1, default=None)
        age = IntCol()

    Person.createTable()

    p = Person(name='Max', gender='m', age=19)
    p.name = 'Max2'
    print(p)

    p2 = Person.get(1)  # get_by_id
    print(p2)

    print(p is p2)  # True (!)

    # way to select 1
    p3 = Person.selectBy(name='Max2')[0]
    print(p3)

    # way to select 2
    p4 = Person.select(Person.q.gender == 'm')  # query
    print(p4[0], p4.count())  # 1
Exemple #23
0
    def __init__(self, dburi='sqlite:/:memory:'):
        super(WebApi, self).__init__()

        # Guest api endpoints
        self.get('/api/token/<token>', callback=self.api_get_guest)
        self.put('/api/token/<token>', callback=self.api_edit_guest)
        self.post('/api/token/<token>', callback=self.api_new_guest)
        self.post('/api/token', callback=self.api_new_event)

        # Event api endpoints
        self.get('/api/token/<token>/event', callback=self.api_get_event)
        self.put('/api/token/<token>/event', callback=self.api_edit_event)

        # Chat api endpoints
        self.get('/api/token/<token>/chat', callback=self.api_get_chat)
        self.post('/api/token/<token>/chat', callback=self.api_new_message)
        self.get('/api/token/<token>/chat/<msgid>', callback=self.api_get_message)
        self.put('/api/token/<token>/chat/<msgid>', callback=self.api_edit_message)
        self.delete('/api/token/<token>/chat/<msgid>', callback=self.api_del_message)

        # Static files
        self.get('/', callback=self.get_static('index.html'))
        self.get('/event', callback=self.get_static('event.html'))

        for f in ['inviter.js', 'histogram.js', 'frontend.js', 'style.css', 'spinner.gif']:
            self.get('/' + f, callback=self.get_static(f))

        # Create tables that do not exist
        self.db= so.connectionForURI(dburi)
        Event.createTable(True, connection=self.db)
        Guest.createTable(True, connection=self.db)
        ChatMsg.createTable(True, connection=self.db)
Exemple #24
0
    def init(self):
        if Config.get("phoenix", "initialized") == "True":
            raise AdminException("Already initialized.")
        
        logging.info("Defining variables for init ...")
        user = self.args.git_user
        base = path.join(self.args.base_dir, user)
        repo = path.join(base, self.args.repository_dir)
        tar = path.join(base, self.args.tarball_dir)
        ssh = path.join(base, ".ssh")
        auth_keys = path.join(ssh, "authorized_keys")
        admin_repo = self.args.admin_repo
        email = self.args.admin_email
        name = self.args.admin_name
        username = self.args.admin_username
        sql = self.args.sql_connect or "sqlite://%s" % path.join(base, "phoenix.db")
                
        logging.info("Checking for permission to write the config file ...")
        if not File.writePermission(Config.get("CONF_FILE")):
            raise AdminException("You don't have permission to write the config file `%s' ..." % Config.get("CONF_FILE"))
        
        if not SysUser.exists(self.args.git_user):
            logging.info("Creating user `%s' ... " % user)
            SysUser.create(user, base)
            Config.set("phoenix", "user", user)
            Config.set("phoenix", "base", base)
        else:
            raise AdminException("The user `%s' already exists." % user)
        
        logging.info("Saving SQL connection string `%s' ..." % sql)
        Config.set("phoenix", "sql_connect", sql)
        Config.set("phoenix", "initialized", True)
        Config.set("phoenix", "authorized_keys", auth_keys)
        
        __import__("os").setgid(__import__("pwd").getpwnam(user).pw_gid)
        __import__("os").setuid(__import__("pwd").getpwnam(user).pw_uid)
                
        logging.info("Checking for permission to write the config file as `%s' ..." % user)
        if not File.writePermission(Config.get("CONF_FILE")):
            raise AdminException("You don't have permission to write the config file `%s' ..." % Config.get("CONF_FILE"))
        
        
        from sqlobject import connectionForURI, sqlhub
        connection = connectionForURI(Config.get("phoenix", "sql_connect"))
        sqlhub.processConnection = connection
        
        self._sqlChanges()
        self._createDirectoryStructure(repo, tar, ssh)

        logging.info("Creating `%s' ..." % auth_keys)
        File.touch(auth_keys)
        
        logging.info("Saving admin user information `%s' and `%s' in database ..." % (name, email))
        admin = Member(username=username, email=email, name=name)
        
        if admin_repo:
            logging.info("Initializing development repository at `%s/phoenix.git' ..." % repo)
            admin.addRepository("Phoenix Server Management", "phoenix.git")
        
        print "Done."
Exemple #25
0
def create_connection(file_name):
    if os.path.exists(file_name):
        os.unlink(file_name)
    _scheme = 'sqlite:' + file_name
    conn = connectionForURI(_scheme)
    sqlhub.processConnection = conn
    return conn
def main(repos, revision):
    """
    Main function.
    """

    import pysvn
    import os.path

    client = pysvn.Client()
    diff = client.diff_summarize(repos,
             revision1=pysvn.Revision(pysvn.opt_revision_kind.number, revision - 1),
             revision2=pysvn.Revision(pysvn.opt_revision_kind.number, revision))

    conn = sqlobject.connectionForURI(DATABASE_URI)
    sqlobject.sqlhub.processConnection = conn
    #PythonScore.createTable()

    func = lambda f: os.path.splitext(f.path)[-1] == ".py"
    for entry in filter(func, diff):
        path = os.path.join(repos, entry.path)
        score, old_score, credit = process_file(path)

        info = client.info(path)

        PythonScore(username=info['commit_author'], pathname=path, revision="1",
                score=score, old_score=old_score, credit=credit)
Exemple #27
0
def attempt_database_upgrade(oLogHandler=None):
    """Attempt to upgrade the database, going via a temporary memory copy."""
    oTempConn = connectionForURI("sqlite:///:memory:")
    oLogger = Logger('attempt upgrade')
    if oLogHandler:
        oLogger.addHandler(oLogHandler)
    (bOK, aMessages) = create_memory_copy(oTempConn, oLogHandler)
    if bOK:
        oLogger.info("Copied database to memory, performing upgrade.")
        if len(aMessages) > 0:
            oLogger.info("Messages reported: %s", aMessages)
        (bOK, aMessages) = create_final_copy(oTempConn, oLogHandler)
        if bOK:
            oLogger.info("Everything seems to have gone OK")
            if len(aMessages) > 0:
                oLogger.info("Messages reported %s", aMessages)
            return True
        else:
            oLogger.critical("Unable to perform upgrade.")
            if len(aMessages) > 0:
                oLogger.error("Errors reported: %s", aMessages)
            oLogger.critical("!!YOUR DATABASE MAY BE CORRUPTED!!")
    else:
        oLogger.error("Unable to create memory copy. Database not upgraded.")
        if len(aMessages) > 0:
            oLogger.error("Errors reported %s", aMessages)
    return False
 def attempt_database_upgrade(self, oLogHandler=None):
     """Attempt to upgrade the database,
        going via a temporary memory copy."""
     oTempConn = connectionForURI("sqlite:///:memory:")
     oLogger = Logger('attempt upgrade')
     if oLogHandler:
         oLogger.addHandler(oLogHandler)
     (bOK, aMessages) = self.create_memory_copy(oTempConn, oLogHandler)
     if bOK:
         oLogger.info("Copied database to memory, performing upgrade.")
         if aMessages:
             oLogger.info("Messages reported: %s", aMessages)
         (bOK, aMessages) = self.create_final_copy(oTempConn, oLogHandler)
         if bOK:
             oLogger.info("Everything seems to have gone OK")
             if aMessages:
                 oLogger.info("Messages reported %s", aMessages)
             return True
         oLogger.critical("Unable to perform upgrade.")
         if aMessages:
             oLogger.error("Errors reported: %s", aMessages)
         oLogger.critical("!!YOUR DATABASE MAY BE CORRUPTED!!")
     else:
         oLogger.error(
             "Unable to create memory copy. Database not upgraded.")
         if aMessages:
             oLogger.error("Errors reported %s", aMessages)
     return False
Exemple #29
0
def set_connection(scheme):
    """
    Sets the databases connection.
    Examples:
        postgres://chris@localhost/mypl_archive
        postgres://[email protected]/mypl_archive
    """
    sqlhub.processConnection = connectionForURI(scheme)
Exemple #30
0
    def _connect(self, database_uri):
        """
        Connect to the database

        Argument:
            * a different uri to connect to another database than the one in the config.py file (ie: for unittest)
        """
        sqlobject.sqlhub.processConnection = sqlobject.connectionForURI(database_uri) if database_uri else sqlobject.connectionForURI(DATABASE_ACCESS)
Exemple #31
0
def getConnection(**kw):
    name = getConnectionURI()
    conn = sqlobject.connectionForURI(name, **kw)
    if conftest.option.show_sql:
        conn.debug = True
    if conftest.option.show_sql_output:
        conn.debugOutput = True
    return conn
Exemple #32
0
 def _check_if_is_same_dir(self, entry, path):
     con_str = "sqlite://" + CATALOGDIR + entry
     conn = connectionForURI(con_str)
     metadircount = MetaDir.select(MetaDir.q.target == path,
                              connection = conn).count()
     if metadircount > 0:
         return MetaDir.select(MetaDir.q.target == path,
                              connection = conn)[0].target == path
Exemple #33
0
def getConnection(**kw):
    name = getConnectionURI()
    conn = sqlobject.connectionForURI(name, **kw)
    if conftest.option.show_sql:
        conn.debug = True
    if conftest.option.show_sql_output:
        conn.debugOutput = True
    return conn
Exemple #34
0
def test_connection_override():
    sqlhub.processConnection = connectionForURI('sqlite:///db1')

    class SOTestSO13(SQLObject):
        _connection = connectionForURI('sqlite:///db2')

    assert SOTestSO13._connection.uri() == 'sqlite:///db2'
    del sqlhub.processConnection
 def __init__(self, connection_string, debug_mode = False):
     # Remove old cached connection
     sqlobject.dbconnection.TheURIOpener.cachedURIs.pop(connection_string, None)
     # Create new connection
     sqlobject.sqlhub.threadConnection = sqlobject.connectionForURI(connection_string)
     sqlobject.sqlhub.threadConnection.debug = debug_mode
     
     self.__drop_relations = [Access, Script, PointGroupLink, UserGroupLink, PointGroup, UserGroup, EmMarineCard, User, Point, Controller, Node]
Exemple #36
0
def test_connection_override():
    sqlhub.processConnection = connectionForURI('sqlite:///db1')

    class SOTestSO13(SQLObject):
        _connection = connectionForURI('sqlite:///db2')

    assert SOTestSO13._connection.uri() == 'sqlite:///db2'
    del sqlhub.processConnection
Exemple #37
0
def connectDb():
	data_types = {}

	sqlhub.processConnection = connectionForURI('sqlite:%s' % DATABASE_FILE)

	for cls in DataPoint.__subclasses__():
		data_types[cls.getDataType()] = cls

	return data_types
Exemple #38
0
def get_correct_filename_from_catalog(entry):
    con_str = "sqlite://" + entry
    conn = connectionForURI(con_str)
    metadircount = MetaDir.select(connection = conn).count()
    if metadircount > 0:
        md = MetaDir.select(connection = conn)[0]
        datestr = md.date.strftime("%Y.%m.%d-%H.%M.%S")
        name = md.name
        return name + ".-." + datestr + ".db"
Exemple #39
0
    def __init__(self, db_connection=None):
        if db_connection is None:
            #if not os.path.exists(DB_FILENAME):
            #    Kilink.createTable()
            db_connection = 'sqlite:' + DB_FILENAME

        # connect
        connection = sqlobject.connectionForURI(db_connection)
        sqlobject.sqlhub.processConnection = connection
Exemple #40
0
 def create_transaction(self):
     from sqlobject import connectionForURI
     if not self.connection:
         self.connection = connectionForURI(self.dsn)
         self.close_conn = True  # because we made it
     if self.use_transaction:
         return self.connection.transaction()
     else:
         return self.connection
Exemple #41
0
 def update_dburi(self, dburi):
     if self.dburi != dburi:
         if self.dburi is not None:
             sqlhub.processConnection.close()
         if dburi is None:
             sqlhub.processConnection
         else:
             sqlhub.processConnection = connectionForURI(dburi)
         self.dburi = dburi
Exemple #42
0
def db_open(filename):
    create = False
    filename = os.path.abspath(filename)
    string_conn = 'sqlite:' + filename
    conn = sqlobject.connectionForURI(string_conn)
    sqlobject.sqlhub.processConnection = conn
    UserObj.createTable(ifNotExists=True)
    TokenObj.createTable(ifNotExists=True)
    ContactObj.createTable(ifNotExists=True)
Exemple #43
0
 def update_dburi(self, dburi):
     if self.dburi != dburi:
         if self.dburi is not None:
             sqlhub.processConnection.close()
         if dburi is None:
             sqlhub.processConnection
         else:
             sqlhub.processConnection = connectionForURI(dburi)
         self.dburi = dburi
Exemple #44
0
 def connect(self):
     try:
         print "\n[+]Conectando db por sqlobject...\n"
         handler = "mysql://%s:%s@%s/%s" % (
             self.__credential['user'], self.__credential['pass'],
             self.__credential['host'], self.__credential['dbname'])
         self.__connect = sqlobject.connectionForURI(handler)
         sqlobject.sqlhub.processConnection = self.__connect
     except Exception, e:
         print "Error Controlado: ", e
Exemple #45
0
def create_pki(fname):
    cnx = "sqlite://" + os.path.realpath(fname)
    sqlhub.processConnection = connectionForURI(cnx)
    for tb in [
            Meta, CA, Key, Cert, Profile, ProfileTemplate, FileExport,
            YubikeyExport, Yubikey
    ]:
        tb.createTable()
    name = raw_input("SSH PKI name: ")
    Meta(version=DBVERSION, pkiname=name)
Exemple #46
0
def getConnection(**kw):
    name = getConnectionURI()
    conn = sqlobject.connectionForURI(name, **kw)
    if conftest.option.show_sql:
        conn.debug = True
    if conftest.option.show_sql_output:
        conn.debugOutput = True
    if (conn.dbName == 'sqlite') and not conn._memory:
        speedupSQLiteConnection(conn)
    return conn
Exemple #47
0
    def setUp(self, dsn=conf.LITE_DSN):
        """should load the dataset"""
        from sqlobject import connectionForURI
        self.conn = connectionForURI(dsn)
        self.fixture.connection = self.conn

        from sqlobject import sqlhub
        sqlhub.processConnection = self.conn

        setup_db(self.conn)
Exemple #48
0
def setup_package():
    """Fill database before any of the tests are run"""
    # Get the database to use from the environment, defaulting to an
    # sqlite memory DB
    sDBUrl = os.getenv('SUTEKH_TEST_DB', "sqlite:///:memory:")
    oConn = connectionForURI(sDBUrl)
    sqlhub.processConnection = oConn
    SutekhTest.set_db_conn(oConn)

    create_db()
Exemple #49
0
def setup(databaseUrl=DATABASE_URL):
    # Establish the connection
    connection = connectionForURI(databaseUrl)
    connection.dbEncoding = "utf8"
    # No pooling
    connection._pool = None
    sqlhub.processConnection = connection
    # Creates tables
    Ad.createTable(ifNotExists=True)
    Report.createTable(ifNotExists=True)
def setup(dburi):
    connection = connectionForURI(dburi)
    sqlhub.processConnection = connection
    # The sqlhub.processConnection assignment means that all classes will,
    # by default, use this connection

    Recipe.createTable(ifNotExists=True)
    User.createTable(ifNotExists=True)

    return connection
    def __init__(self):
        self.registry = Registry(log=log)
        database_url = str(self.registry.get('database').get('database'))
        sqlhub.processConnection = connectionForURI(database_url)

        conn = boto.connect_s3()
        file_conn = boto.connect_s3()

        self.bucket = conn.get_bucket(self.registry.get('storage').get('bucket_name'))
        self.files_bucket = file_conn.get_bucket(self.registry.get('files').get('bucket_name'))
 def setUp(self, dsn=conf.LITE_DSN):
     """should load the dataset"""
     from sqlobject import connectionForURI
     self.conn = connectionForURI(dsn)
     self.fixture.connection = self.conn
     
     from sqlobject import sqlhub
     sqlhub.processConnection = self.conn
     
     setup_db(self.conn)
Exemple #53
0
 def createConnection(self):
     connectionString = "sqlite:" + self._dbFile.replace("\\", "/").replace("C:","///C|/")
     connection = connectionForURI(connectionString)
     sqlhub.processConnection = connection
     if not os.path.exists(self._dbFile):
         if not os.path.exists(self._dbFolder):
             os.makedirs(self._dbFolder)
         self.createDatabase()
     else:
         self.clearDB()
Exemple #54
0
def getConnection(**kw):
    name = conftest.option.Database
    if conftest.connectionShortcuts.has_key(name):
        name = conftest.connectionShortcuts[name]
    conn = sqlobject.connectionForURI(name, **kw)
    if conftest.option.show_sql:
        conn.debug = True
    if conftest.option.show_sql_output:
        conn.debugOutput = True
    return conn
Exemple #55
0
    def __init__(self, sqlite=None):
        if not sqlite:
            sqlite = tempfile.mkstemp('.db', 'subGenCache-')[1]

        self.sqlite = sqlite
        uri = "sqlite://%s" % sqlite
        c = sqlobject.connectionForURI(uri)
        sqlobject.sqlhub.processConnection = c
        SubscriptableGenerator.Data.createTable(ifNotExists=True)

        self._genCounter = 1
Exemple #56
0
    def __init__(self):
        self.queue = EventQueue(handler=self._handle_task, name='RadiusQueue')
        self.queue.start()

        credentials = RadiusDatabaseConfig.user and (
            "%s%s@" % (RadiusDatabaseConfig.user,
                       RadiusDatabaseConfig.password and ":%s" %
                       (RadiusDatabaseConfig.password) or '')) or ''
        self.conn = sqlobject.connectionForURI(
            "mysql://%s%s/%s" % (credentials, RadiusDatabaseConfig.host,
                                 RadiusDatabaseConfig.database))
Exemple #57
0
 def __init__(self, *a,**kw):
     DataHandler.__init__(self, *a,**kw)
     from sqlobject import sqlhub, connectionForURI
     if self.options.dsn:
         self.connection = connectionForURI(self.options.dsn)
     else:
         raise MisconfiguredHandler(
                 "--dsn option is required by %s" % self.__class__)
     if len(self.options.env):
         raise NotImplementedError(
             "sqlobject is not using --env; perhaps we just need to import "
             "the envs so that findClass knows about its objects?")
def perform_sqlobject_benchmark(database, conn_str, args, benchmark_result):
    if database == 'sqlite':
        if conn_str == ':memory:':
            conn_str = 'sqlite:/:memory:'
    sqlhub.processConnection = connectionForURI(conn_str)
    Person.createTable()
    Address.createTable()
    test_data = test_data_from_args(args)
    assert test_data
    record_benchmark_result(
        benchmark_result, 'SQLObject', database, args.num_repeats
    )
Exemple #59
0
def configure():
    db = sqlobject.connectionForURI('sqlite:{0}'.format(
        config.DATABASE_LOCATION))
    sqlobject.sqlhub.processConnection = db
    for model in [models.User, models.Channel]:
        try:
            model.createTable()
        except OperationalError, err:
            logging.debug(err)
            logging.info('\t{0} table already exists'.format(model.__name__))
        else:
            logging.info('\t{0} table created'.format(model.__name__))