Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for AND and OR statements in SQLalchemy core?

How do I write the following SQLite expression in SQLalchemy core?

SELECT * FROM table
WHERE id = 1
AND (last_date IS NULL OR
    last_date < date('now', '-30 day') );

I saw examples in SQLalchemy orm using the _and and _or but I wasn't sure if those applied to SQLalchemy core.

https://docs.sqlalchemy.org/en/latest/orm/tutorial.html#common-filter-operators

like image 459
user784637 Avatar asked Feb 14 '23 15:02

user784637


1 Answers

yes, you can use sqlalchemy.and_ and sqlalchemy.or_ on column expressions (note the underscore at the end, not beginning, leading underscores signify non-supported, private api).

You can also use & and |, the bitwise operators, and they will be compiled in the same fashion as and_/or_. Be sure to parenthesize them properly, & and | have much higher operator precedence than and and or.

Your code would look a bit like:

t.select().where((t.c.id == 1) 
                 & ((t.c.last_date == None)
                    | (t.c.last_date < sa.func.date('now', '-30 day'))))

Another option is to treat conjunctive clauses as progressively filtered relations, since the identity:

σa ∧ bR ↔ σb σaR

you can write that in sqlalchemy as

t.select().where(t.c.id == 1) \
          .where((t.c.last_date == None)
                 | (t.c.last_date < sa.func.date('now', '-30 day')))

And it produces the same SQL as above.

like image 156
SingleNegationElimination Avatar answered Feb 24 '23 05:02

SingleNegationElimination