DB Plan
Often, your extension may rely on certain information existing in the database to run appropriately. For instance, perhaps you want to limit who can view your feature. Or perhaps you want to store text in the database for easy retrieval and update.
Whatever the reason, if you would like to pre-populate the database during extension installation, you want to know about our DbPlan class. Technically this operation happens at the tail end of installation, so your DbPlan can rely on data existing in the database already, such as the FormName or WedgeAddressConfigs.
DB Plans are comprised of one or more InstallSteps, and referenced in an extension’s DbPlan variable.
If you use the default extension built with q2 create_extension entrypoint, these will live in
<your_extension>/install/db_plan.py and look something like this:
from q2_sdk.core.install_steps import db_plan
class DbPlan(db_plan.DbPlan):
def __init__(self):
"""
It is often necessary to configure the database with information
for an extension to run appropriately. This is your home to do so.
Each of these attributes corresponds to a table (or set of tables) in the
database. Instead of forcing all Antilles users to learn the
database structure of Q2, we've opted for this handy abstraction.
"""
super().__init__()
self.ui_text_prefix = 'AccountDashboard' # Will be used for all self.ui_text_elements
# self.send_account_list = True # Populate self.account_list when HQ calls the extension
# self.send_account_details = True # Populate HADE data on accounts in self.account_list
# self.wedge_payload_stored_proc = None # Run a given Stored Procedure to manipulate the call shape from HQ
# self.insight_features = [] # Run a list of Insight API Features as part of the install (Custom stored procedures)
# self.api_stored_procs = [db_plan.ApiStoredProc()]
# self.audit_actions = [db_plan.AuditAction()]
# self.audit_category = [db_plan.AuditCategory()]
# self.data_feeds = [db_plan.DataFeed()]
# ...
Note
Depending on your version of the SDK, the actual options available in BaseDbPlan may vary. Typing self. or
generating a new extension will have the full list available in your codebase.
Let’s say we wanted to save some text into the database. We would first find the appropriate line
(self.ui_text_elements), and replace it with something like this:
self.ui_text_elements = [
db_plan.UiTextElement(
'myTextElement', # Short Name
'Contains text for my extension', # Description
'Radical!' # Text Value
)
]
Now, when we run q2 install the database will be populated with these values.
For a full list of install_vars, refer to Install Steps in the Caliper Class Reference section.
Registering Stored Procedures and Audit Actions
Before the SDK can call a custom stored procedure, that procedure has to be registered in
Q2_ApiStoredProc. Most procedures also want an audit action to go with them, and every audit action needs
a category to live in. All three of those are install steps, so all three belong in your DbPlan.
Important
Writing the equivalent INSERT statements into your install/sql_server script instead is rejected at
review. The DbPlan is the only sanctioned route.
Here is a DbPlan that registers a procedure along with its audit action and category:
from q2_sdk.core.install_steps import db_plan
class DbPlan(db_plan.DbPlan):
def __init__(self):
super().__init__()
# Registers the procedure so you can reach it with ExecuteStoredProcedure
self.api_stored_procs = [
db_plan.ApiStoredProc(
'example_StoredProc', # Short Name, how you refer to it from code
'Returns the example rows for a user', # Description
'example_StoredProc' # Stored Procedure Name, defaults to Short Name
)
]
self.audit_actions = [
db_plan.AuditAction(
'example_StoredProc', # Short Name
'Returns the example rows for a user', # Description
'Example' # Category Short Name
)
]
# Careful: audit_category is singular
self.audit_category = [
db_plan.AuditCategory(
'Example', # Short Name
'Example action or stored proc execution' # Description
)
]
Now q2 install (or q2 run_db_plan) will create all three. The category is always installed ahead of
the action that references it, so the order you declare them in does not matter, and each step only inserts
when the row is missing, so re-running an install is safe.
Warning
audit_category is singular, while api_stored_procs and audit_actions beside it are plural. It
is an easy line to mistype and a quiet one when you do: your DbPlan still picks up an
audit_categories step when you install it directly, but that name is not one the SDK recognizes, so an
install driven from a serialized plan – which is how your extension reaches the datacenter – skips the
category and then fails on the audit action that needed it.
Two things the older hand-written SQL could express have no equivalent here. The ApiStoredProc step does
not take an audit action, so it leaves Q2_ApiStoredProc.ActionID empty; if you need that link, the
ApiStoredProc DbObject accepts one, and you can call it from a
custom install step. The AuditAction step passes along only a short name,
description and category, so the audit flags on the row – whether the action shows in Central, reaches
syslog, or counts as a risk action – are left to HQ rather than set by you. Talk to the SDK team if your
action needs particular flags.
Migrating an existing script
If you already have an install/sql_server script that registers itself, you are not required to rewrite
it. Those blocks keep working, and the review rule only fires on files you change, so the natural time to
move is when you are in there for another reason anyway.
To migrate, delete the INSERT statements, leave just the CREATE OR ALTER PROCEDURE body, and declare
the same three registrations in your DbPlan. Keep in mind that the install steps only insert when the row is
absent, so a procedure that is already installed keeps the row– and the audit flags– your old script gave
it. Because the two routes do not set those flags the same way, check with the SDK team before migrating
anything that depends on its action appearing in Central, reaching syslog, or being treated as a risk action.
Custom Install Steps
There may be times when the install steps provided by the SDK don’t quite meet your needs. That is why you can inherit from the SDKs install step classes, including the Install Steps Base. If any of your install steps in the DbPlan are dependant on any kind of logic it is best to put that logic into your own child install step class. Then you reference your custom class inside the DbPlan just like it was one provided by the SDK.
Example: A custom install step that initializes wedge config with different values based on the selected core:
import json
from q2_sdk.core.install_steps import db_plan
from q2_sdk.core.install_steps.base import InstallStep, InstallStepAttribute
from q2_sdk.hq.db.form import Form
class DbPlan(db_plan.DbPlan):
def __init__(self):
super().__init__()
self.ui_text_prefix = "MyExtensionName"
self.init_config = [InitializeConfig(form_short_name='MyExtensionName')]
class InitializeConfig(InstallStep):
def __init__(self, form_short_name: str):
super().__init__()
self.form_short_name = InstallStepAttribute(form_short_name, is_editable=True)
async def install(self):
# Fetch the specified form from the DB
form = await Form(
logger=self.logger,
hq_credentials=self.hq_credentials
).get_by_name(self.form_short_name.value)
# Parse wedge config JSON
config = json.loads(form.Config.text)
if "moneyMovementStyle" in config:
# Config is already set, don't override
return
# If CorePro was configured
if config["q2_core"]["name"] == "CorePro":
# Set our custom config
config["moneyMovementStyle"] = "fancy"
else:
config["moneyMovementStyle"] = "slightly-less-fancy"
# Update the form in the DB
await Form(self.logger).update(
short_name=form.ShortName.text,
url=form.Url.text,
config=config,
account_rights_bit_flag=int(form.AccountRightsBitFlag.text),
)