Home > Enterprise >  How to use PostgreSQL extensions in SQLAlchemy (specifically Flask-SQLAlchemy)?
How to use PostgreSQL extensions in SQLAlchemy (specifically Flask-SQLAlchemy)?

Time:01-02

In the website I'm making with Flask, I'm trying to "upgrade" my search bar by using the pg_trgm PostgreSQL extension to match words even after being spelled wrong. However, I'm having trouble figuring out how to use the extension's custom functions alongside SQLAlchemy.

Will I have to use raw SQL to properly perform the queries, or is there a way to do this more cleanly?

CodePudding user response:

Assuming the extension is configured correctly, these functions should be accessible like any other database function. For example, here's how the similarity function might be called using SQLAlchemy core:

import sqlalchemy as sa

engine = sa.create_engine('postgresql psycopg2:///test', echo=True, future=True)

metadata = sa.MetaData()

tbl = sa.Table('t70546926', metadata,
               sa.Column('c1', sa.String, primary_key=True),
               sa.Column('c2', sa.String))
tbl.drop(engine, checkfirst=True)
tbl.create(engine)

ins = sa.insert(tbl).values(c1='Alice', c2='Alison')

with engine.begin() as conn:
    conn.execute(ins)

query = sa.select(sa.func.similarity(tbl.c.c1, tbl.c.c2).label('similarity_result'))
with engine.connect() as conn:
    rows = conn.execute(query)
    for row in rows:
        print(row.similarity_result)

For Flask-SQLAlchemy, you might do something like this:

result = dbsession.query(sa.func.similarity(val1, val2)).all()
  • Related