API Reference

DataCaches.CacheEntry — Type
CacheEntry

A 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; use reindexcache! to compact gaps)
  • e.label :: String — user-assigned label (hash string for @filecache entries; empty if none)
  • e.path :: String — absolute path to the backing data file
  • e.description :: String — human-readable source expression (empty if none was recorded)
  • e.datecached :: DateTime — when the entry was written; typemin(DateTime) if unknown
  • e.dateaccessed :: DateTime — when the entry was last read; typemin(DateTime) if never accessed
  • e.ttl :: Union{Nothing,Period} — time-to-live; nothing means 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.

source
DataCaches.CacheSerializer — Type
CacheSerializer

Abstract 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) — write data to fpath
  • read_data(s, fpath::String) — read and return data from fpath

Register a new serializer with register_serializer! so it is available for reading entries by format tag.

source
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)
end

Use 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)
source
DataCaches.PurgePolicy — Type
PurgePolicy

Configuration 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 (by datecached)
  • max_idle::Union{Nothing,Period} — remove entries not accessed within this period
  • keep_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 ≤ limit
  • keep_labeled::Bool — when true, labeled entries are never auto-purged

See set_autopurge! and DataCaches.CacheAssets.purge!.

source
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.

source
Base.keys — Method
keys(cache::DataCache) → Vector{CacheEntry}

Return all CacheEntry objects stored in cache.

Note

Prefer entries for new code — it supports filtering and sorting. keys is maintained for backward compatibility.

source
Base.read — Method
read(cache::DataCache, entry::CacheEntry) → data
read(cache::DataCache, label::AbstractString) → data
read(cache::DataCache, n::Integer) → data

Retrieve 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.

source
DataCaches.active_autocache — Method
active_autocache() → DataCache

Return 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:

  1. A store explicitly set by set_active_autocache! or set_autocaching!(true; cache=x) — if either was called, that store is returned.
  2. Otherwise, the DATACACHES_AUTOCACHE_STORE environment variable — if set, opens a DataCache at that path.
  3. 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!.

source
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 default DataCache. Used when autocache is active but the user did not pass an explicit cache to set_autocaching!. Allows a library to default to its own scratch_datacache!-backed store while still letting the user override via set_autocaching!(true; cache=x). Pass nothing (default) to fall through to active_autocache().
  • force_refresh: When true, bypasses the hit check and overwrites any existing entry.

Store resolution priority

  1. User-explicit: set_autocaching!(true; cache=x) → always uses x
  2. package_cache kwarg → used when no explicit user cache was set
  3. active_autocache() → final fallback (lazy)
source
DataCaches.clear! — Method
clear!(cache::DataCache)

Remove all entries from cache and delete their backing files from disk.

source
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

KeywordTypeEffect
patternAbstractString/RegexKeep entries whose label or description matches
beforeDateTimeKeep entries cached before this time
afterDateTimeKeep entries cached after this time
accessed_beforeDateTimeKeep entries last accessed before this time
accessed_afterDateTimeKeep entries last accessed after this time
labeledBooltrue = only labeled; false = only unlabeled
missing_fileBooltrue = only entries whose backing file is gone

Sorting keyword arguments

KeywordValues
sortby:seq (default), :label, :date, :date_desc, :dateaccessed,
:dateaccessed_desc, :size, :size_desc
revBool — 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 store

See also: entry, labels, keys, DataCaches.CacheAssets.ls.

source
DataCaches.entry — Method
entry(cache::DataCache, label::AbstractString) → CacheEntry
entry(cache::DataCache, n::Integer) → CacheEntry
entry(spec) → CacheEntry

Look 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 index

See also: entries, write!

source
DataCaches.importcache! — Method
DataCaches.importcache!(dest::DataCache, source; conflict=:overwrite) → DataCache

Import all entries from an external cache source into dest.

source can be:

  • A filesystem directory containing a DataCache store (cache_index.toml at its root).
  • A .zip file containing a DataCache store at its root.
  • An HTTP/HTTPS URL pointing to a .zip file; 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 an ErrorException immediately 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.

source
DataCaches.invalidate! — Method
invalidate!(cache::DataCache; kwargs...) → DataCache
invalidate!(; kwargs...) → DataCache

Remove 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 — Regex or String; matched against label, description, or UUID
  • filepath_pattern — Regex or String; matched against full file path
  • filename_pattern — Regex or String; matched against filename only
  • format — String or Regex; matched against the entry's format tag ("csv", "jls", …)
  • before::DateTime — entries cached before this time
  • after::DateTime — entries cached after this time
  • accessed_before_date::DateTime — entries last accessed before this time
  • accessed_after_date::DateTime — entries last accessed after this time
  • labeled::Union{Nothing,Bool} — true = labeled only; false = unlabeled only

Invalidation criteria

  • stale::Bool = false — further restrict to entries that are past their TTL
  • predicate::Union{Nothing,Function} = nothing — further restrict to entries where predicate(entry) returns true

Options

  • dry_run::Bool = false — print matching entries to io without deleting
  • io::IO = stdout — output stream for dry_run messages

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!.

source
DataCaches.isstale — Method
isstale(cache::DataCache, entry::CacheEntry) → Bool
isstale(cache::DataCache, label::AbstractString) → Bool
isstale(entry::CacheEntry) → Bool
isstale(label::AbstractString) → Bool

Return 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 minutes

See also: invalidate!, DataCaches.CacheAssets.purge!.

source
DataCaches.keylabels — Method
keylabels(cache::DataCache) → Vector{String}

Return all labels of entries in cache (empty string for unlabeled entries).

Note

Prefer labels for new code — it returns only user-assigned labels (no empty strings). keylabels is maintained for backward compatibility.

source
DataCaches.keypaths — Method
keypaths(cache::DataCache) → Vector{String}

Return the file paths of all entries in cache.

source
DataCaches.label — Method
label(cache::DataCache, entry::CacheEntry) → String

Return the label associated with entry (same as entry.label).

source
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 store

See also: entries, keylabels.

source
DataCaches.migrate_legacy_autocache — Method
DataCaches.migrate_legacy_autocache(; conflict::Symbol = :skip) → Bool

Migrate 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).

source
DataCaches.migrate_legacy_defaultcache — Method
DataCaches.migrate_legacy_defaultcache(; conflict::Symbol = :skip) → Bool

Migrate 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 false immediately.
  • 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 via importcache! and then the legacy directory is removed. The conflict keyword 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 an ErrorException immediately 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)
source
DataCaches.migrate_v020_defaultcache — Method
DataCaches.migrate_v020_defaultcache(; conflict::Symbol = :skip) → Bool

Migrate 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 false immediately.
  • 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 via importcache! and then the v0.2.0 directory is removed. The conflict keyword 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 an ErrorException immediately 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)
source
DataCaches.movecache! — Method
DataCaches.movecache!(cache::DataCache, new_path::AbstractString) → DataCache

Move 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_path does not exist, it is created (including any missing parent directories).
  • If new_path == abspath(cache.store), returns cache unchanged (no-op).
  • If new_path already exists (and differs), throws an error.

The move is performed with Base.mv, which copies then deletes across filesystem boundaries.

source
DataCaches.path — Method
path(cache::DataCache, entry::CacheEntry) → String

Return the file path of the data file backing entry (same as entry.path).

source
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).

source
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.

source
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) → CacheEntry

Rename 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.

source
DataCaches.scratch_datacache! — Function
scratch_datacache!(pkg_uuid::Base.UUID, key::Symbol = :datacache) → DataCache

Create 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[]
end
source
DataCaches.serializer_for — Method
serializer_for(data) -> CacheSerializer

Infer 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):

  1. NamedTuple → JSONSerializer
  2. AbstractDataFrame → CSVSerializer
  3. Any Tables.jl-compatible type → CSVSerializer
  4. Everything else → OpaqueSerializer (Julia binary .jls)
source
DataCaches.set_active_autocache! — Method
set_active_autocache!(cache::DataCache) → DataCache

Set 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.

source
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)
source
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 store
source
DataCaches.set_autopurge! — Method
set_autopurge!(cache::DataCache; enabled=true, kwargs...) → DataCache
set_autopurge!(; enabled=true, kwargs...) → DataCache

Configure 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 (by datecached)
  • max_idle::Union{Nothing,Period} — remove entries not accessed within this period
  • keep_count::Union{Nothing,Int} — keep only the N most-recently-accessed entries
  • max_size_bytes::Union{Nothing,Int} — purge LRU entries until total cache size ≤ limit
  • keep_labeled::Bool = false — when true, 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!.

source
DataCaches.showcache — Method
showcache(cache::DataCache)

Print a detailed summary of all entries in cache. Equivalent to show(stdout, MIME"text/plain"(), cache).

source
DataCaches.write! — Method
write!(cache::DataCache, data; label::AbstractString = "", description::AbstractString = "", format::Union{String,Nothing} = nothing) → CacheEntry

Store 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:

  • DataFrame and other Tables.jl-compatible types → .csv
  • NamedTuple → .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.

source
DataCaches.@filecache! — Macro
@filecache! expr
@filecache! cache expr

Evaluate 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")
source
DataCaches.@filecache — Macro
@filecache expr
@filecache cache expr

Evaluate 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")
source
DataCaches.@memcache — Macro
@memcache expr

Evaluate 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")
source