Create a new Prorm instance
Configuration options
// 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);
});
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.
ReadonlyexternalObject/key-value stores backing
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 all models as an object for backward compatibility Allows accessing models via prorm.models.ModelName
Sequelize-style model manager, exposing the registered models along with a few convenience accessors on top of the internal model map.
Check if connected
Get all models as an object (for backward compatibility)
Lazily-created ForeignDataManager instance for this Prorm connection. Provides the full FDW management surface (servers, user mappings, foreign tables).
Lazily-created UserManager instance for this Prorm connection. Provides the full user / role / privilege management surface.
UUIDV4 default value for generating UUIDs Use as defaultValue in model definitions
A Literal that generates a UUID v4
Create a literal/raw SQL expression Use this to insert raw SQL into queries without parameter escaping
The raw SQL expression
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 } }
);
Get the connection pool instance
The connection pool or null if not configured
Get pool statistics
Pool statistics or null if pool not configured
Get the logger instance
Set logging level
Connect to the database and authenticate
Disconnect from the database and close the connection pool
Add a hook to the Prorm instance
The name of the hook (e.g., 'beforeDefine', 'afterSync', 'beforeConnect')
The hook handler function
The Prorm instance for chaining
Get the dialect name
The dialect name (e.g., 'sqlite', 'postgres', 'mysql')
Get the query interface for DDL operations
Create a partitioned table (PostgreSQL 10+)
Name of the table to create
Column definitions
Optionaloptions: TableOptions & {Table options including partition configuration
Create a partition for an existing partitioned table (PostgreSQL 10+)
Partition creation options
Attach a partition to a partitioned table (PostgreSQL 11+)
Partition attachment options
Detach a partition from a partitioned table (PostgreSQL 11+)
Partition detachment options
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+).
Promise that resolves when foreign key checks are disabled
Enable foreign key checks for the current session
The inverse of disableForeignKeyChecks, with the same dialect support and the same PostgreSQL privilege requirement.
Promise that resolves when foreign key checks are enabled
Set the transaction isolation level
The isolation level to set
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.
SQL string for disabling foreign key checks
Get SQL for setting transaction isolation level for the current dialect
The isolation level
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.
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.
Promise that resolves when unique key checks are enabled
Get SQL constants for the current dialect
SQL constants for the current dialect
Get the database name
The database name from the configuration
Get the host name
The host from the configuration
Get the port number
The port from the configuration
Get the username
The username from the configuration
Get all registered models
Get a model by name (alias for model())
The name of the model to retrieve
The model static or undefined if not found
Get the table name for a model, including schema if defined
The model to get the table name for
The full table name with schema (e.g., "schema.tableName" or just "tableName")
Check if a table exists in the database
The table name to check (can include schema for PostgreSQL)
True if the table exists, false otherwise
Create a materialized view (PostgreSQL only)
Materialized view options
Optionaldefinition?: ViewDefinitionWhat the view selects, as query options. Preferred over query: the
SELECT is built for the connected dialect instead of written by hand.
Optionalquery?: stringOptionalschema?: stringOptionalifNotExists?: booleanOptionalreplace?: booleanOptionalwithData?: booleanOptionaluniqueIndex?: stringOptionalcomment?: stringPromise
Refresh a materialized view (PostgreSQL only)
Name of the materialized view to refresh
Optionaloptions: { concurrently?: boolean; withNoData?: boolean }
Refresh options
Promise
Drop a materialized view (PostgreSQL only)
Name of the materialized view to drop
Optionaloptions: { ifExists?: boolean; cascade?: boolean }
Drop options
Promise
Define a new model
Name of the model
Model attributes
Model options
Add a model defined with decorators
The model class (decorated with @Table)
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
The SQL query string with optional placeholders
Optionaloptions: QueryOptions
Query options including replacements
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] }
});
Create a savepoint within a transaction
Optionalname: string
Optional savepoint name
Optionaloptions: QueryOptions
Query options including transaction
The savepoint name
Release a savepoint
Savepoint name to release
Optionaloptions: QueryOptions
Query options including transaction
Rollback to a savepoint
Savepoint name to rollback to
Optionaloptions: QueryOptions
Query options including transaction
Execute a raw query and return structured result
The SQL query string with optional placeholders
Optionaloptions: QueryOptions
Query options including replacements
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();
OptionalcallbackOrOptions: TransactionOptions | ((transaction: any) => Promise<T>)Optionaloptions: TransactionOptionsGet the current transaction
Register a hook to be called before a model is defined
Function to call before model definition
Register a hook to be called after a model is defined
Function to call after model definition
Register a hook to be called before sync
Function to call before sync
Register a hook to be called after sync
Function to call after sync
Register a hook to be called before connection
Function to call before connecting
Register a hook to be called after connection
Function to call after connecting, receives connection object
Register a hook to be called before disconnection
Function to call before disconnecting, receives connection object
Register a hook to be called after disconnection
Function to call after disconnecting, receives connection object
Register a hook to be called before destroy
Function to call before destroy
Register a hook to be called after destroy
Function to call after destroy
Register a hook to be called before upsert
Function to call before upsert
Register a hook to be called after upsert
Function to call after upsert
Register a hook to be called before reload
Function to call before reload
Show all tables
Alias for showSchemas - Show all schemas For PostgreSQL, returns all schemas in the database For MySQL/MariaDB, returns all databases For SQLite, returns ['main']
Create a PostgreSQL extension
Name of the extension to create (e.g., 'uuid-ossp', 'postgis', 'pg_trgm')
Optionaloptions: CreateExtensionOptions
Extension options (ifNotExists, schema, version)
Promise that resolves when the extension is created
Drop a PostgreSQL extension
Name of the extension to drop
Optionaloptions: DropExtensionOptions
Drop options (ifExists, cascade)
Promise that resolves when the extension is dropped
Get all installed PostgreSQL extensions
Promise that resolves to an array of extension information
Check if a PostgreSQL extension is installed
Name of the extension to check
Promise that resolves to true if the extension is installed
Check if a PostgreSQL extension is installed (alias for hasExtension). Returns false for non-PostgreSQL dialects instead of throwing.
Optionaloptions: anyOptionaloptions: anyOptionalhost: stringOptionaloptions: anyOptionaloptions: anyOptionaloptions: anyOptionaloptions: anyOptionalhost: stringCREATE FOREIGN SERVER shortcut.
DROP FOREIGN SERVER shortcut.
Optionaloptions: { ifExists?: boolean; cascade?: boolean }List all foreign servers visible in the current PostgreSQL database.
DROP USER MAPPING shortcut.
Optionaluser: stringCREATE FOREIGN TABLE shortcut.
IMPORT FOREIGN SCHEMA shortcut.
Optionaloptions: ImportForeignSchemaOptionsDefine 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.
The local foreign table name
Foreign table options (serverName, columns, etc.)
The model class registered under tableName
Get database version
Get database name
Drop a database schema
Name of the schema to drop
Optionaloptions: { cascade?: boolean; ifExists?: boolean }
Options for dropping the schema (cascade, ifExists)
Promise that resolves when the schema is dropped
Get the full table name with schema prefix
The table name
Optionalschema: string
Optional schema name
OptionalschemaDelimiter: string
Optional delimiter (default: '.')
Full table name with schema prefix
Create a database trigger
Trigger creation options
Promise that resolves when the trigger is created
Drop a database trigger
Trigger drop options
Promise that resolves when the trigger is dropped
Create a custom aggregate function (algorithm) in PostgreSQL PostgreSQL supports creating custom aggregate functions using CREATE AGGREGATE
Algorithm creation options
Name of the aggregate function to create
Input data types for the aggregate
The state type (intermediate state data type)
The state transition function body
OptionalfinalFunction?: stringThe final function body (optional)
OptionalinitialCondition?: stringThe initial condition value (optional)
Optionalschema?: stringSchema name (optional)
Optionalreplace?: booleanIf true, replaces existing aggregate (PostgreSQL 9.5+)
Optionalparallel?: "UNSAFE" | "SAFE" | "RESTRICTED"Parallel mode: UNSAFE, SAFE, or RESTRICTED
Optionallanguage?: stringLanguage for the function (default: sql)
Promise that resolves when the algorithm is created
Drop a custom aggregate function (algorithm) from PostgreSQL
Algorithm drop options
Name of the aggregate function to drop
Input data types for the aggregate
Optionalschema?: stringSchema name (optional)
OptionalifExists?: booleanIf true, uses IF EXISTS (PostgreSQL 9.3+)
Optionalcascade?: booleanIf true, CASCADE dependent objects
Optionalrestrict?: booleanIf true, RESTRICT if dependent objects exist
Promise that resolves when the algorithm is dropped
Add a new column to a table
Remove a column from a table
Change a column definition
Rename a table
Remove an index
Describe a table
Create a new database with the specified options. Supports PostgreSQL, MySQL, and MariaDB.
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' });
Get the migration configuration
Run pending migrations
Optionaloptions: { migration?: string }Revert migrations
Optionaloptions: { steps?: number; migration?: string }Get migration status
Create a SQL function expression
The SQL function name (e.g., 'COUNT', 'UPPER', 'YEAR', 'SUM', 'AVG', 'LOWER')
The arguments to the function (column names, column references, or other functions)
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
Table name (if second param provided) or column name
Optionalcolumn: string
Column name (if first param is table name)
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
The value to cast (column reference, literal, or other expression)
The target data type (e.g., 'VARCHAR', 'INTEGER', 'DATE', 'BOOLEAN')
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
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
The conditions to combine with AND
An AndOrObject with AND operator
Create an OR condition for combining multiple where conditions
The conditions to combine with OR
An AndOrObject with OR operator
Create a JSON path query for querying JSON columns Used to query specific paths in JSON columns (PostgreSQL, MySQL JSON)
The JSON path to query (dot notation or array notation)
Optionalvalue: unknown
Optional value to compare against
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')
StaticwhereStatic version of the where method - creates a WHERE condition Can be used without instantiating Prorm
The column reference (Col, Fn, or Literal)
The value or condition to compare against
A WhereObject for use in find options
StaticandStatic version of the and method - combines conditions with AND Can be used without instantiating Prorm
The conditions to combine with AND
An AndOrObject with AND operator
StaticorStatic version of the or method - combines conditions with OR Can be used without instantiating Prorm
The conditions to combine with OR
An AndOrObject with OR operator
StaticjsonStatic version of the json method - creates a JSON path query Can be used without instantiating Prorm
The JSON path to query
Optionalvalue: unknown
Optional value to compare against
A JsonObject for use in where clauses
StaticvalidateStatic version of the validate method - validates a model's values Can be used without instantiating Prorm
The values to validate
Optionaloptions: { model?: ModelStatic<any> }
Validation options
A promise that resolves with validation errors
Main Prorm class with error handling and logging