【问题标题】:How to set SQLite PRAGMA statements with SQLAlchemy如何使用 SQLAlchemy 设置 SQLite PRAGMA 语句
【发布时间】:2012-03-29 02:43:27
【问题描述】:

我希望 SQLAlchemy 将 SQLite .journal 文件放在内存中以提高性能。我试过这个:

sqlite_db_engine = create_engine('sqlite:///%s' % str(dbname), connect_args = {'PRAGMA     journal_mode':'MEMORY', 'PRAGMA synchronous':'OFF', 'PRAGMA temp_store':'MEMORY', 'PRAGMA cache_size':'5000000'})

db = sqlite_db_engine.connect()

还有这个:

sqlite_db_engine = create_engine('sqlite:///%s' % str(dbname))

db = sqlite_db_engine.connect()
db.execute("PRAGMA journal_mode = MEMORY")
db.execute("PRAGMA synchronous = OFF")
db.execute("PRAGMA temp_store = MEMORY")
db.execute("PRAGMA cache_size = 500000")

没有运气。对于长事务,我仍然可以看到正在磁盘上创建的 .journal 文件。还有其他方法可以设置吗?

*注意我使用内置的python sqlite模块没有问题

【问题讨论】:

  • 我也尝试添加一个像这个线程这样的监听器:stackoverflow.com/questions/2614984/…
  • 我在尝试使用您的代码时收到错误 DBAPIError: (TypeError) 'PRAGMA cache_size' is an invalid keyword argument for this function None None。你也遇到了同样的错误?
  • 我没有收到任何错误,代码执行得很好,但显然什么也没做。

标签: sqlite sqlalchemy


【解决方案1】:

如何使用事件:

from sqlalchemy.engine import Engine
from sqlalchemy import event

@event.listens_for(Engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
    cursor = dbapi_connection.cursor()
    cursor.execute("PRAGMA journal_mode=WAL")
    cursor.close()

http://docs.sqlalchemy.org/en/rel_0_9/dialects/sqlite.html#foreign-key-support

【讨论】:

  • 有没有办法根据目标数据库(例如 SQLite3 vs MySQL vs PostgreSQL)注册不同的侦听器,或者至少在您进入侦听器的主体后将它们区分开来(即以编程方式检查这个?
【解决方案2】:

基本上你应该能够重写关于外键的例子来实现你想要的。看看https://stackoverflow.com/a/7831210/1890086

engine = create_engine(database_url)

def _fk_pragma_on_connect(dbapi_con, con_record):
    dbapi_con.execute('PRAGMA journal_mode = MEMORY')
    # ...

from sqlalchemy import event
event.listen(engine, 'connect', _fk_pragma_on_connect)

【讨论】:

    【解决方案3】:

    之前的两个解决方案都不起作用,所以我找到了the another one

    from sqlalchemy.interfaces import PoolListener
    class MyListener(PoolListener):
        def connect(self, dbapi_con, con_record):
            dbapi_con.execute('pragma journal_mode=OFF')
            dbapi_con.execute('PRAGMA synchronous=OFF')
            dbapi_con.execute('PRAGMA cache_size=100000')
    
    engine = create_engine('sqlite:///' + basefile,echo=False, listeners= [MyListener()])
    

    【讨论】:

    • 在最近的版本中,这将给出:SADeprecationWarning:Pool(和 create_engine())的 'listeners' 参数已被弃用。使用 event.listen()
    猜你喜欢
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 2012-04-15
    • 2011-05-30
    • 1970-01-01
    • 2019-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多