Skip to content

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.

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.

ts
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);
OptionTypeDescription
dialect"postgres"Must be 'postgres' when given.
databasestringDatabase name.
usernamestringUser name.
passwordstringPassword.
hoststringHost. Default 'localhost'.
portnumberPort. Default 5432.
sslboolean | ConnectionOptionsSSL settings passed to pg.
dialectOptionsReadonly<Omit<PoolConfig, "types">>Extra options passed to the pg pool/client as is.
dialectModuleobjectAccepted for Sequelize v6 type compatibility; postgrelize ignores it and always loads pg. Default: undefined.
poolReadonly<{ max?: number | undefined; min?: number | undefined; idle?: number | undefine…Pool settings.
loggingfalse | LoggingFunctionSQL logger, or false to disable. Default console.log.
benchmarkbooleanPass query duration to the logger.
timezonestringSession time zone. Default '+00:00'.
defineReadonly<{ timestamps?: boolean | undefined; underscored?: boolean | undefined; freezeT…Defaults for all models.
replicationReadonly<{ read: Readonly<{ host?: string | undefined; port?: number | undefined; usern…Read replicas and writer (Sequelize v6 replication); entries inherit missing connection settings.
hooksPartial<Readonly<Record<"beforeValidate" | "afterValidate" | "validationFailed" | "befo…Sequelize-level hooks run for every model (and beforeConnect).
minifyAliasesbooleanShorten 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.
retryReadonly<{ 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 extensionnumberMinimum IN-list length compiled to = ANY($n). Default 100. PostgreSQL extension.
statementCache postgrelize extensionboolean | 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.

ts
const pool: PoolOptions = { max: 10, idle: 10_000, acquire: 30_000 };
const db = new Sequelize('postgres://user:pass@localhost:5432/app', { pool });
OptionTypeDescription
maxnumberMaximum number of connections. Default 5.
minnumberMinimum number of connections. Accepted for compatibility; pg does not keep idle minimums.
idlenumberMilliseconds a connection may be idle before release. Default 10000.
acquirenumberMilliseconds to wait for a connection before throwing ConnectionAcquireTimeoutError. Default 60000.
evictnumberAccepted for compatibility; eviction is handled by idle.
maxUsesnumberMaximum 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.

ts
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 });
OptionTypeDescription
readReadonly<{ host?: string | undefined; port?: number | undefined; username?: string | un…Reader(s).
writeReadonly<{ 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.

ts
const retry: RetryOptions = {
  max: 5,
  match: [/SequelizeConnectionRefusedError/, 'ECONNRESET'],
  backoffBase: 100,
  backoffExponent: 1.1,
};
const db = new Sequelize('postgres://user:pass@localhost:5432/app', { retry });
OptionTypeDescription
maxnumberMaximum number of attempts, the first one included. Without it nothing is retried.
matchreadonly RetryMatch[]Errors worth retrying. An empty or missing list retries every error, so list the errors you mean (for example [/SequelizeConnectionError/]).
backoffBasenumberDelay before the first retry in milliseconds. Default 100.
backoffExponentnumberGrowth of the delay per retry: backoffBase * backoffExponent ** (attempt - 1). Default 1.1.
backoffJitternumberRandom variation added to or subtracted from each delay, in milliseconds. Default 0.
timeoutnumberRejects an attempt that takes longer than this many milliseconds, without retrying it.
namestringName 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.

ts
const db = new Sequelize('postgres://user:pass@localhost:5432/app', { statementCache: { max: 50 } });
OptionTypeDescription
maxnumberMaximum 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.

ts
const rows = await sequelize.query('SELECT * FROM users WHERE id = :id', {
  type: QueryTypes.SELECT,
  replacements: { id: 1 },
  model: User,
  mapToModel: true,
});
OptionTypeDescription
transactionTransactionTransaction to run in; null forces running outside the CLS transaction.
loggingfalse | LoggingFunctionSQL logger for this query, or false.
benchmarkbooleanPass query duration to the logger.
statementTimeout postgrelize extensionnumberstatement_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.
retryReadonly<{ 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 extensionbooleanForce the writer even for SELECTs when read replicas are configured. postgrelize extension.
replacementsReplacementsValues 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.
typeQueryTypeShapes the result; default RAW.
bindBindParametersValues for $1 / $name placeholders.
plainbooleanReturn only the first row (or null).
modelModelStatic<AnyModel>Build instances of this model from SELECT rows.
mapToModelbooleanMap column names to attribute names of model.
rawbooleanReturn plain rows even with model.
nestbooleanNests 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.

ts
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();
OptionTypeDescription
isolationLevelIsolationLevelIsolation level of a new transaction.
type"DEFERRED" | "IMMEDIATE" | "EXCLUSIVE"Accepted for compatibility, ignored.
readOnly postgrelize extensionbooleanStart READ ONLY. PostgreSQL extension.
deferrable postgrelize extensionboolean | 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.
transactionTransactionParent transaction: the new transaction becomes a savepoint inside it.
settings postgrelize extensionReadonly<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.
loggingfalse | LoggingFunctionSQL logger for transaction statements.
retryReadonly<{ 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).

ts
const options: GetConnectionOptions = { type: 'read', useMaster: false };
const connection = await sequelize.connectionManager.getConnection(options);
await sequelize.connectionManager.releaseConnection(connection);
OptionTypeDescription
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 extensionbooleanForces the writer even when type is 'read'. postgrelize extension.
uuidstringTransaction 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.

ts
const options: SyncOptions = { alter: true, match: /_test$/, schema: 'tenant_1' };
await sequelize.sync(options);
OptionTypeDescription
transactionTransactionTransaction to run in; null forces running outside the CLS transaction.
loggingfalse | LoggingFunctionSQL logger for this query, or false.
benchmarkbooleanPass query duration to the logger.
statementTimeout postgrelize extensionnumberstatement_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.
retryReadonly<{ 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 extensionbooleanForce the writer even for SELECTs when read replicas are configured. postgrelize extension.
replacementsReplacementsValues 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.
forcebooleanDrop and re-create tables.
alterboolean | Readonly<{ drop?: boolean | undefined; }>Alter existing tables to match models; { drop: false } keeps extra columns.
matchRegExpOnly sync when the database name matches this pattern.
schemastringCreate the tables in this schema instead of the models' schema (references stay in it too).
hooksbooleanRun the beforeSync / afterSync hooks. Default true.

DropOptions ​

Options of drop(): cascade, schema plus the common query options.

ts
const options: DropOptions = { cascade: true, schema: 'tenant_1' };
await sequelize.drop(options);
OptionTypeDescription
transactionTransactionTransaction to run in; null forces running outside the CLS transaction.
loggingfalse | LoggingFunctionSQL logger for this query, or false.
benchmarkbooleanPass query duration to the logger.
statementTimeout postgrelize extensionnumberstatement_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.
retryReadonly<{ 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 extensionbooleanForce the writer even for SELECTs when read replicas are configured. postgrelize extension.
replacementsReplacementsValues 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.
cascadebooleanDROP TABLE ... CASCADE.
schemastringDrop the tables in this schema instead of the models' schema.

Released under the MIT License.