]> git.ipfire.org Git - thirdparty/sqlalchemy/sqlalchemy.git/commitdiff
update dogpile_caching examples
authorMike Bayer <mike_mp@zzzcomputing.com>
Thu, 3 Aug 2023 03:40:17 +0000 (23:40 -0400)
committerMike Bayer <mike_mp@zzzcomputing.com>
Thu, 3 Aug 2023 03:42:08 +0000 (23:42 -0400)
Change-Id: I10e2b48afae01b65d61849841b528f1d275439ba

doc/build/changelog/unreleased_20/dogpile.rst [new file with mode: 0644]
examples/dogpile_caching/advanced.py
examples/dogpile_caching/caching_query.py
examples/dogpile_caching/helloworld.py
examples/dogpile_caching/local_session_caching.py
examples/dogpile_caching/relationship_caching.py

diff --git a/doc/build/changelog/unreleased_20/dogpile.rst b/doc/build/changelog/unreleased_20/dogpile.rst
new file mode 100644 (file)
index 0000000..b9dac22
--- /dev/null
@@ -0,0 +1,7 @@
+.. change::
+    :tags: bug, examples
+
+    The dogpile_caching examples have been updated for 2.0 style queries.
+    Within the "caching query" logic itself there is one conditional added to
+    differentiate between ``Query`` and ``select()`` when performing an
+    invalidation operation.
index e72921ba4f61f7d3c16935645b5e576aec33b4bf..7ccc52bf0ee153f388f9a849131c135c78db8109 100644 (file)
@@ -1,8 +1,10 @@
 """Illustrate usage of Query combined with the FromCache option,
 including front-end loading, cache invalidation and collection caching.
 
+
 """
 
+from sqlalchemy import select
 from .caching_query import FromCache
 from .caching_query import RelationshipCache
 from .environment import cache
@@ -29,7 +31,7 @@ def load_name_range(start, end, invalidate=False):
     of data within the cache.
     """
     q = (
-        Session.query(Person)
+        select(Person)
         .filter(
             Person.name.between("person %.2d" % start, "person %.2d" % end)
         )
@@ -52,7 +54,7 @@ def load_name_range(start, end, invalidate=False):
         cache.invalidate(q, {}, FromCache("default", "name_range"))
         cache.invalidate(q, {}, RelationshipCache(Person.addresses, "default"))
 
-    return q.all()
+    return Session.scalars(q).all()
 
 
 print("two through twelve, possibly from cache:\n")
index 937bf51d557f211066e4fcd0724563a8e6ca2537..b1848631565158d65ca77d21a8ea41309303f4a8 100644 (file)
@@ -23,6 +23,7 @@ from dogpile.cache.api import NO_VALUE
 
 from sqlalchemy import event
 from sqlalchemy.orm import loading
+from sqlalchemy.orm import Query
 from sqlalchemy.orm.interfaces import UserDefinedOption
 
 
@@ -52,7 +53,7 @@ class ORMCache:
                 dogpile_region = self.cache_regions[opt.region]
 
                 our_cache_key = opt._generate_cache_key(
-                    orm_context.statement, orm_context.parameters, self
+                    orm_context.statement, orm_context.parameters or {}, self
                 )
 
                 if opt.ignore_expiration:
@@ -90,7 +91,8 @@ class ORMCache:
     def invalidate(self, statement, parameters, opt):
         """Invalidate the cache value represented by a statement."""
 
-        statement = statement.__clause_element__()
+        if isinstance(statement, Query):
+            statement = statement.__clause_element__()
 
         dogpile_region = self.cache_regions[opt.region]
 
index 6e79fc3fa48d4e136cb7e6e07e00ae3ff8020a41..01934c59fab943b26d72be034c7f0b2e08dea2bf 100644 (file)
@@ -2,6 +2,7 @@
 
 """
 
+from sqlalchemy import select
 from .caching_query import FromCache
 from .environment import cache
 from .environment import Session
@@ -10,7 +11,7 @@ from .model import Person
 
 # load Person objects.  cache the result in the "default" cache region
 print("loading people....")
-people = Session.query(Person).options(FromCache("default")).all()
+people = Session.scalars(select(Person).options(FromCache("default"))).all()
 
 # remove the Session.  next query starts from scratch.
 Session.remove()
@@ -18,39 +19,36 @@ Session.remove()
 # load again, using the same FromCache option. now they're cached,
 # so no SQL is emitted.
 print("loading people....again!")
-people = Session.query(Person).options(FromCache("default")).all()
+people = Session.scalars(select(Person).options(FromCache("default"))).all()
 
 # Specifying a different query produces a different cache key, so
 # these results are independently cached.
 print("loading people two through twelve")
-people_two_through_twelve = (
-    Session.query(Person)
+people_two_through_twelve = Session.scalars(
+    select(Person)
     .options(FromCache("default"))
     .filter(Person.name.between("person 02", "person 12"))
-    .all()
-)
+).all()
 
 # the data is cached under string structure of the SQL statement, *plus*
 # the bind parameters of the query.    So this query, having
 # different literal parameters under "Person.name.between()" than the
 # previous one, issues new SQL...
 print("loading people five through fifteen")
-people_five_through_fifteen = (
-    Session.query(Person)
+people_five_through_fifteen = Session.scalars(
+    select(Person)
     .options(FromCache("default"))
     .filter(Person.name.between("person 05", "person 15"))
-    .all()
-)
+).all()
 
 
 # ... but using the same params as are already cached, no SQL
 print("loading people two through twelve...again!")
-people_two_through_twelve = (
-    Session.query(Person)
+people_two_through_twelve = Session.scalars(
+    select(Person)
     .options(FromCache("default"))
     .filter(Person.name.between("person 02", "person 12"))
-    .all()
-)
+).all()
 
 
 # invalidate the cache for the three queries we've done.  Recreate
@@ -61,16 +59,12 @@ print("invalidating everything")
 
 cache.invalidate(Session.query(Person), {}, FromCache("default"))
 cache.invalidate(
-    Session.query(Person).filter(
-        Person.name.between("person 02", "person 12")
-    ),
+    select(Person).filter(Person.name.between("person 02", "person 12")),
     {},
     FromCache("default"),
 )
 cache.invalidate(
-    Session.query(Person).filter(
-        Person.name.between("person 05", "person 15")
-    ),
+    select(Person).filter(Person.name.between("person 05", "person 15")),
     {},
     FromCache("default", "people_on_range"),
 )
index f3174469681016d97f87643a714b91ff3e67cc77..626003b41335416061b6219d0eb8e37a040dd322 100644 (file)
@@ -15,6 +15,7 @@ from dogpile.cache.api import CacheBackend
 from dogpile.cache.api import NO_VALUE
 from dogpile.cache.region import register_backend
 
+from sqlalchemy import select
 from . import environment
 from .caching_query import FromCache
 from .environment import regions
@@ -76,23 +77,23 @@ if __name__ == "__main__":
     # query to load Person by name, with criterion
     # of "person 10"
     q = (
-        Session.query(Person)
+        select(Person)
         .filter(Person.name == "person 10")
         .options(FromCache("local_session"))
     )
 
     # load from DB
-    person10 = q.one()
+    person10 = Session.scalars(q).one()
 
     # next call, the query is cached.
-    person10 = q.one()
+    person10 = Session.scalars(q).one()
 
     # clear out the Session.  The "_cache_dictionary" dictionary
     # disappears with it.
     Session.remove()
 
     # query calls from DB again
-    person10 = q.one()
+    person10 = Session.scalars(q).one()
 
     # identity is preserved - person10 is the *same* object that's
     # ultimately inside the cache.   So it is safe to manipulate
@@ -102,7 +103,7 @@ if __name__ == "__main__":
     # inserts, deletes, or modification to attributes that are
     # part of query criterion, still require careful invalidation.
     cache_key = FromCache("local_session")._generate_cache_key(
-        q._statement_20(), {}, environment.cache
+        q, {}, environment.cache
     )
 
     assert person10 is regions["local_session"].get(cache_key)().scalar()
index 6b261ade99d37ed798bc5603c4476e67ffcca9a1..058d552225965ceb1d4f601371303e7189677718 100644 (file)
@@ -8,6 +8,7 @@ term cache.
 """
 import os
 
+from sqlalchemy import select
 from sqlalchemy.orm import joinedload
 from .environment import root
 from .environment import Session
@@ -15,9 +16,9 @@ from .model import cache_address_bits
 from .model import Person
 
 
-for p in Session.query(Person).options(
-    joinedload(Person.addresses), cache_address_bits
-):
+for p in Session.scalars(
+    select(Person).options(joinedload(Person.addresses), cache_address_bits)
+).unique():
     print(p.format_full())