prorm API Reference
    Preparing search index...

    Class Prorm

    Main Prorm class with error handling and logging

    Hierarchy

    • EventEmitter
      • Prorm
    Index
    literal getPool getPoolStats getLogger setLoggingLevel connect close addHook authenticate getDialect getDialectInstance getQueryInterface createPartitionedTable createPartition attachPartition detachPartition dropPartition disableForeignKeyChecks enableForeignKeyChecks setIsolationLevel getDisableForeignKeyChecksSQL getEnableForeignKeyChecksSQL getSetIsolationLevelSQL disableUniqueKeyChecks enableUniqueKeyChecks getSQLConstants getDatabase getHost getPort getUsername getModels model getModel hasModel getTableName tableExists createMaterializedView refreshMaterializedView dropMaterializedView hasMaterializedView showMaterializedViews define addModel query createSavepoint releaseSavepoint rollbackToSavepoint queryWithMetadata transaction getTransaction setTransaction beforeDefine afterDefine beforeSync afterSync beforeConnect afterConnect beforeDisconnect afterDisconnect beforeDestroy afterDestroy beforeUpsert afterUpsert beforeReload showTables showAllSchemas createExtension dropExtension getExtensions hasExtension extensionExists createUser alterUser dropUser getUsers userExists grant revoke grantRole revokeRole createRole dropRole flushPrivileges showGrants getRoles createServer dropServer getServers createUserMapping dropUserMapping createForeignTable importForeignSchema defineForeignTable getDatabaseVersion getDatabaseName createSchema dropSchema showSchemas getTableNameWithSchema createTrigger dropTrigger createAlgorithm dropAlgorithm addColumn removeColumn changeColumn renameTable addIndex removeIndex describeTable createDatabase dropDatabase sync registerStore registerProcedures getMigrator migrate migrateUndo migrateStatus fn col cast where and or json where and or json validate
    • Create a new Prorm instance

      Parameters

      Returns Prorm

      // Basic usage with console logging
      const prorm = new Prorm({
      dialect: 'sqlite',
      storage: ':memory:',
      logging: console.log
      });
      // Custom logging function that receives SQL and timing
      const prorm = new Prorm({
      dialect: 'sqlite',
      storage: ':memory:',
      logging: (sql, timing) => {
      console.log(`Query took ${timing}ms: ${sql}`);
      }
      });
      // Enable benchmark mode for query timing
      const prorm = new Prorm({
      dialect: 'sqlite',
      storage: ':memory:',
      logging: console.log
      });

      // Now all queries will log execution time
      await User.findAll({ benchmark: true });
      // Listen to query events
      prorm.on('query', (event) => {
      console.log('Query executed:', event.sql, 'Duration:', event.duration, 'ms');
      });

      // Listen to slow query events
      prorm.on('slowQuery', (event) => {
      console.warn('Slow query detected:', event.sql, 'Duration:', event.duration, 'ms', 'Threshold:', event.threshold);
      });
    connectionManager: ConnectionRegistry | null = null

    The registry this instance was created by, if any.

    ConnectionManager.addConnection() sets this on the instance it builds, which is what makes FindOptions.using work: a query can name a sibling connection and be routed to that connection's copy of the model. Nothing else assigned it before, so using threw "Available: none" on every call. Typed structurally (rather than as ConnectionManager) to keep prorm.ts free of an import cycle with connection-manager.ts.

    associations: Map<string, any> = ...
    externalStores: ExternalStoreRegistry = ...

    Object/key-value stores backing

    properties. Public so the instance accessors built in _wrapInstance can resolve them.

    pool: DatabaseConnectionPool | null = null

    The connection pool instance

    // Get pool statistics
    console.log('Pool size:', prorm.pool.size);
    console.log('Available:', prorm.pool.available);
    console.log('Used:', prorm.pool.used);
    console.log('Pending:', prorm.pool.pending);

    // Listen to pool events
    prorm.pool.on('acquire', (connection) => {
    console.log('Connection acquired:', connection?.id);
    });
    prorm.pool.on('release', (connection) => {
    console.log('Connection released:', connection?.id);
    });
    prorm.pool.on('error', (err) => {
    console.error('Pool error:', err);
    });

    // Manually acquire a connection
    const conn = await prorm.pool.acquire();

    // Release a connection
    prorm.pool.release(conn);

    // Destroy a connection
    await prorm.pool.destroy(conn);
    • get models(): Record<string, ModelStatic<AnyModel>>

      Get all models as an object for backward compatibility Allows accessing models via prorm.models.ModelName

      Returns Record<string, ModelStatic<AnyModel>>

    • get modelManager(): {
          models: Record<string, ModelStatic<AnyModel>>;
          all: ModelStatic<any>[];
          getModel(name: string): ModelStatic<any> | undefined;
          addModel(name: string, model: ModelStatic<any>): void;
          removeModel(name: string): boolean;
      }

      Sequelize-style model manager, exposing the registered models along with a few convenience accessors on top of the internal model map.

      Returns {
          models: Record<string, ModelStatic<AnyModel>>;
          all: ModelStatic<any>[];
          getModel(name: string): ModelStatic<any> | undefined;
          addModel(name: string, model: ModelStatic<any>): void;
          removeModel(name: string): boolean;
      }

    • get isConnected(): boolean

      Check if connected

      Returns boolean

    • get allModels(): Record<string, ModelStatic<AnyModel>>

      Get all models as an object (for backward compatibility)

      Returns Record<string, ModelStatic<AnyModel>>

    • Lazily-created ForeignDataManager instance for this Prorm connection. Provides the full FDW management surface (servers, user mappings, foreign tables).

      Returns ForeignDataManager

      await prorm.fdw.createServer('remote_pg', { fdw: 'postgres_fdw', options: { host: 'db2.example.com', dbname: 'sales', port: '5432' } });
      
    • get users(): UserManager

      Lazily-created UserManager instance for this Prorm connection. Provides the full user / role / privilege management surface.

      Returns UserManager

      await prorm.users.createUser('app', { host: '%', password: 'secret' });
      
    • get UUIDV4(): Literal

      UUIDV4 default value for generating UUIDs Use as defaultValue in model definitions

      Returns Literal

      A Literal that generates a UUID v4

      const User = prorm.define('User', {
      id: { type: DataTypes.UUID, defaultValue: Prorm.UUIDV4, primaryKey: true },
      uuid: { type: DataTypes.UUID, defaultValue: prorm.UUIDV4 }
      });
    • Create a literal/raw SQL expression Use this to insert raw SQL into queries without parameter escaping

      Parameters

      • sql: string

        The raw SQL expression

      Returns Literal

      A Literal instance that can be used in queries

      // Use in default values
      const User = prorm.define('User', {
      createdAt: { type: DATE, defaultValue: prorm.literal('NOW()') },
      updatedAt: { type: DATE, defaultValue: prorm.literal("strftime('%Y-%m-%d %H:%M:%S', 'now')") }
      });
      // Use in updates (increment counter)
      await User.update(
      { count: prorm.literal('count + 1') },
      { where: { id: 1 } }
      );
      // Use in complex calculations in select
      const users = await User.findAll({
      attributes: [
      'id',
      'name',
      [prorm.literal('price * quantity'), 'total']
      ]
      });
      // Use in subqueries
      const posts = await Post.findAll({
      where: {
      userId: prorm.literal('(SELECT id FROM users WHERE active = 1 LIMIT 1)')
      }
      });
    • Get pool statistics

      Returns { size: number; available: number; inUse: number; pending: number } | null

      Pool statistics or null if pool not configured

    • Set logging level

      Parameters

      • level: "debug" | "info" | "warn" | "error"

      Returns void

    • Connect to the database and authenticate

      Returns Promise<void>

    • Disconnect from the database and close the connection pool

      Returns Promise<void>

    • Add a hook to the Prorm instance

      Parameters

      • hookName: string

        The name of the hook (e.g., 'beforeDefine', 'afterSync', 'beforeConnect')

      • handler: HookCallback

        The hook handler function

      Returns this

      The Prorm instance for chaining

      prorm.addHook('beforeDefine', ({ modelName, attributes }) => {
      console.log('Defining model:', modelName);
      });
      prorm.addHook('beforeConnect', async () => {
      console.log('About to connect to database');
      });
    • Authenticate the connection by running a test query

      Returns Promise<void>

      Promise that resolves if connection is successful

      Error if connection fails

      await prorm.authenticate();
      console.log('Connection OK');
    • Get the dialect name

      Returns string

      The dialect name (e.g., 'sqlite', 'postgres', 'mysql')

    • Get the dialect instance

      Returns Dialect | null

      The dialect instance or null if not initialized

    • Get the query interface for DDL operations

      Returns any

    • Create a partitioned table (PostgreSQL 10+)

      Parameters

      • tableName: string

        Name of the table to create

      • columns: Record<string, ColumnDefinition>

        Column definitions

      • Optionaloptions: TableOptions & {
            partitionBy: {
                type: "range" | "list" | "hash";
                column: string | string[];
            };
            partitions?: {
                name: string;
                bound?: {
                    from: string
                    | number
                    | Date;
                    to?: string | number | Date;
                    values?: ((...) | (...))[];
                    modulus?: number;
                    remainder?: number;
                };
                tablespace?: string;
                storageParameters?: Record<string, string | number>;
            }[];
        }

        Table options including partition configuration

      Returns Promise<void>

    • Create a partition for an existing partitioned table (PostgreSQL 10+)

      Parameters

      • options: {
            parentTable: string;
            name: string;
            bound?: {
                from: string | number | Date;
                to?: string | number | Date;
                values?: (string | number)[];
                modulus?: number;
                remainder?: number;
            };
            tablespace?: string;
            storageParameters?: Record<string, string | number>;
        }

        Partition creation options

      Returns Promise<void>

    • Attach a partition to a partitioned table (PostgreSQL 11+)

      Parameters

      • options: { parentTable: string; partitionName: string }

        Partition attachment options

      Returns Promise<void>

    • Detach a partition from a partitioned table (PostgreSQL 11+)

      Parameters

      • options: { partitionName: string; validate?: boolean }

        Partition detachment options

      Returns Promise<void>

    • Drop a partition (PostgreSQL 10+)

      Parameters

      • partitionName: string

        Name of the partition to drop

      • Optionaloptions: { ifExists?: boolean; cascade?: boolean }

        Drop options

      Returns Promise<void>

    • Disable foreign key checks for the current session

      On PostgreSQL this issues SET session_replication_role = 'replica', which needs superuser or a role granted SET ON PARAMETER session_replication_role (PostgreSQL 15+).

      Returns Promise<void>

      Promise that resolves when foreign key checks are disabled

      on dialects with no session-level switch (SQL Server, Oracle and Db2 are per-table; Redshift, Snowflake and ClickHouse never enforce foreign keys).

    • Enable foreign key checks for the current session

      The inverse of disableForeignKeyChecks, with the same dialect support and the same PostgreSQL privilege requirement.

      Returns Promise<void>

      Promise that resolves when foreign key checks are enabled

      on dialects with no session-level switch

    • Set the transaction isolation level

      Parameters

      • level: "SERIALIZABLE" | "READ_UNCOMMITTED" | "READ_COMMITTED" | "REPEATABLE_READ"

        The isolation level to set

      Returns Promise<void>

      Promise that resolves when the isolation level is set

    • Get SQL for disabling foreign key checks for the current dialect

      Routing lives in sql-constants.getForeignKeyChecksSQL so that the three mutually incompatible statements (SQLite's PRAGMA, MySQL's session variable, PostgreSQL's session_replication_role) are chosen from one table. This used to fall through to MySQL syntax for every dialect it did not name - PostgreSQL included - so disableForeignKeyChecks() threw a syntax error at the server on most of the supported databases.

      Returns string

      SQL string for disabling foreign key checks

      when the dialect has no session-level equivalent

    • Get SQL for enabling foreign key checks for the current dialect

      Returns string

      SQL string for enabling foreign key checks

      when the dialect has no session-level equivalent

    • Get SQL for setting transaction isolation level for the current dialect

      Parameters

      • level: "SERIALIZABLE" | "READ_UNCOMMITTED" | "READ_COMMITTED" | "REPEATABLE_READ"

        The isolation level

      Returns string

      SQL string for setting the isolation level

    • Disable unique key checks for the current session (MySQL/MariaDB only)

      The no-op on other dialects is deliberate, and is not the same situation as the foreign key switch above. SET UNIQUE_CHECKS is a MySQL/MariaDB optimisation hint: it defers uniqueness verification on InnoDB secondary indexes during bulk loads. No other supported database has a session setting that suspends unique constraint checking - PostgreSQL's session_replication_role = 'replica' suppresses triggers and foreign keys but still enforces unique indexes - so there is nothing to translate it to. Skipping the statement leaves the database in exactly the state the caller already had (uniqueness enforced), which is safe; throwing would break the common disableUniqueKeyChecks(); bulkCreate(); enable...() bulk-load pattern on every non-MySQL dialect for no benefit.

      Returns Promise<void>

      Promise that resolves when unique key checks are disabled

    • Enable unique key checks for the current session (MySQL/MariaDB only)

      A no-op elsewhere, for the reason given on disableUniqueKeyChecks.

      Returns Promise<void>

      Promise that resolves when unique key checks are enabled

    • Get SQL constants for the current dialect

      Returns object

      SQL constants for the current dialect

    • Get the database name

      Returns string

      The database name from the configuration

    • Get the host name

      Returns string

      The host from the configuration

    • Get the port number

      Returns string | number

      The port from the configuration

    • Get the username

      Returns string

      The username from the configuration

    • Get a model by name (alias for model())

      Parameters

      • modelName: string

        The name of the model to retrieve

      Returns ModelStatic<any> | undefined

      The model static or undefined if not found

      const User = prorm.getModel('User');
      
    • Check if a model is registered with Prorm

      Parameters

      • modelName: string

        The name of the model to check

      Returns boolean

      True if the model is registered, false otherwise

      const hasUser = prorm.hasModel('User');
      
    • Get the table name for a model, including schema if defined

      Parameters

      • model: string | ModelStatic<any>

        The model to get the table name for

      Returns string

      The full table name with schema (e.g., "schema.tableName" or just "tableName")

    • Check if a table exists in the database

      Parameters

      • tableName: string

        The table name to check (can include schema for PostgreSQL)

      Returns Promise<boolean>

      True if the table exists, false otherwise

    • Create a materialized view (PostgreSQL only)

      Parameters

      • options: {
            name: string;
            definition?: ViewDefinition;
            query?: string;
            schema?: string;
            ifNotExists?: boolean;
            replace?: boolean;
            withData?: boolean;
            uniqueIndex?: string;
            comment?: string;
        }

        Materialized view options

        • name: string
        • Optionaldefinition?: ViewDefinition

          What the view selects, as query options. Preferred over query: the SELECT is built for the connected dialect instead of written by hand.

        • Optionalquery?: string

          Prefer definition.

        • Optionalschema?: string
        • OptionalifNotExists?: boolean
        • Optionalreplace?: boolean
        • OptionalwithData?: boolean
        • OptionaluniqueIndex?: string
        • Optionalcomment?: string

      Returns Promise<void>

      Promise

      await prorm.createMaterializedView({
      name: 'user_stats',
      definition: {
      from: Order,
      attributes: ['userId', [fn('COUNT', col('id')), 'orderCount']],
      group: 'userId',
      },
      uniqueIndex: 'user_stats_user_id_key',
      });
    • Refresh a materialized view (PostgreSQL only)

      Parameters

      • viewName: string

        Name of the materialized view to refresh

      • Optionaloptions: { concurrently?: boolean; withNoData?: boolean }

        Refresh options

      Returns Promise<void>

      Promise

      // Simple refresh
      await prorm.refreshMaterializedView('user_stats');

      // Concurrent refresh (requires unique index)
      await prorm.refreshMaterializedView('user_stats', { concurrently: true });

      // Refresh without data
      await prorm.refreshMaterializedView('user_stats', { withNoData: true });
    • Drop a materialized view (PostgreSQL only)

      Parameters

      • viewName: string

        Name of the materialized view to drop

      • Optionaloptions: { ifExists?: boolean; cascade?: boolean }

        Drop options

      Returns Promise<void>

      Promise

      await prorm.dropMaterializedView('user_stats');
      await prorm.dropMaterializedView('user_stats', { ifExists: true, cascade: true });
    • Check if a materialized view exists (PostgreSQL only)

      Parameters

      • viewName: string

        Name of the materialized view

      Returns Promise<boolean>

      True if the materialized view exists

      const exists = await prorm.hasMaterializedView('user_stats');
      
    • Show all materialized views in the database (PostgreSQL only)

      Returns Promise<string[]>

      Array of materialized view names

      const views = await prorm.showMaterializedViews();
      
    • Add a model defined with decorators

      Type Parameters

      • T = any

      Parameters

      • modelClass: new () => T

        The model class (decorated with @Table)

      Returns ModelStatic<any>

      The registered model

      import { Model, DataTypes } from 'orm';
      import { Table, Column, PrimaryKey, AutoIncrement } from 'orm/decorators';

      @Table({ tableName: 'users' })
      export class User extends Model {
      @Column(DataTypes.INTEGER)
      @PrimaryKey
      @AutoIncrement
      declare id: number;

      @Column(DataTypes.STRING)
      declare name: string;
      }

      prorm.addModel(User);
    • Execute a raw query

      Parameters

      • sql: string

        The SQL query string with optional placeholders

      • Optionaloptions: QueryOptions

        Query options including replacements

      Returns Promise<number | unknown[] | [unknown[], boolean]>

      Query results (array for SELECT, [rows, created] for INSERT, count for UPDATE/DELETE)

      // Named replacements
      await prorm.query('SELECT * FROM users WHERE status = :status', {
      replacements: { status: 'active' }
      });
      // IN clause with array replacement
      await prorm.query('SELECT * FROM users WHERE id IN (:ids)', {
      replacements: { ids: [1, 2, 3] }
      });
      // Positional replacements
      await prorm.query('SELECT * FROM users WHERE name = ?', {
      replacements: ['john']
      });
      // Map raw results to model instances
      const users = await prorm.query('SELECT * FROM users', {
      model: User,
      mapToModel: true
      });
      // Returns ModelInstance objects instead of plain objects
    • Create a savepoint within a transaction

      Parameters

      • Optionalname: string

        Optional savepoint name

      • Optionaloptions: QueryOptions

        Query options including transaction

      Returns Promise<string>

      The savepoint name

    • Release a savepoint

      Parameters

      • name: string

        Savepoint name to release

      • Optionaloptions: QueryOptions

        Query options including transaction

      Returns Promise<void>

    • Rollback to a savepoint

      Parameters

      • name: string

        Savepoint name to rollback to

      • Optionaloptions: QueryOptions

        Query options including transaction

      Returns Promise<void>

    • Execute a raw query and return structured result

      Parameters

      • sql: string

        The SQL query string with optional placeholders

      • Optionaloptions: QueryOptions

        Query options including replacements

      Returns Promise<RawQueryResult>

      Structured result with rows, count, and isSelect flag

    • Execute a query within a transaction (callback mode) or return a transaction object (manual mode).

      Callback mode: prorm.transaction(async (t) => { ... }) Manual mode: const t = await prorm.transaction(); await t.commit();

      Type Parameters

      • T

      Parameters

      Returns Promise<any>

    • Register a hook to be called before a model is defined

      Parameters

      • callback: HookCallback

        Function to call before model definition

      Returns void

      prorm.beforeDefine((model, attributes, options) => {
      console.log('Defining:', model.name);
      });
    • Register a hook to be called after a model is defined

      Parameters

      • callback: HookCallback

        Function to call after model definition

      Returns void

      prorm.afterDefine((model) => {
      console.log('Defined:', model.name);
      });
    • Register a hook to be called before sync

      Parameters

      Returns void

      prorm.beforeSync((options) => {
      console.log('About to sync with options:', options);
      });
    • Register a hook to be called after sync

      Parameters

      Returns void

      prorm.afterSync((options) => {
      console.log('Sync complete with options:', options);
      });
    • Register a hook to be called before connection

      Parameters

      Returns void

      prorm.beforeConnect(() => {
      console.log('About to connect to database');
      });
    • Register a hook to be called after connection

      Parameters

      • callback: HookCallback

        Function to call after connecting, receives connection object

      Returns void

      prorm.afterConnect((connection) => {
      console.log('Connected to database', connection.id);
      });
    • Register a hook to be called before disconnection

      Parameters

      • callback: HookCallback

        Function to call before disconnecting, receives connection object

      Returns void

      prorm.beforeDisconnect((connection) => {
      console.log('About to disconnect', connection.id);
      });
    • Register a hook to be called after disconnection

      Parameters

      • callback: HookCallback

        Function to call after disconnecting, receives connection object

      Returns void

      prorm.afterDisconnect((connection) => {
      console.log('Disconnected from database', connection.id);
      });
    • Register a hook to be called before destroy

      Parameters

      Returns void

      prorm.beforeDestroy((options) => {
      console.log('About to destroy records');
      });
    • Register a hook to be called after destroy

      Parameters

      Returns void

      prorm.afterDestroy((options) => {
      console.log('Records destroyed');
      });
    • Register a hook to be called before upsert

      Parameters

      Returns void

      prorm.beforeUpsert((options) => {
      console.log('About to upsert record');
      });
    • Register a hook to be called after upsert

      Parameters

      Returns void

      prorm.afterUpsert((options) => {
      console.log('Record upserted');
      });
    • Register a hook to be called before reload

      Parameters

      Returns void

      prorm.beforeReload((options) => {
      console.log('About to reload record');
      });
    • Show all tables

      Returns Promise<string[]>

    • Alias for showSchemas - Show all schemas For PostgreSQL, returns all schemas in the database For MySQL/MariaDB, returns all databases For SQLite, returns ['main']

      Returns Promise<string[]>

    • Create a PostgreSQL extension

      Parameters

      • extensionName: string

        Name of the extension to create (e.g., 'uuid-ossp', 'postgis', 'pg_trgm')

      • Optionaloptions: CreateExtensionOptions

        Extension options (ifNotExists, schema, version)

      Returns Promise<void>

      Promise that resolves when the extension is created

      // Create the uuid-ossp extension for UUID generation
      await prorm.createExtension('uuid-ossp');
      // Create PostGIS extension for spatial data
      await prorm.createExtension('postgis', { ifNotExists: true });
      // Create pg_trgm extension with specific version
      await prorm.createExtension('pg_trgm', { version: '1.5' });
    • Drop a PostgreSQL extension

      Parameters

      • extensionName: string

        Name of the extension to drop

      • Optionaloptions: DropExtensionOptions

        Drop options (ifExists, cascade)

      Returns Promise<void>

      Promise that resolves when the extension is dropped

      // Drop an extension
      await prorm.dropExtension('uuid-ossp');
      // Drop extension with cascade (drops dependent objects)
      await prorm.dropExtension('postgis', { cascade: true });
    • Get all installed PostgreSQL extensions

      Returns Promise<ExtensionInfo[]>

      Promise that resolves to an array of extension information

      const extensions = await prorm.getExtensions();
      console.log(extensions);
      // Output: [
      // { name: 'uuid-ossp', defaultVersion: null, installedVersion: '1.0', comment: null },
      // { name: 'pg_trgm', defaultVersion: null, installedVersion: '1.5', comment: null }
      // ]
    • Check if a PostgreSQL extension is installed

      Parameters

      • extensionName: string

        Name of the extension to check

      Returns Promise<boolean>

      Promise that resolves to true if the extension is installed

      const hasUuid = await prorm.hasExtension('uuid-ossp');
      if (hasUuid) {
      console.log('UUID extension is available');
      }
    • Check if a PostgreSQL extension is installed (alias for hasExtension). Returns false for non-PostgreSQL dialects instead of throwing.

      Parameters

      • extensionName: string

      Returns Promise<boolean>

    • Parameters

      • username: string
      • Optionaloptions: any

      Returns Promise<void>

    • Parameters

      • username: string
      • options: any

      Returns Promise<void>

    • Parameters

      • username: string
      • Optionaloptions: any

      Returns Promise<void>

    • Parameters

      • username: string
      • Optionalhost: string

      Returns Promise<boolean>

    • Parameters

      • options: any

      Returns Promise<void>

    • Parameters

      • options: any

      Returns Promise<void>

    • Parameters

      • role: string
      • to: string | string[]
      • Optionaloptions: any

      Returns Promise<void>

    • Parameters

      • role: string
      • from: string | string[]
      • Optionaloptions: any

      Returns Promise<void>

    • Parameters

      • roleName: string
      • Optionaloptions: any

      Returns Promise<void>

    • Parameters

      • roleName: string
      • Optionaloptions: any

      Returns Promise<void>

    • Returns Promise<void>

    • Parameters

      • username: string
      • Optionalhost: string

      Returns Promise<any[]>

    • Returns Promise<string[]>

    • CREATE FOREIGN SERVER shortcut.

      Parameters

      Returns Promise<void>

      await prorm.createServer('remote_pg', {
      fdw: 'postgres_fdw',
      options: { host: 'remotehost', dbname: 'remotedb', port: '5432' },
      ifNotExists: true,
      });
    • DROP FOREIGN SERVER shortcut.

      Parameters

      • name: string
      • Optionaloptions: { ifExists?: boolean; cascade?: boolean }

      Returns Promise<void>

    • CREATE USER MAPPING shortcut.

      Parameters

      Returns Promise<void>

      await prorm.createUserMapping({
      serverName: 'remote_pg',
      user: 'CURRENT_USER',
      options: { user: 'remoteuser', password: 'secret' },
      });
    • DROP USER MAPPING shortcut.

      Parameters

      • serverName: string
      • Optionaluser: string

      Returns Promise<void>

    • CREATE FOREIGN TABLE shortcut.

      Parameters

      Returns Promise<void>

      await prorm.createForeignTable('remote_orders', {
      serverName: 'remote_pg',
      columns: {
      id: { type: 'INTEGER' },
      total: { type: 'NUMERIC(12,2)' },
      created_at: { type: 'TIMESTAMP' },
      },
      options: { schema_name: 'public', table_name: 'orders' },
      });
    • IMPORT FOREIGN SCHEMA shortcut.

      Parameters

      Returns Promise<void>

      await prorm.importForeignSchema('public', 'remote_pg', {
      localSchema: 'remote_mirror',
      limitTo: ['users', 'orders'],
      });
    • Define a foreign table and register a read-only model for it.

      Works like define() but issues CREATE FOREIGN TABLE in the database and returns a model whose findAll / findOne / findByPk are usable for read-only queries. Write operations (create/update/destroy) are not prevented at the ORM level but will fail at the database level because PostgreSQL foreign tables are read-only by default.

      Parameters

      • tableName: string

        The local foreign table name

      • options: ForeignTableOptions

        Foreign table options (serverName, columns, etc.)

      Returns Promise<any>

      The model class registered under tableName

      const RemoteUser = await prorm.defineForeignTable('remote_users', {
      serverName: 'remote_pg',
      columns: {
      id: { type: 'INTEGER' },
      email: { type: 'TEXT' },
      name: { type: 'VARCHAR(255)' },
      },
      ifNotExists: true,
      });
      const users = await RemoteUser.findAll({ where: { name: 'Alice' } });
    • Get database version

      Returns Promise<string>

    • Get database name

      Returns string

    • Create a database schema

      Parameters

      • name: string

        Name of the schema to create

      Returns Promise<void>

      Promise that resolves when the schema is created

      // Create a new schema
      await prorm.createSchema('mySchema');
    • Drop a database schema

      Parameters

      • name: string

        Name of the schema to drop

      • Optionaloptions: { cascade?: boolean; ifExists?: boolean }

        Options for dropping the schema (cascade, ifExists)

      Returns Promise<void>

      Promise that resolves when the schema is dropped

      // Drop a schema
      await prorm.dropSchema('mySchema');
      // Drop schema with cascade (drop all objects in schema)
      await prorm.dropSchema('mySchema', { cascade: true });
    • Show all schemas

      Returns Promise<string[]>

      Promise that resolves to an array of schema names

      // Get all schemas
      const schemas = await prorm.showSchemas();
      console.log(schemas); // ['public', 'mySchema', ...]
    • Get the full table name with schema prefix

      Parameters

      • tableName: string

        The table name

      • Optionalschema: string

        Optional schema name

      • OptionalschemaDelimiter: string

        Optional delimiter (default: '.')

      Returns string

      Full table name with schema prefix

    • Create a database trigger

      Parameters

      • options: {
            tableName: string;
            triggerName: string;
            timing: "BEFORE" | "AFTER" | "INSTEAD OF";
            event:
                | "INSERT"
                | "UPDATE"
                | "DELETE"
                | "INSERT UPDATE"
                | "INSERT DELETE"
                | "UPDATE DELETE"
                | "INSERT UPDATE DELETE";
            body: string;
            schema?: string;
            rowLevel?: boolean;
            constraint?: string;
            updateColumns?: string[];
            functionName?: string;
            functionArgs?: any[];
        }

        Trigger creation options

      Returns Promise<void>

      Promise that resolves when the trigger is created

      // Create an INSERT trigger in PostgreSQL
      await prorm.createTrigger({
      tableName: 'users',
      triggerName: 'set_created_at',
      timing: 'BEFORE',
      event: 'INSERT',
      body: 'NEW.created_at = NOW();',
      rowLevel: true
      });
      // Create an UPDATE trigger in MySQL
      await prorm.createTrigger({
      tableName: 'users',
      triggerName: 'update_timestamp',
      timing: 'BEFORE',
      event: 'UPDATE',
      body: 'SET NEW.updated_at = NOW();'
      });
    • Drop a database trigger

      Parameters

      • options: {
            tableName: string;
            triggerName: string;
            schema?: string;
            ifExists?: boolean;
            cascade?: boolean;
            constraint?: boolean;
        }

        Trigger drop options

      Returns Promise<void>

      Promise that resolves when the trigger is dropped

      // Drop a trigger
      await prorm.dropTrigger({
      tableName: 'users',
      triggerName: 'set_created_at'
      });
      // Drop trigger with IF EXISTS (PostgreSQL)
      await prorm.dropTrigger({
      tableName: 'users',
      triggerName: 'old_trigger',
      ifExists: true
      });
    • Create a custom aggregate function (algorithm) in PostgreSQL PostgreSQL supports creating custom aggregate functions using CREATE AGGREGATE

      Parameters

      • options: {
            name: string;
            arguments: string[];
            stateType: string;
            stateFunction: string;
            finalFunction?: string;
            initialCondition?: string;
            schema?: string;
            replace?: boolean;
            parallel?: "UNSAFE" | "SAFE" | "RESTRICTED";
            language?: string;
        }

        Algorithm creation options

        • name: string

          Name of the aggregate function to create

        • arguments: string[]

          Input data types for the aggregate

        • stateType: string

          The state type (intermediate state data type)

        • stateFunction: string

          The state transition function body

        • OptionalfinalFunction?: string

          The final function body (optional)

        • OptionalinitialCondition?: string

          The initial condition value (optional)

        • Optionalschema?: string

          Schema name (optional)

        • Optionalreplace?: boolean

          If true, replaces existing aggregate (PostgreSQL 9.5+)

        • Optionalparallel?: "UNSAFE" | "SAFE" | "RESTRICTED"

          Parallel mode: UNSAFE, SAFE, or RESTRICTED

        • Optionallanguage?: string

          Language for the function (default: sql)

      Returns Promise<void>

      Promise that resolves when the algorithm is created

      // Create a custom aggregate function in PostgreSQL
      await prorm.createAlgorithm({
      name: 'my_aggregate',
      arguments: ['integer'],
      stateType: 'integer',
      stateFunction: 's = s + $1',
      finalFunction: 's = s'
      });
      // Create a custom aggregate with multiple parameters
      await prorm.createAlgorithm({
      name: 'weighted_avg',
      arguments: ['numeric', 'numeric'],
      stateType: 'numeric',
      stateFunction: 's = s + ($1 * $2)',
      finalFunction: 's = s'
      });
    • Drop a custom aggregate function (algorithm) from PostgreSQL

      Parameters

      • options: {
            name: string;
            arguments: string[];
            schema?: string;
            ifExists?: boolean;
            cascade?: boolean;
            restrict?: boolean;
        }

        Algorithm drop options

        • name: string

          Name of the aggregate function to drop

        • arguments: string[]

          Input data types for the aggregate

        • Optionalschema?: string

          Schema name (optional)

        • OptionalifExists?: boolean

          If true, uses IF EXISTS (PostgreSQL 9.3+)

        • Optionalcascade?: boolean

          If true, CASCADE dependent objects

        • Optionalrestrict?: boolean

          If true, RESTRICT if dependent objects exist

      Returns Promise<void>

      Promise that resolves when the algorithm is dropped

      // Drop an algorithm
      await prorm.dropAlgorithm({
      name: 'my_aggregate',
      arguments: ['integer']
      });
      // Drop algorithm with IF EXISTS
      await prorm.dropAlgorithm({
      name: 'my_aggregate',
      arguments: ['integer'],
      ifExists: true
      });
    • Add a new column to a table

      Parameters

      Returns Promise<void>

    • Remove a column from a table

      Parameters

      • tableName: string
      • columnName: string

      Returns Promise<void>

    • Change a column definition

      Parameters

      Returns Promise<void>

    • Rename a table

      Parameters

      • oldName: string
      • newName: string

      Returns Promise<void>

    • Add an index

      Parameters

      • tableName: string
      • indexName: string
      • fields: string[]
      • Optionaloptions: { unique?: boolean; type?: string }

      Returns Promise<void>

    • Remove an index

      Parameters

      • tableName: string
      • indexName: string

      Returns Promise<void>

    • Describe a table

      Parameters

      • tableName: string

      Returns Promise<Record<string, unknown>>

    • Create a new database with the specified options. Supports PostgreSQL, MySQL, and MariaDB.

      Parameters

      • options: {
            name: string;
            encoding?: string;
            lcCollate?: string;
            lcCtype?: string;
            template?: string;
            tablespace?: string;
            collate?: string;
            isTemplate?: boolean;
        }

      Returns Promise<void>

      // Create database with PostgreSQL
      await prorm.createDatabase({
      name: 'myapp',
      encoding: 'UTF8',
      lcCollate: 'en_US.UTF-8',
      lcCtype: 'en_US.UTF-8',
      template: 'template0',
      });
      // Create database with MySQL/MariaDB
      await prorm.createDatabase({
      name: 'myapp',
      encoding: 'UTF8',
      collate: 'utf8mb4_unicode_ci',
      });
    • Drop a database if it exists.

      Parameters

      • name: string

      Returns Promise<void>

      await prorm.dropDatabase('olddb');
      
    • Register an object or key-value store for use by @ExternalField.

      Accepts any of the shipped stores (S3, MinIO, R2, GCS, Azure Blob, Redis, ...) directly - the differing method names are normalized internally - or any object implementing ExternalStoreAdapter.

      const s3 = new S3Store({ region: 'us-east-1' });
      await s3.connect();
      prorm.registerStore('assets', s3, { defaultBucket: 'avatars' });

      Parameters

      Returns this

    • Parameters

      • procedureClass: Function

      Returns this

    • Get the migration configuration

      Returns any

    • Run pending migrations

      Parameters

      • Optionaloptions: { migration?: string }

      Returns Promise<any>

    • Revert migrations

      Parameters

      • Optionaloptions: { steps?: number; migration?: string }

      Returns Promise<any>

    • Get migration status

      Returns Promise<any>

    • Create a SQL function expression

      Parameters

      • fnName: string

        The SQL function name (e.g., 'COUNT', 'UPPER', 'YEAR', 'SUM', 'AVG', 'LOWER')

      • ...args: (string | Literal | Col | Fn)[]

        The arguments to the function (column names, column references, or other functions)

      Returns Fn

      A Fn object that can be used in query attributes

      // COUNT(id) -> COUNT(id)
      prorm.fn('COUNT', 'id')

      // UPPER(name) -> UPPER(name)
      prorm.fn('UPPER', prorm.col('name'))

      // YEAR(createdAt) -> YEAR(createdAt)
      prorm.fn('YEAR', 'createdAt')

      // COUNT with column reference
      prorm.fn('COUNT', prorm.col('id'))

      // Nested function: UPPER(LOWER(name))
      prorm.fn('UPPER', prorm.fn('LOWER', 'name'))

      // Use in findAll
      User.findAll({
      attributes: ['role', [prorm.fn('COUNT', prorm.col('id')), 'count']]
      })
    • Create a column reference for use in SQL functions

      Parameters

      • tableOrColumn: string

        Table name (if second param provided) or column name

      • Optionalcolumn: string

        Column name (if first param is table name)

      Returns Col

      A Col object that can be used as an argument to prorm.fn()

      // Reference a column in a function
      prorm.fn('COUNT', prorm.col('id'))

      // Reference with table name: col('User', 'name') -> "User"."name"
      prorm.fn('UPPER', prorm.col('User', 'name'))

      // Dot notation: col('table.column') -> "table"."column"
      prorm.fn('UPPER', prorm.col('User.name'))

      // Use in findAll
      User.findAll({
      attributes: ['role', [prorm.fn('COUNT', prorm.col('id')), 'count']]
      })
    • Create a type cast expression Used to cast a value to a specific data type in SQL queries

      Parameters

      • value: string | Literal | Col | Fn

        The value to cast (column reference, literal, or other expression)

      • type: string

        The target data type (e.g., 'VARCHAR', 'INTEGER', 'DATE', 'BOOLEAN')

      Returns Cast

      A Cast object that can be used in queries

      // Cast a string to integer
      prorm.cast(prorm.col('count'), 'INTEGER')

      // Cast a value to date
      prorm.cast(prorm.col('timestamp'), 'DATETIME')

      // Cast in where clause
      User.findAll({
      where: prorm.cast(prorm.col('active'), 'BOOLEAN')
      })

      // Use in attributes for type conversion
      User.findAll({
      attributes: [[prorm.cast(prorm.col('price'), 'VARCHAR'), 'priceStr']]
      })
    • Create a where condition for complex queries Allows creating custom WHERE clauses with operators

      Parameters

      • col: Literal | Col | Fn
      • value: unknown

      Returns WhereObject

      A WhereObject for use in find options

      // Simple equality with column reference
      prorm.where(prorm.col('name'), 'John')

      // With a comparator operator
      prorm.where(prorm.col('age'), { $gt: 18 })

      // Complex condition with literal
      prorm.where(prorm.literal('LOWER(name)'), 'john')

      // Using with fn
      prorm.where(prorm.fn('YEAR', prorm.col('createdAt')), 2024)
    • Create an AND condition for combining multiple where conditions

      Parameters

      • ...conditions: unknown[]

        The conditions to combine with AND

      Returns AndOrObject

      An AndOrObject with AND operator

      // Combine multiple conditions
      prorm.and(
      { name: 'John' },
      { age: { $gte: 18 } }
      )

      // Use in where clause
      User.findAll({
      where: prorm.and(
      { status: 'active' },
      { role: 'admin' }
      )
      })

      // Nested with or
      prorm.and(
      { active: true },
      prorm.or({ role: 'admin' }, { role: 'moderator' })
      )
    • Create an OR condition for combining multiple where conditions

      Parameters

      • ...conditions: unknown[]

        The conditions to combine with OR

      Returns AndOrObject

      An AndOrObject with OR operator

      // Combine multiple conditions
      prorm.or(
      { name: 'John' },
      { name: 'Jane' }
      )

      // Use in where clause
      User.findAll({
      where: prorm.or(
      { status: 'active' },
      { role: 'admin' }
      )
      })

      // Complex nested condition
      prorm.or(
      prorm.and({ status: 'active' }, { role: 'admin' }),
      { id: 1 }
      )
    • Create a JSON path query for querying JSON columns Used to query specific paths in JSON columns (PostgreSQL, MySQL JSON)

      Parameters

      • path: string

        The JSON path to query (dot notation or array notation)

      • Optionalvalue: unknown

        Optional value to compare against

      Returns JsonObject

      A JsonObject for use in where clauses

      // Query JSON column path
      prorm.json('profile.name')

      // Query nested JSON path
      prorm.json('settings.theme.color')

      // Query with value comparison
      prorm.json('profile.age', 25)

      // Use in where clause
      User.findAll({
      where: prorm.json('profile.isActive', true)
      })

      // Query array element
      prorm.json('tags[0]', 'important')
    • Static version of the where method - creates a WHERE condition Can be used without instantiating Prorm

      Parameters

      • col: Literal | Col | Fn

        The column reference (Col, Fn, or Literal)

      • value: unknown

        The value or condition to compare against

      Returns WhereObject

      A WhereObject for use in find options

    • Static version of the and method - combines conditions with AND Can be used without instantiating Prorm

      Parameters

      • ...conditions: unknown[]

        The conditions to combine with AND

      Returns AndOrObject

      An AndOrObject with AND operator

    • Static version of the or method - combines conditions with OR Can be used without instantiating Prorm

      Parameters

      • ...conditions: unknown[]

        The conditions to combine with OR

      Returns AndOrObject

      An AndOrObject with OR operator

    • Static version of the json method - creates a JSON path query Can be used without instantiating Prorm

      Parameters

      • path: string

        The JSON path to query

      • Optionalvalue: unknown

        Optional value to compare against

      Returns JsonObject

      A JsonObject for use in where clauses

    • Static version of the validate method - validates a model's values Can be used without instantiating Prorm

      Parameters

      • values: Record<string, unknown>

        The values to validate

      • Optionaloptions: { model?: ModelStatic<any> }

        Validation options

      Returns Promise<ValidationError | null>

      A promise that resolves with validation errors