Skip to content

postgrelize extensions ​

Everything on this page is not in Sequelize v6. Sequelize v6 behaviour never changes (see Migrating); extensions are new options, methods and helpers, marked postgrelize extension wherever they appear in the docs. This page is generated from the code (the option lists compare postgrelize with the sequelize@6 types) and from the PostgreSQL coverage matrix.

Features ​

SELECT clauses ​

FeaturePostgreSQLHowDocs
DISTINCT ON16+distinctOn find option.guide · example
Window functions (OVER, PARTITION BY)16+over() expression; named WINDOW clauses and frame clauses are not modelled.guide · example
CTEs and WITH RECURSIVE16+with find option.guide · example
CTE MATERIALIZED / NOT MATERIALIZED16+materialized flag of a CTE definition.guide · example
Data-modifying CTEs (WITH … UPDATE/DELETE … RETURNING)16+Model.updateStatement(), deleteStatement(), insertStatement() in with; the query goes to the writer. INSERT … SELECT FROM cte as the main statement is not supported.guide · example
CTE SEARCH / CYCLE clauses16+search and cycle in a recursive with definition; cycle.using is required.guide · example
LATERAL joins16+from: { alias: { lateral: subquery } }; lateral: true on a separate include with limit reads the top rows per parent.guide · example
ORDER BY … NULLS FIRST / LAST16+Order direction string, e.g. ["rank", "ASC NULLS LAST"].guide · example
TABLESAMPLE16+sample: { method, percent, seed } find option and { model, sample } in from.guide · example
FETCH FIRST … WITH TIES16+withTies: true with limit and order.guide · example
UNION / INTERSECT / EXCEPT [ALL]16+Subquery#union(), intersect(), except() ({ all: true }); source: subquery reads model rows from the result.guide · example
Subqueries (IN, scalar, EXISTS / NOT EXISTS, correlated)16+Model.subquery(), exists(), notExists(); IN (subquery) in where.guide · example
Row-value comparison (keyset pagination)16+tuple() expression.guide · example
Standalone VALUES lists and set-returning functions in FROM (unnest, generate_series, WITH ORDINALITY)16+from entries { values } and { function, args, columns, ordinality }.guide · example

DML ​

FeaturePostgreSQLHowDocs
INSERT … ON CONFLICT DO NOTHING16+onConflict with action: "nothing".guide · example
ON CONFLICT DO UPDATE with expressions and inserted/updated flag16+onConflict update action with excluded(); Model.insert() reports wasInserted.guide · example
ON CONFLICT DO UPDATE … WHERE16+where of the onConflict update action.guide · example
ON CONFLICT ON CONSTRAINT, expression and partial-index targets16+onConflict targets: constraint, columns or expressions, with where.guide · example
INSERT … OVERRIDING SYSTEM / USER VALUE16+overriding: "system" | "user" write option.guide · example
INSERT … SELECT16+Model.insertFrom().guide · example
UPDATE … FROM and DELETE … USING16+from option of Model.update, using option of Model.destroy.guide · example
MERGE (WHEN MATCHED / NOT MATCHED, DELETE, DO NOTHING)16+Model.merge() with VALUES or subquery source.guide · example
MERGE … RETURNING merge_action() and WHEN NOT MATCHED BY SOURCE17+Rejected before running on servers older than 17.guide · example
RETURNING OLD (pre-statement values)18+returningOld → instance.oldValues. RETURNING NEW is the default row.guide · example
COPY FROM STDIN (bulk load)16+Model.copyFrom() streams arrays and async iterables.guide · example
COPY TO STDOUT (export)16+Model.copyTo() returns an async iterable.guide · example
Bulk insert via UNNEST arrays16+bulkCreate(rows, { unnest: true }).guide · example

Operators and functions ​

FeaturePostgreSQLHowDocs
IS [NOT] DISTINCT FROM16+Op.isDistinctFrom, Op.isNotDistinctFrom.guide · example
= ANY($1) for long IN lists16+Automatic above inAsAnyThreshold.guide · example
SIMILAR TO16+Op.similarTo, Op.notSimilarTo.guide · example
jsonpath operators (@?, @@) and jsonb_path_* functions16+Op.jsonPathExists (@?), Op.match through where() (@@), jsonbPath() for the jsonb_path_* functions.guide · example
JSON_TABLE17+from entry { jsonTable: { doc, path, columns } }; NESTED PATH is not modelled.guide · example
Multirange operators and functions (range_agg, unnest)16+Range operators (Op.contains, Op.overlap, Op.strictLeft, …) on multirange columns; range_agg, unnest through fn().guide · example
Full-text search match (@@)16+Op.match with fn("to_tsquery", …) / fn("websearch_to_tsquery", …).guide · example
Full-text ranking and highlighting (ts_rank, ts_headline, setweight)16+tsRank (also ts_rank_cd), tsHeadline, setWeight, toTsVector, toTsQuery, plainToTsQuery, phraseToTsQuery, websearchToTsQuery with an optional configuration.guide · example
Network operators (<<, <<=, >>, >>=, host(), network())16+Op.strictLeft, Op.strictRight, Op.containedOrEqual, Op.containsOrEqual, Op.overlap; host() and network() through fn().guide · example
Geometric operators and functions16+Op.contains, Op.contained, Op.overlap, Op.strictLeft, Op.strictRight on geometric columns; operands of another type need cast(); <->, ?# and functions through literal() / fn().guide · example
hstore operators (->, ?, @>)16+Op.contains and Op.eq take objects; ->, ? and other operators through literal().guide · example
pg_trgm similarity (%, similarity(), word_similarity())16+Op.trigramSimilar and word variants, trigramSimilarity(), trigramWordSimilarity(), trigramDistance() (<->); needs CREATE EXTENSION pg_trgm; the gin_trgm_ops index uses the operator index option.guide · example

Data types ​

FeaturePostgreSQLHowDocs
timestamp without time zone16+DataTypes.TIMESTAMP(fsp?); values are Dates with the local wall-clock time.guide · example
interval16+DataTypes.INTERVAL.guide · example
money16+DataTypes.MONEY; read as the server formats it (lc_monetary, e.g. $12.50); write numbers or strings.guide · example
composite types16+DataTypes.COMPOSITE(name, fields) with object values; createSql() renders CREATE TYPE; array fields are not supported.guide · example
multirange types16+DataTypes.MULTIRANGE(type) (PostgreSQL 14+) with arrays of [lower, upper] ranges.guide · example
xml16+DataTypes.XML; values are XML text; xpath() through literal() / fn().guide · example
bit and bit varying16+DataTypes.BIT(n), DataTypes.VARBIT(n); values are strings of 0 and 1.guide · example
macaddr816+DataTypes.MACADDR8.guide · example
geometric types (point, line, lseg, box, path, polygon, circle)16+DataTypes.POINT, LINE, LSEG, BOX, PATH, POLYGON, CIRCLE with object / point-array values.guide · example
tsquery16+DataTypes.TSQUERY; values are query strings ('fat' & 'rat').guide · example
ltree (extension)16+DataTypes.LTREE; values are strings ('Top.Science'); run CREATE EXTENSION ltree first.guide · example
Stored and virtual generated columns, identity columns16+generated: { as, stored } and identity: "always" | "byDefault" column options. VIRTUAL generated columns need PostgreSQL 18.guide · example

DDL (sync and QueryInterface) ​

FeaturePostgreSQLHowDocs
UNIQUE NULLS NOT DISTINCT16+nullsNotDistinct on unique columns, constraints and indexes.guide · example
EXCLUDE constraints16+addConstraint({ type: 'exclude', exclude: [{ name | expression, with }], using, where, include, deferrable }); violations raise ExclusionConstraintError.guide · example
NOT VALID constraints and VALIDATE CONSTRAINT16+notValid on check and foreign key constraints, validateConstraint.guide · example
NOT ENFORCED constraints, WITHOUT OVERLAPS keys, FK PERIOD18+enforced: false, withoutOverlaps, period and references.fields on addConstraint; PostgreSQL 18 syntax, sent as written.guide · example
Expression indexes (lower(email))16+{ expression } index fields (trusted SQL) with collate, operator, order, nulls, include; an explicit name is required.guide · example
Views and materialized views16+createView (replace, temporary, recursive, checkOption), createMaterializedView, refreshMaterializedView (concurrently), dropView, dropMaterializedView; the query is trusted SQL.guide · example
Sequences (CREATE SEQUENCE, setval)16+createSequence, alterSequence, dropSequence, nextval, setval; serial and identity sequences stay with autoIncrement.guide · example
Functions and triggers16+createFunction, dropFunction, renameFunction, createTrigger, dropTrigger, renameTrigger with the v6 names; bodies and WHEN clauses are trusted SQL.guide · example
Declarative partitioning (PARTITION BY / PARTITION OF / ATTACH)16+createTable({ partitionBy }), createPartition, attachPartition, detachPartition (concurrently, finalize); bounds in, from / to, modulus / remainder, default. sync does not create partitions.guide · example
Extensions (CREATE EXTENSION)16+createExtension, dropExtension with ifNotExists, schema, version, cascade.guide · example
Row-level security policies16+enableRowLevelSecurity, disableRowLevelSecurity, createPolicy, alterPolicy, dropPolicy; string conditions are trusted SQL, where objects are escaped.guide · example
UNLOGGED and TEMPORARY tables16+unlogged and temporary options on createTable and on model options (sync); a temporary table lives in one session, so use a transaction.guide · example

Session features ​

FeaturePostgreSQLHowDocs
READ ONLY transactions16+readOnly: true.guide · example
DEFERRABLE transaction mode (SERIALIZABLE READ ONLY DEFERRABLE)16+deferrable transaction option.guide · example
Advisory locks16+sequelize.withAdvisoryLock(), transaction.advisoryLock().guide · example
LISTEN / NOTIFY16+sequelize.listen(), sequelize.notify() on a dedicated client.guide · example
SET LOCAL settings (statement_timeout, lock_timeout, RLS variables, search_path)16+settings transaction option.guide · example
Server-side cursors and streaming (findEach)16+Model.findEach().guide · example
COPY streaming with backpressure16+copyTo is an async iterable; copyFrom accepts async iterables.guide · example
Read replicas16+replication: { read, write }, useMaster.guide · example
Named prepared statements16+statementCache option; opt-in, bounded per connection, ADR-023.guide · example
Per-query statement timeout16+statementTimeout query option (ms).guide · example

Other extensions ​

FeatureDocs
Public decorators and sequelize.addModelsguide · example
Standard Schema validation (validationSchema)guide · example
Model.insert() with wasInserted per rowguide · example

Methods ​

Members tagged @postgrelize in the source. Signatures, parameters and examples are on the linked API pages.

MethodWhat it does
Model.insertInserts rows with INSERT ... ON CONFLICT and returns the inserted or updated rows.
Model.insertFromINSERT INTO ... SELECT: inserts the rows produced by a subquery.
Model.mergeMERGE INTO ... USING ... (PostgreSQL 15+).
Model.subqueryBuilds 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.
Model.updateStatementBuilds an UPDATE for a data-modifying CTE (with); nothing runs until the outer query does.
Model.deleteStatementBuilds a DELETE for a data-modifying CTE (with).
Model.insertStatementBuilds an INSERT of attribute-keyed rows for a data-modifying CTE (with).
Model.findEachStreams rows with a server-side cursor (DECLARE ... CURSOR + FETCH n), so large result sets are not loaded at once.
Model.copyFromBulk-loads rows with COPY ... FROM STDIN (text format) — much faster than INSERT for large volumes.
Model.copyToStreams COPY (SELECT ...) TO STDOUT output — the fastest way to export rows (e.g. CSV).
Model.wasInsertedFor 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.
Model.oldValuesFor instances returned with returningOld: true: attribute values of the row before the statement, or null when the row did not exist (inserted). undefined otherwise.
Sequelize.listenSubscribes a handler to NOTIFY messages on a channel over one dedicated connection per instance, which is re-subscribed after connection loss.
Sequelize.notifySends a notification to a channel with pg_notify.
Sequelize.addModelsRegisters 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.
Sequelize.withAdvisoryLockRuns 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.
Transaction.advisoryLockTakes a transaction-level advisory lock (pg_advisory_xact_lock), waiting until it is free.
Transaction.tryAdvisoryLockTries to take a transaction-level advisory lock without waiting.
QueryInterface.validateConstraintValidates a constraint added with notValid: true, scanning existing rows without blocking writes.
QueryInterface.createPartitionCreates a partition of a partitioned table (CREATE TABLE ... PARTITION OF).
QueryInterface.attachPartitionAttaches an existing table as a partition (ALTER TABLE ... ATTACH PARTITION).
QueryInterface.detachPartitionDetaches a partition, keeping it as a standalone table (ALTER TABLE ... DETACH PARTITION).
QueryInterface.enableRowLevelSecurityTurns on row-level security for a table (ALTER TABLE ... ENABLE ROW LEVEL SECURITY).
QueryInterface.disableRowLevelSecurityTurns off row-level security for a table (ALTER TABLE ... DISABLE ROW LEVEL SECURITY); policies are kept.
QueryInterface.createPolicyCreates 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.
QueryInterface.alterPolicyChanges a policy with ALTER POLICY: roles, conditions and name (rename, applied last).
QueryInterface.dropPolicyDrops a policy with DROP POLICY.
QueryInterface.createViewCreates a view with CREATE VIEW; replace renders CREATE OR REPLACE VIEW.
QueryInterface.dropViewDrops a view with DROP VIEW.
QueryInterface.createMaterializedViewCreates a materialized view with CREATE MATERIALIZED VIEW.
QueryInterface.refreshMaterializedViewRecomputes a materialized view with REFRESH MATERIALIZED VIEW.
QueryInterface.dropMaterializedViewDrops a materialized view with DROP MATERIALIZED VIEW.
QueryInterface.createExtensionInstalls an extension with CREATE EXTENSION.
QueryInterface.dropExtensionRemoves an extension with DROP EXTENSION.
QueryInterface.createSequenceCreates a sequence with CREATE SEQUENCE.
QueryInterface.alterSequenceChanges a sequence with ALTER SEQUENCE.
QueryInterface.dropSequenceDrops a sequence with DROP SEQUENCE.
QueryInterface.nextvalAdvances a sequence and returns the new value (SELECT nextval(...); the name is bound).
QueryInterface.setvalSets the current value of a sequence (SELECT setval(...); name and value are bound).

Options that v6 does not have ​

Options of the same-named Sequelize v6 option types that only postgrelize accepts. Descriptions, types and defaults are in the option reference.

OptionAccepted by
statementTimeoutFindOptions, FindAndCountOptions, FindOrCreateOptions, FindOrBuildOptions, CountOptions, CountWithOptions, AggregateOptions, CreateOptions, BulkCreateOptions, UpdateOptions, DestroyOptions, RestoreOptions, UpsertOptions, SaveOptions, InstanceUpdateOptions, InstanceDestroyOptions, IncrementOptions, InsertOptions, InsertFromOptions, CopyFromOptions, CopyToOptions, QueryOptions, SyncOptions, DropOptions, CreateTableOptions, DropTableOptions
useMasterFindOptions, FindAndCountOptions, FindOrCreateOptions, FindOrBuildOptions, CountOptions, CountWithOptions, AggregateOptions, CreateOptions, BulkCreateOptions, UpdateOptions, DestroyOptions, RestoreOptions, UpsertOptions, SaveOptions, InstanceUpdateOptions, InstanceDestroyOptions, IncrementOptions, InsertOptions, InsertFromOptions, CopyFromOptions, CopyToOptions, QueryOptions, GetConnectionOptions, SyncOptions, DropOptions, CreateTableOptions, DropTableOptions
noWaitFindOptions, FindAndCountOptions, FindOrCreateOptions, FindOrBuildOptions, SelectOptions, CopyToOptions
distinctOnFindOptions, FindAndCountOptions, FindOrCreateOptions, FindOrBuildOptions, SelectOptions, CopyToOptions
withTiesFindOptions, FindAndCountOptions, FindOrCreateOptions, FindOrBuildOptions, SelectOptions, CopyToOptions
sampleFindOptions, FindAndCountOptions, FindOrCreateOptions, FindOrBuildOptions, CountOptions, CountWithOptions, AggregateOptions, SelectOptions, CopyToOptions
withFindOptions, FindAndCountOptions, FindOrCreateOptions, FindOrBuildOptions, CountOptions, CountWithOptions, AggregateOptions, CteFindOptions, CopyToOptions
sourceFindOptions, FindAndCountOptions, FindOrCreateOptions, FindOrBuildOptions, CountOptions, CountWithOptions, AggregateOptions, CteFindOptions, CopyToOptions
fromFindOptions, FindAndCountOptions, FindOrCreateOptions, FindOrBuildOptions, CountOptions, CountWithOptions, AggregateOptions, CteFindOptions, UpdateOptions, CopyToOptions
lateralIncludeOptions
overridingCreateOptions, BulkCreateOptions, UpsertOptions, SaveOptions, InstanceUpdateOptions
onConflictCreateOptions, BulkCreateOptions, UpsertOptions
unnestBulkCreateOptions
returningOldUpdateOptions, InsertOptions
returningDestroyOptions
usingDestroyOptions
unloggedInitOptions, DefineOptions, TableOptions
temporaryInitOptions, DefineOptions, TableOptions
validationSchemaInitOptions, DefineOptions, TableOptions
identityAttributeOptions
generatedAttributeOptions
nullsNotDistinctUniqueOptions, ConstraintOptions, IndexOptions
inAsAnyThresholdSequelizeOptions
statementCacheSequelizeOptions
readOnlyTransactionOptions
deferrableTransactionOptions
settingsTransactionOptions
excludeConstraintOptions
withoutOverlapsConstraintOptions
periodConstraintOptions
enforcedConstraintOptions
notValidConstraintOptions

Option types that only exist in postgrelize ​

CteFindOptions, CteSearchOptions, CteCycleOptions, TableSampleOptions, SetOperationOptions, WindowOptions, JsonTableOptions, JsonTableColumnOptions, JsonbPathOptions, TsRankOptions, TsHeadlineOptions, InsertOptions, InsertFromOptions, OnConflictOptions, MergeOptions, UpdateStatementOptions, CopyFromOptions, CopyToOptions, CopyToFormatOptions, StatementCacheOptions, CreatePartitionOptions, DetachPartitionOptions, CreateExtensionOptions, DropExtensionOptions, CreateSequenceOptions, AlterSequenceOptions, DropSequenceOptions, CreateViewOptions, DropViewOptions, CreateMaterializedViewOptions, RefreshMaterializedViewOptions, CreatePolicyOptions, AlterPolicyOptions, DropPolicyOptions, EnableRowLevelSecurityOptions, DisableRowLevelSecurityOptions

Helper functions and constants ​

Exports tagged @postgrelize in the source. Full signatures are in the API reference.

ExportWhat it does
jsonbPathCalls a jsonb_path_* function (exists, match, query, queryFirst, queryArray) with a bound jsonpath.
plainToTsQueryplainto_tsquery([config,] text): ANDs all words of plain text.
phraseToTsQueryphraseto_tsquery([config,] text): words of plain text that must follow each other.
setWeightsetweight(vector, weight): labels every lexeme of a tsvector A, B, C or D.
toTsQueryto_tsquery([config,] query): parses tsquery syntax (&, |, !, <->).
toTsVectorto_tsvector([config,] document): parses a document into a tsvector.
tsHeadlinets_headline: a document excerpt with the query terms highlighted.
tsRankts_rank / ts_rank_cd: relevance of a tsvector for a tsquery, for attributes and order.
websearchToTsQuerywebsearch_to_tsquery([config,] text): web-search syntax (quotes, or, -) that never fails to parse.
trigramDistanceleft <-> right of pg_trgm: trigram distance (1 - similarity), served by GiST trigram indexes for nearest-neighbour order.
trigramSimilaritysimilarity(a, b) of pg_trgm: trigram similarity from 0 to 1.
trigramWordSimilarityword_similarity(a, b) of pg_trgm: similarity of a to the best matching part of b.
excludedReferences the value proposed for insertion (EXCLUDED."column") inside an onConflict update.
existsEXISTS (subquery).
notExistsNOT EXISTS (subquery).
overWindow function call: over(fn('row_number'), { partitionBy: ['userId'], orderBy: [['createdAt', 'DESC']] }).
tupleRow constructor for row comparisons: where(tuple(col('createdAt'), col('id')), Op.lt, tuple(date, id)).
PartitionBoundMINVALUE and MAXVALUE for the from / to lists of a range partition bound.

Released under the MIT License.