当前位置: 首页>>代码示例>>Python>>正文


Python Store.commit方法代码示例

本文整理汇总了Python中storm.locals.Store.commit方法的典型用法代码示例。如果您正苦于以下问题:Python Store.commit方法的具体用法?Python Store.commit怎么用?Python Store.commit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在storm.locals.Store的用法示例。


在下文中一共展示了Store.commit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: initialize

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import commit [as 别名]
 def initialize(self, debug=None):
     """See `IDatabase`."""
     # Calculate the engine url.
     url = expand(config.database.url, config.paths)
     log.debug('Database url: %s', url)
     # XXX By design of SQLite, database file creation does not honor
     # umask.  See their ticket #1193:
     # http://www.sqlite.org/cvstrac/tktview?tn=1193,31
     #
     # This sucks for us because the mailman.db file /must/ be group
     # writable, however even though we guarantee our umask is 002 here, it
     # still gets created without the necessary g+w permission, due to
     # SQLite's policy.  This should only affect SQLite engines because its
     # the only one that creates a little file on the local file system.
     # This kludges around their bug by "touch"ing the database file before
     # SQLite has any chance to create it, thus honoring the umask and
     # ensuring the right permissions.  We only try to do this for SQLite
     # engines, and yes, we could have chmod'd the file after the fact, but
     # half dozen and all...
     self.url = url
     self._prepare(url)
     database = create_database(url)
     store = Store(database, GenerationalCache())
     database.DEBUG = (as_boolean(config.database.debug)
                       if debug is None else debug)
     self.store = store
     store.commit()
开发者ID:trevor,项目名称:mailman3,代码行数:29,代码来源:base.py

示例2: test_check_unmodifiable_strings

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import commit [as 别名]
    def test_check_unmodifiable_strings(self):
        # This test case asserts that data migration updates unmodifiable l10n strings
        self._initStartDB(34)

        notification_l10n = NotificationL10NFactory(self.store)

        t0 = notification_l10n.get_val("export_template", "it")

        notification_l10n.set_val("export_template", "it", "")

        t1 = notification_l10n.get_val("export_template", "it")

        self.assertEqual(t1, "")

        self.store.commit()

        # place a dummy version in the current db
        store = Store(create_database(GLSettings.db_uri))
        prv = config.PrivateFactory(store)
        self.dummy_ver = "2.XX.XX"
        prv.set_val("version", self.dummy_ver)
        self.assertEqual(prv.get_val("version"), self.dummy_ver)
        store.commit()
        store.close()

        migration.perform_data_update(self.db_file)

        store = Store(create_database(GLSettings.db_uri))
        notification_l10n = NotificationL10NFactory(store)
        t2 = notification_l10n.get_val("export_template", "it")
        self.assertEqual(t2, t0)
        store.commit()
        store.close()

        shutil.rmtree(GLSettings.db_path)
开发者ID:globaleaks,项目名称:GlobaLeaks,代码行数:37,代码来源:test_migration.py

示例3: setUp

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import commit [as 别名]
    def setUp(self):
        helpers.init_glsettings_for_unit_tests()

        GLSettings.db_path = os.path.join(GLSettings.ramdisk_path, 'db_test')
        os.mkdir(GLSettings.db_path)
        db_name = 'glbackend-%d.db' % DATABASE_VERSION
        db_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'db', 'populated', db_name)
        shutil.copyfile(db_path, os.path.join(GLSettings.db_path, db_name))

        self.db_file = os.path.join(GLSettings.db_path, db_name)
        GLSettings.db_uri = GLSettings.make_db_uri(self.db_file)

        # place a dummy version in the current db
        store = Store(create_database(GLSettings.db_uri))
        prv = config.PrivateFactory(store)
        self.dummy_ver = '2.XX.XX'
        prv.set_val('version', self.dummy_ver)
        self.assertEqual(prv.get_val('version'), self.dummy_ver)
        store.commit()
        store.close()

        # backup various mocks that we will use
        self._bck_f = config.is_cfg_valid
        GLConfig['private']['xx_smtp_password'] = GLConfig['private'].pop('smtp_password')
        self.dp = u'yes_you_really_should_change_me'
开发者ID:Taipo,项目名称:GlobaLeaks,代码行数:27,代码来源:test_migration.py

示例4: test_migration_error_with_removed_language

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import commit [as 别名]
    def test_migration_error_with_removed_language(self):
        store = Store(create_database(GLSettings.db_uri))
        zyx = EnabledLanguage('zyx')
        store.add(zyx)
        store.commit()
        store.close()

        self.assertRaises(Exception, migration.perform_data_update, self.db_file)
开发者ID:Taipo,项目名称:GlobaLeaks,代码行数:10,代码来源:test_migration.py

示例5: do_statspollute

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import commit [as 别名]
def do_statspollute(dbfile):

    # source
    gl_database = create_database("sqlite:%s" % dbfile)
    source_store = Store(gl_database)

    stats = source_store.find(models.Stats)

    counter = 0
    for s in stats:
        source_store.remove(s)
        counter += 1

    print "removed %d entry in stats" % counter

    counter = 0
    # 21 days in the past
    for past_hours in xrange(24 * 7 * 3):
        past_hours += 4
        when = utc_past_date(hours=past_hours)

        newstat = models.Stats()
        newstat.freemb = randint(1000, 1050)
        newstat.year = when.isocalendar()[0]
        newstat.week = when.isocalendar()[1]

        level = round((randint(0, 1000) / 240.0), 1) - 2

        def random_pollution():
            return int(randint(0,11) + (5 * level))

        activity_fake = {
            'successfull_logins': random_pollution(),
            'failed_logins': random_pollution(),
            'started_submissions': random_pollution(),
            'completed_submissions': random_pollution(),
            'uploaded_files': int(randint(0,11) + (5  * level)),
            'appended_files': random_pollution(),
            'wb_comments': random_pollution(),
            'wb_messages': random_pollution(),
            'receiver_comments': random_pollution(),
            'receiver_messages': random_pollution()
        }

        for k, v in activity_fake.iteritems():
            if v < 0:
                activity_fake[k] = 0

        newstat.start = when
        newstat.summary = activity_fake
        counter += 1
        source_store.add(newstat)

    print "Committing %d stats" % counter
    source_store.commit()
开发者ID:RuanAragao,项目名称:GlobaLeaks,代码行数:57,代码来源:pollutestats.py

示例6: testCreate

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import commit [as 别名]
    def testCreate(self):
        """Test creation of new MusicTrack"""

        store = Store(self.db)
        musictrack = models.MusicTrack()
        musictrack.title = u"The Beautiful Ones"
        store.add(musictrack)
        store.commit()

        self.assertTrue(Store.of(musictrack) is store)

        musictrack_from_database = store.find(models.MusicTrack, models.MusicTrack.title == u"The Beautiful Ones").one()
        self.assertTrue(musictrack is musictrack_from_database)
开发者ID:tiwilliam,项目名称:entertainer,代码行数:15,代码来源:test_models.py

示例7: _create

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import commit [as 别名]
    def _create(self):
        '''Create a new entertainer database

        Reads the current database schema dictionary, and creates the sqlite
        database based on that schema
        '''

        store = Store(self._db)
        store.execute("""
        CREATE TABLE `entertainer_data` (
            name VARCHAR PRIMARY KEY,
            value VARCHAR);""")
        store.execute(
        "INSERT INTO `entertainer_data` VALUES ('version', '0.2a');")

        for query in SCHEMA.itervalues():
            store.execute(query, noresult=True)
            store.commit()
开发者ID:tiwilliam,项目名称:entertainer,代码行数:20,代码来源:connection.py

示例8: getStore

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import commit [as 别名]
def getStore(url, create = False):
    # register new Storm scheme
    register_scheme("sqlitefk", ForeignKeysSQLite)

    d = create_database(url)
    s = Store(d)

    if create:
        schema = file(os.path.join(os.path.dirname(__file__), "schema.sql"), "r").read().split("\n\n")
        for cmd in schema:
            s.execute(cmd)

        version = Meta()
        version.key = u"created"
        s.add(version)

        s.commit()

    return s
开发者ID:MarSik,项目名称:elshelves,代码行数:21,代码来源:model.py

示例9: test_schema_uri

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import commit [as 别名]
    def test_schema_uri(self):
        """
        It's possible to specify an alternate URI for applying the schema
        and cleaning up tables after a test.
        """
        schema_uri = "sqlite:///%s" % self.makeFile()
        self.databases[0]["schema-uri"] = schema_uri
        zstorm = self.resource.make([])
        store = zstorm.get("test")
        schema_store = Store(create_database(schema_uri))

        # The schema was applied using the alternate schema URI
        statement = "SELECT name FROM sqlite_master WHERE name='patch'"
        self.assertEqual([], list(store.execute(statement)))
        self.assertEqual([("patch",)], list(schema_store.execute(statement)))

        # The cleanup is performed with the alternate schema URI
        store.commit()
        schema_store.execute("INSERT INTO test (foo) VALUES ('data')")
        schema_store.commit()
        self.resource.clean(zstorm)
        self.assertEqual([], list(schema_store.execute("SELECT * FROM test")))
开发者ID:DamnWidget,项目名称:mamba-storm,代码行数:24,代码来源:testing.py

示例10: StormORM

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import commit [as 别名]

#.........这里部分代码省略.........
        '''
        @param uri: Database URI following storm rules.
        @param store: Storm store.
        
        If uri is given a new store is instanciated and it is used 
        to execute the statements.
        If both parameters are given the early created store overrides
        the store given.
        '''
        from storm.locals import create_database, Store
        self.uri = uri
        self.store = store
        if self.uri:
            database = create_database(self.uri)
            self.store = Store(database)
        if not self.store:
            raise Exception('None storm store')
        self.attrParser = StormAttributeParser()
            
    def _getObject(self, csvType, csvStatement):
        """
        Retrieves the object to be used at statement execution.
        
        @param csvType: The CSVType
        @param csvStatement: The CSVStatement
        
        @return: The object early instanciated (for insert statement) or
        retrieved from database (for update or delete statements).
        """
        typo = csvType.type
        keys = csvType.keys
        attributes = csvStatement.attributes
        if csvStatement.action in [DELETE, UPDATE]:
            if csvType.hasPrimaryKey:
                return self.store.get(typo, attributes[ csvType.primaryKey[0] ])
            else:
                pred = And([Eq(typo, key, attributes[i]) for i,key in keys.iteritems()])
                result = self.store.find(typo, pred)
                if result.count() == 0:
                    return None
                elif result.count() == 1:
                    return result.one()
                else:
                    return [r for r in result]
        elif csvStatement.action is INSERT:
            return typo()
    
    def executeStatement(self, csvType, csvStatement):
        """
        Executes csv statements matched by the pair csvType, csvStatement.
        
        @param csvType: The CSVType
        @param csvStatement: The CSVStatement
        
        @return: Total statements executed or raises a ValueError if the object retrieved with
        the pair csvType, csvStatement is None.
        """
        obj = self._getObject(csvType, csvStatement)
        
        if not obj:
            msg = 'Statement return None in line %d: %s' % (csvStatement.lineNumber, csvStatement.lineContent)
            raise ValueError(msg)
            
        objs = []
        
        if type(obj) is list:
            objs += obj
        else:
            objs.append(obj)
            
        i = 0
        for _obj in objs:
            self._executeStatement(_obj, csvType, csvStatement)
            i += 1
            
        return i
    
    def _executeStatement(self, obj, csvType, csvStatement):
        """
        Executes a single csv statement
        
        @param csvType: The CSVType
        @param csvStatement: The CSVStatement
        """
        keys = csvType.keys
        attributes = csvType.attributes
        values = csvStatement.attributes
        if csvStatement.action is INSERT:
            pairs = [(key, values[i]) for i,key in keys.iteritems()]
            pairs += [(key, values[i]) for i,key in attributes.iteritems()]
            for key, value in pairs:
                setattr(obj, key, value)
            self.store.add(obj)
        elif csvStatement.action is UPDATE:
            pairs = [(key, values[i]) for i,key in attributes.iteritems()]
            for key, value in pairs:
                setattr(obj, key, value)
        elif csvStatement.action is DELETE:
            self.store.remove(obj)
        self.store.commit()
开发者ID:wilsonfreitas,项目名称:easycsv,代码行数:104,代码来源:easycsv.py

示例11: __init__

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import commit [as 别名]

#.........这里部分代码省略.........
        """
        This method is create a copy of a DBIssueLog object
        """
        aux = DBIssuesLog(db_ilog.issue, db_ilog.tracker_id)
        aux.issue_id = db_ilog.issue_id
        aux.type = db_ilog.type
        aux.summary = db_ilog.summary
        aux.description = db_ilog.description
        aux.status = db_ilog.status
        aux.resolution = db_ilog.resolution
        aux.priority = db_ilog.priority
        aux.submitted_by = db_ilog.submitted_by
        aux.date = db_ilog.date
        aux.assigned_to = db_ilog.assigned_to
        return aux

    def build_initial_state(self, db_ilog):
        """
        This method gets the first changes of every field in
        order to get the initial state of the bug
        """
        fields = self.store.execute("SELECT DISTINCT(field) FROM changes where issue_id=%s" % (db_ilog.issue_id))

        for f in fields:
            value = self.store.execute(
                'SELECT old_value FROM changes WHERE issue_id=%s AND field="%s" ORDER BY changed_on LIMIT 1'
                % (db_ilog.issue_id, f[0])
            )
            for v in value:
                # Bugzilla section
                #
                if f[0] in bg_issues_links:
                    table_field = bg_issues_links[f[0]]
                    if table_field == "summary":
                        db_ilog.summary = v[0]
                    elif table_field == "priority":
                        db_ilog.priority = v[0]
                    elif table_field == "assigned_to":
                        db_ilog.assigned_to = v[0]
                    elif table_field == "status":
                        db_ilog.status = v[0]
                    elif table_field == "resolution":
                        db_ilog.resolution = v[0]
        return db_ilog

    def run(self):
        issues = self.store.find(DBIssue)
        for i in issues:
            db_ilog = DBIssuesLog(i.issue, i.tracker_id)
            db_ilog.issue_id = i.id
            db_ilog.type = i.type
            db_ilog.summary = i.summary
            db_ilog.description = i.description
            db_ilog.status = i.status
            db_ilog.resolution = i.resolution
            db_ilog.priority = i.priority
            db_ilog.submitted_by = i.submitted_by
            db_ilog.date = i.submitted_on
            db_ilog.assigned_to = i.assigned_to

            db_ilog = self.build_initial_state(db_ilog)

            self.store.add(db_ilog)

            # the code below gets all the changes and insert a row per change
            changes = self.store.execute(
                "SELECT field, new_value, changed_by, changed_on FROM changes where issue_id=%s" % (db_ilog.issue_id)
            )

            for ch in changes:
                field = ch[0]
                new_value = ch[1]
                changed_by = ch[2]
                date = ch[3]

                db_ilog = self.copy_issue(db_ilog)

                # Bugzilla section
                #
                if field in bg_issues_links:
                    table_field = bg_issues_links[field]
                    if table_field == "summary":
                        db_ilog.summary = new_value
                    elif table_field == "priority":
                        db_ilog.priority = new_value
                    elif table_field == "assignted_to":
                        db_ilog.assigned_to = new_value
                    elif table_field == "status":
                        db_ilog.status = new_value
                    elif table_field == "resolution":
                        db_ilog.resolution = new_value
                    db_ilog.submitted_by = changed_by
                    db_ilog.date = date

                    try:
                        self.store.add(db_ilog)
                    except:
                        traceback.print_exc()

            self.store.commit()
开发者ID:AlertProject,项目名称:Bicho,代码行数:104,代码来源:IssuesLog.py

示例12: TestMigrationRegression

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import commit [as 别名]
class TestMigrationRegression(unittest.TestCase):
    def _initStartDB(self, target_ver):
        helpers.init_glsettings_for_unit_tests()

        GLSettings.db_path = os.path.join(GLSettings.ramdisk_path, 'db_test')
        os.mkdir(GLSettings.db_path)
        db_name = 'glbackend-%d.db' % target_ver
        db_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'db', 'populated', db_name)
        shutil.copyfile(db_path, os.path.join(GLSettings.db_path, db_name))

        self.db_file = os.path.join(GLSettings.db_path, db_name)
        GLSettings.db_uri = GLSettings.make_db_uri(self.db_file)

        self.store = Store(create_database(GLSettings.db_uri))

    def test_check_field_constraints(self):
        # This test case asserts that a migration from db ver 32 up to 34 with
        # fields that fail the constraints still functions.
        self._initStartDB(32)

        field_dict = helpers.get_dummy_field()
        field_dict['instance'] = 'reference'
        field_dict['step_id'] = None
        field_dict['field_id'] = None

        db_create_field(self.store, field_dict, u'en')

        field_dict = helpers.get_dummy_field()
        field_dict['instance'] = 'instance'

        db_create_field(self.store, field_dict, u'en')

        field_dict = helpers.get_dummy_field()
        field_dict['instance'] = 'template'
        field_dict['step_id'] = None
        fld_grp_id = self.store.find(Field, Field.fieldgroup_id is not None)[0].fieldgroup_id
        field_dict['field_id'] = fld_grp_id

        db_create_field(self.store, field_dict, u'en')
        self.store.commit()

        ret = perform_system_update()
        shutil.rmtree(GLSettings.db_path)
        self.assertNotEqual(ret, -1)

    def test_check_unmodifiable_strings(self):
        # This test case asserts that data migration updates unmodifiable l10n strings
        self._initStartDB(34)

        notification_l10n = NotificationL10NFactory(self.store)

        t0 = notification_l10n.get_val('export_template', 'ar')

        #print notification_l10n.get_val('export_template', 'ar')
        notification_l10n.set_val('export_template', 'ar', '')

        t1 = notification_l10n.get_val('export_template', 'ar')

        self.assertEqual(t1, '')

        self.store.commit()

        # place a dummy version in the current db
        store = Store(create_database(GLSettings.db_uri))
        prv = config.PrivateFactory(store)
        self.dummy_ver = '2.XX.XX'
        prv.set_val('version', self.dummy_ver)
        self.assertEqual(prv.get_val('version'), self.dummy_ver)
        store.commit()
        store.close()

        migration.perform_data_update(self.db_file)

        # place a dummy version in the current db
        store = Store(create_database(GLSettings.db_uri))
        notification_l10n = NotificationL10NFactory(store)
        t2 = notification_l10n.get_val('export_template', 'ar')
        self.assertEqual(t2, t0)
        store.commit()
        store.close()

        shutil.rmtree(GLSettings.db_path)
开发者ID:Taipo,项目名称:GlobaLeaks,代码行数:84,代码来源:test_migration.py

示例13: ZStormResourceManagerTest

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import commit [as 别名]
class ZStormResourceManagerTest(TestHelper):

    def is_supported(self):
        return has_transaction and has_zope_component and has_testresources

    def setUp(self):
        super(ZStormResourceManagerTest, self).setUp()
        package_dir = self.makeDir()
        sys.path.append(package_dir)
        self.patch_dir = os.path.join(package_dir, "patch_package")
        os.mkdir(self.patch_dir)
        self.makeFile(path=os.path.join(self.patch_dir, "__init__.py"),
                      content="")
        self.makeFile(path=os.path.join(self.patch_dir, "patch_1.py"),
                      content=PATCH)
        import patch_package
        create = ["CREATE TABLE test (foo TEXT UNIQUE, bar INT)"]
        drop = ["DROP TABLE test"]
        delete = ["DELETE FROM test"]
        uri = "sqlite:///%s" % self.makeFile()
        schema = ZSchema(create, drop, delete, patch_package)
        self.databases = [{"name": "test", "uri": uri, "schema": schema}]
        self.resource = ZStormResourceManager(self.databases)
        self.store = Store(create_database(uri))

    def tearDown(self):
        global_zstorm._reset()
        del sys.modules["patch_package"]
        if "patch_1" in sys.modules:
            del sys.modules["patch_1"]
        super(ZStormResourceManagerTest, self).tearDown()

    def test_make(self):
        """
        L{ZStormResourceManager.make} returns a L{ZStorm} resource that can be
        used to get the registered L{Store}s.
        """
        zstorm = self.resource.make([])
        store = zstorm.get("test")
        self.assertEqual([], list(store.execute("SELECT foo, bar FROM test")))

    def test_make_lazy(self):
        """
        L{ZStormResourceManager.make} does not create all stores upfront, but
        only when they're actually used, likewise L{ZStorm.get}.
        """
        zstorm = self.resource.make([])
        self.assertEqual([], list(zstorm.iterstores()))
        store = zstorm.get("test")
        self.assertEqual([("test", store)], list(zstorm.iterstores()))

    def test_make_upgrade(self):
        """
        L{ZStormResourceManager.make} upgrades the schema if needed.
        """
        self.store.execute("CREATE TABLE patch "
                           "(version INTEGER NOT NULL PRIMARY KEY)")
        self.store.execute("CREATE TABLE test (foo TEXT)")
        self.store.commit()
        zstorm = self.resource.make([])
        store = zstorm.get("test")
        self.assertEqual([], list(store.execute("SELECT bar FROM test")))

    def test_make_upgrade_unknown_patch(self):
        """
        L{ZStormResourceManager.make} resets the schema if an unknown patch
        is found
        """
        self.store.execute("CREATE TABLE patch "
                           "(version INTEGER NOT NULL PRIMARY KEY)")
        self.store.execute("INSERT INTO patch VALUES (2)")
        self.store.execute("CREATE TABLE test (foo TEXT, egg BOOL)")
        self.store.commit()
        zstorm = self.resource.make([])
        store = zstorm.get("test")
        self.assertEqual([], list(store.execute("SELECT foo, bar FROM test")))
        self.assertEqual([(1,)],
                         list(store.execute("SELECT version FROM patch")))

    def test_make_delete(self):
        """
        L{ZStormResourceManager.make} deletes the data from all tables to make
        sure that tests run against a clean database.
        """
        self.store.execute("CREATE TABLE patch "
                           "(version INTEGER NOT NULL PRIMARY KEY)")
        self.store.execute("CREATE TABLE test (foo TEXT)")
        self.store.execute("INSERT INTO test (foo) VALUES ('data')")
        self.store.commit()
        zstorm = self.resource.make([])
        store = zstorm.get("test")
        self.assertEqual([], list(store.execute("SELECT foo FROM test")))

    def test_make_commits_transaction_once(self):
        """
        L{ZStormResourceManager.make} commits schema changes only once
        across all stores, after all patch and delete statements have
        been executed.
        """
        database2 = {"name": "test2",
#.........这里部分代码省略.........
开发者ID:DamnWidget,项目名称:mamba-storm,代码行数:103,代码来源:testing.py

示例14: __init__

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import commit [as 别名]
class TableReplacer:
    """
    This is the base class used by every Updater
    """

    def __init__(self, old_db_file, new_db_file, start_ver):

        from globaleaks.db.update_5_6 import User_version_5, Comment_version_5, Node_version_5
        from globaleaks.db.update_6_7 import Node_version_6, Context_version_6
        from globaleaks.db.update_7_8 import Node_version_7, Notification_version_7, Context_version_7, \
            Receiver_version_7, InternalFile_version_7
        from globaleaks.db.update_8_9 import Context_version_8, Receiver_version_8, Notification_version_8
        from globaleaks.db.update_9_10 import Node_version_9, ApplicationData_version_10, \
            Receiver_version_9, User_version_9
        from globaleaks.db.update_10_11 import InternalTip_version_10, InternalFile_version_10
        from globaleaks.db.update_11_12 import Node_version_11, ApplicationData_version_11, Context_version_11

        self.old_db_file = old_db_file
        self.new_db_file = new_db_file
        self.start_ver = start_ver

        self.std_fancy = " ł "
        self.debug_info = "   [%d => %d] " % (start_ver, start_ver + 1)

        self.table_history = {
            'Node' : [ Node_version_5, Node_version_6, Node_version_7, Node_version_9, None, Node_version_11, None, models.Node],
            'User' : [ User_version_5, User_version_9, None, None, None, models.User, None, None],
            'Context' : [ Context_version_6, None, Context_version_7, Context_version_8, Context_version_11, None, None, models.Context],
            'Receiver': [ Receiver_version_7, None, None, Receiver_version_8, Receiver_version_9, models.Receiver, None, None],
            'ReceiverFile' : [ models.ReceiverFile, None, None, None, None, None, None, None],
            'Notification': [ Notification_version_7, None, None, Notification_version_8, models.Notification, None, None, None],
            'Comment': [ Comment_version_5, models.Comment, None, None, None, None, None, None],
            'InternalTip' : [ InternalTip_version_10, None, None, None, None, None, models.InternalTip, None],
            'InternalFile' : [ InternalFile_version_7, None, None, InternalFile_version_10, None, None, models.InternalFile, None],
            'WhistleblowerTip' : [ models.WhistleblowerTip, None, None, None, None, None, None, None],
            'ReceiverTip' : [ models.ReceiverTip, None, None, None, None, None, None , None],
            'ReceiverInternalTip' : [ models.ReceiverInternalTip, None, None, None, None, None, None, None],
            'ReceiverContext' : [ models.ReceiverContext, None, None, None, None, None, None, None],
            'Message' : [ models.Message, None, None, None, None, None, None, None],
            'Stats' : [models.Stats, None, None, None, None, None, None, None],
            'ApplicationData' : [ApplicationData_version_10, None, None, None, None, None, None, models.ApplicationData],
        }

        for k, v in self.table_history.iteritems():
            # +1 because count start from 0,
            # -5 because the relase 0,1,2,3,4 are not supported anymore
            assert len(v) == (DATABASE_VERSION + 1 - 5), \
                "I'm expecting a table with %d statuses (%s)" % (DATABASE_VERSION, k)

        print "%s Opening old DB: %s" % (self.debug_info, old_db_file)
        old_database = create_database("sqlite:%s" % self.old_db_file)
        self.store_old = Store(old_database)

        GLSetting.db_file = new_db_file

        new_database = create_database("sqlite:%s" % new_db_file)
        self.store_new = Store(new_database)

        if self.start_ver + 1 == DATABASE_VERSION:

            print "%s Acquire SQL schema %s" % (self.debug_info, GLSetting.db_schema_file)

            if not os.access(GLSetting.db_schema_file, os.R_OK):
                print "Unable to access %s" % GLSetting.db_schema_file
                raise Exception("Unable to access db schema file")

            with open(GLSetting.db_schema_file) as f:
                create_queries = ''.join(f.readlines()).split(';')
                for create_query in create_queries:
                    try:
                        self.store_new.execute(create_query+';')
                    except OperationalError:
                        print "OperationalError in [%s]" % create_query

            self.store_new.commit()
            return
            # return here and manage the migrant versions here:

        for k, v in self.table_history.iteritems():

            create_query = self.get_right_sql_version(k, self.start_ver +1)
            if not create_query:
                # table not present in the version
                continue

            try:
                self.store_new.execute(create_query+';')
            except OperationalError as excep:
                print "%s OperationalError in [%s]" % (self.debug_info, create_query)
                raise excep

        self.store_new.commit()

    def close(self):
        self.store_old.close()
        self.store_new.close()

    def initialize(self):
        pass

#.........这里部分代码省略.........
开发者ID:Acidburn0zzz,项目名称:GLBackend,代码行数:103,代码来源:base_updater.py

示例15: IssuesLog

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import commit [as 别名]

#.........这里部分代码省略.........
            aux.assigned_to = db_ilog.assigned_to

            aux.link = db_ilog.link
            aux.component = db_ilog.component
            aux.version = db_ilog.version
            aux.issue_key = db_ilog.issue_key
            aux.environment = db_ilog.environment
            aux.project = db_ilog.project
            aux.project_key = db_ilog.project_key
            aux.security = db_ilog.security

            return aux

    def get_people_id(self, email, tracker_id):
        """
        Gets the id of an user
        """
        p = self.store.find(DBPeople, DBPeople.email == email).one()
        ##
        ## the code below was created ad-hoc for KDE solid
        ##
        try:
            return p.id
        except AttributeError:
            p = self.store.find(DBPeople, DBPeople.user_id == email).one()
            try:
                return p.id
            except AttributeError:
                # no person was found in People with the email above, so
                # we include it
                printdbg("Person not found. Inserted with email %s " % (email))
                dp = DBPeople(email, tracker_id)
                self.store.add(dp)
                self.store.commit()
                return dp.id

    def get_last_change_date(self):
        """
        This method gets the date of the last change included in the log table
        """
        if self.backend_is_bugzilla():
            result = self.store.find(DBBugzillaIssuesLog)
            aux = result.order_by(Desc(DBBugzillaIssuesLog.date))[:1]
            for entry in aux:
                return entry.date
        elif self.backend_is_jira():
            result = self.store.find(DBJiraIssuesLog)
            aux = result.order_by(Desc(DBJiraIssuesLog.date))[:1]
            for entry in aux:
                return entry.date
        return None

    def get_issues_changed_since(self, date):
        """
        This method fetchs the issues changes since date
        """

        #SELECT DISTINCT(issues.id) FROM issues, changes
        #WHERE issues.id = changes.issue_id
        #AND (issues.submitted_on >= '2012-02-28 12:34:44'
        #    OR changes.changed_on >= '2012-02-28 12:34:44');

        result = self.store.find(DBIssue,
                                 DBChange.issue_id == DBIssue.id,
                                 Or(DBIssue.submitted_on > date,
                                    DBChange.changed_on > date )).group_by(DBIssue.id)
开发者ID:MetricsGrimoire,项目名称:Bicho,代码行数:70,代码来源:logtable.py


注:本文中的storm.locals.Store.commit方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。