REGEXP_LIKE in SQLAlchemy

前端 未结 3 854
星月不相逢
星月不相逢 2020-12-21 10:18

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).         


        
相关标签:
3条回答
  • 2020-12-21 11:06

    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))

    0 讨论(0)
  • 2020-12-21 11:10

    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 - i.e. 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]')
    
    0 讨论(0)
  • 2020-12-21 11:19

    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:]]'))
    
    0 讨论(0)
提交回复
热议问题