Denis Steinman
Denis Steinman

Reputation: 7799

What's the cache_ok flag in SQLAlchemy?

I have the next custom type decorator for SQLAlchemy:

class TimeStamp(TypeDecorator):
    impl = DateTime
    cache_ok = True
    LOCAL_TIMEZONE = datetime.utcnow().astimezone().tzinfo

    def process_literal_param(self, value, dialect):
        return self.imple.process_literal_param(value, dialect)

    @property
    def python_type(self):
        return self.impl.python_type

    def process_bind_param(self, value: datetime, dialect):
        if value is None:
            return None
        if value.tzinfo is None:
            value = value.astimezone(self.LOCAL_TIMEZONE)
        return value.astimezone(timezone.utc)

    def process_result_value(self, value, dialect):
        if value is None:
            return None
        if value.tzinfo is None:
            return value.replace(tzinfo=timezone.utc)
        return value.astimezone(timezone.utc)

The problem is that SQLAlchemy asks me to setup the cache_ok flag... I've tried to read about this flag in docs but it's still not clear for me. I can't get how SQLAlchemy uses it.
What does it cache? Is my type decorator suitable for caching?

Upvotes: 7

Views: 3655

Answers (1)

Loknar
Loknar

Reputation: 1189

Ran into this recently, found your question, no answer :( .. looked further, looked into the docs ..

The TypeDecorator.cache_ok class-level flag indicates if this custom TypeDecorator is safe to be used as part of a cache key. This flag defaults to None which will initially generate a warning when the SQL compiler attempts to generate a cache key for a statement that uses this type. If the TypeDecorator is not guaranteed to produce the same bind/result behavior and SQL generation every time, this flag should be set to False; otherwise if the class produces the same behavior each time, it may be set to True. See TypeDecorator.cache_ok for further notes on how this works.

https://docs.sqlalchemy.org/en/14/core/custom_types.html#sqlalchemy.types.TypeDecorator

.. so if you're confident that your TypeDecorator always produces the same bind/result for a given value then go ahead and issue that statement by setting the value cache_ok = True in your TypeDecorator class.

Upvotes: 6

Related Questions