kvesteri / sqlalchemy-continuum

Versioning extension for SQLAlchemy.
BSD 3-Clause "New" or "Revised" License
580 stars 126 forks source link

Querying in the past? #175

Open vincentwhales opened 6 years ago

vincentwhales commented 6 years ago

I am currently using SQLAlchemy-Continuum. I have the following class:

class Account(db.Model):
  __tablename__ = 'accounts'
  __versioned__ = {}

  id = db.Column(db.Integer, primary_key=True)

  status = db.Column(db.Enum(AccountStatus, name='account_status'), nullable=False, default=AccountStatus.UNINITIALIZED)

So now I am building a tool which will be looking at accounts that have status == active 3 days and 7 days ago.

Is there a way to do so with SQLAlchemy-Continuum?

timster commented 6 years ago

Did you ever figure out a solution to this?

I'm exploring the exact same problem. I think I am close to a solution but not quite.

tsantanaDH commented 6 years ago

As far as I know about this library, this snippet should do the job:

from datetime import datetime, timedelta
from sqlalchemy_continuum import version_class, transaction_class
from .models import Account
from . import db

AccountVersion = version_class(Account)
Transaction = version_class(Account)

query = db.session.query(AccountVersion).join(AccountVersion.transaction).filter(
    AccountVersion.status == 'active' ,
    Transaction.issued_by < datetime.now() - timedelta(days=3),
    Transaction.issued_by > datetime.now() - timedelta(days=7)
)

⚠️ this code wasn't tested, so proceed carefully

carlosvega commented 4 years ago

shouldn't it be Transaction = transaction_class(Account) ?