不要怂,就是干,撸起袖子干!

Commit 26547bc9 by Simon Schick Committed by Sushant

feat: add typescript typings (#10287)

1 parent 554b223c
......@@ -16,6 +16,8 @@ install:
- npm install -g yarn
- yarn
- |-
if [ "$TSC" = true ]; then npm run test-typings; fi
- |-
if [ "$DIALECT" = "postgres-native" ]; then yarn add pg-native; fi
env:
......@@ -38,6 +40,8 @@ script:
- npm run lint
- |-
if [ "$COVERAGE" = true ]; then npm run cover && bash <(curl -s https://codecov.io/bash) -f coverage/lcov.info; else npm run test; fi
- |-
if [ "$TSC" = true ]; then npm run test-typings; fi
jobs:
include:
......@@ -66,7 +70,7 @@ jobs:
env: POSTGRES_VER=postgres-95 SEQ_PG_PORT=8990 DIALECT=postgres-native
- stage: test
node_js: '8'
env: DIALECT=sqlite COVERAGE=false
env: DIALECT=sqlite COVERAGE=false TSC=true
# - stage: release
# node_js: '8'
# script:
......
'use strict';
const _ = require('lodash');
const Utils = require('./utils');
const logger = require('./utils/logger');
const Promise = require('./promise');
const debug = logger.getLogger().debugContext('hooks');
......@@ -86,10 +85,9 @@ const Hooks = {
});
},
runHooks(hooks) {
runHooks(hooks, ...hookArgs) {
if (!hooks) throw new Error('runHooks requires at least 1 argument');
const hookArgs = Utils.sliceArgs(arguments, 1);
let hookType;
if (typeof hooks === 'string') {
......
......@@ -852,7 +852,7 @@ class Sequelize {
* });
*/
static fn(fn, ...args) {
return new Utils.Fn(fn, Utils.sliceArgs(args));
return new Utils.Fn(fn, args);
}
/**
......@@ -909,7 +909,7 @@ class Sequelize {
* @returns {Sequelize.and}
*/
static and(...args) {
return { [Op.and]: Utils.sliceArgs(args) };
return { [Op.and]: args };
}
/**
......@@ -924,7 +924,7 @@ class Sequelize {
* @returns {Sequelize.or}
*/
static or(...args) {
return { [Op.or]: Utils.sliceArgs(args) };
return { [Op.or]: args };
}
/**
......@@ -1067,9 +1067,8 @@ class Sequelize {
return res;
}
log() {
log(...args) {
let options;
let args = Utils.sliceArgs(arguments);
const last = _.last(args);
......
......@@ -323,17 +323,6 @@ function stack() {
}
exports.stack = stack;
function sliceArgs(args, begin) {
begin = begin || 0;
const tmp = new Array(args.length - begin);
for (let i = begin; i < args.length; ++i) {
tmp[i - begin] = args[i];
}
return tmp;
}
exports.sliceArgs = sliceArgs;
const dialects = new Set(['mariadb', 'mysql', 'postgres', 'sqlite', 'mssql']);
function now(dialect) {
......@@ -433,10 +422,10 @@ class Fn extends SequelizeMethod {
exports.Fn = Fn;
class Col extends SequelizeMethod {
constructor(col) {
constructor(col, ...args) {
super();
if (arguments.length > 1) {
col = this.sliceArgs(arguments);
if (args.length > 0) {
col = args;
}
this.col = col;
}
......
......@@ -18,11 +18,14 @@
"url": "https://github.com/sequelize/sequelize/issues"
},
"main": "index.js",
"types": "types",
"engines": {
"node": ">=6.0.0"
},
"files": [
"lib"
"lib",
"types/index.d.ts",
"types/lib"
],
"license": "MIT",
"dependencies": {
......@@ -46,6 +49,9 @@
"devDependencies": {
"@commitlint/cli": "^7.2.0",
"@commitlint/config-angular": "^7.1.2",
"@types/bluebird": "^3.5.25",
"@types/node": "^10.12.18",
"@types/validator": "^9.4.4",
"chai": "^4.x",
"chai-as-promised": "^7.x",
"chai-datetime": "^1.x",
......@@ -75,7 +81,8 @@
"sinon": "^6.3.5",
"sinon-chai": "^3.2.0",
"sqlite3": "^4.0.2",
"tedious": "^3.0.1"
"tedious": "^3.0.1",
"typescript": "^3.2.2"
},
"keywords": [
"mysql",
......@@ -138,6 +145,7 @@
"test-postgresn": "npm run test-postgres-native",
"test-mssql": "cross-env DIALECT=mssql npm test",
"test-all": "npm run test-mariadb && npm run test-mysql && npm run test-sqlite && npm run test-postgres && npm run test-postgres-native && npm run test-mssql",
"test-typings": "tsc -b types/tsconfig.json && tsc -b types/test/tsconfig.json",
"cover": "rimraf coverage && npm run teaser && npm run cover-integration && npm run cover-unit && npm run merge-coverage",
"cover-integration": "cross-env COVERAGE=true ./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha --require scripts/mocha-bootload --report lcovonly -- -t 30000 --exit --ui tdd \"test/integration/**/*.test.js\" && node -e \"require('fs').renameSync('coverage/lcov.info', 'coverage/integration.info')\"",
"cover-unit": "cross-env COVERAGE=true ./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha --require scripts/mocha-bootload --report lcovonly -- -t 30000 --exit --ui tdd \"test/unit/**/*.test.js\" && node -e \"require('fs').renameSync('coverage/lcov.info', 'coverage/unit.info')\"",
......
......@@ -132,15 +132,14 @@ module.exports = function(Sequelize) {
shimMethod(obj, name, original => {
const sequelizeProto = obj === Sequelize.prototype;
return function() {
return function(...args) {
let sequelize = sequelizeProto ? this : this.sequelize;
if (this instanceof Sequelize.Association) sequelize = this.target.sequelize;
if (!sequelize) throw new Error('Object does not have a `sequelize` attribute');
let args = Sequelize.Utils.sliceArgs(arguments);
const fromTests = calledFromTests();
if (conform) args = conform.apply(this, arguments);
if (conform) args = conform.apply(this, args);
let options = args[index];
......
import DataTypes = require('./lib/data-types');
import Deferrable = require('./lib/deferrable');
import Op = require('./lib/operators');
import QueryTypes = require('./lib/query-types');
import TableHints = require('./lib/table-hints');
import Utils = require('./lib/utils');
export * from './lib/sequelize';
export * from './lib/query-interface';
export * from './lib/data-types';
export * from './lib/model';
export * from './lib/transaction';
export * from './lib/model';
export * from './lib/associations/index';
export * from './lib/errors';
export { BaseError as Error } from './lib/errors';
export { useInflection } from './lib/utils';
export { Promise } from './lib/promise';
export { Utils, QueryTypes, Op, TableHints, DataTypes, Deferrable };
export { Validator as validator } from './lib/utils/validator-extras';
import { ColumnOptions, Model } from '../model';
export abstract class Association {
public associationType: string;
public source: typeof Model;
public target: typeof Model;
public isSelfAssociation: boolean;
public isSingleAssociation: boolean;
public isMultiAssociation: boolean;
public as: string;
public isAliased: boolean;
public foreignKey: string;
public identifier: string;
public inspect(): string;
}
export interface SingleAssociationAccessors {
get: string;
set: string;
create: string;
}
export interface MultiAssociationAccessors {
get: string;
set: string;
addMultiple: string;
add: string;
create: string;
remove: string;
removeMultiple: string;
hasSingle: string;
hasAll: string;
count: string;
}
/** Foreign Key Options */
export interface ForeignKeyOptions extends ColumnOptions {
/** Attribute name for the relation */
name?: string;
}
/**
* Options provided when associating models
*/
export interface AssociationOptions {
/**
* Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade.
* For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks
* for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking
* any hooks.
*
* @default false
*/
hooks?: boolean;
/**
* The alias of this model, in singular form. See also the `name` option passed to `sequelize.define`. If
* you create multiple associations between the same tables, you should provide an alias to be able to
* distinguish between them. If you provide an alias when creating the assocition, you should provide the
* same alias when eager loading and when getting assocated models. Defaults to the singularized name of
* target
*/
as?: string | { singular: string; plural: string };
/**
* The name of the foreign key in the target table or an object representing the type definition for the
* foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property
* to set the name of the column. Defaults to the name of source + primary key of source
*/
foreignKey?: string | ForeignKeyOptions;
/**
* What happens when delete occurs.
*
* Cascade if this is a n:m, and set null if it is a 1:m
*
* @default 'SET NULL' or 'CASCADE'
*/
onDelete?: string;
/**
* What happens when update occurs
*
* @default 'CASCADE'
*/
onUpdate?: string;
/**
* Should on update and on delete constraints be enabled on the foreign key.
*/
constraints?: boolean;
foreignKeyConstraint?: boolean;
scope?: AssociationScope;
}
/**
* Options for Association Scope
*/
export interface AssociationScope {
/**
* The name of the column that will be used for the associated scope and it's value
*/
[scopeName: string]: any;
}
/**
* Options provided for many-to-many relationships
*/
export interface ManyToManyOptions extends AssociationOptions {
/**
* A key/value set that will be used for association create and find defaults on the target.
* (sqlite not supported for N:M)
*/
scope?: AssociationScope;
}
import {
BulkCreateOptions,
CreateOptions,
Filterable,
FindOptions,
InstanceDestroyOptions,
InstanceUpdateOptions,
Model,
Transactionable,
WhereOptions,
} from '../model';
import { Promise } from '../promise';
import { Transaction } from '../transaction';
import { Association, AssociationScope, ForeignKeyOptions, ManyToManyOptions, MultiAssociationAccessors } from './base';
/**
* Used for a association table in n:m associations.
*/
export interface ThroughOptions {
/**
* The model used to join both sides of the N:M association.
*/
model: typeof Model;
/**
* A key/value set that will be used for association create and find defaults on the through model.
* (Remember to add the attributes to the through model)
*/
scope?: AssociationScope;
/**
* If true a unique key will be generated from the foreign keys used (might want to turn this off and create
* specific unique keys when using scopes)
*
* @default true
*/
unique?: boolean;
}
/**
* Attributes for the join table
*/
export interface JoinTableAttributes {
[attribute: string]: any;
}
/**
* Options provided when associating models with belongsToMany relationship
*/
export interface BelongsToManyOptions extends ManyToManyOptions {
/**
* The name of the table that is used to join source and target in n:m associations. Can also be a
* sequelize model if you want to define the junction table yourself and add extra attributes to it.
*/
through: typeof Model | string | ThroughOptions;
/**
* The name of the foreign key in the join table (representing the target model) or an object representing
* the type definition for the other column (see `Sequelize.define` for syntax). When using an object, you
* can add a `name` property to set the name of the colum. Defaults to the name of target + primary key of
* target
*/
otherKey?: string | ForeignKeyOptions;
/**
* Should the join model have timestamps
*/
timestamps?: boolean;
}
export class BelongsToMany extends Association {
public otherKey: string;
public accessors: MultiAssociationAccessors;
constructor(source: typeof Model, target: typeof Model, options: BelongsToManyOptions);
}
/**
* The options for the getAssociations mixin of the belongsToMany association.
* @see BelongsToManyGetAssociationsMixin
*/
export interface BelongsToManyGetAssociationsMixinOptions extends FindOptions {
/**
* Apply a scope on the related model, or remove its default scope by passing false.
*/
scope?: string | boolean;
}
/**
* The getAssociations mixin applied to models with belongsToMany.
* An example of usage is as follows:
*
* ```js
*
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* getRoles: Sequelize.BelongsToManyGetAssociationsMixin<RoleInstance>;
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
* @see Instance
*/
export type BelongsToManyGetAssociationsMixin<TModel> = (
options?: BelongsToManyGetAssociationsMixinOptions
) => Promise<TModel[]>;
/**
* The options for the setAssociations mixin of the belongsToMany association.
* @see BelongsToManySetAssociationsMixin
*/
export interface BelongsToManySetAssociationsMixinOptions
extends FindOptions,
BulkCreateOptions,
InstanceUpdateOptions,
InstanceDestroyOptions {
through?: JoinTableAttributes;
}
/**
* The setAssociations mixin applied to models with belongsToMany.
* An example of usage is as follows:
*
* ```js
*
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* setRoles: Sequelize.BelongsToManySetAssociationsMixin<RoleInstance, RoleId, UserRoleAttributes>;
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
* @see Instance
*/
export type BelongsToManySetAssociationsMixin<TModel, TModelPrimaryKey> = (
newAssociations?: (TModel | TModelPrimaryKey)[],
options?: BelongsToManySetAssociationsMixinOptions
) => Promise<void>;
/**
* The options for the addAssociations mixin of the belongsToMany association.
* @see BelongsToManyAddAssociationsMixin
*/
export interface BelongsToManyAddAssociationsMixinOptions
extends FindOptions,
BulkCreateOptions,
InstanceUpdateOptions,
InstanceDestroyOptions {
through?: JoinTableAttributes;
}
/**
* The addAssociations mixin applied to models with belongsToMany.
* An example of usage is as follows:
*
* ```js
*
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* addRoles: Sequelize.BelongsToManyAddAssociationsMixin<RoleInstance, RoleId, UserRoleAttributes>;
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
* @see Instance
*/
export type BelongsToManyAddAssociationsMixin<TModel, TModelPrimaryKey> = (
newAssociations?: (TModel | TModelPrimaryKey)[],
options?: BelongsToManyAddAssociationsMixinOptions
) => Promise<void>;
/**
* The options for the addAssociation mixin of the belongsToMany association.
* @see BelongsToManyAddAssociationMixin
*/
export interface BelongsToManyAddAssociationMixinOptions
extends FindOptions,
BulkCreateOptions,
InstanceUpdateOptions,
InstanceDestroyOptions {
through?: JoinTableAttributes;
}
/**
* The addAssociation mixin applied to models with belongsToMany.
* An example of usage is as follows:
*
* ```js
*
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* addRole: Sequelize.BelongsToManyAddAssociationMixin<RoleInstance, RoleId, UserRoleAttributes>;
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
* @see Instance
*/
export type BelongsToManyAddAssociationMixin<TModel, TModelPrimaryKey> = (
newAssociation?: TModel | TModelPrimaryKey,
options?: BelongsToManyAddAssociationMixinOptions
) => Promise<void>;
/**
* The options for the createAssociation mixin of the belongsToMany association.
* @see BelongsToManyCreateAssociationMixin
*/
export interface BelongsToManyCreateAssociationMixinOptions extends CreateOptions {
through?: JoinTableAttributes;
}
/**
* The createAssociation mixin applied to models with belongsToMany.
* An example of usage is as follows:
*
* ```js
*
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* createRole: Sequelize.BelongsToManyCreateAssociationMixin<RoleAttributes, UserRoleAttributes>;
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
* @see Instance
*/
export type BelongsToManyCreateAssociationMixin<TModel> = (
values?: { [attribute: string]: any },
options?: BelongsToManyCreateAssociationMixinOptions
) => Promise<TModel>;
/**
* The options for the removeAssociation mixin of the belongsToMany association.
* @see BelongsToManyRemoveAssociationMixin
*/
export interface BelongsToManyRemoveAssociationMixinOptions extends InstanceDestroyOptions {}
/**
* The removeAssociation mixin applied to models with belongsToMany.
* An example of usage is as follows:
*
* ```js
*
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* removeRole: Sequelize.BelongsToManyRemoveAssociationMixin<RoleInstance, RoleId>;
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
* @see Instance
*/
export type BelongsToManyRemoveAssociationMixin<TModel, TModelPrimaryKey> = (
oldAssociated?: TModel | TModelPrimaryKey,
options?: BelongsToManyRemoveAssociationMixinOptions
) => Promise<void>;
/**
* The options for the removeAssociations mixin of the belongsToMany association.
* @see BelongsToManyRemoveAssociationsMixin
*/
export interface BelongsToManyRemoveAssociationsMixinOptions extends InstanceDestroyOptions, InstanceDestroyOptions {}
/**
* The removeAssociations mixin applied to models with belongsToMany.
* An example of usage is as follows:
*
* ```js
*
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* removeRoles: Sequelize.BelongsToManyRemoveAssociationsMixin<RoleInstance, RoleId>;
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
* @see Instance
*/
export type BelongsToManyRemoveAssociationsMixin<TModel, TModelPrimaryKey> = (
oldAssociateds?: (TModel | TModelPrimaryKey)[],
options?: BelongsToManyRemoveAssociationsMixinOptions
) => Promise<void>;
/**
* The options for the hasAssociation mixin of the belongsToMany association.
* @see BelongsToManyHasAssociationMixin
*/
export interface BelongsToManyHasAssociationMixinOptions extends BelongsToManyGetAssociationsMixinOptions {}
/**
* The hasAssociation mixin applied to models with belongsToMany.
* An example of usage is as follows:
*
* ```js
*
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* hasRole: Sequelize.BelongsToManyHasAssociationMixin<RoleInstance, RoleId>;
* // hasRoles...
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
* @see Instance
*/
export type BelongsToManyHasAssociationMixin<TModel, TModelPrimaryKey> = (
target: TModel | TModelPrimaryKey,
options?: BelongsToManyHasAssociationMixinOptions
) => Promise<boolean>;
/**
* The options for the hasAssociations mixin of the belongsToMany association.
* @see BelongsToManyHasAssociationsMixin
*/
export interface BelongsToManyHasAssociationsMixinOptions extends BelongsToManyGetAssociationsMixinOptions {}
/**
* The removeAssociations mixin applied to models with belongsToMany.
* An example of usage is as follows:
*
* ```js
*
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles
* // hasRole...
* hasRoles: Sequelize.BelongsToManyHasAssociationsMixin<RoleInstance, RoleId>;
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
* @see Instance
*/
export type BelongsToManyHasAssociationsMixin<TModel, TModelPrimaryKey> = (
targets: (TModel | TModelPrimaryKey)[],
options?: BelongsToManyHasAssociationsMixinOptions
) => Promise<boolean>;
/**
* The options for the countAssociations mixin of the belongsToMany association.
* @see BelongsToManyCountAssociationsMixin
*/
export interface BelongsToManyCountAssociationsMixinOptions extends Transactionable, Filterable {
/**
* Apply a scope on the related model, or remove its default scope by passing false.
*/
scope?: string | boolean;
}
/**
* The countAssociations mixin applied to models with belongsToMany.
* An example of usage is as follows:
*
* ```js
*
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* countRoles: Sequelize.BelongsToManyCountAssociationsMixin;
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
* @see Instance
*/
export type BelongsToManyCountAssociationsMixin = (
options?: BelongsToManyCountAssociationsMixinOptions
) => Promise<number>;
import { DataType } from '../data-types';
import { CreateOptions, FindOptions, Model, SaveOptions } from '../model';
import { Promise } from '../promise';
import { Association, AssociationOptions, SingleAssociationAccessors } from './base';
/**
* Options provided when associating models with belongsTo relationship
*
* @see Association class belongsTo method
*/
export interface BelongsToOptions extends AssociationOptions {
/**
* The name of the field to use as the key for the association in the target table. Defaults to the primary
* key of the target table
*/
targetKey?: string;
/**
* A string or a data type to represent the identifier in the table
*/
keyType?: DataType;
}
export class BelongsTo extends Association {
public accessors: SingleAssociationAccessors;
constructor(source: typeof Model, target: typeof Model, options: BelongsToOptions);
}
/**
* The options for the getAssociation mixin of the belongsTo association.
* @see BelongsToGetAssociationMixin
*/
export interface BelongsToGetAssociationMixinOptions extends FindOptions {
/**
* Apply a scope on the related model, or remove its default scope by passing false.
*/
scope?: string | string[] | boolean;
}
/**
* The getAssociation mixin applied to models with belongsTo.
* An example of usage is as follows:
*
* ```js
*
* User.belongsTo(Role);
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttrib>, UserAttrib {
* getRole: Sequelize.BelongsToGetAssociationMixin<RoleInstance>;
* // setRole...
* // createRole...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to/
* @see Instance
*/
export type BelongsToGetAssociationMixin<TModel> = (options?: BelongsToGetAssociationMixinOptions) => Promise<TModel>;
/**
* The options for the setAssociation mixin of the belongsTo association.
* @see BelongsToSetAssociationMixin
*/
export interface BelongsToSetAssociationMixinOptions extends SaveOptions {
/**
* Skip saving this after setting the foreign key if false.
*/
save?: boolean;
}
/**
* The setAssociation mixin applied to models with belongsTo.
* An example of usage is as follows:
*
* ```js
*
* User.belongsTo(Role);
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRole...
* setRole: Sequelize.BelongsToSetAssociationMixin<RoleInstance, RoleId>;
* // createRole...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to/
* @see Instance
*/
export type BelongsToSetAssociationMixin<TModel, TPrimaryKey> = (
newAssociation?: TModel | TPrimaryKey,
options?: BelongsToSetAssociationMixinOptions
) => Promise<void>;
/**
* The options for the createAssociation mixin of the belongsTo association.
* @see BelongsToCreateAssociationMixin
*/
export interface BelongsToCreateAssociationMixinOptions extends CreateOptions, BelongsToSetAssociationMixinOptions {}
/**
* The createAssociation mixin applied to models with belongsTo.
* An example of usage is as follows:
*
* ```js
*
* User.belongsTo(Role);
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRole...
* // setRole...
* createRole: Sequelize.BelongsToCreateAssociationMixin<RoleAttributes>;
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to/
* @see Instance
*/
export type BelongsToCreateAssociationMixin<TModel> = (
values?: { [attribute: string]: any },
options?: BelongsToCreateAssociationMixinOptions
) => Promise<TModel>;
export default BelongsTo;
import { DataType } from '../data-types';
import {
CreateOptions,
Filterable,
FindOptions,
InstanceUpdateOptions,
Model,
Transactionable,
WhereOptions,
} from '../model';
import { Promise } from '../promise';
import { Transaction } from '../transaction';
import { Association, ManyToManyOptions, MultiAssociationAccessors } from './base';
/**
* Options provided when associating models with hasMany relationship
*/
export interface HasManyOptions extends ManyToManyOptions {
/**
* A string or a data type to represent the identifier in the table
*/
keyType?: DataType;
}
export class HasMany extends Association {
public accessors: MultiAssociationAccessors;
constructor(source: typeof Model, target: typeof Model, options: HasManyOptions);
}
/**
* The options for the getAssociations mixin of the hasMany association.
* @see HasManyGetAssociationsMixin
*/
export interface HasManyGetAssociationsMixinOptions extends FindOptions {
/**
* Apply a scope on the related model, or remove its default scope by passing false.
*/
scope?: string | string[] | boolean;
}
/**
* The getAssociations mixin applied to models with hasMany.
* An example of usage is as follows:
*
* ```js
*
* User.hasMany(Role);
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* getRoles: Sequelize.HasManyGetAssociationsMixin<RoleInstance>;
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
* @see Instance
*/
export type HasManyGetAssociationsMixin<TModel> = (options?: HasManyGetAssociationsMixinOptions) => Promise<TModel[]>;
/**
* The options for the setAssociations mixin of the hasMany association.
* @see HasManySetAssociationsMixin
*/
export interface HasManySetAssociationsMixinOptions extends FindOptions, InstanceUpdateOptions {}
/**
* The setAssociations mixin applied to models with hasMany.
* An example of usage is as follows:
*
* ```js
*
* User.hasMany(Role);
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* setRoles: Sequelize.HasManySetAssociationsMixin<RoleInstance, RoleId>;
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
* @see Instance
*/
export type HasManySetAssociationsMixin<TModel, TModelPrimaryKey> = (
newAssociations?: (TModel | TModelPrimaryKey)[],
options?: HasManySetAssociationsMixinOptions
) => Promise<void>;
/**
* The options for the addAssociations mixin of the hasMany association.
* @see HasManyAddAssociationsMixin
*/
export interface HasManyAddAssociationsMixinOptions extends InstanceUpdateOptions {}
/**
* The addAssociations mixin applied to models with hasMany.
* An example of usage is as follows:
*
* ```js
*
* User.hasMany(Role);
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* addRoles: Sequelize.HasManyAddAssociationsMixin<RoleInstance, RoleId>;
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
* @see Instance
*/
export type HasManyAddAssociationsMixin<TModel, TModelPrimaryKey> = (
newAssociations?: (TModel | TModelPrimaryKey)[],
options?: HasManyAddAssociationsMixinOptions
) => Promise<void>;
/**
* The options for the addAssociation mixin of the hasMany association.
* @see HasManyAddAssociationMixin
*/
export interface HasManyAddAssociationMixinOptions extends InstanceUpdateOptions {}
/**
* The addAssociation mixin applied to models with hasMany.
* An example of usage is as follows:
*
* ```js
*
* User.hasMany(Role);
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* addRole: Sequelize.HasManyAddAssociationMixin<RoleInstance, RoleId>;
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
* @see Instance
*/
export type HasManyAddAssociationMixin<TModel, TModelPrimaryKey> = (
newAssociation?: TModel | TModelPrimaryKey,
options?: HasManyAddAssociationMixinOptions
) => Promise<void>;
/**
* The options for the createAssociation mixin of the hasMany association.
* @see HasManyCreateAssociationMixin
*/
export interface HasManyCreateAssociationMixinOptions extends CreateOptions {}
/**
* The createAssociation mixin applied to models with hasMany.
* An example of usage is as follows:
*
* ```js
*
* User.hasMany(Role);
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* createRole: Sequelize.HasManyCreateAssociationMixin<RoleAttributes>;
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
* @see Instance
*/
export type HasManyCreateAssociationMixin<TModel> = (
values?: { [attribute: string]: any },
options?: HasManyCreateAssociationMixinOptions
) => Promise<TModel>;
/**
* The options for the removeAssociation mixin of the hasMany association.
* @see HasManyRemoveAssociationMixin
*/
export interface HasManyRemoveAssociationMixinOptions extends InstanceUpdateOptions {}
/**
* The removeAssociation mixin applied to models with hasMany.
* An example of usage is as follows:
*
* ```js
*
* User.hasMany(Role);
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* removeRole: Sequelize.HasManyRemoveAssociationMixin<RoleInstance, RoleId>;
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
* @see Instance
*/
export type HasManyRemoveAssociationMixin<TModel, TModelPrimaryKey> = (
oldAssociated?: TModel | TModelPrimaryKey,
options?: HasManyRemoveAssociationMixinOptions
) => Promise<void>;
/**
* The options for the removeAssociations mixin of the hasMany association.
* @see HasManyRemoveAssociationsMixin
*/
export interface HasManyRemoveAssociationsMixinOptions extends InstanceUpdateOptions {}
/**
* The removeAssociations mixin applied to models with hasMany.
* An example of usage is as follows:
*
* ```js
*
* User.hasMany(Role);
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* removeRoles: Sequelize.HasManyRemoveAssociationsMixin<RoleInstance, RoleId>;
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
* @see Instance
*/
export type HasManyRemoveAssociationsMixin<TModel, TModelPrimaryKey> = (
oldAssociateds?: (TModel | TModelPrimaryKey)[],
options?: HasManyRemoveAssociationsMixinOptions
) => Promise<void>;
/**
* The options for the hasAssociation mixin of the hasMany association.
* @see HasManyHasAssociationMixin
*/
export interface HasManyHasAssociationMixinOptions extends HasManyGetAssociationsMixinOptions {}
/**
* The hasAssociation mixin applied to models with hasMany.
* An example of usage is as follows:
*
* ```js
*
* User.hasMany(Role);
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* hasRole: Sequelize.HasManyHasAssociationMixin<RoleInstance, RoleId>;
* // hasRoles...
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
* @see Instance
*/
export type HasManyHasAssociationMixin<TModel, TModelPrimaryKey> = (
target: TModel | TModelPrimaryKey,
options?: HasManyHasAssociationMixinOptions
) => Promise<boolean>;
/**
* The options for the hasAssociations mixin of the hasMany association.
* @see HasManyHasAssociationsMixin
*/
export interface HasManyHasAssociationsMixinOptions extends HasManyGetAssociationsMixinOptions {}
/**
* The removeAssociations mixin applied to models with hasMany.
* An example of usage is as follows:
*
* ```js
*
* User.hasMany(Role);
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles
* // hasRole...
* hasRoles: Sequelize.HasManyHasAssociationsMixin<RoleInstance, RoleId>;
* // countRoles...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
* @see Instance
*/
export type HasManyHasAssociationsMixin<TModel, TModelPrimaryKey> = (
targets: (TModel | TModelPrimaryKey)[],
options?: HasManyHasAssociationsMixinOptions
) => Promise<boolean>;
/**
* The options for the countAssociations mixin of the hasMany association.
* @see HasManyCountAssociationsMixin
*/
export interface HasManyCountAssociationsMixinOptions extends Transactionable, Filterable {
/**
* Apply a scope on the related model, or remove its default scope by passing false.
*/
scope?: string | boolean;
}
/**
* The countAssociations mixin applied to models with hasMany.
* An example of usage is as follows:
*
* ```js
*
* User.hasMany(Role);
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* countRoles: Sequelize.HasManyCountAssociationsMixin;
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
* @see Instance
*/
export type HasManyCountAssociationsMixin = (options?: HasManyCountAssociationsMixinOptions) => Promise<number>;
import { DataType } from '../data-types';
import { CreateOptions, FindOptions, Model, SaveOptions } from '../model';
import { Promise } from '../promise';
import { Association, AssociationOptions, SingleAssociationAccessors } from './base';
/**
* Options provided when associating models with hasOne relationship
*/
export interface HasOneOptions extends AssociationOptions {
/**
* A string or a data type to represent the identifier in the table
*/
keyType?: DataType;
}
export class HasOne extends Association {
public accessors: SingleAssociationAccessors;
constructor(source: typeof Model, target: typeof Model, options: HasOneOptions);
}
/**
* The options for the getAssociation mixin of the hasOne association.
* @see HasOneGetAssociationMixin
*/
export interface HasOneGetAssociationMixinOptions extends FindOptions {
/**
* Apply a scope on the related model, or remove its default scope by passing false.
*/
scope?: string | string[] | boolean;
}
/**
* The getAssociation mixin applied to models with hasOne.
* An example of usage is as follows:
*
* ```js
*
* User.hasOne(Role);
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttrib>, UserAttrib {
* getRole: Sequelize.HasOneGetAssociationMixin<RoleInstance>;
* // setRole...
* // createRole...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/has-one/
* @see Instance
*/
export type HasOneGetAssociationMixin<TModel> = (options?: HasOneGetAssociationMixinOptions) => Promise<TModel>;
/**
* The options for the setAssociation mixin of the hasOne association.
* @see HasOneSetAssociationMixin
*/
export interface HasOneSetAssociationMixinOptions extends HasOneGetAssociationMixinOptions, SaveOptions {
/**
* Skip saving this after setting the foreign key if false.
*/
save?: boolean;
}
/**
* The setAssociation mixin applied to models with hasOne.
* An example of usage is as follows:
*
* ```js
*
* User.hasOne(Role);
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRole...
* setRole: Sequelize.HasOneSetAssociationMixin<RoleInstance, RoleId>;
* // createRole...
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/has-one/
* @see Instance
*/
export type HasOneSetAssociationMixin<TModel, TModelPrimaryKey> = (
newAssociation?: TModel | TModelPrimaryKey,
options?: HasOneSetAssociationMixinOptions
) => Promise<void>;
/**
* The options for the createAssociation mixin of the hasOne association.
* @see HasOneCreateAssociationMixin
*/
export interface HasOneCreateAssociationMixinOptions extends HasOneSetAssociationMixinOptions, CreateOptions {}
/**
* The createAssociation mixin applied to models with hasOne.
* An example of usage is as follows:
*
* ```js
*
* User.hasOne(Role);
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRole...
* // setRole...
* createRole: Sequelize.HasOneCreateAssociationMixin<RoleAttributes>;
* }
* ```
*
* @see http://docs.sequelizejs.com/en/latest/api/associations/has-one/
* @see Instance
*/
export type HasOneCreateAssociationMixin<TModel> = (
values?: { [attribute: string]: any },
options?: HasOneCreateAssociationMixinOptions
) => Promise<TModel>;
export * from './base';
export * from './belongs-to';
export * from './has-one';
export * from './has-many';
export * from './belongs-to-many';
import { Promise } from './promise';
export interface GetConnectionOptions {
/**
* Set which replica to use. Available options are `read` and `write`
*/
type: 'read' | 'write';
/**
* Force master or write replica to get connection from
*/
useMaster?: boolean;
}
export type Connection = object;
export interface ConnectionManager {
refreshTypeParser(dataTypes: object): void;
/**
* Drain the pool and close it permanently
*/
close(): Promise<void>;
/**
* Initialize connection pool. By default pool autostart is set to false, so no connection will be
* be created unless `pool.acquire` is called.
*/
initPools(): void;
/**
* Get connection from pool. It sets database version if it's not already set.
* Call pool.acquire to get a connection.
*/
getConnection(opts: GetConnectionOptions): Promise<Connection>;
/**
* Release a pooled connection so it can be utilized by other connection requests
*/
releaseConnection(conn: Connection): Promise<void>;
}
/**
* The datatypes are used when defining a new model using `Sequelize.define`, like this:
* ```js
* sequelize.define('model', {
* column: DataTypes.INTEGER
* })
* ```
* When defining a model you can just as easily pass a string as type, but often using the types defined here is beneficial. For example, using `DataTypes.BLOB`, mean
* that that column will be returned as an instance of `Buffer` when being fetched by sequelize.
*
* Some data types have special properties that can be accessed in order to change the data type.
* For example, to get an unsigned integer with zerofill you can do `DataTypes.INTEGER.UNSIGNED.ZEROFILL`.
* The order you access the properties in do not matter, so `DataTypes.INTEGER.ZEROFILL.UNSIGNED` is fine as well. The available properties are listed under each data type.
*
* To provide a length for the data type, you can invoke it like a function: `INTEGER(2)`
*
* Three of the values provided here (`NOW`, `UUIDV1` and `UUIDV4`) are special default values, that should not be used to define types. Instead they are used as shorthands for
* defining default values. For example, to get a uuid field with a default value generated following v1 of the UUID standard:
* ```js
* sequelize.define('model', {
* uuid: {
* type: DataTypes.UUID,
* defaultValue: DataTypes.UUIDV1,
* primaryKey: true
* }
* })
* ```
* There may be times when you want to generate your own UUID conforming to some other algorithm. This is accomplised
* using the defaultValue property as well, but instead of specifying one of the supplied UUID types, you return a value
* from a function.
* ```js
* sequelize.define('model', {
* uuid: {
* type: DataTypes.UUID,
* defaultValue: function() {
* return generateMyId()
* },
* primaryKey: true
* }
* })
* ```
*/
/**
*
*/
export type DataType = string | AbstractDataTypeConstructor | AbstractDataType;
export const ABSTRACT: AbstractDataTypeConstructor;
interface AbstractDataTypeConstructor {
key: string;
warn(link: string, text: string): void;
}
export interface AbstractDataType {
key: string;
dialectTypes: string;
toSql(): string;
stringify(value: unknown, options?: object): string;
toString(options: object): string;
}
/**
* A variable length string. Default length 255
*
* Available properties: `BINARY`
*/
export const STRING: StringDataTypeConstructor;
interface StringDataTypeConstructor extends AbstractDataTypeConstructor {
new (length?: number, binary?: boolean): StringDataType;
new (options?: StringDataTypeOptions): StringDataType;
(length?: number, binary?: boolean): StringDataType;
(options?: StringDataTypeOptions): StringDataType;
}
export interface StringDataType extends AbstractDataType {
options?: StringDataTypeOptions;
BINARY: this;
validate(value: any): boolean;
}
export interface StringDataTypeOptions {
length?: number;
binary?: boolean;
}
/**
* A fixed length string. Default length 255
*
* Available properties: `BINARY`
*
*/
export const CHAR: CharDataTypeConstructor;
interface CharDataTypeConstructor extends StringDataTypeConstructor {
new (length?: number, binary?: boolean): CharDataType;
new (options?: CharDataTypeOptions): CharDataType;
(length?: number, binary?: boolean): CharDataType;
(options?: CharDataTypeOptions): CharDataType;
}
export interface CharDataType extends StringDataType {
options: CharDataTypeOptions;
}
export interface CharDataTypeOptions extends StringDataTypeOptions {}
/**
* An (un)limited length text column. Available lengths: `tiny`, `medium`, `long`
*/
export const TEXT: TextDataTypeConstructor;
interface TextDataTypeConstructor extends AbstractDataTypeConstructor {
new (length?: number): TextDataType;
(options?: TextDataTypeOptions): TextDataType;
}
export interface TextDataType extends AbstractDataType {
options: TextDataTypeOptions;
validate(value: any): boolean;
}
export interface TextDataTypeOptions {
length?: number;
}
export const NUMBER: NumberDataTypeConstructor;
interface NumberDataTypeConstructor extends AbstractDataTypeConstructor {
options: NumberDataTypeOptions;
UNSIGNED: this;
ZEROFILL: this;
new (options?: NumberDataTypeOptions): NumberDataType;
(options?: NumberDataTypeOptions): NumberDataType;
validate(value: any): boolean;
}
export interface NumberDataType extends AbstractDataType {
options: NumberDataTypeOptions;
UNSIGNED: this;
ZEROFILL: this;
validate(value: any): boolean;
}
export interface NumberDataTypeOptions {
length?: number;
zerofill?: boolean;
decimals?: number;
precision?: number;
scale?: number;
unsigned?: boolean;
}
/**
* A 32 bit integer.
*
* Available properties: `UNSIGNED`, `ZEROFILL`
*
*/
export const INTEGER: IntegerDataTypeConstructor;
interface IntegerDataTypeConstructor extends NumberDataTypeConstructor {
new (options?: NumberDataTypeOptions): IntegerDataType;
(options?: NumberDataTypeOptions): IntegerDataType;
}
export interface IntegerDataType extends NumberDataType {
options: NumberDataTypeOptions;
}
export interface IntegerDataTypeOptions {
length?: number;
}
/**
* A 64 bit integer.
*
* Available properties: `UNSIGNED`, `ZEROFILL`
*
*/
export const BIGINT: BigIntDataTypeConstructor;
interface BigIntDataTypeConstructor extends NumberDataTypeConstructor {
new (options?: BigIntDataTypeOptions): BigIntDataType;
(options?: BigIntDataTypeOptions): BigIntDataType;
}
export interface BigIntDataType extends NumberDataType {
options: BigIntDataTypeOptions;
}
export interface BigIntDataTypeOptions {
length?: number;
}
/**
* Floating point number (4-byte precision). Accepts one or two arguments for precision
*/
export const FLOAT: FloatDataTypeConstructor;
interface FloatDataTypeConstructor extends NumberDataTypeConstructor {
new (length?: number, decimals?: number): FloatDataType;
new (options?: FloatDataTypeOptions): FloatDataType;
(length?: number, decimals?: number): FloatDataType;
(options?: FloatDataTypeOptions): FloatDataType;
}
export interface FloatDataType extends NumberDataType {
options: FloatDataTypeOptions;
}
export interface FloatDataTypeOptions {
length?: number;
decimals?: number;
}
/**
* Floating point number (4-byte precision). Accepts one or two arguments for precision
*/
export const REAL: RealDataTypeConstructor;
interface RealDataTypeConstructor extends NumberDataTypeConstructor {
new (length?: number, decimals?: number): RealDataType;
new (options?: RealDataTypeOptions): RealDataType;
(length?: number, decimals?: number): RealDataType;
(options?: RealDataTypeOptions): RealDataType;
}
export interface RealDataType extends NumberDataType {
options: RealDataTypeOptions;
}
export interface RealDataTypeOptions {
length?: number;
decimals?: number;
}
/**
* Floating point number (8-byte precision). Accepts one or two arguments for precision
*/
export const DOUBLE: DoubleDataTypeConstructor;
interface DoubleDataTypeConstructor extends NumberDataTypeConstructor {
new (length?: number, decimals?: number): DoubleDataType;
new (options?: DoubleDataTypeOptions): DoubleDataType;
(length?: number, decimals?: number): DoubleDataType;
(options?: DoubleDataTypeOptions): DoubleDataType;
}
export interface DoubleDataType extends NumberDataType {
options: DoubleDataTypeOptions;
}
export interface DoubleDataTypeOptions {
length?: number;
decimals?: number;
}
/**
* Decimal number. Accepts one or two arguments for precision
*/
export const DECIMAL: DecimalDataTypeConstructor;
interface DecimalDataTypeConstructor extends NumberDataTypeConstructor {
PRECISION: this;
SCALE: this;
new (precision?: number, scale?: number): DecimalDataType;
new (options?: DecimalDataTypeOptions): DecimalDataType;
(precision?: number, scale?: number): DecimalDataType;
(options?: DecimalDataTypeOptions): DecimalDataType;
}
export interface DecimalDataType extends NumberDataType {
options: DecimalDataTypeOptions;
}
export interface DecimalDataTypeOptions {
precision?: number;
scale?: number;
}
/**
* A boolean / tinyint column, depending on dialect
*/
export const BOOLEAN: AbstractDataTypeConstructor;
/**
* A time column
*/
export const TIME: AbstractDataTypeConstructor;
/**
* A datetime column
*/
export const DATE: DateDataTypeConstructor;
interface DateDataTypeConstructor extends AbstractDataTypeConstructor {
new (length?: any): DateDataType;
new (options?: DateDataTypeOptions): DateDataType;
(length?: any): DateDataType;
(options?: DateDataTypeOptions): DateDataType;
}
export interface DateDataType extends AbstractDataTypeConstructor {
options: DateDataTypeOptions;
}
export interface DateDataTypeOptions {
length?: any;
}
/**
* A date only column
*/
export const DATEONLY: DateOnlyDataTypeConstructor;
interface DateOnlyDataTypeConstructor extends AbstractDataTypeConstructor {
new (length: any): DateOnlyDataType;
new (options: DateOnlyDataTypeOptions): DateOnlyDataType;
(length: any): DateOnlyDataType;
(options: DateOnlyDataTypeOptions): DateOnlyDataType;
}
export interface DateOnlyDataType extends AbstractDataType {
options: DateOnlyDataTypeOptions;
}
export interface DateOnlyDataTypeOptions {
length?: any;
}
/**
* A key / value column. Only available in postgres.
*/
export const HSTORE: AbstractDataTypeConstructor;
/**
* A JSON string column. Only available in postgres.
*/
export const JSON: AbstractDataTypeConstructor;
/**
* A pre-processed JSON data column. Only available in postgres.
*/
export const JSONB: AbstractDataTypeConstructor;
/**
* A default value of the current timestamp
*/
export const NOW: AbstractDataTypeConstructor;
/**
* Binary storage. Available lengths: `tiny`, `medium`, `long`
*/
export const BLOB: BlobDataTypeConstructor;
export type BlobSize = 'tiny' | 'medium' | 'long';
interface BlobDataTypeConstructor extends AbstractDataTypeConstructor {
new (length?: BlobSize): BlobDataType;
new (options?: BlobDataTypeOptions): BlobDataType;
(length?: BlobSize): BlobDataType;
(options?: BlobDataTypeOptions): BlobDataType;
}
export interface BlobDataType extends AbstractDataType {
options: BlobDataTypeOptions;
escape: boolean;
}
export interface BlobDataTypeOptions {
length?: BlobSize;
escape?: boolean;
}
/**
* Range types are data types representing a range of values of some element type (called the range's subtype).
* Only available in postgres.
*
* See [Postgres documentation](http://www.postgresql.org/docs/9.4/static/rangetypes.html) for more details
*/
export const RANGE: RangeDataTypeConstructor;
export type RangeableDataType =
| IntegerDataTypeConstructor
| IntegerDataType
| BigIntDataTypeConstructor
| BigIntDataType
| DecimalDataTypeConstructor
| DecimalDataType
| DateOnlyDataTypeConstructor
| DateOnlyDataType
| DateDataTypeConstructor
| DateDataType;
interface RangeDataTypeConstructor extends AbstractDataTypeConstructor {
new <T extends RangeableDataType>(subtype?: T): RangeDataType<T>;
new <T extends RangeableDataType>(options: RangeDataTypeOptions<T>): RangeDataType<T>;
<T extends RangeableDataType>(subtype?: T): RangeDataType<T>;
<T extends RangeableDataType>(options: RangeDataTypeOptions<T>): RangeDataType<T>;
}
export interface RangeDataType<T extends RangeableDataType> extends AbstractDataType {
options: RangeDataTypeOptions<T>;
}
export interface RangeDataTypeOptions<T extends RangeableDataType> {
subtype?: T;
}
/**
* A column storing a unique universal identifier. Use with `UUIDV1` or `UUIDV4` for default values.
*/
export const UUID: AbstractDataTypeConstructor;
/**
* A default unique universal identifier generated following the UUID v1 standard
*/
export const UUIDV1: AbstractDataTypeConstructor;
/**
* A default unique universal identifier generated following the UUID v4 standard
*/
export const UUIDV4: AbstractDataTypeConstructor;
/**
* A virtual value that is not stored in the DB. This could for example be useful if you want to provide a default value in your model that is returned to the user but not stored in the DB.
*
* You could also use it to validate a value before permuting and storing it. Checking password length before hashing it for example:
* ```js
* sequelize.define('user', {
* password_hash: DataTypes.STRING,
* password: {
* type: DataTypes.VIRTUAL,
* set: function (val) {
* this.setDataValue('password', val); // Remember to set the data value, otherwise it won't be validated
* this.setDataValue('password_hash', this.salt + val);
* },
* validate: {
* isLongEnough: function (val) {
* if (val.length < 7) {
* throw new Error("Please choose a longer password")
* }
* }
* }
* }
* })
* ```
*
* VIRTUAL also takes a return type and dependency fields as arguments
* If a virtual attribute is present in `attributes` it will automatically pull in the extra fields as well.
* Return type is mostly useful for setups that rely on types like GraphQL.
* ```js
* {
* active: {
* type: new DataTypes.VIRTUAL(DataTypes.BOOLEAN, ['createdAt']),
* get: function() {
* return this.get('createdAt') > Date.now() - (7 * 24 * 60 * 60 * 1000)
* }
* }
* }
* ```
*
* In the above code the password is stored plainly in the password field so it can be validated, but is never stored in the DB.
*/
export const VIRTUAL: VirtualDataTypeConstructor;
interface VirtualDataTypeConstructor extends AbstractDataTypeConstructor {
new <T extends AbstractDataTypeConstructor | AbstractDataType>(ReturnType: T, fields?: string[]): VirtualDataType<
T
>;
<T extends AbstractDataTypeConstructor | AbstractDataType>(ReturnType: T, fields?: string[]): VirtualDataType<T>;
}
export interface VirtualDataType<T extends AbstractDataTypeConstructor | AbstractDataType> extends AbstractDataType {
returnType: T;
fields: string[];
}
/**
* An enumeration. `DataTypes.ENUM('value', 'another value')`.
*/
export const ENUM: EnumDataTypeConstructor;
interface EnumDataTypeConstructor extends AbstractDataTypeConstructor {
new <T extends string>(...values: T[]): EnumDataType<T>;
new <T extends string>(options: EnumDataTypeOptions<T>): EnumDataType<T>;
<T extends string>(...values: T[]): EnumDataType<T>;
<T extends string>(options: EnumDataTypeOptions<T>): EnumDataType<T>;
}
export interface EnumDataType<T extends string> extends AbstractDataType {
values: T[];
options: EnumDataTypeOptions<T>;
}
export interface EnumDataTypeOptions<T extends string> {
values: T[];
}
/**
* An array of `type`, e.g. `DataTypes.ARRAY(DataTypes.DECIMAL)`. Only available in postgres.
*/
export const ARRAY: ArrayDataTypeConstructor;
interface ArrayDataTypeConstructor extends AbstractDataTypeConstructor {
new <T extends AbstractDataTypeConstructor | AbstractDataType>(type: T): ArrayDataType<T>;
new <T extends AbstractDataTypeConstructor | AbstractDataType>(options: ArrayDataTypeOptions<T>): ArrayDataType<T>;
<T extends AbstractDataTypeConstructor | AbstractDataType>(type: T): ArrayDataType<T>;
<T extends AbstractDataTypeConstructor | AbstractDataType>(options: ArrayDataTypeOptions<T>): ArrayDataType<T>;
is<T extends AbstractDataTypeConstructor | AbstractDataType>(obj: any, type: T): obj is ArrayDataType<T>;
}
export interface ArrayDataType<T extends AbstractDataTypeConstructor | AbstractDataType> extends AbstractDataType {
options: ArrayDataTypeOptions<T>;
}
export interface ArrayDataTypeOptions<T extends AbstractDataTypeConstructor | AbstractDataType> {
type: T;
}
/**
* A geometry datatype represents two dimensional spacial objects.
*/
export const GEOMETRY: GeometryDataTypeConstructor;
interface GeometryDataTypeConstructor extends AbstractDataTypeConstructor {
new (type: string, srid?: number): GeometryDataType;
new (options: GeometryDataTypeOptions): GeometryDataType;
(type: string, srid?: number): GeometryDataType;
(options: GeometryDataTypeOptions): GeometryDataType;
}
export interface GeometryDataType extends AbstractDataType {
options: GeometryDataTypeOptions;
type: string;
srid?: number;
escape: boolean;
}
export interface GeometryDataTypeOptions {
type: string;
srid?: number;
}
/**
* A geography datatype represents two dimensional spacial objects in an elliptic coord system.
*/
export const GEOGRAPHY: GeographyDataTypeConstructor;
interface GeographyDataTypeConstructor extends AbstractDataTypeConstructor {
new (type: string, srid?: number): GeographyDataType;
new (options: GeographyDataTypeOptions): GeographyDataType;
(type: string, srid?: number): GeographyDataType;
(options: GeographyDataTypeOptions): GeographyDataType;
}
export interface GeographyDataType extends AbstractDataType {
options: GeographyDataTypeOptions;
type: string;
srid?: number;
escape: boolean;
}
export interface GeographyDataTypeOptions {
type: string;
srid?: number;
}
export const CIDR: AbstractDataTypeConstructor;
export const INET: AbstractDataTypeConstructor;
export const MACADDR: AbstractDataTypeConstructor;
/**
* Case incenstive text
*/
export const CITEXT: AbstractDataTypeConstructor;
// umzug compatibility
export type DataTypeAbstract = AbstractDataTypeConstructor;
/**
* Can be used to
* make foreign key constraints deferrable and to set the constaints within a
* transaction. This is only supported in PostgreSQL.
*
* The foreign keys can be configured like this. It will create a foreign key
* that will check the constraints immediately when the data was inserted.
*
* ```js
* sequelize.define('Model', {
* foreign_id: {
* type: Sequelize.INTEGER,
* references: {
* model: OtherModel,
* key: 'id',
* deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE
* }
* }
* });
* ```
*
* The constraints can be configured in a transaction like this. It will
* trigger a query once the transaction has been started and set the constraints
* to be checked at the very end of the transaction.
*
* ```js
* sequelize.transaction({
* deferrable: Sequelize.Deferrable.SET_DEFERRED
* });
* ```
*/
/**
*
*/
export interface AbstractDeferrableStatic {
new (): Deferrable;
(): Deferrable;
}
export interface Deferrable {
toString(): string;
toSql(): string;
}
export interface InitiallyDeferredDeferrableStatic extends AbstractDeferrableStatic {
new (): InitiallyDeferredDeferrable;
(): InitiallyDeferredDeferrable;
}
export interface InitiallyDeferredDeferrable extends Deferrable {}
export const INITIALLY_DEFERRED: InitiallyDeferredDeferrableStatic;
export interface InitiallyImmediateDeferrableStatic extends AbstractDeferrableStatic {
new (): InitiallyImmediateDeferrable;
(): InitiallyImmediateDeferrable;
}
export interface InitiallyImmediateDeferrable extends Deferrable {}
export const INITIALLY_IMMEDIATE: InitiallyImmediateDeferrableStatic;
export interface NotDeferrableStatic extends AbstractDeferrableStatic {
new (): NotDeferrable;
(): NotDeferrable;
}
export interface NotDeferrable extends Deferrable {}
/**
* Will set the constraints to not deferred. This is the default in PostgreSQL and it make
* it impossible to dynamically defer the constraints within a transaction.
*/
export const NOT: NotDeferrableStatic;
export interface SetDeferredDeferrableStatic extends AbstractDeferrableStatic {
/**
* @param constraints An array of constraint names. Will defer all constraints by default.
*/
new (constraints: string[]): SetDeferredDeferrable;
/**
* @param constraints An array of constraint names. Will defer all constraints by default.
*/
(constraints: string[]): SetDeferredDeferrable;
}
export interface SetDeferredDeferrable extends Deferrable {}
/**
* Will trigger an additional query at the beginning of a
* transaction which sets the constraints to deferred.
*/
export const SET_DEFERRED: SetDeferredDeferrableStatic;
export interface SetImmediateDeferrableStatic extends AbstractDeferrableStatic {
/**
* @param constraints An array of constraint names. Will defer all constraints by default.
*/
new (constraints: string[]): SetImmediateDeferrable;
/**
* @param constraints An array of constraint names. Will defer all constraints by default.
*/
(constraints: string[]): SetImmediateDeferrable;
}
export interface SetImmediateDeferrable extends Deferrable {}
/**
* Will trigger an additional query at the beginning of a
* transaction which sets the constraints to immediately.
*
* @param constraints An array of constraint names. Will defer all constraints by default.
*/
export const SET_IMMEDIATE: SetImmediateDeferrableStatic;
/**
* The Base Error all Sequelize Errors inherit from.
*/
export class BaseError extends Error {
public name: string;
}
/**
* Scope Error. Thrown when the sequelize cannot query the specified scope.
*/
export class SequelizeScopeError extends BaseError {}
export class ValidationError extends BaseError {
/** Array of ValidationErrorItem objects describing the validation errors */
public readonly errors: ValidationErrorItem[];
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors`
* property, which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param message Error message
* @param errors Array of ValidationErrorItem objects describing the validation errors
*/
constructor(message: string, errors?: ValidationErrorItem[]);
/**
* Gets all validation error items for the path / field specified.
*
* @param path The path to be checked for error items
*/
public get(path: string): ValidationErrorItem[];
}
export class ValidationErrorItem {
/** An error message */
public readonly message: string;
/** The type of the validation error */
public readonly type: string;
/** The field that triggered the validation error */
public readonly path: string;
/** The value that generated the error */
public readonly value: string;
public readonly original: Error;
/**
* Validation Error Item
* Instances of this class are included in the `ValidationError.errors` property.
*
* @param message An error message
* @param type The type of the validation error
* @param path The field that triggered the validation error
* @param value The value that generated the error
*/
constructor(message?: string, type?: string, path?: string, value?: string);
}
export interface CommonErrorProperties {
/** The database specific error which triggered this one */
readonly parent: Error;
/** The database specific error which triggered this one */
readonly original: Error;
/** The SQL that triggered the error */
readonly sql: string;
}
/**
* Thrown when a record was not found, Usually used with rejectOnEmpty mode (see message for details)
*/
export class EmptyResultError extends BaseError {
}
export class DatabaseError extends BaseError implements CommonErrorProperties {
public readonly parent: Error;
public readonly original: Error;
public readonly sql: string;
/**
* A base class for all database related errors.
* @param parent The database specific error which triggered this one
*/
constructor(parent: Error);
}
/** Thrown when a database query times out because of a deadlock */
export class TimeoutError extends DatabaseError {}
export interface UniqueConstraintErrorOptions {
parent?: Error;
message?: string;
errors?: ValidationErrorItem[];
fields?: { [key: string]: any };
original?: Error;
}
/**
* Thrown when a unique constraint is violated in the database
*/
export class UniqueConstraintError extends ValidationError implements CommonErrorProperties {
public readonly parent: Error;
public readonly original: Error;
public readonly sql: string;
public readonly fields: { [key: string]: any };
constructor(options?: UniqueConstraintErrorOptions);
}
/**
* Thrown when a foreign key constraint is violated in the database
*/
export class ForeignKeyConstraintError extends DatabaseError {
public table: string;
public fields: { [field: string]: string };
public value: any;
public index: string;
constructor(options: { parent?: Error; message?: string; index?: string; fields?: string[]; table?: string });
}
/**
* Thrown when an exclusion constraint is violated in the database
*/
export class ExclusionConstraintError extends DatabaseError {
public constraint: string;
public fields: { [field: string]: string };
public table: string;
constructor(options: { parent?: Error; message?: string; constraint?: string; fields?: string[]; table?: string });
}
/**
* A base class for all connection related errors.
*/
export class ConnectionError extends BaseError {
public parent: Error;
public original: Error;
constructor(parent: Error);
}
/**
* Thrown when a connection to a database is refused
*/
export class ConnectionRefusedError extends ConnectionError {}
/**
* Thrown when a connection to a database is refused due to insufficient privileges
*/
export class AccessDeniedError extends ConnectionError {}
/**
* Thrown when a connection to a database has a hostname that was not found
*/
export class HostNotFoundError extends ConnectionError {}
/**
* Thrown when a connection to a database has a hostname that was not reachable
*/
export class HostNotReachableError extends ConnectionError {}
/**
* Thrown when a connection to a database has invalid values for any of the connection parameters
*/
export class InvalidConnectionError extends ConnectionError {}
/**
* Thrown when a connection to a database times out
*/
export class ConnectionTimedOutError extends ConnectionError {}
import { ValidationOptions } from './instance-validator';
import Model, {
BulkCreateOptions,
CountOptions,
CreateOptions,
DestroyOptions,
FindOptions,
InstanceDestroyOptions,
InstanceUpdateOptions,
ModelAttributes,
ModelOptions,
UpdateOptions,
} from './model';
import { Config, Options, Sequelize, SyncOptions } from './sequelize';
export type HookReturn = Promise<void> | void;
/**
* Options for Model.init. We mostly duplicate the Hooks here, since there is no way to combine the two
* interfaces.
*/
export interface ModelHookOptions<M extends Model = Model> {
beforeValidate(instance: M, options: ValidationOptions): HookReturn;
afterValidate(instance: M, options: ValidationOptions): HookReturn;
beforeCreate(attributes: M, options: CreateOptions): HookReturn;
afterCreate(attributes: M, options: CreateOptions): HookReturn;
beforeDestroy(instance: M, options: InstanceDestroyOptions): HookReturn;
afterDestroy(instance: M, options: InstanceDestroyOptions): HookReturn;
beforeUpdate(instance: M, options: InstanceUpdateOptions): HookReturn;
afterUpdate(instance: M, options: InstanceUpdateOptions): HookReturn;
beforeBulkCreate(instances: M[], options: BulkCreateOptions): HookReturn;
afterBulkCreate(instances: M[], options: BulkCreateOptions): HookReturn;
beforeBulkDestroy(options: DestroyOptions): HookReturn;
afterBulkDestroy(options: DestroyOptions): HookReturn;
beforeBulkUpdate(options: UpdateOptions): HookReturn;
afterBulkUpdate(options: UpdateOptions): HookReturn;
beforeFind(options: FindOptions): HookReturn;
beforeCount(options: CountOptions): HookReturn;
beforeFindAfterExpandIncludeAll(options: FindOptions): HookReturn;
beforeFindAfterOptions(options: FindOptions): HookReturn;
afterFind(instancesOrInstance: M[] | M, options: FindOptions): HookReturn;
beforeSync(options: SyncOptions): HookReturn;
afterSync(options: SyncOptions): HookReturn;
beforeBulkSync(options: SyncOptions): HookReturn;
afterBulkSync(options: SyncOptions): HookReturn;
}
export interface AllModelHooks extends ModelHookOptions {
beforeDefine(attributes: ModelAttributes, options: ModelOptions<Model>): void;
afterDefine(model: typeof Model): void;
beforeInit(config: Config, options: Options): void;
afterInit(sequelize: Sequelize): void;
}
export interface SequelizeHooks extends AllModelHooks {
beforeConnect(config: Config): HookReturn;
afterConnect(connection: any, config: Config): HookReturn;
}
/**
* Virtual class for deduplication
*/
export class Hooks {
/**
* Add a hook to the model
*
* @param name Provide a name for the hook function. It can be used to remove the hook later or to order
* hooks based on some sort of priority system in the future.
*/
public static addHook<C extends typeof Hooks, K extends keyof SequelizeHooks>(
hookType: K,
name: string,
fn: SequelizeHooks[K]
): C;
public static addHook<C extends typeof Hooks, K extends keyof SequelizeHooks>(
hookType: K,
fn: SequelizeHooks[K]
): C;
/**
* Remove hook from the model
*/
public static removeHook<C extends typeof Hooks, K extends keyof SequelizeHooks>(hookType: K, name: string): C;
/**
* Check whether the mode has any hooks of this type
*/
public static hasHook<K extends keyof SequelizeHooks>(hookType: K): boolean;
public static hasHooks<K extends keyof SequelizeHooks>(hookType: K): boolean;
/**
* Add a hook to the model
*
* @param name Provide a name for the hook function. It can be used to remove the hook later or to order
* hooks based on some sort of priority system in the future.
*/
public addHook<K extends keyof SequelizeHooks>(hookType: K, name: string, fn: SequelizeHooks[K]): this;
public addHook<K extends keyof SequelizeHooks>(hookType: K, fn: SequelizeHooks[K]): this;
/**
* Remove hook from the model
*/
public removeHook<K extends keyof SequelizeHooks>(hookType: K, name: string): this;
/**
* Check whether the mode has any hooks of this type
*/
public hasHook<K extends keyof SequelizeHooks>(hookType: K): boolean;
public hasHooks<K extends keyof SequelizeHooks>(hookType: K): boolean;
}
export interface ValidationOptions {
/**
* An array of strings. All properties that are in this array will not be validated
*/
skip?: string[];
/**
* An array of strings. Only the properties that are in this array will be validated
*/
fields?: string[];
/**
* Run before and after validate hooks.
* @default true.
*/
hooks?: boolean;
}
import { Model } from './model';
import { Sequelize } from './sequelize';
export class ModelManager {
public sequelize: Sequelize;
public models: typeof Model[];
public all: typeof Model[];
constructor(sequelize: Sequelize);
public addModel<T extends typeof Model>(model: T): T;
public removeModel(model: typeof Model): void;
public getModel(against: any, options?: { attribute?: string }): typeof Model;
}
export default ModelManager;
import {
Association,
BelongsTo,
BelongsToMany,
BelongsToManyOptions,
BelongsToOptions,
HasMany,
HasManyOptions,
HasOne,
HasOneOptions,
} from './associations/index';
import { DataType } from './data-types';
import { Deferrable } from './deferrable';
import { AllModelHooks, HookReturn, Hooks, ModelHookOptions } from './hooks';
import { ValidationOptions } from './instance-validator';
import { ModelManager } from './model-manager';
import Op = require('./operators');
import { Promise } from './promise';
import { QueryOptions } from './query-interface';
import { Config, Options, Sequelize, SyncOptions } from './sequelize';
import { Transaction } from './transaction';
import { Col, Fn, Literal, Where } from './utils';
export interface Logging {
/**
* A function that gets executed while running the query to log the sql.
*/
logging?: boolean | ((sql: string, timing?: number) => void);
/**
* Pass query execution time in milliseconds as second argument to logging function (options.logging).
*/
benchmark?: boolean;
}
export interface Transactionable {
/**
* Transaction to run query under
*/
transaction?: Transaction;
}
export interface SearchPathable {
/**
* An optional parameter to specify the schema search_path (Postgres only)
*/
searchPath?: string;
}
export interface Filterable {
/**
* Attribute has to be matched for rows to be selected for the given action.
*/
where?: WhereOptions;
}
export interface Projectable {
/**
* A list of the attributes that you want to select. To rename an attribute, you can pass an array, with
* two elements - the first is the name of the attribute in the DB (or some kind of expression such as
* `Sequelize.literal`, `Sequelize.fn` and so on), and the second is the name you want the attribute to
* have in the returned instance
*/
attributes?: FindAttributeOptions;
}
export interface Paranoid {
/**
* If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will
* be returned. Only applies if `options.paranoid` is true for the model.
*/
paranoid?: boolean;
}
export type GroupOption = string | Fn | Col | (string | Fn | Col)[];
/**
* Options to pass to Model on drop
*/
export interface DropOptions extends Logging {
/**
* Also drop all objects depending on this table, such as views. Only works in postgres
*/
cascade?: boolean;
}
/**
* Schema Options provided for applying a schema to a model
*/
export interface SchemaOptions extends Logging {
/**
* The character(s) that separates the schema name from the table name
*/
schemaDelimiter?: string;
}
/**
* Scope Options for Model.scope
*/
export interface ScopeOptions {
/**
* The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments.
* To apply simple scopes and scope functions with no arguments, pass them as strings. For scope function,
* pass an object, with a `method` property. The value can either be a string, if the method does not take
* any arguments, or an array, where the first element is the name of the method, and consecutive elements
* are arguments to that method. Pass null to remove all scopes, including the default.
*/
method: string | any[];
}
/**
* The type accepted by every `where` option
*/
export type WhereOptions = WhereAttributeHash | AndOperator | OrOperator | Where;
/**
* Example: `[Op.any]: [2,3]` becomes `ANY ARRAY[2, 3]::INTEGER`
*
* _PG only_
*/
export interface AnyOperator {
[Op.any]: (string | number)[];
}
/** Undocumented? */
export interface AllOperator {
[Op.all]: (string | number)[];
}
/**
* Operators that can be used in WhereOptions
*
* See http://docs.sequelizejs.com/en/v3/docs/querying/#operators
*/
export interface WhereOperators {
/**
* Example: `[Op.any]: [2,3]` becomes `ANY ARRAY[2, 3]::INTEGER`
*
* _PG only_
*/
[Op.any]?: (string | number)[];
/** Example: `[Op.gte]: 6,` becomes `>= 6` */
[Op.gte]?: number | string | Date;
/** Example: `[Op.lt]: 10,` becomes `< 10` */
[Op.lt]?: number | string | Date;
/** Example: `[Op.lte]: 10,` becomes `<= 10` */
[Op.lte]?: number | string | Date;
/** Example: `[Op.ne]: 20,` becomes `!= 20` */
[Op.ne]?: string | number | WhereOperators;
/** Example: `[Op.not]: true,` becomes `IS NOT TRUE` */
[Op.not]?: boolean | string | number | WhereOperators;
/** Example: `[Op.between]: [6, 10],` becomes `BETWEEN 6 AND 10` */
[Op.between]?: [number, number];
/** Example: `[Op.in]: [1, 2],` becomes `IN [1, 2]` */
[Op.in]?: (string | number)[] | Literal;
/** Example: `[Op.notIn]: [1, 2],` becomes `NOT IN [1, 2]` */
[Op.notIn]?: (string | number)[] | Literal;
/**
* Examples:
* - `[Op.like]: '%hat',` becomes `LIKE '%hat'`
* - `[Op.like]: { [Op.any]: ['cat', 'hat']}` becomes `LIKE ANY ARRAY['cat', 'hat']`
*/
[Op.like]?: string | AnyOperator | AllOperator;
/**
* Examples:
* - `[Op.notLike]: '%hat'` becomes `NOT LIKE '%hat'`
* - `[Op.notLike]: { [Op.any]: ['cat', 'hat']}` becomes `NOT LIKE ANY ARRAY['cat', 'hat']`
*/
[Op.notLike]?: string | AnyOperator | AllOperator;
/**
* case insensitive PG only
*
* Examples:
* - `[Op.iLike]: '%hat'` becomes `ILIKE '%hat'`
* - `[Op.iLike]: { [Op.any]: ['cat', 'hat']}` becomes `ILIKE ANY ARRAY['cat', 'hat']`
*/
[Op.iLike]?: string | AnyOperator | AllOperator;
/**
* PG array overlap operator
*
* Example: `[Op.overlap]: [1, 2]` becomes `&& [1, 2]`
*/
[Op.overlap]?: [number, number];
/**
* PG array contains operator
*
* Example: `[Op.contains]: [1, 2]` becomes `@> [1, 2]`
*/
[Op.contains]?: any[];
/**
* PG array contained by operator
*
* Example: `[Op.contained]: [1, 2]` becomes `<@ [1, 2]`
*/
[Op.contained]?: any[];
/** Example: `[Op.gt]: 6,` becomes `> 6` */
[Op.gt]?: number | string | Date;
/**
* PG only
*
* Examples:
* - `[Op.notILike]: '%hat'` becomes `NOT ILIKE '%hat'`
* - `[Op.notLike]: ['cat', 'hat']` becomes `LIKE ANY ARRAY['cat', 'hat']`
*/
[Op.notILike]?: string | AnyOperator | AllOperator;
/** Example: `[Op.notBetween]: [11, 15],` becomes `NOT BETWEEN 11 AND 15` */
[Op.notBetween]?: [number, number];
/**
* Strings starts with value.
*/
[Op.startsWith]?: string;
/**
* String ends with value.
*/
[Op.endsWith]?: string;
/**
* String contains value.
*/
[Op.substring]?: string;
}
/** Example: `[Op.or]: [{a: 5}, {a: 6}]` becomes `(a = 5 OR a = 6)` */
export interface OrOperator {
[Op.or]: WhereOptions | WhereOptions[] | WhereValue | WhereValue[];
}
/** Example: `[Op.and]: {a: 5}` becomes `AND (a = 5)` */
export interface AndOperator {
[Op.and]: WhereOptions | WhereOptions[] | WhereValue | WhereValue[];
}
/**
* Where Geometry Options
*/
export interface WhereGeometryOptions {
type: string;
coordinates: (number[] | number)[];
}
/**
* Used for the right hand side of WhereAttributeHash.
* WhereAttributeHash is in there for JSON columns.
*/
export type WhereValue =
| string // literal value
| number // literal value
| boolean // literal value
| null
| WhereOperators
| WhereAttributeHash // for JSON columns
| Col // reference another column
| Fn
| OrOperator
| AndOperator
| WhereGeometryOptions
| (string | number | WhereAttributeHash)[]; // implicit [Op.or]
/**
* A hash of attributes to describe your search.
*/
export interface WhereAttributeHash {
/**
* Possible key values:
* - A simple attribute name
* - A nested key for JSON columns
*
* {
* "meta.audio.length": {
* [Op.gt]: 20
* }
* }
*/
[field: string]: WhereValue | WhereOptions;
}
/**
* Through options for Include Options
*/
export interface IncludeThroughOptions extends Filterable, Projectable {}
/**
* Options for eager-loading associated models, also allowing for all associations to be loaded at once
*/
export type Includeable = typeof Model | Association | IncludeOptions | { all: true };
/**
* Complex include options
*/
export interface IncludeOptions extends Filterable, Projectable {
/**
* The model you want to eagerly load
*/
model?: typeof Model;
/**
* The alias of the relation, in case the model you want to eagerly load is aliassed. For `hasOne` /
* `belongsTo`, this should be the singular name, and for `hasMany`, it should be the plural
*/
as?: string;
/**
* The association you want to eagerly load. (This can be used instead of providing a model/as pair)
*/
association?: Association;
/**
* Note that this converts the eager load to an inner join,
* unless you explicitly set `required: false`
*/
where?: WhereOptions;
/**
* If true, converts to an inner join, which means that the parent model will only be loaded if it has any
* matching children. True if `include.where` is set, false otherwise.
*/
required?: boolean;
/**
* Limit include. Only available when setting `separate` to true.
*/
limit?: number;
/**
* Run include in separate queries.
*/
separate?: boolean;
/**
* Through Options
*/
through?: IncludeThroughOptions;
/**
* Load further nested related models
*/
include?: Includeable[];
/**
* Order include. Only available when setting `separate` to true.
*/
order?: Order;
/**
* Use sub queries. This should only be used if you know for sure the query does not result in a cartesian product.
*/
subQuery?: boolean;
}
export type OrderItem =
| string
| Fn
| Col
| Literal
| [string | Col | Fn | Literal, string]
| [typeof Model | { model: typeof Model; as: string }, string, string]
| [typeof Model, typeof Model, string, string];
export type Order = string | Fn | Col | Literal | OrderItem[];
export type FindAttributeOptions =
| (string | [string | Literal | Fn, string])[]
| {
exclude: string[];
include?: (string | [string | Literal | Fn, string])[];
}
| {
exclude?: string[];
include: (string | [string | Literal | Fn, string])[];
};
/**
* Options that are passed to any model creating a SELECT query
*
* A hash of options to describe the scope of the search
*/
export interface FindOptions extends Logging, Transactionable, Filterable, Projectable, Paranoid {
/**
* A list of associations to eagerly load using a left join. Supported is either
* `{ include: [ Model1, Model2, ...]}`, `{ include: [{ model: Model1, as: 'Alias' }]}` or
* `{ include: [{ all: true }]}`.
* If your association are set up with an `as` (eg. `X.hasMany(Y, { as: 'Z }`, you need to specify Z in
* the as attribute when eager loading Y).
*/
include?: Includeable[];
/**
* Specifies an ordering. If a string is provided, it will be escaped. Using an array, you can provide
* several columns / functions to order by. Each element can be further wrapped in a two-element array. The
* first element is the column / function to order by, the second is the direction. For example:
* `order: [['name', 'DESC']]`. In this way the column will be escaped, but the direction will not.
*/
order?: Order;
/**
* GROUP BY in sql
*/
group?: GroupOption;
/**
* Limit the results
*/
limit?: number;
/**
* Skip the results;
*/
offset?: number;
/**
* Lock the selected rows. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE.
* Postgres also supports transaction.LOCK.KEY_SHARE, transaction.LOCK.NO_KEY_UPDATE and specific model
* locks with joins. See [transaction.LOCK for an example](transaction#lock)
*/
lock?: Transaction.LOCK | { level: Transaction.LOCK; of: typeof Model };
/**
* Return raw result. See sequelize.query for more information.
*/
raw?: boolean;
/**
* having ?!?
*/
having?: WhereAttributeHash;
/**
* Use sub queries (internal)
*/
subQuery?: boolean;
}
export interface NonNullFindOptions extends FindOptions {
/**
* Throw if nothing was found.
*/
rejectOnEmpty: boolean;
}
/**
* Options for Model.count method
*/
export interface CountOptions extends Logging, Transactionable, Filterable, Projectable, Paranoid {
/**
* Include options. See `find` for details
*/
include?: Includeable[];
/**
* Apply COUNT(DISTINCT(col))
*/
distinct?: boolean;
/**
* GROUP BY in sql
* Used in conjunction with `attributes`.
* @see Projectable
*/
group?: GroupOption;
/**
* The column to aggregate on.
*/
col?: string;
}
export interface FindAndCountOptions extends CountOptions, FindOptions {}
/**
* Options for Model.build method
*/
export interface BuildOptions {
/**
* If set to true, values will ignore field and virtual setters.
*/
raw?: boolean;
/**
* Is this record new
*/
isNewRecord?: boolean;
/**
* an array of include options - Used to build prefetched/included model instances. See `set`
*
* TODO: See set
*/
include?: Includeable[];
}
export interface Silent {
/**
* If true, the updatedAt timestamp will not be updated.
*
* @default false
*/
silent?: boolean;
}
/**
* Options for Model.create method
*/
export interface CreateOptions extends BuildOptions, Logging, Silent, Transactionable {
/**
* If set, only columns matching those in fields will be saved
*/
fields?: string[];
/**
* On Duplicate
*/
onDuplicate?: string;
}
/**
* Options for Model.findOrCreate method
*/
export interface FindOrCreateOptions extends Logging, Transactionable {
/**
* A hash of search attributes.
*/
where: WhereOptions;
/**
* Default values to use if building a new instance
*/
defaults?: object;
}
/**
* Options for Model.upsert method
*/
export interface UpsertOptions extends Logging, Transactionable, SearchPathable {
/**
* Run validations before the row is inserted
*/
validate?: boolean;
/**
* The fields to insert / update. Defaults to all fields
*/
fields?: string[];
}
/**
* Options for Model.bulkCreate method
*/
export interface BulkCreateOptions extends Logging, Transactionable {
/**
* Fields to insert (defaults to all fields)
*/
fields?: string[];
/**
* Should each row be subject to validation before it is inserted. The whole insert will fail if one row
* fails validation
*/
validate?: boolean;
/**
* Run before / after bulk create hooks?
*/
hooks?: boolean;
/**
* Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run if
* options.hooks is true.
*/
individualHooks?: boolean;
/**
* Ignore duplicate values for primary keys? (not supported by postgres)
*
* @default false
*/
ignoreDuplicates?: boolean;
/**
* Fields to update if row key already exists (on duplicate key update)? (only supported by mysql &
* mariadb). By default, all fields are updated.
*/
updateOnDuplicate?: string[];
/**
* Return the affected rows (only for postgres)
*/
returning?: boolean;
}
/**
* The options passed to Model.destroy in addition to truncate
*/
export interface TruncateOptions extends Logging, Transactionable, Filterable {
/**
* Only used in conjuction with TRUNCATE. Truncates all tables that have foreign-key references to the
* named table, or to any tables added to the group due to CASCADE.
*
* @default false;
*/
cascade?: boolean;
/**
* Run before / after bulk destroy hooks?
*/
hooks?: boolean;
/**
* If set to true, destroy will SELECT all records matching the where parameter and will execute before /
* after destroy hooks on each row
*/
individualHooks?: boolean;
/**
* How many rows to delete
*/
limit?: number;
/**
* Delete instead of setting deletedAt to current timestamp (only applicable if `paranoid` is enabled)
*/
force?: boolean;
/**
* Only used in conjunction with `truncate`.
* Automatically restart sequences owned by columns of the truncated table
*/
restartIdentity?: boolean;
}
/**
* Options used for Model.destroy
*/
export interface DestroyOptions extends TruncateOptions {
/**
* If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is
* truncated the where and limit options are ignored
*/
truncate?: boolean;
}
/**
* Options for Model.restore
*/
export interface RestoreOptions extends Logging, Transactionable, Filterable {
/**
* Run before / after bulk restore hooks?
*/
hooks?: boolean;
/**
* If set to true, restore will find all records within the where parameter and will execute before / after
* bulkRestore hooks on each row
*/
individualHooks?: boolean;
/**
* How many rows to undelete
*/
limit?: number;
}
/**
* Options used for Model.update
*/
export interface UpdateOptions extends Logging, Transactionable {
/**
* Options to describe the scope of the search.
*/
where: WhereOptions;
/**
* Fields to update (defaults to all fields)
*/
fields?: string[];
/**
* Should each row be subject to validation before it is inserted. The whole insert will fail if one row
* fails validation.
*
* @default true
*/
validate?: boolean;
/**
* Run before / after bulk update hooks?
*
* @default true
*/
hooks?: boolean;
/**
* Whether or not to update the side effects of any virtual setters.
*
* @default true
*/
sideEffects?: boolean;
/**
* Run before / after update hooks?. If true, this will execute a SELECT followed by individual UPDATEs.
* A select is needed, because the row data needs to be passed to the hooks
*
* @default false
*/
individualHooks?: boolean;
/**
* Return the affected rows (only for postgres)
*/
returning?: boolean;
/**
* How many rows to update (only for mysql and mariadb)
*/
limit?: number;
}
/**
* Options used for Model.aggregate
*/
export interface AggregateOptions<T extends DataType | unknown> extends QueryOptions, Filterable, Paranoid {
/**
* The type of the result. If `field` is a field in this Model, the default will be the type of that field,
* otherwise defaults to float.
*/
dataType?: string | T;
/**
* Applies DISTINCT to the field being aggregated over
*/
distinct?: boolean;
}
// instance
/**
* Options used for Instance.increment method
*/
export interface IncrementDecrementOptions extends Logging, Transactionable, Silent, SearchPathable, Filterable {}
/**
* Options used for Instance.increment method
*/
export interface IncrementDecrementOptionsWithBy extends IncrementDecrementOptions {
/**
* The number to increment by
*
* @default 1
*/
by?: number;
}
/**
* Options used for Instance.restore method
*/
export interface InstanceRestoreOptions extends Logging, Transactionable {}
/**
* Options used for Instance.destroy method
*/
export interface InstanceDestroyOptions extends Logging, Transactionable {
/**
* If set to true, paranoid models will actually be deleted
*/
force?: boolean;
}
/**
* Options used for Instance.update method
*/
export interface InstanceUpdateOptions extends SaveOptions, SetOptions, Filterable {}
/**
* Options used for Instance.set method
*/
export interface SetOptions {
/**
* If set to true, field and virtual setters will be ignored
*/
raw?: boolean;
/**
* Clear all previously set data values
*/
reset?: boolean;
}
/**
* Options used for Instance.save method
*/
export interface SaveOptions extends Logging, Transactionable, Silent {
/**
* An optional array of strings, representing database columns. If fields is provided, only those columns
* will be validated and saved.
*/
fields?: string[];
/**
* If false, validations won't be run.
*
* @default true
*/
validate?: boolean;
}
/**
* Model validations, allow you to specify format/content/inheritance validations for each attribute of the
* model.
*
* Validations are automatically run on create, update and save. You can also call validate() to manually
* validate an instance.
*
* The validations are implemented by validator.js.
*/
export interface ModelValidateOptions {
/**
* is: ["^[a-z]+$",'i'] // will only allow letters
* is: /^[a-z]+[Op./i] // same as the previous example using real RegExp
*/
is?: string | (string | RegExp)[] | RegExp | { msg: string; args: string | (string | RegExp)[] | RegExp };
/**
* not: ["[a-z]",'i'] // will not allow letters
*/
not?: string | (string | RegExp)[] | RegExp | { msg: string; args: string | (string | RegExp)[] | RegExp };
/**
* checks for email format (foo@bar.com)
*/
isEmail?: boolean | { msg: string };
/**
* checks for url format (http://foo.com)
*/
isUrl?: boolean | { msg: string };
/**
* checks for IPv4 (129.89.23.1) or IPv6 format
*/
isIP?: boolean | { msg: string };
/**
* checks for IPv4 (129.89.23.1)
*/
isIPv4?: boolean | { msg: string };
/**
* checks for IPv6 format
*/
isIPv6?: boolean | { msg: string };
/**
* will only allow letters
*/
isAlpha?: boolean | { msg: string };
/**
* will only allow alphanumeric characters, so "_abc" will fail
*/
isAlphanumeric?: boolean | { msg: string };
/**
* will only allow numbers
*/
isNumeric?: boolean | { msg: string };
/**
* checks for valid integers
*/
isInt?: boolean | { msg: string };
/**
* checks for valid floating point numbers
*/
isFloat?: boolean | { msg: string };
/**
* checks for any numbers
*/
isDecimal?: boolean | { msg: string };
/**
* checks for lowercase
*/
isLowercase?: boolean | { msg: string };
/**
* checks for uppercase
*/
isUppercase?: boolean | { msg: string };
/**
* won't allow null
*/
notNull?: boolean | { msg: string };
/**
* only allows null
*/
isNull?: boolean | { msg: string };
/**
* don't allow empty strings
*/
notEmpty?: boolean | { msg: string };
/**
* only allow a specific value
*/
equals?: string | { msg: string };
/**
* force specific substrings
*/
contains?: string | { msg: string };
/**
* check the value is not one of these
*/
notIn?: string[][] | { msg: string; args: string[][] };
/**
* check the value is one of these
*/
isIn?: string[][] | { msg: string; args: string[][] };
/**
* don't allow specific substrings
*/
notContains?: string[] | string | { msg: string; args: string[] | string };
/**
* only allow values with length between 2 and 10
*/
len?: [number, number] | { msg: string; args: [number, number] };
/**
* only allow uuids
*/
isUUID?: number | { msg: string; args: number };
/**
* only allow date strings
*/
isDate?: boolean | { msg: string; args: boolean };
/**
* only allow date strings after a specific date
*/
isAfter?: string | { msg: string; args: string };
/**
* only allow date strings before a specific date
*/
isBefore?: string | { msg: string; args: string };
/**
* only allow values
*/
max?: number | { msg: string; args: [number] };
/**
* only allow values >= 23
*/
min?: number | { msg: string; args: [number] };
/**
* only allow arrays
*/
isArray?: boolean | { msg: string; args: boolean };
/**
* check for valid credit card numbers
*/
isCreditCard?: boolean | { msg: string; args: boolean };
/**
* custom validations are also possible
*
* Implementation notes :
*
* We can't enforce any other method to be a function, so :
*
* ```typescript
* [name: string] : ( value : any ) => boolean;
* ```
*
* doesn't work in combination with the properties above
*
* @see https://github.com/Microsoft/TypeScript/issues/1889
*/
[name: string]: any;
}
/**
* Interface for indexes property in DefineOptions
*/
export interface ModelIndexesOptions {
/**
* The name of the index. Defaults to model name + _ + fields concatenated
*/
name?: string;
/**
* Index type. Only used by mysql. One of `UNIQUE`, `FULLTEXT` and `SPATIAL`
*/
index?: string;
/**
* The method to create the index by (`USING` statement in SQL). BTREE and HASH are supported by mysql and
* postgres, and postgres additionally supports GIST and GIN.
*/
method?: string;
/**
* Should the index by unique? Can also be triggered by setting type to `UNIQUE`
*
* @default false
*/
unique?: boolean;
/**
* PostgreSQL will build the index without taking any write locks. Postgres only
*
* @default false
*/
concurrently?: boolean;
/**
* An array of the fields to index. Each field can either be a string containing the name of the field,
* a sequelize object (e.g `sequelize.fn`), or an object with the following attributes: `attribute`
* (field name), `length` (create a prefix index of length chars), `order` (the direction the column
* should be sorted in), `collate` (the collation (sort order) for the column)
*/
fields?: (string | { attribute: string; length: number; order: string; collate: string })[];
}
/**
* Interface for name property in DefineOptions
*/
export interface ModelNameOptions {
/**
* Singular model name
*/
singular?: string;
/**
* Plural model name
*/
plural?: string;
}
/**
* Interface for getterMethods in DefineOptions
*/
export interface ModelGetterOptions {
[name: string]: () => any;
}
/**
* Interface for setterMethods in DefineOptions
*/
export interface ModelSetterOptions {
[name: string]: (val: any) => void;
}
/**
* Interface for Define Scope Options
*/
export interface ModelScopeOptions {
/**
* Name of the scope and it's query
*/
[scopeName: string]: FindOptions | ((...args: any[]) => FindOptions);
}
/**
* General column options
*/
export interface ColumnOptions {
/**
* If false, the column will have a NOT NULL constraint, and a not null validation will be run before an
* instance is saved.
*/
allowNull?: boolean;
/**
* If set, sequelize will map the attribute name to a different name in the database
*/
field?: string;
/**
* A literal default value, a JavaScript function, or an SQL function (see `sequelize.fn`)
*/
defaultValue?: any;
}
/**
* References options for the column's attributes
*/
export interface ModelAttributeColumnReferencesOptions {
/**
* If this column references another table, provide it here as a Model, or a string
*/
model?: string | typeof Model;
/**
* The column of the foreign table that this column references
*/
key?: string;
/**
* When to check for the foreign key constraing
*
* PostgreSQL only
*/
deferrable?: Deferrable;
}
/**
* Column options for the model schema attributes
*/
export interface ModelAttributeColumnOptions extends ColumnOptions {
/**
* A string or a data type
*/
type: DataType;
/**
* If true, the column will get a unique constraint. If a string is provided, the column will be part of a
* composite unique index. If multiple columns have the same string, they will be part of the same unique
* index
*/
unique?: boolean | string | { name: string; msg: string };
/**
* Primary key flag
*/
primaryKey?: boolean;
/**
* Is this field an auto increment field
*/
autoIncrement?: boolean;
/**
* Comment for the database
*/
comment?: string;
/**
* An object with reference configurations
*/
references?: ModelAttributeColumnReferencesOptions;
/**
* What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or
* NO ACTION
*/
onUpdate?: string;
/**
* What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or
* NO ACTION
*/
onDelete?: string;
/**
* An object of validations to execute for this column every time the model is saved. Can be either the
* name of a validation provided by validator.js, a validation function provided by extending validator.js
* (see the
* `DAOValidator` property for more details), or a custom validation function. Custom validation functions
* are called with the value of the field, and can possibly take a second callback argument, to signal that
* they are asynchronous. If the validator is sync, it should throw in the case of a failed validation, it
* it is async, the callback should be called with the error text.
*/
validate?: ModelValidateOptions;
/**
* Usage in object notation
*
* ```js
* sequelize.define('model', {
* states: {
* type: Sequelize.ENUM,
* values: ['active', 'pending', 'deleted']
* }
* })
* ```
*/
values?: string[];
/**
* Provide a custom getter for this column. Use `this.getDataValue(String)` to manipulate the underlying
* values.
*/
get?(): any;
/**
* Provide a custom setter for this column. Use `this.setDataValue(String, Value)` to manipulate the
* underlying values.
*/
set?(val: any): void;
}
/**
* Interface for Attributes provided for a column
*/
export interface ModelAttributes {
/**
* The description of a database column
*/
[name: string]: DataType | ModelAttributeColumnOptions;
}
/**
* Possible types for primary keys
*/
export type Identifier = number | string | Buffer;
/**
* Options for model definition
*/
export interface ModelOptions<M extends Model = Model> {
/**
* Define the default search scope to use for this model. Scopes have the same form as the options passed to
* find / findAll.
*/
defaultScope?: FindOptions;
/**
* More scopes, defined in the same way as defaultScope above. See `Model.scope` for more information about
* how scopes are defined, and what you can do with them
*/
scopes?: ModelScopeOptions;
/**
* Don't persits null values. This means that all columns with null values will not be saved.
*/
omitNull?: boolean;
/**
* Adds createdAt and updatedAt timestamps to the model. Default true.
*/
timestamps?: boolean;
/**
* Calling destroy will not delete the model, but instead set a deletedAt timestamp if this is true. Needs
* timestamps=true to work. Default false.
*/
paranoid?: boolean;
/**
* Converts all camelCased columns to underscored if true. Default false.
*/
underscored?: boolean;
/**
* Indicates if the model's table has a trigger associated with it. Default false.
*/
hasTrigger?: boolean;
/**
* If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name.
* Otherwise, the dao name will be pluralized. Default false.
*/
freezeTableName?: boolean;
/**
* An object with two attributes, `singular` and `plural`, which are used when this model is associated to
* others.
*/
name?: ModelNameOptions;
/**
* Indexes for the provided database table
*/
indexes?: ModelIndexesOptions[];
/**
* Override the name of the createdAt column if a string is provided, or disable it if false. Timestamps
* must be true. Not affected by underscored setting.
*/
createdAt?: string | boolean;
/**
* Override the name of the deletedAt column if a string is provided, or disable it if false. Timestamps
* must be true. Not affected by underscored setting.
*/
deletedAt?: string | boolean;
/**
* Override the name of the updatedAt column if a string is provided, or disable it if false. Timestamps
* must be true. Not affected by underscored setting.
*/
updatedAt?: string | boolean;
/**
* @default pluralized model name, unless freezeTableName is true, in which case it uses model name
* verbatim
*/
tableName?: string;
schema?: string;
/**
* You can also change the database engine, e.g. to MyISAM. InnoDB is the default.
*/
engine?: string;
charset?: string;
/**
* Finaly you can specify a comment for the table in MySQL and PG
*/
comment?: string;
collate?: string;
/**
* Set the initial AUTO_INCREMENT value for the table in MySQL.
*/
initialAutoIncrement?: string;
/**
* An object of hook function that are called before and after certain lifecycle events.
* See Hooks for more information about hook
* functions and their signatures. Each property can either be a function, or an array of functions.
*/
hooks?: Partial<ModelHookOptions<M>>;
/**
* An object of model wide validations. Validations have access to all model values via `this`. If the
* validator function takes an argument, it is asumed to be async, and is called with a callback that
* accepts an optional error.
*/
validate?: ModelValidateOptions;
}
/**
* Options passed to [[Model.init]]
*/
export interface InitOptions extends ModelOptions {
/**
* The sequelize connection. Required ATM.
*/
sequelize: Sequelize;
}
/**
* AddScope Options for Model.addScope
*/
export interface AddScopeOptions {
/**
* If a scope of the same name already exists, should it be overwritten?
*/
override: boolean;
}
export abstract class Model<T = any, T2 = any> extends Hooks {
/** The name of the database table */
public static tableName: string;
/**
* The name of the primary key attribute
*/
public static primaryKeyAttribute: string;
/**
* An object hash from alias to association object
*/
public static associations: any;
/**
* The options that the model was initialized with
*/
public static options: InitOptions;
/**
* The attributes of the model
*/
public static rawAttributes: { [attribute: string]: ModelAttributeColumnOptions };
/**
* Initialize a model, representing a table in the DB, with attributes and options.
*
* The table columns are define by the hash that is given as the second argument. Each attribute of the hash represents a column. A short table definition might look like this:
*
* ```js
* Project.init({
* columnA: {
* type: Sequelize.BOOLEAN,
* validate: {
* is: ['[a-z]','i'], // will only allow letters
* max: 23, // only allow values <= 23
* isIn: {
* args: [['en', 'zh']],
* msg: "Must be English or Chinese"
* }
* },
* field: 'column_a'
* // Other attributes here
* },
* columnB: Sequelize.STRING,
* columnC: 'MY VERY OWN COLUMN TYPE'
* }, {sequelize})
*
* sequelize.models.modelName // The model will now be available in models under the class name
* ```
*
* As shown above, column definitions can be either strings, a reference to one of the datatypes that are predefined on the Sequelize constructor, or an object that allows you to specify both the type of the column, and other attributes such as default values, foreign key constraints and custom setters and getters.
*
* For a list of possible data types, see http://docs.sequelizejs.com/en/latest/docs/models-definition/#data-types
*
* For more about getters and setters, see http://docs.sequelizejs.com/en/latest/docs/models-definition/#getters-setters
*
* For more about instance and class methods, see http://docs.sequelizejs.com/en/latest/docs/models-definition/#expansion-of-models
*
* For more about validation, see http://docs.sequelizejs.com/en/latest/docs/models-definition/#validations
*
* @param attributes
* An object, where each attribute is a column of the table. Each column can be either a DataType, a
* string or a type-description object, with the properties described below:
* @param options These options are merged with the default define options provided to the Sequelize constructor
*/
public static init(attributes: ModelAttributes, options: InitOptions): void;
/**
* Remove attribute from model definition
*
* @param attribute
*/
public static removeAttribute(attribute: string): void;
/**
* Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the
* model instance (this)
*/
public static sync(options?: SyncOptions): Promise<Model>;
/**
* Drop the table represented by this Model
*
* @param options
*/
public static drop(options?: DropOptions): Promise<void>;
/**
* Apply a schema to this model. For postgres, this will actually place the schema in front of the table
* name
* - `"schema"."tableName"`, while the schema will be prepended to the table name for mysql and
* sqlite - `'schema.tablename'`.
*
* @param schema The name of the schema
* @param options
*/
public static schema<M extends Model>(
this: { new (): M } & typeof Model,
schema: string,
options?: SchemaOptions
): M;
/**
* Get the tablename of the model, taking schema into account. The method will return The name as a string
* if the model has no schema, or an object with `tableName`, `schema` and `delimiter` properties.
*
* @param options The hash of options from any query. You can use one model to access tables with matching
* schemas by overriding `getTableName` and using custom key/values to alter the name of the table.
* (eg.
* subscribers_1, subscribers_2)
*/
public static getTableName(): string | {
tableName: string;
schema: string;
delimiter: string;
};
/**
* Apply a scope created in `define` to the model. First let's look at how to create scopes:
* ```js
* var Model = sequelize.define('model', attributes, {
* defaultScope: {
* where: {
* username: 'dan'
* },
* limit: 12
* },
* scopes: {
* isALie: {
* where: {
* stuff: 'cake'
* }
* },
* complexFunction: function(email, accessLevel) {
* return {
* where: {
* email: {
* [Op.like]: email
* },
* accesss_level {
* [Op.gte]: accessLevel
* }
* }
* }
* }
* }
* })
* ```
* Now, since you defined a default scope, every time you do Model.find, the default scope is appended to
* your query. Here's a couple of examples:
* ```js
* Model.findAll() // WHERE username = 'dan'
* Model.findAll({ where: { age: { gt: 12 } } }) // WHERE age > 12 AND username = 'dan'
* ```
*
* To invoke scope functions you can do:
* ```js
* Model.scope({ method: ['complexFunction' 'dan@sequelize.com', 42]}).findAll()
* // WHERE email like 'dan@sequelize.com%' AND access_level >= 42
* ```
*
* @return Model A reference to the model, with the scope(s) applied. Calling scope again on the returned
* model will clear the previous scope.
*/
public static scope<M extends { new (): Model }>(
this: M,
options?: string | string[] | ScopeOptions | WhereAttributeHash
): M;
public static addScope(name: string, scope: FindOptions, options?: AddScopeOptions): void;
/**
* Search for multiple instances.
*
* __Simple search using AND and =__
* ```js
* Model.findAll({
* where: {
* attr1: 42,
* attr2: 'cake'
* }
* })
* ```
* ```sql
* WHERE attr1 = 42 AND attr2 = 'cake'
* ```
*
* __Using greater than, less than etc.__
* ```js
*
* Model.findAll({
* where: {
* attr1: {
* gt: 50
* },
* attr2: {
* lte: 45
* },
* attr3: {
* in: [1,2,3]
* },
* attr4: {
* ne: 5
* }
* }
* })
* ```
* ```sql
* WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5
* ```
* Possible options are: `[Op.ne], [Op.in], [Op.not], [Op.notIn], [Op.gte], [Op.gt], [Op.lte], [Op.lt], [Op.like], [Op.ilike]/[Op.iLike], [Op.notLike],
* [Op.notILike], '..'/[Op.between], '!..'/[Op.notBetween], '&&'/[Op.overlap], '@>'/[Op.contains], '<@'/[Op.contained]`
*
* __Queries using OR__
* ```js
* Model.findAll({
* where: Sequelize.and(
* { name: 'a project' },
* Sequelize.or(
* { id: [1,2,3] },
* { id: { gt: 10 } }
* )
* )
* })
* ```
* ```sql
* WHERE name = 'a project' AND (id` IN (1,2,3) OR id > 10)
* ```
*
* The success listener is called with an array of instances if the query succeeds.
*
* @see {Sequelize#query}
*/
public static findAll<M extends Model>(this: { new (): M } & typeof Model, options?: FindOptions): Promise<M[]>;
/**
* Search for a single instance by its primary key. This applies LIMIT 1, so the listener will
* always be called with a single instance.
*/
public static findByPk<M extends Model>(
this: { new (): M } & typeof Model,
identifier?: Identifier,
options?: FindOptions
): Promise<M | null>;
public static findByPk<M extends Model>(
this: { new (): M } & typeof Model,
identifier: Identifier,
options: NonNullFindOptions
): Promise<M>;
/**
* Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single
* instance.
*/
public static findOne<M extends Model>(
this: { new (): M } & typeof Model,
options?: FindOptions
): Promise<M | null>;
public static findOne<M extends Model>(this: { new (): M } & typeof Model, options: NonNullFindOptions): Promise<M>;
/**
* Run an aggregation method on the specified field
*
* @param field The field to aggregate over. Can be a field name or *
* @param aggregateFunction The function to use for aggregation, e.g. sum, max etc.
* @param options Query options. See sequelize.query for full options
* @return Returns the aggregate result cast to `options.dataType`, unless `options.plain` is false, in
* which case the complete data result is returned.
*/
public static aggregate<M extends Model, T extends DataType | unknown>(
this: { new (): M } & typeof Model,
field: keyof M,
aggregateFunction: string,
options?: AggregateOptions<T>
): Promise<T>;
/**
* Count the number of records matching the provided where clause.
*
* If you provide an `include` option, the number of matching associations will be counted instead.
*/
public static count(options?: CountOptions): Promise<number>;
/**
* Find all the rows matching your query, within a specified offset / limit, and get the total number of
* rows matching your query. This is very usefull for paging
*
* ```js
* Model.findAndCountAll({
* where: ...,
* limit: 12,
* offset: 12
* }).then(function (result) {
* ...
* })
* ```
* In the above example, `result.rows` will contain rows 13 through 24, while `result.count` will return
* the
* total number of rows that matched your query.
*
* When you add includes, only those which are required (either because they have a where clause, or
* because
* `required` is explicitly set to true on the include) will be added to the count part.
*
* Suppose you want to find all users who have a profile attached:
* ```js
* User.findAndCountAll({
* include: [
* { model: Profile, required: true}
* ],
* limit 3
* });
* ```
* Because the include for `Profile` has `required` set it will result in an inner join, and only the users
* who have a profile will be counted. If we remove `required` from the include, both users with and
* without
* profiles will be counted
*/
public static findAndCountAll<M extends Model>(
this: { new (): M } & typeof Model,
options?: FindAndCountOptions
): Promise<{ rows: M[]; count: number }>;
/**
* Find the maximum value of field
*/
public static max<M extends Model, T extends DataType | unknown>(
this: { new (): M } & typeof Model,
field: keyof M,
options?: AggregateOptions<T>
): Promise<T>;
/**
* Find the minimum value of field
*/
public static min<M extends Model, T extends DataType | unknown>(
this: { new (): M } & typeof Model,
field: keyof M,
options?: AggregateOptions<T>
): Promise<T>;
/**
* Find the sum of field
*/
public static sum<M extends Model, T extends DataType | unknown>(
this: { new (): M } & typeof Model,
field: keyof M,
options?: AggregateOptions<T>
): Promise<number>;
/**
* Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty.
*/
public static build<M extends Model>(
this: { new (): M } & typeof Model,
record?: object,
options?: BuildOptions
): M;
/**
* Undocumented bulkBuild
*/
public static bulkBuild<M extends Model>(
this: { new (): M } & typeof Model,
records: object[],
options?: BuildOptions
): M[];
/**
* Builds a new model instance and calls save on it.
*/
public static create<M extends Model>(
this: { new (): M } & typeof Model,
values?: object,
options?: CreateOptions
): Promise<M>;
public static create(values: object, options: CreateOptions & { returning: false }): Promise<void>;
/**
* Find a row that matches the query, or build (but don't save) the row if none is found.
* The successfull result of the promise will be (instance, initialized) - Make sure to use .spread()
*/
public static findOrBuild<M extends Model>(
this: { new (): M } & typeof Model,
options: FindOrCreateOptions
): Promise<[M, boolean]>;
/**
* Find a row that matches the query, or build and save the row if none is found
* The successful result of the promise will be (instance, created) - Make sure to use .spread()
*
* If no transaction is passed in the `options` object, a new transaction will be created internally, to
* prevent the race condition where a matching row is created by another connection after the find but
* before the insert call. However, it is not always possible to handle this case in SQLite, specifically
* if one transaction inserts and another tries to select before the first one has comitted. In this case,
* an instance of sequelize.TimeoutError will be thrown instead. If a transaction is created, a savepoint
* will be created instead, and any unique constraint violation will be handled internally.
*/
public static findOrCreate<M extends Model>(
this: { new (): M } & typeof Model,
options: FindOrCreateOptions
): Promise<[M, boolean]>;
/**
* Insert or update a single row. An update will be executed if a row which matches the supplied values on
* either the primary key or a unique key is found. Note that the unique index must be defined in your
* sequelize model and not just in the table. Otherwise you may experience a unique constraint violation,
* because sequelize fails to identify the row that should be updated.
*
* **Implementation details:**
*
* * MySQL - Implemented as a single query `INSERT values ON DUPLICATE KEY UPDATE values`
* * PostgreSQL - Implemented as a temporary function with exception handling: INSERT EXCEPTION WHEN
* unique_constraint UPDATE
* * SQLite - Implemented as two queries `INSERT; UPDATE`. This means that the update is executed
* regardless
* of whether the row already existed or not
*
* **Note** that SQLite returns undefined for created, no matter if the row was created or updated. This is
* because SQLite always runs INSERT OR IGNORE + UPDATE, in a single query, so there is no way to know
* whether the row was inserted or not.
*/
public static upsert<M extends Model>(
this: { new (): M } & typeof Model,
values: object,
options?: UpsertOptions
): Promise<boolean>;
/**
* Create and insert multiple instances in bulk.
*
* The success handler is passed an array of instances, but please notice that these may not completely
* represent the state of the rows in the DB. This is because MySQL and SQLite do not make it easy to
* obtain
* back automatically generated IDs and other default values in a way that can be mapped to multiple
* records. To obtain Instances for the newly created values, you will need to query for them again.
*
* @param records List of objects (key/value pairs) to create instances from
*/
public static bulkCreate<M extends Model>(
this: { new (): M } & typeof Model,
records: object[],
options?: BulkCreateOptions
): Promise<M[]>;
/**
* Truncate all instances of the model. This is a convenient method for Model.destroy({ truncate: true }).
*/
public static truncate(options?: TruncateOptions): Promise<void>;
/**
* Delete multiple instances, or set their deletedAt timestamp to the current time if `paranoid` is enabled.
*
* @return Promise<number> The number of destroyed rows
*/
public static destroy(options?: DestroyOptions): Promise<number>;
/**
* Restore multiple instances if `paranoid` is enabled.
*/
public static restore(options?: RestoreOptions): Promise<void>;
/**
* Update multiple instances that match the where options. The promise returns an array with one or two
* elements. The first element is always the number of affected rows, while the second element is the actual
* affected rows (only supported in postgres with `options.returning` true.)
*/
public static update<M extends Model>(
this: { new (): M } & typeof Model,
values: object,
options: UpdateOptions
): Promise<[number, M[]]>;
/**
* Increments a single field.
*/
public static increment<M extends Model, K extends keyof M>(
this: { new (): M },
field: K,
options: IncrementDecrementOptionsWithBy
): Promise<M>;
/**
* Increments multiple fields by the same value.
*/
public static increment<M extends Model, K extends keyof M>(
this: { new (): M },
fields: K[],
options: IncrementDecrementOptionsWithBy
): Promise<M>;
/**
* Increments multiple fields by different values.
*/
public static increment<M extends Model, K extends keyof M>(
this: { new (): M },
fields: { [key in K]?: number },
options: IncrementDecrementOptions
): Promise<M>;
/**
* Run a describe query on the table. The result will be return to the listener as a hash of attributes and
* their types.
*/
public static describe(): Promise<object>;
/**
* Unscope the model
*/
public static unscoped<M extends typeof Model>(this: M): M;
/**
* A hook that is run before validation
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static beforeValidate<M extends Model>(
this: { new (): M } & typeof Model,
name: string,
fn: (instance: M, options: ValidationOptions) => HookReturn
): void;
public static beforeValidate<M extends Model>(
this: { new (): M } & typeof Model,
fn: (instance: M, options: ValidationOptions) => HookReturn
): void;
/**
* A hook that is run after validation
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static afterValidate<M extends Model>(
this: { new (): M } & typeof Model,
name: string,
fn: (instance: M, options: ValidationOptions) => HookReturn
): void;
public static afterValidate<M extends Model>(
this: { new (): M } & typeof Model,
fn: (instance: M, options: ValidationOptions) => HookReturn
): void;
/**
* A hook that is run before creating a single instance
*
* @param name
* @param fn A callback function that is called with attributes, options
*/
public static beforeCreate<M extends Model>(
this: { new (): M } & typeof Model,
name: string,
fn: (attributes: M, options: CreateOptions) => HookReturn
): void;
public static beforeCreate<M extends Model>(
this: { new (): M } & typeof Model,
fn: (attributes: M, options: CreateOptions) => HookReturn
): void;
/**
* A hook that is run after creating a single instance
*
* @param name
* @param fn A callback function that is called with attributes, options
*/
public static afterCreate<M extends Model>(
this: { new (): M } & typeof Model,
name: string,
fn: (attributes: M, options: CreateOptions) => HookReturn
): void;
public static afterCreate<M extends Model>(
this: { new (): M } & typeof Model,
fn: (attributes: M, options: CreateOptions) => HookReturn
): void;
/**
* A hook that is run before destroying a single instance
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static beforeDestroy<M extends Model>(
this: { new (): M } & typeof Model,
name: string,
fn: (instance: M, options: InstanceDestroyOptions) => HookReturn
): void;
public static beforeDestroy<M extends Model>(
this: { new (): M } & typeof Model,
fn: (instance: Model, options: InstanceDestroyOptions) => HookReturn
): void;
/**
* A hook that is run after destroying a single instance
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static afterDestroy<M extends Model>(
this: { new (): M } & typeof Model,
name: string,
fn: (instance: M, options: InstanceDestroyOptions) => HookReturn
): void;
public static afterDestroy<M extends Model>(
this: { new (): M } & typeof Model,
fn: (instance: M, options: InstanceDestroyOptions) => HookReturn
): void;
/**
* A hook that is run before updating a single instance
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static beforeUpdate<M extends Model>(
this: { new (): M } & typeof Model,
name: string,
fn: (instance: M, options: UpdateOptions) => HookReturn
): void;
public static beforeUpdate<M extends Model>(
this: { new (): M } & typeof Model,
fn: (instance: M, options: UpdateOptions) => HookReturn
): void;
/**
* A hook that is run after updating a single instance
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static afterUpdate<M extends Model>(
this: { new (): M } & typeof Model,
name: string,
fn: (instance: M, options: UpdateOptions) => HookReturn
): void;
public static afterUpdate<M extends Model>(
this: { new (): M } & typeof Model,
fn: (instance: M, options: UpdateOptions) => HookReturn
): void;
/**
* A hook that is run before creating instances in bulk
*
* @param name
* @param fn A callback function that is called with instances, options
*/
public static beforeBulkCreate<M extends Model>(
this: { new (): M } & typeof Model,
name: string,
fn: (instances: M[], options: BulkCreateOptions) => HookReturn
): void;
public static beforeBulkCreate<M extends Model>(
this: { new (): M } & typeof Model,
fn: (instances: M[], options: BulkCreateOptions) => HookReturn
): void;
/**
* A hook that is run after creating instances in bulk
*
* @param name
* @param fn A callback function that is called with instances, options
*/
public static afterBulkCreate<M extends Model>(
this: { new (): M } & typeof Model,
name: string,
fn: (instances: M[], options: BulkCreateOptions) => HookReturn
): void;
public static afterBulkCreate<M extends Model>(
this: { new (): M } & typeof Model,
fn: (instances: M[], options: BulkCreateOptions) => HookReturn
): void;
/**
* A hook that is run before destroying instances in bulk
*
* @param name
* @param fn A callback function that is called with options
*/
public static beforeBulkDestroy(name: string, fn: (options: BulkCreateOptions) => HookReturn): void;
public static beforeBulkDestroy(fn: (options: BulkCreateOptions) => HookReturn): void;
/**
* A hook that is run after destroying instances in bulk
*
* @param name
* @param fn A callback function that is called with options
*/
public static afterBulkDestroy(name: string, fn: (options: DestroyOptions) => HookReturn): void;
public static afterBulkDestroy(fn: (options: DestroyOptions) => HookReturn): void;
/**
* A hook that is run after updating instances in bulk
*
* @param name
* @param fn A callback function that is called with options
*/
public static beforeBulkUpdate(name: string, fn: (options: UpdateOptions) => HookReturn): void;
public static beforeBulkUpdate(fn: (options: UpdateOptions) => HookReturn): void;
/**
* A hook that is run after updating instances in bulk
*
* @param name
* @param fn A callback function that is called with options
*/
public static afterBulkUpdate(name: string, fn: (options: UpdateOptions) => HookReturn): void;
public static afterBulkUpdate(fn: (options: UpdateOptions) => HookReturn): void;
/**
* A hook that is run before a find (select) query
*
* @param name
* @param fn A callback function that is called with options
*/
public static beforeFind(name: string, fn: (options: FindOptions) => HookReturn): void;
public static beforeFind(fn: (options: FindOptions) => HookReturn): void;
/**
* A hook that is run before a count query
*
* @param name
* @param fn A callback function that is called with options
*/
public static beforeCount(name: string, fn: (options: CountOptions) => HookReturn): void;
public static beforeCount(fn: (options: CountOptions) => HookReturn): void;
/**
* A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded
*
* @param name
* @param fn A callback function that is called with options
*/
public static beforeFindAfterExpandIncludeAll(name: string, fn: (options: FindOptions) => HookReturn): void;
public static beforeFindAfterExpandIncludeAll(fn: (options: FindOptions) => HookReturn): void;
/**
* A hook that is run before a find (select) query, after all option parsing is complete
*
* @param name
* @param fn A callback function that is called with options
*/
public static beforeFindAfterOptions(name: string, fn: (options: FindOptions) => HookReturn): void;
public static beforeFindAfterOptions(fn: (options: FindOptions) => void): HookReturn;
/**
* A hook that is run after a find (select) query
*
* @param name
* @param fn A callback function that is called with instance(s), options
*/
public static afterFind<M extends Model>(
this: { new (): M } & typeof Model,
name: string,
fn: (instancesOrInstance: M[] | M, options: FindOptions) => HookReturn
): void;
public static afterFind<M extends Model>(
this: { new (): M } & typeof Model,
fn: (instancesOrInstance: M[] | M, options: FindOptions) => HookReturn
): void;
/**
* A hook that is run before a define call
*
* @param name
* @param fn A callback function that is called with attributes, options
*/
public static beforeDefine<M extends Model>(
this: { new (): M } & typeof Model,
name: string,
fn: (attributes: ModelAttributes, options: ModelOptions<M>) => void
): void;
public static beforeDefine<M extends Model>(
this: { new (): M } & typeof Model,
fn: (attributes: ModelAttributes, options: ModelOptions<M>) => void
): void;
/**
* A hook that is run after a define call
*
* @param name
* @param fn A callback function that is called with factory
*/
public static afterDefine(name: string, fn: (model: typeof Model) => void): void;
public static afterDefine(fn: (model: typeof Model) => void): void;
/**
* A hook that is run before Sequelize() call
*
* @param name
* @param fn A callback function that is called with config, options
*/
public static beforeInit(name: string, fn: (config: Config, options: Options) => void): void;
public static beforeInit(fn: (config: Config, options: Options) => void): void;
/**
* A hook that is run after Sequelize() call
*
* @param name
* @param fn A callback function that is called with sequelize
*/
public static afterInit(name: string, fn: (sequelize: Sequelize) => void): void;
public static afterInit(fn: (sequelize: Sequelize) => void): void;
/**
* A hook that is run before sequelize.sync call
* @param fn A callback function that is called with options passed to sequelize.sync
*/
public static beforeBulkSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
public static beforeBulkSync(fn: (options: SyncOptions) => HookReturn): void;
/**
* A hook that is run after sequelize.sync call
* @param fn A callback function that is called with options passed to sequelize.sync
*/
public static afterBulkSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
public static afterBulkSync(fn: (options: SyncOptions) => HookReturn): void;
/**
* A hook that is run before Model.sync call
* @param fn A callback function that is called with options passed to Model.sync
*/
public static beforeSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
public static beforeSync(fn: (options: SyncOptions) => HookReturn): void;
/**
* A hook that is run after Model.sync call
* @param fn A callback function that is called with options passed to Model.sync
*/
public static afterSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
public static afterSync(fn: (options: SyncOptions) => HookReturn): void;
/**
* Creates an association between this (the source) and the provided target. The foreign key is added
* on the target.
*
* Example: `User.hasOne(Profile)`. This will add userId to the profile table.
*
* @param target The model that will be associated with hasOne relationship
* @param options Options for the association
*/
public static hasOne(target: typeof Model, options?: HasOneOptions): HasOne;
/**
* Creates an association between this (the source) and the provided target. The foreign key is added on the
* source.
*
* Example: `Profile.belongsTo(User)`. This will add userId to the profile table.
*
* @param target The model that will be associated with hasOne relationship
* @param options Options for the association
*/
public static belongsTo(target: typeof Model, options?: BelongsToOptions): BelongsTo;
/**
* Create an association that is either 1:m or n:m.
*
* ```js
* // Create a 1:m association between user and project
* User.hasMany(Project)
* ```
* ```js
* // Create a n:m association between user and project
* User.hasMany(Project)
* Project.hasMany(User)
* ```
* By default, the name of the join table will be source+target, so in this case projectsusers. This can be
* overridden by providing either a string or a Model as `through` in the options. If you use a through
* model with custom attributes, these attributes can be set when adding / setting new associations in two
* ways. Consider users and projects from before with a join table that stores whether the project has been
* started yet:
* ```js
* var UserProjects = sequelize.define('userprojects', {
* started: Sequelize.BOOLEAN
* })
* User.hasMany(Project, { through: UserProjects })
* Project.hasMany(User, { through: UserProjects })
* ```
* ```js
* jan.addProject(homework, { started: false }) // The homework project is not started yet
* jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner have been
* started
* ```
*
* If you want to set several target instances, but with different attributes you have to set the
* attributes on the instance, using a property with the name of the through model:
*
* ```js
* p1.userprojects {
* started: true
* }
* user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.
* ```
*
* Similarily, when fetching through a join table with custom attributes, these attributes will be
* available as an object with the name of the through model.
* ```js
* user.getProjects().then(function (projects) {
* var p1 = projects[0]
* p1.userprojects.started // Is this project started yet?
* })
* ```
*
* @param target The model that will be associated with hasOne relationship
* @param options Options for the association
*/
public static hasMany(target: typeof Model, options?: HasManyOptions): HasMany;
/**
* Create an N:M association with a join table
*
* ```js
* User.belongsToMany(Project)
* Project.belongsToMany(User)
* ```
* By default, the name of the join table will be source+target, so in this case projectsusers. This can be
* overridden by providing either a string or a Model as `through` in the options.
*
* If you use a through model with custom attributes, these attributes can be set when adding / setting new
* associations in two ways. Consider users and projects from before with a join table that stores whether
* the project has been started yet:
* ```js
* var UserProjects = sequelize.define('userprojects', {
* started: Sequelize.BOOLEAN
* })
* User.belongsToMany(Project, { through: UserProjects })
* Project.belongsToMany(User, { through: UserProjects })
* ```
* ```js
* jan.addProject(homework, { started: false }) // The homework project is not started yet
* jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner has been started
* ```
*
* If you want to set several target instances, but with different attributes you have to set the
* attributes on the instance, using a property with the name of the through model:
*
* ```js
* p1.userprojects {
* started: true
* }
* user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.
* ```
*
* Similarily, when fetching through a join table with custom attributes, these attributes will be
* available as an object with the name of the through model.
* ```js
* user.getProjects().then(function (projects) {
* var p1 = projects[0]
* p1.userprojects.started // Is this project started yet?
* })
* ```
*
* @param target The model that will be associated with hasOne relationship
* @param options Options for the association
*
*/
public static belongsToMany(target: typeof Model, options: BelongsToManyOptions): BelongsToMany;
/**
* Returns true if this instance has not yet been persisted to the database
*/
public isNewRecord: boolean;
/**
* A reference to the sequelize instance
*/
public sequelize: Sequelize;
/**
* Builds a new model instance.
* @param values an object of key value pairs
*/
constructor(values?: object, options?: BuildOptions);
/**
* Get an object representing the query for this instance, use with `options.where`
*/
public where(): object;
/**
* Get the value of the underlying data value
*/
public getDataValue<K extends keyof this>(key: K): this[K];
/**
* Update the underlying data value
*/
public setDataValue<K extends keyof this>(key: K, value: this[K]): void;
/**
* If no key is given, returns all values of the instance, also invoking virtual getters.
*
* If key is given and a field or virtual getter is present for the key it will call that getter - else it
* will return the value for key.
*
* @param options.plain If set to true, included instances will be returned as plain objects
*/
public get(options?: { plain?: boolean; clone?: boolean }): object;
public get(key: string, options?: { plain?: boolean; clone?: boolean }): any;
public get<K extends keyof this>(key: K, options?: { plain?: boolean; clone?: boolean }): this[K];
/**
* Set is used to update values on the instance (the sequelize representation of the instance that is,
* remember that nothing will be persisted before you actually call `save`). In its most basic form `set`
* will update a value stored in the underlying `dataValues` object. However, if a custom setter function
* is defined for the key, that function will be called instead. To bypass the setter, you can pass `raw:
* true` in the options object.
*
* If set is called with an object, it will loop over the object, and call set recursively for each key,
* value pair. If you set raw to true, the underlying dataValues will either be set directly to the object
* passed, or used to extend dataValues, if dataValues already contain values.
*
* When set is called, the previous value of the field is stored and sets a changed flag(see `changed`).
*
* Set can also be used to build instances for associations, if you have values for those.
* When using set with associations you need to make sure the property key matches the alias of the
* association while also making sure that the proper include options have been set (from .build() or
* .findOne())
*
* If called with a dot.seperated key on a JSON/JSONB attribute it will set the value nested and flag the
* entire object as changed.
*
* @param options.raw If set to true, field and virtual setters will be ignored
* @param options.reset Clear all previously set data values
*/
public set<K extends keyof this>(key: K, value: this[K], options?: SetOptions): this;
public set(keys: Partial<this>, options?: SetOptions): this;
public setAttributes<K extends keyof this>(key: K, value: this[K], options?: SetOptions): this;
public setAttributes(keys: object, options?: SetOptions): this;
/**
* If changed is called with a string it will return a boolean indicating whether the value of that key in
* `dataValues` is different from the value in `_previousDataValues`.
*
* If changed is called without an argument, it will return an array of keys that have changed.
*
* If changed is called with two arguments, it will set the property to `dirty`.
*
* If changed is called without an argument and no keys have changed, it will return `false`.
*/
public changed<K extends keyof this>(key: K): boolean;
public changed<K extends keyof this>(key: K, dirty: boolean): void;
public changed(): false | string[];
/**
* Returns the previous value for key from `_previousDataValues`.
*/
public previous<K extends keyof this>(key: K): this[K];
/**
* Validate this instance, and if the validation passes, persist it to the database.
*
* On success, the callback will be called with this instance. On validation error, the callback will be
* called with an instance of `Sequelize.ValidationError`. This error will have a property for each of the
* fields for which validation failed, with the error message for that field.
*/
public save(options?: SaveOptions): Promise<this>;
/**
* Refresh the current instance in-place, i.e. update the object with current data from the DB and return
* the same object. This is different from doing a `find(Instance.id)`, because that would create and
* return a new instance. With this method, all references to the Instance are updated with the new data
* and no new objects are created.
*/
public reload(options?: FindOptions): Promise<this>;
/**
* Validate the attribute of this instance according to validation rules set in the model definition.
*
* Emits null if and only if validation successful; otherwise an Error instance containing
* { field name : [error msgs] } entries.
*
* @param options.skip An array of strings. All properties that are in this array will not be validated
*/
public validate(options?: ValidationOptions): Promise<void>;
/**
* This is the same as calling `set` and then calling `save`.
*/
public update<K extends keyof this>(key: K, value: this[K], options?: InstanceUpdateOptions): Promise<this>;
public update(keys: object, options?: InstanceUpdateOptions): Promise<this>;
/**
* Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will
* either be completely deleted, or have its deletedAt timestamp set to the current time.
*/
public destroy(options?: InstanceDestroyOptions): Promise<void>;
/**
* Restore the row corresponding to this instance. Only available for paranoid models.
*/
public restore(options?: InstanceRestoreOptions): Promise<void>;
/**
* Increment the value of one or more columns. This is done in the database, which means it does not use
* the values currently stored on the Instance. The increment is done using a
* ```sql
* SET column = column + X
* ```
* query. To get the correct value after an increment into the Instance you should do a reload.
*
* ```js
* instance.increment('number') // increment number by 1
* instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2
* instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42, and tries by 1.
* // `by` is ignored, since each column has its own
* // value
* ```
*
* @param fields If a string is provided, that column is incremented by the value of `by` given in options.
* If an array is provided, the same is true for each column.
* If and object is provided, each column is incremented by the value given.
*/
public increment<K extends keyof this>(
fields: K | K[] | Partial<this>,
options?: IncrementDecrementOptionsWithBy
): Promise<this>;
/**
* Decrement the value of one or more columns. This is done in the database, which means it does not use
* the values currently stored on the Instance. The decrement is done using a
* ```sql
* SET column = column - X
* ```
* query. To get the correct value after an decrement into the Instance you should do a reload.
*
* ```js
* instance.decrement('number') // decrement number by 1
* instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2
* instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42, and tries by 1.
* // `by` is ignored, since each column has its own
* // value
* ```
*
* @param fields If a string is provided, that column is decremented by the value of `by` given in options.
* If an array is provided, the same is true for each column.
* If and object is provided, each column is decremented by the value given
*/
public decrement<K extends keyof this>(
fields: K | K[] | Partial<this>,
options?: IncrementDecrementOptionsWithBy
): Promise<this>;
/**
* Check whether all values of this and `other` Instance are the same
*/
public equals(other: this): boolean;
/**
* Check if this is eqaul to one of `others` by calling equals
*/
public equalsOneOf(others: this[]): boolean;
/**
* Convert the instance to a JSON representation. Proxies to calling `get` with no keys. This means get all
* values gotten from the DB, and apply all custom getters.
*/
public toJSON(): object;
}
export default Model;
/**
* object that holds all operator symbols
*/
declare const Op: {
readonly adjacent: unique symbol;
readonly all: unique symbol;
readonly and: unique symbol;
readonly any: unique symbol;
readonly between: unique symbol;
readonly col: unique symbol;
readonly contained: unique symbol;
readonly contains: unique symbol;
readonly endsWith: unique symbol;
readonly eq: unique symbol;
readonly gt: unique symbol;
readonly gte: unique symbol;
readonly iLike: unique symbol;
readonly in: unique symbol;
readonly iRegexp: unique symbol;
readonly is: unique symbol;
readonly like: unique symbol;
readonly lt: unique symbol;
readonly lte: unique symbol;
readonly ne: unique symbol;
readonly noExtendLeft: unique symbol;
readonly noExtendRight: unique symbol;
readonly not: unique symbol;
readonly notBetween: unique symbol;
readonly notILike: unique symbol;
readonly notIn: unique symbol;
readonly notIRegexp: unique symbol;
readonly notLike: unique symbol;
readonly notRegexp: unique symbol;
readonly or: unique symbol;
readonly overlap: unique symbol;
readonly placeholder: unique symbol;
readonly regexp: unique symbol;
readonly startsWith: unique symbol;
readonly strictLeft: unique symbol;
readonly strictRight: unique symbol;
readonly substring: unique symbol;
};
export = Op;
// tslint:disable-next-line:no-implicit-dependencies
import * as Bluebird from 'bluebird';
export const Promise: typeof Bluebird;
export type Promise<T> = Bluebird<T>;
export default Promise;
import { DataType } from './data-types';
import { Logging, Model, ModelAttributeColumnOptions, ModelAttributes, Transactionable, WhereOptions } from './model';
import { Promise } from './promise';
import QueryTypes = require('./query-types');
import { Sequelize } from './sequelize';
import { Transaction } from './transaction';
/**
* Interface for query options
*/
export interface QueryOptions extends Logging, Transactionable {
/**
* If true, sequelize will not try to format the results of the query, or build an instance of a model from
* the result
*/
raw?: boolean;
/**
* The type of query you are executing. The query type affects how results are formatted before they are
* passed back. The type is a string, but `Sequelize.QueryTypes` is provided as convenience shortcuts.
*/
type?: string;
/**
* If true, transforms objects with `.` separated property names into nested objects using
* [dottie.js](https://github.com/mickhansen/dottie.js). For example { 'user.username': 'john' } becomes
* { user: { username: 'john' }}. When `nest` is true, the query type is assumed to be `'SELECT'`,
* unless otherwise specified
*
* @default false
*/
nest?: boolean;
/**
* Sets the query type to `SELECT` and return a single row
*/
plain?: boolean;
/**
* Either an object of named parameter replacements in the format `:param` or an array of unnamed
* replacements to replace `?` in your SQL.
*/
replacements?: {
[key: string]: string | number | string[] | number[];
} | string[];
/**
* Force the query to use the write pool, regardless of the query type.
*
* @default false
*/
useMaster?: boolean;
/**
* A sequelize instance used to build the return instance
*/
instance?: Model;
}
export interface QueryOptionsWithModel {
/**
* A sequelize model used to build the returned model instances (used to be called callee)
*/
model: typeof Model;
}
export interface QueryOptionsWithType<T extends QueryTypes> extends QueryOptions {
/**
* The type of query you are executing. The query type affects how results are formatted before they are
* passed back. The type is a string, but `Sequelize.QueryTypes` is provided as convenience shortcuts.
*/
type: T;
}
/**
* Most of the methods accept options and use only the logger property of the options. That's why the most used
* interface type for options in a method is separated here as another interface.
*/
export interface QueryInterfaceOptions extends Logging, Transactionable {}
export interface CollateCharsetOptions {
collate?: string;
charset?: string;
}
export interface QueryInterfaceCreateTableOptions extends QueryInterfaceOptions, CollateCharsetOptions {
engine?: string;
/**
* Used for compound unique keys.
*/
uniqueKeys?: {
[keyName: string]: {
fields: string[];
customIndex?: boolean;
};
};
}
export interface QueryInterfaceDropTableOptions extends QueryInterfaceOptions {
cascade?: boolean;
force?: boolean;
}
export interface QueryInterfaceDropAllTablesOptions extends QueryInterfaceOptions {
skip?: string[];
}
export interface QueryInterfaceIndexOptions extends QueryInterfaceOptions {
indicesType?: 'UNIQUE' | 'FULLTEXT' | 'SPATIAL';
/** The name of the index. Default is __ */
indexName?: string;
/** For FULLTEXT columns set your parser */
parser?: string;
/** Set a type for the index, e.g. BTREE. See the documentation of the used dialect */
indexType?: string;
}
export interface AddUniqueConstraintOptions {
type: 'unique';
name?: string;
}
export interface AddDefaultConstraintOptions {
type: 'default';
name?: string;
defaultValue?: any;
}
export interface AddCheckConstraintOptions {
type: 'check';
name?: string;
where?: WhereOptions;
}
export interface AddPrimaryKeyConstraintOptions {
type: 'primary key';
name?: string;
}
export interface AddForeignKeyConstraintOptions {
type: 'foreign key';
name?: string;
references?: {
table: string;
field: string;
};
onDelete: string;
onUpdate: string;
}
export type AddConstraintOptions =
| AddUniqueConstraintOptions
| AddDefaultConstraintOptions
| AddCheckConstraintOptions
| AddPrimaryKeyConstraintOptions
| AddForeignKeyConstraintOptions;
export interface CreateDatabaseOptions extends CollateCharsetOptions, QueryOptions {
encoding?: string;
}
/**
* The interface that Sequelize uses to talk to all databases.
*
* This interface is available through sequelize.QueryInterface. It should not be commonly used, but it's
* referenced anyway, so it can be used.
*/
export class QueryInterface {
/**
* Returns the dialect-specific sql generator.
*
* We don't have a definition for the QueryGenerator, because I doubt it is commonly in use separately.
*/
public QueryGenerator: any;
/**
* Returns the current sequelize instance.
*/
public sequelize: Sequelize;
constructor(sequelize: Sequelize);
/**
* Queries the schema (table list).
*
* @param schema The schema to query. Applies only to Postgres.
*/
public createSchema(schema?: string, options?: QueryInterfaceOptions): Promise<void>;
/**
* Drops the specified schema (table).
*
* @param schema The schema to query. Applies only to Postgres.
*/
public dropSchema(schema?: string, options?: QueryInterfaceOptions): Promise<void>;
/**
* Drops all tables.
*/
public dropAllSchemas(options?: QueryInterfaceDropAllTablesOptions): Promise<void>;
/**
* Queries all table names in the database.
*
* @param options
*/
public showAllSchemas(options?: QueryOptions): Promise<object>;
/**
* Return database version
*/
public databaseVersion(options?: QueryInterfaceOptions): Promise<string>;
/**
* Creates a table with specified attributes.
*
* @param tableName Name of table to create
* @param attributes Hash of attributes, key is attribute name, value is data type
* @param options Table options.
*/
public createTable(
tableName: string | { schema?: string; tableName?: string },
attributes: ModelAttributes,
options?: QueryInterfaceCreateTableOptions
): Promise<void>;
/**
* Drops the specified table.
*
* @param tableName Table name.
* @param options Query options, particularly "force".
*/
public dropTable(tableName: string, options?: QueryInterfaceDropTableOptions): Promise<void>;
/**
* Drops all tables.
*
* @param options
*/
public dropAllTables(options?: QueryInterfaceDropTableOptions): Promise<void>;
/**
* Drops all defined enums
*
* @param options
*/
public dropAllEnums(options?: QueryOptions): Promise<void>;
/**
* Renames a table
*/
public renameTable(before: string, after: string, options?: QueryInterfaceOptions): Promise<void>;
/**
* Returns all tables
*/
public showAllTables(options?: QueryOptions): Promise<string[]>;
/**
* Describe a table
*/
public describeTable(
tableName: string | { schema?: string; tableName?: string },
options?: string | { schema?: string; schemaDelimiter?: string } & Logging
): Promise<object>;
/**
* Adds a new column to a table
*/
public addColumn(
table: string | { schema?: string; tableName?: string },
key: string,
attribute: ModelAttributeColumnOptions | DataType,
options?: QueryInterfaceOptions
): Promise<void>;
/**
* Removes a column from a table
*/
public removeColumn(
table: string | { schema?: string; tableName?: string },
attribute: string,
options?: QueryInterfaceOptions
): Promise<void>;
/**
* Changes a column
*/
public changeColumn(
tableName: string | { schema?: string; tableName?: string },
attributeName: string,
dataTypeOrOptions?: DataType | ModelAttributeColumnOptions,
options?: QueryInterfaceOptions
): Promise<void>;
/**
* Renames a column
*/
public renameColumn(
tableName: string | { schema?: string; tableName?: string },
attrNameBefore: string,
attrNameAfter: string,
options?: QueryInterfaceOptions
): Promise<void>;
/**
* Adds a new index to a table
*/
public addIndex(
tableName: string,
attributes: string[],
options?: QueryInterfaceIndexOptions,
rawTablename?: string
): Promise<void>;
public addIndex(
tableName: string,
options: QueryInterfaceIndexOptions & { fields: string[] },
rawTablename?: string
): Promise<void>;
/**
* Removes an index of a table
*/
public removeIndex(tableName: string, indexName: string, options?: QueryInterfaceIndexOptions): Promise<void>;
public removeIndex(tableName: string, attributes: string[], options?: QueryInterfaceIndexOptions): Promise<void>;
/**
* Adds constraints to a table
*/
public addConstraint(
tableName: string,
attributes: string[],
options?: AddConstraintOptions | QueryInterfaceOptions
): Promise<void>;
/**
* Removes constraints from a table
*/
public removeConstraint(tableName: string, constraintName: string, options?: QueryInterfaceOptions): Promise<void>;
/**
* Shows the index of a table
*/
public showIndex(tableName: string | object, options?: QueryOptions): Promise<object>;
/**
* Put a name to an index
*/
public nameIndexes(indexes: string[], rawTablename: string): Promise<void>;
/**
* Returns all foreign key constraints of a table
*/
public getForeignKeysForTables(tableNames: string, options?: QueryInterfaceOptions): Promise<object>;
/**
* Inserts a new record
*/
public insert(instance: Model, tableName: string, values: object, options?: QueryOptions): Promise<object>;
/**
* Inserts or Updates a record in the database
*/
public upsert(
tableName: string,
values: object,
updateValues: object,
model: typeof Model,
options?: QueryOptions
): Promise<object>;
/**
* Inserts multiple records at once
*/
public bulkInsert(
tableName: string,
records: object[],
options?: QueryOptions,
attributes?: string[] | string
): Promise<object>;
/**
* Updates a row
*/
public update(
instance: Model,
tableName: string,
values: object,
identifier: object,
options?: QueryOptions
): Promise<object>;
/**
* Updates multiple rows at once
*/
public bulkUpdate(
tableName: string,
values: object,
identifier: object,
options?: QueryOptions,
attributes?: string[] | string
): Promise<object>;
/**
* Deletes a row
*/
public delete(instance: Model, tableName: string, identifier: object, options?: QueryOptions): Promise<object>;
/**
* Deletes multiple rows at once
*/
public bulkDelete(
tableName: string,
identifier: object,
options?: QueryOptions,
model?: typeof Model
): Promise<object>;
/**
* Returns selected rows
*/
public select(model: typeof Model, tableName: string, options?: QueryOptions): Promise<object[]>;
/**
* Increments a row value
*/
public increment(
instance: Model,
tableName: string,
values: object,
identifier: object,
options?: QueryOptions
): Promise<object>;
/**
* Selects raw without parsing the string into an object
*/
public rawSelect(
tableName: string,
options: QueryOptions,
attributeSelector: string | string[],
model?: typeof Model
): Promise<string[]>;
/**
* Postgres only. Creates a trigger on specified table to call the specified function with supplied
* parameters.
*/
public createTrigger(
tableName: string,
triggerName: string,
timingType: string,
fireOnArray: any[],
functionName: string,
functionParams: any[],
optionsArray: string[],
options?: QueryInterfaceOptions
): Promise<void>;
/**
* Postgres only. Drops the specified trigger.
*/
public dropTrigger(tableName: string, triggerName: string, options?: QueryInterfaceOptions): Promise<void>;
/**
* Postgres only. Renames a trigger
*/
public renameTrigger(
tableName: string,
oldTriggerName: string,
newTriggerName: string,
options?: QueryInterfaceOptions
): Promise<void>;
/**
* Postgres only. Create a function
*/
public createFunction(
functionName: string,
params: any[],
returnType: string,
language: string,
body: string,
options?: QueryOptions
): Promise<void>;
/**
* Postgres only. Drops a function
*/
public dropFunction(functionName: string, params: any[], options?: QueryInterfaceOptions): Promise<void>;
/**
* Postgres only. Rename a function
*/
public renameFunction(
oldFunctionName: string,
params: any[],
newFunctionName: string,
options?: QueryInterfaceOptions
): Promise<void>;
/**
* Escape an identifier (e.g. a table or attribute name). If force is true, the identifier will be quoted
* even if the `quoteIdentifiers` option is false.
*/
public quoteIdentifier(identifier: string, force: boolean): string;
/**
* Escape a table name
*/
public quoteTable(identifier: string): string;
/**
* Split an identifier into .-separated tokens and quote each part. If force is true, the identifier will be
* quoted even if the `quoteIdentifiers` option is false.
*/
public quoteIdentifiers(identifiers: string, force: boolean): string;
/**
* Escape a value (e.g. a string, number or date)
*/
public escape(value?: string | number | Date): string;
/**
* Set option for autocommit of a transaction
*/
public setAutocommit(transaction: Transaction, value: boolean, options?: QueryOptions): Promise<void>;
/**
* Set the isolation level of a transaction
*/
public setIsolationLevel(transaction: Transaction, value: string, options?: QueryOptions): Promise<void>;
/**
* Begin a new transaction
*/
public startTransaction(transaction: Transaction, options?: QueryOptions): Promise<void>;
/**
* Defer constraints
*/
public deferConstraints(transaction: Transaction, options?: QueryOptions): Promise<void>;
/**
* Commit an already started transaction
*/
public commitTransaction(transaction: Transaction, options?: QueryOptions): Promise<void>;
/**
* Rollback ( revert ) a transaction that has'nt been commited
*/
public rollbackTransaction(transaction: Transaction, options?: QueryOptions): Promise<void>;
/**
* Creates a database
*/
public createDatabase(name: string, options?: CreateDatabaseOptions): Promise<void>;
/**
* Creates a database
*/
public dropDatabase(name: string, options?: QueryOptions): Promise<void>;
}
declare enum QueryTypes {
SELECT = 'SELECT',
INSERT = 'INSERT',
UPDATE = 'UPDATE',
BULKUPDATE = 'BULKUPDATE',
BULKDELETE = 'BULKDELETE',
DELETE = 'DELETE',
UPSERT = 'UPSERT',
VERSION = 'VERSION',
SHOWTABLES = 'SHOWTABLES',
SHOWINDEXES = 'SHOWINDEXES',
DESCRIBE = 'DESCRIBE',
RAW = 'RAW',
FOREIGNKEYS = 'FOREIGNKEYS',
}
export = QueryTypes;
import * as DataTypes from './data-types';
import * as Deferrable from './deferrable';
import { HookReturn, Hooks, SequelizeHooks } from './hooks';
import { ValidationOptions } from './instance-validator';
import {
AndOperator,
BulkCreateOptions,
CreateOptions,
DestroyOptions,
DropOptions,
FindOptions,
InstanceDestroyOptions,
Logging,
Model,
ModelAttributeColumnOptions,
ModelAttributes,
ModelOptions,
OrOperator,
UpdateOptions,
WhereAttributeHash,
WhereOperators,
} from './model';
import { ModelManager } from './model-manager';
import * as Op from './operators';
import { Promise } from './promise';
import { QueryInterface, QueryOptions, QueryOptionsWithModel, QueryOptionsWithType } from './query-interface';
import QueryTypes = require('./query-types');
import { Transaction, TransactionOptions } from './transaction';
import { Cast, Col, Fn, Json, Literal, Where } from './utils';
// tslint:disable-next-line:no-duplicate-imports
import * as Utils from './utils';
import { validator } from './utils/validator-extras';
import { ConnectionManager } from './connection-manager';
/**
* Sync Options
*/
export interface SyncOptions extends Logging {
/**
* If force is true, each DAO will do DROP TABLE IF EXISTS ..., before it tries to create its own table
*/
force?: boolean;
/**
* Match a regex against the database name before syncing, a safety check for cases where force: true is
* used in tests but not live code
*/
match?: RegExp;
/**
* The schema that the tables should be created in. This can be overriden for each table in sequelize.define
*/
schema?: string;
}
export interface DefaultSetOptions {}
/**
* Connection Pool options
*/
export interface PoolOptions {
/**
* Maximum number of connections in pool. Default is 5
*/
max?: number;
/**
* Minimum number of connections in pool. Default is 0
*/
min?: number;
/**
* The maximum time, in milliseconds, that a connection can be idle before being released
*/
idle?: number;
/**
* The maximum time, in milliseconds, that pool will try to get connection before throwing error
*/
acquire?: number;
/**
* A function that validates a connection. Called with client. The default function checks that client is an
* object, and that its state is not disconnected
*/
validate?(client?: any): boolean;
}
/**
* Interface for replication Options in the sequelize constructor
*/
export interface ReplicationOptions {
read?: {
host?: string;
port?: string | number;
username?: string;
password?: string;
database?: string;
};
write?: {
host?: string;
port?: string | number;
username?: string;
password?: string;
database?: string;
};
}
/**
* Used to map operators to their Symbol representations
*/
export interface OperatorsAliases {
[K: string]: symbol;
}
/**
* Final config options generated by sequelize.
*/
export interface Config {
readonly database: string;
readonly host?: string;
readonly port?: string;
readonly username: string;
readonly password: string | null;
readonly pool?: {
readonly acquire: number;
readonly idle: number;
readonly max: number;
readonly min: number;
};
readonly protocol: 'tcp';
readonly native: boolean;
readonly ssl: any;
readonly replication: boolean;
readonly dialectModulePath: null | string;
readonly keepDefaultTimezone?: boolean;
readonly dialectOptions?: {
readonly charset?: string;
readonly timeout?: number;
};
}
export type Dialect = 'mysql' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql' | 'mariadb';
/**
* Options for the constructor of Sequelize main class
*/
export interface Options extends Logging {
/**
* The dialect of the database you are connecting to. One of mysql, postgres, sqlite, mariadb and mssql.
*
* @default 'mysql'
*/
dialect?: Dialect;
/**
* If specified, load the dialect library from this path. For example, if you want to use pg.js instead of
* pg when connecting to a pg database, you should specify 'pg.js' here
*/
dialectModulePath?: string;
/**
* An object of additional options, which are passed directly to the connection library
*/
dialectOptions?: object;
/**
* Only used by sqlite.
*
* @default ':memory:'
*/
storage?: string;
/**
* The name of the database
*/
database?: string;
/**
* The username which is used to authenticate against the database.
*/
username?: string;
/**
* The password which is used to authenticate against the database.
*/
password?: string;
/**
* The host of the relational database.
*
* @default 'localhost'
*/
host?: string;
/**
* The port of the relational database.
*/
port?: number;
/**
* A flag that defines if is used SSL.
*/
ssl?: boolean;
/**
* The protocol of the relational database.
*
* @default 'tcp'
*/
protocol?: string;
/**
* Default options for model definitions. See sequelize.define for options
*/
define?: ModelOptions;
/**
* Default options for sequelize.query
*/
query?: QueryOptions;
/**
* Default options for sequelize.set
*/
set?: DefaultSetOptions;
/**
* Default options for sequelize.sync
*/
sync?: SyncOptions;
/**
* The timezone used when converting a date from the database into a JavaScript date. The timezone is also
* used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP
* and other time related functions have in the right timezone. For best cross platform performance use the
* format
* +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles');
* this is useful to capture daylight savings time changes.
*
* @default '+00:00'
*/
timezone?: string;
/**
* A flag that defines if null values should be passed to SQL queries or not.
*
* @default false
*/
omitNull?: boolean;
/**
* A flag that defines if native library shall be used or not. Currently only has an effect for postgres
*
* @default false
*/
native?: boolean;
/**
* Use read / write replication. To enable replication, pass an object, with two properties, read and write.
* Write should be an object (a single server for handling writes), and read an array of object (several
* servers to handle reads). Each read/write server can have the following properties: `host`, `port`,
* `username`, `password`, `database`
*
* @default false
*/
replication?: ReplicationOptions;
/**
* Connection pool options
*/
pool?: PoolOptions;
/**
* Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of
* them.
*
* @default true
*/
quoteIdentifiers?: boolean;
/**
* Set the default transaction isolation level. See `Sequelize.Transaction.ISOLATION_LEVELS` for possible
* options.
*
* @default 'REPEATABLE_READ'
*/
isolationLevel?: string;
/**
* Run built in type validators on insert and update, e.g. validate that arguments passed to integer
* fields are integer-like.
*
* @default false
*/
typeValidation?: boolean;
/**
* Sets available operator aliases. See (http://docs.sequelizejs.com/manual/tutorial/querying.html#operators)
* for more information. Set to false to disable operator aliases completely (recommended)
*
* @default all aliases
*/
operatorsAliases: OperatorsAliases | false;
}
export interface QueryOptionsTransactionRequired {}
/**
* This is the main class, the entry point to sequelize. To use it, you just need to
* import sequelize:
*
* ```js
* var Sequelize = require('sequelize');
* ```
*
* In addition to sequelize, the connection library for the dialect you want to use
* should also be installed in your project. You don't need to import it however, as
* sequelize will take care of that.
*/
export class Sequelize extends Hooks {
// -------------------- Utilities ------------------------------------------------------------------------
/**
* Creates a object representing a database function. This can be used in search queries, both in where and
* order parts, and as default values in column definitions. If you want to refer to columns in your
* function, you should use `sequelize.col`, so that the columns are properly interpreted as columns and
* not a strings.
*
* Convert a user's username to upper case
* ```js
* instance.update({
* username: self.sequelize.fn('upper', self.sequelize.col('username'))
* })
* ```
* @param fn The function you want to call
* @param args All further arguments will be passed as arguments to the function
*/
public static fn: typeof fn;
/**
* Creates a object representing a column in the DB. This is often useful in conjunction with
* `sequelize.fn`, since raw string arguments to fn will be escaped.
*
* @param col The name of the column
*/
public static col: typeof col;
/**
* Creates a object representing a call to the cast function.
*
* @param val The value to cast
* @param type The type to cast it to
*/
public static cast: typeof cast;
/**
* Creates a object representing a literal, i.e. something that will not be escaped.
*
* @param val
*/
public static literal: typeof literal;
/**
* An AND query
*
* @param args Each argument will be joined by AND
*/
public static and: typeof and;
/**
* An OR query
*
* @param args Each argument will be joined by OR
*/
public static or: typeof or;
/**
* Creates an object representing nested where conditions for postgres's json data-type.
*
* @param conditionsOrPath A hash containing strings/numbers or other nested hash, a string using dot
* notation or a string using postgres json syntax.
* @param value An optional value to compare against. Produces a string of the form "<json path> =
* '<value>'".
*/
public static json: typeof json;
/**
* A way of specifying attr = condition.
*
* The attr can either be an object taken from `Model.rawAttributes` (for example `Model.rawAttributes.id`
* or
* `Model.rawAttributes.name`). The attribute should be defined in your model definition. The attribute can
* also be an object from one of the sequelize utility functions (`sequelize.fn`, `sequelize.col` etc.)
*
* For string attributes, use the regular `{ where: { attr: something }}` syntax. If you don't want your
* string to be escaped, use `sequelize.literal`.
*
* @param attr The attribute, which can be either an attribute object from `Model.rawAttributes` or a
* sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the
* POJO syntax
* @param comparator Comparator
* @param logic The condition. Can be both a simply type, or a further condition (`.or`, `.and`, `.literal`
* etc.)
*/
public static where: typeof where;
/**
* A hook that is run before validation
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static beforeValidate(name: string, fn: (instance: Model, options: ValidationOptions) => void): void;
public static beforeValidate(fn: (instance: Model, options: ValidationOptions) => void): void;
/**
* A hook that is run after validation
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static afterValidate(name: string, fn: (instance: Model, options: ValidationOptions) => void): void;
public static afterValidate(fn: (instance: Model, options: ValidationOptions) => void): void;
/**
* A hook that is run before creating a single instance
*
* @param name
* @param fn A callback function that is called with attributes, options
*/
public static beforeCreate(name: string, fn: (attributes: Model, options: CreateOptions) => void): void;
public static beforeCreate(fn: (attributes: Model, options: CreateOptions) => void): void;
/**
* A hook that is run after creating a single instance
*
* @param name
* @param fn A callback function that is called with attributes, options
*/
public static afterCreate(name: string, fn: (attributes: Model, options: CreateOptions) => void): void;
public static afterCreate(fn: (attributes: Model, options: CreateOptions) => void): void;
/**
* A hook that is run before destroying a single instance
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static beforeDestroy(name: string, fn: (instance: Model, options: InstanceDestroyOptions) => void): void;
public static beforeDestroy(fn: (instance: Model, options: InstanceDestroyOptions) => void): void;
/**
* A hook that is run after destroying a single instance
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static afterDestroy(name: string, fn: (instance: Model, options: InstanceDestroyOptions) => void): void;
public static afterDestroy(fn: (instance: Model, options: InstanceDestroyOptions) => void): void;
/**
* A hook that is run before updating a single instance
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static beforeUpdate(name: string, fn: (instance: Model, options: UpdateOptions) => void): void;
public static beforeUpdate(fn: (instance: Model, options: UpdateOptions) => void): void;
/**
* A hook that is run after updating a single instance
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static afterUpdate(name: string, fn: (instance: Model, options: UpdateOptions) => void): void;
public static afterUpdate(fn: (instance: Model, options: UpdateOptions) => void): void;
/**
* A hook that is run before creating instances in bulk
*
* @param name
* @param fn A callback function that is called with instances, options
*/
public static beforeBulkCreate(name: string, fn: (instances: Model[], options: BulkCreateOptions) => void): void;
public static beforeBulkCreate(fn: (instances: Model[], options: BulkCreateOptions) => void): void;
/**
* A hook that is run after creating instances in bulk
*
* @param name
* @param fn A callback function that is called with instances, options
*/
public static afterBulkCreate(name: string, fn: (instances: Model[], options: BulkCreateOptions) => void): void;
public static afterBulkCreate(fn: (instances: Model[], options: BulkCreateOptions) => void): void;
/**
* A hook that is run before destroying instances in bulk
*
* @param name
* @param fn A callback function that is called with options
*/
public static beforeBulkDestroy(name: string, fn: (options: BulkCreateOptions) => void): void;
public static beforeBulkDestroy(fn: (options: BulkCreateOptions) => void): void;
/**
* A hook that is run after destroying instances in bulk
*
* @param name
* @param fn A callback function that is called with options
*/
public static afterBulkDestroy(name: string, fn: (options: DestroyOptions) => void): void;
public static afterBulkDestroy(fn: (options: DestroyOptions) => void): void;
/**
* A hook that is run after updating instances in bulk
*
* @param name
* @param fn A callback function that is called with options
*/
public static beforeBulkUpdate(name: string, fn: (options: UpdateOptions) => void): void;
public static beforeBulkUpdate(fn: (options: UpdateOptions) => void): void;
/**
* A hook that is run after updating instances in bulk
*
* @param name
* @param fn A callback function that is called with options
*/
public static afterBulkUpdate(name: string, fn: (options: UpdateOptions) => void): void;
public static afterBulkUpdate(fn: (options: UpdateOptions) => void): void;
/**
* A hook that is run before a find (select) query
*
* @param name
* @param fn A callback function that is called with options
*/
public static beforeFind(name: string, fn: (options: FindOptions) => void): void;
public static beforeFind(fn: (options: FindOptions) => void): void;
/**
* A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded
*
* @param name
* @param fn A callback function that is called with options
*/
public static beforeFindAfterExpandIncludeAll(name: string, fn: (options: FindOptions) => void): void;
public static beforeFindAfterExpandIncludeAll(fn: (options: FindOptions) => void): void;
/**
* A hook that is run before a find (select) query, after all option parsing is complete
*
* @param name
* @param fn A callback function that is called with options
*/
public static beforeFindAfterOptions(name: string, fn: (options: FindOptions) => void): void;
public static beforeFindAfterOptions(fn: (options: FindOptions) => void): void;
/**
* A hook that is run after a find (select) query
*
* @param name
* @param fn A callback function that is called with instance(s), options
*/
public static afterFind(
name: string,
fn: (instancesOrInstance: Model[] | Model, options: FindOptions) => void
): void;
public static afterFind(
fn: (instancesOrInstance: Model[] | Model, options: FindOptions) => void
): void;
/**
* A hook that is run before a define call
*
* @param name
* @param fn A callback function that is called with attributes, options
*/
public static beforeDefine<M extends Model>(
name: string,
fn: (attributes: ModelAttributes, options: ModelOptions<M>) => void
): void;
public static beforeDefine<M extends Model>(
fn: (attributes: ModelAttributes, options: ModelOptions<M>) => void
): void;
/**
* A hook that is run after a define call
*
* @param name
* @param fn A callback function that is called with factory
*/
public static afterDefine(name: string, fn: (model: typeof Model) => void): void;
public static afterDefine(fn: (model: typeof Model) => void): void;
/**
* A hook that is run before Sequelize() call
*
* @param name
* @param fn A callback function that is called with config, options
*/
public static beforeInit(name: string, fn: (config: Config, options: Options) => void): void;
public static beforeInit(fn: (config: Config, options: Options) => void): void;
/**
* A hook that is run after Sequelize() call
*
* @param name
* @param fn A callback function that is called with sequelize
*/
public static afterInit(name: string, fn: (sequelize: Sequelize) => void): void;
public static afterInit(fn: (sequelize: Sequelize) => void): void;
/**
* A hook that is run before sequelize.sync call
* @param fn A callback function that is called with options passed to sequelize.sync
*/
public static beforeBulkSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
public static beforeBulkSync(fn: (options: SyncOptions) => HookReturn): void;
/**
* A hook that is run after sequelize.sync call
* @param fn A callback function that is called with options passed to sequelize.sync
*/
public static afterBulkSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
public static afterBulkSync(fn: (options: SyncOptions) => HookReturn): void;
/**
* A hook that is run before Model.sync call
* @param fn A callback function that is called with options passed to Model.sync
*/
public static beforeSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
public static beforeSync(fn: (options: SyncOptions) => HookReturn): void;
/**
* A hook that is run after Model.sync call
* @param fn A callback function that is called with options passed to Model.sync
*/
public static afterSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
public static afterSync(fn: (options: SyncOptions) => HookReturn): void;
/**
* A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc.
*/
public Sequelize: typeof Sequelize;
/**
* Final config that is used by sequelize.
*/
public readonly config: Config;
public readonly modelManager: ModelManager;
public readonly connectionManager: ConnectionManager;
/**
* Instantiate sequelize with name of database, username and password
*
* #### Example usage
*
* ```javascript
* // without password and options
* var sequelize = new Sequelize('database', 'username')
*
* // without options
* var sequelize = new Sequelize('database', 'username', 'password')
*
* // without password / with blank password
* var sequelize = new Sequelize('database', 'username', null, {})
*
* // with password and options
* var sequelize = new Sequelize('my_database', 'john', 'doe', {})
*
* // with uri (see below)
* var sequelize = new Sequelize('mysql://localhost:3306/database', {})
* ```
*
* @param database The name of the database
* @param username The username which is used to authenticate against the
* database.
* @param password The password which is used to authenticate against the
* database.
* @param options An object with options.
*/
constructor(database: string, username: string, password?: string, options?: Options);
constructor(database: string, username: string, options?: Options);
constructor(options?: Options);
/**
* Instantiate sequelize with an URI
* @param uri A full database URI
* @param options See above for possible options
*/
constructor(uri: string, options?: Options);
/**
* A hook that is run before validation
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public beforeValidate(name: string, fn: (instance: Model, options: ValidationOptions) => void): void;
public beforeValidate(fn: (instance: Model, options: ValidationOptions) => void): void;
/**
* A hook that is run after validation
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public afterValidate(name: string, fn: (instance: Model, options: ValidationOptions) => void): void;
public afterValidate(fn: (instance: Model, options: ValidationOptions) => void): void;
/**
* A hook that is run before creating a single instance
*
* @param name
* @param fn A callback function that is called with attributes, options
*/
public beforeCreate(name: string, fn: (attributes: Model, options: CreateOptions) => void): void;
public beforeCreate(fn: (attributes: Model, options: CreateOptions) => void): void;
/**
* A hook that is run after creating a single instance
*
* @param name
* @param fn A callback function that is called with attributes, options
*/
public afterCreate(name: string, fn: (attributes: Model, options: CreateOptions) => void): void;
public afterCreate(fn: (attributes: Model, options: CreateOptions) => void): void;
/**
* A hook that is run before destroying a single instance
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public beforeDestroy(name: string, fn: (instance: Model, options: InstanceDestroyOptions) => void): void;
public beforeDestroy(fn: (instance: Model, options: InstanceDestroyOptions) => void): void;
/**
* A hook that is run after destroying a single instance
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public afterDestroy(name: string, fn: (instance: Model, options: InstanceDestroyOptions) => void): void;
public afterDestroy(fn: (instance: Model, options: InstanceDestroyOptions) => void): void;
/**
* A hook that is run before updating a single instance
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public beforeUpdate(name: string, fn: (instance: Model, options: UpdateOptions) => void): void;
public beforeUpdate(fn: (instance: Model, options: UpdateOptions) => void): void;
/**
* A hook that is run after updating a single instance
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public afterUpdate(name: string, fn: (instance: Model, options: UpdateOptions) => void): void;
public afterUpdate(fn: (instance: Model, options: UpdateOptions) => void): void;
/**
* A hook that is run before creating instances in bulk
*
* @param name
* @param fn A callback function that is called with instances, options
*/
public beforeBulkCreate(name: string, fn: (instances: Model[], options: BulkCreateOptions) => void): void;
public beforeBulkCreate(fn: (instances: Model[], options: BulkCreateOptions) => void): void;
/**
* A hook that is run after creating instances in bulk
*
* @param name
* @param fn A callback function that is called with instances, options
*/
public afterBulkCreate(name: string, fn: (instances: Model[], options: BulkCreateOptions) => void): void;
public afterBulkCreate(fn: (instances: Model[], options: BulkCreateOptions) => void): void;
/**
* A hook that is run before destroying instances in bulk
*
* @param name
* @param fn A callback function that is called with options
*/
public beforeBulkDestroy(name: string, fn: (options: BulkCreateOptions) => void): void;
public beforeBulkDestroy(fn: (options: BulkCreateOptions) => void): void;
/**
* A hook that is run after destroying instances in bulk
*
* @param name
* @param fn A callback function that is called with options
*/
public afterBulkDestroy(name: string, fn: (options: DestroyOptions) => void): void;
public afterBulkDestroy(fn: (options: DestroyOptions) => void): void;
/**
* A hook that is run after updating instances in bulk
*
* @param name
* @param fn A callback function that is called with options
*/
public beforeBulkUpdate(name: string, fn: (options: UpdateOptions) => void): void;
public beforeBulkUpdate(fn: (options: UpdateOptions) => void): void;
/**
* A hook that is run after updating instances in bulk
*
* @param name
* @param fn A callback function that is called with options
*/
public afterBulkUpdate(name: string, fn: (options: UpdateOptions) => void): void;
public afterBulkUpdate(fn: (options: UpdateOptions) => void): void;
/**
* A hook that is run before a find (select) query
*
* @param name
* @param fn A callback function that is called with options
*/
public beforeFind(name: string, fn: (options: FindOptions) => void): void;
public beforeFind(fn: (options: FindOptions) => void): void;
/**
* A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded
*
* @param name
* @param fn A callback function that is called with options
*/
public beforeFindAfterExpandIncludeAll(name: string, fn: (options: FindOptions) => void): void;
public beforeFindAfterExpandIncludeAll(fn: (options: FindOptions) => void): void;
/**
* A hook that is run before a find (select) query, after all option parsing is complete
*
* @param name
* @param fn A callback function that is called with options
*/
public beforeFindAfterOptions(name: string, fn: (options: FindOptions) => void): void;
public beforeFindAfterOptions(fn: (options: FindOptions) => void): void;
/**
* A hook that is run after a find (select) query
*
* @param name
* @param fn A callback function that is called with instance(s), options
*/
public afterFind(
name: string,
fn: (instancesOrInstance: Model[] | Model, options: FindOptions) => void
): void;
public afterFind(fn: (instancesOrInstance: Model[] | Model, options: FindOptions) => void): void;
/**
* A hook that is run before a define call
*
* @param name
* @param fn A callback function that is called with attributes, options
*/
public beforeDefine(name: string, fn: (attributes: ModelAttributes, options: ModelOptions) => void): void;
public beforeDefine(fn: (attributes: ModelAttributes, options: ModelOptions) => void): void;
/**
* A hook that is run after a define call
*
* @param name
* @param fn A callback function that is called with factory
*/
public afterDefine(name: string, fn: (model: typeof Model) => void): void;
public afterDefine(fn: (model: typeof Model) => void): void;
/**
* A hook that is run before Sequelize() call
*
* @param name
* @param fn A callback function that is called with config, options
*/
public beforeInit(name: string, fn: (config: Config, options: Options) => void): void;
public beforeInit(fn: (config: Config, options: Options) => void): void;
/**
* A hook that is run after Sequelize() call
*
* @param name
* @param fn A callback function that is called with sequelize
*/
public afterInit(name: string, fn: (sequelize: Sequelize) => void): void;
public afterInit(fn: (sequelize: Sequelize) => void): void;
/**
* A hook that is run before sequelize.sync call
* @param fn A callback function that is called with options passed to sequelize.sync
*/
public beforeBulkSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
public beforeBulkSync(fn: (options: SyncOptions) => HookReturn): void;
/**
* A hook that is run after sequelize.sync call
* @param fn A callback function that is called with options passed to sequelize.sync
*/
public afterBulkSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
public afterBulkSync(fn: (options: SyncOptions) => HookReturn): void;
/**
* A hook that is run before Model.sync call
* @param fn A callback function that is called with options passed to Model.sync
*/
public beforeSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
public beforeSync(fn: (options: SyncOptions) => HookReturn): void;
/**
* A hook that is run after Model.sync call
* @param fn A callback function that is called with options passed to Model.sync
*/
public afterSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
public afterSync(fn: (options: SyncOptions) => HookReturn): void;
/**
* Returns the specified dialect.
*/
public getDialect(): string;
/**
* Returns an instance of QueryInterface.
*/
public getQueryInterface(): QueryInterface;
/**
* Define a new model, representing a table in the DB.
*
* The table columns are define by the hash that is given as the second argument. Each attribute of the
* hash
* represents a column. A short table definition might look like this:
*
* ```js
* sequelize.define('modelName', {
* columnA: {
* type: Sequelize.BOOLEAN,
* validate: {
* is: ["[a-z]",'i'], // will only allow letters
* max: 23, // only allow values <= 23
* isIn: {
* args: [['en', 'zh']],
* msg: "Must be English or Chinese"
* }
* },
* field: 'column_a'
* // Other attributes here
* },
* columnB: Sequelize.STRING,
* columnC: 'MY VERY OWN COLUMN TYPE'
* })
*
* sequelize.models.modelName // The model will now be available in models under the name given to define
* ```
*
* As shown above, column definitions can be either strings, a reference to one of the datatypes that are
* predefined on the Sequelize constructor, or an object that allows you to specify both the type of the
* column, and other attributes such as default values, foreign key constraints and custom setters and
* getters.
*
* For a list of possible data types, see
* http://docs.sequelizejs.com/en/latest/docs/models-definition/#data-types
*
* For more about getters and setters, see
* http://docs.sequelizejs.com/en/latest/docs/models-definition/#getters-setters
*
* For more about instance and class methods, see
* http://docs.sequelizejs.com/en/latest/docs/models-definition/#expansion-of-models
*
* For more about validation, see
* http://docs.sequelizejs.com/en/latest/docs/models-definition/#validations
*
* @param modelName The name of the model. The model will be stored in `sequelize.models` under this name
* @param attributes An object, where each attribute is a column of the table. Each column can be either a
* DataType, a string or a type-description object, with the properties described below:
* @param options These options are merged with the default define options provided to the Sequelize
* constructor
*/
public define(modelName: string, attributes: ModelAttributes, options?: ModelOptions): typeof Model;
/**
* Fetch a Model which is already defined
*
* @param modelName The name of a model defined with Sequelize.define
*/
public model(modelName: string): typeof Model;
/**
* Checks whether a model with the given name is defined
*
* @param modelName The name of a model defined with Sequelize.define
*/
public isDefined(modelName: string): boolean;
/**
* Imports a model defined in another file
*
* Imported models are cached, so multiple calls to import with the same path will not load the file
* multiple times
*
* See https://github.com/sequelize/sequelize/blob/master/examples/using-multiple-model-files/Task.js for a
* short example of how to define your models in separate files so that they can be imported by
* sequelize.import
*
* @param path The path to the file that holds the model you want to import. If the part is relative, it
* will be resolved relatively to the calling file
*
* @param defineFunction An optional function that provides model definitions. Useful if you do not
* want to use the module root as the define function
*/
public import<T extends typeof Model>(
path: string,
defineFunction?: (sequelize: Sequelize, dataTypes: typeof DataTypes) => T
): T;
/**
* Execute a query on the DB, with the posibility to bypass all the sequelize goodness.
*
* By default, the function will return two arguments: an array of results, and a metadata object,
* containing number of affected rows etc. Use `.spread` to access the results.
*
* If you are running a type of query where you don't need the metadata, for example a `SELECT` query, you
* can pass in a query type to make sequelize format the results:
*
* ```js
* sequelize.query('SELECT...').spread(function (results, metadata) {
* // Raw query - use spread
* });
*
* sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(function (results) {
* // SELECT query - use then
* })
* ```
*
* @param sql
* @param options Query options
*/
public query(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.UPDATE>): Promise<[undefined, number]>;
public query(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.BULKUPDATE>): Promise<number>;
public query(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.INSERT>): Promise<[number, number]>;
public query(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.UPSERT>): Promise<number>;
public query(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.DELETE>): Promise<void>;
public query(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.BULKDELETE>): Promise<number>;
public query(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.SHOWTABLES>): Promise<string[]>;
public query(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.DESCRIBE>): Promise<{
[key: string]: {
type: string;
allowNull: boolean;
defaultValue: string;
primaryKey: boolean;
autoIncrement: boolean;
comment: string | null;
}
}>;
public query<M extends Model>(
sql: string | { query: string; values: any[] },
options: QueryOptionsWithModel
): Promise<M[]>;
public query<T extends object>(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.SELECT>): Promise<T[]>;
public query(sql: string | { query: string; values: any[] }, options?: QueryOptions | QueryOptionsWithType<QueryTypes.RAW>): Promise<unknown[]>;
/**
* Execute a query which would set an environment or user variable. The variables are set per connection,
* so this function needs a transaction.
*
* Only works for MySQL.
*
* @param variables object with multiple variables.
* @param options Query options.
*/
public set(variables: object, options: QueryOptionsTransactionRequired): Promise<unknown>;
/**
* Escape value.
*
* @param value Value that needs to be escaped
*/
public escape(value: string | number | Date): string;
/**
* Create a new database schema.
*
* Note,that this is a schema in the
* [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
* not a database table. In mysql and sqlite, this command will do nothing.
*
* @param schema Name of the schema
* @param options Options supplied
*/
public createSchema(schema: string, options: Logging): Promise<unknown>;
/**
* Show all defined schemas
*
* Note,that this is a schema in the
* [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
* not a database table. In mysql and sqlite, this will show all tables.
*
* @param options Options supplied
*/
public showAllSchemas(options: Logging): Promise<object[]>;
/**
* Drop a single schema
*
* Note,that this is a schema in the
* [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
* not a database table. In mysql and sqlite, this drop a table matching the schema name
*
* @param schema Name of the schema
* @param options Options supplied
*/
public dropSchema(schema: string, options: Logging): Promise<unknown[]>;
/**
* Drop all schemas
*
* Note,that this is a schema in the
* [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
* not a database table. In mysql and sqlite, this is the equivalent of drop all tables.
*
* @param options Options supplied
*/
public dropAllSchemas(options: Logging): Promise<unknown[]>;
/**
* Sync all defined models to the DB.
*
* @param options Sync Options
*/
public sync(options?: SyncOptions): Promise<this>;
/**
* Truncate all tables defined through the sequelize models. This is done
* by calling Model.truncate() on each model.
*
* @param [options] The options passed to Model.destroy in addition to truncate
*/
public truncate(options?: DestroyOptions): Promise<unknown[]>;
/**
* Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model
*
* @param options The options passed to each call to Model.drop
*/
public drop(options?: DropOptions): Promise<unknown[]>;
/**
* Test the connection by trying to authenticate
*
* @param options Query Options for authentication
*/
public authenticate(options?: QueryOptions): Promise<void>;
public validate(options?: QueryOptions): Promise<void>;
/**
* Start a transaction. When using transactions, you should pass the transaction in the options argument
* in order for the query to happen under that transaction
*
* ```js
* sequelize.transaction().then(function (t) {
* return User.findOne(..., { transaction: t}).then(function (user) {
* return user.update(..., { transaction: t});
* })
* .then(t.commit.bind(t))
* .catch(t.rollback.bind(t));
* })
* ```
*
* A syntax for automatically committing or rolling back based on the promise chain resolution is also
* supported:
*
* ```js
* sequelize.transaction(function (t) { // Note that we use a callback rather than a promise.then()
* return User.findOne(..., { transaction: t}).then(function (user) {
* return user.update(..., { transaction: t});
* });
* }).then(function () {
* // Commited
* }).catch(function (err) {
* // Rolled back
* console.error(err);
* });
* ```
*
* If you have [CLS](https://github.com/othiym23/node-continuation-local-storage) enabled, the transaction
* will automatically be passed to any query that runs witin the callback. To enable CLS, add it do your
* project, create a namespace and set it on the sequelize constructor:
*
* ```js
* var cls = require('continuation-local-storage'),
* ns = cls.createNamespace('....');
* var Sequelize = require('sequelize');
* Sequelize.cls = ns;
* ```
* Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace
*
* @param options Transaction Options
* @param autoCallback Callback for the transaction
*/
public transaction<T>(options: TransactionOptions, autoCallback: (t: Transaction) => PromiseLike<T>): Promise<T>;
public transaction<T>(autoCallback: (t: Transaction) => PromiseLike<T>): Promise<T>;
public transaction(options?: TransactionOptions): Promise<Transaction>;
/**
* Close all connections used by this sequelize instance, and free all references so the instance can be
* garbage collected.
*
* Normally this is done on process exit, so you only need to call this method if you are creating multiple
* instances, and want to garbage collect some of them.
*/
public close(): void;
/**
* Returns the database version
*/
public databaseVersion(): Promise<string>;
}
// Utilities
/**
* Creates a object representing a database function. This can be used in search queries, both in where and
* order parts, and as default values in column definitions. If you want to refer to columns in your
* function, you should use `sequelize.col`, so that the columns are properly interpreted as columns and
* not a strings.
*
* Convert a user's username to upper case
* ```js
* instance.update({
* username: self.sequelize.fn('upper', self.sequelize.col('username'))
* })
* ```
* @param fn The function you want to call
* @param args All further arguments will be passed as arguments to the function
*/
export function fn(fn: string, ...args: any[]): Fn;
/**
* Creates a object representing a column in the DB. This is often useful in conjunction with
* `sequelize.fn`, since raw string arguments to fn will be escaped.
*
* @param col The name of the column
*/
export function col(col: string): Col;
/**
* Creates a object representing a call to the cast function.
*
* @param val The value to cast
* @param type The type to cast it to
*/
export function cast(val: any, type: string): Cast;
/**
* Creates a object representing a literal, i.e. something that will not be escaped.
*
* @param val
*/
export function literal(val: any): Literal;
/**
* An AND query
*
* @param args Each argument will be joined by AND
*/
export function and(...args: (WhereOperators | WhereAttributeHash | Where)[]): AndOperator;
/**
* An OR query
*
* @param args Each argument will be joined by OR
*/
export function or(...args: (WhereOperators | WhereAttributeHash | Where)[]): OrOperator;
/**
* Creates an object representing nested where conditions for postgres's json data-type.
*
* @param conditionsOrPath A hash containing strings/numbers or other nested hash, a string using dot
* notation or a string using postgres json syntax.
* @param value An optional value to compare against. Produces a string of the form "<json path> =
* '<value>'".
*/
export function json(conditionsOrPath: string | object, value?: string | number | boolean): Json;
export type AttributeType = Fn | Col | Literal | ModelAttributeColumnOptions | string;
export type LogicType = Fn | Col | Literal | OrOperator | AndOperator | string;
/**
* A way of specifying attr = condition.
*
* The attr can either be an object taken from `Model.rawAttributes` (for example `Model.rawAttributes.id`
* or
* `Model.rawAttributes.name`). The attribute should be defined in your model definition. The attribute can
* also be an object from one of the sequelize utility functions (`sequelize.fn`, `sequelize.col` etc.)
*
* For string attributes, use the regular `{ where: { attr: something }}` syntax. If you don't want your
* string to be escaped, use `sequelize.literal`.
*
* @param attr The attribute, which can be either an attribute object from `Model.rawAttributes` or a
* sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the
* POJO syntax
* @param comparator Comparator
* @param logic The condition. Can be both a simply type, or a further condition (`.or`, `.and`, `.literal`
* etc.)
*/
export function where(attr: AttributeType, comparator: string, logic: LogicType): Where;
export function where(attr: AttributeType, logic: LogicType): Where;
export default Sequelize;
export type Escapable = undefined | null | boolean | number | string | Date;
export function escapeId(val: string, forbidQualified?: boolean): string;
export function escape(val: Escapable | Escapable[], timeZone?: string, dialect?: string, format?: string): string;
export function format(sql: string, values: any[], timeZone?: string, dialect?: string): string;
export function formatNamedParameters(sql: string, values: any[], timeZone?: string, dialect?: string): string;
declare enum TableHints {
NOLOCK = 'NOLOCK',
READUNCOMMITTED = 'READUNCOMMITTED',
UPDLOCK = 'UPDLOCK',
REPEATABLEREAD = 'REPEATABLEREAD',
SERIALIZABLE = 'SERIALIZABLE',
READCOMMITTED = 'READCOMMITTED',
TABLOCK = 'TABLOCK',
TABLOCKX = 'TABLOCKX',
PAGLOCK = 'PAGLOCK',
ROWLOCK = 'ROWLOCK',
NOWAIT = 'NOWAIT',
READPAST = 'READPAST',
XLOCK = 'XLOCK',
SNAPSHOT = 'SNAPSHOT',
NOEXPAND = 'NOEXPAND',
}
export = TableHints;
import { Deferrable } from './deferrable';
import { Logging } from './model';
import { Promise } from './promise';
import { Sequelize } from './sequelize';
/**
* The transaction object is used to identify a running transaction. It is created by calling
* `Sequelize.transaction()`.
*
* To run a query under a transaction, you should pass the transaction in the options object.
*/
export class Transaction {
constructor(sequelize: Sequelize, options: TransactionOptions);
/**
* Commit the transaction
*/
public commit(): Promise<void>;
/**
* Rollback (abort) the transaction
*/
public rollback(): Promise<void>;
/**
* Adds hook that is run after a transaction is committed
*/
public afterCommit(fn: (transaction: this) => void | Promise<void>): void;
}
// tslint:disable-next-line no-namespace
export namespace Transaction {
/**
* Isolations levels can be set per-transaction by passing `options.isolationLevel` to `sequelize.transaction`.
* Default to `REPEATABLE_READ` but you can override the default isolation level by passing `options.isolationLevel` in `new Sequelize`.
*
* The possible isolations levels to use when starting a transaction:
*
* ```js
* {
* READ_UNCOMMITTED: "READ UNCOMMITTED",
* READ_COMMITTED: "READ COMMITTED",
* REPEATABLE_READ: "REPEATABLE READ",
* SERIALIZABLE: "SERIALIZABLE"
* }
* ```
*
* Pass in the desired level as the first argument:
*
* ```js
* return sequelize.transaction({isolationLevel: Sequelize.Transaction.SERIALIZABLE}, transaction => {
*
* // your transactions
*
* }).then(result => {
* // transaction has been committed. Do something after the commit if required.
* }).catch(err => {
* // do something with the err.
* });
* ```
*/
const enum ISOLATION_LEVELS {
READ_UNCOMMITTED = 'READ UNCOMMITTED',
READ_COMMITTED = 'READ COMMITTED',
REPEATABLE_READ = 'REPEATABLE READ',
SERIALIZABLE = 'SERIALIZABLE',
}
const enum TYPES {
DEFERRED = 'DEFERRED',
IMMEDIATE = 'IMMEDIATE',
EXCLUSIVE = 'EXCLUSIVE',
}
/**
* Possible options for row locking. Used in conjunction with `find` calls:
*
* ```js
* t1 // is a transaction
* t1.LOCK.UPDATE,
* t1.LOCK.SHARE,
* t1.LOCK.KEY_SHARE, // Postgres 9.3+ only
* t1.LOCK.NO_KEY_UPDATE // Postgres 9.3+ only
* ```
*
* Usage:
* ```js
* t1 // is a transaction
* Model.findAll({
* where: ...,
* transaction: t1,
* lock: t1.LOCK...
* });
* ```
*
* Postgres also supports specific locks while eager loading by using OF:
* ```js
* UserModel.findAll({
* where: ...,
* include: [TaskModel, ...],
* transaction: t1,
* lock: {
* level: t1.LOCK...,
* of: UserModel
* }
* });
* ```
* UserModel will be locked but TaskModel won't!
*/
const enum LOCK {
UPDATE = 'UPDATE',
SHARE = 'SHARE',
/**
* Postgres 9.3+ only
*/
KEY_SHARE = 'KEY SHARE',
/**
* Postgres 9.3+ only
*/
NO_KEY_UPDATE = 'NO KEY UPDATE',
}
}
/**
* Options provided when the transaction is created
*/
export interface TransactionOptions extends Logging {
autocommit?: boolean;
isolationLevel?: Transaction.ISOLATION_LEVELS;
type?: Transaction.TYPES;
deferrable?: string | Deferrable;
}
export default Transaction;
import { DataType } from './data-types';
export type Primitive = 'string' | 'number' | 'boolean';
export interface Inflector {
singularize(str: string): string;
pluralize(str: string): string;
}
export function useInflection(inflection: Inflector): void;
export function camelizeIf(string: string, condition?: boolean): string;
export function underscoredIf(string: string, condition?: boolean): string;
export function isPrimitive(val: unknown): val is Primitive;
/** Same concept as _.merge, but don't overwrite properties that have already been assigned */
export function mergeDefaults<T>(a: T, b: Partial<T>): T;
export function spliceStr(str: string, index: number, count: number, add: string): string;
export function camelize(str: string): string;
export function format(arr: string[], dialect: string): string;
export function formatNamedParameters(sql: string, parameters: {
[key: string]: string | number | boolean;
}, dialect: string): string;
export function cloneDeep<T>(obj: T, fn?: (el: any) => any): T;
/** Expand and normalize finder options */
export function mapFinderOptions(options: any, Model: any): any;
/* Used to map field names in attributes and where conditions */
export function mapOptionFieldNames(options: any, Model: any): any;
export function mapWhereFieldNames(attributes: any, Model: any): any;
/** Used to map field names in values */
export function mapValueFieldNames(dataValues: any, fields: any, Model: any): any;
export function isColString(value: string): boolean;
export function canTreatArrayAsAnd(arr: unknown[]): boolean;
export function combineTableNames(tableName1: string, tableName2: string): string;
export function singularize(s: string): string;
export function pluralize(s: string): string;
export function toDefaultValue(value: any): any;
/**
* Determine if the default value provided exists and can be described
* in a db schema using the DEFAULT directive.
*
* @param value Any default value.
*/
export function defaultValueSchemable(hash: DataType): boolean;
export function stack(): NodeJS.CallSite[];
export function now(dialect: string): Date;
// Note: Use the `quoteIdentifier()` and `escape()` methods on the
// `QueryInterface` instead for more portable code.
export const TICK_CHAR: string;
export function addTicks(s: string, tickChar?: string): string;
export function removeTicks(s: string, tickChar?: string): string;
export class SequelizeMethod {
}
/*
* Utility functions for representing SQL functions, and columns that should be escaped.
* Please do not use these functions directly, use Sequelize.fn and Sequelize.col instead.
*/
export class Fn extends SequelizeMethod {
constructor(fn: string, args: any);
public clone(): this;
}
export class Col extends SequelizeMethod {
public col: string;
constructor(col: string);
}
export class Cast extends SequelizeMethod {
public val: any;
public type: string;
constructor(val: any, type?: string);
}
export class Literal extends SequelizeMethod {
public val: any;
constructor(val: any);
}
export class Json extends SequelizeMethod {
public conditions: object;
public path: string;
public value: string | number | boolean;
constructor(conditionsOrPath: string | object, value?: string | number | boolean);
}
export class Where extends SequelizeMethod {
public attribute: object;
public comparator: string;
public logic: string | object;
constructor(attr: object, comparator: string, logic: string | object);
constructor(attr: object, logic: string | object);
}
export { Promise } from './promise';
export interface LoggerConfig {
/**
* @default `sequelize`
*/
context?: string;
/**
* @default `true`
*/
debug?: boolean;
}
export class Logger {
constructor(config: LoggerConfig)
public deprecate(message: string): void;
public debug(message: string): void;
public warn(message: string): void;
public debugContext(message: string): (message: string) => void;
}
export function deprecate(message: string): void;
export function warn(message: string): void;
export function getLogger(): Logger;
// tslint:disable-next-line:no-implicit-dependencies
import * as val from 'validator';
type OrigValidator = typeof val;
export interface Extensions {
notEmpty(str: string): boolean;
len(str: string, min: number, max: number): boolean;
isUrl(str: string): boolean;
isIPv6(str: string): boolean;
isIPv4(str: string): boolean;
notIn(str: string, values: string[]): boolean;
regex(str: string, pattern: string, modifiers: string): boolean;
notRegex(str: string, pattern: string, modifiers: string): boolean;
min(str: string, val: number): boolean;
max(str: string, val: number): boolean;
not(str: string, pattern: string, modifiers: string): boolean;
contains(str: string, elem: string[]): boolean;
notContains(str: string, elem: string[]): boolean;
is(str: string, pattern: string, modifiers: string): boolean;
}
export const extensions: Extensions;
export interface Validator extends OrigValidator, Extensions {
contains(str: string, elem: string[]): boolean;
}
export const validator: Validator;
import { QueryTypes, Sequelize, SyncOptions } from 'sequelize';
export const sequelize = new Sequelize('uri');
sequelize.afterBulkSync((options: SyncOptions) => {
console.log('synced');
});
sequelize
.query('SELECT * FROM `test`', {
type: QueryTypes.SELECT,
})
.then(rows => {
rows.forEach(row => {
console.log(row);
});
});
sequelize
.query('INSERT into test set test=1', {
type: QueryTypes.INSERT,
})
.then(([aiId, affected]) => {
console.log(aiId, affected);
});
import { DataTypes, Model } from 'sequelize';
import { sequelize } from './connection';
// I really wouldn't recommend this, but if you want you can still use define() and interfaces
interface User extends Model {
id: number;
username: string;
firstName: string;
lastName: string;
createdAt: Date;
updatedAt: Date;
}
type UserModel = {
new (): User
customStaticMethod(): any
} & typeof Model;
const User = sequelize.define('User', { firstName: DataTypes.STRING }, { tableName: 'users' }) as UserModel;
async function test() {
User.customStaticMethod();
const user: User = new User();
const user2: User = (await User.findOne()) as User;
user2.firstName = 'John';
await user2.save();
}
// Error === BaseError
import { BaseError, EmptyResultError, Error, UniqueConstraintError } from 'sequelize';
import { User } from './models/User';
async function test() {
try {
await User.create({ username: 'john_doe' });
} catch (e) {
if (e instanceof UniqueConstraintError) {
console.error((e as UniqueConstraintError).sql);
}
}
try {
await User.findOne({
rejectOnEmpty: true,
where: {
username: 'something_that_doesnt_exist',
},
});
} catch (e) {
if (!(e instanceof EmptyResultError)) {
console.error('should return emptyresulterror');
}
}
}
import { User } from './models/User';
User.findByPk(Buffer.from('asdf'));
import { Model, Sequelize } from 'sequelize';
class MyModel extends Model {}
class AssociatedModel extends Model {}
MyModel.findAll({
include: [
{
limit: 1,
model: AssociatedModel,
order: [['id', 'DESC']],
separate: true,
where: { state: Sequelize.col('project.state') },
},
],
});
MyModel.findAll({
include: [{ all: true }],
});
import {
BelongsTo,
BelongsToCreateAssociationMixin,
BelongsToGetAssociationMixin,
BelongsToSetAssociationMixin,
DataTypes,
FindOptions,
Model,
} from 'sequelize';
import { sequelize } from '../connection';
export class User extends Model {
public static associations: {
group: BelongsTo
};
public id: number;
public username: string;
public firstName: string;
public lastName: string;
public createdAt: Date;
public updatedAt: Date;
// mixins for association (optional)
public groupId: number;
public group: UserGroup;
public getGroup: BelongsToGetAssociationMixin<UserGroup>;
public setGroup: BelongsToSetAssociationMixin<UserGroup, number>;
public createGroup: BelongsToCreateAssociationMixin<UserGroup>;
}
User.init(
{
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
username: DataTypes.STRING,
},
{
scopes: {
custom(a: number) {
return {
where: {
firstName: a,
},
};
}
},
sequelize,
}
);
// Hooks
User.afterFind((users, options) => {
console.log('found');
});
// TODO: VSCode shows the typing being correctly narrowed but doesn't do it correctly
User.addHook('beforeFind', 'test', (options: FindOptions) => {
return undefined;
});
// associate
// it is important to import _after_ the model above is already exported so the circular reference works.
import { UserGroup } from './UserGroup';
export const Group = User.belongsTo(UserGroup, { as: 'group', foreignKey: 'groupId' });
import {
DataTypes,
HasMany,
HasManyAddAssociationMixin,
HasManyAddAssociationsMixin,
HasManyCountAssociationsMixin,
HasManyCreateAssociationMixin,
HasManyGetAssociationsMixin,
HasManyHasAssociationMixin,
HasManyRemoveAssociationMixin,
HasManyRemoveAssociationsMixin,
HasManySetAssociationsMixin,
Model,
} from 'sequelize';
import { sequelize } from '../connection';
export class UserGroup extends Model {
public static associations: {
users: HasMany
};
public id: number;
public name: string;
// mixins for association (optional)
public users: User[];
public getUsers: HasManyGetAssociationsMixin<User>;
public setUsers: HasManySetAssociationsMixin<User, number>;
public addUser: HasManyAddAssociationMixin<User, number>;
public addUsers: HasManyAddAssociationsMixin<User, number>;
public createUser: HasManyCreateAssociationMixin<number>;
public countUsers: HasManyCountAssociationsMixin;
public hasUser: HasManyHasAssociationMixin<User, number>;
public removeUser: HasManyRemoveAssociationMixin<User, number>;
public removeUsers: HasManyRemoveAssociationsMixin<User, number>;
}
// attach all the metadata to the model
// instead of this, you could also use decorators
UserGroup.init({ name: DataTypes.STRING }, { sequelize });
// associate
// it is important to import _after_ the model above is already exported so the circular reference works.
import { User } from './User';
export const Users = UserGroup.hasMany(User, { as: 'users', foreignKey: 'groupId' });
import { Promise } from 'sequelize';
let promise: Promise<number> = Promise.resolve(1);
promise.then((arg: number) => ({})).then((a: {}) => void 0);
promise = new Promise<number>(resolve => resolve());
import { DataTypes } from 'sequelize';
// tslint:disable-next-line:no-submodule-imports
import { QueryInterface } from 'sequelize/lib/query-interface';
declare let queryInterface: QueryInterface;
queryInterface.createTable(
'nameOfTheNewTable',
{
attr1: DataTypes.STRING,
attr2: DataTypes.INTEGER,
attr3: {
allowNull: false,
defaultValue: false,
type: DataTypes.BOOLEAN,
},
// foreign key usage
attr4: {
onDelete: 'cascade',
onUpdate: 'cascade',
references: {
key: 'id',
model: 'another_table_name',
},
type: DataTypes.INTEGER,
},
createdAt: {
type: DataTypes.DATE,
},
id: {
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
updatedAt: {
type: DataTypes.DATE,
},
},
{
charset: 'latin1', // default: null
collate: 'latin1_general_ci',
engine: 'MYISAM', // default: 'InnoDB'
uniqueKeys: {
test: {
customIndex: true,
fields: ['attr2', 'attr3'],
}
}
}
);
queryInterface.dropTable('nameOfTheExistingTable');
queryInterface.dropAllTables();
queryInterface.renameTable('Person', 'User');
queryInterface.showAllTables().then(tableNames => {
// do nothing
});
queryInterface.describeTable('Person').then(attributes => {
/*
attributes will be something like:
{
name: {
type: 'VARCHAR(255)', // this will be 'CHARACTER VARYING' for pg!
allowNull: true,
defaultValue: null
},
isBetaMember: {
type: 'TINYINT(1)', // this will be 'BOOLEAN' for pg!
allowNull: false,
defaultValue: false
}
}
*/
});
queryInterface.addColumn('nameOfAnExistingTable', 'nameOfTheNewAttribute', DataTypes.STRING);
// or
queryInterface.addColumn(
{ tableName: 'nameOfAnExistingTable', schema: 'nameOfSchema' },
'nameOfTheNewAttribute',
DataTypes.STRING
);
// or
queryInterface.addColumn('nameOfAnExistingTable', 'nameOfTheNewAttribute', {
allowNull: false,
type: DataTypes.STRING,
});
queryInterface.removeColumn('Person', 'signature');
// or
queryInterface.removeColumn({ tableName: 'Person', schema: 'nameOfSchema' }, 'signature');
queryInterface.changeColumn('nameOfAnExistingTable', 'nameOfAnExistingAttribute', {
allowNull: false,
defaultValue: 0.0,
type: DataTypes.FLOAT,
});
// or
queryInterface.changeColumn(
{ tableName: 'nameOfAnExistingTable', schema: 'nameOfSchema' },
'nameOfAnExistingAttribute',
{
allowNull: false,
defaultValue: 0.0,
type: DataTypes.FLOAT,
}
);
queryInterface.renameColumn('Person', 'signature', 'sig');
// This example will create the index person_firstname_lastname
queryInterface.addIndex('Person', ['firstname', 'lastname']);
// This example will create a unique index with the name SuperDuperIndex using the optional 'options' field.
// Possible options:
// - indicesType: UNIQUE|FULLTEXT|SPATIAL
// - indexName: The name of the index. Default is __
// - parser: For FULLTEXT columns set your parser
// - indexType: Set a type for the index, e.g. BTREE. See the documentation of the used dialect
// - logging: A function that receives the sql query, e.g. console.log
queryInterface.addIndex('Person', ['firstname', 'lastname'], {
indexName: 'SuperDuperIndex',
indicesType: 'UNIQUE',
});
queryInterface.removeIndex('Person', 'SuperDuperIndex');
// or
queryInterface.removeIndex('Person', ['firstname', 'lastname']);
queryInterface.addConstraint('Person', ['firstname', 'lastname'], {
name: 'firstnamexlastname',
type: 'unique',
});
queryInterface.removeConstraint('Person', 'firstnamexlastname');
import { Config, Sequelize } from 'sequelize';
export const sequelize = new Sequelize('uri');
const conn = sequelize.connectionManager;
// hooks
sequelize.beforeCreate('test', () => {
// noop
});
sequelize
.addHook('beforeConnect', (config: Config) => {
// noop
})
.addHook('beforeBulkSync', () => {
// noop
});
Sequelize.addHook('beforeCreate', () => {
// noop
}).addHook('beforeBulkCreate', () => {
// noop
});
import { Deferrable, Sequelize, Transaction } from 'sequelize';
import { User } from './models/User';
export const sequelize = new Sequelize('uri');
async function trans() {
const a: number = await sequelize.transaction(async transaction => {
transaction.afterCommit(() => console.log('transaction complete'));
User.create(
{
data: 123,
},
{
transaction,
}
);
return 1;
});
}
async function transact() {
const t = await sequelize.transaction({
deferrable: Deferrable.SET_DEFERRED(['test']),
isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED,
type: Transaction.TYPES.DEFERRED,
});
await t.commit();
await t.rollback();
}
transact();
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noEmit": true,
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": ".",
"paths": {
"sequelize": ["../"],
"sequelize/*": ["../"]
},
"types": ["node"],
"lib": ["es2016"]
},
"include": ["../index.d.ts", "./**/sequelize.d.ts", "./**/*.ts"]
}
import { Group, User } from './models/User';
async function test(): Promise<void> {
let user = await User.findOne({ include: [Group] });
if (!user) {
return;
}
User.update({}, { where: {} });
user.firstName = 'John';
await user.save();
await user.setGroup(2);
user = new User();
user = new User({ firstName: 'John' });
user = await User.findOne();
const user2 = await User.create({ firstName: 'John', groupId: 1 });
await User.findAndCountAll({ distinct: true });
}
import { AndOperator, fn, Model, Op, OrOperator, Sequelize, WhereOperators, WhereOptions } from 'sequelize';
import Transaction from '../lib/transaction';
class MyModel extends Model {
public hi: number;
}
let where: WhereOptions;
// From http://docs.sequelizejs.com/en/v4/docs/querying/
// Operators
const and: AndOperator = {
[Op.and]: { a: 5 }, // AND (a = 5)
};
const or: OrOperator = {
[Op.or]: [{ a: 5 }, { a: 6 }], // (a = 5 OR a = 6)
};
let operators: WhereOperators = {
[Op.gt]: 6, // > 6
[Op.gte]: 6, // >= 6
[Op.lt]: 10, // < 10
[Op.lte]: 10, // <= 10
[Op.ne]: 20, // != 20
[Op.not]: true, // IS NOT TRUE
[Op.between]: [6, 10], // BETWEEN 6 AND 10
[Op.notBetween]: [11, 15], // NOT BETWEEN 11 AND 15
[Op.in]: [1, 2], // IN [1, 2]
[Op.notIn]: [1, 2], // NOT IN [1, 2]
[Op.like]: '%hat', // LIKE '%hat'
[Op.notLike]: '%hat', // NOT LIKE '%hat'
[Op.iLike]: '%hat', // ILIKE '%hat' (case insensitive) (PG only)
[Op.notILike]: '%hat', // NOT ILIKE '%hat' (PG only)
[Op.startsWith]: 'hat',
[Op.endsWith]: 'hat',
[Op.substring]: 'hat',
[Op.overlap]: [1, 2], // && [1, 2] (PG array overlap operator)
[Op.contains]: [1, 2], // @> [1, 2] (PG array contains operator)
[Op.contained]: [1, 2], // <@ [1, 2] (PG array contained by operator)
[Op.any]: [2, 3], // ANY ARRAY[2, 3]::INTEGER (PG only)
};
operators = {
[Op.like]: { [Op.any]: ['cat', 'hat'] }, // LIKE ANY ARRAY['cat', 'hat'] - also works for iLike and notLike
};
// Combinations
MyModel.findOne({ where: or });
MyModel.findOne({ where: and });
where = Sequelize.and();
where = Sequelize.or();
where = { [Op.and]: [] };
where = {
rank: Sequelize.and({ [Op.lt]: 1000 }, { [Op.eq]: null }),
};
where = {
rank: Sequelize.or({ [Op.lt]: 1000 }, { [Op.eq]: null }),
};
where = {
rank: {
[Op.or]: {
[Op.lt]: 1000,
[Op.eq]: null,
},
},
};
// rank < 1000 OR rank IS NULL
where = {
createdAt: {
[Op.lt]: new Date(),
[Op.gt]: new Date(Date.now() - 24 * 60 * 60 * 1000),
},
};
// createdAt < [timestamp] AND createdAt > [timestamp]
where = {
[Op.or]: [
{
title: {
[Op.like]: 'Boat%',
},
},
{
description: {
[Op.like]: '%boat%',
},
},
],
};
// title LIKE 'Boat%' OR description LIKE '%boat%'
// Containment
where = {
meta: {
[Op.contains]: {
site: {
url: 'http://google.com',
},
},
},
};
// Relations / Associations
// Find all projects with a least one task where task.state === project.task
MyModel.findAll({
include: [
{
model: MyModel,
where: { state: Sequelize.col('project.state') },
},
],
});
MyModel.findOne({
include: [
{
include: [{ model: MyModel, where }],
model: MyModel,
where,
},
],
where,
});
MyModel.destroy({ where });
MyModel.update({ hi: 1 }, { where });
// From http://docs.sequelizejs.com/en/v4/docs/models-usage/
// find multiple entries
MyModel.findAll().then(projects => {
// projects will be an array of all MyModel instances
});
// search for specific attributes - hash usage
MyModel.findAll({ where: { name: 'A MyModel', enabled: true } }).then(projects => {
// projects will be an array of MyModel instances with the specified name
});
// search within a specific range
MyModel.findAll({ where: { id: [1, 2, 3] } }).then(projects => {
// projects will be an array of MyModels having the id 1, 2 or 3
// this is actually doing an IN query
});
// locks
MyModel.findAll({ lock: Transaction.LOCK.KEY_SHARE }).then(projects => {
// noop
});
// locks on model
MyModel.findAll({ lock: { level: Transaction.LOCK.KEY_SHARE, of: MyModel} }).then(projects => {
// noop
});
MyModel.findAll({
where: {
// tslint:disable-next-line:no-object-literal-type-assertion
id: {
// casting here to check a missing operator is not accepted as field name
[Op.and]: { a: 5 }, // AND (a = 5)
[Op.or]: [{ a: 5 }, { a: 6 }], // (a = 5 OR a = 6)
[Op.gt]: 6, // id > 6
[Op.gte]: 6, // id >= 6
[Op.lt]: 10, // id < 10
[Op.lte]: 10, // id <= 10
[Op.ne]: 20, // id != 20
[Op.between]: [6, 10], // BETWEEN 6 AND 10
[Op.notBetween]: [11, 15], // NOT BETWEEN 11 AND 15
[Op.in]: [1, 2], // IN [1, 2]
[Op.notIn]: [1, 2], // NOT IN [1, 2]
[Op.like]: '%hat', // LIKE '%hat'
[Op.notLike]: '%hat', // NOT LIKE '%hat'
[Op.iLike]: '%hat', // ILIKE '%hat' (case insensitive) (PG only)
[Op.notILike]: '%hat', // NOT ILIKE '%hat' (PG only)
[Op.overlap]: [1, 2], // && [1, 2] (PG array overlap operator)
[Op.contains]: [1, 2], // @> [1, 2] (PG array contains operator)
[Op.contained]: [1, 2], // <@ [1, 2] (PG array contained by operator)
[Op.any]: [2, 3], // ANY ARRAY[2, 3]::INTEGER (PG only)
} as WhereOperators,
status: {
[Op.not]: false, // status NOT FALSE
},
},
});
// Complex filtering / NOT queries
where = {
name: 'a project',
[Op.or]: [{ id: [1, 2, 3] }, { id: { [Op.gt]: 10 } }],
};
where = {
id: {
[Op.or]: [[1, 2, 3], { [Op.gt]: 10 }],
},
name: 'a project',
};
where = {
name: 'a project',
type: {
[Op.and]: [['a', 'b'], { [Op.notLike]: '%z' }],
},
};
// [Op.not] example:
where = {
name: 'a project',
[Op.not]: [{ id: [1, 2, 3] }, { array: { [Op.contains]: [3, 4, 5] } }],
};
// JSONB
// Nested object
where = {
meta: {
video: {
url: {
[Op.ne]: null,
},
},
},
};
// Nested key
where = {
'meta.audio.length': {
[Op.gt]: 20,
},
};
// Operator symbols
where = {
[Op.and]: [{ id: [1, 2, 3] }, { array: { [Op.contains]: [3, 4, 5] } }],
};
// Fn as value
where = {
[Op.gt]: fn('NOW'),
};
{
"compilerOptions": {
"strict": true,
"module": "commonjs",
"moduleResolution": "node",
"noEmit": true,
"lib": ["es2016"]
},
"types": ["node"],
"include": ["lib/**/*.d.ts", "index.d.ts"]
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!