我希望SQLAlchemy在.create_all()期间创建FTS3表。我需要添加哪些特殊选项,以便它知道CREATE VIRTUAL TABLE ... USING FTS3(tokenizer=...)

最佳答案

据我所知,要实现此功能,您必须改进sqlite方言以更改create_table行为。

但是您可以将这种快速但丑陋的解决方案与“monkeypatching”一起使用

# ugly monkeypatch
from sqlalchemy.dialects.sqlite.base import SQLiteDDLCompiler

old_create_table = SQLiteDDLCompiler.visit_create_table

def new_create_table(*args, **kwargs):
    sql = old_create_table(*args, **kwargs)
    # TODO
    # 1) check table with FTS3
    # 2) change sql to CREATE VIRTUAL TABLE ... USING FTS3(tokenizer=...)
    print 'SQL: %s' % sql
    return sql

SQLiteDDLCompiler.visit_create_table = new_create_table
# end of ugly monkey patch

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import schema, MetaData, Column, Integer

metadata = MetaData()
Base = declarative_base(metadata=metadata)

class MyModel(Base):
    __tablename__ = 'table'
    id = Column(Integer, primary_key=True)

if __name__ == '__main__':
    from sqlalchemy import create_engine
    engine = create_engine('sqlite:///', echo=True)
    metadata.bind = engine
    metadata.create_all()

关于sqlite - 如何指示SQLAlchemy在create_all()上创建SQLite FTS3表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3919191/

10-12 22:04