npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

forge-sql-orm

v2.2.3

Published

Drizzle ORM integration for Atlassian @forge/sql. Custom driver, schema migration, local in-memory cache, optimistic locking, and query analysis. Use forge-sql-orm-extra for @forge/kvs global cache and Rovo.

Readme

Forge SQL ORM

npm version (core) npm downloads (core) npm version (extra) npm downloads (extra) npm version (CLI) npm downloads (CLI)

forge-sql-orm CI

Quality Gate Status Code Coverage Security Rating Maintainability Rating Bugs Code Smells Vulnerabilities

DeepScan grade Codacy Badge Snyk Vulnerabilities Maintainability Socket Badge

LoC (full) LoC (src)

License REUSE status License compliance (core) License compliance (extra)

Forge SQL ORM is a TypeScript ORM for Atlassian Forge apps that use @forge/sql — Atlassian’s managed SQL storage (TiDB-compatible) inside Forge resolvers, triggers, and scheduled jobs.

Instead of calling @forge/sql with hand-written SQL strings, you define schemas and queries with Drizzle ORM and get full type safety, migrations, and Forge-specific helpers out of the box. The library provides a custom Drizzle driver for @forge/sql, schema migrations, local in-memory caching, optimistic locking, query analysis, and TiDB-oriented types (vectors, binary columns, SQL function helpers).

Packages in this repository:

| Package | Role | | -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | forge-sql-orm (this README) | Core ORM — Drizzle integration, migrations, local cache, query analysis | | forge-sql-orm-extra | Optional add-on — global query cache (@forge/kvs) and Rovo natural-language analytics | | forge-sql-orm-cli | CLI — generate entities and migrations from existing MySQL/TiDB schemas |

Start with forge-sql-orm for any Forge SQL app; add forge-sql-orm-extra only when you need cross-invocation caching or Rovo.

Key Features

  • Custom Drizzle Driver for direct integration with @forge/sql
  • Local Cache System (Level 1) for in-memory query optimization within single resolver invocation scope
  • Performance Monitoring: Query execution metrics and analysis capabilities with automatic error analysis for timeout and OOM errors, scheduled slow query monitoring with execution plans, and async query degradation analysis for non-blocking performance monitoring
  • Type-Safe Query Building: Write SQL queries with full TypeScript support
  • Supports complex SQL queries with joins and filtering using Drizzle ORM
  • Advanced Query Methods: selectFrom(), selectDistinctFrom() for all-column queries with field aliasing (selectCacheableFrom() / global cache in forge-sql-orm-extra)
  • Query Execution with Metadata: executeWithMetadata() method for capturing detailed execution metrics including database execution time, response size, and query analysis capabilities with performance monitoring. Supports two modes for query plan printing: TopSlowest mode (default) and SummaryTable mode
  • Raw SQL Execution: execute(), executeDDL(), and executeDDLActions() for direct SQL (local caching; executeCacheable() in forge-sql-orm-extra)
  • Common Table Expressions (CTEs): with() method for complex queries with subqueries
  • Schema migration support, allowing automatic schema evolution
  • Automatic entity generation from MySQL/tidb databases
  • Automatic migration generation from MySQL/tidb databases
  • Drop Migrations Generate a migration to drop all tables and clear migrations history for subsequent schema recreation
  • Schema Fetching Development-only web trigger to retrieve current database schema and generate SQL statements for schema recreation
  • Ready-to-use Migration Triggers Built-in web triggers for applying migrations, dropping tables (development-only), and fetching schema (development-only) with proper error handling and security controls
  • Optimistic Locking Ensures data consistency by preventing conflicts when multiple users update the same record
  • Query Plan Analysis: Detailed execution plan analysis and optimization insights
  • Level 2 (global KVS) cache & Rovo via forge-sql-orm-extra; Level 1 local cache stays in core
  • TiDB VECTOR type & vector SQL helpers — Drizzle column type vectorTiDBType plus vecCosineDistance, vecL2Distance, vecDims, and related helpers for SQL with AI (embeddings storage and similarity search)
  • Binary custom types (BINARY / VARBINARY / BLOB) — built-in forgeBinary, forgeVarBinary, forgeBLOB, forgeTinyBLOB, forgeMediumBLOB, and uuidBinary for compact binary storage in Atlassian Forge
  • AI semantic search examples for Forge — embeddings in Custom UI (frontend) or on the Forge backend via an ai-lib sidecar; both use vector search in SQL

Table of Contents

🚀 Getting Started

📖 Core Features

🗄️ Database Operations

⚡ Caching & Rovo (forge-sql-orm-extra)

  • Level 2 (global KVS)forge-sql-orm-extra only
  • Level 1 (local cache)core (executeWithLocalContext, selectFrom, execute, …); same in extra, L2 not required

🔒 Advanced Features

🛠️ Development Tools

📚 Examples

📚 Reference

🚀 Quick Navigation

New to Forge-SQL-ORM? Start here:

Looking for specific features?

Looking for practical examples?

Usage Approaches

1. Full Forge-SQL-ORM Usage

import ForgeSQL from "forge-sql-orm";
const forgeSQL = new ForgeSQL();

Best for: Advanced features like optimistic locking, automatic versioning, and automatic field name collision prevention in complex queries.

2. Direct Drizzle Usage

import { drizzle } from "drizzle-orm/mysql-proxy";
import { forgeDriver } from "forge-sql-orm";
const db = drizzle(forgeDriver);

Best for: Simple Modify operations without optimistic locking. Note that you need to manually patch drizzle patchDbWithSelectAliased for select fields to prevent field name collisions in Atlassian Forge SQL.

3. Local Cache Optimization

import ForgeSQL from "forge-sql-orm";
const forgeSQL = new ForgeSQL();

// Optimize repeated queries within a single invocation
await forgeSQL.executeWithLocalContext(async () => {
  // Multiple queries here will benefit from local caching
  const users = await forgeSQL
    .select({ id: users.id, name: users.name })
    .from(users)
    .where(eq(users.active, true));

  // This query will use local cache (no database call)
  const cachedUsers = await forgeSQL
    .select({ id: users.id, name: users.name })
    .from(users)
    .where(eq(users.active, true));

  // Using new methods for better performance
  const usersFrom = await forgeSQL.selectFrom(users).where(eq(users.active, true));

  // This will use local cache (no database call)
  const cachedUsersFrom = await forgeSQL.selectFrom(users).where(eq(users.active, true));

  // Raw SQL with local caching
  const rawUsers = await forgeSQL.execute("SELECT id, name FROM users WHERE active = ?", [true]);
});

Best for: Performance optimization of repeated queries within a single resolver invocation (Level 1). Available in forge-sql-orm; unchanged in 2.2.x (only Level 2 moved to extra).

Field Name Collision Prevention in Complex Queries

When working with complex queries involving multiple tables (joins, inner joins, etc.), Atlassian Forge SQL has a specific behavior where fields with the same name from different tables get collapsed into a single field with a null value. This is not a Drizzle ORM issue but rather a characteristic of Atlassian Forge SQL's behavior.

Forge-SQL-ORM provides two ways to handle this:

Using Forge-SQL-ORM

import ForgeSQL from "forge-sql-orm";

const forgeSQL = new ForgeSQL();

// Automatic field name collision prevention
await forgeSQL
  .select({ user: users, order: orders })
  .from(orders)
  .innerJoin(users, eq(orders.userId, users.id));

Using Direct Drizzle

import { drizzle } from "drizzle-orm/mysql-proxy";
import { forgeDriver, patchDbWithSelectAliased } from "forge-sql-orm";

const db = patchDbWithSelectAliased(drizzle(forgeDriver));

// Manual field name collision prevention
await db
  .selectAliased({ user: users, order: orders })
  .from(orders)
  .innerJoin(users, eq(orders.userId, users.id));

Important Notes

  • This is a specific behavior of Atlassian Forge SQL, not Drizzle ORM
  • For complex queries involving multiple tables, it's recommended to always specify select fields and avoid using select() without field selection
  • The solution automatically creates unique aliases for each field by prefixing them with the table name
  • This ensures that fields with the same name from different tables remain distinct in the query results

Installation

Forge-SQL-ORM is designed to work with @forge/sql and Drizzle ORM.

npm install forge-sql-orm @forge/sql drizzle-orm -S

For global cache (@forge/kvs) and Rovo, use forge-sql-orm-extra:

npm install forge-sql-orm-extra @forge/kvs -S

(You still need the core dependencies above.)

Installing from GitHub Packages (weekly latest)

Besides official releases on npmjs.com, the repository publishes a weekly snapshot of master to GitHub Packages every Sunday 02:00 UTC (workflow Weekly GitHub Packages (latest); also runnable manually from the Actions tab). These builds pass the same quality gate as CI (lint, Knip, tests, license check) before publish.

| Channel | Registry | dist-tag | When | | ---------------------------- | -------------------------------------------------------- | ------------ | --------------------------------- | | Production (recommended) | npmjs.com | npm latest | Manual semver release + CHANGELOG | | Bleeding-edge snapshot | GitHub Packages | GPR latest | Weekly from current master |

GPR package names are scoped: @forge-sql-orm/forge-sql-orm, @forge-sql-orm/forge-sql-orm-extra, @forge-sql-orm/forge-sql-orm-cli. Published versions look like 2.1.29-weekly.20260608 (immutable); the latest tag always points at the most recent weekly build.

1. Authenticate — create or edit .npmrc in your project (use a GitHub personal access token with read:packages, or GITHUB_TOKEN in CI):

@forge-sql-orm:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=YOUR_GITHUB_TOKEN

Keep the default registry for everything else (Forge apps still install @forge/sql and drizzle-orm from npmjs.com):

registry=https://registry.npmjs.org/

2. Install core (npm alias — your import stays forge-sql-orm):

npm install forge-sql-orm@npm:@forge-sql-orm/forge-sql-orm@latest @forge/sql drizzle-orm -S

3. Optional — extra and CLI from GPR:

npm install forge-sql-orm-extra@npm:@forge-sql-orm/forge-sql-orm-extra@latest @forge/kvs -S
npm install forge-sql-orm-cli@npm:@forge-sql-orm/forge-sql-orm-cli@latest -D

Pin a specific weekly version instead of @latest when you need reproducibility, for example @forge-sql-orm/[email protected].

Weekly GPR builds are not the supported production channel for most apps — prefer npm semver releases. Use GPR latest to try fixes on master before the next npm release, or for internal smoke tests.

forge-sql-orm-extra

forge-sql-orm-extra adds Level 2 (global KVS) cache and Rovo on top of core. Level 1 (local cache) remains in forge-sql-orm and works unchanged with either import.

  • Level 2@forge/kvs, selectCacheable*, *AndEvictCache, cache contexts, scheduler cleanup
  • Rovo — secure dynamic SQL for AI / natural-language analytics

Install: npm install forge-sql-orm-extra @forge/kvs -S. Import: import ForgeSQL from "forge-sql-orm-extra" and pass cacheEntityName / cacheTTL as in the extra README.

Quick Start

1. Basic Setup

import ForgeSQL from "forge-sql-orm";

// Initialize ForgeSQL
const forgeSQL = new ForgeSQL();

// Simple query
const users = await forgeSQL.select().from(users);

2. With global cache (forge-sql-orm-extra)

Install forge-sql-orm-extra and @forge/kvs (see extra README). Same API, different import:

import ForgeSQL from "forge-sql-orm-extra";

const forgeSQL = new ForgeSQL({
  cacheEntityName: "cache",
  cacheTTL: 300,
});

const users = await forgeSQL
  .selectCacheable({ id: users.id, name: users.name })
  .from(users)
  .where(eq(users.active, true));

3. Local Cache Optimization

// Optimize repeated queries within a single invocation
await forgeSQL.executeWithLocalContext(async () => {
  const users = await forgeSQL
    .select({ id: users.id, name: users.name })
    .from(users)
    .where(eq(users.active, true));

  // This query will use local cache (no database call)
  const cachedUsers = await forgeSQL
    .select({ id: users.id, name: users.name })
    .from(users)
    .where(eq(users.active, true));

  // Using new methods for better performance
  const usersFrom = await forgeSQL.selectFrom(users).where(eq(users.active, true));

  // Raw SQL with local caching
  const rawUsers = await forgeSQL.execute("SELECT id, name FROM users WHERE active = ?", [true]);
});

4. Resolver Performance Monitoring

// Resolver with performance monitoring
resolver.define("fetch", async (req: Request) => {
  try {
    return await forgeSQL.executeWithMetadata(
      async () => {
        // Resolver logic with multiple queries
        const users = await forgeSQL.selectFrom(demoUsers);
        const orders = await forgeSQL
          .selectFrom(demoOrders)
          .where(eq(demoOrders.userId, demoUsers.id));
        return { users, orders };
      },
      async (totalDbExecutionTime, totalResponseSize, printQueriesWithPlan) => {
        const threshold = 500; // ms baseline for this resolver

        if (totalDbExecutionTime > threshold * 1.5) {
          console.warn(
            `[Performance Warning fetch] Resolver exceeded DB time: ${totalDbExecutionTime} ms`,
          );
          await printQueriesWithPlan(); // Optionally log or capture diagnostics for further analysis
        } else if (totalDbExecutionTime > threshold) {
          console.debug(`[Performance Debug fetch] High DB time: ${totalDbExecutionTime} ms`);
        }
      },
      {
        // Optional: Configure query plan printing behavior
        mode: "TopSlowest", // Print top slowest queries (default)
        topQueries: 3, // Print top 3 slowest queries
      },
    );
  } catch (e) {
    const error = e?.cause?.debug?.sqlMessage ?? e?.cause;
    console.error(error, e);
    throw error;
  }
});

Query Plan Printing Options:

The printQueriesWithPlan function supports two modes:

  1. TopSlowest Mode (default): Prints execution plans for the slowest queries from the current resolver invocation

    • mode: Set to 'TopSlowest' (default)
    • topQueries: Number of top slowest queries to analyze (default: 1)
  2. SummaryTable Mode: Uses CLUSTER_STATEMENTS_SUMMARY for query analysis

    • mode: Set to 'SummaryTable'
    • summaryTableWindowTime: Time window in milliseconds (default: 15000ms)
    • Only works if queries are executed within the specified time window

5. Rovo (forge-sql-orm-extra)

Secure dynamic SQL for natural-language analytics: forge-sql-orm-extra (import ForgeSQL from "forge-sql-orm-extra", forgeSQL.rovo()).

6. Next Steps

Drizzle Usage with forge-sql-orm

If you prefer to use Drizzle ORM with the additional features of Forge-SQL-ORM (like optimistic locking and caching), you can use the enhanced API:

import ForgeSQL from "forge-sql-orm";
const forgeSQL = new ForgeSQL();

// Versioned operations (recommended)
await forgeSQL.modifyWithVersioning().insert(Users, [userData]);
await forgeSQL.modifyWithVersioning().updateById(updateData, Users);

// Basic Drizzle operations
await forgeSQL.insert(Users).values(userData);
await forgeSQL.update(Users).set(updateData).where(eq(Users.id, 1));

// Direct Drizzle access
const db = forgeSQL.getDrizzleQueryBuilder();
const users = await db.select().from(users);

// Using new methods for enhanced functionality
const usersFrom = await forgeSQL.selectFrom(users).where(eq(users.active, true));

const usersDistinct = await forgeSQL.selectDistinctFrom(users).where(eq(users.active, true));

// Raw SQL execution
const rawUsers = await forgeSQL.execute("SELECT * FROM users WHERE active = ?", [true]);

// Raw SQL with execution metadata and performance monitoring
const usersWithMetadata = await forgeSQL.executeWithMetadata(
  async () => {
    const users = await forgeSQL.selectFrom(usersTable);
    const orders = await forgeSQL
      .selectFrom(ordersTable)
      .where(eq(ordersTable.userId, usersTable.id));
    return { users, orders };
  },
  (totalDbExecutionTime, totalResponseSize, printQueriesWithPlan) => {
    const threshold = 500; // ms baseline for this resolver

    if (totalDbExecutionTime > threshold * 1.5) {
      console.warn(`[Performance Warning] Resolver exceeded DB time: ${totalDbExecutionTime} ms`);
      await printQueriesWithPlan(); // Analyze and print query execution plans
    } else if (totalDbExecutionTime > threshold) {
      console.debug(`[Performance Debug] High DB time: ${totalDbExecutionTime} ms`);
    }

    console.log(`DB response size: ${totalResponseSize} bytes`);
  },
  {
    // Optional: Configure query plan printing
    mode: "TopSlowest", // Print top slowest queries (default)
    topQueries: 2, // Print top 2 slowest queries
  },
);

// DDL operations for schema modifications
await forgeSQL.executeDDL(`
  CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) UNIQUE
  )
`);

// Execute regular SQL queries in DDL context for performance monitoring
await forgeSQL.executeDDLActions(async () => {
  // Execute regular SQL queries in DDL context for monitoring
  const slowQueries = await forgeSQL.execute(`
    SELECT * FROM INFORMATION_SCHEMA.STATEMENTS_SUMMARY 
    WHERE AVG_LATENCY > 1000000
  `);

  // Execute complex analysis queries in DDL context
  const performanceData = await forgeSQL.execute(`
    SELECT * FROM INFORMATION_SCHEMA.CLUSTER_STATEMENTS_SUMMARY_HISTORY
    WHERE SUMMARY_END_TIME > DATE_SUB(NOW(), INTERVAL 1 HOUR)
  `);

  return { slowQueries, performanceData };
});

// Common Table Expressions (CTEs)
const userStats = await forgeSQL
  .with(
    forgeSQL.selectFrom(users).where(eq(users.active, true)).as("activeUsers"),
    forgeSQL.selectFrom(orders).where(eq(orders.status, "completed")).as("completedOrders"),
  )
  .select({
    totalActiveUsers: sql`COUNT(au.id)`,
    totalCompletedOrders: sql`COUNT(co.id)`,
  })
  .from(sql`activeUsers au`)
  .leftJoin(sql`completedOrders co`, eq(sql`au.id`, sql`co.userId`));

// Global cache, cache eviction, and Rovo: see forge-sql-orm-extra/README.md

This approach gives you direct access to all Drizzle ORM features while still using the @forge/sql backend with optimistic locking and local caching. For KVS global cache and Rovo, use forge-sql-orm-extra.

Direct Drizzle Usage with Custom Driver

If you prefer to use Drizzle ORM directly without the additional features of Forge-SQL-ORM (like optimistic locking), you can use the custom driver:

import { drizzle } from "drizzle-orm/mysql-proxy";
import { forgeDriver, patchDbWithSelectAliased } from "forge-sql-orm";

// Initialize drizzle with the custom driver and patch it for aliased selects
const db = patchDbWithSelectAliased(drizzle(forgeDriver));

// Use drizzle directly
const users = await db.select().from(users);
const users = await db.selectAliased(getTableColumns(users)).from(users);
const users = await db.selectAliasedDistinct(getTableColumns(users)).from(users);
await db.insert(users)...;
await db.update(users)...;
await db.delete(users)...;
// Using new methods with direct drizzle
const usersFrom = await forgeSQL.selectFrom(users)
  .where(eq(users.active, true));

const usersDistinct = await forgeSQL.selectDistinctFrom(users)
  .where(eq(users.active, true));

// Raw SQL execution
const rawUsers = await forgeSQL.execute(
  "SELECT * FROM users WHERE active = ?",
  [true]
);

// Raw SQL with execution metadata and performance monitoring
const usersWithMetadata = await forgeSQL.executeWithMetadata(
  async () => {
    const users = await forgeSQL.selectFrom(usersTable);
    const orders = await forgeSQL.selectFrom(ordersTable).where(eq(ordersTable.userId, usersTable.id));
    return { users, orders };
  },
  (totalDbExecutionTime, totalResponseSize, printQueriesWithPlan) => {
    const threshold = 500; // ms baseline for this resolver

    if (totalDbExecutionTime > threshold * 1.5) {
      console.warn(`[Performance Warning] Resolver exceeded DB time: ${totalDbExecutionTime} ms`);
      await printQueriesWithPlan(); // Analyze and print query execution plans
    } else if (totalDbExecutionTime > threshold) {
      console.debug(`[Performance Debug] High DB time: ${totalDbExecutionTime} ms`);
    }

    console.log(`DB response size: ${totalResponseSize} bytes`);
  },
  {
    // Optional: Configure query plan printing
    mode: 'TopSlowest', // Print top slowest queries (default)
    topQueries: 1, // Print top slowest query
  },
);

Step-by-Step Migration Workflow

  1. Install CLI and setup scripts

    npm install forge-sql-orm-cli -D
    npm pkg set scripts.models:create="forge-sql-orm-cli generate:model --output src/entities --saveEnv"
    npm pkg set scripts.migration:create="forge-sql-orm-cli migrations:create --force --output src/migration --entitiesPath src/entities"
    npm pkg set scripts.migration:update="forge-sql-orm-cli migrations:update --entitiesPath src/entities --output src/migration"
    npm pkg set scripts.schema:create="forge-sql-orm-cli schema:create --entitiesPath src/entities"

    (This is done only once when setting up the project)

  2. Generate initial schema from an existing database

    npm run models:create

    (This will prompt for database credentials on first run and save them to .env file)

  3. Create the first migration

    npm run migration:create

    (This initializes the database migration structure, also done once)

  4. Deploy to Forge and verify that migrations work

    • Deploy your Forge app with migrations.
    • Run migrations using a Forge web trigger or Forge scheduler.
  5. Modify the database (e.g., add a new column, index, etc.)

    • Use DbSchema or manually alter the database schema.
  6. Update the migration

    npm run migration:update
    • ⚠️ Do NOT update schema before this step!
    • If schema is updated first, the migration will be empty!
  7. Deploy to Forge and verify that the migration runs without issues

    • Run the updated migration on Forge.
  8. Update the schema

    npm run models:create
  9. Repeat steps 5-8 as needed

⚠️ WARNING:

  • Do NOT swap steps 7 and 5! If you update schema before generating a migration, the migration will be empty!
  • Always generate the migration first, then update the schema.

Drop Migrations

The Drop Migrations feature allows you to completely reset your database schema in Atlassian Forge SQL. This is useful when you need to:

  • Start fresh with a new schema
  • Reset all tables and their data
  • Clear migration history
  • Ensure your local schema matches the deployed database

Important Requirements

Before using Drop Migrations, ensure that:

  1. Your local schema exactly matches the current database schema deployed in Atlassian Forge SQL
  2. You have a backup of your data if needed
  3. You understand that this operation will delete all tables and data

Usage

  1. First, ensure your local schema matches the deployed database:

    npm run models:create
  2. Generate the drop migration:

    npm run migration:drop

    (Add this script to your package.json: npm pkg set scripts.migration:drop="forge-sql-orm-cli migrations:drop --entitiesPath src/entities --output src/migration")

  3. Deploy and run the migration in your Forge app:

    import migrationRunner from "./database/migration";
    import { MigrationRunner } from "@forge/sql/out/migration";
    
    const runner = new MigrationRunner();
    await migrationRunner(runner);
    await runner.run();
  4. After dropping all tables, you can create a new migration to recreate the schema:

    npm run migration:create

    The --force parameter is already included in the script to allow creating migrations after dropping all tables.

Example Migration Output

The generated drop migration will look like this:

import { MigrationRunner } from "@forge/sql/out/migration";

export default (migrationRunner: MigrationRunner): MigrationRunner => {
    return migrationRunner
        .enqueue("v1_MIGRATION0", "ALTER TABLE `orders` DROP FOREIGN KEY `fk_orders_users`")
        .enqueue("v1_MIGRATION1", "DROP INDEX `idx_orders_user_id` ON `orders`")
        .enqueue("v1_MIGRATION2", "DROP TABLE IF EXISTS `orders`")
        .enqueue("v1_MIGRATION3", "DROP TABLE IF EXISTS `users`")
        .enqueue("MIGRATION_V1_1234567890", "DELETE FROM __migrations");
};

⚠️ Important Notes

  • This operation is irreversible - all data will be lost
  • Make sure your local schema is up-to-date with the deployed database
  • Consider backing up your data before running drop migrations
  • The migration will clear the __migrations table to allow for fresh migration history
  • Drop operations are performed in the correct order: first foreign keys, then indexes, then tables

Date and Time Types

When working with date and time fields in your models, you should use the custom types provided by Forge-SQL-ORM to ensure proper handling of date/time values. This is necessary because Forge SQL has specific format requirements for date/time values:

| Date type | Required Format | Example | | --------- | ------------------------------ | -------------------------- | | DATE | YYYY-MM-DD | 2024-09-19 | | TIME | HH:MM:SS[.fraction] | 06:40:34 | | TIMESTAMP | YYYY-MM-DD HH:MM:SS[.fraction] | 2024-09-19 06:40:34.999999 |

// ❌ Don't use standard Drizzle date/time types
export const testEntityTimeStampVersion = mysqlTable("test_entity", {
  id: int("id").primaryKey().autoincrement(),
  time_stamp: timestamp("times_tamp").notNull(),
  date_time: datetime("date_time").notNull(),
  time: time("time").notNull(),
  date: date("date").notNull(),
});

// ✅ Use Forge-SQL-ORM custom types instead
import {
  forgeDateTimeString,
  forgeDateString,
  forgeTimestampString,
  forgeTimeString,
} from "forge-sql-orm";

export const testEntityTimeStampVersion = mysqlTable("test_entity", {
  id: int("id").primaryKey().autoincrement(),
  time_stamp: forgeTimestampString("times_tamp").notNull(),
  date_time: forgeDateTimeString("date_time").notNull(),
  time: forgeTimeString("time").notNull(),
  date: forgeDateString("date").notNull(),
});

Why Custom Types?

The custom types in Forge-SQL-ORM handle the conversion between JavaScript Date objects and Forge SQL's required string formats automatically. Without these custom types, you would need to manually format dates like this:

// Without custom types, you'd need to do this manually:
const date = moment().format("YYYY-MM-DD");
const time = moment().format("HH:mm:ss.SSS");
const timestamp = moment().format("YYYY-MM-DDTHH:mm:ss.SSS");

Our custom types provide:

  • Automatic conversion between JavaScript Date objects and Forge SQL's required string formats
  • Consistent date/time handling across your application
  • Type safety for date/time fields
  • Proper handling of timezone conversions
  • Support for all Forge SQL date/time types (datetime, timestamp, date, time)

Available Custom Types

  • forgeDateTimeString - For datetime fields (YYYY-MM-DD HH:MM:SS[.fraction])
  • forgeTimestampString - For timestamp fields (YYYY-MM-DD HH:MM:SS[.fraction])
  • forgeDateString - For date fields (YYYY-MM-DD)
  • forgeTimeString - For time fields (HH:MM:SS[.fraction])

Each type ensures that the data is properly formatted according to Forge SQL's requirements while providing a clean, type-safe interface for your application code.


TiDB vector types (AI / similarity search)

Forge SQL ORM exposes TiDB-compatible VECTOR columns and vector functions so you can store embeddings and run similarity search in SQL—typical for AI features (semantic search, RAG-style retrieval) built on Forge SQL.

Schema: vectorTiDBType

Use the Drizzle custom column type from forge-sql-orm. With a fixed dimension, DDL becomes VECTOR(n); without it, VECTOR.

import { int, mysqlTable, primaryKey, text } from "drizzle-orm/mysql-core";
import { vectorTiDBType } from "forge-sql-orm";

export const documents = mysqlTable(
  "documents",
  {
    id: int().autoincrement().notNull(),
    body: text().notNull(),
    embedding: vectorTiDBType("embedding", { dimension: 1536 }).notNull(),
  },
  (table) => [primaryKey({ columns: [table.id], name: "id" })],
);

Values in application code are number[]; the driver maps them to the textual form TiDB expects.

Queries: distance helpers

Helpers build the same expressions as TiDB’s vector functions (e.g. VEC_COSINE_DISTANCE). Use them inside forgeSQL.select(), where(), orderBy(), etc.

import { asc, sql } from "drizzle-orm";
import { vecCosineDistance } from "forge-sql-orm";
import { documents } from "./schema";

const queryVector = [0.1, 0.2, 0.3];

const distanceAlias = sql.raw("distance");
const distance = sql<number>`${vecCosineDistance(documents.embedding, queryVector)} AS \`${distanceAlias}\``;

const nearest = await forgeSQL
  .select({
    id: documents.id,
    body: documents.body,
    distance,
  })
  .from(documents)
  .orderBy(asc(distanceAlias))
  .limit(10);

Also available (see src/core/VectorTiDB.ts): vecFromText, vecAsText, vecDims, vecL2Norm, vecL2Distance, vecL1Distance, vecNegativeInnerProduct.

Example app

See examples/forge-sql-orm-example-vector for a full Forge app (migrations, resolvers, UI) aligned with Get Started with Vector Search via SQL.

For semantic search with learned embeddings, use examples/forge-sql-orm-example-ai (embeddings in Custom UI) or examples/forge-sql-orm-example-backend-ai (embeddings in Forge resolvers via ai-lib).

Custom types for binary and UUID data

Forge SQL ORM provides custom types from src/core/customTypes.ts for compact binary storage and UUID primary keys.

| Type | SQL type | Use case | | ----------------- | --------------- | --------------------------------------------------------------------------------------------------------- | | uuidBinary | VARBINARY(16) | Store UUID primary keys in compact binary form; writes use UUID_TO_BIN(...), reads return UUID strings. | | forgeVarBinary | VARBINARY(n) | Variable-length binary payloads (e.g., small encrypted payloads or protocol bytes). | | forgeBinary | BINARY(n) | Fixed-length binary values (e.g., hashes, signatures, fixed-size binary tokens). | | forgeBLOB | BLOB | General-purpose binary files/content. | | forgeTinyBLOB | TINYBLOB | Small binary payloads. | | forgeMediumBLOB | MEDIUMBLOB | Medium-size binary payloads. |

Binary custom types encode data to Base64 in JS and write through FROM_BASE64(...), which keeps SQL safe and works well with Forge SQL payload constraints.

Example (with BLOB)

import { int, mysqlTable, text } from "drizzle-orm/mysql-core";
import { forgeBLOB, uuidBinary } from "forge-sql-orm";

export const files = mysqlTable("files", {
  id: uuidBinary("id").primaryKey().notNull(),
  name: text("name").notNull(),
  content: forgeBLOB("content").notNull(),
});

await forgeSQL.insert(files).values({
  id: "00112233-4455-6677-8899-aabbccddeeff",
  name: "avatar.png",
  content: Buffer.from([137, 80, 78, 71]), // PNG signature bytes (example)
});

TiDB SQL function helpers

forge-sql-orm also includes ready-to-use TiDB/MySQL SQL helper modules in src/core/functions. They return Drizzle sql fragments, so you can compose them inside select, where, orderBy, groupBy, computed columns, and other query builders.

| Module | What it does | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | VectorTiDB | Vector search helpers such as cosine distance, L1/L2 distance, dimensions, and vector text conversion. | | StringTiDB | String manipulation helpers such as concatenation, substring, replace, trim, case conversion, and pattern-oriented string operations. | | NumericTiDB | Arithmetic and numeric helpers such as addition/subtraction operators, rounding, powers, logarithms, trigonometry, and random values. | | DateTiDB | Date/time helpers such as DATE_ADD, DATE_SUB, formatting, extraction, timestamp conversion, and calendar calculations. | | BitTiDB | Bitwise operators and bit functions such as AND/OR/XOR, shifts, negation, and bit counting. | | CastTiDB | SQL casting helpers for CAST, CONVERT, binary conversion, and reusable cast target builders. | | EncryptTiDB | Encryption, hashing, compression, and password-strength helpers such as AES, SHA, MD5, and compression functions. | | InformationTiDB | Metadata helpers such as current database/user, connection id, version, row count, and TiDB environment info. | | JsonTiDB | JSON creation, extraction, search, mutation, validation, schema checking, and storage inspection helpers. | | AggregateTiDB | Extra aggregate helpers not already covered by Drizzle, such as percentile/approximation and specialized aggregate expressions. | | WindowTiDB | Window function call helpers such as rowNumber, rank, denseRank, lag, lead, and firstValue for use with OVER (...). | | SequenceTiDB | Sequence helpers such as NEXTVAL, LASTVAL, and SETVAL for working with TiDB sequences. | | UtilityTiDB | Small utility helpers such as byte and nanosecond formatting functions. | | MiscellaneousTiDB | Miscellaneous helpers such as UUID/IP utilities, sleep, default, and compatibility helpers. | | TiDBSpecificTiDB | TiDB-specific helpers such as TSO parsing, resource-group helpers, SQL digest helpers, MVCC inspection, and key encoding helpers. |

Example

import { sql } from "drizzle-orm";
import { concat } from "forge-sql-orm";
import { users } from "./schema";

const rows = await forgeSQL
  .select({
    label: sql<string>`${concat(users.firstName, sql`' '`, users.lastName)}`,
  })
  .from(users);

In this example, concat(...) builds a safe SQL fragment that Drizzle can embed into the final query.

Connection to ORM

import ForgeSQL from "forge-sql-orm";

const forgeSQL = new ForgeSQL();

or

import { drizzle } from "drizzle-orm/mysql-proxy";
import { forgeDriver } from "forge-sql-orm";

// Initialize drizzle with the custom driver
const db = drizzle(forgeDriver);

// Use drizzle directly
const users = await db.select().from(users);

Fetch Data

Basic Fetch Operations

// Using forgeSQL.select()
const user = await forgeSQL.select({ user: users }).from(users);

// Using forgeSQL.selectDistinct()
const user = await forgeSQL.selectDistinct({ user: users }).from(users);

// Using forgeSQL.selectFrom() - Select all columns with field aliasing
const user = await forgeSQL.selectFrom(users).where(eq(users.id, 1));

// Using forgeSQL.selectDistinctFrom() - Select distinct all columns with field aliasing
const user = await forgeSQL.selectDistinctFrom(users).where(eq(users.id, 1));

// Using forgeSQL.execute() - Execute raw SQL with local caching
const user = await forgeSQL.execute("SELECT * FROM users WHERE id = ?", [1]);

// Using forgeSQL.getDrizzleQueryBuilder()
const user = await forgeSQL.getDrizzleQueryBuilder().select().from(Users).where(eq(Users.id, 1));

// OR using direct drizzle with custom driver
const db = drizzle(forgeDriver);
const user = await db.select().from(Users).where(eq(Users.id, 1));
// Returns: { id: 1, name: "John Doe" }

// Using executeQueryOnlyOne for single result with error handling
const user = await forgeSQL
  .fetch()
  .executeQueryOnlyOne(
    forgeSQL.getDrizzleQueryBuilder().select().from(Users).where(eq(Users.id, 1)),
  );
// Returns: { id: 1, name: "John Doe" }
// Throws error if multiple records found
// Returns undefined if no records found

// Using with aliases
// With forgeSQL
const usersAlias = alias(Users, "u");
const result = await forgeSQL
  .getDrizzleQueryBuilder()
  .select({
    userId: sql < string > `${usersAlias.id} as \`userId\``,
    userName: sql < string > `${usersAlias.name} as \`userName\``,
  })
  .from(usersAlias);

// OR with direct drizzle
const db = drizzle(forgeDriver);
const result = await db
  .select({
    userId: sql < string > `${usersAlias.id} as \`userId\``,
    userName: sql < string > `${usersAlias.name} as \`userName\``,
  })
  .from(usersAlias);
// Returns: { userId: 1, userName: "John Doe" }

Complex Queries

// Using joins with automatic field name collision prevention
// With forgeSQL
const orderWithUser = await forgeSQL
  .select({ user: users, order: orders })
  .from(orders)
  .innerJoin(users, eq(orders.userId, users.id));

// Using new selectFrom methods with joins
const orderWithUser = await forgeSQL
  .selectFrom(orders)
  .innerJoin(users, eq(orders.userId, users.id))
  .where(eq(orders.id, 1));

// Using with() for Common Table Expressions (CTEs)
const userStats = await forgeSQL
  .with(
    forgeSQL.selectFrom(users).where(eq(users.active, true)).as("activeUsers"),
    forgeSQL.selectFrom(orders).where(eq(orders.status, "completed")).as("completedOrders"),
  )
  .select({
    totalActiveUsers: sql`COUNT(au.id)`,
    totalCompletedOrders: sql`COUNT(co.id)`,
  })
  .from(sql`activeUsers au`)
  .leftJoin(sql`completedOrders co`, eq(sql`au.id`, sql`co.userId`));

// OR with direct drizzle
const db = patchDbWithSelectAliased(drizzle(forgeDriver));
const orderWithUser = await db
  .selectAliased({ user: users, order: orders })
  .from(orders)
  .innerJoin(users, eq(orders.userId, users.id));
// Returns: {
//   user_id: 1,
//   user_name: "John Doe",
//   order_id: 1,
//   order_product: "Product 1"
// }

// Using distinct with aliases
const uniqueUsers = await db.selectAliasedDistinct({ user: users }).from(users);
// Returns unique users with aliased fields

// Using executeQueryOnlyOne for unique results
const userStats = await forgeSQL.fetch().executeQueryOnlyOne(
  forgeSQL
    .getDrizzleQueryBuilder()
    .select({
      totalUsers: sql`COUNT(*) as \`totalUsers\``,
      uniqueNames: sql`COUNT(DISTINCT name) as \`uniqueNames\``,
    })
    .from(Users),
);
// Returns: { totalUsers: 100, uniqueNames: 80 }
// Throws error if multiple records found

Raw SQL Queries

// Using executeRawSQL for direct SQL queries
const users = await forgeSQL
  .fetch()
  .executeRawSQL<Users>("SELECT * FROM users");

// Using execute() for raw SQL with local caching
const users = await forgeSQL
  .execute("SELECT * FROM users WHERE active = ?", [true]);

// Using executeWithMetadata() for capturing execution metrics and performance monitoring
const usersWithMetadata = await forgeSQL.executeWithMetadata(
  async () => {
    const users = await forgeSQL.selectFrom(usersTable);
    const orders = await forgeSQL.selectFrom(ordersTable).where(eq(ordersTable.userId, usersTable.id));
    return { users, orders };
  },
  (totalDbExecutionTime, totalResponseSize, printQueriesWithPlan) => {
    const threshold = 500; // ms baseline for this resolver

    if (totalDbExecutionTime > threshold * 1.5) {
      console.warn(`[Performance Warning] Resolver exceeded DB time: ${totalDbExecutionTime} ms`);
      await printQueriesWithPlan(); // Analyze and print query execution plans
    } else if (totalDbExecutionTime > threshold) {
      console.debug(`[Performance Debug] High DB time: ${totalDbExecutionTime} ms`);
    }

    console.log(`DB response size: ${totalResponseSize} bytes`);
  },
  {
    // Optional: Configure query plan printing
    mode: 'TopSlowest', // Print top slowest queries (default)
    topQueries: 1, // Print top slowest query
  },
);

// Using executeDDL() for DDL operations (CREATE, ALTER, DROP, etc.)
await forgeSQL.executeDDL(`
  CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) UNIQUE
  )
`);

await forgeSQL.executeDDL(sql`
  ALTER TABLE users
  ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
`);

await forgeSQL.executeDDL("DROP TABLE IF EXISTS old_users");

// Using executeDDLActions() for executing regular SQL queries in DDL context
// This method executes a series of actions within a DDL operation context for monitoring
await forgeSQL.executeDDLActions(async () => {
  // Execute regular SQL queries in DDL context for performance monitoring
  const slowQueries = await forgeSQL.execute(`
    SELECT * FROM INFORMATION_SCHEMA.STATEMENTS_SUMMARY
    WHERE AVG_LATENCY > 1000000
  `);

  // Execute complex analysis queries in DDL context
  const performanceData = await forgeSQL.execute(`
    SELECT * FROM INFORMATION_SCHEMA.CLUSTER_STATEMENTS_SUMMARY_HISTORY
    WHERE SUMMARY_END_TIME > DATE_SUB(NOW(), INTERVAL 1 HOUR)
  `);

  return { slowQueries, performanceData };
});

// Using execute() with complex queries
const userStats = await forgeSQL
  .execute(`
    SELECT
      u.id,
      u.name,
      COUNT(o.id) as order_count,
      SUM(o.amount) as total_amount
    FROM users u
    LEFT JOIN orders o ON u.id = o.user_id
    WHERE u.active = ?
    GROUP BY u.id, u.name
  `, [true]);

Modify Operations

Forge-SQL-ORM provides multiple approaches for Modify operations, each with different characteristics:

1. Basic Drizzle Operations

await forgeSQL.insert(Users).values({ id: 1, name: "Smith" });
await forgeSQL.update(Users).set({ name: "Smith Updated" }).where(eq(Users.id, 1));
await forgeSQL.delete(Users).where(eq(Users.id, 1));

Cache-aware variants (insertAndEvictCache, modifyWithVersioningAndEvictCache, executeWithCacheContext, …) are in forge-sql-orm-extra.

2. Versioned Operations (recommended)

// Insert with versioning only (no cache management)
const userId = await forgeSQL.modifyWithVersioning().insert(Users, [{ id: 1, name: "Smith" }]);

// Update with versioning only
await forgeSQL.modifyWithVersioning().updateById({ id: 1, name: "Smith Updated" }, Users);

// Delete with versioning only
await forgeSQL.modifyWithVersioning().deleteById(1, Users);

5. Legacy Modify Operations (Removed in 2.1.x)

⚠️ BREAKING CHANGE: The crud() and modify() methods have been completely removed in version 2.1.x.

// ❌ These methods no longer exist in 2.1.x
// const userId = await forgeSQL.crud().insert(Users, [{ id: 1, name: "Smith" }]);
// await forgeSQL.crud().updateById({ id: 1, name: "Smith Updated" }, Users);
// await forgeSQL.crud().deleteById(1, Users);

// ✅ Use the new methods instead
const userId = await forgeSQL.modifyWithVersioning().insert(Users, [{ id: 1, name: "Smith" }]);
await forgeSQL.modifyWithVersioning().updateById({ id: 1, name: "Smith Updated" }, Users);
await forgeSQL.modifyWithVersioning().deleteById(1, Users);

Advanced Operations

// Insert with sequence (nextVal)
import { nextVal } from "forge-sql-orm";

const user = {
  id: nextVal("user_id_seq"),
  name: "user test",
  organization_id: 1,
};
const id = await forgeSQL.modifyWithVersioning().insert(appUser, [user]);

// Update with custom WHERE condition
await forgeSQL
  .modifyWithVersioning()
  .updateFields({ name: "New Name", age: 35 }, Users, eq(Users.email, "[email protected]"));

// Insert with duplicate handling
await forgeSQL.modifyWithVersioning().insert(
  Users,
  [
    { id: 4, name: "Smith" },
    { id: 4, name: "Vasyl" },
  ],
  true,
);

SQL Utilities

formatLimitOffset

The formatLimitOffset utility function is used to safely insert numeric values directly into SQL queries for LIMIT and OFFSET clauses. This is necessary because Atlassian Forge SQL doesn't support parameterized queries for these clauses.

import { formatLimitOffset } from "forge-sql-orm";

// Example usage in a query
const result = await forgeSQL
  .select()
  .from(orderItem)
  .orderBy(asc(orderItem.createdAt))
  .limit(formatLimitOffset(10))
  .offset(formatLimitOffset(350000));

// The generated SQL will be:
// SELECT * FROM order_item
// ORDER BY created_at ASC
// LIMIT 10
// OFFSET 350000

Important Notes:

  • The function performs type checking to prevent SQL injection
  • It throws an error if the input is not a valid number
  • Use this function instead of direct parameter binding for LIMIT and OFFSET clauses
  • The function is specifically designed to work with Atlassian Forge SQL's limitations

Security Considerations:

  • The function includes validation to ensure the input is a valid number
  • This prevents SQL injection by ensuring only numeric values are inserted
  • Always use this function instead of string concatenation for LIMIT and OFFSET values

Optimistic Locking

↑ Back to Top

Optimistic locking is a concurrency control mechanism that prevents data conflicts when multiple transactions attempt to update the same record concurrently. Instead of using locks, this technique relies on a version field in your entity models.

Supported Version Field Types

  • datetime - Timestamp-based versioning
  • timestamp - Timestamp-based versioning
  • integer - Numeric version increment
  • decimal - Numeric version increment

Configuration

const options = {
  additionalMetadata: {
    users: {
      tableName: "users",
      versionField: {
        fieldName: "updatedAt",
      },
    },
  },
};

const forgeSQL = new ForgeSQL(options);

Example Usage

// The version field will be automatically handled
await forgeSQL.modifyWithVersioning().updateById(
  {
    id: 1,
    name: "Updated Name",
    updatedAt: new Date(), // Will be automatically set if not provided
  },
  Users,
);

With global cache, use modifyWithVersioningAndEvictCache() from forge-sql-orm-extra.

ForgeSqlOrmOptions

The ForgeSqlOrmOptions object allows customization of ORM behavior (core). Global cache options (cacheEntityName, cacheTTL, …) are documented in forge-sql-orm-extra.

| Option | Type | Description | | -------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | logRawSqlQuery | boolean | Enables logging of raw SQL queries in the Atlassian Forge Developer Console. Useful for debugging and monitoring. Defaults to false. | | disableOptimisticLocking | boolean | Disables optimistic locking. When set to true, no additional condition (e.g., a version check) is added during record updates, which can improve performance. However, this may lead to conflicts when multiple transactions attempt to update the same record concurrently. | | additionalMetadata | object | Allows adding custom metadata to all entities. This is useful for tracking common fields across all tables (e.g., createdAt, updatedAt, createdBy, etc.). The metadata will be automatically added to all generated entities. |

CLI Commands

Forge-SQL-ORM provides a command-line interface for managing database migrations and model generation.

📖 Full CLI Documentation - Complete CLI reference with all commands and options.

Quick CLI Reference

The CLI tool provides the following main commands:

  • generate:model - Generate Drizzle ORM models from your database schema
  • migrations:create - Create new migration files
  • migrations:update - Update existing migrations with schema changes
  • migrations:drop - Create migration to drop tables
  • schema:create - Apply schema directly from Drizzle models to database

Installation

The CLI tool must be installed as a local dependency and used via npm scripts in your package.json:

npm install forge-sql-orm-cli -D

Setup npm Scripts

Add the following scripts to your package.json:

npm pkg set scripts.models:create="forge-sql-orm-cli generate:model --output src/entities --saveEnv"
npm pkg set scripts.migration:create="forge-sql-orm-cli migrations:create --force --output src/migration --entitiesPath src/entities"
npm pkg set scripts.migration:update="forge-sql-orm-cli migrations:update --entitiesPath src/entities --output src/migration"
npm pkg set scripts.schema:create="forge-sql-orm-cli schema:create --entitiesPath src/entities"

Basic Usage

After setting up the scripts, use them via npm:

# Generate models from database
npm run models:create

# Create migration
npm run migration:create

# Update migration
npm run migration:update

# Apply schema directly from Drizzle models
npm run schema:create

Note: The CLI tool is designed to work as a local dependency through npm scripts. Configuration is saved to .env file using the --saveEnv flag, so you only need to provide database credentials once.

For detailed information about all available options and advanced usage, see the Full CLI Documentation.

Web Triggers for Migrations

Forge-SQL-ORM provides web triggers for managing database migrations in Atlassian Forge:

1. Apply Migrations Trigger

This trigger allows you to apply database migrations through a web endpoint. It's useful for:

  • Manually triggering migrations
  • Running migrations as part of your deployment process
  • Testing migrations in different environments
// Example usage in your Forge app
import { applySchemaMigrations } from "forge-sql-orm";
import migration from "./migration";

export const handlerMigration = async () => {
  return applySchemaMigrations(migration);
};

Configure in manifest.yml:

webtrigger:
  - key: invoke-schema-migration
    function: runSchemaMigration
    security:
      egress:
        allowDataEgress: false
        allowedResponses:
          - statusCode: 200
            body: '{"body": "Migrations successfully executed"}'
sql:
  - key: main
    engine: mysql
function:
  - key: runSchemaMigration
    handler: index.handlerMigration

2. Drop Migrations Trigger

⚠️ WARNING: This trigger will permanently delete all data in the specified tables and clear the migrations history. This operation cannot be undone!

This trigger allows you to completely reset your database schema. It's useful for:

  • Development environments where you need to start fresh
  • Testing scenarios requiring a clean database
  • Resetting the database before applying new migrations

Important: The trigger will drop all tables including migration.

// Example usage in your Forge app
import { dropSchemaMigrations } from "forge-sql-orm";

export const dropMigrations = () => {
  return dropSchemaMigrations();
};

Configure in manifest.yml:

webtrigger:
  - key: drop-schema-migration
    function: dropMigrations
sql:
  - key: main
    engine: mysql
function:
  - key: dropMigrations
    handler: index.dropMigrations

3. Fetch Schema Trigger

⚠️ DEVELOPMENT ONLY: This trigger is designed for development environments only and should not be used in production.

This trigger retrieves the current database schema from Atlassian Forge SQL and generates SQL statements that can be used to recreate the database structure. It's useful for:

  • Development environment setup
  • Schema documentation
  • Database structure verification
  • Creati