# postgrelize > PostgreSQL-only ORM for Node.js and TypeScript that implements the Sequelize v6 public API (drop-in) and adds PostgreSQL features: ON CONFLICT upserts, MERGE, CTEs, COPY, LISTEN/NOTIFY, advisory locks, read replicas, RETURNING old values. # Guide and reference ## Getting started Source: https://tormozz48.github.io/postgrelize/guide/getting-started postgrelize is an ORM for Node.js that implements the [Sequelize v6](https://sequelize.org/docs/v6/) public API for PostgreSQL only. Code written for Sequelize v6 on PostgreSQL runs unchanged in most cases. On top of that, postgrelize exposes PostgreSQL features that Sequelize cannot express: `ON CONFLICT` upserts with expressions, `MERGE`, CTEs, `COPY`, `LISTEN/NOTIFY` and more. ### Requirements - Node.js 20 or newer (CI tests Node 20, 22 and 24) - PostgreSQL 16, 17 or 18 (some features need a newer server; each page says so) - the [`pg`](https://node-postgres.com/) driver ### Install Install the package from npmjs.com together with `pg`: ```bash npm install postgrelize pg ``` Imports read `from 'postgrelize'`, as in every example of this guide. The old GitHub Packages name `@tormozz48/postgrelize` is deprecated. ### Connect Create one `Sequelize` instance per database and share it across your application. It accepts a connection URI or the usual Sequelize options: ```ts import { Sequelize } from 'postgrelize'; const sequelize = new Sequelize(process.env.DATABASE_URL!, { logging: false, pool: { max: 10 }, }); await sequelize.authenticate(); // throws a ConnectionError subclass when the server is unreachable ``` The constructor also takes `(database, username, password, options)` or a single options object with `host`, `port`, `database`, `username`, `password`, `ssl` and `dialectOptions` (passed to the `pg` pool). `dialect` may be omitted; any value other than `'postgres'` is rejected. The session time zone defaults to UTC (`timezone: '+00:00'`), as in Sequelize v6. Call `sequelize.close()` when the process shuts down. ### Define a model and query it Models are TypeScript classes. `InferAttributes` and `InferCreationAttributes` derive the attribute types from the `declare`d fields; `CreationOptional` marks attributes that the database fills in. ```ts import { DataTypes, Model, Op, type Sequelize } from 'postgrelize'; import type { CreationOptional, InferAttributes, InferCreationAttributes } from 'postgrelize'; ``` ```ts class User extends Model, InferCreationAttributes> { declare id: CreationOptional; declare email: string; declare active: CreationOptional; } User.init( { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, email: { type: DataTypes.STRING, allowNull: false, unique: true }, active: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true }, }, { sequelize }, ); await sequelize.sync(); ``` `sequelize.sync()` creates missing tables. Use it in tests and prototypes; production schemas are usually managed with migrations (see [Schema, sync and migrations](./schema)). The familiar Sequelize v6 methods work as before: ```ts const ann = await User.create({ email: 'ann@example.com' }); await User.bulkCreate([ { email: 'bob@example.com' }, { email: 'eve@example.com', active: false }, ]); const active = await User.findAll({ where: { active: true }, order: [['email', 'ASC']] }); const count = await User.count({ where: { email: { [Op.iLike]: '%@example.com' } } }); ann.active = false; await ann.save(); await User.destroy({ where: { active: false } }); ``` Every example in this guide is executed against PostgreSQL in CI, so the code you see is code that runs. ### Logging `logging` takes a function receiving each SQL statement (or `false`). With `benchmark: true` the function also receives the execution time in milliseconds. Statements inside a transaction are prefixed with the transaction id: ```ts const sequelize = new Sequelize(url, { logging: (sql) => logger.debug(sql) }); // Executing (default): SELECT ... // Executing (6f1c...): INSERT INTO ... ``` All values are sent as bound parameters (`$1`, `$2`, ...), never interpolated into the SQL text. ### Errors Errors are the Sequelize v6 classes, exported from the package root: `ValidationError`, `UniqueConstraintError`, `ForeignKeyConstraintError`, `ExclusionConstraintError`, `DatabaseError`, `TimeoutError`, `ConnectionRefusedError` and the other `ConnectionError` subclasses, `EmptyResultError`, `OptimisticLockError`. Check them with `instanceof`: ```ts import { UniqueConstraintError } from 'postgrelize'; try { await User.create({ email: 'ann@example.com' }); } catch (error) { if (error instanceof UniqueConstraintError) { // error.fields: { email: 'ann@example.com' } } } ``` ### Next steps - Coming from Sequelize? Read [Migrating from Sequelize](./migrating). - Learn the Sequelize v6 API as implemented here: [Models and data types](./models), [Querying](./querying), [Associations](./associations). - See what PostgreSQL adds: [Upserts and RETURNING](./upserts), [Bulk writes and COPY](./bulk-writes), [Advanced queries](./advanced-queries), [Sessions and scaling](./sessions). - Browse the [API reference](/api/). ## Migrating from Sequelize Source: https://tormozz48.github.io/postgrelize/guide/migrating postgrelize implements the public API of Sequelize v6 for PostgreSQL. A differential test suite runs the same scenarios on `sequelize@6` and on postgrelize and compares the results, so for most applications migrating is a change of the package name. ### 1. Replace the packages Remove `sequelize` and `pg-hstore` (postgrelize does not use it), and install postgrelize from npmjs.com: ```bash npm uninstall sequelize pg-hstore npm install postgrelize pg ``` If you installed the deprecated GitHub Packages name `@tormozz48/postgrelize` (or the alias `postgrelize@npm:@tormozz48/postgrelize`), remove the `.npmrc` scope line, run `npm uninstall @tormozz48/postgrelize` and install `postgrelize` as above. Imports from `'@tormozz48/postgrelize'` become `'postgrelize'`; the API is identical. ### 2. Update imports Replace `'sequelize'` with `'postgrelize'`. The exported names are the same as in Sequelize v6: ```ts // before import { DataTypes, Model, Op, Sequelize, Transaction } from 'sequelize'; // after import { DataTypes, Model, Op, Sequelize, Transaction } from 'postgrelize'; ``` The package ships ES modules and CommonJS. As in v6, the default export and `require('postgrelize')` are the `Sequelize` class (`import Sequelize from 'postgrelize'`, `const Sequelize = require('postgrelize')`, `new Sequelize(url)`), and every named export is also a property of it (`require('postgrelize').DataTypes`). One CommonJS difference: `require('postgrelize').HasOne`, `HasMany`, `BelongsTo` and `BelongsToMany` are the decorators, not v6's association classes. Type helpers (`InferAttributes`, `InferCreationAttributes`, `CreationOptional`, `ForeignKey`, `NonAttribute`, `ModelStatic`, `WhereOptions`, ...) are exported under their v6 names. ### TypeScript types The type API follows the v6 declarations, so code that compiles against `sequelize` compiles against postgrelize: `Model`, `ModelStatic`, `FindOptions`, `Includeable`, the `Sequelize#query` overloads (`query(sql, { type: QueryTypes.SELECT })`), generic `Association` and the association mixin types (`BelongsToGetAssociationMixin`, `HasManyGetAssociationsMixin`, ...). A test compiles a corpus of v6-style code against both libraries and lists the v6 type names and option keys that postgrelize still lacks (`tests/compat/type-parity/exceptions.json`). Differences to know: - `HasMany`, `HasOne`, `BelongsTo` and `BelongsToMany` are exported as generic types next to the decorators of the same names; use `Sequelize.HasMany` (and the others) for the class value. - `InitOptions.name` (`{ singular, plural }`) works as in v6: it gives the default alias and foreign key of `belongsTo`, `hasOne`, `hasMany` and `belongsToMany` and the accessor names (`name: { singular: 'user', plural: 'users' }` makes `Agent.belongsTo(User)` use alias `user` and foreign key `userId`). A missing form falls back to the inflected `modelName`. Before this release the option was ignored. - `onDelete: 'CASCADE'` with `hooks: true` on an association works as in v6: destroying an instance loads the associated rows and destroys each with its own hooks before the row itself is deleted (not for the soft delete of a paranoid model). Without `hooks: true` PostgreSQL cascades the delete and no hooks of the target run. `QueryInterface#queryGenerator` only provides `selectQuery(tableName, options, model)`, which renders finder options to a SQL string (values as escaped literals, no scope or paranoid filter), as in v6; the other v6 generator methods do not exist. - `findAndCountAll({ group })` returns `count` as an array of `{ ...groupedAttributes, count }` like v6 (earlier releases ignored `group` in the count query). - `FindOptions.replacements` works as in v6: `:name` and `?` placeholders inside `literal()` (in `where`, `attributes`, `order`, ...) of `findAll`, `findOne`, `findByPk`, `count` and `findAndCountAll` are substituted and written into the SQL text as escaped literals, as in v6, so a placeholder used in `SELECT` and `GROUP BY` gives identical expressions (1.6.0; ADR-037). Unlike v6, `update` and `destroy` accept `replacements` too (v6 rejects them for `update`). Before 1.3.0 the finders ignored the option. - `Model#reload(options)` takes the finder options (`include`, `attributes`, `paranoid`, `lock`, `hooks`, ...) and reads the row through `findOne`, so default scopes and `paranoid` apply as in v6: reloading a soft-deleted row needs `paranoid: false`. Associations the instance was built with are not reloaded unless you pass `include`. - `findByPk(id, { rejectOnEmpty: true })` resolves to the model (not `M | null`), as `findOne` does. - `sequelize.query` accepts a string or a `literal()`, not the v6 `{ query, values }` object form. - Option keys that postgrelize does not implement (`searchPath`, `omitNull`, ...) are not in the option types, so the compiler points at them. - `Model.sequelize` and `instance.sequelize` are typed `Sequelize` (not optional, it throws on a model that is not initialized), `WhereAttributeHash` defaults to `any`, attribute `get` / `set` and model-level `validate` functions can be written with a typed `this` and a callback style `next`, and the parameters of hook functions are `any` so an unannotated hook compiles. ### 3. Check the connection options - Only PostgreSQL is supported. Omit `dialect` or set it to `'postgres'`; any other value throws. - `dialectOptions` is passed to the [`pg`](https://node-postgres.com/) pool as is. - `pool` accepts `max`, `min`, `idle`, `acquire`, `evict` and `maxUses`. `min` and `evict` are accepted for compatibility but have no effect: `pg` does not keep idle connections open. - `retry` (instance option and per-query / per-transaction option) is supported with the v6 fields and matching rules; it is off by default, as v6's default only lists a SQLite message. Statements inside an open transaction are not retried (v6 retries them). See [Retrying failed queries](/guide/sessions#retrying-failed-queries). - `sequelize.connectionManager` exposes `getConnection(options?)`, `releaseConnection(connection)`, `destroyConnection(connection)` and the `pool` counters (`size`, `available`, `using`, `waiting`, `maxSize`), and you can reassign the first two on the instance to route connections, as in v6. With `replication`, `pool` carries the totals plus `read` and `write` counters (v6 has no totals there), and `getConnection({ type: 'read' })` reaches a replica (v6 reaches it only for `'SELECT'`). The other v6 members (`initPools`, `close`, `refreshTypeParser`, `pool.acquire` / `pool.drain`, ...) are not provided. See [Routing connections](/guide/sessions#routing-connections). - `minifyAliases: true` works as in v6 for include aliases, see [Associations](./associations#eager-loading). - `replication: { read, write }` works as in v6, see [Sessions and scaling](./sessions#read-replicas). ### 4. Run your tests Things that behave the same as in Sequelize v6 include model definition (`init`, `define`), all finders, `create`/`bulkCreate`/`upsert`/`update`/`destroy`, instance methods and change tracking, hooks, validators, scopes, paranoid models, optimistic locking, associations with `include` and accessors, nested creation with `include`, managed and unmanaged transactions with savepoints and CLS (`Sequelize.useCLS()` and `Sequelize.useCLS(namespace)` with a `cls-hooked` namespace), `QueryInterface` and `sync`. Value conventions follow v6 too: `BIGINT` and `DECIMAL` values are strings, and `upsert` returns `[instance, null]` because PostgreSQL does not report whether a row was inserted (use the [`onConflict` option](./upserts) to get a boolean). ### Intentional differences Some Sequelize v6 behaviours are bugs on PostgreSQL. postgrelize fixes them instead of copying them, for example: - JSON `where` keys containing `,`, `"` or `\` are matched correctly. - `upsert` on a partial unique index uses the index predicate. - `sync({ alter: true })` keeps the sequence of non-key `autoIncrement` columns. - `describeTable`, `showAllTables` and `tableExists` default to `current_schema()` instead of `public`, so they respect `search_path`. - `findCreateFind` inside a transaction inserts in a savepoint: when another session inserted the row first it returns that row with `created: false`; v6 returns an unsaved instance with `created: true`. - `order: ['json.path']` orders by the jsonb value (numbers sort numerically). - Foreign-key cycles in `sync()` are created after all tables exist instead of being skipped. The full list, with the Sequelize issue numbers and regression tests, is on [Sequelize issues fixed in postgrelize](/sequelize-issues). If your code depends on one of these v6 behaviours, it needs a change. ### Not supported These Sequelize v6 features are not implemented: | Feature | What to do instead | | -------------------------------------- | ----------------------------------------------------------------------------------------------------- | | Other dialects (MySQL, SQLite, MSSQL…) | postgrelize is PostgreSQL only. | | `searchPath` query / connection option | Set `search_path` with `dialectOptions: { options: '-c search_path=tenant' }`. | | Named or shared `ENUM` types | Each `ENUM` attribute gets its own type, `enum__`, as v6 does by default. | | `create({ ignoreDuplicates })` | `create(values, { onConflict: { action: 'nothing' } })` or `bulkCreate([...], { ignoreDuplicates })`. | | Sequelize v7 (`@sequelize/core`) API | Not planned. | Hooks are accepted for every v6 hook name, but model lifecycle hooks, `beforeConnect`, `afterConnect`, the sync hooks (`beforeBulkSync`, `afterBulkSync`, `beforeSync`, `afterSync`), the define hooks of the instance (`beforeDefine`, `afterDefine`) and the static `Sequelize.beforeInit` / `Sequelize.afterInit` run; the other connection hooks and `beforeQuery`, `beforeAssociate`, ... are registered and never called. See [Hooks and validation](./hooks-validation). ### API differences postgrelize is checked against the public API of Sequelize v6.37 (`Sequelize`, `Model`, `QueryInterface`, `Transaction`, `DataTypes` and the exports): a test fails when a v6 name is missing and not listed here. The list below is generated from `tests/compat/api-surface-exceptions.json` and only shrinks. | Surface | Status | Names | | ---------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Sequelize` statics | Not planned | `ABSTRACT`, `UUIDV1` | | `Sequelize` statics | Other dialects only | `IndexHints`, `TableHints`, `db2`, `mariadb`, `mssql`, `mysql`, `oracle`, `postgres`, `snowflake`, `sqlite` | | `Sequelize` statics | v6 internals | `AsyncQueueError`, `Sequelize`, `default` | | `Sequelize` instance | Not planned | `afterAssociate`, `afterDefine`, `afterDisconnect`, `afterInit`, `afterPoolAcquire`, `afterQuery`, `beforeAssociate`, `beforeDefine`, `beforeDisconnect`, `beforeInit`, `beforePoolAcquire`, `beforeQuery` | | `Sequelize` instance | Other dialects only | `set` | | `Sequelize` instance | v6 internals | `Sequelize`, `dialect`, `normalizeAttribute`, `normalizeDataType` | | `Model` statics | Not planned | `afterAssociate`, `afterBulkSync`, `afterQuery`, `beforeAssociate`, `beforeBulkSync`, `beforeQuery` | | `Model` statics | v6 internals | `Mixin`, `default`, `queryGenerator`, `warnOnInvalidOptions` | | `Model` instance | Not planned | `addHook`, `hasHook`, `hasHooks`, `removeHook`, `runHooks`, `setValidators` | | `Transaction` statics | v6 internals | `Transaction`, `default` | | `Transaction` instance | v6 internals | `cleanup`, `forceCleanup`, `prepareEnvironment`, `setDeferrable` | | `QueryInterface` | Not planned | `commitTransaction`, `decrement`, `delete`, `increment`, `insert`, `rawSelect`, `rollbackTransaction`, `select`, `setIsolationLevel`, `startTransaction`, `update`, `upsert` | | `QueryInterface` | v6 internals | `ensureEnums`, `normalizeAttribute`, `pgListEnums` | | `DataTypes` | Not planned | `ABSTRACT`, `UUIDV1` | | `DataTypes` | Other dialects only | `db2`, `mariadb`, `mssql`, `mysql`, `oracle`, `postgres`, `snowflake`, `sqlite` | | Module exports | Not planned | `ABSTRACT`, `UUIDV1` | | Module exports | Other dialects only | `IndexHints`, `TableHints` | | Module exports | v6 internals | `AsyncQueueError` | ### Using the PostgreSQL extensions Once the application runs on postgrelize, you can replace workarounds with native features step by step: - `literal()`-based upserts and `updateOnDuplicate` → [`onConflict` and `Model.insert`](./upserts) - loops of `update` → [`UPDATE ... FROM` and `MERGE`](./bulk-writes) - large `bulkCreate` imports → [`COPY`](./bulk-writes#copy) - `sequelize.query` with hand-written CTEs and window functions → [advanced queries](./advanced-queries) Extensions are additive: they are new options or new methods, and none of them changes the behaviour of v6 calls. ## Models and data types Source: https://tormozz48.github.io/postgrelize/guide/models Models work as in Sequelize v6: extend `Model` and call `init`, or use `sequelize.define`. Both forms accept the same attribute and model options. ### Class models Declare attributes with `declare` so TypeScript knows their types without emitting class fields that would shadow the attribute getters. `InferAttributes` collects the declared fields; `InferCreationAttributes` additionally makes `CreationOptional` fields optional in `create` and `build`. ```ts class Product extends Model, InferCreationAttributes> { declare id: CreationOptional; declare sku: string; declare name: string; declare tags: CreationOptional; declare attrs: CreationOptional>; declare status: CreationOptional<'draft' | 'live'>; declare label: CreationOptional; } Product.init( { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, sku: { type: DataTypes.STRING(32), allowNull: false, unique: true, set(this: Product, value: string) { this.setDataValue('sku', value.toUpperCase()); }, }, name: { type: DataTypes.TEXT, allowNull: false }, tags: { type: DataTypes.ARRAY(DataTypes.TEXT), allowNull: false, defaultValue: [] }, attrs: { type: DataTypes.JSONB, allowNull: false, defaultValue: {} }, status: { type: DataTypes.ENUM('draft', 'live'), allowNull: false, defaultValue: 'draft' }, label: { type: DataTypes.VIRTUAL, get(this: Product) { return `${this.sku} ${this.name}`; }, }, }, { sequelize, tableName: 'products', underscored: true }, ); ``` The example shows: - a custom setter (`set`) that normalizes the value before it is stored, using `setDataValue`; - a `VIRTUAL` attribute with a getter: it is never stored, but is part of `get()` and `toJSON()`; - `ARRAY`, `JSONB` and `ENUM` columns with defaults; - `underscored: true`, which maps `createdAt` to `created_at` and so on, and `tableName` to skip pluralization. Other type helpers from v6 are available: `ForeignKey` for foreign key attributes created by associations, and `NonAttribute` for class fields that are not columns (for example, included associations). ### Decorators Models can also be declared with decorators (`@Table`, `@Column`, `@HasMany`, …) and registered with `sequelize.addModels`; see [Decorators](/guide/decorators). ### `sequelize.define` `define` returns a model class without static attribute types. It is convenient in scripts and tests: ```ts const Order = sequelize.define( 'Order', { number: { type: DataTypes.TEXT, allowNull: false }, placedAt: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW }, }, { paranoid: true }, ); ``` `paranoid: true` adds `deletedAt`: `destroy()` sets it instead of deleting the row, finders skip such rows, and `paranoid: false` in find options includes them. `restore()` brings them back; `destroy({ force: true })` deletes for real. ### Using instances ```ts const product = await Product.create({ sku: 'ab-1', name: 'Anvil', tags: ['heavy'] }); product.attrs = { color: 'black' }; await product.save(); const line = await Line.create({ price: '2.50', qty: 4, period: '1 year 2 mons' }); // line.get('id') === '1' (BIGINT is returned as a string), line.get('total') === '10.00' ``` Instances track changes as in v6: `changed()`, `previous()`, `save()` writes only changed attributes, `reload()` reads the row again, and `toJSON()` returns plain values. Like v6, an attribute that was assigned a different value stays in `changed()` even when you set it back to the stored value. `create` and `bulkCreate` accept `fields` to restrict which attributes are written. As in v6, the timestamps (`createdAt`, `updatedAt`), the version attribute and primary keys with a default are added to the list for you: ```ts const partial = await Product.create( { sku: 'cd-2', name: 'Anchor', status: 'live' }, { fields: ['sku', 'name'] }, ); // `status` is not written: the column default applies; timestamps are added for you ``` `Model.schema(name)` returns a copy of the model whose queries target another PostgreSQL schema, e.g. one per tenant. `getTableName()` of the copy returns `{ tableName, schema, delimiter }`; the copy keeps the scope selection of the model it was made from, and `unscoped()` / `scope()` work on it. Hooks, scopes and associations are copied when `schema()` is called; later changes to the original are not seen by the copy. ```ts await sequelize.createSchema('tenant_a'); const TenantOrder = Order.schema('tenant_a'); await TenantOrder.sync(); await TenantOrder.create({ number: 'T-1' }); const tenantCount = await TenantOrder.count(); // counts "tenant_a"."Orders" only ``` ### Data types `DataTypes` contains the Sequelize v6 types that PostgreSQL supports: | Category | Types | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | Text | `STRING(n)` (`VARCHAR`), `CHAR(n)`, `TEXT`, `CITEXT` | | Numbers | `INTEGER`, `SMALLINT`, `BIGINT`, `FLOAT`, `REAL`, `DOUBLE`, `DECIMAL(p, s)` | | Date and time | `DATE` (`TIMESTAMP WITH TIME ZONE`), `TIMESTAMP`, `DATEONLY`, `TIME`, `INTERVAL` | | Other scalars | `BOOLEAN`, `UUID`, `BLOB` (`BYTEA`), `INET`, `CIDR`, `MACADDR`, `MACADDR8`, `MONEY`, `XML`, `BIT(n)`, `VARBIT(n)`, `LTREE`, `TSVECTOR`, `TSQUERY` | | Structured | `JSON`, `JSONB`, `HSTORE`, `ARRAY(type)`, `RANGE(type)`, `ENUM(...values)` | | PostGIS | `GEOMETRY`, `GEOGRAPHY` | | Not stored | `VIRTUAL` | | Default values | `DataTypes.NOW` (current time), `DataTypes.UUIDV4` (random UUID generated in Node.js) | As in v6, `BIGINT` and `DECIMAL` values are returned as strings to avoid precision loss. `INTERVAL` values are strings in PostgreSQL output format (`'1 year 2 mons'`). `RANGE` values are arrays of two bounds, `{ value, inclusive }` objects as in v6. `ENUM` creates a PostgreSQL enum type named `enum_
_`. `sync({ alter: true })` adds new values to an existing enum type. ### PostgreSQL-specific types Types marked (postgrelize extension) do not exist in Sequelize v6. ```ts const Asset = sequelize.define( 'Asset', { attrs: DataTypes.HSTORE, path: DataTypes.LTREE, price: DataTypes.MONEY, mac: DataTypes.MACADDR8, manifest: DataTypes.XML, flags: DataTypes.BIT(4), mask: DataTypes.VARBIT(16), filter: DataTypes.TSQUERY, seenAt: DataTypes.TIMESTAMP, }, { timestamps: false }, ); await sequelize.sync(); ``` ```ts await Asset.create({ attrs: { color: 'red', note: null }, path: 'Top.Science.Astronomy', price: 12.5, mac: '08:00:2b:01:02:03:04:05', manifest: '1', flags: '1010', mask: '101', filter: "'fat' & 'rat'", seenAt: new Date(2024, 0, 2, 3, 4, 5), }); const found = await Asset.findOne({ where: { attrs: { [Op.contains]: { color: 'red' } } } }); const descendants = await Asset.count({ where: literal("path <@ 'Top.Science'") }); ``` - (postgrelize extension) `HSTORE` operators and `LTREE` are postgrelize additions; `HSTORE` values are objects with string (or `null`) values, like Sequelize v6 with `pg-hstore`; `Op.contains` and `Op.eq` accept objects. Run `CREATE EXTENSION hstore` first. `LTREE` needs `CREATE EXTENSION ltree`; use `literal()` for its operators (`<@`, `@>`, `~`). - (postgrelize extension) `TIMESTAMP` is `TIMESTAMP WITHOUT TIME ZONE`. Values are `Date`s whose local wall-clock time is the stored time, so they depend on the process time zone. - (postgrelize extension) `MONEY` is read as the server formats it (`lc_monetary`, for example `'$12.50'`). Write a number or a string. - (postgrelize extension) `BIT(n)` and `VARBIT(n)` values are strings of `0` and `1`; `BIT` without a length is `BIT(1)`. - (postgrelize extension) `XML`, `MACADDR8` and `TSQUERY` values are strings. #### Geometric types (postgrelize extension) ```ts const Place = sequelize.define( 'Place', { name: DataTypes.STRING, at: DataTypes.POINT, area: DataTypes.BOX, route: DataTypes.PATH, zone: DataTypes.POLYGON, range: DataTypes.CIRCLE, }, { timestamps: false }, ); await sequelize.sync(); ``` ```ts await Place.create({ name: 'depot', at: { x: 1, y: 1 }, area: [ { x: 2, y: 2 }, { x: 0, y: 0 }, ], route: { closed: false, points: [ { x: 0, y: 0 }, { x: 1, y: 1 }, ], }, zone: [ { x: 0, y: 0 }, { x: 4, y: 0 }, { x: 0, y: 4 }, ], range: { x: 1, y: 1, radius: 5 }, }); const inside = await Place.count({ where: { area: { [Op.contains]: cast('(1,1)', 'point') } } }); const near = await Place.count({ where: literal('"at" <-> point(0,0) < 2') }); ``` | Type | Value | | ------------- | ---------------------------------------------------------------------- | | `POINT` | `{ x, y }` | | `LINE` | `{ a, b, c }` (`a·x + b·y + c = 0`) | | `LSEG`, `BOX` | `[Point, Point]` (a box is returned with its upper-right corner first) | | `PATH` | `{ points, closed }` | | `POLYGON` | `Point[]` | | `CIRCLE` | `{ x, y, radius }` | Text literals (`'(1,2)'`) are accepted on write. `Op.contains`, `Op.contained`, `Op.overlap`, `Op.strictLeft` and `Op.strictRight` take the column's own shape; an operand of another type (a point against a box column) is a text literal wrapped in `cast('(1,1)', 'point')`. Distance (`<->`), intersection (`?#`) and the geometric functions go through `literal()` or `fn()`. `point` has no `=` operator in PostgreSQL (use `~=`). #### Multirange types (postgrelize extension) ```ts const Shift = sequelize.define( 'Shift', { worker: DataTypes.STRING, hours: DataTypes.MULTIRANGE(DataTypes.INTEGER), }, { timestamps: false }, ); await sequelize.sync(); ``` ```ts await Shift.create({ worker: 'ann', hours: [ [8, 12], [13, 17], ], }); await Shift.create({ worker: 'bob', hours: [[18, 22]] }); const working = await Shift.findAll({ where: { hours: { [Op.contains]: cast('9', 'int4') } }, }); const evening = await Shift.count({ where: { hours: { [Op.overlap]: [[20, 24]] } } }); ``` `DataTypes.MULTIRANGE(subtype)` needs PostgreSQL 14+. The subtype is `INTEGER` (`int4multirange`), `BIGINT`, `DECIMAL`, `TIMESTAMP` (`tsmultirange`), `DATE` (`tstzmultirange`) or `DATEONLY`. A value is an array of ranges; each range is a `[lower, upper]` pair as for `RANGE` (plain values or `{ value, inclusive }` bounds); `[]` is the empty multirange. `Op.contains`, `Op.contained`, `Op.overlap`, `Op.strictLeft`, `Op.strictRight`, `Op.adjacent` and the other range operators apply; an element operand (`multirange @> int`) is wrapped in `cast('9', 'int4')`. `range_agg`, `unnest` and the other multirange functions go through `fn()`. #### Composite types (postgrelize extension) ```ts const address = DataTypes.COMPOSITE('address', { street: DataTypes.TEXT, zip: DataTypes.INTEGER, verified: DataTypes.BOOLEAN, }); await sequelize.query(address.createSql()); const Customer = sequelize.define( 'Customer', { name: DataTypes.STRING, home: address }, { timestamps: false }, ); await sequelize.sync(); ``` ```ts await Customer.create({ name: 'ann', home: { street: 'Main St, 1', zip: 12345, verified: true }, }); const found = await Customer.findOne({ where: { home: { [Op.eq]: { street: 'Main St, 1', zip: 12345, verified: true } } }, }); ``` `DataTypes.COMPOSITE(name, fields)` maps a `CREATE TYPE … AS (…)` type to an object keyed by field name; each field is converted by its own data type (`NULL` is `null`; numbers, booleans, `Date`, `Buffer`, JSON and nested composites are supported, array fields are not). The type must exist: `createSql()` returns its `CREATE TYPE` statement (name and field names quoted), which you run once with `sequelize.query()`; `sync()` does not create it. `where` values compare the whole row (`Op.eq`); single fields go through `literal('("home").zip = 12345')`. #### Identity, generated and interval columns (postgrelize extension) {#identity-generated} Column kinds that Sequelize v6 cannot create: ```ts const Line = sequelize.define( 'Line', { id: { type: DataTypes.BIGINT, primaryKey: true, identity: 'always' }, price: { type: DataTypes.DECIMAL(10, 2), allowNull: false }, qty: { type: DataTypes.INTEGER, allowNull: false }, total: { type: DataTypes.DECIMAL(12, 2), generated: { as: literal('"price" * "qty"') } }, period: DataTypes.INTERVAL, }, { timestamps: false }, ); ``` - `identity: 'always'` or `'byDefault'` creates `GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY` instead of `SERIAL`. To write an explicit value into a `GENERATED ALWAYS` column (for example when importing rows with their ids), pass `overriding: 'system'` to `create`, `bulkCreate`, `upsert` or `insert`; `overriding: 'user'` makes a `BY DEFAULT` column ignore the supplied value. ```ts const imported = await Line.create( { id: '500', price: '1.00', qty: 1 }, { overriding: 'system' }, ); // GENERATED ALWAYS rejects an explicit id unless `overriding` says so ``` - `generated: { as: expression }` creates a stored generated column. postgrelize never writes it in `INSERT` or `UPDATE` and reads the computed value back after each write. `generated: { as, stored: false }` creates a virtual generated column, which needs PostgreSQL 18. - `INTERVAL` is a plain data type here; Sequelize v6 has no interval type. ### Model options The options of `init` / `define` are the v6 ones: `tableName`, `freezeTableName`, `schema`, `timestamps`, `createdAt` / `updatedAt` / `deletedAt` (rename or disable with `false`), `underscored`, `paranoid`, `version` (optimistic locking), `indexes`, `hooks`, `scopes`, `defaultScope`, `validate`. postgrelize adds: - `validationSchema`: a [Standard Schema](./hooks-validation#standard-schema) validating the whole row; - `whereMergeStrategy: 'and'` for scopes, see [Querying](./querying#scopes). Defaults for all models go into the `define` option of the `Sequelize` constructor, e.g. `new Sequelize(url, { define: { underscored: true } })`. ### API reference - [`Model`](/api/classes/Model) - [`DataTypes`](/api/variables/DataTypes) - [`AttributeOptions`](/api/type-aliases/AttributeOptions), [`InitOptions`](/api/type-aliases/InitOptions) ## Querying Source: https://tormozz48.github.io/postgrelize/guide/querying Finders, `where` operators, ordering, grouping, aggregates, scopes and raw queries follow Sequelize v6. This page shows the common patterns and the PostgreSQL-specific operators. For subqueries, CTEs and window functions see [Advanced queries](./advanced-queries). The examples use this model: ```ts const Item = sequelize.define('Item', { code: DataTypes.TEXT, qty: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 }, attrs: DataTypes.JSONB, tags: DataTypes.ARRAY(DataTypes.TEXT), }); ``` ### Filtering `where` takes attribute hashes, `Op` operators, `Op.and` / `Op.or` / `Op.not`, and nested JSON paths with dotted keys: ```ts const red = await Item.findAll({ where: { 'attrs.color': 'red' } }); const big = await Item.findAll({ where: { [Op.or]: [{ qty: { [Op.gte]: 2 } }, { code: { [Op.iLike]: 'A%' } }] }, order: [['qty', 'DESC']], }); const withSize = await Item.count({ where: { attrs: { [Op.hasKey]: 'size' } } }); const notA = await Item.count({ where: { code: { [Op.isDistinctFrom]: 'a' } } }); const listed = await Item.count({ where: { id: { [Op.any]: [1, 3] } } }); ``` Supported operators are the v6 ones for PostgreSQL: comparison (`eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `between`, `notBetween`), lists (`in`, `notIn`, `any`, `all`), text (`like`, `iLike`, `startsWith`, `endsWith`, `substring`, `regexp`, `iRegexp` and their negations), `is` / `not`, arrays and ranges (`contains`, `contained`, `overlap`, `adjacent`, `strictLeft`, `strictRight`, `noExtendLeft`, `noExtendRight`), full-text `match`, and `col` for column comparisons. PostgreSQL additions and fixes ( (postgrelize extension) marks what v6 does not have): - (postgrelize extension) `Op.isDistinctFrom` / `Op.isNotDistinctFrom` compare with `IS [NOT] DISTINCT FROM`, which treats `NULL` as a value. - `Op.hasKey`, `Op.hasAnyKeys`, `Op.hasAllKeys` map to the jsonb `?`, `?|` and `?&` operators; they also work on nested JSON paths. - (postgrelize extension) `{ [Op.any]: [1, 3] }` is shorthand for `= ANY($1)` with one array parameter. - `IN` lists with 100 or more values are sent as `= ANY($1)` with a single array parameter instead of one parameter per value. Change the threshold with the `inAsAnyThreshold` constructor option. ```ts const ids = Array.from({ length: 150 }, (_, index) => index + 1); const statements: string[] = []; const longIn = await Item.count({ where: { id: { [Op.in]: ids } }, logging: (_sql, info?: unknown) => statements.push((info as { parameterizedSql: string }).parameterizedSql), }); // 150 values: one array parameter, `"id" = ANY($1)` ``` ### Operator and search helpers (postgrelize extension) PostgreSQL operators that Sequelize v6 leaves to `literal()` have first-class `Op` entries and expression helpers. Every value is a bound parameter; regconfig names, weights and function kinds are validated. **`SIMILAR TO`.** `Op.similarTo` / `Op.notSimilarTo` take an SQL regular expression. `%`, `_`, `|`, `*`, `+`, `?`, `{}`, `()`, `[]` and `\` are pattern syntax: escape them with `\` to match literally. ```ts const sqlPattern = await Doc.findAll({ where: { name: { [Op.similarTo]: '(c|d)%' } }, order, }); ``` **jsonpath.** `Op.jsonPathExists` is `@?`; `@@` for a jsonpath predicate is `where(col('attrs'), Op.match, '$.price > 10')` (use `where()` so the string is not serialized as a JSON value). `jsonbPath(kind, target, path, { vars, silent, tz })` calls `jsonb_path_exists`, `jsonb_path_match`, `jsonb_path_query`, `jsonb_path_query_first` or `jsonb_path_query_array`; `vars` are passed as one bound jsonb parameter. ```ts const exists = await Doc.findAll({ where: { attrs: { [Op.jsonPathExists]: '$.price ? (@ > 10)' } }, }); const withVars = await Doc.findAll({ where: where( jsonbPath('exists', col('attrs'), '$.price ? (@ < $max)', { vars: { max: 10 } }), true, ), }); ``` **Network.** `Op.containedOrEqual` (`<<=`) and `Op.containsOrEqual` (`>>=`) are new; `<<`, `>>` and `&&` are `Op.strictLeft`, `Op.strictRight` and `Op.overlap`. `host()`, `network()` and the other functions go through `fn()`. ```ts const inSubnet = await Doc.findAll({ where: { ip: { [Op.containedOrEqual]: '10.0.0.0/8' } } }); ``` **Full-text search.** `toTsVector`, `toTsQuery`, `plainToTsQuery`, `phraseToTsQuery` and `websearchToTsQuery` take an optional text search configuration (`'english'`, `'pg_catalog.simple'`). `tsRank` (with `cd`, `weights`, `normalization`), `tsHeadline` and `setWeight` cover ranking and highlighting. Use `Op.match` for `@@`. ```ts const vector = toTsVector(col('body'), 'english'); const query = websearchToTsQuery('"fat cats" -dog', 'english'); const found = await Doc.findAll({ attributes: [ 'name', [tsRank(vector, query, { normalization: 1 }), 'rank'], [ tsHeadline(col('body'), query, { config: 'english', options: 'StartSel=, StopSel=', }), 'excerpt', ], ], where: where(vector, Op.match, query), order: [[tsRank(vector, query), 'DESC']], }); // found[0].get('excerpt'): 'The fat cats sat on the mat' const anyWord = await Doc.findAll({ where: where(vector, Op.match, plainToTsQuery('dog home', 'english')), }); ``` **Trigram similarity (`pg_trgm`).** Run `CREATE EXTENSION pg_trgm` first. `Op.trigramSimilar` (`%`), `Op.trigramWordSimilar` (`<%`), `Op.trigramStrictWordSimilar` (`<<%`) and the commutators `Op.trigramHasSimilarWord` (`%>`), `Op.trigramHasSimilarStrictWord` (`%>>`) filter; `trigramSimilarity`, `trigramWordSimilarity` and `trigramDistance` (`<->`) build expressions for `attributes` and `order`. The similarity threshold is the `pg_trgm.similarity_threshold` setting. ```ts const similar = await Doc.findAll({ where: { name: { [Op.trigramSimilar]: 'dogg' } }, order: [[trigramDistance(col('name'), 'dogg'), 'ASC']], }); ``` ### Selecting, ordering and paginating `attributes` selects columns (`['id', 'code']`, `{ exclude: [...] }`, `{ include: [...] }`, or `[expression, 'alias']` pairs). `order` takes `[attribute, direction]` pairs, expressions, and nested association paths. Directions are allow-listed: `ASC`, `DESC`, optionally with `NULLS FIRST` / `NULLS LAST`. ```ts const { count, rows } = await Item.findAndCountAll({ attributes: ['id', 'code'], order: [['id', 'ASC']], limit: 2, offset: 1, }); ``` (postgrelize extension) PostgreSQL sorts `NULL` last in `ASC` and first in `DESC` order. Add `NULLS FIRST` or `NULLS LAST` to the direction to choose where rows with `NULL` go; any other direction text is rejected. ```ts const nullsFirst = await Item.findAll({ order: [['code', 'ASC NULLS FIRST']] }); const nullsLast = await Item.findAll({ order: [['code', 'ASC NULLS LAST']] }); ``` `findOne`, `findByPk`, `findOrCreate`, `findOrBuild` and `findAndCountAll` behave as in v6. Pass `rejectOnEmpty: true` to throw `EmptyResultError` instead of returning `null`. `raw: true` returns plain objects, and `nest: true` turns dotted keys into nested objects. ### Aggregates and expressions ```ts const total = await Item.sum('qty'); const maxQty = await Item.max('qty'); const perTag = await Item.findAll({ attributes: [ [fn('unnest', col('tags')), 'tag'], [fn('count', col('id')), 'n'], ], group: ['tag'], order: [['tag', 'ASC']], raw: true, }); await Item.increment('qty', { by: 5, where: { code: 'c' } }); ``` `count`, `sum`, `min`, `max` and `aggregate` accept the same `where` as finders; `aggregate` and the helpers convert the result to the type of the attribute (`FLOAT` for `'*'`), `dataType` overrides that, and `plain: false` returns the raw rows with the driver's strings (like v6); `count` also takes `distinct`, `col` and `group`. `increment` and `decrement` work on the model (with `where`) and on instances. Build SQL expressions with `fn`, `col`, `literal`, `cast`, `json` and `where`. Values inside them are bound parameters; identifiers are quoted. Use `literal` only with trusted SQL text. ### Scopes Scopes are named sets of query options, defined with `scopes` and `defaultScope` in the model options or later with `addScope`: ```ts const onSale = await Item.scope('inStock', { method: ['tagged', 'sale'] }).findAll(); ``` As in v6, `scope()` merges scopes, `unscoped()` removes the default scope, and function scopes take arguments through `{ method: [name, ...args] }`. By default, when two merged scopes filter the same attribute, the later one wins (the v6 behaviour). The model option `whereMergeStrategy: 'and'` combines them with `AND` instead: ```ts sequelize.define('Person', attributes, { whereMergeStrategy: 'and', scopes: { adults: { where: { age: { [Op.gte]: 18 } } }, young: { where: { age: { [Op.lt]: 30 } } }, }, }); await Person.scope('adults', 'young').findAll(); // 18 <= age < 30 ``` ### Raw SQL `sequelize.query` runs SQL with replacements (`:name` or `?`, escaped into the SQL text as in Sequelize v6) or bind parameters (`$1`, sent separately). `type: QueryTypes.SELECT` returns the rows only: ```ts const byReplacement = (await sequelize.query('SELECT code FROM "Items" WHERE qty > :min', { replacements: { min: 1 }, type: QueryTypes.SELECT, })) as { code: string }[]; const byBind = (await sequelize.query('SELECT code FROM "Items" WHERE code = $1', { bind: ['a'], type: QueryTypes.SELECT, })) as { code: string }[]; // Replacements are escaped into the SQL text (as in Sequelize v6), so one call may hold several statements. const code = 'a\'; DROP TABLE "Items"; --'; await sequelize.query('UPDATE "Items" SET qty = qty WHERE code = :code; SELECT :code AS code', { replacements: { code }, }); ``` `sequelize.query` returns `Promise`; cast the result to the row type you expect. The result follows the query `type` like v6: `SELECT` rows, `INSERT` / `UPDATE` `[rows, rowCount]`, `DELETE` the statement rows (`[]` without `RETURNING`), `BULKUPDATE` / `BULKDELETE` the row count, `UPSERT` `[undefined, null]`. Other v6 options are supported: `plain`, `raw`, `nest` (nests `a.b` column names into objects), `model` / `mapToModel`, `transaction`, `logging`. Because replacements are written into the SQL text, the query goes to PostgreSQL as one simple query and may hold several `;`-separated statements, as in v6 (bind parameters cannot: PostgreSQL rejects several commands in one prepared statement). Strings are quoted (`'` doubled, `E'...'` when they contain a backslash), numbers and booleans are written as is, `null` is `NULL`, dates are ISO strings, objects are JSON text and arrays in `IN (:ids)` expand to a list. A string with a NUL character throws (v6 writes `\0` and changes the value). Placeholders inside string literals, quoted identifiers, comments, dollar quotes and `::` casts are left alone. Never build the SQL text from user input; pass the values as replacements. The finders take `replacements` as well, for placeholders inside `literal()`: `await User.findAll({ where: literal('"age" > :min AND "role" IN (:roles)'), replacements: { min: 18, roles: ['admin', 'editor'] } })`. Arrays expand to a list, `?` placeholders take an array, and every value is written into the SQL text as an escaped literal, exactly as in `sequelize.query` and Sequelize v6, so the same placeholder used twice (`SELECT` and `GROUP BY`) gives identical expressions. Values the finder builds itself (`where` values, `limit`, ...) stay bound parameters. A placeholder without a value throws. ### Locking `lock: true` (or `Transaction.LOCK.UPDATE`, `SHARE`, `KEY_SHARE`, `NO_KEY_UPDATE`) adds `FOR UPDATE` and friends; `skipLocked: true` adds `SKIP LOCKED`, and `noWait: true` (a PostgreSQL extension) adds `NOWAIT`. Locks need a transaction, see [Transactions](./transactions#row-locks). ### API reference - [`Model`](/api/classes/Model) — finders and aggregates - [`FindOptions`](/api/type-aliases/FindOptions), [`WhereOptions`](/api/type-aliases/WhereOptions) - [`Op`](/api/variables/Op), [`fn`](/api/functions/fn), [`col`](/api/functions/col), [`literal`](/api/functions/literal) - [`Sequelize.query`](/api/classes/Sequelize) ## Associations Source: https://tormozz48.github.io/postgrelize/guide/associations `belongsTo`, `hasOne`, `hasMany` and `belongsToMany` work as in Sequelize v6, including aliases, custom keys, junction models, eager loading with `include`, accessor methods and nested creation. ### Defining associations ```ts class Author extends Model, InferCreationAttributes> { declare id: CreationOptional; declare name: string; declare posts?: NonAttribute; declare getPosts: (options?: FindOptions) => Promise; declare countPosts: (options?: FindOptions) => Promise; declare createPost: (values: Partial>) => Promise; } class Post extends Model, InferCreationAttributes> { declare id: CreationOptional; declare title: string; declare authorId: ForeignKey; declare author?: NonAttribute; declare tags?: NonAttribute; declare addTags: (tags: Tag[]) => Promise; } class Tag extends Model, InferCreationAttributes> { declare id: CreationOptional; declare label: string; } Author.init( { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, name: { type: DataTypes.TEXT, allowNull: false }, }, { sequelize }, ); Post.init( { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, title: { type: DataTypes.TEXT, allowNull: false }, }, { sequelize }, ); Tag.init( { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, label: { type: DataTypes.TEXT, allowNull: false }, }, { sequelize }, ); Author.hasMany(Post, { as: 'posts', foreignKey: 'authorId' }); Post.belongsTo(Author, { as: 'author', foreignKey: 'authorId' }); Post.belongsToMany(Tag, { as: 'tags', through: 'PostTags' }); Tag.belongsToMany(Post, { as: 'posts', through: 'PostTags' }); await sequelize.sync(); ``` Notes on the example: - `as` names the association. It is the key of the loaded value (`author.posts`) and the base of the accessor names (`getPosts`, `countPosts`, `createPost`). - `foreignKey` sets the foreign key attribute; without it, v6 naming applies (`AuthorId` for `Author.hasMany(Post)`). - `through: 'PostTags'` creates the junction model automatically. Pass a model to add your own columns to the junction table. - `ForeignKey` and `NonAttribute<...>` keep these fields out of the creation attributes. - The accessor methods exist at runtime; declare the ones you use with `declare` so TypeScript knows them. postgrelize does not export the v6 `HasManyGetAssociationsMixin`-style helper types, so write the signatures directly. `sync()` creates the foreign key constraints with the v6 defaults: `ON DELETE SET NULL` for nullable foreign keys (`NO ACTION` for `allowNull: false`), `ON DELETE CASCADE` for junction tables, and `ON UPDATE CASCADE`. Override them with `onDelete` / `onUpdate`, or skip constraints with `constraints: false`. Default aliases and foreign keys come from the model's `name` init option when it is set (`name: { singular: 'user', plural: 'users' }`, as in v6), otherwise from the inflected `modelName`. An `include` entry takes a custom join condition with `on`; it replaces the key condition of `belongsTo`, `hasOne` and `hasMany` includes (not of `belongsToMany`). ### Nested creation `create`, `build` and `bulkCreate` accept nested values for associations listed in `include`. postgrelize inserts the parent, then the children with the foreign keys set: ```ts // Nested values are not creation attributes: pass them as a variable, not an object literal. const values = { name: 'Ann', posts: [{ title: 'Hello' }, { title: 'PostgreSQL tips' }] }; const ann = await Author.create(values, { include: [{ association: 'posts' }] }); ``` Nested creation works for all four association types and for multiple levels (`include: [{ association: 'posts', include: ['comments'] }]`). For `belongsToMany`, the junction row can carry values: `{ label: 'admin', UserRoles: { level: 'high' } }`. ### Accessors Instances get the v6 accessor methods: | Association | Methods | | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `belongsTo`, `hasOne` | `get`, `set`, `create` | | `hasMany`, `belongsToMany` | `get`, `count`, `has` / `has`, `set`, `add` / `add`, `remove` / `remove`, `create` | ```ts const sql = await Tag.create({ label: 'sql' }); const [tips] = await ann.getPosts({ where: { title: { [Op.like]: '%tips' } } }); await tips?.addTags([sql]); await ann.createPost({ title: 'Drafts' }); const postCount = await ann.countPosts(); ``` `get` and `count` take find options (`where`, `order`, `limit`, `transaction`, ...). Return values follow v6: - `hasOne` `set` accepts an instance, a primary key (a stub is built from the key, no lookup) or `null`. It resolves to the saved instance, or to `null` when the instance is already linked or the association is cleared. - `belongsTo` `set(value, { save: false })` only sets the foreign key and resolves to `undefined`. - `belongsToMany` `get` attaches the junction row under the junction model name. `joinTableAttributes` picks its columns (`[]` omits it); with `raw: true` the rows are flat and carry `Junction.column` keys. - Including a model with an unknown `as`, or a model associated several times without `as`, rejects with `EagerLoadingError`. ### Eager loading `include` loads associations in the same query with `LEFT OUTER JOIN` (or `INNER JOIN` with `required: true`, which is implied when the include has a `where`): ```ts const authors = await Author.findAll({ include: [ { association: 'posts', required: true, include: [{ association: 'tags', where: { label: 'sql' }, through: { attributes: [] } }], }, ], }); const withAuthor = await Post.findAll({ include: [{ association: 'author', attributes: ['name'] }], order: [['id', 'ASC']], }); const separate = await Author.findAll({ include: [{ association: 'posts', separate: true, order: [['title', 'ASC']] }], }); ``` Include options follow v6: `association` or `model` + `as`, `where`, `required`, `right`, `attributes`, nested `include`, `paranoid`, `through: { attributes, where }` for `belongsToMany`, and `all: true`. - **`limit` with multi-row includes.** As in v6, a `limit` on the main query together with a `hasMany` / `belongsToMany` include moves the main table into a subquery, so the limit counts parent rows. `subQuery: false` turns this off. - **`separate: true`** (hasMany only) loads the association with a second query instead of a join, with its own `order` and `limit` (applied per parent, as in Sequelize v6). This avoids row multiplication when a parent has many children. - **`$nested.attr$` keys** in the top-level `where` filter on included columns, as in v6. - **`minifyAliases: true`** (constructor option, as in v6) shortens the aliases of included columns (`Posts.Comments.title` becomes `_0`) and of table aliases of 64 or more characters, then maps the rows back. PostgreSQL identifiers hold 63 bytes: without the option a deeply nested include with long association names gets truncated column aliases that can collide, and attributes go missing. It is off by default and applies to the joined include query of `findAll`, `findOne`, `findByPk` and `findAndCountAll`; `separate` includes run their own query with their own aliases. SQL logs show the short names. Unlike v6, aliases of attributes you rename yourself (`attributes: [[fn(...), 'total']]`) are left as written. Counting with includes: `count({ include })` counts joined rows, as in v6; add `distinct: true` to count parent rows. ### Differences from Sequelize v6 Associations behave like v6, including default scopes of included models (a scoped include with a `where` becomes required) and `Model.unscoped()` or `Model.scope(...)` passed as the include `model`. Three v6 bugs are fixed (see [Sequelize issues fixed](/sequelize-issues)): - `belongsToMany` with a custom `sourceKey` and `limit` returns the right rows. - A top-level `$include.attr$` condition with a `hasMany` include and `limit` produces valid SQL: the limit subquery is turned off, so `limit` counts joined rows. - Nested `create` with a built instance as a child (`Post.create({ Comments: [Comment.build(...)] }, { include: [Comment] })`) saves and links the instance; v6 silently drops it. ### API reference - [`Model`](/api/classes/Model) — `belongsTo`, `hasOne`, `hasMany`, `belongsToMany` - [`AssociationOptions`](/api/type-aliases/AssociationOptions), [`BelongsToManyOptions`](/api/type-aliases/BelongsToManyOptions) - [`IncludeOptions`](/api/type-aliases/IncludeOptions) ## Decorators Source: https://tormozz48.github.io/postgrelize/guide/decorators Decorators and `sequelize.addModels` do not exist in Sequelize v6. The rest of the library works the same with or without them. See all [extensions](/extensions/). Decorators are an optional way to define models. They produce exactly what `Model.init` and the association methods produce, so everything else in this guide (queries, hooks, scopes, sync) works unchanged. The names follow `sequelize-typescript`, which makes moving from it straightforward. ### Defining models (postgrelize extension) Decorate the class and its fields, then register the classes with `sequelize.addModels`: ```ts @Table({ tableName: 'authors' }) @DefaultScope({ where: { active: true } }) @Scopes({ byName: (name: string) => ({ where: { name } }) }) class Author extends Model { @PrimaryKey @AutoIncrement @Column(DataTypes.INTEGER) id!: number; @AllowNull(false) @Column(DataTypes.TEXT) name!: string; @Unique @Column(DataTypes.STRING(120)) email!: string; @Column({ type: DataTypes.BOOLEAN, defaultValue: true }) active!: boolean; @HasMany(() => Post) posts?: Post[]; @BeforeCreate static normalize(author: Author): void { author.name = author.name.trim(); } } @Table({ tableName: 'posts' }) class Post extends Model { @PrimaryKey @AutoIncrement @Column(DataTypes.INTEGER) id!: number; @Column(DataTypes.TEXT) title!: string; @ForeignKey(() => Author) @Column(DataTypes.INTEGER) authorId!: number; @BelongsTo(() => Author) author?: Author; @BelongsToMany(() => Tag, () => PostTag) tags?: Tag[]; } @Table({ tableName: 'tags' }) class Tag extends Model { @PrimaryKey @AutoIncrement @Column(DataTypes.INTEGER) id!: number; @Column(DataTypes.TEXT) label!: string; } @Table({ tableName: 'post_tags', timestamps: false }) class PostTag extends Model { @ForeignKey(() => Post) @PrimaryKey @Column(DataTypes.INTEGER) postId!: number; @ForeignKey(() => Tag) @PrimaryKey @Column(DataTypes.INTEGER) tagId!: number; } sequelize.addModels([Author, Post, Tag, PostTag]); await sequelize.sync(); ``` `addModels` initializes every class with `Model.init` first and adds the associations afterwards, so classes can refer to each other in any order (`() => Post` is evaluated when `addModels` runs). A model class belongs to one `Sequelize` instance at a time. The classes then work like any other model: ```ts const ann = await Author.create({ name: ' Ann ', email: 'ann@example.com' }); const post = (await Post.create({ title: 'Hello', authorId: ann.id })) as Post & { addTag: (tag: Tag) => Promise; }; await post.addTag(await Tag.create({ label: 'news' })); const posts = await Post.findAll({ include: ['author', 'tags'] }); ``` ### Reference | Decorator | Target | Equivalent | | -------------------------------------------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------ | | `@Table(options?)` | class | `Model.init` options without `sequelize` (`tableName`, `schema`, `paranoid`, `indexes`, `hooks`, …) | | `@DefaultScope(options \| () => options)`, `@Scopes({ … } \| () => ({ … }))` | class | `defaultScope`, `scopes` | | `@Column(type \| options)` | field | an entry of the `attributes` argument of `init` | | `@PrimaryKey`, `@AutoIncrement`, `@AllowNull(bool?)`, `@Default(value)`, `@Unique(nameOrOptions?)`, `@Comment(text)` | field | `primaryKey`, `autoIncrement`, `allowNull`, `defaultValue`, `unique`, `comment` | | `@Index(nameOrOptions?)` | field | an entry of `indexes`; fields that share an index name form one composite index | | `@CreatedAt`, `@UpdatedAt`, `@DeletedAt` | field | `createdAt`, `updatedAt`, `deletedAt` names; `@DeletedAt` also sets `paranoid: true` unless `@Table` sets it | | `@ForeignKey(() => Model)` | field | tells association decorators which attribute is the foreign key | | `@HasOne`, `@HasMany`, `@BelongsTo`, `@BelongsToMany(() => Model, through, options?)` | field | `hasOne`, `hasMany`, `belongsTo`, `belongsToMany`; the property name is the alias (`as`) | | `@BeforeCreate`, `@AfterCreate`, `@BeforeFind`, … (one per model hook) | static method | `Model.addHook('beforeCreate', fn)` / the `hooks` option | Details worth knowing: - **Types are explicit.** There is no `reflect-metadata`, so the column type is never inferred from the TypeScript type. Pass a `DataTypes` value or `{ type }` to `@Column`; an attribute without a type makes `addModels` throw. - **Foreign keys.** `@HasMany(() => Post)` uses the attribute of `Post` marked `@ForeignKey(() => ThisModel)`. `@BelongsTo(() => Author)` uses the attribute of this class marked `@ForeignKey(() => Author)`. `@BelongsToMany` reads `foreignKey` and `otherKey` from the junction model. Pass `foreignKey` / `otherKey` in the options to override. Without any of them, the v6 defaults apply. - **Hooks** are static methods and receive the same arguments as hooks added with `addHook`. - **Inheritance.** Attributes, associations and hooks of base classes are inherited. A base class that is not passed to `addModels` is not a model. - **Instance fields.** Declare decorated attributes as fields with `!` (`name!: string`). Under TC39 decorators the field is removed from each instance right after construction, so the attribute getters and setters of the model keep working. ### Compiler settings The decorators accept both calling conventions, so they work in either mode: - **Standard decorators** (TypeScript 5+ without `experimentalDecorators`, which is the default). Use a toolchain that lowers them: `tsc`, `esbuild` 0.21+, `swc`, `tsx`, or and Vitest with a TypeScript-based lowering step (`build/decorators-plugin.ts` in this repository). Node cannot run decorator syntax natively. - **Legacy decorators** (`"experimentalDecorators": true`), as used by NestJS and `sequelize-typescript`. Also set `"useDefineForClassFields": false`, otherwise class fields shadow the attribute accessors (this mode has no hook to remove them). postgrelize itself ships plain JavaScript and needs no decorator support from consumers. Importing it defines `Symbol.metadata` when the runtime has not, which standard decorators need to find the class of a field. ### Security Decorators add no new inputs to SQL: they feed the same options as `Model.init` and the association methods, whose values are bound parameters or quoted identifiers like everything else. ## Transactions Source: https://tormozz48.github.io/postgrelize/guide/transactions `sequelize.transaction()` works as in Sequelize v6: managed transactions with a callback, unmanaged transactions you commit yourself, savepoints for nested transactions, isolation levels, row locks, `afterCommit` hooks and optional CLS. Session settings and advisory locks are PostgreSQL extensions described in [Sessions and scaling](./sessions). The examples use an `Account` model with `owner` and `balance` columns. ### Managed transactions Pass a callback: the transaction commits when the callback resolves and rolls back when it throws. The result of the callback is returned. Pass `transaction` to every query that should run inside it: ```ts await sequelize.transaction(async (transaction) => { await Account.decrement('balance', { by: 30, where: { owner: 'ann' }, transaction }); await Account.increment('balance', { by: 30, where: { owner: 'bob' }, transaction }); }); const failed = await sequelize .transaction(async (transaction) => { await Account.update({ balance: 0 }, { where: {}, transaction }); throw new Error('abort'); }) .catch((error: Error) => error.message); // failed === 'abort'; the update was rolled back ``` ### Unmanaged transactions Without a callback, `transaction()` resolves to a started `Transaction`. Commit or roll it back yourself: ```ts const transaction = await sequelize.transaction({ isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ, }); const committed: string[] = []; transaction.afterCommit(() => { committed.push(transaction.id); }); try { await Account.create({ owner: 'cid', balance: 5 }, { transaction }); await transaction.commit(); } catch (error) { await transaction.rollback(); throw error; } ``` `afterCommit` callbacks run after a successful commit and are skipped on rollback. Committing or rolling back a finished transaction throws. Options of `sequelize.transaction(options)`: | Option | Description | | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `isolationLevel` | `Transaction.ISOLATION_LEVELS.READ_COMMITTED` (PostgreSQL default), `REPEATABLE_READ`, `SERIALIZABLE`, `READ_UNCOMMITTED` (behaves as read committed) | | `readOnly` | Starts the transaction `READ ONLY`. PostgreSQL extension. | | `deferrable` | `true` / `false` adds `DEFERRABLE` / `NOT DEFERRABLE`; see [Deferrable read-only transactions](#deferrable-read-only-transactions). `Deferrable.SET_DEFERRED` / `SET_IMMEDIATE` run `SET CONSTRAINTS`; see [Deferred constraints](#deferred-constraints). | | `transaction` | Parent transaction: the new one becomes a savepoint inside it. | | `settings` | Settings applied with `SET LOCAL` semantics. PostgreSQL extension, see [Sessions](./sessions#transaction-settings). | | `logging` | Logger for the `BEGIN` / `COMMIT` / `ROLLBACK` statements. | | `type` | Accepted for v6 compatibility (`DEFERRED`, ...) and ignored. | ### Savepoints A transaction started with `{ transaction: parent }` is a savepoint. When it fails, only its work is rolled back and the parent can continue: ```ts await sequelize.transaction(async (outer) => { await Account.create({ owner: 'dan', balance: 1 }, { transaction: outer }); await sequelize .transaction({ transaction: outer }, async (inner) => { await Account.create({ owner: 'eve', balance: 1 }, { transaction: inner }); throw new Error('rolls back to the savepoint only'); }) .catch(() => undefined); }); // dan is saved, eve is not ``` ### CLS As in v6, `Sequelize.useCLS()` makes queries inside a managed transaction callback pick up the transaction automatically, without the `transaction` option. postgrelize uses Node.js `AsyncLocalStorage`, so no namespace argument is needed: ```ts Sequelize.useCLS(); await sequelize.transaction(async () => { await Account.update({ balance: 0 }, { where: { owner: 'ann' } }); // runs in the transaction }); ``` CLS is a global switch for all `Sequelize` instances in the process. Nested `sequelize.transaction()` calls inside a CLS transaction become savepoints. #### CLS namespaces (`cls-hooked`) Code written for v6 passes a [`cls-hooked`](https://www.npmjs.com/package/cls-hooked) or `continuation-local-storage` namespace: `Sequelize.useCLS(createNamespace('app'))`. postgrelize accepts it (any object with `bind`, `run`, `get` and `set`; `cls-hooked` is not a dependency) and then behaves as v6 does, so helpers that read `namespace.get('transaction')` keep working: - A managed transaction runs in `namespace.run` and stores itself under the key `transaction`; it clears the key when it finishes, so `afterCommit` hooks see `null`. - A query without a `transaction` option uses `namespace.get('transaction')`, including a transaction your own code stored there. Code outside the callback sees none. - As in v6, a nested `sequelize.transaction(callback)` does not join the enclosing one by itself: it opens its own transaction on another connection. Pass `{ transaction: outer }` to get a savepoint. (Without a namespace, `AsyncLocalStorage` mode turns it into a savepoint automatically.) Anything that is not a namespace (no `bind` or `run`) throws `Must provide CLS namespace`, as in v6; `useCLS()` without an argument keeps the `AsyncLocalStorage` mode. ### Row locks `lock` adds a locking clause to a `SELECT`; it must run inside a transaction. `skipLocked: true` skips rows locked by others (useful for job queues), and `noWait: true` fails immediately instead of waiting: ```ts const holder = await sequelize.transaction(); await Account.findAll({ where: { owner: 'ann' }, lock: true, transaction: holder }); const free = await sequelize.transaction((worker) => Account.findAll({ lock: Transaction.LOCK.UPDATE, skipLocked: true, transaction: worker }), ); const noWait = await sequelize .transaction((worker) => Account.findAll({ where: { owner: 'ann' }, lock: true, noWait: true, transaction: worker }), ) .catch((error: unknown) => error); await holder.rollback(); // free: every row except ann's; noWait: DatabaseError (could not obtain lock) ``` | `lock` value | SQL | | ------------------------------------------------- | ------------------------- | | `true` or `Transaction.LOCK.UPDATE` | `FOR UPDATE` | | `Transaction.LOCK.NO_KEY_UPDATE` | `FOR NO KEY UPDATE` | | `Transaction.LOCK.SHARE` | `FOR SHARE` | | `Transaction.LOCK.KEY_SHARE` | `FOR KEY SHARE` | | `{ level: Transaction.LOCK.UPDATE, of: Account }` | `FOR UPDATE OF "Account"` | `noWait` is a PostgreSQL extension; Sequelize v6 has no way to express `NOWAIT`. ### Read-only transactions (postgrelize extension) `readOnly: true` makes PostgreSQL reject every write in the transaction. On a [read replica setup](./sessions#read-replicas) the transaction still runs on the writer. ```ts const readOnly = await sequelize .transaction({ readOnly: true }, (tx) => Account.create({ owner: 'x', balance: 0 }, { transaction: tx }), ) .catch((error: unknown) => error); // readOnly: DatabaseError (cannot execute INSERT in a read-only transaction) ``` ### Deferrable read-only transactions (postgrelize extension) `deferrable: true` together with `isolationLevel: SERIALIZABLE` and `readOnly: true` starts a `SERIALIZABLE READ ONLY DEFERRABLE` transaction, meant for long reports. PostgreSQL waits for a snapshot that cannot be involved in a serialization failure, then runs the transaction without taking predicate locks and without ever failing with `40001`. The start may be delayed while other serializable transactions finish. For any other transaction PostgreSQL accepts the flag and ignores it; `deferrable` must be a boolean and is ignored for savepoints. ```ts // Waits for a snapshot that cannot hit serialization failures, then runs without predicate locks. const report = await sequelize.transaction( { isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE, readOnly: true, deferrable: true }, () => Account.sum('balance'), ); ``` ### Deferred constraints As in v6, `deferrable: Deferrable.SET_DEFERRED` (all constraints) or `Deferrable.SET_DEFERRED(['child_parent_fk'])` (named constraints) runs `SET CONSTRAINTS ... DEFERRED` right after the transaction starts, so deferrable foreign keys are checked at commit; `Deferrable.SET_IMMEDIATE` does the opposite. The constraints must be declared `DEFERRABLE` (see [Schema](./schema)). Names are quoted as identifiers, and `deferrable` accepts only values made by `Deferrable`. `queryInterface.deferConstraints(transaction, { deferrable })` does the same inside a running transaction. ### Errors Serialization failures, deadlocks and `NOWAIT` lock failures surface as `DatabaseError`; the PostgreSQL error code is on `error.parent.code` (`40001` serialization failure, `40P01` deadlock, `55P03` lock not available). A cancelled statement (`statement_timeout`, code `57014`) throws `TimeoutError`. Retry logic is up to the application, as in v6. ### API reference - [`Transaction`](/api/classes/Transaction) - [`TransactionOptions`](/api/type-aliases/TransactionOptions) - [`Sequelize.transaction`](/api/classes/Sequelize) ## Hooks and validation Source: https://tormozz48.github.io/postgrelize/guide/hooks-validation Lifecycle hooks and attribute / model validators work as in Sequelize v6. postgrelize adds validation with any [Standard Schema](https://standardschema.dev) library, such as zod, valibot or arktype. ### Hooks Register hooks in the model options (`hooks`), with the shorthand methods (`Model.beforeCreate(fn)`), or with `addHook(type, [name], fn)`. A named hook can be removed later with `removeHook(type, name)`. ```ts const audit: string[] = []; const Member = sequelize.define( 'Member', { email: { type: DataTypes.TEXT, allowNull: false }, role: DataTypes.TEXT, }, { hooks: { beforeValidate: (member: { email: string }) => { member.email = member.email.trim().toLowerCase(); }, afterCreate: (member: { get: (key: string) => unknown }) => { audit.push(`created ${String(member.get('email'))}`); }, }, }, ); Member.beforeCreate((member: { role: string | null }) => { member.role ??= 'member'; }); Member.addHook('beforeBulkDestroy', 'log-deletes', () => { audit.push('bulk destroy'); }); ``` Hooks may be async; postgrelize awaits them in registration order. `before*` hooks may change the instance or the options object; throwing from a hook aborts the operation. | Operation | Hooks (in order) | | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | `create`, `save` of a new record | `beforeValidate`, `afterValidate` (or `validationFailed`), `beforeCreate`, `afterCreate` | | `save` / `update` of an instance | `beforeValidate`, `afterValidate` (or `validationFailed`), `beforeUpdate`, `afterUpdate` | | instance `destroy` / `restore` | `beforeDestroy` / `afterDestroy`, `beforeRestore` / `afterRestore` | | `upsert` | `beforeUpsert`, `afterUpsert` | | `bulkCreate`, `Model.insert` | `beforeBulkCreate`, `afterBulkCreate` | | `Model.update` / `destroy` / `restore` | `beforeBulkUpdate` / `afterBulkUpdate`, `beforeBulkDestroy` / `afterBulkDestroy`, `beforeBulkRestore` / `afterBulkRestore` | | finders | `beforeFind`, `beforeFindAfterExpandIncludeAll`, `beforeFindAfterOptions`, `afterFind`; `beforeCount` for `count` | | connecting | `beforeConnect` (on the `Sequelize` instance; may change the connection config) | As in v6, `beforeSave` / `afterSave` hooks are registered as both create and update hooks, so they run in registration order together with `beforeCreate` / `beforeUpdate`. Bulk operations run per-row hooks only with `individualHooks: true`. Pass `hooks: false` to skip hooks for one call. An association defined with `onDelete: 'CASCADE'` and `hooks: true` destroys its associated rows one by one, with their `beforeDestroy` / `afterDestroy` hooks, when the owner instance is destroyed (as in v6); without `hooks: true` PostgreSQL cascades the delete and no hooks of the target run. #### Sequelize-level hooks Hooks can also be registered for every model: through the `hooks` constructor option, with `sequelize.addHook(...)`, or as model defaults in `define: { hooks }`. Model hooks run first, then the Sequelize-level hooks: ```ts const sequelize = new Sequelize(url, { hooks: { beforeCreate: (instance) => audit('create', instance) }, }); sequelize.addHook('beforeConnect', async (config) => { config.password = await fetchDatabaseToken(); // e.g. short-lived IAM tokens }); ``` On the `Sequelize` instance every hook that runs also has a shorthand as in v6 (`sequelize.beforeCreate(fn)`, `sequelize.afterConnect('name', fn)`, `sequelize.beforeBulkSync(fn)`, ...) next to `addHook`, `removeHook`, `hasHook(s)` and `runHooks`; models have `Model.beforeSync(fn)` / `Model.afterSync(fn)` besides the lifecycle shorthands. Hooks postgrelize never runs (`beforeQuery`, `beforeAssociate`, ...) have no shorthand. The class-level `Sequelize.addHook`, `removeHook`, `hasHook(s)`, `runHooks` and the shorthands (`Sequelize.beforeInit(fn)`, ...) exist as in v6; `beforeInit(config, options)` and `afterInit(sequelize)` run for every instance created afterwards (`config` and `options` may be changed before they are used), the other static hooks are only stored. `sequelize.addHook('beforeDefine', (attributes, options) => ...)` runs when a model is defined and may change the model name (`options.modelName`), `options.name`, the attributes and the options; `afterDefine` receives the model. `afterConnect` runs once for every new pooled connection, after `beforeConnect`, with `(connection, config)` as in v6; `connection` is the `pg` client, so the hook can run session setup on it. If the hook throws, the connection is closed and the query that needed it rejects with that error. ```ts sequelize.addHook('afterConnect', async (connection) => { await connection.query("SET idle_in_transaction_session_timeout = '30s'"); }); ``` All v6 hook names are accepted, but connection hooks other than `beforeConnect` and `afterConnect` and `beforeQuery` / `afterQuery`, `beforeAssociate` / `afterAssociate` are not run yet. `beforeBulkSync` / `afterBulkSync` run around `sequelize.sync()` and `beforeSync` / `afterSync` around each model's sync (also `Model.sync()`); `hooks: false` skips them. #### Transactions in hooks Hooks receive the options of the operation, including `options.transaction`. Pass it on to queries made inside the hook so they join the same transaction. ### Validators Attribute validators go into `validate`: the validator.js-based built-ins of v6 (`isEmail`, `isUrl`, `len`, `min`, `max`, `isIn`, `notEmpty`, `is`, `not`, ...) with optional `{ args, msg }`, and custom functions that throw. An unknown validator name fails validation with `Invalid validator function: ` as a `ValidationErrorItem`, like v6. Model-level validators go into the `validate` model option and run with the instance as `this`: ```ts const Person = sequelize.define( 'Person', { email: { type: DataTypes.TEXT, allowNull: false, validate: { isEmail: true } }, name: { type: DataTypes.TEXT, validate: { len: { args: [2, 50], msg: 'name must be 2-50 characters' } }, }, age: { type: DataTypes.INTEGER, validate: { isAdult(value: unknown) { if (typeof value === 'number' && value < 18) { throw new Error('must be an adult'); } }, }, }, }, { validate: { nameOrEmail(this: { name: string | null; email: string | null }) { if (this.name === null && this.email === null) { throw new Error('name or email is required'); } }, }, }, ); ``` Validation runs before `create` and `save` (skip it with `validate: false`) and on `Model.update`. `bulkCreate` and `Model.insert` validate only with `validate: true`. `allowNull: false` violations are reported as validation errors before the query runs; set a custom message with `validate: { notNull: { msg } }`. ### Standard Schema (postgrelize extension) Any [Standard Schema](https://standardschema.dev) v1 object can validate a single attribute (`validate: { schema }`) or the whole row (`validationSchema` model option). Schema issues become `ValidationErrorItem`s with `validatorKey: 'schema'`, and the issue path selects the attribute: ```ts const Signup = sequelize.define( 'Signup', { email: { type: DataTypes.TEXT, allowNull: false, validate: { schema: z.email() } }, age: { type: DataTypes.INTEGER, validate: { schema: z.number().int().min(0) } }, role: DataTypes.TEXT, }, { validationSchema: z .object({ age: z.number().nullish(), role: z.string().nullish() }) .refine((row) => row.role !== 'admin' || (row.age ?? 0) >= 18, { message: 'admins must be adults', path: ['role'], }), }, ); ``` The row schema receives all attribute values of the instance. postgrelize does not use the schema output: transformations (`z.coerce`, `.transform`) do not change the stored values. Use setters or hooks for that. `validationSchema` is an extension. The model option `schema` keeps its v6 meaning (the PostgreSQL schema of the table). ### Validation errors A failed validation rejects with `ValidationError`, whose `errors` array holds one `ValidationErrorItem` per problem, with `message`, `path` (attribute), `value`, `validatorKey` and `type`: ```ts const error = await Signup.create({ email: 'nope', age: 12, role: 'admin' }).catch( (caught: unknown) => caught, ); if (error instanceof ValidationError) { const paths = error.errors.map((item) => `${String(item.path)}:${String(item.validatorKey)}`); // paths: ['email:schema', 'role:schema'] audit.push(...paths.toSorted()); } ``` Database constraint violations are reported separately, as `UniqueConstraintError`, `ForeignKeyConstraintError` or `ExclusionConstraintError`. ### API reference - [`Model`](/api/classes/Model) — `addHook`, `removeHook`, `validate` - [`HOOK_TYPES`](/api/variables/HOOK_TYPES), [`HookFunction`](/api/type-aliases/HookFunction) - [`AttributeValidateOptions`](/api/type-aliases/AttributeValidateOptions), [`StandardSchemaV1`](/api/type-aliases/StandardSchemaV1) - [`ValidationError`](/api/classes/ValidationError), [`ValidationErrorItem`](/api/classes/ValidationErrorItem) ## Schema, sync and migrations Source: https://tormozz48.github.io/postgrelize/guide/schema postgrelize creates and changes tables in two ways, both compatible with Sequelize v6: `sync()` derives the schema from model definitions, and `QueryInterface` runs explicit DDL for migrations (umzug, sequelize-cli style migration files). ### `sync` `sequelize.sync()` creates missing tables, enum types, indexes and foreign keys for all defined models; `Model.sync()` does it for one model. Indexes come from the `indexes` model option and from `unique` attribute options: ```ts const Device = sequelize.define( 'Device', { serial: { type: DataTypes.TEXT, unique: { name: 'devices_serial', nullsNotDistinct: true } }, vendor: DataTypes.TEXT, model: DataTypes.TEXT, }, { indexes: [ { fields: ['vendor', 'model'], unique: true, nullsNotDistinct: true }, { fields: ['model'], where: { vendor: null } }, ], }, ); await sequelize.sync(); ``` `sync` options: | Option | Effect | | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | (none) | `CREATE TABLE IF NOT EXISTS`; existing tables are left as they are. | | `force: true` | Drops and recreates the tables. Data is lost. | | `alter: true` | Compares each table with the model and adds, changes or drops columns, enum values and constraints. `alter: { drop: false }` keeps columns that are not in the model. | | `match: /_test$/` | Throws unless the database name matches the pattern (a safety net for `force`). | | `schema` | Creates the tables in this PostgreSQL schema. | ```ts sequelize.define( 'Device', { serial: { type: DataTypes.TEXT, unique: { name: 'devices_serial', nullsNotDistinct: true } }, vendor: DataTypes.TEXT, model: DataTypes.TEXT, firmware: { type: DataTypes.TEXT, allowNull: false, defaultValue: '1.0' }, }, { indexes: [{ fields: ['vendor', 'model'], unique: true, nullsNotDistinct: true }] }, ); await sequelize.sync({ alter: true }); ``` `sync({ alter: true })` is convenient during development; for production, prefer migrations that you review. `sequelize.drop()` and `Model.drop()` drop the tables (`cascade` and `schema` options as in v6). #### PostgreSQL index and constraint options Index options are the v6 ones (`name`, `fields`, `unique`, `using`, `operator`, `where`, `concurrently`) plus: - (postgrelize extension) `nullsNotDistinct: true` → `UNIQUE NULLS NOT DISTINCT`: `NULL` values count as equal, so only one row may have `NULL` in the key. Also accepted in the attribute option `unique: { nullsNotDistinct: true }`. - `include: ['col']` → covering index (`INCLUDE (...)`). - `ifNotExists: true` → `CREATE INDEX IF NOT EXISTS`. Foreign keys accept `deferrable: Deferrable.INITIALLY_DEFERRED` (or `INITIALLY_IMMEDIATE`, `NOT`) in `references`, so the constraint is checked at commit. ### Migrations with `QueryInterface` `sequelize.getQueryInterface()` returns a `QueryInterface` with the v6 methods. A migration is a pair of `up` / `down` functions receiving it, as with [umzug](https://github.com/sequelize/umzug) or sequelize-cli: ```ts export const up = async (queryInterface: QueryInterface): Promise => { await queryInterface.createTable('accounts', { id: { type: DataTypes.BIGINT, primaryKey: true, autoIncrement: true }, email: { type: DataTypes.TEXT, allowNull: false, unique: true }, plan: { type: DataTypes.ENUM('free', 'pro'), allowNull: false, defaultValue: 'free' }, created_at: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW }, }); await queryInterface.createTable('sessions', { id: { type: DataTypes.UUID, primaryKey: true }, account_id: { type: DataTypes.BIGINT, allowNull: false, references: { model: 'accounts', key: 'id', deferrable: Deferrable.INITIALLY_DEFERRED }, onDelete: 'CASCADE', }, }); await queryInterface.addIndex('sessions', ['account_id']); await queryInterface.addColumn('accounts', 'note', { type: DataTypes.TEXT }); }; export const down = async (queryInterface: QueryInterface): Promise => { await queryInterface.dropTable('sessions'); await queryInterface.dropTable('accounts'); await queryInterface.dropEnum('enum_accounts_plan'); }; ``` ```ts const queryInterface = sequelize.getQueryInterface(); await up(queryInterface); const tables = await queryInterface.showAllTables(); const accounts = await queryInterface.describeTable('accounts'); await down(queryInterface); ``` Available methods: - tables: `createTable`, `dropTable`, `dropAllTables`, `renameTable`, `tableExists`, `showAllTables`, `describeTable` - columns: `addColumn`, `removeColumn`, `changeColumn`, `renameColumn` - indexes and constraints: `addIndex`, `removeIndex`, `showIndex`, `addConstraint`, `removeConstraint`, `showConstraint`, `getForeignKeyReferencesForTable`, `getForeignKeysForTables` - databases and helpers: `createDatabase`, `dropDatabase`, `databaseVersion`, `assertTableHasColumn`, `quoteIdentifier`, `quoteIdentifiers` - schemas and enums: `createSchema`, `dropSchema`, `showAllSchemas`, `dropEnum`, `dropAllEnums` - extensions, sequences, views, row-level security, functions and triggers: `createExtension`, `createSequence`, `nextval`, `createView`, `createMaterializedView`, `refreshMaterializedView`, `createFunction`, `createTrigger`, `createPolicy` and their drop / alter / rename counterparts (see [Schema objects](/guide/schema-objects)) - data: `bulkInsert`, `bulkUpdate`, `bulkDelete` All methods take a `transaction` option, so a migration can run in one transaction. Table names may be strings or `{ tableName, schema }` objects. ### Differences from Sequelize v6 - `describeTable`, `showAllTables` and `tableExists` look in `current_schema()` (the first schema of `search_path`) when no schema is given; v6 always uses `public`. - `showIndex`, `showConstraint` and `getForeignKeysForTables` filter by schema like `describeTable` (v6 looks up the table name in every schema, and breaks for `{ tableName, schema }` in `getForeignKeysForTables`). `showConstraint(table, name)` returns only that constraint; v6 ignores the name on PostgreSQL. `quoteIdentifier` doubles embedded `"` where v6 strips them. - `describeTable` returns literal defaults unquoted (`it's`, not `'it''s'::text`). - `sync({ alter: true })` keeps the sequence of non-key `autoIncrement` columns and does not duplicate foreign keys when tables live in a non-default schema. - `sync({ schema })` / `drop({ schema })` only touch that schema, even if tables with the same name exist elsewhere. - Foreign-key cycles are created after all tables exist. The details and issue links are on [Sequelize issues fixed](/sequelize-issues). ### API reference - [`QueryInterface`](/api/classes/QueryInterface) - [`SyncOptions`](/api/type-aliases/SyncOptions), [`AlterOptions`](/api/type-aliases/AlterOptions) - [`IndexOptions`](/api/type-aliases/IndexOptions), [`Deferrable`](/api/variables/Deferrable) ## Schema objects Source: https://tormozz48.github.io/postgrelize/guide/schema-objects Sections marked (postgrelize extension) describe options, methods and statements that Sequelize v6 does not have. Everything else here behaves as in v6. All extensions are listed on the [extensions page](/extensions/). `QueryInterface` creates more than tables: extensions, sequences, views, functions, triggers and row-level security policies. These are PostgreSQL features, so they are additions to Sequelize v6 (except `createFunction` and `createTrigger`, which v6 has too). Object names are always quoted identifiers; the few places that take SQL text are listed in [Security](/security). ### Extensions (postgrelize extension) ```ts await queryInterface.createExtension('pg_trgm', { ifNotExists: true }); ``` `createExtension(name, { ifNotExists, schema, version, cascade })` and `dropExtension(name, { ifExists, cascade })`. The database role needs the privileges PostgreSQL requires for that extension. ### Sequences (postgrelize extension) ```ts await queryInterface.createSequence('invoice_number', { start: 1000, increment: 1 }); const first = await queryInterface.nextval('invoice_number'); await queryInterface.setval('invoice_number', 5000); const afterSet = await queryInterface.nextval('invoice_number'); await queryInterface.alterSequence('invoice_number', { restartWith: 1, cycle: false }); await queryInterface.dropSequence('invoice_number'); ``` - `createSequence(name, { dataType, start, increment, minValue, maxValue, cache, cycle, ownedBy, ifNotExists })`: `minValue` / `maxValue` accept `false` for `NO MINVALUE` / `NO MAXVALUE`; numbers are `number` or `bigint` and must be whole. - `alterSequence(name, { restartWith, increment, ... })`, `dropSequence(name, { ifExists, cascade })`. - `nextval(name)` and `setval(name, value, isCalled = true)` return the value as text, so bigint values stay exact. Sequences of `autoIncrement` and identity columns are created by `sync`; use these methods for standalone counters. ### Functions and triggers (postgrelize extension) `createFunction`, `dropFunction`, `renameFunction`, `createTrigger`, `dropTrigger` and `renameTrigger` have the Sequelize v6 names and argument order, so v6 migrations run unchanged. ```ts await queryInterface.createFunction( 'touch_post', [], 'trigger', 'plpgsql', 'NEW."updatedAt" := now(); NEW.edits := OLD.edits + 1; RETURN NEW;', ['VOLATILE'], { force: true }, ); await queryInterface.createTrigger( 'posts', 'posts_touch', 'before', ['update'], 'touch_post', [], ['FOR EACH ROW', 'WHEN (OLD.title IS DISTINCT FROM NEW.title)'], ); ``` - **The function `body` is SQL you write.** It is wrapped in `BEGIN ... END;` like v6 and is not escaped: never build it from user input. The same holds for a `WHEN (...)` clause in the trigger options. See [Security](/security). - A function name given as a string (`'touch_post'`, `'app.touch_post'`) is an unquoted identifier that folds to lower case, like v6. Use `{ name, schema }` for an exact, quoted name. - Parameter and variable names and the language are identifier words. Types (`'integer'`, `'varchar(10)'`, `'text[]'`, `'SETOF users'`) and keywords (`'IMMUTABLE'`, `'SECURITY DEFINER'`, `'COST 10'`, `'FOR EACH ROW'`, `'DEFERRABLE'`) are checked against strict patterns and allowlists; anything else throws before SQL is sent. - Trigger arguments are literals: `createTrigger(table, name, 'before', ['insert'], 'f', ['a', 1])` renders `EXECUTE FUNCTION f('a', 1)`. v6 rendered typed parameter declarations, which PostgreSQL rejects. - New options: `dropFunction` / `dropTrigger` accept `ifExists` and `cascade`; `createTrigger` accepts `replace` (`CREATE OR REPLACE TRIGGER`, PostgreSQL 14+). - Timing is `'before' | 'after' | 'instead_of' | 'after_constraint'` (a deferrable `CONSTRAINT TRIGGER`); events are `'insert' | 'update' | 'delete' | 'truncate'`. ### Views and materialized views (postgrelize extension) ```ts await queryInterface.createView('edited_posts', 'SELECT id, title FROM posts WHERE edits > 0', { replace: true, }); await queryInterface.createMaterializedView( 'post_stats', 'SELECT 1 AS k, count(*)::int AS posts, sum(edits)::int AS edits FROM posts', ); await sequelize.query('CREATE UNIQUE INDEX post_stats_k ON post_stats (k)'); await queryInterface.refreshMaterializedView('post_stats', { concurrently: true }); ``` - `createView(name, query, { replace, temporary, recursive, columns, checkOption, securityBarrier, securityInvoker })`, `dropView(name, { ifExists, cascade })`. - `createMaterializedView(name, query, { ifNotExists, columns, using, withData })`, `refreshMaterializedView(name, { concurrently, withData })`, `dropMaterializedView(name, { ifExists, cascade })`. PostgreSQL has no `OR REPLACE` for materialized views. `concurrently` needs a unique index on the view and cannot be combined with `withData: false`. - **The `query` is SQL you write.** It is not escaped: never build it from user input. See [Security](/security). View and column names are quoted identifiers. - A model can read a view like a table (`freezeTableName` or `tableName`, `timestamps: false`). - A `temporary` view lives only as long as its database session, which is one pooled connection: create and use it in one transaction (`transaction` option). ### Row-level security (postgrelize extension) ```ts await queryInterface.enableRowLevelSecurity('posts', { force: true }); await queryInterface.createPolicy('posts', 'edited_only', { command: 'select', using: { edits: { [Op.gt]: 0 } }, }); await queryInterface.alterPolicy('posts', 'edited_only', { using: 'edits >= 0' }); ``` - `enableRowLevelSecurity(table, { force })` and `disableRowLevelSecurity(table, { noForce })`. `force` also subjects the table owner to the policies; superusers and roles with `BYPASSRLS` are never subject to them. - `createPolicy(table, name, { command, kind, roles, using, withCheck })`: `command` is `'all'` (default), `'select'`, `'insert'`, `'update'` or `'delete'`; `kind` is `'permissive'` (default) or `'restrictive'`; `roles` are role names or `'public'`, `'current_user'`, `'current_role'`, `'session_user'`. - `alterPolicy(table, name, { roles, using, withCheck, rename })`, `dropPolicy(table, name, { ifExists, cascade })`. - **A string condition is SQL you write**: not escaped, never build it from user input. A where object (`{ edits: { [Op.gt]: 0 } }`) compiles like a partial-index condition and its values are escaped as literals. See [Security](/security). - Policies usually read a per-request setting. Set it with the `settings` option of a transaction ([Sessions](/guide/sessions)) and refer to it with `current_setting('app.tenant_id')::int`. ### Unlogged and temporary tables (postgrelize extension) ```ts const Cache = sequelize.define( 'Cache', { key: DataTypes.TEXT }, { tableName: 'cache', unlogged: true }, ); await Cache.sync(); await sequelize.transaction(async (transaction) => { await queryInterface.createTable( 'scratch', { n: DataTypes.INTEGER }, { temporary: true, transaction }, ); await sequelize.query('INSERT INTO scratch (n) VALUES (1)', { transaction }); }); ``` - `unlogged: true` (on `createTable` options and on the model options used by `sync`) creates an `UNLOGGED` table: writes skip the write-ahead log, so they are faster, but the table is emptied after a crash and is not replicated. Use it for caches and staging data. - `temporary: true` creates a `TEMPORARY` table that exists only for the database session and is dropped when the connection closes. A pool hands out different connections, so create and use the table inside one transaction (pass `transaction`), or run with a single connection. A temporary table cannot have a `schema`, and it cannot be combined with `unlogged`. - Existing tables are not converted: `sync({ alter: true })` does not change the persistence of a table that already exists. ### API reference - [`QueryInterface`](/api/classes/QueryInterface) ## Constraints and indexes Source: https://tormozz48.github.io/postgrelize/guide/constraints-indexes Sections marked (postgrelize extension) describe options, methods and statements that Sequelize v6 does not have. Everything else here behaves as in v6. All extensions are listed on the [extensions page](/extensions/). `addIndex` and `addConstraint` cover the Sequelize v6 shapes (see [Schema](/guide/schema)). This page lists the PostgreSQL additions. They are new options: existing option shapes and defaults do not change. ### Expression indexes (postgrelize extension) ```ts await queryInterface.addIndex('accounts', { name: 'accounts_lower_email', unique: true, fields: [{ expression: 'lower(email)' }], include: ['nick'], }); await queryInterface.addIndex('accounts', { name: 'accounts_nick_search', fields: [ { name: 'nick', collate: 'C', operator: 'text_pattern_ops', order: 'DESC', nulls: 'LAST' }, ], }); ``` - An index field is a column (`'email'`, `{ name: 'email' }`) or an expression (`{ expression: 'lower(email)' }`). Every field accepts `order`, `nulls` (`'FIRST'` / `'LAST'`), `collate` (a quoted collation name) and `operator` (operator class); `include` adds covering columns. - **The `expression` is SQL you write.** It is wrapped in parentheses and is not escaped: never build it from user input. See [Security](/security). - A name cannot be derived from an expression, so an index with an expression field needs an explicit `name`. - Model `indexes` accept the same fields. An expression must be immutable (PostgreSQL rejects `date_trunc` on `timestamptz`, for example). ### EXCLUDE constraints (postgrelize extension) ```ts await queryInterface.addConstraint('bookings', { type: 'exclude', name: 'bookings_no_overlap', using: 'gist', exclude: [ { name: 'room', with: '=' }, { name: 'period', with: '&&' }, ], }); ``` - `addConstraint(table, { type: 'exclude', exclude: [{ name | expression, with }], using, where, include, deferrable })`. Each element is a column or an expression with the operator it is compared with (`with`), and accepts `collate`, `operator` (operator class), `order` and `nulls`. - Scalar columns with `=` in a `gist` / `spgist` exclusion need the `btree_gist` extension (`createExtension('btree_gist')`). - The operator is checked against a pattern of operator characters (`=`, `&&`, `-|-`, `<->`); a name or expression cannot be smuggled in. Expressions are trusted SQL (see above). `where` is a where-object compiled like a partial-index condition; `deferrable` takes a `Deferrable` constant. - Without `name` the constraint is called `
__excl`; with an expression element give a `name`. - A violation raises `ExclusionConstraintError`. ### NOT VALID and VALIDATE CONSTRAINT (postgrelize extension) ```ts await queryInterface.addConstraint('products', { type: 'check', fields: ['price'], name: 'products_price_positive', where: { price: { [Op.gt]: 0 } }, notValid: true, }); await sequelize.query('UPDATE products SET price = 1'); await queryInterface.validateConstraint('products', 'products_price_positive'); ``` `notValid: true` (check and foreign key constraints) adds the constraint without scanning existing rows, so it takes only a short lock; new and updated rows are checked at once. After cleaning the old rows, `validateConstraint(table, name)` scans the table without blocking writes. Using `notValid` with another constraint type throws. ### Declarative partitioning (postgrelize extension) ```ts await queryInterface.createTable( 'events', { at: DataTypes.DATE, kind: DataTypes.TEXT }, { partitionBy: { strategy: 'range', columns: ['at'] } }, ); await queryInterface.createPartition('events', 'events_2026', { from: ['2026-01-01'], to: ['2027-01-01'], }); await queryInterface.createPartition('events', 'events_other', { default: true }); await queryInterface.createTable('events_2027', { at: DataTypes.DATE, kind: DataTypes.TEXT }); await queryInterface.attachPartition('events', 'events_2027', { from: ['2027-01-01'], to: ['2028-01-01'], }); await queryInterface.detachPartition('events', 'events_2026'); ``` - `createTable(name, attributes, { partitionBy: { strategy: 'range' | 'list' | 'hash', columns } })` creates the partitioned parent. Columns are names or `{ name | expression, collate, operator }`; an `expression` is trusted SQL. Primary and unique keys must include every partition column (PostgreSQL rule). - `createPartition(parent, name, bound, { partitionBy, ifNotExists })` bounds: `{ in: [...] }` for list, `{ from: [...], to: [...] }` for range (`PartitionBound.MINVALUE` / `MAXVALUE` are markers, a string `'MINVALUE'` is just a string), `{ modulus, remainder }` for hash and `{ default: true }`. Values are literals. `partitionBy` makes the partition itself partitioned. - `attachPartition(parent, existingTable, bound)` and `detachPartition(parent, partition, { concurrently, finalize })`. `concurrently` cannot run inside a transaction. - Partitions are real tables: `showAllTables` lists them, `describeTable` works on parent and partitions, and queries and models on the parent work as usual. `sync` does not create partitions: create them with `createPartition`. ### PostgreSQL 18 constraints (postgrelize extension) ```ts await queryInterface.addConstraint('rooms', { type: 'primary key', name: 'rooms_pk', fields: ['id', 'validAt'], withoutOverlaps: true, }); await queryInterface.addConstraint('stays', { type: 'foreign key', name: 'stays_room_fk', fields: ['roomId', 'during'], period: true, references: { table: 'rooms', field: 'id', fields: ['id', 'validAt'] }, }); ``` ```ts await queryInterface.addConstraint('stays', { type: 'check', name: 'stays_nights_positive', fields: ['nights'], where: { nights: { [Op.gt]: 0 } }, enforced: false, }); ``` These options render PostgreSQL 18 syntax. Older servers reject the statement with their own syntax error; nothing is sent differently by version. - `withoutOverlaps: true` (unique and primary key): the last field is a range or multirange column and no two rows with equal other fields may overlap. Scalar columns in a temporal key need the `btree_gist` extension. - `period: true` (foreign key): the last field and the last referenced field are `PERIOD` columns; the referenced table needs a `withoutOverlaps` key. List the referenced columns with `references.fields` (`references.field` stays the single-column form). - `enforced: false` (check and foreign key): `NOT ENFORCED` records the constraint without checking it, so it documents a rule or helps the planner. It can be combined with `notValid`. ## Errors Source: https://tormozz48.github.io/postgrelize/guide/errors postgrelize throws the Sequelize v6 error classes, exported from the package root, so `instanceof` checks and `error.name` strings from v6 code keep working. Constraint violations, validation failures, timeouts and connection problems each have their own class; everything the server rejects that has no specific class is a `DatabaseError`. The original `pg` error is always available as `error.parent` (also `error.original`), with the PostgreSQL error `code`, `constraint`, `table`, `detail` and the rest of its fields. ### Class hierarchy | Class | Thrown when | Useful fields | | ---------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | `ValidationError` | A model validator, `allowNull: false` or a type check fails before the query runs | `errors` (`ValidationErrorItem[]`: `path`, `message`, `type`, `value`, `origin`) | | `UniqueConstraintError` (extends `ValidationError`) | `23505` unique violation | `fields`, `errors`, `parent`, `sql` | | `DatabaseError` | Any other server error | `parent` (the `pg` error, `parent.code`), `sql`, `parameters` | | `ForeignKeyConstraintError` (extends `DatabaseError`) | `23503` foreign key violation | `table`, `fields`, `index` (constraint name) | | `ExclusionConstraintError` (extends `DatabaseError`) | `23P01` exclusion violation | `constraint`, `fields`, `table` | | `UnknownConstraintError` (extends `DatabaseError`) | Exported for v6 compatibility (a constraint that does not exist was referenced); the library itself reports a missing constraint as a plain `DatabaseError` | `constraint`, `table` | | `TimeoutError` (extends `DatabaseError`) | `57014` the statement was cancelled (`statement_timeout`, [`statementTimeout`](./sessions#statement-timeout-per-query)) | as `DatabaseError` | | `EmptyResultError` | `rejectOnEmpty` found no row | | | `OptimisticLockError` | Saving a stale instance of a model with `version: true` | `modelName`, `where`, `values` | | `ConnectionError` and subclasses | The connection could not be made or was lost | `parent` | | `AggregateError`, `BulkRecordError`, `EagerLoadingError`, `InstanceError`, `AssociationError`, `SequelizeScopeError`, `QueryError` | Library-level problems: failed bulk records, bad `include`, wrong instance use, unknown scope | per class | `ConnectionError` subclasses: `ConnectionRefusedError`, `AccessDeniedError`, `HostNotFoundError`, `HostNotReachableError`, `InvalidConnectionError`, `ConnectionTimedOutError`, `ConnectionAcquireTimeoutError` (the pool had no free connection within `pool.acquire`). The `error.name` of each keeps the v6 spelling (`SequelizeUniqueConstraintError`, ...). ### Unique violations `fields` maps the violated columns to the offered values, and `errors` has one `ValidationErrorItem` per column, so the same code can show per-field messages for both validation and unique failures: ```ts try { await Author.create({ email: 'ann@example.com', name: 'Ann again' }); } catch (error) { if (!(error instanceof UniqueConstraintError)) throw error; // error.fields: { email: 'ann@example.com' } // error.errors[0].type === 'unique violation', error.errors[0].path === 'email' // error.parent.code === '23505': the original pg error if (error.fields.email !== 'ann@example.com') throw new Error('unexpected fields', { cause: error }); } ``` ### Foreign key violations ```ts try { await Book.create({ title: 'Orphan', authorId: 999 }); } catch (error) { if (!(error instanceof ForeignKeyConstraintError)) throw error; // error.table === 'Authors', error.index is the constraint name, error.fields lists the columns if (error.parent.code !== '23503') throw new Error('unexpected code', { cause: error }); } ``` ### Validation errors Validators run before the query; the error lists every failing attribute, not just the first. See [Hooks and validation](./hooks-validation#validators) for the validators themselves. ```ts try { await Author.create({ email: 'bob@example.com', name: 'B' }); } catch (error) { if (!(error instanceof ValidationError)) throw error; for (const item of error.errors) { // item.path === 'name', item.type === 'Validation error', item.message, item.value === 'B' if (item.path !== 'name') throw new Error('unexpected path', { cause: error }); } } ``` ### Missing rows `findOne`, `findByPk` and `findAll` resolve to `null` or `[]` by default. Pass `rejectOnEmpty: true` (or an `Error` instance to throw your own) to turn a missing row into an exception: ```ts const missing = await Author.findOne({ where: { email: 'nobody@example.com' }, rejectOnEmpty: true, }) .then(() => null) .catch((error: unknown) => error); if (!(missing instanceof EmptyResultError)) throw new Error('expected EmptyResultError'); ``` ### Optimistic locking Set `version: true` in the model options and every update becomes `UPDATE ... WHERE id = $1 AND version = $2`. A second writer holding an older copy gets an `OptimisticLockError` instead of silently overwriting the first: ```ts const ticket = await Ticket.create({ subject: 'printer' }); const sameTicket = await Ticket.findByPk(ticket.get('id') as number); await ticket.update({ subject: 'printer on fire' }); const stale = await sameTicket!.update({ subject: 'paper jam' }).catch((error: unknown) => error); if (!(stale instanceof OptimisticLockError)) throw new Error('expected OptimisticLockError'); ``` ### Timeouts (postgrelize extension) `statementTimeout` is a postgrelize option that cancels one slow statement on the server and throws `TimeoutError`; the connection stays usable for the next query. `TimeoutError` is a `DatabaseError`, so a generic handler still catches it. ```ts const slow = await sequelize .query('SELECT pg_sleep(5)', { statementTimeout: 50 }) .catch((error: unknown) => error); if (!(slow instanceof TimeoutError)) throw new Error('expected TimeoutError'); // TimeoutError extends DatabaseError, so a generic handler still catches it if (!(slow instanceof DatabaseError)) throw new Error('TimeoutError is a DatabaseError'); ``` ### Any other server error Everything without a dedicated class is a `DatabaseError`. Branch on `error.parent.code` (the SQLSTATE) when you need to tell them apart: `40001` serialization failure and `40P01` deadlock (retry the whole transaction), `55P03` lock not available (`noWait`), `22012` division by zero, `42P01` undefined table. ```ts const bad = await sequelize.query('SELECT 1 / 0').catch((error: unknown) => error); if (!(bad instanceof DatabaseError)) throw new Error('expected DatabaseError'); // bad.parent.code === '22012' (division_by_zero), bad.sql is the statement that failed if (bad.parent.code !== '22012') throw new Error('unexpected code'); ``` Retrying is up to the application, or use the [`retry` option](./sessions#retrying-failed-queries) for connection and transaction-start failures. Errors inside a [transaction](./transactions#errors) abort it: roll back and run the transaction again. ### API reference - [`Error`](/api/classes/Error) (the base class, also exported as `BaseError`), [`ValidationError`](/api/classes/ValidationError), [`ValidationErrorItem`](/api/classes/ValidationErrorItem), [`UniqueConstraintError`](/api/classes/UniqueConstraintError) - [`DatabaseError`](/api/classes/DatabaseError), [`ForeignKeyConstraintError`](/api/classes/ForeignKeyConstraintError), [`ExclusionConstraintError`](/api/classes/ExclusionConstraintError), [`TimeoutError`](/api/classes/TimeoutError) - [`ConnectionError`](/api/classes/ConnectionError), [`EmptyResultError`](/api/classes/EmptyResultError), [`OptimisticLockError`](/api/classes/OptimisticLockError) ## Connection, pool and logging Source: https://tormozz48.github.io/postgrelize/guide/connection One `Sequelize` instance owns one connection pool (or one pool per replica, see [read replicas](./sessions#read-replicas)). Create it once, share it across the application and call `sequelize.close()` on shutdown. Every option of the constructor is listed with its type and default in the [connection option reference](/reference/options/connection#sequelizeoptions); this page shows how they fit together. ### Connection URI A URI carries host, port, database and credentials. Options given next to it override the values in the URI: ```ts const fromUrl = new Sequelize(url, { logging: false, dialectOptions }); await fromUrl.authenticate(); // throws a ConnectionError subclass when the server is unreachable await fromUrl.close(); ``` `authenticate()` runs `SELECT 1` and rejects with a [`ConnectionError`](./errors) subclass when the server cannot be reached, so it is a good startup check. ### Options object The same settings can be given as separate options, together with the pool, session and model defaults: ```ts const fromOptions = new Sequelize({ host, port, database, username, password, dialectOptions, logging: false, timezone: '+00:00', // session time zone, the default define: { underscored: true, freezeTableName: true }, // defaults for every model pool: { max: 10, idle: 10_000, acquire: 30_000 }, }); ``` | Option | What it does | | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `dialect` | Optional; the only accepted value is `'postgres'`. | | `ssl` | TLS settings passed to `pg` (`true`, or `{ ca, rejectUnauthorized, ... }`). `dialectOptions` takes any other `pg` pool setting. | | `pool` | `max` (default 5), `idle` (10 000 ms), `acquire` (60 000 ms, then `ConnectionAcquireTimeoutError`), `maxUses`. `min` and `evict` are accepted and ignored. | | `timezone` | Session time zone; default `'+00:00'`. | | `define` | Defaults for every model: `timestamps`, `underscored`, `freezeTableName`, `paranoid`, ... | | `minifyAliases` | Shorten generated aliases of deep includes to stay inside PostgreSQL's 63-byte identifier limit. | | `hooks` | Sequelize-level [hooks](./hooks-validation#sequelize-level-hooks) for every model. | | `retry` | Retry failed connection acquisition and transaction starts; see [retrying](./sessions#retrying-failed-queries). | | `replication` | Read replicas and a writer; see [read replicas](./sessions#read-replicas). | | `statementCache` (postgrelize extension) | Opt-in named prepared statements, bounded per connection; see [performance](./performance#prepared-statements). | | `inAsAnyThreshold` (postgrelize extension) | Length from which `IN (...)` lists compile to `= ANY($1)`, so one statement text serves every list length. | ### Logging `logging` receives the SQL text of every executed query with the values inlined as literals, like Sequelize v6, so a logged statement can be run as it is. The query itself is still sent to the server with bound parameters; the second argument is `{ bind, parameterizedSql }` (the bound values and the statement as sent, `$1`, `$2`, …; `parameterizedSql` is a postgrelize extension). Use `false` to silence it and `benchmark: true` to receive the duration in milliseconds as the second argument. A per-query `logging` option overrides the instance value. ```ts const statements: string[] = []; const logged = new Sequelize({ host, port, database, username, password, dialectOptions, logging: (sql) => statements.push(sql), // called with the SQL text of every query benchmark: true, // also pass the duration in ms as the second argument }); await logged.query('SELECT 1'); await logged.close(); ``` ### Wrapping `sequelize.query` Like in Sequelize v6, the queries of models, instances and the `QueryInterface` run through the instance method `sequelize.query`, so a wrapper or an override of it sees the SQL of every statement (to add a route comment, to measure, to trace). The wrapper receives the SQL as a string and the bound values in `options.bind`; it must hand `options` on to the original method unchanged (the options carry what tells `query` that the statement comes from a model). A wrapper written for v6 that also handles a `{ query, bind }` object as the first argument works with both libraries. ```ts const original = sequelize.query.bind(sequelize); sequelize.query = (sql, options) => original(typeof sql === 'string' ? `/* route:web */ ${sql}` : sql, options); ``` ### Prepared statements and long `IN` lists (postgrelize extension) Two constructor options exist only in postgrelize. `statementCache` turns on named prepared statements, `inAsAnyThreshold` makes long `IN` lists use one statement shape: ```ts const cached = new Sequelize({ host, port, database, username, password, dialectOptions, logging: false, statementCache: { max: 50 }, // postgrelize extension: named prepared statements, 50 per connection inAsAnyThreshold: 50, // postgrelize extension: IN lists of 50+ values compile to = ANY($1) }); ``` ### Pool counters and shutdown `sequelize.connectionManager.pool` reports live `size`, `available`, `using`, `waiting` and `maxSize`; useful for health checks. The routing and raw-connection details are in [Sessions and scaling](./sessions#routing-connections). ```ts const Note = fromOptions.define('Note', { body: DataTypes.TEXT }); await Note.sync({ force: true }); // freezeTableName: the table is "Note", columns are snake_case const { size, using } = fromOptions.connectionManager.pool; // live pool counters await fromOptions.close(); // call it on shutdown; pending connections are closed ``` ### API reference - [`Sequelize`](/api/classes/Sequelize), [`SequelizeOptions`](/api/type-aliases/SequelizeOptions), [`PoolOptions`](/api/type-aliases/PoolOptions) - [`ConnectionManagerContract`](/api/interfaces/ConnectionManagerContract), [`ConnectionPool`](/api/interfaces/ConnectionPool), [`PoolCounters`](/api/interfaces/PoolCounters) ## Reference Source: https://tormozz48.github.io/postgrelize/reference/ Find what you need by entity or by task. Items marked (postgrelize extension) are postgrelize extensions that Sequelize v6 does not have; the full list is on the [extensions page](/extensions/). ### By entity | Entity | Guide | Options | API | | ------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ------------------------------------------------------------ | | Models and attributes | [Models](/guide/models) | [Model options](/reference/options/models) | [`Model`](/api/classes/Model) | | Data types | [Data types](/guide/models#data-types) | [Model options](/reference/options/models#attributeoptions) | [`DataTypes`](/api/variables/DataTypes) | | Decorators | [Decorators](/guide/decorators) | [Model options](/reference/options/models) | [API index](/api/) | | Associations | [Associations](/guide/associations) | [Model options](/reference/options/models#associationoptions) | [`Association`](/api/classes/Association) | | Finders, aggregates | [Querying](/guide/querying) | [Query options](/reference/options/queries) | [`Model.findAll`](/api/classes/Model#findall) | | Scopes | [Scopes](/guide/querying#scopes) | [Query options](/reference/options/queries) | [`Model.scope`](/api/classes/Model#scope) | | Writes | [Querying](/guide/querying), [Upserts](/guide/upserts), [Bulk writes](/guide/bulk-writes) | [Write options](/reference/options/writes) | [`Model.create`](/api/classes/Model#create) | | Raw SQL | [Raw SQL](/guide/querying#raw-sql) | [Connection options](/reference/options/connection#queryoptions) | [`Sequelize.query`](/api/classes/Sequelize#query) | | Transactions | [Transactions](/guide/transactions) | [Connection options](/reference/options/connection#transactionoptions) | [`Transaction`](/api/classes/Transaction) | | Hooks | [Hooks and validation](/guide/hooks-validation#hooks) | [Model options](/reference/options/models) | [`HookRegistry`](/api/interfaces/HookRegistry) | | Validation | [Validation](/guide/hooks-validation#validators) | [Model options](/reference/options/models#validateoptions) | [`ValidationError`](/api/classes/ValidationError) | | Errors | [Errors](/guide/errors) | - | [`DatabaseError`](/api/classes/DatabaseError) | | Connection, pool | [Connection](/guide/connection) | [Connection options](/reference/options/connection) | [`Sequelize`](/api/classes/Sequelize) | | Replicas, retry, sessions | [Sessions and scaling](/guide/sessions) | [Connection options](/reference/options/connection#replicationoptions) | [`ReplicationOptions`](/api/type-aliases/ReplicationOptions) | | Schema, sync, DDL | [Schema](/guide/schema), [Schema objects](/guide/schema-objects), [Constraints and indexes](/guide/constraints-indexes) | [Schema options](/reference/options/schema) | [`QueryInterface`](/api/classes/QueryInterface) | ### By task | I want to... | Use | Where | | ----------------------------------------------- | ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | Define a model | `sequelize.define`, `class extends Model` + `init`, or decorators | [Models](/guide/models), [Decorators](/guide/decorators) | | Store JSON, arrays, ranges, UUIDs, geometry | `DataTypes.JSONB`, `ARRAY`, `RANGE`, `UUID`, geometric types | [Models: data types](/guide/models#data-types) | | Use an identity or generated column | `identity`, `generated` attribute options (postgrelize extension) | [Identity and generated columns](/guide/models#identity-generated) | | Filter rows with operators | `where` with `Op` | [Filtering](/guide/querying#filtering) | | Search text (full-text, trigram, `SIMILAR TO`) | `toTsQuery`, `tsRank`, `trigramSimilarity` (postgrelize extension) | [Operator and search helpers](/guide/querying#operator-and-search-helpers) | | Paginate | `limit`, `offset`; keyset with `tuple` (postgrelize extension) | [Paginating](/guide/querying#selecting-ordering-and-paginating), [Keyset](/guide/advanced-queries#row-comparison-and-keyset-pagination) | | Count and aggregate | `count`, `sum`, `max`, `group` | [Aggregates](/guide/querying#aggregates-and-expressions) | | Load related rows | `include` | [Eager loading](/guide/associations#eager-loading) | | Take the latest N rows per parent | `include` with `lateral` (postgrelize extension) | [LATERAL joins](/guide/advanced-queries#lateral-joins-and-top-n-per-parent) | | Reuse a filter | scopes | [Scopes](/guide/querying#scopes) | | Run raw SQL safely | `sequelize.query` with `replacements` or `bind` | [Raw SQL](/guide/querying#raw-sql) | | Lock rows | `lock`, `skipLocked`, `noWait` (postgrelize extension) | [Locking](/guide/querying#locking), [Row locks](/guide/transactions#row-locks) | | Insert or update in one statement | `upsert`, `onConflict` (postgrelize extension) | [Upserts](/guide/upserts) | | Read old values after an update | `returningOld` (postgrelize extension) (PostgreSQL 18) | [RETURNING OLD](/guide/upserts#old-values-with-returningold-postgresql-18) | | Insert many rows quickly | `bulkCreate` with `unnest` (postgrelize extension), `copyFrom` (postgrelize extension) | [Bulk writes](/guide/bulk-writes) | | Update or delete using another table | `updateStatement`, `deleteStatement` (postgrelize extension) | [UPDATE ... FROM](/guide/bulk-writes#update-from) | | Sync rows from a source table | `Model.merge` (postgrelize extension) | [MERGE](/guide/bulk-writes#merge) | | Export a table | `copyTo` (postgrelize extension) | [Export with `copyTo`](/guide/bulk-writes#export-with-copyto) | | Process a huge table in batches | `findEach` (postgrelize extension) | [`findEach`](/guide/advanced-queries#server-side-cursors-with-findeach) | | Write recursive or multi-step queries | CTEs: `with`, `source` (postgrelize extension) | [Common table expressions](/guide/advanced-queries#common-table-expressions) | | Rank or number rows | `over(...)` window functions (postgrelize extension) | [Window functions](/guide/advanced-queries#window-functions) | | Run several statements atomically | `sequelize.transaction` | [Transactions](/guide/transactions) | | Pick an isolation level or read-only mode | `isolationLevel`, `readOnly`, `deferrable` (postgrelize extension) | [Transactions](/guide/transactions#read-only-transactions) | | Serialize work across processes | `withAdvisoryLock` (postgrelize extension) | [Advisory locks](/guide/sessions#advisory-locks) | | Push events between processes | `listen`, `notify` (postgrelize extension) | [LISTEN / NOTIFY](/guide/sessions#listen-notify) | | Send reads to replicas | `replication` (postgrelize extension) | [Read replicas](/guide/sessions#read-replicas) | | Stop a slow query | `statementTimeout` (postgrelize extension) | [Statement timeout](/guide/sessions#statement-timeout-per-query) | | Retry transient failures | `retry` | [Retrying](/guide/sessions#retrying-failed-queries) | | Handle a unique or foreign key violation | `UniqueConstraintError`, `ForeignKeyConstraintError` | [Errors](/guide/errors) | | Validate input | validators, `validationSchema` (postgrelize extension) (zod, valibot) | [Hooks and validation](/guide/hooks-validation) | | React to create / update / destroy | hooks | [Hooks](/guide/hooks-validation#hooks) | | Create tables, indexes and constraints | `sync`, `QueryInterface.createTable`, `addIndex` | [Schema](/guide/schema), [Constraints and indexes](/guide/constraints-indexes) | | Use views, sequences, triggers, partitions, RLS | `QueryInterface.createView`, `createPartition`, `createPolicy` (postgrelize extension) | [Schema objects](/guide/schema-objects), [Partitioning](/guide/constraints-indexes#declarative-partitioning) | | Tune pool size, logging, timezone | `Sequelize` constructor options | [Connection](/guide/connection) | | Move from Sequelize v6 | change the import | [Migrating](/guide/migrating) | ## Using postgrelize with LLMs and agents Source: https://tormozz48.github.io/postgrelize/guide/llm postgrelize ships documentation in formats that language models and coding agents read well. Pick the one that fits how your agent works. All of them are generated from the same tested code, so they do not drift from the library. | Format | Where | Use it when | | ---------------- | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `llms.txt` | | the agent browses the web: an index of the guide, reference and API pages | | `llms-full.txt` | | the agent can load one large file: every guide page, the security page, the PostgreSQL coverage matrix, the Sequelize differences and the whole API reference | | `llm/USAGE.md` | inside the npm package: `node_modules/postgrelize/llm/USAGE.md` | the agent sees only your project and `node_modules`: one compact cheat sheet | | Agent Skill | inside the npm package: `node_modules/postgrelize/skills/postgrelize/` | the agent supports Skills (Claude Code and compatible tools) | | TSDoc in `.d.ts` | `node_modules/postgrelize/dist/*.d.ts` | always: every public item has a description, `@param`, `@throws` and an `@example` | ### llms.txt and llms-full.txt Both follow the [llms.txt convention](https://llmstxt.org): `llms.txt` is a markdown index (title, summary, sections with links and one-line descriptions); `llms-full.txt` is the full text. They are built with the site (`npm run docs`) from `docs/guide`, the reference pages and `docs/api`; code blocks come from `docs/examples` and the coverage matrix from `docs/coverage/postgresql-features.ts`. Give the URL to your agent, or add it to your project instructions: ```md For postgrelize usage, read https://tormozz48.github.io/postgrelize/llms-full.txt ``` ### USAGE.md in the package `llm/USAGE.md` covers install, connecting, defining models, CRUD, operators, associations, transactions, hooks, upserts and other PostgreSQL features, schema, errors, the most common mistakes, differences from Sequelize v6, unsupported features and security rules. Reference it from `AGENTS.md` or `CLAUDE.md`: ```md postgrelize: read node_modules/postgrelize/llm/USAGE.md before writing database code. ``` ### Agent Skill The package contains a ready-made skill: `skills/postgrelize/SKILL.md` with `reference/*.md` files that the agent loads on demand (querying, writing, schema, associations, transactions and sessions, errors, security, migrating from Sequelize, PostgreSQL features). Install it for Claude Code by copying the folder: ```bash # project-level (shared with the team through git) mkdir -p .claude/skills cp -r node_modules/postgrelize/skills/postgrelize .claude/skills/ # or for all your projects cp -r node_modules/postgrelize/skills/postgrelize ~/.claude/skills/ ``` The skill activates when you write or migrate code that uses postgrelize or Sequelize v6 on PostgreSQL. Other agents that read the same `SKILL.md` format can use the same folder; agents without Skills support can read `SKILL.md` and the reference files directly. ### How the files stay correct - Every snippet in `USAGE.md` and the skill is a region of a file in `docs/examples`, mostly `docs/examples/llm-usage.ts`. The `docs` test project runs these files against PostgreSQL and fails on unexpected results. - `npm run llm:build` renders the templates in `docs/llm` into `llm/` and `skills/`; a test fails when the committed files differ from a fresh render. - The "not supported" lists come from the PostgreSQL coverage matrix. - When you change public API or behaviour, update the matching region in `docs/examples/llm-usage.ts` and run `npm run llm:build`. ## Upserts and RETURNING Source: https://tormozz48.github.io/postgrelize/guide/upserts Sections marked (postgrelize extension) describe options, methods and statements that Sequelize v6 does not have. Everything else here behaves as in v6. All extensions are listed on the [extensions page](/extensions/). Sequelize v6 can upsert only with fixed column lists (`upsert`, `bulkCreate({ updateOnDuplicate })`). postgrelize keeps those and adds the `onConflict` option, which exposes the full `INSERT ... ON CONFLICT` clause of PostgreSQL: any conflict target, expression updates, a `WHERE` condition and `DO NOTHING`. `Model.insert()` returns every written row with a flag telling whether it was inserted or updated. The examples use this model, with a composite unique key and a partial unique index: ```ts class Counter extends Model, InferCreationAttributes> { declare id: CreationOptional; declare tenant: string; declare key: string; declare hits: CreationOptional; declare version: CreationOptional; declare tags: CreationOptional; declare archived: CreationOptional; } Counter.init( { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, tenant: { type: DataTypes.TEXT, allowNull: false, unique: 'counters_tenant_key' }, key: { type: DataTypes.TEXT, allowNull: false, unique: 'counters_tenant_key' }, hits: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 }, version: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 1 }, tags: { type: DataTypes.ARRAY(DataTypes.TEXT), allowNull: false, defaultValue: [] }, archived: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }, }, { sequelize, tableName: 'counters', timestamps: false, indexes: [ { name: 'counters_active_key', unique: true, fields: ['key'], where: { archived: false } }, ], }, ); await sequelize.sync(); await Counter.bulkCreate([ { tenant: 't1', key: 'a', hits: 1, tags: ['x'] }, { tenant: 't1', key: 'b', hits: 2, version: 5 }, ]); ``` ### Sequelize v6 upserts These work unchanged: ```ts const [row, created] = await Counter.upsert({ tenant: 't1', key: 'a', hits: 5 }); // row.hits === 5; created is null on PostgreSQL, as in Sequelize v6 await Counter.bulkCreate([{ tenant: 't1', key: 'b', hits: 7 }], { updateOnDuplicate: ['hits'], conflictAttributes: ['tenant', 'key'], }); ``` `upsert` picks the conflict target from the unique keys of the given attributes (or the primary key); `conflictFields` sets it explicitly. As in Sequelize v6 on PostgreSQL, the second element of the result is `null`. `bulkCreate` takes `updateOnDuplicate`, `conflictAttributes`, `conflictWhere` (for partial indexes) and `ignoreDuplicates`. ### `onConflict` (postgrelize extension) `onConflict` is accepted by `Model.insert`, `create`, `bulkCreate`, `upsert` and [`insertFrom`](./bulk-writes#insert-select). It has two parts: ```ts onConflict: { target: ['tenant', 'key'], // or { constraint: 'name' }, or { columns, where } for partial indexes action: 'nothing', // or { update: [...attributes] | { attr: value | expression }, where? } } ``` #### Expression updates and `wasInserted` (postgrelize extension) `Model.insert(rows, options)` inserts one row or an array of rows and returns model instances for every row written. `instance.wasInserted` is `true` for inserted rows and `false` for rows updated on conflict: ```ts const rows = await Counter.insert( [ { tenant: 't1', key: 'a', hits: 10 }, { tenant: 't1', key: 'c', hits: 3 }, ], { onConflict: { target: ['tenant', 'key'], action: { update: { hits: literal('"Counter"."hits" + EXCLUDED."hits"') } }, }, }, ); const report = rows.map((counter) => [counter.key, counter.hits, counter.wasInserted]); // report: [['a', 15, false], ['c', 3, true]] ``` Inside `action.update`, `EXCLUDED` is the proposed row and the model name is the alias of the existing row. Use `excluded('attr')` for a column of the proposed row, `col('Counter.attr')` for the existing one, and `fn` / `literal` for anything else. `updatedAt` is set automatically. #### Conditional updates (postgrelize extension) `action.where` adds `DO UPDATE ... WHERE`. Rows that fail the condition are left alone and are not returned: ```ts const newer = await Counter.insert( [ { tenant: 't1', key: 'a', hits: 100, version: 2 }, { tenant: 't1', key: 'b', hits: 100, version: 3 }, ], { onConflict: { target: ['tenant', 'key'], action: { update: ['hits', 'version'], where: { version: { [Op.lt]: excluded('version') } }, }, }, }, ); // only 'a' is updated: 'b' already has version 5; rows that were skipped are not returned ``` This is the usual pattern for "apply only newer versions" in sync jobs and event consumers. #### Conflict targets (postgrelize extension) | `target` | SQL | | -------------------------------------------------- | ------------------------------------------------------ | | `['tenant', 'key']` | `ON CONFLICT ("tenant", "key")` | | `[fn('lower', col('email'))]` | `ON CONFLICT (lower("email"))` — expression index | | `{ columns: ['key'], where: { archived: false } }` | `ON CONFLICT ("key") WHERE ...` — partial unique index | | `{ constraint: 'counters_tenant_key' }` | `ON CONFLICT ON CONSTRAINT "counters_tenant_key"` | | omitted (only with `action: 'nothing'`) | `ON CONFLICT DO NOTHING` — any unique violation | ```ts await Counter.bulkCreate([{ tenant: 't1', key: 'a', tags: ['y'] }], { onConflict: { target: { constraint: 'counters_tenant_key' }, action: { update: { tags: fn('array_cat', col('Counter.tags'), excluded('tags')) } }, }, }); const [partial] = await Counter.insert( { tenant: 't9', key: 'c', hits: 50 }, { onConflict: { target: { columns: ['key'], where: { archived: false } }, action: { update: { hits: excluded('hits') } }, }, }, ); // partial.tenant === 't1': the existing active row with key 'c' was updated const skipped = await Counter.bulkCreate( [ { tenant: 't1', key: 'b' }, { tenant: 't1', key: 'n' }, ], { onConflict: { action: 'nothing' } }, ); // skipped: only the inserted row 'n' ``` With `action: 'nothing'`, skipped rows are not returned: `bulkCreate` and `insert` resolve to the inserted rows only. `create` with `action: 'nothing'` returns the unsaved instance (`isNewRecord` stays `true`) when the row was skipped. Options are checked before any SQL runs: an unknown attribute, an `update` without a `target`, an empty update list, or `onConflict` combined with `ignoreDuplicates` / `updateOnDuplicate` throws an `Error`. #### `upsert` with `onConflict` With `onConflict`, `upsert` resolves to `[instance, created]` with a real boolean: ```ts const [visit, isNew] = await Counter.upsert( { tenant: 't2', key: 'home', hits: 1 }, { onConflict: { target: ['tenant', 'key'], action: { update: { hits: literal('"Counter"."hits" + 1') } }, }, }, ); // isNew === true on the first call, false afterwards (visit.hits is then incremented) ``` ### RETURNING PostgreSQL returns written rows with `RETURNING`. Besides `create` and `save` (which always read the row back), postgrelize supports: - `Model.update(values, { where, returning: true })` → `[count, instances]` (as in v6); - `Model.destroy({ where, returning: true })` → the deleted instances instead of a count (an extension). ```ts const [updatedCount, updated = []] = await Counter.update( { hits: 0 }, { where: { key: ['a', 'b'] }, returning: true }, ); const deleted = await Counter.destroy({ where: { key: 'n' }, returning: true }); // deleted: the removed Counter instances instead of a count ``` ### Old values with `returningOld` (PostgreSQL 18+) (postgrelize extension) PostgreSQL 18 can return the row as it was before the statement (`RETURNING OLD.*`). With `returningOld: true`, every returned instance gets `oldValues`: the attribute values before the write, or `null` when the row was inserted. ```ts const [, changed = []] = await Stock.update( { qty: literal('qty + 10') }, { where: { sku: 'a' }, returning: true, returningOld: true }, ); const [stock] = changed; // stock.get('qty') === 11, stock.oldValues === { id: 1, sku: 'a', qty: 1 } ``` ```ts const written = await Stock.insert( [ { sku: 'b', qty: 5 }, { sku: 'z', qty: 7 }, ], { onConflict: { target: ['sku'], action: { update: { qty: excluded('qty') } } }, returningOld: true, }, ); const previous = written.map((row) => row.oldValues?.['qty'] ?? null); // previous: [2, null] — 'b' was updated from 2, 'z' was inserted ``` `returningOld` is accepted by `Model.update` (together with `returning: true`), `Model.insert`, `insertFrom` and `merge` (with `returning: true`). On PostgreSQL 16 and 17 it throws `returningOld requires PostgreSQL 18 or newer` before running the query. ### API reference - [`Model`](/api/classes/Model) — `insert`, `upsert`, `bulkCreate`, `wasInserted`, `oldValues` - [`OnConflictOptions`](/api/type-aliases/OnConflictOptions), [`InsertOptions`](/api/type-aliases/InsertOptions) - [`excluded`](/api/functions/excluded) ## Bulk writes and COPY Source: https://tormozz48.github.io/postgrelize/guide/bulk-writes Sections marked (postgrelize extension) describe options, methods and statements that Sequelize v6 does not have. Everything else here behaves as in v6. All extensions are listed on the [extensions page](/extensions/). Set-based writes avoid loading rows into Node.js and writing them back one by one. postgrelize exposes the PostgreSQL statements for this: `UPDATE ... FROM`, `DELETE ... USING`, `INSERT ... SELECT`, `MERGE`, and `COPY` for bulk import and export. None of them exist in Sequelize v6. The examples use three models: `Stock` (`sku`, `qty`), `Delivery` (`sku`, `amount`) and `Archive` (`sku`, `qty`): ```ts const Stock = sequelize.define('Stock', { sku: { type: DataTypes.TEXT, allowNull: false, unique: true }, qty: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 }, }); const Delivery = sequelize.define( 'Delivery', { sku: DataTypes.TEXT, amount: DataTypes.INTEGER }, { timestamps: false }, ); const Archive = sequelize.define( 'Archive', { sku: DataTypes.TEXT, qty: DataTypes.INTEGER }, { timestamps: false }, ); await sequelize.sync(); await Stock.bulkCreate([ { sku: 'a', qty: 1 }, { sku: 'b', qty: 2 }, { sku: 'c', qty: 0 }, ]); await Delivery.bulkCreate([ { sku: 'a', amount: 10 }, { sku: 'b', amount: 20 }, ]); ``` ### Large inserts with `unnest` (postgrelize extension) {#unnest} `bulkCreate` sends one bound parameter per cell, and PostgreSQL accepts at most 65 535 parameters per statement. `bulkCreate(rows, { unnest: true })` sends one array parameter per column instead (`INSERT … SELECT * FROM unnest($1::integer[], $2::text[])`), so one statement can insert hundreds of thousands of rows: ```ts // One array parameter per column: no 65535-parameter cap on the batch size. const many = Array.from({ length: 70_000 }, (_, index) => ({ sku: `u${index}`, qty: index })); const inserted = await Archive.bulkCreate(many, { unnest: true }); ``` Every row must provide every column (there is no per-row `DEFAULT`), and `ARRAY` columns and the conflict options (`ignoreDuplicates`, `updateOnDuplicate`, `onConflict`) are not supported with `unnest`; those calls throw. Values, hooks, validation and returned instances behave as for the default path. For millions of rows prefer [`copyFrom`](#copy). ### `UPDATE ... FROM` (postgrelize extension) The `from` option of `Model.update` joins other relations, keyed by alias. Reference their columns with `col('alias.attr')` in `where` and with `literal` or `col` in the new values: ```ts const [updated] = await Stock.update( { qty: literal('"Stock"."qty" + "d"."amount"') }, { where: { sku: col('d.sku') }, from: { d: Delivery } }, ); // UPDATE "Stocks" AS "Stock" SET ... FROM "Deliveries" AS "d" WHERE "Stock"."sku" = "d"."sku" ``` A `from` value can be a model, a subquery from `Model.subquery()`, or a table / CTE name as a string. ### `DELETE ... USING` (postgrelize extension) `Model.destroy` takes `using` with the same shape: ```ts const removed = await Stock.destroy({ where: { sku: col('a.sku') }, using: { a: Archive }, }); ``` ### `INSERT ... SELECT` (postgrelize extension) {#insert-select} `Model.insertFrom(subquery, { columns })` inserts the rows a subquery produces, without a round trip through Node.js. `columns` lists the target attributes in the order of the subquery columns: ```ts const archived = await Archive.insertFrom( Stock.subquery({ attributes: ['sku', 'qty'], where: { qty: { [Op.gt]: 20 } } }), { columns: ['sku', 'qty'] }, ); ``` It returns the written rows as instances (with `wasInserted`) and accepts [`onConflict`](./upserts#onconflict), so it can upsert from another table. Fill `NOT NULL` timestamps in the subquery, e.g. `attributes: ['sku', [literal('now()'), 'createdAt']]`. ### `MERGE` (postgrelize extension) `Model.merge` runs `MERGE INTO ... USING ...` (PostgreSQL 15+): one statement that updates, deletes or inserts depending on whether each source row matches a target row. The source is an array of plain objects (sent as a `VALUES` list with bound parameters) or a subquery: ```ts const merged = await Stock.merge({ source: [ { sku: 'a', qty: 5 }, { sku: 'c', qty: -1 }, { sku: 'z', qty: 7 }, ], on: { sku: col('source.sku') }, whenMatched: [ { where: literal('"source"."qty" < 0'), delete: true }, { update: { qty: literal('"Stock"."qty" + "source"."qty"') } }, ], whenNotMatched: { insert: true }, }); // merged.rowCount === 3: 'a' updated, 'c' deleted, 'z' inserted ``` - `on` is the join condition; the source alias is `source` unless you pass `as`. - `whenMatched` and `whenNotMatched` take one action or an array, evaluated in order. Each action may have a `where` condition. - Matched actions: `{ update: {...} }`, `{ delete: true }` or `{ nothing: true }`. Not-matched actions: `{ insert: true }` (copy same-named source columns), `{ insert: {...} }` or `{ nothing: true }`. - Timestamps are set automatically. Hooks and validation do not run. - The result is `{ rowCount, rows }`; `rows` is filled only with `returning: true`. With a subquery source and an explicit insert map: ```ts await Stock.merge({ source: Delivery.subquery({ attributes: ['sku', 'amount'] }), as: 'd', on: { sku: col('d.sku') }, whenMatched: { update: { qty: col('d.amount') } }, whenNotMatched: { insert: { sku: col('d.sku'), qty: col('d.amount') } }, }); ``` #### `RETURNING` and `NOT MATCHED BY SOURCE` (PostgreSQL 17+) (postgrelize extension) On PostgreSQL 17, `returning: true` returns each written row with the action taken, and `whenNotMatchedBySource` handles target rows that have no source row — for example to retire items missing from a full import: ```ts const { rows } = await Stock.merge({ source: [ { sku: 'a', qty: 3 }, { sku: 'n', qty: 9 }, ], on: { sku: col('source.sku') }, whenMatched: { update: { qty: col('source.qty') } }, whenNotMatched: { insert: true }, whenNotMatchedBySource: { update: { status: 'retired' } }, returning: true, }); const actions = rows.map(({ action, instance }) => `${action} ${String(instance.get('sku'))}`); // actions (in any order): 'UPDATE a', 'INSERT n', 'UPDATE b' (b is retired) ``` On older servers these options throw before any SQL runs. With `returningOld: true` (PostgreSQL 18), each instance also has [`oldValues`](./upserts#old-values-with-returningold-postgresql-18). ### COPY (postgrelize extension) {#copy} `COPY` is the fastest way to move many rows in or out of PostgreSQL. #### Import with `copyFrom` (postgrelize extension) `Model.copyFrom(rows, options)` streams rows with `COPY ... FROM STDIN`. `rows` can be an array, an iterable or an async iterable, so you can pipe a file parser or another database cursor through it without holding everything in memory: ```ts async function* readEvents(): AsyncGenerator<{ kind: string; payload: object }> { for (let index = 0; index < 1000; index += 1) { yield { kind: index % 2 === 0 ? 'view' : 'click', payload: { index } }; } } ``` ```ts const fromArray = await Event.copyFrom([ { kind: 'signup', payload: { plan: 'pro' }, tags: ['web'] }, { kind: 'login', payload: null, tags: null }, ]); const fromStream = await Event.copyFrom(readEvents(), { columns: ['kind', 'payload'] }); // fromArray === 2, fromStream === 1000; createdAt / updatedAt are filled in ``` - `columns` lists the attributes to copy. It defaults to the keys of the first row of an array and is required for iterables. - Values are serialized like in `create` (JSON, arrays, dates); escaping is handled for you. - `createdAt` / `updatedAt` are filled when the model has timestamps. - No hooks, validation or defaults defined in Node.js run, and missing values are `NULL` (column defaults of the table do not apply to listed columns). The result is the number of copied rows. - With `transaction`, the copy is rolled back together with the transaction. #### Export with `copyTo` (postgrelize extension) `Model.copyTo(options)` runs `COPY (SELECT ...) TO STDOUT` and returns an async iterator of `Buffer` chunks. It takes the find options (`attributes`, `where`, `order`, `include`, scopes, `with`) and the output format: ```ts const chunks: Buffer[] = []; for await (const chunk of Event.copyTo({ attributes: ['id', 'kind', 'tags'], where: { kind: { [Op.in]: ['signup', 'login'] } }, order: [['id', 'ASC']], format: 'csv', header: true, })) { chunks.push(chunk); } const csv = Buffer.concat(chunks).toString('utf8'); // id,kind,tags // 1,signup,{web} // 2,login, ``` | Option | Description | | ------------ | -------------------------------------------- | | `format` | `'text'` (default), `'csv'` or `'binary'` | | `header` | Header line with column names (text and CSV) | | `delimiter` | Single-character field delimiter | | `nullString` | Text written for `NULL` | | `quote` | Single-character quote (CSV) | Write the chunks straight to an HTTP response or a file stream. Stopping the iteration early is safe: the rest of the output is drained before the connection returns to the pool. Because `COPY` cannot take parameters, values of the query are inlined as escaped literals. ### API reference - [`Model`](/api/classes/Model) — `update`, `destroy`, `insertFrom`, `merge`, `copyFrom`, `copyTo` - [`UpdateOptions`](/api/type-aliases/UpdateOptions), [`DestroyOptions`](/api/type-aliases/DestroyOptions), [`JoinSources`](/api/type-aliases/JoinSources) - [`MergeOptions`](/api/interfaces/MergeOptions), [`MergeResult`](/api/type-aliases/MergeResult) - [`CopyFromOptions`](/api/type-aliases/CopyFromOptions), [`CopyToOptions`](/api/type-aliases/CopyToOptions) ## Advanced queries Source: https://tormozz48.github.io/postgrelize/guide/advanced-queries Sections marked (postgrelize extension) describe options, methods and statements that Sequelize v6 does not have. Everything else here behaves as in v6. All extensions are listed on the [extensions page](/extensions/). In Sequelize v6, subqueries, CTEs and window functions need `literal()` SQL strings. postgrelize builds them from the same find options you already use, with bound parameters and quoted identifiers, and returns model instances where that makes sense. The examples use `User` (`name`), `Post` (`title`, `rank`, `published`, `UserId`; `User.hasMany(Post)`) and `Category` (`name`, `parentId`), a tree. ### Subqueries (postgrelize extension) `Model.subquery(findOptions)` builds a `SELECT` that can be embedded in another query instead of running it. It accepts the find options (`attributes`, `where`, `order`, `limit`, `include`, scopes) plus `as` for the table alias, which defaults to the model name. The default scope and the paranoid filter apply. Use it with `Op.in` / `Op.notIn`, as a scalar value in `attributes`, as a `from` / `using` source, and as the source of [`insertFrom`](./bulk-writes#insert-select) and [`merge`](./bulk-writes#merge): ```ts const authors = await User.findAll({ where: { id: { [Op.in]: Post.subquery({ attributes: ['UserId'], where: { published: true } }) }, }, order: [['id', 'ASC']], }); const counted = await User.findAll({ attributes: [ 'name', [ Post.subquery({ attributes: [[fn('count', col('Post.id')), 'n']], where: { UserId: col('User.id') }, }), 'postCount', ], ], order: [['id', 'ASC']], raw: true, }); // counted: [{ name: 'ann', postCount: '2' }, { name: 'bob', postCount: '2' }, { name: 'cid', postCount: '0' }] ``` A subquery can reference the outer query with `col('User.id')` (a correlated subquery). Its parameters are numbered together with the outer statement. ### `EXISTS` (postgrelize extension) `exists(subquery)` and `notExists(subquery)` produce `EXISTS (...)` conditions. Use them as the `where` value or inside `Op.and` / `Op.or`: ```ts const postsOf = (extra: object) => Post.subquery({ attributes: ['id'], where: { UserId: col('User.id'), ...extra } }); const highRanked = await User.findAll({ where: exists(postsOf({ rank: { [Op.gte]: 5 } })) }); const silent = await User.findAll({ where: notExists(postsOf({})) }); // highRanked: bob; silent: cid ``` ### `DISTINCT ON` (postgrelize extension) `distinctOn` keeps the first row of each group, as defined by `order`. It is the idiomatic PostgreSQL way to get "the latest / best row per key": ```ts const topPerUser = await Post.findAll({ distinctOn: ['UserId'], order: [ ['UserId', 'ASC'], ['rank', 'DESC'], ], }); // topPerUser: a1, b2 ``` As PostgreSQL requires, the `order` must start with the `distinctOn` expressions. ### Window functions (postgrelize extension) `over(fn, { partitionBy, orderBy })` adds an `OVER (...)` clause to a function call. Use it in `attributes` (and, through a subquery or CTE, in filters): ```ts const ranked = await Post.findAll({ attributes: [ 'title', [ over(fn('row_number'), { partitionBy: ['UserId'], orderBy: [['rank', 'DESC']] }), 'position', ], ], order: [['title', 'ASC']], raw: true, }); // ranked: a1 → '1', a2 → '2', b1 → '2', b2 → '1' ``` `orderBy` uses the same format and the same direction allow-list as `order`. ### Row comparison and keyset pagination (postgrelize extension) `tuple(...)` builds a row value `(a, b)`. Combined with `where(left, operator, right)`, it expresses keyset ("seek") pagination, which stays fast on deep pages where `OFFSET` does not: ```ts const nextPage = await Post.findAll({ where: where(tuple(col('rank'), col('id')), Op.lt, tuple(3, 1)), order: [ ['rank', 'DESC'], ['id', 'DESC'], ], limit: 10, }); // nextPage: b1, a2 — rows after (rank 3, id 1) in (rank DESC, id DESC) order ``` Back the comparison with an index on the same columns in the same order, e.g. `indexes: [{ fields: ['rank', 'id'] }]`. ### Common table expressions (postgrelize extension) The `with` option adds `WITH` clauses to `findAll`, `findOne`, `count`, aggregates and `copyTo`. Each CTE is a subquery, or `{ query, recursive?, unionAll?, materialized? }`. `source` reads the model rows from a CTE instead of the table, and the result is still model instances. A recursive CTE walks a tree in one query: ```ts const subtree = await Category.findAll({ with: { tree: { query: Category.subquery({ where: { name: 'a' } }), recursive: Category.subquery({ where: { parentId: col('tree.id') }, from: { tree: 'tree' }, }), }, }, source: 'tree', order: [['id', 'ASC']], }); // subtree: a, a1, a1x — Category instances read from the CTE ``` - `recursive` makes the clause `WITH RECURSIVE` and is joined to `query` with `UNION ALL` (`unionAll: false` for `UNION`). - Inside the recursive part, `from: { tree: 'tree' }` adds the CTE as an extra relation, so `col('tree.id')` can reference it. - `materialized: true` / `false` adds `MATERIALIZED` / `NOT MATERIALIZED`. CTEs can also be used as filters: ```ts const rootChildren = await Category.count({ with: { roots: { query: Category.subquery({ attributes: ['id'], where: { parentId: null } }), materialized: true, }, }, where: { parentId: { [Op.in]: Category.subquery({ attributes: ['id'], source: 'roots' }) }, }, }); // rootChildren === 2 ``` #### `SEARCH` and `CYCLE` (postgrelize extension) A recursive CTE definition accepts `search` and `cycle`: - `search: { by, mode?, set }` adds a column `set` that orders the rows depth first (`mode: 'depth'`, the default) or breadth first (`'breadth'`) by the `by` columns. Order the result by it. - `cycle: { columns, set, using }` adds a boolean column `set` that is true on the row that revisits the same `columns`, and an array column `using` with the path. The recursion stops at such a row, so cyclic data cannot loop forever. Both need `recursive`. The added columns are not model attributes: select them with `[col('walk'), 'walk']` (or read `raw` rows). ```ts const depthFirst = await Category.findAll({ with: { tree: { query: Category.subquery({ where: { name: 'root' } }), recursive: Category.subquery({ where: { parentId: col('tree.id') }, from: { tree: 'tree' }, }), search: { by: ['id'], mode: 'depth', set: 'walk' }, }, }, source: 'tree', attributes: ['name'], order: [[col('walk'), 'ASC']], raw: true, }); // depthFirst: root, a, a1, a1x, b — `walk` orders the rows depth first ``` ```ts await Category.update({ parentId: 5 }, { where: { name: 'root' } }); // root → a → a1 → a1x → root const cyclic = await Category.findAll({ with: { tree: { query: Category.subquery({ where: { name: 'root' } }), recursive: Category.subquery({ where: { parentId: col('tree.id') }, from: { tree: 'tree' }, }), cycle: { columns: ['id'], set: 'looped', using: 'trail' }, }, }, source: 'tree', attributes: ['name', [col('looped'), 'looped']], order: [[col('trail'), 'ASC']], raw: true, }); // cyclic: root, a, a1, a1x, then root again with looped = true (the recursion stops there), then b ``` #### Data-modifying CTEs (postgrelize extension) `Model.updateStatement(values, { where, returning })`, `Model.deleteStatement({ where, returning })` and `Model.insertStatement(rows, { returning })` build a statement for the `with` option. The statement runs as part of the finder's query. With `returning: true`, read its rows through `source: ''`, or filter with them. No hooks or validation run; `updatedAt` is set (not with `silent: true`), defaults and timestamps are filled for inserts, and `deleteStatement` is a real delete, also for paranoid models. ```ts const removed = await Post.findAll({ with: { gone: Post.deleteStatement({ where: { published: false }, returning: true }) }, source: 'gone', }); // removed: a2 — deleted and returned by one statement ``` - The query is sent to the writer, never to a read replica. - A data-modifying statement cannot be `recursive`, and cannot be the main statement of a finder: only the CTE body is supported (for example, there is no `INSERT … SELECT FROM cte`). - All CTEs of one statement see the same snapshot: the main query does not see the changes of a data-modifying CTE in the tables, only in its `RETURNING` rows. ### Set operations (postgrelize extension) `Subquery` has `union()`, `intersect()` and `except()` (pass `{ all: true }` for the `ALL` forms). The result is another subquery, so it works wherever a subquery does: in `Op.in`, in `with`, as a source of `insertFrom` or `merge`. Both sides must select the same columns. ```ts const published = Post.subquery({ attributes: [['UserId', 'id']], where: { published: true } }); const withoutPosts = await User.findAll({ where: { id: { [Op.in]: User.subquery({ attributes: ['id'] }).except(published) } }, }); // withoutPosts: cid const pair = await User.findAll({ source: User.subquery({ where: { name: 'ann' } }).union( User.subquery({ where: { name: 'cid' } }), ), order: [['name', 'DESC']], }); // pair: cid, ann — rows of the UNION, read as User instances ``` `source` also accepts a subquery: the finder then reads model rows from `(… UNION …) AS "User"`, and its own `order`, `limit` and `offset` apply to the combined result. Select all attributes in the operands for that (no `attributes` option), because the finder selects every attribute of the model. ### `FETCH FIRST … WITH TIES` (postgrelize extension) `withTies: true` with `limit` and `order` returns the first `limit` rows plus every row that ties with the last one on the `order` columns (`FETCH FIRST $1 ROWS WITH TIES`). PostgreSQL rejects it without `ORDER BY`; postgrelize throws `withTies requires a limit` when `limit` is missing. ```ts const topPublished = await Post.findAll({ order: [['published', 'DESC']], limit: 1, withTies: true, }); // topPublished: a1, b1, b2 — every row that ties with the first on `published` ``` ### Extra relations with `from` (postgrelize extension) `from` on finders adds relations to the `FROM` clause, keyed by alias, without an association. Correlate them in `where`: ```ts const parents = await Category.findAll({ attributes: ['name', [fn('count', col('child.id')), 'children']], from: { child: Category }, where: { id: col('child.parentId') }, group: ['Category.id', 'Category.name'], raw: true, }); ``` #### VALUES, set-returning functions and `JSON_TABLE` (postgrelize extension) A `from` entry can also be an object that produces rows. Every value is a bound parameter; names are quoted identifiers. | Entry | SQL | | ------------------------------------------------------- | -------------------------------------------------------------------------------------- | | `{ values: { columns, rows } }` | `(VALUES (…), …) AS "alias"("col", …)` | | `{ function, args?, columns?, ordinality? }` | `fn(args) [WITH ORDINALITY] AS "alias"("col", …)`; `ordinality` names the extra column | | `{ lateral: subquery }` | `LATERAL (subquery) AS "alias"` | | `{ model, sample }` | the model table with `TABLESAMPLE` | | `{ jsonTable: { doc, path, columns } }` (PostgreSQL 17) | `JSON_TABLE(doc, path COLUMNS (…)) AS "alias"` | ```ts const ordered = await User.findAll({ from: { v: { values: { columns: ['id', 'rank'], rows: [ [cast(3, 'integer'), 1], [cast(1, 'integer'), 2], ], }, }, }, where: { id: col('v.id') }, order: [[col('v.rank'), 'ASC']], }); // ordered: cid, ann — joined to an inline VALUES list const numbered = await User.findAll({ attributes: ['name', [col('n.pos'), 'pos']], from: { n: { function: 'unnest', args: [cast([3, 1], 'integer[]')], columns: ['id'], ordinality: 'pos', }, }, where: { id: col('n.id') }, order: [[col('n.pos'), 'ASC']], raw: true, }); // numbered: cid at position 1, ann at position 2 (WITH ORDINALITY) ``` PostgreSQL cannot always infer the type of a bound parameter in a function call or `VALUES` cell (`generate_series($1, $2)` is ambiguous). Wrap such values in `cast(value, 'integer')`. `JSON_TABLE` turns a JSON document, given as a value or an expression such as `col('Order.data')`, into rows. The `path` and each column `path` are jsonpath strings, which PostgreSQL only accepts as constants, so they are rendered as escaped string literals. Column `type` is checked against the same list as `'attr::type'` casts. It needs PostgreSQL 17; older servers reject the query. Nested paths (`NESTED PATH`) are not supported. ```ts const rows = await Product.findAll({ attributes: ['sku', [col('item.qty'), 'qty'], [col('item.position'), 'position']], from: { item: { jsonTable: { doc: { items: [ { sku: 'a', qty: 5 }, { sku: 'b', qty: 9 }, ], }, path: '$.items[*]', columns: [ { name: 'position', ordinality: true }, { name: 'sku', type: 'text' }, { name: 'qty', type: 'integer' }, ], }, }, }, where: { sku: col('item.sku') }, order: [['sku', 'ASC']], raw: true, }); // rows: a → qty 5, position 1; b → qty 9, position 2 ``` ### `LATERAL` joins and top-N per parent (postgrelize extension) A `LATERAL` subquery may reference relations that come before it in `FROM`, so it runs once per row. Use it for "latest N per parent" queries. A lateral entry in `from` behaves like an inner join: rows without a match disappear. For includes, `lateral: true` on a `separate` include with `limit` makes the database return only the first `limit` rows per parent (`unnest(keys)` joined with a `LATERAL` subquery), instead of loading every child and trimming in memory. `order` applies per parent. It cannot have nested includes. ```ts const latest = await User.findAll({ attributes: ['name', [col('latest.title'), 'title']], from: { latest: { lateral: Post.subquery({ attributes: ['title'], where: { UserId: col('User.id') }, order: [['id', 'DESC']], limit: 1, }), }, }, order: [['id', 'ASC']], raw: true, }); // latest: ann → a2, bob → b2 (cid has no posts, so the join drops it) const withLatestPost = await User.findAll({ include: [ { association: 'Posts', separate: true, lateral: true, limit: 1, order: [['id', 'DESC']] }, ], order: [['id', 'ASC']], }); // each user's Posts holds at most one row, read with one LATERAL query ``` ### `TABLESAMPLE` (postgrelize extension) `sample: { method, percent, seed? }` on `findAll` and `count` reads a random part of the table: `BERNOULLI` samples row by row, `SYSTEM` block by block (faster, clustered). `percent` is from 0 to 100; the same `seed` gives the same sample while the data is unchanged (`REPEATABLE`). The same option works on a `from` entry: `{ model, sample }`. ```ts const sampled = await Post.findAll({ sample: { method: 'BERNOULLI', percent: 100, seed: 1 } }); // sampled: every row at 100 percent; use a smaller percent to read a random part of a big table ``` ### Server-side cursors with `findEach` (postgrelize extension) `Model.findEach(findOptions, { batchSize })` streams rows with a server-side cursor (`DECLARE ... CURSOR` and `FETCH n`), so a large result is never loaded at once: ```ts const seen: string[] = []; for await (const post of Post.findEach({ order: [['id', 'ASC']] }, { batchSize: 2 })) { seen.push(String(post.get('title'))); } // seen: a1, a2, b1, b2 — fetched two rows at a time through a server-side cursor ``` - The cursor needs a transaction. Pass `transaction`, or `findEach` opens one and commits it when the iteration ends. - Leaving the loop early (`break`, `return`, an exception) closes the cursor. - `batchSize` defaults to 100. Includes must be `separate: true`; they are loaded with one extra query per batch. Joined includes are rejected. For exporting rows as text, [`copyTo`](./bulk-writes#export-with-copyto) is faster still. ### API reference - [`Model`](/api/classes/Model) — `subquery`, `findEach` - [`exists`](/api/functions/exists), [`notExists`](/api/functions/notExists), [`over`](/api/functions/over), [`tuple`](/api/functions/tuple), [`where`](/api/variables/where) - [`CteDefinition`](/api/type-aliases/CteDefinition), [`CteFindOptions`](/api/type-aliases/CteFindOptions), [`WindowOptions`](/api/type-aliases/WindowOptions) ## Sessions and scaling Source: https://tormozz48.github.io/postgrelize/guide/sessions Sections marked (postgrelize extension) describe options, methods and statements that Sequelize v6 does not have. Everything else here behaves as in v6. All extensions are listed on the [extensions page](/extensions/). PostgreSQL features that work at the connection or transaction level: `LISTEN` / `NOTIFY`, transaction-local settings (for row-level security and timeouts), advisory locks, and read replicas. ### LISTEN / NOTIFY (postgrelize extension) `sequelize.listen(channel, handler)` subscribes to notifications and resolves to an unsubscribe function. `sequelize.notify(channel, payload)` sends one with `pg_notify`; objects are sent as JSON text: ```ts const received: string[] = []; const unlisten = await sequelize.listen('jobs', (payload, channel) => { received.push(`${channel}: ${payload ?? ''}`); }); await sequelize.notify('jobs', { id: 1 }); await sequelize.transaction(async (transaction) => { await Job.create({ name: 'export', state: 'queued' }, { transaction }); await sequelize.notify('jobs', 'export queued', { transaction }); // delivered on commit }); await pause(200); await unlisten(); // received: ['jobs: {"id":1}', 'jobs: export queued'] ``` - All `listen` calls of a `Sequelize` instance share one dedicated connection outside the pool. It re-subscribes automatically after the connection is lost; notifications sent while it was down are not delivered. - The handler receives the payload as a string (`undefined` for an empty payload) and the channel name. Parse JSON yourself. - `notify` inside a transaction is delivered when the transaction commits, and dropped on rollback — use this to announce committed changes. - PostgreSQL limits a payload to about 8000 bytes; send ids, not documents. - `sequelize.close()` closes the listener connection too. ### Transaction settings (postgrelize extension) The `settings` option of `sequelize.transaction()` applies configuration parameters for the duration of the transaction (`set_config(name, value, true)`, the same as `SET LOCAL`). They are reset when the transaction ends, so pooled connections never leak them: ```ts const user = await sequelize.transaction( { settings: { 'app.user_id': 42, statement_timeout: '5s' } }, (transaction) => sequelize.query("SELECT current_setting('app.user_id') AS id", { type: QueryTypes.SELECT, plain: true, transaction, }), ); // user: { id: '42' }; the settings end with the transaction (SET LOCAL semantics) ``` Typical uses: - **Row-level security.** Policies read the current user from a custom setting: ```sql CREATE POLICY tenant_isolation ON documents USING (tenant_id = current_setting('app.tenant_id')::int); ``` ```ts await sequelize.transaction({ settings: { 'app.tenant_id': tenantId } }, async (transaction) => { return Document.findAll({ transaction }); // only this tenant's rows }); ``` - **Per-transaction limits:** `statement_timeout`, `lock_timeout`, `idle_in_transaction_session_timeout`. Names and values are sent as bound parameters. Custom setting names need a dot (`app.user_id`). ### Statement timeout per query (postgrelize extension) The `statementTimeout` option (milliseconds, a non-negative integer; `0` disables the limit) applies `statement_timeout` to one query. PostgreSQL cancels a longer statement and the call rejects with a `DatabaseError` (code `57014`). It works on `sequelize.query` and on model finders and writers: ```ts // Cancel just this query after 200 ms; the pooled connection keeps its normal timeout. const timedOut = await sequelize .query('SELECT pg_sleep(5)', { statementTimeout: 200 }) .then(() => false) .catch(() => true); ``` Outside a transaction the query runs in its own short transaction, so the value never leaks to the pooled connection. Inside a transaction the previous timeout (for example from `settings`) is restored after the query. To limit a whole transaction use the `settings` option above; to limit every query of the pool use `dialectOptions.statement_timeout`. ### Advisory locks (postgrelize extension) Advisory locks are application-defined locks managed by PostgreSQL — for example to make sure only one worker runs a job. postgrelize uses transaction-level locks (`pg_advisory_xact_lock`), which are released automatically on commit or rollback, so a crashed worker cannot leave a lock behind. Keys are integers (64-bit, `number` or `bigint`) or strings; a string is hashed with PostgreSQL's `hashtextextended`. ```ts const holder = await sequelize.transaction(); await holder.advisoryLock('jobs:42'); const other = await sequelize.transaction(); const busy = await other.tryAdvisoryLock('jobs:42'); // false: held by `holder` const free = await other.tryAdvisoryLock(7); // true: integer keys work too await holder.commit(); // transaction-level locks are released on commit / rollback await other.rollback(); ``` - `transaction.advisoryLock(key)` waits until the lock is free. - `transaction.tryAdvisoryLock(key)` returns `false` immediately when another session holds the lock. - Both take `{ shared: true }` for a shared lock: shared holders do not block each other, only exclusive ones. `sequelize.withAdvisoryLock(key, run, options?)` wraps the common case: it starts a transaction, takes the lock, runs the callback and commits. Concurrent callers with the same key run one after another: ```ts const order: string[] = []; let firstHoldsLock: (() => void) | undefined; const held = new Promise((resolve) => { firstHoldsLock = resolve; }); await Promise.all([ sequelize.withAdvisoryLock('nightly-report', async () => { order.push('first start'); firstHoldsLock?.(); await pause(100); order.push('first end'); }), held.then(() => sequelize.withAdvisoryLock('nightly-report', async () => { order.push('second'); }), ), ]); // order: ['first start', 'first end', 'second'] ``` ### Read replicas (postgrelize extension) The `replication` option of Sequelize v6 is supported. Reads go to the readers in round-robin order; writes go to the writer: ```ts const sequelize = new Sequelize({ database: 'app', username: 'app', password: process.env.DB_PASSWORD, replication: { read: [{ host: 'replica-1.internal' }, { host: 'replica-2.internal' }], write: { host: 'primary.internal' }, }, }); ``` Each member inherits missing settings (`port`, `database`, `username`, `password`) from the top-level options, and each has its own pool with the `pool` settings. ```ts const queued = await Replicated.count({ where: { state: 'queued' } }); // a reader const fresh = await Replicated.findAll({ where: { state: 'queued' }, useMaster: true }); // the writer await replicated.transaction(async (transaction) => { await Replicated.findAll({ transaction }); // the writer: transactions never use readers }); ``` Routing rules: - Finders, `count` and other aggregates, `copyTo`, and `sequelize.query` with `type: QueryTypes.SELECT` use a reader. - Everything else (writes, DDL, `copyFrom`, `listen` / `notify`) uses the writer. - Queries with `transaction` always use the writer, as does `useMaster: true`. Replicas lag behind the primary. To read your own writes immediately, pass `useMaster: true` or read inside the writing transaction. There is no automatic failover: a failing reader surfaces as a `ConnectionError`, as in v6. ### Routing connections `sequelize.connectionManager` is the Sequelize v6 object that hands out pooled connections. Routing uses two methods: - `getConnection(options?: { type?: 'read' | 'write'; useMaster?: boolean; uuid?: string })` returns a connection (the pooled `pg` client). `type: 'read'` (or `'SELECT'`, what v6 passes for a SELECT) selects a read replica when one is configured and `useMaster` is not set. `uuid` is the id of the transaction the connection is for. - `releaseConnection(connection)` gives a connection back to the pool it came from. Every query, finder, write, managed or unmanaged transaction, `findEach`, `copyFrom` / `copyTo`, advisory lock and `sync` acquires through `getConnection` and releases through `releaseConnection`, looked up on the manager at call time. A transaction takes one connection when it starts and releases it on commit or rollback. As in v6, you can reassign both methods on the instance to route connections, for example each request to one of several databases chosen from an `AsyncLocalStorage` value: ```ts const shardOfRequest = new AsyncLocalStorage(); const shards: Record = { b: shard }; const manager = sequelize.connectionManager; const defaultGet = manager.getConnection.bind(manager); const defaultRelease = manager.releaseConnection.bind(manager); const owners = new WeakMap(); manager.getConnection = async (options) => { const target = shards[shardOfRequest.getStore() ?? '']; if (target === undefined) { return defaultGet(options); } const connection = await target.connectionManager.getConnection(options); owners.set(connection, target); // remember which pool the connection must go back to return connection; }; manager.releaseConnection = (connection) => { const owner = owners.get(connection); return owner === undefined ? defaultRelease(connection) : owner.connectionManager.releaseConnection(connection); }; const applicationName = async (): Promise => { const rows = (await sequelize.query('SHOW application_name', { type: QueryTypes.SELECT, })) as { application_name: string }[]; return rows[0]?.application_name ?? ''; }; routed = [ await applicationName(), // no routing value: the instance's own pool await shardOfRequest.run('b', applicationName), // routed to the other instance's pool await shardOfRequest.run('b', () => sequelize.transaction(() => applicationName())), ]; // routed: ['', 'shard-b', 'shard-b'] ``` Rules for a replacement: - Keep acquire and release paired: whatever `getConnection` returns must reach `releaseConnection` exactly once per use. Releasing the same connection twice is ignored. - Release a connection to the pool that owns it. A connection from another `Sequelize` instance's manager works on this instance's queries and transactions, but only that instance's `releaseConnection` returns it to its pool; remember the owner (a `WeakMap` keyed by the connection, as above). - Wrap the original methods (`manager.getConnection.bind(manager)`) to fall back to the default pool. #### Raw connections, destroying and pool counters You can hold a connection outside any query, for example a replica connection for a long running report, and watch the pools from a health check: ```ts const manager = replicated.connectionManager; const { pool } = manager; // live counters: size, available, using, waiting, maxSize // A raw connection held outside any query; `type: 'read'` takes a replica. const reader = await manager.getConnection({ type: 'read' }); const readerUsing = pool.read?.using; // 1: the replicas' pools, `pool.write?.using` is 0 try { await reader.query('SELECT 1'); await manager.releaseConnection(reader); // back to the replica pool it came from } catch (error) { await manager.destroyConnection(reader); // a broken connection: closed, never reused throw error; } // pool: { size: 1, available: 1, using: 0, waiting: 0 } ``` - `releaseConnection(connection)` returns the connection to the pool it came from: a read connection goes back to its replica pool. A connection that is acquired late (the caller timed out and the promise resolved afterwards) is released the same way, and releasing it twice is ignored. - `destroyConnection(connection)` closes a broken connection and removes it from its pool without returning it; the pool opens a replacement when one is needed. A later `releaseConnection` of the same connection is ignored. - `pool` has `size` (open connections), `available` (idle), `using` (checked out), `waiting` (acquisitions queued for a free connection) and `maxSize` (`pool.max`, default 5). They are read live, are `0` before the first connection and never open one. They mirror the `pg` pool: `size = totalCount`, `available = idleCount`, `waiting = waitingCount`, `using = size - available`. - With `replication`, v6 has no totals: `pool` is an object with separate `read` and `write` pools. Here `pool.size` and the other counters are the sums over the writer and all replicas, and `pool.write` and `pool.read` hold the counters of each side (`pool.read` sums all replicas). Without replication `pool.read` and `pool.write` are `undefined`. `getConnection({ type: 'read' })` goes to a replica. In v6 the runtime only recognises the query type `'SELECT'` there, so `type: 'read'` (the value its typings document) reaches the writer; postgrelize accepts both names. `listen` does not go through the manager: it opens a dedicated connection outside the pool, from this instance's own settings, so it is not routed. Hooks such as `beforePoolAcquire` are not run (see [migrating](/guide/migrating)). ### Retrying failed queries The `retry` option of Sequelize v6 repeats a query or a transaction start that failed. It takes the same fields as v6 (`max`, `match`, `backoffBase`, `backoffExponent`, `backoffJitter`, `timeout`, `name`, `report`) and follows the same rules as `retry-as-promised`: ```ts const retry = { max: 5, // attempts, the first one included match: [/SequelizeConnectionRefusedError/, 'ECONNRESET'], // retry only these errors backoffBase: 10, // ms before the first retry; grows by backoffExponent (default 1.1) }; const refusing = new Sequelize({ database, username, password, host, port, logging: false, dialectOptions: sequelize.options.dialectOptions, retry, // every query and transaction start of this instance }); // Simulate a database that refuses the first two connections. const manager = refusing.connectionManager; const getConnection = manager.getConnection.bind(manager); manager.getConnection = async (options) => { attempts += 1; if (attempts <= 2) { throw new ConnectionRefusedError(new Error('connect ECONNREFUSED')); } return getConnection(options); }; retried = await refusing.query('SELECT 1 AS one', { type: QueryTypes.SELECT, plain: true }); // retried: { one: 1 }, attempts: 3 // A query can override the instance setting; a statement inside a transaction is never retried. await refusing.query('SELECT 1', { retry: { max: 2 } }); await refusing.close(); ``` - Nothing is retried unless `max` is set (the number of attempts, the first one included) and `retry` is configured. There is no default retry on PostgreSQL. - `match` lists the errors worth retrying. An entry is a string equal to `error.message` or to `String(error)`, a regular expression tested against both, an error class (`instanceof`), or an arrow function used as a predicate. An empty or missing `match` retries every error, including constraint violations, so always list the errors you mean. - Connection errors carry the v6 names, so `match: [/SequelizeConnectionError/]` style lists keep working: `SequelizeConnectionError`, `SequelizeConnectionRefusedError`, `SequelizeHostNotFoundError`, `SequelizeHostNotReachableError`, `SequelizeInvalidConnectionError`, `SequelizeConnectionTimedOutError` (and `SequelizeConnectionAcquireTimeoutError` for an exhausted pool). - The delay before retry _n_ is `backoffBase * backoffExponent ** (n - 1)` milliseconds (defaults 100 and 1.1), plus or minus up to `backoffJitter`. An attempt that runs longer than `timeout` ms fails with a `TimeoutError` and is not retried. - A per-query `retry` is merged over the instance option field by field, so `{ max: 2 }` keeps the instance `match`. What is retried: connection acquisition and execution of `sequelize.query`, finders, writes and the other statements outside a transaction; for a transaction, acquiring the connection and `BEGIN` (the transaction option `retry` is merged the same way, and the callback of a managed transaction runs once, after a successful start). A statement inside an open transaction is never retried: PostgreSQL has aborted the transaction, so run the whole `sequelize.transaction(...)` again in your code when you need that. `COMMIT` / `ROLLBACK`, `copyFrom` / `copyTo` and `listen` are not retried either. Differences from v6: v6 also retries statements that run inside a transaction (they fail again on the aborted transaction); a timed out attempt is not retried in the background. ### API reference - [`Sequelize`](/api/classes/Sequelize) — `listen`, `notify`, `withAdvisoryLock` - [`Transaction`](/api/classes/Transaction) — `advisoryLock`, `tryAdvisoryLock` - [`TransactionOptions`](/api/type-aliases/TransactionOptions), [`AdvisoryLockKey`](/api/type-aliases/AdvisoryLockKey) - [`ConnectionManagerContract`](/api/interfaces/ConnectionManagerContract), [`ConnectionPool`](/api/interfaces/ConnectionPool), [`PoolCounters`](/api/interfaces/PoolCounters), [`GetConnectionOptions`](/api/type-aliases/GetConnectionOptions), `Sequelize#connectionManager` - [`RetryOptions`](/api/type-aliases/RetryOptions), [`RetryMatch`](/api/type-aliases/RetryMatch) - [`ReplicationOptions`](/api/type-aliases/ReplicationOptions), [`NotificationHandler`](/api/type-aliases/NotificationHandler) ## Performance Source: https://tormozz48.github.io/postgrelize/guide/performance postgrelize builds SQL, maps rows to instances and runs hooks and validation itself, so its overhead is what you pay on top of PostgreSQL. This page shows what that overhead is compared with Sequelize v6, how it is measured, and what to tune in your application. ### How it compares with Sequelize v6 The benchmark (`bench/`) runs the same scenarios on postgrelize and on `sequelize@6` in one process, alternating which library goes first in every round, and records CPU time per operation (`process.cpuUsage()`). The ratio is stable on a busy machine even when absolute times are not. In **stub mode** the `pg` driver is replaced by an in-memory responder, so only the library's own work is measured: | Scenario | postgrelize µs/op | v6 ÷ postgrelize | | --------------------------------------------- | ----------------: | ---------------: | | `findByPk` | 13.3 | 7.7× | | `findAll` 100 rows | 132.9 | 4.2× | | `findAll` 10 000 rows | 11 500 | 1.9× | | `findAll` 10 000 rows, `raw: true` | 1 014 | 1.3× | | `findAll` with `include` (belongsTo) | 242 | 3.1× | | `findAll` with `include` (hasMany) | 151 | 1.7× | | `findAll` with `include` (belongsToMany) | 167 | 1.9× | | `findAndCountAll` | 74 | 3.2× | | `where` with nested operators and a JSON path | 38 | 5.6× | | `where` with `Op.in` of 5 000 values | 124 | 18× | | `create` | 39 | 3.3× | | `bulkCreate` 100 / 1 000 rows | 434 / 5 053 | 3.1× / 2.6× | | `save()` of a changed instance | 17.3 | 6.7× | | transaction with 3 queries | 81 | 5.1× | | `build` + `toJSON` | 5.4 | 0.9× | | model definition | 45 | 9.8× | Measured on a GitHub Actions runner (`ubuntu-latest`, Node 22; no database involved in stub mode) with the `bench gate` workflow on 2026-11-24: `main` after 1.8.3, median of three runs. Absolute numbers differ on your machine, the ratios are what to compare. The database-mode figures below come from an earlier measurement on a developer machine. Against a real database a statement spends most of its time in the network and in PostgreSQL, so the end-to-end difference is smaller: in database mode postgrelize used 1.1–2.4× less CPU than v6 per operation (`raw: true` reads of 10 000 rows about 1.1× less), and read 10 000 rows at about 255 000 rows/s (344 000 rows/s with `raw: true`). Run it yourself: ```bash PGZ_BENCH_STUB=1 npm run bench # library overhead only, no database npm run bench # real PostgreSQL (PGZ_TEST_URL or the docker default) ``` ### Tuning your application #### Pool size Every statement needs a pooled connection, so `pool.max` is the concurrency limit of one Node.js process. A value close to the number of cores of the _database_ server divided by the number of application processes is a good start; more connections than the server can run in parallel only add queueing and memory use on the server. ```ts export const createPool = (url: string): Sequelize => new Sequelize(url, { logging: false, // At most `max` statements run at once per Node.js process; extra calls wait for a connection. pool: { max: 10, idle: 10_000, acquire: 30_000 }, }); ``` #### Load less Instances cost allocation and change tracking; rows you do not need cost network and parsing time. For read-only paths: ```ts // Only the columns you need, as plain objects: no instances, no change tracking. const lean = await Reading.findAll({ attributes: ['id', 'value'], where: { sensor: 's1' }, limit: 100, raw: true, }); ``` - `attributes` limits the columns PostgreSQL sends. - `raw: true` returns plain objects: no instance construction, getters or change tracking. It is about 3× faster than building instances for large reads. - `limit` / `offset`, or a cursor (`findEach`, see [Advanced queries](./advanced-queries)), keep result sets bounded. Let PostgreSQL aggregate: ```ts // Aggregates and counts are computed by PostgreSQL; do not load rows to count them. const total = await Reading.count({ where: { sensor: 's1' } }); ``` #### Write in bulk One statement for many rows beats a loop of `create` calls by a wide margin, because every `create` is a round trip: ```ts // One INSERT for all rows instead of one round trip per row. const rows = Array.from({ length: 500 }, (_, index) => ({ sensor: `s${index % 5}`, value: index, })); await Reading.bulkCreate(rows, { validate: false }); ``` - `bulkCreate` sends one multi-row `INSERT`. Pass `validate: false` when the rows are already trusted. - For imports of many thousands of rows use `Model.copyFrom` (`COPY ... FROM STDIN`); see [Bulk writes and COPY](./bulk-writes). - Use `UPDATE ... FROM`, `INSERT ... SELECT` and `MERGE` ([Bulk writes and COPY](./bulk-writes)) to change data without moving it through Node.js. - Upserts: [`onConflict`](./upserts) instead of "find, then create or update". #### Transactions and includes - Group dependent writes in one transaction ([Transactions](./transactions)): one `BEGIN`/`COMMIT` pair instead of one implicit transaction per statement. - Prefer `include` over a query per parent row. Joined `hasMany` and `belongsToMany` includes multiply result rows; for large hasMany collections use `separate: true` on the include (see [Associations](./associations)) or query the child model directly. - Large `Op.in` lists are cheap to build, but PostgreSQL limits a statement to 65 535 bound values; split larger lists or join against a `VALUES` list / subquery. #### Read replicas Read-only traffic can go to replicas ([Sessions and scaling](./sessions)); the pool of each replica has its own limit. #### Prepared statements (postgrelize extension) By default every query is sent as an unnamed statement, so PostgreSQL parses and plans it on each call. The `statementCache` constructor option names repeated statements so each connection parses and plans them once: ```ts export const createCachedPool = (url: string): Sequelize => new Sequelize(url, { logging: false, // Repeated SELECT / INSERT / UPDATE / DELETE texts are parsed once per connection. statementCache: { max: 50 }, pool: { max: 10 }, }); ``` - Only `SELECT`, `INSERT`, `UPDATE`, `DELETE` and `WITH` texts of at most 8192 characters are named. Multi-statement texts, DDL, `COPY`, `LISTEN` / `NOTIFY` and cursors stay unnamed. The name is `pgz_` plus a hash of the SQL text; values are still bound as `$n` parameters. - Each connection names at most `max` statements (default 100); further texts run unnamed. There is no eviction: statements disappear with the connection (`pool.maxUses` and `pool.idle` recycle them). Keep `pool.max` bounded: server memory is `pool.max × max` statements. - Texts that vary per call (long `IN` lists, dynamic `where` shapes) fill the slots without being reused; the cache pays off for a small set of hot, repeated queries (`findByPk`, counts, single-row writes). - After a schema change that alters a result's columns, PostgreSQL rejects the cached statement with "cached plan must not change result type". Outside a transaction the query is retried once unnamed and that text stays unnamed on that connection; inside a transaction the error is thrown like any other. - Not for PgBouncer in transaction pooling mode (without protocol-level prepared statement support). The gain is visible only against a real database; the `findByPk statementCache` case of `npm run bench` shows it. ### What the library does for you Query building, SQL text assembly and row mapping are optimised for the common paths: columns of a model are resolved once and reused, rows are converted without per-row lookups, hooks and validators that are not defined cost almost nothing, and identifier quoting is cached. None of it changes SQL text or Sequelize v6 behaviour. If you find a case where postgrelize is slower than v6, [open an issue](https://github.com/tormozz48/postgrelize/issues) with the scenario; the benchmark in `bench/scenarios.ts` is the place to add it. ## PostgreSQL coverage Source: https://tormozz48.github.io/postgrelize/postgresql-coverage ### SELECT clauses | Feature | Status | Since | Note | | --- | --- | --- | --- | | DISTINCT ON | supported | PG 16+ | `distinctOn` find option. | | Window functions (OVER, PARTITION BY) | supported | PG 16+ | `over()` expression; named `WINDOW` clauses and frame clauses are not modelled. | | CTEs and WITH RECURSIVE | supported | PG 16+ | `with` find option. | | CTE MATERIALIZED / NOT MATERIALIZED | supported | PG 16+ | `materialized` flag of a CTE definition. | | Data-modifying CTEs (WITH … UPDATE/DELETE … RETURNING) | supported | PG 16+ | `Model.updateStatement()`, `deleteStatement()`, `insertStatement()` in `with`; the query goes to the writer. `INSERT … SELECT FROM cte` as the main statement is not supported. | | CTE SEARCH / CYCLE clauses | supported | PG 16+ | `search` and `cycle` in a recursive `with` definition; `cycle.using` is required. | | LATERAL joins | supported | PG 16+ | `from: { alias: { lateral: subquery } }`; `lateral: true` on a `separate` include with `limit` reads the top rows per parent. | | GROUPING SETS / ROLLUP / CUBE | via literal() / raw SQL | PG 16+ | `group: literal("ROLLUP (a, b)")`. `GROUPING()` through `fn("grouping", …)`. | | Row locks: FOR UPDATE / NO KEY UPDATE / SHARE / KEY SHARE, OF, NOWAIT, SKIP LOCKED | supported | PG 16+ | `lock`, `skipLocked`, `noWait` find options. | | ORDER BY … NULLS FIRST / LAST | supported | PG 16+ | Order direction string, e.g. `["rank", "ASC NULLS LAST"]`. | | TABLESAMPLE | supported | PG 16+ | `sample: { method, percent, seed }` find option and `{ model, sample }` in `from`. | | FETCH FIRST … WITH TIES | supported | PG 16+ | `withTies: true` with `limit` and `order`. | | UNION / INTERSECT / EXCEPT [ALL] | supported | PG 16+ | `Subquery#union()`, `intersect()`, `except()` (`{ all: true }`); `source: subquery` reads model rows from the result. | | Subqueries (IN, scalar, EXISTS / NOT EXISTS, correlated) | supported | PG 16+ | `Model.subquery()`, `exists()`, `notExists()`; `IN (subquery)` in `where`. | | Row-value comparison (keyset pagination) | supported | PG 16+ | `tuple()` expression. | | Standalone VALUES lists and set-returning functions in FROM (unnest, generate_series, WITH ORDINALITY) | supported | PG 16+ | `from` entries `{ values }` and `{ function, args, columns, ordinality }`. | | Aggregates with FILTER, ORDER BY and ordered-set forms | via literal() / raw SQL | PG 16+ | Plain aggregates through `fn()`; `FILTER (WHERE …)` and `WITHIN GROUP` through `literal()`. | | ONLY (table inheritance) | out of scope | PG 16+ | Legacy inheritance; partitioning is the supported way to split tables. | ### DML | Feature | Status | Since | Note | | --- | --- | --- | --- | | INSERT … ON CONFLICT DO NOTHING | supported | PG 16+ | `onConflict` with `action: "nothing"`. | | ON CONFLICT DO UPDATE with expressions and inserted/updated flag | supported | PG 16+ | `onConflict` update action with `excluded()`; `Model.insert()` reports `wasInserted`. | | ON CONFLICT DO UPDATE … WHERE | supported | PG 16+ | `where` of the `onConflict` update action. | | ON CONFLICT ON CONSTRAINT, expression and partial-index targets | supported | PG 16+ | `onConflict` targets: `constraint`, columns or expressions, with `where`. | | INSERT … OVERRIDING SYSTEM / USER VALUE | supported | PG 16+ | `overriding: "system" \| "user"` write option. | | INSERT … SELECT | supported | PG 16+ | `Model.insertFrom()`. | | UPDATE … FROM and DELETE … USING | supported | PG 16+ | `from` option of `Model.update`, `using` option of `Model.destroy`. | | UPDATE SET (a, b) = (sub-SELECT) and WHERE CURRENT OF | via literal() / raw SQL | PG 16+ | Per-column expressions work through `literal()`; row-assignment forms need a raw query. | | MERGE (WHEN MATCHED / NOT MATCHED, DELETE, DO NOTHING) | supported | PG 16+ | `Model.merge()` with VALUES or subquery source. | | MERGE … RETURNING merge_action() and WHEN NOT MATCHED BY SOURCE | supported | PG 17+ | Rejected before running on servers older than 17. | | RETURNING on INSERT / UPDATE / DELETE | supported | PG 16+ | `returning` option of create, bulkCreate, update, destroy. | | RETURNING OLD (pre-statement values) | supported | PG 18+ | `returningOld` → `instance.oldValues`. `RETURNING NEW` is the default row. | | TRUNCATE | supported | PG 16+ | `Model.truncate()`. | | COPY FROM STDIN (bulk load) | supported | PG 16+ | `Model.copyFrom()` streams arrays and async iterables. | | COPY TO STDOUT (export) | supported | PG 16+ | `Model.copyTo()` returns an async iterable. | | Bulk insert via UNNEST arrays | supported | PG 16+ | `bulkCreate(rows, { unnest: true })`. | ### Operators and functions | Feature | Status | Since | Note | | --- | --- | --- | --- | | Comparison and logical operators (=, <>, <, >, BETWEEN, IN, IS NULL, AND/OR/NOT) | supported | PG 16+ | `Op.*` as in Sequelize v6. | | IS [NOT] DISTINCT FROM | supported | PG 16+ | `Op.isDistinctFrom`, `Op.isNotDistinctFrom`. | | = ANY($1) for long IN lists | supported | PG 16+ | Automatic above `inAsAnyThreshold`. | | LIKE / ILIKE patterns | supported | PG 16+ | `Op.like`, `Op.iLike`, `Op.startsWith`, `Op.endsWith`, `Op.substring`. | | POSIX regular expressions (~, ~*, !~, !~*) | supported | PG 16+ | `Op.regexp`, `Op.iRegexp` and negations. | | SIMILAR TO | supported | PG 16+ | `Op.similarTo`, `Op.notSimilarTo`. | | JSON / JSONB containment, nested paths and key-exists (@>, #>>, ?, ?|, ?&) | supported | PG 16+ | Nested `where` objects, `Op.contains`, `Op.hasKey`, `Op.hasAnyKeys`, `Op.hasAllKeys`. | | jsonpath operators (@?, @@) and jsonb_path_* functions | supported | PG 16+ | `Op.jsonPathExists` (`@?`), `Op.match` through `where()` (`@@`), `jsonbPath()` for the `jsonb_path_*` functions. | | SQL/JSON constructors and query functions (JSON_EXISTS, JSON_QUERY, JSON_VALUE) | via literal() / raw SQL | PG 17+ | Through `literal()` in attributes or `where`. | | JSON_TABLE | supported | PG 17+ | `from` entry `{ jsonTable: { doc, path, columns } }`; `NESTED PATH` is not modelled. | | Array operators (@>, <@, &&, ANY, ALL) | supported | PG 16+ | `Op.contains`, `Op.contained`, `Op.overlap`, `Op.any`, `Op.all`. | | Range operators (@>, &&, <<, >>, &<, &>, -|-) | supported | PG 16+ | `Op.contains`, `Op.overlap`, `Op.strictLeft`, `Op.strictRight`, `Op.noExtendLeft`, `Op.noExtendRight`, `Op.adjacent`. | | Multirange operators and functions (range_agg, unnest) | supported | PG 16+ | Range operators (`Op.contains`, `Op.overlap`, `Op.strictLeft`, …) on multirange columns; `range_agg`, `unnest` through `fn()`. | | Full-text search match (@@) | supported | PG 16+ | `Op.match` with `fn("to_tsquery", …)` / `fn("websearch_to_tsquery", …)`. | | Full-text ranking and highlighting (ts_rank, ts_headline, setweight) | supported | PG 16+ | `tsRank` (also `ts_rank_cd`), `tsHeadline`, `setWeight`, `toTsVector`, `toTsQuery`, `plainToTsQuery`, `phraseToTsQuery`, `websearchToTsQuery` with an optional configuration. | | Network operators (<<, <<=, >>, >>=, host(), network()) | supported | PG 16+ | `Op.strictLeft`, `Op.strictRight`, `Op.containedOrEqual`, `Op.containsOrEqual`, `Op.overlap`; `host()` and `network()` through `fn()`. | | Geometric operators and functions | supported | PG 16+ | `Op.contains`, `Op.contained`, `Op.overlap`, `Op.strictLeft`, `Op.strictRight` on geometric columns; operands of another type need `cast()`; `<->`, `?#` and functions through `literal()` / `fn()`. | | hstore operators (->, ?, @>) | supported | PG 16+ | `Op.contains` and `Op.eq` take objects; `->`, `?` and other operators through `literal()`. | | ltree operators (@>, <@, ~, ?) | via literal() / raw SQL | PG 16+ | Equality and `IN` work on `DataTypes.LTREE` columns; `<@`, `@>`, `~` and `?` through `literal()` (see the ltree row in Data types). | | pg_trgm similarity (%, similarity(), word_similarity()) | supported | PG 16+ | `Op.trigramSimilar` and word variants, `trigramSimilarity()`, `trigramWordSimilarity()`, `trigramDistance()` (`<->`); needs `CREATE EXTENSION pg_trgm`; the `gin_trgm_ops` index uses the `operator` index option. | | UUID functions (gen_random_uuid, uuidv7) | supported | PG 16+ | `fn("gen_random_uuid")` as default or expression; `uuidv7()` needs PostgreSQL 18; `DataTypes.UUIDV4` generates client-side. | | Interval arithmetic and date functions (date_trunc, age, make_interval) | via literal() / raw SQL | PG 16+ | Through `fn()` / `literal()`; the INTERVAL column type is supported. | | Any SQL function or expression through fn(), cast(), col(), literal() | supported | PG 16+ | Function names pass an allowlist; `literal()` is raw by design. | ### Data types | Feature | Status | Since | Note | | --- | --- | --- | --- | | smallint, integer, bigint, serial, identity | supported | PG 16+ | `SMALLINT`, `INTEGER`, `BIGINT` (returned as string), `autoIncrement` (serial or identity). | | numeric / decimal, real, double precision | supported | PG 16+ | `DECIMAL(p, s)` returned as string; `REAL`, `DOUBLE`, `FLOAT`. | | text, varchar, char, boolean | supported | PG 16+ | `TEXT`, `STRING(n)`, `CHAR(n)`, `BOOLEAN`. | | timestamptz, date, time | supported | PG 16+ | `DATE` (timestamptz), `DATEONLY`, `TIME`. | | timestamp without time zone | supported | PG 16+ | `DataTypes.TIMESTAMP(fsp?)`; values are `Date`s with the local wall-clock time. | | interval | supported | PG 16+ | `DataTypes.INTERVAL`. | | money | supported | PG 16+ | `DataTypes.MONEY`; read as the server formats it (`lc_monetary`, e.g. `$12.50`); write numbers or strings. | | bytea | supported | PG 16+ | `DataTypes.BLOB` ↔ `Buffer`. | | enum (CREATE TYPE … AS ENUM) | supported | PG 16+ | `DataTypes.ENUM`; `sync({ alter })` adds new values. | | composite types | supported | PG 16+ | `DataTypes.COMPOSITE(name, fields)` with object values; `createSql()` renders `CREATE TYPE`; array fields are not supported. | | domains | via literal() / raw SQL | PG 16+ | Create with raw DDL, then use the base type in the model; the type name cannot be set directly. | | arrays (including arrays of enum) | supported | PG 16+ | `DataTypes.ARRAY(type)`. | | range types (int4range, int8range, numrange, daterange, tsrange, tstzrange) | supported | PG 16+ | `DataTypes.RANGE(type)` with `[lower, upper]` values. | | multirange types | supported | PG 16+ | `DataTypes.MULTIRANGE(type)` (PostgreSQL 14+) with arrays of `[lower, upper]` ranges. | | json and jsonb | supported | PG 16+ | `DataTypes.JSON`, `DataTypes.JSONB`. | | xml | supported | PG 16+ | `DataTypes.XML`; values are XML text; `xpath()` through `literal()` / `fn()`. | | bit and bit varying | supported | PG 16+ | `DataTypes.BIT(n)`, `DataTypes.VARBIT(n)`; values are strings of `0` and `1`. | | uuid | supported | PG 16+ | `DataTypes.UUID` with `UUIDV4` client default. | | inet, cidr, macaddr | supported | PG 16+ | `DataTypes.INET`, `CIDR`, `MACADDR`. | | macaddr8 | supported | PG 16+ | `DataTypes.MACADDR8`. | | geometric types (point, line, lseg, box, path, polygon, circle) | supported | PG 16+ | `DataTypes.POINT`, `LINE`, `LSEG`, `BOX`, `PATH`, `POLYGON`, `CIRCLE` with object / point-array values. | | tsvector | supported | PG 16+ | `DataTypes.TSVECTOR`. | | tsquery | supported | PG 16+ | `DataTypes.TSQUERY`; values are query strings (`'fat' & 'rat'`). | | pg_lsn, txid_snapshot and other system types | out of scope | PG 16+ | Replication and internals types; read through raw queries. | | citext (extension) | supported | PG 16+ | `DataTypes.CITEXT`; run `CREATE EXTENSION citext` first. | | hstore (extension) | supported | PG 16+ | `DataTypes.HSTORE`; values are objects of strings (or `null`); run `CREATE EXTENSION hstore` first. | | ltree (extension) | supported | PG 16+ | `DataTypes.LTREE`; values are strings (`'Top.Science'`); run `CREATE EXTENSION ltree` first. | | PostGIS geometry / geography | supported | PG 16+ | `DataTypes.GEOMETRY(type, srid)` / `GEOGRAPHY(type, srid)` with GeoJSON values (SRID in `crs`); needs `CREATE EXTENSION postgis`; tests run only where PostGIS is installed (CI job `PostGIS`). | | Stored and virtual generated columns, identity columns | supported | PG 16+ | `generated: { as, stored }` and `identity: "always" \| "byDefault"` column options. `VIRTUAL` generated columns need PostgreSQL 18. | ### DDL (sync and QueryInterface) | Feature | Status | Since | Note | | --- | --- | --- | --- | | Tables from models (sync, force, alter) and createTable / dropTable | supported | PG 16+ | `sequelize.sync()`, `QueryInterface.createTable()`. | | Primary key, unique, check and foreign-key constraints with referential actions | supported | PG 16+ | `addConstraint`, column `references`, `onDelete`, `onUpdate`. | | DEFERRABLE constraints | supported | PG 16+ | `Deferrable` values on `references`. | | UNIQUE NULLS NOT DISTINCT | supported | PG 16+ | `nullsNotDistinct` on unique columns, constraints and indexes. | | EXCLUDE constraints | supported | PG 16+ | `addConstraint({ type: 'exclude', exclude: [{ name \| expression, with }], using, where, include, deferrable })`; violations raise `ExclusionConstraintError`. | | NOT VALID constraints and VALIDATE CONSTRAINT | supported | PG 16+ | `notValid` on check and foreign key constraints, `validateConstraint`. | | NOT ENFORCED constraints, WITHOUT OVERLAPS keys, FK PERIOD | supported | PG 18+ | `enforced: false`, `withoutOverlaps`, `period` and `references.fields` on `addConstraint`; PostgreSQL 18 syntax, sent as written. | | Indexes: unique, partial, covering (INCLUDE), GIN, BRIN, CONCURRENTLY, IF NOT EXISTS | supported | PG 16+ | `addIndex` / model `indexes`: `where`, `include`, `using`, `operator`, `concurrently`, `ifNotExists`. GiST, SP-GiST and hash go through `using`. | | Expression indexes (lower(email)) | supported | PG 16+ | `{ expression }` index fields (trusted SQL) with `collate`, `operator`, `order`, `nulls`, `include`; an explicit `name` is required. | | ALTER TABLE: add / change / rename / remove column, rename table | supported | PG 16+ | `QueryInterface` methods. | | Enum ALTER (ADD VALUE) | supported | PG 16+ | `sync({ alter: true })`; `dropEnum` and `dropAllEnums`. | | Comments on tables and columns | supported | PG 16+ | `comment` option on `createTable` and columns. | | Schemas | supported | PG 16+ | `createSchema`, `dropSchema`, `showAllSchemas`, model `schema` option. | | Introspection (describeTable, showAllTables, tableExists, foreign keys) | supported | PG 16+ | `QueryInterface`; every query filters by schema. | | Views and materialized views | supported | PG 16+ | `createView` (`replace`, `temporary`, `recursive`, `checkOption`), `createMaterializedView`, `refreshMaterializedView` (`concurrently`), `dropView`, `dropMaterializedView`; the query is trusted SQL. | | Sequences (CREATE SEQUENCE, setval) | supported | PG 16+ | `createSequence`, `alterSequence`, `dropSequence`, `nextval`, `setval`; serial and identity sequences stay with `autoIncrement`. | | Functions and triggers | supported | PG 16+ | `createFunction`, `dropFunction`, `renameFunction`, `createTrigger`, `dropTrigger`, `renameTrigger` with the v6 names; bodies and `WHEN` clauses are trusted SQL. | | Declarative partitioning (PARTITION BY / PARTITION OF / ATTACH) | supported | PG 16+ | `createTable({ partitionBy })`, `createPartition`, `attachPartition`, `detachPartition` (`concurrently`, `finalize`); bounds `in`, `from` / `to`, `modulus` / `remainder`, `default`. `sync` does not create partitions. | | Extensions (CREATE EXTENSION) | supported | PG 16+ | `createExtension`, `dropExtension` with `ifNotExists`, `schema`, `version`, `cascade`. | | Row-level security policies | supported | PG 16+ | `enableRowLevelSecurity`, `disableRowLevelSecurity`, `createPolicy`, `alterPolicy`, `dropPolicy`; string conditions are trusted SQL, where objects are escaped. | | UNLOGGED and TEMPORARY tables | supported | PG 16+ | `unlogged` and `temporary` options on `createTable` and on model options (`sync`); a temporary table lives in one session, so use a transaction. | | Rules (CREATE RULE) | out of scope | PG 16+ | Legacy mechanism; triggers and views cover the use cases. | ### Session features | Feature | Status | Since | Note | | --- | --- | --- | --- | | Transactions: managed, unmanaged, CLS, afterCommit hooks | supported | PG 16+ | `sequelize.transaction()`. | | Isolation levels | supported | PG 16+ | `isolationLevel` option. | | READ ONLY transactions | supported | PG 16+ | `readOnly: true`. | | DEFERRABLE transaction mode (SERIALIZABLE READ ONLY DEFERRABLE) | supported | PG 16+ | `deferrable` transaction option. | | Savepoints (nested transactions) | supported | PG 16+ | A `transaction` option inside a transaction creates a savepoint. | | Advisory locks | supported | PG 16+ | `sequelize.withAdvisoryLock()`, `transaction.advisoryLock()`. | | LISTEN / NOTIFY | supported | PG 16+ | `sequelize.listen()`, `sequelize.notify()` on a dedicated client. | | SET LOCAL settings (statement_timeout, lock_timeout, RLS variables, search_path) | supported | PG 16+ | `settings` transaction option. | | Server-side cursors and streaming (findEach) | supported | PG 16+ | `Model.findEach()`. | | COPY streaming with backpressure | supported | PG 16+ | `copyTo` is an async iterable; `copyFrom` accepts async iterables. | | Read replicas | supported | PG 16+ | `replication: { read, write }`, `useMaster`. | | Bound parameters and replacements in raw queries | supported | PG 16+ | `sequelize.query()` with `bind` and `replacements`. | | Named prepared statements | supported | PG 16+ | `statementCache` option; opt-in, bounded per connection, ADR-023. | | SSL / TLS connections | via literal() / raw SQL | PG 16+ | The `ssl` option and `dialectOptions` pass through to `pg`; no test runs against a TLS server. | | Per-query statement timeout | supported | PG 16+ | `statementTimeout` query option (ms). | | EXPLAIN / EXPLAIN ANALYZE | via literal() / raw SQL | PG 16+ | `sequelize.query("EXPLAIN (FORMAT JSON) …")`. | | Two-phase commit (PREPARE TRANSACTION) | out of scope | PG 16+ | Needs a transaction manager outside the ORM. | ### Out of scope | Feature | Status | Since | Note | | --- | --- | --- | --- | | Roles, GRANT / REVOKE, default privileges | out of scope | PG 16+ | Server administration; use migrations with raw SQL or your infrastructure tooling. | | Replication setup (publications, subscriptions, slots, logical decoding) | out of scope | PG 16+ | Operations concern, not data access. Replica reads are supported. | | Tablespaces | out of scope | PG 16+ | Storage layout is an operations concern. | | VACUUM, ANALYZE, REINDEX, CLUSTER, pg_stat views | out of scope | PG 16+ | Maintenance; run through a raw query when needed. | | Procedural languages (PL/pgSQL bodies, DO blocks, procedures) | out of scope | PG 16+ | The ORM does not author server-side code; calling `fn()` works. Creating functions is tracked under DDL. | | Extension internals (writing or configuring extensions) | out of scope | PG 16+ | Types and operators of popular extensions are covered above; their administration is not. | | Foreign data wrappers and foreign tables | out of scope | PG 16+ | Server configuration; a foreign table can be modelled like a regular table. | | Server configuration (ALTER SYSTEM, pg_hba.conf, event triggers) | out of scope | PG 16+ | Server administration. | ## Security Source: https://tormozz48.github.io/postgrelize/security postgrelize builds SQL so that data from your users cannot change the meaning of a statement. This page lists every input that reaches SQL, how it is protected, and the few APIs that take raw SQL by design. To report a vulnerability, see [SECURITY.md](https://github.com/tormozz48/postgrelize/blob/main/SECURITY.md). ### How inputs are protected | Mechanism | Meaning | | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Bound** | Sent to PostgreSQL as a `$n` parameter, never as SQL text | | **Identifier** | Quoted as an identifier (`"` doubled): the value can only name a table, column, alias, channel, … | | **Allowlist** | Checked against a fixed set or a strict pattern; anything else throws before SQL is built | | **Literal** | Escaped string literal (`''`, `E'…'` with doubled backslashes; NUL bytes rejected). In DDL, `COPY TO` and `JSON_TABLE` paths, where PostgreSQL does not accept parameters, and in `replacements` of `sequelize.query` and of the finders ([ADR-036](https://github.com/tormozz48/postgrelize/blob/main/.10x/adrs/036-inlined-raw-query-replacements.md), [ADR-037](https://github.com/tormozz48/postgrelize/blob/main/.10x/adrs/037-inlined-finder-replacements.md)) | | **Raw by design** | SQL you write yourself. Not escaped. Never build it from user input | | Input | Protection | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | | `where` values, `Op.*` values, `in` lists, JSON values, `limit` / `offset`, `increment` amounts, values of `create` / `update` / `upsert` / `bulkCreate` / `insert` / `merge` | Bound | | `Op.similarTo` / `Op.jsonPathExists` / trigram `Op.*` values, text of `toTsQuery` / `plainToTsQuery` / `phraseToTsQuery` / `websearchToTsQuery` / `toTsVector`, `tsHeadline` options string, `jsonbPath` path (as `jsonpath`) and `vars` (one jsonb parameter), `trigramSimilarity` / `trigramDistance` arguments | Bound | | `sequelize.query` `bind` (`$1`, `$name`) | Bound | | `replacements` (`:name`, `?`) of `sequelize.query` and of the finders (`findAll`, `findOne`, `findByPk`, `count`, `findAndCountAll`, `Model.reload`, ...) for placeholders inside `literal()`: strings, numbers, booleans, dates, JSON, arrays for `IN (:ids)`; written into the SQL text like v6, so one call can run several statements | Literal | | String arguments of `fn()` (`fn('COUNT', '*')`, `fn('concat_ws', ' ', col('a'))`) and the value of `Op.is` (`null`, booleans, `literal()`, or any value, as in v6; [ADR-038](https://github.com/tormozz48/postgrelize/blob/main/.10x/adrs/038-inlined-fn-string-arguments.md)) | Literal | | JSON paths in `where` keys (`'meta.a.b'`, nested objects) | Bound | | Attribute and column names, `where` keys, `order` / `group` targets, aliases, `as`, table and schema names, CTE names, index and constraint names, `LISTEN` / `NOTIFY` channels, `lock.of` | Identifier | | `HSTORE` keys and values (serialized to one bound hstore text parameter), values of `LTREE`, `MONEY`, `XML`, `BIT`, `TSQUERY`, `MACADDR8`, `TIMESTAMP` columns, values of `POINT`, `LINE`, `LSEG`, `BOX`, `PATH`, `POLYGON`, `CIRCLE` columns (coordinates validated as finite numbers, then one bound text parameter), values of `MULTIRANGE` columns (bounds formatted into one bound multirange text parameter), values of `GEOMETRY` / `GEOGRAPHY` columns (GeoJSON type allowlisted, coordinates finite numbers, SRID digits only, sent as one bound hex EWKB parameter), values of `COMPOSITE` columns (fields quoted into one bound record text parameter, cast to the quoted type name in `where`) | Bound | | Values and conditions of `insertStatement` / `updateStatement` / `deleteStatement` | Bound | | `VALUES` cells, function arguments, `TABLESAMPLE` percent and seed, `JSON_TABLE` document | Bound | | CTE `search` / `cycle` columns and added column names, `from` aliases, source column aliases, set-returning function names, `JSON_TABLE` column names | Identifier | | `TABLESAMPLE` method, CTE `search` mode, `JSON_TABLE` column types | Allowlist | | `JSON_TABLE` jsonpath strings (PostgreSQL accepts only constants there) | Literal | | Operands of set operations (`union()`, `intersect()`, `except()`), `source` subqueries, the `withTies` fetch count | Bound | | `NOTIFY` payloads, advisory-lock keys, transaction `settings`, `statementTimeout` (validated integer), `bulkCreate` `unnest` column arrays | Bound | | `order` directions, `Op` operators, `where(col, comparator, value)` comparators, `fn()` names, `Model.aggregate` function names, `cast()` and `'attr::type'` types, `lock` strengths, isolation levels, transaction `deferrable` (booleans only), `onDelete` / `onUpdate`, index `using` / operator classes, `Deferrable`, DataTypes parameters (`STRING(n)`, `DECIMAL(p, s)`, `BIT(n)`, `VARBIT(n)`, `TIMESTAMP(p)`, …), `timezone`, `COPY TO` format options | Allowlist | | Text search configuration names (plain or schema-qualified identifier, bound as `regconfig`), `setWeight` labels (`A`–`D`), `jsonbPath` kinds, `tsRank` `weights` (four finite numbers) and `normalization` (integer 0–63) | Allowlist | | DDL defaults (an `HSTORE` or geometric default object is serialized, then escaped), table and column comments, `ENUM` values, partial-index and `CHECK` conditions, `COPY TO` filters | Literal | | `COMPOSITE` type and field names (quoted by `createSql()` and in column DDL; field types come from data types), extension, sequence names and schemas, `ownedBy` table and column | Identifier | | Extension `version` | Literal | | Sequence `dataType` | Allowlist | | Sequence `start`, `increment`, bounds, `cache`, `restartWith`, `setval` values | Allowlist (whole numbers only) | | `nextval` / `setval` sequence names | Bound (as `regclass` text) | | Policy names, policy roles | Identifier | | Policy `command` and `kind` | Allowlist | | Policy `using` / `withCheck` where-object values | Literal | | View and materialized-view names, view column lists | Identifier | | View `checkOption`, materialized-view `using` access method | Allowlist | | Function names (strings), parameter and variable names, languages | Allowlist (identifier words) | | Function names given as `{ name, schema }`, trigger names, trigger tables | Identifier | | Function parameter and return types | Allowlist (strict type-name pattern) | | Function parameter directions, function characteristic keywords, trigger timing, events and clauses (`FOR EACH ROW`, `DEFERRABLE`, `REFERENCING`) | Allowlist | | Trigger function arguments, variable defaults | Literal | | Table, schema and constraint names given to `showIndex`, `showConstraint`, `getForeignKeysForTables` and `assertTableHasColumn` | Bound | | Database names given to `createDatabase` / `dropDatabase`, and everything given to `quoteIdentifier` / `quoteIdentifiers` | Identifier | | Constraint names given to `Deferrable.SET_DEFERRED` / `SET_IMMEDIATE` (`SET CONSTRAINTS`); the `deferrable` option only accepts values made by `Deferrable` | Identifier | | `createDatabase` options `encoding`, `collate`, `ctype` and `template` | Literal | | `COPY FROM` data | Escaped in the `COPY` text format | | `literal()`, the SQL text of `sequelize.query`, string `where` / `order` | **Raw by design** | | Index names, index columns, `collate` collations | Identifier | | Index and `exclude` `using` method, field `operator` class | Allowlist | | Constraint names, `validateConstraint` names, `exclude` element columns | Identifier | | `exclude` element `with` operators | Allowlist (operator characters only) | | Partition names, partition key columns and collations | Identifier | | Partition `strategy` | Allowlist | | Partition bound values (`in`, `from`, `to`), `modulus`, `remainder` | Literal (modulus and remainder: validated integer) | | Index field `nulls` and `order` | Allowlist | | Index, `exclude` and partition key `expression`, function `body`, trigger `WHEN (...)` clause, view and materialized-view `query`, policy `using` / `withCheck` strings | Raw by design (trusted SQL, not escaped) | The `statementCache` option sends no user data to PostgreSQL as a name: a prepared statement is named `pgz_` plus a hash of the SQL text, and its `max` must be a positive integer. Values stay bound parameters. ### Safe patterns User values in model queries are always bound: ```ts // Values from users are always sent as bound parameters. const byTitle = await Post.findAll({ where: { title: input['title'] } }); const searched = await Post.count({ where: { title: { [Op.iLike]: `%${input['search']}%` } } }); ``` In raw SQL, pass user values through `replacements` (escaped into the SQL text, as in Sequelize v6) or `bind` (bound parameters): ```ts // Raw SQL: put user values in replacements or bind, never in the SQL text. const rows = (await sequelize.query('SELECT title FROM "Posts" WHERE title = :title', { type: QueryTypes.SELECT, replacements: { title: input['title'] }, })) as { title: string }[]; ``` Column names chosen by users (sorting, filtering by a field) are quoted, so they cannot inject SQL. But they can still name any column of the table. Map them through your own allowlist: ```ts // Column names from users: map them through your own allowlist. const sortable = { rank: 'rank', title: 'title' } as const; const column = sortable[input['sort'] as keyof typeof sortable] ?? 'rank'; const sorted = await Post.findAll({ order: [[column, 'DESC']] }); ``` `literal()` inserts its text unchanged. Use it only for constant SQL written by you: ```ts // literal() is inserted as is: only constant SQL written by you. const nullsLast = await Post.findAll({ order: [literal('"rank" DESC NULLS LAST')] }); ``` ### Not injection, but worth knowing - **Filtering on any column.** Passing a request object straight in as `where` lets callers filter on any column, including ones you never show. Build `where` from the fields you allow. - **Mass assignment.** `Model.update(values)` and `create(values)` write every attribute present in `values`. Pass `fields` or pick the allowed attributes first. - **LIKE patterns.** `Op.like`, `Op.startsWith`, `Op.substring` and `Op.endsWith` keep LIKE semantics, as in Sequelize v6: `%`, `_` and `\` in the value act as wildcards. Escape them when users should match literally. ### How this is verified - Every input above has tests on a real PostgreSQL in `tests/integration/security/`. The tests use a payload corpus: quote breakouts, backslash and `E''` tricks, dollar quoting, `U&` escapes, comments, stacked statements, very long strings. They also run property-based tests with random strings, checking that values read back byte-for-byte and identifiers name exactly what was given. A canary table proves that no injected statement ran. - CodeQL (`security-extended` queries) scans every pull request. - Every input that reaches SQL must have a protection and tests before it is merged ([ADR-020](https://github.com/tormozz48/postgrelize/blob/main/.10x/adrs/020-injection-assurance.md)). ## Sequelize issues fixed in postgrelize Source: https://tormozz48.github.io/postgrelize/sequelize-issues Open issues of [sequelize/sequelize](https://github.com/sequelize/sequelize/issues) that affect Sequelize v6 on PostgreSQL, checked against postgrelize (review of 73 issues, 2026-11-14). Fixes made in postgrelize and the v6 parity items have regression tests in this repository; the "works correctly" list was verified with reproduction scripts run on both libraries at review time. ### Bugs fixed in postgrelize (Sequelize v6 still affected) These fixes intentionally differ from Sequelize v6 ([ADR-016](https://github.com/tormozz48/postgrelize/blob/main/.10x/adrs/016-v6-bug-divergence.md)). | Issue | Fixed behaviour | | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [#18617](https://github.com/sequelize/sequelize/issues/18617) | JSON `where` keys with `,`, `"` or `\` are matched correctly | | [#5173](https://github.com/sequelize/sequelize/issues/5173) | jsonb operators (`Op.contains`, `Op.hasKey`, …) on nested JSON paths | | [#16043](https://github.com/sequelize/sequelize/issues/16043) | `{ [Op.any]: [...] }` shorthand | | [#14497](https://github.com/sequelize/sequelize/issues/14497) | `upsert` with `overriding` on `GENERATED ALWAYS` identity columns | | [#12595](https://github.com/sequelize/sequelize/issues/12595) | `upsert` on a partial unique index uses its predicate | | (no issue) `createTrigger` function arguments | Arguments are rendered as literals (`EXECUTE FUNCTION f('a', 1)`); v6 rendered typed parameter declarations, which PostgreSQL rejects | | [#16787](https://github.com/sequelize/sequelize/issues/16787) | `describeTable` unquotes literal defaults (`'it''s'`, `'x::y'`) | | [#13167](https://github.com/sequelize/sequelize/issues/13167) | `sync({ alter })` keeps the sequence of non-key `autoIncrement` columns | | [#18423](https://github.com/sequelize/sequelize/issues/18423) | `sync({ schema })` / `drop({ schema })` work in that schema only | | [#18256](https://github.com/sequelize/sequelize/issues/18256) | `belongsToMany` with a custom `sourceKey` and `limit` | | [#12971](https://github.com/sequelize/sequelize/issues/12971) | top-level `$include.attr$` condition with a hasMany include and `limit` | | — | `describeTable` reads enum values of the column's type in its own schema, in declared order (v6 matches the type name in any schema) | | — | `Model.aggregate` validates the function name (v6 inserts it into SQL unchecked) | | — | `transaction({ isolationLevel })` accepts only `ISOLATION_LEVELS` values (v6 inserts it into SQL unchecked) | | — | `bulkCreate({ ignoreDuplicates })` assigns returned rows to the records that were inserted (v6 mixes them up) | | — | Nested `create` with a built instance as a child (`Post.create({ Comments: [Comment.build()] }, { include })`) saves and links it (v6 silently drops the child) | ### Works correctly in postgrelize | Issue | Title | Kind | | ------------------------------------------------------------- | -------------------------------------------------------------------- | -------- | | [#18379](https://github.com/sequelize/sequelize/issues/18379) | Sync fails when multiple schemas contain same-named table | bug | | [#18362](https://github.com/sequelize/sequelize/issues/18362) | PG column queries parse generated SQL | bug | | [#18320](https://github.com/sequelize/sequelize/issues/18320) | Normalize generated-column expressions in alter drift detection | bug | | [#18306](https://github.com/sequelize/sequelize/issues/18306) | `Op.in: []` emits `IN (NULL)`, `Op.not` around it returns 0 rows | bug | | [#17806](https://github.com/sequelize/sequelize/issues/17806) | Postgres join with schema errors | bug | | [#17769](https://github.com/sequelize/sequelize/issues/17769) | upsert not returning PK for concurrent duplicates | bug | | [#17570](https://github.com/sequelize/sequelize/issues/17570) | findOrCreate breaks logical replication (temp function DDL) | bug | | [#17544](https://github.com/sequelize/sequelize/issues/17544) | `ENUM('PREFERENCES')` parsed as `REFERENCES` | bug | | [#17455](https://github.com/sequelize/sequelize/issues/17455) | upsert returns wrong ID for an existing row | bug | | [#17435](https://github.com/sequelize/sequelize/issues/17435) | `undefined` in JSON fields breaks change detection | bug | | [#17288](https://github.com/sequelize/sequelize/issues/17288) | describeTable fails with column comments + same table in two schemas | bug | | [#16445](https://github.com/sequelize/sequelize/issues/16445) | getForeignKeyReferencesForTable does not filter by schema | bug | | [#16404](https://github.com/sequelize/sequelize/issues/16404) | bulkCreate updateOnDuplicate with UUID PK makes bad SQL | bug | | [#16239](https://github.com/sequelize/sequelize/issues/16239) | bulkCreate wrong ON CONFLICT target for composite PK | bug | | [#15883](https://github.com/sequelize/sequelize/issues/15883) | Crash when the connection fails | bug | | [#15860](https://github.com/sequelize/sequelize/issues/15860) | Cloning `ARRAY` fails with scopes | bug | | [#15543](https://github.com/sequelize/sequelize/issues/15543) | Index not created when table exists in another schema | bug | | [#15058](https://github.com/sequelize/sequelize/issues/15058) | upsert second element is always `null` | bug/docs | | [#14750](https://github.com/sequelize/sequelize/issues/14750) | Returning values after delete | feature | | [#13184](https://github.com/sequelize/sequelize/issues/13184) | `Model.drop()` throws without options | bug | | [#12961](https://github.com/sequelize/sequelize/issues/12961) | `sync({alter})` duplicates FKs with schemas | bug | | [#12718](https://github.com/sequelize/sequelize/issues/12718) | VIRTUAL/GENERATED STORED columns | feature | | [#12654](https://github.com/sequelize/sequelize/issues/12654) | NOWAIT in SELECT FOR UPDATE | feature | | [#12612](https://github.com/sequelize/sequelize/issues/12612) | IS [NOT] DISTINCT FROM | feature | | [#12382](https://github.com/sequelize/sequelize/issues/12382) | `returning` on `Model.destroy()` | feature | | [#11749](https://github.com/sequelize/sequelize/issues/11749) | Missing `::VARCHAR[]` cast for `Op.contains` via `$nested$` | bug | | [#11748](https://github.com/sequelize/sequelize/issues/11748) | Can't update a row with an empty array | bug | | [#11671](https://github.com/sequelize/sequelize/issues/11671) | JSONB `?` operator | feature | | [#11656](https://github.com/sequelize/sequelize/issues/11656) | ON CONFLICT DO UPDATE with WHERE | feature | | [#11223](https://github.com/sequelize/sequelize/issues/11223) | bulkCreate updateOnDuplicate: no PK for new rows | bug | | [#11204](https://github.com/sequelize/sequelize/issues/11204) | bulkCreate ignores trigger-set values | bug | | [#10966](https://github.com/sequelize/sequelize/issues/10966) | bulkCreate returns `Literal` for literal defaults | bug | | [#10952](https://github.com/sequelize/sequelize/issues/10952) | removeIndex with schema | bug | | [#10710](https://github.com/sequelize/sequelize/issues/10710) | upsert broken with `literal('uuid_generate_v4()')` default | bug | | [#10533](https://github.com/sequelize/sequelize/issues/10533) | SUM returns string | bug | | [#10435](https://github.com/sequelize/sequelize/issues/10435) | Ambiguous column with JOIN + GROUP BY | bug | | [#9853](https://github.com/sequelize/sequelize/issues/9853) | AVG not properly averaging | bug | | [#9635](https://github.com/sequelize/sequelize/issues/9635) | changeColumn does not drop NOT NULL | bug | | [#9565](https://github.com/sequelize/sequelize/issues/9565) | JSONB keys replaced with column names | bug | | [#7941](https://github.com/sequelize/sequelize/issues/7941) | Concurrent findOrCreate fails with comma in unique value | bug | | [#5475](https://github.com/sequelize/sequelize/issues/5475) | `SELECT DISTINCT ON` | feature | | [#4900](https://github.com/sequelize/sequelize/issues/4900) | INTERVAL data type | feature | | [#3000](https://github.com/sequelize/sequelize/issues/3000) | Datetimes wrong with TIMESTAMP WITHOUT TIME ZONE | bug | ### Matches Sequelize v6 6.37 (fixed upstream, verified here) | Issue | Behaviour | | ------------------------------------------------------------- | ------------------------------------------------------------------ | | [#13734](https://github.com/sequelize/sequelize/issues/13734) | upsert / `updateOnDuplicate` conflict target from unique `indexes` | | [#10419](https://github.com/sequelize/sequelize/issues/10419) | explicitly declared `createdAt` / `updatedAt` attributes | | [#17486](https://github.com/sequelize/sequelize/issues/17486) | `upsert` keeps a supplied `updatedAt` | | [#15466](https://github.com/sequelize/sequelize/issues/15466) | `ARRAY(ENUM)` values returned as arrays | | [#11100](https://github.com/sequelize/sequelize/issues/11100) | `findOrCreate` returns `ARRAY(ENUM)` as an array | | [#15522](https://github.com/sequelize/sequelize/issues/15522) | `sync()` with foreign-key cycles | | [#17118](https://github.com/sequelize/sequelize/issues/17118) | `addColumn` keeps the column comment | | [#9040](https://github.com/sequelize/sequelize/issues/9040) | `order` by a JSON path; numbers sort numerically | ### Intentional differences from Sequelize v6 - Foreign-key cycles: v6 creates the tables without the cyclic foreign keys; postgrelize creates both constraints after all tables exist. - `order: ['json.path']`: v6 orders the text value (`10, 100, 9`); postgrelize orders the jsonb value (`9, 10, 100`). - `upsert` with timestamp attributes mapped to another `field`: v6 overwrites supplied values with now; postgrelize keeps them. - `$include.attr$` in a top-level `where` together with `limit`: postgrelize turns the limit subquery off (as `subQuery: false`) instead of producing invalid SQL; `limit` then counts joined rows. - `describeTable` returns unquoted literal defaults (`it's` instead of `its`). ### Known, not fixed - [#16929](https://github.com/sequelize/sequelize/issues/16929) `literal()` increments through `upsert`: inherent to the v6 `upsert` API. Use the `onConflict` option with `literal('"T"."balance" + EXCLUDED."balance"')` in `action.update`. - [#11968](https://github.com/sequelize/sequelize/issues/11968) `upsert` does not restore soft-deleted paranoid rows (same as v6). - [#11288](https://github.com/sequelize/sequelize/issues/11288) ordering by an included hasMany column with `limit` (same SQL as v6). - [#12948](https://github.com/sequelize/sequelize/issues/12948) memory leak report: not reproduced. - [#11146](https://github.com/sequelize/sequelize/issues/11146) the same association included twice under one alias (`separate: false` and `separate: true`) is not merged or rejected. - v6 public names postgrelize lacks (statics such as `Sequelize.STRING` or the error classes, hook shorthands, some `Model` and `QueryInterface` methods) are tracked by a test against `sequelize@6` and listed in [API differences](./guide/migrating#api-differences); the list only shrinks. - Not implemented v6 options: `searchPath`, `create({ ignoreDuplicates })`, named / shared `ENUM` types. # API reference ## Class: AccessDeniedError Thrown when PostgreSQL rejects the credentials (SQLSTATE `28P01` or `28000`). ### Example ```ts try { await sequelize.authenticate(); } catch (e) { if (e instanceof AccessDeniedError) { console.error('check username and password'); } } ``` ### Extends - [`ConnectionError`](ConnectionError.md)\<`this`\> ### Constructors #### Constructor > **new AccessDeniedError**(`parent`): `AccessDeniedError` Wraps a driver error; the message and `cause` are taken from it. ##### Parameters ###### parent `Error` Original driver error. ##### Returns `AccessDeniedError` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`constructor`](ConnectionError.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`cause`](ConnectionError.md#cause) *** #### message > **message**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`message`](ConnectionError.md#message) *** #### name > **name**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`name`](ConnectionError.md#name) *** #### original > `readonly` **original**: `Error` Original driver error (alias of `parent`). ##### Inherited from [`ConnectionError`](ConnectionError.md).[`original`](ConnectionError.md#original) *** #### parent > `readonly` **parent**: `Error` Original driver error. ##### Inherited from [`ConnectionError`](ConnectionError.md).[`parent`](ConnectionError.md#parent) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`stack`](ConnectionError.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`ConnectionError`](ConnectionError.md).[`stackTraceLimit`](ConnectionError.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`captureStackTrace`](ConnectionError.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`ConnectionError`](ConnectionError.md).[`prepareStackTrace`](ConnectionError.md#preparestacktrace) ## Class: AggregateError Bundles the errors of one bulk operation into a single error (Sequelize v6 `AggregateError`). `bulkCreate` with `validate: true` validates every record and throws this error with one [BulkRecordError](BulkRecordError.md) per invalid record. The message joins the messages of all errors with newlines. ### Example ```ts try { await User.bulkCreate([{ email: 'a' }, { email: 'b' }], { validate: true }); } catch (e) { if (e instanceof AggregateError) { console.error(`${e.errors.length} records failed`); } } ``` ### Extends - [`Error`](Error.md) ### Constructors #### Constructor > **new AggregateError**(`errors`): `AggregateError` Creates the error from the collected errors. ##### Parameters ###### errors readonly `Error`[] Collected errors. ##### Returns `AggregateError` ##### Overrides [`Error`](Error.md).[`constructor`](Error.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`Error`](Error.md).[`cause`](Error.md#cause) *** #### errors > `readonly` **errors**: readonly `Error`[] Collected errors. *** #### message > **message**: `string` ##### Inherited from [`Error`](Error.md).[`message`](Error.md#message) *** #### name > **name**: `string` ##### Inherited from [`Error`](Error.md).[`name`](Error.md#name) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`Error`](Error.md).[`stack`](Error.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`Error`](Error.md).[`stackTraceLimit`](Error.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`Error`](Error.md).[`captureStackTrace`](Error.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`Error`](Error.md).[`prepareStackTrace`](Error.md#preparestacktrace) ## Abstract Class: Association\ Association between two models (Sequelize v6 `Association`). Subclasses resolve the keys, add the foreign key attributes and implement the accessor methods that are installed on the source prototype (`getX`, `setX`, `createX`, ...). ### Example ```ts const association: Association = Post.belongsTo(User); association.associationType; // 'BelongsTo' ``` ### Type Parameters #### S `S` *extends* [`AnyModel`](../type-aliases/AnyModel.md) = [`AnyModel`](../type-aliases/AnyModel.md) Instance type of the source model. #### T `T` *extends* [`AnyModel`](../type-aliases/AnyModel.md) = [`AnyModel`](../type-aliases/AnyModel.md) Instance type of the target model. ### Implements - `Association` ### Constructors #### Constructor > `protected` **new Association**\<`S`, `T`\>(`type`, `source`, `target`, `options`, `name`, `keys`): `Association`\<`S`, `T`\> Creates the association description; subclasses call `install()` afterwards. ##### Parameters ###### type [`AssociationType`](../type-aliases/AssociationType.md) Kind of association. ###### source [`ModelStatic`](../type-aliases/ModelStatic.md)\<`S`\> Model the association is defined on. ###### target [`ModelStatic`](../type-aliases/ModelStatic.md)\<`T`\> Associated model. ###### options [`AssociationOptions`](../type-aliases/AssociationOptions.md) Association options. ###### name [`AssociationName`](../type-aliases/AssociationName.md) Singular and plural alias forms. ###### keys `AssociationKeyFields` Resolved keys. ##### Returns `Association`\<`S`, `T`\> ### Properties #### accessors > `readonly` **accessors**: `Readonly`\<`Record`\<`string`, `string`\>\> Names of the instance methods added to the source model. ##### Implementation of `AssociationFields.accessors` *** #### as > `readonly` **as**: `string` Alias used in `include` and as the instance property. ##### Implementation of `AssociationFields.as` *** #### associationType > `readonly` **associationType**: [`AssociationType`](../type-aliases/AssociationType.md) Kind of association. ##### Implementation of `AssociationFields.associationType` *** #### foreignKey > `readonly` **foreignKey**: `string` Foreign key attribute (on the source for belongsTo, on the target for hasOne/hasMany, on the junction for belongsToMany). ##### Implementation of `AssociationFields.foreignKey` *** #### identifierField > `readonly` **identifierField**: `string` Column of the foreign key. ##### Implementation of `AssociationFields.identifierField` *** #### isAliased > `readonly` **isAliased**: `boolean` Whether `as` was given explicitly. ##### Implementation of `AssociationFields.isAliased` *** #### isMultiAssociation > `readonly` **isMultiAssociation**: `boolean` True for hasMany / belongsToMany. ##### Implementation of `AssociationFields.isMultiAssociation` *** #### isSingleAssociation > `readonly` **isSingleAssociation**: `boolean` True for belongsTo / hasOne. ##### Implementation of `AssociationFields.isSingleAssociation` *** #### name > `readonly` **name**: [`AssociationName`](../type-aliases/AssociationName.md) Singular and plural alias forms. ##### Implementation of `AssociationFields.name` *** #### options > `readonly` **options**: [`AssociationOptions`](../type-aliases/AssociationOptions.md) Options the association was defined with. ##### Implementation of `AssociationFields.options` *** #### otherKey > `readonly` **otherKey**: `string` \| `undefined` Junction foreign key pointing at the target (belongsToMany). ##### Implementation of `AssociationFields.otherKey` *** #### scope > `readonly` **scope**: `Readonly`\<`Record`\<`string`, `unknown`\>\> \| `undefined` Association scope. ##### Implementation of `AssociationFields.scope` *** #### source > `readonly` **source**: [`ModelStatic`](../type-aliases/ModelStatic.md)\<`S`\> Model the association is defined on. ##### Implementation of `AssociationFields.source` *** #### sourceKey > `readonly` **sourceKey**: `string` Source attribute referenced by the foreign key. ##### Implementation of `AssociationFields.sourceKey` *** #### target > `readonly` **target**: [`ModelStatic`](../type-aliases/ModelStatic.md)\<`T`\> Associated model. ##### Implementation of `AssociationFields.target` *** #### targetKey > `readonly` **targetKey**: `string` Target attribute referenced by the foreign key (belongsTo) or by `otherKey` (belongsToMany). ##### Implementation of `AssociationFields.targetKey` *** #### through > `readonly` **through**: `Readonly`\<\{ `model`: [`ModelStatic`](../type-aliases/ModelStatic.md)\<[`AnyModel`](../type-aliases/AnyModel.md)\>; `scope?`: `Readonly`\<`Record`\<`string`, `unknown`\>\>; \}\> \| `undefined` Junction model (belongsToMany). ##### Implementation of `AssociationFields.through` ## Class: AssociationError Thrown when an association is defined incorrectly, e.g. two associations of one model share an alias. ### Example ```ts try { User.hasMany(Post, { as: 'items' }); User.hasMany(Task, { as: 'items' }); } catch (e) { if (e instanceof AssociationError) { console.error(e.message); } } ``` ### Extends - [`Error`](Error.md) ### Constructors #### Constructor > **new AssociationError**(`message`): `AssociationError` Creates the error. ##### Parameters ###### message `string` Error message. ##### Returns `AssociationError` ##### Overrides [`Error`](Error.md).[`constructor`](Error.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`Error`](Error.md).[`cause`](Error.md#cause) *** #### message > **message**: `string` ##### Inherited from [`Error`](Error.md).[`message`](Error.md#message) *** #### name > **name**: `string` ##### Inherited from [`Error`](Error.md).[`name`](Error.md#name) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`Error`](Error.md).[`stack`](Error.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`Error`](Error.md).[`stackTraceLimit`](Error.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`Error`](Error.md).[`captureStackTrace`](Error.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`Error`](Error.md).[`prepareStackTrace`](Error.md#preparestacktrace) ## Class: BulkRecordError Failure of one record in a bulk operation, carrying the offending record. Collected into an [AggregateError](AggregateError.md) by `bulkCreate` with `validate: true`. ### Example ```ts try { await User.bulkCreate([{ email: 'not-an-email' }], { validate: true }); } catch (e) { if (e instanceof AggregateError) { for (const item of e.errors) { if (item instanceof BulkRecordError) { console.error(item.record, item.errors.message); } } } } ``` ### Extends - [`Error`](Error.md) ### Constructors #### Constructor > **new BulkRecordError**(`error`, `record`): `BulkRecordError` Wraps the validation error of one record; the message is copied from it. ##### Parameters ###### error `Error` Underlying error. ###### record `object` Record that failed. ##### Returns `BulkRecordError` ##### Overrides [`Error`](Error.md).[`constructor`](Error.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`Error`](Error.md).[`cause`](Error.md#cause) *** #### errors > `readonly` **errors**: `Error` Underlying error. *** #### message > **message**: `string` ##### Inherited from [`Error`](Error.md).[`message`](Error.md#message) *** #### name > **name**: `string` ##### Inherited from [`Error`](Error.md).[`name`](Error.md#name) *** #### record > `readonly` **record**: `object` Record that failed. *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`Error`](Error.md).[`stack`](Error.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`Error`](Error.md).[`stackTraceLimit`](Error.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`Error`](Error.md).[`captureStackTrace`](Error.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`Error`](Error.md).[`prepareStackTrace`](Error.md#preparestacktrace) ## Class: ConnectionAcquireTimeoutError Thrown when no pooled connection became free within `pool.acquire` milliseconds (default 60000). Raise `pool.max` or shorten the transactions that hold connections. See [PoolOptions](../type-aliases/PoolOptions.md). ### Example ```ts try { await User.findAll(); } catch (e) { if (e instanceof ConnectionAcquireTimeoutError) { console.error('pool exhausted'); } } ``` ### Extends - [`ConnectionError`](ConnectionError.md)\<`this`\> ### Constructors #### Constructor > **new ConnectionAcquireTimeoutError**(`parent`): `ConnectionAcquireTimeoutError` Wraps a driver error; the message and `cause` are taken from it. ##### Parameters ###### parent `Error` Original driver error. ##### Returns `ConnectionAcquireTimeoutError` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`constructor`](ConnectionError.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`cause`](ConnectionError.md#cause) *** #### message > **message**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`message`](ConnectionError.md#message) *** #### name > **name**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`name`](ConnectionError.md#name) *** #### original > `readonly` **original**: `Error` Original driver error (alias of `parent`). ##### Inherited from [`ConnectionError`](ConnectionError.md).[`original`](ConnectionError.md#original) *** #### parent > `readonly` **parent**: `Error` Original driver error. ##### Inherited from [`ConnectionError`](ConnectionError.md).[`parent`](ConnectionError.md#parent) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`stack`](ConnectionError.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`ConnectionError`](ConnectionError.md).[`stackTraceLimit`](ConnectionError.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`captureStackTrace`](ConnectionError.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`ConnectionError`](ConnectionError.md).[`prepareStackTrace`](ConnectionError.md#preparestacktrace) ## Class: ConnectionError Failure to reach or authenticate against PostgreSQL (Sequelize v6 `ConnectionError`). Thrown when connecting fails and for driver errors with an unmapped `08xxx` SQLSTATE. The subclasses below narrow the cause; `parent` and `original` hold the driver error. ### Example ```ts try { await sequelize.authenticate(); } catch (e) { if (e instanceof ConnectionError) { console.error('cannot connect:', e.parent.message); } } ``` ### Extends - [`Error`](Error.md) ### Extended by - [`AccessDeniedError`](AccessDeniedError.md) - [`ConnectionAcquireTimeoutError`](ConnectionAcquireTimeoutError.md) - [`ConnectionRefusedError`](ConnectionRefusedError.md) - [`ConnectionTimedOutError`](ConnectionTimedOutError.md) - [`HostNotFoundError`](HostNotFoundError.md) - [`HostNotReachableError`](HostNotReachableError.md) - [`InvalidConnectionError`](InvalidConnectionError.md) ### Constructors #### Constructor > **new ConnectionError**(`parent`): `ConnectionError` Wraps a driver error; the message and `cause` are taken from it. ##### Parameters ###### parent `Error` Original driver error. ##### Returns `ConnectionError` ##### Overrides [`Error`](Error.md).[`constructor`](Error.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`Error`](Error.md).[`cause`](Error.md#cause) *** #### message > **message**: `string` ##### Inherited from [`Error`](Error.md).[`message`](Error.md#message) *** #### name > **name**: `string` ##### Inherited from [`Error`](Error.md).[`name`](Error.md#name) *** #### original > `readonly` **original**: `Error` Original driver error (alias of `parent`). *** #### parent > `readonly` **parent**: `Error` Original driver error. *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`Error`](Error.md).[`stack`](Error.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`Error`](Error.md).[`stackTraceLimit`](Error.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`Error`](Error.md).[`captureStackTrace`](Error.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`Error`](Error.md).[`prepareStackTrace`](Error.md#preparestacktrace) ## Class: ConnectionRefusedError Thrown when the server refuses the connection (`ECONNREFUSED`), typically because PostgreSQL is not running on that host and port. ### Example ```ts try { await sequelize.authenticate(); } catch (e) { if (e instanceof ConnectionRefusedError) { console.error('database is down'); } } ``` ### Extends - [`ConnectionError`](ConnectionError.md)\<`this`\> ### Constructors #### Constructor > **new ConnectionRefusedError**(`parent`): `ConnectionRefusedError` Wraps a driver error; the message and `cause` are taken from it. ##### Parameters ###### parent `Error` Original driver error. ##### Returns `ConnectionRefusedError` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`constructor`](ConnectionError.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`cause`](ConnectionError.md#cause) *** #### message > **message**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`message`](ConnectionError.md#message) *** #### name > **name**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`name`](ConnectionError.md#name) *** #### original > `readonly` **original**: `Error` Original driver error (alias of `parent`). ##### Inherited from [`ConnectionError`](ConnectionError.md).[`original`](ConnectionError.md#original) *** #### parent > `readonly` **parent**: `Error` Original driver error. ##### Inherited from [`ConnectionError`](ConnectionError.md).[`parent`](ConnectionError.md#parent) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`stack`](ConnectionError.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`ConnectionError`](ConnectionError.md).[`stackTraceLimit`](ConnectionError.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`captureStackTrace`](ConnectionError.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`ConnectionError`](ConnectionError.md).[`prepareStackTrace`](ConnectionError.md#preparestacktrace) ## Class: ConnectionTimedOutError Thrown when the TCP connection to the server times out (`ETIMEDOUT`). ### Example ```ts try { await sequelize.authenticate(); } catch (e) { if (e instanceof ConnectionTimedOutError) { console.error('database did not answer in time'); } } ``` ### Extends - [`ConnectionError`](ConnectionError.md)\<`this`\> ### Constructors #### Constructor > **new ConnectionTimedOutError**(`parent`): `ConnectionTimedOutError` Wraps a driver error; the message and `cause` are taken from it. ##### Parameters ###### parent `Error` Original driver error. ##### Returns `ConnectionTimedOutError` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`constructor`](ConnectionError.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`cause`](ConnectionError.md#cause) *** #### message > **message**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`message`](ConnectionError.md#message) *** #### name > **name**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`name`](ConnectionError.md#name) *** #### original > `readonly` **original**: `Error` Original driver error (alias of `parent`). ##### Inherited from [`ConnectionError`](ConnectionError.md).[`original`](ConnectionError.md#original) *** #### parent > `readonly` **parent**: `Error` Original driver error. ##### Inherited from [`ConnectionError`](ConnectionError.md).[`parent`](ConnectionError.md#parent) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`stack`](ConnectionError.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`ConnectionError`](ConnectionError.md).[`stackTraceLimit`](ConnectionError.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`captureStackTrace`](ConnectionError.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`ConnectionError`](ConnectionError.md).[`prepareStackTrace`](ConnectionError.md#preparestacktrace) ## Class: DatabaseError Error returned by PostgreSQL while executing a query (Sequelize v6 `DatabaseError`). Any driver error without a more specific mapping becomes a `DatabaseError`; `sql` and `parameters` describe the failed statement and `parent.code` holds the SQLSTATE. ### Example ```ts try { await sequelize.query('SELECT * FROM missing_table'); } catch (e) { if (e instanceof DatabaseError) { console.error(e.parent.code, e.sql, e.parameters); } } ``` ### Extends - [`Error`](Error.md) ### Extended by - [`ExclusionConstraintError`](ExclusionConstraintError.md) - [`ForeignKeyConstraintError`](ForeignKeyConstraintError.md) - [`UnknownConstraintError`](UnknownConstraintError.md) - [`TimeoutError`](TimeoutError.md) ### Constructors #### Constructor > **new DatabaseError**(`parent`, `context?`): `DatabaseError` Wraps a driver error together with the statement that failed. ##### Parameters ###### parent [`DriverError`](../type-aliases/DriverError.md) \| `undefined` Original driver error; an empty one is substituted when omitted. ###### context? [`QueryErrorContext`](../type-aliases/QueryErrorContext.md) = `{}` Executed SQL and parameters; `sql` defaults to `''` and `parameters` to `[]`. ##### Returns `DatabaseError` ##### Overrides [`Error`](Error.md).[`constructor`](Error.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`Error`](Error.md).[`cause`](Error.md#cause) *** #### message > **message**: `string` ##### Inherited from [`Error`](Error.md).[`message`](Error.md#message) *** #### name > **name**: `string` ##### Inherited from [`Error`](Error.md).[`name`](Error.md#name) *** #### original > `readonly` **original**: [`DriverError`](../type-aliases/DriverError.md) Original driver error (alias of `parent`). *** #### parameters > `readonly` **parameters**: readonly `unknown`[] Bound parameter values. *** #### parent > `readonly` **parent**: [`DriverError`](../type-aliases/DriverError.md) Original driver error. *** #### sql > `readonly` **sql**: `string` Executed SQL text. *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`Error`](Error.md).[`stack`](Error.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`Error`](Error.md).[`stackTraceLimit`](Error.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`Error`](Error.md).[`captureStackTrace`](Error.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`Error`](Error.md).[`prepareStackTrace`](Error.md#preparestacktrace) ## Class: EagerLoadingError Thrown when an `include` names a model that is not associated with the queried model. ### Example ```ts try { await User.findAll({ include: [Tag] }); } catch (e) { if (e instanceof EagerLoadingError) { console.error(e.message); } } ``` ### Extends - [`Error`](Error.md) ### Constructors #### Constructor > **new EagerLoadingError**(`message`): `EagerLoadingError` Creates the error. ##### Parameters ###### message `string` Error message. ##### Returns `EagerLoadingError` ##### Overrides [`Error`](Error.md).[`constructor`](Error.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`Error`](Error.md).[`cause`](Error.md#cause) *** #### message > **message**: `string` ##### Inherited from [`Error`](Error.md).[`message`](Error.md#message) *** #### name > **name**: `string` ##### Inherited from [`Error`](Error.md).[`name`](Error.md#name) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`Error`](Error.md).[`stack`](Error.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`Error`](Error.md).[`stackTraceLimit`](Error.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`Error`](Error.md).[`captureStackTrace`](Error.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`Error`](Error.md).[`prepareStackTrace`](Error.md#preparestacktrace) ## Class: EmptyResultError Thrown by finders called with `rejectOnEmpty: true` when no row matches. Pass an `Error` instance as `rejectOnEmpty` to throw it instead of this class. ### Example ```ts try { await User.findOne({ where: { email: 'nobody@example.com' }, rejectOnEmpty: true }); } catch (e) { if (e instanceof EmptyResultError) { console.error('no such user'); } } ``` ### Extends - [`Error`](Error.md) ### Constructors #### Constructor > **new EmptyResultError**(`message?`): `EmptyResultError` Creates the error. ##### Parameters ###### message? `string` Error message. ##### Returns `EmptyResultError` ##### Overrides [`Error`](Error.md).[`constructor`](Error.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`Error`](Error.md).[`cause`](Error.md#cause) *** #### message > **message**: `string` ##### Inherited from [`Error`](Error.md).[`message`](Error.md#message) *** #### name > **name**: `string` ##### Inherited from [`Error`](Error.md).[`name`](Error.md#name) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`Error`](Error.md).[`stack`](Error.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`Error`](Error.md).[`stackTraceLimit`](Error.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`Error`](Error.md).[`captureStackTrace`](Error.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`Error`](Error.md).[`prepareStackTrace`](Error.md#preparestacktrace) ## Class: Error Root of the error hierarchy, so one `instanceof` check catches every error postgrelize throws (Sequelize v6 `BaseError`). Programmer mistakes (such as committing a finished transaction) still throw a plain `Error`. ### Example ```ts try { await User.findOne({ where: { id: 1 }, rejectOnEmpty: true }); } catch (e) { if (e instanceof BaseError) { console.error(e.name, e.message); } } ``` ### Extends - `Error` ### Extended by - [`AggregateError`](AggregateError.md) - [`AssociationError`](AssociationError.md) - [`BulkRecordError`](BulkRecordError.md) - [`ConnectionError`](ConnectionError.md) - [`DatabaseError`](DatabaseError.md) - [`EagerLoadingError`](EagerLoadingError.md) - [`EmptyResultError`](EmptyResultError.md) - [`InstanceError`](InstanceError.md) - [`QueryError`](QueryError.md) - [`SequelizeScopeError`](SequelizeScopeError.md) - [`OptimisticLockError`](OptimisticLockError.md) - [`ValidationError`](ValidationError.md) ### Constructors #### Constructor > **new Error**(`message?`, `options?`): `BaseError` Creates the error and sets `name` to `'SequelizeBaseError'`. ##### Parameters ###### message? `string` Error message. ###### options? `ErrorOptions` Standard error options (`cause`). ##### Returns `BaseError` ##### Overrides `Error.constructor` ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from `Error.cause` *** #### message > **message**: `string` ##### Inherited from `Error.message` *** #### name > **name**: `string` ##### Inherited from `Error.name` *** #### stack? > `optional` **stack?**: `string` ##### Inherited from `Error.stack` *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from `Error.stackTraceLimit` ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from `Error.captureStackTrace` *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from `Error.prepareStackTrace` ## Class: ExclusionConstraintError Thrown when a row conflicts with an exclusion constraint, e.g. overlapping ranges (SQLSTATE `23P01`). PostgreSQL-specific; v6 has no such class. `constraint` is the constraint name, `fields` the columns parsed from the PostgreSQL detail and `table` the table. ### Example ```ts try { await Task.create({ room: 'A', during: [new Date('2026-01-01'), new Date('2026-01-02')] }); } catch (e) { if (e instanceof ExclusionConstraintError) { console.error(e.constraint, e.fields); } } ``` ### Extends - [`DatabaseError`](DatabaseError.md) ### Constructors #### Constructor > **new ExclusionConstraintError**(`options`): `ExclusionConstraintError` Builds the error from the constraint details. ##### Parameters ###### options [`ConstraintErrorOptions`](../type-aliases/ConstraintErrorOptions.md) Driver error, fields and context. ##### Returns `ExclusionConstraintError` ##### Overrides [`DatabaseError`](DatabaseError.md).[`constructor`](DatabaseError.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`cause`](DatabaseError.md#cause) *** #### constraint > `readonly` **constraint**: `string` \| `undefined` Constraint name. *** #### fields > `readonly` **fields**: `Readonly`\<`Record`\<`string`, `string`\>\> \| readonly `string`[] \| `undefined` Constraint columns, exactly as passed (an object or an array, like v6). *** #### message > **message**: `string` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`message`](DatabaseError.md#message) *** #### name > **name**: `string` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`name`](DatabaseError.md#name) *** #### original > `readonly` **original**: [`DriverError`](../type-aliases/DriverError.md) Original driver error (alias of `parent`). ##### Inherited from [`DatabaseError`](DatabaseError.md).[`original`](DatabaseError.md#original) *** #### parameters > `readonly` **parameters**: readonly `unknown`[] Bound parameter values. ##### Inherited from [`DatabaseError`](DatabaseError.md).[`parameters`](DatabaseError.md#parameters) *** #### parent > `readonly` **parent**: [`DriverError`](../type-aliases/DriverError.md) Original driver error. ##### Inherited from [`DatabaseError`](DatabaseError.md).[`parent`](DatabaseError.md#parent) *** #### sql > `readonly` **sql**: `string` Executed SQL text. ##### Inherited from [`DatabaseError`](DatabaseError.md).[`sql`](DatabaseError.md#sql) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`stack`](DatabaseError.md#stack) *** #### table > `readonly` **table**: `string` \| `undefined` Table name. *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`DatabaseError`](DatabaseError.md).[`stackTraceLimit`](DatabaseError.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`captureStackTrace`](DatabaseError.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`DatabaseError`](DatabaseError.md).[`prepareStackTrace`](DatabaseError.md#preparestacktrace) ## Class: ForeignKeyConstraintError Thrown when a write references a missing row or removes a row that is still referenced (SQLSTATE `23503`). `fields` lists the referencing columns (parsed from the PostgreSQL detail), `table` the table and `index` the constraint name. ### Example ```ts try { await Post.create({ title: 'Hello', userId: 999999 }); } catch (e) { if (e instanceof ForeignKeyConstraintError) { console.error(e.table, e.fields, e.index); } } ``` ### Extends - [`DatabaseError`](DatabaseError.md) ### Constructors #### Constructor > **new ForeignKeyConstraintError**(`options`): `ForeignKeyConstraintError` Builds the error from the constraint details. ##### Parameters ###### options [`ConstraintErrorOptions`](../type-aliases/ConstraintErrorOptions.md) Driver error, fields and context. ##### Returns `ForeignKeyConstraintError` ##### Overrides [`DatabaseError`](DatabaseError.md).[`constructor`](DatabaseError.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`cause`](DatabaseError.md#cause) *** #### fields > `readonly` **fields**: `Readonly`\<`Record`\<`string`, `string`\>\> \| readonly `string`[] \| `undefined` Referencing columns, exactly as passed (an object or an array, like v6). *** #### index > `readonly` **index**: `string` \| `undefined` Constraint name. *** #### message > **message**: `string` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`message`](DatabaseError.md#message) *** #### name > **name**: `string` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`name`](DatabaseError.md#name) *** #### original > `readonly` **original**: [`DriverError`](../type-aliases/DriverError.md) Original driver error (alias of `parent`). ##### Inherited from [`DatabaseError`](DatabaseError.md).[`original`](DatabaseError.md#original) *** #### parameters > `readonly` **parameters**: readonly `unknown`[] Bound parameter values. ##### Inherited from [`DatabaseError`](DatabaseError.md).[`parameters`](DatabaseError.md#parameters) *** #### parent > `readonly` **parent**: [`DriverError`](../type-aliases/DriverError.md) Original driver error. ##### Inherited from [`DatabaseError`](DatabaseError.md).[`parent`](DatabaseError.md#parent) *** #### sql > `readonly` **sql**: `string` Executed SQL text. ##### Inherited from [`DatabaseError`](DatabaseError.md).[`sql`](DatabaseError.md#sql) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`stack`](DatabaseError.md#stack) *** #### table > `readonly` **table**: `string` \| `undefined` Table name. *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`DatabaseError`](DatabaseError.md).[`stackTraceLimit`](DatabaseError.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`captureStackTrace`](DatabaseError.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`DatabaseError`](DatabaseError.md).[`prepareStackTrace`](DatabaseError.md#preparestacktrace) ## Class: HostNotFoundError Thrown when the host name cannot be resolved (`ENOTFOUND` or `EAI_AGAIN`). ### Example ```ts try { await sequelize.authenticate(); } catch (e) { if (e instanceof HostNotFoundError) { console.error('unknown database host'); } } ``` ### Extends - [`ConnectionError`](ConnectionError.md)\<`this`\> ### Constructors #### Constructor > **new HostNotFoundError**(`parent`): `HostNotFoundError` Wraps a driver error; the message and `cause` are taken from it. ##### Parameters ###### parent `Error` Original driver error. ##### Returns `HostNotFoundError` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`constructor`](ConnectionError.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`cause`](ConnectionError.md#cause) *** #### message > **message**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`message`](ConnectionError.md#message) *** #### name > **name**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`name`](ConnectionError.md#name) *** #### original > `readonly` **original**: `Error` Original driver error (alias of `parent`). ##### Inherited from [`ConnectionError`](ConnectionError.md).[`original`](ConnectionError.md#original) *** #### parent > `readonly` **parent**: `Error` Original driver error. ##### Inherited from [`ConnectionError`](ConnectionError.md).[`parent`](ConnectionError.md#parent) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`stack`](ConnectionError.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`ConnectionError`](ConnectionError.md).[`stackTraceLimit`](ConnectionError.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`captureStackTrace`](ConnectionError.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`ConnectionError`](ConnectionError.md).[`prepareStackTrace`](ConnectionError.md#preparestacktrace) ## Class: HostNotReachableError Thrown when no route to the host exists (`EHOSTUNREACH`). ### Example ```ts try { await sequelize.authenticate(); } catch (e) { if (e instanceof HostNotReachableError) { console.error('database host is unreachable'); } } ``` ### Extends - [`ConnectionError`](ConnectionError.md)\<`this`\> ### Constructors #### Constructor > **new HostNotReachableError**(`parent`): `HostNotReachableError` Wraps a driver error; the message and `cause` are taken from it. ##### Parameters ###### parent `Error` Original driver error. ##### Returns `HostNotReachableError` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`constructor`](ConnectionError.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`cause`](ConnectionError.md#cause) *** #### message > **message**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`message`](ConnectionError.md#message) *** #### name > **name**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`name`](ConnectionError.md#name) *** #### original > `readonly` **original**: `Error` Original driver error (alias of `parent`). ##### Inherited from [`ConnectionError`](ConnectionError.md).[`original`](ConnectionError.md#original) *** #### parent > `readonly` **parent**: `Error` Original driver error. ##### Inherited from [`ConnectionError`](ConnectionError.md).[`parent`](ConnectionError.md#parent) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`stack`](ConnectionError.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`ConnectionError`](ConnectionError.md).[`stackTraceLimit`](ConnectionError.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`captureStackTrace`](ConnectionError.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`ConnectionError`](ConnectionError.md).[`prepareStackTrace`](ConnectionError.md#preparestacktrace) ## Class: InstanceError Thrown when an instance method is used on an instance in the wrong state, e.g. `reload()` for a row that no longer exists. ### Example ```ts try { await user.destroy(); await user.reload(); } catch (e) { if (e instanceof InstanceError) { console.error(e.message); } } ``` ### Extends - [`Error`](Error.md) ### Constructors #### Constructor > **new InstanceError**(`message`): `InstanceError` Creates the error. ##### Parameters ###### message `string` Error message. ##### Returns `InstanceError` ##### Overrides [`Error`](Error.md).[`constructor`](Error.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`Error`](Error.md).[`cause`](Error.md#cause) *** #### message > **message**: `string` ##### Inherited from [`Error`](Error.md).[`message`](Error.md#message) *** #### name > **name**: `string` ##### Inherited from [`Error`](Error.md).[`name`](Error.md#name) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`Error`](Error.md).[`stack`](Error.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`Error`](Error.md).[`stackTraceLimit`](Error.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`Error`](Error.md).[`captureStackTrace`](Error.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`Error`](Error.md).[`prepareStackTrace`](Error.md#preparestacktrace) ## Class: InvalidConnectionError Thrown when the connection parameters are rejected by the network layer (`EINVAL`). ### Example ```ts try { await sequelize.authenticate(); } catch (e) { if (e instanceof InvalidConnectionError) { console.error('check host and port settings'); } } ``` ### Extends - [`ConnectionError`](ConnectionError.md)\<`this`\> ### Constructors #### Constructor > **new InvalidConnectionError**(`parent`): `InvalidConnectionError` Wraps a driver error; the message and `cause` are taken from it. ##### Parameters ###### parent `Error` Original driver error. ##### Returns `InvalidConnectionError` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`constructor`](ConnectionError.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`cause`](ConnectionError.md#cause) *** #### message > **message**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`message`](ConnectionError.md#message) *** #### name > **name**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`name`](ConnectionError.md#name) *** #### original > `readonly` **original**: `Error` Original driver error (alias of `parent`). ##### Inherited from [`ConnectionError`](ConnectionError.md).[`original`](ConnectionError.md#original) *** #### parent > `readonly` **parent**: `Error` Original driver error. ##### Inherited from [`ConnectionError`](ConnectionError.md).[`parent`](ConnectionError.md#parent) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`stack`](ConnectionError.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`ConnectionError`](ConnectionError.md).[`stackTraceLimit`](ConnectionError.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`ConnectionError`](ConnectionError.md).[`captureStackTrace`](ConnectionError.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`ConnectionError`](ConnectionError.md).[`prepareStackTrace`](ConnectionError.md#preparestacktrace) ## Class: Model\ Base class of models, API-compatible with Sequelize v6 `Model`. ### Example ```ts class User extends Model, InferCreationAttributes> { declare id: CreationOptional; declare email: string; } User.init({ id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, email: DataTypes.STRING }, { sequelize }); ``` ### Extends - `ModelInstanceValues`\<`TAttributes`\> - `ModelInstancePersistence`\<`TAttributes`\> - `ModelStatics` ### Type Parameters #### TAttributes `TAttributes` *extends* `object` = `any` Attribute types (usually `InferAttributes`). #### TCreationAttributes `TCreationAttributes` *extends* `object` = `TAttributes` Attribute types accepted on creation (usually `InferCreationAttributes`). ### Constructors #### Constructor > **new Model**\<`TAttributes`, `TCreationAttributes`\>(`values?`, `options?`): `Model`\<`TAttributes`, `TCreationAttributes`\> Builds an instance without saving it. Prefer `Model.build`. ##### Parameters ###### values? [`Values`](../type-aliases/Values.md) \| `Partial`\<`TCreationAttributes`\> = `{}` Attribute values. ###### options? [`BuildOptions`](../type-aliases/BuildOptions.md) = `{}` Build options. ##### Returns `Model`\<`TAttributes`, `TCreationAttributes`\> ##### Inherited from `ModelInstanceValues.constructor` ### Properties #### \_attributes > **\_attributes**: `TAttributes` Phantom type of attributes; not set at runtime. *** #### \_creationAttributes > **\_creationAttributes**: `TCreationAttributes` Phantom type of creation attributes; not set at runtime. *** #### \_previousDataValues > **\_previousDataValues**: `Partial`\<`TAttributes`\> Values as of the last load/save. *** #### dataValues > **dataValues**: `TAttributes` Current attribute values. ##### Inherited from `ModelInstanceValues.dataValues` *** #### isNewRecord > **isNewRecord**: `boolean` True until the instance is saved or when built from a query result. *** #### afterBulkCreate > `static` **afterBulkCreate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `afterBulkCreate` hook: `Model.afterBulkCreate(fn)` or `Model.afterBulkCreate(name, fn)`. *** #### afterBulkDestroy > `static` **afterBulkDestroy**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `afterBulkDestroy` hook: `Model.afterBulkDestroy(fn)` or `Model.afterBulkDestroy(name, fn)`. *** #### afterBulkRestore > `static` **afterBulkRestore**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `afterBulkRestore` hook: `Model.afterBulkRestore(fn)` or `Model.afterBulkRestore(name, fn)`. *** #### afterBulkUpdate > `static` **afterBulkUpdate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `afterBulkUpdate` hook: `Model.afterBulkUpdate(fn)` or `Model.afterBulkUpdate(name, fn)`. *** #### afterCreate > `static` **afterCreate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `afterCreate` hook: `Model.afterCreate(fn)` or `Model.afterCreate(name, fn)`. *** #### afterDestroy > `static` **afterDestroy**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `afterDestroy` hook: `Model.afterDestroy(fn)` or `Model.afterDestroy(name, fn)`. *** #### afterFind > `static` **afterFind**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `afterFind` hook: `Model.afterFind(fn)` or `Model.afterFind(name, fn)`. *** #### afterRestore > `static` **afterRestore**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `afterRestore` hook: `Model.afterRestore(fn)` or `Model.afterRestore(name, fn)`. *** #### afterSave > `static` **afterSave**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `afterSave` hook: `Model.afterSave(fn)` or `Model.afterSave(name, fn)`. *** #### afterSync > `static` **afterSync**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds an `afterSync` hook: runs after `Model.sync()` and after this model's turn in `sequelize.sync()`. *** #### afterUpdate > `static` **afterUpdate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `afterUpdate` hook: `Model.afterUpdate(fn)` or `Model.afterUpdate(name, fn)`. *** #### afterUpsert > `static` **afterUpsert**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `afterUpsert` hook: `Model.afterUpsert(fn)` or `Model.afterUpsert(name, fn)`. *** #### afterValidate > `static` **afterValidate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `afterValidate` hook: `Model.afterValidate(fn)` or `Model.afterValidate(name, fn)`. *** #### beforeBulkCreate > `static` **beforeBulkCreate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `beforeBulkCreate` hook: `Model.beforeBulkCreate(fn)` or `Model.beforeBulkCreate(name, fn)`. *** #### beforeBulkDestroy > `static` **beforeBulkDestroy**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `beforeBulkDestroy` hook: `Model.beforeBulkDestroy(fn)` or `Model.beforeBulkDestroy(name, fn)`. *** #### beforeBulkRestore > `static` **beforeBulkRestore**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `beforeBulkRestore` hook: `Model.beforeBulkRestore(fn)` or `Model.beforeBulkRestore(name, fn)`. *** #### beforeBulkUpdate > `static` **beforeBulkUpdate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `beforeBulkUpdate` hook: `Model.beforeBulkUpdate(fn)` or `Model.beforeBulkUpdate(name, fn)`. *** #### beforeCount > `static` **beforeCount**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `beforeCount` hook: `Model.beforeCount(fn)` or `Model.beforeCount(name, fn)`. *** #### beforeCreate > `static` **beforeCreate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `beforeCreate` hook: `Model.beforeCreate(fn)` or `Model.beforeCreate(name, fn)`. *** #### beforeDestroy > `static` **beforeDestroy**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `beforeDestroy` hook: `Model.beforeDestroy(fn)` or `Model.beforeDestroy(name, fn)`. *** #### beforeFind > `static` **beforeFind**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `beforeFind` hook: `Model.beforeFind(fn)` or `Model.beforeFind(name, fn)`. *** #### beforeFindAfterExpandIncludeAll > `static` **beforeFindAfterExpandIncludeAll**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `beforeFindAfterExpandIncludeAll` hook: `Model.beforeFindAfterExpandIncludeAll(fn)` or `Model.beforeFindAfterExpandIncludeAll(name, fn)`. *** #### beforeFindAfterOptions > `static` **beforeFindAfterOptions**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `beforeFindAfterOptions` hook: `Model.beforeFindAfterOptions(fn)` or `Model.beforeFindAfterOptions(name, fn)`. *** #### beforeRestore > `static` **beforeRestore**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `beforeRestore` hook: `Model.beforeRestore(fn)` or `Model.beforeRestore(name, fn)`. *** #### beforeSave > `static` **beforeSave**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `beforeSave` hook: `Model.beforeSave(fn)` or `Model.beforeSave(name, fn)`. *** #### beforeSync > `static` **beforeSync**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `beforeSync` hook: runs before `Model.sync()` and before this model's turn in `sequelize.sync()`. *** #### beforeUpdate > `static` **beforeUpdate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `beforeUpdate` hook: `Model.beforeUpdate(fn)` or `Model.beforeUpdate(name, fn)`. *** #### beforeUpsert > `static` **beforeUpsert**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `beforeUpsert` hook: `Model.beforeUpsert(fn)` or `Model.beforeUpsert(name, fn)`. *** #### beforeValidate > `static` **beforeValidate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `beforeValidate` hook: `Model.beforeValidate(fn)` or `Model.beforeValidate(name, fn)`. *** #### validationFailed > `static` **validationFailed**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a `validationFailed` hook: `Model.validationFailed(fn)` or `Model.validationFailed(name, fn)`. ### Accessors #### \_model ##### Get Signature > **get** **\_model**(): *typeof* `Model` Model class of the instance. ###### Returns *typeof* `Model` *** #### oldValues ##### Get Signature > **get** **oldValues**(): `Readonly`\<`Record`\<`string`, `unknown`\>\> \| `null` \| `undefined` For instances returned with `returningOld: true`: attribute values of the row before the statement, or `null` when the row did not exist (inserted). `undefined` otherwise. PostgreSQL 18+. ###### Returns `Readonly`\<`Record`\<`string`, `unknown`\>\> \| `null` \| `undefined` *** #### sequelize ##### Get Signature > **get** **sequelize**(): [`Sequelize`](Sequelize.md) `Sequelize` instance the model belongs to. ###### Returns [`Sequelize`](Sequelize.md) *** #### wasInserted ##### Get Signature > **get** **wasInserted**(): `boolean` \| `undefined` For instances returned by `insert`, `create` / `bulkCreate` / `upsert` with `onConflict`: true when the row was inserted, false when an existing row was updated (or nothing was written). `undefined` otherwise. PostgreSQL extension. ###### Returns `boolean` \| `undefined` *** #### associations ##### Get Signature > **get** `static` **associations**(): `Readonly`\<`Record`\<`string`, [`Association`](Association.md)\>\> Associations of the model by alias (Sequelize v6 `Model.associations`). ###### Returns `Readonly`\<`Record`\<`string`, [`Association`](Association.md)\>\> *** #### modelName ##### Get Signature > **get** `static` **modelName**(): `string` Name the model was registered under, as given by `modelName` in the init options (default: the class name). ###### Returns `string` *** #### options ##### Get Signature > **get** `static` **options**(): [`DefinitionOptions`](../type-aliases/DefinitionOptions.md) Model options after defaults were applied. ###### Returns [`DefinitionOptions`](../type-aliases/DefinitionOptions.md) *** #### primaryKeyAttribute ##### Get Signature > **get** `static` **primaryKeyAttribute**(): `string` First primary key attribute name. ###### Returns `string` *** #### primaryKeyAttributes ##### Get Signature > **get** `static` **primaryKeyAttributes**(): readonly `string`[] All primary key attribute names. ###### Returns readonly `string`[] *** #### queryInterface ##### Get Signature > **get** `static` **queryInterface**(): [`QueryInterface`](QueryInterface.md) Schema API of the owning `Sequelize` instance (Sequelize v6 `Model.queryInterface`). ###### Returns [`QueryInterface`](QueryInterface.md) *** #### rawAttributes ##### Get Signature > **get** `static` **rawAttributes**(): `Readonly`\<`Record`\<`string`, [`AttributeDefinition`](../type-aliases/AttributeDefinition.md)\>\> Normalized attributes keyed by attribute name. ###### Returns `Readonly`\<`Record`\<`string`, [`AttributeDefinition`](../type-aliases/AttributeDefinition.md)\>\> *** #### sequelize ##### Get Signature > **get** `static` **sequelize**(): [`Sequelize`](Sequelize.md) `Sequelize` instance the model belongs to. ###### Returns [`Sequelize`](Sequelize.md) *** #### tableName ##### Get Signature > **get** `static` **tableName**(): `string` Name of the database table backing the model (pluralized model name unless `tableName` was set). ###### Returns `string` ### Methods #### changed() ##### Call Signature > **changed**(): `false` \| (keyof `TAttributes` & `string`)[] Lists the attributes changed since the instance was loaded or last saved. ###### Returns `false` \| (keyof `TAttributes` & `string`)[] Changed attribute names, or `false` when nothing changed. ###### Example ```ts user.set('email', 'ada@example.com'); const changedFields = user.changed(); ``` ###### Inherited from `ModelInstanceValues.changed` ##### Call Signature > **changed**(`key`): `boolean` Checks whether one attribute changed since the instance was loaded or last saved. ###### Parameters ###### key keyof `TAttributes` & `string` Attribute name. ###### Returns `boolean` True when changed. ###### Inherited from `ModelInstanceValues.changed` ##### Call Signature > **changed**(`key`, `value`): `void` Marks an attribute as changed or unchanged, which controls whether [Model.save](#save) writes it. ###### Parameters ###### key keyof `TAttributes` & `string` Attribute name. ###### value `boolean` Changed flag. ###### Returns `void` ###### Inherited from `ModelInstanceValues.changed` ##### Call Signature > **changed**\<`K`\>(`key`): `boolean` Checks whether one attribute changed, addressed by a key of the model class (Sequelize v6 signature, so `keyof M` works in generic code). ###### Type Parameters ###### K `K` *extends* keyof `Model`\<`TAttributes`, `TCreationAttributes`\> ###### Parameters ###### key `K` Attribute name. ###### Returns `boolean` True when changed. ###### Inherited from `ModelInstanceValues.changed` ##### Call Signature > **changed**\<`K`\>(`key`, `value`): `void` Marks an attribute as changed or unchanged, addressed by a key of the model class (Sequelize v6 signature). ###### Type Parameters ###### K `K` *extends* keyof `Model`\<`TAttributes`, `TCreationAttributes`\> ###### Parameters ###### key `K` Attribute name. ###### value `boolean` Changed flag. ###### Returns `void` ###### Inherited from `ModelInstanceValues.changed` *** #### decrement() > **decrement**(`fields`, `options?`): `Promise`\<`Model`\<`TAttributes`, `TCreationAttributes`\>\> Decrements numeric attributes of this row in the database (`SET x = x - by`). The instance values are not reloaded; call [Model.reload](#reload) to read the new numbers. ##### Parameters ###### fields [`AttributeAmounts`](../type-aliases/AttributeAmounts.md)\<`TAttributes`\> Attribute name(s) or map of amounts. ###### options? `Omit`\<[`IncrementOptions`](../type-aliases/IncrementOptions.md)\<`TAttributes`\>, `"where"`\> = `{}` `by` (default 1), `silent`, and query options. ##### Returns `Promise`\<`Model`\<`TAttributes`, `TCreationAttributes`\>\> This instance. ##### Example ```ts await user.decrement('credits', { by: 5 }); ``` ##### Inherited from `ModelInstancePersistence.decrement` *** #### destroy() > **destroy**(`options?`): `Promise`\<`void`\> Deletes the row of this instance. For paranoid models it sets `deletedAt` instead, unless `force: true`. Runs `beforeDestroy`/`afterDestroy` hooks unless `hooks: false`. ##### Parameters ###### options? [`InstanceDestroyOptions`](../type-aliases/InstanceDestroyOptions.md) = `{}` Destroy options (`force`, `hooks`, query options). ##### Returns `Promise`\<`void`\> Resolves when deleted. ##### Example ```ts await user.destroy(); ``` ##### Inherited from `ModelInstancePersistence.destroy` *** #### equals() > **equals**(`other`): `boolean` Compares the primary keys of two instances. ##### Parameters ###### other `Model` Instance to compare with. ##### Returns `boolean` True when all primary key values are equal. ##### Example ```ts const other = User.build({ id: user.get('id') }); const same = user.equals(other); ``` ##### Inherited from `ModelInstanceValues.equals` *** #### equalsOneOf() > **equalsOneOf**(`others`): `boolean` Tells whether the instance equals any of the given instances (same model and primary keys). ##### Parameters ###### others readonly `Model`\<`any`, `any`\>[] Instances to compare with. ##### Returns `boolean` True when at least one equals this instance. ##### Example ```ts const known = user.equalsOneOf(users); ``` ##### Inherited from `ModelInstanceValues.equalsOneOf` *** #### get() ##### Call Signature > **get**(`options?`): `TAttributes` Returns all attribute values of the instance; no query is run. ###### Parameters ###### options? `Readonly`\<\{ `clone?`: `boolean`; `plain?`: `boolean`; `raw?`: `boolean`; \}\> `plain: true` returns a copy of all values with custom getters applied; `raw: true` skips custom getters. ###### Returns `TAttributes` Values object. ###### Example ```ts const values = user.get({ plain: true }); ``` ###### Inherited from `ModelInstanceValues.get` ##### Call Signature > **get**\<`K`\>(`key`, `options?`): `Model`\<`TAttributes`, `TCreationAttributes`\>\[`K`\] Returns one attribute value, applying its custom getter unless `raw` is set. ###### Type Parameters ###### K `K` *extends* keyof `Model`\<`TAttributes`, `TCreationAttributes`\> ###### Parameters ###### key `K` Attribute name. ###### options? `Readonly`\<\{ `clone?`: `boolean`; `plain?`: `boolean`; `raw?`: `boolean`; \}\> `raw: true` skips the custom getter. ###### Returns `Model`\<`TAttributes`, `TCreationAttributes`\>\[`K`\] Attribute value. ###### Example ```ts const email = user.get('email'); ``` ###### Inherited from `ModelInstanceValues.get` ##### Call Signature > **get**(`key`, `options?`): `unknown` Returns the value of an attribute or association that is addressed by a plain string, for example an included association or a dynamic key. ###### Parameters ###### key `string` Attribute or association name. ###### options? `Readonly`\<\{ `clone?`: `boolean`; `plain?`: `boolean`; `raw?`: `boolean`; \}\> `raw: true` skips the custom getter. ###### Returns `unknown` The value, untyped. ###### Example ```ts const posts = user.get('Posts'); ``` ###### Inherited from `ModelInstanceValues.get` *** #### getDataValue() > **getDataValue**\<`K`\>(`key`): `TAttributes`\[`K`\] Reads the stored value of an attribute, bypassing its custom getter. ##### Type Parameters ###### K `K` *extends* `string` \| `number` \| `symbol` ##### Parameters ###### key `K` Attribute name. ##### Returns `TAttributes`\[`K`\] Raw value. ##### Example ```ts const stored = user.getDataValue('email'); ``` ##### Inherited from `ModelInstanceValues.getDataValue` *** #### increment() > **increment**(`fields`, `options?`): `Promise`\<`Model`\<`TAttributes`, `TCreationAttributes`\>\> Increments numeric attributes of this row in the database (`SET x = x + by`). The instance values are not reloaded; call [Model.reload](#reload) to read the new numbers. ##### Parameters ###### fields [`AttributeAmounts`](../type-aliases/AttributeAmounts.md)\<`TAttributes`\> Attribute name(s) or map of amounts. ###### options? `Omit`\<[`IncrementOptions`](../type-aliases/IncrementOptions.md)\<`TAttributes`\>, `"where"`\> = `{}` `by` (default 1), `silent`, and query options. ##### Returns `Promise`\<`Model`\<`TAttributes`, `TCreationAttributes`\>\> This instance. ##### Example ```ts await user.increment('loginCount'); await user.increment({ loginCount: 2, score: 10 }); ``` ##### Inherited from `ModelInstancePersistence.increment` *** #### isSoftDeleted() > **isSoftDeleted**(): `boolean` Whether this instance of a paranoid model is soft-deleted. ##### Returns `boolean` True when `deletedAt` is set. ##### Throws Error when the model is not paranoid. ##### Example ```ts if (user.isSoftDeleted()) { await user.restore(); } ``` ##### Inherited from `ModelInstancePersistence.isSoftDeleted` *** #### previous() ##### Call Signature > **previous**(): `Partial`\<`TAttributes`\> Returns the previous values of all changed attributes. ###### Returns `Partial`\<`TAttributes`\> Previous values keyed by attribute name. ###### Example ```ts user.set('email', 'ada@example.com'); const before = user.previous(); ``` ###### Inherited from `ModelInstanceValues.previous` ##### Call Signature > **previous**\<`K`\>(`key`): `TAttributes`\[`K`\] \| `undefined` Returns the value an attribute had before it was changed. ###### Type Parameters ###### K `K` *extends* `string` \| `number` \| `symbol` ###### Parameters ###### key `K` Attribute name. ###### Returns `TAttributes`\[`K`\] \| `undefined` Previous value. ###### Example ```ts user.set('email', 'ada@example.com'); const before = user.previous('email'); ``` ###### Inherited from `ModelInstanceValues.previous` *** #### reload() > **reload**(`options?`): `Promise`\<`Model`\<`TAttributes`, `TCreationAttributes`\>\> Re-reads the row from the database and replaces the instance values, discarding unsaved changes. The row is read with `findOne` by primary key, so `include`, `attributes`, `paranoid`, `lock`, scopes and the find hooks apply as in Sequelize v6 (a soft-deleted row needs `paranoid: false`). ##### Parameters ###### options? [`FindOptions`](../type-aliases/FindOptions.md)\<`TAttributes`\> = `{}` Find options; `where` is always the primary key of this instance. ##### Returns `Promise`\<`Model`\<`TAttributes`, `TCreationAttributes`\>\> This instance. ##### Throws InstanceError when the row no longer exists. ##### Example ```ts await user.reload({ transaction }); await user.reload({ include: [Post], lock: transaction.LOCK.UPDATE }); ``` ##### Inherited from `ModelInstancePersistence.reload` *** #### restore() > **restore**(`options?`): `Promise`\<`void`\> Clears `deletedAt` of this soft-deleted instance of a paranoid model. ##### Parameters ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) & `Readonly`\<\{ `hooks?`: `boolean`; \}\> = `{}` Query options; `hooks: false` skips restore hooks. ##### Returns `Promise`\<`void`\> Resolves when restored. ##### Throws Error when the model is not paranoid. ##### Example ```ts await user.restore(); ``` ##### Inherited from `ModelInstancePersistence.restore` *** #### save() > **save**(`options?`): `Promise`\<`Model`\<`TAttributes`, `TCreationAttributes`\>\> Inserts the instance when it is new, otherwise updates its changed attributes. Runs validation and the `beforeValidate`/`afterValidate`, `beforeSave`/`afterSave` and `beforeCreate`/`beforeUpdate` (and `after*`) hooks unless disabled in the options; updating an unchanged instance sends no query. ##### Parameters ###### options? [`SaveOptions`](../type-aliases/SaveOptions.md)\<`TAttributes`\> = `{}` Save options. ##### Returns `Promise`\<`Model`\<`TAttributes`, `TCreationAttributes`\>\> This instance with values returned by the database. ##### Throws ValidationError when validation fails. ##### Throws UniqueConstraintError when a unique constraint is violated. ##### Throws ForeignKeyConstraintError when a foreign key constraint is violated. ##### Example ```ts const user = User.build({ email: 'ada@example.com' }); await user.save({ transaction }); ``` ##### Inherited from `ModelInstancePersistence.save` *** #### set() ##### Call Signature > **set**\<`K`\>(`key`, `value`, `options?`): `this` Sets one attribute value, applying its custom setter unless `raw` is set. Nothing is written to the database until [Model.save](#save); the attribute is marked as changed when the value differs. ###### Type Parameters ###### K `K` *extends* `string` \| `number` \| `symbol` ###### Parameters ###### key `K` Attribute name. ###### value `TAttributes`\[`K`\] New value. ###### options? `Readonly`\<\{ `raw?`: `boolean`; \}\> `raw: true` skips the custom setter and change tracking. ###### Returns `this` This instance. ###### Example ```ts user.set('email', 'ada@example.com'); await user.save(); ``` ###### Inherited from `ModelInstanceValues.set` ##### Call Signature > **set**(`values`, `options?`): `this` Sets several attribute values at once, applying custom setters unless `raw` is set. ###### Parameters ###### values [`Values`](../type-aliases/Values.md) \| `Partial`\<`TAttributes`\> Attribute values. ###### options? `Readonly`\<\{ `raw?`: `boolean`; \}\> `raw: true` skips custom setters and change tracking. ###### Returns `this` This instance. ###### Example ```ts user.set({ email: 'ada@example.com', active: true }); ``` ###### Inherited from `ModelInstanceValues.set` *** #### setAttributes() > **setAttributes**(`updates`): `this` Alias of [Model.set](#set) for several values (Sequelize v6 `setAttributes`). ##### Parameters ###### updates [`Values`](../type-aliases/Values.md) \| `Partial`\<`TAttributes`\> Attribute values. ##### Returns `this` This instance. ##### Example ```ts user.setAttributes({ email: 'ada@example.com' }); ``` ##### Inherited from `ModelInstanceValues.setAttributes` *** #### setDataValue() > **setDataValue**\<`K`\>(`key`, `value`): `this` Writes the stored value of an attribute, bypassing its custom setter, and marks it as changed. ##### Type Parameters ###### K `K` *extends* `string` \| `number` \| `symbol` ##### Parameters ###### key `K` Attribute name. ###### value `TAttributes`\[`K`\] New value. ##### Returns `this` This instance. ##### Example ```ts user.setDataValue('email', 'ada@example.com'); ``` ##### Inherited from `ModelInstanceValues.setDataValue` *** #### toJSON() > **toJSON**(): `TAttributes` Returns a deep copy of the values with custom getters applied, used by `JSON.stringify`. ##### Returns `TAttributes` Plain object. ##### Example ```ts const json = JSON.stringify(user); ``` ##### Inherited from `ModelInstanceValues.toJSON` *** #### toString() > **toString**(): `string` Describes the instance as `[object SequelizeInstance:Model]`. ##### Returns `string` The description. ##### Example ```ts String(user); // '[object SequelizeInstance:User]' ``` ##### Inherited from `ModelInstanceValues.toString` *** #### update() ##### Call Signature > **update**\<`K`\>(`key`, `value`, `options?`): `Promise`\<`Model`\<`TAttributes`, `TCreationAttributes`\>\> Sets one attribute and saves the instance. ###### Type Parameters ###### K `K` *extends* `string` \| `number` \| `symbol` ###### Parameters ###### key `K` Attribute name. ###### value [`Literal`](../interfaces/Literal.md) \| [`Fn`](../interfaces/Fn.md) \| [`Col`](../interfaces/Col.md) \| `TAttributes`\[`K`\] New value, or a `fn` / `col` / `literal` expression. ###### options? [`SaveOptions`](../type-aliases/SaveOptions.md)\<`TAttributes`\> Save options. ###### Returns `Promise`\<`Model`\<`TAttributes`, `TCreationAttributes`\>\> This instance. ###### Throws ValidationError when validation fails. ###### Example ```ts await user.update('email', 'ada@example.com'); ``` ###### Inherited from `ModelInstancePersistence.update` ##### Call Signature > **update**(`values`, `options?`): `Promise`\<`Model`\<`TAttributes`, `TCreationAttributes`\>\> Sets values and saves the instance, same as [Model.set](#set) followed by [Model.save](#save). ###### Parameters ###### values `UpdateValues`\<`TAttributes`\> New values. ###### options? [`SaveOptions`](../type-aliases/SaveOptions.md)\<`TAttributes`\> Save options. ###### Returns `Promise`\<`Model`\<`TAttributes`, `TCreationAttributes`\>\> This instance. ###### Throws ValidationError when validation fails. ###### Example ```ts await user.update({ email: 'ada@example.com' }); ``` ###### Inherited from `ModelInstancePersistence.update` *** #### validate() > **validate**(`options?`): `Promise`\<`void`\> Runs the attribute validators and model validators without saving (Sequelize v6 `instance.validate()`). ##### Parameters ###### options? [`ValidateOptions`](../type-aliases/ValidateOptions.md) = `{}` `hooks`, `skip`, `fields`. ##### Returns `Promise`\<`void`\> Resolves when valid. ##### Throws ValidationError with all failures. ##### Example ```ts await user.validate(); ``` ##### Inherited from `ModelInstancePersistence.validate` *** #### where() > **where**(`checkVersion?`): `Record`\<`string`, `unknown`\> \| `undefined` Condition that selects this row: its primary key values keyed by column name. ##### Parameters ###### checkVersion? `boolean` Also match the optimistic-locking `version` value. ##### Returns `Record`\<`string`, `unknown`\> \| `undefined` The where object (the model's `whereCollection` option when it has no primary key). ##### Example ```ts const where = user.where(); ``` ##### Inherited from `ModelInstanceValues.where` *** #### addHook() > `static` **addHook**\<`MS`\>(`this`, `type`, `nameOrFn`, `fn?`): `MS` Registers a hook function for a lifecycle event of this model, same as the named adders such as `Model.beforeCreate(fn)`. Hooks of one type run in registration order. ##### Type Parameters ###### MS `MS` *extends* [`ModelStatic`](../type-aliases/ModelStatic.md)\<[`AnyModel`](../type-aliases/AnyModel.md)\> ##### Parameters ###### this `MS` The model class. ###### type `"beforeValidate"` \| `"afterValidate"` \| `"validationFailed"` \| `"beforeCreate"` \| `"afterCreate"` \| `"beforeUpdate"` \| `"afterUpdate"` \| `"beforeSave"` \| `"afterSave"` \| `"beforeDestroy"` \| `"afterDestroy"` \| `"beforeRestore"` \| `"afterRestore"` \| `"beforeUpsert"` \| `"afterUpsert"` \| `"beforeBulkCreate"` \| `"afterBulkCreate"` \| `"beforeBulkUpdate"` \| `"afterBulkUpdate"` \| `"beforeBulkDestroy"` \| `"afterBulkDestroy"` \| `"beforeBulkRestore"` \| `"afterBulkRestore"` \| `"beforeFind"` \| `"beforeFindAfterExpandIncludeAll"` \| `"beforeFindAfterOptions"` \| `"afterFind"` \| `"beforeCount"` \| `"beforeConnect"` \| `"afterConnect"` \| `"beforeDisconnect"` \| `"afterDisconnect"` \| `"beforePoolAcquire"` \| `"afterPoolAcquire"` \| `"beforeQuery"` \| `"afterQuery"` \| `"beforeSync"` \| `"afterSync"` \| `"beforeBulkSync"` \| `"afterBulkSync"` \| `"beforeDefine"` \| `"afterDefine"` \| `"beforeInit"` \| `"afterInit"` \| `"beforeAssociate"` \| `"afterAssociate"` Hook type, e.g. `'beforeCreate'`. ###### nameOrFn `string` \| [`HookFunction`](../type-aliases/HookFunction.md) Hook name (to remove it later) or the hook function. ###### fn? [`HookFunction`](../type-aliases/HookFunction.md) Hook function when a name is given. ##### Returns `MS` The model class. ##### Example ```ts User.addHook('beforeCreate', 'normalizeEmail', async (instance: User) => { instance.set('email', String(instance.get('email')).toLowerCase()); }); ``` ##### See [Hooks guide](/guide/hooks-validation) *** #### addScope() > `static` **addScope**(`name`, `scope`, `options?`): `void` Adds a named scope (or replaces the default scope with name `'defaultScope'`). ##### Parameters ###### name `string` Scope name. ###### scope [`ScopeDefinition`](../type-aliases/ScopeDefinition.md) Options or a function returning options. ###### options? `Readonly`\<\{ `override?`: `boolean`; \}\> = `{}` `override: true` replaces an existing scope. ##### Returns `void` ##### Throws Error when the scope exists and `override` is not set. ##### Example ```ts User.addScope('active', { where: { active: true } }); User.addScope('olderThan', (age: number) => ({ where: { age: { [Op.gt]: age } } })); ``` *** #### aggregate() > `static` **aggregate**\<`M`, `T`\>(`this`, `field`, `aggregateFunction`, `options?`): `Promise`\<`T`\> Runs one SQL aggregate function over a column (`SELECT fn(col) ...`), applying the default scope and the paranoid filter. The function name is checked against a safe name pattern, never concatenated unchecked. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ###### T `T` = `unknown` ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### field `"*"` \| keyof [`Attributes`](../type-aliases/Attributes.md)\<`M`\> Attribute name or `'*'`. ###### aggregateFunction `string` SQL aggregate function name, e.g. `'max'`. ###### options? [`AggregateOptions`](../type-aliases/AggregateOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> = `{}` Options (`where`, `distinct`, `group`, `plain: false` to get rows, query options). ##### Returns `Promise`\<`T`\> Aggregated value: a number for `count` and numeric attributes, otherwise parsed like the attribute; rows with `plain: false`. ##### Example ```ts const avgPrice = await Product.aggregate('price', 'avg', { where: { active: true } }); ``` *** #### belongsTo() > `static` **belongsTo**\<`M`, `T`\>(`this`, `target`, `options?`): `BelongsTo`\<`M`, `T`\> Declares that each row of this model refers to one row of the target; the foreign key column lives on this model's table. Adds accessors such as `getX` / `setX` / `createX` to instances. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ###### T `T` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The source model class. ###### target [`ModelStatic`](../type-aliases/ModelStatic.md)\<`T`\> Associated model. ###### options? `Readonly`\<\{ `as?`: `string` \| `Readonly`\<\{ `plural`: `string`; `singular`: `string`; \}\>; `constraints?`: `boolean`; `foreignKey?`: `string` \| `Readonly`\<\{ `allowNull?`: `boolean`; `field?`: `string`; `name?`: `string`; \}\>; `hooks?`: `boolean`; `onDelete?`: `string`; `onUpdate?`: `string`; `scope?`: `Readonly`\<`Record`\<`string`, `unknown`\>\>; `sourceKey?`: `string`; `targetKey?`: `string`; \}\> Association options. ##### Returns `BelongsTo`\<`M`, `T`\> The association. ##### Example ```ts Post.belongsTo(User, { foreignKey: 'authorId', as: 'author' }); ``` ##### See [Associations guide](/guide/associations) *** #### belongsToMany() > `static` **belongsToMany**\<`M`, `T`\>(`this`, `target`, `options`): `BelongsToMany`\<`M`, `T`\> Declares a many-to-many relation between this model and the target through a junction table. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ###### T `T` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The source model class. ###### target [`ModelStatic`](../type-aliases/ModelStatic.md)\<`T`\> Associated model. ###### options [`BelongsToManyOptions`](../type-aliases/BelongsToManyOptions.md) Association options with `through`. ##### Returns `BelongsToMany`\<`M`, `T`\> The association. ##### Example ```ts Project.belongsToMany(Task, { through: 'ProjectTasks' }); ``` *** #### build() > `static` **build**\<`M`\>(`this`, `values?`, `options?`): `M` Builds a new instance in memory without touching the database; call `save()` to insert it. Defaults and custom setters are applied. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### values? [`Values`](../type-aliases/Values.md) \| [`CreationAttributes`](../type-aliases/CreationAttributes.md)\<`M`\> Attribute values. ###### options? `Readonly`\<\{ `include?`: [`IncludeOption`](../type-aliases/IncludeOption.md); `isNewRecord?`: `boolean`; `raw?`: `boolean`; \}\> Build options. ##### Returns `M` New instance. ##### Example ```ts const user = User.build({ email: 'ada@example.com' }); await user.save(); ``` *** #### bulkBuild() > `static` **bulkBuild**\<`M`\>(`this`, `records`, `options?`): `M`[] Builds several new instances in memory, same as calling [Model.build](#build) for each record. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### records readonly ([`Values`](../type-aliases/Values.md) \| [`CreationAttributes`](../type-aliases/CreationAttributes.md)\<`M`\>)[] Attribute values per instance. ###### options? `Readonly`\<\{ `include?`: [`IncludeOption`](../type-aliases/IncludeOption.md); `isNewRecord?`: `boolean`; `raw?`: `boolean`; \}\> Build options. ##### Returns `M`[] New instances. ##### Example ```ts const tags = Tag.bulkBuild([{ name: 'news' }, { name: 'sports' }]); ``` *** #### bulkCreate() > `static` **bulkCreate**\<`M`\>(`this`, `records`, `options?`): `Promise`\<`M`[]\> Inserts many rows with one multi-row `INSERT ... RETURNING`. Runs `beforeBulkCreate` and `afterBulkCreate` hooks; rows are not validated unless `validate: true`. `ignoreDuplicates`, `updateOnDuplicate` and `onConflict` map to `ON CONFLICT`; `individualHooks` or `include` insert row by row like Sequelize v6. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### records readonly [`CreationAttributes`](../type-aliases/CreationAttributes.md)\<`M`\>[] Attribute values per row. ###### options? [`BulkCreateOptions`](../type-aliases/BulkCreateOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> = `{}` Bulk create options. ##### Returns `Promise`\<`M`[]\> Instances with values returned by the database. ##### Throws ValidationError with `validate: true` when a row is invalid. ##### Throws UniqueConstraintError when a unique constraint is violated and no conflict handling is set. ##### Example ```ts const tags = await Tag.bulkCreate([{ name: 'news' }, { name: 'sports' }], { ignoreDuplicates: true }); ``` ##### See [Model.insert](#insert) for the PostgreSQL variant that returns only the rows actually written. *** #### copyFrom() > `static` **copyFrom**\<`M`\>(`this`, `rows`, `options?`): `Promise`\<`number`\> Bulk-loads rows with `COPY ... FROM STDIN` (text format) — much faster than INSERT for large volumes. No hooks or validation run; missing values are written as `NULL`. `createdAt` / `updatedAt` are filled when the model has timestamps. PostgreSQL extension. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### rows `Iterable`\<[`CreationAttributes`](../type-aliases/CreationAttributes.md)\<`M`\>, `any`, `any`\> \| `AsyncIterable`\<[`CreationAttributes`](../type-aliases/CreationAttributes.md)\<`M`\>, `any`, `any`\> Rows (array, iterable or async iterable of attribute values). ###### options? [`CopyFromOptions`](../type-aliases/CopyFromOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> = `{}` `columns` (attribute names; default: keys of the first row of an array) and query options. ##### Returns `Promise`\<`number`\> Number of copied rows. ##### Example ```ts const copied = await Task.copyFrom( [{ title: 'first' }, { title: 'second' }], { columns: ['title'] }, ); ``` *** #### copyTo() > `static` **copyTo**\<`M`\>(`this`, `options?`): `AsyncGenerator`\<`Buffer`\<`ArrayBufferLike`\>, `void`, `undefined`\> Streams `COPY (SELECT ...) TO STDOUT` output — the fastest way to export rows (e.g. CSV). Default scope, paranoid filter, `with` / `source` and includes apply. Values of the query are inlined as escaped literals because COPY cannot take parameters (ADR-013). Stopping early drains the rest before the connection is released. PostgreSQL extension. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### options? [`CopyToOptions`](../type-aliases/CopyToOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> = `{}` Find options and output format (`format`, `header`, ...). ##### Returns `AsyncGenerator`\<`Buffer`\<`ArrayBufferLike`\>, `void`, `undefined`\> Async iterator of raw output chunks. ##### Example ```ts for await (const chunk of User.copyTo({ attributes: ['id', 'email'], format: 'csv', header: true })) { process.stdout.write(chunk); } ``` *** #### count() ##### Call Signature > `static` **count**\<`M`\>(`this`, `options`): `Promise`\<[`GroupedCountResultItem`](../type-aliases/GroupedCountResultItem.md)[]\> Counts rows per group, applying the default scope and the paranoid filter. Runs `beforeCount` hooks unless `hooks: false`. ###### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ###### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class (or a scoped model class from [Model.scope](#scope)). ###### options [`CountWithOptions`](../type-aliases/CountWithOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> Count options with `group`. ###### Returns `Promise`\<[`GroupedCountResultItem`](../type-aliases/GroupedCountResultItem.md)[]\> One `{ count, ...groupColumns }` item per group. ###### Example ```ts const rows = await User.count({ group: ['role'] }); rows.map((r) => r.count); ``` ##### Call Signature > `static` **count**\<`M`\>(`this`, `options?`): `Promise`\<`number`\> Counts rows, applying the default scope and the paranoid filter. Runs `beforeCount` hooks unless `hooks: false`. ###### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ###### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class (or a scoped model class from [Model.scope](#scope)). ###### options? `Omit`\<[`CountOptions`](../type-aliases/CountOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\>, `"group"`\> Count options (`where`, `col`, `distinct`, `include`). ###### Returns `Promise`\<`number`\> The count. Use the `group` overload for per-group counts. ###### Example ```ts const active = await User.count({ where: { active: true } }); ``` *** #### create() > `static` **create**\<`M`\>(`this`, `values?`, `options?`): `Promise`\<`M`\> Builds an instance and inserts it with `INSERT ... RETURNING`, running validation and the create/save hooks. With `onConflict` (PostgreSQL extension) the insert may be skipped or turned into an update, and `instance.wasInserted` tells which happened. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### values? [`CreationAttributes`](../type-aliases/CreationAttributes.md)\<`M`\> Attribute values. ###### options? [`CreateOptions`](../type-aliases/CreateOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> = `{}` Create options (`fields`, `hooks`, `validate`, `include`, `onConflict`, query options). ##### Returns `Promise`\<`M`\> Saved instance. ##### Throws ValidationError when validation fails. ##### Throws UniqueConstraintError when a unique constraint is violated. ##### Throws ForeignKeyConstraintError when a foreign key constraint is violated. ##### Throws DatabaseError for other database errors. ##### Example ```ts const user = await User.create({ email: 'ada@example.com' }, { transaction }); ``` *** #### decrement() > `static` **decrement**\<`M`\>(`this`, `fields`, `options?`): `Promise`\<\[`affectedRows`: `M`[], `affectedCount`: `number`\]\> Atomically decrements numeric attributes of the rows matching `where` (`SET x = x - by`). ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### fields [`AttributeAmounts`](../type-aliases/AttributeAmounts.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> Attribute name(s), or a map of attribute to amount. ###### options? [`IncrementOptions`](../type-aliases/IncrementOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> = `{}` Decrement options (`where`, `by` default 1, `silent`, query options). ##### Returns `Promise`\<\[`affectedRows`: `M`[], `affectedCount`: `number`\]\> `[affectedRows, affectedCount]`: the updated instances and their number. ##### Example ```ts await Product.decrement({ stock: 3 }, { where: { id: 7 } }); ``` ##### Inherited from `ModelInstancePersistence.decrement` *** #### deleteStatement() > `static` **deleteStatement**\<`M`\>(`this`, `options?`): [`WriteStatement`](../interfaces/WriteStatement.md) Builds a `DELETE` for a data-modifying CTE (`with`). It is a real delete, also for paranoid models, and ignores the paranoid filter. With `returning: true` the deleted rows can be read through `source`, e.g. to move them to another table. PostgreSQL extension. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### options? [`WriteStatementOptions`](../type-aliases/WriteStatementOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> = `{}` `where`, `returning`. ##### Returns [`WriteStatement`](../interfaces/WriteStatement.md) Statement for the `with` option. ##### Example ```ts const done = Task.deleteStatement({ where: { done: true }, returning: true }); const removed = await Task.findAll({ with: { done }, source: 'done' }); ``` *** #### describe() > `static` **describe**(`schema?`, `options?`): `Promise`\<`Record`\<`string`, `Readonly`\<\{ `allowNull`: `boolean`; `comment`: `string` \| `null`; `defaultValue`: `unknown`; `primaryKey`: `boolean`; `special`: readonly `string`[]; `type`: `string`; \}\>\>\> Describes the table of this model: its columns, types, nullability and defaults. ##### Parameters ###### schema? `string` Schema to read; defaults to the model's schema, then `current_schema()`. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`Record`\<`string`, `Readonly`\<\{ `allowNull`: `boolean`; `comment`: `string` \| `null`; `defaultValue`: `unknown`; `primaryKey`: `boolean`; `special`: readonly `string`[]; `type`: `string`; \}\>\>\> Column descriptions by column name. ##### Example ```ts const columns = await User.describe(); ``` *** #### destroy() ##### Call Signature > `static` **destroy**\<`M`\>(`this`, `options`): `Promise`\<`M`[]\> Deletes rows matching `where` and returns the deleted instances (`DELETE ... RETURNING`, a PostgreSQL extension). For paranoid models the rows are soft-deleted unless `force: true`. ###### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ###### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### options [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) & `object` & [`BulkHookOptions`](../type-aliases/BulkHookOptions.md) & `Readonly`\<\{ `returning`: `true`; \}\> Destroy options with `returning: true`. ###### Returns `Promise`\<`M`[]\> Deleted instances. ###### Example ```ts const removed = await Post.destroy({ where: { published: false }, returning: true }); ``` ###### Inherited from `ModelInstancePersistence.destroy` ##### Call Signature > `static` **destroy**\<`M`\>(`this`, `options?`): `Promise`\<`number`\> Deletes rows matching `where` (`truncate: true` empties the table instead). For paranoid models the rows are soft-deleted (`deletedAt` is set) unless `force: true`. Runs bulk destroy hooks unless `hooks: false`. ###### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ###### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### options? [`DestroyOptions`](../type-aliases/DestroyOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> Destroy options. ###### Returns `Promise`\<`number`\> Number of deleted rows. ###### Inherited from `ModelInstancePersistence.destroy` *** #### drop() > `static` **drop**(`options?`): `Promise`\<`void`\> Drops the table of this model and the enum types it owns. ##### Parameters ###### options? [`DropOptions`](../type-aliases/DropOptions.md) = `{}` `cascade`, `schema` and query options. ##### Returns `Promise`\<`void`\> Resolves when done. ##### Example ```ts await Task.drop({ cascade: true }); ``` *** #### dropSchema() > `static` **dropSchema**(`schema`): `Promise`\<`void`\> Drops a schema with `DROP SCHEMA` (shortcut of `queryInterface.dropSchema`, Sequelize v6 `Model.dropSchema`). ##### Parameters ###### schema `string` Schema name. ##### Returns `Promise`\<`void`\> Resolves when done. ##### Example ```ts await User.dropSchema('tenant_1'); ``` *** #### findAll() > `static` **findAll**\<`M`\>(`this`, `options?`): `Promise`\<`M`[]\> Selects all rows matching the options, applying the default scope and, for paranoid models, hiding soft-deleted rows. Runs `beforeFind` and `afterFind` hooks unless `hooks: false`. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class (or a scoped model class from [Model.scope](#scope)). ###### options? [`FindOptions`](../type-aliases/FindOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> = `{}` Query options (`where`, `attributes`, `order`, `limit`, `include`, ...). ##### Returns `Promise`\<`M`[]\> Instances, or plain objects with `raw: true`. ##### Example ```ts const posts = await Post.findAll({ where: { published: true }, order: [['createdAt', 'DESC']], limit: 20, include: [User], }); ``` ##### See [Model.findEach](#findeach) to stream large result sets. *** #### findAndCountAll() ##### Call Signature > `static` **findAndCountAll**\<`M`\>(`this`, `options?`): `Promise`\<[`FindAndCountResult`](../type-aliases/FindAndCountResult.md)\<`M`\>\> Runs [Model.findAll](#findall) and [Model.count](#count) with the same filter, so `limit` / `offset` paginate the rows while `count` is the total. ###### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ###### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class (or a scoped model class from [Model.scope](#scope)). ###### options? `Omit`\<[`FindAndCountOptions`](../type-aliases/FindAndCountOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\>, `"group"`\> Query options. ###### Returns `Promise`\<[`FindAndCountResult`](../type-aliases/FindAndCountResult.md)\<`M`\>\> Total count and the current page of rows. ###### Example ```ts const { count, rows } = await Post.findAndCountAll({ where: { published: true }, limit: 10, offset: 20 }); ``` ##### Call Signature > `static` **findAndCountAll**\<`M`\>(`this`, `options`): `Promise`\<[`FindAndCountResult`](../type-aliases/FindAndCountResult.md)\<`M`, [`GroupedCountResultItem`](../type-aliases/GroupedCountResultItem.md)[]\>\> With `group`, `count` is an array with one item per group (the grouped attributes and the row count of the group) instead of a number. ###### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ###### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class (or a scoped model class from [Model.scope](#scope)). ###### options `Omit`\<[`FindAndCountOptions`](../type-aliases/FindAndCountOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\>, `"group"`\> & `Required`\<`Pick`\<[`FindAndCountOptions`](../type-aliases/FindAndCountOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\>, `"group"`\>\> Query options including `group`. ###### Returns `Promise`\<[`FindAndCountResult`](../type-aliases/FindAndCountResult.md)\<`M`, [`GroupedCountResultItem`](../type-aliases/GroupedCountResultItem.md)[]\>\> Per-group counts and the current page of rows. ###### Example ```ts const { count, rows } = await Post.findAndCountAll({ group: ['status'] }); ``` *** #### findByPk() ##### Call Signature > `static` **findByPk**\<`M`\>(`this`, `key`, `options`): `Promise`\<`M`\> Selects the row with the given primary key and rejects when none is found. ###### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ###### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class (or a scoped model class from [Model.scope](#scope)). ###### key `unknown` Primary key value. ###### options `Omit`\<[`NonNullFindOptions`](../type-aliases/NonNullFindOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\>, `"where"`\> Query options other than `where`, with `rejectOnEmpty`. ###### Returns `Promise`\<`M`\> Instance. ###### Throws EmptyResultError (or the given error) when nothing is found. ###### Example ```ts const user = await User.findByPk(42, { rejectOnEmpty: true }); ``` ##### Call Signature > `static` **findByPk**\<`M`\>(`this`, `key?`, `options?`): `Promise`\<`M` \| `null`\> Selects the row with the given primary key. ###### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ###### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class (or a scoped model class from [Model.scope](#scope)). ###### key? `unknown` Primary key value. ###### options? `Omit`\<[`FindOptions`](../type-aliases/FindOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\>, `"where"`\> Query options other than `where`. ###### Returns `Promise`\<`M` \| `null`\> Instance or `null`. ###### Example ```ts const user = await User.findByPk(42, { include: [Profile] }); ``` *** #### findCreateFind() > `static` **findCreateFind**\<`M`\>(`this`, `options`): `Promise`\<\[`M`, `boolean`\]\> Finds a row; when none matches, inserts it and, if that fails with a unique violation (a concurrent insert won), reads the row again. Unlike `findOrCreate` the insert is not wrapped in a transaction, so it suits code that already handles the race itself. Inside a transaction the insert uses a savepoint, which fixes v6 returning an unsaved instance after a conflict. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class (or a scoped model class from [Model.scope](#scope)). ###### options [`FindOrCreateOptions`](../type-aliases/FindOrCreateOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> `where` to search (required; its equality values also seed the new row), `defaults` to add on creation. ##### Returns `Promise`\<\[`M`, `boolean`\]\> `[instance, created]`. ##### Throws Error when `where` is missing. ##### Example ```ts const [tag, created] = await Tag.findCreateFind({ where: { name: 'news' }, defaults: { color: 'red' } }); ``` *** #### findEach() > `static` **findEach**\<`M`\>(`this`, `options?`, `cursor?`): `AsyncGenerator`\<`M`, `void`, `undefined`\> Streams rows with a server-side cursor (`DECLARE ... CURSOR` + `FETCH n`), so large result sets are not loaded at once. Runs inside `options.transaction` or its own transaction; the cursor is closed when iteration ends or is stopped early. Joined includes are not supported. PostgreSQL extension. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### options? [`FindOptions`](../type-aliases/FindOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> = `{}` Find options. ###### cursor? `Readonly`\<\{ `batchSize?`: `number`; \}\> = `{}` `batchSize` (rows per FETCH, default 100). ##### Returns `AsyncGenerator`\<`M`, `void`, `undefined`\> Async iterator of instances. ##### Example ```ts for await (const user of User.findEach({ where: { active: true } }, { batchSize: 500 })) { console.log(user.get('email')); } ``` *** #### findOne() ##### Call Signature > `static` **findOne**\<`M`\>(`this`, `options`): `Promise`\<`M`\> Selects the first row matching the options and rejects when none is found. ###### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ###### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class (or a scoped model class from [Model.scope](#scope)). ###### options [`NonNullFindOptions`](../type-aliases/NonNullFindOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> Query options with `rejectOnEmpty`. ###### Returns `Promise`\<`M`\> Instance. ###### Throws EmptyResultError (or the given error) when nothing is found. ###### Example ```ts const user = await User.findOne({ where: { email: 'ada@example.com' }, rejectOnEmpty: true }); ``` ##### Call Signature > `static` **findOne**\<`M`\>(`this`, `options?`): `Promise`\<`M` \| `null`\> Selects the first row matching the options (`LIMIT 1` unless `limit` is given). ###### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ###### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class (or a scoped model class from [Model.scope](#scope)). ###### options? [`FindOptions`](../type-aliases/FindOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> Query options. ###### Returns `Promise`\<`M` \| `null`\> Instance or `null`. *** #### findOrBuild() > `static` **findOrBuild**\<`M`\>(`this`, `options`): `Promise`\<\[`M`, `boolean`\]\> Finds a row, or builds a new unsaved instance when none matches; nothing is inserted. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class (or a scoped model class from [Model.scope](#scope)). ###### options [`FindOrCreateOptions`](../type-aliases/FindOrCreateOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> `where` to search (its equality values also seed the built instance), `defaults` to add when building. ##### Returns `Promise`\<\[`M`, `boolean`\]\> `[instance, built]`. ##### Example ```ts const [tag, built] = await Tag.findOrBuild({ where: { name: 'news' } }); if (built) { await tag.save(); } ``` *** #### findOrCreate() > `static` **findOrCreate**\<`M`\>(`this`, `options`): `Promise`\<\[`M`, `boolean`\]\> Finds a row, or creates it when none matches. Creation runs inside a transaction (a nested one when `options.transaction` is given); when creation fails but the row exists after all (a concurrent insert won), that row is returned, otherwise the error is rethrown. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class (or a scoped model class from [Model.scope](#scope)). ###### options [`FindOrCreateOptions`](../type-aliases/FindOrCreateOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> `where` to search (its equality values also seed the new row), `defaults` to add on creation. ##### Returns `Promise`\<\[`M`, `boolean`\]\> `[instance, created]`. ##### Example ```ts const [tag, created] = await Tag.findOrCreate({ where: { name: 'news' }, defaults: { color: 'red' } }); ``` *** #### getAssociationForAlias() > `static` **getAssociationForAlias**(`target`, `alias?`): [`Association`](Association.md)\<[`AnyModel`](../type-aliases/AnyModel.md), [`AnyModel`](../type-aliases/AnyModel.md)\> \| `null` Association to `target` for an alias, or the one declared without alias when `alias` is not a string. ##### Parameters ###### target Target model. ###### name `string` ###### alias? `string` \| \{ `plural?`: `string`; \} \| `null` Association alias. ##### Returns [`Association`](Association.md)\<[`AnyModel`](../type-aliases/AnyModel.md), [`AnyModel`](../type-aliases/AnyModel.md)\> \| `null` The association, or `null`. ##### Example ```ts const association = User.getAssociationForAlias(Post, 'posts'); ``` *** #### getAssociations() > `static` **getAssociations**(`target`): [`Association`](Association.md)\<[`AnyModel`](../type-aliases/AnyModel.md), [`AnyModel`](../type-aliases/AnyModel.md)\>[] Associations of this model whose target is the given model. ##### Parameters ###### target Target model. ###### name `string` ##### Returns [`Association`](Association.md)\<[`AnyModel`](../type-aliases/AnyModel.md), [`AnyModel`](../type-aliases/AnyModel.md)\>[] Matching associations. ##### Example ```ts const toPosts = User.getAssociations(Post); ``` *** #### getAttributes() > `static` **getAttributes**(): `Readonly`\<`Record`\<`string`, [`AttributeDefinition`](../type-aliases/AttributeDefinition.md)\>\> Returns the normalized attribute definitions, same as [Model.rawAttributes](#rawattributes). ##### Returns `Readonly`\<`Record`\<`string`, [`AttributeDefinition`](../type-aliases/AttributeDefinition.md)\>\> Attribute definitions. ##### Example ```ts const attributes = User.getAttributes(); Object.keys(attributes); ``` *** #### getTableName() > `static` **getTableName**(): `string` \| `Readonly`\<\{ `delimiter`: `string`; `name`: `string`; `schema`: `string`; `table`: `string`; `tableName`: `string`; `toString`: () => `string`; \}\> Table name, or the qualified table (`{ tableName, schema, delimiter, ... }`, like v6) when the model has a schema. `String(qualified)` is the quoted `"schema"."table"` reference. ##### Returns `string` \| `Readonly`\<\{ `delimiter`: `string`; `name`: `string`; `schema`: `string`; `table`: `string`; `tableName`: `string`; `toString`: () => `string`; \}\> Table name or qualified table. ##### Example ```ts const table = User.getTableName(); ``` *** #### hasAlias() > `static` **hasAlias**(`alias`): `boolean` Tells whether an association with this alias exists. ##### Parameters ###### alias `string` Association alias. ##### Returns `boolean` True when the model has the association. ##### Example ```ts if (User.hasAlias('posts')) {} ``` *** #### hasHook() > `static` **hasHook**(`type`): `boolean` Checks whether hooks of the type are registered on the model. ##### Parameters ###### type `"beforeValidate"` \| `"afterValidate"` \| `"validationFailed"` \| `"beforeCreate"` \| `"afterCreate"` \| `"beforeUpdate"` \| `"afterUpdate"` \| `"beforeSave"` \| `"afterSave"` \| `"beforeDestroy"` \| `"afterDestroy"` \| `"beforeRestore"` \| `"afterRestore"` \| `"beforeUpsert"` \| `"afterUpsert"` \| `"beforeBulkCreate"` \| `"afterBulkCreate"` \| `"beforeBulkUpdate"` \| `"afterBulkUpdate"` \| `"beforeBulkDestroy"` \| `"afterBulkDestroy"` \| `"beforeBulkRestore"` \| `"afterBulkRestore"` \| `"beforeFind"` \| `"beforeFindAfterExpandIncludeAll"` \| `"beforeFindAfterOptions"` \| `"afterFind"` \| `"beforeCount"` \| `"beforeConnect"` \| `"afterConnect"` \| `"beforeDisconnect"` \| `"afterDisconnect"` \| `"beforePoolAcquire"` \| `"afterPoolAcquire"` \| `"beforeQuery"` \| `"afterQuery"` \| `"beforeSync"` \| `"afterSync"` \| `"beforeBulkSync"` \| `"afterBulkSync"` \| `"beforeDefine"` \| `"afterDefine"` \| `"beforeInit"` \| `"afterInit"` \| `"beforeAssociate"` \| `"afterAssociate"` Hook type. ##### Returns `boolean` True when at least one hook exists, `false` after all were removed and `undefined` (typed `boolean`, like Sequelize v6) for a type that never had a hook. ##### Example ```ts const registered = User.hasHook('beforeCreate'); ``` *** #### hasHooks() > `static` **hasHooks**(`type`): `boolean` Alias of [Model.hasHook](#hashook). ##### Parameters ###### type `"beforeValidate"` \| `"afterValidate"` \| `"validationFailed"` \| `"beforeCreate"` \| `"afterCreate"` \| `"beforeUpdate"` \| `"afterUpdate"` \| `"beforeSave"` \| `"afterSave"` \| `"beforeDestroy"` \| `"afterDestroy"` \| `"beforeRestore"` \| `"afterRestore"` \| `"beforeUpsert"` \| `"afterUpsert"` \| `"beforeBulkCreate"` \| `"afterBulkCreate"` \| `"beforeBulkUpdate"` \| `"afterBulkUpdate"` \| `"beforeBulkDestroy"` \| `"afterBulkDestroy"` \| `"beforeBulkRestore"` \| `"afterBulkRestore"` \| `"beforeFind"` \| `"beforeFindAfterExpandIncludeAll"` \| `"beforeFindAfterOptions"` \| `"afterFind"` \| `"beforeCount"` \| `"beforeConnect"` \| `"afterConnect"` \| `"beforeDisconnect"` \| `"afterDisconnect"` \| `"beforePoolAcquire"` \| `"afterPoolAcquire"` \| `"beforeQuery"` \| `"afterQuery"` \| `"beforeSync"` \| `"afterSync"` \| `"beforeBulkSync"` \| `"afterBulkSync"` \| `"beforeDefine"` \| `"afterDefine"` \| `"beforeInit"` \| `"afterInit"` \| `"beforeAssociate"` \| `"afterAssociate"` Hook type. ##### Returns `boolean` Same as [Model.hasHook](#hashook). ##### Example ```ts const registered = User.hasHooks('afterFind'); ``` *** #### hasMany() > `static` **hasMany**\<`M`, `T`\>(`this`, `target`, `options?`): `HasMany`\<`M`, `T`\> Declares that each row of this model has many related target rows; the foreign key column lives on the target's table. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ###### T `T` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The source model class. ###### target [`ModelStatic`](../type-aliases/ModelStatic.md)\<`T`\> Associated model. ###### options? `Readonly`\<\{ `as?`: `string` \| `Readonly`\<\{ `plural`: `string`; `singular`: `string`; \}\>; `constraints?`: `boolean`; `foreignKey?`: `string` \| `Readonly`\<\{ `allowNull?`: `boolean`; `field?`: `string`; `name?`: `string`; \}\>; `hooks?`: `boolean`; `onDelete?`: `string`; `onUpdate?`: `string`; `scope?`: `Readonly`\<`Record`\<`string`, `unknown`\>\>; `sourceKey?`: `string`; `targetKey?`: `string`; \}\> Association options. ##### Returns `HasMany`\<`M`, `T`\> The association. ##### Example ```ts User.hasMany(Post, { foreignKey: 'authorId', as: 'posts' }); ``` *** #### hasOne() > `static` **hasOne**\<`M`, `T`\>(`this`, `target`, `options?`): `HasOne`\<`M`, `T`\> Declares that each row of this model has at most one related target row; the foreign key column lives on the target's table. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ###### T `T` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The source model class. ###### target [`ModelStatic`](../type-aliases/ModelStatic.md)\<`T`\> Associated model. ###### options? `Readonly`\<\{ `as?`: `string` \| `Readonly`\<\{ `plural`: `string`; `singular`: `string`; \}\>; `constraints?`: `boolean`; `foreignKey?`: `string` \| `Readonly`\<\{ `allowNull?`: `boolean`; `field?`: `string`; `name?`: `string`; \}\>; `hooks?`: `boolean`; `onDelete?`: `string`; `onUpdate?`: `string`; `scope?`: `Readonly`\<`Record`\<`string`, `unknown`\>\>; `sourceKey?`: `string`; `targetKey?`: `string`; \}\> Association options. ##### Returns `HasOne`\<`M`, `T`\> The association. ##### Example ```ts User.hasOne(Profile, { foreignKey: 'userId' }); ``` *** #### increment() > `static` **increment**\<`M`\>(`this`, `fields`, `options?`): `Promise`\<\[`affectedRows`: `M`[], `affectedCount`: `number`\]\> Atomically increments numeric attributes of the rows matching `where` (`SET x = x + by`). ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### fields [`AttributeAmounts`](../type-aliases/AttributeAmounts.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> Attribute name(s), or a map of attribute to amount. ###### options? [`IncrementOptions`](../type-aliases/IncrementOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> = `{}` Increment options (`where`, `by` default 1, `silent`, query options). ##### Returns `Promise`\<\[`affectedRows`: `M`[], `affectedCount`: `number`\]\> `[affectedRows, affectedCount]`: the updated instances and their number. ##### Example ```ts await Post.increment('views', { by: 1, where: { id: 5 } }); ``` ##### Inherited from `ModelInstancePersistence.increment` *** #### init() > `static` **init**\<`MS`, `M`\>(`this`, `attributes`, `options`): `MS` Defines attributes and options of the model and registers it in `sequelize.models`. Does not touch the database; call [Model.sync](#sync) or run migrations to create the table. ##### Type Parameters ###### MS `MS` *extends* [`ModelStatic`](../type-aliases/ModelStatic.md)\<[`AnyModel`](../type-aliases/AnyModel.md)\> ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) = `InstanceType`\<`MS`\> ##### Parameters ###### this `MS` The model class being initialized. ###### attributes [`ModelAttributes`](../type-aliases/ModelAttributes.md)\<`M`\> Attribute definitions. ###### options [`InitOptions`](../type-aliases/InitOptions.md) Model options, including the `sequelize` instance. ##### Returns `MS` The model class. ##### Example ```ts class Project extends Model {} Project.init( { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, name: DataTypes.STRING }, { sequelize, modelName: 'Project', paranoid: true }, ); ``` *** #### insert() > `static` **insert**\<`M`\>(`this`, `values`, `options?`): `Promise`\<`M`[]\> Inserts rows with `INSERT ... ON CONFLICT` and returns the inserted or updated rows. Unlike `bulkCreate`, rows skipped by `DO NOTHING` or by the `DO UPDATE ... WHERE` condition are not returned. Each instance has `wasInserted`. PostgreSQL extension. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### values [`CreationAttributes`](../type-aliases/CreationAttributes.md)\<`M`\> \| readonly [`CreationAttributes`](../type-aliases/CreationAttributes.md)\<`M`\>[] Attribute values of one row or several rows. ###### options? [`InsertOptions`](../type-aliases/InsertOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> = `{}` Insert options (`onConflict`, `fields`, `hooks`, `validate`, `overriding`, `returningOld`, query options). ##### Returns `Promise`\<`M`[]\> Instances of the rows written by the statement. ##### See - [Model.bulkCreate](#bulkcreate) for the Sequelize v6 variant. - [Bulk writes guide](/guide/bulk-writes) ##### Example ```ts const items = [{ sku: 'a-1', qty: 5 }]; const rows = await Product.insert(items, { onConflict: { target: ['sku'], action: { update: { qty: literal('"Product"."qty" + EXCLUDED."qty"') } } }, }); const inserted = rows.filter((row) => row.wasInserted); ``` *** #### insertFrom() > `static` **insertFrom**\<`M`\>(`this`, `source`, `options`): `Promise`\<`M`[]\> `INSERT INTO ... SELECT`: inserts the rows produced by a subquery. Returns the inserted (or, with `onConflict`, updated) rows with `wasInserted`. PostgreSQL extension. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The target model class. ###### source [`Subquery`](../interfaces/Subquery.md) Subquery from `Model.subquery()`; its columns must match `options.columns`. ###### options [`InsertFromOptions`](../type-aliases/InsertFromOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> Target columns, `onConflict` and query options. ##### Returns `Promise`\<`M`[]\> Written rows. ##### Example ```ts await Task.insertFrom( Post.subquery({ attributes: ['id', 'title'], where: { published: false } }), { columns: ['postId', 'title'] }, ); ``` *** #### insertStatement() > `static` **insertStatement**\<`M`\>(`this`, `rows`, `options?`): [`WriteStatement`](../interfaces/WriteStatement.md) Builds an `INSERT` of attribute-keyed rows for a data-modifying CTE (`with`). Defaults and timestamps are filled in; no hooks or validation run. PostgreSQL extension. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### rows readonly [`CreationAttributes`](../type-aliases/CreationAttributes.md)\<`M`\>[] Rows to insert (at least one). ###### options? `Pick`\<[`WriteStatementOptions`](../type-aliases/WriteStatementOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\>, `"returning"`\> = `{}` `returning`. ##### Returns [`WriteStatement`](../interfaces/WriteStatement.md) Statement for the `with` option. ##### Throws Error without rows. ##### Example ```ts const added = Task.insertStatement([{ title: 'write docs' }], { returning: true }); const rows = await Task.findAll({ with: { added }, source: 'added' }); ``` *** #### max() > `static` **max**\<`T`, `M`\>(`this`, `field`, `options?`): `Promise`\<`T`\> Finds the largest value of an attribute with `max()`. ##### Type Parameters ###### T `T` = `unknown` ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) = [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### field keyof [`Attributes`](../type-aliases/Attributes.md)\<`M`\> Attribute name. ###### options? [`AggregateOptions`](../type-aliases/AggregateOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> Options, see [Model.aggregate](#aggregate). ##### Returns `Promise`\<`T`\> Maximum or `null` when there are no rows. ##### Example ```ts const highest = await Product.max('price'); ``` *** #### merge() > `static` **merge**\<`M`\>(`this`, `options`): `Promise`\<`Readonly`\<\{ `rowCount`: `number`; `rows`: readonly `Readonly`\<\{ `action`: [`MergeActionName`](../type-aliases/MergeActionName.md); `instance`: `M`; \}\>[]; \}\>\> `MERGE INTO ... USING ...` (PostgreSQL 15+). With `returning: true` (PostgreSQL 17+) returns the written rows with the action taken. PostgreSQL extension. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### options [`MergeOptions`](../interfaces/MergeOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) & `Readonly`\<\{ `returning?`: `boolean`; `returningOld?`: `boolean`; \}\> Source, join condition and WHEN clauses. ##### Returns `Promise`\<`Readonly`\<\{ `rowCount`: `number`; `rows`: readonly `Readonly`\<\{ `action`: [`MergeActionName`](../type-aliases/MergeActionName.md); `instance`: `M`; \}\>[]; \}\>\> Affected row count and, with `returning`, `{ action, instance }` per row. ##### Throws DatabaseError when the server rejects the statement (for example on PostgreSQL older than 15). ##### Example ```ts await Product.merge({ source: [{ sku: 'a', qty: 5 }], on: { sku: col('source.sku') }, whenMatched: { update: { qty: literal('"Product"."qty" + "source"."qty"') } }, whenNotMatched: { insert: true }, }); ``` *** #### min() > `static` **min**\<`T`, `M`\>(`this`, `field`, `options?`): `Promise`\<`T`\> Finds the smallest value of an attribute with `min()`. ##### Type Parameters ###### T `T` = `unknown` ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) = [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### field keyof [`Attributes`](../type-aliases/Attributes.md)\<`M`\> Attribute name. ###### options? [`AggregateOptions`](../type-aliases/AggregateOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> Options, see [Model.aggregate](#aggregate). ##### Returns `Promise`\<`T`\> Minimum or `null` when there are no rows. ##### Example ```ts const lowest = await Product.min('price', { where: { active: true } }); ``` *** #### refreshAttributes() > `static` **refreshAttributes**(): `void` Rebuilds the normalized attribute definitions from the model's `init` input. ##### Returns `void` ##### Example ```ts User.refreshAttributes(); ``` *** #### removeAttribute() > `static` **removeAttribute**(`attribute`): `void` Removes an attribute from the model definition, e.g. a column added by an association. ##### Parameters ###### attribute `string` Attribute name. ##### Returns `void` ##### Example ```ts User.removeAttribute('legacyFlag'); ``` *** #### removeHook() > `static` **removeHook**\<`MS`\>(`this`, `type`, `nameOrFn?`): `MS` Removes hooks of a type from this model: one by name or function, or all of them. ##### Type Parameters ###### MS `MS` *extends* [`ModelStatic`](../type-aliases/ModelStatic.md)\<[`AnyModel`](../type-aliases/AnyModel.md)\> ##### Parameters ###### this `MS` The model class. ###### type `"beforeValidate"` \| `"afterValidate"` \| `"validationFailed"` \| `"beforeCreate"` \| `"afterCreate"` \| `"beforeUpdate"` \| `"afterUpdate"` \| `"beforeSave"` \| `"afterSave"` \| `"beforeDestroy"` \| `"afterDestroy"` \| `"beforeRestore"` \| `"afterRestore"` \| `"beforeUpsert"` \| `"afterUpsert"` \| `"beforeBulkCreate"` \| `"afterBulkCreate"` \| `"beforeBulkUpdate"` \| `"afterBulkUpdate"` \| `"beforeBulkDestroy"` \| `"afterBulkDestroy"` \| `"beforeBulkRestore"` \| `"afterBulkRestore"` \| `"beforeFind"` \| `"beforeFindAfterExpandIncludeAll"` \| `"beforeFindAfterOptions"` \| `"afterFind"` \| `"beforeCount"` \| `"beforeConnect"` \| `"afterConnect"` \| `"beforeDisconnect"` \| `"afterDisconnect"` \| `"beforePoolAcquire"` \| `"afterPoolAcquire"` \| `"beforeQuery"` \| `"afterQuery"` \| `"beforeSync"` \| `"afterSync"` \| `"beforeBulkSync"` \| `"afterBulkSync"` \| `"beforeDefine"` \| `"afterDefine"` \| `"beforeInit"` \| `"afterInit"` \| `"beforeAssociate"` \| `"afterAssociate"` Hook type. ###### nameOrFn? `string` \| [`HookFunction`](../type-aliases/HookFunction.md) Hook name or function; all hooks of the type when omitted. ##### Returns `MS` The model class. ##### Example ```ts User.removeHook('beforeCreate', 'normalizeEmail'); ``` *** #### restore() > `static` **restore**\<`M`\>(`this`, `options?`): `Promise`\<`void`\> Restores soft-deleted rows of a paranoid model by setting `deletedAt` back to `NULL`. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### options? [`RestoreOptions`](../type-aliases/RestoreOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> = `{}` Rows to restore and hook options. ##### Returns `Promise`\<`void`\> Resolves when done. ##### Throws Error when the model is not paranoid. ##### Example ```ts await Post.restore({ where: { userId: 1 } }); ``` ##### Inherited from `ModelInstancePersistence.restore` *** #### runHooks() > `static` **runHooks**(`type`, ...`args`): `Promise`\<`void`\> Runs the hooks of a type with the given arguments (model hooks, then Sequelize-level hooks). ##### Parameters ###### type `"beforeValidate"` \| `"afterValidate"` \| `"validationFailed"` \| `"beforeCreate"` \| `"afterCreate"` \| `"beforeUpdate"` \| `"afterUpdate"` \| `"beforeSave"` \| `"afterSave"` \| `"beforeDestroy"` \| `"afterDestroy"` \| `"beforeRestore"` \| `"afterRestore"` \| `"beforeUpsert"` \| `"afterUpsert"` \| `"beforeBulkCreate"` \| `"afterBulkCreate"` \| `"beforeBulkUpdate"` \| `"afterBulkUpdate"` \| `"beforeBulkDestroy"` \| `"afterBulkDestroy"` \| `"beforeBulkRestore"` \| `"afterBulkRestore"` \| `"beforeFind"` \| `"beforeFindAfterExpandIncludeAll"` \| `"beforeFindAfterOptions"` \| `"afterFind"` \| `"beforeCount"` \| `"beforeConnect"` \| `"afterConnect"` \| `"beforeDisconnect"` \| `"afterDisconnect"` \| `"beforePoolAcquire"` \| `"afterPoolAcquire"` \| `"beforeQuery"` \| `"afterQuery"` \| `"beforeSync"` \| `"afterSync"` \| `"beforeBulkSync"` \| `"afterBulkSync"` \| `"beforeDefine"` \| `"afterDefine"` \| `"beforeInit"` \| `"afterInit"` \| `"beforeAssociate"` \| `"afterAssociate"` Hook type. ###### args ...readonly `unknown`[] Hook arguments. ##### Returns `Promise`\<`void`\> Resolves when all hooks finished. ##### Example ```ts await User.runHooks('beforeCreate', user, {}); ``` *** #### schema() > `static` **schema**\<`MS`\>(`this`, `schema`, `options?`): `MS` Returns a model class whose queries target a PostgreSQL schema, like Sequelize v6. The copy has the attributes, hooks, scopes and associations of this model as they are at the time of the call and keeps the scope selection of this class. Changes made to the original afterwards are not seen by the copy. ##### Type Parameters ###### MS `MS` *extends* [`ModelStatic`](../type-aliases/ModelStatic.md)\<[`AnyModel`](../type-aliases/AnyModel.md)\> ##### Parameters ###### this `MS` The model class being bound. ###### schema `string` Schema name. ###### options? `string` \| `Readonly`\<\{ `schemaDelimiter?`: `string`; \}\> Separator between schema and table reported by `getTableName` (a string, or `{ schemaDelimiter }`); PostgreSQL always qualifies with `.` in SQL. Defaults to `.`. ##### Returns `MS` Schema-bound model class (instances are instances of this model). ##### Example ```ts const TenantUser = User.schema('tenant_a'); await TenantUser.findAll(); // SELECT ... FROM "tenant_a"."users" TenantUser.getTableName(); // { tableName: 'users', schema: 'tenant_a', delimiter: '.' } ``` *** #### scope() > `static` **scope**\<`MS`\>(`this`, ...`selectors`): `MS` Creates a model class that applies the given scopes to its queries instead of the default scope. The original class is not changed. ##### Type Parameters ###### MS `MS` *extends* [`ModelStatic`](../type-aliases/ModelStatic.md)\<[`AnyModel`](../type-aliases/AnyModel.md)\> ##### Parameters ###### this `MS` The model class. ###### selectors ...readonly ([`ScopeSelector`](../type-aliases/ScopeSelector.md) \| readonly [`ScopeSelector`](../type-aliases/ScopeSelector.md)[])[] Scope names, `{ method: [name, ...args] }`, inline options, `'defaultScope'`, or `null`. ##### Returns `MS` Scoped model class (instances are instances of this model). ##### Throws Error when a named scope does not exist. ##### Example ```ts await User.scope('active', { method: ['olderThan', 18] }).findAll(); ``` ##### See [Querying guide](/guide/querying) *** #### subquery() > `static` **subquery**\<`M`\>(`this`, `options?`): [`Subquery`](../interfaces/Subquery.md) Builds a SELECT that can be embedded in another query: in `where` (`[Op.in]`, `=`, `exists()`), in `attributes` (scalar subquery) and as a source of `insertFrom` / `merge`. Default scope and paranoid filter apply; values stay bound parameters of the outer statement. PostgreSQL extension. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class the subquery selects from. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) & `Omit`\<[`SelectOptions`](../type-aliases/SelectOptions.md), `"where"`\> & `object` & `Readonly`\<\{ `from?`: `Readonly`\<`Record`\<`string`, [`FromSourceOption`](../type-aliases/FromSourceOption.md)\>\>; `source?`: `string` \| [`Subquery`](../interfaces/Subquery.md); `with?`: `Readonly`\<`Record`\<`string`, [`Subquery`](../interfaces/Subquery.md) \| [`WriteStatement`](../interfaces/WriteStatement.md) \| `Readonly`\<\{ `cycle?`: `Readonly`\<...\>; `materialized?`: `boolean`; `query`: [`Subquery`](../interfaces/Subquery.md) \| [`WriteStatement`](../interfaces/WriteStatement.md); `recursive?`: [`Subquery`](../interfaces/Subquery.md); `search?`: `Readonly`\<...\>; `unionAll?`: `boolean`; \}\>\>\>; \}\> & `Readonly`\<\{ `as?`: `string`; \}\> = `{}` Find options (`attributes`, `where`, `order`, `limit`, `include`, ...) and `as` (table alias). ##### Returns [`Subquery`](../interfaces/Subquery.md) Subquery expression. ##### Example ```ts await User.findAll({ where: { id: { [Op.in]: Post.subquery({ attributes: ['userId'], where: { published: true } }) } } }); ``` *** #### sum() > `static` **sum**\<`M`\>(`this`, `field`, `options?`): `Promise`\<`number`\> Adds up the values of an attribute with `sum()`. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### field keyof [`Attributes`](../type-aliases/Attributes.md)\<`M`\> Attribute name. ###### options? [`AggregateOptions`](../type-aliases/AggregateOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> Options, see [Model.aggregate](#aggregate). ##### Returns `Promise`\<`number`\> Sum, or `null` when there are no rows (as returned by PostgreSQL). ##### Example ```ts const total = await Invoice.sum('amount', { where: { paid: true } }); ``` *** #### sync() > `static` **sync**\<`MS`\>(`this`, `options?`): `Promise`\<`MS`\> Creates the table of this model and its indexes when missing. `force: true` drops it first (with `CASCADE`); `alter` changes an existing table to match the model. ##### Type Parameters ###### MS `MS` *extends* [`ModelStatic`](../type-aliases/ModelStatic.md)\<[`AnyModel`](../type-aliases/AnyModel.md)\> ##### Parameters ###### this `MS` The model class. ###### options? [`SyncOptions`](../type-aliases/SyncOptions.md) = `{}` `force`, `alter`, `match`, `schema` and query options. ##### Returns `Promise`\<`MS`\> The model class. ##### Example ```ts await User.sync({ alter: true }); ``` ##### See [Schema guide](/guide/schema) *** #### truncate() > `static` **truncate**(`options?`): `Promise`\<`void`\> Removes all rows with `TRUNCATE`, without running hooks. ##### Parameters ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) & `Readonly`\<\{ `cascade?`: `boolean`; `restartIdentity?`: `boolean`; \}\> = `{}` `cascade`, `restartIdentity` and query options. ##### Returns `Promise`\<`void`\> Resolves when done. ##### Example ```ts await Task.truncate({ restartIdentity: true, cascade: true }); ``` *** #### unscoped() > `static` **unscoped**\<`MS`\>(`this`): `MS` Creates a model class that applies no scope at all, not even the default scope. ##### Type Parameters ###### MS `MS` *extends* [`ModelStatic`](../type-aliases/ModelStatic.md)\<[`AnyModel`](../type-aliases/AnyModel.md)\> ##### Parameters ###### this `MS` The model class. ##### Returns `MS` Unscoped model class. ##### Example ```ts const everyone = await User.unscoped().findAll(); ``` *** #### update() ##### Call Signature > `static` **update**\<`M`\>(`this`, `values`, `options`): `Promise`\<\[`affectedCount`: `number`, `affectedRows`: `M`[]\]\> Updates all rows matching `where` with one `UPDATE` and refreshes `updatedAt` unless `silent`. Values are validated unless `validate: false`; bulk hooks run unless `hooks: false`. With `returning: true` the updated instances are returned as the second element. ###### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ###### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### values `UpdateValues`\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> New attribute values. ###### options `Omit`\<[`UpdateOptions`](../type-aliases/UpdateOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\>, `"returning"`\> & `object` Update options with `returning: true`; `where` is required. ###### Returns `Promise`\<\[`affectedCount`: `number`, `affectedRows`: `M`[]\]\> `[affectedCount, affectedRows]`. ###### Throws ValidationError when the new values are invalid. ###### Example ```ts const [count, rows] = await Post.update({ published: true }, { where: { userId: 1 }, returning: true }); ``` ###### Inherited from `ModelInstancePersistence.update` ##### Call Signature > `static` **update**\<`M`\>(`this`, `values`, `options`): `Promise`\<\[`affectedCount`: `number`\]\> Updates all rows matching `where` with one `UPDATE` and refreshes `updatedAt` unless `silent`. Values are validated unless `validate: false`; bulk hooks run unless `hooks: false`. ###### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ###### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### values `UpdateValues`\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> New attribute values. ###### options [`UpdateOptions`](../type-aliases/UpdateOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> Update options; `where` is required. ###### Returns `Promise`\<\[`affectedCount`: `number`\]\> `[affectedCount]`. ###### Throws ValidationError when the new values are invalid. ###### Example ```ts const [count] = await Post.update({ published: true }, { where: { userId: 1 } }); ``` ###### Inherited from `ModelInstancePersistence.update` *** #### updateStatement() > `static` **updateStatement**\<`M`\>(`this`, `values`, `options?`): [`WriteStatement`](../interfaces/WriteStatement.md) Builds an `UPDATE` for a data-modifying CTE (`with`); nothing runs until the outer query does. No hooks or validation run; `updatedAt` is set unless `silent`. With `returning: true` the CTE can be read through `source`. Queries with such a CTE always use the writer. PostgreSQL extension. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### values `UpdateValues`\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> New attribute values. ###### options? [`UpdateStatementOptions`](../type-aliases/UpdateStatementOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> = `{}` `where`, `returning`, `silent`. ##### Returns [`WriteStatement`](../interfaces/WriteStatement.md) Statement for the `with` option. ##### Example ```ts const bumped = Task.updateStatement({ done: true }, { where: { id: 1 }, returning: true }); const rows = await Task.findAll({ with: { bumped }, source: 'bumped' }); ``` *** #### upsert() > `static` **upsert**\<`M`\>(`this`, `values`, `options?`): `Promise`\<\[`M`, `boolean` \| `null`\]\> Inserts a row, or updates it when it conflicts with a unique key (`INSERT ... ON CONFLICT DO UPDATE`, Sequelize v6 `upsert`). Runs the `beforeUpsert` and `afterUpsert` hooks. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) ##### Parameters ###### this [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ###### values [`CreationAttributes`](../type-aliases/CreationAttributes.md)\<`M`\> Attribute values. ###### options? [`UpsertOptions`](../type-aliases/UpsertOptions.md)\<[`Attributes`](../type-aliases/Attributes.md)\<`M`\>\> = `{}` Upsert options (`conflictFields`, `fields`, `onConflict`, query options). ##### Returns `Promise`\<\[`M`, `boolean` \| `null`\]\> `[instance, null]` like Sequelize v6, or `[instance, created]` with `onConflict`. ##### Throws ValidationError when validation fails. ##### Throws UniqueConstraintError when a unique constraint other than the conflict target is violated. ##### Example ```ts const [user] = await User.upsert({ email: 'ada@example.com', name: 'Ada' }, { conflictFields: ['email'] }); ``` ## Class: OptimisticLockError Thrown when saving an instance of a model with `version: true` updates no row because another writer changed it first (optimistic locking). The failed update is not retried; reload the instance and apply the change again. ### Example ```ts const user = await User.findByPk(1); try { await user!.update({ name: 'New name' }); } catch (e) { if (e instanceof OptimisticLockError) { console.error(e.modelName, e.where); } } ``` ### Extends - [`Error`](Error.md) ### Constructors #### Constructor > **new OptimisticLockError**(`options?`): `OptimisticLockError` Builds the error; the message defaults to `Attempting to update a stale model instance: `. ##### Parameters ###### options? `Readonly`\<\{ `message?`: `string`; `modelName?`: `string`; `values?`: `unknown`; `where?`: `unknown`; \}\> = `{}` Model name, values and where of the failed update. ##### Returns `OptimisticLockError` ##### Overrides [`Error`](Error.md).[`constructor`](Error.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`Error`](Error.md).[`cause`](Error.md#cause) *** #### message > **message**: `string` ##### Inherited from [`Error`](Error.md).[`message`](Error.md#message) *** #### modelName > `readonly` **modelName**: `string` \| `undefined` Name of the model whose row was stale; `undefined` when not given. *** #### name > **name**: `string` ##### Inherited from [`Error`](Error.md).[`name`](Error.md#name) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`Error`](Error.md).[`stack`](Error.md#stack) *** #### values > `readonly` **values**: `unknown` Expected version values. *** #### where > `readonly` **where**: `unknown` Primary key values of the row. *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`Error`](Error.md).[`stackTraceLimit`](Error.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`Error`](Error.md).[`captureStackTrace`](Error.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`Error`](Error.md).[`prepareStackTrace`](Error.md#preparestacktrace) ## Class: QueryError Base class of query construction errors (Sequelize v6 `QueryError`); postgrelize does not throw it itself. ### Example ```ts try { await User.findAll(); } catch (e) { if (e instanceof QueryError) { console.error(e.message); } } ``` ### Extends - [`Error`](Error.md) ### Constructors #### Constructor > **new QueryError**(`message?`): `QueryError` Creates the error and sets `name` to `'SequelizeQueryError'`. ##### Parameters ###### message? `string` Error message. ##### Returns `QueryError` ##### Overrides [`Error`](Error.md).[`constructor`](Error.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`Error`](Error.md).[`cause`](Error.md#cause) *** #### message > **message**: `string` ##### Inherited from [`Error`](Error.md).[`message`](Error.md#message) *** #### name > **name**: `string` ##### Inherited from [`Error`](Error.md).[`name`](Error.md#name) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`Error`](Error.md).[`stack`](Error.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`Error`](Error.md).[`stackTraceLimit`](Error.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`Error`](Error.md).[`captureStackTrace`](Error.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`Error`](Error.md).[`prepareStackTrace`](Error.md#preparestacktrace) ## Class: QueryInterface Schema manipulation API (Sequelize v6 `QueryInterface`) for PostgreSQL. Used by `sync()` and by migrations (`sequelize-cli`, umzug). Obtain the instance with [Sequelize.getQueryInterface](Sequelize.md#getqueryinterface). Table names are `string` or `{ tableName, schema }`; identifiers are always quoted and values bound or escaped, never concatenated raw. ### Example ```ts const queryInterface = sequelize.getQueryInterface(); await queryInterface.createTable('users', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, name: { type: DataTypes.STRING, allowNull: false }, }); await queryInterface.addIndex('users', ['name'], { unique: true }); ``` ### See [Schema guide](/guide/schema) ### Extends - `QueryInterfaceCatalog` ### Constructors #### Constructor > **new QueryInterface**(`sequelize`): `QueryInterface` Creates the schema API bound to a `Sequelize` instance; prefer [Sequelize.getQueryInterface](Sequelize.md#getqueryinterface). ##### Parameters ###### sequelize [`RuntimeOwner`](../interfaces/RuntimeOwner.md) Owning `Sequelize` instance. ##### Returns `QueryInterface` ##### Example ```ts const api = new QueryInterface(sequelize); await api.showAllTables(); ``` ##### Overrides `QueryInterfaceCatalog.constructor` ### Properties #### queryGenerator > `readonly` **queryGenerator**: `QueryGenerator` Sequelize v6 `queryGenerator` property; only `selectQuery` is provided. *** #### sequelize > `readonly` **sequelize**: [`RuntimeOwner`](../interfaces/RuntimeOwner.md) Owning `Sequelize` instance. ##### Inherited from `QueryInterfaceCatalog.sequelize` ### Methods #### addColumn() > **addColumn**(`table`, `column`, `attribute`, `options?`): `Promise`\<`void`\> Adds a column with `ALTER TABLE ... ADD COLUMN`; a plain data type or a full attribute definition (nullability, default, references, ...) is accepted. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### column `string` Column name. ###### attribute [`DataTypeInput`](../type-aliases/DataTypeInput.md) \| `Readonly`\<\{ `allowNull?`: `boolean`; `autoIncrement?`: `boolean`; `comment?`: `string`; `defaultValue?`: `unknown`; `field?`: `string`; `generated?`: `Readonly`\<\{ `as`: `unknown`; `stored?`: `boolean`; \}\>; `identity?`: `"always"` \| `"byDefault"`; `onDelete?`: `string`; `onUpdate?`: `string`; `primaryKey?`: `boolean`; `references?`: `string` \| `Readonly`\<\{ `deferrable?`: `Readonly`\<\{ `sql`: `string`; \}\>; `key?`: `string`; `model`: `string` \| `Readonly`\<\{ `schema?`: `string`; `tableName`: `string`; \}\> \| `Readonly`\<\{ `getTableName`(): `string` \| `Readonly`\<...\>; \}\>; \}\>; `type`: [`DataTypeInput`](../type-aliases/DataTypeInput.md); `unique?`: `string` \| `boolean` \| `Readonly`\<\{ `msg?`: `string`; `name?`: `string`; `nullsNotDistinct?`: `boolean`; \}\>; `validate?`: `Readonly`\<`Record`\<`string`, `unknown`\> & `object`\>; `values?`: readonly `string`[]; `get?`(`this`): `unknown`; `set?`(`this`, `value`): `void`; \}\> Column definition. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.addColumn('users', 'nickname', { type: DataTypes.STRING, allowNull: true }); ``` *** #### addConstraint() > **addConstraint**(`table`, `options`): `Promise`\<`void`\> Adds a `CHECK`, `UNIQUE`, `PRIMARY KEY`, `FOREIGN KEY` or `EXCLUDE` constraint to a table. `notValid: true` skips checking existing rows (check and foreign key); validate later with [QueryInterface.validateConstraint](#validateconstraint). ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### options `Readonly`\<\{ `deferrable?`: `Readonly`\<\{ `sql`: `string`; \}\>; `enforced?`: `boolean`; `exclude?`: readonly [`ExcludeElement`](../type-aliases/ExcludeElement.md)[]; `fields?`: readonly `string`[]; `include?`: readonly `string`[]; `name?`: `string`; `notValid?`: `boolean`; `nullsNotDistinct?`: `boolean`; `onDelete?`: `string`; `onUpdate?`: `string`; `period?`: `boolean`; `references?`: `Readonly`\<\{ `field`: `string`; `fields?`: readonly `string`[]; `table`: [`TableName`](../type-aliases/TableName.md); \}\>; `type`: `"unique"` \| `"check"` \| `"primary key"` \| `"foreign key"` \| `"exclude"` \| `"CHECK"` \| `"UNIQUE"` \| `"PRIMARY KEY"` \| `"FOREIGN KEY"` \| `"EXCLUDE"`; `using?`: `string`; `where?`: `unknown`; `withoutOverlaps?`: `boolean`; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Constraint definition. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.addConstraint('products', { type: 'check', fields: ['price'], name: 'products_price_positive', where: { price: { [Op.gt]: 0 } }, }); await queryInterface.addConstraint('bookings', { type: 'exclude', name: 'bookings_no_overlap', using: 'gist', exclude: [ { name: 'room', with: '=' }, { expression: 'tstzrange(starts, ends)', with: '&&' }, ], }); ``` *** #### addIndex() > **addIndex**(`table`, `fieldsOrOptions`, `options?`): `Promise`\<`void`\> Creates an index on a table, optionally unique, partial, covering or `CONCURRENTLY`. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### fieldsOrOptions readonly [`IndexField`](../type-aliases/IndexField.md)[] \| `Readonly`\<\{ `concurrently?`: `boolean`; `fields?`: readonly [`IndexField`](../type-aliases/IndexField.md)[]; `ifNotExists?`: `boolean`; `include?`: readonly `string`[]; `name?`: `string`; `nullsNotDistinct?`: `boolean`; `operator?`: `string`; `unique?`: `boolean`; `using?`: `string`; `where?`: `unknown`; \}\> Indexed fields or index options. ###### options? `Readonly`\<\{ `concurrently?`: `boolean`; `fields?`: readonly [`IndexField`](../type-aliases/IndexField.md)[]; `ifNotExists?`: `boolean`; `include?`: readonly `string`[]; `name?`: `string`; `nullsNotDistinct?`: `boolean`; `operator?`: `string`; `unique?`: `boolean`; `using?`: `string`; `where?`: `unknown`; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Index options when fields are given separately. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.addIndex('users', ['email'], { unique: true, name: 'users_email_unique' }); await queryInterface.addIndex('users', { name: 'users_lower_email', fields: [{ expression: 'lower(email)', nulls: 'LAST' }], }); ``` *** #### alterPolicy() > **alterPolicy**(`table`, `name`, `options?`): `Promise`\<`void`\> Changes a policy with `ALTER POLICY`: roles, conditions and name (`rename`, applied last). ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### name `string` Current policy name. ###### options? `Readonly`\<`Pick`\<`Readonly`\<\{ `command?`: `"all"` \| `"update"` \| `"delete"` \| `"insert"` \| `"select"`; `kind?`: `"permissive"` \| `"restrictive"`; `roles?`: readonly `string`[]; `using?`: [`PolicyCondition`](../type-aliases/PolicyCondition.md); `withCheck?`: [`PolicyCondition`](../type-aliases/PolicyCondition.md); \}\>, `"using"` \| `"roles"` \| `"withCheck"`\> & `object`\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Changes (at least one) and query options. ##### Returns `Promise`\<`void`\> ##### Throws Error when no change is given. ##### Example ```ts await queryInterface.alterPolicy('documents', 'tenant_isolation', { roles: ['app_user', 'app_admin'] }); ``` ##### Inherited from `QueryInterfaceCatalog.alterPolicy` *** #### alterSequence() > **alterSequence**(`name`, `options?`): `Promise`\<`void`\> Changes a sequence with `ALTER SEQUENCE`. ##### Parameters ###### name [`TableName`](../type-aliases/TableName.md) Sequence name or `{ tableName, schema }`. ###### options? `Omit`\<`Readonly`\<\{ `cache?`: [`SequenceNumber`](../type-aliases/SequenceNumber.md); `cycle?`: `boolean`; `dataType?`: `"bigint"` \| `"integer"` \| `"smallint"`; `ifNotExists?`: `boolean`; `increment?`: [`SequenceNumber`](../type-aliases/SequenceNumber.md); `maxValue?`: `false` \| [`SequenceNumber`](../type-aliases/SequenceNumber.md); `minValue?`: `false` \| [`SequenceNumber`](../type-aliases/SequenceNumber.md); `ownedBy?`: `Readonly`\<\{ `column`: `string`; `table`: [`TableName`](../type-aliases/TableName.md); \}\> \| `null`; `start?`: [`SequenceNumber`](../type-aliases/SequenceNumber.md); \}\>, `"ifNotExists"` \| `"dataType"` \| `"start"`\> & `Readonly`\<\{ `ifExists?`: `boolean`; `restartWith?`: `true` \| [`SequenceNumber`](../type-aliases/SequenceNumber.md); \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Properties to change (at least one) and query options. ##### Returns `Promise`\<`void`\> ##### Throws Error when no property is given or a number is not whole. ##### Example ```ts await queryInterface.alterSequence('invoice_number', { restartWith: 5000, cycle: false }); ``` ##### Inherited from `QueryInterfaceCatalog.alterSequence` *** #### assertTableHasColumn() > **assertTableHasColumn**(`table`, `column`, `options?`): `Promise`\<`Record`\<`string`, `Readonly`\<\{ `allowNull`: `boolean`; `comment`: `string` \| `null`; `defaultValue`: `unknown`; `primaryKey`: `boolean`; `special`: readonly `string`[]; `type`: `string`; \}\>\>\> Describes a table and throws when it lacks a column. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### column `string` Column name. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`Record`\<`string`, `Readonly`\<\{ `allowNull`: `boolean`; `comment`: `string` \| `null`; `defaultValue`: `unknown`; `primaryKey`: `boolean`; `special`: readonly `string`[]; `type`: `string`; \}\>\>\> The table description (see [QueryInterface.describeTable](#describetable)). ##### Throws Error when the table has no such column. ##### Example ```ts const columns = await queryInterface.assertTableHasColumn('users', 'email'); ``` ##### Inherited from `QueryInterfaceCatalog.assertTableHasColumn` *** #### attachPartition() > **attachPartition**(`parent`, `partition`, `bound`, `options?`): `Promise`\<`void`\> Attaches an existing table as a partition (`ALTER TABLE ... ATTACH PARTITION`). PostgreSQL scans the table to check the bounds unless a matching `CHECK` constraint exists. ##### Parameters ###### parent [`TableName`](../type-aliases/TableName.md) Partitioned table name or `{ tableName, schema }`. ###### partition [`TableName`](../type-aliases/TableName.md) Existing table name or `{ tableName, schema }`. ###### bound [`PartitionBoundSpec`](../type-aliases/PartitionBoundSpec.md) Partition bounds, see [QueryInterface.createPartition](#createpartition). ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.attachPartition('events', 'events_2027', { from: ['2027-01-01'], to: ['2028-01-01'], }); ``` ##### Inherited from `QueryInterfaceCatalog.attachPartition` *** #### bulkDelete() > **bulkDelete**(`table`, `where?`, `options?`): `Promise`\<`number`\> Deletes every row matching a where object with one `DELETE`, without model hooks. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### where? `unknown` = `{}` Filter (where object keyed by column); empty deletes all rows. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`number`\> Number of deleted rows. ##### Example ```ts const removed = await queryInterface.bulkDelete('users', { active: false }); ``` *** #### bulkInsert() > **bulkInsert**(`table`, `records`, `options?`): `Promise`\<`number`\> Inserts several rows with one `INSERT` (used by seeders). Values are bound as parameters. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### records readonly `Readonly`\<`Record`\<`string`, `unknown`\>\>[] Rows keyed by column name. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`number`\> Number of inserted rows. ##### Example ```ts const inserted = await queryInterface.bulkInsert('users', [ { name: 'Ada', email: 'ada@example.com' }, { name: 'Alan', email: 'alan@example.com' }, ]); ``` *** #### bulkUpdate() > **bulkUpdate**(`table`, `values`, `where`, `options?`): `Promise`\<`number`\> Updates every row matching a where object with one `UPDATE`, without model hooks or validation. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### values `Readonly`\<`Record`\<`string`, `unknown`\>\> New column values. ###### where `unknown` Filter (where object keyed by column). ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`number`\> Number of updated rows. ##### Example ```ts const updated = await queryInterface.bulkUpdate('users', { active: false }, { name: 'Ada' }); ``` *** #### changeColumn() > **changeColumn**(`table`, `column`, `attribute`, `options?`): `Promise`\<`void`\> Alters the type, nullability, default and comment of an existing column in one go. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### column `string` Column name. ###### attribute [`DataTypeInput`](../type-aliases/DataTypeInput.md) \| `Readonly`\<\{ `allowNull?`: `boolean`; `autoIncrement?`: `boolean`; `comment?`: `string`; `defaultValue?`: `unknown`; `field?`: `string`; `generated?`: `Readonly`\<\{ `as`: `unknown`; `stored?`: `boolean`; \}\>; `identity?`: `"always"` \| `"byDefault"`; `onDelete?`: `string`; `onUpdate?`: `string`; `primaryKey?`: `boolean`; `references?`: `string` \| `Readonly`\<\{ `deferrable?`: `Readonly`\<\{ `sql`: `string`; \}\>; `key?`: `string`; `model`: `string` \| `Readonly`\<\{ `schema?`: `string`; `tableName`: `string`; \}\> \| `Readonly`\<\{ `getTableName`(): `string` \| `Readonly`\<...\>; \}\>; \}\>; `type`: [`DataTypeInput`](../type-aliases/DataTypeInput.md); `unique?`: `string` \| `boolean` \| `Readonly`\<\{ `msg?`: `string`; `name?`: `string`; `nullsNotDistinct?`: `boolean`; \}\>; `validate?`: `Readonly`\<`Record`\<`string`, `unknown`\> & `object`\>; `values?`: readonly `string`[]; `get?`(`this`): `unknown`; `set?`(`this`, `value`): `void`; \}\> New column definition. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.changeColumn('users', 'name', { type: DataTypes.STRING(100), allowNull: false }); ``` *** #### createDatabase() > **createDatabase**(`database`, `options?`): `Promise`\<`void`\> Runs `CREATE DATABASE`. Must run outside a transaction. ##### Parameters ###### database `string` Database name (quoted). ###### options? `CreateDatabaseOptions` = `{}` `encoding`, `collate`, `ctype`, `template` (escaped as literals) and query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.createDatabase('tenant_42', { encoding: 'UTF8', template: 'template0' }); ``` ##### Inherited from `QueryInterfaceCatalog.createDatabase` *** #### createExtension() > **createExtension**(`name`, `options?`): `Promise`\<`void`\> Installs an extension with `CREATE EXTENSION`. Needs the privileges PostgreSQL requires for that extension (superuser or a trusted extension). ##### Parameters ###### name `string` Extension name, quoted as an identifier. ###### options? `Readonly`\<\{ `cascade?`: `boolean`; `ifNotExists?`: `boolean`; `schema?`: `string`; `version?`: `string`; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `ifNotExists`, `schema`, `version`, `cascade` and query options. ##### Returns `Promise`\<`void`\> ##### Throws DatabaseError when the extension is not available on the server or the role may not install it. ##### Example ```ts await queryInterface.createExtension('pg_trgm', { ifNotExists: true }); ``` ##### See [Schema guide](/guide/schema) ##### Inherited from `QueryInterfaceCatalog.createExtension` *** #### createFunction() > **createFunction**(`name`, `params`, `returnType`, `language`, `body`, `optionsArray?`, `options?`): `Promise`\<`void`\> Creates a function with `CREATE [OR REPLACE] FUNCTION` (Sequelize v6 `createFunction`). The body is wrapped in `BEGIN ... END;` as in v6. The `body` is SQL text you provide: it is not escaped, so never build it from user input. Names, parameter names and the language are validated identifier words; types and characteristic keywords are checked against strict patterns and allowlists. A function name given as a string is unquoted (folds to lower case, like v6); use `{ name, schema }` for an exact quoted name. ##### Parameters ###### name [`FunctionName`](../type-aliases/FunctionName.md) Function name (`'touch'`, `'app.touch'` or `{ name, schema }`). ###### params readonly `Readonly`\<\{ `direction?`: `string`; `name?`: `string`; `type`: `string`; \}\>[] Parameters `{ type, name?, direction? }`; pass `[]` for none. ###### returnType `string` Return type, e.g. `'trigger'`, `'integer'`, `'SETOF text'`. ###### language `string` Language, e.g. `'plpgsql'`. ###### body `string` Trusted function body without `BEGIN` / `END`. ###### optionsArray? readonly `string`[] = `[]` Characteristic keywords such as `'IMMUTABLE'`, `'SECURITY DEFINER'`, `'COST 10'`. ###### options? `Readonly`\<\{ `force?`: `boolean`; `variables?`: readonly `Readonly`\<\{ `default?`: `unknown`; `name`: `string`; `type`: `string`; \}\>[]; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `variables`, `force` (`OR REPLACE`) and query options. ##### Returns `Promise`\<`void`\> ##### Throws Error when a part is missing or fails validation. ##### Throws DatabaseError when PostgreSQL rejects the function. ##### Example ```ts await queryInterface.createFunction( 'touch_updated_at', [], 'trigger', 'plpgsql', 'NEW."updatedAt" := now(); RETURN NEW;', ['VOLATILE'], { force: true }, ); ``` ##### See [Schema objects guide](/guide/schema-objects) ##### Inherited from `QueryInterfaceCatalog.createFunction` *** #### createMaterializedView() > **createMaterializedView**(`name`, `query`, `options?`): `Promise`\<`void`\> Creates a materialized view with `CREATE MATERIALIZED VIEW`. The `query` is trusted SQL text, as in [QueryInterface.createView](#createview). PostgreSQL has no `OR REPLACE` for materialized views: drop and create, or use `ifNotExists`. ##### Parameters ###### name [`TableName`](../type-aliases/TableName.md) View name or `{ tableName, schema }`. ###### query `string` Trusted `SELECT` text. ###### options? `Readonly`\<\{ `columns?`: readonly `string`[]; `ifNotExists?`: `boolean`; `using?`: `string`; `withData?`: `boolean`; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `ifNotExists`, `columns`, `using`, `withData` and query options. ##### Returns `Promise`\<`void`\> ##### Throws Error for an empty query or an invalid access method. ##### Example ```ts await queryInterface.createMaterializedView('post_stats', 'SELECT author_id, count(*) AS n FROM "Posts" GROUP BY author_id'); ``` ##### Inherited from `QueryInterfaceCatalog.createMaterializedView` *** #### createPartition() > **createPartition**(`parent`, `partition`, `bound`, `options?`): `Promise`\<`void`\> Creates a partition of a partitioned table (`CREATE TABLE ... PARTITION OF`). The partitioned parent comes from `createTable` with `partitionBy`. ##### Parameters ###### parent [`TableName`](../type-aliases/TableName.md) Partitioned table name or `{ tableName, schema }`. ###### partition [`TableName`](../type-aliases/TableName.md) New partition name or `{ tableName, schema }`. ###### bound [`PartitionBoundSpec`](../type-aliases/PartitionBoundSpec.md) `{ in }` (list), `{ from, to }` (range), `{ modulus, remainder }` (hash) or `{ default: true }`; values are rendered as literals. ###### options? `Readonly`\<\{ `ifNotExists?`: `boolean`; `partitionBy?`: `Readonly`\<\{ `columns`: readonly [`PartitionKeyElement`](../type-aliases/PartitionKeyElement.md)[]; `strategy`: [`PartitionStrategy`](../type-aliases/PartitionStrategy.md); \}\>; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `partitionBy` (sub-partitioning), `ifNotExists` and query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.createTable('events', { at: DataTypes.DATE }, { partitionBy: { strategy: 'range', columns: ['at'] }, }); await queryInterface.createPartition('events', 'events_2026', { from: ['2026-01-01'], to: ['2027-01-01'], }); ``` ##### See [Constraints and indexes guide](/guide/constraints-indexes) ##### Inherited from `QueryInterfaceCatalog.createPartition` *** #### createPolicy() > **createPolicy**(`table`, `name`, `options?`): `Promise`\<`void`\> Creates a row-level security policy with `CREATE POLICY`. `using` and `withCheck` are SQL text you provide (not escaped, never build them from user input) or a where object, whose values are rendered as escaped literals. Session variables set with the `settings` transaction option work in conditions: `"tenant_id = current_setting('app.tenant_id')::int"`. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### name `string` Policy name. ###### options? `Readonly`\<\{ `command?`: `"all"` \| `"update"` \| `"delete"` \| `"insert"` \| `"select"`; `kind?`: `"permissive"` \| `"restrictive"`; `roles?`: readonly `string`[]; `using?`: [`PolicyCondition`](../type-aliases/PolicyCondition.md); `withCheck?`: [`PolicyCondition`](../type-aliases/PolicyCondition.md); \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `command`, `kind`, `roles`, `using`, `withCheck` and query options. ##### Returns `Promise`\<`void`\> ##### Throws Error for an unknown `command` or `kind`, empty `roles` or an empty condition. ##### Example ```ts await queryInterface.createPolicy('documents', 'tenant_isolation', { roles: ['app_user'], using: "tenant_id = current_setting('app.tenant_id')::int", withCheck: "tenant_id = current_setting('app.tenant_id')::int", }); ``` ##### Inherited from `QueryInterfaceCatalog.createPolicy` *** #### createSchema() > **createSchema**(`schema`, `options?`): `Promise`\<`void`\> Runs `CREATE SCHEMA IF NOT EXISTS` for a schema. ##### Parameters ###### schema `string` Schema name. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.createSchema('tenant_1'); ``` ##### Inherited from `QueryInterfaceCatalog.createSchema` *** #### createSequence() > **createSequence**(`name`, `options?`): `Promise`\<`void`\> Creates a sequence with `CREATE SEQUENCE`. Numbers must be whole (`number` or `bigint`). ##### Parameters ###### name [`TableName`](../type-aliases/TableName.md) Sequence name or `{ tableName, schema }`. ###### options? `Readonly`\<\{ `cache?`: [`SequenceNumber`](../type-aliases/SequenceNumber.md); `cycle?`: `boolean`; `dataType?`: `"bigint"` \| `"integer"` \| `"smallint"`; `ifNotExists?`: `boolean`; `increment?`: [`SequenceNumber`](../type-aliases/SequenceNumber.md); `maxValue?`: `false` \| [`SequenceNumber`](../type-aliases/SequenceNumber.md); `minValue?`: `false` \| [`SequenceNumber`](../type-aliases/SequenceNumber.md); `ownedBy?`: `Readonly`\<\{ `column`: `string`; `table`: [`TableName`](../type-aliases/TableName.md); \}\> \| `null`; `start?`: [`SequenceNumber`](../type-aliases/SequenceNumber.md); \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Sequence properties and query options. ##### Returns `Promise`\<`void`\> ##### Throws Error for an unknown `dataType` or a non-integer number. ##### Example ```ts await queryInterface.createSequence('invoice_number', { start: 1000, increment: 1, cache: 10 }); ``` ##### Inherited from `QueryInterfaceCatalog.createSequence` *** #### createTable() > **createTable**(`table`, `attributes`, `options?`): `Promise`\<`void`\> Creates a table together with the enum types its columns need, if the table does not exist yet. Foreign keys, defaults and comments come from the attribute definitions. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### attributes [`ModelAttributes`](../type-aliases/ModelAttributes.md) Column definitions keyed by column name. ###### options? [`CreateTableOptions`](../type-aliases/CreateTableOptions.md) = `{}` Comment and query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.createTable( { tableName: 'posts', schema: 'tenant_1' }, { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, title: { type: DataTypes.STRING, allowNull: false }, }, { comment: 'Blog posts' }, ); ``` ##### Inherited from `QueryInterfaceCatalog.createTable` *** #### createTrigger() > **createTrigger**(`table`, `name`, `timing`, `events`, `functionName`, `functionArgs?`, `optionsArray?`, `options?`): `Promise`\<`void`\> Creates a trigger with `CREATE TRIGGER` (Sequelize v6 `createTrigger`; `'after_constraint'` creates a `CONSTRAINT TRIGGER`). `functionArgs` are rendered as literals (v6 rendered typed parameter declarations, which PostgreSQL rejects). The `optionsArray` clauses are checked against an allowlist (`'FOR EACH ROW'`, `'FOR EACH STATEMENT'`, `'DEFERRABLE'`, `'INITIALLY DEFERRED'`, `REFERENCING ... TABLE AS name`); a `WHEN (condition)` clause is trusted SQL and is not escaped. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### name `string` Trigger name. ###### timing [`TriggerTiming`](../type-aliases/TriggerTiming.md) `'before'`, `'after'`, `'instead_of'` or `'after_constraint'`. ###### events readonly [`TriggerEvent`](../type-aliases/TriggerEvent.md)[] Events that fire the trigger: `'insert'`, `'update'`, `'delete'`, `'truncate'`. ###### functionName [`FunctionName`](../type-aliases/FunctionName.md) Trigger function (see [QueryInterface.createFunction](#createfunction)). ###### functionArgs? readonly [`TriggerArgument`](../type-aliases/TriggerArgument.md)[] = `[]` Literal arguments for the function; pass `[]` for none. ###### optionsArray? readonly `string`[] = `[]` Clauses such as `['FOR EACH ROW']`. ###### options? `Readonly`\<\{ `replace?`: `boolean`; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `replace` (`OR REPLACE`, PostgreSQL 14+) and query options. ##### Returns `Promise`\<`void`\> ##### Throws Error for an unknown timing, event or clause. ##### Example ```ts await queryInterface.createTrigger('Posts', 'posts_touch', 'before', ['insert', 'update'], 'touch_updated_at', [], ['FOR EACH ROW']); ``` ##### Inherited from `QueryInterfaceCatalog.createTrigger` *** #### createView() > **createView**(`name`, `query`, `options?`): `Promise`\<`void`\> Creates a view with `CREATE VIEW`; `replace` renders `CREATE OR REPLACE VIEW`. The `query` is SQL text you provide: it is not escaped, so never build it from user input. Names and column lists are quoted identifiers. A trailing `;` is removed. ##### Parameters ###### name [`TableName`](../type-aliases/TableName.md) View name or `{ tableName, schema }`. ###### query `string` Trusted `SELECT` text. ###### options? `Readonly`\<\{ `checkOption?`: `"local"` \| `"cascaded"`; `columns?`: readonly `string`[]; `recursive?`: `boolean`; `replace?`: `boolean`; `securityBarrier?`: `boolean`; `securityInvoker?`: `boolean`; `temporary?`: `boolean`; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `replace`, `temporary`, `recursive`, `columns`, `checkOption`, `securityBarrier`, `securityInvoker` and query options. ##### Returns `Promise`\<`void`\> ##### Throws Error for an empty query, a recursive view without `columns` or an unknown `checkOption`. ##### Example ```ts await queryInterface.createView('published_posts', 'SELECT id, title FROM "Posts" WHERE published', { replace: true }); ``` ##### See [Schema objects guide](/guide/schema-objects) ##### Inherited from `QueryInterfaceCatalog.createView` *** #### databaseVersion() > **databaseVersion**(`options?`): `Promise`\<`string`\> Reads the PostgreSQL server version (`SHOW server_version`), e.g. `'17.2'`. ##### Parameters ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`string`\> Version string. ##### Example ```ts const version = await queryInterface.databaseVersion(); ``` ##### Inherited from `QueryInterfaceCatalog.databaseVersion` *** #### deferConstraints() > **deferConstraints**(`transaction`, `options?`): `Promise`\<`void`\> Runs `SET CONSTRAINTS ...` for `options.deferrable` (`Deferrable.SET_DEFERRED` / `SET_IMMEDIATE`) on the connection of a transaction. ##### Parameters ###### transaction [`Transaction`](Transaction.md) Transaction to run in. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) & `Readonly`\<\{ `deferrable?`: `Readonly`\<\{ `sql`: `string`; \}\>; \}\> = `{}` `deferrable` and query options. ##### Returns `Promise`\<`void`\> ##### Throws Error when `deferrable` is not `Deferrable.SET_DEFERRED` / `SET_IMMEDIATE`. ##### Example ```ts await queryInterface.deferConstraints(transaction, { deferrable: Deferrable.SET_DEFERRED(['posts_user_fk']) }); ``` ##### Inherited from `QueryInterfaceCatalog.deferConstraints` *** #### describeTable() > **describeTable**(`table`, `options?`): `Promise`\<`Record`\<`string`, `Readonly`\<\{ `allowNull`: `boolean`; `comment`: `string` \| `null`; `defaultValue`: `unknown`; `primaryKey`: `boolean`; `special`: readonly `string`[]; `type`: `string`; \}\>\>\> Reads the column metadata of a table from the catalog. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) & `Readonly`\<\{ `schema?`: `string`; \}\> = `{}` `schema` and query options. ##### Returns `Promise`\<`Record`\<`string`, `Readonly`\<\{ `allowNull`: `boolean`; `comment`: `string` \| `null`; `defaultValue`: `unknown`; `primaryKey`: `boolean`; `special`: readonly `string`[]; `type`: `string`; \}\>\>\> Column descriptions keyed by column name. ##### Throws Error when the table does not exist. ##### Example ```ts const columns = await queryInterface.describeTable('users'); const emailNullable = columns['email']?.allowNull; ``` ##### Inherited from `QueryInterfaceCatalog.describeTable` *** #### detachPartition() > **detachPartition**(`parent`, `partition`, `options?`): `Promise`\<`void`\> Detaches a partition, keeping it as a standalone table (`ALTER TABLE ... DETACH PARTITION`). ##### Parameters ###### parent [`TableName`](../type-aliases/TableName.md) Partitioned table name or `{ tableName, schema }`. ###### partition [`TableName`](../type-aliases/TableName.md) Partition name or `{ tableName, schema }`. ###### options? `Readonly`\<\{ `concurrently?`: `boolean`; `finalize?`: `boolean`; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `concurrently` (PostgreSQL 14+, not inside a transaction), `finalize` and query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.detachPartition('events', 'events_2026', { concurrently: true }); ``` ##### Inherited from `QueryInterfaceCatalog.detachPartition` *** #### disableRowLevelSecurity() > **disableRowLevelSecurity**(`table`, `options?`): `Promise`\<`void`\> Turns off row-level security for a table (`ALTER TABLE ... DISABLE ROW LEVEL SECURITY`); policies are kept. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### options? `Readonly`\<\{ `noForce?`: `boolean`; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `noForce` and query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.disableRowLevelSecurity('documents', { noForce: true }); ``` ##### Inherited from `QueryInterfaceCatalog.disableRowLevelSecurity` *** #### dropAllEnums() > **dropAllEnums**(`options?`): `Promise`\<`void`\> Drops every enum type of the current schema with `CASCADE`, which also drops dependent columns' defaults. Destructive. ##### Parameters ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.dropAllEnums(); ``` *** #### dropAllSchemas() > **dropAllSchemas**(`options?`): `Promise`\<`void`\> Drops, with `CASCADE`, every schema listed by [QueryInterface.showAllSchemas](#showallschemas) Destructive. ##### Parameters ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.dropAllSchemas(); ``` ##### Inherited from `QueryInterfaceCatalog.dropAllSchemas` *** #### dropAllTables() > **dropAllTables**(`options?`): `Promise`\<`void`\> Drops every table of the current schema with `CASCADE`, except the skipped ones. Destructive. ##### Parameters ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) & `Readonly`\<\{ `skip?`: readonly `string`[]; \}\> = `{}` `skip`: table names to keep, plus query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.dropAllTables({ skip: ['SequelizeMeta'] }); ``` ##### Inherited from `QueryInterfaceCatalog.dropAllTables` *** #### dropDatabase() > **dropDatabase**(`database`, `options?`): `Promise`\<`void`\> Runs `DROP DATABASE IF EXISTS`. Must run outside a transaction. ##### Parameters ###### database `string` Database name (quoted). ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.dropDatabase('tenant_42'); ``` ##### Inherited from `QueryInterfaceCatalog.dropDatabase` *** #### dropEnum() > **dropEnum**(`name`, `options?`): `Promise`\<`void`\> Runs `DROP TYPE IF EXISTS` for an enum type. ##### Parameters ###### name `string` Enum type name. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.dropEnum('enum_users_role'); ``` *** #### dropExtension() > **dropExtension**(`name`, `options?`): `Promise`\<`void`\> Removes an extension with `DROP EXTENSION`. ##### Parameters ###### name `string` Extension name. ###### options? `Readonly`\<\{ `cascade?`: `boolean`; `ifExists?`: `boolean`; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `ifExists`, `cascade` and query options. ##### Returns `Promise`\<`void`\> ##### Throws DatabaseError when objects depend on the extension and `cascade` is not set. ##### Example ```ts await queryInterface.dropExtension('pg_trgm', { ifExists: true }); ``` ##### Inherited from `QueryInterfaceCatalog.dropExtension` *** #### dropFunction() > **dropFunction**(`name`, `params`, `options?`): `Promise`\<`void`\> Drops a function with `DROP FUNCTION ... RESTRICT` (Sequelize v6 `dropFunction`). ##### Parameters ###### name [`FunctionName`](../type-aliases/FunctionName.md) Function name. ###### params readonly `Readonly`\<\{ `direction?`: `string`; `name?`: `string`; `type`: `string`; \}\>[] Parameters that identify the overload; pass `[]` for none. ###### options? `Readonly`\<\{ `cascade?`: `boolean`; `ifExists?`: `boolean`; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `ifExists`, `cascade` and query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.dropFunction('touch_updated_at', [], { ifExists: true }); ``` ##### Inherited from `QueryInterfaceCatalog.dropFunction` *** #### dropMaterializedView() > **dropMaterializedView**(`name`, `options?`): `Promise`\<`void`\> Drops a materialized view with `DROP MATERIALIZED VIEW`. ##### Parameters ###### name [`TableName`](../type-aliases/TableName.md) View name or `{ tableName, schema }`. ###### options? `Readonly`\<\{ `cascade?`: `boolean`; `ifExists?`: `boolean`; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `ifExists`, `cascade` and query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.dropMaterializedView('post_stats', { ifExists: true }); ``` ##### Inherited from `QueryInterfaceCatalog.dropMaterializedView` *** #### dropPolicy() > **dropPolicy**(`table`, `name`, `options?`): `Promise`\<`void`\> Drops a policy with `DROP POLICY`. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### name `string` Policy name. ###### options? `Readonly`\<\{ `cascade?`: `boolean`; `ifExists?`: `boolean`; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `ifExists`, `cascade` and query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.dropPolicy('documents', 'tenant_isolation', { ifExists: true }); ``` ##### Inherited from `QueryInterfaceCatalog.dropPolicy` *** #### dropSchema() > **dropSchema**(`schema`, `options?`): `Promise`\<`void`\> Runs `DROP SCHEMA IF EXISTS ... CASCADE`, removing the schema and everything in it. ##### Parameters ###### schema `string` Schema name. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.dropSchema('tenant_1'); ``` ##### Inherited from `QueryInterfaceCatalog.dropSchema` *** #### dropSequence() > **dropSequence**(`name`, `options?`): `Promise`\<`void`\> Drops a sequence with `DROP SEQUENCE`. ##### Parameters ###### name [`TableName`](../type-aliases/TableName.md) Sequence name or `{ tableName, schema }`. ###### options? `Readonly`\<\{ `cascade?`: `boolean`; `ifExists?`: `boolean`; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `ifExists`, `cascade` and query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.dropSequence('invoice_number', { ifExists: true }); ``` ##### Inherited from `QueryInterfaceCatalog.dropSequence` *** #### dropTable() > **dropTable**(`table`, `options?`): `Promise`\<`void`\> Runs `DROP TABLE IF EXISTS` for a table; it does not drop the table's enum types. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### options? [`DropTableOptions`](../type-aliases/DropTableOptions.md) = `{}` `cascade` and query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.dropTable('posts', { cascade: true }); ``` ##### Inherited from `QueryInterfaceCatalog.dropTable` *** #### dropTrigger() > **dropTrigger**(`table`, `name`, `options?`): `Promise`\<`void`\> Drops a trigger with `DROP TRIGGER ... RESTRICT` (Sequelize v6 `dropTrigger`). ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### name `string` Trigger name. ###### options? `Readonly`\<\{ `cascade?`: `boolean`; `ifExists?`: `boolean`; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `ifExists`, `cascade` and query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.dropTrigger('Posts', 'posts_touch', { ifExists: true }); ``` ##### Inherited from `QueryInterfaceCatalog.dropTrigger` *** #### dropView() > **dropView**(`name`, `options?`): `Promise`\<`void`\> Drops a view with `DROP VIEW`. ##### Parameters ###### name [`TableName`](../type-aliases/TableName.md) View name or `{ tableName, schema }`. ###### options? `Readonly`\<\{ `cascade?`: `boolean`; `ifExists?`: `boolean`; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `ifExists`, `cascade` and query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.dropView('published_posts', { ifExists: true }); ``` ##### Inherited from `QueryInterfaceCatalog.dropView` *** #### enableRowLevelSecurity() > **enableRowLevelSecurity**(`table`, `options?`): `Promise`\<`void`\> Turns on row-level security for a table (`ALTER TABLE ... ENABLE ROW LEVEL SECURITY`). Without policies, non-owners see no rows. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### options? `Readonly`\<\{ `force?`: `boolean`; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `force` (also applies to the table owner) and query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.enableRowLevelSecurity('documents', { force: true }); ``` ##### See [Schema objects guide](/guide/schema-objects) ##### Inherited from `QueryInterfaceCatalog.enableRowLevelSecurity` *** #### getForeignKeyReferencesForTable() > **getForeignKeyReferencesForTable**(`table`, `options?`): `Promise`\<`Readonly`\<\{ `columnName`: `string`; `constraintName`: `string`; `referencedColumnName`: `string`; `referencedTableName`: `string`; \}\>[]\> Lists the foreign key columns of a table with the table and column each one references. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`Readonly`\<\{ `columnName`: `string`; `constraintName`: `string`; `referencedColumnName`: `string`; `referencedTableName`: `string`; \}\>[]\> Constraint name, column and referenced table/column per foreign key column. ##### Example ```ts const references = await queryInterface.getForeignKeyReferencesForTable('posts'); const targets = references.map((reference) => reference.referencedTableName); ``` ##### Inherited from `QueryInterfaceCatalog.getForeignKeyReferencesForTable` *** #### getForeignKeysForTables() > **getForeignKeysForTables**(`tables`, `options?`): `Promise`\<`Record`\<`string`, readonly `string`[]\>\> Names of the foreign key constraints of each table. ##### Parameters ###### tables readonly [`TableName`](../type-aliases/TableName.md)[] Table names or `{ tableName, schema }`. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`Record`\<`string`, readonly `string`[]\>\> Constraint names keyed by table (`schema.table` for qualified tables). ##### Example ```ts const keys = await queryInterface.getForeignKeysForTables(['posts', 'comments']); ``` ##### Inherited from `QueryInterfaceCatalog.getForeignKeysForTables` *** #### nextval() > **nextval**(`name`, `options?`): `Promise`\<`string`\> Advances a sequence and returns the new value (`SELECT nextval(...)`; the name is bound). ##### Parameters ###### name [`TableName`](../type-aliases/TableName.md) Sequence name or `{ tableName, schema }`. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`string`\> The value as text, so bigint values stay exact. ##### Example ```ts const next = await queryInterface.nextval('invoice_number'); ``` ##### Inherited from `QueryInterfaceCatalog.nextval` *** #### quoteIdentifier() > **quoteIdentifier**(`identifier`, `_force?`): `string` Quotes an identifier for SQL: `"name"`, embedded double quotes are doubled. ##### Parameters ###### identifier `string` Identifier. ###### \_force? `boolean` Accepted for Sequelize v6 compatibility; identifiers are always quoted. ##### Returns `string` Quoted identifier. ##### Example ```ts queryInterface.quoteIdentifier('user name'); // "user name" ``` ##### Inherited from `QueryInterfaceCatalog.quoteIdentifier` *** #### quoteIdentifiers() > **quoteIdentifiers**(`identifiers`): `string` Quotes a dotted identifier part by part: `schema.table` becomes `"schema"."table"`. ##### Parameters ###### identifiers `string` Dot separated identifiers. ##### Returns `string` Quoted identifiers. ##### Example ```ts queryInterface.quoteIdentifiers('tenant.users'); // "tenant"."users" ``` ##### Inherited from `QueryInterfaceCatalog.quoteIdentifiers` *** #### refreshMaterializedView() > **refreshMaterializedView**(`name`, `options?`): `Promise`\<`void`\> Recomputes a materialized view with `REFRESH MATERIALIZED VIEW`. ##### Parameters ###### name [`TableName`](../type-aliases/TableName.md) View name or `{ tableName, schema }`. ###### options? `Readonly`\<\{ `concurrently?`: `boolean`; `withData?`: `boolean`; \}\> & [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` `concurrently` (needs a unique index), `withData` and query options. ##### Returns `Promise`\<`void`\> ##### Throws Error when `concurrently` is combined with `withData: false`. ##### Example ```ts await queryInterface.refreshMaterializedView('post_stats', { concurrently: true }); ``` ##### Inherited from `QueryInterfaceCatalog.refreshMaterializedView` *** #### removeColumn() > **removeColumn**(`table`, `column`, `options?`): `Promise`\<`void`\> Drops a column with `ALTER TABLE ... DROP COLUMN`. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### column `string` Column name. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.removeColumn('users', 'nickname'); ``` *** #### removeConstraint() > **removeConstraint**(`table`, `name`, `options?`): `Promise`\<`void`\> Drops a named constraint from a table. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### name `string` Constraint name. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.removeConstraint('products', 'products_price_positive'); ``` *** #### removeIndex() > **removeIndex**(`table`, `nameOrFields`, `options?`): `Promise`\<`void`\> Drops an index identified by name, or by the fields it was created on (the default generated name is derived from them). ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### nameOrFields `string` \| readonly [`IndexField`](../type-aliases/IndexField.md)[] Index name or indexed fields. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) & `Readonly`\<\{ `concurrently?`: `boolean`; \}\> = `{}` `concurrently` and query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.removeIndex('users', 'users_email_unique'); ``` *** #### renameColumn() > **renameColumn**(`table`, `before`, `after`, `options?`): `Promise`\<`void`\> Renames a column with `ALTER TABLE ... RENAME COLUMN`. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### before `string` Current column name. ###### after `string` New column name. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.renameColumn('users', 'name', 'full_name'); ``` *** #### renameFunction() > **renameFunction**(`name`, `params`, `newName`, `options?`): `Promise`\<`void`\> Renames a function with `ALTER FUNCTION ... RENAME TO` (Sequelize v6 `renameFunction`). ##### Parameters ###### name [`FunctionName`](../type-aliases/FunctionName.md) Current function name. ###### params readonly `Readonly`\<\{ `direction?`: `string`; `name?`: `string`; `type`: `string`; \}\>[] Parameters that identify the overload. ###### newName `string` New unqualified name. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.renameFunction('touch_updated_at', [], 'set_updated_at'); ``` ##### Inherited from `QueryInterfaceCatalog.renameFunction` *** #### renameTable() > **renameTable**(`before`, `after`, `options?`): `Promise`\<`void`\> Renames a table with `ALTER TABLE ... RENAME TO`; the schema of `after` is ignored. ##### Parameters ###### before [`TableName`](../type-aliases/TableName.md) Current table. ###### after [`TableName`](../type-aliases/TableName.md) New table name. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.renameTable('posts', 'articles'); ``` ##### Inherited from `QueryInterfaceCatalog.renameTable` *** #### renameTrigger() > **renameTrigger**(`table`, `name`, `newName`, `options?`): `Promise`\<`void`\> Renames a trigger with `ALTER TRIGGER ... RENAME TO` (Sequelize v6 `renameTrigger`). ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### name `string` Current trigger name. ###### newName `string` New trigger name. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.renameTrigger('Posts', 'posts_touch', 'posts_set_updated_at'); ``` ##### Inherited from `QueryInterfaceCatalog.renameTrigger` *** #### setval() > **setval**(`name`, `value`, `isCalled?`, `options?`): `Promise`\<`string`\> Sets the current value of a sequence (`SELECT setval(...)`; name and value are bound). ##### Parameters ###### name [`TableName`](../type-aliases/TableName.md) Sequence name or `{ tableName, schema }`. ###### value [`SequenceNumber`](../type-aliases/SequenceNumber.md) New value (`number` or `bigint`). ###### isCalled? `boolean` = `true` `true` (default): the next `nextval` returns `value + increment`; `false`: it returns `value`. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`string`\> The value set, as text. ##### Example ```ts await queryInterface.setval('invoice_number', 9000, false); ``` ##### Inherited from `QueryInterfaceCatalog.setval` *** #### showAllSchemas() > **showAllSchemas**(`options?`): `Promise`\<`string`[]\> Lists application schemas, leaving out `public`, `information_schema` and `pg_*` schemas. ##### Parameters ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`string`[]\> Schema names. ##### Example ```ts const schemas = await queryInterface.showAllSchemas(); ``` ##### Inherited from `QueryInterfaceCatalog.showAllSchemas` *** #### showAllTables() > **showAllTables**(`options?`): `Promise`\<`string`[]\> Lists the table names of the current schema in alphabetical order. ##### Parameters ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`string`[]\> Table names. ##### Example ```ts const tables = await queryInterface.showAllTables(); // e.g. ['posts', 'users'] ``` ##### Inherited from `QueryInterfaceCatalog.showAllTables` *** #### showConstraint() > **showConstraint**(`table`, `constraintName?`, `options?`): `Promise`\<`Readonly`\<`Record`\<`string`, `unknown`\>\>[]\> Lists the constraints of a table (`information_schema.table_constraints`), optionally one by name. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`; `current_schema()` when no schema is given. ###### constraintName? `string` \| `null` Only this constraint. Sequelize v6 ignores it for PostgreSQL and lists all. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`Readonly`\<`Record`\<`string`, `unknown`\>\>[]\> Constraint rows (`constraintName`, `constraintType`, `isDeferrable`, ...), ordered by name. ##### Example ```ts const constraints = await queryInterface.showConstraint('users'); const names = constraints.map((constraint) => constraint.constraintName); ``` ##### Inherited from `QueryInterfaceCatalog.showConstraint` *** #### showIndex() > **showIndex**(`table`, `options?`): `Promise`\<`Readonly`\<\{ `definition`: `string`; `fields`: readonly `Readonly`\<\{ `attribute`: `string`; `collate`: `string` \| `undefined`; `length`: `undefined`; `order`: `"ASC"` \| `"DESC"` \| `undefined`; \}\>[]; `indkey`: `string`; `name`: `string`; `primary`: `boolean`; `unique`: `boolean`; \}\>[]\> Lists the indexes of a table, with their columns, uniqueness and definition. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`; `current_schema()` when no schema is given. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`Readonly`\<\{ `definition`: `string`; `fields`: readonly `Readonly`\<\{ `attribute`: `string`; `collate`: `string` \| `undefined`; `length`: `undefined`; `order`: `"ASC"` \| `"DESC"` \| `undefined`; \}\>[]; `indkey`: `string`; `name`: `string`; `primary`: `boolean`; `unique`: `boolean`; \}\>[]\> One entry per index, ordered by name. ##### Example ```ts const indexes = await queryInterface.showIndex('users'); const unique = indexes.filter((index) => index.unique).map((index) => index.name); ``` ##### Inherited from `QueryInterfaceCatalog.showIndex` *** #### tableExists() > **tableExists**(`table`, `options?`): `Promise`\<`boolean`\> Tells whether a table exists in its schema (the current schema when none is given). ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`boolean`\> True when the table exists. ##### Example ```ts if (!(await queryInterface.tableExists('posts'))) { await queryInterface.createTable('posts', { title: DataTypes.STRING }); } ``` ##### Inherited from `QueryInterfaceCatalog.tableExists` *** #### validateConstraint() > **validateConstraint**(`table`, `name`, `options?`): `Promise`\<`void`\> Validates a constraint added with `notValid: true`, scanning existing rows without blocking writes. ##### Parameters ###### table [`TableName`](../type-aliases/TableName.md) Table name or `{ tableName, schema }`. ###### name `string` Constraint name. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await queryInterface.addConstraint('products', { type: 'check', name: 'products_price_positive', where: { price: { [Op.gt]: 0 } }, notValid: true, }); await queryInterface.validateConstraint('products', 'products_price_positive'); ``` ## Class: Sequelize Entry point, API-compatible with Sequelize v6 `Sequelize` for PostgreSQL. ### Example ```ts const sequelize = new Sequelize('postgres://user:pass@localhost:5432/app', { logging: false }); ``` ### Extends - [`RuntimeOwner`](../interfaces/RuntimeOwner.md) - `InstanceHookAdders` - `SequelizeMembers` ### Constructors #### Constructor > **new Sequelize**(`uri`, `options?`): `Sequelize` Creates an instance from a connection URI. ##### Parameters ###### uri `string` `postgres://user:password@host:port/database`. ###### options? `Readonly`\<\{ `benchmark?`: `boolean`; `database?`: `string`; `define?`: `Readonly`\<\{ `freezeTableName?`: `boolean`; `hooks?`: `Partial`\<`Readonly`\<`Record`\<... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ..., ... \| ...\>\>\>; `paranoid?`: `boolean`; `schema?`: `string`; `timestamps?`: `boolean`; `underscored?`: `boolean`; \}\>; `dialect?`: `"postgres"`; `dialectModule?`: `object`; `dialectOptions?`: `Readonly`\<`Omit`\<`PoolConfig`, `"types"`\>\>; `hooks?`: `Partial`\<`Readonly`\<`Record`\<`"beforeValidate"` \| `"afterValidate"` \| `"validationFailed"` \| `"beforeCreate"` \| `"afterCreate"` \| `"beforeUpdate"` \| `"afterUpdate"` \| `"beforeSave"` \| `"afterSave"` \| `"beforeDestroy"` \| `"afterDestroy"` \| `"beforeRestore"` \| `"afterRestore"` \| `"beforeUpsert"` \| `"afterUpsert"` \| `"beforeBulkCreate"` \| `"afterBulkCreate"` \| `"beforeBulkUpdate"` \| `"afterBulkUpdate"` \| `"beforeBulkDestroy"` \| `"afterBulkDestroy"` \| `"beforeBulkRestore"` \| `"afterBulkRestore"` \| `"beforeFind"` \| `"beforeFindAfterExpandIncludeAll"` \| `"beforeFindAfterOptions"` \| `"afterFind"` \| `"beforeCount"` \| `"beforeConnect"` \| `"afterConnect"` \| `"beforeDisconnect"` \| `"afterDisconnect"` \| `"beforePoolAcquire"` \| `"afterPoolAcquire"` \| `"beforeQuery"` \| `"afterQuery"` \| `"beforeSync"` \| `"afterSync"` \| `"beforeBulkSync"` \| `"afterBulkSync"` \| `"beforeDefine"` \| `"afterDefine"` \| `"beforeInit"` \| `"afterInit"` \| `"beforeAssociate"` \| `"afterAssociate"`, [`HookFunction`](../type-aliases/HookFunction.md) \| readonly [`HookFunction`](../type-aliases/HookFunction.md)[]\>\>\>; `host?`: `string`; `inAsAnyThreshold?`: `number`; `logging?`: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md); `minifyAliases?`: `boolean`; `password?`: `string`; `pool?`: `Readonly`\<\{ `acquire?`: `number`; `evict?`: `number`; `idle?`: `number`; `max?`: `number`; `maxUses?`: `number`; `min?`: `number`; \}\>; `port?`: `number`; `replication?`: `Readonly`\<\{ `read`: `Readonly`\<\{ `database?`: `string`; `host?`: `string`; `password?`: `string`; `port?`: `number`; `username?`: `string`; \}\> \| readonly `Readonly`\<\{ `database?`: ... \| ...; `host?`: ... \| ...; `password?`: ... \| ...; `port?`: ... \| ...; `username?`: ... \| ...; \}\>[]; `write?`: `Readonly`\<\{ `database?`: `string`; `host?`: `string`; `password?`: `string`; `port?`: `number`; `username?`: `string`; \}\>; \}\>; `retry?`: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\>; `ssl?`: `boolean` \| `ConnectionOptions`; `statementCache?`: `boolean` \| `Readonly`\<\{ `max?`: `number`; \}\>; `timezone?`: `string`; `username?`: `string`; \}\> Options. ##### Returns `Sequelize` ##### Inherited from `RuntimeOwner.constructor` #### Constructor > **new Sequelize**(`database`, `username?`, `password?`, `options?`): `Sequelize` Creates an instance from connection parameters. ##### Parameters ###### database `string` Database name. ###### username? `string` \| `null` User name. ###### password? `string` \| `null` Password. ###### options? `Readonly`\<\{ `benchmark?`: `boolean`; `database?`: `string`; `define?`: `Readonly`\<\{ `freezeTableName?`: `boolean`; `hooks?`: `Partial`\<`Readonly`\<`Record`\<... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ..., ... \| ...\>\>\>; `paranoid?`: `boolean`; `schema?`: `string`; `timestamps?`: `boolean`; `underscored?`: `boolean`; \}\>; `dialect?`: `"postgres"`; `dialectModule?`: `object`; `dialectOptions?`: `Readonly`\<`Omit`\<`PoolConfig`, `"types"`\>\>; `hooks?`: `Partial`\<`Readonly`\<`Record`\<`"beforeValidate"` \| `"afterValidate"` \| `"validationFailed"` \| `"beforeCreate"` \| `"afterCreate"` \| `"beforeUpdate"` \| `"afterUpdate"` \| `"beforeSave"` \| `"afterSave"` \| `"beforeDestroy"` \| `"afterDestroy"` \| `"beforeRestore"` \| `"afterRestore"` \| `"beforeUpsert"` \| `"afterUpsert"` \| `"beforeBulkCreate"` \| `"afterBulkCreate"` \| `"beforeBulkUpdate"` \| `"afterBulkUpdate"` \| `"beforeBulkDestroy"` \| `"afterBulkDestroy"` \| `"beforeBulkRestore"` \| `"afterBulkRestore"` \| `"beforeFind"` \| `"beforeFindAfterExpandIncludeAll"` \| `"beforeFindAfterOptions"` \| `"afterFind"` \| `"beforeCount"` \| `"beforeConnect"` \| `"afterConnect"` \| `"beforeDisconnect"` \| `"afterDisconnect"` \| `"beforePoolAcquire"` \| `"afterPoolAcquire"` \| `"beforeQuery"` \| `"afterQuery"` \| `"beforeSync"` \| `"afterSync"` \| `"beforeBulkSync"` \| `"afterBulkSync"` \| `"beforeDefine"` \| `"afterDefine"` \| `"beforeInit"` \| `"afterInit"` \| `"beforeAssociate"` \| `"afterAssociate"`, [`HookFunction`](../type-aliases/HookFunction.md) \| readonly [`HookFunction`](../type-aliases/HookFunction.md)[]\>\>\>; `host?`: `string`; `inAsAnyThreshold?`: `number`; `logging?`: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md); `minifyAliases?`: `boolean`; `password?`: `string`; `pool?`: `Readonly`\<\{ `acquire?`: `number`; `evict?`: `number`; `idle?`: `number`; `max?`: `number`; `maxUses?`: `number`; `min?`: `number`; \}\>; `port?`: `number`; `replication?`: `Readonly`\<\{ `read`: `Readonly`\<\{ `database?`: `string`; `host?`: `string`; `password?`: `string`; `port?`: `number`; `username?`: `string`; \}\> \| readonly `Readonly`\<\{ `database?`: ... \| ...; `host?`: ... \| ...; `password?`: ... \| ...; `port?`: ... \| ...; `username?`: ... \| ...; \}\>[]; `write?`: `Readonly`\<\{ `database?`: `string`; `host?`: `string`; `password?`: `string`; `port?`: `number`; `username?`: `string`; \}\>; \}\>; `retry?`: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\>; `ssl?`: `boolean` \| `ConnectionOptions`; `statementCache?`: `boolean` \| `Readonly`\<\{ `max?`: `number`; \}\>; `timezone?`: `string`; `username?`: `string`; \}\> Options. ##### Returns `Sequelize` ##### Inherited from `RuntimeOwner.constructor` #### Constructor > **new Sequelize**(`options?`): `Sequelize` Creates an instance from options only. ##### Parameters ###### options? `Readonly`\<\{ `benchmark?`: `boolean`; `database?`: `string`; `define?`: `Readonly`\<\{ `freezeTableName?`: `boolean`; `hooks?`: `Partial`\<`Readonly`\<`Record`\<... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ... \| ..., ... \| ...\>\>\>; `paranoid?`: `boolean`; `schema?`: `string`; `timestamps?`: `boolean`; `underscored?`: `boolean`; \}\>; `dialect?`: `"postgres"`; `dialectModule?`: `object`; `dialectOptions?`: `Readonly`\<`Omit`\<`PoolConfig`, `"types"`\>\>; `hooks?`: `Partial`\<`Readonly`\<`Record`\<`"beforeValidate"` \| `"afterValidate"` \| `"validationFailed"` \| `"beforeCreate"` \| `"afterCreate"` \| `"beforeUpdate"` \| `"afterUpdate"` \| `"beforeSave"` \| `"afterSave"` \| `"beforeDestroy"` \| `"afterDestroy"` \| `"beforeRestore"` \| `"afterRestore"` \| `"beforeUpsert"` \| `"afterUpsert"` \| `"beforeBulkCreate"` \| `"afterBulkCreate"` \| `"beforeBulkUpdate"` \| `"afterBulkUpdate"` \| `"beforeBulkDestroy"` \| `"afterBulkDestroy"` \| `"beforeBulkRestore"` \| `"afterBulkRestore"` \| `"beforeFind"` \| `"beforeFindAfterExpandIncludeAll"` \| `"beforeFindAfterOptions"` \| `"afterFind"` \| `"beforeCount"` \| `"beforeConnect"` \| `"afterConnect"` \| `"beforeDisconnect"` \| `"afterDisconnect"` \| `"beforePoolAcquire"` \| `"afterPoolAcquire"` \| `"beforeQuery"` \| `"afterQuery"` \| `"beforeSync"` \| `"afterSync"` \| `"beforeBulkSync"` \| `"afterBulkSync"` \| `"beforeDefine"` \| `"afterDefine"` \| `"beforeInit"` \| `"afterInit"` \| `"beforeAssociate"` \| `"afterAssociate"`, [`HookFunction`](../type-aliases/HookFunction.md) \| readonly [`HookFunction`](../type-aliases/HookFunction.md)[]\>\>\>; `host?`: `string`; `inAsAnyThreshold?`: `number`; `logging?`: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md); `minifyAliases?`: `boolean`; `password?`: `string`; `pool?`: `Readonly`\<\{ `acquire?`: `number`; `evict?`: `number`; `idle?`: `number`; `max?`: `number`; `maxUses?`: `number`; `min?`: `number`; \}\>; `port?`: `number`; `replication?`: `Readonly`\<\{ `read`: `Readonly`\<\{ `database?`: `string`; `host?`: `string`; `password?`: `string`; `port?`: `number`; `username?`: `string`; \}\> \| readonly `Readonly`\<\{ `database?`: ... \| ...; `host?`: ... \| ...; `password?`: ... \| ...; `port?`: ... \| ...; `username?`: ... \| ...; \}\>[]; `write?`: `Readonly`\<\{ `database?`: `string`; `host?`: `string`; `password?`: `string`; `port?`: `number`; `username?`: `string`; \}\>; \}\>; `retry?`: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\>; `ssl?`: `boolean` \| `ConnectionOptions`; `statementCache?`: `boolean` \| `Readonly`\<\{ `max?`: `number`; \}\>; `timezone?`: `string`; `username?`: `string`; \}\> Options including connection settings. ##### Returns `Sequelize` ##### Inherited from `RuntimeOwner.constructor` ### Properties #### \[runtimeKey\] > `readonly` **\[runtimeKey\]**: `ModelRuntime` Internal services used by models. ##### Inherited from [`RuntimeOwner`](../interfaces/RuntimeOwner.md).[`[runtimeKey]`](../interfaces/RuntimeOwner.md#runtimekey) *** #### afterBulkCreate > `readonly` **afterBulkCreate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterBulkCreate` hook: `sequelize.afterBulkCreate(fn)` or `sequelize.afterBulkCreate(name, fn)`. ##### Inherited from `InstanceHookAdders.afterBulkCreate` *** #### afterBulkDestroy > `readonly` **afterBulkDestroy**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterBulkDestroy` hook: `sequelize.afterBulkDestroy(fn)` or `sequelize.afterBulkDestroy(name, fn)`. ##### Inherited from `InstanceHookAdders.afterBulkDestroy` *** #### afterBulkRestore > `readonly` **afterBulkRestore**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterBulkRestore` hook: `sequelize.afterBulkRestore(fn)` or `sequelize.afterBulkRestore(name, fn)`. ##### Inherited from `InstanceHookAdders.afterBulkRestore` *** #### afterBulkSync > `readonly` **afterBulkSync**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterBulkSync` hook: `sequelize.afterBulkSync(fn)` or `sequelize.afterBulkSync(name, fn)`. ##### Inherited from `InstanceHookAdders.afterBulkSync` *** #### afterBulkUpdate > `readonly` **afterBulkUpdate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterBulkUpdate` hook: `sequelize.afterBulkUpdate(fn)` or `sequelize.afterBulkUpdate(name, fn)`. ##### Inherited from `InstanceHookAdders.afterBulkUpdate` *** #### afterConnect > `readonly` **afterConnect**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterConnect` hook: `sequelize.afterConnect(fn)` or `sequelize.afterConnect(name, fn)`. ##### Inherited from `InstanceHookAdders.afterConnect` *** #### afterCreate > `readonly` **afterCreate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterCreate` hook: `sequelize.afterCreate(fn)` or `sequelize.afterCreate(name, fn)`. ##### Inherited from `InstanceHookAdders.afterCreate` *** #### afterDestroy > `readonly` **afterDestroy**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterDestroy` hook: `sequelize.afterDestroy(fn)` or `sequelize.afterDestroy(name, fn)`. ##### Inherited from `InstanceHookAdders.afterDestroy` *** #### afterFind > `readonly` **afterFind**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterFind` hook: `sequelize.afterFind(fn)` or `sequelize.afterFind(name, fn)`. ##### Inherited from `InstanceHookAdders.afterFind` *** #### afterRestore > `readonly` **afterRestore**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterRestore` hook: `sequelize.afterRestore(fn)` or `sequelize.afterRestore(name, fn)`. ##### Inherited from `InstanceHookAdders.afterRestore` *** #### afterSave > `readonly` **afterSave**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterSave` hook: `sequelize.afterSave(fn)` or `sequelize.afterSave(name, fn)`. ##### Inherited from `InstanceHookAdders.afterSave` *** #### afterSync > `readonly` **afterSync**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterSync` hook: `sequelize.afterSync(fn)` or `sequelize.afterSync(name, fn)`. ##### Inherited from `InstanceHookAdders.afterSync` *** #### afterUpdate > `readonly` **afterUpdate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterUpdate` hook: `sequelize.afterUpdate(fn)` or `sequelize.afterUpdate(name, fn)`. ##### Inherited from `InstanceHookAdders.afterUpdate` *** #### afterUpsert > `readonly` **afterUpsert**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterUpsert` hook: `sequelize.afterUpsert(fn)` or `sequelize.afterUpsert(name, fn)`. ##### Inherited from `InstanceHookAdders.afterUpsert` *** #### afterValidate > `readonly` **afterValidate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterValidate` hook: `sequelize.afterValidate(fn)` or `sequelize.afterValidate(name, fn)`. ##### Inherited from `InstanceHookAdders.afterValidate` *** #### and > `readonly` **and**: (...`conditions`) => [`WhereOptions`](../type-aliases/WhereOptions.md) Combines conditions with `AND`. Combines conditions with `AND` (Sequelize v6 `and`), for use inside `where`. ##### Parameters ###### conditions ...readonly [`WhereOptions`](../type-aliases/WhereOptions.md)[] Conditions to combine. ##### Returns [`WhereOptions`](../type-aliases/WhereOptions.md) A `{ [Op.and]: conditions }` condition usable as `where`. ##### Example ```ts await User.findAll({ where: and({ age: { [Op.gt]: 18 } }, { active: true }) }); ``` *** #### Association > `readonly` **Association**: *typeof* [`Association`](Association.md) Base class of the association classes. *** #### beforeBulkCreate > `readonly` **beforeBulkCreate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeBulkCreate` hook: `sequelize.beforeBulkCreate(fn)` or `sequelize.beforeBulkCreate(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeBulkCreate` *** #### beforeBulkDestroy > `readonly` **beforeBulkDestroy**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeBulkDestroy` hook: `sequelize.beforeBulkDestroy(fn)` or `sequelize.beforeBulkDestroy(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeBulkDestroy` *** #### beforeBulkRestore > `readonly` **beforeBulkRestore**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeBulkRestore` hook: `sequelize.beforeBulkRestore(fn)` or `sequelize.beforeBulkRestore(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeBulkRestore` *** #### beforeBulkSync > `readonly` **beforeBulkSync**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeBulkSync` hook: `sequelize.beforeBulkSync(fn)` or `sequelize.beforeBulkSync(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeBulkSync` *** #### beforeBulkUpdate > `readonly` **beforeBulkUpdate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeBulkUpdate` hook: `sequelize.beforeBulkUpdate(fn)` or `sequelize.beforeBulkUpdate(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeBulkUpdate` *** #### beforeConnect > `readonly` **beforeConnect**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeConnect` hook: `sequelize.beforeConnect(fn)` or `sequelize.beforeConnect(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeConnect` *** #### beforeCount > `readonly` **beforeCount**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeCount` hook: `sequelize.beforeCount(fn)` or `sequelize.beforeCount(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeCount` *** #### beforeCreate > `readonly` **beforeCreate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeCreate` hook: `sequelize.beforeCreate(fn)` or `sequelize.beforeCreate(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeCreate` *** #### beforeDestroy > `readonly` **beforeDestroy**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeDestroy` hook: `sequelize.beforeDestroy(fn)` or `sequelize.beforeDestroy(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeDestroy` *** #### beforeFind > `readonly` **beforeFind**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeFind` hook: `sequelize.beforeFind(fn)` or `sequelize.beforeFind(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeFind` *** #### beforeFindAfterExpandIncludeAll > `readonly` **beforeFindAfterExpandIncludeAll**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeFindAfterExpandIncludeAll` hook: `sequelize.beforeFindAfterExpandIncludeAll(fn)` or `sequelize.beforeFindAfterExpandIncludeAll(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeFindAfterExpandIncludeAll` *** #### beforeFindAfterOptions > `readonly` **beforeFindAfterOptions**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeFindAfterOptions` hook: `sequelize.beforeFindAfterOptions(fn)` or `sequelize.beforeFindAfterOptions(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeFindAfterOptions` *** #### beforeRestore > `readonly` **beforeRestore**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeRestore` hook: `sequelize.beforeRestore(fn)` or `sequelize.beforeRestore(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeRestore` *** #### beforeSave > `readonly` **beforeSave**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeSave` hook: `sequelize.beforeSave(fn)` or `sequelize.beforeSave(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeSave` *** #### beforeSync > `readonly` **beforeSync**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeSync` hook: `sequelize.beforeSync(fn)` or `sequelize.beforeSync(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeSync` *** #### beforeUpdate > `readonly` **beforeUpdate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeUpdate` hook: `sequelize.beforeUpdate(fn)` or `sequelize.beforeUpdate(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeUpdate` *** #### beforeUpsert > `readonly` **beforeUpsert**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeUpsert` hook: `sequelize.beforeUpsert(fn)` or `sequelize.beforeUpsert(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeUpsert` *** #### beforeValidate > `readonly` **beforeValidate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeValidate` hook: `sequelize.beforeValidate(fn)` or `sequelize.beforeValidate(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeValidate` *** #### cast > `readonly` **cast**: (`val`, `type`) => [`Cast`](../interfaces/Cast.md) Type cast builder. Creates a type cast `CAST(value AS type)`. ##### Parameters ###### val `unknown` Value or expression to cast. ###### type `string` PostgreSQL type name, e.g. `'integer'`. ##### Returns [`Cast`](../interfaces/Cast.md) Cast expression. ##### Example ```ts await Product.findAll({ attributes: [[cast(col('price'), 'integer'), 'rounded']] }); ``` *** #### col > `readonly` **col**: (`name`) => [`Col`](../interfaces/Col.md) Column reference builder. Creates a column reference. Dots separate table and column: `'user.id'`. ##### Parameters ###### name `string` Column name, optionally prefixed with a table alias. ##### Returns [`Col`](../interfaces/Col.md) Column expression. ##### Example ```ts await Post.findAll({ attributes: [[fn('count', col('Post.id')), 'total']], group: [col('Post.userId')] }); ``` *** #### config > `readonly` **config**: [`ConnectionConfig`](../type-aliases/ConnectionConfig.md) Connection settings. *** #### fn > `readonly` **fn**: (`name`, ...`args`) => [`Fn`](../interfaces/Fn.md) SQL function call builder. Creates an SQL function call. String arguments are written into the SQL as escaped literals, like v6 (`COUNT('*')`, `concat_ws(' ', ...)`); other values are bound as parameters; expressions are rendered as is. ##### Parameters ###### name `string` Function name, e.g. `'lower'`. ###### args ...readonly `unknown`[] Function arguments. ##### Returns [`Fn`](../interfaces/Fn.md) Function call expression. ##### Example ```ts await User.findAll({ where: where(fn('lower', col('email')), 'a@b.c') }); ``` *** #### json > `readonly` **json**: (`conditionsOrPath`, `value?`) => [`Json`](../interfaces/Json.md) JSON path builder. Accesses a JSON(B) value by path (`json('meta.a.b')`) or builds JSON conditions (`json({ meta: { a: 1 } })`). ##### Parameters ###### conditionsOrPath `string` \| `object` Dot-separated path, starting with the attribute name, or a conditions object. ###### value? `string` \| `number` \| `boolean` \| `null` Value to compare with when a path is given. ##### Returns [`Json`](../interfaces/Json.md) JSON expression. ##### Example ```ts await User.findAll({ where: json('meta.address.city', 'Berlin') }); await User.findAll({ where: json({ meta: { active: true } }) }); ``` *** #### literal > `readonly` **literal**: (`val`) => [`Literal`](../interfaces/Literal.md) Raw SQL fragment builder. Creates a raw SQL fragment. The text is not escaped — never pass user input. ##### Parameters ###### val `string` SQL text. ##### Returns [`Literal`](../interfaces/Literal.md) Literal expression. ##### Example ```ts await Post.findAll({ order: [literal('"createdAt" DESC NULLS LAST')] }); ``` *** #### modelManager > `readonly` **modelManager**: `ModelManager` Registry of the defined models (a view on [Sequelize.models](#models)). *** #### models > `readonly` **models**: `Record`\<`string`, [`ModelStatic`](../type-aliases/ModelStatic.md)\<[`AnyModel`](../type-aliases/AnyModel.md)\>\> = `{}` Models registered with `define` / `Model.init`, by model name. *** #### options > `readonly` **options**: [`SequelizeOptions`](../type-aliases/SequelizeOptions.md) Normalized constructor options. *** #### or > `readonly` **or**: (...`conditions`) => [`WhereOptions`](../type-aliases/WhereOptions.md) Combines conditions with `OR`. Combines conditions with `OR` (Sequelize v6 `or`), for use inside `where`. ##### Parameters ###### conditions ...readonly [`WhereOptions`](../type-aliases/WhereOptions.md)[] Conditions to combine. ##### Returns [`WhereOptions`](../type-aliases/WhereOptions.md) A `{ [Op.or]: conditions }` condition usable as `where`. ##### Example ```ts await User.findAll({ where: or({ role: 'admin' }, { role: 'owner' }) }); ``` *** #### QueryTypes > `readonly` **QueryTypes**: `object` Result shapes of `query`, alias of [QueryTypes](../variables/QueryTypes.md). ##### BULKDELETE > `readonly` **BULKDELETE**: `"BULKDELETE"` = `'BULKDELETE'` Returns the number of affected rows. ##### BULKUPDATE > `readonly` **BULKUPDATE**: `"BULKUPDATE"` = `'BULKUPDATE'` Returns the number of affected rows. ##### DELETE > `readonly` **DELETE**: `"DELETE"` = `'DELETE'` Returns the rows of the statement (`[]` without `RETURNING`). ##### DESCRIBE > `readonly` **DESCRIBE**: `"DESCRIBE"` = `'DESCRIBE'` Returns `[rows, result]`. ##### FOREIGNKEYS > `readonly` **FOREIGNKEYS**: `"FOREIGNKEYS"` = `'FOREIGNKEYS'` Returns `[rows, result]`. ##### INSERT > `readonly` **INSERT**: `"INSERT"` = `'INSERT'` Returns `[rows, rowCount]`. ##### RAW > `readonly` **RAW**: `"RAW"` = `'RAW'` Returns `[rows, result]` (default). ##### SELECT > `readonly` **SELECT**: `"SELECT"` = `'SELECT'` Returns rows. ##### SHOWCONSTRAINTS > `readonly` **SHOWCONSTRAINTS**: `"SHOWCONSTRAINTS"` = `'SHOWCONSTRAINTS'` Returns `[rows, result]`. ##### SHOWINDEXES > `readonly` **SHOWINDEXES**: `"SHOWINDEXES"` = `'SHOWINDEXES'` Returns `[rows, result]`. ##### SHOWTABLES > `readonly` **SHOWTABLES**: `"SHOWTABLES"` = `'SHOWTABLES'` Returns `[rows, result]`. ##### UPDATE > `readonly` **UPDATE**: `"UPDATE"` = `'UPDATE'` Returns `[rows, rowCount]`. ##### UPSERT > `readonly` **UPSERT**: `"UPSERT"` = `'UPSERT'` Returns `[undefined, null]` like v6 on PostgreSQL (the statement runs; its rows are not returned). ##### VERSION > `readonly` **VERSION**: `"VERSION"` = `'VERSION'` Returns `[rows, result]`. *** #### validationFailed > `readonly` **validationFailed**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `validationFailed` hook: `sequelize.validationFailed(fn)` or `sequelize.validationFailed(name, fn)`. ##### Inherited from `InstanceHookAdders.validationFailed` *** #### Validator > `readonly` **Validator**: *typeof* `validator` = `validatorJs` The `validator` library used by the built-in validators. *** #### where > `readonly` **where**: [`WhereFactory`](../type-aliases/WhereFactory.md) Comparison builder. *** #### AccessDeniedError > `readonly` `static` **AccessDeniedError**: *typeof* [`AccessDeniedError`](AccessDeniedError.md) = `errorClasses.AccessDeniedError` Alias of the exported `AccessDeniedError`. *** #### afterAssociate > `readonly` `static` **afterAssociate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterAssociate` hook for every `Sequelize` instance: `Sequelize.afterAssociate(fn)` or `Sequelize.afterAssociate(name, fn)`. *** #### afterBulkCreate > `readonly` `static` **afterBulkCreate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterBulkCreate` hook for every `Sequelize` instance: `Sequelize.afterBulkCreate(fn)` or `Sequelize.afterBulkCreate(name, fn)`. ##### Inherited from `InstanceHookAdders.afterBulkCreate` *** #### afterBulkDestroy > `readonly` `static` **afterBulkDestroy**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterBulkDestroy` hook for every `Sequelize` instance: `Sequelize.afterBulkDestroy(fn)` or `Sequelize.afterBulkDestroy(name, fn)`. ##### Inherited from `InstanceHookAdders.afterBulkDestroy` *** #### afterBulkRestore > `readonly` `static` **afterBulkRestore**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterBulkRestore` hook for every `Sequelize` instance: `Sequelize.afterBulkRestore(fn)` or `Sequelize.afterBulkRestore(name, fn)`. ##### Inherited from `InstanceHookAdders.afterBulkRestore` *** #### afterBulkSync > `readonly` `static` **afterBulkSync**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterBulkSync` hook for every `Sequelize` instance: `Sequelize.afterBulkSync(fn)` or `Sequelize.afterBulkSync(name, fn)`. ##### Inherited from `InstanceHookAdders.afterBulkSync` *** #### afterBulkUpdate > `readonly` `static` **afterBulkUpdate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterBulkUpdate` hook for every `Sequelize` instance: `Sequelize.afterBulkUpdate(fn)` or `Sequelize.afterBulkUpdate(name, fn)`. ##### Inherited from `InstanceHookAdders.afterBulkUpdate` *** #### afterConnect > `readonly` `static` **afterConnect**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterConnect` hook for every `Sequelize` instance: `Sequelize.afterConnect(fn)` or `Sequelize.afterConnect(name, fn)`. ##### Inherited from `InstanceHookAdders.afterConnect` *** #### afterCreate > `readonly` `static` **afterCreate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterCreate` hook for every `Sequelize` instance: `Sequelize.afterCreate(fn)` or `Sequelize.afterCreate(name, fn)`. ##### Inherited from `InstanceHookAdders.afterCreate` *** #### afterDefine > `readonly` `static` **afterDefine**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterDefine` hook for every `Sequelize` instance: `Sequelize.afterDefine(fn)` or `Sequelize.afterDefine(name, fn)`. *** #### afterDestroy > `readonly` `static` **afterDestroy**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterDestroy` hook for every `Sequelize` instance: `Sequelize.afterDestroy(fn)` or `Sequelize.afterDestroy(name, fn)`. ##### Inherited from `InstanceHookAdders.afterDestroy` *** #### afterDisconnect > `readonly` `static` **afterDisconnect**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterDisconnect` hook for every `Sequelize` instance: `Sequelize.afterDisconnect(fn)` or `Sequelize.afterDisconnect(name, fn)`. *** #### afterFind > `readonly` `static` **afterFind**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterFind` hook for every `Sequelize` instance: `Sequelize.afterFind(fn)` or `Sequelize.afterFind(name, fn)`. ##### Inherited from `InstanceHookAdders.afterFind` *** #### afterInit > `readonly` `static` **afterInit**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterInit` hook for every `Sequelize` instance: `Sequelize.afterInit(fn)` or `Sequelize.afterInit(name, fn)`. *** #### afterPoolAcquire > `readonly` `static` **afterPoolAcquire**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterPoolAcquire` hook for every `Sequelize` instance: `Sequelize.afterPoolAcquire(fn)` or `Sequelize.afterPoolAcquire(name, fn)`. *** #### afterQuery > `readonly` `static` **afterQuery**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterQuery` hook for every `Sequelize` instance: `Sequelize.afterQuery(fn)` or `Sequelize.afterQuery(name, fn)`. *** #### afterRestore > `readonly` `static` **afterRestore**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterRestore` hook for every `Sequelize` instance: `Sequelize.afterRestore(fn)` or `Sequelize.afterRestore(name, fn)`. ##### Inherited from `InstanceHookAdders.afterRestore` *** #### afterSave > `readonly` `static` **afterSave**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterSave` hook for every `Sequelize` instance: `Sequelize.afterSave(fn)` or `Sequelize.afterSave(name, fn)`. ##### Inherited from `InstanceHookAdders.afterSave` *** #### afterSync > `readonly` `static` **afterSync**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterSync` hook for every `Sequelize` instance: `Sequelize.afterSync(fn)` or `Sequelize.afterSync(name, fn)`. ##### Inherited from `InstanceHookAdders.afterSync` *** #### afterUpdate > `readonly` `static` **afterUpdate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterUpdate` hook for every `Sequelize` instance: `Sequelize.afterUpdate(fn)` or `Sequelize.afterUpdate(name, fn)`. ##### Inherited from `InstanceHookAdders.afterUpdate` *** #### afterUpsert > `readonly` `static` **afterUpsert**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterUpsert` hook for every `Sequelize` instance: `Sequelize.afterUpsert(fn)` or `Sequelize.afterUpsert(name, fn)`. ##### Inherited from `InstanceHookAdders.afterUpsert` *** #### afterValidate > `readonly` `static` **afterValidate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `afterValidate` hook for every `Sequelize` instance: `Sequelize.afterValidate(fn)` or `Sequelize.afterValidate(name, fn)`. ##### Inherited from `InstanceHookAdders.afterValidate` *** #### AggregateError > `readonly` `static` **AggregateError**: *typeof* [`AggregateError`](AggregateError.md) = `errorClasses.AggregateError` Alias of the exported `AggregateError`. *** #### and > `readonly` `static` **and**: (...`conditions`) => [`WhereOptions`](../type-aliases/WhereOptions.md) Combines conditions with `AND`. Combines conditions with `AND` (Sequelize v6 `and`), for use inside `where`. ##### Parameters ###### conditions ...readonly [`WhereOptions`](../type-aliases/WhereOptions.md)[] Conditions to combine. ##### Returns [`WhereOptions`](../type-aliases/WhereOptions.md) A `{ [Op.and]: conditions }` condition usable as `where`. ##### Example ```ts await User.findAll({ where: and({ age: { [Op.gt]: 18 } }, { active: true }) }); ``` *** #### ARRAY > `readonly` `static` **ARRAY**: \<`T`\>(`subtype`) => `ArrayType` & [`ArrayDataType`](../postgrelize/namespaces/DataTypes/interfaces/ArrayDataType.md)\<`Element`\<`T`\>\> = `DataTypes.ARRAY` Alias of `DataTypes.ARRAY`. ##### Type Parameters ###### T `T` *extends* [`DataTypeInput`](../type-aliases/DataTypeInput.md) ##### Parameters ###### subtype `T` ##### Returns `ArrayType` & [`ArrayDataType`](../postgrelize/namespaces/DataTypes/interfaces/ArrayDataType.md)\<`Element`\<`T`\>\> *** #### Association > `readonly` `static` **Association**: *typeof* [`Association`](Association.md) Base class of the association classes. *** #### AssociationError > `readonly` `static` **AssociationError**: *typeof* [`AssociationError`](AssociationError.md) = `errorClasses.AssociationError` Alias of the exported `AssociationError`. *** #### BaseError > `readonly` `static` **BaseError**: *typeof* [`Error`](Error.md) = `errorClasses.BaseError` Alias of the exported `BaseError`. *** #### beforeAssociate > `readonly` `static` **beforeAssociate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeAssociate` hook for every `Sequelize` instance: `Sequelize.beforeAssociate(fn)` or `Sequelize.beforeAssociate(name, fn)`. *** #### beforeBulkCreate > `readonly` `static` **beforeBulkCreate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeBulkCreate` hook for every `Sequelize` instance: `Sequelize.beforeBulkCreate(fn)` or `Sequelize.beforeBulkCreate(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeBulkCreate` *** #### beforeBulkDestroy > `readonly` `static` **beforeBulkDestroy**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeBulkDestroy` hook for every `Sequelize` instance: `Sequelize.beforeBulkDestroy(fn)` or `Sequelize.beforeBulkDestroy(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeBulkDestroy` *** #### beforeBulkRestore > `readonly` `static` **beforeBulkRestore**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeBulkRestore` hook for every `Sequelize` instance: `Sequelize.beforeBulkRestore(fn)` or `Sequelize.beforeBulkRestore(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeBulkRestore` *** #### beforeBulkSync > `readonly` `static` **beforeBulkSync**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeBulkSync` hook for every `Sequelize` instance: `Sequelize.beforeBulkSync(fn)` or `Sequelize.beforeBulkSync(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeBulkSync` *** #### beforeBulkUpdate > `readonly` `static` **beforeBulkUpdate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeBulkUpdate` hook for every `Sequelize` instance: `Sequelize.beforeBulkUpdate(fn)` or `Sequelize.beforeBulkUpdate(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeBulkUpdate` *** #### beforeConnect > `readonly` `static` **beforeConnect**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeConnect` hook for every `Sequelize` instance: `Sequelize.beforeConnect(fn)` or `Sequelize.beforeConnect(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeConnect` *** #### beforeCount > `readonly` `static` **beforeCount**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeCount` hook for every `Sequelize` instance: `Sequelize.beforeCount(fn)` or `Sequelize.beforeCount(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeCount` *** #### beforeCreate > `readonly` `static` **beforeCreate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeCreate` hook for every `Sequelize` instance: `Sequelize.beforeCreate(fn)` or `Sequelize.beforeCreate(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeCreate` *** #### beforeDefine > `readonly` `static` **beforeDefine**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeDefine` hook for every `Sequelize` instance: `Sequelize.beforeDefine(fn)` or `Sequelize.beforeDefine(name, fn)`. *** #### beforeDestroy > `readonly` `static` **beforeDestroy**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeDestroy` hook for every `Sequelize` instance: `Sequelize.beforeDestroy(fn)` or `Sequelize.beforeDestroy(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeDestroy` *** #### beforeDisconnect > `readonly` `static` **beforeDisconnect**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeDisconnect` hook for every `Sequelize` instance: `Sequelize.beforeDisconnect(fn)` or `Sequelize.beforeDisconnect(name, fn)`. *** #### beforeFind > `readonly` `static` **beforeFind**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeFind` hook for every `Sequelize` instance: `Sequelize.beforeFind(fn)` or `Sequelize.beforeFind(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeFind` *** #### beforeFindAfterExpandIncludeAll > `readonly` `static` **beforeFindAfterExpandIncludeAll**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeFindAfterExpandIncludeAll` hook for every `Sequelize` instance: `Sequelize.beforeFindAfterExpandIncludeAll(fn)` or `Sequelize.beforeFindAfterExpandIncludeAll(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeFindAfterExpandIncludeAll` *** #### beforeFindAfterOptions > `readonly` `static` **beforeFindAfterOptions**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeFindAfterOptions` hook for every `Sequelize` instance: `Sequelize.beforeFindAfterOptions(fn)` or `Sequelize.beforeFindAfterOptions(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeFindAfterOptions` *** #### beforeInit > `readonly` `static` **beforeInit**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeInit` hook for every `Sequelize` instance: `Sequelize.beforeInit(fn)` or `Sequelize.beforeInit(name, fn)`. *** #### beforePoolAcquire > `readonly` `static` **beforePoolAcquire**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforePoolAcquire` hook for every `Sequelize` instance: `Sequelize.beforePoolAcquire(fn)` or `Sequelize.beforePoolAcquire(name, fn)`. *** #### beforeQuery > `readonly` `static` **beforeQuery**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeQuery` hook for every `Sequelize` instance: `Sequelize.beforeQuery(fn)` or `Sequelize.beforeQuery(name, fn)`. *** #### beforeRestore > `readonly` `static` **beforeRestore**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeRestore` hook for every `Sequelize` instance: `Sequelize.beforeRestore(fn)` or `Sequelize.beforeRestore(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeRestore` *** #### beforeSave > `readonly` `static` **beforeSave**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeSave` hook for every `Sequelize` instance: `Sequelize.beforeSave(fn)` or `Sequelize.beforeSave(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeSave` *** #### beforeSync > `readonly` `static` **beforeSync**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeSync` hook for every `Sequelize` instance: `Sequelize.beforeSync(fn)` or `Sequelize.beforeSync(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeSync` *** #### beforeUpdate > `readonly` `static` **beforeUpdate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeUpdate` hook for every `Sequelize` instance: `Sequelize.beforeUpdate(fn)` or `Sequelize.beforeUpdate(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeUpdate` *** #### beforeUpsert > `readonly` `static` **beforeUpsert**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeUpsert` hook for every `Sequelize` instance: `Sequelize.beforeUpsert(fn)` or `Sequelize.beforeUpsert(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeUpsert` *** #### beforeValidate > `readonly` `static` **beforeValidate**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `beforeValidate` hook for every `Sequelize` instance: `Sequelize.beforeValidate(fn)` or `Sequelize.beforeValidate(name, fn)`. ##### Inherited from `InstanceHookAdders.beforeValidate` *** #### BelongsTo > `readonly` `static` **BelongsTo**: *typeof* `BelongsTo` `belongsTo` association class. *** #### BelongsToMany > `readonly` `static` **BelongsToMany**: *typeof* `BelongsToMany` `belongsToMany` association class. *** #### BIGINT > `readonly` `static` **BIGINT**: `CallableInteger`\<[`BigIntDataType`](../postgrelize/namespaces/DataTypes/interfaces/BigIntDataType.md)\> = `DataTypes.BIGINT` Alias of `DataTypes.BIGINT`. *** #### BLOB > `readonly` `static` **BLOB**: `Callable`\<`BlobType`, \[`size?`: `"tiny"` \| `"medium"` \| `"long"`\], `BlobType`\> = `DataTypes.BLOB` Alias of `DataTypes.BLOB`. *** #### BOOLEAN > `readonly` `static` **BOOLEAN**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.BOOLEAN` Alias of `DataTypes.BOOLEAN`. *** #### BulkRecordError > `readonly` `static` **BulkRecordError**: *typeof* [`BulkRecordError`](BulkRecordError.md) = `errorClasses.BulkRecordError` Alias of the exported `BulkRecordError`. *** #### cast > `readonly` `static` **cast**: (`val`, `type`) => [`Cast`](../interfaces/Cast.md) Type cast builder. Creates a type cast `CAST(value AS type)`. ##### Parameters ###### val `unknown` Value or expression to cast. ###### type `string` PostgreSQL type name, e.g. `'integer'`. ##### Returns [`Cast`](../interfaces/Cast.md) Cast expression. ##### Example ```ts await Product.findAll({ attributes: [[cast(col('price'), 'integer'), 'rounded']] }); ``` *** #### CHAR > `readonly` `static` **CHAR**: `Callable`\<`CharType`, \[`length?`: `number`\], `CharType`\> = `DataTypes.CHAR` Alias of `DataTypes.CHAR`. *** #### CIDR > `readonly` `static` **CIDR**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.CIDR` Alias of `DataTypes.CIDR`. *** #### CITEXT > `readonly` `static` **CITEXT**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.CITEXT` Alias of `DataTypes.CITEXT`. *** #### col > `readonly` `static` **col**: (`name`) => [`Col`](../interfaces/Col.md) Column reference builder. Creates a column reference. Dots separate table and column: `'user.id'`. ##### Parameters ###### name `string` Column name, optionally prefixed with a table alias. ##### Returns [`Col`](../interfaces/Col.md) Column expression. ##### Example ```ts await Post.findAll({ attributes: [[fn('count', col('Post.id')), 'total']], group: [col('Post.userId')] }); ``` *** #### ConnectionAcquireTimeoutError > `readonly` `static` **ConnectionAcquireTimeoutError**: *typeof* [`ConnectionAcquireTimeoutError`](ConnectionAcquireTimeoutError.md) = `errorClasses.ConnectionAcquireTimeoutError` Alias of the exported `ConnectionAcquireTimeoutError`. *** #### ConnectionError > `readonly` `static` **ConnectionError**: *typeof* [`ConnectionError`](ConnectionError.md) = `errorClasses.ConnectionError` Alias of the exported `ConnectionError`. *** #### ConnectionRefusedError > `readonly` `static` **ConnectionRefusedError**: *typeof* [`ConnectionRefusedError`](ConnectionRefusedError.md) = `errorClasses.ConnectionRefusedError` Alias of the exported `ConnectionRefusedError`. *** #### ConnectionTimedOutError > `readonly` `static` **ConnectionTimedOutError**: *typeof* [`ConnectionTimedOutError`](ConnectionTimedOutError.md) = `errorClasses.ConnectionTimedOutError` Alias of the exported `ConnectionTimedOutError`. *** #### DatabaseError > `readonly` `static` **DatabaseError**: *typeof* [`DatabaseError`](DatabaseError.md) = `errorClasses.DatabaseError` Alias of the exported `DatabaseError`. *** #### DataTypes > `readonly` `static` **DataTypes**: `object` Column types. ##### ARRAY > `readonly` **ARRAY**: \<`T`\>(`subtype`) => `ArrayType` & [`ArrayDataType`](../postgrelize/namespaces/DataTypes/interfaces/ArrayDataType.md)\<`Element`\<`T`\>\> `type[]`, e.g. `DataTypes.ARRAY(DataTypes.TEXT)`. ###### Type Parameters ###### T `T` *extends* [`DataTypeInput`](../type-aliases/DataTypeInput.md) ###### Parameters ###### subtype `T` ###### Returns `ArrayType` & [`ArrayDataType`](../postgrelize/namespaces/DataTypes/interfaces/ArrayDataType.md)\<`Element`\<`T`\>\> ##### BIGINT > `readonly` **BIGINT**: `CallableInteger`\<[`BigIntDataType`](../postgrelize/namespaces/DataTypes/interfaces/BigIntDataType.md)\> `BIGINT`; values are returned as strings. ##### BIT > `readonly` **BIT**: `Callable`\<`BitType`, \[`length?`: `number`\], `BitType`\> `BIT(length)`, default length 1; values are strings of `0` and `1`. PostgreSQL extension. ##### BLOB > `readonly` **BLOB**: `Callable`\<`BlobType`, \[`size?`: `"tiny"` \| `"medium"` \| `"long"`\], `BlobType`\> `BYTEA`; values are `Buffer`s. ##### BOOLEAN > `readonly` **BOOLEAN**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `BOOLEAN`. ##### BOX > `readonly` **BOX**: `GeometricType` `BOX`; values are `[corner, corner]` points (the server returns the upper right first). PostgreSQL extension. ##### CHAR > `readonly` **CHAR**: `Callable`\<`CharType`, \[`length?`: `number`\], `CharType`\> `CHAR(length)`, default length 255. ##### CIDR > `readonly` **CIDR**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `CIDR`. ##### CIRCLE > `readonly` **CIRCLE**: `GeometricType` `CIRCLE`; values are `{ x, y, radius }`. PostgreSQL extension. ##### CITEXT > `readonly` **CITEXT**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `CITEXT` (case-insensitive text, requires the `citext` extension). ##### COMPOSITE > `readonly` **COMPOSITE**: (`name`, `fields`) => `CompositeType` Composite type, e.g. `DataTypes.COMPOSITE('address', { street: DataTypes.TEXT, zip: DataTypes.INTEGER })`; values are objects keyed by field name. Create the type first with `createSql()`. PostgreSQL extension. ###### Parameters ###### name `string` ###### fields `Readonly`\<`Record`\<`string`, [`DataTypeInput`](../type-aliases/DataTypeInput.md)\>\> ###### Returns `CompositeType` ##### DATE > `readonly` **DATE**: `Callable`\<`DateType`, \[`fsp?`: `number`\], `DateType`\> `TIMESTAMP WITH TIME ZONE`; values are `Date` objects. ##### DATEONLY > `readonly` **DATEONLY**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `DATE`; values are `'YYYY-MM-DD'` strings. ##### DECIMAL > `readonly` **DECIMAL**: `Callable`\<`DecimalType`, \[`digits?`: `number`, `scale?`: `number`\], `DecimalType`\> `DECIMAL(precision, scale)`; values are returned as strings. ##### DOUBLE > `readonly` **DOUBLE**: `Callable`\<`ScalarType`, \[`length?`: `number`, `decimals?`: `number`\], [`DoubleDataType`](../postgrelize/namespaces/DataTypes/interfaces/DoubleDataType.md)\> `DOUBLE PRECISION`. ##### DOUBLE PRECISION > `readonly` **DOUBLE PRECISION**: `Callable`\<`ScalarType`, \[`length?`: `number`, `decimals?`: `number`\], [`DoubleDataType`](../postgrelize/namespaces/DataTypes/interfaces/DoubleDataType.md)\> `DOUBLE PRECISION` (v6 alias of `DOUBLE`). ##### ENUM > `readonly` **ENUM**: \<`T`\>(...`args`) => `EnumType` & [`EnumDataType`](../postgrelize/namespaces/DataTypes/interfaces/EnumDataType.md)\<`T`\> Enumerated values: `DataTypes.ENUM('a', 'b')` or `DataTypes.ENUM({ values: ['a', 'b'] })`. ###### Type Parameters ###### T `T` *extends* `string` = `string` ###### Parameters ###### args ...readonly (`T` \| readonly `T`[] \| `Readonly`\<\{ `values`: readonly `T`[]; \}\>)[] ###### Returns `EnumType` & [`EnumDataType`](../postgrelize/namespaces/DataTypes/interfaces/EnumDataType.md)\<`T`\> ##### FLOAT > `readonly` **FLOAT**: `Callable`\<`FloatType`, \[`digits?`: `number`\], `FloatType`\> `FLOAT(precision)`. ##### GEOGRAPHY > `readonly` **GEOGRAPHY**: `Callable`\<`SpatialType`, \[`geographyType?`: `string`, `srid?`: `number`\], `SpatialType`\> PostGIS `GEOGRAPHY(type, srid)`. ##### GEOMETRY > `readonly` **GEOMETRY**: `Callable`\<`SpatialType`, \[`geometryType?`: `string`, `srid?`: `number`\], `SpatialType`\> PostGIS `GEOMETRY(type, srid)`. ##### HSTORE > `readonly` **HSTORE**: `Callable`\<`HstoreType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `HSTORE` (requires the `hstore` extension); values are objects of string (or `null`) values, like Sequelize v6. ##### INET > `readonly` **INET**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `INET`. ##### INTEGER > `readonly` **INTEGER**: `CallableInteger`\<[`IntegerDataType`](../postgrelize/namespaces/DataTypes/interfaces/IntegerDataType.md)\> `INTEGER`. ##### INTERVAL > `readonly` **INTERVAL**: `ScalarType` `INTERVAL`; values are PostgreSQL interval strings (e.g. `'1 day 02:00:00'`). PostgreSQL extension. ##### JSON > `readonly` **JSON**: `Callable`\<`JsonType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `JSON`. ##### JSONB > `readonly` **JSONB**: `Callable`\<`JsonType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `JSONB`. ##### LINE > `readonly` **LINE**: `GeometricType` `LINE` (`a·x + b·y + c = 0`); values are `{ a, b, c }`. PostgreSQL extension. ##### LSEG > `readonly` **LSEG**: `GeometricType` `LSEG` line segment; values are `[start, end]` points. PostgreSQL extension. ##### LTREE > `readonly` **LTREE**: `ScalarType` `LTREE` label path (requires the `ltree` extension); values are strings like `'Top.Science'`. PostgreSQL extension. ##### MACADDR > `readonly` **MACADDR**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `MACADDR`. ##### MACADDR8 > `readonly` **MACADDR8**: `ScalarType` `MACADDR8` (EUI-64 address). PostgreSQL extension. ##### MEDIUMINT > `readonly` **MEDIUMINT**: `CallableInteger`\<[`MediumIntegerDataType`](../postgrelize/namespaces/DataTypes/interfaces/MediumIntegerDataType.md)\> Mapped to `INTEGER` (PostgreSQL has no `MEDIUMINT`). ##### MONEY > `readonly` **MONEY**: `ScalarType` `MONEY`; values are strings formatted by the server's `lc_monetary` (e.g. `'$12.50'`); numbers are accepted on write. PostgreSQL extension. ##### MULTIRANGE > `readonly` **MULTIRANGE**: `Callable`\<`MultirangeType`, \[`subtype`: [`DataTypeInput`](../type-aliases/DataTypeInput.md)\], `MultirangeType`\> Multirange type (PostgreSQL 14+), e.g. `DataTypes.MULTIRANGE(DataTypes.INTEGER)` → `INT4MULTIRANGE`; values are arrays of `[lower, upper]` ranges. PostgreSQL extension. ##### NOW > `readonly` **NOW**: [`DefaultValueGenerator`](../interfaces/DefaultValueGenerator.md) Default value: current timestamp. ##### NUMBER > `readonly` **NUMBER**: `Callable`\<`DecimalType`, \[`digits?`: `number`, `scale?`: `number`\], `DecimalType`\> Alias of `DECIMAL`. ##### NUMERIC > `readonly` **NUMERIC**: `Callable`\<`DecimalType`, \[`digits?`: `number`, `scale?`: `number`\], `DecimalType`\> Alias of `DECIMAL` (v6 `NUMERIC`). ##### PATH > `readonly` **PATH**: `GeometricType` `PATH`; values are `{ points, closed }`. PostgreSQL extension. ##### POINT > `readonly` **POINT**: `GeometricType` `POINT`; values are `{ x, y }`. PostgreSQL extension. ##### POLYGON > `readonly` **POLYGON**: `GeometricType` `POLYGON`; values are arrays of `{ x, y }` points. PostgreSQL extension. ##### RANGE > `readonly` **RANGE**: `RangeFactory` Range type, e.g. `DataTypes.RANGE(DataTypes.INTEGER)` → `INT4RANGE`. ##### REAL > `readonly` **REAL**: `Callable`\<`ScalarType`, \[`length?`: `number`, `decimals?`: `number`\], [`RealDataType`](../postgrelize/namespaces/DataTypes/interfaces/RealDataType.md)\> `REAL`. ##### SMALLINT > `readonly` **SMALLINT**: `CallableInteger`\<[`SmallIntegerDataType`](../postgrelize/namespaces/DataTypes/interfaces/SmallIntegerDataType.md)\> `SMALLINT`. ##### STRING > `readonly` **STRING**: `Callable`\<`StringType`, \[`length?`: `number`\], `StringType`\> `VARCHAR(length)`, default length 255. ##### TEXT > `readonly` **TEXT**: `Callable`\<`TextType`, \[`size?`: `"tiny"` \| `"medium"` \| `"long"`\], `TextType`\> `TEXT`. The size argument is accepted for compatibility and ignored. ##### TIME > `readonly` **TIME**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `TIME`. ##### TIMESTAMP > `readonly` **TIMESTAMP**: `Callable`\<`TimestampType`, \[`fsp?`: `number`\], `TimestampType`\> `TIMESTAMP WITHOUT TIME ZONE`; values are `Date` objects whose local wall-clock time is the stored time. PostgreSQL extension. ##### TINYINT > `readonly` **TINYINT**: `CallableInteger`\<[`TinyIntegerDataType`](../postgrelize/namespaces/DataTypes/interfaces/TinyIntegerDataType.md)\> Mapped to `SMALLINT` (PostgreSQL has no `TINYINT`). ##### TSQUERY > `readonly` **TSQUERY**: `ScalarType` `TSQUERY`; values are full-text query strings. PostgreSQL extension. ##### TSVECTOR > `readonly` **TSVECTOR**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `TSVECTOR`. ##### UUID > `readonly` **UUID**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `UUID`. ##### UUIDV4 > `readonly` **UUIDV4**: [`DefaultValueGenerator`](../interfaces/DefaultValueGenerator.md) Default value: random UUID v4 generated on the client. ##### VARBIT > `readonly` **VARBIT**: `Callable`\<`BitType`, \[`length?`: `number`\], `BitType`\> `BIT VARYING(length)`, unlimited without a length; values are strings of `0` and `1`. PostgreSQL extension. ##### VIRTUAL > `readonly` **VIRTUAL**: `VirtualFactory` Attribute that is not stored in the database (computed by getters/setters). ##### XML > `readonly` **XML**: `ScalarType` `XML`; values are XML text. PostgreSQL extension. *** #### DATE > `readonly` `static` **DATE**: `Callable`\<`DateType`, \[`fsp?`: `number`\], `DateType`\> = `DataTypes.DATE` Alias of `DataTypes.DATE`. *** #### DATEONLY > `readonly` `static` **DATEONLY**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.DATEONLY` Alias of `DataTypes.DATEONLY`. *** #### DECIMAL > `readonly` `static` **DECIMAL**: `Callable`\<`DecimalType`, \[`digits?`: `number`, `scale?`: `number`\], `DecimalType`\> = `DataTypes.DECIMAL` Alias of `DataTypes.DECIMAL`. *** #### Deferrable > `readonly` `static` **Deferrable**: `object` `Deferrable` constraint modes. ##### INITIALLY\_DEFERRED > `readonly` **INITIALLY\_DEFERRED**: `Readonly`\<`Readonly`\<\{ `sql`: `string`; \}\>\> `DEFERRABLE INITIALLY DEFERRED`. ##### INITIALLY\_IMMEDIATE > `readonly` **INITIALLY\_IMMEDIATE**: `Readonly`\<`Readonly`\<\{ `sql`: `string`; \}\>\> `DEFERRABLE INITIALLY IMMEDIATE`. ##### NOT > `readonly` **NOT**: `Readonly`\<`Readonly`\<\{ `sql`: `string`; \}\>\> `NOT DEFERRABLE`. ##### SET\_DEFERRED > `readonly` **SET\_DEFERRED**: `ConstraintModeSetter` `SET CONSTRAINTS ... DEFERRED`: for the `deferrable` option of `sequelize.transaction()`, defers the given constraints (all of them when used bare or called without names) for the rest of the transaction. ##### SET\_IMMEDIATE > `readonly` **SET\_IMMEDIATE**: `ConstraintModeSetter` `SET CONSTRAINTS ... IMMEDIATE`: the counterpart of `SET_DEFERRED`. *** #### DOUBLE > `readonly` `static` **DOUBLE**: `Callable`\<`ScalarType`, \[`length?`: `number`, `decimals?`: `number`\], [`DoubleDataType`](../postgrelize/namespaces/DataTypes/interfaces/DoubleDataType.md)\> = `DataTypes.DOUBLE` Alias of `DataTypes.DOUBLE`. *** #### DOUBLE PRECISION > `readonly` `static` **DOUBLE PRECISION**: `Callable`\<`ScalarType`, \[`length?`: `number`, `decimals?`: `number`\], [`DoubleDataType`](../postgrelize/namespaces/DataTypes/interfaces/DoubleDataType.md)\> Alias of `DataTypes.DOUBLE`. *** #### EagerLoadingError > `readonly` `static` **EagerLoadingError**: *typeof* [`EagerLoadingError`](EagerLoadingError.md) = `errorClasses.EagerLoadingError` Alias of the exported `EagerLoadingError`. *** #### EmptyResultError > `readonly` `static` **EmptyResultError**: *typeof* [`EmptyResultError`](EmptyResultError.md) = `errorClasses.EmptyResultError` Alias of the exported `EmptyResultError`. *** #### ENUM > `readonly` `static` **ENUM**: \<`T`\>(...`args`) => `EnumType` & [`EnumDataType`](../postgrelize/namespaces/DataTypes/interfaces/EnumDataType.md)\<`T`\> = `DataTypes.ENUM` Alias of `DataTypes.ENUM`. ##### Type Parameters ###### T `T` *extends* `string` = `string` ##### Parameters ###### args ...readonly (`T` \| readonly `T`[] \| `Readonly`\<\{ `values`: readonly `T`[]; \}\>)[] ##### Returns `EnumType` & [`EnumDataType`](../postgrelize/namespaces/DataTypes/interfaces/EnumDataType.md)\<`T`\> *** #### Error > `readonly` `static` **Error**: *typeof* [`Error`](Error.md) = `errorClasses.BaseError` Alias of `BaseError`. *** #### ExclusionConstraintError > `readonly` `static` **ExclusionConstraintError**: *typeof* [`ExclusionConstraintError`](ExclusionConstraintError.md) = `errorClasses.ExclusionConstraintError` Alias of the exported `ExclusionConstraintError`. *** #### FLOAT > `readonly` `static` **FLOAT**: `Callable`\<`FloatType`, \[`digits?`: `number`\], `FloatType`\> = `DataTypes.FLOAT` Alias of `DataTypes.FLOAT`. *** #### fn > `readonly` `static` **fn**: (`name`, ...`args`) => [`Fn`](../interfaces/Fn.md) SQL function call builder. Creates an SQL function call. String arguments are written into the SQL as escaped literals, like v6 (`COUNT('*')`, `concat_ws(' ', ...)`); other values are bound as parameters; expressions are rendered as is. ##### Parameters ###### name `string` Function name, e.g. `'lower'`. ###### args ...readonly `unknown`[] Function arguments. ##### Returns [`Fn`](../interfaces/Fn.md) Function call expression. ##### Example ```ts await User.findAll({ where: where(fn('lower', col('email')), 'a@b.c') }); ``` *** #### ForeignKeyConstraintError > `readonly` `static` **ForeignKeyConstraintError**: *typeof* [`ForeignKeyConstraintError`](ForeignKeyConstraintError.md) = `errorClasses.ForeignKeyConstraintError` Alias of the exported `ForeignKeyConstraintError`. *** #### GEOGRAPHY > `readonly` `static` **GEOGRAPHY**: `Callable`\<`SpatialType`, \[`geographyType?`: `string`, `srid?`: `number`\], `SpatialType`\> = `DataTypes.GEOGRAPHY` Alias of `DataTypes.GEOGRAPHY`. *** #### GEOMETRY > `readonly` `static` **GEOMETRY**: `Callable`\<`SpatialType`, \[`geometryType?`: `string`, `srid?`: `number`\], `SpatialType`\> = `DataTypes.GEOMETRY` Alias of `DataTypes.GEOMETRY`. *** #### HasMany > `readonly` `static` **HasMany**: *typeof* `HasMany` `hasMany` association class. *** #### HasOne > `readonly` `static` **HasOne**: *typeof* `HasOne` `hasOne` association class. *** #### HostNotFoundError > `readonly` `static` **HostNotFoundError**: *typeof* [`HostNotFoundError`](HostNotFoundError.md) = `errorClasses.HostNotFoundError` Alias of the exported `HostNotFoundError`. *** #### HostNotReachableError > `readonly` `static` **HostNotReachableError**: *typeof* [`HostNotReachableError`](HostNotReachableError.md) = `errorClasses.HostNotReachableError` Alias of the exported `HostNotReachableError`. *** #### HSTORE > `readonly` `static` **HSTORE**: `Callable`\<`HstoreType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.HSTORE` Alias of `DataTypes.HSTORE`. *** #### INET > `readonly` `static` **INET**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.INET` Alias of `DataTypes.INET`. *** #### InstanceError > `readonly` `static` **InstanceError**: *typeof* [`InstanceError`](InstanceError.md) = `errorClasses.InstanceError` Alias of the exported `InstanceError`. *** #### INTEGER > `readonly` `static` **INTEGER**: `CallableInteger`\<[`IntegerDataType`](../postgrelize/namespaces/DataTypes/interfaces/IntegerDataType.md)\> = `DataTypes.INTEGER` Alias of `DataTypes.INTEGER`. *** #### InvalidConnectionError > `readonly` `static` **InvalidConnectionError**: *typeof* [`InvalidConnectionError`](InvalidConnectionError.md) = `errorClasses.InvalidConnectionError` Alias of the exported `InvalidConnectionError`. *** #### json > `readonly` `static` **json**: (`conditionsOrPath`, `value?`) => [`Json`](../interfaces/Json.md) JSON path builder. Accesses a JSON(B) value by path (`json('meta.a.b')`) or builds JSON conditions (`json({ meta: { a: 1 } })`). ##### Parameters ###### conditionsOrPath `string` \| `object` Dot-separated path, starting with the attribute name, or a conditions object. ###### value? `string` \| `number` \| `boolean` \| `null` Value to compare with when a path is given. ##### Returns [`Json`](../interfaces/Json.md) JSON expression. ##### Example ```ts await User.findAll({ where: json('meta.address.city', 'Berlin') }); await User.findAll({ where: json({ meta: { active: true } }) }); ``` *** #### JSON > `readonly` `static` **JSON**: `Callable`\<`JsonType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.JSON` Alias of `DataTypes.JSON`. *** #### JSONB > `readonly` `static` **JSONB**: `Callable`\<`JsonType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.JSONB` Alias of `DataTypes.JSONB`. *** #### literal > `readonly` `static` **literal**: (`val`) => [`Literal`](../interfaces/Literal.md) Raw SQL fragment builder. Creates a raw SQL fragment. The text is not escaped — never pass user input. ##### Parameters ###### val `string` SQL text. ##### Returns [`Literal`](../interfaces/Literal.md) Literal expression. ##### Example ```ts await Post.findAll({ order: [literal('"createdAt" DESC NULLS LAST')] }); ``` *** #### MACADDR > `readonly` `static` **MACADDR**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.MACADDR` Alias of `DataTypes.MACADDR`. *** #### MEDIUMINT > `readonly` `static` **MEDIUMINT**: `CallableInteger`\<[`MediumIntegerDataType`](../postgrelize/namespaces/DataTypes/interfaces/MediumIntegerDataType.md)\> = `DataTypes.MEDIUMINT` Alias of `DataTypes.MEDIUMINT`. *** #### Model > `readonly` `static` **Model**: *typeof* [`Model`](Model.md) Model base class. *** #### NOW > `readonly` `static` **NOW**: [`DefaultValueGenerator`](../interfaces/DefaultValueGenerator.md) = `DataTypes.NOW` Alias of `DataTypes.NOW`. *** #### NUMBER > `readonly` `static` **NUMBER**: `Callable`\<`DecimalType`, \[`digits?`: `number`, `scale?`: `number`\], `DecimalType`\> = `DataTypes.NUMBER` Alias of `DataTypes.NUMBER`. *** #### NUMERIC > `readonly` `static` **NUMERIC**: `Callable`\<`DecimalType`, \[`digits?`: `number`, `scale?`: `number`\], `DecimalType`\> = `DataTypes.NUMERIC` Alias of `DataTypes.NUMERIC`. *** #### Op > `readonly` `static` **Op**: `object` Query operators. ##### adjacent > **adjacent**: *typeof* `adjacent` `-|-` — ranges are adjacent. ##### all > **all**: *typeof* `all` `ALL (ARRAY[...])`, combined with a comparison operator. ##### and > **and**: *typeof* `and` Logical AND of nested conditions. ##### any > **any**: *typeof* `any` `ANY (ARRAY[...])`, combined with a comparison operator. ##### between > **between**: *typeof* `between` `BETWEEN a AND b`, value is `[a, b]`. ##### col > **col**: *typeof* `col` Compares with another column, value is a column reference such as `'user.id'`. ##### contained > **contained**: *typeof* `contained` `<@` — array, range or jsonb is contained by the value. ##### containedOrEqual > **containedOrEqual**: *typeof* `containedOrEqual` `<<=` — inet/cidr subnet is contained within or equals the value. PostgreSQL extension. ##### contains > **contains**: *typeof* `contains` `@>` — array, range or jsonb contains the value. ##### containsOrEqual > **containsOrEqual**: *typeof* `containsOrEqual` `>>=` — inet/cidr subnet contains or equals the value. PostgreSQL extension. ##### endsWith > **endsWith**: *typeof* `endsWith` `LIKE '%value'`. ##### eq > **eq**: *typeof* `eq` `= value`; `IS NULL` when the value is `null`. ##### gt > **gt**: *typeof* `gt` `> value`. ##### gte > **gte**: *typeof* `gte` `>= value`. ##### hasAllKeys > **hasAllKeys**: *typeof* `hasAllKeys` jsonb `?&` — all of the keys exist. PostgreSQL extension. ##### hasAnyKeys > **hasAnyKeys**: *typeof* `hasAnyKeys` jsonb `?|` — any of the keys exist. PostgreSQL extension. ##### hasKey > **hasKey**: *typeof* `hasKey` jsonb `?` — top-level key exists. PostgreSQL extension. ##### iLike > **iLike**: *typeof* `iLike` `ILIKE pattern`. ##### in > `readonly` **in**: *typeof* `inOp` = `inOp` `IN (...)`; long lists compile to `= ANY($n)`. ##### iRegexp > **iRegexp**: *typeof* `iRegexp` `~* pattern` (case-insensitive regular expression). ##### is > **is**: *typeof* `is` `IS value`, for `null`, `true` or `false`. ##### isDistinctFrom > **isDistinctFrom**: *typeof* `isDistinctFrom` `IS DISTINCT FROM value` (null-safe `<>`). PostgreSQL extension. ##### isNotDistinctFrom > **isNotDistinctFrom**: *typeof* `isNotDistinctFrom` `IS NOT DISTINCT FROM value` (null-safe `=`). PostgreSQL extension. ##### join > **join**: *typeof* `join` Reserved by Sequelize v6 for internal use. ##### jsonPathExists > **jsonPathExists**: *typeof* `jsonPathExists` jsonb `@?` — the jsonpath returns any item; the value is a jsonpath string. PostgreSQL extension. ##### like > **like**: *typeof* `like` `LIKE pattern`. ##### lt > **lt**: *typeof* `lt` `< value`. ##### lte > **lte**: *typeof* `lte` `<= value`. ##### match > **match**: *typeof* `match` `@@` — tsvector matches tsquery. ##### ne > **ne**: *typeof* `ne` `<> value`; `IS NOT NULL` when the value is `null`. ##### noExtendLeft > **noExtendLeft**: *typeof* `noExtendLeft` `&>` — range does not extend to the left of the value. ##### noExtendRight > **noExtendRight**: *typeof* `noExtendRight` `&<` — range does not extend to the right of the value. ##### not > **not**: *typeof* `not` `IS NOT value` for `null`/booleans, otherwise negates a nested condition. ##### notBetween > **notBetween**: *typeof* `notBetween` `NOT BETWEEN a AND b`, value is `[a, b]`. ##### notILike > **notILike**: *typeof* `notILike` `NOT ILIKE pattern`. ##### notIn > **notIn**: *typeof* `notIn` `NOT IN (...)`; long lists compile to `<> ALL($n)`. ##### notIRegexp > **notIRegexp**: *typeof* `notIRegexp` `!~* pattern`. ##### notLike > **notLike**: *typeof* `notLike` `NOT LIKE pattern`. ##### notRegexp > **notRegexp**: *typeof* `notRegexp` `!~ pattern`. ##### notSimilarTo > **notSimilarTo**: *typeof* `notSimilarTo` `NOT SIMILAR TO pattern`. PostgreSQL extension. ##### or > **or**: *typeof* `or` Logical OR of nested conditions. ##### overlap > **overlap**: *typeof* `overlap` `&&` — arrays or ranges overlap. ##### placeholder > **placeholder**: *typeof* `placeholder` Reserved by Sequelize v6 for internal use. ##### regexp > **regexp**: *typeof* `regexp` `~ pattern` (POSIX regular expression). ##### similarTo > **similarTo**: *typeof* `similarTo` `SIMILAR TO pattern` (SQL regular expression). PostgreSQL extension. ##### startsWith > **startsWith**: *typeof* `startsWith` `LIKE 'value%'`. ##### strictLeft > **strictLeft**: *typeof* `strictLeft` `<<` — range is strictly left of the value. ##### strictRight > **strictRight**: *typeof* `strictRight` `>>` — range is strictly right of the value. ##### substring > **substring**: *typeof* `substring` `LIKE '%value%'`. ##### trigramHasSimilarStrictWord > **trigramHasSimilarStrictWord**: *typeof* `trigramHasSimilarStrictWord` `%>>` — `pg_trgm`: the column has a strictly similar word of the value. PostgreSQL extension. ##### trigramHasSimilarWord > **trigramHasSimilarWord**: *typeof* `trigramHasSimilarWord` `%>` — `pg_trgm`: the column has a part similar to the value (commutator of `<%`). PostgreSQL extension. ##### trigramSimilar > **trigramSimilar**: *typeof* `trigramSimilar` `%` — `pg_trgm` trigram similarity above `pg_trgm.similarity_threshold`. PostgreSQL extension. ##### trigramStrictWordSimilar > **trigramStrictWordSimilar**: *typeof* `trigramStrictWordSimilar` `<<%` — `pg_trgm`: the column is strictly similar to a word of the value. PostgreSQL extension. ##### trigramWordSimilar > **trigramWordSimilar**: *typeof* `trigramWordSimilar` `<%` — `pg_trgm`: the column is similar to a part of the value (word similarity above the threshold). PostgreSQL extension. ##### values > **values**: *typeof* `values` `VALUES (...)` list for `Op.any` / `Op.all`. *** #### OptimisticLockError > `readonly` `static` **OptimisticLockError**: *typeof* [`OptimisticLockError`](OptimisticLockError.md) = `errorClasses.OptimisticLockError` Alias of the exported `OptimisticLockError`. *** #### options > `readonly` `static` **options**: `object` Static options of v6 (`Sequelize.options.hooks`); assigning an empty object to `hooks` removes every static hook. ##### hooks > **hooks**: `Readonly`\<`Record`\<`string`, `unknown`\>\> Static hooks as v6 stores them; reading gives an empty object, assigning an empty object removes every static hook. *** #### or > `readonly` `static` **or**: (...`conditions`) => [`WhereOptions`](../type-aliases/WhereOptions.md) Combines conditions with `OR`. Combines conditions with `OR` (Sequelize v6 `or`), for use inside `where`. ##### Parameters ###### conditions ...readonly [`WhereOptions`](../type-aliases/WhereOptions.md)[] Conditions to combine. ##### Returns [`WhereOptions`](../type-aliases/WhereOptions.md) A `{ [Op.or]: conditions }` condition usable as `where`. ##### Example ```ts await User.findAll({ where: or({ role: 'admin' }, { role: 'owner' }) }); ``` *** #### QueryError > `readonly` `static` **QueryError**: *typeof* [`QueryError`](QueryError.md) = `errorClasses.QueryError` Alias of the exported `QueryError`. *** #### QueryInterface > `readonly` `static` **QueryInterface**: *typeof* [`QueryInterface`](QueryInterface.md) Schema API class. *** #### QueryTypes > `readonly` `static` **QueryTypes**: `object` Result shapes accepted by the `type` option of [Sequelize.query](#query), e.g. `QueryTypes.SELECT`. ##### BULKDELETE > `readonly` **BULKDELETE**: `"BULKDELETE"` = `'BULKDELETE'` Returns the number of affected rows. ##### BULKUPDATE > `readonly` **BULKUPDATE**: `"BULKUPDATE"` = `'BULKUPDATE'` Returns the number of affected rows. ##### DELETE > `readonly` **DELETE**: `"DELETE"` = `'DELETE'` Returns the rows of the statement (`[]` without `RETURNING`). ##### DESCRIBE > `readonly` **DESCRIBE**: `"DESCRIBE"` = `'DESCRIBE'` Returns `[rows, result]`. ##### FOREIGNKEYS > `readonly` **FOREIGNKEYS**: `"FOREIGNKEYS"` = `'FOREIGNKEYS'` Returns `[rows, result]`. ##### INSERT > `readonly` **INSERT**: `"INSERT"` = `'INSERT'` Returns `[rows, rowCount]`. ##### RAW > `readonly` **RAW**: `"RAW"` = `'RAW'` Returns `[rows, result]` (default). ##### SELECT > `readonly` **SELECT**: `"SELECT"` = `'SELECT'` Returns rows. ##### SHOWCONSTRAINTS > `readonly` **SHOWCONSTRAINTS**: `"SHOWCONSTRAINTS"` = `'SHOWCONSTRAINTS'` Returns `[rows, result]`. ##### SHOWINDEXES > `readonly` **SHOWINDEXES**: `"SHOWINDEXES"` = `'SHOWINDEXES'` Returns `[rows, result]`. ##### SHOWTABLES > `readonly` **SHOWTABLES**: `"SHOWTABLES"` = `'SHOWTABLES'` Returns `[rows, result]`. ##### UPDATE > `readonly` **UPDATE**: `"UPDATE"` = `'UPDATE'` Returns `[rows, rowCount]`. ##### UPSERT > `readonly` **UPSERT**: `"UPSERT"` = `'UPSERT'` Returns `[undefined, null]` like v6 on PostgreSQL (the statement runs; its rows are not returned). ##### VERSION > `readonly` **VERSION**: `"VERSION"` = `'VERSION'` Returns `[rows, result]`. *** #### RANGE > `readonly` `static` **RANGE**: `RangeFactory` = `DataTypes.RANGE` Alias of `DataTypes.RANGE`. *** #### REAL > `readonly` `static` **REAL**: `Callable`\<`ScalarType`, \[`length?`: `number`, `decimals?`: `number`\], [`RealDataType`](../postgrelize/namespaces/DataTypes/interfaces/RealDataType.md)\> = `DataTypes.REAL` Alias of `DataTypes.REAL`. *** #### SequelizeScopeError > `readonly` `static` **SequelizeScopeError**: *typeof* [`SequelizeScopeError`](SequelizeScopeError.md) = `errorClasses.SequelizeScopeError` Alias of the exported `SequelizeScopeError`. *** #### SMALLINT > `readonly` `static` **SMALLINT**: `CallableInteger`\<[`SmallIntegerDataType`](../postgrelize/namespaces/DataTypes/interfaces/SmallIntegerDataType.md)\> = `DataTypes.SMALLINT` Alias of `DataTypes.SMALLINT`. *** #### STRING > `readonly` `static` **STRING**: `Callable`\<`StringType`, \[`length?`: `number`\], `StringType`\> = `DataTypes.STRING` Alias of `DataTypes.STRING`. *** #### TEXT > `readonly` `static` **TEXT**: `Callable`\<`TextType`, \[`size?`: `"tiny"` \| `"medium"` \| `"long"`\], `TextType`\> = `DataTypes.TEXT` Alias of `DataTypes.TEXT`. *** #### TIME > `readonly` `static` **TIME**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.TIME` Alias of `DataTypes.TIME`. *** #### TimeoutError > `readonly` `static` **TimeoutError**: *typeof* [`TimeoutError`](TimeoutError.md) = `errorClasses.TimeoutError` Alias of the exported `TimeoutError`. *** #### TINYINT > `readonly` `static` **TINYINT**: `CallableInteger`\<[`TinyIntegerDataType`](../postgrelize/namespaces/DataTypes/interfaces/TinyIntegerDataType.md)\> = `DataTypes.TINYINT` Alias of `DataTypes.TINYINT`. *** #### Transaction > `readonly` `static` **Transaction**: *typeof* [`Transaction`](Transaction.md) Transaction class. *** #### TSVECTOR > `readonly` `static` **TSVECTOR**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.TSVECTOR` Alias of `DataTypes.TSVECTOR`. *** #### UniqueConstraintError > `readonly` `static` **UniqueConstraintError**: *typeof* [`UniqueConstraintError`](UniqueConstraintError.md) = `errorClasses.UniqueConstraintError` Alias of the exported `UniqueConstraintError`. *** #### UnknownConstraintError > `readonly` `static` **UnknownConstraintError**: *typeof* [`UnknownConstraintError`](UnknownConstraintError.md) = `errorClasses.UnknownConstraintError` Alias of the exported `UnknownConstraintError`. *** #### useInflection > `readonly` `static` **useInflection**: (`custom`) => `void` Replaces the inflection library, see [useInflection](../functions/useInflection.md). Replaces the inflection library used to singularize and pluralize association names and to underscore column names (Sequelize v6 `useInflection`). Call it before defining models. ##### Parameters ###### custom [`Inflection`](../interfaces/Inflection.md) Library with `singularize`, `pluralize` and `underscore`. ##### Returns `void` ##### See [Sequelize.useInflection](#useinflection) ##### Example ```ts useInflection({ singularize: (word) => word.replace(/s$/, ''), pluralize: (word) => `${word}s`, underscore: (word) => word.replace(/([A-Z])/g, '_$1').toLowerCase(), }); ``` *** #### Utils > `readonly` `static` **Utils**: `Readonly`\<\{ `Cast`: *typeof* [`Cast`](../interfaces/Cast.md); `Col`: *typeof* [`Col`](../interfaces/Col.md); `Fn`: *typeof* [`Fn`](../interfaces/Fn.md); `Json`: *typeof* [`Json`](../interfaces/Json.md); `Literal`: *typeof* [`Literal`](../interfaces/Literal.md); `pluralize`: (`word`) => `string`; `SequelizeMethod`: *typeof* [`SqlExpression`](../interfaces/SqlExpression.md); `singularize`: (`word`) => `string`; `useInflection`: (`custom`) => `void`; `Where`: *typeof* [`Where`](../interfaces/Where.md); \}\> Subset of the v6 `Utils` helpers, see [Utils](../variables/Utils.md). *** #### UUID > `readonly` `static` **UUID**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.UUID` Alias of `DataTypes.UUID`. *** #### UUIDV4 > `readonly` `static` **UUIDV4**: [`DefaultValueGenerator`](../interfaces/DefaultValueGenerator.md) = `DataTypes.UUIDV4` Alias of `DataTypes.UUIDV4`. *** #### ValidationError > `readonly` `static` **ValidationError**: *typeof* [`ValidationError`](ValidationError.md) = `errorClasses.ValidationError` Alias of the exported `ValidationError`. *** #### ValidationErrorItem > `readonly` `static` **ValidationErrorItem**: *typeof* [`ValidationErrorItem`](ValidationErrorItem.md) = `errorClasses.ValidationErrorItem` Alias of the exported `ValidationErrorItem`. *** #### ValidationErrorItemOrigin > `readonly` `static` **ValidationErrorItemOrigin**: `ValidationErrorItemOrigins` = `errorClasses.ValidationErrorItemOrigin` Alias of the exported `ValidationErrorItemOrigin`. *** #### ValidationErrorItemType > `readonly` `static` **ValidationErrorItemType**: `ValidationErrorItemTypes` = `errorClasses.ValidationErrorItemType` Alias of the exported `ValidationErrorItemType`. *** #### validationFailed > `readonly` `static` **validationFailed**: [`NamedHookAdder`](../type-aliases/NamedHookAdder.md) Adds a global `validationFailed` hook for every `Sequelize` instance: `Sequelize.validationFailed(fn)` or `Sequelize.validationFailed(name, fn)`. ##### Inherited from `InstanceHookAdders.validationFailed` *** #### Validator > `readonly` `static` **Validator**: *typeof* `validator` = `validatorJs` The `validator` library used by the built-in validators. *** #### VIRTUAL > `readonly` `static` **VIRTUAL**: `VirtualFactory` = `DataTypes.VIRTUAL` Alias of `DataTypes.VIRTUAL`. *** #### where > `readonly` `static` **where**: [`WhereFactory`](../type-aliases/WhereFactory.md) Comparison builder. ### Accessors #### connectionManager ##### Get Signature > **get** **connectionManager**(): [`ConnectionManagerContract`](../interfaces/ConnectionManagerContract.md) Acquire / release contract of the instance's pools (Sequelize v6 `sequelize.connectionManager`). Every query, finder, write, transaction, `findEach`, COPY, advisory lock and `sync` gets its pooled connection from `getConnection` and gives it back through `releaseConnection`, looked up on this object at call time, so both can be replaced on the instance to route connections (for example per request to one of several databases). A replacement must keep the acquire / release pairing and release a connection to the pool it came from; a connection taken from another `Sequelize` instance's manager works on this instance too. `LISTEN` opens its own dedicated connection and does not use the manager. `pool` gives live pool counters for health gauges and `destroyConnection` drops a broken connection from its pool. ###### See [ConnectionManagerContract](../interfaces/ConnectionManagerContract.md) ###### Example ```ts const manager = sequelize.connectionManager; const defaultGet = manager.getConnection.bind(manager); const defaultRelease = manager.releaseConnection.bind(manager); const other = new Sequelize('postgres://localhost/other'); const owners = new WeakMap(); manager.getConnection = async (options) => { const shard = other; const connection = await shard.connectionManager.getConnection(options); owners.set(connection, shard); return connection; }; manager.releaseConnection = (connection) => { const owner = owners.get(connection); return owner === undefined ? defaultRelease(connection) : owner.connectionManager.releaseConnection(connection); }; ``` ###### Returns [`ConnectionManagerContract`](../interfaces/ConnectionManagerContract.md) *** #### queryInterface ##### Get Signature > **get** **queryInterface**(): [`QueryInterface`](QueryInterface.md) Schema API of this instance (Sequelize v6 property; same object as `getQueryInterface()`). ###### Returns [`QueryInterface`](QueryInterface.md) The QueryInterface. *** #### version ##### Get Signature > **get** `static` **version**(): `string` Version of the installed postgrelize package (Sequelize v6 `Sequelize.version` reports its own version). ###### Returns `string` Semver string, e.g. `'1.1.0'`. ### Methods #### addHook() > **addHook**(`type`, `nameOrFn`, `hook?`): `this` Registers a global hook that runs for every model of this instance, or a connection hook such as `beforeConnect`. Global hooks are not fired for models that never use the hook type. ##### Parameters ###### type `string` Hook type, e.g. `'beforeCreate'`. ###### nameOrFn `string` \| [`HookFunction`](../type-aliases/HookFunction.md) Hook name (to remove it later) or the hook function. ###### hook? [`HookFunction`](../type-aliases/HookFunction.md) Hook function when a name is given. ##### Returns `this` This instance. ##### Example ```ts sequelize.addHook('beforeCreate', 'stamp', (instance: any) => { instance.createdBy = 'system'; }); ``` *** #### addModels() > **addModels**(`models`): `this` Registers model classes defined with decorators (`@Table`, `@Column`, `@HasMany`, …): initializes each one like `Model.init` and then adds its associations, so classes may refer to each other in any order. Pass every class of an association before using it. ##### Parameters ###### models readonly [`ModelStatic`](../type-aliases/ModelStatic.md)\<[`AnyModel`](../type-aliases/AnyModel.md)\>[] Model classes. ##### Returns `this` This instance. ##### Example ```ts sequelize.addModels([User, Post]); ``` ##### See [Table](../variables/Table.md) *** #### authenticate() > **authenticate**(`options?`): `Promise`\<`void`\> Verifies that the database is reachable by running `SELECT 1+1 AS result`. ##### Parameters ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`void`\> Resolves when the database is reachable. ##### Throws ConnectionError and its subclasses when the connection cannot be established. ##### Example ```ts try { await sequelize.authenticate(); } catch (error) { console.error('Database unreachable', error); } ``` *** #### close() > **close**(): `Promise`\<`void`\> Closes all pooled connections and stops the notification listener. The instance cannot run queries afterwards. ##### Returns `Promise`\<`void`\> Resolves when closed. ##### Example ```ts await sequelize.close(); ``` *** #### createSchema() > **createSchema**(`schema`, `options?`): `Promise`\<`void`\> Runs `CREATE SCHEMA IF NOT EXISTS` for a schema. ##### Parameters ###### schema `string` Schema name. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await sequelize.createSchema('tenant_1'); ``` *** #### databaseVersion() > **databaseVersion**(`options?`): `Promise`\<`string`\> Reads the PostgreSQL server version with `SHOW server_version`, e.g. `'16.4'`. ##### Parameters ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`string`\> Version string. ##### Example ```ts const version = await sequelize.databaseVersion(); // e.g. '17.2' ``` *** #### define() > **define**\<`M`\>(`modelName`, `attributes?`, `options?`): [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> Defines a model without declaring a class, like `Model.init` on an anonymous subclass named `modelName`. The model is registered in `sequelize.models`. ##### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) = [`Model`](Model.md)\<`any`, `any`\> ##### Parameters ###### modelName `string` Model name. ###### attributes? [`ModelAttributes`](../type-aliases/ModelAttributes.md)\<`M`\> = `{}` Attribute definitions keyed by attribute name; defaults to none (only the primary key and timestamps). ###### options? [`DefineOptions`](../type-aliases/DefineOptions.md) = `{}` Model options (`sequelize` is set for you). ##### Returns [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\> The model class. ##### See [Model.init](Model.md#init) ##### Example ```ts const Product = sequelize.define('Product', { sku: { type: DataTypes.STRING, allowNull: false, unique: true }, price: DataTypes.DECIMAL(10, 2), }); await Product.sync(); ``` *** #### drop() > **drop**(`options?`): `Promise`\<`void`\> Drops the tables of all defined models in reverse foreign-key order. Destructive. ##### Parameters ###### options? [`DropOptions`](../type-aliases/DropOptions.md) = `{}` `cascade` and query options. ##### Returns `Promise`\<`void`\> Resolves when done. ##### Example ```ts await sequelize.drop({ cascade: true }); ``` *** #### dropAllSchemas() > **dropAllSchemas**(`options?`): `Promise`\<`void`\> Drops every schema returned by [Sequelize.showAllSchemas](#showallschemas) with `CASCADE`. Destructive. ##### Parameters ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await sequelize.dropAllSchemas(); ``` *** #### dropSchema() > **dropSchema**(`schema`, `options?`): `Promise`\<`void`\> Runs `DROP SCHEMA IF EXISTS ... CASCADE`, removing the schema and every object in it. ##### Parameters ###### schema `string` Schema name. ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`void`\> ##### Example ```ts await sequelize.dropSchema('tenant_1'); ``` *** #### escape() > **escape**(`value`): `string` Renders a value as a PostgreSQL literal, e.g. `'O''Brien'`. Prefer bound parameters for queries. ##### Parameters ###### value `unknown` String, number, boolean, `null`, `Date`, array or JSON value. ##### Returns `string` SQL literal text. ##### Example ```ts const sql = `SELECT ${sequelize.escape("O'Brien")}`; // SELECT 'O''Brien' ``` *** #### getDatabaseName() > **getDatabaseName**(): `string` \| `undefined` Name of the connected database. ##### Returns `string` \| `undefined` Database name from the connection settings. ##### Example ```ts const name = sequelize.getDatabaseName(); ``` *** #### getDialect() > **getDialect**(): `"postgres"` Reports the SQL dialect of this instance; postgrelize supports PostgreSQL only. ##### Returns `"postgres"` Always `'postgres'`. ##### Example ```ts sequelize.getDialect(); // 'postgres' ``` *** #### getQueryInterface() > **getQueryInterface**(): [`QueryInterface`](QueryInterface.md) Returns the schema manipulation API of this instance (used by migrations). The instance is created on first use and then reused. ##### Returns [`QueryInterface`](QueryInterface.md) The QueryInterface of this instance. ##### Example ```ts const queryInterface = sequelize.getQueryInterface(); await queryInterface.dropTable('legacy_logs'); ``` *** #### hasHook() > **hasHook**(`type`): `boolean` Tells whether this instance has at least one global hook of the given type. ##### Parameters ###### type `string` Hook type. ##### Returns `boolean` True when at least one hook exists. ##### Example ```ts if (!sequelize.hasHook('beforeCreate')) { sequelize.addHook('beforeCreate', () => {}); } ``` *** #### hasHooks() > **hasHooks**(`type`): `boolean` Alias of [Sequelize.hasHook](#hashook-1), kept for Sequelize v6 compatibility. ##### Parameters ###### type `string` Hook type. ##### Returns `boolean` True when at least one hook exists. ##### Example ```ts const registered = sequelize.hasHooks('afterUpdate'); ``` *** #### isDefined() > **isDefined**(`modelName`): `boolean` Tells whether a model with the given name is registered on this instance. ##### Parameters ###### modelName `string` Model name. ##### Returns `boolean` True when defined. ##### Example ```ts if (!sequelize.isDefined('Product')) { sequelize.define('Product', { sku: DataTypes.STRING }); } ``` *** #### listen() > **listen**(`channel`, `handler`): `Promise`\<() => `Promise`\<`void`\>\> Subscribes a handler to `NOTIFY` messages on a channel over one dedicated connection per instance, which is re-subscribed after connection loss. PostgreSQL extension. ##### Parameters ###### channel `string` Channel name. ###### handler [`NotificationHandler`](../type-aliases/NotificationHandler.md) Called with the payload and the channel. ##### Returns `Promise`\<() => `Promise`\<`void`\>\> Function that unsubscribes the handler. ##### Example ```ts const stop = await sequelize.listen('jobs', (payload, channel) => { console.log(channel, payload); }); await sequelize.notify('jobs', { id: 1 }); await stop(); ``` *** #### log() > **log**(...`args`): `void` Passes a message to the configured `logging` function (or to the `logging` option of the last argument, as in v6). ##### Parameters ###### args ...`unknown`[] Message parts; an options object with `logging` may come last. ##### Returns `void` ##### Example ```ts sequelize.log('Cache warmed up'); ``` *** #### model() > **model**(`modelName`): [`ModelStatic`](../type-aliases/ModelStatic.md)\<[`AnyModel`](../type-aliases/AnyModel.md)\> Looks up a model registered with `define`, `Model.init` or `addModels`. ##### Parameters ###### modelName `string` Model name. ##### Returns [`ModelStatic`](../type-aliases/ModelStatic.md)\<[`AnyModel`](../type-aliases/AnyModel.md)\> The model class. ##### Throws Error when the model is not defined. ##### Example ```ts const Product = sequelize.model('Product'); const total = await Product.count(); ``` *** #### notify() > **notify**(`channel`, `payload?`, `options?`): `Promise`\<`void`\> Sends a notification to a channel with `pg_notify`. PostgreSQL extension. ##### Parameters ###### channel `string` Channel name. ###### payload? `unknown` Payload text (objects are sent as JSON). ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options (inside a transaction the notification is sent on commit). ##### Returns `Promise`\<`void`\> Resolves when sent. ##### See [Sequelize.listen](#listen) ##### Example ```ts await sequelize.notify('jobs', 'refresh'); await sequelize.notify('jobs', { id: 42 }, { transaction }); ``` *** #### query() ##### Call Signature > **query**\<`T`\>(`sql`, `options`): `Promise`\<`T` \| `null`\> Runs a raw SQL statement and shapes the result by `options.type`. Replacements are escaped into the SQL text like Sequelize v6 (so one call can run several statements); `bind` values are sent as parameters. The SQL text itself is sent as is: never build it from user input — pass user values through `replacements` or `bind`. Overloads follow Sequelize v6: with a `type` the result type is known (`SELECT` gives `T[]`, or `T | null` with `plain: true`), with a `model` the rows are instances of it, otherwise the result is `[rows, metadata]`. ###### Type Parameters ###### T `T` *extends* `object` Row type of a `SELECT` query. ###### Parameters ###### sql `string` \| [`Literal`](../interfaces/Literal.md) SQL text, or a literal. ###### options [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) & `Readonly`\<\{ `bind?`: [`BindParameters`](../type-aliases/BindParameters.md); `mapToModel?`: `boolean`; `model?`: [`ModelStatic`](../type-aliases/ModelStatic.md)\<[`AnyModel`](../type-aliases/AnyModel.md)\>; `nest?`: `boolean`; `plain?`: `boolean`; `raw?`: `boolean`; `replacements?`: [`Replacements`](../type-aliases/Replacements.md); `type?`: [`QueryType`](../type-aliases/QueryType.md); \}\> & `Readonly`\<\{ `type`: `"SELECT"`; \}\> & `Readonly`\<\{ `plain`: `true`; \}\> Query options with `type: QueryTypes.SELECT` and `plain: true`. ###### Returns `Promise`\<`T` \| `null`\> The first row, or `null`. ###### Throws DatabaseError subclasses mapped from the PostgreSQL error (unique violation, foreign key violation, ...). ###### See [QueryTypes](../variables/QueryTypes.md) ###### Example ```ts const row = await sequelize.query<{ id: number }>('SELECT id FROM users LIMIT 1', { type: QueryTypes.SELECT, plain: true, }); ``` ##### Call Signature > **query**\<`T`\>(`sql`, `options`): `Promise`\<`T`[]\> Runs a `SELECT` statement and returns its rows. ###### Type Parameters ###### T `T` *extends* `object` Row type. ###### Parameters ###### sql `string` \| [`Literal`](../interfaces/Literal.md) SQL text, or a literal. ###### options [`QueryOptionsWithType`](../type-aliases/QueryOptionsWithType.md)\<`"SELECT"`\> Query options with `type: QueryTypes.SELECT`. ###### Returns `Promise`\<`T`[]\> The rows. ###### Example ```ts const rows = await sequelize.query<{ id: number; name: string }>( 'SELECT id, name FROM users WHERE name = :name', { type: QueryTypes.SELECT, replacements: { name: 'Ada' } }, ); ``` ##### Call Signature > **query**\<`M`\>(`sql`, `options`): `Promise`\<`M` \| `null`\> Runs a statement and returns the first row as an instance of `options.model`. ###### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) Model instance type. ###### Parameters ###### sql `string` \| [`Literal`](../interfaces/Literal.md) SQL text, or a literal. ###### options [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) & `Readonly`\<\{ `bind?`: [`BindParameters`](../type-aliases/BindParameters.md); `mapToModel?`: `boolean`; `model?`: [`ModelStatic`](../type-aliases/ModelStatic.md)\<[`AnyModel`](../type-aliases/AnyModel.md)\>; `nest?`: `boolean`; `plain?`: `boolean`; `raw?`: `boolean`; `replacements?`: [`Replacements`](../type-aliases/Replacements.md); `type?`: [`QueryType`](../type-aliases/QueryType.md); \}\> & `Readonly`\<\{ `model`: [`ModelStatic`](../type-aliases/ModelStatic.md)\<`M`\>; \}\> & `Readonly`\<\{ `plain`: `true`; \}\> Query options with `model` and `plain: true`. ###### Returns `Promise`\<`M` \| `null`\> The instance, or `null`. ###### Example ```ts const user = await sequelize.query('SELECT * FROM users LIMIT 1', { model: User, plain: true }); ``` ##### Call Signature > **query**\<`M`\>(`sql`, `options`): `Promise`\<`M`[]\> Runs a statement and returns its rows as instances of `options.model`. ###### Type Parameters ###### M `M` *extends* [`AnyModel`](../type-aliases/AnyModel.md) Model instance type. ###### Parameters ###### sql `string` \| [`Literal`](../interfaces/Literal.md) SQL text, or a literal. ###### options [`QueryOptionsWithModel`](../type-aliases/QueryOptionsWithModel.md)\<`M`\> Query options with `model`. ###### Returns `Promise`\<`M`[]\> The instances. ###### Example ```ts const users = await sequelize.query('SELECT * FROM users', { model: User, mapToModel: true }); ``` ##### Call Signature > **query**\<`T`\>(`sql`, `options`): `Promise`\<[`TypedQueryResults`](../type-aliases/TypedQueryResults.md)\[`T`\]\> Runs a statement of a known non-`SELECT` query type; the result type follows the v6 typings (`UPDATE`: `[undefined, number]`, `INSERT`: `[number, number]`, `BULKUPDATE` / `BULKDELETE` / `UPSERT`: the affected row count, `DELETE`: nothing, `SHOWTABLES`: table names, `DESCRIBE`: columns). ###### Type Parameters ###### T `T` *extends* keyof [`TypedQueryResults`](../type-aliases/TypedQueryResults.md) The query type. ###### Parameters ###### sql `string` \| [`Literal`](../interfaces/Literal.md) SQL text, or a literal. ###### options [`QueryOptionsWithType`](../type-aliases/QueryOptionsWithType.md)\<`T`\> Query options with a `type`. ###### Returns `Promise`\<[`TypedQueryResults`](../type-aliases/TypedQueryResults.md)\[`T`\]\> The result shaped by the type. ###### Example ```ts const [, affected] = await sequelize.query('UPDATE users SET active = true', { type: QueryTypes.UPDATE, }); ``` ##### Call Signature > **query**(`sql`, `options`): `Promise`\<`Record`\<`string`, `unknown`\> \| `null`\> Runs a raw statement and returns the first row. ###### Parameters ###### sql `string` \| [`Literal`](../interfaces/Literal.md) SQL text, or a literal. ###### options [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) & `Readonly`\<\{ `bind?`: [`BindParameters`](../type-aliases/BindParameters.md); `mapToModel?`: `boolean`; `model?`: [`ModelStatic`](../type-aliases/ModelStatic.md)\<[`AnyModel`](../type-aliases/AnyModel.md)\>; `nest?`: `boolean`; `plain?`: `boolean`; `raw?`: `boolean`; `replacements?`: [`Replacements`](../type-aliases/Replacements.md); `type?`: [`QueryType`](../type-aliases/QueryType.md); \}\> & `Readonly`\<\{ `plain`: `true`; \}\> Query options with `plain: true`. ###### Returns `Promise`\<`Record`\<`string`, `unknown`\> \| `null`\> The first row, or `null`. ###### Example ```ts const row = await sequelize.query('SELECT 1 AS one', { plain: true }); ``` ##### Call Signature > **query**(`sql`, `options?`): `Promise`\<\[`unknown`[], `unknown`\]\> Runs a raw statement and returns `[rows, metadata]`. ###### Parameters ###### sql `string` \| [`Literal`](../interfaces/Literal.md) SQL text, or a literal. ###### options? [`QueryOptions`](../type-aliases/QueryOptions.md) Query options. ###### Returns `Promise`\<\[`unknown`[], `unknown`\]\> Rows and driver metadata. ###### Example ```ts const [rows, metadata] = await sequelize.query('SELECT id FROM users'); ``` *** #### random() > **random**(): [`Fn`](../interfaces/Fn.md) SQL `RANDOM()` call, e.g. for `order: [sequelize.random()]`. ##### Returns [`Fn`](../interfaces/Fn.md) A `fn('RANDOM')` expression. ##### Example ```ts const sample = await User.findAll({ order: sequelize.random(), limit: 5 }); ``` *** #### refreshTypes() > **refreshTypes**(): `void` Accepted for compatibility; postgrelize reads type information from each result, so there is nothing to refresh. ##### Returns `void` ##### Example ```ts sequelize.refreshTypes(); ``` *** #### removeHook() > **removeHook**(`type`, `nameOrFn?`): `this` Unregisters global hooks by name or by function reference. ##### Parameters ###### type `string` Hook type. ###### nameOrFn? `string` \| [`HookFunction`](../type-aliases/HookFunction.md) Hook name or function; all hooks of the type when omitted. ##### Returns `this` This instance. ##### Example ```ts sequelize.removeHook('beforeCreate', 'stamp'); ``` *** #### runHooks() > **runHooks**(`type`, ...`args`): `Promise`\<`void`\> Runs the global hooks of a type with the given arguments. ##### Parameters ###### type `string` Hook type. ###### args ...readonly `unknown`[] Hook arguments. ##### Returns `Promise`\<`void`\> Resolves when all hooks finished. ##### Example ```ts await sequelize.runHooks('beforeConnect', { host: 'localhost' }); ``` *** #### showAllSchemas() > **showAllSchemas**(`options?`): `Promise`\<`string`[]\> Lists the schemas that belong to the application (without `public`, `information_schema` and `pg_*`). ##### Parameters ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) Query options. ##### Returns `Promise`\<`string`[]\> Schema names. ##### Example ```ts const schemas = await sequelize.showAllSchemas(); // e.g. ['tenant_1'] ``` *** #### sync() > **sync**(`options?`): `Promise`\<`Sequelize`\> Creates (or alters / re-creates) the tables of all defined models in foreign-key order. Reference cycles use deferred foreign keys. ##### Parameters ###### options? [`SyncOptions`](../type-aliases/SyncOptions.md) = `{}` `force`, `alter`, `match` and query options. ##### Returns `Promise`\<`Sequelize`\> This instance. ##### Throws Error when `options.match` does not match the database name. ##### See [Model.sync](Model.md#sync) ##### Example ```ts await sequelize.sync({ alter: { drop: false } }); await sequelize.sync({ force: true, match: /_test$/ }); ``` *** #### transaction() ##### Call Signature > **transaction**\<`T`\>(`run`): `Promise`\<`T`\> Runs a callback in a managed transaction: committed when it resolves, rolled back when it throws. Queries must pass `{ transaction }` unless CLS is enabled with [Sequelize.useCLS](#usecls). ###### Type Parameters ###### T `T` ###### Parameters ###### run (`transaction`) => `PromiseLike`\<`T`\> Callback receiving the transaction. ###### Returns `Promise`\<`T`\> Result of `run`. ###### Example ```ts const created = await sequelize.transaction(async (t) => { const owner = await User.create({ name: 'Ada' }, { transaction: t }); return Post.create({ title: 'Hello', userId: owner.id }, { transaction: t }); }); ``` ##### Call Signature > **transaction**\<`T`\>(`options`, `run`): `Promise`\<`T`\> Runs a callback in a managed transaction started with the given options (isolation level, read only, settings, savepoint parent). ###### Type Parameters ###### T `T` ###### Parameters ###### options [`TransactionOptions`](../type-aliases/TransactionOptions.md) Transaction options. ###### run (`transaction`) => `PromiseLike`\<`T`\> Callback receiving the transaction. ###### Returns `Promise`\<`T`\> Result of `run`. ###### Example ```ts const count = await sequelize.transaction({ readOnly: true }, async (t) => { return User.count({ transaction: t }); }); ``` ##### Call Signature > **transaction**(`options?`): `Promise`\<[`Transaction`](Transaction.md)\> Begins an unmanaged transaction that you must commit or roll back yourself. With `options.transaction` it becomes a savepoint inside that transaction. ###### Parameters ###### options? `Readonly`\<\{ `deferrable?`: `boolean` \| `Readonly`\<\{ `sql`: `string`; \}\>; `isolationLevel?`: [`IsolationLevel`](../type-aliases/IsolationLevel.md); `logging?`: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md); `readOnly?`: `boolean`; `retry?`: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\>; `settings?`: `Readonly`\<`Record`\<`string`, `string` \| `number` \| `boolean`\>\>; `transaction?`: [`Transaction`](Transaction.md) \| `null`; `type?`: `"DEFERRED"` \| `"IMMEDIATE"` \| `"EXCLUSIVE"`; \}\> Transaction options. ###### Returns `Promise`\<[`Transaction`](Transaction.md)\> Started transaction. ###### Example ```ts const t = await sequelize.transaction({ isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE }); try { await User.create({ name: 'Ada' }, { transaction: t }); await t.commit(); } catch (error) { await t.rollback(); throw error; } ``` *** #### truncate() > **truncate**(`options?`): `Promise`\<`void`\> Empties the tables of all defined models (`TRUNCATE`), tables that reference others first. With `cascade` the tables are truncated one after the other, otherwise all at once. Destructive. ##### Parameters ###### options? `TruncateOptions` = `{}` `cascade`, `restartIdentity` and query options. ##### Returns `Promise`\<`void`\> Resolves when done. ##### Throws Error when foreign keys form a cycle and `cascade` is not set. ##### Example ```ts await sequelize.truncate({ cascade: true }); ``` *** #### validate() > **validate**(`options?`): `Promise`\<`void`\> Alias of `authenticate`: checks that the database is reachable. ##### Parameters ###### options? [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) = `{}` Query options. ##### Returns `Promise`\<`void`\> Resolves when the database is reachable. ##### Throws ConnectionError and its subclasses when the connection cannot be established. ##### Example ```ts await sequelize.validate(); ``` *** #### withAdvisoryLock() > **withAdvisoryLock**\<`T`\>(`key`, `run`, `options?`): `Promise`\<`T`\> Runs a callback in a managed transaction that first takes a transaction-level advisory lock, so concurrent callers with the same key run one at a time. The lock is released when the transaction ends. PostgreSQL extension. ##### Type Parameters ###### T `T` ##### Parameters ###### key [`AdvisoryLockKey`](../type-aliases/AdvisoryLockKey.md) Lock key (integer or string). ###### run (`transaction`) => `Promise`\<`T`\> Callback receiving the transaction. ###### options? [`TransactionOptions`](../type-aliases/TransactionOptions.md) = `{}` Transaction options. ##### Returns `Promise`\<`T`\> Result of `run`. ##### Example ```ts await sequelize.withAdvisoryLock('nightly-report', async (t) => { await Invoice.update({ status: 'sent' }, { where: { status: 'ready' }, transaction: t }); }); ``` *** #### addHook() > `static` **addHook**\<`T`\>(`this`, `type`, `nameOrFn`, `fn?`): `T` Registers a static hook. ##### Type Parameters ###### T `T` ##### Parameters ###### this `T` The `Sequelize` class. ###### type `string` Hook type, e.g. `'beforeInit'`. ###### nameOrFn `string` \| [`HookFunction`](../type-aliases/HookFunction.md) Hook name (to remove it later) or the hook function. ###### fn? [`HookFunction`](../type-aliases/HookFunction.md) Hook function when a name is given. ##### Returns `T` The class. ##### Example ```ts Sequelize.addHook('beforeInit', (config: any, options: any) => { options.logging = false; }); ``` *** #### hasHook() > `static` **hasHook**(`type`): `boolean` Tells whether a static hook of the type exists. ##### Parameters ###### type `string` Hook type. ##### Returns `boolean` True when at least one hook exists. ##### Example ```ts Sequelize.hasHook('beforeInit'); ``` *** #### hasHooks() > `static` **hasHooks**(`type`): `boolean` Alias of [Sequelize.hasHook](#hashook-1) for Sequelize v6 compatibility. ##### Parameters ###### type `string` Hook type. ##### Returns `boolean` True when at least one hook exists. ##### Example ```ts Sequelize.hasHooks('afterInit'); ``` *** #### removeHook() > `static` **removeHook**\<`T`\>(`this`, `type`, `nameOrFn?`): `T` Unregisters static hooks by name or by function reference. ##### Type Parameters ###### T `T` ##### Parameters ###### this `T` The `Sequelize` class. ###### type `string` Hook type. ###### nameOrFn? `string` \| [`HookFunction`](../type-aliases/HookFunction.md) Hook name or function; all hooks of the type when omitted. ##### Returns `T` The class. ##### Example ```ts Sequelize.removeHook('beforeInit', 'logging'); ``` *** #### runHooks() > `static` **runHooks**(`type`, ...`args`): `Promise`\<`void`\> Runs the static hooks of a type. ##### Parameters ###### type `string` Hook type. ###### args ...readonly `unknown`[] Hook arguments. ##### Returns `Promise`\<`void`\> Resolves when all hooks finished. ##### Example ```ts await Sequelize.runHooks('beforeInit', {}, {}); ``` *** #### useCLS() > `static` **useCLS**(`namespace?`): *typeof* `Sequelize` Enables continuation-local transactions: queries inside `sequelize.transaction(fn)` use the transaction automatically. Without an argument `AsyncLocalStorage` is used. With a `cls-hooked` style namespace (an object with `bind`, `run`, `get` and `set`) it behaves as in Sequelize v6: managed transactions run in `namespace.run` and store themselves under `namespace.get('transaction')` (cleared when they finish), queries without a `transaction` option read the key, and a nested `sequelize.transaction(callback)` opens its own transaction instead of a savepoint. ##### Parameters ###### namespace? `unknown` CLS namespace; `AsyncLocalStorage` when omitted. ##### Returns *typeof* `Sequelize` The `Sequelize` class. ##### Throws Error `Must provide CLS namespace` when `namespace` has no `bind` or `run`. ##### See [Sequelize.transaction](#transaction-1) ##### Example ```ts Sequelize.useCLS(); await sequelize.transaction(async () => { // No `{ transaction }` option needed: the queries join the managed transaction. const user = await User.create({ name: 'Ada' }); await Post.create({ title: 'Hello', userId: user.id }); }); ``` ## Class: SequelizeScopeError Thrown for an invalid scope definition or use (Sequelize v6 `SequelizeScopeError`). ### Example ```ts try { User.scope('missing'); } catch (e) { if (e instanceof SequelizeScopeError) { console.error(e.message); } } ``` ### Extends - [`Error`](Error.md) ### Constructors #### Constructor > **new SequelizeScopeError**(`message?`): `SequelizeScopeError` Creates the error and sets `name` to `'SequelizeScopeError'`. ##### Parameters ###### message? `string` Error message. ##### Returns `SequelizeScopeError` ##### Overrides [`Error`](Error.md).[`constructor`](Error.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`Error`](Error.md).[`cause`](Error.md#cause) *** #### message > **message**: `string` ##### Inherited from [`Error`](Error.md).[`message`](Error.md#message) *** #### name > **name**: `string` ##### Inherited from [`Error`](Error.md).[`name`](Error.md#name) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`Error`](Error.md).[`stack`](Error.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`Error`](Error.md).[`stackTraceLimit`](Error.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`Error`](Error.md).[`captureStackTrace`](Error.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`Error`](Error.md).[`prepareStackTrace`](Error.md#preparestacktrace) ## Class: TimeoutError Query cancelled by PostgreSQL, e.g. because `statement_timeout` elapsed (SQLSTATE `57014`). ### Example ```ts try { await sequelize.query('SELECT pg_sleep(10)'); } catch (e) { if (e instanceof TimeoutError) { console.error('query was cancelled:', e.sql); } } ``` ### Extends - [`DatabaseError`](DatabaseError.md) ### Constructors #### Constructor > **new TimeoutError**(`parent`, `context?`): `TimeoutError` Wraps a driver error together with the statement that failed. ##### Parameters ###### parent [`DriverError`](../type-aliases/DriverError.md) Original driver error. ###### context? `Readonly`\<\{ `parameters?`: readonly `unknown`[]; `sql?`: `string`; \}\> Executed SQL and parameters. ##### Returns `TimeoutError` ##### Overrides [`DatabaseError`](DatabaseError.md).[`constructor`](DatabaseError.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`cause`](DatabaseError.md#cause) *** #### message > **message**: `string` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`message`](DatabaseError.md#message) *** #### name > **name**: `string` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`name`](DatabaseError.md#name) *** #### original > `readonly` **original**: [`DriverError`](../type-aliases/DriverError.md) Original driver error (alias of `parent`). ##### Inherited from [`DatabaseError`](DatabaseError.md).[`original`](DatabaseError.md#original) *** #### parameters > `readonly` **parameters**: readonly `unknown`[] Bound parameter values. ##### Inherited from [`DatabaseError`](DatabaseError.md).[`parameters`](DatabaseError.md#parameters) *** #### parent > `readonly` **parent**: [`DriverError`](../type-aliases/DriverError.md) Original driver error. ##### Inherited from [`DatabaseError`](DatabaseError.md).[`parent`](DatabaseError.md#parent) *** #### sql > `readonly` **sql**: `string` Executed SQL text. ##### Inherited from [`DatabaseError`](DatabaseError.md).[`sql`](DatabaseError.md#sql) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`stack`](DatabaseError.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`DatabaseError`](DatabaseError.md).[`stackTraceLimit`](DatabaseError.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`captureStackTrace`](DatabaseError.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`DatabaseError`](DatabaseError.md).[`prepareStackTrace`](DatabaseError.md#preparestacktrace) ## Class: Transaction Handle of an open database transaction or savepoint (Sequelize v6 `Transaction`). Obtain one from `sequelize.transaction()` and pass it to queries with the `transaction` option. Unmanaged transactions must be finished with [Transaction.commit](#commit) or [Transaction.rollback](#rollback); the connection is released to the pool when that happens. ### Example ```ts const t = await sequelize.transaction(); try { const created = await User.create({ name: 'Ann' }, { transaction: t }); await Post.create({ title: 'Hi', userId: created.id }, { transaction: t }); await t.commit(); } catch (e) { await t.rollback(); throw e; } ``` ### Constructors #### Constructor > **new Transaction**(`connections`, `options?`, `retries?`): `Transaction` Creates an unstarted transaction; use `sequelize.transaction()` instead of calling this directly. ##### Parameters ###### connections `ConnectionManager` Connection manager of the owning `Sequelize` instance. ###### options? [`TransactionOptions`](../type-aliases/TransactionOptions.md) = `{}` Transaction options. ###### retries? `RetryRunner` Retry settings applied when starting the transaction. ##### Returns `Transaction` ### Properties #### finished > **finished**: `"commit"` \| `"rollback"` \| `undefined` `'commit'` or `'rollback'` once the transaction is finished. *** #### id > `readonly` **id**: `string` Unique id, used in SQL logs and as savepoint name. *** #### options > `readonly` **options**: [`TransactionOptions`](../type-aliases/TransactionOptions.md) Options the transaction was started with. *** #### parent > `readonly` **parent**: `Transaction` \| `undefined` Parent transaction when this one is a savepoint. *** #### ISOLATION\_LEVELS > `readonly` `static` **ISOLATION\_LEVELS**: `object` Values for the `isolationLevel` option, e.g. `SERIALIZABLE` or `READ_COMMITTED`. ##### READ\_COMMITTED > `readonly` **READ\_COMMITTED**: `"READ COMMITTED"` = `'READ COMMITTED'` `READ COMMITTED` (PostgreSQL default). ##### READ\_UNCOMMITTED > `readonly` **READ\_UNCOMMITTED**: `"READ UNCOMMITTED"` = `'READ UNCOMMITTED'` `READ UNCOMMITTED` (behaves as `READ COMMITTED` in PostgreSQL). ##### REPEATABLE\_READ > `readonly` **REPEATABLE\_READ**: `"REPEATABLE READ"` = `'REPEATABLE READ'` `REPEATABLE READ`. ##### SERIALIZABLE > `readonly` **SERIALIZABLE**: `"SERIALIZABLE"` = `'SERIALIZABLE'` `SERIALIZABLE`. *** #### LOCK > `readonly` `static` **LOCK**: `object` Row lock strengths. ##### KEY\_SHARE > `readonly` **KEY\_SHARE**: `"KEY SHARE"` = `'KEY SHARE'` `FOR KEY SHARE`. ##### NO\_KEY\_UPDATE > `readonly` **NO\_KEY\_UPDATE**: `"NO KEY UPDATE"` = `'NO KEY UPDATE'` `FOR NO KEY UPDATE`. ##### SHARE > `readonly` **SHARE**: `"SHARE"` = `'SHARE'` `FOR SHARE`. ##### UPDATE > `readonly` **UPDATE**: `"UPDATE"` = `'UPDATE'` `FOR UPDATE`. *** #### TYPES > `readonly` `static` **TYPES**: `object` = `TRANSACTION_TYPES` Transaction types (ignored by PostgreSQL). ##### DEFERRED > `readonly` **DEFERRED**: `"DEFERRED"` = `'DEFERRED'` SQLite-only, ignored. ##### EXCLUSIVE > `readonly` **EXCLUSIVE**: `"EXCLUSIVE"` = `'EXCLUSIVE'` SQLite-only, ignored. ##### IMMEDIATE > `readonly` **IMMEDIATE**: `"IMMEDIATE"` = `'IMMEDIATE'` SQLite-only, ignored. ### Accessors #### LOCK ##### Get Signature > **get** **LOCK**(): `object` Row lock strengths (instance alias of [Transaction.LOCK](#lock)). ###### Returns ###### KEY\_SHARE > `readonly` **KEY\_SHARE**: `"KEY SHARE"` = `'KEY SHARE'` `FOR KEY SHARE`. ###### NO\_KEY\_UPDATE > `readonly` **NO\_KEY\_UPDATE**: `"NO KEY UPDATE"` = `'NO KEY UPDATE'` `FOR NO KEY UPDATE`. ###### SHARE > `readonly` **SHARE**: `"SHARE"` = `'SHARE'` `FOR SHARE`. ###### UPDATE > `readonly` **UPDATE**: `"UPDATE"` = `'UPDATE'` `FOR UPDATE`. ### Methods #### advisoryLock() > **advisoryLock**(`key`, `options?`): `Promise`\<`void`\> Takes a transaction-level advisory lock (`pg_advisory_xact_lock`), waiting until it is free. The lock is released on commit or rollback. PostgreSQL extension. ##### Parameters ###### key [`AdvisoryLockKey`](../type-aliases/AdvisoryLockKey.md) Integer key, or a string hashed with `hashtextextended`. ###### options? `Readonly`\<\{ `shared?`: `boolean`; \}\> = `{}` `shared: true` for a shared lock. ##### Returns `Promise`\<`void`\> Resolves when the lock is held. ##### Example ```ts await sequelize.transaction(async (t) => { await t.advisoryLock('invoice-42'); await Invoice.update({ status: 'sent' }, { where: { id: 42 }, transaction: t }); }); ``` *** #### afterCommit() > **afterCommit**(`hook`): `void` Registers a callback run after a successful commit. ##### Parameters ###### hook (`transaction`) => `unknown` Callback receiving this transaction; hooks run in registration order after the transaction is committed and are awaited by `commit()`. They never run after a rollback. ##### Returns `void` ##### Example ```ts await sequelize.transaction(async (t) => { t.afterCommit(() => console.log('committed, safe to notify')); await User.create({ name: 'Ann' }, { transaction: t }); }); ``` *** #### commit() > **commit**(): `Promise`\<`void`\> Commits the transaction (or releases the savepoint) and runs `afterCommit` hooks. ##### Returns `Promise`\<`void`\> Resolves when committed and all `afterCommit` hooks have run. ##### Throws Error when the transaction is already finished. ##### Example ```ts const t = await sequelize.transaction(); await User.create({ name: 'Ann' }, { transaction: t }); await t.commit(); ``` *** #### rollback() > **rollback**(): `Promise`\<`void`\> Rolls the transaction back (or rolls back to the savepoint). ##### Returns `Promise`\<`void`\> Resolves when rolled back. ##### Throws Error when the transaction is already finished. ##### Example ```ts const t = await sequelize.transaction(); try { await User.create({ name: 'Ann' }, { transaction: t }); await t.commit(); } catch (e) { await t.rollback(); } ``` *** #### tryAdvisoryLock() > **tryAdvisoryLock**(`key`, `options?`): `Promise`\<`boolean`\> Tries to take a transaction-level advisory lock without waiting. PostgreSQL extension. ##### Parameters ###### key [`AdvisoryLockKey`](../type-aliases/AdvisoryLockKey.md) Integer key, or a string hashed with `hashtextextended`. ###### options? `Readonly`\<\{ `shared?`: `boolean`; \}\> = `{}` `shared: true` for a shared lock. ##### Returns `Promise`\<`boolean`\> True when the lock was acquired. ##### Example ```ts await sequelize.transaction(async (t) => { if (await t.tryAdvisoryLock(42, { shared: true })) { await Task.findAll({ transaction: t }); } }); ``` ## Class: UniqueConstraintError Thrown when PostgreSQL reports a unique violation (SQLSTATE `23505`); a [ValidationError](ValidationError.md) subclass like in Sequelize v6. `fields` maps the unique columns to the offending values (parsed from the PostgreSQL detail) and `errors` has one `not_unique` item per column. ### Example ```ts try { await User.create({ email: 'taken@example.com' }); } catch (e) { if (e instanceof UniqueConstraintError) { console.error(e.fields, e.errors[0]?.message); } } ``` ### Extends - [`ValidationError`](ValidationError.md) ### Constructors #### Constructor > **new UniqueConstraintError**(`options`): `UniqueConstraintError` Builds the error; the message defaults to `Validation error`. ##### Parameters ###### options `Omit`\<[`ConstraintErrorOptions`](../type-aliases/ConstraintErrorOptions.md), `"fields"`\> & `Readonly`\<\{ `errors?`: readonly [`ValidationErrorItem`](ValidationErrorItem.md)[]; `fields?`: `Readonly`\<`Record`\<`string`, `string`\>\>; \}\> Driver error, fields and validation items. ##### Returns `UniqueConstraintError` ##### Overrides [`ValidationError`](ValidationError.md).[`constructor`](ValidationError.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`ValidationError`](ValidationError.md).[`cause`](ValidationError.md#cause) *** #### errors > `readonly` **errors**: readonly [`ValidationErrorItem`](ValidationErrorItem.md)[] Individual validation failures. ##### Inherited from [`ValidationError`](ValidationError.md).[`errors`](ValidationError.md#errors) *** #### fields > `readonly` **fields**: `Readonly`\<`Record`\<`string`, `string`\>\> Unique columns mapped to offending values. *** #### message > **message**: `string` ##### Inherited from [`ValidationError`](ValidationError.md).[`message`](ValidationError.md#message) *** #### name > **name**: `string` ##### Inherited from [`ValidationError`](ValidationError.md).[`name`](ValidationError.md#name) *** #### original > `readonly` **original**: [`DriverError`](../type-aliases/DriverError.md) Original driver error (alias of `parent`). *** #### parent > `readonly` **parent**: [`DriverError`](../type-aliases/DriverError.md) Original driver error. *** #### sql > `readonly` **sql**: `string` Executed SQL text. *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`ValidationError`](ValidationError.md).[`stack`](ValidationError.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`ValidationError`](ValidationError.md).[`stackTraceLimit`](ValidationError.md#stacktracelimit) ### Methods #### get() > **get**(`path`): [`ValidationErrorItem`](ValidationErrorItem.md)[] Returns the validation items reported for one attribute. ##### Parameters ###### path `string` Attribute name, compared with each item's `path`. ##### Returns [`ValidationErrorItem`](ValidationErrorItem.md)[] Items whose `path` equals `path`; an empty array when there are none. ##### Example ```ts try { await User.create({}); } catch (e) { if (e instanceof ValidationError) { console.error(e.get('email').map((item) => item.message)); } } ``` ##### Inherited from [`ValidationError`](ValidationError.md).[`get`](ValidationError.md#get) *** #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`ValidationError`](ValidationError.md).[`captureStackTrace`](ValidationError.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`ValidationError`](ValidationError.md).[`prepareStackTrace`](ValidationError.md#preparestacktrace) ## Class: UnknownConstraintError A constraint that does not exist was referenced (Sequelize v6 `UnknownConstraintError`). ### Example ```ts try { await queryInterface.removeConstraint('users', 'missing'); } catch (e) { if (e instanceof UnknownConstraintError) { console.error(e.constraint, e.table); } } ``` ### Extends - [`DatabaseError`](DatabaseError.md) ### Constructors #### Constructor > **new UnknownConstraintError**(`options?`): `UnknownConstraintError` Builds the error; `message` defaults to v6's "The specified constraint does not exist". ##### Parameters ###### options? `Readonly`\<\{ `constraint?`: `string`; `fields?`: `Readonly`\<`Record`\<`string`, `unknown`\>\>; `message?`: `string`; `parent?`: [`DriverError`](../type-aliases/DriverError.md); `table?`: `string`; \}\> = `{}` Constraint details and an optional driver error. ##### Returns `UnknownConstraintError` ##### Overrides [`DatabaseError`](DatabaseError.md).[`constructor`](DatabaseError.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`cause`](DatabaseError.md#cause) *** #### constraint > `readonly` **constraint**: `string` \| `undefined` Constraint name. *** #### fields > `readonly` **fields**: `Readonly`\<`Record`\<`string`, `unknown`\>\> \| `undefined` Constraint columns. *** #### message > **message**: `string` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`message`](DatabaseError.md#message) *** #### name > **name**: `string` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`name`](DatabaseError.md#name) *** #### original > `readonly` **original**: [`DriverError`](../type-aliases/DriverError.md) Original driver error (alias of `parent`). ##### Inherited from [`DatabaseError`](DatabaseError.md).[`original`](DatabaseError.md#original) *** #### parameters > `readonly` **parameters**: readonly `unknown`[] Bound parameter values. ##### Inherited from [`DatabaseError`](DatabaseError.md).[`parameters`](DatabaseError.md#parameters) *** #### parent > `readonly` **parent**: [`DriverError`](../type-aliases/DriverError.md) Original driver error. ##### Inherited from [`DatabaseError`](DatabaseError.md).[`parent`](DatabaseError.md#parent) *** #### sql > `readonly` **sql**: `string` Executed SQL text. ##### Inherited from [`DatabaseError`](DatabaseError.md).[`sql`](DatabaseError.md#sql) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`stack`](DatabaseError.md#stack) *** #### table > `readonly` **table**: `string` \| `undefined` Table name. *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`DatabaseError`](DatabaseError.md).[`stackTraceLimit`](DatabaseError.md#stacktracelimit) ### Methods #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`DatabaseError`](DatabaseError.md).[`captureStackTrace`](DatabaseError.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`DatabaseError`](DatabaseError.md).[`prepareStackTrace`](DatabaseError.md#preparestacktrace) ## Class: ValidationError Thrown when a model instance fails validation, carrying one item per failed rule (Sequelize v6 `ValidationError`). Raised by `create`, `save`, `update`, `build(...).validate()` and similar before any SQL is sent. Not-null, unique and validator failures all end up in `errors`. ### Example ```ts try { await User.create({ email: 'not-an-email' }); } catch (e) { if (e instanceof ValidationError) { console.error(e.errors.map((item) => `${item.path}: ${item.message}`)); } } ``` ### Extends - [`Error`](Error.md) ### Extended by - [`UniqueConstraintError`](UniqueConstraintError.md) ### Constructors #### Constructor > **new ValidationError**(`message`, `errors?`): `ValidationError` Creates the error from a message and its items. ##### Parameters ###### message `string` \| `null` \| `undefined` Error message; when empty it is built from the items like Sequelize v6. ###### errors? readonly [`ValidationErrorItem`](ValidationErrorItem.md)[] = `[]` Individual validation failures. ##### Returns `ValidationError` ##### Overrides [`Error`](Error.md).[`constructor`](Error.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`Error`](Error.md).[`cause`](Error.md#cause) *** #### errors > `readonly` **errors**: readonly [`ValidationErrorItem`](ValidationErrorItem.md)[] Individual validation failures. *** #### message > **message**: `string` ##### Inherited from [`Error`](Error.md).[`message`](Error.md#message) *** #### name > **name**: `string` ##### Inherited from [`Error`](Error.md).[`name`](Error.md#name) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`Error`](Error.md).[`stack`](Error.md#stack) *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`Error`](Error.md).[`stackTraceLimit`](Error.md#stacktracelimit) ### Methods #### get() > **get**(`path`): [`ValidationErrorItem`](ValidationErrorItem.md)[] Returns the validation items reported for one attribute. ##### Parameters ###### path `string` Attribute name, compared with each item's `path`. ##### Returns [`ValidationErrorItem`](ValidationErrorItem.md)[] Items whose `path` equals `path`; an empty array when there are none. ##### Example ```ts try { await User.create({}); } catch (e) { if (e instanceof ValidationError) { console.error(e.get('email').map((item) => item.message)); } } ``` *** #### captureStackTrace() > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ##### Returns `void` ##### Inherited from [`Error`](Error.md).[`captureStackTrace`](Error.md#capturestacktrace) *** #### prepareStackTrace() > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`Error`](Error.md).[`prepareStackTrace`](Error.md#preparestacktrace) ## Class: ValidationErrorItem Describes a single failed validation: which attribute, which value and which validator (Sequelize v6 `ValidationErrorItem`). `origin` is derived from `type`: `'CORE'` for not-null and string violations, `'DB'` for unique violations, `'FUNCTION'` for custom validators. ### Example ```ts try { await User.create({ email: 'not-an-email' }); } catch (e) { if (e instanceof ValidationError) { for (const item of e.errors) { console.error(item.path, item.validatorKey, item.value, item.origin); } } } ``` ### Constructors #### Constructor > **new ValidationErrorItem**(`message`, `type?`, `path?`, `value?`, `instance?`, `validatorKey?`, `validatorName?`, `validatorArgs?`): `ValidationErrorItem` Creates an item; `path`, `instance`, `validatorKey` and `validatorName` default to `null`, `validatorArgs` to `[]`, and `value` to `null` when `undefined`. ##### Parameters ###### message `string` Human-readable message. ###### type? `string` \| `null` Validation type or origin. ###### path? `string` \| `null` Attribute name. ###### value? `unknown` Offending value. ###### instance? `object` \| `null` Instance being validated. ###### validatorKey? `string` \| `null` Validator key. ###### validatorName? `string` \| `null` Built-in validator name. ###### validatorArgs? readonly `unknown`[] Built-in validator arguments. ##### Returns `ValidationErrorItem` ### Properties #### instance > `readonly` **instance**: `object` \| `null` Instance being validated. *** #### message > `readonly` **message**: `string` Human-readable message. *** #### origin > `readonly` **origin**: [`ValidationErrorItemOrigin`](../type-aliases/ValidationErrorItemOrigin.md) \| `null` Where the error was raised, derived from `type`. *** #### original? > `optional` **original?**: `unknown` What a custom validator threw (v6 `original`); set only on items of failed custom validators. *** #### path > `readonly` **path**: `string` \| `null` Attribute name (or model validator name). *** #### type > `readonly` **type**: `string` \| `null` Validation type, e.g. `'unique violation'`, `'notNull Violation'`, `'Validation error'`. *** #### validatorArgs > `readonly` **validatorArgs**: readonly `unknown`[] Built-in validator arguments. *** #### validatorKey > `readonly` **validatorKey**: `string` \| `null` Validator key, e.g. `'not_unique'`, `'is_null'`, `'isEmail'`. *** #### validatorName > `readonly` **validatorName**: `string` \| `null` Built-in validator name. *** #### value > `readonly` **value**: `unknown` Offending value. ## Function: Column() > **Column**(`input`): [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) Declares a class field as a model attribute (a column). The type is not inferred from the TypeScript type (there is no `reflect-metadata`): pass a `DataTypes` value or an options object with `type`. Combine with the shortcut decorators. ### Parameters #### input [`ColumnInput`](../type-aliases/ColumnInput.md) A data type (`DataTypes.STRING(64)`) or column options (`{ type, allowNull, … }`). ### Returns [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) An attribute decorator. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @Column({ type: DataTypes.STRING, allowNull: false }) name!: string; } ``` ## Function: Comment() > **Comment**(`text`): [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) Sets the column comment (`comment`). ### Parameters #### text `string` Comment text. ### Returns [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) An attribute decorator. ### Example ```ts class User extends Model { @Comment('Login name') @Column(DataTypes.STRING) login!: string; } ``` ## Function: Default() > **Default**(`value`): [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) Sets the default value of the attribute (`defaultValue`). ### Parameters #### value `unknown` A value, an expression, or `DataTypes.NOW` / `DataTypes.UUIDV4`. ### Returns [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) An attribute decorator. ### Example ```ts class User extends Model { @Default(false) @Column(DataTypes.BOOLEAN) active!: boolean; } ``` ## Function: DefaultScope() > **DefaultScope**(`scope`): [`ModelClassDecorator`](../type-aliases/ModelClassDecorator.md) Sets the default scope of a model (`defaultScope` of `Model.init`). ### Parameters #### scope `Readonly`\<`Record`\<`string`, `unknown`\>\> \| (() => [`ScopeOptions`](../type-aliases/ScopeOptions.md)) Scope options, or a function returning them (evaluated by `addModels`, so it may refer to other models). ### Returns [`ModelClassDecorator`](../type-aliases/ModelClassDecorator.md) A class decorator. ### Example ```ts @DefaultScope(() => ({ where: { active: true } })) class User extends Model {} ``` ## Function: Scopes() > **Scopes**(`scopes`): [`ModelClassDecorator`](../type-aliases/ModelClassDecorator.md) Defines the named scopes of a model (`scopes` of `Model.init`). ### Parameters #### scopes `Readonly`\<`Record`\<`string`, [`ScopeDefinition`](../type-aliases/ScopeDefinition.md)\>\> \| (() => [`ScopesInput`](../type-aliases/ScopesInput.md)) Scopes by name (options or functions returning options), or a function returning them. ### Returns [`ModelClassDecorator`](../type-aliases/ModelClassDecorator.md) A class decorator. ### Example ```ts @Scopes({ recent: { order: [['createdAt', 'DESC']] }, named: (name: string) => ({ where: { name } }) }) class User extends Model {} ``` ## Function: and() > **and**(...`conditions`): [`WhereOptions`](../type-aliases/WhereOptions.md) Combines conditions with `AND` (Sequelize v6 `and`), for use inside `where`. ### Parameters #### conditions ...readonly [`WhereOptions`](../type-aliases/WhereOptions.md)[] Conditions to combine. ### Returns [`WhereOptions`](../type-aliases/WhereOptions.md) A `{ [Op.and]: conditions }` condition usable as `where`. ### Example ```ts await User.findAll({ where: and({ age: { [Op.gt]: 18 } }, { active: true }) }); ``` ## Function: cast() > **cast**(`val`, `type`): [`Cast`](../interfaces/Cast.md) Creates a type cast `CAST(value AS type)`. ### Parameters #### val `unknown` Value or expression to cast. #### type `string` PostgreSQL type name, e.g. `'integer'`. ### Returns [`Cast`](../interfaces/Cast.md) Cast expression. ### Example ```ts await Product.findAll({ attributes: [[cast(col('price'), 'integer'), 'rounded']] }); ``` ## Function: col() > **col**(`name`): [`Col`](../interfaces/Col.md) Creates a column reference. Dots separate table and column: `'user.id'`. ### Parameters #### name `string` Column name, optionally prefixed with a table alias. ### Returns [`Col`](../interfaces/Col.md) Column expression. ### Example ```ts await Post.findAll({ attributes: [[fn('count', col('Post.id')), 'total']], group: [col('Post.userId')] }); ``` ## Function: excluded() > **excluded**(`attribute`): [`Excluded`](../interfaces/Excluded.md) References the value proposed for insertion (`EXCLUDED."column"`) inside an `onConflict` update. PostgreSQL extension. ### Parameters #### attribute `string` Model attribute name. ### Returns [`Excluded`](../interfaces/Excluded.md) Excluded column expression. ### Example ```ts const rows = [{ key: 'home', hits: 1 }]; await Product.bulkCreate(rows, { onConflict: { target: ['key'], action: { update: { hits: excluded('hits') } } }, }); ``` ## Function: exists() > **exists**(`subquery`): [`Exists`](../interfaces/Exists.md) `EXISTS (subquery)`. PostgreSQL extension. ### Parameters #### subquery [`Subquery`](../interfaces/Subquery.md) Subquery from `Model.subquery()`. ### Returns [`Exists`](../interfaces/Exists.md) Condition usable as `where`. ### Example ```ts await User.findAll({ where: exists(Post.subquery({ where: { userId: col('User.id') } })) }); ``` ## Function: fn() > **fn**(`name`, ...`args`): [`Fn`](../interfaces/Fn.md) Creates an SQL function call. String arguments are written into the SQL as escaped literals, like v6 (`COUNT('*')`, `concat_ws(' ', ...)`); other values are bound as parameters; expressions are rendered as is. ### Parameters #### name `string` Function name, e.g. `'lower'`. #### args ...readonly `unknown`[] Function arguments. ### Returns [`Fn`](../interfaces/Fn.md) Function call expression. ### Example ```ts await User.findAll({ where: where(fn('lower', col('email')), 'a@b.c') }); ``` ## Function: json() > **json**(`conditionsOrPath`, `value?`): [`Json`](../interfaces/Json.md) Accesses a JSON(B) value by path (`json('meta.a.b')`) or builds JSON conditions (`json({ meta: { a: 1 } })`). ### Parameters #### conditionsOrPath `string` \| `object` Dot-separated path, starting with the attribute name, or a conditions object. #### value? `string` \| `number` \| `boolean` \| `null` Value to compare with when a path is given. ### Returns [`Json`](../interfaces/Json.md) JSON expression. ### Example ```ts await User.findAll({ where: json('meta.address.city', 'Berlin') }); await User.findAll({ where: json({ meta: { active: true } }) }); ``` ## Function: jsonbPath() > **jsonbPath**(`kind`, `target`, `path`, `options?`): [`Fn`](../interfaces/Fn.md) Calls a `jsonb_path_*` function (`exists`, `match`, `query`, `queryFirst`, `queryArray`) with a bound jsonpath. PostgreSQL extension. `Op.jsonPathExists` (`@?`) and `Op.match` (`@@`) are the operator forms of `exists` and `match`. ### Parameters #### kind [`JsonbPathKind`](../type-aliases/JsonbPathKind.md) Which function to call. #### target `unknown` jsonb expression, e.g. `col('doc')`. #### path `string` jsonpath text, bound as a parameter. Invalid syntax is a database error. #### options? [`JsonbPathOptions`](../type-aliases/JsonbPathOptions.md) = `{}` `vars`, `silent` and `tz`. ### Returns [`Fn`](../interfaces/Fn.md) Function call expression. ### Throws Error when `kind` is not one of the five names. ### Example ```ts await Product.findAll({ where: where(jsonbPath('exists', col('attrs'), '$.price ? (@ > $min)', { vars: { min: 10 } }), true) }); ``` ## Function: literal() > **literal**(`val`): [`Literal`](../interfaces/Literal.md) Creates a raw SQL fragment. The text is not escaped — never pass user input. ### Parameters #### val `string` SQL text. ### Returns [`Literal`](../interfaces/Literal.md) Literal expression. ### Example ```ts await Post.findAll({ order: [literal('"createdAt" DESC NULLS LAST')] }); ``` ## Function: notExists() > **notExists**(`subquery`): [`Exists`](../interfaces/Exists.md) `NOT EXISTS (subquery)`. PostgreSQL extension. ### Parameters #### subquery [`Subquery`](../interfaces/Subquery.md) Subquery from `Model.subquery()`. ### Returns [`Exists`](../interfaces/Exists.md) Condition usable as `where`. ### Example ```ts await User.findAll({ where: notExists(Post.subquery({ where: { userId: col('User.id') } })) }); ``` ## Function: or() > **or**(...`conditions`): [`WhereOptions`](../type-aliases/WhereOptions.md) Combines conditions with `OR` (Sequelize v6 `or`), for use inside `where`. ### Parameters #### conditions ...readonly [`WhereOptions`](../type-aliases/WhereOptions.md)[] Conditions to combine. ### Returns [`WhereOptions`](../type-aliases/WhereOptions.md) A `{ [Op.or]: conditions }` condition usable as `where`. ### Example ```ts await User.findAll({ where: or({ role: 'admin' }, { role: 'owner' }) }); ``` ## Function: over() > **over**(`windowFunction`, `window?`): [`Over`](../interfaces/Over.md) Window function call: `over(fn('row_number'), { partitionBy: ['userId'], orderBy: [['createdAt', 'DESC']] })`. PostgreSQL extension. ### Parameters #### windowFunction [`Literal`](../interfaces/Literal.md) \| [`Fn`](../interfaces/Fn.md) Function call, e.g. `fn('rank')`. #### window? [`WindowOptions`](../type-aliases/WindowOptions.md) = `{}` Partition and order. ### Returns [`Over`](../interfaces/Over.md) Expression usable in `attributes` and `order`. ### Example ```ts await Post.findAll({ attributes: ['id', [over(fn('row_number'), { partitionBy: ['userId'], orderBy: [['createdAt', 'DESC']] }), 'rank']], }); ``` ## Function: phraseToTsQuery() > **phraseToTsQuery**(`text`, `config?`): [`Fn`](../interfaces/Fn.md) `phraseto_tsquery([config,] text)`: words of plain text that must follow each other. PostgreSQL extension. ### Parameters #### text `unknown` Plain text, bound as a parameter. #### config? `string` Text search configuration; the server default when omitted. ### Returns [`Fn`](../interfaces/Fn.md) Function call expression. ### Throws Error when `config` is not a plain or schema-qualified identifier. ### Example ```ts await Post.findAll({ where: { search: { [Op.match]: phraseToTsQuery('fat cats', 'english') } } }); ``` ## Function: plainToTsQuery() > **plainToTsQuery**(`text`, `config?`): [`Fn`](../interfaces/Fn.md) `plainto_tsquery([config,] text)`: ANDs all words of plain text. PostgreSQL extension. ### Parameters #### text `unknown` Plain text, bound as a parameter. #### config? `string` Text search configuration; the server default when omitted. ### Returns [`Fn`](../interfaces/Fn.md) Function call expression. ### Throws Error when `config` is not a plain or schema-qualified identifier. ### Example ```ts await Post.findAll({ where: { search: { [Op.match]: plainToTsQuery('fat cats', 'english') } } }); ``` ## Function: setWeight() > **setWeight**(`vector`, `weight`): [`Fn`](../interfaces/Fn.md) `setweight(vector, weight)`: labels every lexeme of a `tsvector` `A`, `B`, `C` or `D`. PostgreSQL extension. ### Parameters #### vector `unknown` `tsvector` expression, e.g. [toTsVector](toTsVector.md). #### weight `"A"` \| `"B"` \| `"C"` \| `"D"` Label `'A'`, `'B'`, `'C'` or `'D'`. ### Returns [`Fn`](../interfaces/Fn.md) Function call expression. ### Throws Error when `weight` is not one of the four labels. ### Example ```ts await Post.findAll({ attributes: [[setWeight(toTsVector(col('title'), 'english'), 'A'), 'titleVector']] }); ``` ## Function: toTsQuery() > **toTsQuery**(`query`, `config?`): [`Fn`](../interfaces/Fn.md) `to_tsquery([config,] query)`: parses `tsquery` syntax (`&`, `|`, `!`, `<->`). PostgreSQL extension. ### Parameters #### query `unknown` Query text in `tsquery` syntax, bound as a parameter. Invalid syntax is a database error. #### config? `string` Text search configuration; the server default when omitted. ### Returns [`Fn`](../interfaces/Fn.md) Function call expression. ### Throws Error when `config` is not a plain or schema-qualified identifier. ### Example ```ts await Post.findAll({ where: { search: { [Op.match]: toTsQuery('cat & !dog', 'english') } } }); ``` ## Function: toTsVector() > **toTsVector**(`document`, `config?`): [`Fn`](../interfaces/Fn.md) `to_tsvector([config,] document)`: parses a document into a `tsvector`. PostgreSQL extension. ### Parameters #### document `unknown` Text value (bound as a parameter) or an expression such as `col('body')`. #### config? `string` Text search configuration; the server default when omitted. ### Returns [`Fn`](../interfaces/Fn.md) Function call expression. ### Throws Error when `config` is not a plain or schema-qualified identifier. ### Example ```ts await Post.findAll({ where: where(toTsVector(col('body'), 'english'), Op.match, websearchToTsQuery('cat -dog', 'english')) }); ``` ## Function: trigramDistance() > **trigramDistance**(`left`, `right`): [`Where`](../interfaces/Where.md) `left <-> right` of `pg_trgm`: trigram distance (`1 - similarity`), served by GiST trigram indexes for nearest-neighbour `order`. PostgreSQL extension. ### Parameters #### left `unknown` Text expression, e.g. `col('name')`. #### right `unknown` Text expression or value (bound as a parameter). ### Returns [`Where`](../interfaces/Where.md) Where expression usable in `order` and `attributes`. ### Example ```ts await User.findAll({ order: [[trigramDistance(col('name'), 'jon'), 'ASC']], limit: 5 }); ``` ## Function: trigramSimilarity() > **trigramSimilarity**(`left`, `right`): [`Fn`](../interfaces/Fn.md) `similarity(a, b)` of `pg_trgm`: trigram similarity from 0 to 1. PostgreSQL extension; needs `CREATE EXTENSION pg_trgm`. ### Parameters #### left `unknown` Text expression, e.g. `col('name')`. #### right `unknown` Text expression or value (bound as a parameter). ### Returns [`Fn`](../interfaces/Fn.md) Function call expression. ### Example ```ts await User.findAll({ order: [[trigramSimilarity(col('name'), 'jon'), 'DESC']], limit: 5 }); ``` ## Function: trigramWordSimilarity() > **trigramWordSimilarity**(`left`, `right`): [`Fn`](../interfaces/Fn.md) `word_similarity(a, b)` of `pg_trgm`: similarity of `a` to the best matching part of `b`. PostgreSQL extension. ### Parameters #### left `unknown` Text expression or value, the searched word. #### right `unknown` Text expression, e.g. `col('body')`. ### Returns [`Fn`](../interfaces/Fn.md) Function call expression. ### Example ```ts await Post.findAll({ attributes: [[trigramWordSimilarity('postgre', col('title')), 'score']] }); ``` ## Function: tsHeadline() > **tsHeadline**(`document`, `query`, `options?`): [`Fn`](../interfaces/Fn.md) `ts_headline`: a document excerpt with the query terms highlighted. PostgreSQL extension. ### Parameters #### document `unknown` Text expression or value, bound as a parameter. #### query `unknown` `tsquery` expression. #### options? [`TsHeadlineOptions`](../type-aliases/TsHeadlineOptions.md) = `{}` Configuration and `ts_headline` options string. ### Returns [`Fn`](../interfaces/Fn.md) Function call expression. ### Throws Error when `config` is not a plain or schema-qualified identifier. ### Example ```ts await Post.findAll({ attributes: [[tsHeadline(col('body'), websearchToTsQuery('cat'), { options: 'StartSel=, StopSel=' }), 'excerpt']] }); ``` ## Function: tsRank() > **tsRank**(`vector`, `query`, `options?`): [`Fn`](../interfaces/Fn.md) `ts_rank` / `ts_rank_cd`: relevance of a `tsvector` for a `tsquery`, for `attributes` and `order`. PostgreSQL extension. ### Parameters #### vector `unknown` `tsvector` expression, e.g. `col('search')`. #### query `unknown` `tsquery` expression, e.g. [websearchToTsQuery](websearchToTsQuery.md). #### options? [`TsRankOptions`](../type-aliases/TsRankOptions.md) = `{}` `cd`, `weights` and `normalization`. ### Returns [`Fn`](../interfaces/Fn.md) Function call expression. ### Throws Error when `weights` is not four finite numbers or `normalization` is not an integer from 0 to 63. ### Example ```ts const query = websearchToTsQuery('cat', 'english'); await Post.findAll({ where: { search: { [Op.match]: query } }, order: [[tsRank(col('search'), query, { normalization: 1 }), 'DESC']] }); ``` ## Function: tuple() > **tuple**(...`items`): [`Tuple`](../interfaces/Tuple.md) Row constructor for row comparisons: `where(tuple(col('createdAt'), col('id')), Op.lt, tuple(date, id))`. PostgreSQL extension. ### Parameters #### items ...readonly `unknown`[] Row items (values or expressions). ### Returns [`Tuple`](../interfaces/Tuple.md) Row expression. ### Example ```ts const cursor = new Date(); await Post.findAll({ where: where(tuple(col('createdAt'), col('id')), Op.lt, tuple(cursor, 100)) }); ``` ## Function: useInflection() > **useInflection**(`custom`): `void` Replaces the inflection library used to singularize and pluralize association names and to underscore column names (Sequelize v6 `useInflection`). Call it before defining models. ### Parameters #### custom [`Inflection`](../interfaces/Inflection.md) Library with `singularize`, `pluralize` and `underscore`. ### Returns `void` ### See [Sequelize.useInflection](../classes/Sequelize.md#useinflection) ### Example ```ts useInflection({ singularize: (word) => word.replace(/s$/, ''), pluralize: (word) => `${word}s`, underscore: (word) => word.replace(/([A-Z])/g, '_$1').toLowerCase(), }); ``` ## Function: websearchToTsQuery() > **websearchToTsQuery**(`text`, `config?`): [`Fn`](../interfaces/Fn.md) `websearch_to_tsquery([config,] text)`: web-search syntax (quotes, `or`, `-`) that never fails to parse. PostgreSQL extension. ### Parameters #### text `unknown` User search text, bound as a parameter. #### config? `string` Text search configuration; the server default when omitted. ### Returns [`Fn`](../interfaces/Fn.md) Function call expression. ### Throws Error when `config` is not a plain or schema-qualified identifier. ### Example ```ts await Post.findAll({ where: { search: { [Op.match]: websearchToTsQuery('"fat cat" -dog', 'english') } } }); ``` ## Interface: BelongsToCreateAssociationMixinOptions Options of the `createX` accessor of a belongsTo association (Sequelize v6). ### Example ```ts const options: BelongsToCreateAssociationMixinOptions = { save: true, transaction }; ``` ### Extends - [`CreateOptions`](../type-aliases/CreateOptions.md)\<`any`\> - [`BelongsToSetAssociationMixinOptions`](BelongsToSetAssociationMixinOptions.md) ### Properties #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from [`BelongsToSetAssociationMixinOptions`](BelongsToSetAssociationMixinOptions.md).[`benchmark`](BelongsToSetAssociationMixinOptions.md#benchmark) *** #### fields? > `optional` **fields?**: readonly `any`[] Attributes to save; others are ignored. Default: all changed attributes. Mutable so hooks can adjust it, as in v6. ##### Inherited from `CreateOptions.fields` *** #### hooks? > `optional` **hooks?**: `boolean` Run lifecycle hooks. ##### Default Value ```ts true ``` ##### Inherited from [`BelongsToSetAssociationMixinOptions`](BelongsToSetAssociationMixinOptions.md).[`hooks`](BelongsToSetAssociationMixinOptions.md#hooks) *** #### include? > `optional` **include?**: [`IncludeOption`](../type-aliases/IncludeOption.md) Create associated rows from nested values (Sequelize v6). ##### Inherited from `CreateOptions.include` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from [`BelongsToSetAssociationMixinOptions`](BelongsToSetAssociationMixinOptions.md).[`logging`](BelongsToSetAssociationMixinOptions.md#logging) *** #### onConflict? > `optional` **onConflict?**: `Readonly`\<\{ `action`: `"nothing"` \| `Readonly`\<\{ `update`: [`OnConflictUpdate`](../type-aliases/OnConflictUpdate.md)\<`any`\>; `where?`: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\>; \}\>; `target?`: [`OnConflictTarget`](../type-aliases/OnConflictTarget.md)\<`any`\>; \}\> Advanced `ON CONFLICT` handling. PostgreSQL extension. ##### Inherited from `CreateOptions.onConflict` *** #### overriding? > `optional` **overriding?**: `"user"` \| `"system"` `OVERRIDING SYSTEM VALUE` / `OVERRIDING USER VALUE` for identity columns. PostgreSQL extension. ##### Inherited from [`BelongsToSetAssociationMixinOptions`](BelongsToSetAssociationMixinOptions.md).[`overriding`](BelongsToSetAssociationMixinOptions.md#overriding) *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from [`BelongsToSetAssociationMixinOptions`](BelongsToSetAssociationMixinOptions.md).[`replacements`](BelongsToSetAssociationMixinOptions.md#replacements) *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from [`BelongsToSetAssociationMixinOptions`](BelongsToSetAssociationMixinOptions.md).[`retry`](BelongsToSetAssociationMixinOptions.md#retry) *** #### returning? > `optional` **returning?**: `boolean` Return all columns after insert/update; PostgreSQL always uses `RETURNING`, so this is accepted for v6 compatibility. ##### Default Value ```ts true ``` ##### Inherited from [`BelongsToSetAssociationMixinOptions`](BelongsToSetAssociationMixinOptions.md).[`returning`](BelongsToSetAssociationMixinOptions.md#returning) *** #### save? > `optional` **save?**: `boolean` Skip saving the source after setting the foreign key when `false`. ##### Inherited from [`BelongsToSetAssociationMixinOptions`](BelongsToSetAssociationMixinOptions.md).[`save`](BelongsToSetAssociationMixinOptions.md#save) *** #### silent? > `optional` **silent?**: `boolean` Do not update `updatedAt`. ##### Default Value ```ts false ``` ##### Inherited from [`BelongsToSetAssociationMixinOptions`](BelongsToSetAssociationMixinOptions.md).[`silent`](BelongsToSetAssociationMixinOptions.md#silent) *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from [`BelongsToSetAssociationMixinOptions`](BelongsToSetAssociationMixinOptions.md).[`statementTimeout`](BelongsToSetAssociationMixinOptions.md#statementtimeout) *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from [`BelongsToSetAssociationMixinOptions`](BelongsToSetAssociationMixinOptions.md).[`transaction`](BelongsToSetAssociationMixinOptions.md#transaction) *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from [`BelongsToSetAssociationMixinOptions`](BelongsToSetAssociationMixinOptions.md).[`useMaster`](BelongsToSetAssociationMixinOptions.md#usemaster) *** #### validate? > `optional` **validate?**: `boolean` Run validations. ##### Default Value true (`false` for `bulkCreate`) ##### Inherited from [`BelongsToSetAssociationMixinOptions`](BelongsToSetAssociationMixinOptions.md).[`validate`](BelongsToSetAssociationMixinOptions.md#validate) ## Interface: BelongsToGetAssociationMixinOptions Options of the `getX` accessor of a belongsTo association (Sequelize v6). ### Example ```ts const options: BelongsToGetAssociationMixinOptions = { scope: false, transaction }; ``` ### Extends - [`FindOptions`](../type-aliases/FindOptions.md)\<`any`\> ### Properties #### attributes? > `optional` **attributes?**: [`FindAttributeOptions`](../type-aliases/FindAttributeOptions.md) Selected attributes. All attributes when omitted. ##### Inherited from `FindOptions.attributes` *** #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `FindOptions.benchmark` *** #### distinctOn? > `optional` **distinctOn?**: readonly `unknown`[] `SELECT DISTINCT ON (...)`: attributes or expressions. PostgreSQL extension. ##### Inherited from `FindOptions.distinctOn` *** #### from? > `readonly` `optional` **from?**: `Readonly`\<`Record`\<`string`, [`FromSourceOption`](../type-aliases/FromSourceOption.md)\>\> Extra relations (`FROM "Model", "alias"`), keyed by alias; correlate them in `where`. PostgreSQL extension. ##### Inherited from `FindOptions.from` *** #### group? > `optional` **group?**: `unknown` `GROUP BY` attributes or expressions. ##### Inherited from `FindOptions.group` *** #### having? > `optional` **having?**: `unknown` `HAVING` condition. ##### Inherited from `FindOptions.having` *** #### hooks? > `optional` **hooks?**: `boolean` Run `beforeFind` / `afterFind` hooks. ##### Default Value ```ts true ``` ##### Inherited from `FindOptions.hooks` *** #### include? > `optional` **include?**: [`IncludeOption`](../type-aliases/IncludeOption.md) Eager-load associations through JOINs (or separate queries for `separate` includes). ##### Inherited from `FindOptions.include` *** #### limit? > `optional` **limit?**: `number` \| `null` Maximum number of rows; `null` or `undefined` for no limit. ##### Inherited from `FindOptions.limit` *** #### lock? > `optional` **lock?**: [`LockOption`](../type-aliases/LockOption.md) Row lock (`FOR UPDATE` etc.); requires a transaction. ##### Inherited from `FindOptions.lock` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `FindOptions.logging` *** #### nest? > `optional` **nest?**: `boolean` With `raw`, build nested objects from dotted keys such as `'posts.title'`. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.nest` *** #### noWait? > `optional` **noWait?**: `boolean` Add `NOWAIT` to the row lock so the query fails instead of waiting; only with `lock`. PostgreSQL extension. ##### Inherited from `FindOptions.noWait` *** #### offset? > `optional` **offset?**: `number` \| `null` Number of rows to skip; `null` or `undefined` to skip none. ##### Inherited from `FindOptions.offset` *** #### order? > `optional` **order?**: readonly `unknown`[] \| [`Order`](../type-aliases/Order.md) Sort order: attribute names, `[attribute, 'ASC' | 'DESC']` pairs or expressions. ##### Inherited from `FindOptions.order` *** #### paranoid? > `optional` **paranoid?**: `boolean` For paranoid models: `false` includes soft-deleted rows. ##### Default Value ```ts true ``` ##### Inherited from `FindOptions.paranoid` *** #### plain? > `optional` **plain?**: `boolean` Return a single row instead of an array (set internally by `findOne`). ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.plain` *** #### raw? > `optional` **raw?**: `boolean` Return plain row objects instead of model instances. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.raw` *** #### rejectOnEmpty? > `optional` **rejectOnEmpty?**: `boolean` \| `Error` Throw `EmptyResultError` (or the given `Error`) when no row is found. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.rejectOnEmpty` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `FindOptions.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `FindOptions.retry` *** #### sample? > `optional` **sample?**: `Readonly`\<\{ `method`: `"BERNOULLI"` \| `"SYSTEM"`; `percent`: `number`; `seed?`: `number`; \}\> Read only a random sample of the model table (`TABLESAMPLE`). PostgreSQL extension. ##### Inherited from `FindOptions.sample` *** #### scope? > `optional` **scope?**: `string` \| `boolean` \| `string`[] Scope to apply on the associated model, or `false` to remove its default scope. *** #### skipLocked? > `optional` **skipLocked?**: `boolean` Add `SKIP LOCKED` to the row lock; only with `lock`. ##### Inherited from `FindOptions.skipLocked` *** #### source? > `readonly` `optional` **source?**: `string` \| [`Subquery`](Subquery.md) Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (`a.union(b)`), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. ##### Inherited from `FindOptions.source` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `FindOptions.statementTimeout` *** #### subQuery? > `optional` **subQuery?**: `boolean` `false` disables the sub-query used for `limit` combined with multi-row includes. ##### Inherited from `FindOptions.subQuery` *** #### tableAs? > `optional` **tableAs?**: `string` Alias of the main table in `FROM` instead of the model name, so `literal`s and `col('alias.x')` can refer to it (a v6 internal option that v6's typings omit). Ignored when `include` is set. ##### Inherited from `FindOptions.tableAs` *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `FindOptions.transaction` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `FindOptions.useMaster` *** #### where? > `optional` **where?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Filter rows; see [WhereOptions](../type-aliases/WhereOptions.md). All rows when omitted. ##### Inherited from `FindOptions.where` *** #### with? > `readonly` `optional` **with?**: `Readonly`\<`Record`\<`string`, [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md) \| `Readonly`\<\{ `cycle?`: `Readonly`\<\{ `columns`: readonly `string`[]; `set`: `string`; `using`: `string`; \}\>; `materialized?`: `boolean`; `query`: [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md); `recursive?`: [`Subquery`](Subquery.md); `search?`: `Readonly`\<\{ `by`: readonly `string`[]; `mode?`: `"breadth"` \| `"depth"`; `set`: `string`; \}\>; `unionAll?`: `boolean`; \}\>\>\> Common table expressions (`WITH [RECURSIVE] ...`). PostgreSQL extension. ##### Inherited from `FindOptions.with` *** #### withTies? > `optional` **withTies?**: `boolean` `FETCH FIRST limit ROWS WITH TIES` instead of `LIMIT`: also returns the rows that tie with the last one on the `order` columns. Needs `limit` and `order`. PostgreSQL extension. ##### Inherited from `FindOptions.withTies` ## Interface: BelongsToManyAddAssociationMixinOptions Options of the `addX` accessor of a belongsToMany association (Sequelize v6). ### Example ```ts const options: BelongsToManyAddAssociationMixinOptions = { through: { role: 'member' } }; ``` ### Extends - [`FindOptions`](../type-aliases/FindOptions.md)\<`any`\> - [`BulkCreateOptions`](../type-aliases/BulkCreateOptions.md)\<`any`\> - [`InstanceUpdateOptions`](../type-aliases/InstanceUpdateOptions.md)\<`any`\> - [`InstanceDestroyOptions`](../type-aliases/InstanceDestroyOptions.md) ### Properties #### attributes? > `optional` **attributes?**: [`FindAttributeOptions`](../type-aliases/FindAttributeOptions.md) Selected attributes. All attributes when omitted. ##### Inherited from `FindOptions.attributes` *** #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `FindOptions.benchmark` *** #### conflictAttributes? > `optional` **conflictAttributes?**: readonly `string`[] Conflict target attributes for `updateOnDuplicate`. Default: first unique key, else primary key. ##### Inherited from `BulkCreateOptions.conflictAttributes` *** #### conflictWhere? > `optional` **conflictWhere?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Predicate of a partial unique index used as conflict target. ##### Inherited from `BulkCreateOptions.conflictWhere` *** #### distinctOn? > `optional` **distinctOn?**: readonly `unknown`[] `SELECT DISTINCT ON (...)`: attributes or expressions. PostgreSQL extension. ##### Inherited from `FindOptions.distinctOn` *** #### fields? > `optional` **fields?**: readonly `any`[] Attributes to save; others are ignored. Default: all changed attributes. Mutable so hooks can adjust it, as in v6. ##### Inherited from `BulkCreateOptions.fields` *** #### force? > `optional` **force?**: `boolean` For paranoid models: delete the row instead of setting `deletedAt`. ##### Default Value ```ts false ``` ##### Inherited from `InstanceDestroyOptions.force` *** #### from? > `readonly` `optional` **from?**: `Readonly`\<`Record`\<`string`, [`FromSourceOption`](../type-aliases/FromSourceOption.md)\>\> Extra relations (`FROM "Model", "alias"`), keyed by alias; correlate them in `where`. PostgreSQL extension. ##### Inherited from `FindOptions.from` *** #### group? > `optional` **group?**: `unknown` `GROUP BY` attributes or expressions. ##### Inherited from `FindOptions.group` *** #### having? > `optional` **having?**: `unknown` `HAVING` condition. ##### Inherited from `FindOptions.having` *** #### hooks? > `optional` **hooks?**: `boolean` Run `beforeFind` / `afterFind` hooks. ##### Default Value ```ts true ``` ##### Inherited from `FindOptions.hooks` *** #### ignoreDuplicates? > `optional` **ignoreDuplicates?**: `boolean` Add `ON CONFLICT DO NOTHING`, skipping rows that violate a unique constraint. ##### Default Value ```ts false ``` ##### Inherited from `BulkCreateOptions.ignoreDuplicates` *** #### include? > `optional` **include?**: [`IncludeOption`](../type-aliases/IncludeOption.md) Eager-load associations through JOINs (or separate queries for `separate` includes). ##### Inherited from `FindOptions.include` *** #### individualHooks? > `optional` **individualHooks?**: `boolean` Run per-instance `create` hooks (rows are then inserted one by one, like v6). ##### Default Value ```ts false ``` ##### Inherited from `BulkCreateOptions.individualHooks` *** #### limit? > `optional` **limit?**: `number` \| `null` Maximum number of rows; `null` or `undefined` for no limit. ##### Inherited from `FindOptions.limit` *** #### lock? > `optional` **lock?**: [`LockOption`](../type-aliases/LockOption.md) Row lock (`FOR UPDATE` etc.); requires a transaction. ##### Inherited from `FindOptions.lock` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `FindOptions.logging` *** #### nest? > `optional` **nest?**: `boolean` With `raw`, build nested objects from dotted keys such as `'posts.title'`. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.nest` *** #### noWait? > `optional` **noWait?**: `boolean` Add `NOWAIT` to the row lock so the query fails instead of waiting; only with `lock`. PostgreSQL extension. ##### Inherited from `FindOptions.noWait` *** #### offset? > `optional` **offset?**: `number` \| `null` Number of rows to skip; `null` or `undefined` to skip none. ##### Inherited from `FindOptions.offset` *** #### onConflict? > `optional` **onConflict?**: `Readonly`\<\{ `action`: `"nothing"` \| `Readonly`\<\{ `update`: [`OnConflictUpdate`](../type-aliases/OnConflictUpdate.md)\<`any`\>; `where?`: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\>; \}\>; `target?`: [`OnConflictTarget`](../type-aliases/OnConflictTarget.md)\<`any`\>; \}\> Advanced `ON CONFLICT` handling; cannot be combined with the options above. PostgreSQL extension. ##### Inherited from `BulkCreateOptions.onConflict` *** #### order? > `optional` **order?**: readonly `unknown`[] \| [`Order`](../type-aliases/Order.md) Sort order: attribute names, `[attribute, 'ASC' | 'DESC']` pairs or expressions. ##### Inherited from `FindOptions.order` *** #### overriding? > `optional` **overriding?**: `"user"` \| `"system"` `OVERRIDING SYSTEM VALUE` / `OVERRIDING USER VALUE` for identity columns. PostgreSQL extension. ##### Inherited from `BulkCreateOptions.overriding` *** #### paranoid? > `optional` **paranoid?**: `boolean` For paranoid models: `false` includes soft-deleted rows. ##### Default Value ```ts true ``` ##### Inherited from `FindOptions.paranoid` *** #### plain? > `optional` **plain?**: `boolean` Return a single row instead of an array (set internally by `findOne`). ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.plain` *** #### raw? > `optional` **raw?**: `boolean` Return plain row objects instead of model instances. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.raw` *** #### rejectOnEmpty? > `optional` **rejectOnEmpty?**: `boolean` \| `Error` Throw `EmptyResultError` (or the given `Error`) when no row is found. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.rejectOnEmpty` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `FindOptions.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `FindOptions.retry` *** #### returning? > `optional` **returning?**: `boolean` Return all columns after insert/update; PostgreSQL always uses `RETURNING`, so this is accepted for v6 compatibility. ##### Default Value ```ts true ``` ##### Inherited from `BulkCreateOptions.returning` *** #### sample? > `optional` **sample?**: `Readonly`\<\{ `method`: `"BERNOULLI"` \| `"SYSTEM"`; `percent`: `number`; `seed?`: `number`; \}\> Read only a random sample of the model table (`TABLESAMPLE`). PostgreSQL extension. ##### Inherited from `FindOptions.sample` *** #### silent? > `optional` **silent?**: `boolean` Do not update `updatedAt`. ##### Default Value ```ts false ``` ##### Inherited from `BulkCreateOptions.silent` *** #### skipLocked? > `optional` **skipLocked?**: `boolean` Add `SKIP LOCKED` to the row lock; only with `lock`. ##### Inherited from `FindOptions.skipLocked` *** #### source? > `readonly` `optional` **source?**: `string` \| [`Subquery`](Subquery.md) Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (`a.union(b)`), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. ##### Inherited from `FindOptions.source` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `FindOptions.statementTimeout` *** #### subQuery? > `optional` **subQuery?**: `boolean` `false` disables the sub-query used for `limit` combined with multi-row includes. ##### Inherited from `FindOptions.subQuery` *** #### tableAs? > `optional` **tableAs?**: `string` Alias of the main table in `FROM` instead of the model name, so `literal`s and `col('alias.x')` can refer to it (a v6 internal option that v6's typings omit). Ignored when `include` is set. ##### Inherited from `FindOptions.tableAs` *** #### through? > `optional` **through?**: [`JoinTableAttributes`](JoinTableAttributes.md) Attributes of the junction row. *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `FindOptions.transaction` *** #### unnest? > `optional` **unnest?**: `boolean` Insert with one array parameter per column (`INSERT … SELECT * FROM unnest($1::type[], …)`) instead of one parameter per cell, so batches are not capped by PostgreSQL's 65535 parameters. Every row must provide every column; `ARRAY` columns and conflict options are not supported. PostgreSQL extension. ##### Default Value ```ts false @postgrelize ``` ##### Inherited from `BulkCreateOptions.unnest` *** #### updateOnDuplicate? > `optional` **updateOnDuplicate?**: readonly `string`[] Attributes updated from the proposed row on conflict (`DO UPDATE SET a = EXCLUDED.a`). ##### Inherited from `BulkCreateOptions.updateOnDuplicate` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `FindOptions.useMaster` *** #### validate? > `optional` **validate?**: `boolean` Run validations. ##### Default Value true (`false` for `bulkCreate`) ##### Inherited from `BulkCreateOptions.validate` *** #### where? > `optional` **where?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Filter rows; see [WhereOptions](../type-aliases/WhereOptions.md). All rows when omitted. ##### Inherited from `FindOptions.where` *** #### with? > `readonly` `optional` **with?**: `Readonly`\<`Record`\<`string`, [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md) \| `Readonly`\<\{ `cycle?`: `Readonly`\<\{ `columns`: readonly `string`[]; `set`: `string`; `using`: `string`; \}\>; `materialized?`: `boolean`; `query`: [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md); `recursive?`: [`Subquery`](Subquery.md); `search?`: `Readonly`\<\{ `by`: readonly `string`[]; `mode?`: `"breadth"` \| `"depth"`; `set`: `string`; \}\>; `unionAll?`: `boolean`; \}\>\>\> Common table expressions (`WITH [RECURSIVE] ...`). PostgreSQL extension. ##### Inherited from `FindOptions.with` *** #### withTies? > `optional` **withTies?**: `boolean` `FETCH FIRST limit ROWS WITH TIES` instead of `LIMIT`: also returns the rows that tie with the last one on the `order` columns. Needs `limit` and `order`. PostgreSQL extension. ##### Inherited from `FindOptions.withTies` ## Interface: BelongsToManyAddAssociationsMixinOptions Options of the `addXs` accessor of a belongsToMany association (Sequelize v6). ### Example ```ts const options: BelongsToManyAddAssociationsMixinOptions = { through: { role: 'member' } }; ``` ### Extends - [`FindOptions`](../type-aliases/FindOptions.md)\<`any`\> - [`BulkCreateOptions`](../type-aliases/BulkCreateOptions.md)\<`any`\> - [`InstanceUpdateOptions`](../type-aliases/InstanceUpdateOptions.md)\<`any`\> - [`InstanceDestroyOptions`](../type-aliases/InstanceDestroyOptions.md) ### Properties #### attributes? > `optional` **attributes?**: [`FindAttributeOptions`](../type-aliases/FindAttributeOptions.md) Selected attributes. All attributes when omitted. ##### Inherited from `FindOptions.attributes` *** #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `FindOptions.benchmark` *** #### conflictAttributes? > `optional` **conflictAttributes?**: readonly `string`[] Conflict target attributes for `updateOnDuplicate`. Default: first unique key, else primary key. ##### Inherited from `BulkCreateOptions.conflictAttributes` *** #### conflictWhere? > `optional` **conflictWhere?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Predicate of a partial unique index used as conflict target. ##### Inherited from `BulkCreateOptions.conflictWhere` *** #### distinctOn? > `optional` **distinctOn?**: readonly `unknown`[] `SELECT DISTINCT ON (...)`: attributes or expressions. PostgreSQL extension. ##### Inherited from `FindOptions.distinctOn` *** #### fields? > `optional` **fields?**: readonly `any`[] Attributes to save; others are ignored. Default: all changed attributes. Mutable so hooks can adjust it, as in v6. ##### Inherited from `BulkCreateOptions.fields` *** #### force? > `optional` **force?**: `boolean` For paranoid models: delete the row instead of setting `deletedAt`. ##### Default Value ```ts false ``` ##### Inherited from `InstanceDestroyOptions.force` *** #### from? > `readonly` `optional` **from?**: `Readonly`\<`Record`\<`string`, [`FromSourceOption`](../type-aliases/FromSourceOption.md)\>\> Extra relations (`FROM "Model", "alias"`), keyed by alias; correlate them in `where`. PostgreSQL extension. ##### Inherited from `FindOptions.from` *** #### group? > `optional` **group?**: `unknown` `GROUP BY` attributes or expressions. ##### Inherited from `FindOptions.group` *** #### having? > `optional` **having?**: `unknown` `HAVING` condition. ##### Inherited from `FindOptions.having` *** #### hooks? > `optional` **hooks?**: `boolean` Run `beforeFind` / `afterFind` hooks. ##### Default Value ```ts true ``` ##### Inherited from `FindOptions.hooks` *** #### ignoreDuplicates? > `optional` **ignoreDuplicates?**: `boolean` Add `ON CONFLICT DO NOTHING`, skipping rows that violate a unique constraint. ##### Default Value ```ts false ``` ##### Inherited from `BulkCreateOptions.ignoreDuplicates` *** #### include? > `optional` **include?**: [`IncludeOption`](../type-aliases/IncludeOption.md) Eager-load associations through JOINs (or separate queries for `separate` includes). ##### Inherited from `FindOptions.include` *** #### individualHooks? > `optional` **individualHooks?**: `boolean` Run per-instance `create` hooks (rows are then inserted one by one, like v6). ##### Default Value ```ts false ``` ##### Inherited from `BulkCreateOptions.individualHooks` *** #### limit? > `optional` **limit?**: `number` \| `null` Maximum number of rows; `null` or `undefined` for no limit. ##### Inherited from `FindOptions.limit` *** #### lock? > `optional` **lock?**: [`LockOption`](../type-aliases/LockOption.md) Row lock (`FOR UPDATE` etc.); requires a transaction. ##### Inherited from `FindOptions.lock` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `FindOptions.logging` *** #### nest? > `optional` **nest?**: `boolean` With `raw`, build nested objects from dotted keys such as `'posts.title'`. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.nest` *** #### noWait? > `optional` **noWait?**: `boolean` Add `NOWAIT` to the row lock so the query fails instead of waiting; only with `lock`. PostgreSQL extension. ##### Inherited from `FindOptions.noWait` *** #### offset? > `optional` **offset?**: `number` \| `null` Number of rows to skip; `null` or `undefined` to skip none. ##### Inherited from `FindOptions.offset` *** #### onConflict? > `optional` **onConflict?**: `Readonly`\<\{ `action`: `"nothing"` \| `Readonly`\<\{ `update`: [`OnConflictUpdate`](../type-aliases/OnConflictUpdate.md)\<`any`\>; `where?`: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\>; \}\>; `target?`: [`OnConflictTarget`](../type-aliases/OnConflictTarget.md)\<`any`\>; \}\> Advanced `ON CONFLICT` handling; cannot be combined with the options above. PostgreSQL extension. ##### Inherited from `BulkCreateOptions.onConflict` *** #### order? > `optional` **order?**: readonly `unknown`[] \| [`Order`](../type-aliases/Order.md) Sort order: attribute names, `[attribute, 'ASC' | 'DESC']` pairs or expressions. ##### Inherited from `FindOptions.order` *** #### overriding? > `optional` **overriding?**: `"user"` \| `"system"` `OVERRIDING SYSTEM VALUE` / `OVERRIDING USER VALUE` for identity columns. PostgreSQL extension. ##### Inherited from `BulkCreateOptions.overriding` *** #### paranoid? > `optional` **paranoid?**: `boolean` For paranoid models: `false` includes soft-deleted rows. ##### Default Value ```ts true ``` ##### Inherited from `FindOptions.paranoid` *** #### plain? > `optional` **plain?**: `boolean` Return a single row instead of an array (set internally by `findOne`). ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.plain` *** #### raw? > `optional` **raw?**: `boolean` Return plain row objects instead of model instances. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.raw` *** #### rejectOnEmpty? > `optional` **rejectOnEmpty?**: `boolean` \| `Error` Throw `EmptyResultError` (or the given `Error`) when no row is found. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.rejectOnEmpty` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `FindOptions.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `FindOptions.retry` *** #### returning? > `optional` **returning?**: `boolean` Return all columns after insert/update; PostgreSQL always uses `RETURNING`, so this is accepted for v6 compatibility. ##### Default Value ```ts true ``` ##### Inherited from `BulkCreateOptions.returning` *** #### sample? > `optional` **sample?**: `Readonly`\<\{ `method`: `"BERNOULLI"` \| `"SYSTEM"`; `percent`: `number`; `seed?`: `number`; \}\> Read only a random sample of the model table (`TABLESAMPLE`). PostgreSQL extension. ##### Inherited from `FindOptions.sample` *** #### silent? > `optional` **silent?**: `boolean` Do not update `updatedAt`. ##### Default Value ```ts false ``` ##### Inherited from `BulkCreateOptions.silent` *** #### skipLocked? > `optional` **skipLocked?**: `boolean` Add `SKIP LOCKED` to the row lock; only with `lock`. ##### Inherited from `FindOptions.skipLocked` *** #### source? > `readonly` `optional` **source?**: `string` \| [`Subquery`](Subquery.md) Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (`a.union(b)`), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. ##### Inherited from `FindOptions.source` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `FindOptions.statementTimeout` *** #### subQuery? > `optional` **subQuery?**: `boolean` `false` disables the sub-query used for `limit` combined with multi-row includes. ##### Inherited from `FindOptions.subQuery` *** #### tableAs? > `optional` **tableAs?**: `string` Alias of the main table in `FROM` instead of the model name, so `literal`s and `col('alias.x')` can refer to it (a v6 internal option that v6's typings omit). Ignored when `include` is set. ##### Inherited from `FindOptions.tableAs` *** #### through? > `optional` **through?**: [`JoinTableAttributes`](JoinTableAttributes.md) Attributes of the junction row. *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `FindOptions.transaction` *** #### unnest? > `optional` **unnest?**: `boolean` Insert with one array parameter per column (`INSERT … SELECT * FROM unnest($1::type[], …)`) instead of one parameter per cell, so batches are not capped by PostgreSQL's 65535 parameters. Every row must provide every column; `ARRAY` columns and conflict options are not supported. PostgreSQL extension. ##### Default Value ```ts false @postgrelize ``` ##### Inherited from `BulkCreateOptions.unnest` *** #### updateOnDuplicate? > `optional` **updateOnDuplicate?**: readonly `string`[] Attributes updated from the proposed row on conflict (`DO UPDATE SET a = EXCLUDED.a`). ##### Inherited from `BulkCreateOptions.updateOnDuplicate` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `FindOptions.useMaster` *** #### validate? > `optional` **validate?**: `boolean` Run validations. ##### Default Value true (`false` for `bulkCreate`) ##### Inherited from `BulkCreateOptions.validate` *** #### where? > `optional` **where?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Filter rows; see [WhereOptions](../type-aliases/WhereOptions.md). All rows when omitted. ##### Inherited from `FindOptions.where` *** #### with? > `readonly` `optional` **with?**: `Readonly`\<`Record`\<`string`, [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md) \| `Readonly`\<\{ `cycle?`: `Readonly`\<\{ `columns`: readonly `string`[]; `set`: `string`; `using`: `string`; \}\>; `materialized?`: `boolean`; `query`: [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md); `recursive?`: [`Subquery`](Subquery.md); `search?`: `Readonly`\<\{ `by`: readonly `string`[]; `mode?`: `"breadth"` \| `"depth"`; `set`: `string`; \}\>; `unionAll?`: `boolean`; \}\>\>\> Common table expressions (`WITH [RECURSIVE] ...`). PostgreSQL extension. ##### Inherited from `FindOptions.with` *** #### withTies? > `optional` **withTies?**: `boolean` `FETCH FIRST limit ROWS WITH TIES` instead of `LIMIT`: also returns the rows that tie with the last one on the `order` columns. Needs `limit` and `order`. PostgreSQL extension. ##### Inherited from `FindOptions.withTies` ## Interface: BelongsToManyCountAssociationsMixinOptions Options of the `countXs` accessor of a belongsToMany association (Sequelize v6). ### Example ```ts const options: BelongsToManyCountAssociationsMixinOptions = { where: { active: true } }; ``` ### Extends - [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) ### Properties #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `QueryOptionsBase.benchmark` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `QueryOptionsBase.logging` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `QueryOptionsBase.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `QueryOptionsBase.retry` *** #### scope? > `optional` **scope?**: `string` \| `boolean` Scope to apply on the associated model, or `false` to remove its default scope. *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `QueryOptionsBase.statementTimeout` *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `QueryOptionsBase.transaction` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `QueryOptionsBase.useMaster` *** #### where? > `optional` **where?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Filter on the counted rows. ## Interface: BelongsToManyCreateAssociationMixinOptions Options of the `createX` accessor of a belongsToMany association (Sequelize v6). ### Example ```ts const options: BelongsToManyCreateAssociationMixinOptions = { through: { role: 'member' } }; ``` ### Extends - [`CreateOptions`](../type-aliases/CreateOptions.md)\<`any`\> ### Properties #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `CreateOptions.benchmark` *** #### fields? > `optional` **fields?**: readonly `any`[] Attributes to save; others are ignored. Default: all changed attributes. Mutable so hooks can adjust it, as in v6. ##### Inherited from `CreateOptions.fields` *** #### hooks? > `optional` **hooks?**: `boolean` Run lifecycle hooks. ##### Default Value ```ts true ``` ##### Inherited from `CreateOptions.hooks` *** #### include? > `optional` **include?**: [`IncludeOption`](../type-aliases/IncludeOption.md) Create associated rows from nested values (Sequelize v6). ##### Inherited from `CreateOptions.include` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `CreateOptions.logging` *** #### onConflict? > `optional` **onConflict?**: `Readonly`\<\{ `action`: `"nothing"` \| `Readonly`\<\{ `update`: [`OnConflictUpdate`](../type-aliases/OnConflictUpdate.md)\<`any`\>; `where?`: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\>; \}\>; `target?`: [`OnConflictTarget`](../type-aliases/OnConflictTarget.md)\<`any`\>; \}\> Advanced `ON CONFLICT` handling. PostgreSQL extension. ##### Inherited from `CreateOptions.onConflict` *** #### overriding? > `optional` **overriding?**: `"user"` \| `"system"` `OVERRIDING SYSTEM VALUE` / `OVERRIDING USER VALUE` for identity columns. PostgreSQL extension. ##### Inherited from `CreateOptions.overriding` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `CreateOptions.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `CreateOptions.retry` *** #### returning? > `optional` **returning?**: `boolean` Return all columns after insert/update; PostgreSQL always uses `RETURNING`, so this is accepted for v6 compatibility. ##### Default Value ```ts true ``` ##### Inherited from `CreateOptions.returning` *** #### silent? > `optional` **silent?**: `boolean` Do not update `updatedAt`. ##### Default Value ```ts false ``` ##### Inherited from `CreateOptions.silent` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `CreateOptions.statementTimeout` *** #### through? > `optional` **through?**: [`JoinTableAttributes`](JoinTableAttributes.md) Attributes of the junction row. *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `CreateOptions.transaction` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `CreateOptions.useMaster` *** #### validate? > `optional` **validate?**: `boolean` Run validations. ##### Default Value true (`false` for `bulkCreate`) ##### Inherited from `CreateOptions.validate` ## Interface: BelongsToManyGetAssociationsMixinOptions Options of the `getXs` accessor of a belongsToMany association (Sequelize v6). ### Example ```ts const options: BelongsToManyGetAssociationsMixinOptions = { joinTableAttributes: [] }; ``` ### Extends - [`FindOptions`](../type-aliases/FindOptions.md)\<`any`\> ### Extended by - [`BelongsToManyHasAssociationMixinOptions`](BelongsToManyHasAssociationMixinOptions.md) - [`BelongsToManyHasAssociationsMixinOptions`](BelongsToManyHasAssociationsMixinOptions.md) ### Properties #### attributes? > `optional` **attributes?**: [`FindAttributeOptions`](../type-aliases/FindAttributeOptions.md) Selected attributes. All attributes when omitted. ##### Inherited from `FindOptions.attributes` *** #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `FindOptions.benchmark` *** #### distinctOn? > `optional` **distinctOn?**: readonly `unknown`[] `SELECT DISTINCT ON (...)`: attributes or expressions. PostgreSQL extension. ##### Inherited from `FindOptions.distinctOn` *** #### from? > `readonly` `optional` **from?**: `Readonly`\<`Record`\<`string`, [`FromSourceOption`](../type-aliases/FromSourceOption.md)\>\> Extra relations (`FROM "Model", "alias"`), keyed by alias; correlate them in `where`. PostgreSQL extension. ##### Inherited from `FindOptions.from` *** #### group? > `optional` **group?**: `unknown` `GROUP BY` attributes or expressions. ##### Inherited from `FindOptions.group` *** #### having? > `optional` **having?**: `unknown` `HAVING` condition. ##### Inherited from `FindOptions.having` *** #### hooks? > `optional` **hooks?**: `boolean` Run `beforeFind` / `afterFind` hooks. ##### Default Value ```ts true ``` ##### Inherited from `FindOptions.hooks` *** #### include? > `optional` **include?**: [`IncludeOption`](../type-aliases/IncludeOption.md) Eager-load associations through JOINs (or separate queries for `separate` includes). ##### Inherited from `FindOptions.include` *** #### joinTableAttributes? > `optional` **joinTableAttributes?**: [`FindAttributeOptions`](../type-aliases/FindAttributeOptions.md) Junction attributes to select. *** #### limit? > `optional` **limit?**: `number` \| `null` Maximum number of rows; `null` or `undefined` for no limit. ##### Inherited from `FindOptions.limit` *** #### lock? > `optional` **lock?**: [`LockOption`](../type-aliases/LockOption.md) Row lock (`FOR UPDATE` etc.); requires a transaction. ##### Inherited from `FindOptions.lock` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `FindOptions.logging` *** #### nest? > `optional` **nest?**: `boolean` With `raw`, build nested objects from dotted keys such as `'posts.title'`. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.nest` *** #### noWait? > `optional` **noWait?**: `boolean` Add `NOWAIT` to the row lock so the query fails instead of waiting; only with `lock`. PostgreSQL extension. ##### Inherited from `FindOptions.noWait` *** #### offset? > `optional` **offset?**: `number` \| `null` Number of rows to skip; `null` or `undefined` to skip none. ##### Inherited from `FindOptions.offset` *** #### order? > `optional` **order?**: readonly `unknown`[] \| [`Order`](../type-aliases/Order.md) Sort order: attribute names, `[attribute, 'ASC' | 'DESC']` pairs or expressions. ##### Inherited from `FindOptions.order` *** #### paranoid? > `optional` **paranoid?**: `boolean` For paranoid models: `false` includes soft-deleted rows. ##### Default Value ```ts true ``` ##### Inherited from `FindOptions.paranoid` *** #### plain? > `optional` **plain?**: `boolean` Return a single row instead of an array (set internally by `findOne`). ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.plain` *** #### raw? > `optional` **raw?**: `boolean` Return plain row objects instead of model instances. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.raw` *** #### rejectOnEmpty? > `optional` **rejectOnEmpty?**: `boolean` \| `Error` Throw `EmptyResultError` (or the given `Error`) when no row is found. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.rejectOnEmpty` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `FindOptions.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `FindOptions.retry` *** #### sample? > `optional` **sample?**: `Readonly`\<\{ `method`: `"BERNOULLI"` \| `"SYSTEM"`; `percent`: `number`; `seed?`: `number`; \}\> Read only a random sample of the model table (`TABLESAMPLE`). PostgreSQL extension. ##### Inherited from `FindOptions.sample` *** #### scope? > `optional` **scope?**: `string` \| `boolean` Scope to apply on the associated model, or `false` to remove its default scope. *** #### skipLocked? > `optional` **skipLocked?**: `boolean` Add `SKIP LOCKED` to the row lock; only with `lock`. ##### Inherited from `FindOptions.skipLocked` *** #### source? > `readonly` `optional` **source?**: `string` \| [`Subquery`](Subquery.md) Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (`a.union(b)`), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. ##### Inherited from `FindOptions.source` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `FindOptions.statementTimeout` *** #### subQuery? > `optional` **subQuery?**: `boolean` `false` disables the sub-query used for `limit` combined with multi-row includes. ##### Inherited from `FindOptions.subQuery` *** #### tableAs? > `optional` **tableAs?**: `string` Alias of the main table in `FROM` instead of the model name, so `literal`s and `col('alias.x')` can refer to it (a v6 internal option that v6's typings omit). Ignored when `include` is set. ##### Inherited from `FindOptions.tableAs` *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `FindOptions.transaction` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `FindOptions.useMaster` *** #### where? > `optional` **where?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Filter rows; see [WhereOptions](../type-aliases/WhereOptions.md). All rows when omitted. ##### Inherited from `FindOptions.where` *** #### with? > `readonly` `optional` **with?**: `Readonly`\<`Record`\<`string`, [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md) \| `Readonly`\<\{ `cycle?`: `Readonly`\<\{ `columns`: readonly `string`[]; `set`: `string`; `using`: `string`; \}\>; `materialized?`: `boolean`; `query`: [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md); `recursive?`: [`Subquery`](Subquery.md); `search?`: `Readonly`\<\{ `by`: readonly `string`[]; `mode?`: `"breadth"` \| `"depth"`; `set`: `string`; \}\>; `unionAll?`: `boolean`; \}\>\>\> Common table expressions (`WITH [RECURSIVE] ...`). PostgreSQL extension. ##### Inherited from `FindOptions.with` *** #### withTies? > `optional` **withTies?**: `boolean` `FETCH FIRST limit ROWS WITH TIES` instead of `LIMIT`: also returns the rows that tie with the last one on the `order` columns. Needs `limit` and `order`. PostgreSQL extension. ##### Inherited from `FindOptions.withTies` ## Interface: BelongsToManyHasAssociationMixinOptions Options of the `hasX` accessor of a belongsToMany association (Sequelize v6). ### Example ```ts const options: BelongsToManyHasAssociationMixinOptions = { transaction }; ``` ### Extends - [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md) ### Properties #### attributes? > `optional` **attributes?**: [`FindAttributeOptions`](../type-aliases/FindAttributeOptions.md) Selected attributes. All attributes when omitted. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.attributes` *** #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`benchmark`](BelongsToManyGetAssociationsMixinOptions.md#benchmark) *** #### distinctOn? > `optional` **distinctOn?**: readonly `unknown`[] `SELECT DISTINCT ON (...)`: attributes or expressions. PostgreSQL extension. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.distinctOn` *** #### from? > `readonly` `optional` **from?**: `Readonly`\<`Record`\<`string`, [`FromSourceOption`](../type-aliases/FromSourceOption.md)\>\> Extra relations (`FROM "Model", "alias"`), keyed by alias; correlate them in `where`. PostgreSQL extension. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.from` *** #### group? > `optional` **group?**: `unknown` `GROUP BY` attributes or expressions. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.group` *** #### having? > `optional` **having?**: `unknown` `HAVING` condition. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.having` *** #### hooks? > `optional` **hooks?**: `boolean` Run `beforeFind` / `afterFind` hooks. ##### Default Value ```ts true ``` ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`hooks`](BelongsToManyGetAssociationsMixinOptions.md#hooks) *** #### include? > `optional` **include?**: [`IncludeOption`](../type-aliases/IncludeOption.md) Eager-load associations through JOINs (or separate queries for `separate` includes). ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.include` *** #### joinTableAttributes? > `optional` **joinTableAttributes?**: [`FindAttributeOptions`](../type-aliases/FindAttributeOptions.md) Junction attributes to select. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`joinTableAttributes`](BelongsToManyGetAssociationsMixinOptions.md#jointableattributes) *** #### limit? > `optional` **limit?**: `number` \| `null` Maximum number of rows; `null` or `undefined` for no limit. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.limit` *** #### lock? > `optional` **lock?**: [`LockOption`](../type-aliases/LockOption.md) Row lock (`FOR UPDATE` etc.); requires a transaction. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.lock` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`logging`](BelongsToManyGetAssociationsMixinOptions.md#logging) *** #### nest? > `optional` **nest?**: `boolean` With `raw`, build nested objects from dotted keys such as `'posts.title'`. ##### Default Value ```ts false ``` ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`nest`](BelongsToManyGetAssociationsMixinOptions.md#nest) *** #### noWait? > `optional` **noWait?**: `boolean` Add `NOWAIT` to the row lock so the query fails instead of waiting; only with `lock`. PostgreSQL extension. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.noWait` *** #### offset? > `optional` **offset?**: `number` \| `null` Number of rows to skip; `null` or `undefined` to skip none. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.offset` *** #### order? > `optional` **order?**: readonly `unknown`[] \| [`Order`](../type-aliases/Order.md) Sort order: attribute names, `[attribute, 'ASC' | 'DESC']` pairs or expressions. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.order` *** #### paranoid? > `optional` **paranoid?**: `boolean` For paranoid models: `false` includes soft-deleted rows. ##### Default Value ```ts true ``` ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`paranoid`](BelongsToManyGetAssociationsMixinOptions.md#paranoid) *** #### plain? > `optional` **plain?**: `boolean` Return a single row instead of an array (set internally by `findOne`). ##### Default Value ```ts false ``` ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`plain`](BelongsToManyGetAssociationsMixinOptions.md#plain) *** #### raw? > `optional` **raw?**: `boolean` Return plain row objects instead of model instances. ##### Default Value ```ts false ``` ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`raw`](BelongsToManyGetAssociationsMixinOptions.md#raw) *** #### rejectOnEmpty? > `optional` **rejectOnEmpty?**: `boolean` \| `Error` Throw `EmptyResultError` (or the given `Error`) when no row is found. ##### Default Value ```ts false ``` ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`rejectOnEmpty`](BelongsToManyGetAssociationsMixinOptions.md#rejectonempty) *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`replacements`](BelongsToManyGetAssociationsMixinOptions.md#replacements) *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`retry`](BelongsToManyGetAssociationsMixinOptions.md#retry) *** #### sample? > `optional` **sample?**: `Readonly`\<\{ `method`: `"BERNOULLI"` \| `"SYSTEM"`; `percent`: `number`; `seed?`: `number`; \}\> Read only a random sample of the model table (`TABLESAMPLE`). PostgreSQL extension. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.sample` *** #### scope? > `optional` **scope?**: `string` \| `boolean` Scope to apply on the associated model, or `false` to remove its default scope. ##### Inherited from `BelongsToManyHasAssociationMixinOptions`.[`scope`](#scope) *** #### skipLocked? > `optional` **skipLocked?**: `boolean` Add `SKIP LOCKED` to the row lock; only with `lock`. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.skipLocked` *** #### source? > `readonly` `optional` **source?**: `string` \| [`Subquery`](Subquery.md) Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (`a.union(b)`), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.source` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`statementTimeout`](BelongsToManyGetAssociationsMixinOptions.md#statementtimeout) *** #### subQuery? > `optional` **subQuery?**: `boolean` `false` disables the sub-query used for `limit` combined with multi-row includes. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`subQuery`](BelongsToManyGetAssociationsMixinOptions.md#subquery) *** #### tableAs? > `optional` **tableAs?**: `string` Alias of the main table in `FROM` instead of the model name, so `literal`s and `col('alias.x')` can refer to it (a v6 internal option that v6's typings omit). Ignored when `include` is set. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`tableAs`](BelongsToManyGetAssociationsMixinOptions.md#tableas) *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`transaction`](BelongsToManyGetAssociationsMixinOptions.md#transaction) *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`useMaster`](BelongsToManyGetAssociationsMixinOptions.md#usemaster) *** #### where? > `optional` **where?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Filter rows; see [WhereOptions](../type-aliases/WhereOptions.md). All rows when omitted. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.where` *** #### with? > `readonly` `optional` **with?**: `Readonly`\<`Record`\<`string`, [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md) \| `Readonly`\<\{ `cycle?`: `Readonly`\<\{ `columns`: readonly `string`[]; `set`: `string`; `using`: `string`; \}\>; `materialized?`: `boolean`; `query`: [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md); `recursive?`: [`Subquery`](Subquery.md); `search?`: `Readonly`\<\{ `by`: readonly `string`[]; `mode?`: `"breadth"` \| `"depth"`; `set`: `string`; \}\>; `unionAll?`: `boolean`; \}\>\>\> Common table expressions (`WITH [RECURSIVE] ...`). PostgreSQL extension. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.with` *** #### withTies? > `optional` **withTies?**: `boolean` `FETCH FIRST limit ROWS WITH TIES` instead of `LIMIT`: also returns the rows that tie with the last one on the `order` columns. Needs `limit` and `order`. PostgreSQL extension. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.withTies` ## Interface: BelongsToManyHasAssociationsMixinOptions Options of the `hasXs` accessor of a belongsToMany association (Sequelize v6). ### Example ```ts const options: BelongsToManyHasAssociationsMixinOptions = { transaction }; ``` ### Extends - [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md) ### Properties #### attributes? > `optional` **attributes?**: [`FindAttributeOptions`](../type-aliases/FindAttributeOptions.md) Selected attributes. All attributes when omitted. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.attributes` *** #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`benchmark`](BelongsToManyGetAssociationsMixinOptions.md#benchmark) *** #### distinctOn? > `optional` **distinctOn?**: readonly `unknown`[] `SELECT DISTINCT ON (...)`: attributes or expressions. PostgreSQL extension. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.distinctOn` *** #### from? > `readonly` `optional` **from?**: `Readonly`\<`Record`\<`string`, [`FromSourceOption`](../type-aliases/FromSourceOption.md)\>\> Extra relations (`FROM "Model", "alias"`), keyed by alias; correlate them in `where`. PostgreSQL extension. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.from` *** #### group? > `optional` **group?**: `unknown` `GROUP BY` attributes or expressions. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.group` *** #### having? > `optional` **having?**: `unknown` `HAVING` condition. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.having` *** #### hooks? > `optional` **hooks?**: `boolean` Run `beforeFind` / `afterFind` hooks. ##### Default Value ```ts true ``` ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`hooks`](BelongsToManyGetAssociationsMixinOptions.md#hooks) *** #### include? > `optional` **include?**: [`IncludeOption`](../type-aliases/IncludeOption.md) Eager-load associations through JOINs (or separate queries for `separate` includes). ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.include` *** #### joinTableAttributes? > `optional` **joinTableAttributes?**: [`FindAttributeOptions`](../type-aliases/FindAttributeOptions.md) Junction attributes to select. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`joinTableAttributes`](BelongsToManyGetAssociationsMixinOptions.md#jointableattributes) *** #### limit? > `optional` **limit?**: `number` \| `null` Maximum number of rows; `null` or `undefined` for no limit. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.limit` *** #### lock? > `optional` **lock?**: [`LockOption`](../type-aliases/LockOption.md) Row lock (`FOR UPDATE` etc.); requires a transaction. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.lock` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`logging`](BelongsToManyGetAssociationsMixinOptions.md#logging) *** #### nest? > `optional` **nest?**: `boolean` With `raw`, build nested objects from dotted keys such as `'posts.title'`. ##### Default Value ```ts false ``` ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`nest`](BelongsToManyGetAssociationsMixinOptions.md#nest) *** #### noWait? > `optional` **noWait?**: `boolean` Add `NOWAIT` to the row lock so the query fails instead of waiting; only with `lock`. PostgreSQL extension. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.noWait` *** #### offset? > `optional` **offset?**: `number` \| `null` Number of rows to skip; `null` or `undefined` to skip none. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.offset` *** #### order? > `optional` **order?**: readonly `unknown`[] \| [`Order`](../type-aliases/Order.md) Sort order: attribute names, `[attribute, 'ASC' | 'DESC']` pairs or expressions. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.order` *** #### paranoid? > `optional` **paranoid?**: `boolean` For paranoid models: `false` includes soft-deleted rows. ##### Default Value ```ts true ``` ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`paranoid`](BelongsToManyGetAssociationsMixinOptions.md#paranoid) *** #### plain? > `optional` **plain?**: `boolean` Return a single row instead of an array (set internally by `findOne`). ##### Default Value ```ts false ``` ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`plain`](BelongsToManyGetAssociationsMixinOptions.md#plain) *** #### raw? > `optional` **raw?**: `boolean` Return plain row objects instead of model instances. ##### Default Value ```ts false ``` ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`raw`](BelongsToManyGetAssociationsMixinOptions.md#raw) *** #### rejectOnEmpty? > `optional` **rejectOnEmpty?**: `boolean` \| `Error` Throw `EmptyResultError` (or the given `Error`) when no row is found. ##### Default Value ```ts false ``` ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`rejectOnEmpty`](BelongsToManyGetAssociationsMixinOptions.md#rejectonempty) *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`replacements`](BelongsToManyGetAssociationsMixinOptions.md#replacements) *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`retry`](BelongsToManyGetAssociationsMixinOptions.md#retry) *** #### sample? > `optional` **sample?**: `Readonly`\<\{ `method`: `"BERNOULLI"` \| `"SYSTEM"`; `percent`: `number`; `seed?`: `number`; \}\> Read only a random sample of the model table (`TABLESAMPLE`). PostgreSQL extension. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.sample` *** #### scope? > `optional` **scope?**: `string` \| `boolean` Scope to apply on the associated model, or `false` to remove its default scope. ##### Inherited from [`BelongsToManyHasAssociationMixinOptions`](BelongsToManyHasAssociationMixinOptions.md).[`scope`](BelongsToManyHasAssociationMixinOptions.md#scope) *** #### skipLocked? > `optional` **skipLocked?**: `boolean` Add `SKIP LOCKED` to the row lock; only with `lock`. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.skipLocked` *** #### source? > `readonly` `optional` **source?**: `string` \| [`Subquery`](Subquery.md) Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (`a.union(b)`), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.source` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`statementTimeout`](BelongsToManyGetAssociationsMixinOptions.md#statementtimeout) *** #### subQuery? > `optional` **subQuery?**: `boolean` `false` disables the sub-query used for `limit` combined with multi-row includes. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`subQuery`](BelongsToManyGetAssociationsMixinOptions.md#subquery) *** #### tableAs? > `optional` **tableAs?**: `string` Alias of the main table in `FROM` instead of the model name, so `literal`s and `col('alias.x')` can refer to it (a v6 internal option that v6's typings omit). Ignored when `include` is set. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`tableAs`](BelongsToManyGetAssociationsMixinOptions.md#tableas) *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`transaction`](BelongsToManyGetAssociationsMixinOptions.md#transaction) *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from [`BelongsToManyGetAssociationsMixinOptions`](BelongsToManyGetAssociationsMixinOptions.md).[`useMaster`](BelongsToManyGetAssociationsMixinOptions.md#usemaster) *** #### where? > `optional` **where?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Filter rows; see [WhereOptions](../type-aliases/WhereOptions.md). All rows when omitted. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.where` *** #### with? > `readonly` `optional` **with?**: `Readonly`\<`Record`\<`string`, [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md) \| `Readonly`\<\{ `cycle?`: `Readonly`\<\{ `columns`: readonly `string`[]; `set`: `string`; `using`: `string`; \}\>; `materialized?`: `boolean`; `query`: [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md); `recursive?`: [`Subquery`](Subquery.md); `search?`: `Readonly`\<\{ `by`: readonly `string`[]; `mode?`: `"breadth"` \| `"depth"`; `set`: `string`; \}\>; `unionAll?`: `boolean`; \}\>\>\> Common table expressions (`WITH [RECURSIVE] ...`). PostgreSQL extension. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.with` *** #### withTies? > `optional` **withTies?**: `boolean` `FETCH FIRST limit ROWS WITH TIES` instead of `LIMIT`: also returns the rows that tie with the last one on the `order` columns. Needs `limit` and `order`. PostgreSQL extension. ##### Inherited from `BelongsToManyGetAssociationsMixinOptions.withTies` ## Interface: BelongsToManyRemoveAssociationMixinOptions Options of the `removeX` accessor of a belongsToMany association (Sequelize v6). ### Example ```ts const options: BelongsToManyRemoveAssociationMixinOptions = { transaction }; ``` ### Extends - [`InstanceDestroyOptions`](../type-aliases/InstanceDestroyOptions.md) ### Properties #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `InstanceDestroyOptions.benchmark` *** #### force? > `optional` **force?**: `boolean` For paranoid models: delete the row instead of setting `deletedAt`. ##### Default Value ```ts false ``` ##### Inherited from `InstanceDestroyOptions.force` *** #### hooks? > `optional` **hooks?**: `boolean` Run `beforeDestroy` / `afterDestroy` hooks. ##### Default Value ```ts true ``` ##### Inherited from `InstanceDestroyOptions.hooks` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `InstanceDestroyOptions.logging` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `InstanceDestroyOptions.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `InstanceDestroyOptions.retry` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `InstanceDestroyOptions.statementTimeout` *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `InstanceDestroyOptions.transaction` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `InstanceDestroyOptions.useMaster` ## Interface: BelongsToManyRemoveAssociationsMixinOptions Options of the `removeXs` accessor of a belongsToMany association (Sequelize v6). ### Example ```ts const options: BelongsToManyRemoveAssociationsMixinOptions = { transaction }; ``` ### Extends - [`InstanceDestroyOptions`](../type-aliases/InstanceDestroyOptions.md) ### Properties #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `InstanceDestroyOptions.benchmark` *** #### force? > `optional` **force?**: `boolean` For paranoid models: delete the row instead of setting `deletedAt`. ##### Default Value ```ts false ``` ##### Inherited from `InstanceDestroyOptions.force` *** #### hooks? > `optional` **hooks?**: `boolean` Run `beforeDestroy` / `afterDestroy` hooks. ##### Default Value ```ts true ``` ##### Inherited from `InstanceDestroyOptions.hooks` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `InstanceDestroyOptions.logging` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `InstanceDestroyOptions.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `InstanceDestroyOptions.retry` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `InstanceDestroyOptions.statementTimeout` *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `InstanceDestroyOptions.transaction` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `InstanceDestroyOptions.useMaster` ## Interface: BelongsToManySetAssociationsMixinOptions Options of the `setXs` accessor of a belongsToMany association (Sequelize v6). ### Example ```ts const options: BelongsToManySetAssociationsMixinOptions = { through: { role: 'owner' } }; ``` ### Extends - [`FindOptions`](../type-aliases/FindOptions.md)\<`any`\> - [`BulkCreateOptions`](../type-aliases/BulkCreateOptions.md)\<`any`\> - [`InstanceUpdateOptions`](../type-aliases/InstanceUpdateOptions.md)\<`any`\> - [`InstanceDestroyOptions`](../type-aliases/InstanceDestroyOptions.md) ### Properties #### attributes? > `optional` **attributes?**: [`FindAttributeOptions`](../type-aliases/FindAttributeOptions.md) Selected attributes. All attributes when omitted. ##### Inherited from `FindOptions.attributes` *** #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `FindOptions.benchmark` *** #### conflictAttributes? > `optional` **conflictAttributes?**: readonly `string`[] Conflict target attributes for `updateOnDuplicate`. Default: first unique key, else primary key. ##### Inherited from `BulkCreateOptions.conflictAttributes` *** #### conflictWhere? > `optional` **conflictWhere?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Predicate of a partial unique index used as conflict target. ##### Inherited from `BulkCreateOptions.conflictWhere` *** #### distinctOn? > `optional` **distinctOn?**: readonly `unknown`[] `SELECT DISTINCT ON (...)`: attributes or expressions. PostgreSQL extension. ##### Inherited from `FindOptions.distinctOn` *** #### fields? > `optional` **fields?**: readonly `any`[] Attributes to save; others are ignored. Default: all changed attributes. Mutable so hooks can adjust it, as in v6. ##### Inherited from `BulkCreateOptions.fields` *** #### force? > `optional` **force?**: `boolean` For paranoid models: delete the row instead of setting `deletedAt`. ##### Default Value ```ts false ``` ##### Inherited from `InstanceDestroyOptions.force` *** #### from? > `readonly` `optional` **from?**: `Readonly`\<`Record`\<`string`, [`FromSourceOption`](../type-aliases/FromSourceOption.md)\>\> Extra relations (`FROM "Model", "alias"`), keyed by alias; correlate them in `where`. PostgreSQL extension. ##### Inherited from `FindOptions.from` *** #### group? > `optional` **group?**: `unknown` `GROUP BY` attributes or expressions. ##### Inherited from `FindOptions.group` *** #### having? > `optional` **having?**: `unknown` `HAVING` condition. ##### Inherited from `FindOptions.having` *** #### hooks? > `optional` **hooks?**: `boolean` Run `beforeFind` / `afterFind` hooks. ##### Default Value ```ts true ``` ##### Inherited from `FindOptions.hooks` *** #### ignoreDuplicates? > `optional` **ignoreDuplicates?**: `boolean` Add `ON CONFLICT DO NOTHING`, skipping rows that violate a unique constraint. ##### Default Value ```ts false ``` ##### Inherited from `BulkCreateOptions.ignoreDuplicates` *** #### include? > `optional` **include?**: [`IncludeOption`](../type-aliases/IncludeOption.md) Eager-load associations through JOINs (or separate queries for `separate` includes). ##### Inherited from `FindOptions.include` *** #### individualHooks? > `optional` **individualHooks?**: `boolean` Run per-instance `create` hooks (rows are then inserted one by one, like v6). ##### Default Value ```ts false ``` ##### Inherited from `BulkCreateOptions.individualHooks` *** #### limit? > `optional` **limit?**: `number` \| `null` Maximum number of rows; `null` or `undefined` for no limit. ##### Inherited from `FindOptions.limit` *** #### lock? > `optional` **lock?**: [`LockOption`](../type-aliases/LockOption.md) Row lock (`FOR UPDATE` etc.); requires a transaction. ##### Inherited from `FindOptions.lock` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `FindOptions.logging` *** #### nest? > `optional` **nest?**: `boolean` With `raw`, build nested objects from dotted keys such as `'posts.title'`. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.nest` *** #### noWait? > `optional` **noWait?**: `boolean` Add `NOWAIT` to the row lock so the query fails instead of waiting; only with `lock`. PostgreSQL extension. ##### Inherited from `FindOptions.noWait` *** #### offset? > `optional` **offset?**: `number` \| `null` Number of rows to skip; `null` or `undefined` to skip none. ##### Inherited from `FindOptions.offset` *** #### onConflict? > `optional` **onConflict?**: `Readonly`\<\{ `action`: `"nothing"` \| `Readonly`\<\{ `update`: [`OnConflictUpdate`](../type-aliases/OnConflictUpdate.md)\<`any`\>; `where?`: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\>; \}\>; `target?`: [`OnConflictTarget`](../type-aliases/OnConflictTarget.md)\<`any`\>; \}\> Advanced `ON CONFLICT` handling; cannot be combined with the options above. PostgreSQL extension. ##### Inherited from `BulkCreateOptions.onConflict` *** #### order? > `optional` **order?**: readonly `unknown`[] \| [`Order`](../type-aliases/Order.md) Sort order: attribute names, `[attribute, 'ASC' | 'DESC']` pairs or expressions. ##### Inherited from `FindOptions.order` *** #### overriding? > `optional` **overriding?**: `"user"` \| `"system"` `OVERRIDING SYSTEM VALUE` / `OVERRIDING USER VALUE` for identity columns. PostgreSQL extension. ##### Inherited from `BulkCreateOptions.overriding` *** #### paranoid? > `optional` **paranoid?**: `boolean` For paranoid models: `false` includes soft-deleted rows. ##### Default Value ```ts true ``` ##### Inherited from `FindOptions.paranoid` *** #### plain? > `optional` **plain?**: `boolean` Return a single row instead of an array (set internally by `findOne`). ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.plain` *** #### raw? > `optional` **raw?**: `boolean` Return plain row objects instead of model instances. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.raw` *** #### rejectOnEmpty? > `optional` **rejectOnEmpty?**: `boolean` \| `Error` Throw `EmptyResultError` (or the given `Error`) when no row is found. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.rejectOnEmpty` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `FindOptions.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `FindOptions.retry` *** #### returning? > `optional` **returning?**: `boolean` Return all columns after insert/update; PostgreSQL always uses `RETURNING`, so this is accepted for v6 compatibility. ##### Default Value ```ts true ``` ##### Inherited from `BulkCreateOptions.returning` *** #### sample? > `optional` **sample?**: `Readonly`\<\{ `method`: `"BERNOULLI"` \| `"SYSTEM"`; `percent`: `number`; `seed?`: `number`; \}\> Read only a random sample of the model table (`TABLESAMPLE`). PostgreSQL extension. ##### Inherited from `FindOptions.sample` *** #### silent? > `optional` **silent?**: `boolean` Do not update `updatedAt`. ##### Default Value ```ts false ``` ##### Inherited from `BulkCreateOptions.silent` *** #### skipLocked? > `optional` **skipLocked?**: `boolean` Add `SKIP LOCKED` to the row lock; only with `lock`. ##### Inherited from `FindOptions.skipLocked` *** #### source? > `readonly` `optional` **source?**: `string` \| [`Subquery`](Subquery.md) Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (`a.union(b)`), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. ##### Inherited from `FindOptions.source` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `FindOptions.statementTimeout` *** #### subQuery? > `optional` **subQuery?**: `boolean` `false` disables the sub-query used for `limit` combined with multi-row includes. ##### Inherited from `FindOptions.subQuery` *** #### tableAs? > `optional` **tableAs?**: `string` Alias of the main table in `FROM` instead of the model name, so `literal`s and `col('alias.x')` can refer to it (a v6 internal option that v6's typings omit). Ignored when `include` is set. ##### Inherited from `FindOptions.tableAs` *** #### through? > `optional` **through?**: [`JoinTableAttributes`](JoinTableAttributes.md) Attributes of the junction row. *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `FindOptions.transaction` *** #### unnest? > `optional` **unnest?**: `boolean` Insert with one array parameter per column (`INSERT … SELECT * FROM unnest($1::type[], …)`) instead of one parameter per cell, so batches are not capped by PostgreSQL's 65535 parameters. Every row must provide every column; `ARRAY` columns and conflict options are not supported. PostgreSQL extension. ##### Default Value ```ts false @postgrelize ``` ##### Inherited from `BulkCreateOptions.unnest` *** #### updateOnDuplicate? > `optional` **updateOnDuplicate?**: readonly `string`[] Attributes updated from the proposed row on conflict (`DO UPDATE SET a = EXCLUDED.a`). ##### Inherited from `BulkCreateOptions.updateOnDuplicate` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `FindOptions.useMaster` *** #### validate? > `optional` **validate?**: `boolean` Run validations. ##### Default Value true (`false` for `bulkCreate`) ##### Inherited from `BulkCreateOptions.validate` *** #### where? > `optional` **where?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Filter rows; see [WhereOptions](../type-aliases/WhereOptions.md). All rows when omitted. ##### Inherited from `FindOptions.where` *** #### with? > `readonly` `optional` **with?**: `Readonly`\<`Record`\<`string`, [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md) \| `Readonly`\<\{ `cycle?`: `Readonly`\<\{ `columns`: readonly `string`[]; `set`: `string`; `using`: `string`; \}\>; `materialized?`: `boolean`; `query`: [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md); `recursive?`: [`Subquery`](Subquery.md); `search?`: `Readonly`\<\{ `by`: readonly `string`[]; `mode?`: `"breadth"` \| `"depth"`; `set`: `string`; \}\>; `unionAll?`: `boolean`; \}\>\>\> Common table expressions (`WITH [RECURSIVE] ...`). PostgreSQL extension. ##### Inherited from `FindOptions.with` *** #### withTies? > `optional` **withTies?**: `boolean` `FETCH FIRST limit ROWS WITH TIES` instead of `LIMIT`: also returns the rows that tie with the last one on the `order` columns. Needs `limit` and `order`. PostgreSQL extension. ##### Inherited from `FindOptions.withTies` ## Interface: BelongsToSetAssociationMixinOptions Options of the `setX` accessor of a belongsTo association (Sequelize v6). ### Example ```ts const options: BelongsToSetAssociationMixinOptions = { save: false }; ``` ### Extends - [`SaveOptions`](../type-aliases/SaveOptions.md)\<`any`\> ### Extended by - [`BelongsToCreateAssociationMixinOptions`](BelongsToCreateAssociationMixinOptions.md) ### Properties #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `SaveOptions.benchmark` *** #### fields? > `optional` **fields?**: readonly `any`[] Attributes to save; others are ignored. Default: all changed attributes. Mutable so hooks can adjust it, as in v6. ##### Inherited from `SaveOptions.fields` *** #### hooks? > `optional` **hooks?**: `boolean` Run lifecycle hooks. ##### Default Value ```ts true ``` ##### Inherited from `SaveOptions.hooks` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `SaveOptions.logging` *** #### overriding? > `optional` **overriding?**: `"user"` \| `"system"` `OVERRIDING SYSTEM VALUE` / `OVERRIDING USER VALUE` for identity columns. PostgreSQL extension. ##### Inherited from `SaveOptions.overriding` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `SaveOptions.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `SaveOptions.retry` *** #### returning? > `optional` **returning?**: `boolean` Return all columns after insert/update; PostgreSQL always uses `RETURNING`, so this is accepted for v6 compatibility. ##### Default Value ```ts true ``` ##### Inherited from `SaveOptions.returning` *** #### save? > `optional` **save?**: `boolean` Skip saving the source after setting the foreign key when `false`. *** #### silent? > `optional` **silent?**: `boolean` Do not update `updatedAt`. ##### Default Value ```ts false ``` ##### Inherited from `SaveOptions.silent` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `SaveOptions.statementTimeout` *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `SaveOptions.transaction` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `SaveOptions.useMaster` *** #### validate? > `optional` **validate?**: `boolean` Run validations. ##### Default Value true (`false` for `bulkCreate`) ##### Inherited from `SaveOptions.validate` ## Interface: Cast Type cast `CAST(value AS type)`. Created by [cast](../functions/cast.md). ### Extends - [`SqlExpression`](SqlExpression.md) ### Properties #### json > `readonly` **json**: `boolean` = `false` Kept for Sequelize v6 compatibility. *** #### type > `readonly` **type**: `string` Target type. *** #### val > `readonly` **val**: `unknown` Value or expression to cast. ## Interface: Col Column reference. Created by [col](#col). ### Extends - [`SqlExpression`](SqlExpression.md) ### Properties #### col > `readonly` **col**: `string` \| readonly `string`[] Column name or path. ## Interface: ConnectionManagerContract Acquire / release contract of `sequelize.connectionManager`. Every query, transaction, COPY and `sync` of the instance takes its pooled connection through `getConnection` and gives it back through `releaseConnection`, looked up on the manager at call time: both may be replaced on the instance (wrapped) to route connections. ### Example ```ts const manager = sequelize.connectionManager; const defaultGet = manager.getConnection.bind(manager); manager.getConnection = async (options) => { console.log('acquiring', options?.type ?? 'write'); return defaultGet(options); }; ``` ### Properties #### pool > `readonly` **pool**: [`ConnectionPool`](ConnectionPool.md) Live connection counts of the instance's pools, for health gauges. ##### Example ```ts const { size, using, waiting, maxSize } = sequelize.connectionManager.pool; ``` ### Methods #### destroyConnection() > **destroyConnection**(`connection`): `Promise`\<`void`\> Removes a broken connection from the pool that owns it instead of returning it: the client is closed and the pool opens a replacement when one is needed. The connection must not be used or released afterwards (a later release is ignored). ##### Parameters ###### connection [`Connection`](../type-aliases/Connection.md) Connection obtained from `getConnection`. ##### Returns `Promise`\<`void`\> Resolves when the connection is removed from its pool. ##### Example ```ts const connection = await sequelize.connectionManager.getConnection({ type: 'read' }); try { await connection.query('SELECT 1'); await sequelize.connectionManager.releaseConnection(connection); } catch (error) { await sequelize.connectionManager.destroyConnection(connection); throw error; } ``` *** #### getConnection() > **getConnection**(`options?`): `Promise`\<`Client`\> Acquires a pooled connection. ##### Parameters ###### options? `Readonly`\<\{ `type?`: `"read"` \| `"write"` \| `"SELECT"`; `useMaster?`: `boolean`; `uuid?`: `string`; \}\> Replica selection and transaction id. ##### Returns `Promise`\<`Client`\> A connection that stays checked out until it is passed to `releaseConnection`. ##### Example ```ts const connection = await sequelize.connectionManager.getConnection({ type: 'read' }); await sequelize.connectionManager.releaseConnection(connection); ``` *** #### releaseConnection() > **releaseConnection**(`connection`): `void` \| `Promise`\<`void`\> Returns a connection obtained from `getConnection` to the pool that owns it. ##### Parameters ###### connection [`Connection`](../type-aliases/Connection.md) Connection to release. ##### Returns `void` \| `Promise`\<`void`\> Nothing (may be asynchronous). ##### Example ```ts const connection = await sequelize.connectionManager.getConnection(); await connection.query('SELECT 1'); await sequelize.connectionManager.releaseConnection(connection); ``` ## Interface: ConnectionPool `sequelize.connectionManager.pool`: [PoolCounters](PoolCounters.md) of the whole instance. With `replication` configured the counters are the sums over the writer pool and every replica pool (v6 has no totals there, it has a separate `read` and `write` pool), and `read` / `write` give the counters of each side. `read` sums all replicas. Without replication `read` and `write` are `undefined`. ### Example ```ts const { write, read } = sequelize.connectionManager.pool; console.log(write?.using, read?.using); ``` ### Extends - [`PoolCounters`](PoolCounters.md) ### Properties #### available > `readonly` **available**: `number` Idle connections ready to be handed out (`idleCount`). ##### Inherited from [`PoolCounters`](PoolCounters.md).[`available`](PoolCounters.md#available) *** #### maxSize > `readonly` **maxSize**: `number` Configured `pool.max` (the `pg` default of 10 when unset). ##### Inherited from [`PoolCounters`](PoolCounters.md).[`maxSize`](PoolCounters.md#maxsize) *** #### read > `readonly` **read**: [`PoolCounters`](PoolCounters.md) \| `undefined` Counters of all read replica pools together; only with `replication`. *** #### size > `readonly` **size**: `number` Open connections, idle and checked out (`totalCount` of the `pg` pool). ##### Inherited from [`PoolCounters`](PoolCounters.md).[`size`](PoolCounters.md#size) *** #### using > `readonly` **using**: `number` Checked out connections: `size - available`. ##### Inherited from [`PoolCounters`](PoolCounters.md).[`using`](PoolCounters.md#using) *** #### waiting > `readonly` **waiting**: `number` Acquisitions waiting for a free connection (`waitingCount`). ##### Inherited from [`PoolCounters`](PoolCounters.md).[`waiting`](PoolCounters.md#waiting) *** #### write > `readonly` **write**: [`PoolCounters`](PoolCounters.md) \| `undefined` Counters of the writer pool; only with `replication`. ## Interface: DefaultValueGenerator Default value marker (`DataTypes.NOW`, `DataTypes.UUIDV4`): generates a value on the client when a row is built. ### Properties #### generate > `readonly` **generate**: () => `unknown` Produces the default value. ##### Returns `unknown` *** #### key > `readonly` **key**: `string` Sequelize v6 type key, e.g. `'UUIDV4'`. ## Interface: Excluded Reference to a column of the row proposed for insertion in `ON CONFLICT DO UPDATE`. Created by [excluded](../functions/excluded.md). ### Extends - [`SqlExpression`](SqlExpression.md) ### Properties #### column > `readonly` **column**: `string` Attribute name. ## Interface: Exists `EXISTS (subquery)` / `NOT EXISTS (subquery)`. Created by [exists](../functions/exists.md) / [notExists](../functions/notExists.md). ### Extends - [`SqlExpression`](SqlExpression.md) ### Properties #### negated > `readonly` **negated**: `boolean` `NOT EXISTS`. *** #### subquery > `readonly` **subquery**: [`Subquery`](Subquery.md) The wrapped `SELECT` that `EXISTS` tests for rows. ## Interface: Fn SQL function call. Created by [fn](#fn). ### Extends - [`SqlExpression`](SqlExpression.md) ### Properties #### args > `readonly` **args**: readonly `unknown`[] Arguments. *** #### fn > `readonly` **fn**: `string` Function name. ## Interface: HasManyAddAssociationMixinOptions Options of the `addX` accessor of a hasMany association (Sequelize v6). ### Example ```ts const options: HasManyAddAssociationMixinOptions = { transaction }; ``` ### Extends - [`InstanceUpdateOptions`](../type-aliases/InstanceUpdateOptions.md)\<`any`\> ### Properties #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `InstanceUpdateOptions.benchmark` *** #### fields? > `optional` **fields?**: readonly `any`[] Attributes to save; others are ignored. Default: all changed attributes. Mutable so hooks can adjust it, as in v6. ##### Inherited from `InstanceUpdateOptions.fields` *** #### hooks? > `optional` **hooks?**: `boolean` Run lifecycle hooks. ##### Default Value ```ts true ``` ##### Inherited from `InstanceUpdateOptions.hooks` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `InstanceUpdateOptions.logging` *** #### overriding? > `optional` **overriding?**: `"user"` \| `"system"` `OVERRIDING SYSTEM VALUE` / `OVERRIDING USER VALUE` for identity columns. PostgreSQL extension. ##### Inherited from `InstanceUpdateOptions.overriding` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `InstanceUpdateOptions.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `InstanceUpdateOptions.retry` *** #### returning? > `optional` **returning?**: `boolean` Return all columns after insert/update; PostgreSQL always uses `RETURNING`, so this is accepted for v6 compatibility. ##### Default Value ```ts true ``` ##### Inherited from `InstanceUpdateOptions.returning` *** #### silent? > `optional` **silent?**: `boolean` Do not update `updatedAt`. ##### Default Value ```ts false ``` ##### Inherited from `InstanceUpdateOptions.silent` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `InstanceUpdateOptions.statementTimeout` *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `InstanceUpdateOptions.transaction` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `InstanceUpdateOptions.useMaster` *** #### validate? > `optional` **validate?**: `boolean` Run validations. ##### Default Value true (`false` for `bulkCreate`) ##### Inherited from `InstanceUpdateOptions.validate` ## Interface: HasManyAddAssociationsMixinOptions Options of the `addXs` accessor of a hasMany association (Sequelize v6). ### Example ```ts const options: HasManyAddAssociationsMixinOptions = { transaction }; ``` ### Extends - [`InstanceUpdateOptions`](../type-aliases/InstanceUpdateOptions.md)\<`any`\> ### Properties #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `InstanceUpdateOptions.benchmark` *** #### fields? > `optional` **fields?**: readonly `any`[] Attributes to save; others are ignored. Default: all changed attributes. Mutable so hooks can adjust it, as in v6. ##### Inherited from `InstanceUpdateOptions.fields` *** #### hooks? > `optional` **hooks?**: `boolean` Run lifecycle hooks. ##### Default Value ```ts true ``` ##### Inherited from `InstanceUpdateOptions.hooks` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `InstanceUpdateOptions.logging` *** #### overriding? > `optional` **overriding?**: `"user"` \| `"system"` `OVERRIDING SYSTEM VALUE` / `OVERRIDING USER VALUE` for identity columns. PostgreSQL extension. ##### Inherited from `InstanceUpdateOptions.overriding` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `InstanceUpdateOptions.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `InstanceUpdateOptions.retry` *** #### returning? > `optional` **returning?**: `boolean` Return all columns after insert/update; PostgreSQL always uses `RETURNING`, so this is accepted for v6 compatibility. ##### Default Value ```ts true ``` ##### Inherited from `InstanceUpdateOptions.returning` *** #### silent? > `optional` **silent?**: `boolean` Do not update `updatedAt`. ##### Default Value ```ts false ``` ##### Inherited from `InstanceUpdateOptions.silent` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `InstanceUpdateOptions.statementTimeout` *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `InstanceUpdateOptions.transaction` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `InstanceUpdateOptions.useMaster` *** #### validate? > `optional` **validate?**: `boolean` Run validations. ##### Default Value true (`false` for `bulkCreate`) ##### Inherited from `InstanceUpdateOptions.validate` ## Interface: HasManyCountAssociationsMixinOptions Options of the `countXs` accessor of a hasMany association (Sequelize v6). ### Example ```ts const options: HasManyCountAssociationsMixinOptions = { where: { active: true } }; ``` ### Extends - [`QueryOptionsBase`](../type-aliases/QueryOptionsBase.md) ### Properties #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `QueryOptionsBase.benchmark` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `QueryOptionsBase.logging` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `QueryOptionsBase.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `QueryOptionsBase.retry` *** #### scope? > `optional` **scope?**: `string` \| `boolean` Scope to apply on the associated model, or `false` to remove its default scope. *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `QueryOptionsBase.statementTimeout` *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `QueryOptionsBase.transaction` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `QueryOptionsBase.useMaster` *** #### where? > `optional` **where?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Filter on the counted rows. ## Interface: HasManyCreateAssociationMixinOptions Options of the `createX` accessor of a hasMany association (Sequelize v6). ### Example ```ts const options: HasManyCreateAssociationMixinOptions = { transaction }; ``` ### Extends - [`CreateOptions`](../type-aliases/CreateOptions.md)\<`any`\> ### Properties #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `CreateOptions.benchmark` *** #### fields? > `optional` **fields?**: readonly `any`[] Attributes to save; others are ignored. Default: all changed attributes. Mutable so hooks can adjust it, as in v6. ##### Inherited from `CreateOptions.fields` *** #### hooks? > `optional` **hooks?**: `boolean` Run lifecycle hooks. ##### Default Value ```ts true ``` ##### Inherited from `CreateOptions.hooks` *** #### include? > `optional` **include?**: [`IncludeOption`](../type-aliases/IncludeOption.md) Create associated rows from nested values (Sequelize v6). ##### Inherited from `CreateOptions.include` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `CreateOptions.logging` *** #### onConflict? > `optional` **onConflict?**: `Readonly`\<\{ `action`: `"nothing"` \| `Readonly`\<\{ `update`: [`OnConflictUpdate`](../type-aliases/OnConflictUpdate.md)\<`any`\>; `where?`: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\>; \}\>; `target?`: [`OnConflictTarget`](../type-aliases/OnConflictTarget.md)\<`any`\>; \}\> Advanced `ON CONFLICT` handling. PostgreSQL extension. ##### Inherited from `CreateOptions.onConflict` *** #### overriding? > `optional` **overriding?**: `"user"` \| `"system"` `OVERRIDING SYSTEM VALUE` / `OVERRIDING USER VALUE` for identity columns. PostgreSQL extension. ##### Inherited from `CreateOptions.overriding` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `CreateOptions.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `CreateOptions.retry` *** #### returning? > `optional` **returning?**: `boolean` Return all columns after insert/update; PostgreSQL always uses `RETURNING`, so this is accepted for v6 compatibility. ##### Default Value ```ts true ``` ##### Inherited from `CreateOptions.returning` *** #### silent? > `optional` **silent?**: `boolean` Do not update `updatedAt`. ##### Default Value ```ts false ``` ##### Inherited from `CreateOptions.silent` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `CreateOptions.statementTimeout` *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `CreateOptions.transaction` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `CreateOptions.useMaster` *** #### validate? > `optional` **validate?**: `boolean` Run validations. ##### Default Value true (`false` for `bulkCreate`) ##### Inherited from `CreateOptions.validate` ## Interface: HasManyGetAssociationsMixinOptions Options of the `getXs` accessor of a hasMany association (Sequelize v6). ### Example ```ts const options: HasManyGetAssociationsMixinOptions = { where: { active: true }, scope: false }; ``` ### Extends - [`FindOptions`](../type-aliases/FindOptions.md)\<`any`\> ### Extended by - [`HasManyHasAssociationMixinOptions`](HasManyHasAssociationMixinOptions.md) - [`HasManyHasAssociationsMixinOptions`](HasManyHasAssociationsMixinOptions.md) ### Properties #### attributes? > `optional` **attributes?**: [`FindAttributeOptions`](../type-aliases/FindAttributeOptions.md) Selected attributes. All attributes when omitted. ##### Inherited from `FindOptions.attributes` *** #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `FindOptions.benchmark` *** #### distinctOn? > `optional` **distinctOn?**: readonly `unknown`[] `SELECT DISTINCT ON (...)`: attributes or expressions. PostgreSQL extension. ##### Inherited from `FindOptions.distinctOn` *** #### from? > `readonly` `optional` **from?**: `Readonly`\<`Record`\<`string`, [`FromSourceOption`](../type-aliases/FromSourceOption.md)\>\> Extra relations (`FROM "Model", "alias"`), keyed by alias; correlate them in `where`. PostgreSQL extension. ##### Inherited from `FindOptions.from` *** #### group? > `optional` **group?**: `unknown` `GROUP BY` attributes or expressions. ##### Inherited from `FindOptions.group` *** #### having? > `optional` **having?**: `unknown` `HAVING` condition. ##### Inherited from `FindOptions.having` *** #### hooks? > `optional` **hooks?**: `boolean` Run `beforeFind` / `afterFind` hooks. ##### Default Value ```ts true ``` ##### Inherited from `FindOptions.hooks` *** #### include? > `optional` **include?**: [`IncludeOption`](../type-aliases/IncludeOption.md) Eager-load associations through JOINs (or separate queries for `separate` includes). ##### Inherited from `FindOptions.include` *** #### limit? > `optional` **limit?**: `number` \| `null` Maximum number of rows; `null` or `undefined` for no limit. ##### Inherited from `FindOptions.limit` *** #### lock? > `optional` **lock?**: [`LockOption`](../type-aliases/LockOption.md) Row lock (`FOR UPDATE` etc.); requires a transaction. ##### Inherited from `FindOptions.lock` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `FindOptions.logging` *** #### nest? > `optional` **nest?**: `boolean` With `raw`, build nested objects from dotted keys such as `'posts.title'`. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.nest` *** #### noWait? > `optional` **noWait?**: `boolean` Add `NOWAIT` to the row lock so the query fails instead of waiting; only with `lock`. PostgreSQL extension. ##### Inherited from `FindOptions.noWait` *** #### offset? > `optional` **offset?**: `number` \| `null` Number of rows to skip; `null` or `undefined` to skip none. ##### Inherited from `FindOptions.offset` *** #### order? > `optional` **order?**: readonly `unknown`[] \| [`Order`](../type-aliases/Order.md) Sort order: attribute names, `[attribute, 'ASC' | 'DESC']` pairs or expressions. ##### Inherited from `FindOptions.order` *** #### paranoid? > `optional` **paranoid?**: `boolean` For paranoid models: `false` includes soft-deleted rows. ##### Default Value ```ts true ``` ##### Inherited from `FindOptions.paranoid` *** #### plain? > `optional` **plain?**: `boolean` Return a single row instead of an array (set internally by `findOne`). ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.plain` *** #### raw? > `optional` **raw?**: `boolean` Return plain row objects instead of model instances. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.raw` *** #### rejectOnEmpty? > `optional` **rejectOnEmpty?**: `boolean` \| `Error` Throw `EmptyResultError` (or the given `Error`) when no row is found. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.rejectOnEmpty` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `FindOptions.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `FindOptions.retry` *** #### sample? > `optional` **sample?**: `Readonly`\<\{ `method`: `"BERNOULLI"` \| `"SYSTEM"`; `percent`: `number`; `seed?`: `number`; \}\> Read only a random sample of the model table (`TABLESAMPLE`). PostgreSQL extension. ##### Inherited from `FindOptions.sample` *** #### scope? > `optional` **scope?**: `string` \| `boolean` \| `string`[] Scope to apply on the associated model, or `false` to remove its default scope. *** #### skipLocked? > `optional` **skipLocked?**: `boolean` Add `SKIP LOCKED` to the row lock; only with `lock`. ##### Inherited from `FindOptions.skipLocked` *** #### source? > `readonly` `optional` **source?**: `string` \| [`Subquery`](Subquery.md) Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (`a.union(b)`), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. ##### Inherited from `FindOptions.source` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `FindOptions.statementTimeout` *** #### subQuery? > `optional` **subQuery?**: `boolean` `false` disables the sub-query used for `limit` combined with multi-row includes. ##### Inherited from `FindOptions.subQuery` *** #### tableAs? > `optional` **tableAs?**: `string` Alias of the main table in `FROM` instead of the model name, so `literal`s and `col('alias.x')` can refer to it (a v6 internal option that v6's typings omit). Ignored when `include` is set. ##### Inherited from `FindOptions.tableAs` *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `FindOptions.transaction` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `FindOptions.useMaster` *** #### where? > `optional` **where?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Filter rows; see [WhereOptions](../type-aliases/WhereOptions.md). All rows when omitted. ##### Inherited from `FindOptions.where` *** #### with? > `readonly` `optional` **with?**: `Readonly`\<`Record`\<`string`, [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md) \| `Readonly`\<\{ `cycle?`: `Readonly`\<\{ `columns`: readonly `string`[]; `set`: `string`; `using`: `string`; \}\>; `materialized?`: `boolean`; `query`: [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md); `recursive?`: [`Subquery`](Subquery.md); `search?`: `Readonly`\<\{ `by`: readonly `string`[]; `mode?`: `"breadth"` \| `"depth"`; `set`: `string`; \}\>; `unionAll?`: `boolean`; \}\>\>\> Common table expressions (`WITH [RECURSIVE] ...`). PostgreSQL extension. ##### Inherited from `FindOptions.with` *** #### withTies? > `optional` **withTies?**: `boolean` `FETCH FIRST limit ROWS WITH TIES` instead of `LIMIT`: also returns the rows that tie with the last one on the `order` columns. Needs `limit` and `order`. PostgreSQL extension. ##### Inherited from `FindOptions.withTies` ## Interface: HasManyHasAssociationMixinOptions Options of the `hasX` accessor of a hasMany association (Sequelize v6). ### Example ```ts const options: HasManyHasAssociationMixinOptions = { transaction }; ``` ### Extends - [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md) ### Properties #### attributes? > `optional` **attributes?**: [`FindAttributeOptions`](../type-aliases/FindAttributeOptions.md) Selected attributes. All attributes when omitted. ##### Inherited from `HasManyGetAssociationsMixinOptions.attributes` *** #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`benchmark`](HasManyGetAssociationsMixinOptions.md#benchmark) *** #### distinctOn? > `optional` **distinctOn?**: readonly `unknown`[] `SELECT DISTINCT ON (...)`: attributes or expressions. PostgreSQL extension. ##### Inherited from `HasManyGetAssociationsMixinOptions.distinctOn` *** #### from? > `readonly` `optional` **from?**: `Readonly`\<`Record`\<`string`, [`FromSourceOption`](../type-aliases/FromSourceOption.md)\>\> Extra relations (`FROM "Model", "alias"`), keyed by alias; correlate them in `where`. PostgreSQL extension. ##### Inherited from `HasManyGetAssociationsMixinOptions.from` *** #### group? > `optional` **group?**: `unknown` `GROUP BY` attributes or expressions. ##### Inherited from `HasManyGetAssociationsMixinOptions.group` *** #### having? > `optional` **having?**: `unknown` `HAVING` condition. ##### Inherited from `HasManyGetAssociationsMixinOptions.having` *** #### hooks? > `optional` **hooks?**: `boolean` Run `beforeFind` / `afterFind` hooks. ##### Default Value ```ts true ``` ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`hooks`](HasManyGetAssociationsMixinOptions.md#hooks) *** #### include? > `optional` **include?**: [`IncludeOption`](../type-aliases/IncludeOption.md) Eager-load associations through JOINs (or separate queries for `separate` includes). ##### Inherited from `HasManyGetAssociationsMixinOptions.include` *** #### limit? > `optional` **limit?**: `number` \| `null` Maximum number of rows; `null` or `undefined` for no limit. ##### Inherited from `HasManyGetAssociationsMixinOptions.limit` *** #### lock? > `optional` **lock?**: [`LockOption`](../type-aliases/LockOption.md) Row lock (`FOR UPDATE` etc.); requires a transaction. ##### Inherited from `HasManyGetAssociationsMixinOptions.lock` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`logging`](HasManyGetAssociationsMixinOptions.md#logging) *** #### nest? > `optional` **nest?**: `boolean` With `raw`, build nested objects from dotted keys such as `'posts.title'`. ##### Default Value ```ts false ``` ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`nest`](HasManyGetAssociationsMixinOptions.md#nest) *** #### noWait? > `optional` **noWait?**: `boolean` Add `NOWAIT` to the row lock so the query fails instead of waiting; only with `lock`. PostgreSQL extension. ##### Inherited from `HasManyGetAssociationsMixinOptions.noWait` *** #### offset? > `optional` **offset?**: `number` \| `null` Number of rows to skip; `null` or `undefined` to skip none. ##### Inherited from `HasManyGetAssociationsMixinOptions.offset` *** #### order? > `optional` **order?**: readonly `unknown`[] \| [`Order`](../type-aliases/Order.md) Sort order: attribute names, `[attribute, 'ASC' | 'DESC']` pairs or expressions. ##### Inherited from `HasManyGetAssociationsMixinOptions.order` *** #### paranoid? > `optional` **paranoid?**: `boolean` For paranoid models: `false` includes soft-deleted rows. ##### Default Value ```ts true ``` ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`paranoid`](HasManyGetAssociationsMixinOptions.md#paranoid) *** #### plain? > `optional` **plain?**: `boolean` Return a single row instead of an array (set internally by `findOne`). ##### Default Value ```ts false ``` ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`plain`](HasManyGetAssociationsMixinOptions.md#plain) *** #### raw? > `optional` **raw?**: `boolean` Return plain row objects instead of model instances. ##### Default Value ```ts false ``` ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`raw`](HasManyGetAssociationsMixinOptions.md#raw) *** #### rejectOnEmpty? > `optional` **rejectOnEmpty?**: `boolean` \| `Error` Throw `EmptyResultError` (or the given `Error`) when no row is found. ##### Default Value ```ts false ``` ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`rejectOnEmpty`](HasManyGetAssociationsMixinOptions.md#rejectonempty) *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`replacements`](HasManyGetAssociationsMixinOptions.md#replacements) *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`retry`](HasManyGetAssociationsMixinOptions.md#retry) *** #### sample? > `optional` **sample?**: `Readonly`\<\{ `method`: `"BERNOULLI"` \| `"SYSTEM"`; `percent`: `number`; `seed?`: `number`; \}\> Read only a random sample of the model table (`TABLESAMPLE`). PostgreSQL extension. ##### Inherited from `HasManyGetAssociationsMixinOptions.sample` *** #### scope? > `optional` **scope?**: `string` \| `boolean` \| `string`[] Scope to apply on the associated model, or `false` to remove its default scope. ##### Inherited from `HasManyHasAssociationMixinOptions`.[`scope`](#scope) *** #### skipLocked? > `optional` **skipLocked?**: `boolean` Add `SKIP LOCKED` to the row lock; only with `lock`. ##### Inherited from `HasManyGetAssociationsMixinOptions.skipLocked` *** #### source? > `readonly` `optional` **source?**: `string` \| [`Subquery`](Subquery.md) Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (`a.union(b)`), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. ##### Inherited from `HasManyGetAssociationsMixinOptions.source` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`statementTimeout`](HasManyGetAssociationsMixinOptions.md#statementtimeout) *** #### subQuery? > `optional` **subQuery?**: `boolean` `false` disables the sub-query used for `limit` combined with multi-row includes. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`subQuery`](HasManyGetAssociationsMixinOptions.md#subquery) *** #### tableAs? > `optional` **tableAs?**: `string` Alias of the main table in `FROM` instead of the model name, so `literal`s and `col('alias.x')` can refer to it (a v6 internal option that v6's typings omit). Ignored when `include` is set. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`tableAs`](HasManyGetAssociationsMixinOptions.md#tableas) *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`transaction`](HasManyGetAssociationsMixinOptions.md#transaction) *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`useMaster`](HasManyGetAssociationsMixinOptions.md#usemaster) *** #### where? > `optional` **where?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Filter rows; see [WhereOptions](../type-aliases/WhereOptions.md). All rows when omitted. ##### Inherited from `HasManyGetAssociationsMixinOptions.where` *** #### with? > `readonly` `optional` **with?**: `Readonly`\<`Record`\<`string`, [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md) \| `Readonly`\<\{ `cycle?`: `Readonly`\<\{ `columns`: readonly `string`[]; `set`: `string`; `using`: `string`; \}\>; `materialized?`: `boolean`; `query`: [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md); `recursive?`: [`Subquery`](Subquery.md); `search?`: `Readonly`\<\{ `by`: readonly `string`[]; `mode?`: `"breadth"` \| `"depth"`; `set`: `string`; \}\>; `unionAll?`: `boolean`; \}\>\>\> Common table expressions (`WITH [RECURSIVE] ...`). PostgreSQL extension. ##### Inherited from `HasManyGetAssociationsMixinOptions.with` *** #### withTies? > `optional` **withTies?**: `boolean` `FETCH FIRST limit ROWS WITH TIES` instead of `LIMIT`: also returns the rows that tie with the last one on the `order` columns. Needs `limit` and `order`. PostgreSQL extension. ##### Inherited from `HasManyGetAssociationsMixinOptions.withTies` ## Interface: HasManyHasAssociationsMixinOptions Options of the `hasXs` accessor of a hasMany association (Sequelize v6). ### Example ```ts const options: HasManyHasAssociationsMixinOptions = { transaction }; ``` ### Extends - [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md) ### Properties #### attributes? > `optional` **attributes?**: [`FindAttributeOptions`](../type-aliases/FindAttributeOptions.md) Selected attributes. All attributes when omitted. ##### Inherited from `HasManyGetAssociationsMixinOptions.attributes` *** #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`benchmark`](HasManyGetAssociationsMixinOptions.md#benchmark) *** #### distinctOn? > `optional` **distinctOn?**: readonly `unknown`[] `SELECT DISTINCT ON (...)`: attributes or expressions. PostgreSQL extension. ##### Inherited from `HasManyGetAssociationsMixinOptions.distinctOn` *** #### from? > `readonly` `optional` **from?**: `Readonly`\<`Record`\<`string`, [`FromSourceOption`](../type-aliases/FromSourceOption.md)\>\> Extra relations (`FROM "Model", "alias"`), keyed by alias; correlate them in `where`. PostgreSQL extension. ##### Inherited from `HasManyGetAssociationsMixinOptions.from` *** #### group? > `optional` **group?**: `unknown` `GROUP BY` attributes or expressions. ##### Inherited from `HasManyGetAssociationsMixinOptions.group` *** #### having? > `optional` **having?**: `unknown` `HAVING` condition. ##### Inherited from `HasManyGetAssociationsMixinOptions.having` *** #### hooks? > `optional` **hooks?**: `boolean` Run `beforeFind` / `afterFind` hooks. ##### Default Value ```ts true ``` ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`hooks`](HasManyGetAssociationsMixinOptions.md#hooks) *** #### include? > `optional` **include?**: [`IncludeOption`](../type-aliases/IncludeOption.md) Eager-load associations through JOINs (or separate queries for `separate` includes). ##### Inherited from `HasManyGetAssociationsMixinOptions.include` *** #### limit? > `optional` **limit?**: `number` \| `null` Maximum number of rows; `null` or `undefined` for no limit. ##### Inherited from `HasManyGetAssociationsMixinOptions.limit` *** #### lock? > `optional` **lock?**: [`LockOption`](../type-aliases/LockOption.md) Row lock (`FOR UPDATE` etc.); requires a transaction. ##### Inherited from `HasManyGetAssociationsMixinOptions.lock` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`logging`](HasManyGetAssociationsMixinOptions.md#logging) *** #### nest? > `optional` **nest?**: `boolean` With `raw`, build nested objects from dotted keys such as `'posts.title'`. ##### Default Value ```ts false ``` ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`nest`](HasManyGetAssociationsMixinOptions.md#nest) *** #### noWait? > `optional` **noWait?**: `boolean` Add `NOWAIT` to the row lock so the query fails instead of waiting; only with `lock`. PostgreSQL extension. ##### Inherited from `HasManyGetAssociationsMixinOptions.noWait` *** #### offset? > `optional` **offset?**: `number` \| `null` Number of rows to skip; `null` or `undefined` to skip none. ##### Inherited from `HasManyGetAssociationsMixinOptions.offset` *** #### order? > `optional` **order?**: readonly `unknown`[] \| [`Order`](../type-aliases/Order.md) Sort order: attribute names, `[attribute, 'ASC' | 'DESC']` pairs or expressions. ##### Inherited from `HasManyGetAssociationsMixinOptions.order` *** #### paranoid? > `optional` **paranoid?**: `boolean` For paranoid models: `false` includes soft-deleted rows. ##### Default Value ```ts true ``` ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`paranoid`](HasManyGetAssociationsMixinOptions.md#paranoid) *** #### plain? > `optional` **plain?**: `boolean` Return a single row instead of an array (set internally by `findOne`). ##### Default Value ```ts false ``` ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`plain`](HasManyGetAssociationsMixinOptions.md#plain) *** #### raw? > `optional` **raw?**: `boolean` Return plain row objects instead of model instances. ##### Default Value ```ts false ``` ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`raw`](HasManyGetAssociationsMixinOptions.md#raw) *** #### rejectOnEmpty? > `optional` **rejectOnEmpty?**: `boolean` \| `Error` Throw `EmptyResultError` (or the given `Error`) when no row is found. ##### Default Value ```ts false ``` ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`rejectOnEmpty`](HasManyGetAssociationsMixinOptions.md#rejectonempty) *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`replacements`](HasManyGetAssociationsMixinOptions.md#replacements) *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`retry`](HasManyGetAssociationsMixinOptions.md#retry) *** #### sample? > `optional` **sample?**: `Readonly`\<\{ `method`: `"BERNOULLI"` \| `"SYSTEM"`; `percent`: `number`; `seed?`: `number`; \}\> Read only a random sample of the model table (`TABLESAMPLE`). PostgreSQL extension. ##### Inherited from `HasManyGetAssociationsMixinOptions.sample` *** #### scope? > `optional` **scope?**: `string` \| `boolean` \| `string`[] Scope to apply on the associated model, or `false` to remove its default scope. ##### Inherited from [`HasManyHasAssociationMixinOptions`](HasManyHasAssociationMixinOptions.md).[`scope`](HasManyHasAssociationMixinOptions.md#scope) *** #### skipLocked? > `optional` **skipLocked?**: `boolean` Add `SKIP LOCKED` to the row lock; only with `lock`. ##### Inherited from `HasManyGetAssociationsMixinOptions.skipLocked` *** #### source? > `readonly` `optional` **source?**: `string` \| [`Subquery`](Subquery.md) Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (`a.union(b)`), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. ##### Inherited from `HasManyGetAssociationsMixinOptions.source` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`statementTimeout`](HasManyGetAssociationsMixinOptions.md#statementtimeout) *** #### subQuery? > `optional` **subQuery?**: `boolean` `false` disables the sub-query used for `limit` combined with multi-row includes. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`subQuery`](HasManyGetAssociationsMixinOptions.md#subquery) *** #### tableAs? > `optional` **tableAs?**: `string` Alias of the main table in `FROM` instead of the model name, so `literal`s and `col('alias.x')` can refer to it (a v6 internal option that v6's typings omit). Ignored when `include` is set. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`tableAs`](HasManyGetAssociationsMixinOptions.md#tableas) *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`transaction`](HasManyGetAssociationsMixinOptions.md#transaction) *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from [`HasManyGetAssociationsMixinOptions`](HasManyGetAssociationsMixinOptions.md).[`useMaster`](HasManyGetAssociationsMixinOptions.md#usemaster) *** #### where? > `optional` **where?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Filter rows; see [WhereOptions](../type-aliases/WhereOptions.md). All rows when omitted. ##### Inherited from `HasManyGetAssociationsMixinOptions.where` *** #### with? > `readonly` `optional` **with?**: `Readonly`\<`Record`\<`string`, [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md) \| `Readonly`\<\{ `cycle?`: `Readonly`\<\{ `columns`: readonly `string`[]; `set`: `string`; `using`: `string`; \}\>; `materialized?`: `boolean`; `query`: [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md); `recursive?`: [`Subquery`](Subquery.md); `search?`: `Readonly`\<\{ `by`: readonly `string`[]; `mode?`: `"breadth"` \| `"depth"`; `set`: `string`; \}\>; `unionAll?`: `boolean`; \}\>\>\> Common table expressions (`WITH [RECURSIVE] ...`). PostgreSQL extension. ##### Inherited from `HasManyGetAssociationsMixinOptions.with` *** #### withTies? > `optional` **withTies?**: `boolean` `FETCH FIRST limit ROWS WITH TIES` instead of `LIMIT`: also returns the rows that tie with the last one on the `order` columns. Needs `limit` and `order`. PostgreSQL extension. ##### Inherited from `HasManyGetAssociationsMixinOptions.withTies` ## Interface: HasManyRemoveAssociationMixinOptions Options of the `removeX` accessor of a hasMany association (Sequelize v6). ### Example ```ts const options: HasManyRemoveAssociationMixinOptions = { transaction }; ``` ### Extends - [`InstanceUpdateOptions`](../type-aliases/InstanceUpdateOptions.md)\<`any`\> ### Properties #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `InstanceUpdateOptions.benchmark` *** #### fields? > `optional` **fields?**: readonly `any`[] Attributes to save; others are ignored. Default: all changed attributes. Mutable so hooks can adjust it, as in v6. ##### Inherited from `InstanceUpdateOptions.fields` *** #### hooks? > `optional` **hooks?**: `boolean` Run lifecycle hooks. ##### Default Value ```ts true ``` ##### Inherited from `InstanceUpdateOptions.hooks` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `InstanceUpdateOptions.logging` *** #### overriding? > `optional` **overriding?**: `"user"` \| `"system"` `OVERRIDING SYSTEM VALUE` / `OVERRIDING USER VALUE` for identity columns. PostgreSQL extension. ##### Inherited from `InstanceUpdateOptions.overriding` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `InstanceUpdateOptions.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `InstanceUpdateOptions.retry` *** #### returning? > `optional` **returning?**: `boolean` Return all columns after insert/update; PostgreSQL always uses `RETURNING`, so this is accepted for v6 compatibility. ##### Default Value ```ts true ``` ##### Inherited from `InstanceUpdateOptions.returning` *** #### silent? > `optional` **silent?**: `boolean` Do not update `updatedAt`. ##### Default Value ```ts false ``` ##### Inherited from `InstanceUpdateOptions.silent` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `InstanceUpdateOptions.statementTimeout` *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `InstanceUpdateOptions.transaction` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `InstanceUpdateOptions.useMaster` *** #### validate? > `optional` **validate?**: `boolean` Run validations. ##### Default Value true (`false` for `bulkCreate`) ##### Inherited from `InstanceUpdateOptions.validate` ## Interface: HasManyRemoveAssociationsMixinOptions Options of the `removeXs` accessor of a hasMany association (Sequelize v6). ### Example ```ts const options: HasManyRemoveAssociationsMixinOptions = { transaction }; ``` ### Extends - [`InstanceUpdateOptions`](../type-aliases/InstanceUpdateOptions.md)\<`any`\> ### Properties #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `InstanceUpdateOptions.benchmark` *** #### fields? > `optional` **fields?**: readonly `any`[] Attributes to save; others are ignored. Default: all changed attributes. Mutable so hooks can adjust it, as in v6. ##### Inherited from `InstanceUpdateOptions.fields` *** #### hooks? > `optional` **hooks?**: `boolean` Run lifecycle hooks. ##### Default Value ```ts true ``` ##### Inherited from `InstanceUpdateOptions.hooks` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `InstanceUpdateOptions.logging` *** #### overriding? > `optional` **overriding?**: `"user"` \| `"system"` `OVERRIDING SYSTEM VALUE` / `OVERRIDING USER VALUE` for identity columns. PostgreSQL extension. ##### Inherited from `InstanceUpdateOptions.overriding` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `InstanceUpdateOptions.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `InstanceUpdateOptions.retry` *** #### returning? > `optional` **returning?**: `boolean` Return all columns after insert/update; PostgreSQL always uses `RETURNING`, so this is accepted for v6 compatibility. ##### Default Value ```ts true ``` ##### Inherited from `InstanceUpdateOptions.returning` *** #### silent? > `optional` **silent?**: `boolean` Do not update `updatedAt`. ##### Default Value ```ts false ``` ##### Inherited from `InstanceUpdateOptions.silent` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `InstanceUpdateOptions.statementTimeout` *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `InstanceUpdateOptions.transaction` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `InstanceUpdateOptions.useMaster` *** #### validate? > `optional` **validate?**: `boolean` Run validations. ##### Default Value true (`false` for `bulkCreate`) ##### Inherited from `InstanceUpdateOptions.validate` ## Interface: HasManySetAssociationsMixinOptions Options of the `setXs` accessor of a hasMany association (Sequelize v6). ### Example ```ts const options: HasManySetAssociationsMixinOptions = { transaction }; ``` ### Extends - [`FindOptions`](../type-aliases/FindOptions.md)\<`any`\> - [`InstanceUpdateOptions`](../type-aliases/InstanceUpdateOptions.md)\<`any`\> ### Properties #### attributes? > `optional` **attributes?**: [`FindAttributeOptions`](../type-aliases/FindAttributeOptions.md) Selected attributes. All attributes when omitted. ##### Inherited from `FindOptions.attributes` *** #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `FindOptions.benchmark` *** #### distinctOn? > `optional` **distinctOn?**: readonly `unknown`[] `SELECT DISTINCT ON (...)`: attributes or expressions. PostgreSQL extension. ##### Inherited from `FindOptions.distinctOn` *** #### fields? > `optional` **fields?**: readonly `any`[] Attributes to save; others are ignored. Default: all changed attributes. Mutable so hooks can adjust it, as in v6. ##### Inherited from `InstanceUpdateOptions.fields` *** #### from? > `readonly` `optional` **from?**: `Readonly`\<`Record`\<`string`, [`FromSourceOption`](../type-aliases/FromSourceOption.md)\>\> Extra relations (`FROM "Model", "alias"`), keyed by alias; correlate them in `where`. PostgreSQL extension. ##### Inherited from `FindOptions.from` *** #### group? > `optional` **group?**: `unknown` `GROUP BY` attributes or expressions. ##### Inherited from `FindOptions.group` *** #### having? > `optional` **having?**: `unknown` `HAVING` condition. ##### Inherited from `FindOptions.having` *** #### hooks? > `optional` **hooks?**: `boolean` Run `beforeFind` / `afterFind` hooks. ##### Default Value ```ts true ``` ##### Inherited from `FindOptions.hooks` *** #### include? > `optional` **include?**: [`IncludeOption`](../type-aliases/IncludeOption.md) Eager-load associations through JOINs (or separate queries for `separate` includes). ##### Inherited from `FindOptions.include` *** #### limit? > `optional` **limit?**: `number` \| `null` Maximum number of rows; `null` or `undefined` for no limit. ##### Inherited from `FindOptions.limit` *** #### lock? > `optional` **lock?**: [`LockOption`](../type-aliases/LockOption.md) Row lock (`FOR UPDATE` etc.); requires a transaction. ##### Inherited from `FindOptions.lock` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `FindOptions.logging` *** #### nest? > `optional` **nest?**: `boolean` With `raw`, build nested objects from dotted keys such as `'posts.title'`. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.nest` *** #### noWait? > `optional` **noWait?**: `boolean` Add `NOWAIT` to the row lock so the query fails instead of waiting; only with `lock`. PostgreSQL extension. ##### Inherited from `FindOptions.noWait` *** #### offset? > `optional` **offset?**: `number` \| `null` Number of rows to skip; `null` or `undefined` to skip none. ##### Inherited from `FindOptions.offset` *** #### order? > `optional` **order?**: readonly `unknown`[] \| [`Order`](../type-aliases/Order.md) Sort order: attribute names, `[attribute, 'ASC' | 'DESC']` pairs or expressions. ##### Inherited from `FindOptions.order` *** #### overriding? > `optional` **overriding?**: `"user"` \| `"system"` `OVERRIDING SYSTEM VALUE` / `OVERRIDING USER VALUE` for identity columns. PostgreSQL extension. ##### Inherited from `InstanceUpdateOptions.overriding` *** #### paranoid? > `optional` **paranoid?**: `boolean` For paranoid models: `false` includes soft-deleted rows. ##### Default Value ```ts true ``` ##### Inherited from `FindOptions.paranoid` *** #### plain? > `optional` **plain?**: `boolean` Return a single row instead of an array (set internally by `findOne`). ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.plain` *** #### raw? > `optional` **raw?**: `boolean` Return plain row objects instead of model instances. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.raw` *** #### rejectOnEmpty? > `optional` **rejectOnEmpty?**: `boolean` \| `Error` Throw `EmptyResultError` (or the given `Error`) when no row is found. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.rejectOnEmpty` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `FindOptions.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `FindOptions.retry` *** #### returning? > `optional` **returning?**: `boolean` Return all columns after insert/update; PostgreSQL always uses `RETURNING`, so this is accepted for v6 compatibility. ##### Default Value ```ts true ``` ##### Inherited from `InstanceUpdateOptions.returning` *** #### sample? > `optional` **sample?**: `Readonly`\<\{ `method`: `"BERNOULLI"` \| `"SYSTEM"`; `percent`: `number`; `seed?`: `number`; \}\> Read only a random sample of the model table (`TABLESAMPLE`). PostgreSQL extension. ##### Inherited from `FindOptions.sample` *** #### silent? > `optional` **silent?**: `boolean` Do not update `updatedAt`. ##### Default Value ```ts false ``` ##### Inherited from `InstanceUpdateOptions.silent` *** #### skipLocked? > `optional` **skipLocked?**: `boolean` Add `SKIP LOCKED` to the row lock; only with `lock`. ##### Inherited from `FindOptions.skipLocked` *** #### source? > `readonly` `optional` **source?**: `string` \| [`Subquery`](Subquery.md) Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (`a.union(b)`), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. ##### Inherited from `FindOptions.source` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `FindOptions.statementTimeout` *** #### subQuery? > `optional` **subQuery?**: `boolean` `false` disables the sub-query used for `limit` combined with multi-row includes. ##### Inherited from `FindOptions.subQuery` *** #### tableAs? > `optional` **tableAs?**: `string` Alias of the main table in `FROM` instead of the model name, so `literal`s and `col('alias.x')` can refer to it (a v6 internal option that v6's typings omit). Ignored when `include` is set. ##### Inherited from `FindOptions.tableAs` *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `FindOptions.transaction` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `FindOptions.useMaster` *** #### validate? > `optional` **validate?**: `boolean` Run validations. ##### Default Value true (`false` for `bulkCreate`) ##### Inherited from `InstanceUpdateOptions.validate` *** #### where? > `optional` **where?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Filter rows; see [WhereOptions](../type-aliases/WhereOptions.md). All rows when omitted. ##### Inherited from `FindOptions.where` *** #### with? > `readonly` `optional` **with?**: `Readonly`\<`Record`\<`string`, [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md) \| `Readonly`\<\{ `cycle?`: `Readonly`\<\{ `columns`: readonly `string`[]; `set`: `string`; `using`: `string`; \}\>; `materialized?`: `boolean`; `query`: [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md); `recursive?`: [`Subquery`](Subquery.md); `search?`: `Readonly`\<\{ `by`: readonly `string`[]; `mode?`: `"breadth"` \| `"depth"`; `set`: `string`; \}\>; `unionAll?`: `boolean`; \}\>\>\> Common table expressions (`WITH [RECURSIVE] ...`). PostgreSQL extension. ##### Inherited from `FindOptions.with` *** #### withTies? > `optional` **withTies?**: `boolean` `FETCH FIRST limit ROWS WITH TIES` instead of `LIMIT`: also returns the rows that tie with the last one on the `order` columns. Needs `limit` and `order`. PostgreSQL extension. ##### Inherited from `FindOptions.withTies` ## Interface: HasOneCreateAssociationMixinOptions Options of the `createX` accessor of a hasOne association (Sequelize v6). ### Example ```ts const options: HasOneCreateAssociationMixinOptions = { transaction }; ``` ### Extends - [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md) - [`CreateOptions`](../type-aliases/CreateOptions.md)\<`any`\> ### Properties #### attributes? > `optional` **attributes?**: [`FindAttributeOptions`](../type-aliases/FindAttributeOptions.md) Selected attributes. All attributes when omitted. ##### Inherited from `HasOneSetAssociationMixinOptions.attributes` *** #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`benchmark`](HasOneSetAssociationMixinOptions.md#benchmark) *** #### distinctOn? > `optional` **distinctOn?**: readonly `unknown`[] `SELECT DISTINCT ON (...)`: attributes or expressions. PostgreSQL extension. ##### Inherited from `HasOneSetAssociationMixinOptions.distinctOn` *** #### fields? > `optional` **fields?**: readonly `any`[] Attributes to save; others are ignored. Default: all changed attributes. Mutable so hooks can adjust it, as in v6. ##### Inherited from `HasOneSetAssociationMixinOptions.fields` *** #### from? > `readonly` `optional` **from?**: `Readonly`\<`Record`\<`string`, [`FromSourceOption`](../type-aliases/FromSourceOption.md)\>\> Extra relations (`FROM "Model", "alias"`), keyed by alias; correlate them in `where`. PostgreSQL extension. ##### Inherited from `HasOneSetAssociationMixinOptions.from` *** #### group? > `optional` **group?**: `unknown` `GROUP BY` attributes or expressions. ##### Inherited from `HasOneSetAssociationMixinOptions.group` *** #### having? > `optional` **having?**: `unknown` `HAVING` condition. ##### Inherited from `HasOneSetAssociationMixinOptions.having` *** #### hooks? > `optional` **hooks?**: `boolean` Run `beforeFind` / `afterFind` hooks. ##### Default Value ```ts true ``` ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`hooks`](HasOneSetAssociationMixinOptions.md#hooks) *** #### include? > `optional` **include?**: [`IncludeOption`](../type-aliases/IncludeOption.md) Eager-load associations through JOINs (or separate queries for `separate` includes). ##### Inherited from `HasOneSetAssociationMixinOptions.include` *** #### limit? > `optional` **limit?**: `number` \| `null` Maximum number of rows; `null` or `undefined` for no limit. ##### Inherited from `HasOneSetAssociationMixinOptions.limit` *** #### lock? > `optional` **lock?**: [`LockOption`](../type-aliases/LockOption.md) Row lock (`FOR UPDATE` etc.); requires a transaction. ##### Inherited from `HasOneSetAssociationMixinOptions.lock` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`logging`](HasOneSetAssociationMixinOptions.md#logging) *** #### nest? > `optional` **nest?**: `boolean` With `raw`, build nested objects from dotted keys such as `'posts.title'`. ##### Default Value ```ts false ``` ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`nest`](HasOneSetAssociationMixinOptions.md#nest) *** #### noWait? > `optional` **noWait?**: `boolean` Add `NOWAIT` to the row lock so the query fails instead of waiting; only with `lock`. PostgreSQL extension. ##### Inherited from `HasOneSetAssociationMixinOptions.noWait` *** #### offset? > `optional` **offset?**: `number` \| `null` Number of rows to skip; `null` or `undefined` to skip none. ##### Inherited from `HasOneSetAssociationMixinOptions.offset` *** #### onConflict? > `optional` **onConflict?**: `Readonly`\<\{ `action`: `"nothing"` \| `Readonly`\<\{ `update`: [`OnConflictUpdate`](../type-aliases/OnConflictUpdate.md)\<`any`\>; `where?`: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\>; \}\>; `target?`: [`OnConflictTarget`](../type-aliases/OnConflictTarget.md)\<`any`\>; \}\> Advanced `ON CONFLICT` handling. PostgreSQL extension. ##### Inherited from `CreateOptions.onConflict` *** #### order? > `optional` **order?**: readonly `unknown`[] \| [`Order`](../type-aliases/Order.md) Sort order: attribute names, `[attribute, 'ASC' | 'DESC']` pairs or expressions. ##### Inherited from `HasOneSetAssociationMixinOptions.order` *** #### overriding? > `optional` **overriding?**: `"user"` \| `"system"` `OVERRIDING SYSTEM VALUE` / `OVERRIDING USER VALUE` for identity columns. PostgreSQL extension. ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`overriding`](HasOneSetAssociationMixinOptions.md#overriding) *** #### paranoid? > `optional` **paranoid?**: `boolean` For paranoid models: `false` includes soft-deleted rows. ##### Default Value ```ts true ``` ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`paranoid`](HasOneSetAssociationMixinOptions.md#paranoid) *** #### plain? > `optional` **plain?**: `boolean` Return a single row instead of an array (set internally by `findOne`). ##### Default Value ```ts false ``` ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`plain`](HasOneSetAssociationMixinOptions.md#plain) *** #### raw? > `optional` **raw?**: `boolean` Return plain row objects instead of model instances. ##### Default Value ```ts false ``` ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`raw`](HasOneSetAssociationMixinOptions.md#raw) *** #### rejectOnEmpty? > `optional` **rejectOnEmpty?**: `boolean` \| `Error` Throw `EmptyResultError` (or the given `Error`) when no row is found. ##### Default Value ```ts false ``` ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`rejectOnEmpty`](HasOneSetAssociationMixinOptions.md#rejectonempty) *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`replacements`](HasOneSetAssociationMixinOptions.md#replacements) *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`retry`](HasOneSetAssociationMixinOptions.md#retry) *** #### returning? > `optional` **returning?**: `boolean` Return all columns after insert/update; PostgreSQL always uses `RETURNING`, so this is accepted for v6 compatibility. ##### Default Value ```ts true ``` ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`returning`](HasOneSetAssociationMixinOptions.md#returning) *** #### sample? > `optional` **sample?**: `Readonly`\<\{ `method`: `"BERNOULLI"` \| `"SYSTEM"`; `percent`: `number`; `seed?`: `number`; \}\> Read only a random sample of the model table (`TABLESAMPLE`). PostgreSQL extension. ##### Inherited from `HasOneSetAssociationMixinOptions.sample` *** #### save? > `optional` **save?**: `boolean` Skip saving the associated instance after setting the foreign key when `false`. ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`save`](HasOneSetAssociationMixinOptions.md#save) *** #### scope? > `optional` **scope?**: `string` \| `boolean` \| `string`[] Scope to apply on the associated model, or `false` to remove its default scope. ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`scope`](HasOneSetAssociationMixinOptions.md#scope) *** #### silent? > `optional` **silent?**: `boolean` Do not update `updatedAt`. ##### Default Value ```ts false ``` ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`silent`](HasOneSetAssociationMixinOptions.md#silent) *** #### skipLocked? > `optional` **skipLocked?**: `boolean` Add `SKIP LOCKED` to the row lock; only with `lock`. ##### Inherited from `HasOneSetAssociationMixinOptions.skipLocked` *** #### source? > `readonly` `optional` **source?**: `string` \| [`Subquery`](Subquery.md) Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (`a.union(b)`), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. ##### Inherited from `HasOneSetAssociationMixinOptions.source` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`statementTimeout`](HasOneSetAssociationMixinOptions.md#statementtimeout) *** #### subQuery? > `optional` **subQuery?**: `boolean` `false` disables the sub-query used for `limit` combined with multi-row includes. ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`subQuery`](HasOneSetAssociationMixinOptions.md#subquery) *** #### tableAs? > `optional` **tableAs?**: `string` Alias of the main table in `FROM` instead of the model name, so `literal`s and `col('alias.x')` can refer to it (a v6 internal option that v6's typings omit). Ignored when `include` is set. ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`tableAs`](HasOneSetAssociationMixinOptions.md#tableas) *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`transaction`](HasOneSetAssociationMixinOptions.md#transaction) *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`useMaster`](HasOneSetAssociationMixinOptions.md#usemaster) *** #### validate? > `optional` **validate?**: `boolean` Run validations. ##### Default Value true (`false` for `bulkCreate`) ##### Inherited from [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md).[`validate`](HasOneSetAssociationMixinOptions.md#validate) *** #### where? > `optional` **where?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Filter rows; see [WhereOptions](../type-aliases/WhereOptions.md). All rows when omitted. ##### Inherited from `HasOneSetAssociationMixinOptions.where` *** #### with? > `readonly` `optional` **with?**: `Readonly`\<`Record`\<`string`, [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md) \| `Readonly`\<\{ `cycle?`: `Readonly`\<\{ `columns`: readonly `string`[]; `set`: `string`; `using`: `string`; \}\>; `materialized?`: `boolean`; `query`: [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md); `recursive?`: [`Subquery`](Subquery.md); `search?`: `Readonly`\<\{ `by`: readonly `string`[]; `mode?`: `"breadth"` \| `"depth"`; `set`: `string`; \}\>; `unionAll?`: `boolean`; \}\>\>\> Common table expressions (`WITH [RECURSIVE] ...`). PostgreSQL extension. ##### Inherited from `HasOneSetAssociationMixinOptions.with` *** #### withTies? > `optional` **withTies?**: `boolean` `FETCH FIRST limit ROWS WITH TIES` instead of `LIMIT`: also returns the rows that tie with the last one on the `order` columns. Needs `limit` and `order`. PostgreSQL extension. ##### Inherited from `HasOneSetAssociationMixinOptions.withTies` ## Interface: HasOneGetAssociationMixinOptions Options of the `getX` accessor of a hasOne association (Sequelize v6). ### Example ```ts const options: HasOneGetAssociationMixinOptions = { scope: false }; ``` ### Extends - [`FindOptions`](../type-aliases/FindOptions.md)\<`any`\> ### Extended by - [`HasOneSetAssociationMixinOptions`](HasOneSetAssociationMixinOptions.md) ### Properties #### attributes? > `optional` **attributes?**: [`FindAttributeOptions`](../type-aliases/FindAttributeOptions.md) Selected attributes. All attributes when omitted. ##### Inherited from `FindOptions.attributes` *** #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from `FindOptions.benchmark` *** #### distinctOn? > `optional` **distinctOn?**: readonly `unknown`[] `SELECT DISTINCT ON (...)`: attributes or expressions. PostgreSQL extension. ##### Inherited from `FindOptions.distinctOn` *** #### from? > `readonly` `optional` **from?**: `Readonly`\<`Record`\<`string`, [`FromSourceOption`](../type-aliases/FromSourceOption.md)\>\> Extra relations (`FROM "Model", "alias"`), keyed by alias; correlate them in `where`. PostgreSQL extension. ##### Inherited from `FindOptions.from` *** #### group? > `optional` **group?**: `unknown` `GROUP BY` attributes or expressions. ##### Inherited from `FindOptions.group` *** #### having? > `optional` **having?**: `unknown` `HAVING` condition. ##### Inherited from `FindOptions.having` *** #### hooks? > `optional` **hooks?**: `boolean` Run `beforeFind` / `afterFind` hooks. ##### Default Value ```ts true ``` ##### Inherited from `FindOptions.hooks` *** #### include? > `optional` **include?**: [`IncludeOption`](../type-aliases/IncludeOption.md) Eager-load associations through JOINs (or separate queries for `separate` includes). ##### Inherited from `FindOptions.include` *** #### limit? > `optional` **limit?**: `number` \| `null` Maximum number of rows; `null` or `undefined` for no limit. ##### Inherited from `FindOptions.limit` *** #### lock? > `optional` **lock?**: [`LockOption`](../type-aliases/LockOption.md) Row lock (`FOR UPDATE` etc.); requires a transaction. ##### Inherited from `FindOptions.lock` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from `FindOptions.logging` *** #### nest? > `optional` **nest?**: `boolean` With `raw`, build nested objects from dotted keys such as `'posts.title'`. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.nest` *** #### noWait? > `optional` **noWait?**: `boolean` Add `NOWAIT` to the row lock so the query fails instead of waiting; only with `lock`. PostgreSQL extension. ##### Inherited from `FindOptions.noWait` *** #### offset? > `optional` **offset?**: `number` \| `null` Number of rows to skip; `null` or `undefined` to skip none. ##### Inherited from `FindOptions.offset` *** #### order? > `optional` **order?**: readonly `unknown`[] \| [`Order`](../type-aliases/Order.md) Sort order: attribute names, `[attribute, 'ASC' | 'DESC']` pairs or expressions. ##### Inherited from `FindOptions.order` *** #### paranoid? > `optional` **paranoid?**: `boolean` For paranoid models: `false` includes soft-deleted rows. ##### Default Value ```ts true ``` ##### Inherited from `FindOptions.paranoid` *** #### plain? > `optional` **plain?**: `boolean` Return a single row instead of an array (set internally by `findOne`). ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.plain` *** #### raw? > `optional` **raw?**: `boolean` Return plain row objects instead of model instances. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.raw` *** #### rejectOnEmpty? > `optional` **rejectOnEmpty?**: `boolean` \| `Error` Throw `EmptyResultError` (or the given `Error`) when no row is found. ##### Default Value ```ts false ``` ##### Inherited from `FindOptions.rejectOnEmpty` *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from `FindOptions.replacements` *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from `FindOptions.retry` *** #### sample? > `optional` **sample?**: `Readonly`\<\{ `method`: `"BERNOULLI"` \| `"SYSTEM"`; `percent`: `number`; `seed?`: `number`; \}\> Read only a random sample of the model table (`TABLESAMPLE`). PostgreSQL extension. ##### Inherited from `FindOptions.sample` *** #### scope? > `optional` **scope?**: `string` \| `boolean` \| `string`[] Scope to apply on the associated model, or `false` to remove its default scope. *** #### skipLocked? > `optional` **skipLocked?**: `boolean` Add `SKIP LOCKED` to the row lock; only with `lock`. ##### Inherited from `FindOptions.skipLocked` *** #### source? > `readonly` `optional` **source?**: `string` \| [`Subquery`](Subquery.md) Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (`a.union(b)`), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. ##### Inherited from `FindOptions.source` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from `FindOptions.statementTimeout` *** #### subQuery? > `optional` **subQuery?**: `boolean` `false` disables the sub-query used for `limit` combined with multi-row includes. ##### Inherited from `FindOptions.subQuery` *** #### tableAs? > `optional` **tableAs?**: `string` Alias of the main table in `FROM` instead of the model name, so `literal`s and `col('alias.x')` can refer to it (a v6 internal option that v6's typings omit). Ignored when `include` is set. ##### Inherited from `FindOptions.tableAs` *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from `FindOptions.transaction` *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from `FindOptions.useMaster` *** #### where? > `optional` **where?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Filter rows; see [WhereOptions](../type-aliases/WhereOptions.md). All rows when omitted. ##### Inherited from `FindOptions.where` *** #### with? > `readonly` `optional` **with?**: `Readonly`\<`Record`\<`string`, [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md) \| `Readonly`\<\{ `cycle?`: `Readonly`\<\{ `columns`: readonly `string`[]; `set`: `string`; `using`: `string`; \}\>; `materialized?`: `boolean`; `query`: [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md); `recursive?`: [`Subquery`](Subquery.md); `search?`: `Readonly`\<\{ `by`: readonly `string`[]; `mode?`: `"breadth"` \| `"depth"`; `set`: `string`; \}\>; `unionAll?`: `boolean`; \}\>\>\> Common table expressions (`WITH [RECURSIVE] ...`). PostgreSQL extension. ##### Inherited from `FindOptions.with` *** #### withTies? > `optional` **withTies?**: `boolean` `FETCH FIRST limit ROWS WITH TIES` instead of `LIMIT`: also returns the rows that tie with the last one on the `order` columns. Needs `limit` and `order`. PostgreSQL extension. ##### Inherited from `FindOptions.withTies` ## Interface: HasOneSetAssociationMixinOptions Options of the `setX` accessor of a hasOne association (Sequelize v6). ### Example ```ts const options: HasOneSetAssociationMixinOptions = { save: false }; ``` ### Extends - [`HasOneGetAssociationMixinOptions`](HasOneGetAssociationMixinOptions.md) - [`SaveOptions`](../type-aliases/SaveOptions.md)\<`any`\> ### Extended by - [`HasOneCreateAssociationMixinOptions`](HasOneCreateAssociationMixinOptions.md) ### Properties #### attributes? > `optional` **attributes?**: [`FindAttributeOptions`](../type-aliases/FindAttributeOptions.md) Selected attributes. All attributes when omitted. ##### Inherited from `HasOneGetAssociationMixinOptions.attributes` *** #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. ##### Inherited from [`HasOneGetAssociationMixinOptions`](HasOneGetAssociationMixinOptions.md).[`benchmark`](HasOneGetAssociationMixinOptions.md#benchmark) *** #### distinctOn? > `optional` **distinctOn?**: readonly `unknown`[] `SELECT DISTINCT ON (...)`: attributes or expressions. PostgreSQL extension. ##### Inherited from `HasOneGetAssociationMixinOptions.distinctOn` *** #### fields? > `optional` **fields?**: readonly `any`[] Attributes to save; others are ignored. Default: all changed attributes. Mutable so hooks can adjust it, as in v6. ##### Inherited from `SaveOptions.fields` *** #### from? > `readonly` `optional` **from?**: `Readonly`\<`Record`\<`string`, [`FromSourceOption`](../type-aliases/FromSourceOption.md)\>\> Extra relations (`FROM "Model", "alias"`), keyed by alias; correlate them in `where`. PostgreSQL extension. ##### Inherited from `HasOneGetAssociationMixinOptions.from` *** #### group? > `optional` **group?**: `unknown` `GROUP BY` attributes or expressions. ##### Inherited from `HasOneGetAssociationMixinOptions.group` *** #### having? > `optional` **having?**: `unknown` `HAVING` condition. ##### Inherited from `HasOneGetAssociationMixinOptions.having` *** #### hooks? > `optional` **hooks?**: `boolean` Run `beforeFind` / `afterFind` hooks. ##### Default Value ```ts true ``` ##### Inherited from [`HasOneGetAssociationMixinOptions`](HasOneGetAssociationMixinOptions.md).[`hooks`](HasOneGetAssociationMixinOptions.md#hooks) *** #### include? > `optional` **include?**: [`IncludeOption`](../type-aliases/IncludeOption.md) Eager-load associations through JOINs (or separate queries for `separate` includes). ##### Inherited from `HasOneGetAssociationMixinOptions.include` *** #### limit? > `optional` **limit?**: `number` \| `null` Maximum number of rows; `null` or `undefined` for no limit. ##### Inherited from `HasOneGetAssociationMixinOptions.limit` *** #### lock? > `optional` **lock?**: [`LockOption`](../type-aliases/LockOption.md) Row lock (`FOR UPDATE` etc.); requires a transaction. ##### Inherited from `HasOneGetAssociationMixinOptions.lock` *** #### logging? > `optional` **logging?**: `false` \| [`LoggingFunction`](../type-aliases/LoggingFunction.md) SQL logger for this query, or `false`. ##### Inherited from [`HasOneGetAssociationMixinOptions`](HasOneGetAssociationMixinOptions.md).[`logging`](HasOneGetAssociationMixinOptions.md#logging) *** #### nest? > `optional` **nest?**: `boolean` With `raw`, build nested objects from dotted keys such as `'posts.title'`. ##### Default Value ```ts false ``` ##### Inherited from [`HasOneGetAssociationMixinOptions`](HasOneGetAssociationMixinOptions.md).[`nest`](HasOneGetAssociationMixinOptions.md#nest) *** #### noWait? > `optional` **noWait?**: `boolean` Add `NOWAIT` to the row lock so the query fails instead of waiting; only with `lock`. PostgreSQL extension. ##### Inherited from `HasOneGetAssociationMixinOptions.noWait` *** #### offset? > `optional` **offset?**: `number` \| `null` Number of rows to skip; `null` or `undefined` to skip none. ##### Inherited from `HasOneGetAssociationMixinOptions.offset` *** #### order? > `optional` **order?**: readonly `unknown`[] \| [`Order`](../type-aliases/Order.md) Sort order: attribute names, `[attribute, 'ASC' | 'DESC']` pairs or expressions. ##### Inherited from `HasOneGetAssociationMixinOptions.order` *** #### overriding? > `optional` **overriding?**: `"user"` \| `"system"` `OVERRIDING SYSTEM VALUE` / `OVERRIDING USER VALUE` for identity columns. PostgreSQL extension. ##### Inherited from `SaveOptions.overriding` *** #### paranoid? > `optional` **paranoid?**: `boolean` For paranoid models: `false` includes soft-deleted rows. ##### Default Value ```ts true ``` ##### Inherited from [`HasOneGetAssociationMixinOptions`](HasOneGetAssociationMixinOptions.md).[`paranoid`](HasOneGetAssociationMixinOptions.md#paranoid) *** #### plain? > `optional` **plain?**: `boolean` Return a single row instead of an array (set internally by `findOne`). ##### Default Value ```ts false ``` ##### Inherited from [`HasOneGetAssociationMixinOptions`](HasOneGetAssociationMixinOptions.md).[`plain`](HasOneGetAssociationMixinOptions.md#plain) *** #### raw? > `optional` **raw?**: `boolean` Return plain row objects instead of model instances. ##### Default Value ```ts false ``` ##### Inherited from [`HasOneGetAssociationMixinOptions`](HasOneGetAssociationMixinOptions.md).[`raw`](HasOneGetAssociationMixinOptions.md#raw) *** #### rejectOnEmpty? > `optional` **rejectOnEmpty?**: `boolean` \| `Error` Throw `EmptyResultError` (or the given `Error`) when no row is found. ##### Default Value ```ts false ``` ##### Inherited from [`HasOneGetAssociationMixinOptions`](HasOneGetAssociationMixinOptions.md).[`rejectOnEmpty`](HasOneGetAssociationMixinOptions.md#rejectonempty) *** #### replacements? > `optional` **replacements?**: [`Replacements`](../type-aliases/Replacements.md) 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. ##### Inherited from [`HasOneGetAssociationMixinOptions`](HasOneGetAssociationMixinOptions.md).[`replacements`](HasOneGetAssociationMixinOptions.md#replacements) *** #### retry? > `optional` **retry?**: `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](../type-aliases/RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> 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. ##### Inherited from [`HasOneGetAssociationMixinOptions`](HasOneGetAssociationMixinOptions.md).[`retry`](HasOneGetAssociationMixinOptions.md#retry) *** #### returning? > `optional` **returning?**: `boolean` Return all columns after insert/update; PostgreSQL always uses `RETURNING`, so this is accepted for v6 compatibility. ##### Default Value ```ts true ``` ##### Inherited from `SaveOptions.returning` *** #### sample? > `optional` **sample?**: `Readonly`\<\{ `method`: `"BERNOULLI"` \| `"SYSTEM"`; `percent`: `number`; `seed?`: `number`; \}\> Read only a random sample of the model table (`TABLESAMPLE`). PostgreSQL extension. ##### Inherited from `HasOneGetAssociationMixinOptions.sample` *** #### save? > `optional` **save?**: `boolean` Skip saving the associated instance after setting the foreign key when `false`. *** #### scope? > `optional` **scope?**: `string` \| `boolean` \| `string`[] Scope to apply on the associated model, or `false` to remove its default scope. ##### Inherited from [`HasOneCreateAssociationMixinOptions`](HasOneCreateAssociationMixinOptions.md).[`scope`](HasOneCreateAssociationMixinOptions.md#scope) *** #### silent? > `optional` **silent?**: `boolean` Do not update `updatedAt`. ##### Default Value ```ts false ``` ##### Inherited from `SaveOptions.silent` *** #### skipLocked? > `optional` **skipLocked?**: `boolean` Add `SKIP LOCKED` to the row lock; only with `lock`. ##### Inherited from `HasOneGetAssociationMixinOptions.skipLocked` *** #### source? > `readonly` `optional` **source?**: `string` \| [`Subquery`](Subquery.md) Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (`a.union(b)`), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. ##### Inherited from `HasOneGetAssociationMixinOptions.source` *** #### statementTimeout? > `optional` **statementTimeout?**: `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. ##### Inherited from [`HasOneGetAssociationMixinOptions`](HasOneGetAssociationMixinOptions.md).[`statementTimeout`](HasOneGetAssociationMixinOptions.md#statementtimeout) *** #### subQuery? > `optional` **subQuery?**: `boolean` `false` disables the sub-query used for `limit` combined with multi-row includes. ##### Inherited from [`HasOneGetAssociationMixinOptions`](HasOneGetAssociationMixinOptions.md).[`subQuery`](HasOneGetAssociationMixinOptions.md#subquery) *** #### tableAs? > `optional` **tableAs?**: `string` Alias of the main table in `FROM` instead of the model name, so `literal`s and `col('alias.x')` can refer to it (a v6 internal option that v6's typings omit). Ignored when `include` is set. ##### Inherited from [`HasOneGetAssociationMixinOptions`](HasOneGetAssociationMixinOptions.md).[`tableAs`](HasOneGetAssociationMixinOptions.md#tableas) *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. ##### Inherited from [`HasOneGetAssociationMixinOptions`](HasOneGetAssociationMixinOptions.md).[`transaction`](HasOneGetAssociationMixinOptions.md#transaction) *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ##### Inherited from [`HasOneGetAssociationMixinOptions`](HasOneGetAssociationMixinOptions.md).[`useMaster`](HasOneGetAssociationMixinOptions.md#usemaster) *** #### validate? > `optional` **validate?**: `boolean` Run validations. ##### Default Value true (`false` for `bulkCreate`) ##### Inherited from `SaveOptions.validate` *** #### where? > `optional` **where?**: [`WhereOptions`](../type-aliases/WhereOptions.md)\<`any`\> Filter rows; see [WhereOptions](../type-aliases/WhereOptions.md). All rows when omitted. ##### Inherited from `HasOneGetAssociationMixinOptions.where` *** #### with? > `readonly` `optional` **with?**: `Readonly`\<`Record`\<`string`, [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md) \| `Readonly`\<\{ `cycle?`: `Readonly`\<\{ `columns`: readonly `string`[]; `set`: `string`; `using`: `string`; \}\>; `materialized?`: `boolean`; `query`: [`Subquery`](Subquery.md) \| [`WriteStatement`](WriteStatement.md); `recursive?`: [`Subquery`](Subquery.md); `search?`: `Readonly`\<\{ `by`: readonly `string`[]; `mode?`: `"breadth"` \| `"depth"`; `set`: `string`; \}\>; `unionAll?`: `boolean`; \}\>\>\> Common table expressions (`WITH [RECURSIVE] ...`). PostgreSQL extension. ##### Inherited from `HasOneGetAssociationMixinOptions.with` *** #### withTies? > `optional` **withTies?**: `boolean` `FETCH FIRST limit ROWS WITH TIES` instead of `LIMIT`: also returns the rows that tie with the last one on the `order` columns. Needs `limit` and `order`. PostgreSQL extension. ##### Inherited from `HasOneGetAssociationMixinOptions.withTies` ## Interface: HookRegistry Immutable registry of hooks by type: `add` and `remove` return a new registry, so a model or `Sequelize` instance replaces its registry on change. ### Methods #### add() > **add**(`type`, `fn`, `name?`): `HookRegistry` Returns a registry with `fn` added (to the proxied types for `beforeSave` / `afterSave`, like v6). ##### Parameters ###### type `string` Hook type. ###### fn [`HookFunction`](../type-aliases/HookFunction.md) Hook function. ###### name? `string` Name to remove the hook by. ##### Returns `HookRegistry` New registry; the receiver is not modified. ##### Throws Error for an unknown hook type. ##### Example ```ts let registry!: HookRegistry; const next = registry.add('beforeCreate', () => {}, 'audit'); next.has('beforeCreate'); ``` *** #### has() > **has**(`type`): `boolean` Checks whether the registry has hooks of the type. ##### Parameters ###### type `string` Hook type. ##### Returns `boolean` True when at least one hook exists. ##### Throws Error for an unknown hook type. ##### Example ```ts let registry!: HookRegistry; if (registry.has('afterCreate')) { console.log('afterCreate hooks registered'); } ``` *** #### hasOrUndefined() > **hasOrUndefined**(`type`): `boolean` \| `undefined` Like [HookRegistry.has](#has), but `undefined` for a type that never had a hook (what Sequelize v6 `hasHook` returns). ##### Parameters ###### type `string` Hook type. ##### Returns `boolean` \| `undefined` Whether hooks exist, `undefined` when none was ever added. ##### Throws Error for an unknown hook type. ##### Example ```ts let registry!: HookRegistry; const known = registry.hasOrUndefined('beforeCreate'); // undefined until a hook was added ``` *** #### remove() > **remove**(`type`, `nameOrFn?`): `HookRegistry` Returns a registry without hooks matching `nameOrFn`. ##### Parameters ###### type `string` Hook type. ###### nameOrFn? `string` \| [`HookFunction`](../type-aliases/HookFunction.md) Hook name or function; all hooks of the type when omitted. ##### Returns `HookRegistry` New registry; the receiver is not modified. ##### Throws Error for an unknown hook type. ##### Example ```ts let registry!: HookRegistry; const next = registry.remove('beforeCreate', 'audit'); next.has('beforeCreate'); ``` *** #### run() > **run**(`type`, `context`, ...`args`): `Promise`\<`void`\> Runs the hooks of `type` in registration order. ##### Parameters ###### type `"beforeValidate"` \| `"afterValidate"` \| `"validationFailed"` \| `"beforeCreate"` \| `"afterCreate"` \| `"beforeUpdate"` \| `"afterUpdate"` \| `"beforeSave"` \| `"afterSave"` \| `"beforeDestroy"` \| `"afterDestroy"` \| `"beforeRestore"` \| `"afterRestore"` \| `"beforeUpsert"` \| `"afterUpsert"` \| `"beforeBulkCreate"` \| `"afterBulkCreate"` \| `"beforeBulkUpdate"` \| `"afterBulkUpdate"` \| `"beforeBulkDestroy"` \| `"afterBulkDestroy"` \| `"beforeBulkRestore"` \| `"afterBulkRestore"` \| `"beforeFind"` \| `"beforeFindAfterExpandIncludeAll"` \| `"beforeFindAfterOptions"` \| `"afterFind"` \| `"beforeCount"` \| `"beforeConnect"` \| `"afterConnect"` \| `"beforeDisconnect"` \| `"afterDisconnect"` \| `"beforePoolAcquire"` \| `"afterPoolAcquire"` \| `"beforeQuery"` \| `"afterQuery"` \| `"beforeSync"` \| `"afterSync"` \| `"beforeBulkSync"` \| `"afterBulkSync"` \| `"beforeDefine"` \| `"afterDefine"` \| `"beforeInit"` \| `"afterInit"` \| `"beforeAssociate"` \| `"afterAssociate"` Hook type. ###### context `unknown` `this` of the hook functions. ###### args ...readonly `unknown`[] Hook arguments. ##### Returns `Promise`\<`void`\> Resolves when all hooks finished; a rejecting hook stops the chain. ##### Example ```ts let registry!: HookRegistry; await registry.run('beforeCreate', User, { name: 'Ann' }, {}); ``` ## Interface: Inflection The inflection functions postgrelize uses; a library given to `useInflection` must provide them. ### Properties #### pluralize > **pluralize**: (`word`) => `string` Plural form of a word. ##### Parameters ###### word `string` ##### Returns `string` *** #### singularize > **singularize**: (`word`) => `string` Singular form of a word. ##### Parameters ###### word `string` ##### Returns `string` *** #### underscore > **underscore**: (`word`) => `string` `snake_case` form of a name. ##### Parameters ###### word `string` ##### Returns `string` ## Interface: JoinTableAttributes Attributes of a junction row (Sequelize v6 `JoinTableAttributes`). ### Example ```ts const through: JoinTableAttributes = { role: 'owner' }; ``` ### Indexable > \[`attribute`: `string`\]: `unknown` ## Interface: Json JSON path access or JSON conditions. Created by [json](../functions/json.md). ### Extends - [`SqlExpression`](SqlExpression.md) ### Properties #### conditions? > `readonly` `optional` **conditions?**: `object` Conditions object. *** #### path? > `readonly` `optional` **path?**: `string` Dot-separated path starting with the attribute name. *** #### value? > `readonly` `optional` **value?**: `string` \| `number` \| `boolean` \| `null` Value compared with the path (`undefined`: no comparison). ## Interface: Literal Raw SQL fragment inserted into a query as-is. Created by [literal](../functions/literal.md). ### Extends - [`SqlExpression`](SqlExpression.md) ### Properties #### val > `readonly` **val**: `string` SQL text. ## Interface: MergeInsertAction\ `WHEN NOT MATCHED` action of `merge`. Set `insert` or `nothing`. ### Example ```ts const action: MergeInsertAction = { insert: { sku: col('source.sku'), price: 0 } }; ``` ### Type Parameters #### T `T` ### Properties #### insert? > `readonly` `optional` **insert?**: `true` \| `Partial`\<`Record`\\> Values to insert: `true` copies same-named source columns, or a map of values / expressions. *** #### nothing? > `readonly` `optional` **nothing?**: `true` Do nothing. *** #### where? > `readonly` `optional` **where?**: `unknown` Extra condition (`WHEN NOT MATCHED AND ...`); may reference only source columns. ## Interface: MergeMatchedAction\ One `WHEN MATCHED` / `WHEN NOT MATCHED BY SOURCE` action of `merge`. Set exactly one of `update`, `delete` or `nothing`. ### Example ```ts const action: MergeMatchedAction = { where: { active: true }, update: { price: col('source.price') } }; ``` ### Type Parameters #### T `T` ### Properties #### delete? > `readonly` `optional` **delete?**: `true` Delete the target row. *** #### nothing? > `readonly` `optional` **nothing?**: `true` Do nothing. *** #### update? > `readonly` `optional` **update?**: `Partial`\<`Record`\\> Update the target row with these values / expressions (`col('source.attr')`). *** #### where? > `readonly` `optional` **where?**: `unknown` Extra condition (`WHEN MATCHED AND ...`). ## Interface: MergeOptions\ Options of `Model.merge`, which runs a `MERGE` statement. PostgreSQL extension. PostgreSQL 15+ (RETURNING: 17+). Rows of the model table are the target; `source` rows or a subquery are the source. ### See [Model.merge](../classes/Model.md#merge) ### Example ```ts const opts: MergeOptions = { source: [{ sku: 'a1', price: 10 }], on: { sku: col('source.sku') }, whenMatched: { update: { price: col('source.price') } }, whenNotMatched: { insert: true }, }; ``` ### Type Parameters #### T `T` ### Properties #### as? > `readonly` `optional` **as?**: `string` Alias of the source relation. ##### Default Value ```ts 'source' ``` *** #### on > `readonly` **on**: `unknown` Join condition between target (model alias) and source (`col('source.attr')`). *** #### source > `readonly` **source**: [`Subquery`](Subquery.md) \| readonly `Readonly`\<`Record`\<`string`, `unknown`\>\>[] Source rows (plain objects) or a subquery. *** #### whenMatched? > `readonly` `optional` **whenMatched?**: [`MergeMatchedAction`](MergeMatchedAction.md)\<`T`\> \| readonly [`MergeMatchedAction`](MergeMatchedAction.md)\<`T`\>[] Actions for matched rows, applied in order. *** #### whenNotMatched? > `readonly` `optional` **whenNotMatched?**: [`MergeInsertAction`](MergeInsertAction.md)\<`T`\> \| readonly [`MergeInsertAction`](MergeInsertAction.md)\<`T`\>[] Actions for source rows without a target row. *** #### whenNotMatchedBySource? > `readonly` `optional` **whenNotMatchedBySource?**: [`MergeMatchedAction`](MergeMatchedAction.md)\<`T`\> \| readonly [`MergeMatchedAction`](MergeMatchedAction.md)\<`T`\>[] Actions for target rows without a source row (PostgreSQL 17+). ## Interface: Over Window function call `fn OVER (...)`. Created by [over](../functions/over.md). ### Extends - [`SqlExpression`](SqlExpression.md) ### Properties #### fn > `readonly` **fn**: [`Literal`](Literal.md) \| [`Fn`](Fn.md) Window function, e.g. `fn('row_number')`. *** #### orderBy > `readonly` **orderBy**: readonly `unknown`[] `ORDER BY` items: attribute, `[attribute, direction]` or expression. *** #### partitionBy > `readonly` **partitionBy**: readonly `unknown`[] `PARTITION BY` attributes or expressions. ## Interface: PoolCounters Live connection counts of a pool (Sequelize v6 `sequelize-pool` `Pool`). Every property is read at access time, so a health gauge can keep one reference. Reading never opens a connection: all counters are `0` before the first query. ### Example ```ts const { size, available, using, waiting, maxSize } = sequelize.connectionManager.pool; console.log(`${using}/${maxSize} in use, ${waiting} waiting, ${available} idle of ${size}`); ``` ### Extended by - [`ConnectionPool`](ConnectionPool.md) ### Properties #### available > `readonly` **available**: `number` Idle connections ready to be handed out (`idleCount`). *** #### maxSize > `readonly` **maxSize**: `number` Configured `pool.max` (the `pg` default of 10 when unset). *** #### size > `readonly` **size**: `number` Open connections, idle and checked out (`totalCount` of the `pg` pool). *** #### using > `readonly` **using**: `number` Checked out connections: `size - available`. *** #### waiting > `readonly` **waiting**: `number` Acquisitions waiting for a free connection (`waitingCount`). ## Interface: RuntimeOwner Owner of the internal model services: the `Sequelize` instance. ### Extended by - [`Sequelize`](../classes/Sequelize.md) ### Properties #### \[runtimeKey\] > `readonly` **\[runtimeKey\]**: `ModelRuntime` Internal services used by models. ## Abstract Interface: SqlExpression Any expression builder accepted where Sequelize v6 accepts a `SequelizeMethod`. Instances are immutable. ### Extended by - [`Cast`](Cast.md) - [`Col`](Col.md) - [`Excluded`](Excluded.md) - [`Exists`](Exists.md) - [`Fn`](Fn.md) - [`Json`](Json.md) - [`Literal`](Literal.md) - [`Over`](Over.md) - [`Subquery`](Subquery.md) - [`Tuple`](Tuple.md) - [`Where`](Where.md) ## Interface: Subquery SELECT embedded in another statement. Created by `Model.subquery()`, or by combining subqueries with a set operation. PostgreSQL extension. ### Extends - [`SqlExpression`](SqlExpression.md) ### Properties #### build > `readonly` **build**: () => `QueryNode` Builds the query AST (called when the outer statement is compiled). ##### Returns `QueryNode` ### Methods #### except() > **except**(`other`, `options?`): `Subquery` Rows of this query that are not in `other` (`EXCEPT`). ##### Parameters ###### other `Subquery` Query whose rows are removed. ###### options? `Readonly`\<\{ `all?`: `boolean`; \}\> `all` keeps duplicates. ##### Returns `Subquery` Combined subquery. ##### Example ```ts const quiet = User.subquery({ attributes: ['id'] }).except(Post.subquery({ attributes: ['userId'] })); ``` *** #### intersect() > **intersect**(`other`, `options?`): `Subquery` Rows that are in both this query and `other` (`INTERSECT`). ##### Parameters ###### other `Subquery` Query to intersect with. ###### options? `Readonly`\<\{ `all?`: `boolean`; \}\> `all` keeps duplicates. ##### Returns `Subquery` Combined subquery. ##### Example ```ts const both = Post.subquery({ attributes: ['userId'] }).intersect(Task.subquery({ attributes: ['userId'] })); ``` *** #### union() > **union**(`other`, `options?`): `Subquery` Rows of this query or of `other`, without duplicates unless `all` is set (`UNION`). Both queries must select the same number of columns of compatible types. Use the result wherever a subquery fits: `source`, `with`, `Op.in`, `insertFrom`, `merge`. ##### Parameters ###### other `Subquery` Query to combine with. ###### options? `Readonly`\<\{ `all?`: `boolean`; \}\> `all` keeps duplicates. ##### Returns `Subquery` Combined subquery. ##### Example ```ts const ids = Post.subquery({ attributes: ['userId'] }).union(Task.subquery({ attributes: ['userId'] })); const users = await User.findAll({ where: { id: { [Op.in]: ids } } }); ``` ## Interface: Tuple Row constructor `(a, b, ...)` for row comparisons. Created by [tuple](../functions/tuple.md). ### Extends - [`SqlExpression`](SqlExpression.md) ### Properties #### items > `readonly` **items**: readonly `unknown`[] Row items. ## Interface: Where Comparison of an arbitrary expression with a value. Created by [where](../variables/where.md). ### Extends - [`SqlExpression`](SqlExpression.md) ### Properties #### attribute > `readonly` **attribute**: `unknown` Left-hand expression. *** #### comparator > `readonly` **comparator**: `string` \| `symbol` Comparison operator. *** #### logic > `readonly` **logic**: `unknown` Right-hand value. ## Interface: WriteStatement INSERT, UPDATE or DELETE statement for a data-modifying CTE. Created by `Model.insertStatement()`, `Model.updateStatement()` and `Model.deleteStatement()`; not executed on its own. PostgreSQL extension. ### Example ```ts const moved = Task.deleteStatement({ where: { done: true }, returning: true }); const rows = await Task.findAll({ with: { moved }, source: 'moved' }); ``` ### Properties #### build > `readonly` **build**: () => `ModifyingNode` Builds the statement AST (called when the outer statement is compiled). ##### Returns `ModifyingNode` ## Type Alias: AdvisoryLockKey > **AdvisoryLockKey** = `number` \| `bigint` \| `string` Advisory lock key: a 64-bit integer, or a string hashed by PostgreSQL. ## Type Alias: AggregateOptions\ > **AggregateOptions**\<`T`\> = [`CountOptions`](CountOptions.md)\<`T`\> & `Readonly`\<\{ `dataType?`: [`DataTypeInput`](DataTypeInput.md); `plain?`: `boolean`; \}\> Options of `aggregate`, `max`, `min` and `sum`. Same as [CountOptions](CountOptions.md) plus `plain`. ### Type Parameters #### T `T` = [`Values`](Values.md) ### See [Model.aggregate](../classes/Model.md#aggregate) ### Example ```ts const opts: AggregateOptions = { where: { active: true }, paranoid: false }; const highest = await Product.max('price', opts); ``` ## Type Alias: AllowArray\ > **AllowArray**\<`T`\> = `T` \| readonly `T`[] A value or an array of values. ### Type Parameters #### T `T` ## Type Alias: AlterOptions > **AlterOptions** = `Readonly`\<\{ `drop?`: `boolean`; \}\> `alter` options of `sync()`. ### Example ```ts const alter: AlterOptions = { drop: false }; await sequelize.sync({ alter }); ``` ## Type Alias: AlterPolicyOptions > **AlterPolicyOptions** = `Readonly`\<`Pick`\<[`CreatePolicyOptions`](CreatePolicyOptions.md), `"roles"` \| `"using"` \| `"withCheck"`\> & `object`\> Options of `alterPolicy`. PostgreSQL extension. ### Example ```ts const options: AlterPolicyOptions = { roles: ['app_user', 'app_admin'], rename: 'tenant_rows' }; await queryInterface.alterPolicy('documents', 'tenant_isolation', options); ``` ## Type Alias: AlterSequenceOptions > **AlterSequenceOptions** = `Omit`\<[`CreateSequenceOptions`](CreateSequenceOptions.md), `"dataType"` \| `"start"` \| `"ifNotExists"`\> & `Readonly`\<\{ `ifExists?`: `boolean`; `restartWith?`: [`SequenceNumber`](SequenceNumber.md) \| `true`; \}\> Options of `alterSequence`. PostgreSQL extension. ### Example ```ts const options: AlterSequenceOptions = { restartWith: 1, cycle: true }; await queryInterface.alterSequence('invoice_number', options); ``` ## Type Alias: AnyAll\ > **AnyAll**\<`V`\> = \{ `[any]`: readonly `Comparable`\<`V`\>[] \| [`ValuesList`](ValuesList.md)\<`V`\>; \} \| \{ `[all]`: readonly `Comparable`\<`V`\>[] \| [`ValuesList`](ValuesList.md)\<`V`\>; \} `{ [Op.any]: values }` / `{ [Op.all]: values }` used with comparison operators. ### Type Parameters #### V `V` ### Union Members #### Type Literal \{ `[any]`: readonly `Comparable`\<`V`\>[] \| [`ValuesList`](ValuesList.md)\<`V`\>; \} ##### \[any\] > **\[any\]**: readonly `Comparable`\<`V`\>[] \| [`ValuesList`](ValuesList.md)\<`V`\> `ANY (...)`. *** #### Type Literal \{ `[all]`: readonly `Comparable`\<`V`\>[] \| [`ValuesList`](ValuesList.md)\<`V`\>; \} ##### \[all\] > **\[all\]**: readonly `Comparable`\<`V`\>[] \| [`ValuesList`](ValuesList.md)\<`V`\> `ALL (...)`. ## Type Alias: AnyModel > **AnyModel** = [`Model`](../classes/Model.md)\<`any`, `any`\> Any model instance type. ## Type Alias: AssociationName > **AssociationName** = `Readonly`\<\{ `plural`: `string`; `singular`: `string`; \}\> Singular and plural names of an association alias. ## Type Alias: AssociationOptions > **AssociationOptions** = `Readonly`\<\{ `as?`: `string` \| [`AssociationName`](AssociationName.md); `constraints?`: `boolean`; `foreignKey?`: `string` \| [`ForeignKeyOptions`](ForeignKeyOptions.md); `hooks?`: `boolean`; `onDelete?`: `string`; `onUpdate?`: `string`; `scope?`: `Readonly`\<`Record`\<`string`, `unknown`\>\>; `sourceKey?`: `string`; `targetKey?`: `string`; \}\> Options shared by all association methods (Sequelize v6 `AssociationOptions`). Used by `hasOne`, `hasMany`, `belongsTo` and (extended) `belongsToMany`. ### See [Model.hasMany](../classes/Model.md#hasmany) ### Example ```ts const opts: AssociationOptions = { as: 'posts', foreignKey: { name: 'authorId', allowNull: false }, onDelete: 'CASCADE', }; User.hasMany(Post, opts); ``` ## Type Alias: AssociationThrough > **AssociationThrough** = `Readonly`\<\{ `model`: [`ModelStatic`](ModelStatic.md)\<[`AnyModel`](AnyModel.md)\>; `scope?`: `Readonly`\<`Record`\<`string`, `unknown`\>\>; \}\> Resolved junction of a belongsToMany association. ## Type Alias: AssociationType > **AssociationType** = `"BelongsTo"` \| `"HasOne"` \| `"HasMany"` \| `"BelongsToMany"` Kind of association (Sequelize v6 `associationType`). ## Type Alias: AttributeAmounts\ > **AttributeAmounts**\<`T`\> = keyof `T` & `string` \| readonly (keyof `T` & `string`)[] \| `Partial`\<`Record`\\> Attribute name(s) or a map of attribute name to amount for `increment` / `decrement`. ### Type Parameters #### T `T` ## Type Alias: AttributeDefinition > **AttributeDefinition** = `Readonly`\<`Omit`\<[`AttributeOptions`](AttributeOptions.md), `"type"` \| `"field"`\> & `object`\> Normalized attribute (exposed as `Model.rawAttributes[name]`). ## Type Alias: AttributeOptions\ > **AttributeOptions**\<`M`\> = `Readonly`\<\{ `allowNull?`: `boolean`; `autoIncrement?`: `boolean`; `comment?`: `string`; `defaultValue?`: `unknown`; `field?`: `string`; `generated?`: `GeneratedColumn`; `identity?`: `"always"` \| `"byDefault"`; `onDelete?`: `string`; `onUpdate?`: `string`; `primaryKey?`: `boolean`; `references?`: `string` \| [`ReferenceOptions`](ReferenceOptions.md); `type`: [`DataTypeInput`](DataTypeInput.md); `unique?`: `boolean` \| `string` \| [`UniqueOptions`](UniqueOptions.md); `validate?`: [`AttributeValidateOptions`](AttributeValidateOptions.md); `values?`: readonly `string`[]; `get?`(`this`): `unknown`; `set?`(`this`, `value`): `void`; \}\> Column definition of a model attribute (Sequelize v6 `ModelAttributeColumnOptions`). `sync()` turns these into `CREATE TABLE` column definitions; validators run before INSERT / UPDATE. ### Type Parameters #### M `M` *extends* [`AnyModel`](AnyModel.md) = [`AnyModel`](AnyModel.md) ### See [Model.init](../classes/Model.md#init) ### Example ```ts const attr: AttributeOptions = { type: DataTypes.STRING, allowNull: false, unique: true, validate: { isEmail: true }, }; ``` ## Type Alias: AttributeSpec > **AttributeSpec** = `Readonly`\<\{ `exclude?`: readonly `string`[]; `include?`: readonly (`string` \| readonly \[`unknown`, `string`\])[]; \}\> The `attributes: { include, exclude }` form: all attributes plus/minus some. ## Type Alias: AttributeValidateOptions > **AttributeValidateOptions** = `Readonly`\<`Record`\<`string`, [`BuiltinValidatorOption`](BuiltinValidatorOption.md) \| [`AttributeValidatorFunction`](AttributeValidatorFunction.md)\> & `object`\> Attribute `validate` option: Sequelize v6 built-in validators (validator.js names plus `is`, `not`, `len`, `notEmpty`, `min`, `max`, ...), custom functions, and `schema` — any Standard Schema (zod, valibot, arktype; PostgreSQL-independent extension). ### Example ```ts const validate: AttributeValidateOptions = { isEmail: true, len: { args: [3, 120], msg: 'Email must be 3-120 characters' }, noGmail(value: unknown) { if (String(value).endsWith('@gmail.com')) throw new Error('Gmail is not allowed'); }, }; ``` ## Type Alias: AttributeValidatorFunction > **AttributeValidatorFunction** = (`value`) => `unknown` Custom attribute validator; throw (or reject) to fail. Called with the instance as `this`. ### Parameters #### value `unknown` ### Returns `unknown` ## Type Alias: Attributes\ > **Attributes**\<`M`\> = `M`\[`"_attributes"`\] Attribute types of model instance type `M`. ### Type Parameters #### M `M` *extends* [`AnyModel`](AnyModel.md) ## Type Alias: BelongsTo\ > **BelongsTo**\<`S`, `T`\> = `BelongsToAssociation`\<`S`, `T`\> The association created by `Model.belongsTo` (Sequelize v6 `BelongsTo` class type); the `@BelongsTo` decorator has the same name as a value. ### Type Parameters #### S `S` *extends* [`AnyModel`](AnyModel.md) = [`AnyModel`](AnyModel.md) #### T `T` *extends* [`AnyModel`](AnyModel.md) = [`AnyModel`](AnyModel.md) ## Type Alias: BelongsToCreateAssociationMixin\ > **BelongsToCreateAssociationMixin**\<`TModel`\> = (`values?`, `options?`) => `Promise`\<`TModel`\> Type of the `createX` accessor of a belongsTo association (Sequelize v6). ### Type Parameters #### TModel `TModel` *extends* [`AnyModel`](AnyModel.md) ### Parameters #### values? [`CreationAttributes`](CreationAttributes.md)\<`TModel`\> #### options? [`BelongsToCreateAssociationMixinOptions`](../interfaces/BelongsToCreateAssociationMixinOptions.md) ### Returns `Promise`\<`TModel`\> ## Type Alias: BelongsToGetAssociationMixin\ > **BelongsToGetAssociationMixin**\<`TModel`\> = (`options?`) => `Promise`\<`TModel`\> Type of the `getX` accessor of a belongsTo association: `declare getClient: BelongsToGetAssociationMixin;` (Sequelize v6). ### Type Parameters #### TModel `TModel` ### Parameters #### options? [`BelongsToGetAssociationMixinOptions`](../interfaces/BelongsToGetAssociationMixinOptions.md) ### Returns `Promise`\<`TModel`\> ## Type Alias: BelongsToMany\ > **BelongsToMany**\<`S`, `T`\> = `BelongsToManyAssociation`\<`S`, `T`\> The association created by `Model.belongsToMany` (Sequelize v6 `BelongsToMany` class type); the `@BelongsToMany` decorator has the same name as a value. ### Type Parameters #### S `S` *extends* [`AnyModel`](AnyModel.md) = [`AnyModel`](AnyModel.md) #### T `T` *extends* [`AnyModel`](AnyModel.md) = [`AnyModel`](AnyModel.md) ## Type Alias: BelongsToManyAddAssociationMixin\ > **BelongsToManyAddAssociationMixin**\<`TModel`, `TModelPrimaryKey`\> = (`newAssociation?`, `options?`) => `Promise`\<`void`\> Type of the `addX` accessor of a belongsToMany association (Sequelize v6). ### Type Parameters #### TModel `TModel` #### TModelPrimaryKey `TModelPrimaryKey` ### Parameters #### newAssociation? `TModel` \| `TModelPrimaryKey` #### options? [`BelongsToManyAddAssociationMixinOptions`](../interfaces/BelongsToManyAddAssociationMixinOptions.md) ### Returns `Promise`\<`void`\> ## Type Alias: BelongsToManyAddAssociationsMixin\ > **BelongsToManyAddAssociationsMixin**\<`TModel`, `TModelPrimaryKey`\> = (`newAssociations?`, `options?`) => `Promise`\<`void`\> Type of the `addXs` accessor of a belongsToMany association (Sequelize v6). ### Type Parameters #### TModel `TModel` #### TModelPrimaryKey `TModelPrimaryKey` ### Parameters #### newAssociations? (`TModel` \| `TModelPrimaryKey`)[] #### options? [`BelongsToManyAddAssociationsMixinOptions`](../interfaces/BelongsToManyAddAssociationsMixinOptions.md) ### Returns `Promise`\<`void`\> ## Type Alias: BelongsToManyCountAssociationsMixin > **BelongsToManyCountAssociationsMixin** = (`options?`) => `Promise`\<`number`\> Type of the `countXs` accessor of a belongsToMany association (Sequelize v6). ### Parameters #### options? [`BelongsToManyCountAssociationsMixinOptions`](../interfaces/BelongsToManyCountAssociationsMixinOptions.md) ### Returns `Promise`\<`number`\> ## Type Alias: BelongsToManyCreateAssociationMixin\ > **BelongsToManyCreateAssociationMixin**\<`TModel`\> = (`values?`, `options?`) => `Promise`\<`TModel`\> Type of the `createX` accessor of a belongsToMany association (Sequelize v6). ### Type Parameters #### TModel `TModel` *extends* [`AnyModel`](AnyModel.md) ### Parameters #### values? [`CreationAttributes`](CreationAttributes.md)\<`TModel`\> #### options? [`BelongsToManyCreateAssociationMixinOptions`](../interfaces/BelongsToManyCreateAssociationMixinOptions.md) ### Returns `Promise`\<`TModel`\> ## Type Alias: BelongsToManyGetAssociationsMixin\ > **BelongsToManyGetAssociationsMixin**\<`TModel`\> = (`options?`) => `Promise`\<`TModel`[]\> Type of the `getXs` accessor of a belongsToMany association (Sequelize v6). ### Type Parameters #### TModel `TModel` ### Parameters #### options? [`BelongsToManyGetAssociationsMixinOptions`](../interfaces/BelongsToManyGetAssociationsMixinOptions.md) ### Returns `Promise`\<`TModel`[]\> ## Type Alias: BelongsToManyHasAssociationMixin\ > **BelongsToManyHasAssociationMixin**\<`TModel`, `TModelPrimaryKey`\> = (`target`, `options?`) => `Promise`\<`boolean`\> Type of the `hasX` accessor of a belongsToMany association (Sequelize v6). ### Type Parameters #### TModel `TModel` #### TModelPrimaryKey `TModelPrimaryKey` ### Parameters #### target `TModel` \| `TModelPrimaryKey` #### options? [`BelongsToManyHasAssociationMixinOptions`](../interfaces/BelongsToManyHasAssociationMixinOptions.md) ### Returns `Promise`\<`boolean`\> ## Type Alias: BelongsToManyHasAssociationsMixin\ > **BelongsToManyHasAssociationsMixin**\<`TModel`, `TModelPrimaryKey`\> = (`targets`, `options?`) => `Promise`\<`boolean`\> Type of the `hasXs` accessor of a belongsToMany association (Sequelize v6). ### Type Parameters #### TModel `TModel` #### TModelPrimaryKey `TModelPrimaryKey` ### Parameters #### targets (`TModel` \| `TModelPrimaryKey`)[] #### options? [`BelongsToManyHasAssociationsMixinOptions`](../interfaces/BelongsToManyHasAssociationsMixinOptions.md) ### Returns `Promise`\<`boolean`\> ## Type Alias: BelongsToManyOptions > **BelongsToManyOptions** = [`AssociationOptions`](AssociationOptions.md) & `Readonly`\<\{ `otherKey?`: `string` \| [`ForeignKeyOptions`](ForeignKeyOptions.md); `through`: `string` \| [`ModelStatic`](ModelStatic.md)\<[`AnyModel`](AnyModel.md)\> \| [`ThroughOptions`](ThroughOptions.md); \}\> Options of `belongsToMany`. Extends [AssociationOptions](AssociationOptions.md); `foreignKey` is the junction column pointing at the source, `otherKey` the one pointing at the target. ### See [Model.belongsToMany](../classes/Model.md#belongstomany) ### Example ```ts const opts: BelongsToManyOptions = { through: 'ProjectTask', foreignKey: 'projectId', otherKey: 'taskId' }; Project.belongsToMany(Task, opts); ``` ## Type Alias: BelongsToManyRemoveAssociationMixin\ > **BelongsToManyRemoveAssociationMixin**\<`TModel`, `TModelPrimaryKey`\> = (`oldAssociated?`, `options?`) => `Promise`\<`void`\> Type of the `removeX` accessor of a belongsToMany association (Sequelize v6). ### Type Parameters #### TModel `TModel` #### TModelPrimaryKey `TModelPrimaryKey` ### Parameters #### oldAssociated? `TModel` \| `TModelPrimaryKey` #### options? [`BelongsToManyRemoveAssociationMixinOptions`](../interfaces/BelongsToManyRemoveAssociationMixinOptions.md) ### Returns `Promise`\<`void`\> ## Type Alias: BelongsToManyRemoveAssociationsMixin\ > **BelongsToManyRemoveAssociationsMixin**\<`TModel`, `TModelPrimaryKey`\> = (`oldAssociateds?`, `options?`) => `Promise`\<`void`\> Type of the `removeXs` accessor of a belongsToMany association (Sequelize v6). ### Type Parameters #### TModel `TModel` #### TModelPrimaryKey `TModelPrimaryKey` ### Parameters #### oldAssociateds? (`TModel` \| `TModelPrimaryKey`)[] #### options? [`BelongsToManyRemoveAssociationsMixinOptions`](../interfaces/BelongsToManyRemoveAssociationsMixinOptions.md) ### Returns `Promise`\<`void`\> ## Type Alias: BelongsToManySetAssociationsMixin\ > **BelongsToManySetAssociationsMixin**\<`TModel`, `TModelPrimaryKey`\> = (`newAssociations?`, `options?`) => `Promise`\<`void`\> Type of the `setXs` accessor of a belongsToMany association (Sequelize v6). ### Type Parameters #### TModel `TModel` #### TModelPrimaryKey `TModelPrimaryKey` ### Parameters #### newAssociations? (`TModel` \| `TModelPrimaryKey`)[] #### options? [`BelongsToManySetAssociationsMixinOptions`](../interfaces/BelongsToManySetAssociationsMixinOptions.md) ### Returns `Promise`\<`void`\> ## Type Alias: BelongsToSetAssociationMixin\ > **BelongsToSetAssociationMixin**\<`TModel`, `TPrimaryKey`\> = (`newAssociation?`, `options?`) => `Promise`\<`void`\> Type of the `setX` accessor of a belongsTo association (Sequelize v6). ### Type Parameters #### TModel `TModel` #### TPrimaryKey `TPrimaryKey` ### Parameters #### newAssociation? `TModel` \| `TPrimaryKey` #### options? [`BelongsToSetAssociationMixinOptions`](../interfaces/BelongsToSetAssociationMixinOptions.md) ### Returns `Promise`\<`void`\> ## Type Alias: BindOrReplacements > **BindOrReplacements** = [`Replacements`](Replacements.md) \| [`BindParameters`](BindParameters.md) Values of `replacements` or `bind` (Sequelize v6 `BindOrReplacements`). ## Type Alias: BindParameters > **BindParameters** = readonly `unknown`[] \| `Readonly`\<`Record`\<`string`, `unknown`\>\> Bind parameters for raw SQL: `$1` for arrays, `$name` for objects. ## Type Alias: BuildOptions > **BuildOptions** = `Readonly`\<\{ `include?`: [`IncludeOption`](IncludeOption.md); `isNewRecord?`: `boolean`; `raw?`: `boolean`; \}\> Options of `Model.build` (and the model constructor). ### See [Model.build](../classes/Model.md#build) ### Example ```ts const opts: BuildOptions = { isNewRecord: false, raw: true }; const user = User.build({ id: 1, name: 'Ann' }, opts); ``` ## Type Alias: BuiltinValidatorOption > **BuiltinValidatorOption** = `boolean` \| `unknown` \| [`ValidatorSetting`](ValidatorSetting.md) Built-in validator setting: `true`, arguments, or `{ args, msg }`. ## Type Alias: BulkCreateOptions\ > **BulkCreateOptions**\<`T`\> = [`SaveOptions`](SaveOptions.md)\<`T`\> & `object` Options of `bulkCreate`. Extends [SaveOptions](SaveOptions.md). Rows are inserted with one `INSERT` unless `individualHooks` or `include` is set. Validation is off by default (unlike `create`). ### Type Parameters #### T `T` = [`Values`](Values.md) ### Type Declaration #### conflictAttributes? > `optional` **conflictAttributes?**: readonly (keyof `T` & `string`)[] Conflict target attributes for `updateOnDuplicate`. Default: first unique key, else primary key. #### conflictWhere? > `optional` **conflictWhere?**: [`WhereOptions`](WhereOptions.md)\<`T`\> Predicate of a partial unique index used as conflict target. #### ignoreDuplicates? > `optional` **ignoreDuplicates?**: `boolean` Add `ON CONFLICT DO NOTHING`, skipping rows that violate a unique constraint. ##### Default Value ```ts false ``` #### include? > `optional` **include?**: [`IncludeOption`](IncludeOption.md) Create associated rows from nested values (rows are inserted one by one). #### individualHooks? > `optional` **individualHooks?**: `boolean` Run per-instance `create` hooks (rows are then inserted one by one, like v6). ##### Default Value ```ts false ``` #### onConflict? > `optional` **onConflict?**: [`OnConflictOptions`](OnConflictOptions.md)\<`T`\> Advanced `ON CONFLICT` handling; cannot be combined with the options above. PostgreSQL extension. #### unnest? > `optional` **unnest?**: `boolean` Insert with one array parameter per column (`INSERT … SELECT * FROM unnest($1::type[], …)`) instead of one parameter per cell, so batches are not capped by PostgreSQL's 65535 parameters. Every row must provide every column; `ARRAY` columns and conflict options are not supported. PostgreSQL extension. ##### Default Value ```ts false @postgrelize ``` #### updateOnDuplicate? > `optional` **updateOnDuplicate?**: readonly (keyof `T` & `string`)[] Attributes updated from the proposed row on conflict (`DO UPDATE SET a = EXCLUDED.a`). ### See - [Model.bulkCreate](../classes/Model.md#bulkcreate) - [OnConflictOptions](OnConflictOptions.md) ### Example ```ts const rows = [{ email: 'a@example.com', name: 'Ann' }]; await User.bulkCreate(rows, { updateOnDuplicate: ['name'], conflictAttributes: ['email'], transaction, }); const opts: BulkCreateOptions = { ignoreDuplicates: true }; ``` ## Type Alias: BulkHookOptions > **BulkHookOptions** = `object` Hook switches shared by bulk `update`, `destroy` and `restore`. ### Example ```ts const opts: BulkHookOptions = { hooks: true, individualHooks: true }; await User.destroy({ where: { active: false }, ...opts }); ``` ### Properties #### hooks? > `optional` **hooks?**: `boolean` Run the bulk hooks (`beforeBulkUpdate`, `beforeBulkDestroy`, ...). ##### Default Value ```ts true ``` *** #### individualHooks? > `optional` **individualHooks?**: `boolean` Also run per-instance hooks; rows are loaded first, which costs an extra query. ##### Default Value ```ts false ``` ## Type Alias: ColumnDescription > **ColumnDescription** = `Readonly`\<\{ `allowNull`: `boolean`; `comment`: `string` \| `null`; `defaultValue`: `unknown`; `primaryKey`: `boolean`; `special`: readonly `string`[]; `type`: `string`; \}\> Column description returned by `describeTable` (Sequelize v6 shape). ## Type Alias: ColumnInput > **ColumnInput** = [`DataTypeInput`](DataTypeInput.md) \| [`AttributeOptions`](AttributeOptions.md) Argument of `@Column`: a data type or column options. ## Type Alias: ColumnsDescription > **ColumnsDescription** = `Record`\<`string`, [`ColumnDescription`](ColumnDescription.md)\> Column descriptions by column name, as `describeTable` returns them (Sequelize v6 `ColumnsDescription`). ## Type Alias: CompositeValue > **CompositeValue** = `Readonly`\<`Record`\<`string`, `unknown`\>\> Value of a composite column: an object keyed by field name. ## Type Alias: Connection > **Connection** = `Client` Connection that `sequelize.connectionManager.getConnection()` hands out and `releaseConnection()` takes back: the pooled `pg` client of the instance that owns it. ## Type Alias: ConnectionConfig > **ConnectionConfig** = `Readonly`\<\{ `database`: `string` \| `undefined`; `host`: `string`; `password`: `string` \| `undefined`; `port`: `number`; `username`: `string` \| `undefined`; \}\> Connection settings exposed as `sequelize.config` (Sequelize v6 shape). ## Type Alias: ConstraintErrorOptions > **ConstraintErrorOptions** = [`QueryErrorContext`](QueryErrorContext.md) & `Readonly`\<\{ `constraint?`: `string`; `fields?`: `Readonly`\<`Record`\<`string`, `string`\>\> \| readonly `string`[]; `message?`: `string`; `parent?`: [`DriverError`](DriverError.md); `table?`: `string`; \}\> Input of the constraint error constructors: the driver error plus what PostgreSQL reported about the constraint. ### Example ```ts const options: ConstraintErrorOptions = { parent: Object.assign(new Error('violates foreign key constraint'), { code: '23503' }), fields: ['userId'], table: 'posts', constraint: 'posts_userId_fkey', sql: 'INSERT INTO "posts" ("userId") VALUES ($1)', parameters: [42], }; const error = new ForeignKeyConstraintError(options); ``` ## Type Alias: ConstraintOptions > **ConstraintOptions** = `Readonly`\<\{ `deferrable?`: [`DeferrableValue`](DeferrableValue.md); `enforced?`: `boolean`; `exclude?`: readonly [`ExcludeElement`](ExcludeElement.md)[]; `fields?`: readonly `string`[]; `include?`: readonly `string`[]; `name?`: `string`; `notValid?`: `boolean`; `nullsNotDistinct?`: `boolean`; `onDelete?`: `string`; `onUpdate?`: `string`; `period?`: `boolean`; `references?`: `Readonly`\<\{ `field`: `string`; `fields?`: readonly `string`[]; `table`: [`TableName`](TableName.md); \}\>; `type`: `"check"` \| `"unique"` \| `"primary key"` \| `"foreign key"` \| `"exclude"` \| `"CHECK"` \| `"UNIQUE"` \| `"PRIMARY KEY"` \| `"FOREIGN KEY"` \| `"EXCLUDE"`; `using?`: `string`; `where?`: `unknown`; `withoutOverlaps?`: `boolean`; \}\> Options of `addConstraint` (Sequelize v6). ### Example ```ts const options: ConstraintOptions = { type: 'foreign key', fields: ['userId'], name: 'posts_user_fk', references: { table: 'users', field: 'id' }, onDelete: 'CASCADE', }; await queryInterface.addConstraint('posts', options); ``` ## Type Alias: CopyFromOptions\ > **CopyFromOptions**\<`T`\> = [`QueryOptionsBase`](QueryOptionsBase.md) & `Readonly`\<\{ `columns?`: readonly (keyof `T` & `string`)[]; \}\> Options of `Model.copyFrom`, which loads rows with `COPY ... FROM STDIN`. PostgreSQL extension. ### Type Parameters #### T `T` = [`Values`](Values.md) ### See [Model.copyFrom](../classes/Model.md#copyfrom) ### Example ```ts const opts: CopyFromOptions = { columns: ['name', 'email'], transaction }; await User.copyFrom([{ name: 'Ann', email: 'a@example.com' }], opts); ``` ## Type Alias: CopyToFormatOptions > **CopyToFormatOptions** = `Readonly`\<\{ `delimiter?`: `string`; `format?`: `"text"` \| `"csv"` \| `"binary"`; `header?`: `boolean`; `nullString?`: `string`; `quote?`: `string`; \}\> Output format options of `Model.copyTo` (`COPY ... TO STDOUT`). PostgreSQL extension. ### Example ```ts const format: CopyToFormatOptions = { format: 'csv', header: true, delimiter: ';', nullString: '' }; ``` ## Type Alias: CopyToOptions\ > **CopyToOptions**\<`T`\> = [`FindOptions`](FindOptions.md)\<`T`\> & [`CopyToFormatOptions`](CopyToFormatOptions.md) Options of `Model.copyTo`: a finder query that selects the exported rows plus the output format. PostgreSQL extension. ### Type Parameters #### T `T` = [`Values`](Values.md) ### See [Model.copyTo](../classes/Model.md#copyto) ### Example ```ts const opts: CopyToOptions = { where: { active: true }, order: [['id', 'ASC']], format: 'csv', header: true }; ``` ## Type Alias: CountOptions\ > **CountOptions**\<`T`\> = [`QueryOptionsBase`](QueryOptionsBase.md) & `Readonly`\<\{ `col?`: `string`; `distinct?`: `boolean`; `group?`: `string` \| readonly `string`[]; `hooks?`: `boolean`; `include?`: [`IncludeOption`](IncludeOption.md); `paranoid?`: `boolean`; `sample?`: [`TableSampleOptions`](TableSampleOptions.md); `where?`: [`WhereOptions`](WhereOptions.md)\<`T`\>; \}\> & [`CteFindOptions`](CteFindOptions.md) Options of `count`. Includes joins and CTE options; `count` fires `beforeCount` hooks. ### Type Parameters #### T `T` = [`Values`](Values.md) ### See [Model.count](../classes/Model.md#count) ### Example ```ts const total = await Post.count({ where: { published: true }, distinct: true, col: 'authorId' }); const opts: CountOptions = { group: 'authorId' }; const perAuthor = await Post.count(opts); // [{ authorId, count }, ...] ``` ## Type Alias: CountWithOptions\ > **CountWithOptions**\<`T`\> = [`CountOptions`](CountOptions.md)\<`T`\> & `Readonly`\<\{ `group`: `string` \| readonly `string`[]; \}\> [CountOptions](CountOptions.md) with a required `group`, which makes [Model.count](../classes/Model.md#count) resolve to one [GroupedCountResultItem](GroupedCountResultItem.md) per group. ### Type Parameters #### T `T` = [`Values`](Values.md) ### See [Model.count](../classes/Model.md#count) ### Example ```ts const opts: CountWithOptions = { group: ['authorId'] }; const perAuthor = await Post.count(opts); // [{ authorId, count }, ...] ``` ## Type Alias: CreateExtensionOptions > **CreateExtensionOptions** = `Readonly`\<\{ `cascade?`: `boolean`; `ifNotExists?`: `boolean`; `schema?`: `string`; `version?`: `string`; \}\> Options of `createExtension`. PostgreSQL extension. ### Example ```ts const options: CreateExtensionOptions = { ifNotExists: true, schema: 'public' }; await queryInterface.createExtension('pg_trgm', options); ``` ## Type Alias: CreateFunctionOptions > **CreateFunctionOptions** = `Readonly`\<\{ `force?`: `boolean`; `variables?`: readonly [`FunctionVariable`](FunctionVariable.md)[]; \}\> Options of `createFunction`. ### Example ```ts const options: CreateFunctionOptions = { force: true, variables: [{ name: 'limit_rows', type: 'integer', default: 100 }], }; await queryInterface.createFunction('f', [], 'integer', 'plpgsql', 'RETURN limit_rows;', [], options); ``` ## Type Alias: CreateMaterializedViewOptions > **CreateMaterializedViewOptions** = `Readonly`\<\{ `columns?`: readonly `string`[]; `ifNotExists?`: `boolean`; `using?`: `string`; `withData?`: `boolean`; \}\> Options of `createMaterializedView`. PostgreSQL extension. ### Example ```ts const options: CreateMaterializedViewOptions = { ifNotExists: true, withData: false }; await queryInterface.createMaterializedView('post_stats', 'SELECT count(*) AS n FROM "Posts"', options); ``` ## Type Alias: CreateOptions\ > **CreateOptions**\<`T`\> = [`SaveOptions`](SaveOptions.md)\<`T`\> & `object` Options of `create`. Extends [SaveOptions](SaveOptions.md). ### Type Parameters #### T `T` = [`Values`](Values.md) ### Type Declaration #### include? > `optional` **include?**: [`IncludeOption`](IncludeOption.md) Create associated rows from nested values (Sequelize v6). #### onConflict? > `optional` **onConflict?**: [`OnConflictOptions`](OnConflictOptions.md)\<`T`\> Advanced `ON CONFLICT` handling. PostgreSQL extension. ### See [Model.create](../classes/Model.md#create) ### Example ```ts const post = await Post.create( { title: 'Hello', author: { name: 'Ann' } }, { include: [{ association: 'author' }], transaction }, ); ``` ## Type Alias: CreatePartitionOptions > **CreatePartitionOptions** = `Readonly`\<\{ `ifNotExists?`: `boolean`; `partitionBy?`: [`PartitionKey`](PartitionKey.md); \}\> Options of `createPartition`. PostgreSQL extension. ### Example ```ts await queryInterface.createPartition( 'events', 'events_2026', { from: ['2026-01-01'], to: ['2027-01-01'] }, { ifNotExists: true, partitionBy: { strategy: 'list', columns: ['kind'] } }, ); ``` ## Type Alias: CreatePolicyOptions > **CreatePolicyOptions** = `Readonly`\<\{ `command?`: `"all"` \| `"select"` \| `"insert"` \| `"update"` \| `"delete"`; `kind?`: `"permissive"` \| `"restrictive"`; `roles?`: readonly `string`[]; `using?`: [`PolicyCondition`](PolicyCondition.md); `withCheck?`: [`PolicyCondition`](PolicyCondition.md); \}\> Options of `createPolicy`. PostgreSQL extension. ### Example ```ts const options: CreatePolicyOptions = { command: 'select', roles: ['app_user'], using: "tenant_id = current_setting('app.tenant_id')::int", }; await queryInterface.createPolicy('documents', 'tenant_isolation', options); ``` ## Type Alias: CreateSequenceOptions > **CreateSequenceOptions** = `Readonly`\<\{ `cache?`: [`SequenceNumber`](SequenceNumber.md); `cycle?`: `boolean`; `dataType?`: `"smallint"` \| `"integer"` \| `"bigint"`; `ifNotExists?`: `boolean`; `increment?`: [`SequenceNumber`](SequenceNumber.md); `maxValue?`: [`SequenceNumber`](SequenceNumber.md) \| `false`; `minValue?`: [`SequenceNumber`](SequenceNumber.md) \| `false`; `ownedBy?`: [`SequenceOwner`](SequenceOwner.md) \| `null`; `start?`: [`SequenceNumber`](SequenceNumber.md); \}\> Options of `createSequence`. PostgreSQL extension. ### Example ```ts const options: CreateSequenceOptions = { dataType: 'bigint', start: 1000, cache: 10 }; await queryInterface.createSequence('invoice_number', options); ``` ## Type Alias: CreateTableOptions > **CreateTableOptions** = [`QueryOptionsBase`](QueryOptionsBase.md) & `Readonly`\<\{ `comment?`: `string`; `partitionBy?`: [`PartitionKey`](PartitionKey.md); `temporary?`: `boolean`; `unlogged?`: `boolean`; \}\> Options of `createTable`: a table comment, the table persistence and the common query options. ### Example ```ts const options: CreateTableOptions = { comment: 'Blog posts', transaction }; await queryInterface.createTable('posts', { title: DataTypes.STRING }, options); await queryInterface.createTable('scratch', { n: DataTypes.INTEGER }, { temporary: true, transaction }); await queryInterface.createTable('events', { at: DataTypes.DATE }, { partitionBy: { strategy: 'range', columns: ['at'] } }); ``` ## Type Alias: CreateTriggerOptions > **CreateTriggerOptions** = `Readonly`\<\{ `replace?`: `boolean`; \}\> Options of `createTrigger`. ### Example ```ts const options: CreateTriggerOptions = { replace: true }; await queryInterface.createTrigger('Posts', 'posts_touch', 'before', ['update'], 'touch', [], [], options); ``` ## Type Alias: CreateViewOptions > **CreateViewOptions** = `Readonly`\<\{ `checkOption?`: `"local"` \| `"cascaded"`; `columns?`: readonly `string`[]; `recursive?`: `boolean`; `replace?`: `boolean`; `securityBarrier?`: `boolean`; `securityInvoker?`: `boolean`; `temporary?`: `boolean`; \}\> Options of `createView`. PostgreSQL extension. ### Example ```ts const options: CreateViewOptions = { replace: true, columns: ['id', 'title'], checkOption: 'local' }; await queryInterface.createView('published_posts', 'SELECT id, title FROM "Posts" WHERE published', options); ``` ## Type Alias: CreationAttributes\ > **CreationAttributes**\<`M`\> = [`MakeNullishOptional`](MakeNullishOptional.md)\<`M`\[`"_creationAttributes"`\]\> Creation attribute types of model instance type `M`. ### Type Parameters #### M `M` *extends* [`AnyModel`](AnyModel.md) ## Type Alias: CreationOptional\ > **CreationOptional**\<`T`\> = `T` *extends* `null` \| `undefined` ? `T` : `T` & [`CreationOptionalBrand`](CreationOptionalBrand.md) Marks an attribute as optional on creation (e.g. auto-increment ids, defaults). Same semantics as Sequelize v6 `CreationOptional`. ### Type Parameters #### T `T` ## Type Alias: CreationOptionalBrand > **CreationOptionalBrand** = `object` Type brand of [CreationOptional](CreationOptional.md). ### Properties #### \[CreationAttributeBrand\]? > `optional` **\[CreationAttributeBrand\]?**: `true` Brand marker. ## Type Alias: CteCycleOptions > **CteCycleOptions** = `Readonly`\<\{ `columns`: readonly `string`[]; `set`: `string`; `using`: `string`; \}\> `cycle` of a recursive CTE definition. PostgreSQL extension. ### Example ```ts const cycle: CteCycleOptions = { columns: ['id'], set: 'is_cycle', using: 'path' }; ``` ## Type Alias: CteDefinition > **CteDefinition** = `Readonly`\<\{ `cycle?`: [`CteCycleOptions`](CteCycleOptions.md); `materialized?`: `boolean`; `query`: [`Subquery`](../interfaces/Subquery.md) \| [`WriteStatement`](../interfaces/WriteStatement.md); `recursive?`: [`Subquery`](../interfaces/Subquery.md); `search?`: [`CteSearchOptions`](CteSearchOptions.md); `unionAll?`: `boolean`; \}\> Common table expression of the `with` option. PostgreSQL extension. ### Example ```ts const cte: CteDefinition = { query: Task.subquery({ attributes: ['id'], where: { parentId: null } }), unionAll: true, materialized: false, }; ``` ## Type Alias: CteFindOptions > **CteFindOptions** = `Readonly`\<\{ `from?`: [`JoinSources`](JoinSources.md); `source?`: `string` \| [`Subquery`](../interfaces/Subquery.md); `with?`: [`WithOption`](WithOption.md); \}\> CTE-related find options. PostgreSQL extension. Combined into [FindOptions](FindOptions.md) and [CountOptions](CountOptions.md). ### Example ```ts const opts: CteFindOptions = { with: { recent: { query: Post.subquery({ where: { published: true } }) } }, source: 'recent', }; ``` ## Type Alias: CteSearchOptions > **CteSearchOptions** = `Readonly`\<\{ `by`: readonly `string`[]; `mode?`: `"breadth"` \| `"depth"`; `set`: `string`; \}\> `search` of a recursive CTE definition. PostgreSQL extension. ### Example ```ts const search: CteSearchOptions = { by: ['id'], mode: 'breadth', set: 'ordercol' }; ``` ## Type Alias: DataType > **DataType** = `Readonly`\<\{ `bindCast?`: `string`; `isJson?`: `boolean`; `isVirtual?`: `boolean`; `key`: `string`; `parse?`: (`value`) => `unknown`; `serialize?`: (`value`) => `unknown`; `sqlType`: `string`; `subtype?`: `DataType`; `values?`: readonly `string`[]; \}\> Description of a column type: its SQL type and conversions between JavaScript values and the values sent to / received from PostgreSQL. ## Type Alias: DataTypeInput > **DataTypeInput** = `string` \| [`DataType`](DataType.md) \| ((...`args`) => [`DataType`](DataType.md)) A data type used as is (`DataTypes.INTEGER`) or after calling it (`DataTypes.STRING(64)`), or a raw PostgreSQL type name (`'vector(384)'`) like in Sequelize v6. ## Type Alias: DeferrableValue > **DeferrableValue** = `Readonly`\<\{ `sql`: `string`; \}\> `Deferrable` setting of a foreign key or transaction (Sequelize v6 `Deferrable`). ## Type Alias: DefineOptions > **DefineOptions** = `Omit`\<[`InitOptions`](InitOptions.md), `"sequelize"`\> Options of `sequelize.define`: the model options of `Model.init` without `sequelize`. ### Example ```ts const options: DefineOptions = { tableName: 'products', timestamps: false, paranoid: false }; const Product = sequelize.define('Product', { sku: DataTypes.STRING }, options); ``` ## Type Alias: DefinitionOptions > **DefinitionOptions** = [`ModelDefaults`](ModelDefaults.md) & `Readonly`\<\{ `comment?`: `string`; `createdAt?`: `string` \| `boolean`; `deletedAt?`: `string` \| `boolean`; `indexes?`: readonly [`IndexOptions`](IndexOptions.md)[]; `modelName?`: `string`; `name?`: [`ModelNameOptions`](ModelNameOptions.md); `schemaDelimiter?`: `string`; `tableName?`: `string`; `temporary?`: `boolean`; `unlogged?`: `boolean`; `updatedAt?`: `string` \| `boolean`; `version?`: `boolean` \| `string`; \}\> Table-level model options shared by `Model.init` and `sequelize.define`. Extends the model defaults (`paranoid`, `timestamps`, `schema`, ...). ### Example ```ts const opts: DefinitionOptions = { modelName: 'Invoice', tableName: 'invoices', timestamps: true, paranoid: true, version: true, indexes: [{ fields: ['number'], unique: true }], }; ``` ## Type Alias: DestroyOptions\ > **DestroyOptions**\<`T`\> = [`QueryOptionsBase`](QueryOptionsBase.md) & `object` & [`BulkHookOptions`](BulkHookOptions.md) Options of static `destroy`. Extends [BulkHookOptions](BulkHookOptions.md). Paranoid models are soft-deleted (`deletedAt` set) unless `force`. ### Type Parameters #### T `T` = [`Values`](Values.md) ### Type Declaration #### cascade? > `optional` **cascade?**: `boolean` With `truncate`: add `CASCADE`. ##### Default Value ```ts false ``` #### force? > `optional` **force?**: `boolean` For paranoid models: delete rows instead of setting `deletedAt`. ##### Default Value ```ts false ``` #### limit? > `optional` **limit?**: `number` Delete at most this many rows. #### restartIdentity? > `optional` **restartIdentity?**: `boolean` With `truncate`: add `RESTART IDENTITY`. ##### Default Value ```ts false ``` #### returning? > `optional` **returning?**: `boolean` Return deleted rows instead of their count (`DELETE ... RETURNING`). PostgreSQL extension. #### truncate? > `optional` **truncate?**: `boolean` Use `TRUNCATE` instead of `DELETE`. ##### Default Value ```ts false ``` #### using? > `optional` **using?**: [`JoinSources`](JoinSources.md) Extra relations (`DELETE ... USING`), keyed by alias. PostgreSQL extension. #### where? > `optional` **where?**: [`WhereOptions`](WhereOptions.md)\<`T`\> Rows to delete. ### See [Model.destroy](../classes/Model.md#destroy-1) ### Example ```ts await Post.destroy({ where: { draft: true }, force: true }); const opts: DestroyOptions = { truncate: true, cascade: true, restartIdentity: true }; ``` ## Type Alias: DetachPartitionOptions > **DetachPartitionOptions** = `Readonly`\<\{ `concurrently?`: `boolean`; `finalize?`: `boolean`; \}\> Options of `detachPartition`. PostgreSQL extension. ### Example ```ts await queryInterface.detachPartition('events', 'events_2026', { concurrently: true }); ``` ## Type Alias: DisableRowLevelSecurityOptions > **DisableRowLevelSecurityOptions** = `Readonly`\<\{ `noForce?`: `boolean`; \}\> Options of `disableRowLevelSecurity`. PostgreSQL extension. ### Example ```ts const options: DisableRowLevelSecurityOptions = { noForce: true }; await queryInterface.disableRowLevelSecurity('documents', options); ``` ## Type Alias: DriverError > **DriverError** = `Error` & `Readonly`\<\{ `code?`: `string`; `column?`: `string`; `constraint?`: `string`; `detail?`: `string`; `schema?`: `string`; `table?`: `string`; \}\> Driver error object as produced by `pg` (a subset of its fields). ## Type Alias: DropExtensionOptions > **DropExtensionOptions** = `Readonly`\<\{ `cascade?`: `boolean`; `ifExists?`: `boolean`; \}\> Options of `dropExtension`. PostgreSQL extension. ### Example ```ts const options: DropExtensionOptions = { ifExists: true, cascade: true }; await queryInterface.dropExtension('pg_trgm', options); ``` ## Type Alias: DropFunctionOptions > **DropFunctionOptions** = `Readonly`\<\{ `cascade?`: `boolean`; `ifExists?`: `boolean`; \}\> Options of `dropFunction`. ### Example ```ts const options: DropFunctionOptions = { ifExists: true, cascade: true }; await queryInterface.dropFunction('f', [], options); ``` ## Type Alias: DropOptions > **DropOptions** = [`QueryOptionsBase`](QueryOptionsBase.md) & `Readonly`\<\{ `cascade?`: `boolean`; `schema?`: `string`; \}\> Options of `drop()`: `cascade`, `schema` plus the common query options. ### Example ```ts const options: DropOptions = { cascade: true, schema: 'tenant_1' }; await sequelize.drop(options); ``` ## Type Alias: DropPolicyOptions > **DropPolicyOptions** = `Readonly`\<\{ `cascade?`: `boolean`; `ifExists?`: `boolean`; \}\> Options of `dropPolicy`. PostgreSQL extension. ### Example ```ts const options: DropPolicyOptions = { ifExists: true }; await queryInterface.dropPolicy('documents', 'tenant_isolation', options); ``` ## Type Alias: DropSequenceOptions > **DropSequenceOptions** = `Readonly`\<\{ `cascade?`: `boolean`; `ifExists?`: `boolean`; \}\> Options of `dropSequence`. PostgreSQL extension. ### Example ```ts const options: DropSequenceOptions = { ifExists: true }; await queryInterface.dropSequence('invoice_number', options); ``` ## Type Alias: DropTableOptions > **DropTableOptions** = [`QueryOptionsBase`](QueryOptionsBase.md) & `Readonly`\<\{ `cascade?`: `boolean`; \}\> Options of `dropTable`: `cascade` plus the common query options. ### Example ```ts const options: DropTableOptions = { cascade: true }; await queryInterface.dropTable('posts', options); ``` ## Type Alias: DropTriggerOptions > **DropTriggerOptions** = `Readonly`\<\{ `cascade?`: `boolean`; `ifExists?`: `boolean`; \}\> Options of `dropTrigger`. ### Example ```ts const options: DropTriggerOptions = { ifExists: true }; await queryInterface.dropTrigger('Posts', 'posts_touch', options); ``` ## Type Alias: DropViewOptions > **DropViewOptions** = `Readonly`\<\{ `cascade?`: `boolean`; `ifExists?`: `boolean`; \}\> Options of `dropView` and `dropMaterializedView`. PostgreSQL extension. ### Example ```ts const options: DropViewOptions = { ifExists: true, cascade: true }; await queryInterface.dropView('published_posts', options); ``` ## Type Alias: EnableRowLevelSecurityOptions > **EnableRowLevelSecurityOptions** = `Readonly`\<\{ `force?`: `boolean`; \}\> Options of `enableRowLevelSecurity`. PostgreSQL extension. ### Example ```ts const options: EnableRowLevelSecurityOptions = { force: true }; await queryInterface.enableRowLevelSecurity('documents', options); ``` ## Type Alias: ExcludeElement > **ExcludeElement** = `Exclude`\<[`IndexField`](IndexField.md), `string`\> & `Readonly`\<\{ `with`: `string`; \}\> One element of an `exclude` constraint: an index field plus the operator it is compared with. The `expression`, when used, is trusted SQL. ## Type Alias: Expression > **Expression** = [`SqlExpression`](../interfaces/SqlExpression.md) Any expression builder value. ## Type Alias: FindAndCountOptions\ > **FindAndCountOptions**\<`T`\> = [`FindOptions`](FindOptions.md)\<`T`\> & `Readonly`\<\{ `col?`: `string`; `distinct?`: `boolean`; \}\> Options of `findAndCountAll` (Sequelize v6 `FindAndCountOptions`): the finder options plus the count options `distinct` and `col`. The count query reuses `where`, `include`, `paranoid`, `distinct`, `col`, `group`, `replacements`, `transaction` and `logging`. With `group`, `count` is an array of [GroupedCountResultItem](GroupedCountResultItem.md) like in v6. ### Type Parameters #### T `T` = [`Values`](Values.md) ### See [Model.findAndCountAll](../classes/Model.md#findandcountall) ### Example ```ts const options: FindAndCountOptions = { where: { active: true }, limit: 10, offset: 20 }; const { count, rows } = await User.findAndCountAll(options); ``` ## Type Alias: FindAndCountResult\ > **FindAndCountResult**\<`M`, `C`\> = `object` Result of `findAndCountAll`: one page of rows plus the total count (an array of [GroupedCountResultItem](GroupedCountResultItem.md) with `group`). ### Type Parameters #### M `M` #### C `C` = `number` ### Properties #### count > **count**: `C` Total number of matching rows, ignoring `limit` / `offset`. *** #### rows > **rows**: `M`[] Rows of the current page. ## Type Alias: FindAttributeOptions > **FindAttributeOptions** = readonly (`string` \| readonly \[`unknown`, `string`\])[] \| [`AttributeSpec`](AttributeSpec.md) Selected attributes: a list of names or `[expression, alias]` pairs, or an `{ include, exclude }` spec. ### Example ```ts const list: FindAttributeOptions = ['id', 'name', [fn('count', col('id')), 'total']]; const spec: FindAttributeOptions = { include: [[literal('1'), 'one']], exclude: ['password'] }; ``` ## Type Alias: FindOptions\ > **FindOptions**\<`T`\> = [`QueryOptionsBase`](QueryOptionsBase.md) & `Omit`\<[`SelectOptions`](SelectOptions.md), `"where"`\> & `object` & [`CteFindOptions`](CteFindOptions.md) Options of the finders (`findAll`, `findOne`, `findByPk`, ...), without association loading details. Extends the query options (`transaction`, `logging`, ...) and the SELECT options with finder flags and the PostgreSQL CTE extension. `include` is typed through [IncludeOption](IncludeOption.md). A `beforeFind` hook may change these options before the query runs. ### Type Parameters #### T `T` = [`Values`](Values.md) ### Type Declaration #### hooks? > `optional` **hooks?**: `boolean` Run `beforeFind` / `afterFind` hooks. ##### Default Value ```ts true ``` #### include? > `optional` **include?**: [`IncludeOption`](IncludeOption.md) Eager-load associations through JOINs (or separate queries for `separate` includes). #### nest? > `optional` **nest?**: `boolean` With `raw`, build nested objects from dotted keys such as `'posts.title'`. ##### Default Value ```ts false ``` #### paranoid? > `optional` **paranoid?**: `boolean` For paranoid models: `false` includes soft-deleted rows. ##### Default Value ```ts true ``` #### plain? > `optional` **plain?**: `boolean` Return a single row instead of an array (set internally by `findOne`). ##### Default Value ```ts false ``` #### raw? > `optional` **raw?**: `boolean` Return plain row objects instead of model instances. ##### Default Value ```ts false ``` #### rejectOnEmpty? > `optional` **rejectOnEmpty?**: `boolean` \| `Error` Throw `EmptyResultError` (or the given `Error`) when no row is found. ##### Default Value ```ts false ``` #### subQuery? > `optional` **subQuery?**: `boolean` `false` disables the sub-query used for `limit` combined with multi-row includes. #### tableAs? > `optional` **tableAs?**: `string` Alias of the main table in `FROM` instead of the model name, so `literal`s and `col('alias.x')` can refer to it (a v6 internal option that v6's typings omit). Ignored when `include` is set. #### where? > `optional` **where?**: [`WhereOptions`](WhereOptions.md)\<`T`\> Filter rows; see [WhereOptions](WhereOptions.md). All rows when omitted. ### See - [Model.findAll](../classes/Model.md#findall) - [WhereOptions](WhereOptions.md) ### Example ```ts const opts: FindOptions = { where: { active: true, age: { [Op.gte]: 18 } }, attributes: ['id', 'name'], order: [['name', 'ASC']], limit: 10, include: [Post], }; const rows = await User.findAll(opts); ``` ## Type Alias: FindOrBuildOptions\ > **FindOrBuildOptions**\<`T`\> = [`FindOrCreateOptions`](FindOrCreateOptions.md)\<`T`\> Options of `findOrBuild` (Sequelize v6 `FindOrBuildOptions`); the same as [FindOrCreateOptions](FindOrCreateOptions.md). ### Type Parameters #### T `T` = [`Values`](Values.md) ### Example ```ts const options: FindOrBuildOptions = { where: { email: 'a@example.com' }, defaults: { name: 'Ann' } }; ``` ## Type Alias: FindOrCreateOptions\ > **FindOrCreateOptions**\<`T`\> = [`FindOptions`](FindOptions.md)\<`T`\> & `Readonly`\<\{ `defaults?`: `Partial`\<`T`\>; \}\> Options of `findOrCreate` and `findOrBuild`. Extends [FindOptions](FindOptions.md); the `where` values are also used when creating the row. ### Type Parameters #### T `T` = [`Values`](Values.md) ### See [Model.findOrCreate](../classes/Model.md#findorcreate) ### Example ```ts const [user, created] = await User.findOrCreate({ where: { email: 'a@example.com' }, defaults: { name: 'Ann' }, }); ``` ## Type Alias: ForeignKey\ > **ForeignKey**\<`T`\> = `ForeignKeyType`\<`T`\> Marks an attribute type as a foreign key, so it stays out of the creation attributes (Sequelize v6 `ForeignKey`). ### Type Parameters #### T `T` ## Type Alias: ForeignKeyBrandType > **ForeignKeyBrandType** = `object` Type brand of [ForeignKey](ForeignKey.md). ### Properties #### \[ForeignKeyBrand\]? > `optional` **\[ForeignKeyBrand\]?**: `true` Brand marker. ## Type Alias: ForeignKeyOptions > **ForeignKeyOptions** = `Readonly`\<\{ `allowNull?`: `boolean`; `field?`: `string`; `name?`: `string`; \}\> Foreign key given as an object instead of a plain name. ### Example ```ts const fk: ForeignKeyOptions = { name: 'authorId', field: 'author_id', allowNull: false }; User.hasMany(Post, { foreignKey: fk }); ``` ## Type Alias: FromSourceOption > **FromSourceOption** = [`ModelStatic`](ModelStatic.md)\<[`AnyModel`](AnyModel.md)\> \| [`Subquery`](../interfaces/Subquery.md) \| `string` \| `Readonly`\<\{ `values`: `Readonly`\<\{ `columns`: readonly `string`[]; `rows`: readonly (readonly `unknown`[])[]; \}\>; \}\> \| `Readonly`\<\{ `args?`: readonly `unknown`[]; `columns?`: readonly `string`[]; `function`: `string`; `ordinality?`: `string`; \}\> \| `Readonly`\<\{ `jsonTable`: [`JsonTableOptions`](JsonTableOptions.md); \}\> \| `Readonly`\<\{ `lateral`: [`Subquery`](../interfaces/Subquery.md); \}\> \| `Readonly`\<\{ `model`: [`ModelStatic`](ModelStatic.md)\<[`AnyModel`](AnyModel.md)\>; `sample`: [`TableSampleOptions`](TableSampleOptions.md); \}\> Relation of a `from` entry: a model, a subquery, a relation name, or one of the source forms. PostgreSQL extension. ### Example ```ts const from: FromSourceOption[] = [ Post, 'audit_log', { values: { columns: ['id', 'label'], rows: [[1, 'a'], [2, 'b']] } }, { function: 'generate_series', args: [cast(1, 'integer'), cast(3, 'integer')], columns: ['n'] }, { lateral: Post.subquery({ limit: 3 }) }, { model: Post, sample: { method: 'SYSTEM', percent: 5 } }, ]; ``` ## Type Alias: FunctionName > **FunctionName** = `string` \| `Readonly`\<\{ `name`: `string`; `schema?`: `string`; \}\> Function reference: a plain name (`'touch'`, `'app.touch'`) or `{ name, schema }` (quoted exactly). ## Type Alias: FunctionParam > **FunctionParam** = `Readonly`\<\{ `direction?`: `string`; `name?`: `string`; `type`: `string`; \}\> Parameter of a function. ## Type Alias: FunctionVariable > **FunctionVariable** = `Readonly`\<\{ `default?`: `unknown`; `name`: `string`; `type`: `string`; \}\> Local variable declared before `BEGIN`. ## Type Alias: GeoCircle > **GeoCircle** = `Readonly`\<\{ `radius`: `number`; `x`: `number`; `y`: `number`; \}\> `circle` value: center and radius. ## Type Alias: GeoLine > **GeoLine** = `Readonly`\<\{ `a`: `number`; `b`: `number`; `c`: `number`; \}\> `line` value: the line `a·x + b·y + c = 0`. ## Type Alias: GeoPath > **GeoPath** = `Readonly`\<\{ `closed`: `boolean`; `points`: readonly [`GeoPoint`](GeoPoint.md)[]; \}\> `path` value: `closed` paths are written `( … )`, open ones `[ … ]`. ## Type Alias: GeoPoint > **GeoPoint** = `Readonly`\<\{ `x`: `number`; `y`: `number`; \}\> A `point` value. ## Type Alias: GetConnectionOptions > **GetConnectionOptions** = `Readonly`\<\{ `type?`: `"read"` \| `"write"` \| `"SELECT"`; `useMaster?`: `boolean`; `uuid?`: `string`; \}\> Options of `sequelize.connectionManager.getConnection()` (Sequelize v6 `GetConnectionOptions`). ### Example ```ts const options: GetConnectionOptions = { type: 'read', useMaster: false }; const connection = await sequelize.connectionManager.getConnection(options); await sequelize.connectionManager.releaseConnection(connection); ``` ## Type Alias: GroupOption > **GroupOption** = `string` \| [`Fn`](../interfaces/Fn.md) \| [`Col`](../interfaces/Col.md) \| (`string` \| [`Fn`](../interfaces/Fn.md) \| [`Col`](../interfaces/Col.md))[] Value of the `group` option (Sequelize v6 `GroupOption`): attribute names, `col()` or `fn()` expressions. ### Example ```ts const group: GroupOption = ['authorId', fn('date_trunc', 'day', col('createdAt'))]; ``` ## Type Alias: GroupedCountResultItem > **GroupedCountResultItem** = `object` One group of a grouped count (Sequelize v6 `GroupedCountResultItem`): the grouped attributes plus the group's row count. ### Indexable > \[`key`: `string`\]: `unknown` Value of each grouped / projected attribute. ### Properties #### count > **count**: `number` Number of rows in the group. ## Type Alias: HasMany\ > **HasMany**\<`S`, `T`\> = `HasManyAssociation`\<`S`, `T`\> The association created by `Model.hasMany` (Sequelize v6 `HasMany` class type); the `@HasMany` decorator has the same name as a value. ### Type Parameters #### S `S` *extends* [`AnyModel`](AnyModel.md) = [`AnyModel`](AnyModel.md) #### T `T` *extends* [`AnyModel`](AnyModel.md) = [`AnyModel`](AnyModel.md) ## Type Alias: HasManyAddAssociationMixin\ > **HasManyAddAssociationMixin**\<`TModel`, `TModelPrimaryKey`\> = (`newAssociation?`, `options?`) => `Promise`\<`void`\> Type of the `addX` accessor of a hasMany association (Sequelize v6). ### Type Parameters #### TModel `TModel` #### TModelPrimaryKey `TModelPrimaryKey` ### Parameters #### newAssociation? `TModel` \| `TModelPrimaryKey` #### options? [`HasManyAddAssociationMixinOptions`](../interfaces/HasManyAddAssociationMixinOptions.md) ### Returns `Promise`\<`void`\> ## Type Alias: HasManyAddAssociationsMixin\ > **HasManyAddAssociationsMixin**\<`TModel`, `TModelPrimaryKey`\> = (`newAssociations?`, `options?`) => `Promise`\<`void`\> Type of the `addXs` accessor of a hasMany association (Sequelize v6). ### Type Parameters #### TModel `TModel` #### TModelPrimaryKey `TModelPrimaryKey` ### Parameters #### newAssociations? (`TModel` \| `TModelPrimaryKey`)[] #### options? [`HasManyAddAssociationsMixinOptions`](../interfaces/HasManyAddAssociationsMixinOptions.md) ### Returns `Promise`\<`void`\> ## Type Alias: HasManyCountAssociationsMixin > **HasManyCountAssociationsMixin** = (`options?`) => `Promise`\<`number`\> Type of the `countXs` accessor of a hasMany association (Sequelize v6). ### Parameters #### options? [`HasManyCountAssociationsMixinOptions`](../interfaces/HasManyCountAssociationsMixinOptions.md) ### Returns `Promise`\<`number`\> ## Type Alias: HasManyCreateAssociationMixin\ > **HasManyCreateAssociationMixin**\<`TModel`, `TForeignKey`, `TScope`\> = (`values?`, `options?`) => `Promise`\<`TModel`\> Type of the `createX` accessor of a hasMany association; the foreign key and scope attributes are filled in for you (Sequelize v6). ### Type Parameters #### TModel `TModel` *extends* [`AnyModel`](AnyModel.md) #### TForeignKey `TForeignKey` *extends* keyof [`CreationAttributes`](CreationAttributes.md)\<`TModel`\> = `never` #### TScope `TScope` *extends* keyof [`CreationAttributes`](CreationAttributes.md)\<`TModel`\> = `never` ### Parameters #### values? `Omit`\<[`CreationAttributes`](CreationAttributes.md)\<`TModel`\>, `TForeignKey` \| `TScope`\> #### options? [`HasManyCreateAssociationMixinOptions`](../interfaces/HasManyCreateAssociationMixinOptions.md) ### Returns `Promise`\<`TModel`\> ## Type Alias: HasManyGetAssociationsMixin\ > **HasManyGetAssociationsMixin**\<`TModel`\> = (`options?`) => `Promise`\<`TModel`[]\> Type of the `getXs` accessor of a hasMany association: `declare getFiles: HasManyGetAssociationsMixin;` (Sequelize v6). ### Type Parameters #### TModel `TModel` ### Parameters #### options? [`HasManyGetAssociationsMixinOptions`](../interfaces/HasManyGetAssociationsMixinOptions.md) ### Returns `Promise`\<`TModel`[]\> ## Type Alias: HasManyHasAssociationMixin\ > **HasManyHasAssociationMixin**\<`TModel`, `TModelPrimaryKey`\> = (`target`, `options?`) => `Promise`\<`boolean`\> Type of the `hasX` accessor of a hasMany association (Sequelize v6). ### Type Parameters #### TModel `TModel` #### TModelPrimaryKey `TModelPrimaryKey` ### Parameters #### target `TModel` \| `TModelPrimaryKey` #### options? [`HasManyHasAssociationMixinOptions`](../interfaces/HasManyHasAssociationMixinOptions.md) ### Returns `Promise`\<`boolean`\> ## Type Alias: HasManyHasAssociationsMixin\ > **HasManyHasAssociationsMixin**\<`TModel`, `TModelPrimaryKey`\> = (`targets`, `options?`) => `Promise`\<`boolean`\> Type of the `hasXs` accessor of a hasMany association (Sequelize v6). ### Type Parameters #### TModel `TModel` #### TModelPrimaryKey `TModelPrimaryKey` ### Parameters #### targets (`TModel` \| `TModelPrimaryKey`)[] #### options? [`HasManyHasAssociationsMixinOptions`](../interfaces/HasManyHasAssociationsMixinOptions.md) ### Returns `Promise`\<`boolean`\> ## Type Alias: HasManyRemoveAssociationMixin\ > **HasManyRemoveAssociationMixin**\<`TModel`, `TModelPrimaryKey`\> = (`oldAssociated?`, `options?`) => `Promise`\<`void`\> Type of the `removeX` accessor of a hasMany association (Sequelize v6). ### Type Parameters #### TModel `TModel` #### TModelPrimaryKey `TModelPrimaryKey` ### Parameters #### oldAssociated? `TModel` \| `TModelPrimaryKey` #### options? [`HasManyRemoveAssociationMixinOptions`](../interfaces/HasManyRemoveAssociationMixinOptions.md) ### Returns `Promise`\<`void`\> ## Type Alias: HasManyRemoveAssociationsMixin\ > **HasManyRemoveAssociationsMixin**\<`TModel`, `TModelPrimaryKey`\> = (`oldAssociateds?`, `options?`) => `Promise`\<`void`\> Type of the `removeXs` accessor of a hasMany association (Sequelize v6). ### Type Parameters #### TModel `TModel` #### TModelPrimaryKey `TModelPrimaryKey` ### Parameters #### oldAssociateds? (`TModel` \| `TModelPrimaryKey`)[] #### options? [`HasManyRemoveAssociationsMixinOptions`](../interfaces/HasManyRemoveAssociationsMixinOptions.md) ### Returns `Promise`\<`void`\> ## Type Alias: HasManySetAssociationsMixin\ > **HasManySetAssociationsMixin**\<`TModel`, `TModelPrimaryKey`\> = (`newAssociations?`, `options?`) => `Promise`\<`void`\> Type of the `setXs` accessor of a hasMany association (Sequelize v6). ### Type Parameters #### TModel `TModel` #### TModelPrimaryKey `TModelPrimaryKey` ### Parameters #### newAssociations? (`TModel` \| `TModelPrimaryKey`)[] #### options? [`HasManySetAssociationsMixinOptions`](../interfaces/HasManySetAssociationsMixinOptions.md) ### Returns `Promise`\<`void`\> ## Type Alias: HasOne\ > **HasOne**\<`S`, `T`\> = `HasOneAssociation`\<`S`, `T`\> The association created by `Model.hasOne` (Sequelize v6 `HasOne` class type); the `@HasOne` decorator has the same name as a value. ### Type Parameters #### S `S` *extends* [`AnyModel`](AnyModel.md) = [`AnyModel`](AnyModel.md) #### T `T` *extends* [`AnyModel`](AnyModel.md) = [`AnyModel`](AnyModel.md) ## Type Alias: HasOneCreateAssociationMixin\ > **HasOneCreateAssociationMixin**\<`TModel`\> = (`values?`, `options?`) => `Promise`\<`TModel`\> Type of the `createX` accessor of a hasOne association (Sequelize v6). ### Type Parameters #### TModel `TModel` *extends* [`AnyModel`](AnyModel.md) ### Parameters #### values? [`CreationAttributes`](CreationAttributes.md)\<`TModel`\> #### options? [`HasOneCreateAssociationMixinOptions`](../interfaces/HasOneCreateAssociationMixinOptions.md) ### Returns `Promise`\<`TModel`\> ## Type Alias: HasOneGetAssociationMixin\ > **HasOneGetAssociationMixin**\<`TModel`\> = (`options?`) => `Promise`\<`TModel`\> Type of the `getX` accessor of a hasOne association (Sequelize v6). ### Type Parameters #### TModel `TModel` ### Parameters #### options? [`HasOneGetAssociationMixinOptions`](../interfaces/HasOneGetAssociationMixinOptions.md) ### Returns `Promise`\<`TModel`\> ## Type Alias: HasOneSetAssociationMixin\ > **HasOneSetAssociationMixin**\<`TModel`, `TModelPrimaryKey`\> = (`newAssociation?`, `options?`) => `Promise`\<`void`\> Type of the `setX` accessor of a hasOne association (Sequelize v6). ### Type Parameters #### TModel `TModel` #### TModelPrimaryKey `TModelPrimaryKey` ### Parameters #### newAssociation? `TModel` \| `TModelPrimaryKey` #### options? [`HasOneSetAssociationMixinOptions`](../interfaces/HasOneSetAssociationMixinOptions.md) ### Returns `Promise`\<`void`\> ## Type Alias: Hook > **Hook** = `Readonly`\<\{ `fn`: [`HookFunction`](HookFunction.md); `name?`: `string`; \}\> Registered hook: a function, optionally named so it can be removed by name. ## Type Alias: HookFunction > **HookFunction** = (...`args`) => `unknown` Hook function. May be async; its return value is ignored. Receives the model class as `this`. Its parameters are `any`, so an unannotated callback (`Model.beforeFind((options) => ...)`) compiles as it does against the Sequelize v6 typings; annotate them for type checking. ### Parameters #### args ...`any`[] ### Returns `unknown` ## Type Alias: HookType > **HookType** = *typeof* [`HOOK_TYPES`](../variables/HOOK_TYPES.md)\[`number`\] One of [HOOK\_TYPES](../variables/HOOK_TYPES.md). ## Type Alias: HooksOption > **HooksOption** = `Partial`\<`Readonly`\<`Record`\<[`HookType`](HookType.md), [`HookFunction`](HookFunction.md) \| readonly [`HookFunction`](HookFunction.md)[]\>\>\> Hooks passed in `init({ hooks })` / `define({ hooks })`: one function or a list per hook type. ## Type Alias: Identifier > **Identifier** = `number` \| `bigint` \| `string` \| `Buffer` A primary key value (Sequelize v6 `Identifier`). ## Type Alias: IncludeOption > **IncludeOption** = [`Includeable`](Includeable.md) \| readonly [`Includeable`](Includeable.md)[] `include` option: one entry or a list of entries (Sequelize v6 `Includeable | Includeable[]`). ## Type Alias: IncludeOptions > **IncludeOptions** = `object` One `include` entry (Sequelize v6 `IncludeOptions`): which association to load and how. Name the association with `model`, `as` or `association`. Eager loading uses JOINs (see the guide), except `separate`, which runs another query. ### See [FindOptions](FindOptions.md) ### Example ```ts const opts: IncludeOptions = { model: Post, as: 'posts', where: { published: true }, required: false, attributes: ['id', 'title'], include: [{ model: Tag }], }; const users = await User.findAll({ include: [opts] }); ``` ### Properties #### all? > `optional` **all?**: `boolean` Include every association of the model (`{ all: true }`). ##### Default Value ```ts false ``` *** #### as? > `optional` **as?**: `string` Alias of the association, as given when it was defined. *** #### association? > `optional` **association?**: `Association` \| `string` Association object or alias. *** #### attributes? > `optional` **attributes?**: [`FindAttributeOptions`](FindAttributeOptions.md) Selected attributes. *** #### include? > `optional` **include?**: [`IncludeOption`](IncludeOption.md) Nested includes. *** #### lateral? > `optional` **lateral?**: `boolean` Fetch only the first `limit` rows per parent in the database (`JOIN LATERAL` over the parent keys) instead of loading every child and trimming in memory. Needs `separate` and `limit`. PostgreSQL extension. ##### Default Value ```ts false ``` *** #### limit? > `optional` **limit?**: `number` Maximum rows per include of a separate include. *** #### model? > `optional` **model?**: `Model` Associated model; the association is looked up by model (and `as`). *** #### on? > `optional` **on?**: `unknown` Custom `ON` condition of the join; replaces the condition derived from the association keys. Not used by belongsToMany includes (the junction joins keep their key conditions). See [WhereOptions](WhereOptions.md). *** #### order? > `optional` **order?**: `unknown` Order of a separate include. *** #### paranoid? > `optional` **paranoid?**: `boolean` For paranoid targets: `false` includes soft-deleted rows. ##### Default Value ```ts true ``` *** #### required? > `optional` **required?**: `boolean` `INNER JOIN` (true) or `LEFT OUTER JOIN` (false). *** #### right? > `optional` **right?**: `boolean` Use `RIGHT OUTER JOIN`. ##### Default Value ```ts false ``` *** #### separate? > `optional` **separate?**: `boolean` Load a hasMany association with a separate query instead of a JOIN. ##### Default Value ```ts false ``` *** #### through? > `optional` **through?**: [`IncludeThroughOptions`](IncludeThroughOptions.md) Junction options for belongsToMany. *** #### where? > `optional` **where?**: `unknown` Filter on the included rows; makes the include required unless `required: false`. See [WhereOptions](WhereOptions.md). ## Type Alias: IncludeThroughOptions > **IncludeThroughOptions** = `Readonly`\<\{ `attributes?`: [`FindAttributeOptions`](FindAttributeOptions.md); `where?`: `unknown`; \}\> Options of the junction table of an included belongsToMany association. ### Example ```ts const through: IncludeThroughOptions = { attributes: ['role'], where: { role: 'owner' } }; const rows = await Project.findAll({ include: [{ model: User, through }] }); ``` ## Type Alias: Includeable > **Includeable** = `Model` \| `Association` \| `string` \| [`IncludeOptions`](IncludeOptions.md) One entry of the `include` option (Sequelize v6 `Includeable`): a model, an association (or its alias), include options, or `{ all: true }` for every association of the model. ### See [IncludeOptions](IncludeOptions.md) ### Example ```ts const entries: Includeable[] = [Post, 'profile', { model: Tag, required: false }, { all: true }]; const users = await User.findAll({ include: entries }); ``` ## Type Alias: IncrementOptions\ > **IncrementOptions**\<`T`\> = [`QueryOptionsBase`](QueryOptionsBase.md) & `Readonly`\<\{ `by?`: `number`; `silent?`: `boolean`; `where?`: [`WhereOptions`](WhereOptions.md)\<`T`\>; \}\> Options of `increment` and `decrement`. Runs one `UPDATE ... SET col = col + n` and updates `updatedAt` unless `silent`. ### Type Parameters #### T `T` = [`Values`](Values.md) ### See [Model.increment](../classes/Model.md#increment-1) ### Example ```ts await Product.increment('stock', { by: 5, where: { id: 1 } }); const opts: IncrementOptions = { by: 2, silent: true, transaction }; const product = await Product.findByPk(1); await product!.decrement('stock', opts); ``` ## Type Alias: IndexField > **IndexField** = `string` \| `IndexElementModifiers` & `Readonly`\<\{ `expression?`: `undefined`; `name`: `string`; \}\> \| `IndexElementModifiers` & `Readonly`\<\{ `expression`: `string`; `name?`: `undefined`; \}\> Index field: a column name, `{ name, order, nulls, collate, operator }` or an expression `{ expression, ... }`. The `expression` is trusted SQL (not escaped): never build it from user input. An index with an expression field needs an explicit `name`. ## Type Alias: IndexOptions > **IndexOptions** = `Readonly`\<\{ `concurrently?`: `boolean`; `fields?`: readonly [`IndexField`](IndexField.md)[]; `ifNotExists?`: `boolean`; `include?`: readonly `string`[]; `name?`: `string`; `nullsNotDistinct?`: `boolean`; `operator?`: `string`; `unique?`: `boolean`; `using?`: `string`; `where?`: `unknown`; \}\> Options of `addIndex` and model `indexes` (Sequelize v6 `IndexesOptions`). ### Example ```ts const options: IndexOptions = { fields: ['email'], unique: true, where: { active: true }, using: 'btree', }; await queryInterface.addIndex('users', options); ``` ## Type Alias: InferAttributes\ > **InferAttributes**\<`M`, `Options`\> = `{ [K in keyof M as AttributeKey]: M[K] }` Infers attribute types from a model class declaration (Sequelize v6 `InferAttributes`). ### Type Parameters #### M `M` #### Options `Options` *extends* [`InferAttributesOptions`](InferAttributesOptions.md)\ = [`InferAttributesOptions`](InferAttributesOptions.md)\<`never`\> ## Type Alias: InferAttributesOptions\ > **InferAttributesOptions**\<`OmittedKeys`\> = `Readonly`\<\{ `omit?`: `OmittedKeys`; \}\> Options of [InferAttributes](InferAttributes.md). ### Type Parameters #### OmittedKeys `OmittedKeys` ### Example ```ts type UserAttributes = InferAttributes; ``` ## Type Alias: InferCreationAttributes\ > **InferCreationAttributes**\<`M`, `Options`\> = \{ \[K in keyof M as AttributeKey\\]: IsBranded\ extends true ? M\[K\] \| undefined : M\[K\] \} Infers creation attribute types; `CreationOptional` attributes may be `undefined` (Sequelize v6 `InferCreationAttributes`). ### Type Parameters #### M `M` #### Options `Options` *extends* [`InferAttributesOptions`](InferAttributesOptions.md)\ = [`InferAttributesOptions`](InferAttributesOptions.md)\<`never`\> ## Type Alias: InitOptions > **InitOptions** = [`DefinitionOptions`](DefinitionOptions.md) & `Readonly`\<\{ `defaultScope?`: [`ScopeOptions`](ScopeOptions.md); `hooks?`: [`HooksOption`](HooksOption.md); `scopes?`: `Readonly`\<`Record`\<`string`, [`ScopeDefinition`](ScopeDefinition.md)\>\>; `sequelize`: [`RuntimeOwner`](../interfaces/RuntimeOwner.md); `validate?`: `Readonly`\<`Record`\<`string`, [`ModelValidatorFunction`](ModelValidatorFunction.md)\>\>; `validationSchema?`: [`StandardSchemaV1`](StandardSchemaV1.md); `whereMergeStrategy?`: [`WhereMergeStrategy`](WhereMergeStrategy.md); \}\> Options of `Model.init`: table-level options plus hooks, scopes and validation. Extends [DefinitionOptions](DefinitionOptions.md). ### See [Model.init](../classes/Model.md#init) ### Example ```ts User.init( { name: DataTypes.STRING, email: DataTypes.STRING }, { sequelize, modelName: 'User', paranoid: true, defaultScope: { where: { active: true } }, scopes: { admins: { where: { role: 'admin' } } }, }, ); ``` ## Type Alias: InsertFromOptions\ > **InsertFromOptions**\<`T`\> = [`QueryOptionsBase`](QueryOptionsBase.md) & `Readonly`\<\{ `columns`: readonly (keyof `T` & `string`)[]; `onConflict?`: [`OnConflictOptions`](OnConflictOptions.md)\<`T`\>; `returningOld?`: `boolean`; \}\> Options of `Model.insertFrom`, which inserts the result of a subquery (`INSERT ... SELECT`). PostgreSQL extension. ### Type Parameters #### T `T` = [`Values`](Values.md) ### See [Model.insertFrom](../classes/Model.md#insertfrom) ### Example ```ts const opts: InsertFromOptions = { columns: ['title', 'projectId'], onConflict: { action: 'nothing' }, }; ``` ## Type Alias: InsertOptions\ > **InsertOptions**\<`T`\> = [`QueryOptionsBase`](QueryOptionsBase.md) & `object` Options of `Model.insert`. PostgreSQL extension. Rows are inserted with a single `INSERT` and no per-row save hooks; only the bulk-create hooks run. ### Type Parameters #### T `T` = [`Values`](Values.md) ### Type Declaration #### fields? > `optional` **fields?**: readonly (keyof `T` & `string`)[] Attributes to insert; others are ignored. Default: all given attributes. #### hooks? > `optional` **hooks?**: `boolean` Run `beforeBulkCreate` / `afterBulkCreate` hooks. ##### Default Value ```ts true ``` #### onConflict? > `optional` **onConflict?**: [`OnConflictOptions`](OnConflictOptions.md)\<`T`\> Advanced `ON CONFLICT` handling. #### overriding? > `optional` **overriding?**: `"system"` \| `"user"` `OVERRIDING SYSTEM VALUE` / `OVERRIDING USER VALUE` for identity columns. #### returningOld? > `optional` **returningOld?**: `boolean` Return the pre-statement row values as `instance.oldValues`. PostgreSQL extension, needs PostgreSQL 18+. #### validate? > `optional` **validate?**: `boolean` Validate rows before inserting. ##### Default Value ```ts false ``` ### See [Model.insert](../classes/Model.md#insert) ### Example ```ts const opts: InsertOptions = { onConflict: { target: ['email'], action: 'nothing' }, hooks: false, }; const rows = await User.insert([{ email: 'a@example.com' }], opts); ``` ## Type Alias: InstanceDestroyOptions > **InstanceDestroyOptions** = [`QueryOptionsBase`](QueryOptionsBase.md) & `object` Options of instance `destroy`. ### Type Declaration #### force? > `optional` **force?**: `boolean` For paranoid models: delete the row instead of setting `deletedAt`. ##### Default Value ```ts false ``` #### hooks? > `optional` **hooks?**: `boolean` Run `beforeDestroy` / `afterDestroy` hooks. ##### Default Value ```ts true ``` ### See [Model.destroy](../classes/Model.md#destroy-1) ### Example ```ts await post.destroy({ force: true, transaction }); const opts: InstanceDestroyOptions = { hooks: false }; ``` ## Type Alias: InstanceUpdateOptions\ > **InstanceUpdateOptions**\<`T`\> = [`SaveOptions`](SaveOptions.md)\<`T`\> Options of the instance updates that association accessors run (Sequelize v6 `InstanceUpdateOptions`): the [SaveOptions](SaveOptions.md). ### Type Parameters #### T `T` = [`Values`](Values.md) ### Example ```ts const options: InstanceUpdateOptions = { fields: ['name'], transaction }; await user.update({ name: 'Ann' }, options); ``` ## Type Alias: IntegerDataType > **IntegerDataType** = [`DataType`](DataType.md) & `Readonly`\<\{ `UNSIGNED`: `IntegerDataType`; `ZEROFILL`: `IntegerDataType`; \}\> Integer type with Sequelize v6 MySQL-only modifiers kept as no-ops for compatibility. ## Type Alias: IsolationLevel > **IsolationLevel** = *typeof* [`ISOLATION_LEVELS`](../variables/ISOLATION_LEVELS.md)\[keyof *typeof* [`ISOLATION_LEVELS`](../variables/ISOLATION_LEVELS.md)\] One of [ISOLATION\_LEVELS](../variables/ISOLATION_LEVELS.md). ## Type Alias: JoinSources > **JoinSources** = `Readonly`\<`Record`\<`string`, [`FromSourceOption`](FromSourceOption.md)\>\> Extra relations for finders' `from`, `UPDATE ... FROM` and `DELETE ... USING`, keyed by alias. PostgreSQL extension. ## Type Alias: JsonTableColumnOptions > **JsonTableColumnOptions** = `Readonly`\<\{ `exists?`: `boolean`; `name`: `string`; `ordinality?`: `boolean`; `path?`: `string`; `type?`: `string`; \}\> One column of a [JsonTableOptions](JsonTableOptions.md). PostgreSQL extension. ### Example ```ts const columns: JsonTableColumnOptions[] = [ { name: 'position', ordinality: true }, { name: 'qty', type: 'integer', path: '$.quantity' }, { name: 'hasNote', exists: true, path: '$.note' }, ]; ``` ## Type Alias: JsonTableOptions > **JsonTableOptions** = `Readonly`\<\{ `columns`: readonly [`JsonTableColumnOptions`](JsonTableColumnOptions.md)[]; `doc`: `unknown`; `path`: `string`; \}\> `JSON_TABLE` source: turns a JSON document into rows. PostgreSQL extension. Needs PostgreSQL 17. ### Example ```ts const source: JsonTableOptions = { doc: { items: [{ sku: 'a', qty: 2 }] }, path: '$.items[*]', columns: [{ name: 'sku', type: 'text' }, { name: 'qty', type: 'integer' }], }; ``` ## Type Alias: JsonbPathKind > **JsonbPathKind** = `"exists"` \| `"match"` \| `"query"` \| `"queryFirst"` \| `"queryArray"` Function of [jsonbPath](../functions/jsonbPath.md): `exists`, `match`, `query`, `queryFirst` or `queryArray`. ## Type Alias: JsonbPathOptions > **JsonbPathOptions** = `Readonly`\<\{ `silent?`: `boolean`; `tz?`: `boolean`; `vars?`: `Readonly`\<`Record`\<`string`, `unknown`\>\>; \}\> Options of [jsonbPath](../functions/jsonbPath.md). PostgreSQL extension. ### Example ```ts const options: JsonbPathOptions = { vars: { min: 10 }, silent: true }; ``` ## Type Alias: LOCK > **LOCK** = [`LockStrength`](LockStrength.md) Row lock strength, as a type (Sequelize v6 `LOCK` is both an enum value and a type). Same as [LockStrength](LockStrength.md). ## Type Alias: LockOption > **LockOption** = `boolean` \| `LockNode`\[`"strength"`\] \| `Readonly`\<\{ `level`: `LockNode`\[`"strength"`\]; `of?`: [`LockTarget`](LockTarget.md); \}\> `lock` option of finders: `true` (`FOR UPDATE`), a lock strength, or `{ level, of }`. ## Type Alias: LockStrength > **LockStrength** = *typeof* [`LOCK`](../variables/LOCK.md)\[keyof *typeof* [`LOCK`](../variables/LOCK.md)\] One of [LOCK](../variables/LOCK.md). ## Type Alias: LockTarget > **LockTarget** = `Readonly`\<\{ `name`: `string`; \}\> Model whose rows are locked by `lock.of`. ## Type Alias: LoggingFunction > **LoggingFunction** = (`sql`, `timing?`) => `void` Function receiving executed SQL. The text has the values inlined as literals, like in Sequelize v6, so it can be run as it is; the statement sent to PostgreSQL keeps its bound parameters. With `benchmark: true` the second argument is the duration in ms; otherwise it is an object `{ bind, parameterizedSql }` (v6 passes its query options there, whose typings declare the parameter as `timing?: number`): `bind` holds the bound values and `parameterizedSql` the statement as it was sent (`$1`, `$2`, ...), without the `Executing (...)` prefix. `parameterizedSql` is a postgrelize extension. ### Parameters #### sql `string` #### timing? `number` ### Returns `void` ## Type Alias: MakeNullishOptional\ > **MakeNullishOptional**\<`T`\> = `{ [K in keyof T as null extends T[K] ? never : undefined extends T[K] ? never : K]: T[K] }` & `{ [K in keyof T as null extends T[K] ? K : undefined extends T[K] ? K : never]?: T[K] }` Makes nullable attributes optional (Sequelize v6 `MakeNullishOptional`). ### Type Parameters #### T `T` ## Type Alias: MergeActionName > **MergeActionName** = `"INSERT"` \| `"UPDATE"` \| `"DELETE"` Action reported by `merge_action()`. ## Type Alias: MergeResult\ > **MergeResult**\<`M`\> = `Readonly`\<\{ `rowCount`: `number`; `rows`: readonly `Readonly`\<\{ `action`: [`MergeActionName`](MergeActionName.md); `instance`: `M`; \}\>[]; \}\> Result of `Model.merge`. ### Type Parameters #### M `M` ## Type Alias: ModelAttributes\ > **ModelAttributes**\<`M`, `TAttributes`\> = \{ readonly \[name in keyof TAttributes\]: DataTypeInput \| AttributeOptions\ \} Attributes passed to `Model.init` / `sequelize.define`: a type or full column options per attribute. `M` is the model instance type of `this` in `get` / `set`; with `TAttributes` (v6 shape) every attribute of that type must be defined. ### Type Parameters #### M `M` *extends* [`AnyModel`](AnyModel.md) = [`AnyModel`](AnyModel.md) #### TAttributes `TAttributes` = `any` ## Type Alias: ModelBase > **ModelBase** = `Readonly`\<\{ `_attributes`: `unknown`; `_creationAttributes`: `unknown`; `_model`: `unknown`; `_previousDataValues`: `unknown`; `dataValues`: `unknown`; `isNewRecord`: `unknown`; `oldValues`: `unknown`; `sequelize`: `unknown`; `wasInserted`: `unknown`; \}\> Base instance members that are never attributes. ## Type Alias: ModelClassDecorator > **ModelClassDecorator** = \{(`value`, `context`): `void`; (`constructor`): `void`; \} Decorator applied to a class. Accepts the TC39 standard call `(value, context)` and the legacy `experimentalDecorators` call `(constructor)`. ### Call Signature > (`value`, `context`): `void` #### Parameters ##### value new (...`args`) => `object` ##### context `ClassDecoratorContext` #### Returns `void` ### Call Signature > (`constructor`): `void` #### Parameters ##### constructor new (...`args`) => `object` #### Returns `void` ## Type Alias: ModelCtor\ > **ModelCtor**\<`M`\> = [`ModelStatic`](ModelStatic.md)\<`M`\> A model class whose instances are `M` (Sequelize v6 `ModelCtor`, the old name of [ModelStatic](ModelStatic.md)). ### Type Parameters #### M `M` *extends* [`Model`](../classes/Model.md)\<`any`, `any`\> ### Example ```ts const register = (model: ModelCtor): ModelCtor => model; ``` ## Type Alias: ModelDefaults > **ModelDefaults** = `Readonly`\<\{ `freezeTableName?`: `boolean`; `hooks?`: [`HooksOption`](HooksOption.md); `paranoid?`: `boolean`; `schema?`: `string`; `timestamps?`: `boolean`; `underscored?`: `boolean`; \}\> Defaults applied to every model defined through this instance (Sequelize v6 `define` option). ## Type Alias: ModelDefined\ > **ModelDefined**\<`S`, `T`\> = [`ModelStatic`](ModelStatic.md)\<[`Model`](../classes/Model.md)\<`S`, `T`\>\> A model class with the given attribute and creation attribute types (Sequelize v6 `ModelDefined`), the return type of `sequelize.define` in typed code. ### Type Parameters #### S `S` *extends* `object` #### T `T` *extends* `object` ### Example ```ts type UserModel = ModelDefined<{ id: number; name: string }, { name: string }>; ``` ## Type Alias: ModelGetter > **ModelGetter** = () => [`ModelStatic`](ModelStatic.md)\<[`AnyModel`](AnyModel.md)\> Lazily resolved model class, so decorators can refer to classes defined later in the file. ### Returns [`ModelStatic`](ModelStatic.md)\<[`AnyModel`](AnyModel.md)\> ## Type Alias: ModelNameOptions > **ModelNameOptions** = `Readonly`\<\{ `plural?`: `string`; `singular?`: `string`; \}\> Singular and plural forms of a model name (Sequelize v6 `ModelNameOptions`). ### Example ```ts const name: ModelNameOptions = { singular: 'person', plural: 'people' }; ``` ## Type Alias: ModelPropertyDecorator > **ModelPropertyDecorator** = \{(`value`, `context`): `void`; (`prototype`, `key`): `void`; \} Decorator applied to an attribute (class field). Accepts the TC39 standard call `(undefined, context)` and the legacy `experimentalDecorators` call `(prototype, key)`. ### Call Signature > (`value`, `context`): `void` #### Parameters ##### value `undefined` ##### context `ClassFieldDecoratorContext` #### Returns `void` ### Call Signature > (`prototype`, `key`): `void` #### Parameters ##### prototype `object` ##### key `string` \| `symbol` #### Returns `void` ## Type Alias: ModelStatic\ > **ModelStatic**\<`M`\> = `NonConstructor`\<*typeof* [`Model`](../classes/Model.md)\> & \{new (`values?`, `options?`): `M`; `prototype`: `M`; \} A model class whose instances are `M` (Sequelize v6 `ModelStatic`). ### Type Parameters #### M `M` *extends* [`AnyModel`](AnyModel.md) ## Type Alias: ModelStaticMethodDecorator > **ModelStaticMethodDecorator** = \{(`value`, `context`): `void`; (`constructor`, `key`, `descriptor?`): `void`; \} Decorator applied to a static method (hooks). Accepts the TC39 standard call `(method, context)` and the legacy `experimentalDecorators` call `(constructor, key, descriptor)`. ### Call Signature > (`value`, `context`): `void` #### Parameters ##### value (...`args`) => `unknown` ##### context `ClassMethodDecoratorContext` #### Returns `void` ### Call Signature > (`constructor`, `key`, `descriptor?`): `void` #### Parameters ##### constructor `object` ##### key `string` \| `symbol` ##### descriptor? `PropertyDescriptor` #### Returns `void` ## Type Alias: ModelType\ > **ModelType**\<`TModelAttributes`, `TCreationAttributes`\> = new () => [`Model`](../classes/Model.md)\<`TModelAttributes`, `TCreationAttributes`\> A no-argument model constructor with the given attribute types (Sequelize v6 `ModelType`). ### Type Parameters #### TModelAttributes `TModelAttributes` *extends* `object` = `any` #### TCreationAttributes `TCreationAttributes` *extends* `object` = `TModelAttributes` ### Returns [`Model`](../classes/Model.md)\<`TModelAttributes`, `TCreationAttributes`\> ### Example ```ts const factory: ModelType<{ id: number }> = class extends Model<{ id: number }> {}; ``` ## Type Alias: ModelValidatorFunction > **ModelValidatorFunction** = (`this`, `next`) => `unknown` Model-level validator (`validate` model option); throw (or reject) to fail. Called with the instance as `this`. As in Sequelize v6, a validator that declares a parameter is callback style: it receives `next` and calls `next(error)` to fail or `next()` to pass. ### Parameters #### this `any` #### next (`error?`) => `void` ### Returns `unknown` ### Example ```ts const sync: ModelValidatorFunction = () => { throw new Error('invalid'); }; const callback: ModelValidatorFunction = (next) => next('invalid'); ``` ## Type Alias: NamedHookAdder > **NamedHookAdder** = \{(`fn`): `void`; (`name`, `fn`): `void`; \} Named hook method of a model class, e.g. `Model.beforeCreate`: registers a hook function, optionally under a name that [Model.removeHook](../classes/Model.md#removehook) can use later. ### Call Signature > (`fn`): `void` #### Parameters ##### fn [`HookFunction`](HookFunction.md) Hook function. #### Returns `void` ### Call Signature > (`name`, `fn`): `void` #### Parameters ##### name `string` Hook name, used to remove it later. ##### fn [`HookFunction`](HookFunction.md) Hook function. #### Returns `void` ### Example ```ts User.beforeCreate(async (instance: User) => { instance.set('email', String(instance.get('email')).trim()); }); User.afterCreate('audit', async (instance: User) => { console.log('created', instance.get('id')); }); ``` ## Type Alias: NonAttribute\ > **NonAttribute**\<`T`\> = `T` *extends* `null` \| `undefined` ? `T` : `T` & [`NonAttributeBrandType`](NonAttributeBrandType.md) Marks a class property as not being a model attribute (Sequelize v6 `NonAttribute`). ### Type Parameters #### T `T` ## Type Alias: NonAttributeBrandType > **NonAttributeBrandType** = `object` Type brand of [NonAttribute](NonAttribute.md). ### Properties #### \[NonAttributeBrand\]? > `optional` **\[NonAttributeBrand\]?**: `true` Brand marker. ## Type Alias: NonNullFindOptions\ > **NonNullFindOptions**\<`T`\> = [`FindOptions`](FindOptions.md)\<`T`\> & `Readonly`\<\{ `rejectOnEmpty`: `boolean` \| `Error`; \}\> [FindOptions](FindOptions.md) with a required `rejectOnEmpty` (Sequelize v6 `NonNullFindOptions`): the finder never resolves to `null`. ### Type Parameters #### T `T` = [`Values`](Values.md) ### Example ```ts const options: NonNullFindOptions = { where: { id: 1 }, rejectOnEmpty: true }; const user = await User.findOne(options); ``` ## Type Alias: NotificationHandler > **NotificationHandler** = (`payload`, `channel`) => `unknown` Handler of `LISTEN` notifications. ### Parameters #### payload `string` \| `undefined` #### channel `string` ### Returns `unknown` ## Type Alias: OnConflictColumnsTarget\ > **OnConflictColumnsTarget**\<`T`\> = `Readonly`\<\{ `columns`: readonly (keyof `T` & `string` \| [`Literal`](../interfaces/Literal.md) \| [`Fn`](../interfaces/Fn.md))[]; `where?`: [`WhereOptions`](WhereOptions.md)\<`T`\>; \}\> Columns or index expressions identifying the unique index, optionally a partial index. ### Type Parameters #### T `T` ## Type Alias: OnConflictConstraintTarget > **OnConflictConstraintTarget** = `Readonly`\<\{ `constraint`: `string`; \}\> Named constraint used as arbiter (`ON CONFLICT ON CONSTRAINT name`). ## Type Alias: OnConflictOptions\ > **OnConflictOptions**\<`T`\> = `Readonly`\<\{ `action`: `"nothing"` \| [`OnConflictUpdateAction`](OnConflictUpdateAction.md)\<`T`\>; `target?`: [`OnConflictTarget`](OnConflictTarget.md)\<`T`\>; \}\> Advanced `INSERT ... ON CONFLICT` specification. PostgreSQL extension. ### Type Parameters #### T `T` ### Example ```ts const rows = [{ tenantId: 1, key: 'views', hits: 1, version: 2 }]; await Product.bulkCreate(rows, { onConflict: { target: ['tenantId', 'key'], action: { update: { hits: literal('"Product"."hits" + EXCLUDED."hits"'), updatedAt: fn('now') }, where: { version: { [Op.lt]: excluded('version') } }, }, }, }); ``` ## Type Alias: OnConflictTarget\ > **OnConflictTarget**\<`T`\> = readonly (keyof `T` & `string` \| [`Literal`](../interfaces/Literal.md) \| [`Fn`](../interfaces/Fn.md))[] \| [`OnConflictColumnsTarget`](OnConflictColumnsTarget.md)\<`T`\> \| [`OnConflictConstraintTarget`](OnConflictConstraintTarget.md) Conflict target of [OnConflictOptions](OnConflictOptions.md). ### Type Parameters #### T `T` ## Type Alias: OnConflictUpdate\ > **OnConflictUpdate**\<`T`\> = readonly (keyof `T` & `string`)[] \| `Readonly`\<\{ \[K in keyof T\]?: T\[K\] \| SqlExpression \}\> Values assigned on conflict: a list of attributes (each set to `excluded(attribute)`) or a map of attribute to value or expression (`excluded()`, `col()`, `fn()`, `literal()`). ### Type Parameters #### T `T` ## Type Alias: OnConflictUpdateAction\ > **OnConflictUpdateAction**\<`T`\> = `Readonly`\<\{ `update`: [`OnConflictUpdate`](OnConflictUpdate.md)\<`T`\>; `where?`: [`WhereOptions`](WhereOptions.md)\<`T`\>; \}\> `DO UPDATE` action of [OnConflictOptions](OnConflictOptions.md). ### Type Parameters #### T `T` ## Type Alias: OpSymbol > **OpSymbol** = *typeof* [`Op`](../variables/Op.md)\[keyof *typeof* [`Op`](../variables/Op.md)\] Union of all operator symbols in [Op](../variables/Op.md). ## Type Alias: Optional\ > **Optional**\<`T`, `K`\> = `Omit`\<`T`, `K`\> & `Partial`\<`Pick`\<`T`, `K`\>\> Makes the given keys of `T` optional (Sequelize v6 `Optional`). ### Type Parameters #### T `T` #### K `K` *extends* keyof `T` ## Type Alias: Options > **Options** = [`SequelizeOptions`](SequelizeOptions.md) Options of the `Sequelize` constructor (Sequelize v6 `Options`); same as [SequelizeOptions](SequelizeOptions.md). ### Example ```ts const options: Options = { dialect: 'postgres', logging: false }; const sequelize = new Sequelize('postgres://localhost/app', options); ``` ## Type Alias: Order > **Order** = [`Fn`](../interfaces/Fn.md) \| [`Col`](../interfaces/Col.md) \| [`Literal`](../interfaces/Literal.md) \| [`OrderItem`](OrderItem.md)[] `order` option of finders: a single expression or a list of [OrderItem](OrderItem.md). ## Type Alias: OrderItem > **OrderItem** = `string` \| `unknown` \| readonly \[`unknown`, `string`?\] One `order` item: attribute name, `[attribute, direction]`, `[expression, direction]` or an expression. ## Type Alias: PartitionBoundMarker > **PartitionBoundMarker** = `Readonly`\<\{ `keyword`: `"MINVALUE"` \| `"MAXVALUE"`; \}\> Marker of a `MINVALUE` / `MAXVALUE` bound inside a range partition bound. ## Type Alias: PartitionBoundSpec > **PartitionBoundSpec** = `Readonly`\<\{ `in`: readonly `unknown`[]; \}\> \| `Readonly`\<\{ `from`: readonly `unknown`[]; `to`: readonly `unknown`[]; \}\> \| `Readonly`\<\{ `modulus`: `number`; `remainder`: `number`; \}\> \| `Readonly`\<\{ `default`: `true`; \}\> Bounds of a partition: `{ in }` (list), `{ from, to }` (range; `PartitionBound.MINVALUE` / `MAXVALUE` allowed), `{ modulus, remainder }` (hash) or `{ default: true }`. Values are rendered as literals. ### Example ```ts const bound: PartitionBoundSpec = { from: ['2026-01-01'], to: ['2027-01-01'] }; await queryInterface.createPartition('events', 'events_2026', bound); ``` ## Type Alias: PartitionKey > **PartitionKey** = `Readonly`\<\{ `columns`: readonly [`PartitionKeyElement`](PartitionKeyElement.md)[]; `strategy`: [`PartitionStrategy`](PartitionStrategy.md); \}\> Partition key of `createTable({ partitionBy })` and of a sub-partitioned partition. ### Example ```ts const key: PartitionKey = { strategy: 'range', columns: ['createdAt'] }; await queryInterface.createTable('events', { createdAt: DataTypes.DATE }, { partitionBy: key }); ``` ## Type Alias: PartitionKeyElement > **PartitionKeyElement** = `string` \| `Readonly`\<\{ `collate?`: `string`; `expression?`: `undefined`; `name`: `string`; `operator?`: `string`; \}\> \| `Readonly`\<\{ `collate?`: `string`; `expression`: `string`; `name?`: `undefined`; `operator?`: `string`; \}\> Element of a partition key: a column, or an expression (trusted SQL) with collation and operator class. ## Type Alias: PartitionStrategy > **PartitionStrategy** = `"range"` \| `"list"` \| `"hash"` Partitioning method of a partitioned table. ## Type Alias: PolicyCondition > **PolicyCondition** = `string` \| `Readonly`\<`Record`\<`string` \| `symbol`, `unknown`\>\> Condition of a policy: SQL text (trusted) or a where object (values rendered as literals). ## Type Alias: PoolOptions > **PoolOptions** = `Readonly`\<\{ `acquire?`: `number`; `evict?`: `number`; `idle?`: `number`; `max?`: `number`; `maxUses?`: `number`; `min?`: `number`; \}\> Connection pool settings (Sequelize v6 `PoolOptions`), given as the `pool` option of [SequelizeOptions](SequelizeOptions.md). ### Example ```ts const pool: PoolOptions = { max: 10, idle: 10_000, acquire: 30_000 }; const db = new Sequelize('postgres://user:pass@localhost:5432/app', { pool }); ``` ## Type Alias: ProjectionAlias > **ProjectionAlias** = readonly \[`string` \| [`Literal`](../interfaces/Literal.md) \| [`Fn`](../interfaces/Fn.md) \| [`Col`](../interfaces/Col.md), `string`\] Aliased attribute `[expression, alias]` in `attributes` (Sequelize v6 `ProjectionAlias`). ### Example ```ts const total: ProjectionAlias = [fn('count', col('id')), 'total']; const rows = await Post.findAll({ attributes: ['authorId', total], group: ['authorId'] }); ``` ## Type Alias: QualifiedTable > **QualifiedTable** = `Readonly`\<\{ `schema?`: `string`; `tableName`: `string`; \}\> Schema-qualified table reference. ## Type Alias: QualifiedTableName > **QualifiedTableName** = `Readonly`\<\{ `delimiter`: `string`; `name`: `string`; `schema`: `string`; `table`: `string`; `tableName`: `string`; `toString`: () => `string`; \}\> Schema-qualified table name returned by `getTableName`. ## Type Alias: QueryErrorContext > **QueryErrorContext** = `Readonly`\<\{ `parameters?`: readonly `unknown`[]; `sql?`: `string`; \}\> Context attached to errors raised while executing SQL. ## Type Alias: QueryOptions > **QueryOptions** = [`QueryOptionsBase`](QueryOptionsBase.md) & `Readonly`\<\{ `bind?`: [`BindParameters`](BindParameters.md); `mapToModel?`: `boolean`; `model?`: [`ModelStatic`](ModelStatic.md)\<[`AnyModel`](AnyModel.md)\>; `nest?`: `boolean`; `plain?`: `boolean`; `raw?`: `boolean`; `replacements?`: [`Replacements`](Replacements.md); `type?`: [`QueryType`](QueryType.md); \}\> Options of `sequelize.query`, in addition to the common query options such as `transaction` and `logging`. ### Example ```ts const rows = await sequelize.query('SELECT * FROM users WHERE id = :id', { type: QueryTypes.SELECT, replacements: { id: 1 }, model: User, mapToModel: true, }); ``` ## Type Alias: QueryOptionsBase > **QueryOptionsBase** = `object` Options common to every query issued by a model. ### Extended by - [`BelongsToManyCountAssociationsMixinOptions`](../interfaces/BelongsToManyCountAssociationsMixinOptions.md) - [`HasManyCountAssociationsMixinOptions`](../interfaces/HasManyCountAssociationsMixinOptions.md) ### Properties #### benchmark? > `optional` **benchmark?**: `boolean` Pass query duration to the logger. *** #### logging? > `optional` **logging?**: [`LoggingFunction`](LoggingFunction.md) \| `false` SQL logger for this query, or `false`. *** #### replacements? > `optional` **replacements?**: [`Replacements`](Replacements.md) 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. *** #### retry? > `optional` **retry?**: [`RetryOptions`](RetryOptions.md) 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. *** #### statementTimeout? > `optional` **statementTimeout?**: `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. *** #### transaction? > `optional` **transaction?**: [`Transaction`](../classes/Transaction.md) \| `null` Transaction to run in; `null` forces running outside the CLS transaction. *** #### useMaster? > `optional` **useMaster?**: `boolean` Force the writer even for SELECTs when read replicas are configured. postgrelize extension. ## Type Alias: QueryOptionsWithModel\ > **QueryOptionsWithModel**\<`M`\> = [`QueryOptions`](QueryOptions.md) & `Readonly`\<\{ `model`: [`ModelStatic`](ModelStatic.md)\<`M`\>; \}\> [QueryOptions](QueryOptions.md) with a required `model` (Sequelize v6 `QueryOptionsWithModel`): the rows become instances of it. ### Type Parameters #### M `M` *extends* [`AnyModel`](AnyModel.md) The model instance type. ### Example ```ts const options: QueryOptionsWithModel = { model: User, mapToModel: true }; const users = await sequelize.query('SELECT * FROM users', options); ``` ## Type Alias: QueryOptionsWithType\ > **QueryOptionsWithType**\<`T`\> = [`QueryOptions`](QueryOptions.md) & `Readonly`\<\{ `type`: `T`; \}\> [QueryOptions](QueryOptions.md) with a required query `type` (Sequelize v6 `QueryOptionsWithType`). ### Type Parameters #### T `T` *extends* [`QueryType`](QueryType.md) The query type, e.g. `QueryTypes.SELECT`. ### Example ```ts const options: QueryOptionsWithType = { type: QueryTypes.SELECT }; const rows = await sequelize.query('SELECT 1 AS one', options); ``` ## Type Alias: QueryType > **QueryType** = *typeof* [`QueryTypes`](../variables/QueryTypes.md)\[keyof *typeof* [`QueryTypes`](../variables/QueryTypes.md)\] One of [QueryTypes](../variables/QueryTypes.md). ## Type Alias: QueryTypes > **QueryTypes** = [`QueryType`](QueryType.md) `QueryTypes` is also a type, as the v6 enum is: the union of the query type names. ## Type Alias: RangeBound\ > **RangeBound**\<`T`\> = `Readonly`\<\{ `inclusive`: `boolean`; `value`: `T` \| `null`; \}\> Range bound as returned by Sequelize v6 for `RANGE` attributes. ### Type Parameters #### T `T` ## Type Alias: ReferenceOptions > **ReferenceOptions** = `Readonly`\<\{ `deferrable?`: [`DeferrableValue`](DeferrableValue.md); `key?`: `string`; `model`: `string` \| [`ReferencedTable`](ReferencedTable.md) \| `ReferencedModel`; \}\> Foreign key target of an attribute. ### Example ```ts const ref: ReferenceOptions = { model: 'Users', key: 'id', deferrable: Deferrable.INITIALLY_DEFERRED }; ``` ## Type Alias: ReferencedTable > **ReferencedTable** = `Readonly`\<\{ `schema?`: `string`; `tableName`: `string`; \}\> Table referenced by a foreign key. ## Type Alias: RefreshMaterializedViewOptions > **RefreshMaterializedViewOptions** = `Readonly`\<\{ `concurrently?`: `boolean`; `withData?`: `boolean`; \}\> Options of `refreshMaterializedView`. PostgreSQL extension. ### Example ```ts const options: RefreshMaterializedViewOptions = { concurrently: true }; await queryInterface.refreshMaterializedView('post_stats', options); ``` ## Type Alias: Replacements > **Replacements** = readonly `unknown`[] \| `Readonly`\<`Record`\<`string`, `unknown`\>\> Values substituted into raw SQL: `?` for arrays, `:name` for objects. ## Type Alias: ReplicationMember > **ReplicationMember** = `Readonly`\<\{ `database?`: `string`; `host?`: `string`; `password?`: `string`; `port?`: `number`; `username?`: `string`; \}\> Connection settings of one replication member. ## Type Alias: ReplicationOptions > **ReplicationOptions** = `Readonly`\<\{ `read`: [`ReplicationMember`](ReplicationMember.md) \| readonly [`ReplicationMember`](ReplicationMember.md)[]; `write?`: [`ReplicationMember`](ReplicationMember.md); \}\> The `replication` option: readers receive SELECTs outside transactions, the writer everything else. Members inherit missing connection settings from the top-level options. See [ReplicationMember](ReplicationMember.md). ### Example ```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 }); ``` ## Type Alias: RestoreOptions\ > **RestoreOptions**\<`T`\> = [`QueryOptionsBase`](QueryOptionsBase.md) & `Readonly`\<\{ `where?`: [`WhereOptions`](WhereOptions.md)\<`T`\>; \}\> & [`BulkHookOptions`](BulkHookOptions.md) Options of static `restore`, which clears `deletedAt` of soft-deleted rows of paranoid models. ### Type Parameters #### T `T` = [`Values`](Values.md) ### See [Model.restore](../classes/Model.md#restore-1) ### Example ```ts await Post.restore({ where: { authorId: 1 }, transaction }); const opts: RestoreOptions = { hooks: false }; ``` ## Type Alias: RetryMatch > **RetryMatch** = `string` \| `RegExp` \| (abstract new (...`args`) => `unknown`) \| ((`error`) => `unknown`) One entry of `RetryOptions.match`, compared with the error that made an attempt fail (as in `retry-as-promised`, which Sequelize v6 uses): a string equal to `error.message` or `String(error)`, a regular expression that matches either of them, an error class (`error instanceof match`), or a predicate `(error) => boolean`. ## Type Alias: RetryOptions > **RetryOptions** = `Readonly`\<\{ `backoffBase?`: `number`; `backoffExponent?`: `number`; `backoffJitter?`: `number`; `match?`: readonly [`RetryMatch`](RetryMatch.md)[]; `max?`: `number`; `name?`: `string`; `report?`: (`message`, `options`, `error?`) => `void`; `timeout?`: `number`; \}\> Retry settings (Sequelize v6 `RetryOptions`), given as the `retry` option of [SequelizeOptions](SequelizeOptions.md) 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`. ### Example ```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 }); ``` ## Type Alias: SaveOptions\ > **SaveOptions**\<`T`\> = [`QueryOptionsBase`](QueryOptionsBase.md) & `object` & `object` Options of `create` and instance `save`. Runs `beforeSave` / `beforeCreate` / `beforeUpdate` hooks (and their `after` counterparts) unless `hooks` is `false`. ### Type Parameters #### T `T` = `any` ### Type Declaration #### fields? > `optional` **fields?**: readonly (`0` *extends* `1` & `T` ? `any` : keyof `T` & `string`)[] Attributes to save; others are ignored. Default: all changed attributes. Mutable so hooks can adjust it, as in v6. #### hooks? > `optional` **hooks?**: `boolean` Run lifecycle hooks. ##### Default Value ```ts true ``` #### overriding? > `optional` **overriding?**: `"system"` \| `"user"` `OVERRIDING SYSTEM VALUE` / `OVERRIDING USER VALUE` for identity columns. PostgreSQL extension. #### returning? > `optional` **returning?**: `boolean` Return all columns after insert/update; PostgreSQL always uses `RETURNING`, so this is accepted for v6 compatibility. ##### Default Value ```ts true ``` #### silent? > `optional` **silent?**: `boolean` Do not update `updatedAt`. ##### Default Value ```ts false ``` #### validate? > `optional` **validate?**: `boolean` Run validations. ##### Default Value true (`false` for `bulkCreate`) ### See [Model.create](../classes/Model.md#create) ### Example ```ts const opts: SaveOptions = { fields: ['name', 'email'], validate: true, transaction }; await user.save(opts); ``` ## Type Alias: ScopeDefinition > **ScopeDefinition** = [`ScopeOptions`](ScopeOptions.md) \| ((...`args`) => [`ScopeOptions`](ScopeOptions.md)) Scope definition: options, or a function of arguments returning options. ## Type Alias: ScopeOptions > **ScopeOptions** = `Readonly`\<`Record`\<`string`, `unknown`\>\> Find options stored in a scope (`where`, `attributes`, `order`, `limit`, ...). ### Example ```ts const scope: ScopeOptions = { where: { active: true }, order: [['createdAt', 'DESC']], limit: 100 }; User.init({ name: DataTypes.STRING }, { sequelize, defaultScope: scope }); ``` ## Type Alias: ScopeSelector > **ScopeSelector** = `string` \| `ScopeMethodSelector` \| [`ScopeOptions`](ScopeOptions.md) \| `null` Scope selector for `Model.scope()`: a name, `{ method: [name, ...args] }`, or inline options. ## Type Alias: ScopesInput > **ScopesInput** = `Readonly`\<`Record`\<`string`, [`ScopeDefinition`](ScopeDefinition.md)\>\> Named scopes given to `@Scopes`. ## Type Alias: SelectOptions > **SelectOptions** = `object` Options that shape a SELECT statement, shared by finders and `copyTo`. Finders extend this with flags such as `raw` and `include` ([FindOptions](FindOptions.md)). ### Example ```ts const opts: SelectOptions = { attributes: ['status', [fn('count', col('id')), 'n']], group: ['status'], having: { n: { [Op.gt]: 1 } }, order: [['status', 'DESC']], limit: 20, offset: 40, }; ``` ### Properties #### attributes? > `optional` **attributes?**: [`FindAttributeOptions`](FindAttributeOptions.md) Selected attributes. All attributes when omitted. *** #### distinctOn? > `optional` **distinctOn?**: readonly `unknown`[] `SELECT DISTINCT ON (...)`: attributes or expressions. PostgreSQL extension. *** #### group? > `optional` **group?**: `unknown` `GROUP BY` attributes or expressions. *** #### having? > `optional` **having?**: `unknown` `HAVING` condition. *** #### limit? > `optional` **limit?**: `number` \| `null` Maximum number of rows; `null` or `undefined` for no limit. *** #### lock? > `optional` **lock?**: [`LockOption`](LockOption.md) Row lock (`FOR UPDATE` etc.); requires a transaction. *** #### noWait? > `optional` **noWait?**: `boolean` Add `NOWAIT` to the row lock so the query fails instead of waiting; only with `lock`. PostgreSQL extension. *** #### offset? > `optional` **offset?**: `number` \| `null` Number of rows to skip; `null` or `undefined` to skip none. *** #### order? > `optional` **order?**: [`Order`](Order.md) \| readonly [`OrderItem`](OrderItem.md)[] Sort order: attribute names, `[attribute, 'ASC' | 'DESC']` pairs or expressions. *** #### sample? > `optional` **sample?**: [`TableSampleOptions`](TableSampleOptions.md) Read only a random sample of the model table (`TABLESAMPLE`). PostgreSQL extension. *** #### skipLocked? > `optional` **skipLocked?**: `boolean` Add `SKIP LOCKED` to the row lock; only with `lock`. *** #### where? > `optional` **where?**: `unknown` Filter; finders type this as [WhereOptions](WhereOptions.md). *** #### withTies? > `optional` **withTies?**: `boolean` `FETCH FIRST limit ROWS WITH TIES` instead of `LIMIT`: also returns the rows that tie with the last one on the `order` columns. Needs `limit` and `order`. PostgreSQL extension. ## Type Alias: SequelizeOptions > **SequelizeOptions** = `Readonly`\<\{ `benchmark?`: `boolean`; `database?`: `string`; `define?`: [`ModelDefaults`](ModelDefaults.md); `dialect?`: `"postgres"`; `dialectModule?`: `object`; `dialectOptions?`: `Readonly`\<`Omit`\<`PoolConfig`, `"types"`\>\>; `hooks?`: [`HooksOption`](HooksOption.md); `host?`: `string`; `inAsAnyThreshold?`: `number`; `logging?`: [`LoggingFunction`](LoggingFunction.md) \| `false`; `minifyAliases?`: `boolean`; `password?`: `string`; `pool?`: [`PoolOptions`](PoolOptions.md); `port?`: `number`; `replication?`: [`ReplicationOptions`](ReplicationOptions.md); `retry?`: [`RetryOptions`](RetryOptions.md); `ssl?`: `PoolConfig`\[`"ssl"`\]; `statementCache?`: `boolean` \| [`StatementCacheOptions`](StatementCacheOptions.md); `timezone?`: `string`; `username?`: `string`; \}\> Options of the [Sequelize](../classes/Sequelize.md) constructor (PostgreSQL subset of Sequelize v6 `Options`). All fields are optional; values given in a connection URL are overridden by these fields. ### Example ```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); ``` ## Type Alias: SequenceNumber > **SequenceNumber** = `number` \| `bigint` Whole number accepted in sequence options. ## Type Alias: SequenceOwner > **SequenceOwner** = `Readonly`\<\{ `column`: `string`; `table`: [`TableName`](TableName.md); \}\> Column that owns a sequence (the sequence is dropped with the column). ## Type Alias: SetOperationOptions > **SetOperationOptions** = `Readonly`\<\{ `all?`: `boolean`; \}\> Options of [Subquery.union](../interfaces/Subquery.md#union), [Subquery.intersect](../interfaces/Subquery.md#intersect) and [Subquery.except](../interfaces/Subquery.md#except). PostgreSQL extension. ### Example ```ts const opts: SetOperationOptions = { all: true }; const rows = Post.subquery({ attributes: ['userId'] }).union(Task.subquery({ attributes: ['userId'] }), opts); ``` ## Type Alias: SqlValue > **SqlValue** = [`Literal`](../interfaces/Literal.md) \| [`Fn`](../interfaces/Fn.md) \| [`Col`](../interfaces/Col.md) \| [`Cast`](../interfaces/Cast.md) \| [`Excluded`](../interfaces/Excluded.md) \| [`Subquery`](../interfaces/Subquery.md) \| [`Tuple`](../interfaces/Tuple.md) Expressions accepted in place of a value (`Excluded` only inside `onConflict`). ## Type Alias: StandardSchemaIssue > **StandardSchemaIssue** = `Readonly`\<\{ `message`: `string`; `path?`: readonly (`PropertyKey` \| [`StandardSchemaPathSegment`](StandardSchemaPathSegment.md))[]; \}\> One problem reported by a Standard Schema validator. ## Type Alias: StandardSchemaPathSegment > **StandardSchemaPathSegment** = `Readonly`\<\{ `key`: `PropertyKey`; \}\> A path segment of a Standard Schema issue. ## Type Alias: StandardSchemaProps > **StandardSchemaProps** = `Readonly`\<\{ `validate`: (`value`) => [`StandardSchemaResult`](StandardSchemaResult.md) \| `Promise`\<[`StandardSchemaResult`](StandardSchemaResult.md)\>; `vendor`: `string`; `version`: `1`; \}\> The `~standard` property of a Standard Schema v1 object. ## Type Alias: StandardSchemaResult > **StandardSchemaResult** = `Readonly`\<\{ `issues?`: `undefined`; `value`: `unknown`; \}\> \| `Readonly`\<\{ `issues`: readonly [`StandardSchemaIssue`](StandardSchemaIssue.md)[]; \}\> Result of Standard Schema validation. ## Type Alias: StandardSchemaV1 > **StandardSchemaV1** = `Readonly`\<\{ `~standard`: [`StandardSchemaProps`](StandardSchemaProps.md); \}\> Any schema implementing [Standard Schema v1](https://standardschema.dev) — zod, valibot, arktype and others. Used by `validate: { schema }` on attributes and `schema` on models. ## Type Alias: StatementCacheOptions > **StatementCacheOptions** = `Readonly`\<\{ `max?`: `number`; \}\> Named prepared statement cache settings, given as the `statementCache` option of [SequelizeOptions](SequelizeOptions.md). PostgreSQL extension. ### Example ```ts const db = new Sequelize('postgres://user:pass@localhost:5432/app', { statementCache: { max: 50 } }); ``` ## Type Alias: SyncOptions > **SyncOptions** = [`QueryOptionsBase`](QueryOptionsBase.md) & `Readonly`\<\{ `alter?`: `boolean` \| [`AlterOptions`](AlterOptions.md); `force?`: `boolean`; `hooks?`: `boolean`; `match?`: `RegExp`; `schema?`: `string`; \}\> Options of `sync()`: `force`, `alter`, `match`, `schema` plus the common query options. ### Example ```ts const options: SyncOptions = { alter: true, match: /_test$/, schema: 'tenant_1' }; await sequelize.sync(options); ``` ## Type Alias: TableName > **TableName** = `string` \| [`QualifiedTable`](QualifiedTable.md) Table reference accepted by QueryInterface: a name or `{ tableName, schema }`. ## Type Alias: TableOptions > **TableOptions** = `Omit`\<[`InitOptions`](InitOptions.md), `"sequelize"`\> Table options of `@Table`: the `Model.init` options without the `sequelize` instance. ### Example ```ts const options: TableOptions = { tableName: 'users', schema: 'app', paranoid: true, timestamps: true }; ``` ## Type Alias: TableSampleOptions > **TableSampleOptions** = `Readonly`\<\{ `method`: `"BERNOULLI"` \| `"SYSTEM"`; `percent`: `number`; `seed?`: `number`; \}\> `TABLESAMPLE` of a table. PostgreSQL extension. ### Example ```ts const sample: TableSampleOptions = { method: 'BERNOULLI', percent: 10, seed: 42 }; const rows = await Post.findAll({ sample }); ``` ## Type Alias: ThroughOptions > **ThroughOptions** = `Readonly`\<\{ `model`: `string` \| [`ModelStatic`](ModelStatic.md)\<[`AnyModel`](AnyModel.md)\>; `scope?`: `Readonly`\<`Record`\<`string`, `unknown`\>\>; \}\> Junction table of a belongsToMany association given as an object. ### Example ```ts const through: ThroughOptions = { model: 'ProjectTask', scope: { kind: 'member' } }; Project.belongsToMany(Task, { through }); ``` ## Type Alias: TransactionOptions > **TransactionOptions** = `Readonly`\<\{ `deferrable?`: `boolean` \| [`DeferrableValue`](DeferrableValue.md); `isolationLevel?`: [`IsolationLevel`](IsolationLevel.md); `logging?`: [`LoggingFunction`](LoggingFunction.md) \| `false`; `readOnly?`: `boolean`; `retry?`: [`RetryOptions`](RetryOptions.md); `settings?`: `Readonly`\<`Record`\<`string`, `string` \| `number` \| `boolean`\>\>; `transaction?`: [`Transaction`](../classes/Transaction.md) \| `null`; `type?`: *typeof* [`TRANSACTION_TYPES`](../variables/TRANSACTION_TYPES.md)\[keyof *typeof* [`TRANSACTION_TYPES`](../variables/TRANSACTION_TYPES.md)\]; \}\> Options of `sequelize.transaction()`. All fields are optional. ### Example ```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(); ``` ## Type Alias: TriggerArgument > **TriggerArgument** = `string` \| `number` \| `boolean` \| `bigint` Argument passed to the trigger function, rendered as a literal. ## Type Alias: TriggerEvent > **TriggerEvent** = `"insert"` \| `"update"` \| `"delete"` \| `"truncate"` Table event that fires a trigger. ## Type Alias: TriggerTiming > **TriggerTiming** = `"before"` \| `"after"` \| `"instead_of"` \| `"after_constraint"` When a trigger fires relative to the event (Sequelize v6 values). ## Type Alias: TsHeadlineOptions > **TsHeadlineOptions** = `Readonly`\<\{ `config?`: `string`; `options?`: `string`; \}\> Options of [tsHeadline](../functions/tsHeadline.md). PostgreSQL extension. ### Example ```ts const options: TsHeadlineOptions = { config: 'english', options: 'StartSel=, StopSel=' }; ``` ## Type Alias: TsRankOptions > **TsRankOptions** = `Readonly`\<\{ `cd?`: `boolean`; `normalization?`: `number`; `weights?`: readonly \[`number`, `number`, `number`, `number`\]; \}\> Options of [tsRank](../functions/tsRank.md). PostgreSQL extension. ### Example ```ts const options: TsRankOptions = { cd: true, weights: [0.1, 0.2, 0.4, 1], normalization: 1 }; ``` ## Type Alias: TypedQueryResults > **TypedQueryResults** = `object` Result types of `sequelize.query` per query `type`, as the Sequelize v6 typings declare them. ### Example ```ts type Updated = TypedQueryResults['UPDATE']; // [undefined, number] ``` ### Properties #### BULKDELETE > **BULKDELETE**: `number` `QueryTypes.BULKDELETE`: affected rows. *** #### BULKUPDATE > **BULKUPDATE**: `number` `QueryTypes.BULKUPDATE`: affected rows. *** #### DELETE > **DELETE**: `void` `QueryTypes.DELETE`. *** #### DESCRIBE > **DESCRIBE**: `Record`\<`string`, [`ColumnDescription`](ColumnDescription.md)\> `QueryTypes.DESCRIBE`: column descriptions by column name. *** #### INSERT > **INSERT**: \[`number`, `number`\] `QueryTypes.INSERT`. *** #### SHOWTABLES > **SHOWTABLES**: `string`[] `QueryTypes.SHOWTABLES`: table names. *** #### UPDATE > **UPDATE**: \[`undefined`, `number`\] `QueryTypes.UPDATE`. *** #### UPSERT > **UPSERT**: `number` `QueryTypes.UPSERT`. ## Type Alias: UniqueOptions > **UniqueOptions** = `Readonly`\<\{ `msg?`: `string`; `name?`: `string`; `nullsNotDistinct?`: `boolean`; \}\> Named unique constraint of an attribute. Give several attributes the same `name` to form one composite unique key. ### Example ```ts const email: UniqueOptions = { name: 'users_email_unique', msg: 'Email already taken', nullsNotDistinct: true }; ``` ## Type Alias: UpdateOptions\ > **UpdateOptions**\<`T`\> = [`QueryOptionsBase`](QueryOptionsBase.md) & `object` & `object` & [`BulkHookOptions`](BulkHookOptions.md) Options of static `update`. Extends [BulkHookOptions](BulkHookOptions.md). Updates `updatedAt` unless `silent`. ### Type Parameters #### T `T` = [`Values`](Values.md) ### Type Declaration #### fields? > `optional` **fields?**: readonly (keyof `T` & `string`)[] Attributes to update; others are ignored. Mutable so hooks can adjust it, as in v6. #### from? > `optional` **from?**: [`JoinSources`](JoinSources.md) Extra relations (`UPDATE ... FROM`), keyed by alias; reference them with `col('alias.attr')`. PostgreSQL extension. #### paranoid? > `optional` **paranoid?**: `boolean` For paranoid models: `false` also updates soft-deleted rows. ##### Default Value ```ts true ``` #### returning? > `optional` **returning?**: `boolean` Return updated rows as the second element of the result. #### returningOld? > `optional` **returningOld?**: `boolean` With `returning`: expose values before the update as `instance.oldValues`. PostgreSQL extension, needs PostgreSQL 18+. #### silent? > `optional` **silent?**: `boolean` Do not update `updatedAt`. ##### Default Value ```ts false ``` #### validate? > `optional` **validate?**: `boolean` Validate the new values. ##### Default Value ```ts true ``` #### where > **where**: [`WhereOptions`](WhereOptions.md)\<`T`\> Rows to update. ### See [Model.update](../classes/Model.md#update-1) ### Example ```ts const [count] = await User.update( { active: false }, { where: { lastLogin: { [Op.lt]: new Date('2020-01-01') } }, transaction }, ); const opts: UpdateOptions = { where: { done: false }, returning: true }; ``` ## Type Alias: UpdateStatementOptions\ > **UpdateStatementOptions**\<`T`\> = [`WriteStatementOptions`](WriteStatementOptions.md)\<`T`\> & `Readonly`\<\{ `silent?`: `boolean`; \}\> Options of `Model.updateStatement()`. PostgreSQL extension. ### Type Parameters #### T `T` = [`Values`](Values.md) ### Example ```ts const options: UpdateStatementOptions = { where: { id: 1 }, returning: true, silent: true }; ``` ## Type Alias: UpsertOptions\ > **UpsertOptions**\<`T`\> = [`SaveOptions`](SaveOptions.md)\<`T`\> & `object` Options of `upsert`. Extends [SaveOptions](SaveOptions.md). With `onConflict` the result of `upsert` becomes `[instance, created]`. ### Type Parameters #### T `T` = [`Values`](Values.md) ### Type Declaration #### conflictFields? > `optional` **conflictFields?**: readonly `string`[] Conflict target columns. Default: unique key containing a given attribute, else the primary key. #### onConflict? > `optional` **onConflict?**: [`OnConflictOptions`](OnConflictOptions.md)\<`T`\> Advanced `ON CONFLICT` handling; the result becomes `[instance, created]`. PostgreSQL extension. #### overriding? > `optional` **overriding?**: `"system"` \| `"user"` `OVERRIDING SYSTEM VALUE` / `OVERRIDING USER VALUE` for identity columns. ### See [Model.upsert](../classes/Model.md#upsert) ### Example ```ts const [user] = await User.upsert( { email: 'a@example.com', name: 'Ann' }, { conflictFields: ['email'] }, ); ``` ## Type Alias: ValidateOptions > **ValidateOptions** = `Readonly`\<\{ `fields?`: readonly `string`[]; `hooks?`: `boolean`; `skip?`: readonly `string`[]; \}\> Options of `instance.validate()`. Validation throws `ValidationError` when an attribute is invalid. ### See [Model.validate](../classes/Model.md#validate) ### Example ```ts const opts: ValidateOptions = { skip: ['password'], hooks: false }; await user.validate(opts); ``` ## Type Alias: ValidationErrorItemOrigin > **ValidationErrorItemOrigin** = `"CORE"` \| `"DB"` \| `"FUNCTION"` Origin of a validation error item. ## Type Alias: ValidatorSetting > **ValidatorSetting** = `Readonly`\<\{ `args?`: `unknown`; `msg?`: `string`; \}\> `{ args, msg }` form of a built-in validator setting. ## Type Alias: Values > **Values** = `Record`\<`string`, `unknown`\> Plain attribute values of a model. ## Type Alias: ValuesList\ > **ValuesList**\<`V`\> = `object` `{ [Op.values]: [...] }` — `VALUES (...)` list for `Op.any` / `Op.all`. ### Type Parameters #### V `V` ### Properties #### \[values\] > **\[values\]**: readonly `Comparable`\<`V`\>[] Values. ## Type Alias: WhereAttributeHash\ > **WhereAttributeHash**\<`T`\> = `WhereAttributeShape`\<\[`T`\]\> & `object` & [`WhereLogic`](WhereLogic.md)\<`T`\> Where object keyed by attribute names, nested JSON paths (`'meta.a'`), casts (`'id::text'`) or included columns (`'$posts.title$'`). Without a type argument every key is accepted, as in Sequelize v6. ### Type Parameters #### T `T` = `any` ### Example ```ts const any: WhereAttributeHash = { id: 1, 'meta.key': 'a' }; const typed: WhereAttributeHash<{ id: number }> = { id: 1 }; ``` ## Type Alias: WhereAttributeHashValue\ > **WhereAttributeHashValue**\<`V`\> = [`WhereAttributeValue`](WhereAttributeValue.md)\<`V`\> Condition for one attribute in a where object (Sequelize v6 `WhereAttributeHashValue`); the same type as [WhereAttributeValue](WhereAttributeValue.md). ### Type Parameters #### V `V` ### Example ```ts const name: WhereAttributeHashValue = { [Op.iLike]: 'a%' }; const ids: WhereAttributeHashValue = [1, 2, 3]; ``` ## Type Alias: WhereAttributeValue\ > **WhereAttributeValue**\<`V`\> = `Comparable`\<`V`\> \| `undefined` \| `null` \| readonly `Comparable`\<`V`\>[] \| [`WhereOperators`](WhereOperators.md)\<`V`\> \| `V` *extends* `object` ? `Readonly`\<`Record`\<`string`, `unknown`\>\> : `never` Condition for one attribute: a value, a list of values (`IN`), operators, or an expression. ### Type Parameters #### V `V` ## Type Alias: WhereFactory > **WhereFactory** = \{(`attribute`, `logic`): [`Where`](../interfaces/Where.md); (`attribute`, `comparator`, `logic`): [`Where`](../interfaces/Where.md); \} Call signatures of [where](../variables/where.md). ### Call Signature > (`attribute`, `logic`): [`Where`](../interfaces/Where.md) #### Parameters ##### attribute `unknown` Left-hand expression. ##### logic `unknown` Right-hand value or condition object, compared with `=`. #### Returns [`Where`](../interfaces/Where.md) ### Call Signature > (`attribute`, `comparator`, `logic`): [`Where`](../interfaces/Where.md) #### Parameters ##### attribute `unknown` Left-hand expression. ##### comparator `string` \| `symbol` `Op.*` symbol or SQL operator string such as `'>='`. ##### logic `unknown` Right-hand value. #### Returns [`Where`](../interfaces/Where.md) ## Type Alias: WhereLogic\ > **WhereLogic**\<`T`\> = `object` Logical combinators allowed at any level of a where object. ### Type Parameters #### T `T` ### Properties #### \[and\]? > `optional` **\[and\]?**: [`AllowArray`](AllowArray.md)\<[`WhereOptions`](WhereOptions.md)\<`NoInfer`\<`T`\>\>\> Logical AND of nested conditions. *** #### \[not\]? > `optional` **\[not\]?**: [`WhereOptions`](WhereOptions.md)\<`NoInfer`\<`T`\>\> `IS NOT value` for `null`/booleans, otherwise negates a nested condition. *** #### \[or\]? > `optional` **\[or\]?**: [`AllowArray`](AllowArray.md)\<[`WhereOptions`](WhereOptions.md)\<`NoInfer`\<`T`\>\>\> Logical OR of nested conditions. ## Type Alias: WhereMergeStrategy > **WhereMergeStrategy** = `"overwrite"` \| `"and"` `whereMergeStrategy` model option: overwrite same keys (v6 default) or combine with `Op.and`. ## Type Alias: WhereOperators\ > **WhereOperators**\<`V`\> = `object` Operators applicable to an attribute of type `V`. ### Type Parameters #### V `V` = `unknown` ### Properties #### \[adjacent\]? > `optional` **\[adjacent\]?**: `unknown` `-|-` — ranges are adjacent. *** #### \[all\]? > `optional` **\[all\]?**: readonly `Comparable`\<`V`\>[] \| [`Literal`](../interfaces/Literal.md) `ALL (ARRAY[...])`, combined with a comparison operator. *** #### \[and\]? > `optional` **\[and\]?**: [`AllowArray`](AllowArray.md)\<`Comparable`\<`V`\> \| `WhereOperators`\<`V`\>\> Logical AND of nested conditions. *** #### \[any\]? > `optional` **\[any\]?**: readonly `Comparable`\<`V`\>[] \| [`Literal`](../interfaces/Literal.md) `ANY (ARRAY[...])`, combined with a comparison operator. *** #### \[between\]? > `optional` **\[between\]?**: readonly `Comparable`\<`V`\>[] `BETWEEN a AND b`, value is `[a, b]`. *** #### \[col\]? > `optional` **\[col\]?**: `string` Compares with another column, value is a column reference such as `'user.id'`. *** #### \[contained\]? > `optional` **\[contained\]?**: `unknown` `<@` — array, range or jsonb is contained by the value. *** #### \[containedOrEqual\]? > `optional` **\[containedOrEqual\]?**: `unknown` `<<=` — inet/cidr subnet is contained within or equals the value. PostgreSQL extension. *** #### \[contains\]? > `optional` **\[contains\]?**: `unknown` `@>` — array, range or jsonb contains the value. *** #### \[containsOrEqual\]? > `optional` **\[containsOrEqual\]?**: `unknown` `>>=` — inet/cidr subnet contains or equals the value. PostgreSQL extension. *** #### \[endsWith\]? > `optional` **\[endsWith\]?**: `string` \| [`SqlValue`](SqlValue.md) `LIKE '%value'`. *** #### \[eq\]? > `optional` **\[eq\]?**: `Comparable`\<`V`\> \| `null` `= value`; `IS NULL` when the value is `null`. *** #### \[gt\]? > `optional` **\[gt\]?**: `Comparable`\<`V`\> \| [`AnyAll`](AnyAll.md)\<`V`\> `> value`. *** #### \[gte\]? > `optional` **\[gte\]?**: `Comparable`\<`V`\> \| [`AnyAll`](AnyAll.md)\<`V`\> `>= value`. *** #### \[hasAllKeys\]? > `optional` **\[hasAllKeys\]?**: readonly `string`[] jsonb `?&` — all of the keys exist. PostgreSQL extension. *** #### \[hasAnyKeys\]? > `optional` **\[hasAnyKeys\]?**: readonly `string`[] jsonb `?|` — any of the keys exist. PostgreSQL extension. *** #### \[hasKey\]? > `optional` **\[hasKey\]?**: `string` jsonb `?` — top-level key exists. PostgreSQL extension. *** #### \[iLike\]? > `optional` **\[iLike\]?**: `string` \| [`SqlValue`](SqlValue.md) \| [`AnyAll`](AnyAll.md)\<`string`\> `ILIKE pattern`. *** #### \[inOp\]? > `optional` **\[inOp\]?**: readonly `Comparable`\<`V`\>[] \| [`Literal`](../interfaces/Literal.md) \| [`Subquery`](../interfaces/Subquery.md) `IN (...)`; long lists compile to `= ANY($n)`. *** #### \[iRegexp\]? > `optional` **\[iRegexp\]?**: `string` \| [`SqlValue`](SqlValue.md) `~* pattern` (case-insensitive regular expression). *** #### \[is\]? > `optional` **\[is\]?**: `boolean` \| `null` \| [`Literal`](../interfaces/Literal.md) `IS value`: `null`, `true`, `false` or a `literal(...)` written as is, like v6. *** #### \[isDistinctFrom\]? > `optional` **\[isDistinctFrom\]?**: `Comparable`\<`V`\> \| `null` `IS DISTINCT FROM value` (null-safe `<>`). PostgreSQL extension. *** #### \[isNotDistinctFrom\]? > `optional` **\[isNotDistinctFrom\]?**: `Comparable`\<`V`\> \| `null` `IS NOT DISTINCT FROM value` (null-safe `=`). PostgreSQL extension. *** #### \[jsonPathExists\]? > `optional` **\[jsonPathExists\]?**: `string` \| [`SqlValue`](SqlValue.md) jsonb `@?` — the jsonpath returns any item; the value is a jsonpath string. PostgreSQL extension. *** #### \[like\]? > `optional` **\[like\]?**: `string` \| [`SqlValue`](SqlValue.md) \| [`AnyAll`](AnyAll.md)\<`string`\> `LIKE pattern`. *** #### \[lt\]? > `optional` **\[lt\]?**: `Comparable`\<`V`\> \| [`AnyAll`](AnyAll.md)\<`V`\> `< value`. *** #### \[lte\]? > `optional` **\[lte\]?**: `Comparable`\<`V`\> \| [`AnyAll`](AnyAll.md)\<`V`\> `<= value`. *** #### \[match\]? > `optional` **\[match\]?**: [`SqlValue`](SqlValue.md) `@@` — tsvector matches tsquery. *** #### \[ne\]? > `optional` **\[ne\]?**: `Comparable`\<`V`\> \| `null` `<> value`; `IS NOT NULL` when the value is `null`. *** #### \[noExtendLeft\]? > `optional` **\[noExtendLeft\]?**: `unknown` `&>` — range does not extend to the left of the value. *** #### \[noExtendRight\]? > `optional` **\[noExtendRight\]?**: `unknown` `&<` — range does not extend to the right of the value. *** #### \[not\]? > `optional` **\[not\]?**: `Comparable`\<`V`\> \| `boolean` \| `null` \| `WhereOperators`\<`V`\> `IS NOT value` for `null`/booleans, otherwise negates a nested condition. *** #### \[notBetween\]? > `optional` **\[notBetween\]?**: readonly `Comparable`\<`V`\>[] `NOT BETWEEN a AND b`, value is `[a, b]`. *** #### \[notILike\]? > `optional` **\[notILike\]?**: `string` \| [`SqlValue`](SqlValue.md) \| [`AnyAll`](AnyAll.md)\<`string`\> `NOT ILIKE pattern`. *** #### \[notIn\]? > `optional` **\[notIn\]?**: readonly `Comparable`\<`V`\>[] \| [`Literal`](../interfaces/Literal.md) \| [`Subquery`](../interfaces/Subquery.md) `NOT IN (...)`; long lists compile to `<> ALL($n)`. *** #### \[notIRegexp\]? > `optional` **\[notIRegexp\]?**: `string` \| [`SqlValue`](SqlValue.md) `!~* pattern`. *** #### \[notLike\]? > `optional` **\[notLike\]?**: `string` \| [`SqlValue`](SqlValue.md) \| [`AnyAll`](AnyAll.md)\<`string`\> `NOT LIKE pattern`. *** #### \[notRegexp\]? > `optional` **\[notRegexp\]?**: `string` \| [`SqlValue`](SqlValue.md) `!~ pattern`. *** #### \[notSimilarTo\]? > `optional` **\[notSimilarTo\]?**: `string` \| [`SqlValue`](SqlValue.md) `NOT SIMILAR TO pattern`. PostgreSQL extension. *** #### \[or\]? > `optional` **\[or\]?**: [`AllowArray`](AllowArray.md)\<`Comparable`\<`V`\> \| `WhereOperators`\<`V`\>\> Logical OR of nested conditions. *** #### \[overlap\]? > `optional` **\[overlap\]?**: `unknown` `&&` — arrays or ranges overlap. *** #### \[regexp\]? > `optional` **\[regexp\]?**: `string` \| [`SqlValue`](SqlValue.md) `~ pattern` (POSIX regular expression). *** #### \[similarTo\]? > `optional` **\[similarTo\]?**: `string` \| [`SqlValue`](SqlValue.md) `SIMILAR TO pattern` (SQL regular expression). PostgreSQL extension. *** #### \[startsWith\]? > `optional` **\[startsWith\]?**: `string` \| [`SqlValue`](SqlValue.md) `LIKE 'value%'`. *** #### \[strictLeft\]? > `optional` **\[strictLeft\]?**: `unknown` `<<` — range is strictly left of the value. *** #### \[strictRight\]? > `optional` **\[strictRight\]?**: `unknown` `>>` — range is strictly right of the value. *** #### \[substring\]? > `optional` **\[substring\]?**: `string` \| [`SqlValue`](SqlValue.md) `LIKE '%value%'`. *** #### \[trigramHasSimilarStrictWord\]? > `optional` **\[trigramHasSimilarStrictWord\]?**: `string` \| [`SqlValue`](SqlValue.md) `%>>` — `pg_trgm`: the column has a strictly similar word of the value. PostgreSQL extension. *** #### \[trigramHasSimilarWord\]? > `optional` **\[trigramHasSimilarWord\]?**: `string` \| [`SqlValue`](SqlValue.md) `%>` — `pg_trgm`: the column has a part similar to the value. PostgreSQL extension. *** #### \[trigramSimilar\]? > `optional` **\[trigramSimilar\]?**: `string` \| [`SqlValue`](SqlValue.md) `%` — `pg_trgm` trigram similarity above `pg_trgm.similarity_threshold`. PostgreSQL extension. *** #### \[trigramStrictWordSimilar\]? > `optional` **\[trigramStrictWordSimilar\]?**: `string` \| [`SqlValue`](SqlValue.md) `<<%` — `pg_trgm`: the column is strictly similar to a word of the value. PostgreSQL extension. *** #### \[trigramWordSimilar\]? > `optional` **\[trigramWordSimilar\]?**: `string` \| [`SqlValue`](SqlValue.md) `<%` — `pg_trgm`: the column is similar to a part of the value. PostgreSQL extension. ## Type Alias: WhereOptions\ > **WhereOptions**\<`T`\> = [`WhereAttributeHash`](WhereAttributeHash.md)\<`NoInfer`\<`T`\>\> \| `RequiredLogic`\<`T`\> \| readonly `WhereOptions`\<`T`\>[] \| [`Where`](../interfaces/Where.md) \| [`Literal`](../interfaces/Literal.md) \| [`Fn`](../interfaces/Fn.md) \| [`Json`](../interfaces/Json.md) \| [`Exists`](../interfaces/Exists.md) `where` option of queries (Sequelize v6 `WhereOptions`). A condition is an object keyed by attribute (equality, `IN` for arrays, or operators), a list of conditions (`OR`), or an expression (`where()`, `literal()`, `fn()`, ...). Values are always bound parameters. ### Type Parameters #### T `T` = `Record`\<`string`, `unknown`\> ### See [Op](../variables/Op.md) ### Example ```ts const w: WhereOptions = { active: true, age: { [Op.between]: [18, 65] }, role: ['admin', 'editor'], [Op.or]: [{ name: { [Op.iLike]: 'a%' } }, { email: { [Op.endsWith]: '@example.com' } }], '$posts.title$': 'Hello', }; const rows = await User.findAll({ where: w, include: [Post] }); ``` ## Type Alias: WindowOptions > **WindowOptions** = `Readonly`\<\{ `orderBy?`: readonly `unknown`[]; `partitionBy?`: readonly `unknown`[]; \}\> Window definition of [over](../functions/over.md). PostgreSQL extension. ### Example ```ts const window: WindowOptions = { partitionBy: ['userId'], orderBy: [['createdAt', 'DESC']] }; ``` ## Type Alias: WithOption > **WithOption** = `Readonly`\<`Record`\<`string`, [`Subquery`](../interfaces/Subquery.md) \| [`WriteStatement`](../interfaces/WriteStatement.md) \| [`CteDefinition`](CteDefinition.md)\>\> `with` option: CTEs by name. ## Type Alias: WriteStatementOptions\ > **WriteStatementOptions**\<`T`\> = `Readonly`\<\{ `returning?`: `boolean`; `where?`: [`WhereOptions`](WhereOptions.md)\<`T`\>; \}\> Options of `Model.deleteStatement()` and `Model.updateStatement()`. ### Type Parameters #### T `T` = [`Values`](Values.md) ### Example ```ts const options: WriteStatementOptions = { where: { done: true }, returning: true }; ``` ## Variable: ARRAY > `const` **ARRAY**: \<`T`\>(`subtype`) => `ArrayType` & [`ArrayDataType`](../postgrelize/namespaces/DataTypes/interfaces/ArrayDataType.md)\<`Element`\<`T`\>\> = `DataTypes.ARRAY` Alias of `DataTypes.ARRAY` (Sequelize v6 module export). ### Type Parameters #### T `T` *extends* [`DataTypeInput`](../type-aliases/DataTypeInput.md) ### Parameters #### subtype `T` ### Returns `ArrayType` & [`ArrayDataType`](../postgrelize/namespaces/DataTypes/interfaces/ArrayDataType.md)\<`Element`\<`T`\>\> ## Variable: AfterBulkCreate > `const` **AfterBulkCreate**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as an `afterBulkCreate` hook of the model (like `Model.afterBulkCreate`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @AfterBulkCreate static async onAfterBulkCreate(users: User[], options: unknown) {} } ``` ## Variable: AfterBulkDestroy > `const` **AfterBulkDestroy**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as an `afterBulkDestroy` hook of the model (like `Model.afterBulkDestroy`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @AfterBulkDestroy static async onAfterBulkDestroy(options: unknown) {} } ``` ## Variable: AfterBulkRestore > `const` **AfterBulkRestore**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as an `afterBulkRestore` hook of the model (like `Model.afterBulkRestore`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @AfterBulkRestore static async onAfterBulkRestore(options: unknown) {} } ``` ## Variable: AfterBulkUpdate > `const` **AfterBulkUpdate**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as an `afterBulkUpdate` hook of the model (like `Model.afterBulkUpdate`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @AfterBulkUpdate static async onAfterBulkUpdate(options: unknown) {} } ``` ## Variable: AfterCreate > `const` **AfterCreate**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as an `afterCreate` hook of the model (like `Model.afterCreate`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @AfterCreate static async onAfterCreate(user: User, options: unknown) {} } ``` ## Variable: AfterDestroy > `const` **AfterDestroy**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as an `afterDestroy` hook of the model (like `Model.afterDestroy`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @AfterDestroy static async onAfterDestroy(user: User, options: unknown) {} } ``` ## Variable: AfterFind > `const` **AfterFind**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as an `afterFind` hook of the model (like `Model.afterFind`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @AfterFind static async onAfterFind(result: unknown, options: unknown) {} } ``` ## Variable: AfterRestore > `const` **AfterRestore**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as an `afterRestore` hook of the model (like `Model.afterRestore`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @AfterRestore static async onAfterRestore(user: User, options: unknown) {} } ``` ## Variable: AfterSave > `const` **AfterSave**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as an `afterSave` hook of the model (like `Model.afterSave`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @AfterSave static async onAfterSave(user: User, options: unknown) {} } ``` ## Variable: AfterUpdate > `const` **AfterUpdate**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as an `afterUpdate` hook of the model (like `Model.afterUpdate`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @AfterUpdate static async onAfterUpdate(user: User, options: unknown) {} } ``` ## Variable: AfterUpsert > `const` **AfterUpsert**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as an `afterUpsert` hook of the model (like `Model.afterUpsert`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @AfterUpsert static async onAfterUpsert(result: unknown, options: unknown) {} } ``` ## Variable: AfterValidate > `const` **AfterValidate**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as an `afterValidate` hook of the model (like `Model.afterValidate`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @AfterValidate static async onAfterValidate(user: User, options: unknown) {} } ``` ## Variable: AllowNull > `const` **AllowNull**: [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) & ((`argument?`) => [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md)) Sets `allowNull`. Usable bare (`@AllowNull`, meaning `true`) or called. ### Param **allowNull** Whether `NULL` is allowed. ### Default Value ```ts true ``` ### Returns An attribute decorator. ### Example ```ts class User extends Model { @AllowNull(false) @Column(DataTypes.TEXT) name!: string; } ``` ## Variable: AutoIncrement > `const` **AutoIncrement**: [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) Generates the attribute from a sequence (`autoIncrement: true`). ### Example ```ts class User extends Model { @PrimaryKey @AutoIncrement @Column(DataTypes.INTEGER) id!: number; } ``` ## Variable: BIGINT > `const` **BIGINT**: `CallableInteger`\<[`BigIntDataType`](../postgrelize/namespaces/DataTypes/interfaces/BigIntDataType.md)\> = `DataTypes.BIGINT` Alias of `DataTypes.BIGINT` (Sequelize v6 module export). ## Variable: BLOB > `const` **BLOB**: `Callable`\<`BlobType`, \[`size?`: `"tiny"` \| `"medium"` \| `"long"`\], `BlobType`\> = `DataTypes.BLOB` Alias of `DataTypes.BLOB` (Sequelize v6 module export). ## Variable: BOOLEAN > `const` **BOOLEAN**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.BOOLEAN` Alias of `DataTypes.BOOLEAN` (Sequelize v6 module export). ## Variable: BeforeBulkCreate > `const` **BeforeBulkCreate**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as a `beforeBulkCreate` hook of the model (like `Model.beforeBulkCreate`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @BeforeBulkCreate static async onBeforeBulkCreate(users: User[], options: unknown) {} } ``` ## Variable: BeforeBulkDestroy > `const` **BeforeBulkDestroy**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as a `beforeBulkDestroy` hook of the model (like `Model.beforeBulkDestroy`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @BeforeBulkDestroy static async onBeforeBulkDestroy(options: unknown) {} } ``` ## Variable: BeforeBulkRestore > `const` **BeforeBulkRestore**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as a `beforeBulkRestore` hook of the model (like `Model.beforeBulkRestore`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @BeforeBulkRestore static async onBeforeBulkRestore(options: unknown) {} } ``` ## Variable: BeforeBulkUpdate > `const` **BeforeBulkUpdate**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as a `beforeBulkUpdate` hook of the model (like `Model.beforeBulkUpdate`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @BeforeBulkUpdate static async onBeforeBulkUpdate(options: unknown) {} } ``` ## Variable: BeforeCount > `const` **BeforeCount**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as a `beforeCount` hook of the model (like `Model.beforeCount`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @BeforeCount static async onBeforeCount(options: unknown) {} } ``` ## Variable: BeforeCreate > `const` **BeforeCreate**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as a `beforeCreate` hook of the model (like `Model.beforeCreate`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @BeforeCreate static async onBeforeCreate(user: User, options: unknown) {} } ``` ## Variable: BeforeDestroy > `const` **BeforeDestroy**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as a `beforeDestroy` hook of the model (like `Model.beforeDestroy`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @BeforeDestroy static async onBeforeDestroy(user: User, options: unknown) {} } ``` ## Variable: BeforeFind > `const` **BeforeFind**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as a `beforeFind` hook of the model (like `Model.beforeFind`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @BeforeFind static async onBeforeFind(options: unknown) {} } ``` ## Variable: BeforeFindAfterExpandIncludeAll > `const` **BeforeFindAfterExpandIncludeAll**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as a `beforeFindAfterExpandIncludeAll` hook of the model (like `Model.beforeFindAfterExpandIncludeAll`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @BeforeFindAfterExpandIncludeAll static async onBeforeFindAfterExpandIncludeAll(options: unknown) {} } ``` ## Variable: BeforeFindAfterOptions > `const` **BeforeFindAfterOptions**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as a `beforeFindAfterOptions` hook of the model (like `Model.beforeFindAfterOptions`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @BeforeFindAfterOptions static async onBeforeFindAfterOptions(options: unknown) {} } ``` ## Variable: BeforeRestore > `const` **BeforeRestore**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as a `beforeRestore` hook of the model (like `Model.beforeRestore`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @BeforeRestore static async onBeforeRestore(user: User, options: unknown) {} } ``` ## Variable: BeforeSave > `const` **BeforeSave**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as a `beforeSave` hook of the model (like `Model.beforeSave`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @BeforeSave static async onBeforeSave(user: User, options: unknown) {} } ``` ## Variable: BeforeUpdate > `const` **BeforeUpdate**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as a `beforeUpdate` hook of the model (like `Model.beforeUpdate`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @BeforeUpdate static async onBeforeUpdate(user: User, options: unknown) {} } ``` ## Variable: BeforeUpsert > `const` **BeforeUpsert**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as a `beforeUpsert` hook of the model (like `Model.beforeUpsert`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @BeforeUpsert static async onBeforeUpsert(values: unknown, options: unknown) {} } ``` ## Variable: BeforeValidate > `const` **BeforeValidate**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as a `beforeValidate` hook of the model (like `Model.beforeValidate`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @BeforeValidate static async onBeforeValidate(user: User, options: unknown) {} } ``` ## Variable: BelongsTo > **BelongsTo**: (`target`, `options?`) => [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) Adds a `belongsTo` association; the foreign key is on this model, marked with `@ForeignKey` for the target unless `options.foreignKey` is given. The property name is the alias (`as`). ### Parameters #### target [`ModelGetter`](../type-aliases/ModelGetter.md) Function returning the associated model. #### options? `Readonly`\<\{ `as?`: `string` \| `Readonly`\<\{ `plural`: `string`; `singular`: `string`; \}\>; `constraints?`: `boolean`; `foreignKey?`: `string` \| `Readonly`\<\{ `allowNull?`: `boolean`; `field?`: `string`; `name?`: `string`; \}\>; `hooks?`: `boolean`; `onDelete?`: `string`; `onUpdate?`: `string`; `scope?`: `Readonly`\<`Record`\<`string`, `unknown`\>\>; `sourceKey?`: `string`; `targetKey?`: `string`; \}\> Association options (`foreignKey`, `targetKey`, `onDelete`, …). ### Returns [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) An attribute decorator. ### Example ```ts class Post extends Model { @ForeignKey(() => User) @Column(DataTypes.INTEGER) userId!: number; @BelongsTo(() => User) user!: User; } ``` ## Variable: BelongsToMany > **BelongsToMany**: (`target`, `through`, `options?`) => [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) Adds a `belongsToMany` association through a junction model. The junction model's `@ForeignKey` attributes give `foreignKey` (to this model) and `otherKey` (to the target) unless `options` sets them. ### Parameters #### target [`ModelGetter`](../type-aliases/ModelGetter.md) Function returning the associated model. #### through `NonNullable`\<`string` \| `Readonly`\<\{ `model`: `string` \| [`ModelStatic`](../type-aliases/ModelStatic.md)\<[`AnyModel`](../type-aliases/AnyModel.md)\>; `scope?`: `Readonly`\<`Record`\<`string`, `unknown`\>\>; \}\> \| [`ModelGetter`](../type-aliases/ModelGetter.md) \| `undefined`\> Junction table name, function returning the junction model, or `{ model, scope }`. #### options? `Omit`\<[`BelongsToManyOptions`](../type-aliases/BelongsToManyOptions.md), `"through"`\> Association options (`foreignKey`, `otherKey`, …). ### Returns [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) An attribute decorator. ### Example ```ts class Post extends Model { @BelongsToMany(() => Tag, 'post_tags') tags!: Tag[]; } ``` ## Variable: CHAR > `const` **CHAR**: `Callable`\<`CharType`, \[`length?`: `number`\], `CharType`\> = `DataTypes.CHAR` Alias of `DataTypes.CHAR` (Sequelize v6 module export). ## Variable: CIDR > `const` **CIDR**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.CIDR` Alias of `DataTypes.CIDR` (Sequelize v6 module export). ## Variable: CITEXT > `const` **CITEXT**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.CITEXT` Alias of `DataTypes.CITEXT` (Sequelize v6 module export). ## Variable: CreatedAt > `const` **CreatedAt**: [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) Names the attribute that holds the creation time (`createdAt: ''`). ### Example ```ts class User extends Model { @CreatedAt creationDate!: Date; } ``` ## Variable: DATE > `const` **DATE**: `Callable`\<`DateType`, \[`fsp?`: `number`\], `DateType`\> = `DataTypes.DATE` Alias of `DataTypes.DATE` (Sequelize v6 module export). ## Variable: DATEONLY > `const` **DATEONLY**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.DATEONLY` Alias of `DataTypes.DATEONLY` (Sequelize v6 module export). ## Variable: DECIMAL > `const` **DECIMAL**: `Callable`\<`DecimalType`, \[`digits?`: `number`, `scale?`: `number`\], `DecimalType`\> = `DataTypes.DECIMAL` Alias of `DataTypes.DECIMAL` (Sequelize v6 module export). ## Variable: DOUBLE > `const` **DOUBLE**: `Callable`\<`ScalarType`, \[`length?`: `number`, `decimals?`: `number`\], [`DoubleDataType`](../postgrelize/namespaces/DataTypes/interfaces/DoubleDataType.md)\> = `DataTypes.DOUBLE` Alias of `DataTypes.DOUBLE` (Sequelize v6 module export). ## Variable: DataTypes > `const` **DataTypes**: `object` Column types, API-compatible with Sequelize v6 `DataTypes` for PostgreSQL. `BIGINT` and `DECIMAL` values are returned as strings (like Sequelize v6) to avoid precision loss. ### Type Declaration #### ARRAY > `readonly` **ARRAY**: \<`T`\>(`subtype`) => `ArrayType` & [`ArrayDataType`](../postgrelize/namespaces/DataTypes/interfaces/ArrayDataType.md)\<`Element`\<`T`\>\> `type[]`, e.g. `DataTypes.ARRAY(DataTypes.TEXT)`. ##### Type Parameters ###### T `T` *extends* [`DataTypeInput`](../type-aliases/DataTypeInput.md) ##### Parameters ###### subtype `T` ##### Returns `ArrayType` & [`ArrayDataType`](../postgrelize/namespaces/DataTypes/interfaces/ArrayDataType.md)\<`Element`\<`T`\>\> #### BIGINT > `readonly` **BIGINT**: `CallableInteger`\<[`BigIntDataType`](../postgrelize/namespaces/DataTypes/interfaces/BigIntDataType.md)\> `BIGINT`; values are returned as strings. #### BIT > `readonly` **BIT**: `Callable`\<`BitType`, \[`length?`: `number`\], `BitType`\> `BIT(length)`, default length 1; values are strings of `0` and `1`. PostgreSQL extension. #### BLOB > `readonly` **BLOB**: `Callable`\<`BlobType`, \[`size?`: `"tiny"` \| `"medium"` \| `"long"`\], `BlobType`\> `BYTEA`; values are `Buffer`s. #### BOOLEAN > `readonly` **BOOLEAN**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `BOOLEAN`. #### BOX > `readonly` **BOX**: `GeometricType` `BOX`; values are `[corner, corner]` points (the server returns the upper right first). PostgreSQL extension. #### CHAR > `readonly` **CHAR**: `Callable`\<`CharType`, \[`length?`: `number`\], `CharType`\> `CHAR(length)`, default length 255. #### CIDR > `readonly` **CIDR**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `CIDR`. #### CIRCLE > `readonly` **CIRCLE**: `GeometricType` `CIRCLE`; values are `{ x, y, radius }`. PostgreSQL extension. #### CITEXT > `readonly` **CITEXT**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `CITEXT` (case-insensitive text, requires the `citext` extension). #### COMPOSITE > `readonly` **COMPOSITE**: (`name`, `fields`) => `CompositeType` Composite type, e.g. `DataTypes.COMPOSITE('address', { street: DataTypes.TEXT, zip: DataTypes.INTEGER })`; values are objects keyed by field name. Create the type first with `createSql()`. PostgreSQL extension. ##### Parameters ###### name `string` ###### fields `Readonly`\<`Record`\<`string`, [`DataTypeInput`](../type-aliases/DataTypeInput.md)\>\> ##### Returns `CompositeType` #### DATE > `readonly` **DATE**: `Callable`\<`DateType`, \[`fsp?`: `number`\], `DateType`\> `TIMESTAMP WITH TIME ZONE`; values are `Date` objects. #### DATEONLY > `readonly` **DATEONLY**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `DATE`; values are `'YYYY-MM-DD'` strings. #### DECIMAL > `readonly` **DECIMAL**: `Callable`\<`DecimalType`, \[`digits?`: `number`, `scale?`: `number`\], `DecimalType`\> `DECIMAL(precision, scale)`; values are returned as strings. #### DOUBLE > `readonly` **DOUBLE**: `Callable`\<`ScalarType`, \[`length?`: `number`, `decimals?`: `number`\], [`DoubleDataType`](../postgrelize/namespaces/DataTypes/interfaces/DoubleDataType.md)\> `DOUBLE PRECISION`. #### DOUBLE PRECISION > `readonly` **DOUBLE PRECISION**: `Callable`\<`ScalarType`, \[`length?`: `number`, `decimals?`: `number`\], [`DoubleDataType`](../postgrelize/namespaces/DataTypes/interfaces/DoubleDataType.md)\> `DOUBLE PRECISION` (v6 alias of `DOUBLE`). #### ENUM > `readonly` **ENUM**: \<`T`\>(...`args`) => `EnumType` & [`EnumDataType`](../postgrelize/namespaces/DataTypes/interfaces/EnumDataType.md)\<`T`\> Enumerated values: `DataTypes.ENUM('a', 'b')` or `DataTypes.ENUM({ values: ['a', 'b'] })`. ##### Type Parameters ###### T `T` *extends* `string` = `string` ##### Parameters ###### args ...readonly (`T` \| readonly `T`[] \| `Readonly`\<\{ `values`: readonly `T`[]; \}\>)[] ##### Returns `EnumType` & [`EnumDataType`](../postgrelize/namespaces/DataTypes/interfaces/EnumDataType.md)\<`T`\> #### FLOAT > `readonly` **FLOAT**: `Callable`\<`FloatType`, \[`digits?`: `number`\], `FloatType`\> `FLOAT(precision)`. #### GEOGRAPHY > `readonly` **GEOGRAPHY**: `Callable`\<`SpatialType`, \[`geographyType?`: `string`, `srid?`: `number`\], `SpatialType`\> PostGIS `GEOGRAPHY(type, srid)`. #### GEOMETRY > `readonly` **GEOMETRY**: `Callable`\<`SpatialType`, \[`geometryType?`: `string`, `srid?`: `number`\], `SpatialType`\> PostGIS `GEOMETRY(type, srid)`. #### HSTORE > `readonly` **HSTORE**: `Callable`\<`HstoreType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `HSTORE` (requires the `hstore` extension); values are objects of string (or `null`) values, like Sequelize v6. #### INET > `readonly` **INET**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `INET`. #### INTEGER > `readonly` **INTEGER**: `CallableInteger`\<[`IntegerDataType`](../postgrelize/namespaces/DataTypes/interfaces/IntegerDataType.md)\> `INTEGER`. #### INTERVAL > `readonly` **INTERVAL**: `ScalarType` `INTERVAL`; values are PostgreSQL interval strings (e.g. `'1 day 02:00:00'`). PostgreSQL extension. #### JSON > `readonly` **JSON**: `Callable`\<`JsonType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `JSON`. #### JSONB > `readonly` **JSONB**: `Callable`\<`JsonType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `JSONB`. #### LINE > `readonly` **LINE**: `GeometricType` `LINE` (`a·x + b·y + c = 0`); values are `{ a, b, c }`. PostgreSQL extension. #### LSEG > `readonly` **LSEG**: `GeometricType` `LSEG` line segment; values are `[start, end]` points. PostgreSQL extension. #### LTREE > `readonly` **LTREE**: `ScalarType` `LTREE` label path (requires the `ltree` extension); values are strings like `'Top.Science'`. PostgreSQL extension. #### MACADDR > `readonly` **MACADDR**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `MACADDR`. #### MACADDR8 > `readonly` **MACADDR8**: `ScalarType` `MACADDR8` (EUI-64 address). PostgreSQL extension. #### MEDIUMINT > `readonly` **MEDIUMINT**: `CallableInteger`\<[`MediumIntegerDataType`](../postgrelize/namespaces/DataTypes/interfaces/MediumIntegerDataType.md)\> Mapped to `INTEGER` (PostgreSQL has no `MEDIUMINT`). #### MONEY > `readonly` **MONEY**: `ScalarType` `MONEY`; values are strings formatted by the server's `lc_monetary` (e.g. `'$12.50'`); numbers are accepted on write. PostgreSQL extension. #### MULTIRANGE > `readonly` **MULTIRANGE**: `Callable`\<`MultirangeType`, \[`subtype`: [`DataTypeInput`](../type-aliases/DataTypeInput.md)\], `MultirangeType`\> Multirange type (PostgreSQL 14+), e.g. `DataTypes.MULTIRANGE(DataTypes.INTEGER)` → `INT4MULTIRANGE`; values are arrays of `[lower, upper]` ranges. PostgreSQL extension. #### NOW > `readonly` **NOW**: [`DefaultValueGenerator`](../interfaces/DefaultValueGenerator.md) Default value: current timestamp. #### NUMBER > `readonly` **NUMBER**: `Callable`\<`DecimalType`, \[`digits?`: `number`, `scale?`: `number`\], `DecimalType`\> Alias of `DECIMAL`. #### NUMERIC > `readonly` **NUMERIC**: `Callable`\<`DecimalType`, \[`digits?`: `number`, `scale?`: `number`\], `DecimalType`\> Alias of `DECIMAL` (v6 `NUMERIC`). #### PATH > `readonly` **PATH**: `GeometricType` `PATH`; values are `{ points, closed }`. PostgreSQL extension. #### POINT > `readonly` **POINT**: `GeometricType` `POINT`; values are `{ x, y }`. PostgreSQL extension. #### POLYGON > `readonly` **POLYGON**: `GeometricType` `POLYGON`; values are arrays of `{ x, y }` points. PostgreSQL extension. #### RANGE > `readonly` **RANGE**: `RangeFactory` Range type, e.g. `DataTypes.RANGE(DataTypes.INTEGER)` → `INT4RANGE`. #### REAL > `readonly` **REAL**: `Callable`\<`ScalarType`, \[`length?`: `number`, `decimals?`: `number`\], [`RealDataType`](../postgrelize/namespaces/DataTypes/interfaces/RealDataType.md)\> `REAL`. #### SMALLINT > `readonly` **SMALLINT**: `CallableInteger`\<[`SmallIntegerDataType`](../postgrelize/namespaces/DataTypes/interfaces/SmallIntegerDataType.md)\> `SMALLINT`. #### STRING > `readonly` **STRING**: `Callable`\<`StringType`, \[`length?`: `number`\], `StringType`\> `VARCHAR(length)`, default length 255. #### TEXT > `readonly` **TEXT**: `Callable`\<`TextType`, \[`size?`: `"tiny"` \| `"medium"` \| `"long"`\], `TextType`\> `TEXT`. The size argument is accepted for compatibility and ignored. #### TIME > `readonly` **TIME**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `TIME`. #### TIMESTAMP > `readonly` **TIMESTAMP**: `Callable`\<`TimestampType`, \[`fsp?`: `number`\], `TimestampType`\> `TIMESTAMP WITHOUT TIME ZONE`; values are `Date` objects whose local wall-clock time is the stored time. PostgreSQL extension. #### TINYINT > `readonly` **TINYINT**: `CallableInteger`\<[`TinyIntegerDataType`](../postgrelize/namespaces/DataTypes/interfaces/TinyIntegerDataType.md)\> Mapped to `SMALLINT` (PostgreSQL has no `TINYINT`). #### TSQUERY > `readonly` **TSQUERY**: `ScalarType` `TSQUERY`; values are full-text query strings. PostgreSQL extension. #### TSVECTOR > `readonly` **TSVECTOR**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `TSVECTOR`. #### UUID > `readonly` **UUID**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> `UUID`. #### UUIDV4 > `readonly` **UUIDV4**: [`DefaultValueGenerator`](../interfaces/DefaultValueGenerator.md) Default value: random UUID v4 generated on the client. #### VARBIT > `readonly` **VARBIT**: `Callable`\<`BitType`, \[`length?`: `number`\], `BitType`\> `BIT VARYING(length)`, unlimited without a length; values are strings of `0` and `1`. PostgreSQL extension. #### VIRTUAL > `readonly` **VIRTUAL**: `VirtualFactory` Attribute that is not stored in the database (computed by getters/setters). #### XML > `readonly` **XML**: `ScalarType` `XML`; values are XML text. PostgreSQL extension. ### Example ```ts User.init({ id: { type: DataTypes.BIGINT, primaryKey: true }, name: DataTypes.STRING(64) }, { sequelize }); ``` ## Variable: Deferrable > `const` **Deferrable**: `object` Deferrable constraint modes (Sequelize v6 `Deferrable`). ### Type Declaration #### INITIALLY\_DEFERRED > `readonly` **INITIALLY\_DEFERRED**: `Readonly`\<`Readonly`\<\{ `sql`: `string`; \}\>\> `DEFERRABLE INITIALLY DEFERRED`. #### INITIALLY\_IMMEDIATE > `readonly` **INITIALLY\_IMMEDIATE**: `Readonly`\<`Readonly`\<\{ `sql`: `string`; \}\>\> `DEFERRABLE INITIALLY IMMEDIATE`. #### NOT > `readonly` **NOT**: `Readonly`\<`Readonly`\<\{ `sql`: `string`; \}\>\> `NOT DEFERRABLE`. #### SET\_DEFERRED > `readonly` **SET\_DEFERRED**: `ConstraintModeSetter` `SET CONSTRAINTS ... DEFERRED`: for the `deferrable` option of `sequelize.transaction()`, defers the given constraints (all of them when used bare or called without names) for the rest of the transaction. #### SET\_IMMEDIATE > `readonly` **SET\_IMMEDIATE**: `ConstraintModeSetter` `SET CONSTRAINTS ... IMMEDIATE`: the counterpart of `SET_DEFERRED`. ### Example ```ts await queryInterface.addColumn('posts', 'userId', { type: DataTypes.INTEGER, references: { model: 'Users', key: 'id', deferrable: Deferrable.INITIALLY_DEFERRED }, }); ``` ## Variable: DeletedAt > `const` **DeletedAt**: [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) Names the attribute that holds the deletion time (`deletedAt: ''`) and makes the model paranoid unless `@Table` sets `paranoid` explicitly. ### Example ```ts class User extends Model { @DeletedAt removedAt!: Date | null; } ``` ## Variable: ENUM > `const` **ENUM**: \<`T`\>(...`args`) => `EnumType` & [`EnumDataType`](../postgrelize/namespaces/DataTypes/interfaces/EnumDataType.md)\<`T`\> = `DataTypes.ENUM` Alias of `DataTypes.ENUM` (Sequelize v6 module export). ### Type Parameters #### T `T` *extends* `string` = `string` ### Parameters #### args ...readonly (`T` \| readonly `T`[] \| `Readonly`\<\{ `values`: readonly `T`[]; \}\>)[] ### Returns `EnumType` & [`EnumDataType`](../postgrelize/namespaces/DataTypes/interfaces/EnumDataType.md)\<`T`\> ## Variable: FLOAT > `const` **FLOAT**: `Callable`\<`FloatType`, \[`digits?`: `number`\], `FloatType`\> = `DataTypes.FLOAT` Alias of `DataTypes.FLOAT` (Sequelize v6 module export). ## Variable: ForeignKey > **ForeignKey**: (`target`) => [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) Marks the attribute as a foreign key to a model (also the v6 type `ForeignKey` of the same name). Association decorators use it to find the foreign key; it does not change the column definition. ### Parameters #### target [`ModelGetter`](../type-aliases/ModelGetter.md) Function returning the referenced model. ### Returns [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) An attribute decorator. ### Example ```ts class Post extends Model { @ForeignKey(() => User) @Column(DataTypes.INTEGER) userId!: number; } ``` ## Variable: GEOGRAPHY > `const` **GEOGRAPHY**: `Callable`\<`SpatialType`, \[`geographyType?`: `string`, `srid?`: `number`\], `SpatialType`\> = `DataTypes.GEOGRAPHY` Alias of `DataTypes.GEOGRAPHY` (Sequelize v6 module export). ## Variable: GEOMETRY > `const` **GEOMETRY**: `Callable`\<`SpatialType`, \[`geometryType?`: `string`, `srid?`: `number`\], `SpatialType`\> = `DataTypes.GEOMETRY` Alias of `DataTypes.GEOMETRY` (Sequelize v6 module export). ## Variable: HOOK\_TYPES > `const` **HOOK\_TYPES**: readonly \[`"beforeValidate"`, `"afterValidate"`, `"validationFailed"`, `"beforeCreate"`, `"afterCreate"`, `"beforeUpdate"`, `"afterUpdate"`, `"beforeSave"`, `"afterSave"`, `"beforeDestroy"`, `"afterDestroy"`, `"beforeRestore"`, `"afterRestore"`, `"beforeUpsert"`, `"afterUpsert"`, `"beforeBulkCreate"`, `"afterBulkCreate"`, `"beforeBulkUpdate"`, `"afterBulkUpdate"`, `"beforeBulkDestroy"`, `"afterBulkDestroy"`, `"beforeBulkRestore"`, `"afterBulkRestore"`, `"beforeFind"`, `"beforeFindAfterExpandIncludeAll"`, `"beforeFindAfterOptions"`, `"afterFind"`, `"beforeCount"`, `"beforeConnect"`, `"afterConnect"`, `"beforeDisconnect"`, `"afterDisconnect"`, `"beforePoolAcquire"`, `"afterPoolAcquire"`, `"beforeQuery"`, `"afterQuery"`, `"beforeSync"`, `"afterSync"`, `"beforeBulkSync"`, `"afterBulkSync"`, `"beforeDefine"`, `"afterDefine"`, `"beforeInit"`, `"afterInit"`, `"beforeAssociate"`, `"afterAssociate"`\] Hook names accepted by `addHook` (Sequelize v6). Model lifecycle hooks, `beforeConnect`, `afterConnect`, the sync hooks (`beforeBulkSync`, `afterBulkSync`, `beforeSync`, `afterSync`), `beforeDefine` / `afterDefine` and the static `beforeInit` / `afterInit` run; the other connection hooks and query / association hooks are accepted and not run yet. ## Variable: HSTORE > `const` **HSTORE**: `Callable`\<`HstoreType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.HSTORE` Alias of `DataTypes.HSTORE` (Sequelize v6 module export). ## Variable: HasMany > **HasMany**: (`target`, `options?`) => [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) Adds a `hasMany` association; the foreign key is on the target. The property name is the alias (`as`). ### Parameters #### target [`ModelGetter`](../type-aliases/ModelGetter.md) Function returning the associated model. #### options? `Readonly`\<\{ `as?`: `string` \| `Readonly`\<\{ `plural`: `string`; `singular`: `string`; \}\>; `constraints?`: `boolean`; `foreignKey?`: `string` \| `Readonly`\<\{ `allowNull?`: `boolean`; `field?`: `string`; `name?`: `string`; \}\>; `hooks?`: `boolean`; `onDelete?`: `string`; `onUpdate?`: `string`; `scope?`: `Readonly`\<`Record`\<`string`, `unknown`\>\>; `sourceKey?`: `string`; `targetKey?`: `string`; \}\> Association options (`foreignKey`, `onDelete`, …). ### Returns [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) An attribute decorator. ### Example ```ts class User extends Model { @HasMany(() => Post) posts!: Post[]; } ``` ## Variable: HasOne > **HasOne**: (`target`, `options?`) => [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) Adds a `hasOne` association; the foreign key is on the target. The property name is the alias (`as`). The foreign key is the attribute of the target marked with `@ForeignKey` for this model, unless `options.foreignKey` is given. ### Parameters #### target [`ModelGetter`](../type-aliases/ModelGetter.md) Function returning the associated model. #### options? `Readonly`\<\{ `as?`: `string` \| `Readonly`\<\{ `plural`: `string`; `singular`: `string`; \}\>; `constraints?`: `boolean`; `foreignKey?`: `string` \| `Readonly`\<\{ `allowNull?`: `boolean`; `field?`: `string`; `name?`: `string`; \}\>; `hooks?`: `boolean`; `onDelete?`: `string`; `onUpdate?`: `string`; `scope?`: `Readonly`\<`Record`\<`string`, `unknown`\>\>; `sourceKey?`: `string`; `targetKey?`: `string`; \}\> Association options (`foreignKey`, `onDelete`, …). ### Returns [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) An attribute decorator. ### Example ```ts class User extends Model { @HasOne(() => Profile) profile!: Profile; } ``` ## Variable: INET > `const` **INET**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.INET` Alias of `DataTypes.INET` (Sequelize v6 module export). ## Variable: INTEGER > `const` **INTEGER**: `CallableInteger`\<[`IntegerDataType`](../postgrelize/namespaces/DataTypes/interfaces/IntegerDataType.md)\> = `DataTypes.INTEGER` Alias of `DataTypes.INTEGER` (Sequelize v6 module export). ## Variable: ISOLATION\_LEVELS > `const` **ISOLATION\_LEVELS**: `object` Transaction isolation levels (Sequelize v6 `Transaction.ISOLATION_LEVELS`). ### Type Declaration #### READ\_COMMITTED > `readonly` **READ\_COMMITTED**: `"READ COMMITTED"` = `'READ COMMITTED'` `READ COMMITTED` (PostgreSQL default). #### READ\_UNCOMMITTED > `readonly` **READ\_UNCOMMITTED**: `"READ UNCOMMITTED"` = `'READ UNCOMMITTED'` `READ UNCOMMITTED` (behaves as `READ COMMITTED` in PostgreSQL). #### REPEATABLE\_READ > `readonly` **REPEATABLE\_READ**: `"REPEATABLE READ"` = `'REPEATABLE READ'` `REPEATABLE READ`. #### SERIALIZABLE > `readonly` **SERIALIZABLE**: `"SERIALIZABLE"` = `'SERIALIZABLE'` `SERIALIZABLE`. ## Variable: JSON > `const` **JSON**: `Callable`\<`JsonType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.JSON` Alias of `DataTypes.JSON` (Sequelize v6 module export). ## Variable: JSONB > `const` **JSONB**: `Callable`\<`JsonType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.JSONB` Alias of `DataTypes.JSONB` (Sequelize v6 module export). ## Variable: LOCK > `const` **LOCK**: `object` Row lock strengths for `findAll({ lock })` (Sequelize v6 `Transaction.LOCK`). ### Type Declaration #### KEY\_SHARE > `readonly` **KEY\_SHARE**: `"KEY SHARE"` = `'KEY SHARE'` `FOR KEY SHARE`. #### NO\_KEY\_UPDATE > `readonly` **NO\_KEY\_UPDATE**: `"NO KEY UPDATE"` = `'NO KEY UPDATE'` `FOR NO KEY UPDATE`. #### SHARE > `readonly` **SHARE**: `"SHARE"` = `'SHARE'` `FOR SHARE`. #### UPDATE > `readonly` **UPDATE**: `"UPDATE"` = `'UPDATE'` `FOR UPDATE`. ## Variable: MACADDR > `const` **MACADDR**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.MACADDR` Alias of `DataTypes.MACADDR` (Sequelize v6 module export). ## Variable: MEDIUMINT > `const` **MEDIUMINT**: `CallableInteger`\<[`MediumIntegerDataType`](../postgrelize/namespaces/DataTypes/interfaces/MediumIntegerDataType.md)\> = `DataTypes.MEDIUMINT` Alias of `DataTypes.MEDIUMINT` (Sequelize v6 module export). ## Variable: NOW > `const` **NOW**: [`DefaultValueGenerator`](../interfaces/DefaultValueGenerator.md) = `DataTypes.NOW` Alias of `DataTypes.NOW` (Sequelize v6 module export). ## Variable: NUMBER > `const` **NUMBER**: `Callable`\<`DecimalType`, \[`digits?`: `number`, `scale?`: `number`\], `DecimalType`\> = `DataTypes.NUMBER` Alias of `DataTypes.NUMBER` (Sequelize v6 module export). ## Variable: NUMERIC > `const` **NUMERIC**: `Callable`\<`DecimalType`, \[`digits?`: `number`, `scale?`: `number`\], `DecimalType`\> = `DataTypes.NUMERIC` Alias of `DataTypes.NUMERIC` (Sequelize v6 module export). ## Variable: Op > `const` **Op**: `object` Query operators for `where` clauses. Symbols are created with `Symbol.for(name)` exactly like Sequelize v6, so operators imported from `sequelize` and from `postgrelize` are interchangeable. Operators marked "PostgreSQL extension" do not exist in Sequelize v6. ### Type Declaration #### adjacent > **adjacent**: *typeof* `adjacent` `-|-` — ranges are adjacent. #### all > **all**: *typeof* `all` `ALL (ARRAY[...])`, combined with a comparison operator. #### and > **and**: *typeof* `and` Logical AND of nested conditions. #### any > **any**: *typeof* `any` `ANY (ARRAY[...])`, combined with a comparison operator. #### between > **between**: *typeof* `between` `BETWEEN a AND b`, value is `[a, b]`. #### col > **col**: *typeof* `col` Compares with another column, value is a column reference such as `'user.id'`. #### contained > **contained**: *typeof* `contained` `<@` — array, range or jsonb is contained by the value. #### containedOrEqual > **containedOrEqual**: *typeof* `containedOrEqual` `<<=` — inet/cidr subnet is contained within or equals the value. PostgreSQL extension. #### contains > **contains**: *typeof* `contains` `@>` — array, range or jsonb contains the value. #### containsOrEqual > **containsOrEqual**: *typeof* `containsOrEqual` `>>=` — inet/cidr subnet contains or equals the value. PostgreSQL extension. #### endsWith > **endsWith**: *typeof* `endsWith` `LIKE '%value'`. #### eq > **eq**: *typeof* `eq` `= value`; `IS NULL` when the value is `null`. #### gt > **gt**: *typeof* `gt` `> value`. #### gte > **gte**: *typeof* `gte` `>= value`. #### hasAllKeys > **hasAllKeys**: *typeof* `hasAllKeys` jsonb `?&` — all of the keys exist. PostgreSQL extension. #### hasAnyKeys > **hasAnyKeys**: *typeof* `hasAnyKeys` jsonb `?|` — any of the keys exist. PostgreSQL extension. #### hasKey > **hasKey**: *typeof* `hasKey` jsonb `?` — top-level key exists. PostgreSQL extension. #### iLike > **iLike**: *typeof* `iLike` `ILIKE pattern`. #### in > `readonly` **in**: *typeof* `inOp` = `inOp` `IN (...)`; long lists compile to `= ANY($n)`. #### iRegexp > **iRegexp**: *typeof* `iRegexp` `~* pattern` (case-insensitive regular expression). #### is > **is**: *typeof* `is` `IS value`, for `null`, `true` or `false`. #### isDistinctFrom > **isDistinctFrom**: *typeof* `isDistinctFrom` `IS DISTINCT FROM value` (null-safe `<>`). PostgreSQL extension. #### isNotDistinctFrom > **isNotDistinctFrom**: *typeof* `isNotDistinctFrom` `IS NOT DISTINCT FROM value` (null-safe `=`). PostgreSQL extension. #### join > **join**: *typeof* `join` Reserved by Sequelize v6 for internal use. #### jsonPathExists > **jsonPathExists**: *typeof* `jsonPathExists` jsonb `@?` — the jsonpath returns any item; the value is a jsonpath string. PostgreSQL extension. #### like > **like**: *typeof* `like` `LIKE pattern`. #### lt > **lt**: *typeof* `lt` `< value`. #### lte > **lte**: *typeof* `lte` `<= value`. #### match > **match**: *typeof* `match` `@@` — tsvector matches tsquery. #### ne > **ne**: *typeof* `ne` `<> value`; `IS NOT NULL` when the value is `null`. #### noExtendLeft > **noExtendLeft**: *typeof* `noExtendLeft` `&>` — range does not extend to the left of the value. #### noExtendRight > **noExtendRight**: *typeof* `noExtendRight` `&<` — range does not extend to the right of the value. #### not > **not**: *typeof* `not` `IS NOT value` for `null`/booleans, otherwise negates a nested condition. #### notBetween > **notBetween**: *typeof* `notBetween` `NOT BETWEEN a AND b`, value is `[a, b]`. #### notILike > **notILike**: *typeof* `notILike` `NOT ILIKE pattern`. #### notIn > **notIn**: *typeof* `notIn` `NOT IN (...)`; long lists compile to `<> ALL($n)`. #### notIRegexp > **notIRegexp**: *typeof* `notIRegexp` `!~* pattern`. #### notLike > **notLike**: *typeof* `notLike` `NOT LIKE pattern`. #### notRegexp > **notRegexp**: *typeof* `notRegexp` `!~ pattern`. #### notSimilarTo > **notSimilarTo**: *typeof* `notSimilarTo` `NOT SIMILAR TO pattern`. PostgreSQL extension. #### or > **or**: *typeof* `or` Logical OR of nested conditions. #### overlap > **overlap**: *typeof* `overlap` `&&` — arrays or ranges overlap. #### placeholder > **placeholder**: *typeof* `placeholder` Reserved by Sequelize v6 for internal use. #### regexp > **regexp**: *typeof* `regexp` `~ pattern` (POSIX regular expression). #### similarTo > **similarTo**: *typeof* `similarTo` `SIMILAR TO pattern` (SQL regular expression). PostgreSQL extension. #### startsWith > **startsWith**: *typeof* `startsWith` `LIKE 'value%'`. #### strictLeft > **strictLeft**: *typeof* `strictLeft` `<<` — range is strictly left of the value. #### strictRight > **strictRight**: *typeof* `strictRight` `>>` — range is strictly right of the value. #### substring > **substring**: *typeof* `substring` `LIKE '%value%'`. #### trigramHasSimilarStrictWord > **trigramHasSimilarStrictWord**: *typeof* `trigramHasSimilarStrictWord` `%>>` — `pg_trgm`: the column has a strictly similar word of the value. PostgreSQL extension. #### trigramHasSimilarWord > **trigramHasSimilarWord**: *typeof* `trigramHasSimilarWord` `%>` — `pg_trgm`: the column has a part similar to the value (commutator of `<%`). PostgreSQL extension. #### trigramSimilar > **trigramSimilar**: *typeof* `trigramSimilar` `%` — `pg_trgm` trigram similarity above `pg_trgm.similarity_threshold`. PostgreSQL extension. #### trigramStrictWordSimilar > **trigramStrictWordSimilar**: *typeof* `trigramStrictWordSimilar` `<<%` — `pg_trgm`: the column is strictly similar to a word of the value. PostgreSQL extension. #### trigramWordSimilar > **trigramWordSimilar**: *typeof* `trigramWordSimilar` `<%` — `pg_trgm`: the column is similar to a part of the value (word similarity above the threshold). PostgreSQL extension. #### values > **values**: *typeof* `values` `VALUES (...)` list for `Op.any` / `Op.all`. ### Example ```ts await User.findAll({ where: { age: { [Op.gte]: 18 }, name: { [Op.iLike]: 'a%' } } }); ``` ## Variable: PartitionBound > `const` **PartitionBound**: `object` `MINVALUE` and `MAXVALUE` for the `from` / `to` lists of a range partition bound. They are markers, not strings, so a string value can never be read as a keyword. ### Type Declaration #### MAXVALUE > `readonly` **MAXVALUE**: `Readonly`\<`Readonly`\<\{ `keyword`: `"MINVALUE"` \| `"MAXVALUE"`; \}\>\> Highest possible value of a range column. #### MINVALUE > `readonly` **MINVALUE**: `Readonly`\<`Readonly`\<\{ `keyword`: `"MINVALUE"` \| `"MAXVALUE"`; \}\>\> Lowest possible value of a range column. ### Example ```ts await queryInterface.createPartition('events', 'events_old', { from: [PartitionBound.MINVALUE], to: ['2020-01-01'], }); ``` ## Variable: PrimaryKey > `const` **PrimaryKey**: [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) Makes the attribute part of the primary key (`primaryKey: true`). ### Example ```ts class User extends Model { @PrimaryKey @Column(DataTypes.INTEGER) id!: number; } ``` ## Variable: QueryTypes > `const` **QueryTypes**: `object` Query types of `sequelize.query` (Sequelize v6 `QueryTypes`). ### Type Declaration #### BULKDELETE > `readonly` **BULKDELETE**: `"BULKDELETE"` = `'BULKDELETE'` Returns the number of affected rows. #### BULKUPDATE > `readonly` **BULKUPDATE**: `"BULKUPDATE"` = `'BULKUPDATE'` Returns the number of affected rows. #### DELETE > `readonly` **DELETE**: `"DELETE"` = `'DELETE'` Returns the rows of the statement (`[]` without `RETURNING`). #### DESCRIBE > `readonly` **DESCRIBE**: `"DESCRIBE"` = `'DESCRIBE'` Returns `[rows, result]`. #### FOREIGNKEYS > `readonly` **FOREIGNKEYS**: `"FOREIGNKEYS"` = `'FOREIGNKEYS'` Returns `[rows, result]`. #### INSERT > `readonly` **INSERT**: `"INSERT"` = `'INSERT'` Returns `[rows, rowCount]`. #### RAW > `readonly` **RAW**: `"RAW"` = `'RAW'` Returns `[rows, result]` (default). #### SELECT > `readonly` **SELECT**: `"SELECT"` = `'SELECT'` Returns rows. #### SHOWCONSTRAINTS > `readonly` **SHOWCONSTRAINTS**: `"SHOWCONSTRAINTS"` = `'SHOWCONSTRAINTS'` Returns `[rows, result]`. #### SHOWINDEXES > `readonly` **SHOWINDEXES**: `"SHOWINDEXES"` = `'SHOWINDEXES'` Returns `[rows, result]`. #### SHOWTABLES > `readonly` **SHOWTABLES**: `"SHOWTABLES"` = `'SHOWTABLES'` Returns `[rows, result]`. #### UPDATE > `readonly` **UPDATE**: `"UPDATE"` = `'UPDATE'` Returns `[rows, rowCount]`. #### UPSERT > `readonly` **UPSERT**: `"UPSERT"` = `'UPSERT'` Returns `[undefined, null]` like v6 on PostgreSQL (the statement runs; its rows are not returned). #### VERSION > `readonly` **VERSION**: `"VERSION"` = `'VERSION'` Returns `[rows, result]`. ## Variable: RANGE > `const` **RANGE**: `RangeFactory` = `DataTypes.RANGE` Alias of `DataTypes.RANGE` (Sequelize v6 module export). ## Variable: REAL > `const` **REAL**: `Callable`\<`ScalarType`, \[`length?`: `number`, `decimals?`: `number`\], [`RealDataType`](../postgrelize/namespaces/DataTypes/interfaces/RealDataType.md)\> = `DataTypes.REAL` Alias of `DataTypes.REAL` (Sequelize v6 module export). ## Variable: SMALLINT > `const` **SMALLINT**: `CallableInteger`\<[`SmallIntegerDataType`](../postgrelize/namespaces/DataTypes/interfaces/SmallIntegerDataType.md)\> = `DataTypes.SMALLINT` Alias of `DataTypes.SMALLINT` (Sequelize v6 module export). ## Variable: STRING > `const` **STRING**: `Callable`\<`StringType`, \[`length?`: `number`\], `StringType`\> = `DataTypes.STRING` Alias of `DataTypes.STRING` (Sequelize v6 module export). ## Variable: TEXT > `const` **TEXT**: `Callable`\<`TextType`, \[`size?`: `"tiny"` \| `"medium"` \| `"long"`\], `TextType`\> = `DataTypes.TEXT` Alias of `DataTypes.TEXT` (Sequelize v6 module export). ## Variable: TIME > `const` **TIME**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.TIME` Alias of `DataTypes.TIME` (Sequelize v6 module export). ## Variable: TINYINT > `const` **TINYINT**: `CallableInteger`\<[`TinyIntegerDataType`](../postgrelize/namespaces/DataTypes/interfaces/TinyIntegerDataType.md)\> = `DataTypes.TINYINT` Alias of `DataTypes.TINYINT` (Sequelize v6 module export). ## Variable: TRANSACTION\_TYPES > `const` **TRANSACTION\_TYPES**: `object` Transaction types; accepted for Sequelize v6 compatibility and ignored by PostgreSQL. ### Type Declaration #### DEFERRED > `readonly` **DEFERRED**: `"DEFERRED"` = `'DEFERRED'` SQLite-only, ignored. #### EXCLUSIVE > `readonly` **EXCLUSIVE**: `"EXCLUSIVE"` = `'EXCLUSIVE'` SQLite-only, ignored. #### IMMEDIATE > `readonly` **IMMEDIATE**: `"IMMEDIATE"` = `'IMMEDIATE'` SQLite-only, ignored. ## Variable: TSVECTOR > `const` **TSVECTOR**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.TSVECTOR` Alias of `DataTypes.TSVECTOR` (Sequelize v6 module export). ## Variable: Table > `const` **Table**: [`ModelClassDecorator`](../type-aliases/ModelClassDecorator.md) & ((`argument?`) => [`ModelClassDecorator`](../type-aliases/ModelClassDecorator.md)) Marks a class as a model and sets its table options: everything `Model.init` accepts except `sequelize`. Optional; a decorated class without `@Table` gets the `Model.init` defaults. Use it bare (`@Table`) or called. The class must be registered with `sequelize.addModels`. ### Param **options** Table options (`tableName`, `schema`, `timestamps`, `paranoid`, `indexes`, `hooks`, …). ### Returns A class decorator. ### Example ```ts @Table({ tableName: 'users', paranoid: true }) class User extends Model {} ``` ### See [Sequelize.addModels](../classes/Sequelize.md#addmodels) ## Variable: UUID > `const` **UUID**: `Callable`\<`ScalarType`, \[\], [`AbstractDataType`](../postgrelize/namespaces/DataTypes/interfaces/AbstractDataType.md)\> = `DataTypes.UUID` Alias of `DataTypes.UUID` (Sequelize v6 module export). ## Variable: UUIDV4 > `const` **UUIDV4**: [`DefaultValueGenerator`](../interfaces/DefaultValueGenerator.md) = `DataTypes.UUIDV4` Alias of `DataTypes.UUIDV4` (Sequelize v6 module export). ## Variable: Unique > `const` **Unique**: [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) & ((`argument?`) => [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md)) Adds a unique constraint (`unique`). Usable bare or with a constraint name or options. ### Param **unique** Constraint name or `{ name, msg, nullsNotDistinct }`. Attributes sharing a name form a composite key. ### Returns An attribute decorator. ### Example ```ts class User extends Model { @Unique @Column(DataTypes.STRING) email!: string; } ``` ## Variable: UpdatedAt > `const` **UpdatedAt**: [`ModelPropertyDecorator`](../type-aliases/ModelPropertyDecorator.md) Names the attribute that holds the last update time (`updatedAt: ''`). ### Example ```ts class User extends Model { @UpdatedAt updatedOn!: Date; } ``` ## Variable: Utils > `const` **Utils**: `Readonly`\<\{ `Cast`: *typeof* [`Cast`](../interfaces/Cast.md); `Col`: *typeof* [`Col`](../interfaces/Col.md); `Fn`: *typeof* [`Fn`](../interfaces/Fn.md); `Json`: *typeof* [`Json`](../interfaces/Json.md); `Literal`: *typeof* [`Literal`](../interfaces/Literal.md); `pluralize`: (`word`) => `string`; `SequelizeMethod`: *typeof* [`SqlExpression`](../interfaces/SqlExpression.md); `singularize`: (`word`) => `string`; `useInflection`: (`custom`) => `void`; `Where`: *typeof* [`Where`](../interfaces/Where.md); \}\> The part of Sequelize v6 `Utils` that has a postgrelize counterpart: the expression classes behind `fn`, `col`, `cast`, `literal`, `json` and `where` (`Utils.Fn`, `Utils.Literal`, ... both as values and as types), `SequelizeMethod` (the base class of expressions), `useInflection`, `pluralize` and `singularize`. The other v6 helpers are internal and not provided. ### Example ```ts const isLiteral = (value: unknown): value is Utils.Literal => value instanceof Utils.Literal; const amount: Utils.Literal = literal('1 + 1'); ``` ## Variable: VIRTUAL > `const` **VIRTUAL**: `VirtualFactory` = `DataTypes.VIRTUAL` Alias of `DataTypes.VIRTUAL` (Sequelize v6 module export). ## Variable: ValidationErrorItemOrigin > **ValidationErrorItemOrigin**: `ValidationErrorItemOrigins` Values of [ValidationErrorItem.origin](../classes/ValidationErrorItem.md#origin), as in Sequelize v6. ## Variable: ValidationErrorItemType > `const` **ValidationErrorItemType**: `ValidationErrorItemTypes` Origin by validation error type, as in Sequelize v6 (`ValidationErrorItemType['unique violation']` is `'DB'`). ## Variable: ValidationFailed > `const` **ValidationFailed**: [`ModelStaticMethodDecorator`](../type-aliases/ModelStaticMethodDecorator.md) Registers the decorated static method as a `validationFailed` hook of the model (like `Model.validationFailed`). The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class. Accepts the TC39 and the legacy `experimentalDecorators` call signature. ### Example ```ts class User extends Model { @ValidationFailed static async onValidationFailed(user: User, options: unknown, error: unknown) {} } ``` ## Variable: Validator > `const` **Validator**: *typeof* `validator` = `validatorJs` The `validator` (validator.js) library used by the built-in validators, e.g. `Validator.isEmail(value)` (Sequelize v6 `Validator`). ## Variable: where > `const` **where**: [`WhereFactory`](../type-aliases/WhereFactory.md) Compares an expression with a value: `where(fn('lower', col('name')), 'bob')` or `where(col('age'), Op.gt, 18)`. ### Returns Where expression. ### Example ```ts await User.findAll({ where: where(fn('lower', col('name')), 'bob') }); await User.findAll({ where: where(col('age'), Op.gt, 18) }); ```