MCPcopy
hub / github.com/sqlalchemy/sqlalchemy / load_name_range

Function load_name_range

examples/dogpile_caching/advanced.py:16–57  ·  view source on GitHub ↗

Load Person objects on a range of names. start/end are integers, range is then "person <start>" - "person <end>". The cache option we set up is called "name_range", indicating a range of names for the Person class. The `Person.addresses` collections are also cached. Its basic

(start, end, invalidate=False)

Source from the content-addressed store, hash-verified

14
15
16def load_name_range(start, end, invalidate=False):
17 """Load Person objects on a range of names.
18
19 start/end are integers, range is then
20 "person <start>" - "person <end>".
21
22 The cache option we set up is called "name_range", indicating
23 a range of names for the Person class.
24
25 The `Person.addresses` collections are also cached. Its basically
26 another level of tuning here, as that particular cache option
27 can be transparently replaced with joinedload(Person.addresses).
28 The effect is that each Person and their Address collection
29 is cached either together or separately, affecting the kind of
30 SQL that emits for unloaded Person objects as well as the distribution
31 of data within the cache.
32 """
33 q = (
34 select(Person)
35 .filter(
36 Person.name.between("person %.2d" % start, "person %.2d" % end)
37 )
38 .options(cache_address_bits)
39 .options(FromCache("default", "name_range"))
40 )
41
42 # have the "addresses" collection cached separately
43 # each lazyload of Person.addresses loads from cache.
44 q = q.options(RelationshipCache(Person.addresses, "default"))
45
46 # alternatively, eagerly load the "addresses" collection, so that they'd
47 # be cached together. This issues a bigger SQL statement and caches
48 # a single, larger value in the cache per person rather than two
49 # separate ones.
50 # q = q.options(joinedload(Person.addresses))
51
52 # if requested, invalidate the cache on current criterion.
53 if invalidate:
54 cache.invalidate(q, {}, FromCache("default", "name_range"))
55 cache.invalidate(q, {}, RelationshipCache(Person.addresses, "default"))
56
57 return Session.scalars(q).all()
58
59
60print("two through twelve, possibly from cache:\n")

Callers 1

advanced.pyFile · 0.85

Calls 9

selectFunction · 0.90
FromCacheClass · 0.85
RelationshipCacheClass · 0.70
optionsMethod · 0.45
filterMethod · 0.45
betweenMethod · 0.45
invalidateMethod · 0.45
allMethod · 0.45
scalarsMethod · 0.45

Tested by

no test coverage detected