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


Python Store.rollback方法代码示例

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


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

示例1: SchemaTest

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

    def setUp(self):
        super(SchemaTest, self).setUp()
        self.database = create_database("sqlite:///%s" % self.makeFile())
        self.store = Store(self.database)

        self._package_dirs = set()
        self._package_names = set()
        self.package = self.create_package(self.makeDir(), "patch_package")
        import patch_package

        creates = ["CREATE TABLE person (id INTEGER, name TEXT)"]
        drops = ["DROP TABLE person"]
        deletes = ["DELETE FROM person"]

        self.schema = Schema(creates, drops, deletes, patch_package)

    def tearDown(self):
        for package_dir in self._package_dirs:
            sys.path.remove(package_dir)

        for name in list(sys.modules):
            if name in self._package_names:
                del sys.modules[name]
            elif filter(
                None,
                [name.startswith("%s." % x) for x in self._package_names]):
                del sys.modules[name]

        super(SchemaTest, self).tearDown()

    def create_package(self, base_dir, name, init_module=None):
        """Create a Python package.

        Packages created using this method will be removed from L{sys.path}
        and L{sys.modules} during L{tearDown}.

        @param package_dir: The directory in which to create the new package.
        @param name: The name of the package.
        @param init_module: Optionally, the text to include in the __init__.py
            file.
        @return: A L{Package} instance that can be used to create modules.
        """
        package_dir = os.path.join(base_dir, name)
        self._package_names.add(name)
        os.makedirs(package_dir)

        file = open(os.path.join(package_dir, "__init__.py"), "w")
        if init_module:
            file.write(init_module)
        file.close()
        sys.path.append(base_dir)
        self._package_dirs.add(base_dir)

        return Package(package_dir, name)

    def test_create(self):
        """
        L{Schema.create} can be used to create the tables of a L{Store}.
        """
        self.assertRaises(StormError,
                          self.store.execute, "SELECT * FROM person")
        self.schema.create(self.store)
        self.assertEquals(list(self.store.execute("SELECT * FROM person")), [])

    def test_create_with_autocommit_off(self):
        """
        L{Schema.autocommit} can be used to turn automatic commits off.
        """
        self.schema.autocommit(False)
        self.schema.create(self.store)
        self.store.rollback()
        self.assertRaises(StormError, self.store.execute,
                          "SELECT * FROM patch")

    def test_drop(self):
        """
        L{Schema.drop} can be used to drop the tables of a L{Store}.
        """
        self.schema.create(self.store)
        self.assertEquals(list(self.store.execute("SELECT * FROM person")), [])
        self.schema.drop(self.store)
        self.assertRaises(StormError,
                          self.store.execute, "SELECT * FROM person")

    def test_delete(self):
        """
        L{Schema.delete} can be used to clear the tables of a L{Store}.
        """
        self.schema.create(self.store)
        self.store.execute("INSERT INTO person (id, name) VALUES (1, 'Jane')")
        self.assertEquals(list(self.store.execute("SELECT * FROM person")),
                          [(1, u"Jane")])
        self.schema.delete(self.store)
        self.assertEquals(list(self.store.execute("SELECT * FROM person")), [])

    def test_upgrade_creates_schema(self):
        """
        L{Schema.upgrade} creates a schema from scratch if no exist, and is
#.........这里部分代码省略.........
开发者ID:petrhosek,项目名称:storm,代码行数:103,代码来源:schema.py

示例2: TestChangeTracker

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


    class A(object):
        __storm_table__ = 'testob'
        changehistory = ChangeHistory.configure("history")
        clt = ChangeTracker(changehistory)
        id = Int(primary=1)
        textval = Unicode(validator=clt)
        intval = Int(validator=clt)

    def setUp(self):
        database = create_database('sqlite:')
        self.store = Store(database)
        self.store.execute("""
            CREATE table history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                ref_class VARCHAR(200),
                ref_pk VARCHAR(200),
                ref_attr VARCHAR(200),
                new_value VARCHAR(200),
                ctime DATETIME,
                cuser INT
            )
        """)
        self.store.execute("""
            CREATE TABLE testob (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                textval VARCHAR(200),
                intval INT,
                dateval DATETIME
            )""")

    def tearDown(self):
        self.store.rollback()

    def test_calls_next_validator(self):
        clt = ChangeTracker(ChangeHistory.configure("history"), next_validator = lambda ob, attr, v: v*2)

        class B(self.A):
            textval = Unicode(validator=clt)

        b = B()
        b.textval = u'bork'
        assert b.textval == u'borkbork'

    def test_adds_log_entries(self):

        class B(self.A):
            clt = ChangeTracker(ChangeHistory.configure("history"))
            textval = Unicode(validator=clt)

        b = self.store.add(B())
        b.textval = u'pointless'
        b.textval = u'aimless'
        changes = list(self.store.find(b.clt.change_cls))
        assert_equal(len(changes), 2)
        assert_equal(changes[0].new_value, 'pointless')
        assert_equal(changes[1].new_value, 'aimless')

    def test_value_type_preserved(self):
        a = self.store.add(self.A())
        a.textval = u'one'
        a.intval = 1
        changes = list(self.store.find(a.clt.change_cls))
        assert_equal(type(changes[0].new_value), unicode)
        assert_equal(type(changes[1].new_value), int)

    def test_ctime_set(self):
        start = datetime.now()
        a = self.store.add(self.A())
        a.textval = u'x'
        changes = list(self.store.find(a.clt.change_cls))
        assert_equal(type(changes[0].ctime), datetime)
        assert start < changes[0].ctime < datetime.now()

    def test_cuser_set(self):
        def getuser():
            return u'Fred'

        history = ChangeHistory.configure("history", getuser=getuser, usertype=Unicode)
        class B(self.A):
            textval = Unicode(validator=ChangeTracker(history))

        b = self.store.add(B())
        b.textval = u'foo'
        changes = self.store.find(history)
        assert_equal(changes[0].cuser, u'Fred')


    def test_changes_for_returns_change_history(self):
        a = self.store.add(self.A())
        b = self.store.add(self.A())
        a.id = 1
        a.textval = u'one'
        a.textval = u'two'
        b.id = 2
        b.textval = u'ein'
        b.textval = u'zwei'

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

示例3: db_update_schema

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import rollback [as 别名]
def db_update_schema(database):
    """
        Check for pending database schema updates.
        If any are found, apply them and bump the version.
    """

    # Connect to the database
    db_store = Store(database)

    # Check if the DB schema has been loaded
    db_exists = False
    try:
        db_store.execute(Select(DBSchema.version))
        db_exists = True
    except:
        db_store.rollback()
        logging.debug("Failed to query schema table.")

    if not db_exists:
        logging.info("Creating database")
        schema_file = sorted(glob.glob("schema/schema-*.sql"))[-1]
        schema_version = schema_file.split(".")[0].split("-")[-1]
        logging.debug("Using '%s' to deploy schema '%s'" % (schema_file,
                                                            schema_version))
        with open(schema_file, "r") as fd:
            try:
                for line in fd.read().replace("\n", "").split(";"):
                    if not line:
                        continue
                    db_store.execute("%s;" % line)
                    db_commit(db_store)
                logging.info("Database created")
            except:
                logging.critical("Failed to initialize the database")
                return False

    # Get schema version
    version = db_store.execute(Select(Max(DBSchema.version))).get_one()[0]
    if not version:
        logging.critical("No schema version.")
        return False

    # Apply updates
    for update_file in sorted(glob.glob("schema/update-*.sql")):
        update_version = update_file.split(".")[0].split("-")[-1]
        if int(update_version) > version:
            logging.info("Using '%s' to deploy update '%s'" % (update_file,
                                                               update_version))
            with open(update_file, "r") as fd:
                try:
                    for line in fd.read().replace("\n", "").split(";"):
                        if not line:
                            continue
                        db_store.execute("%s;" % line)
                        db_commit(db_store)
                except:
                    logging.critical("Failed to load schema update")
                    return False

    # Get schema version
    new_version = db_store.execute(Select(Max(DBSchema.version))).get_one()[0]
    if new_version > version:
        logging.info("Database schema successfuly updated from '%s' to '%s'" %
                     (version, new_version))

    db_store.close()
开发者ID:scarpentier,项目名称:askgod,代码行数:68,代码来源:db.py

示例4: PatchTest

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

    def setUp(self):
        super(PatchTest, self).setUp()

        self.patchdir = self.makeDir()
        self.pkgdir = os.path.join(self.patchdir, "mypackage")
        os.makedirs(self.pkgdir)

        f = open(os.path.join(self.pkgdir, "__init__.py"), "w")
        f.write("shared_data = []")
        f.close()

        # Order of creation here is important to try to screw up the
        # patch ordering, as os.listdir returns in order of mtime (or
        # something).
        for pname, data in [("patch_380.py", patch_test_1),
                            ("patch_42.py", patch_test_0)]:
            self.add_module(pname, data)

        sys.path.append(self.patchdir)

        self.filename = self.makeFile()
        self.uri = "sqlite:///%s" % self.filename
        self.store = Store(create_database(self.uri))

        self.store.execute("CREATE TABLE patch "
                           "(version INTEGER NOT NULL PRIMARY KEY)")

        self.assertFalse(self.store.get(Patch, (42)))
        self.assertFalse(self.store.get(Patch, (380)))

        import mypackage
        self.mypackage = mypackage

        # Create another connection just to keep track of the state of the
        # whole transaction manager.  See the assertion functions below.
        self.another_store = Store(create_database("sqlite:"))
        self.another_store.execute("CREATE TABLE test (id INT)")
        self.another_store.commit()
        self.prepare_for_transaction_check()

        class Committer(object):

            def commit(committer):
                self.store.commit()
                self.another_store.commit()

            def rollback(committer):
                self.store.rollback()
                self.another_store.rollback()

        self.committer = Committer()
        self.patch_applier = PatchApplier(self.store, self.mypackage,
                                          self.committer)

    def tearDown(self):
        super(PatchTest, self).tearDown()
        self.committer.rollback()
        sys.path.remove(self.patchdir)
        for name in list(sys.modules):
            if name == "mypackage" or name.startswith("mypackage."):
                del sys.modules[name]

    def add_module(self, module_filename, contents):
        filename = os.path.join(self.pkgdir, module_filename)
        file = open(filename, "w")
        file.write(contents)
        file.close()

    def remove_all_modules(self):
        for filename in os.listdir(self.pkgdir):
            os.unlink(os.path.join(self.pkgdir, filename))

    def prepare_for_transaction_check(self):
        self.another_store.execute("DELETE FROM test")
        self.another_store.execute("INSERT INTO test VALUES (1)")

    def assert_transaction_committed(self):
        self.another_store.rollback()
        result = self.another_store.execute("SELECT * FROM test").get_one()
        self.assertEquals(result, (1,),
                          "Transaction manager wasn't committed.")

    def assert_transaction_aborted(self):
        self.another_store.commit()
        result = self.another_store.execute("SELECT * FROM test").get_one()
        self.assertEquals(result, None,
                          "Transaction manager wasn't aborted.")

    def test_apply(self):
        """
        L{PatchApplier.apply} executes the patch with the given version.
        """
        self.patch_applier.apply(42)

        x = getattr(self.mypackage, "patch_42").x
        self.assertEquals(x, 42)
        self.assertTrue(self.store.get(Patch, (42)))
        self.assertTrue("mypackage.patch_42" in sys.modules)
#.........这里部分代码省略.........
开发者ID:DamnWidget,项目名称:mamba-storm,代码行数:103,代码来源:patch.py


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