Skip to content

Foundry DB

R edited this page Sep 27, 2026 · 7 revisions

Foundry.DB

Part of the Foundry API reference.

New to WoW addons? Start here →

Foundry.DB is the saved-data module. It loads your addon's SavedVariables, fills in your defaults, runs your version migrations, hands you live tables to read and write, and strips default-equal values back out when the player logs out, so your save file stays small and your code never has to nil-check a setting that has a default. It is the replacement for AceDB-3.0's :New, for the two storage shapes the addons that built Foundry actually use.

This page explains what WoW gives you raw (a single global table that survives between sessions), then why a settings layer helps once an addon has defaults and migrations to manage, then the Foundry.DB API with worked examples, and finally how to migrate from AceDB-3.0.

API version: Foundry.DB is API version 2. Assert it with F:RequireModule("DB", 2) if your addon needs the module present at a minimum version. (This is the module's version; the library as a whole is F.API_VERSION.) F:RequireModule raises in both dev and release builds if the module is missing or too old, because an addon that needs DB cannot safely start without it.

Load order. Foundry.DB requires Foundry.Events and Foundry.Lifecycle to be loaded first; both are hard load-time dependencies and DB refuses to load without either. Loading through Foundry-1.0.xml gets the order right; if you list Foundry's files by hand, keep Events and Lifecycle ahead of DB.

One sentence of caution up front. Save-file bugs are silent: a user's data is gone before anyone notices. Foundry.DB is built to that fact: where it cannot do something safely, it refuses loudly and changes nothing on disk, rather than starting up with half-migrated or half-built data. Several behaviors below that look strict are strict on purpose for that reason.


1. SavedVariables in WoW: the raw primitive

When your TOC declares a SavedVariables file, WoW gives you exactly one thing: a named global table that is written to disk at logout and restored at the next login.

-- MyAddon.toc
-- ## SavedVariables: MyAddonDB
local f = CreateFrame("Frame")
f:RegisterEvent("ADDON_LOADED")
f:SetScript("OnEvent", function(_, event, loadedName)
    if event == "ADDON_LOADED" and loadedName == "MyAddon" then
        MyAddonDB = MyAddonDB or {}      -- the global is nil on a brand-new install
        -- everything in MyAddonDB persists between sessions
    end
end)

That global (MyAddonDB here) is an ordinary Lua table. WoW does four things with it and nothing else:

  • It is nil until your addon's ADDON_LOADED fires; reading it before then gets you the unrestored value (typically nil), not your saved data.
  • After ADDON_LOADED it holds whatever was on disk at the last logout.
  • It is serialized back to disk at PLAYER_LOGOUT (and on /reload).
  • It is keyed by nothing: there is no concept of "this character" versus "that character" or "this setting versus its default." All of that is your job.

For a tiny addon with two booleans, that raw table is the right tool and Foundry.DB is unnecessary: write MyAddonDB.enabled and you are done.


2. Why a settings layer, and when

Past a handful of settings, four jobs appear that the raw table does not do for you, and each one is a place where a hand-rolled version quietly goes wrong:

  • Defaults. You want db.profile.iconSize to read 16 on a fresh install without writing 16 to disk for every user, and you want a stored false to beat a default of true, not be silently treated as "unset."
  • Per-character vs shared. Some data is the character's (their history, their position); some is the whole account's (a vendor cache). The raw table has no character key; you would compute "Name - Realm" yourself and key every read by hand.
  • Migrations. When your data shape changes between versions, something has to detect the old version and upgrade it once, and refuse to load a file written by a newer build it does not understand.
  • Cleanup at logout. A save file that stores every default for every user bloats forever. Stripping values that equal their default keeps it small, and has to happen at exactly the right moment without losing the user's real data.

Foundry.DB does these four jobs and stops there. It is deliberately not a full AceDB clone: no profile switching, no callbacks, no namespaces, no wildcard defaults (see section 10). It supports the two on-disk shapes its consumers actually have, and any feature neither of them uses fails loudly rather than sitting there as a half-working trap. Reach for Foundry.DB when an addon has defaults and persistence to manage; use the raw global directly when it does not.


3. Creating a database: F.DB:New(config)

local F  = _G.Foundry_1_0
local db = F.DB:New({
    name           = "MyAddon",          -- your TOC addon name (who owns this)
    sv             = "MyAddonDB",         -- your TOC ## SavedVariables global name
    defaults       = MyAddon.Defaults,    -- optional: defaults by section
    defaultProfile = true,                -- required: literal true
    schema         = MyAddon.Schema,      -- optional: migration seam (section 8)
})

:New returns a controller that you hold. The controller is the live view of your saved data: read and write through its section properties (db.profile, db.char, db.global, db.sv), call its methods. Foundry does not attach anything to your addon object; where you store db is entirely your choice (MyAddon.db, a local, wherever), and Foundry never writes into your tables.

Config fields

Field Type Required Meaning
name non-empty string yes Your addon's TOC name, the owner identity. Foundry uses it to confirm your SavedVariables have actually finished loading before it touches them (section 6). This must be the addon whose TOC declares ## SavedVariables: <sv> (see the constraint below).
sv non-empty string yes Your SavedVariables global name, exactly as in your TOC ## SavedVariables line. Foundry resolves and (if needed) creates _G[sv]. This is the only global Foundry.DB ever writes.
defaults table no Your defaults, grouped by section. Top-level keys may be only profile, char, and global. Anything else is rejected (section 4). Foundry holds this table by reference and never writes into it.
defaultProfile literal true yes Must be the literal value true. This selects the shared-profile model: every character resolves to one shared profile named "Default". (AceDB's other two third-argument modes are not supported; see below.)
schema table no The migration seam: { version, key, migrate } (section 8). Optional; if absent, run your migrations yourself after :New as you do today.

Why name and sv are two fields. Under AceDB you passed one string (the SavedVariables name) as the first argument. Foundry splits them deliberately: name is who you are (the owner identity, the same field Foundry.Commands and Foundry.Lifecycle take) and sv is which global holds your data. They are usually different ("MyAddon" vs "MyAddonDB"), and collapsing them would invite a silent disaster: if name doubled as the SV name, a typo that named a real addon global would resolve, persist nothing, and never warn you. Two fields make the mistake impossible to make quietly.

name must be the declaring addon. Foundry confirms your data is loaded by asking WoW whether name has finished loading (section 6). That check is only meaningful for the addon whose TOC actually declares the SavedVariables file. If you have a load-on-demand data module that declares its own ## SavedVariables, pass that module's name, never its parent's. WoW does not expose which addon declared a SavedVariables file, so Foundry cannot check this for you. It is a rule you have to follow, and breaking it re-opens the load-timing hazard the check exists to close.

Required defaultProfile = true. Foundry.DB v1 supports exactly the shared "Default" profile model, the third argument both founding consumers pass. AceDB's other two modes (a literal string for a differently-named shared profile, or omitting the argument for one profile per character) are rejected at :New: neither has a real consumer, and the omitted mode would manufacture a whole third on-disk layout. Pass the literal true; passing a string, or leaving it out, fails loudly. (Saved profile keys already on disk still resolve exactly as before; this only constrains how new databases are constructed.)

Validation is all-or-nothing

:New checks everything before it changes anything: the field types, the defaults section names, a recursive scan for forbidden wildcard keys, the defaultProfile mode, the schema.key rules (its required global root and a collision check against your defaults; section 8), the player/realm identity, whether your addon has actually loaded, the structural soundness of the existing file, and a downgrade check. Only after every check passes does it touch _G[sv].

A rejected :New leaves your SavedVariables byte-for-byte untouched. It does not even create the global if it was missing, and creates no library state you can observe. There is no half-built database. Type problems are reported before state problems. This is the governing rule of the whole module: one loud failure at startup is always preferred to a partial start over half-valid save data.

One database per SavedVariables global

Calling :New a second time for an sv that already has a live (un-Destroyed) database is rejected. AceDB allowed two objects over one file and stripped it twice at logout; Foundry refuses, the same way Foundry.Lifecycle allows one controller per addon name. Neither founding consumer relies on the double form.

What you can do the moment :New returns

When :New returns, your database is fully ready: sections resolve, defaults apply on first access, and any migrations you registered via schema have already run. You can read and write db.profile / db.char / db.global on the very next line, and run your own ad-hoc migrations against them immediately (exactly the synchronous use you have today with AceDB).


4. Reading and writing: sections and defaults

4.1 The four section properties

The controller exposes your data as four properties. Three are the familiar section tables; the fourth is the raw root.

Property Is Use it for
db.profile The current character's resolved profile table (sv.profiles[<resolved key>], normally "Default" for a fresh save; a profile key already saved in profileKeys[charKey] resolves to that key instead). Per-account settings the user expects to follow them across characters in the shared profile.
db.char This character's own bucket (sv.char[charKey], ordinarily "Name - Realm"; see "The per-character key on a client with region-wide unique names" in section 6). Strictly per-character data: history, positions, per-character state.
db.global The account-wide table (sv.global), no key layer. Account-wide data shared by every character: caches, collected records.
db.sv The live SavedVariables root (_G[sv] itself). The escape hatch for cross-character work: reading or writing another character's bucket via db.sv.char[someOtherKey].

These are plain Lua tables. There are no proxies, no __newindex, no write-tracking. Wholesale assignment works (db.global.cache = {}), reads of absent keys return nil, and pairs(db.global) iterates the real keys. What you store is what is on disk; Foundry adds no magic to the section tables themselves. (The few guard behaviors described below live on the controller object, not on these section tables; your data tables stay completely plain.)

db.global IS the SavedVariables' own global sub-table, the same table you would reach by reading the raw global directly. If some other part of your addon reads MyAddonDB.global.x raw, it sees exactly what db.global.x sees; there is no shadow copy to keep in sync.

Table identity is stable for the whole session. Sections and their sub-tables are the SavedVariables' own tables, handed to you by reference. If you bind local cache = db.global.cache once at init and hold it, that reference stays valid and live for the session: no swap, no copy, no metatable replacement happens later.

4.2 How defaults apply

Defaults are declared by section, with only concrete keys (no wildcards), and fill in lazily the first time you read a section:

MyAddon.Defaults = {
    profile = {
        iconSize    = 16,
        showTooltip = true,
    },
    global = {
        schemaVersion = 1,
        cache = {},
    },
}
  • A scalar default fills a slot only when the stored slot is raw-nil. A stored value is never overwritten, including a stored false. false beats a default of true, always. Foundry never uses a truthiness test here, because "is this set?" and "is this true?" are different questions and conflating them loses data.
  • A table default fills in missing keys only. If the stored slot is nil, a fresh table is built from the default subtree. If the stored slot is already a table, Foundry recurses and adds only the keys that are missing. This is the additive backfill that lets a new setting you add in v2 appear in a user's v1 save without disturbing anything they already had.
  • A type mismatch is preserved, not destroyed. If the stored value is a non-nil, non-table where the default declares a table, Foundry keeps the stored value and skips applying the default subtree (with a loud diagnostic in dev builds). It never clobbers your data to make room for a default. This is a deliberate, documented one-case difference from AceDB, which would destroy a stored false in that slot (see the migration notes in section 9).
  • Defaults are held by reference, never copied or mutated. One defaults table can safely back two databases at once; Foundry never writes into it.

Sections materialize lazily. A section's defaults are not applied until you first read that section. This matters for on-disk shape: if your addon never reads db.profile, the profiles table is never created in your file, so your save shape stays exactly as it was. (Reading it once is enough to materialize it; that is normal and expected for an addon that uses profiles.) Once materialized, the merged defaults are real, pairs()-visible keys in your own table (not served through any metatable), so iteration sees them.

4.3 Dynamic keys: data you store that is not in your defaults

Anything you write that is not declared in defaults is yours, untouched, forever: records you scan, history entries, caches keyed by id. Foundry never deletes, rewrites, or strips a key it has no default for. Three consequences fall straight out of the rules above and are worth stating plainly:

  • Setting a non-default key to nil deletes it permanently. That is the clean way to remove obsolete data in a migration.
  • Setting a key back to its default value is, on disk, the same as deleting it. Next session it reads as the default again. (See stripping, below.)
  • The contents of a {}-default persist; the empty parent may be dropped and re-merged. If you store into db.global.cache, your entries are kept; an empty cache may be pruned at logout and re-created next session. Guard the parent (db.global.cache = db.global.cache or {}) the way you already do.

4.4 What is NOT supported in defaults

['*'] and ['**'] wildcard defaults are not supported and are rejected at :New: Foundry scans your defaults recursively and refuses any '*'/'**' key at any depth. Neither founding consumer uses them, and their AceDB semantics (materialize-on-read, blocker-stripping) are the most error-prone surface in the whole library. There is no degraded wildcard mode; declare the concrete keys you need.


5. Logout: how the file is kept small

When the player logs out (and on every /reload), Foundry strips your save file back down: any value equal to its default is removed, because the default will just be re-applied next session. This is what keeps a save file from growing a copy of every default for every user. The behavior to know:

  • A scalar equal to its default is removed. Set a setting back to its default and it disappears from disk, and reads as that default again next time.
  • Tables are recursed; an emptied table is pruned. A char bucket that ends up empty is removed entirely.
  • Your dynamic data is never touched. Anything not covered by a default (history, caches, unknown leftover keys, sections Foundry does not manage) is written back exactly as-is, byte-for-byte.
  • profileKeys always survives, carrying this character's mapping, so the file remains a valid AceDB-shaped file.

You do not call anything to make this happen; it rides the logout signal automatically for every database you constructed this session. (One subtlety worth knowing: an empty shared profile on a main database survives as {} on disk rather than being pruned. That is a deliberate AceDB-compatible asymmetry, not a leak.)

If your addon also registers a Foundry.Lifecycle OnLogout handler, your handler runs first, then the strip, so anything you write at logout is stripped consistently with everything else. One database's strip never interferes with another's, even if a handler errors along the way.

Note on the live object after logout. Once the strip has run, the in-memory database has had its defaults removed; it is in an end-of-session state and should not be read further. That is fine, because the session is ending; AceDB behaved the same way. There is nothing to do here; it is documented so the behavior is not a surprise if you inspect state during logout.


6. Timing: when it is safe to call :New

SavedVariables are only readable after your addon's ADDON_LOADED has fired. Call :New too early and you would build a fresh, empty database that WoW then clobbers when it restores the real file: silent data loss on every login. Foundry refuses to let that happen:

  • :New asks WoW whether name has finished loading. If it has not, :New refuses (per section 7) before touching anything. So construct your database inside your addon-loaded window (a Foundry.Lifecycle OnAddonLoaded handler, or your AceAddon OnInitialize body during migration), exactly where you construct today.
  • Identity is checked at the same moment: the character name and realm must be real, non-empty strings. WoW's not-yet-resolved "Unknown" placeholder is rejected too, and so is a non-English client's own localized version of that same placeholder. A junk character key would silently orphan the user's existing per-character bucket and write a junk one, so nil, "", and the unresolved placeholder all refuse before any key is computed or any data written.
  • On some clients this identity can still be unresolved at the real ADDON_LOADED, briefly, on a cold client-session login, and, on a client with region-wide unique names, briefly while a character's surname has not arrived yet. Foundry.Lifecycle's OnAddonLoaded hook already holds your handler through exactly that window (see the Lifecycle reference), so constructing your database there, as above, means you should not see this refusal in practice. Constructing from a raw ADDON_LOADED frame instead of OnAddonLoaded loses that protection and can hit this refusal on a cold login or an unsettled surname.

The character key, when valid, is exactly "<character name> - <realm name>" (space-hyphen-space, realm spaces intact) on every client except one with region-wide unique names (below), the same key AceDB used, so your existing per-character buckets resolve unchanged.

The per-character key on a client with region-wide unique names

On a client where a character is identified by first name plus surname, unique across the region, rather than by name plus realm, the character key is instead "First Surname" (a single space, no realm), matching the key AceDB-3.0 minor 39 uses on those clients. A character the client reports without a surname is keyed by first name alone for that session (see the Lifecycle reference for the capped wait that precedes this). Every other client keeps the "Name - Realm" key described above.

Adopting this key carries a one-time move of a character's data from its old "Name - Realm" key. The move runs the first time that character's database is built under the new key, and only when doing so is unambiguous, since two characters on the same realm can share a first name: nothing is already saved under the new key, and no other character sharing that first name has data saved under a full-name or a first-name-only key. The old key was shared by every character of that name on the realm, so if two characters share a first name, the first of them to log in with a surname after upgrading takes whatever was saved under it; the second gets a fresh bucket.

A session that keys a character by first name alone, because its surname has not arrived yet, never triggers the move and leaves the old key's data where it is. It also saves that first-name-only key, and from then on that key blocks the move exactly as another character's first-name-only key would, so the old key's data is not moved automatically in any later session either.

The move itself happens immediately after :New finishes validating the request, as the first change it makes to your SavedVariables. So if :New goes on to refuse for a reason found later in construction, such as a migration that raises, the move has already completed: your data is never left split across the two keys.

The "ready" moment and db:OnReady

The completion of :New is the "settings ready" moment: your data is loaded, defaults apply on access, and your registered migrations have already run. Because that moment is already complete by the time :New returns, holding the controller already means "ready."

db:OnReady(function(db)
    -- runs once, immediately, right here: data is loaded and ready
    MyAddon:ApplyStartupSettings(db)
end)

db:OnReady(handler) lets any module that holds the database register a ready callback. Each handler runs once, called as handler(db). You may register multiple handlers; the point is that several modules can each self-gate on "settings ready" without coordinating who constructed the database.

Honesty boundary: read this before relying on it. Because the ready moment always completes inside :New, db:OnReady(h) is behaviorally just h(db) called right now. It adds convention and discoverability, not a guarantee that holding the controller does not already give you. And the readiness it promises covers migrations registered through schema (section 8); if you run your own ad-hoc migrations after :New, those are your code's responsibility, not part of the ready guarantee. The hook will never claim work Foundry did not do.

Reporting a failed save: db:OnSavedVariablesTooLarge

WoW can decline to save an addon's SavedVariables at all if the file has grown too large. Before Foundry.DB, that condition was silent: the client dropped the save and your addon never found out. db:OnSavedVariablesTooLarge registers a handler that is told when this happens to this database's addon:

db:OnSavedVariablesTooLarge(function(db, addonName, svName)
    -- called when the client refused to save `addonName`'s SavedVariables
    MyAddon:LogSizeWarning(svName)
end)

The handler receives (db, addonName, svName): the database controller, your addon's TOC name, and this database's own SavedVariables global name. You may register more than one handler on the same database; there is no one-handler limit here, and every registered handler runs.

The client's warning names only the addon, not a specific global. An addon that owns two databases sees both handlers called, each with its own svName; the report does not identify which global was the large one.

This is a report, not a rescue. The warning arrives at the very end of the session, after the client has already decided it cannot write the file. By the time your handler runs, that save is already lost; there is nothing your handler can do to make the client accept it after the fact. Use the handler to record the failure, warn the player for next time, or trim data proactively before it happens again, not to try to save the data a different way in the moment.

One handler's error does not stop another's. If two databases belonging to the same addon both register handlers, or a single database has more than one, an error in one handler is captured and the rest still run; the failure is surfaced once afterward rather than aborting the fan-out partway through, the same continue-on-error approach the rest of Foundry uses for shared signals.

Registering a handler on a destroyed controller is refused like any other method call on a destroyed controller (section 7): raised in a dev build, printed and refused in a release build.


7. Error behavior: dev vs release

Foundry.DB uses Foundry's single diagnostic surface. In a dev build a problem raises a clear, named error so you see it immediately. In a release build the behavior depends on whether the failing call has a return value you could have checked:

  • Where a return could be checked (a method call like Destroy on an already-destroyed controller), release prints and returns nil.
  • Where no checked return exists (a refused :New, an access to an unsupported AceDB feature, or a section read on a destroyed controller), release raises the same clear error as dev. For these, the raised error is the refusal: there is no safe nil to hand back, because if db.realm then … after a printed warning would silently disable a feature, which is exactly the silent degradation this module exists to prevent.

In every case the safety is identical in both builds; only the noise differs. A refused operation never half-completes and never loses data; the difference between dev and release is whether you get a raised stack or a printed line, never whether your data is safe.

Condition Dev build Release build
Bad :New config (types, sections, wildcards, defaultProfile mode, schema.key root or collision, duplicate live sv) Raise Raise, same error; nothing was mutated
Too-early :New, or invalid identity (nil / "" / "Unknown" / the client's localized placeholder) Raise Raise, same error; nothing was mutated
Malformed existing data (section 8) Raise Raise, same error; construction refused, file untouched
Downgrade (stored version newer than declared) Raise Raise, same error; construction refused, file untouched
Access/call/write of an unsupported AceDB feature (section 10) Raise Raise, same error
Method call on a destroyed controller Raise Print + refuse (nil)
Section read on a destroyed controller (db.profile etc.) Raise Raise, same error
Your migrate callback raises Surfaced after capture Raise, same error after capture; construction refused

A method invoked on a forged or non-controller value (a copied or fabricated table with no controller mapping) raises a named error in BOTH builds, not print+nil.

Messages follow the house format, for example "DB:New: name must be a non-empty string". All diagnostics are developer-facing English; Foundry.DB emits no player-facing text whatsoever. The only strings it produces are diagnostics for you when the API is misused.


8. Migrations and version protection

You have two ways to migrate, and they coexist.

8.1 Run your own migrations after :New (the default)

Sections are live and synchronous the moment :New returns, so the migration code you run against AceDB today works unchanged: read db.global.schemaVersion, step your data forward, write the new version. Nothing wraps or blocks this. If you already own a working version-stepper, keep it; adopting the seam below is optional.

8.2 The schema seam (optional)

If you would rather Foundry drive the version check, supply a schema:

MyAddon.Schema = {
    version = 4,                          -- your current schema version (positive integer)
    key     = "global.schemaVersion",     -- dot-path to the stamp, rooted at `global`
    migrate = function(db, storedVersion)
        -- storedVersion is the number found on disk (or nil for an unversioned save).
        -- It is lower than `version` when this runs; step it forward to `version`.
    end,
}

What :New does with it, in order:

  1. (Validation) schema.key must be rooted at global. char and profile are keyed maps (one bucket per character, one per profile), so a single flat stamp path inside them has no one place to live: it would land as a stray scalar beside the per-character buckets, and the structural check would then reject the file on every later load, locking the user out of their own save permanently. The only legal root is global (e.g. "global.schemaVersion"); anything else is rejected at :New, before anything is touched.
  2. (Validation) schema.key must not be covered by your defaults. This is rejected at :New, and it matters: the logout strip deletes any stored value equal to its default, so a version stamp that is a default would evaporate from disk at every logout. The seam would then see nil on a healthy save and re-run migrate(db, nil) forever, and downgrade protection would never work. So a version stamp must live outside your defaults table. (Both founding consumers currently declare their stamp inside defaults; adopting the seam means removing that one key from the defaults table. That is a code change, not an on-disk change.)
  3. Read the stored version raw at schema.key.
  4. Stored version newer than version → downgrade: refuse construction (section 8.3).
  5. Brand-new file → stamp version, do not call migrate.
  6. Stored version lower than version, or missing/non-number → call migrate(db, storedVersion) (where storedVersion may be nil for an unversioned save). On a normal return, stamp version. Next session, with the stamp current, migrate is not called again. (A stamp that is present but not a number also slips past the numeric downgrade check, so the two builds split: a release build prints a loud diagnostic, then treats the save as unversioned: migrate(db, nil) runs and the stamp is overwritten. A dev build raises that diagnostic instead, halting construction before migrate runs, so the author fixes the bad stamp rather than silently adopting it.)
  7. If migrate raises, the error is surfaced and construction is refused: a half-migrated database is never handed out. WoW has no transactional rollback, so partial writes may remain on disk, but refusing the controller keeps the session from compounding the damage; next session re-runs the migration from the un-stamped version.

8.3 Downgrade protection

If the stored version is newer than your declared version, :New refuses: a raised, named error in both builds, with the file left byte-for-byte untouched. An older build cannot know what a newer schema means, so loading it could corrupt the newer data; refusing with the data intact is the safe choice. (This protection is exactly why the version stamp must live outside defaults: a stamp the strip could delete would never survive to be recognized as newer.)

8.4 Malformed data

If the existing file is structurally broken (the SavedVariables global is not a table, or a section / bucket / profileKeys entry is the wrong type), :New clearly fails: it refuses construction with a raised error in both builds and never overwrites the corrupt value, so whatever recovery is possible stays possible. Foundry.DB v1 ships no automatic structural repair; that judgment belongs to you or the user, not the library. (A value-level type mismatch against a table default is the gentler case from section 4.2: the stored value is preserved and the default skipped, so your own repair layer can still heal it.)


9. Migrating from AceDB-3.0

For both founding consumers the migration is one line: the construction call. Everything after it (your defaults table, your db.global / db.profile use, your own migrations) stays exactly as it is.

AceDB-3.0 Foundry.DB
LibStub("AceDB-3.0"):New("MyAddonDB", defaults, true) F.DB:New({ name = "MyAddon", sv = "MyAddonDB", defaults = defaults, defaultProfile = true })
Pass the SavedVariables name as the first string Pass name (addon) and sv (SavedVariables) as two fields
Third arg true (shared "Default" profile) defaultProfile = true (required literal)
Third arg as a string / omitted Not supported; both modes are rejected (section 3)
db.profile / db.char / db.global Identical: same names, same plain-table semantics
Your post-:New migration code Identical: runs the same way

Before (AceDB-3.0):

function MyAddon:OnInitialize()
    self.db = LibStub("AceDB-3.0"):New("MyAddonDB", MyAddon.Defaults, true)
    -- migrations run right here against self.db.global / self.db.profile
    self:RunMigrations()
end

After (Foundry.DB):

local F = _G.Foundry_1_0

function MyAddon:OnInitialize()
    F:RequireModule("DB", 2)                      -- refuse to start if DB is missing/old
    self.db = F.DB:New({
        name           = "MyAddon",
        sv             = "MyAddonDB",
        defaults       = MyAddon.Defaults,
        defaultProfile = true,
    })
    self:RunMigrations()                          -- unchanged
end

Things to know when migrating:

  • The constructor's shape changed, not its behavior. Defaults apply the same way, the character key is the same one AceDB uses ("Name - Realm", or on a client with region-wide unique names "First Surname" as in AceDB-3.0 minor 39; see section 6), the shared profile is still "Default", the file on disk is the same shape. A user who has been running your AceDB build keeps every setting.
  • The AceDB raw-table constructor form has no Foundry equivalent. AceDB let you pass the SavedVariables table itself instead of its name. Foundry.DB takes a config table with a string sv; an AceDB-style call simply fails ordinary config validation ("DB:New: name must be a non-empty string"). Use the sv string.
  • One AceDB behavior is not reproduced, on purpose. AceDB destroys a stored false that sits under a table-typed default (it clobbers it to {}). Foundry.DB preserves it. If you ever revert from Foundry.DB back to AceDB, that one slot class is where AceDB, not Foundry, can lose the value. Foundry never produces the loss; this is the one documented round-trip carve-out, and it errs toward keeping your data.
  • Unsupported features fail loudly, not silently. If your addon happens to call db:SetProfile, register a callback, use a namespace, or read db.realm, those raise a clear named error (section 10) rather than half-working. Both founding consumers were checked to use none of these; check yours before you rely on the swap being one line.

10. What Foundry.DB does NOT do

Foundry.DB supports two storage shapes and the four jobs in section 2. Every AceDB surface beyond that is unsupported and fails loudly: never a silent stub, never a nil that flows onward, never a fabricated empty table.

  • No profile management. No SetProfile, GetProfiles, CopyProfile, DeleteProfile, ResetProfile, ResetDB, or GetCurrentProfile. The shared "Default" profile is the whole model. Each call fails with a named error.
  • No extra sections. db.realm, db.class, db.race, db.faction, db.factionrealm, db.locale and the like are not implemented; reading one fails with a named error. (Existing file content under those names round-trips untouched; Foundry just does not surface it as a section.)
  • No callbacks. No RegisterCallback / UnregisterCallback, none of the eight profile/database callback events. There is no OnDatabaseShutdown; Foundry.DB fires no hooks of its own at logout, apart from the size report in section 6. No CallbackHandler dependency.
  • No namespaces. RegisterNamespace / GetNamespace are not implemented; sv.namespaces content in a file round-trips untouched.
  • No post-construction defaults API. RegisterDefaults after :New is not supported; defaults are fixed at construction.
  • No wildcard defaults. ['*'] / ['**'] are rejected at :New (section 4.4).
  • No second database over one file. One live database per sv (section 3).
  • No drop-in LibStub shim. LibStub("AceDB-3.0") never resolves to Foundry.DB; migration is the explicit one-line change in section 9.

A note on the controller object. Reads and writes of unsupported names on the controller fail loudly, including writes, because a stray db.realm = {} would otherwise quietly attach a table to the controller that is never connected to your save file, and everything you then did to it would vanish at logout. That is the worst kind of silent data loss, so the controller guards writes to reserved and unsupported names as well as reads. Two consequences for you:

  • Hold the controller by reference; do not Mixin() it or copy it. Those guards, the lazy section materialization, and the destroyed-controller check all live on the controller's metatable. Copying the controller (as Mixin() does) would silently drop them and the unmaterialized sections, in the one module where silent degradation is most dangerous. Keep the object Foundry hands you and use it directly. (Your section tables, db.profile and friends, are completely plain and safe to pass around by reference; this applies only to the controller object itself.)
  • Your own arbitrary names are fine. Writing or reading a name that is neither a Foundry method nor an AceDB-reserved section behaves as plain Lua, exactly as it would on any table. The guards only intercept the AceDB surface and Foundry's own reserved names.

Escape hatches

When you need the raw data, two hatches hand it back explicitly:

local handles = db:GetNativeHandles()
-- handles.sv  == the LIVE SavedVariables root (your own data, not a Blizzard object)
-- plus read-only snapshots of the character key, profile key, and materialization state

GetNativeHandles returns the live sv root (which is your own saved data, not any Blizzard object) alongside read-only snapshots of Foundry's internal state. Mutating a snapshot changes nothing live. There is no frame field: GetNativeHandles exposes no frame. The logout strip rides Foundry.Lifecycle's shared frame, so if you need the logout frame itself, reach it through a Foundry.Lifecycle controller's own GetNativeHandles.

db:Destroy()   -- release this database's controller surface

Destroy frees the sv slot (so a later :New for that sv is allowed again) and marks the controller destroyed; after it, every method call and every section read fails per section 7, and a second Destroy refuses. Crucially:

  • Destroy never deletes or alters your saved data. Your section tables, if you still hold references to them, remain valid, fully-merged plain tables.

  • The logout strip still runs for a Destroyed database. This is deliberate and important: a database whose materialized defaults were not stripped would serialize those defaults to disk as real values, and after any later change to your defaults the stale value would block the new default forever: a phantom "the user changed this" that pins them to an old default with no warning. So the end-of-session strip duty survives Destroy. (AceDB had no skip-strip state either; this matches it.)

  • No persisted state of its own. Foundry-1.0 owns no SavedVariables. Foundry.DB operates only on your SavedVariables global.

  • No player-facing text. Its only output is developer diagnostics when the API is misused.


By BawrLabs.

Clone this wiki locally