开发者

How do I instruct SQLAlchemy to create SQLite FTS3 tables on create_all()?

开发者 https://www.devze.com 2023-01-20 10:28 出处:网络
I would like SQLAlchemy to create an FTS3 table during .create开发者_开发技巧_all(). What special options do I need to add so it knows to CREATE VIRTUAL TABLE ... USING FTS3(tokenizer=...)?As I know t

I would like SQLAlchemy to create an FTS3 table during .create开发者_开发技巧_all(). What special options do I need to add so it knows to CREATE VIRTUAL TABLE ... USING FTS3(tokenizer=...)?


As I know to implement this futer you must improve sqlite dialect to change create_table behavior.

But you can use this quick, but ugly solution with "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() 
0

精彩评论

暂无评论...
验证码 换一张
取 消