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


Python Store.execute方法代码示例

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


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

示例1: BioDBBase

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import execute [as 别名]
class BioDBBase(object):
    def __init__(self, db_name):       
        self.db_name= db_name
        self.__init_database()


    def __init_database(self):    
        """
        creates the sqlite database instance and checks if the database exists in biodb.
        """
        database= create_database("sqlite:%s" % biodb_sql_db_path)
        print "Created storm database from %s." % biodb_sql_db_path
        self.store= Store(database)
        

    def init_table(self):
        self.biodb_table = "biodb_" + self.db_name
        self.hier_table= "hier_"+ self.db_name
        self.lineage_table= "lineage_"+ self.db_name
      
        BioDB.__storm_table__ = self.biodb_table
        Hierarchy.__storm_table__ = self.hier_table
        Lineage.__storm_table__ = self.lineage_table
        #### check if the db_name exists in the database
        table_list= [table[0] for table in self.store.execute('select tbl_name from SQLITE_MASTER')]
       
        return 0 if self.biodb_table not in table_list else 1 
开发者ID:ecotox,项目名称:biodb,代码行数:29,代码来源:biodb_base.py

示例2: _checkValidDatabase

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import execute [as 别名]
    def _checkValidDatabase(self, storage):
        '''Checks the Store to make sure it has a valid database'''

        store = Store(storage)
        for table in SCHEMA.iterkeys():
            result = store.execute('SELECT * FROM `%s`' % table.lower())
            self.assertEqual(result.get_all(), [])
        return True
开发者ID:tiwilliam,项目名称:entertainer,代码行数:10,代码来源:test_database.py

示例3: createTable

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import execute [as 别名]
def createTable(model, transactor, database):
    """
    Create the table for the specified model.
    Specification of a transactor and database is useful in unittesting.
    """
    if not transactor:
        from oonib.db import transactor
    if not database:
        from oonib.db import database
    store = Store(database)
    create_query = generateCreateQuery(model)
    try:
        store.execute(create_query)
    # XXX trap the specific error that is raised when the table exists
    except StormError, e:
        print "Failed to create table!"
        print e
        store.close()
开发者ID:Shadiesna,项目名称:ooni-probe,代码行数:20,代码来源:tables.py

示例4: getStore

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import execute [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

示例5: createTable

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import execute [as 别名]
def createTable(model, transactor, database):
    """
    Create the table for the specified model.
    It will default to using globaleaks.db transactor and database if none is
    specified.
    Specification of a transactor and database is useful in unittesting.
    """
    if not transactor:
        from globaleaks.db import transactor
    if not database:
        from globaleaks.db import database
    store = Store(database)
    create_query = generateCreateQuery(model)

    try:
        store.execute(create_query)
    # XXX trap the specific error that is raised when the table exists
    # seem to be OperationalError raised, but not a specific error exists.
    except StormError, e:
        print "Failed to create table!", e
        store.close()
开发者ID:Afridocs,项目名称:GLBackend,代码行数:23,代码来源:tables.py

示例6: test_schema_uri

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import execute [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

示例7: perform_storm_benchmark

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import execute [as 别名]
def perform_storm_benchmark(database, conn_str, args, benchmark_result):
    if database == 'sqlite':
        if conn_str == ':memory:':
            conn_str = 'sqlite:'
    db = create_database(conn_str)
    store = Store(db)
    if database == 'sqlite':
        store.execute("""
            CREATE TABLE person
            (id INTEGER PRIMARY KEY, name VARCHAR)
        """)
        store.execute("""
            CREATE TABLE address
            (id INTEGER PRIMARY KEY, address VARCHAR, person_id INTEGER,
            FOREIGN KEY(person_id) REFERENCES person(id))
        """)
    elif database == 'mysql':
        store.execute("""
            CREATE TABLE person
            (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
             name VARCHAR(256))
        """)
        store.execute("""
            CREATE TABLE address
            (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
             address VARCHAR(256),
             person_id INT,
             FOREIGN KEY(person_id) REFERENCES person(id))
        """)
    __builtin__.__dict__.update(locals())
    test_data = test_data_from_args(args)
    if 'Storm' not in benchmark_result:
        benchmark_result['Storm'] = dict()
    if database not in benchmark_result['Storm']:
        benchmark_result['Storm'][database] = dict()
    test_aspects = ['insert', 'read', 'update', 'delete']
    timeit_funcs = [
        "_{0}_{1}_data(test_data, store)".format(
            'storm', test_aspect
        )
        for test_aspect in test_aspects
    ]
    for index, tf in enumerate(timeit_funcs):
        rst = timeit.timeit(tf, number=args.num_repeats)
        benchmark_result['Storm'][database][test_aspects[index]] = rst
开发者ID:XiaonuoGantan,项目名称:sqlalchemy_benchmarks,代码行数:47,代码来源:storm_benchmark.py

示例8: _create

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import execute [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

示例9: SchemaTest

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import execute [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_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
        effectively equivalent to L{Schema.create} in such case.
        """
        self.assertRaises(StormError,
                          self.store.execute, "SELECT * FROM person")
        self.schema.upgrade(self.store)
        self.assertEquals(list(self.store.execute("SELECT * FROM person")), [])

    def test_upgrade_marks_patches_applied(self):
        """
        L{Schema.upgrade} updates the patch table after applying the needed
#.........这里部分代码省略.........
开发者ID:datnguyen0606,项目名称:storm,代码行数:103,代码来源:schema.py

示例10: ZStormResourceManagerTest

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import execute [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

示例11: ZStormResourceManagerTest

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

    def is_supported(self):
        return has_zope and has_testresources

    def setUp(self):
        super(ZStormResourceManagerTest, self).setUp()
        self._package_dir = self.makeDir()
        sys.path.append(self._package_dir)
        patch_dir = os.path.join(self._package_dir, "patch_package")
        os.mkdir(patch_dir)
        self.makeFile(path=os.path.join(patch_dir, "__init__.py"), content="")
        self.makeFile(path=os.path.join(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"]
        schema = ZSchema(create, drop, delete, patch_package)
        uri = "sqlite:///%s" % self.makeFile()
        self.resource = ZStormResourceManager({"test": (uri, schema)})
        self.store = Store(create_database(uri))

    def tearDown(self):
        del sys.modules["patch_package"]
        sys.path.remove(self._package_dir)
        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_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_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_clean_flush(self):
        """
        L{ZStormResourceManager.clean} tries to flush the stores to make sure
        that they are all in a consistent state.
        """

        class Test(object):
            __storm_table__ = "test"
            foo = Unicode()
            bar = Int(primary=True)

            def __init__(self, foo, bar):
                self.foo = foo
                self.bar = bar

        zstorm = self.resource.make([])
        store = zstorm.get("test")
        store.add(Test(u"data", 1))
        store.add(Test(u"data", 2))
        self.assertRaises(IntegrityError, self.resource.clean, zstorm)

    def test_clean_delete(self):
        """
        L{ZStormResourceManager.clean} cleans the database tables from the data
        created by the tests.
        """
        zstorm = self.resource.make([])
        store = zstorm.get("test")
        store.execute("INSERT INTO test (foo, bar) VALUES ('data', 123)")
        store.commit()
        self.resource.clean(zstorm)
        self.assertEqual([], list(self.store.execute("SELECT * FROM test")))
开发者ID:quodt,项目名称:storm,代码行数:99,代码来源:testing.py

示例12: __init__

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import execute [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

示例13: __repr__

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import execute [as 别名]
			id = self.id,
			name = self.name,
			age = self.age
		)

	def __repr__( self ):
		return '<Person (name=%s, age=%s)>' % (
			self.name,
			self.age,
		)

database = create_database('sqlite://:memory:')
store = Store(database)
store.execute('''CREATE TABLE person (
	id INTEGER PRIMARY KEY,
	name VARCHAR,
	age INTEGER
)''')

persons = [
	Person( name=u'Amy', age=52 ),
	Person( name=u'Bob', age=48 ),
	Person( name=u'Cat', age=23 ),
	Person( name=u'Dan', age=17 ),
	Person( name=u'Edd', age=77 ),
	Person( name=u'Fan', age=65 ),
	Person( name=u'Gin', age=27 ),
	Person( name=u'Hil', age=30 ),
	Person( name=u'Iri', age=62 ),
	Person( name=u'Jac', age=18 )
]
开发者ID:ippo615,项目名称:experiments,代码行数:33,代码来源:export.py

示例14: Sale

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import execute [as 别名]
from kiwi.ui.objectlist import Column
from kiwi.ui.search import SearchContainer, DateSearchFilter


class Sale(object):
    __storm_table__ = 'sale'
    id = Int(primary=True)
    description = Unicode()
    price = Float()
    date = Date()

database = create_database("sqlite:")
store = Store(database)

store.execute(
    "CREATE TABLE sale "
    "(id INTEGER PRIMARY KEY, description VARCHAR, price FLOAT, date DATE)"
)

today = datetime.date.today()

for description, price, date in [
    ('Cup of coffee', 2.04, today - datetime.timedelta(1)),
    ('Chocolate bar', 1.85, today - datetime.timedelta(40)),
    ('Candy',         0.99, today - datetime.timedelta(30)),
    ('Grape Juice',   3.38, today - datetime.timedelta(23)),
    ('Ice tea',       1.25, today - datetime.timedelta(10)),
    ('Cookies',       0.85, today - datetime.timedelta(5)),
    ('Noogies',       1.45, today - datetime.timedelta(2)),
    ('Chocolate bar', 1.85, today)]:

    s = Sale()
开发者ID:gxela,项目名称:kiwi-gtk,代码行数:34,代码来源:search_storm.py

示例15: ZStormResourceManagerTest

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import execute [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()
        self._package_dir = self.makeDir()
        sys.path.append(self._package_dir)
        patch_dir = os.path.join(self._package_dir, "patch_package")
        os.mkdir(patch_dir)
        self.makeFile(path=os.path.join(patch_dir, "__init__.py"), content="")
        self.makeFile(path=os.path.join(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):
        del sys.modules["patch_package"]
        sys.path.remove(self._package_dir)
        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_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_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_zstorm_overwritten(self):
        """
        L{ZStormResourceManager.make} registers its own ZStorm again if a test
        has registered a new ZStorm utility overwriting the resource one.
        """
        zstorm = self.resource.make([])
        provideUtility(ZStorm())
        self.resource.make([])
        self.assertIs(zstorm, getUtility(IZStorm))

    def test_clean_flush(self):
        """
        L{ZStormResourceManager.clean} tries to flush the stores to make sure
        that they are all in a consistent state.
        """
        class Test(object):
            __storm_table__ = "test"
            foo = Unicode()
            bar = Int(primary=True)

            def __init__(self, foo, bar):
                self.foo = foo
                self.bar = bar

        zstorm = self.resource.make([])
        store = zstorm.get("test")
        store.add(Test(u"data", 1))
        store.add(Test(u"data", 2))
        self.assertRaises(IntegrityError, self.resource.clean, zstorm)

    def test_clean_delete(self):
        """
        L{ZStormResourceManager.clean} cleans the database tables from the data
        created by the tests.
#.........这里部分代码省略.........
开发者ID:datnguyen0606,项目名称:storm,代码行数:103,代码来源:testing.py


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