Custom SQL

Rather than calling raw SQL queries at runtime, the Caliper SDK uses “stored procedures” registered ahead of time. Most of the DbObjects rely on stored procedures, and it is possible to write your own– you can even build new table schema.

Custom stored procedures are to be placed in the install/sql_server directory of your extension and will be run in alphanumeric order. These SQL scripts will only run in the sandbox environments, and will not run in the Q2 datacenter.

Why you might need to write your own

  • If the DbObjects provided by the Caliper SDK are not sufficient to access the data you need

  • If you are creating your own custom database table, specific to your use-case

Note

Reach out to the SDK team before writing custom SQL. Unexpected custom SQL can lead to much longer code reviews and deployment delays because the team will need to review and approve all SQL before running in the datacenter.

Caveats

To minimize the security and functionality risks of using custom SQL, please follow these steps:

  • Ensure all your custom stored procedures start with a common prefix that is NOT sdk_ or Q2_.

  • Any custom schema that you add must be non-destructive. You do NOT want a future re-run of your query to wipe out all data that has been written to your table.

  • Ensure your stored procedures are added to the Q2_ApiStoredProc table as part of the extension’s DbPlan, via use of the ApiStoredProc InstallStep. If this step is missed, you will not be able to call the stored procedure. Registering from the SQL itself instead– by hand-writing the INSERT statements into your script– is rejected at review, so see Registering Stored Procedures and Audit Actions for the route we do take.

  • Test your SQL! Run it multiple times in a row with q2 run_sql. Make sure it works before running it against a production database! We cannot review every possible case under which your SQL could be run.

Automating installation

By default, these stored procedures will only be installed manually. Depending on how frequent the SQL will need to be installed, the SDK team may convert the SQL into something called an insight feature, or a marketplace feature. After review and approval by Q2’s database team, the sql will then be registered under a name. The addition of that name to your DbPlan’s insight_features, or marketplace_features list will then enable the feature– and your stored procs– as part of the installation.

Installing Insight Features Locally

To install insight features locally during development:

  1. Ensure you have InsightAPI credentials (internal Q2 developers only)

  2. Run q2 insight login to authenticate and cache your token

  3. Run q2 install or q2 run_db_plan

  4. When prompted, enter your customer_key (e.g., DEV_ABC123)

  5. Insight features will be installed automatically

If you don’t have InsightAPI credentials (external developers), the insight features will be skipped locally and will be installed by the CDM during production deployment.

To test SQL locally without InsightAPI access, use q2 run_sql to execute your local SQL files.

Note: The customer_key is environment-specific. Contact your team lead or check your environment configuration to determine the correct customer_key for your development environment.

Examples

A few examples of some custom SQL templates:

CREATE OR ALTER PROCEDURE dbo.example_StoredProc @user_id    INT
AS
BEGIN

    SELECT * FROM dbo.example_Table AS et
    WHERE et.UserID = @user_id

END
GO

-- Registration does not belong here. Declare the ApiStoredProc, AuditAction and
-- AuditCategory install steps in your extension's DbPlan instead.

When creating a custom stored procedure, keep performance in mind. The team will look for indexed columns in WHERE and ORDER BY clauses as well as SARGability.

That procedure is not callable until it is registered, and that registration belongs in your DbPlan rather than alongside the SQL:

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
            )
        ]

See Registering Stored Procedures and Audit Actions for what these steps cover, what they leave to HQ, and how to migrate a script that registers itself today.

IF NOT EXISTS(SELECT NULL
              FROM sys.tables t
                       INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
              WHERE t.name = 'sdk_CaliperAPICustomEndpoint'
                AND s.name = 'dbo')
    BEGIN
        CREATE TABLE [dbo].[sdk_CaliperAPICustomEndpoint]
        (
            [CustomEndpointID] [int]          NOT NULL IDENTITY (1, 1),
            [ShortName]        [varchar](50)  NOT NULL,
            [Description]      [varchar](100) NULL,
            [WedgeAddressID]   [int]          NOT NULL,
            [Author]           [varchar](50)  NULL
        );


        ALTER TABLE [dbo].[sdk_CaliperAPICustomEndpoint]
            ADD CONSTRAINT [PKC_sdk_CaliperAPICustomEndpoint_ShortName] PRIMARY KEY CLUSTERED ([ShortName]);

        ALTER TABLE [dbo].[sdk_CaliperAPICustomEndpoint]
            ADD CONSTRAINT [FK_sdk_CaliperAPICustomEndpoint_Q2_WedgeAddress] FOREIGN KEY ([WedgeAddressID]) REFERENCES [dbo].[Q2_WedgeAddress] ([WedgeAddressID]);

    END

GO

When creating a custom table, keep these in mind:

  1. Always check for the tables existence

  2. All tables must have a clustered index

    • It is easier to do this in a different script that will also check for the existence of the index before creation

  3. Indexes and other constraints must be named

    • Q2’s constraint naming convention is as follows: [PK/FK/IX][u if unique][c if clustered]_[table name]_[column names]_[inc if included fields]

  4. Table names should have a grouping prefix, similar to how the Q2 tables are Q2_ or SDK tables are SDK_

  5. All fields should be explicitly named NULL or NOT NULL

  6. Tables should have a mechanism for removing old rows that are not needed anymore

Reviewing Custom SQL

If there are custom database scripts (stored procedures or tables), this will be reviewed and highly scrutinized. The database is currently Q2’s single point of failure, so we want to make sure that your custom scripts do not threaten the technology stack. These reviews will add more time to the deployment SLA. To reduce long wait times for deployments, here is a list of things we will check:

  1. Does the SQL need to exist? Are there any other ways to solve the issue?

  2. Does a DB object or HQ method already do the same procedure

  • If there is just a small change to a DB object to get it where it needs to be, we may insist on making the change

  1. Are procedures and/or table names prefixed and have a schema identifier, ie. dbo.companyname_GetSomeData.

  2. Are any custom tables using foreign keys to other Q2 tables? We don’t want to affect any Q2 operation that might fail because of a foreign key constraint on a custom table.

  3. Are any procedures included to delete or cleanup rows on a custom table, to prevent it from being forever growing?

  4. Are the procedures performant?

  • Are the queries sargable?

  • Do queries that return a large amount of data use pagination?

  • Are queries being performed on high traffic tables? These include, but are not limited to, the Q2_Audit, Q2_Message, and Q2_Notification tables

  1. If a stored procedure is querying a list of entities, like Q2_Users, are deleted entities being filtered out?

  2. Does the stored procedure have any EXEC functions?

External Db Storage(Beta)

The q2_externaldb package allows you to store and retrieve data from external databases like Postgres. This allows creating your custom tables, stored procedures separated from the Q2 tables.

External Database High-Level Architecture

The diagram above shows the high-level architecture of how SDK extensions connect to external databases. Client-controlled databases (Aurora Postgres) are separated from the Q2 HQ SqlServer.

External Database Internal Components

This diagram shows the internal components of the ExternalDb package, including the ExterDbObjectFactory, ExternalDbObject, and EnginePool that manage connections to Aurora Postgres.

Following steps would guide you to create the boiler plate scripts in your extension directory.

Creating External Db Objects

  1. Install q2_externaldb using pip install q2-externaldb

  2. Once you install the package, let’s call the entrypoint to create the external db objects:

    $ q2 create_external_db_object
    Select extension:
    
        1) GoalSaver
    
    Please make a selection and press Return: 1
    GoalSaver
    Select database type:
    
        1) Postgres
    
    Please make a selection and press Return: 1
    Postgres
    
    Postgres support requires additional dependencies that are not installed.
    Would you like to install them now with 'pip install q2-externaldb[postgres]'? [Y/n] Y
    Installing q2-externaldb[postgres]...
    Successfully installed PostgreSQL dependencies.
    Name of the database object: savingsgoal
    Select operation:
    
    1) Get
    2) Add
    3) Update
    4) Delete
    
    Please make a selection and press Return: 1
    Get
    writing rendered jinja template to GoalSaver/external_db_objects/savingsgoal_object.py
    writing rendered jinja template to GoalSaver/install/postgres/get_savingsgoal.sql
    Generated GoalSaver/install/postgres/get_savingsgoal.sql
    writing rendered jinja template to GoalSaver/external_db_objects/factory.py
    Created GoalSaver/external_db_objects/savingsgoal_object.py
    
  3. The command generates a boilerplate external db object file and a factory file in your extension’s external_db_objects directory.

External Db Object Structure

Each external db object extends PostgresObject and defines methods to interact with your Postgres database. The factory provides typed access to your external db objects. Wire it up in your extension handler:

GoalSaver/external_db_objects/savingsgoal_object.py
from typing import Optional

from q2_externaldb.postgres_db import PostgresObject, PostgresRow


class SavingsgoalRow(PostgresRow):
    pass


class Savingsgoal(PostgresObject):
    REPRESENTATION_ROW_CLASS = SavingsgoalRow

    async def get(self, savingsgoal_id: Optional[int] = None) -> list[dict]:
        params = {"p_savingsgoal_id": savingsgoal_id} if savingsgoal_id else None
        return await self.call_function("sp_get_savingsgoal", params)

    async def add(self, data: dict) -> dict:
        result = await self.call_procedure("sp_create_savingsgoal", data)
        return result[0] if result else {}

    async def update(
        self, savingsgoal_id: int, name: str, amount: float, target_date
    ) -> dict:
        params = {
            "p_savingsgoal_id": savingsgoal_id,
            "p_name": name,
            "p_amount": amount,
            "p_target_date": target_date,
        }
        result = await self.call_procedure("sp_update_savingsgoal", params)
        return result[0] if result else {}

    async def delete(self, savingsgoal_id: int) -> bool:
        params = {"p_savingsgoal_id": savingsgoal_id}
        await self.call_procedure("sp_delete_savingsgoal", params)
        return True

Key concepts:

  • PostgresObject: Base class that provides database connectivity and helper methods

  • PostgresRow: Base class for representing database rows

  • call_function: Calls a Postgres function that returns results

  • call_procedure: Calls a Postgres stored procedure

Environment Configuration

Set the following environment variables to configure your Postgres connection:

POSTGRES_HOST=localhost/Aurora Postgres
POSTGRES_PORT=5432
POSTGRES_DB=mydb
POSTGRES_USER=myuser
POSTGRES_PASSWORD=mypassword
POSTGRES_SSL_MODE=disable(for local development)
POSTGRES_SSL_MODE=allow (For AWS Aurora Postgres)

Use the command q2 migrate to install the custom sql that you have written under install/postgres in the configured postgres database