AceDB-2.0

From WowAce Wiki
Jump to: navigation, search

AceDB-2.0 is a Mixin to allow for fast, clean, and featureful saved variable access.

Example 1

As simple as it gets:

MyAddon.toc:

## SavedVariables: MyAddonDB
## SavedVariablesPerCharacter: MyAddonDBPerChar

MyAddon.lua:

MyAddon = AceLibrary("AceAddon-2.0"):new("AceDB-2.0") -- database mixin

MyAddon:RegisterDB("MyAddonDB", "MyAddonDBPerChar")

function MyAddon:PrintSettings()
  self:Print("Alpha for this character is " .. self.db.char.myAlpha)
  self:Print("Beta (shared for all characters) is " .. self.db.account.myBeta)
end

function MyAddon:SetAlpha(value)
  self.db.char.myAlpha = value
end

function MyAddon:SetBeta(value)
  self.db.account.myBeta = value
end

Example 2

With profiles and defaults:

MyAddon.toc:

## SavedVariables: MyAddonDB
## SavedVariablesPerCharacter: MyAddonDBPerChar

MyAddon.lua:

MyAddon = AceLibrary("AceAddon-2.0"):new("AceDB-2.0") -- database mixin

MyAddon:RegisterDB("MyAddonDB", "MyAddonDBPerChar")

MyAddon:RegisterDefaults('char', {
    alpha = {
        bravo = {
            charlie = {}
        }
    },
})

MyAddon:RegisterDefaults('realm', {
    chars = {
        ['*'] = {
            money = 0
        }
    }
})

MyAddon:RegisterDefaults('profile', {
    value = 0
})

function MyAddon:OnInitialize()
    -- the database is usable starting here.
    self.db.profile.value = 0
    print(self.db.profile.value) -- prints out 0
end

function MyAddon:OnEnable(first)
    self.db.char.alpha.bravo.charlie.delta = 50
    self.db.realm.chars[UnitName("player")].money = GetMoney()
    self:OnProfileEnable()
end

function MyAddon:OnProfileDisable()
    -- this is called every time your profile changes (before the change)
end

function MyAddon:OnProfileEnable()
    -- this is called every time your profile changes (after the change)
    if self.db.profile.value < 100 then
        self.db.profile.value = 100
    end
end

function MyAddon:OnDisable()
    
end

function MyAddon:MethodThatHandlesMoney()
    self.db.realm.chars[UnitName("player")].money = GetMoney()
    -- methods that deal with money typically work on a realm-wide basis.
    -- note: an alliance and a horde character on the same realm are seen
    -- as two different realms by AceDB.
end

function MyAddon:MethodThatHandlesNeutralVendors()
    self.db.server.someVendor = { x, y }
    -- methods that deal with server non-faction-based information is stored in .server
end

function MyAddon:MethodThatChangesASetting()
    self.db.profile.setting = not self.db.profile.setting
    -- settings should always be handled on a profile-specific basis.
end

function MyAddon:MethodThatLooksAtAllCharaters()
    self.db.account.value = self.db.account.value + 1
    -- if you need to handle something shared between all characters, use
    -- the "account" part of the db.
end

function MyAddon:MethodThatHandlesSpells()
    self.db.char.spells = 50
    -- character-specific methods use the "char" part of the db.
end

function MyAddon:MethodThatLooksAtAClass()
    self.db.class.points = self.db.class.points + 100
    -- class-specific (Warlock, Hunter) methods use the "class" part of the db.
end

function MyAddon:MethodThatDealsWithFactions()
    self.db.faction.monkeys = self.db.faction.monkeys + 1
    -- faction-specific (Horde, Alliance) methods use the "faction" part of the db.
end

API Documentation

Data types

There are 7 kinds of data as far as AceDB is concerned.

  • char
    • Character-specific data. No other characters can access or change this data, it is specific to one character and one character alone.
  • class
    • Class-specific data. Only other members of your class (Warlock, Warrior, Hunter, etc.) can access/change the data.
  • realm
    • Realm-specific data. Only other members of your realm and faction can access/change the data. AceDB sees characters of different factions (Horde vs. Alliance) as two separate realms.
  • server
    • Server-specific data. Only other members of your server can access/change the data. Different factions are seen as the same server.
  • faction
    • Faction-specific data. If you are a Horde, everyone else who is Horde has this data, even on different realms. Same if you are Alliance.
  • account
    • Account-specific data. Absolutely every has access to and can change this data.
  • profile
    • Profile-specific data. Characters with the same profile have access to and can change this data. Even if your profile is character-specific, that does _not_ mean that it has anything at all to do with the character data type.

:RegisterDB("globalName" [, "perCharName"] [, "defaultProfile"])

Register a saved variable as the database table.

Args

"globalName" 
global name of the saved variable.
["perCharName"] 
global name of the per-character saved variable.
["defaultProfile"] 
name of the profile to default to (default: "Default")

Remarks

Setting the charName is unnecessary if you never use char-specific data. If you do use them, it is a good idea to have. "defaultProfile" can be any arbitrary name, but it's recommended to use "Default", "Alternative", "char", "class", or "realm".

Example

MyAddon:RegisterDB("MyAddonDB")
-- or
MyAddon:RegisterDB("MyAddonDB", "MyAddonCDB")
-- or
MyAddon:RegisterDB("MyAddonDB", nil, "char")
-- or
MyAddon:RegisterDB("MyAddonDB", "MyAddonCDB", "char")

:RegisterDefaults("dataType", defaults) or ("namespace", "dataType", defaults)

Register a set of default values onto a specific data type.

Args

"dataType" 
string - "char", "class", "realm", "server", "account", "faction", or "profile"
"defaults" 
table - A defaults table.
"namespace" 
string - name of a namespace.

Remarks

The defaults table can have subtables as well (as many as you want). This can be used to define your basic db structure. You can also set a whole table's default value by using the special key ['*'], which even works with tables. There is another key, ['**'], which does the same thing as ['*'] _but_ also populates inside sibling nodes. For example, { ['**'] = { alpha = true, bravo = true, charlie = true}, monkey = { bravo = false } } makes monkey behave like { alpha = true, bravo = false, charlie = true } If you use the 'profile' dataType, it applies to _all_ profiles.

Example

self:RegisterDefaults('char', {
    alpha = {
        bravo = {
            charlie = true
        }
    }
})
assert(self.db.char.alpha.bravo.charlie == true) -- note: assert tests for truth.

self:RegisterDefaults('realm', {
    ['*'] = false -- special key
})
assert(self.db.realm.anyKeyHere == false)

self:RegisterDefaults('class', {
    colors = {
        ['*'] = {
             r = 1, g = 1, b = 1
        }
    }
})
assert(self.db.class.colors.boss.r == 1)
self.db.class.colors.boss.r = 0
assert(self.db.class.colors.boss.r == 0)
assert(self.db.class.colors.otherBoss.r == 1)

self:RegisterDefaults('myModule', 'char', {
    value = 50
})

assert(self:AcquireDBNamespace('myModule').char.value == 50)

:GetProfile()

Returns the current profile

Returns

"short", "long"

"short" 
string - The current profile, short-form.
"long" 
string - The current profile, in its full, long form.

Remarks

If you are in a char, class, or realm profile, "short" will be "char", "class", or "realm" and "long" will be "char/Player of Realm Name", "class/Warlock", or "realm/My Realm - Horde". Otherwise, "short" and "long" will be equivalent. "Default" is the default profile.
This is only accurate after ADDON_LOADED.

Example

if self:GetProfile() == "default" then
    -- do something here
end

:SetProfile("profile")

Set the current profile to "profile"

Args

"profile" 
string - the new profile name

Remarks

If "profile" is "char", "realm", or "class", it gets set to the appropriate profile based on the current character. This will call :OnProfileDisable() if available, change the profile, then call :OnProfileEnable("oldName", oldData) if available. In turn, this will call any embeds/superclasses :OnEmbedProfileDisable(self) and :OnProfileEnable(self, "oldName", oldData) if available. 'profile' Defaults will properly transfer to the new profile without harm.

Example

self:SetProfile("Monkey") -- for all your monkey-based goodness.
self:SetProfile("char") -- change to your character

:CopyFromProfile("profile")

Copy the profile at "profile" to your current profile.

Args

"profile" 
string - the profile to copy from.

Remarks

Char-based profiles start with char/, realm with realm/, and class with class/. All others do not have such a prefix. You cannot copy from non-compatible profiles, e.g. a class profile into a char profile. This will call :OnProfileDisable() if available, change the profile, then call :OnProfileEnable("profile", oldData, "profile") if available. In turn, this will call any embeds/superclasses :OnEmbedProfileDisable(self) and :OnProfileEnable(self, "profile", oldData, "profile") if available. 'profile' Defaults will properly transfer to the new profile without harm.

Example

self:CopyFromProfile("Monkey") -- for all your monkey-based goodness.
self:CopyFromProfile("char/Otherchar of Some Realm") -- copy from your other character

:IsActive()

Returns whether the addon is currently activated.

Returns

boolean - whether the addon is currently activated.

Remarks

This is only accurate after ADDON_LOADED. If this is false at ADDON_LOADED, AceAddon will intelligently not call OnEnable at PLAYER_LOGIN.

Example

if self:IsActive() then
    -- do something
end

:ResetDB(["dataType"]) or ("namespace" [, "dataType"])

Resets the database or part of a database, or namespace or part of that namespace

Args

["dataType"] 
Type of data to reset (char, profile, etc.)
"namespace" 
Namespace to reset.

Remarks

If "dataType" is not given, then the whole database is reset. If no namespace is given, all namespaces are reset, as well as the global database.

Example

self:ResetDB("profile") -- resets the profile settings. (for this profile only)

self:ResetDB("MyNamespace", "char") -- resets the character settings for the MyNamespace namespace. (for this character only)

:ToggleActive([state])

Toggles the enabled value of this addon.

Args

[state] 
boolean - the new state to force. by default, not :IsActive()

Remarks

If suspending, This will call :OnDisable() on the addon if it is available. Also, it will iterate through the addon's mixins and call either :OnEmbedDisable(addon) or :OnEmbedEnable(addon) if available. - this in turn will, through AceEvent and others, unregister events/hooks/etc. depending on the mixin. If resuming, This will call :OnEnable(first) on the addon if it is available. If you call :ToggleActive(true) and it is already active, it silently returns, same if you pass false and it is inactive.

Example

self:ToggleActive(true) -- turns on
self:ToggleActive(false) -- turns off
self:ToggleActive() -- turns on
self:ToggleActive() -- turns off

:AcquireDBNamespace("name")

Acquire a database namespace.

Args

"name" 
string - name of the namespace.

Remarks

This is especially handy for a module system to use, simply get a namespace with the same name as your module, and it acts as a fully functioning database.

Example

bank.db = self:AcquireDBNamespace("bank")

.CHAR_ID

string - unique character ID, in the form of "Player of Realm Name", for english. In other locales, the "of" part might be different.

Remarks

This is not exported into addons that use AceDB-2.0 as a mixin.

.REALM_ID

string - realm name and faction id, in the form of "Realm Name - Horde". Horde might instead be Alliance. It is properly localized.

Remarks

This is not exported into addons that use AceDB-2.0 as a mixin.

.CLASS_ID

string - class name, in the form of "Warlock", where Warlock is your class. It is properly localized.

Remarks

This is not exported into addons that use AceDB-2.0 as a mixin.

.FACTION

string - faction, either "Horde" or "Alliance", properly localized. This is available to you at all times (not just after PEW)

Remarks

This is not exported into addons that use AceDB-2.0 as a mixin.

.REALM

string - realm name, guaranteed to not have leading/trailing spaces. Typically same as GetRealmName()

Remarks

This is not exported into addons that use AceDB-2.0 as a mixin.

.NAME

string - player name. Same as UnitName("player")

Remarks

This is not exported into addons that use AceDB-2.0 as a mixin.

Event: Ace2_AddonEnabled

Triggered right after an addon has been enabled.

Args

addon 
table - the addon that was enabled
first 
boolean - whether this is the first time :OnEnable is called.

Example

self:RegisterEvent("Ace2_AddonEnabled")

Event: Ace2_AddonDisabled

Triggered right after an addon has been disabled.

Args

addon 
table - the addon that was disabled

Example

self:RegisterEvent("Ace2_AddonDisabled")

Event: AceDB20_ResetDB

Triggered after the database is reset.

Args

addon 
table - the addon of which the database was reset
"name" 
string - database name
[,"kind"] 
string or nil - database type ( "char", "class", "profile", "account", "realm", "faction", "server" ) or nil if no type

Example

self:RegisterEvent("AceDB20_ResetDB")