Skip to content

Commit

Permalink
models: avoid flushing when getting records
Browse files Browse the repository at this point in the history
  • Loading branch information
ntarocco authored and zzacharo committed Sep 18, 2023
1 parent 9097342 commit 05bae22
Showing 1 changed file with 26 additions and 23 deletions.
49 changes: 26 additions & 23 deletions invenio_drafts_resources/records/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import uuid
from datetime import datetime, timedelta

from invenio_db import db
from invenio_pidstore.models import PIDStatus
from invenio_pidstore.providers.recordid_v2 import RecordIdProviderV2
from invenio_records.systemfields import ModelField
Expand Down Expand Up @@ -92,36 +93,38 @@ class Record(RecordBase):
@classmethod
def get_records_by_parent(cls, parent, with_deleted=True, ids_only=False):
"""Get all sibling records for the specified parent record."""
rec_models = cls.model_cls.query.filter_by(parent_id=parent.id)
if not with_deleted:
rec_models = rec_models.filter_by(is_deleted=False)

if ids_only:
return (rec_model.id for rec_model in rec_models)
else:
return (
cls(rec_model.data, model=rec_model, parent=parent)
for rec_model in rec_models
)
with db.session.no_autoflush:
rec_models = cls.model_cls.query.filter_by(parent_id=parent.id)
if not with_deleted:
rec_models = rec_models.filter_by(is_deleted=False)

if ids_only:
return (rec_model.id for rec_model in rec_models)
else:
return (
cls(rec_model.data, model=rec_model, parent=parent)
for rec_model in rec_models
)

@classmethod
def get_latest_by_parent(cls, parent, id_only=False):
"""Get the latest record for the specified parent record.
It might return None if there is no latest published version yet.
"""
version = cls.versions_model_cls.query.filter_by(
parent_id=parent.id
).one_or_none()
has_latest = version and version.latest_id
if not has_latest:
return None

rec_model = cls.model_cls.query.filter_by(id=version.latest_id).one()
if id_only:
return rec_model.id
else:
return cls(rec_model.data, model=rec_model, parent=parent)
with db.session.no_autoflush:
version = cls.versions_model_cls.query.filter_by(
parent_id=parent.id
).one_or_none()
has_latest = version and version.latest_id
if not has_latest:
return None

rec_model = cls.model_cls.query.filter_by(id=version.latest_id).one()
if id_only:
return rec_model.id
else:
return cls(rec_model.data, model=rec_model, parent=parent)

@classmethod
def publish(cls, draft):
Expand Down

0 comments on commit 05bae22

Please sign in to comment.