Connection, pool and transaction options
Options of the Sequelize constructor (pool, replicas, retry, statement cache), common query options, transactions, raw connections and sync.
Options marked postgrelize extension exist only in postgrelize; Sequelize v6 has no such option. This page is generated from the TypeScript declarations and their TSDoc, so it always matches the code.
SequelizeOptionsPoolOptionsReplicationOptionsRetryOptionsStatementCacheOptionsQueryOptionsTransactionOptionsGetConnectionOptionsSyncOptionsDropOptions
SequelizeOptions
Options of the Sequelize constructor (PostgreSQL subset of Sequelize v6 Options). All fields are optional; values given in a connection URL are overridden by these fields.
const options: SequelizeOptions = {
dialect: 'postgres',
host: 'localhost',
port: 5432,
pool: { max: 10 },
logging: false,
define: { underscored: true },
};
const db = new Sequelize('app', 'user', 'pass', options);| Option | Type | Description |
|---|---|---|
dialect | "postgres" | Must be 'postgres' when given. |
database | string | Database name. |
username | string | User name. |
password | string | Password. |
host | string | Host. Default 'localhost'. |
port | number | Port. Default 5432. |
ssl | boolean | ConnectionOptions | SSL settings passed to pg. |
dialectOptions | Readonly<Omit<PoolConfig, "types">> | Extra options passed to the pg pool/client as is. |
dialectModule | object | Accepted for Sequelize v6 type compatibility; postgrelize ignores it and always loads pg. Default: undefined. |
pool | Readonly<{ max?: number | undefined; min?: number | undefined; idle?: number | undefine… | Pool settings. |
logging | false | LoggingFunction | SQL logger, or false to disable. Default console.log. |
benchmark | boolean | Pass query duration to the logger. |
timezone | string | Session time zone. Default '+00:00'. |
define | Readonly<{ timestamps?: boolean | undefined; underscored?: boolean | undefined; freezeT… | Defaults for all models. |
replication | Readonly<{ read: Readonly<{ host?: string | undefined; port?: number | undefined; usern… | Read replicas and writer (Sequelize v6 replication); entries inherit missing connection settings. |
hooks | Partial<Readonly<Record<"beforeValidate" | "afterValidate" | "validationFailed" | "befo… | Sequelize-level hooks run for every model (and beforeConnect). |
minifyAliases | boolean | Shorten the aliases of included columns (Posts.Comments.title becomes _0) and of table aliases of 64 or more characters, as in Sequelize v6, so deep includes stay within PostgreSQL's 63-byte identifier limit. Without it PostgreSQL truncates longer aliases and columns can collide. Default false. |
retry | Readonly<{ max?: number | undefined; match?: readonly RetryMatch[] | undefined; backoff… | Retries failed queries and transaction starts (Sequelize v6 retry, backed by the same rules as retry-as-promised). Applies to connection acquisition and query execution of query, finders and writes, and to acquiring the connection and BEGIN of a transaction; never to a statement inside an open transaction (PostgreSQL aborts it) or to COPY. A per-query or per-transaction retry option is merged over it. Off by default. |
inAsAnyThreshold postgrelize extension | number | Minimum IN-list length compiled to = ANY($n). Default 100. PostgreSQL extension. |
statementCache postgrelize extension | boolean | Readonly<{ max?: number | undefined; }> | Opt-in named prepared statements (PostgreSQL extension): repeated SELECT / INSERT / UPDATE / DELETE texts are parsed and planned once per connection. true uses the default bound of 100 statements per connection. Off by default; not for PgBouncer in transaction pooling mode; pair with a bounded pool.max. |
PoolOptions
Connection pool settings (Sequelize v6 PoolOptions), given as the pool option of SequelizeOptions.
const pool: PoolOptions = { max: 10, idle: 10_000, acquire: 30_000 };
const db = new Sequelize('postgres://user:pass@localhost:5432/app', { pool });| Option | Type | Description |
|---|---|---|
max | number | Maximum number of connections. Default 5. |
min | number | Minimum number of connections. Accepted for compatibility; pg does not keep idle minimums. |
idle | number | Milliseconds a connection may be idle before release. Default 10000. |
acquire | number | Milliseconds to wait for a connection before throwing ConnectionAcquireTimeoutError. Default 60000. |
evict | number | Accepted for compatibility; eviction is handled by idle. |
maxUses | number | Maximum times a connection may be used before it is replaced (pg maxUses). |
ReplicationOptions
The replication option: readers receive SELECTs outside transactions, the writer everything else. Members inherit missing connection settings from the top-level options. See ReplicationMember.
const replication: ReplicationOptions = {
read: [{ host: 'replica-1.internal' }, { host: 'replica-2.internal' }],
write: { host: 'primary.internal' },
};
const db = new Sequelize('app', 'user', 'pass', { dialect: 'postgres', replication });| Option | Type | Description |
|---|---|---|
read | Readonly<{ host?: string | undefined; port?: number | undefined; username?: string | un… | Reader(s). |
write | Readonly<{ host?: string | undefined; port?: number | undefined; username?: string | un… | Writer; defaults to the top-level connection settings. |
RetryOptions
Retry settings (Sequelize v6 RetryOptions), given as the retry option of SequelizeOptions and of a single query or transaction (the query option is merged over the instance option). Nothing is retried unless max is set. An attempt is repeated only when it failed, fewer than max attempts ran and, when match is non-empty, the error matches an entry. Connection errors are matchable by the v6 names SequelizeConnectionError, SequelizeConnectionRefusedError, SequelizeHostNotFoundError, SequelizeHostNotReachableError, SequelizeInvalidConnectionError and SequelizeConnectionTimedOutError.
const retry: RetryOptions = {
max: 5,
match: [/SequelizeConnectionRefusedError/, 'ECONNRESET'],
backoffBase: 100,
backoffExponent: 1.1,
};
const db = new Sequelize('postgres://user:pass@localhost:5432/app', { retry });| Option | Type | Description |
|---|---|---|
max | number | Maximum number of attempts, the first one included. Without it nothing is retried. |
match | readonly RetryMatch[] | Errors worth retrying. An empty or missing list retries every error, so list the errors you mean (for example [/SequelizeConnectionError/]). |
backoffBase | number | Delay before the first retry in milliseconds. Default 100. |
backoffExponent | number | Growth of the delay per retry: backoffBase * backoffExponent ** (attempt - 1). Default 1.1. |
backoffJitter | number | Random variation added to or subtracted from each delay, in milliseconds. Default 0. |
timeout | number | Rejects an attempt that takes longer than this many milliseconds, without retrying it. |
name | string | Name used in messages and in the timeout error. Default 'unknown'. |
report | (message: string, options: Readonly<{ max?: number | undefined; match?: readonly RetryM… | Receives progress messages. |
StatementCacheOptions postgrelize extension
Named prepared statement cache settings, given as the statementCache option of SequelizeOptions. PostgreSQL extension.
const db = new Sequelize('postgres://user:pass@localhost:5432/app', { statementCache: { max: 50 } });| Option | Type | Description |
|---|---|---|
max | number | Maximum named statements per connection. Default 100. Further statements run unnamed. |
QueryOptions
Options of sequelize.query, in addition to the common query options such as transaction and logging.
const rows = await sequelize.query('SELECT * FROM users WHERE id = :id', {
type: QueryTypes.SELECT,
replacements: { id: 1 },
model: User,
mapToModel: true,
});| Option | Type | Description |
|---|---|---|
transaction | Transaction | Transaction to run in; null forces running outside the CLS transaction. |
logging | false | LoggingFunction | SQL logger for this query, or false. |
benchmark | boolean | Pass query duration to the logger. |
statementTimeout postgrelize extension | number | statement_timeout for this query only, in milliseconds (non-negative integer; 0 disables it). PostgreSQL cancels the statement with a DatabaseError (code 57014) when it runs longer. Outside a transaction the query runs in its own short transaction; inside one the previous timeout is restored afterwards. PostgreSQL extension. |
retry | Readonly<{ max?: number | undefined; match?: readonly RetryMatch[] | undefined; backoff… | Retries this query when it fails, merged over the instance retry option (Sequelize v6). The connection acquisition is part of the retried work; a query that runs in a transaction is never retried. |
useMaster postgrelize extension | boolean | Force the writer even for SELECTs when read replicas are configured. postgrelize extension. |
replacements | Replacements | Values of ? (array) or :name (object) placeholders written in raw SQL inside the options (where: literal('"a" = :a'), attributes: [[literal(...), 'x']]), as in Sequelize v6. Every value is sent as a bound parameter, never concatenated into the SQL text; arrays expand to a comma separated list of parameters. Values for ? / :name placeholders; bound as parameters. |
type | QueryType | Shapes the result; default RAW. |
bind | BindParameters | Values for $1 / $name placeholders. |
plain | boolean | Return only the first row (or null). |
model | ModelStatic<AnyModel> | Build instances of this model from SELECT rows. |
mapToModel | boolean | Map column names to attribute names of model. |
raw | boolean | Return plain rows even with model. |
nest | boolean | Nests a.b keys of the rows into objects ({ a: { b } }); implies type: SELECT unless a type is given. |
TransactionOptions
Options of sequelize.transaction(). All fields are optional.
const options: TransactionOptions = {
isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE,
readOnly: true,
deferrable: true,
settings: { 'app.user_id': '42', statement_timeout: '5s' },
};
const t = await sequelize.transaction(options);
await t.commit();| Option | Type | Description |
|---|---|---|
isolationLevel | IsolationLevel | Isolation level of a new transaction. |
type | "DEFERRED" | "IMMEDIATE" | "EXCLUSIVE" | Accepted for compatibility, ignored. |
readOnly postgrelize extension | boolean | Start READ ONLY. PostgreSQL extension. |
deferrable postgrelize extension | boolean | Readonly<{ sql: string; }> | true / false: start DEFERRABLE / NOT DEFERRABLE. PostgreSQL honours it only for SERIALIZABLE READ ONLY transactions: a deferrable one waits for a safe snapshot and then runs without serialization failures; ignored for savepoints (PostgreSQL extension). Deferrable.SET_DEFERRED / Deferrable.SET_IMMEDIATE (Sequelize v6): run SET CONSTRAINTS ... DEFERRED / IMMEDIATE right after the transaction starts, for all constraints or the names given. |
transaction | Transaction | Parent transaction: the new transaction becomes a savepoint inside it. |
settings postgrelize extension | Readonly<Record<string, string | number | boolean>> | Session settings applied with SET LOCAL semantics (set_config(name, value, true)), e.g. { 'app.user_id': '42', statement_timeout: '5s' } for row-level security. PostgreSQL extension. |
logging | false | LoggingFunction | SQL logger for transaction statements. |
retry | Readonly<{ max?: number | undefined; match?: readonly RetryMatch[] | undefined; backoff… | Retries acquiring the connection and BEGIN (and the statements that follow it, up to the first user statement) when they fail, merged over the instance retry option (Sequelize v6). Ignored for savepoints and for statements inside the transaction. See RetryOptions. |
GetConnectionOptions
Options of sequelize.connectionManager.getConnection() (Sequelize v6 GetConnectionOptions).
const options: GetConnectionOptions = { type: 'read', useMaster: false };
const connection = await sequelize.connectionManager.getConnection(options);
await sequelize.connectionManager.releaseConnection(connection);| Option | Type | Description |
|---|---|---|
type | "SELECT" | "read" | "write" | 'read' takes a read replica when one is configured. Default 'write'. 'SELECT' is the same as 'read' (v6 passes the query type of a SELECT there). |
useMaster postgrelize extension | boolean | Forces the writer even when type is 'read'. postgrelize extension. |
uuid | string | Transaction id the connection is acquired for; informational (v6 passes it for transactions). |
SyncOptions
Options of sync(): force, alter, match, schema plus the common query options.
const options: SyncOptions = { alter: true, match: /_test$/, schema: 'tenant_1' };
await sequelize.sync(options);| Option | Type | Description |
|---|---|---|
transaction | Transaction | Transaction to run in; null forces running outside the CLS transaction. |
logging | false | LoggingFunction | SQL logger for this query, or false. |
benchmark | boolean | Pass query duration to the logger. |
statementTimeout postgrelize extension | number | statement_timeout for this query only, in milliseconds (non-negative integer; 0 disables it). PostgreSQL cancels the statement with a DatabaseError (code 57014) when it runs longer. Outside a transaction the query runs in its own short transaction; inside one the previous timeout is restored afterwards. PostgreSQL extension. |
retry | Readonly<{ max?: number | undefined; match?: readonly RetryMatch[] | undefined; backoff… | Retries this query when it fails, merged over the instance retry option (Sequelize v6). The connection acquisition is part of the retried work; a query that runs in a transaction is never retried. |
useMaster postgrelize extension | boolean | Force the writer even for SELECTs when read replicas are configured. postgrelize extension. |
replacements | Replacements | Values of ? (array) or :name (object) placeholders written in raw SQL inside the options (where: literal('"a" = :a'), attributes: [[literal(...), 'x']]), as in Sequelize v6. Every value is sent as a bound parameter, never concatenated into the SQL text; arrays expand to a comma separated list of parameters. |
force | boolean | Drop and re-create tables. |
alter | boolean | Readonly<{ drop?: boolean | undefined; }> | Alter existing tables to match models; { drop: false } keeps extra columns. |
match | RegExp | Only sync when the database name matches this pattern. |
schema | string | Create the tables in this schema instead of the models' schema (references stay in it too). |
hooks | boolean | Run the beforeSync / afterSync hooks. Default true. |
DropOptions
Options of drop(): cascade, schema plus the common query options.
const options: DropOptions = { cascade: true, schema: 'tenant_1' };
await sequelize.drop(options);| Option | Type | Description |
|---|---|---|
transaction | Transaction | Transaction to run in; null forces running outside the CLS transaction. |
logging | false | LoggingFunction | SQL logger for this query, or false. |
benchmark | boolean | Pass query duration to the logger. |
statementTimeout postgrelize extension | number | statement_timeout for this query only, in milliseconds (non-negative integer; 0 disables it). PostgreSQL cancels the statement with a DatabaseError (code 57014) when it runs longer. Outside a transaction the query runs in its own short transaction; inside one the previous timeout is restored afterwards. PostgreSQL extension. |
retry | Readonly<{ max?: number | undefined; match?: readonly RetryMatch[] | undefined; backoff… | Retries this query when it fails, merged over the instance retry option (Sequelize v6). The connection acquisition is part of the retried work; a query that runs in a transaction is never retried. |
useMaster postgrelize extension | boolean | Force the writer even for SELECTs when read replicas are configured. postgrelize extension. |
replacements | Replacements | Values of ? (array) or :name (object) placeholders written in raw SQL inside the options (where: literal('"a" = :a'), attributes: [[literal(...), 'x']]), as in Sequelize v6. Every value is sent as a bound parameter, never concatenated into the SQL text; arrays expand to a comma separated list of parameters. |
cascade | boolean | DROP TABLE ... CASCADE. |
schema | string | Drop the tables in this schema instead of the models' schema. |