简体   繁体   中英

REGEXP_LIKE in SQLAlchemy

Any one knows how could I use the equivalent of REGEXP_LIKE in SQLAlchemy? For example I'd like to be able to do something like:

sa.Session.query(sa.Table).filter(sa.Table.field.like(regex-to match))

Thanks for your help!

It should (I have no access to Oracle) work like this:

sa.Session.query(sa.Table) \
          .filter(sa.func.REGEXP_LIKE(sa.Table.c.column, '[[:digit:]]'))

In cases when you need to do database specific function which is not supported by SQLAlchemy you can use literal filter. So you can still use SQLAlchemy to build query for you - ie take care about joins etc.

Here is example how to put together literal filter with PostgreSQL Regex Matching operator ~

session.query(sa.Table).filter("%s ~':regex_pattern'" % sa.Table.c.column.name).params(regex_pattern='stack')

or you can manually specify table and column as a part of literal string to avoid ambigious column names case

session.query(sa.Table).filter("table.column ~':regex_pattern'"  ).params(regex_pattern='[123]')

This is not fully portable, but here is a Postgres solution, which uses a ~ operator. We can use arbitrary operators thus:

sa.Session.query(sa.Table).filter(sa.Table.field.op('~', is_comparison=True)(regex-to match))

Or, assuming a default precedence of 0,

sa.Session.query(sa.Table).filter(sa.Table.field.op('~', 0, True)(regex-to match))

This also works with ORM constructs:

sa.Session.query(SomeClass).filter(SomeClass.field.op('~', 0, True)(regex-to match))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM