简体   繁体   English

SQLAlchemy中的REGEXP_LIKE

[英]REGEXP_LIKE in SQLAlchemy

Any one knows how could I use the equivalent of REGEXP_LIKE in SQLAlchemy? 谁知道我该如何在SQLAlchemy中使用REGEXP_LIKE? 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: 它应该(我无权访问Oracle)是这样的:

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. 如果您需要执行SQLAlchemy不支持的数据库特定功能,则可以使用文字过滤器。 So you can still use SQLAlchemy to build query for you - ie take care about joins etc. 因此,您仍然可以使用SQLAlchemy为您构建查询-即,注意连接等。

Here is example how to put together literal filter with PostgreSQL Regex Matching operator ~ 这是如何将文字过滤器与PostgreSQL Regex Matching运算符组合在一起的示例~

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. 这不是完全可移植的,但是这里是一个Postgres解决方案,它使用〜运算符。 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, 或者,假设默认优先级为0,

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

This also works with ORM constructs: 这也适用于ORM构造:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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