Pedro Werneck
Pedro Werneck

Reputation: 41908

SQLAlchemy datetime operations on server side

I have a table with scheduled and past payments, and I need to find if there are any two charges made in the same week for the same user/contract.

select count(*) from charge as c1, charge as c2 
where c1.id_contract = c2.id_contract 
  and c1.status = 'SUCCESS' 
  and c2.status in ('SUCCESS', 'PENDING', 'WAITING') 
  and c1.id > c2.id and c2.due_time > (c1.due_time - interval 7 day);

I'm having a hard time at reproducing this query in sqlalchemy, mainly because I can't find how to translate MySQL's 'interval' to SQLAlchemy in a database agnostic form.

So far I came up with this, which translates everything, but the interval:

db.session.query(Charge, OldCharge).filter(Charge.id_contract == OldCharge.id_contract, Charge.status=='WAITING', OldCharge.status.in_(('SUCCESS', 'PENDING')), Charge.id > OldCharge.id).count()

Any ideas?

Upvotes: 1

Views: 2225

Answers (2)

Pedro Werneck
Pedro Werneck

Reputation: 41908

So, I ended up writing a custom date_diff() expression:

class date_diff(expression.FunctionElement):
    type = Integer()
    name = 'age'

@compiles(date_diff, 'default')
def _default_date_diff(element, compiler, **kw):  # pragma: no cover
    return "DATEDIFF(%s, %s)" % (compiler.process(element.clauses.clauses[0]),
                                 compiler.process(element.clauses.clauses[1]),
                                 )
@compiles(date_diff, 'mysql')
def _my_date_diff(element, compiler, **kw):  # pragma: no cover
    return "DATEDIFF(%s, %s)" % (compiler.process(element.clauses.clauses[0]),
                                 compiler.process(element.clauses.clauses[1]),
                                 )

@compiles(date_diff, 'sqlite')
def _sl_date_diff(element, compiler, **kw):    # pragma: no cover
    return "julianday(%s) - julianday(%s)" % (compiler.process(element.clauses.clauses[0]),
                                              compiler.process(element.clauses.clauses[1]),
                                              )

Upvotes: 4

van
van

Reputation: 76992

If you need this only for DAYs (which are default intervals), then simply restating your SQL as:

c2.due_time > ADDDATE(c1.due_time, - 7)

can be written in SA terms as:

filter(Charge.due_time > func.ADDDATE(OldCharge.due_time, -7))

If you need to filter for different interval types (weeks, months, years), you probably need to write a custom SQL Construct compiler (see Custom SQL Constructs and Compilation Extension for more info).

Upvotes: 4

Related Questions