API Reference
DataCaches.SERIALIZER_REGISTRYDataCaches.CacheEntryDataCaches.CacheSerializerDataCaches.DataCacheDataCaches.PurgePolicyBase.delete!Base.keysBase.readDataCaches.CacheAssets.cpDataCaches.CacheAssets.lsDataCaches.CacheAssets.ls!DataCaches.CacheAssets.mvDataCaches.CacheAssets.purge!DataCaches.CacheAssets.purge!DataCaches.CacheAssets.rmDataCaches.Caches.autocachestoreDataCaches.Caches.cpDataCaches.Caches.lsDataCaches.Caches.ls!DataCaches.Caches.mvDataCaches.Caches.pwdDataCaches.Caches.rmDataCaches.active_autocacheDataCaches.autocacheDataCaches.autocacheDataCaches.clear!DataCaches.entriesDataCaches.entryDataCaches.importcache!DataCaches.invalidate!DataCaches.invalidate!DataCaches.isstaleDataCaches.isstaleDataCaches.keylabelsDataCaches.keypathsDataCaches.labelDataCaches.labelsDataCaches.memcache_clear!DataCaches.migrate_legacy_autocacheDataCaches.migrate_legacy_defaultcacheDataCaches.migrate_v020_defaultcacheDataCaches.movecache!DataCaches.pathDataCaches.register_serializer!DataCaches.reindexcache!DataCaches.relabel!DataCaches.scratch_datacache!DataCaches.scratch_datacache!DataCaches.serializer_forDataCaches.set_active_autocache!DataCaches.set_autocaching!DataCaches.set_autocaching!DataCaches.set_autocaching!DataCaches.set_autopurge!DataCaches.set_autopurge!DataCaches.showcacheDataCaches.write!DataCaches.@filecacheDataCaches.@filecache!DataCaches.@memcache
DataCaches.SERIALIZER_REGISTRY — Constant
SERIALIZER_REGISTRYDict mapping format tags to CacheSerializer instances used for reading. Populated at module load with built-in serializers; extensions add entries via register_serializer!.
DataCaches.CacheEntry — Type
CacheEntryA metadata descriptor for a single cached dataset in a DataCache.
A CacheEntry is returned by write!, entries, entry, and related functions. Fields are accessed directly:
e.id :: String— unique identifier (UUID)e.seq :: Int— stable integer index (persisted; usereindexcache!to compact gaps)e.label :: String— user-assigned label (hash string for@filecacheentries; empty if none)e.path :: String— absolute path to the backing data filee.description :: String— human-readable source expression (empty if none was recorded)e.datecached :: DateTime— when the entry was written;typemin(DateTime)if unknowne.dateaccessed :: DateTime— when the entry was last read;typemin(DateTime)if never accessede.ttl :: Union{Nothing,Period}— time-to-live;nothingmeans no expiry
Backward compatibility
CacheKey is a backward-compatible alias for CacheEntry. Existing code using CacheKey continues to work without modification. The alias will gain a deprecation warning in a future release.
DataCaches.CacheSerializer — Type
CacheSerializerAbstract type for cache serialization backends. Implement four methods to define a new serializer:
format_tag(s)::String— short tag stored in the TOML index (e.g."csv","json")file_extension(s)::String— file extension including dot (e.g.".csv")write_data(s, fpath::String, data)— writedatatofpathread_data(s, fpath::String)— read and return data fromfpath
Register a new serializer with register_serializer! so it is available for reading entries by format tag.
DataCaches.DataCache — Type
DataCache(store::AbstractString; track_access=true)
DataCache(key::Symbol; track_access=true)A labeled, file-backed key-value store for caching query results across Julia sessions.
Data is persisted in store as CSV files (for DataFrame values) or serialized Julia objects (.jls) for anything else. An index file (cache_index.toml) in store keeps track of all entries.
A store argument is always required. To access the shared autocache store used by @filecache, set_autocaching!, and similar mechanisms, call active_autocache() instead.
Symbol argument (DataCache(:name)): creates a named user store within DataCaches.jl's own depot directory (~/.julia/scratchspaces/<DataCaches-UUID>/caches/user/<name>/). The cache is automatically removed along with DataCaches.jl when the package is uninstalled. This is the recommended approach for users and library authors who want a persistent, named cache without managing filesystem paths or package UUIDs:
# User: a named project cache in DataCaches' scratchspace
dc = DataCache(:myproject)
# Library author: lifecycle-managed cache in __init__
const _CACHE = Ref{Union{DataCache,Nothing}}(nothing)
function __init__()
_CACHE[] = DataCache(:mypackage_results)
endUse scratch_datacache! instead when you need the cache tied to your own package's lifecycle rather than DataCaches.jl's.
track_access keyword: when true (the default), every read updates the dateaccessed field of the corresponding CacheEntry and rewrites the index. This supports LRU inspection via entries and DataCaches.CacheAssets.ls. Set track_access = false to skip this rewrite on caches that are read very frequently or have many entries.
Examples
cache = DataCache(:myproject) # named store: caches/user/myproject/
cache = DataCache("/my/project/cache") # explicit filesystem path
cache = DataCache(:logs; track_access = false) # disable access-time recording
# Access the active autocache store
cache = active_autocache()
# Write
key = write!(cache, df)
key = write!(cache, df; label="Dinosaur families")
cache["Trilobites"] = df # setindex! sugar
# Read
df = read(cache, key)
df = read(cache, "Dinosaur families")
df = cache["Dinosaur families"]
df = cache[key]
# Introspect
entries(cache) # → Vector{CacheEntry} (primary — filterable, sortable)
entry(cache, "Dinosaur families") # → CacheEntry (single entry by label)
labels(cache) # → Vector{String} (user-assigned labels only)
keys(cache) # → Vector{CacheEntry} (backward-compat; prefer entries())
keylabels(cache) # → Vector{String} (backward-compat; prefer labels())
keypaths(cache) # → Vector{String}
label(cache, key) # → String
path(cache, key) # → String
haskey(cache, "Dinosaur families")
# Manage
delete!(cache, key)
delete!(cache, "Dinosaur families")
clear!(cache)
showcache(cache)DataCaches.PurgePolicy — Type
PurgePolicyConfiguration for automatic cache purging, applied after each write! call when a policy has been set with set_autopurge!.
Fields:
max_age::Union{Nothing,Period}— remove entries older than this age (bydatecached)max_idle::Union{Nothing,Period}— remove entries not accessed within this periodkeep_count::Union{Nothing,Int}— keep only the N most-recently-accessed entries (LRU)max_size_bytes::Union{Nothing,Int}— purge LRU entries until total cache size ≤ limitkeep_labeled::Bool— whentrue, labeled entries are never auto-purged
Base.delete! — Method
delete!(cache::DataCache, entry::CacheEntry)
delete!(cache::DataCache, label::AbstractString)
delete!(cache::DataCache, uuid_prefix::AbstractString)
delete!(cache::DataCache, n::Integer)
delete!(cache::DataCache, specs::AbstractVector)Remove an entry (or multiple entries) from cache and delete their backing files from disk.
The AbstractString form first tries to match a label exactly, then falls back to matching the UUID prefix shown in brackets by showcache (e.g. "2a9d4a87"). An ambiguous prefix (matching more than one entry) is an error.
The Integer form identifies the entry by its stable sequence index (as shown in showcache). Use reindexcache! to compact gaps after many deletions.
The AbstractVector form accepts a vector of any mix of CacheEntry, label String, UUID-prefix String, and sequence index Integer specifiers. All removals are batched into a single index rewrite for efficiency. Unresolvable specifiers are silently skipped.
Base.keys — Method
keys(cache::DataCache) → Vector{CacheEntry}Return all CacheEntry objects stored in cache.
Prefer entries for new code — it supports filtering and sorting. keys is maintained for backward compatibility.
Base.read — Method
read(cache::DataCache, entry::CacheEntry) → data
read(cache::DataCache, label::AbstractString) → data
read(cache::DataCache, n::Integer) → dataRetrieve a cached dataset by CacheEntry, label string, or stable sequence index. The Integer form uses the sequence index shown in brackets by showcache (e.g. [1], [2]). Use reindexcache! to compact gaps after many deletions.
DataCaches.active_autocache — Method
active_autocache() → DataCacheReturn the active autocache store used by @filecache, @filecache!, autocache, and the no-argument forms of entries, entry, labels, isstale, invalidate!, and set_autopurge!.
The store is resolved lazily on first call. Resolution order:
- A store explicitly set by
set_active_autocache!orset_autocaching!(true; cache=x)— if either was called, that store is returned. - Otherwise, the
DATACACHES_AUTOCACHE_STOREenvironment variable — if set, opens aDataCacheat that path. - Otherwise, the named store
DataCache(:_AUTOCACHE)inside DataCaches.jl's own scratchspace (<depot>/caches/user/_AUTOCACHE/).
To permanently redirect the autocache store, call set_active_autocache!.
DataCaches.autocache — Method
autocache(fetch_fn, func, endpoint, kwargs;
package_cache::Union{DataCache,Nothing} = nothing,
force_refresh::Bool = false)Integration hook for library authors: transparently apply autocaching around a fetch closure.
If autocache is enabled for func, checks the cache for a prior result keyed on (func, endpoint, kwargs). On a hit (and force_refresh = false) returns the cached value immediately. On a miss, calls fetch_fn(), stores the result, and returns it.
If autocache is not active for func, calls fetch_fn() directly.
Arguments
fetch_fn: Zero-argument callable that performs the real fetch.func: The public API function whose autocache opt-in is checked.endpoint: The API endpoint string (e.g."occs/list").kwargs: Keyword arguments passed by the caller.package_cache: Optional library-owned defaultDataCache. Used when autocache is active but the user did not pass an explicitcachetoset_autocaching!. Allows a library to default to its ownscratch_datacache!-backed store while still letting the user override viaset_autocaching!(true; cache=x). Passnothing(default) to fall through toactive_autocache().force_refresh: Whentrue, bypasses the hit check and overwrites any existing entry.
Store resolution priority
- User-explicit:
set_autocaching!(true; cache=x)→ always usesx package_cachekwarg → used when no explicit user cache was setactive_autocache()→ final fallback (lazy)
DataCaches.clear! — Method
clear!(cache::DataCache)Remove all entries from cache and delete their backing files from disk.
DataCaches.entries — Method
entries(cache::DataCache; kwargs...) → Vector{CacheEntry}
entries(; kwargs...) → Vector{CacheEntry}Return the entries of cache as a Vector{CacheEntry}, optionally filtered and sorted. When called without a cache argument, uses active_autocache().
This is the primary function for inspecting a cache's contents. Use entry to look up a single entry by label or index, and labels to get just the labels.
Filtering keyword arguments
| Keyword | Type | Effect |
|---|---|---|
pattern | AbstractString/Regex | Keep entries whose label or description matches |
before | DateTime | Keep entries cached before this time |
after | DateTime | Keep entries cached after this time |
accessed_before | DateTime | Keep entries last accessed before this time |
accessed_after | DateTime | Keep entries last accessed after this time |
labeled | Bool | true = only labeled; false = only unlabeled |
missing_file | Bool | true = only entries whose backing file is gone |
Sorting keyword arguments
| Keyword | Values |
|---|---|
sortby | :seq (default), :label, :date, :date_desc, :dateaccessed, |
:dateaccessed_desc, :size, :size_desc | |
rev | Bool — reverse the sort order |
Examples
dc = DataCache(:myproject)
all_entries = entries(dc)
labeled_only = entries(dc; labeled = true)
recent = entries(dc; after = DateTime("2026-01-01T00:00:00"))
lru = entries(dc; sortby = :dateaccessed_desc) # oldest-accessed first
large_first = entries(dc; sortby = :size_desc)
canidae = entries(dc; pattern = r"canidae")
entries() # autocache storeSee also: entry, labels, keys, DataCaches.CacheAssets.ls.
DataCaches.entry — Method
entry(cache::DataCache, label::AbstractString) → CacheEntry
entry(cache::DataCache, n::Integer) → CacheEntry
entry(spec) → CacheEntryLook up a single CacheEntry by label string or sequence index n. When called with a single non-DataCache argument, uses active_autocache().
Throws a KeyError if no matching entry exists.
Examples
dc = DataCache(:myproject)
e = entry(dc, "dinosaurs") # by label
e = entry(dc, 3) # by sequence index
e = entry("dinosaurs") # autocache store, by label
e = entry(2) # autocache store, by indexDataCaches.importcache! — Method
DataCaches.importcache!(dest::DataCache, source; conflict=:overwrite) → DataCacheImport all entries from an external cache source into dest.
source can be:
- A filesystem directory containing a DataCache store (
cache_index.tomlat its root). - A
.zipfile containing a DataCache store at its root. - An HTTP/HTTPS URL pointing to a
.zipfile; downloaded to a temp location first.
The conflict keyword controls behavior when an entry in source has the same label as an existing entry in dest:
:overwrite(default) — replace the existing entry with the imported one.:skip— keep the existing entry, discard the incoming one.:error— raise anErrorExceptionimmediately on conflict.
Unlabeled entries are always imported regardless of conflict. Imported entries receive a new UUID, sequence number, and datecached timestamp in dest. Returns dest.
DataCaches.invalidate! — Method
invalidate!(cache::DataCache; kwargs...) → DataCache
invalidate!(; kwargs...) → DataCacheRemove entries from cache that match the given criteria. All removals are batched into a single index rewrite.
When called without a cache argument, uses active_autocache().
Filtering keyword arguments
Entries are first selected by the standard filter set (same as entries):
pattern—RegexorString; matched against label, description, or UUIDfilepath_pattern—RegexorString; matched against full file pathfilename_pattern—RegexorString; matched against filename onlyformat—StringorRegex; matched against the entry's format tag ("csv","jls", …)before::DateTime— entries cached before this timeafter::DateTime— entries cached after this timeaccessed_before_date::DateTime— entries last accessed before this timeaccessed_after_date::DateTime— entries last accessed after this timelabeled::Union{Nothing,Bool}—true= labeled only;false= unlabeled only
Invalidation criteria
stale::Bool = false— further restrict to entries that are past their TTLpredicate::Union{Nothing,Function} = nothing— further restrict to entries wherepredicate(entry)returnstrue
Options
dry_run::Bool = false— print matching entries toiowithout deletingio::IO = stdout— output stream fordry_runmessages
Examples
dc = DataCache(:myproject; default_ttl = Dates.Hour(24))
# Remove all stale entries
invalidate!(dc; stale = true)
# Remove entries matching a label pattern
invalidate!(dc; pattern = r"^temp_")
# Remove CSV entries older than a week
invalidate!(dc; format = "csv", before = Dates.now() - Dates.Day(7))
# Remove entries matching a custom predicate
invalidate!(dc; predicate = e -> startswith(e.description, "my_func("))
# Preview what would be removed
invalidate!(dc; stale = true, dry_run = true)See also: isstale, DataCaches.CacheAssets.purge!.
DataCaches.isstale — Method
isstale(cache::DataCache, entry::CacheEntry) → Bool
isstale(cache::DataCache, label::AbstractString) → Bool
isstale(entry::CacheEntry) → Bool
isstale(label::AbstractString) → BoolReturn true if entry (or the entry identified by label) has exceeded its time-to-live and is considered stale.
The effective TTL for an entry is its own entry.ttl if set, otherwise the cache's default_ttl. When no TTL applies (both are nothing), returns false.
Staleness is purely informational — read does not enforce it. The caller decides whether to refresh (enabling stale-while-revalidate patterns).
Examples
dc = DataCache(:myproject; default_ttl = Dates.Hour(1))
write!(dc, result; label = "query1")
isstale(dc, "query1") # false immediately after write
# … one hour later …
isstale(dc, "query1") # true
# Per-entry TTL overrides the cache default:
write!(dc, result2; label = "short", ttl = Dates.Minute(5))
isstale(dc, "short") # true after 5 minutesSee also: invalidate!, DataCaches.CacheAssets.purge!.
DataCaches.keylabels — Method
keylabels(cache::DataCache) → Vector{String}Return all labels of entries in cache (empty string for unlabeled entries).
Prefer labels for new code — it returns only user-assigned labels (no empty strings). keylabels is maintained for backward compatibility.
DataCaches.keypaths — Method
keypaths(cache::DataCache) → Vector{String}Return the file paths of all entries in cache.
DataCaches.label — Method
label(cache::DataCache, entry::CacheEntry) → StringReturn the label associated with entry (same as entry.label).
DataCaches.labels — Method
labels(cache::DataCache) → Vector{String}
labels() → Vector{String}Return all user-assigned labels for entries in cache, excluding unlabeled entries (those keyed only by an auto-generated hash). When called without arguments, uses active_autocache().
Examples
dc = DataCache(:myproject)
dc["foo"] = 1
dc["bar"] = 2
labels(dc) # → ["foo", "bar"] (order may vary)
labels() # autocache storeDataCaches.memcache_clear! — Method
memcache_clear!()Discard all results stored by @memcache for this session.
DataCaches.migrate_legacy_autocache — Method
DataCaches.migrate_legacy_autocache(; conflict::Symbol = :skip) → BoolMigrate from the pre-v0.5.0 _DEFAULT autocache store location to the current _AUTOCACHE location. Returns true if migration was performed, false if nothing to migrate. Safe to call multiple times (idempotent).
DataCaches.migrate_legacy_defaultcache — Method
DataCaches.migrate_legacy_defaultcache(; conflict::Symbol = :skip) → BoolMigrate the default cache from its pre-Scratch.jl location to the current default store.
Before DataCaches.jl integrated with Scratch.jl (prior to v0.2.0), autocached data was stored at:
~/.cache/DataCaches/_DEFAULT/After Scratch.jl integration (v0.2.0+) the autocache store moved to the managed scratchspace:
~/.julia/scratchspaces/<DataCaches-UUID>/caches/user/_AUTOCACHE/(or the path given by DATACACHES_AUTOCACHE_STORE if that environment variable is set).
Call this function once after upgrading from pre-v0.2.0 to move any data accumulated under the old location into the current autocache store. It is safe to call multiple times (idempotent).
Return value:
true— migration was performed; legacy directory existed and was processed.false— nothing to migrate; legacy directory did not exist (or was already removed).
Migration strategy:
- If the legacy directory does not exist, returns
falseimmediately. - If the current autocache store does not yet exist, the legacy directory is moved wholesale via
Base.mv— no re-indexing, no data copying. - If the current autocache store already exists (e.g.
active_autocache()was already called after upgrading), all entries from the legacy directory are imported viaimportcache!and then the legacy directory is removed. Theconflictkeyword controls label collisions between the two stores.
conflict keyword (applies only when both stores already contain data):
:skip(default) — keep the entry already in the current store; discard the legacy one.:overwrite— replace the current store's entry with the legacy one.:error— raise anErrorExceptionimmediately on any label collision.
Examples
# Migrate once after upgrading:
DataCaches.migrate_legacy_defaultcache()
# Prefer legacy data when labels collide:
DataCaches.migrate_legacy_defaultcache(; conflict = :overwrite)DataCaches.migrate_v020_defaultcache — Method
DataCaches.migrate_v020_defaultcache(; conflict::Symbol = :skip) → BoolMigrate the default cache from its v0.2.0 location to the current default store.
In DataCaches.jl v0.2.0, autocached data was stored at:
<depot>/caches/defaultcache/In v0.3.0+ the autocache store moved into the user silo:
<depot>/caches/user/_AUTOCACHE/(or the path given by DATACACHES_AUTOCACHE_STORE if that environment variable is set).
Call this function once after upgrading from v0.2.0 to move any data accumulated under the old location into the current autocache store. It is safe to call multiple times (idempotent).
Return value:
true— migration was performed; v0.2.0 directory existed and was processed.false— nothing to migrate; v0.2.0 directory did not exist (or was already removed).
Migration strategy:
- If the v0.2.0 directory does not exist, returns
falseimmediately. - If the new location does not yet exist, the v0.2.0 directory is moved wholesale via
Base.mv— no re-indexing, no data copying. - If the new location already has data (e.g.
active_autocache()was already called after upgrading), all entries are imported viaimportcache!and then the v0.2.0 directory is removed. Theconflictkeyword controls label collisions.
conflict keyword (applies only when both stores already contain data):
:skip(default) — keep the entry already in the new store; discard the v0.2.0 one.:overwrite— replace the new store's entry with the v0.2.0 one.:error— raise anErrorExceptionimmediately on any label collision.
Examples
# Migrate once after upgrading:
DataCaches.migrate_v020_defaultcache()
# Prefer v0.2.0 data when labels collide:
DataCaches.migrate_v020_defaultcache(; conflict = :overwrite)DataCaches.movecache! — Method
DataCaches.movecache!(cache::DataCache, new_path::AbstractString) → DataCacheMove the cache's underlying store directory to new_path, updating cache.store.
Because cache_index.toml stores paths as relative paths, the TOML file does not need rewriting. In-memory CacheEntry.path fields (which are absolute) are updated in place.
- If
new_pathdoes not exist, it is created (including any missing parent directories). - If
new_path == abspath(cache.store), returnscacheunchanged (no-op). - If
new_pathalready exists (and differs), throws an error.
The move is performed with Base.mv, which copies then deletes across filesystem boundaries.
DataCaches.path — Method
path(cache::DataCache, entry::CacheEntry) → StringReturn the file path of the data file backing entry (same as entry.path).
DataCaches.register_serializer! — Method
register_serializer!(tag::String, s::CacheSerializer)Add or replace a serializer in the registry. After registration, cache entries with format == tag will be read using s. Called automatically by package extensions (e.g. FileIOExt for PNG/JPG support).
DataCaches.reindexcache! — Method
reindexcache!(cache::DataCache)Renumber all entries 1..n (sorted by current sequence order), closing gaps left by deletions. After reindexcache!, integer indices in showcache output restart from 1 with no gaps.
Use this after many write/delete cycles to keep index numbers manageable.
DataCaches.relabel! — Method
relabel!(cache::DataCache, entry::CacheEntry, new_label::AbstractString) → CacheEntry
relabel!(cache::DataCache, old_label::AbstractString, new_label::AbstractString) → CacheEntry
relabel!(cache::DataCache, n::Integer, new_label::AbstractString) → CacheEntryRename the label of an existing cache entry without touching its backing data file.
The CacheEntry overload identifies the entry by its UUID. The AbstractString overload first tries to match old_label as an exact label, then falls back to UUID-prefix matching (same rules as delete!). The Integer overload identifies the entry by its stable sequence index (as shown in showcache).
Raises an error if new_label is already in use by a different entry. Returns the updated CacheEntry.
DataCaches.scratch_datacache! — Function
scratch_datacache!(pkg_uuid::Base.UUID, key::Symbol = :datacache) → DataCacheCreate a DataCache stored under DataCaches' own depot, namespaced by pkg_uuid and key, at <depot>/caches/module/<pkg_uuid>/<key>/.
The store is managed as part of the DataCaches depot (cleaned up when DataCaches is uninstalled), not the calling package's own lifecycle. Use different key values to create multiple independent stores for the same package UUID.
Use this in a package's __init__ to create a named, module-scoped cache:
module MyPackage
using DataCaches
const _MY_UUID = Base.UUID("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") # match Project.toml
const _CACHE = Ref{Union{DataCache,Nothing}}(nothing)
function __init__()
_CACHE[] = DataCaches.scratch_datacache!(_MY_UUID, :results)
end
get_cache() = _CACHE[]
endDataCaches.serializer_for — Method
serializer_for(data) -> CacheSerializerInfer the appropriate serializer for data. Add methods to this function to support new types:
DataCaches.serializer_for(data::MyType) = MySerializer()Built-in dispatch priority (most to least specific):
NamedTuple→JSONSerializerAbstractDataFrame→CSVSerializer- Any Tables.jl-compatible type →
CSVSerializer - Everything else →
OpaqueSerializer(Julia binary.jls)
DataCaches.set_active_autocache! — Method
set_active_autocache!(cache::DataCache) → DataCacheSet the module-level autocache store used by @filecache, @filecache!, autocache, and all no-argument inspection functions.
Unlike set_autocaching!(true; cache=x), this function does not enable autocaching for instrumented library functions — it only redirects the store used by the macros and inspection helpers.
DataCaches.set_autocaching! — Method
set_autocaching!(enabled::Bool, func; cache::Union{DataCache,Nothing} = nothing) → Union{DataCache,Nothing}
set_autocaching!(enabled::Bool, funcs::AbstractVector; cache::Union{DataCache,Nothing} = nothing) → Union{DataCache,Nothing}Enable or disable automatic caching for a specific function (or list of functions).
When enabled=true, autocache is activated for func (additive — does not affect other per-function settings). If global autocache is currently on, calling this switches to per-function mode with only {func}.
When enabled=false and per-function mode is active, removes func from the allowlist. If the allowlist becomes empty, autocache is fully disabled.
Note: set_autocaching!(false, func) has no effect when global autocache is on; call set_autocaching!(false) to disable globally.
Returns the pinned DataCache if one was set via cache=, or nothing otherwise.
Examples
DataCaches.set_autocaching!(true, pbdb_occurrences)
DataCaches.set_autocaching!(true, [pbdb_occurrences, pbdb_taxa])
DataCaches.set_autocaching!(false, pbdb_occurrences)DataCaches.set_autocaching! — Method
set_autocaching!(enabled::Bool; cache::Union{DataCache,Nothing} = nothing) → Union{DataCache,Nothing}Enable or disable automatic caching for all instrumented API functions.
When enabled=true, every call to an instrumented function automatically stores its result in a DataCache and returns the cached result on subsequent identical calls.
Pass cache to pin a specific store; that cache is then used regardless of any package_cache the library supplies, and the _autocache_cache_explicit flag is set. When cache is omitted, store resolution is deferred lazily to each autocache call site: any package_cache supplied by the library takes priority, with active_autocache() as the final fallback.
Returns the pinned DataCache when cache is given, or nothing otherwise.
Examples
set_autocaching!(true) # library default or active_autocache()
set_autocaching!(false)
set_autocaching!(true; cache=DataCache("/my/project/cache")) # pin explicit storeDataCaches.set_autopurge! — Method
set_autopurge!(cache::DataCache; enabled=true, kwargs...) → DataCache
set_autopurge!(; enabled=true, kwargs...) → DataCacheConfigure an automatic purge policy on cache. After each write!, the policy is applied to keep the cache within the specified limits.
When called without a cache argument, uses active_autocache().
Pass enabled = false to remove the current policy (disabling auto-purge).
Keyword arguments
max_age::Union{Nothing,Period}— remove entries older than this age (bydatecached)max_idle::Union{Nothing,Period}— remove entries not accessed within this periodkeep_count::Union{Nothing,Int}— keep only the N most-recently-accessed entriesmax_size_bytes::Union{Nothing,Int}— purge LRU entries until total cache size ≤ limitkeep_labeled::Bool = false— whentrue, labeled entries are never auto-purged
Examples
dc = DataCache(:myproject)
# Keep only the 20 most recently accessed entries
set_autopurge!(dc; keep_count = 20)
# Remove entries older than 30 days, never delete labeled entries
set_autopurge!(dc; max_age = Dates.Day(30), keep_labeled = true)
# Disable auto-purge
set_autopurge!(dc; enabled = false)See also: DataCaches.CacheAssets.purge!, invalidate!.
DataCaches.showcache — Method
showcache(cache::DataCache)Print a detailed summary of all entries in cache. Equivalent to show(stdout, MIME"text/plain"(), cache).
DataCaches.write! — Method
write!(cache::DataCache, data; label::AbstractString = "", description::AbstractString = "", format::Union{String,Nothing} = nothing) → CacheEntryStore data in cache and return a CacheEntry describing the stored item.
If label is given and another entry with that label already exists, it is silently replaced. The storage format is selected automatically based on the data type:
DataFrameand other Tables.jl-compatible types →.csvNamedTuple→.json(JSON-primitive values only; Float32/Float16 widen to Float64)- Images (
Matrix{<:Colorant}) →.png(requires FileIO to be loaded) - Anything else →
.jls(Julia binary serialization; not stable across Julia versions)
Pass format explicitly (e.g. format = "jls") to override the automatic selection.
description is an optional human-readable string (e.g. the source expression) stored alongside the entry for display.
The returned CacheEntry can be passed directly to read, delete!, relabel!, and related functions, or retrieved later by label using entry.
DataCaches.@filecache! — Macro
@filecache! expr
@filecache! cache exprEvaluate expr (a function call), unconditionally store the result in a DataCache, and return the result. Unlike @filecache, this macro always re-executes the function and overwrites any existing cached entry, making it useful for forcing a cache refresh.
The one-argument form uses active_autocache(). Pass an explicit DataCache as the first argument to target a specific store.
A @debug message is emitted (visible when ENV["JULIA_DEBUG"] = "DataCaches") announcing the update.
Examples
# Force-refresh the autocache store
occs = @filecache! pbdb_occurrences(base_name="Canidae", show="full")
# Force-refresh a specific cache
my_cache = DataCache("/data/pbdb_cache")
occs = @filecache! my_cache pbdb_occurrences(base_name="Canidae")DataCaches.@filecache — Macro
@filecache expr
@filecache cache exprEvaluate expr (a function call) and store the result in a DataCache, persisting it across Julia sessions. Subsequent calls with identical arguments load from cache without executing the function again.
The one-argument form uses active_autocache(). Pass an explicit DataCache as the first argument to use a different store.
Examples
occs = @filecache pbdb_occurrences(base_name="Canidae", show="full")
my_cache = DataCache("/data/pbdb_cache")
occs = @filecache my_cache pbdb_occurrences(base_name="Canidae")DataCaches.@memcache — Macro
@memcache exprEvaluate expr (a function call) and cache the result in memory for the current Julia session. Subsequent calls with identical arguments return the cached value without re-executing the function.
The cache is keyed on the runtime values of all arguments. Use memcache_clear! to discard cached results.
Example
occs = @memcache pbdb_occurrences(base_name="Canidae", show="full")
taxa = @memcache pbdb_taxa(name="Dinosauria")