├── .editorconfig ├── .gitignore ├── .npmrc ├── .prettierignore ├── .prettierrc ├── .travis.yml ├── .vscode └── tasks.json ├── README.md ├── docs_index.md ├── index.d.ts ├── lib ├── associations │ ├── base.d.ts │ ├── belongs-to-many.d.ts │ ├── belongs-to.d.ts │ ├── has-many.d.ts │ ├── has-one.d.ts │ └── index.d.ts ├── data-types.d.ts ├── deferrable.d.ts ├── errors.d.ts ├── model-manager.d.ts ├── model.d.ts ├── promise.d.ts ├── query-interface.d.ts ├── query-types.d.ts ├── sequelize.d.ts ├── sql-string.d.ts ├── transaction.d.ts ├── utils.d.ts └── utils │ ├── parameter-validator.d.ts │ └── validator-extras.d.ts ├── package.json ├── test ├── connection.ts ├── define.ts ├── errors.ts ├── include.ts ├── models │ ├── User.ts │ └── UserGroup.ts ├── promise.ts ├── query-interface.ts ├── tsconfig.json ├── usage.ts └── where.ts ├── tsconfig.json └── tslint.json /.editorconfig: -------------------------------------------------------------------------------- 1 | 2 | [*] 3 | end_of_line = lf 4 | insert_final_newline = true 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | trim_trailing_whitespace = true 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | dist/ 3 | *.js 4 | *.log 5 | typedoc/ 6 | package-lock.json 7 | package-lock.json.* 8 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | typedoc/ 3 | package.json 4 | package-lock.json 5 | package-lock.json.* 6 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 4, 3 | "printWidth": 120, 4 | "semi": false, 5 | "singleQuote": true, 6 | "trailingComma": "es5", 7 | "proseWrap": "preserve", 8 | "overrides": [ 9 | { 10 | "files": ["{*.json,.prettierrc}"], 11 | "options": { 12 | "tabWidth": 2 13 | } 14 | } 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | 3 | node_js: 4 | - '8' 5 | 6 | install: 7 | - npm install 8 | 9 | script: 10 | - npm run prettier 11 | - npm run tslint 12 | - npm run build 13 | - npm test 14 | - npm run typedoc 15 | 16 | deploy: 17 | provider: surge 18 | project: ./typedoc/ 19 | domain: typed-sequelize.surge.sh 20 | skip_cleanup: true 21 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "type": "npm", 8 | "script": "tslint", 9 | "problemMatcher": ["$tslint5"] 10 | }, 11 | { 12 | "type": "npm", 13 | "script": "build", 14 | "problemMatcher": ["$tsc"] 15 | } 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Typescript Typings for [Sequelize](http://sequelizejs.com). 2 | 3 | [![build](https://travis-ci.org/types/sequelize.svg?branch=master)](https://travis-ci.org/types/sequelize) 4 | [![dependencies](https://david-dm.org/types/sequelize/status.svg)](https://david-dm.org/types/sequelize) 5 | [![devDependencies](https://david-dm.org/types/sequelize/dev-status.svg)](https://david-dm.org/types/sequelize?type=dev) 6 | [![peerDependencies](https://david-dm.org/types/sequelize/peer-status.svg)](https://david-dm.org/types/sequelize?type=peer) 7 | [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier) 8 | 9 | ## [API Documentation](https://typed-sequelize.surge.sh) 10 | 11 | ## Installation 12 | 13 | ```bash 14 | npm install --save-dev types/sequelize# 15 | ``` 16 | 17 | ## Usage 18 | 19 | ```ts 20 | import { 21 | Model, 22 | FindOptions, 23 | STRING, 24 | BelongsTo, 25 | BelongsToGetAssociationMixin, 26 | BelongsToSetAssociationMixin, 27 | BelongsToCreateAssociationMixin, 28 | } from 'sequelize' 29 | import { sequelize } from '../connection' 30 | 31 | export class User extends Model { 32 | static associations: { 33 | group: BelongsTo 34 | } 35 | 36 | id: number 37 | username: string 38 | firstName: string 39 | lastName: string 40 | createdAt: Date 41 | updatedAt: Date 42 | 43 | // mixins for association (optional) 44 | groupId: number 45 | group: UserGroup 46 | getGroup: BelongsToGetAssociationMixin 47 | setGroup: BelongsToSetAssociationMixin 48 | createGroup: BelongsToCreateAssociationMixin 49 | } 50 | 51 | User.init( 52 | { 53 | username: STRING, 54 | firstName: STRING, 55 | lastName: STRING, 56 | }, 57 | { sequelize } 58 | ) 59 | 60 | // associate 61 | // it is important to import _after_ the model above is already exported so the circular reference works. 62 | import { UserGroup } from './UserGroup' 63 | User.belongsTo(UserGroup, { as: 'group', foreignKey: 'groupId' }) 64 | ``` 65 | 66 | ```ts 67 | import { User, Group } from './models/User' 68 | 69 | async function test() { 70 | const user = (await User.findOne({ include: [Group] })) as User 71 | user.firstName = 'John' 72 | await user.save() 73 | await user.setGroup(2) 74 | 75 | new User() 76 | new User({ firstName: 'John' }) 77 | 78 | const user2 = (await User.create({ firstName: 'John', groupId: 1 })) as User 79 | } 80 | ``` 81 | -------------------------------------------------------------------------------- /docs_index.md: -------------------------------------------------------------------------------- 1 | _Start typing to search_ 2 | 3 | ## API 4 | 5 | 14 | 15 | #### Associations 16 | 17 | 23 | 24 | ## Example 25 | 26 | _User.ts_ 27 | 28 | ```ts 29 | import { 30 | Model, 31 | FindOptions, 32 | DataTypes, 33 | BelongsTo, 34 | BelongsToGetAssociationMixin, 35 | BelongsToSetAssociationMixin, 36 | BelongsToCreateAssociationMixin, 37 | } from 'sequelize' 38 | import { sequelize } from '../connection' 39 | 40 | export class User extends Model { 41 | static associations: { 42 | group: BelongsTo 43 | } 44 | 45 | id: number 46 | username: string 47 | firstName: string 48 | lastName: string 49 | createdAt: Date 50 | updatedAt: Date 51 | 52 | // mixins for association (optional) 53 | groupId: number 54 | group: UserGroup 55 | getGroup: BelongsToGetAssociationMixin 56 | setGroup: BelongsToSetAssociationMixin 57 | createGroup: BelongsToCreateAssociationMixin 58 | } 59 | 60 | User.init( 61 | { 62 | username: DataTypes.STRING, 63 | firstName: DataTypes.STRING, 64 | lastName: DataTypes.STRING, 65 | }, 66 | { sequelize } 67 | ) 68 | 69 | // associate 70 | // it is important to import _after_ the model above is already exported 71 | // so the circular dependency works. 72 | import { UserGroup } from './UserGroup' 73 | User.belongsTo(UserGroup, { as: 'group', foreignKey: 'groupId' }) 74 | ``` 75 | 76 | _app.ts_ 77 | 78 | ```ts 79 | import { User, Group } from './models/User' 80 | 81 | async function test() { 82 | const user = await User.findOne({ include: [Group] }) 83 | user.firstName = 'John' 84 | await user.save() 85 | await user.setGroup(2) 86 | 87 | new User() 88 | new User({ firstName: 'John' }) 89 | 90 | const user2 = await User.create({ firstName: 'John', groupId: 1 }) 91 | } 92 | ``` 93 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | export * from './lib/sequelize' 2 | export * from './lib/query-interface' 3 | export * from './lib/data-types' 4 | -------------------------------------------------------------------------------- /lib/associations/base.d.ts: -------------------------------------------------------------------------------- 1 | import { Model } from '../model' 2 | import { ColumnOptions } from '../model' 3 | 4 | export abstract class Association { 5 | public associationType: string 6 | public source: typeof Model 7 | public target: typeof Model 8 | public isSelfAssociation: boolean 9 | public isSingleAssociation: boolean 10 | public isMultiAssociation: boolean 11 | public as: string 12 | public isAliased: boolean 13 | public foreignKey: string 14 | public identifier: string 15 | public toInstanceArray(objs: any): Model[] 16 | public inspect(): string 17 | } 18 | 19 | export interface SingleAssociationAccessors { 20 | get: string 21 | set: string 22 | create: string 23 | } 24 | 25 | export interface MultiAssociationAccessors { 26 | get: string 27 | set: string 28 | addMultiple: string 29 | add: string 30 | create: string 31 | remove: string 32 | removeMultiple: string 33 | hasSingle: string 34 | hasAll: string 35 | count: string 36 | } 37 | 38 | /** Foreign Key Options */ 39 | export interface ForeignKeyOptions extends ColumnOptions { 40 | /** Attribute name for the relation */ 41 | name?: string 42 | } 43 | 44 | /** 45 | * Options provided when associating models 46 | */ 47 | export interface AssociationOptions { 48 | /** 49 | * Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. 50 | * For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks 51 | * for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking 52 | * any hooks. 53 | * 54 | * Defaults to false 55 | */ 56 | hooks?: boolean 57 | 58 | /** 59 | * The alias of this model, in singular form. See also the `name` option passed to `sequelize.define`. If 60 | * you create multiple associations between the same tables, you should provide an alias to be able to 61 | * distinguish between them. If you provide an alias when creating the assocition, you should provide the 62 | * same alias when eager loading and when getting assocated models. Defaults to the singularized name of 63 | * target 64 | */ 65 | as?: string | { singular: string; plural: string } 66 | 67 | /** 68 | * The name of the foreign key in the target table or an object representing the type definition for the 69 | * foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property 70 | * to set the name of the column. Defaults to the name of source + primary key of source 71 | */ 72 | foreignKey?: string | ForeignKeyOptions 73 | 74 | /** 75 | * What happens when delete occurs. 76 | * 77 | * Cascade if this is a n:m, and set null if it is a 1:m 78 | * 79 | * Defaults to 'SET NULL' or 'CASCADE' 80 | */ 81 | onDelete?: string 82 | 83 | /** 84 | * What happens when update occurs 85 | * 86 | * Defaults to 'CASCADE' 87 | */ 88 | onUpdate?: string 89 | 90 | /** 91 | * Should on update and on delete constraints be enabled on the foreign key. 92 | */ 93 | constraints?: boolean 94 | foreignKeyConstraint?: boolean 95 | 96 | scope?: AssociationScope 97 | } 98 | 99 | /** 100 | * Options for Association Scope 101 | */ 102 | export interface AssociationScope { 103 | /** 104 | * The name of the column that will be used for the associated scope and it's value 105 | */ 106 | [scopeName: string]: any 107 | } 108 | 109 | /** 110 | * Options provided for many-to-many relationships 111 | */ 112 | export interface ManyToManyOptions extends AssociationOptions { 113 | /** 114 | * A key/value set that will be used for association create and find defaults on the target. 115 | * (sqlite not supported for N:M) 116 | */ 117 | scope?: AssociationScope 118 | } 119 | -------------------------------------------------------------------------------- /lib/associations/belongs-to-many.d.ts: -------------------------------------------------------------------------------- 1 | import { 2 | BulkCreateOptions, 3 | CreateOptions, 4 | Filterable, 5 | FindOptions, 6 | InstanceDestroyOptions, 7 | InstanceUpdateOptions, 8 | Model, 9 | Transactionable, 10 | WhereOptions, 11 | } from '../model' 12 | import { Promise } from '../promise' 13 | import { Transaction } from '../transaction' 14 | import { Association, AssociationScope, ForeignKeyOptions, ManyToManyOptions, MultiAssociationAccessors } from './base' 15 | 16 | /** 17 | * Used for a association table in n:m associations. 18 | */ 19 | export interface ThroughOptions { 20 | /** 21 | * The model used to join both sides of the N:M association. 22 | */ 23 | model: typeof Model 24 | 25 | /** 26 | * A key/value set that will be used for association create and find defaults on the through model. 27 | * (Remember to add the attributes to the through model) 28 | */ 29 | scope?: AssociationScope 30 | 31 | /** 32 | * If true a unique key will be generated from the foreign keys used (might want to turn this off and create 33 | * specific unique keys when using scopes) 34 | * 35 | * Defaults to true 36 | */ 37 | unique?: boolean 38 | } 39 | 40 | /** 41 | * Attributes for the join table 42 | */ 43 | export interface JoinTableAttributes { 44 | [attribute: string]: any 45 | } 46 | 47 | /** 48 | * Options provided when associating models with belongsToMany relationship 49 | */ 50 | export interface BelongsToManyOptions extends ManyToManyOptions { 51 | /** 52 | * The name of the table that is used to join source and target in n:m associations. Can also be a 53 | * sequelize model if you want to define the junction table yourself and add extra attributes to it. 54 | */ 55 | through: typeof Model | string | ThroughOptions 56 | 57 | /** 58 | * The name of the foreign key in the join table (representing the target model) or an object representing 59 | * the type definition for the other column (see `Sequelize.define` for syntax). When using an object, you 60 | * can add a `name` property to set the name of the colum. Defaults to the name of target + primary key of 61 | * target 62 | */ 63 | otherKey?: string | ForeignKeyOptions 64 | 65 | /** 66 | * Should the join model have timestamps 67 | */ 68 | timestamps?: boolean 69 | } 70 | 71 | export class BelongsToMany extends Association { 72 | public otherKey: string 73 | public accessors: MultiAssociationAccessors 74 | constructor(source: typeof Model, target: typeof Model, options: BelongsToManyOptions) 75 | } 76 | 77 | /** 78 | * The options for the getAssociations mixin of the belongsToMany association. 79 | * @see BelongsToManyGetAssociationsMixin 80 | */ 81 | export interface BelongsToManyGetAssociationsMixinOptions extends FindOptions { 82 | /** 83 | * Apply a scope on the related model, or remove its default scope by passing false. 84 | */ 85 | scope?: string | boolean 86 | } 87 | 88 | /** 89 | * The getAssociations mixin applied to models with belongsToMany. 90 | * An example of usage is as follows: 91 | * 92 | * ```js 93 | * 94 | * User.belongsToMany(Role, { through: UserRole }); 95 | * 96 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 97 | * getRoles: Sequelize.BelongsToManyGetAssociationsMixin; 98 | * // setRoles... 99 | * // addRoles... 100 | * // addRole... 101 | * // createRole... 102 | * // removeRole... 103 | * // removeRoles... 104 | * // hasRole... 105 | * // hasRoles... 106 | * // countRoles... 107 | * } 108 | * ``` 109 | * 110 | * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/ 111 | * @see Instance 112 | */ 113 | export type BelongsToManyGetAssociationsMixin = ( 114 | options?: BelongsToManyGetAssociationsMixinOptions 115 | ) => Promise 116 | 117 | /** 118 | * The options for the setAssociations mixin of the belongsToMany association. 119 | * @see BelongsToManySetAssociationsMixin 120 | */ 121 | export interface BelongsToManySetAssociationsMixinOptions 122 | extends FindOptions, 123 | BulkCreateOptions, 124 | InstanceUpdateOptions, 125 | InstanceDestroyOptions { 126 | through?: JoinTableAttributes 127 | } 128 | 129 | /** 130 | * The setAssociations mixin applied to models with belongsToMany. 131 | * An example of usage is as follows: 132 | * 133 | * ```js 134 | * 135 | * User.belongsToMany(Role, { through: UserRole }); 136 | * 137 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 138 | * // getRoles... 139 | * setRoles: Sequelize.BelongsToManySetAssociationsMixin; 140 | * // addRoles... 141 | * // addRole... 142 | * // createRole... 143 | * // removeRole... 144 | * // removeRoles... 145 | * // hasRole... 146 | * // hasRoles... 147 | * // countRoles... 148 | * } 149 | * ``` 150 | * 151 | * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/ 152 | * @see Instance 153 | */ 154 | export type BelongsToManySetAssociationsMixin = ( 155 | newAssociations?: (TModel | TModelPrimaryKey)[], 156 | options?: BelongsToManySetAssociationsMixinOptions 157 | ) => Promise 158 | 159 | /** 160 | * The options for the addAssociations mixin of the belongsToMany association. 161 | * @see BelongsToManyAddAssociationsMixin 162 | */ 163 | export interface BelongsToManyAddAssociationsMixinOptions 164 | extends FindOptions, 165 | BulkCreateOptions, 166 | InstanceUpdateOptions, 167 | InstanceDestroyOptions { 168 | through?: JoinTableAttributes 169 | } 170 | 171 | /** 172 | * The addAssociations mixin applied to models with belongsToMany. 173 | * An example of usage is as follows: 174 | * 175 | * ```js 176 | * 177 | * User.belongsToMany(Role, { through: UserRole }); 178 | * 179 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 180 | * // getRoles... 181 | * // setRoles... 182 | * addRoles: Sequelize.BelongsToManyAddAssociationsMixin; 183 | * // addRole... 184 | * // createRole... 185 | * // removeRole... 186 | * // removeRoles... 187 | * // hasRole... 188 | * // hasRoles... 189 | * // countRoles... 190 | * } 191 | * ``` 192 | * 193 | * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/ 194 | * @see Instance 195 | */ 196 | export type BelongsToManyAddAssociationsMixin = ( 197 | newAssociations?: (TModel | TModelPrimaryKey)[], 198 | options?: BelongsToManyAddAssociationsMixinOptions 199 | ) => Promise 200 | 201 | /** 202 | * The options for the addAssociation mixin of the belongsToMany association. 203 | * @see BelongsToManyAddAssociationMixin 204 | */ 205 | export interface BelongsToManyAddAssociationMixinOptions 206 | extends FindOptions, 207 | BulkCreateOptions, 208 | InstanceUpdateOptions, 209 | InstanceDestroyOptions { 210 | through?: JoinTableAttributes 211 | } 212 | 213 | /** 214 | * The addAssociation mixin applied to models with belongsToMany. 215 | * An example of usage is as follows: 216 | * 217 | * ```js 218 | * 219 | * User.belongsToMany(Role, { through: UserRole }); 220 | * 221 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 222 | * // getRoles... 223 | * // setRoles... 224 | * // addRoles... 225 | * addRole: Sequelize.BelongsToManyAddAssociationMixin; 226 | * // createRole... 227 | * // removeRole... 228 | * // removeRoles... 229 | * // hasRole... 230 | * // hasRoles... 231 | * // countRoles... 232 | * } 233 | * ``` 234 | * 235 | * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/ 236 | * @see Instance 237 | */ 238 | export type BelongsToManyAddAssociationMixin = ( 239 | newAssociation?: TModel | TModelPrimaryKey, 240 | options?: BelongsToManyAddAssociationMixinOptions 241 | ) => Promise 242 | 243 | /** 244 | * The options for the createAssociation mixin of the belongsToMany association. 245 | * @see BelongsToManyCreateAssociationMixin 246 | */ 247 | export interface BelongsToManyCreateAssociationMixinOptions extends CreateOptions { 248 | through?: JoinTableAttributes 249 | } 250 | /** 251 | * The createAssociation mixin applied to models with belongsToMany. 252 | * An example of usage is as follows: 253 | * 254 | * ```js 255 | * 256 | * User.belongsToMany(Role, { through: UserRole }); 257 | * 258 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 259 | * // getRoles... 260 | * // setRoles... 261 | * // addRoles... 262 | * // addRole... 263 | * createRole: Sequelize.BelongsToManyCreateAssociationMixin; 264 | * // removeRole... 265 | * // removeRoles... 266 | * // hasRole... 267 | * // hasRoles... 268 | * // countRoles... 269 | * } 270 | * ``` 271 | * 272 | * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/ 273 | * @see Instance 274 | */ 275 | export type BelongsToManyCreateAssociationMixin = ( 276 | values?: { [attribute: string]: any }, 277 | options?: BelongsToManyCreateAssociationMixinOptions 278 | ) => Promise 279 | 280 | /** 281 | * The options for the removeAssociation mixin of the belongsToMany association. 282 | * @see BelongsToManyRemoveAssociationMixin 283 | */ 284 | export interface BelongsToManyRemoveAssociationMixinOptions extends InstanceDestroyOptions {} 285 | 286 | /** 287 | * The removeAssociation mixin applied to models with belongsToMany. 288 | * An example of usage is as follows: 289 | * 290 | * ```js 291 | * 292 | * User.belongsToMany(Role, { through: UserRole }); 293 | * 294 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 295 | * // getRoles... 296 | * // setRoles... 297 | * // addRoles... 298 | * // addRole... 299 | * // createRole... 300 | * removeRole: Sequelize.BelongsToManyRemoveAssociationMixin; 301 | * // removeRoles... 302 | * // hasRole... 303 | * // hasRoles... 304 | * // countRoles... 305 | * } 306 | * ``` 307 | * 308 | * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/ 309 | * @see Instance 310 | */ 311 | export type BelongsToManyRemoveAssociationMixin = ( 312 | oldAssociated?: TModel | TModelPrimaryKey, 313 | options?: BelongsToManyRemoveAssociationMixinOptions 314 | ) => Promise 315 | 316 | /** 317 | * The options for the removeAssociations mixin of the belongsToMany association. 318 | * @see BelongsToManyRemoveAssociationsMixin 319 | */ 320 | export interface BelongsToManyRemoveAssociationsMixinOptions extends InstanceDestroyOptions, InstanceDestroyOptions {} 321 | 322 | /** 323 | * The removeAssociations mixin applied to models with belongsToMany. 324 | * An example of usage is as follows: 325 | * 326 | * ```js 327 | * 328 | * User.belongsToMany(Role, { through: UserRole }); 329 | * 330 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 331 | * // getRoles... 332 | * // setRoles... 333 | * // addRoles... 334 | * // addRole... 335 | * // createRole... 336 | * // removeRole... 337 | * removeRoles: Sequelize.BelongsToManyRemoveAssociationsMixin; 338 | * // hasRole... 339 | * // hasRoles... 340 | * // countRoles... 341 | * } 342 | * ``` 343 | * 344 | * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/ 345 | * @see Instance 346 | */ 347 | export type BelongsToManyRemoveAssociationsMixin = ( 348 | oldAssociateds?: (TModel | TModelPrimaryKey)[], 349 | options?: BelongsToManyRemoveAssociationsMixinOptions 350 | ) => Promise 351 | 352 | /** 353 | * The options for the hasAssociation mixin of the belongsToMany association. 354 | * @see BelongsToManyHasAssociationMixin 355 | */ 356 | export interface BelongsToManyHasAssociationMixinOptions extends BelongsToManyGetAssociationsMixinOptions {} 357 | 358 | /** 359 | * The hasAssociation mixin applied to models with belongsToMany. 360 | * An example of usage is as follows: 361 | * 362 | * ```js 363 | * 364 | * User.belongsToMany(Role, { through: UserRole }); 365 | * 366 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 367 | * // getRoles... 368 | * // setRoles... 369 | * // addRoles... 370 | * // addRole... 371 | * // createRole... 372 | * // removeRole... 373 | * // removeRoles... 374 | * hasRole: Sequelize.BelongsToManyHasAssociationMixin; 375 | * // hasRoles... 376 | * // countRoles... 377 | * } 378 | * ``` 379 | * 380 | * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/ 381 | * @see Instance 382 | */ 383 | export type BelongsToManyHasAssociationMixin = ( 384 | target: TModel | TModelPrimaryKey, 385 | options?: BelongsToManyHasAssociationMixinOptions 386 | ) => Promise 387 | 388 | /** 389 | * The options for the hasAssociations mixin of the belongsToMany association. 390 | * @see BelongsToManyHasAssociationsMixin 391 | */ 392 | export interface BelongsToManyHasAssociationsMixinOptions extends BelongsToManyGetAssociationsMixinOptions {} 393 | 394 | /** 395 | * The removeAssociations mixin applied to models with belongsToMany. 396 | * An example of usage is as follows: 397 | * 398 | * ```js 399 | * 400 | * User.belongsToMany(Role, { through: UserRole }); 401 | * 402 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 403 | * // getRoles... 404 | * // setRoles... 405 | * // addRoles... 406 | * // addRole... 407 | * // createRole... 408 | * // removeRole... 409 | * // removeRoles 410 | * // hasRole... 411 | * hasRoles: Sequelize.BelongsToManyHasAssociationsMixin; 412 | * // countRoles... 413 | * } 414 | * ``` 415 | * 416 | * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/ 417 | * @see Instance 418 | */ 419 | export type BelongsToManyHasAssociationsMixin = ( 420 | targets: (TModel | TModelPrimaryKey)[], 421 | options?: BelongsToManyHasAssociationsMixinOptions 422 | ) => Promise 423 | 424 | /** 425 | * The options for the countAssociations mixin of the belongsToMany association. 426 | * @see BelongsToManyCountAssociationsMixin 427 | */ 428 | export interface BelongsToManyCountAssociationsMixinOptions extends Transactionable, Filterable { 429 | /** 430 | * Apply a scope on the related model, or remove its default scope by passing false. 431 | */ 432 | scope?: string | boolean 433 | } 434 | 435 | /** 436 | * The countAssociations mixin applied to models with belongsToMany. 437 | * An example of usage is as follows: 438 | * 439 | * ```js 440 | * 441 | * User.belongsToMany(Role, { through: UserRole }); 442 | * 443 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 444 | * // getRoles... 445 | * // setRoles... 446 | * // addRoles... 447 | * // addRole... 448 | * // createRole... 449 | * // removeRole... 450 | * // removeRoles... 451 | * // hasRole... 452 | * // hasRoles... 453 | * countRoles: Sequelize.BelongsToManyCountAssociationsMixin; 454 | * } 455 | * ``` 456 | * 457 | * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/ 458 | * @see Instance 459 | */ 460 | export type BelongsToManyCountAssociationsMixin = ( 461 | options?: BelongsToManyCountAssociationsMixinOptions 462 | ) => Promise 463 | -------------------------------------------------------------------------------- /lib/associations/belongs-to.d.ts: -------------------------------------------------------------------------------- 1 | import { DataType } from '../data-types' 2 | import { CreateOptions, FindOptions, Model, SaveOptions } from '../model' 3 | import { Promise } from '../promise' 4 | import { Association, SingleAssociationAccessors } from './base' 5 | import { AssociationOptions } from './base' 6 | 7 | /** 8 | * Options provided when associating models with belongsTo relationship 9 | * 10 | * @see Association class belongsTo method 11 | */ 12 | export interface BelongsToOptions extends AssociationOptions { 13 | /** 14 | * The name of the field to use as the key for the association in the target table. Defaults to the primary 15 | * key of the target table 16 | */ 17 | targetKey?: string 18 | 19 | /** 20 | * A string or a data type to represent the identifier in the table 21 | */ 22 | keyType?: DataType 23 | } 24 | 25 | export class BelongsTo extends Association { 26 | public accessors: SingleAssociationAccessors 27 | constructor(source: typeof Model, target: typeof Model, options: BelongsToOptions) 28 | } 29 | 30 | /** 31 | * The options for the getAssociation mixin of the belongsTo association. 32 | * @see BelongsToGetAssociationMixin 33 | */ 34 | export interface BelongsToGetAssociationMixinOptions extends FindOptions { 35 | /** 36 | * Apply a scope on the related model, or remove its default scope by passing false. 37 | */ 38 | scope?: string | string[] | boolean 39 | } 40 | 41 | /** 42 | * The getAssociation mixin applied to models with belongsTo. 43 | * An example of usage is as follows: 44 | * 45 | * ```js 46 | * 47 | * User.belongsTo(Role); 48 | * 49 | * interface UserInstance extends Sequelize.Instance, UserAttrib { 50 | * getRole: Sequelize.BelongsToGetAssociationMixin; 51 | * // setRole... 52 | * // createRole... 53 | * } 54 | * ``` 55 | * 56 | * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to/ 57 | * @see Instance 58 | */ 59 | export type BelongsToGetAssociationMixin = (options?: BelongsToGetAssociationMixinOptions) => Promise 60 | 61 | /** 62 | * The options for the setAssociation mixin of the belongsTo association. 63 | * @see BelongsToSetAssociationMixin 64 | */ 65 | export interface BelongsToSetAssociationMixinOptions extends SaveOptions { 66 | /** 67 | * Skip saving this after setting the foreign key if false. 68 | */ 69 | save?: boolean 70 | } 71 | 72 | /** 73 | * The setAssociation mixin applied to models with belongsTo. 74 | * An example of usage is as follows: 75 | * 76 | * ```js 77 | * 78 | * User.belongsTo(Role); 79 | * 80 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 81 | * // getRole... 82 | * setRole: Sequelize.BelongsToSetAssociationMixin; 83 | * // createRole... 84 | * } 85 | * ``` 86 | * 87 | * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to/ 88 | * @see Instance 89 | */ 90 | export type BelongsToSetAssociationMixin = ( 91 | newAssociation?: TModel | TPrimaryKey, 92 | options?: BelongsToSetAssociationMixinOptions 93 | ) => Promise 94 | 95 | /** 96 | * The options for the createAssociation mixin of the belongsTo association. 97 | * @see BelongsToCreateAssociationMixin 98 | */ 99 | export interface BelongsToCreateAssociationMixinOptions extends CreateOptions, BelongsToSetAssociationMixinOptions {} 100 | 101 | /** 102 | * The createAssociation mixin applied to models with belongsTo. 103 | * An example of usage is as follows: 104 | * 105 | * ```js 106 | * 107 | * User.belongsTo(Role); 108 | * 109 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 110 | * // getRole... 111 | * // setRole... 112 | * createRole: Sequelize.BelongsToCreateAssociationMixin; 113 | * } 114 | * ``` 115 | * 116 | * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to/ 117 | * @see Instance 118 | */ 119 | export type BelongsToCreateAssociationMixin = ( 120 | values?: { [attribute: string]: any }, 121 | options?: BelongsToCreateAssociationMixinOptions 122 | ) => Promise 123 | 124 | export default BelongsTo 125 | -------------------------------------------------------------------------------- /lib/associations/has-many.d.ts: -------------------------------------------------------------------------------- 1 | import { DataType } from '../data-types' 2 | import { 3 | CreateOptions, 4 | Filterable, 5 | FindOptions, 6 | InstanceUpdateOptions, 7 | Model, 8 | Transactionable, 9 | WhereOptions, 10 | } from '../model' 11 | import { Promise } from '../promise' 12 | import { Transaction } from '../transaction' 13 | import { Association, ManyToManyOptions, MultiAssociationAccessors } from './base' 14 | 15 | /** 16 | * Options provided when associating models with hasMany relationship 17 | */ 18 | export interface HasManyOptions extends ManyToManyOptions { 19 | /** 20 | * A string or a data type to represent the identifier in the table 21 | */ 22 | keyType?: DataType 23 | } 24 | 25 | export class HasMany extends Association { 26 | public accessors: MultiAssociationAccessors 27 | constructor(source: typeof Model, target: typeof Model, options: HasManyOptions) 28 | } 29 | 30 | /** 31 | * The options for the getAssociations mixin of the hasMany association. 32 | * @see HasManyGetAssociationsMixin 33 | */ 34 | export interface HasManyGetAssociationsMixinOptions extends FindOptions { 35 | /** 36 | * Apply a scope on the related model, or remove its default scope by passing false. 37 | */ 38 | scope?: string | string[] | boolean 39 | } 40 | 41 | /** 42 | * The getAssociations mixin applied to models with hasMany. 43 | * An example of usage is as follows: 44 | * 45 | * ```js 46 | * 47 | * User.hasMany(Role); 48 | * 49 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 50 | * getRoles: Sequelize.HasManyGetAssociationsMixin; 51 | * // setRoles... 52 | * // addRoles... 53 | * // addRole... 54 | * // createRole... 55 | * // removeRole... 56 | * // removeRoles... 57 | * // hasRole... 58 | * // hasRoles... 59 | * // countRoles... 60 | * } 61 | * ``` 62 | * 63 | * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/ 64 | * @see Instance 65 | */ 66 | export type HasManyGetAssociationsMixin = (options?: HasManyGetAssociationsMixinOptions) => Promise 67 | 68 | /** 69 | * The options for the setAssociations mixin of the hasMany association. 70 | * @see HasManySetAssociationsMixin 71 | */ 72 | export interface HasManySetAssociationsMixinOptions extends FindOptions, InstanceUpdateOptions {} 73 | 74 | /** 75 | * The setAssociations mixin applied to models with hasMany. 76 | * An example of usage is as follows: 77 | * 78 | * ```js 79 | * 80 | * User.hasMany(Role); 81 | * 82 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 83 | * // getRoles... 84 | * setRoles: Sequelize.HasManySetAssociationsMixin; 85 | * // addRoles... 86 | * // addRole... 87 | * // createRole... 88 | * // removeRole... 89 | * // removeRoles... 90 | * // hasRole... 91 | * // hasRoles... 92 | * // countRoles... 93 | * } 94 | * ``` 95 | * 96 | * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/ 97 | * @see Instance 98 | */ 99 | export type HasManySetAssociationsMixin = ( 100 | newAssociations?: (TModel | TModelPrimaryKey)[], 101 | options?: HasManySetAssociationsMixinOptions 102 | ) => Promise 103 | 104 | /** 105 | * The options for the addAssociations mixin of the hasMany association. 106 | * @see HasManyAddAssociationsMixin 107 | */ 108 | export interface HasManyAddAssociationsMixinOptions extends InstanceUpdateOptions {} 109 | 110 | /** 111 | * The addAssociations mixin applied to models with hasMany. 112 | * An example of usage is as follows: 113 | * 114 | * ```js 115 | * 116 | * User.hasMany(Role); 117 | * 118 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 119 | * // getRoles... 120 | * // setRoles... 121 | * addRoles: Sequelize.HasManyAddAssociationsMixin; 122 | * // addRole... 123 | * // createRole... 124 | * // removeRole... 125 | * // removeRoles... 126 | * // hasRole... 127 | * // hasRoles... 128 | * // countRoles... 129 | * } 130 | * ``` 131 | * 132 | * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/ 133 | * @see Instance 134 | */ 135 | export type HasManyAddAssociationsMixin = ( 136 | newAssociations?: (TModel | TModelPrimaryKey)[], 137 | options?: HasManyAddAssociationsMixinOptions 138 | ) => Promise 139 | 140 | /** 141 | * The options for the addAssociation mixin of the hasMany association. 142 | * @see HasManyAddAssociationMixin 143 | */ 144 | export interface HasManyAddAssociationMixinOptions extends InstanceUpdateOptions {} 145 | 146 | /** 147 | * The addAssociation mixin applied to models with hasMany. 148 | * An example of usage is as follows: 149 | * 150 | * ```js 151 | * 152 | * User.hasMany(Role); 153 | * 154 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 155 | * // getRoles... 156 | * // setRoles... 157 | * // addRoles... 158 | * addRole: Sequelize.HasManyAddAssociationMixin; 159 | * // createRole... 160 | * // removeRole... 161 | * // removeRoles... 162 | * // hasRole... 163 | * // hasRoles... 164 | * // countRoles... 165 | * } 166 | * ``` 167 | * 168 | * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/ 169 | * @see Instance 170 | */ 171 | export type HasManyAddAssociationMixin = ( 172 | newAssociation?: TModel | TModelPrimaryKey, 173 | options?: HasManyAddAssociationMixinOptions 174 | ) => Promise 175 | 176 | /** 177 | * The options for the createAssociation mixin of the hasMany association. 178 | * @see HasManyCreateAssociationMixin 179 | */ 180 | export interface HasManyCreateAssociationMixinOptions extends CreateOptions {} 181 | 182 | /** 183 | * The createAssociation mixin applied to models with hasMany. 184 | * An example of usage is as follows: 185 | * 186 | * ```js 187 | * 188 | * User.hasMany(Role); 189 | * 190 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 191 | * // getRoles... 192 | * // setRoles... 193 | * // addRoles... 194 | * // addRole... 195 | * createRole: Sequelize.HasManyCreateAssociationMixin; 196 | * // removeRole... 197 | * // removeRoles... 198 | * // hasRole... 199 | * // hasRoles... 200 | * // countRoles... 201 | * } 202 | * ``` 203 | * 204 | * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/ 205 | * @see Instance 206 | */ 207 | export type HasManyCreateAssociationMixin = ( 208 | values?: { [attribute: string]: any }, 209 | options?: HasManyCreateAssociationMixinOptions 210 | ) => Promise 211 | 212 | /** 213 | * The options for the removeAssociation mixin of the hasMany association. 214 | * @see HasManyRemoveAssociationMixin 215 | */ 216 | export interface HasManyRemoveAssociationMixinOptions extends InstanceUpdateOptions {} 217 | 218 | /** 219 | * The removeAssociation mixin applied to models with hasMany. 220 | * An example of usage is as follows: 221 | * 222 | * ```js 223 | * 224 | * User.hasMany(Role); 225 | * 226 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 227 | * // getRoles... 228 | * // setRoles... 229 | * // addRoles... 230 | * // addRole... 231 | * // createRole... 232 | * removeRole: Sequelize.HasManyRemoveAssociationMixin; 233 | * // removeRoles... 234 | * // hasRole... 235 | * // hasRoles... 236 | * // countRoles... 237 | * } 238 | * ``` 239 | * 240 | * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/ 241 | * @see Instance 242 | */ 243 | export type HasManyRemoveAssociationMixin = ( 244 | oldAssociated?: TModel | TModelPrimaryKey, 245 | options?: HasManyRemoveAssociationMixinOptions 246 | ) => Promise 247 | 248 | /** 249 | * The options for the removeAssociations mixin of the hasMany association. 250 | * @see HasManyRemoveAssociationsMixin 251 | */ 252 | export interface HasManyRemoveAssociationsMixinOptions extends InstanceUpdateOptions {} 253 | 254 | /** 255 | * The removeAssociations mixin applied to models with hasMany. 256 | * An example of usage is as follows: 257 | * 258 | * ```js 259 | * 260 | * User.hasMany(Role); 261 | * 262 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 263 | * // getRoles... 264 | * // setRoles... 265 | * // addRoles... 266 | * // addRole... 267 | * // createRole... 268 | * // removeRole... 269 | * removeRoles: Sequelize.HasManyRemoveAssociationsMixin; 270 | * // hasRole... 271 | * // hasRoles... 272 | * // countRoles... 273 | * } 274 | * ``` 275 | * 276 | * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/ 277 | * @see Instance 278 | */ 279 | export type HasManyRemoveAssociationsMixin = ( 280 | oldAssociateds?: (TModel | TModelPrimaryKey)[], 281 | options?: HasManyRemoveAssociationsMixinOptions 282 | ) => Promise 283 | 284 | /** 285 | * The options for the hasAssociation mixin of the hasMany association. 286 | * @see HasManyHasAssociationMixin 287 | */ 288 | export interface HasManyHasAssociationMixinOptions extends HasManyGetAssociationsMixinOptions {} 289 | 290 | /** 291 | * The hasAssociation mixin applied to models with hasMany. 292 | * An example of usage is as follows: 293 | * 294 | * ```js 295 | * 296 | * User.hasMany(Role); 297 | * 298 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 299 | * // getRoles... 300 | * // setRoles... 301 | * // addRoles... 302 | * // addRole... 303 | * // createRole... 304 | * // removeRole... 305 | * // removeRoles... 306 | * hasRole: Sequelize.HasManyHasAssociationMixin; 307 | * // hasRoles... 308 | * // countRoles... 309 | * } 310 | * ``` 311 | * 312 | * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/ 313 | * @see Instance 314 | */ 315 | export type HasManyHasAssociationMixin = ( 316 | target: TModel | TModelPrimaryKey, 317 | options?: HasManyHasAssociationMixinOptions 318 | ) => Promise 319 | 320 | /** 321 | * The options for the hasAssociations mixin of the hasMany association. 322 | * @see HasManyHasAssociationsMixin 323 | */ 324 | export interface HasManyHasAssociationsMixinOptions extends HasManyGetAssociationsMixinOptions {} 325 | 326 | /** 327 | * The removeAssociations mixin applied to models with hasMany. 328 | * An example of usage is as follows: 329 | * 330 | * ```js 331 | * 332 | * User.hasMany(Role); 333 | * 334 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 335 | * // getRoles... 336 | * // setRoles... 337 | * // addRoles... 338 | * // addRole... 339 | * // createRole... 340 | * // removeRole... 341 | * // removeRoles 342 | * // hasRole... 343 | * hasRoles: Sequelize.HasManyHasAssociationsMixin; 344 | * // countRoles... 345 | * } 346 | * ``` 347 | * 348 | * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/ 349 | * @see Instance 350 | */ 351 | export type HasManyHasAssociationsMixin = ( 352 | targets: (TModel | TModelPrimaryKey)[], 353 | options?: HasManyHasAssociationsMixinOptions 354 | ) => Promise 355 | 356 | /** 357 | * The options for the countAssociations mixin of the hasMany association. 358 | * @see HasManyCountAssociationsMixin 359 | */ 360 | export interface HasManyCountAssociationsMixinOptions extends Transactionable, Filterable { 361 | /** 362 | * Apply a scope on the related model, or remove its default scope by passing false. 363 | */ 364 | scope?: string | boolean 365 | } 366 | 367 | /** 368 | * The countAssociations mixin applied to models with hasMany. 369 | * An example of usage is as follows: 370 | * 371 | * ```js 372 | * 373 | * User.hasMany(Role); 374 | * 375 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 376 | * // getRoles... 377 | * // setRoles... 378 | * // addRoles... 379 | * // addRole... 380 | * // createRole... 381 | * // removeRole... 382 | * // removeRoles... 383 | * // hasRole... 384 | * // hasRoles... 385 | * countRoles: Sequelize.HasManyCountAssociationsMixin; 386 | * } 387 | * ``` 388 | * 389 | * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/ 390 | * @see Instance 391 | */ 392 | export type HasManyCountAssociationsMixin = (options?: HasManyCountAssociationsMixinOptions) => Promise 393 | -------------------------------------------------------------------------------- /lib/associations/has-one.d.ts: -------------------------------------------------------------------------------- 1 | import { DataType } from '../data-types' 2 | import { CreateOptions, FindOptions, Model, SaveOptions } from '../model' 3 | import { Promise } from '../promise' 4 | import { Association, AssociationOptions, SingleAssociationAccessors } from './base' 5 | 6 | /** 7 | * Options provided when associating models with hasOne relationship 8 | */ 9 | export interface HasOneOptions extends AssociationOptions { 10 | /** 11 | * A string or a data type to represent the identifier in the table 12 | */ 13 | keyType?: DataType 14 | } 15 | 16 | export class HasOne extends Association { 17 | public accessors: SingleAssociationAccessors 18 | constructor(source: typeof Model, target: typeof Model, options: HasOneOptions) 19 | } 20 | 21 | /** 22 | * The options for the getAssociation mixin of the hasOne association. 23 | * @see HasOneGetAssociationMixin 24 | */ 25 | export interface HasOneGetAssociationMixinOptions extends FindOptions { 26 | /** 27 | * Apply a scope on the related model, or remove its default scope by passing false. 28 | */ 29 | scope?: string | string[] | boolean 30 | } 31 | 32 | /** 33 | * The getAssociation mixin applied to models with hasOne. 34 | * An example of usage is as follows: 35 | * 36 | * ```js 37 | * 38 | * User.hasOne(Role); 39 | * 40 | * interface UserInstance extends Sequelize.Instance, UserAttrib { 41 | * getRole: Sequelize.HasOneGetAssociationMixin; 42 | * // setRole... 43 | * // createRole... 44 | * } 45 | * ``` 46 | * 47 | * @see http://docs.sequelizejs.com/en/latest/api/associations/has-one/ 48 | * @see Instance 49 | */ 50 | export type HasOneGetAssociationMixin = (options?: HasOneGetAssociationMixinOptions) => Promise 51 | 52 | /** 53 | * The options for the setAssociation mixin of the hasOne association. 54 | * @see HasOneSetAssociationMixin 55 | */ 56 | export interface HasOneSetAssociationMixinOptions extends HasOneGetAssociationMixinOptions, SaveOptions { 57 | /** 58 | * Skip saving this after setting the foreign key if false. 59 | */ 60 | save?: boolean 61 | } 62 | 63 | /** 64 | * The setAssociation mixin applied to models with hasOne. 65 | * An example of usage is as follows: 66 | * 67 | * ```js 68 | * 69 | * User.hasOne(Role); 70 | * 71 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 72 | * // getRole... 73 | * setRole: Sequelize.HasOneSetAssociationMixin; 74 | * // createRole... 75 | * } 76 | * ``` 77 | * 78 | * @see http://docs.sequelizejs.com/en/latest/api/associations/has-one/ 79 | * @see Instance 80 | */ 81 | export type HasOneSetAssociationMixin = ( 82 | newAssociation?: TModel | TModelPrimaryKey, 83 | options?: HasOneSetAssociationMixinOptions 84 | ) => Promise 85 | 86 | /** 87 | * The options for the createAssociation mixin of the hasOne association. 88 | * @see HasOneCreateAssociationMixin 89 | */ 90 | export interface HasOneCreateAssociationMixinOptions extends HasOneSetAssociationMixinOptions, CreateOptions {} 91 | 92 | /** 93 | * The createAssociation mixin applied to models with hasOne. 94 | * An example of usage is as follows: 95 | * 96 | * ```js 97 | * 98 | * User.hasOne(Role); 99 | * 100 | * interface UserInstance extends Sequelize.Instance, UserAttributes { 101 | * // getRole... 102 | * // setRole... 103 | * createRole: Sequelize.HasOneCreateAssociationMixin; 104 | * } 105 | * ``` 106 | * 107 | * @see http://docs.sequelizejs.com/en/latest/api/associations/has-one/ 108 | * @see Instance 109 | */ 110 | export type HasOneCreateAssociationMixin = ( 111 | values?: { [attribute: string]: any }, 112 | options?: HasOneCreateAssociationMixinOptions 113 | ) => Promise 114 | -------------------------------------------------------------------------------- /lib/associations/index.d.ts: -------------------------------------------------------------------------------- 1 | export * from './base' 2 | export * from './belongs-to' 3 | export * from './has-one' 4 | export * from './has-many' 5 | export * from './belongs-to-many' 6 | -------------------------------------------------------------------------------- /lib/data-types.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * The datatypes are used when defining a new model using `Sequelize.define`, like this: 3 | * ```js 4 | * sequelize.define('model', { 5 | * column: DataTypes.INTEGER 6 | * }) 7 | * ``` 8 | * 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 9 | * that that column will be returned as an instance of `Buffer` when being fetched by sequelize. 10 | * 11 | * Some data types have special properties that can be accessed in order to change the data type. 12 | * For example, to get an unsigned integer with zerofill you can do `DataTypes.INTEGER.UNSIGNED.ZEROFILL`. 13 | * 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. 14 | * 15 | * To provide a length for the data type, you can invoke it like a function: `INTEGER(2)` 16 | * 17 | * 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 18 | * defining default values. For example, to get a uuid field with a default value generated following v1 of the UUID standard: 19 | * ```js 20 | * sequelize.define('model', { 21 | * uuid: { 22 | * type: DataTypes.UUID, 23 | * defaultValue: DataTypes.UUIDV1, 24 | * primaryKey: true 25 | * } 26 | * }) 27 | * ``` 28 | * There may be times when you want to generate your own UUID conforming to some other algorithm. This is accomplised 29 | * using the defaultValue property as well, but instead of specifying one of the supplied UUID types, you return a value 30 | * from a function. 31 | * ```js 32 | * sequelize.define('model', { 33 | * uuid: { 34 | * type: DataTypes.UUID, 35 | * defaultValue: function() { 36 | * return generateMyId() 37 | * }, 38 | * primaryKey: true 39 | * } 40 | * }) 41 | * ``` 42 | */ 43 | 44 | /** 45 | * 46 | */ 47 | export type DataType = string | AbstractDataTypeConstructor | AbstractDataType 48 | 49 | export const ABSTRACT: AbstractDataTypeConstructor 50 | 51 | interface AbstractDataTypeConstructor { 52 | key: string 53 | warn(link: string, text: string): void 54 | } 55 | 56 | export interface AbstractDataType { 57 | key: string 58 | dialectTypes: string 59 | toSql(): string 60 | stringify(value: any, options?: object): string 61 | toString(options: object): string 62 | } 63 | 64 | /** 65 | * A variable length string. Default length 255 66 | * 67 | * Available properties: `BINARY` 68 | * 69 | * @property STRING 70 | */ 71 | export const STRING: StringDataTypeConstructor 72 | 73 | interface StringDataTypeConstructor extends AbstractDataTypeConstructor { 74 | new (length?: number, binary?: boolean): StringDataType 75 | new (options?: StringDataTypeOptions): StringDataType 76 | (length?: number, binary?: boolean): StringDataType 77 | (options?: StringDataTypeOptions): StringDataType 78 | } 79 | 80 | export interface StringDataType extends AbstractDataType { 81 | options?: StringDataTypeOptions 82 | BINARY: this 83 | validate(value: any): boolean 84 | } 85 | 86 | export interface StringDataTypeOptions { 87 | length?: number 88 | binary?: boolean 89 | } 90 | 91 | /** 92 | * A fixed length string. Default length 255 93 | * 94 | * Available properties: `BINARY` 95 | * 96 | */ 97 | export const CHAR: CharDataTypeConstructor 98 | 99 | interface CharDataTypeConstructor extends StringDataTypeConstructor { 100 | new (length?: number, binary?: boolean): CharDataType 101 | new (options?: CharDataTypeOptions): CharDataType 102 | (length?: number, binary?: boolean): CharDataType 103 | (options?: CharDataTypeOptions): CharDataType 104 | } 105 | 106 | export interface CharDataType extends StringDataType { 107 | options: CharDataTypeOptions 108 | } 109 | 110 | export interface CharDataTypeOptions extends StringDataTypeOptions {} 111 | 112 | /** 113 | * An (un)limited length text column. Available lengths: `tiny`, `medium`, `long` 114 | */ 115 | export const TEXT: TextDataTypeConstructor 116 | 117 | interface TextDataTypeConstructor extends AbstractDataTypeConstructor { 118 | new (length?: number): TextDataType 119 | (options?: TextDataTypeOptions): TextDataType 120 | } 121 | 122 | export interface TextDataType extends AbstractDataType { 123 | options: TextDataTypeOptions 124 | validate(value: any): boolean 125 | } 126 | 127 | export interface TextDataTypeOptions { 128 | length?: number 129 | } 130 | 131 | export const NUMBER: NumberDataTypeConstructor 132 | 133 | interface NumberDataTypeConstructor extends AbstractDataTypeConstructor { 134 | new (options?: NumberDataTypeOptions): NumberDataType 135 | (options?: NumberDataTypeOptions): NumberDataType 136 | options: NumberDataTypeOptions 137 | validate(value: any): boolean 138 | UNSIGNED: this 139 | ZEROFILL: this 140 | } 141 | 142 | export interface NumberDataType extends AbstractDataType { 143 | options: NumberDataTypeOptions 144 | validate(value: any): boolean 145 | UNSIGNED: this 146 | ZEROFILL: this 147 | } 148 | 149 | export interface NumberDataTypeOptions { 150 | length?: number 151 | zerofill?: boolean 152 | decimals?: number 153 | precision?: number 154 | scale?: number 155 | unsigned?: boolean 156 | } 157 | 158 | /** 159 | * A 32 bit integer. 160 | * 161 | * Available properties: `UNSIGNED`, `ZEROFILL` 162 | * 163 | */ 164 | export const INTEGER: IntegerDataTypeConstructor 165 | 166 | interface IntegerDataTypeConstructor extends NumberDataTypeConstructor { 167 | new (options?: NumberDataTypeOptions): IntegerDataType 168 | (options?: NumberDataTypeOptions): IntegerDataType 169 | } 170 | 171 | export interface IntegerDataType extends NumberDataType { 172 | options: NumberDataTypeOptions 173 | } 174 | 175 | export interface IntegerDataTypeOptions { 176 | length?: number 177 | } 178 | 179 | /** 180 | * A 64 bit integer. 181 | * 182 | * Available properties: `UNSIGNED`, `ZEROFILL` 183 | * 184 | */ 185 | export const BIGINT: BigIntDataTypeConstructor 186 | 187 | interface BigIntDataTypeConstructor extends NumberDataTypeConstructor { 188 | new (options?: BigIntDataTypeOptions): BigIntDataType 189 | (options?: BigIntDataTypeOptions): BigIntDataType 190 | } 191 | 192 | export interface BigIntDataType extends NumberDataType { 193 | options: BigIntDataTypeOptions 194 | } 195 | 196 | export interface BigIntDataTypeOptions { 197 | length?: number 198 | } 199 | 200 | /** 201 | * Floating point number (4-byte precision). Accepts one or two arguments for precision 202 | */ 203 | export const FLOAT: FloatDataTypeConstructor 204 | 205 | interface FloatDataTypeConstructor extends NumberDataTypeConstructor { 206 | new (length?: number, decimals?: number): FloatDataType 207 | new (options?: FloatDataTypeOptions): FloatDataType 208 | (length?: number, decimals?: number): FloatDataType 209 | (options?: FloatDataTypeOptions): FloatDataType 210 | } 211 | 212 | export interface FloatDataType extends NumberDataType { 213 | options: FloatDataTypeOptions 214 | } 215 | 216 | export interface FloatDataTypeOptions { 217 | length?: number 218 | decimals?: number 219 | } 220 | 221 | /** 222 | * Floating point number (4-byte precision). Accepts one or two arguments for precision 223 | */ 224 | export const REAL: RealDataTypeConstructor 225 | 226 | interface RealDataTypeConstructor extends NumberDataTypeConstructor { 227 | new (length?: number, decimals?: number): RealDataType 228 | new (options?: RealDataTypeOptions): RealDataType 229 | (length?: number, decimals?: number): RealDataType 230 | (options?: RealDataTypeOptions): RealDataType 231 | } 232 | 233 | export interface RealDataType extends NumberDataType { 234 | options: RealDataTypeOptions 235 | } 236 | 237 | export interface RealDataTypeOptions { 238 | length?: number 239 | decimals?: number 240 | } 241 | 242 | /** 243 | * Floating point number (8-byte precision). Accepts one or two arguments for precision 244 | */ 245 | export const DOUBLE: DoubleDataTypeConstructor 246 | 247 | interface DoubleDataTypeConstructor extends NumberDataTypeConstructor { 248 | new (length?: number, decimals?: number): DoubleDataType 249 | new (options?: DoubleDataTypeOptions): DoubleDataType 250 | (length?: number, decimals?: number): DoubleDataType 251 | (options?: DoubleDataTypeOptions): DoubleDataType 252 | } 253 | 254 | export interface DoubleDataType extends NumberDataType { 255 | options: DoubleDataTypeOptions 256 | } 257 | 258 | export interface DoubleDataTypeOptions { 259 | length?: number 260 | decimals?: number 261 | } 262 | 263 | /** 264 | * Decimal number. Accepts one or two arguments for precision 265 | */ 266 | export const DECIMAL: DecimalDataTypeConstructor 267 | 268 | interface DecimalDataTypeConstructor extends NumberDataTypeConstructor { 269 | new (precision?: number, scale?: number): DecimalDataType 270 | new (options?: DecimalDataTypeOptions): DecimalDataType 271 | (precision?: number, scale?: number): DecimalDataType 272 | (options?: DecimalDataTypeOptions): DecimalDataType 273 | PRECISION: this 274 | SCALE: this 275 | } 276 | 277 | export interface DecimalDataType extends NumberDataType { 278 | options: DecimalDataTypeOptions 279 | } 280 | 281 | export interface DecimalDataTypeOptions { 282 | precision?: number 283 | scale?: number 284 | } 285 | 286 | /** 287 | * A boolean / tinyint column, depending on dialect 288 | */ 289 | export const BOOLEAN: AbstractDataTypeConstructor 290 | 291 | /** 292 | * A time column 293 | */ 294 | export const TIME: AbstractDataTypeConstructor 295 | 296 | /** 297 | * A datetime column 298 | */ 299 | export const DATE: DateDataTypeConstructor 300 | 301 | interface DateDataTypeConstructor extends AbstractDataTypeConstructor { 302 | new (length?: any): DateDataType 303 | new (options?: DateDataTypeOptions): DateDataType 304 | (length?: any): DateDataType 305 | (options?: DateDataTypeOptions): DateDataType 306 | } 307 | 308 | export interface DateDataType extends AbstractDataTypeConstructor { 309 | options: DateDataTypeOptions 310 | } 311 | 312 | export interface DateDataTypeOptions { 313 | length?: any 314 | } 315 | 316 | /** 317 | * A date only column 318 | */ 319 | export const DATEONLY: DateOnlyDataTypeConstructor 320 | 321 | interface DateOnlyDataTypeConstructor extends AbstractDataTypeConstructor { 322 | new (length: any): DateOnlyDataType 323 | new (options: DateOnlyDataTypeOptions): DateOnlyDataType 324 | (length: any): DateOnlyDataType 325 | (options: DateOnlyDataTypeOptions): DateOnlyDataType 326 | } 327 | 328 | export interface DateOnlyDataType extends AbstractDataType { 329 | options: DateOnlyDataTypeOptions 330 | } 331 | 332 | export interface DateOnlyDataTypeOptions { 333 | length?: any 334 | } 335 | 336 | /** 337 | * A key / value column. Only available in postgres. 338 | */ 339 | export const HSTORE: AbstractDataTypeConstructor 340 | 341 | /** 342 | * A JSON string column. Only available in postgres. 343 | */ 344 | export const JSON: AbstractDataTypeConstructor 345 | 346 | /** 347 | * A pre-processed JSON data column. Only available in postgres. 348 | */ 349 | export const JSONB: AbstractDataTypeConstructor 350 | 351 | /** 352 | * A default value of the current timestamp 353 | */ 354 | export const NOW: AbstractDataTypeConstructor 355 | 356 | /** 357 | * Binary storage. Available lengths: `tiny`, `medium`, `long` 358 | */ 359 | export const BLOB: BlobDataTypeConstructor 360 | 361 | export type BlobSize = 'tiny' | 'medium' | 'long' 362 | 363 | interface BlobDataTypeConstructor extends AbstractDataTypeConstructor { 364 | new (length?: BlobSize): BlobDataType 365 | new (options?: BlobDataTypeOptions): BlobDataType 366 | (length?: BlobSize): BlobDataType 367 | (options?: BlobDataTypeOptions): BlobDataType 368 | } 369 | 370 | export interface BlobDataType extends AbstractDataType { 371 | options: BlobDataTypeOptions 372 | escape: boolean 373 | } 374 | 375 | export interface BlobDataTypeOptions { 376 | length?: BlobSize 377 | escape?: boolean 378 | } 379 | 380 | /** 381 | * Range types are data types representing a range of values of some element type (called the range's subtype). 382 | * Only available in postgres. 383 | * 384 | * See [Postgres documentation](http://www.postgresql.org/docs/9.4/static/rangetypes.html) for more details 385 | */ 386 | export const RANGE: RangeDataTypeConstructor 387 | 388 | export type RangeableDataType = 389 | | IntegerDataTypeConstructor 390 | | IntegerDataType 391 | | BigIntDataTypeConstructor 392 | | BigIntDataType 393 | | DecimalDataTypeConstructor 394 | | DecimalDataType 395 | | DateOnlyDataTypeConstructor 396 | | DateOnlyDataType 397 | | DateDataTypeConstructor 398 | | DateDataType 399 | 400 | interface RangeDataTypeConstructor extends AbstractDataTypeConstructor { 401 | new (subtype?: T): RangeDataType 402 | new (options: RangeDataTypeOptions): RangeDataType 403 | (subtype?: T): RangeDataType 404 | (options: RangeDataTypeOptions): RangeDataType 405 | } 406 | 407 | export interface RangeDataType extends AbstractDataType { 408 | options: RangeDataTypeOptions 409 | } 410 | 411 | export interface RangeDataTypeOptions { 412 | subtype?: T 413 | } 414 | 415 | /** 416 | * A column storing a unique universal identifier. Use with `UUIDV1` or `UUIDV4` for default values. 417 | */ 418 | export const UUID: AbstractDataTypeConstructor 419 | 420 | /** 421 | * A default unique universal identifier generated following the UUID v1 standard 422 | */ 423 | export const UUIDV1: AbstractDataTypeConstructor 424 | 425 | /** 426 | * A default unique universal identifier generated following the UUID v4 standard 427 | */ 428 | export const UUIDV4: AbstractDataTypeConstructor 429 | 430 | /** 431 | * 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. 432 | * 433 | * You could also use it to validate a value before permuting and storing it. Checking password length before hashing it for example: 434 | * ```js 435 | * sequelize.define('user', { 436 | * password_hash: DataTypes.STRING, 437 | * password: { 438 | * type: DataTypes.VIRTUAL, 439 | * set: function (val) { 440 | * this.setDataValue('password', val); // Remember to set the data value, otherwise it won't be validated 441 | * this.setDataValue('password_hash', this.salt + val); 442 | * }, 443 | * validate: { 444 | * isLongEnough: function (val) { 445 | * if (val.length < 7) { 446 | * throw new Error("Please choose a longer password") 447 | * } 448 | * } 449 | * } 450 | * } 451 | * }) 452 | * ``` 453 | * 454 | * VIRTUAL also takes a return type and dependency fields as arguments 455 | * If a virtual attribute is present in `attributes` it will automatically pull in the extra fields as well. 456 | * Return type is mostly useful for setups that rely on types like GraphQL. 457 | * ```js 458 | * { 459 | * active: { 460 | * type: new DataTypes.VIRTUAL(DataTypes.BOOLEAN, ['createdAt']), 461 | * get: function() { 462 | * return this.get('createdAt') > Date.now() - (7 * 24 * 60 * 60 * 1000) 463 | * } 464 | * } 465 | * } 466 | * ``` 467 | * 468 | * 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. 469 | * @alias NONE 470 | */ 471 | export const VIRTUAL: VirtualDataTypeConstructor 472 | 473 | interface VirtualDataTypeConstructor extends AbstractDataTypeConstructor { 474 | new (ReturnType: T, fields?: string[]): VirtualDataType 475 | (ReturnType: T, fields?: string[]): VirtualDataType 476 | } 477 | 478 | export interface VirtualDataType extends AbstractDataType { 479 | returnType: T 480 | fields: string[] 481 | } 482 | 483 | /** 484 | * An enumeration. `DataTypes.ENUM('value', 'another value')`. 485 | */ 486 | export const ENUM: EnumDataTypeConstructor 487 | 488 | interface EnumDataTypeConstructor extends AbstractDataTypeConstructor { 489 | new (...values: T[]): EnumDataType 490 | new (options: EnumDataTypeOptions): EnumDataType 491 | (...values: T[]): EnumDataType 492 | (options: EnumDataTypeOptions): EnumDataType 493 | } 494 | 495 | export interface EnumDataType extends AbstractDataType { 496 | values: T[] 497 | options: EnumDataTypeOptions 498 | } 499 | 500 | export interface EnumDataTypeOptions { 501 | values: T[] 502 | } 503 | 504 | /** 505 | * An array of `type`, e.g. `DataTypes.ARRAY(DataTypes.DECIMAL)`. Only available in postgres. 506 | */ 507 | export const ARRAY: ArrayDataTypeConstructor 508 | 509 | interface ArrayDataTypeConstructor extends AbstractDataTypeConstructor { 510 | new (type: T): ArrayDataType 511 | new (options: ArrayDataTypeOptions): ArrayDataType 512 | (type: T): ArrayDataType 513 | (options: ArrayDataTypeOptions): ArrayDataType 514 | is(obj: any, type: T): obj is ArrayDataType 515 | } 516 | 517 | export interface ArrayDataType extends AbstractDataType { 518 | options: ArrayDataTypeOptions 519 | } 520 | 521 | export interface ArrayDataTypeOptions { 522 | type: T 523 | } 524 | 525 | /** 526 | * A geometry datatype represents two dimensional spacial objects. 527 | */ 528 | export const GEOMETRY: GeometryDataTypeConstructor 529 | 530 | interface GeometryDataTypeConstructor extends AbstractDataTypeConstructor { 531 | new (type: string, srid?: number): GeometryDataType 532 | new (options: GeometryDataTypeOptions): GeometryDataType 533 | (type: string, srid?: number): GeometryDataType 534 | (options: GeometryDataTypeOptions): GeometryDataType 535 | } 536 | 537 | export interface GeometryDataType extends AbstractDataType { 538 | options: GeometryDataTypeOptions 539 | type: string 540 | srid?: number 541 | escape: boolean 542 | } 543 | 544 | export interface GeometryDataTypeOptions { 545 | type: string 546 | srid?: number 547 | } 548 | 549 | /** 550 | * A geography datatype represents two dimensional spacial objects in an elliptic coord system. 551 | */ 552 | export const GEOGRAPHY: GeographyDataTypeConstructor 553 | 554 | interface GeographyDataTypeConstructor extends AbstractDataTypeConstructor { 555 | new (type: string, srid?: number): GeographyDataType 556 | new (options: GeographyDataTypeOptions): GeographyDataType 557 | (type: string, srid?: number): GeographyDataType 558 | (options: GeographyDataTypeOptions): GeographyDataType 559 | } 560 | 561 | export interface GeographyDataType extends AbstractDataType { 562 | options: GeographyDataTypeOptions 563 | type: string 564 | srid?: number 565 | escape: boolean 566 | } 567 | 568 | export interface GeographyDataTypeOptions { 569 | type: string 570 | srid?: number 571 | } 572 | 573 | export const NONE: typeof VIRTUAL 574 | // export ['DOUBLE PRECISION']: typeof DOUBLE; 575 | -------------------------------------------------------------------------------- /lib/deferrable.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Can be used to 3 | * make foreign key constraints deferrable and to set the constaints within a 4 | * transaction. This is only supported in PostgreSQL. 5 | * 6 | * The foreign keys can be configured like this. It will create a foreign key 7 | * that will check the constraints immediately when the data was inserted. 8 | * 9 | * ```js 10 | * sequelize.define('Model', { 11 | * foreign_id: { 12 | * type: Sequelize.INTEGER, 13 | * references: { 14 | * model: OtherModel, 15 | * key: 'id', 16 | * deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE 17 | * } 18 | * } 19 | * }); 20 | * ``` 21 | * 22 | * The constraints can be configured in a transaction like this. It will 23 | * trigger a query once the transaction has been started and set the constraints 24 | * to be checked at the very end of the transaction. 25 | * 26 | * ```js 27 | * sequelize.transaction({ 28 | * deferrable: Sequelize.Deferrable.SET_DEFERRED 29 | * }); 30 | * ``` 31 | */ 32 | 33 | /** 34 | * 35 | */ 36 | export interface AbstractDeferrableStatic { 37 | new (): AbstractDeferrable 38 | (): AbstractDeferrable 39 | } 40 | export interface AbstractDeferrable { 41 | toString(): string 42 | toSql(): string 43 | } 44 | 45 | export interface InitiallyDeferredDeferrableStatic extends AbstractDeferrableStatic { 46 | new (): InitiallyDeferredDeferrable 47 | (): InitiallyDeferredDeferrable 48 | } 49 | export interface InitiallyDeferredDeferrable extends AbstractDeferrable {} 50 | export const INITIALLY_DEFERRED: InitiallyDeferredDeferrableStatic 51 | 52 | export interface InitiallyImmediateDeferrableStatic extends AbstractDeferrableStatic { 53 | new (): InitiallyImmediateDeferrable 54 | (): InitiallyImmediateDeferrable 55 | } 56 | export interface InitiallyImmediateDeferrable extends AbstractDeferrable {} 57 | export const INITIALLY_IMMEDIATE: InitiallyImmediateDeferrableStatic 58 | 59 | export interface NotDeferrableStatic extends AbstractDeferrableStatic { 60 | new (): NotDeferrable 61 | (): NotDeferrable 62 | } 63 | export interface NotDeferrable {} 64 | /** 65 | * Will set the constraints to not deferred. This is the default in PostgreSQL and it make 66 | * it impossible to dynamically defer the constraints within a transaction. 67 | */ 68 | export const NOT: NotDeferrableStatic 69 | 70 | export interface SetDeferredDeferrableStatic extends AbstractDeferrableStatic { 71 | /** 72 | * @param constraints An array of constraint names. Will defer all constraints by default. 73 | */ 74 | new (constraints: string[]): SetDeferredDeferrable 75 | /** 76 | * @param constraints An array of constraint names. Will defer all constraints by default. 77 | */ 78 | (constraints: string[]): SetDeferredDeferrable 79 | } 80 | export interface SetDeferredDeferrable {} 81 | /** 82 | * Will trigger an additional query at the beginning of a 83 | * transaction which sets the constraints to deferred. 84 | */ 85 | export const SET_DEFERRED: SetDeferredDeferrableStatic 86 | 87 | export interface SetImmediateDeferrableStatic extends AbstractDeferrableStatic { 88 | /** 89 | * @param constraints An array of constraint names. Will defer all constraints by default. 90 | */ 91 | new (constraints: string[]): SetImmediateDeferrable 92 | /** 93 | * @param constraints An array of constraint names. Will defer all constraints by default. 94 | */ 95 | (constraints: string[]): SetImmediateDeferrable 96 | } 97 | export interface SetImmediateDeferrable {} 98 | /** 99 | * Will trigger an additional query at the beginning of a 100 | * transaction which sets the constraints to immediately. 101 | * 102 | * @param constraints An array of constraint names. Will defer all constraints by default. 103 | */ 104 | export const SET_IMMEDIATE: SetImmediateDeferrableStatic 105 | -------------------------------------------------------------------------------- /lib/errors.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * The Base Error all Sequelize Errors inherit from. 3 | */ 4 | export class BaseError extends Error { 5 | public name: string 6 | } 7 | 8 | /** 9 | * Scope Error. Thrown when the sequelize cannot query the specified scope. 10 | */ 11 | export class SequelizeScopeError extends BaseError {} 12 | 13 | export class ValidationError extends BaseError { 14 | /** Array of ValidationErrorItem objects describing the validation errors */ 15 | public errors: ValidationErrorItem[] 16 | 17 | /** 18 | * Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` 19 | * property, which is an array with 1 or more ValidationErrorItems, one for each validation that failed. 20 | * 21 | * @param message Error message 22 | * @param errors Array of ValidationErrorItem objects describing the validation errors 23 | */ 24 | constructor(message: string, errors?: ValidationErrorItem[]) 25 | 26 | /** 27 | * Gets all validation error items for the path / field specified. 28 | * 29 | * @param path The path to be checked for error items 30 | */ 31 | public get(path: string): ValidationErrorItem[] 32 | } 33 | 34 | export class ValidationErrorItem { 35 | /** An error message */ 36 | public message: string 37 | 38 | /** The type of the validation error */ 39 | public type: string 40 | 41 | /** The field that triggered the validation error */ 42 | public path: string 43 | 44 | /** The value that generated the error */ 45 | public value: string 46 | 47 | /** 48 | * Validation Error Item 49 | * Instances of this class are included in the `ValidationError.errors` property. 50 | * 51 | * @param message An error message 52 | * @param type The type of the validation error 53 | * @param path The field that triggered the validation error 54 | * @param value The value that generated the error 55 | */ 56 | constructor(message?: string, type?: string, path?: string, value?: string) 57 | } 58 | 59 | export interface CommonErrorProperties { 60 | /** The database specific error which triggered this one */ 61 | readonly parent: Error 62 | 63 | /** The database specific error which triggered this one */ 64 | readonly original: Error 65 | 66 | /** The SQL that triggered the error */ 67 | readonly sql: string 68 | } 69 | 70 | export class DatabaseError extends BaseError implements CommonErrorProperties { 71 | public readonly parent: Error 72 | public readonly original: Error 73 | public readonly sql: string 74 | /** 75 | * A base class for all database related errors. 76 | * @param parent The database specific error which triggered this one 77 | */ 78 | constructor(parent: Error) 79 | } 80 | 81 | /** Thrown when a database query times out because of a deadlock */ 82 | export class TimeoutError extends DatabaseError {} 83 | 84 | export interface UniqueConstraintErrorOptions { 85 | parent?: Error 86 | message?: string 87 | errors?: ValidationErrorItem[] 88 | fields?: { [key: string]: any } 89 | original?: Error 90 | } 91 | 92 | /** 93 | * Thrown when a unique constraint is violated in the database 94 | */ 95 | export class UniqueConstraintError extends ValidationError implements CommonErrorProperties { 96 | public readonly parent: Error 97 | public readonly original: Error 98 | public readonly sql: string 99 | public readonly fields: { [key: string]: any } 100 | constructor(options?: UniqueConstraintErrorOptions) 101 | } 102 | 103 | /** 104 | * Thrown when a foreign key constraint is violated in the database 105 | */ 106 | export class ForeignKeyConstraintError extends DatabaseError { 107 | public table: string 108 | public fields: { [field: string]: string } 109 | public value: any 110 | public index: string 111 | constructor(options: { parent?: Error; message?: string; index?: string; fields?: string[]; table?: string }) 112 | } 113 | 114 | /** 115 | * Thrown when an exclusion constraint is violated in the database 116 | */ 117 | export class ExclusionConstraintError extends DatabaseError { 118 | public constraint: string 119 | public fields: { [field: string]: string } 120 | public table: string 121 | constructor(options: { parent?: Error; message?: string; constraint?: string; fields?: string[]; table?: string }) 122 | } 123 | 124 | /** 125 | * A base class for all connection related errors. 126 | */ 127 | export class ConnectionError extends BaseError { 128 | public parent: Error 129 | public original: Error 130 | constructor(parent: Error) 131 | } 132 | 133 | /** 134 | * Thrown when a connection to a database is refused 135 | */ 136 | export class ConnectionRefusedError extends ConnectionError {} 137 | 138 | /** 139 | * Thrown when a connection to a database is refused due to insufficient privileges 140 | */ 141 | export class AccessDeniedError extends ConnectionError {} 142 | 143 | /** 144 | * Thrown when a connection to a database has a hostname that was not found 145 | */ 146 | export class HostNotFoundError extends ConnectionError {} 147 | 148 | /** 149 | * Thrown when a connection to a database has a hostname that was not reachable 150 | */ 151 | export class HostNotReachableError extends ConnectionError {} 152 | 153 | /** 154 | * Thrown when a connection to a database has invalid values for any of the connection parameters 155 | */ 156 | export class InvalidConnectionError extends ConnectionError {} 157 | 158 | /** 159 | * Thrown when a connection to a database times out 160 | */ 161 | export class ConnectionTimedOutError extends ConnectionError {} 162 | -------------------------------------------------------------------------------- /lib/model-manager.d.ts: -------------------------------------------------------------------------------- 1 | import { Model } from './model' 2 | import { Sequelize } from './sequelize' 3 | 4 | export class ModelManager { 5 | public sequelize: Sequelize 6 | public models: typeof Model[] 7 | public all: typeof Model[] 8 | 9 | constructor(sequelize: Sequelize) 10 | public addModel(model: T): T 11 | public removeModel(model: typeof Model): void 12 | public getModel(against: any, options?: { attribute?: string }): typeof Model 13 | 14 | /** 15 | * Iterate over Models in an order suitable for e.g. creating tables. Will 16 | * take foreign key constraints into account so that dependencies are visited 17 | * before dependents. 18 | */ 19 | public forEachModel(iterator: (model: typeof Model, name: string) => any, options?: { reverse?: boolean }): void 20 | } 21 | 22 | export default ModelManager 23 | -------------------------------------------------------------------------------- /lib/promise.d.ts: -------------------------------------------------------------------------------- 1 | import * as Bluebird from 'bluebird' 2 | 3 | export const Promise: typeof Bluebird 4 | export type Promise = Bluebird 5 | export default Promise 6 | -------------------------------------------------------------------------------- /lib/query-interface.d.ts: -------------------------------------------------------------------------------- 1 | import { DataType } from './data-types' 2 | import { Logging, Model, ModelAttributeColumnOptions, ModelAttributes, Transactionable, WhereOptions } from './model' 3 | import { Promise } from './promise' 4 | import QueryTypes = require('./query-types') 5 | import { Sequelize } from './sequelize' 6 | import { Transaction } from './transaction' 7 | 8 | /** 9 | * Interface for query options 10 | */ 11 | export interface QueryOptions extends Logging, Transactionable { 12 | /** 13 | * If true, sequelize will not try to format the results of the query, or build an instance of a model from 14 | * the result 15 | */ 16 | raw?: boolean 17 | 18 | /** 19 | * The type of query you are executing. The query type affects how results are formatted before they are 20 | * passed back. The type is a string, but `Sequelize.QueryTypes` is provided as convenience shortcuts. 21 | */ 22 | type?: string 23 | 24 | /** 25 | * If true, transforms objects with `.` separated property names into nested objects using 26 | * [dottie.js](https://github.com/mickhansen/dottie.js). For example { 'user.username': 'john' } becomes 27 | * { user: { username: 'john' }}. When `nest` is true, the query type is assumed to be `'SELECT'`, 28 | * unless otherwise specified 29 | * 30 | * Defaults to false 31 | */ 32 | nest?: boolean 33 | 34 | /** 35 | * Sets the query type to `SELECT` and return a single row 36 | */ 37 | plain?: boolean 38 | 39 | /** 40 | * Either an object of named parameter replacements in the format `:param` or an array of unnamed 41 | * replacements to replace `?` in your SQL. 42 | */ 43 | replacements?: object | string[] 44 | 45 | /** 46 | * Force the query to use the write pool, regardless of the query type. 47 | * 48 | * Defaults to false 49 | */ 50 | useMaster?: boolean 51 | 52 | /** 53 | * A sequelize instance used to build the return instance 54 | */ 55 | instance?: Model 56 | } 57 | 58 | export interface QueryOptionsWithModel { 59 | /** 60 | * A sequelize model used to build the returned model instances (used to be called callee) 61 | */ 62 | model: typeof Model 63 | } 64 | 65 | export interface QueryOptionsWithType { 66 | /** 67 | * The type of query you are executing. The query type affects how results are formatted before they are 68 | * passed back. The type is a string, but `Sequelize.QueryTypes` is provided as convenience shortcuts. 69 | */ 70 | type: QueryTypes 71 | } 72 | 73 | /** 74 | * Most of the methods accept options and use only the logger property of the options. That's why the most used 75 | * interface type for options in a method is separated here as another interface. 76 | */ 77 | export interface QueryInterfaceOptions extends Logging, Transactionable {} 78 | 79 | export interface QueryInterfaceCreateTableOptions extends QueryInterfaceOptions { 80 | collate?: string 81 | engine?: string 82 | charset?: string 83 | /** 84 | * Used for compound unique keys. 85 | */ 86 | uniqueKeys?: { 87 | [keyName: string]: { 88 | fields: string[] 89 | } 90 | } 91 | } 92 | 93 | export interface QueryInterfaceDropTableOptions extends QueryInterfaceOptions { 94 | cascade?: boolean 95 | force?: boolean 96 | } 97 | 98 | export interface QueryInterfaceDropAllTablesOptions extends QueryInterfaceOptions { 99 | skip?: string[] 100 | } 101 | 102 | export interface QueryInterfaceIndexOptions extends QueryInterfaceOptions { 103 | indicesType?: 'UNIQUE' | 'FULLTEXT' | 'SPATIAL' 104 | 105 | /** The name of the index. Default is __ */ 106 | indexName?: string 107 | 108 | /** For FULLTEXT columns set your parser */ 109 | parser?: string 110 | 111 | /** Set a type for the index, e.g. BTREE. See the documentation of the used dialect */ 112 | indexType?: string 113 | } 114 | 115 | export interface AddUniqueConstraintOptions { 116 | type: 'unique' 117 | name?: string 118 | } 119 | 120 | export interface AddDefaultConstraintOptions { 121 | type: 'default' 122 | name?: string 123 | defaultValue?: any 124 | } 125 | 126 | export interface AddCheckConstraintOptions { 127 | type: 'check' 128 | name?: string 129 | where?: WhereOptions 130 | } 131 | 132 | export interface AddPrimaryKeyConstraintOptions { 133 | type: 'primary key' 134 | name?: string 135 | } 136 | 137 | export interface AddForeignKeyConstraintOptions { 138 | type: 'foreign key' 139 | name?: string 140 | references?: { 141 | table: string 142 | field: string 143 | } 144 | onDelete: string 145 | onUpdate: string 146 | } 147 | 148 | export type AddConstraintOptions = 149 | | AddUniqueConstraintOptions 150 | | AddDefaultConstraintOptions 151 | | AddCheckConstraintOptions 152 | | AddPrimaryKeyConstraintOptions 153 | | AddForeignKeyConstraintOptions 154 | 155 | /** 156 | * The interface that Sequelize uses to talk to all databases. 157 | * 158 | * This interface is available through sequelize.QueryInterface. It should not be commonly used, but it's 159 | * referenced anyway, so it can be used. 160 | */ 161 | export class QueryInterface { 162 | /** 163 | * Returns the dialect-specific sql generator. 164 | * 165 | * We don't have a definition for the QueryGenerator, because I doubt it is commonly in use separately. 166 | */ 167 | public QueryGenerator: any 168 | 169 | /** 170 | * Returns the current sequelize instance. 171 | */ 172 | public sequelize: Sequelize 173 | 174 | constructor(sequelize: Sequelize) 175 | 176 | /** 177 | * Queries the schema (table list). 178 | * 179 | * @param schema The schema to query. Applies only to Postgres. 180 | */ 181 | public createSchema(schema?: string, options?: QueryInterfaceOptions): Promise 182 | 183 | /** 184 | * Drops the specified schema (table). 185 | * 186 | * @param schema The schema to query. Applies only to Postgres. 187 | */ 188 | public dropSchema(schema?: string, options?: QueryInterfaceOptions): Promise 189 | 190 | /** 191 | * Drops all tables. 192 | */ 193 | public dropAllSchemas(options?: QueryInterfaceDropAllTablesOptions): Promise 194 | 195 | /** 196 | * Queries all table names in the database. 197 | * 198 | * @param options 199 | */ 200 | public showAllSchemas(options?: QueryOptions): Promise 201 | 202 | /** 203 | * Return database version 204 | */ 205 | public databaseVersion(options?: QueryInterfaceOptions): Promise 206 | 207 | /** 208 | * Creates a table with specified attributes. 209 | * 210 | * @param tableName Name of table to create 211 | * @param attributes Hash of attributes, key is attribute name, value is data type 212 | * @param options Table options. 213 | */ 214 | public createTable( 215 | tableName: string | { schema?: string; tableName?: string }, 216 | attributes: ModelAttributes, 217 | options?: QueryInterfaceCreateTableOptions 218 | ): Promise 219 | 220 | /** 221 | * Drops the specified table. 222 | * 223 | * @param tableName Table name. 224 | * @param options Query options, particularly "force". 225 | */ 226 | public dropTable(tableName: string, options?: QueryInterfaceDropTableOptions): Promise 227 | 228 | /** 229 | * Drops all tables. 230 | * 231 | * @param options 232 | */ 233 | public dropAllTables(options?: QueryInterfaceDropTableOptions): Promise 234 | 235 | /** 236 | * Drops all defined enums 237 | * 238 | * @param options 239 | */ 240 | public dropAllEnums(options?: QueryOptions): Promise 241 | 242 | /** 243 | * Renames a table 244 | */ 245 | public renameTable(before: string, after: string, options?: QueryInterfaceOptions): Promise 246 | 247 | /** 248 | * Returns all tables 249 | */ 250 | public showAllTables(options?: QueryOptions): Promise 251 | 252 | /** 253 | * Describe a table 254 | */ 255 | public describeTable( 256 | tableName: string | { schema?: string; tableName?: string }, 257 | options?: string | { schema?: string; schemaDelimeter?: string } & Logging 258 | ): Promise 259 | 260 | /** 261 | * Adds a new column to a table 262 | */ 263 | public addColumn( 264 | table: string | { schema?: string; tableName?: string }, 265 | key: string, 266 | attribute: ModelAttributeColumnOptions | DataType, 267 | options?: QueryInterfaceOptions 268 | ): Promise 269 | 270 | /** 271 | * Removes a column from a table 272 | */ 273 | public removeColumn( 274 | table: string | { schema?: string; tableName?: string }, 275 | attribute: string, 276 | options?: QueryInterfaceOptions 277 | ): Promise 278 | 279 | /** 280 | * Changes a column 281 | */ 282 | public changeColumn( 283 | tableName: string | { schema?: string; tableName?: string }, 284 | attributeName: string, 285 | dataTypeOrOptions?: DataType | ModelAttributeColumnOptions, 286 | options?: QueryInterfaceOptions 287 | ): Promise 288 | 289 | /** 290 | * Renames a column 291 | */ 292 | public renameColumn( 293 | tableName: string | { schema?: string; tableName?: string }, 294 | attrNameBefore: string, 295 | attrNameAfter: string, 296 | options?: QueryInterfaceOptions 297 | ): Promise 298 | 299 | /** 300 | * Adds a new index to a table 301 | */ 302 | public addIndex( 303 | tableName: string, 304 | attributes: string[], 305 | options?: QueryInterfaceIndexOptions, 306 | rawTablename?: string 307 | ): Promise 308 | public addIndex( 309 | tableName: string, 310 | options: QueryInterfaceIndexOptions & { fields: string[] }, 311 | rawTablename?: string 312 | ): Promise 313 | 314 | /** 315 | * Removes an index of a table 316 | */ 317 | public removeIndex(tableName: string, indexName: string, options?: QueryInterfaceIndexOptions): Promise 318 | public removeIndex(tableName: string, attributes: string[], options?: QueryInterfaceIndexOptions): Promise 319 | 320 | /** 321 | * Adds constraints to a table 322 | */ 323 | public addConstraint( 324 | tableName: string, 325 | attributes: string[], 326 | options?: AddConstraintOptions | QueryInterfaceOptions 327 | ): Promise 328 | 329 | /** 330 | * Removes constraints from a table 331 | */ 332 | public removeConstraint(tableName: string, constraintName: string, options?: QueryInterfaceOptions): Promise 333 | 334 | /** 335 | * Shows the index of a table 336 | */ 337 | public showIndex(tableName: string | object, options?: QueryOptions): Promise 338 | 339 | /** 340 | * Put a name to an index 341 | */ 342 | public nameIndexes(indexes: string[], rawTablename: string): Promise 343 | 344 | /** 345 | * Returns all foreign key constraints of a table 346 | */ 347 | public getForeignKeysForTables(tableNames: string, options?: QueryInterfaceOptions): Promise 348 | 349 | /** 350 | * Inserts a new record 351 | */ 352 | public insert(instance: Model, tableName: string, values: object, options?: QueryOptions): Promise 353 | 354 | /** 355 | * Inserts or Updates a record in the database 356 | */ 357 | public upsert( 358 | tableName: string, 359 | values: object, 360 | updateValues: object, 361 | model: typeof Model, 362 | options?: QueryOptions 363 | ): Promise 364 | 365 | /** 366 | * Inserts multiple records at once 367 | */ 368 | public bulkInsert( 369 | tableName: string, 370 | records: object[], 371 | options?: QueryOptions, 372 | attributes?: string[] | string 373 | ): Promise 374 | 375 | /** 376 | * Updates a row 377 | */ 378 | public update( 379 | instance: Model, 380 | tableName: string, 381 | values: object, 382 | identifier: object, 383 | options?: QueryOptions 384 | ): Promise 385 | 386 | /** 387 | * Updates multiple rows at once 388 | */ 389 | public bulkUpdate( 390 | tableName: string, 391 | values: object, 392 | identifier: object, 393 | options?: QueryOptions, 394 | attributes?: string[] | string 395 | ): Promise 396 | 397 | /** 398 | * Deletes a row 399 | */ 400 | public delete(instance: Model, tableName: string, identifier: object, options?: QueryOptions): Promise 401 | 402 | /** 403 | * Deletes multiple rows at once 404 | */ 405 | public bulkDelete( 406 | tableName: string, 407 | identifier: object, 408 | options?: QueryOptions, 409 | model?: typeof Model 410 | ): Promise 411 | 412 | /** 413 | * Returns selected rows 414 | */ 415 | public select(model: typeof Model, tableName: string, options?: QueryOptions): Promise 416 | 417 | /** 418 | * Increments a row value 419 | */ 420 | public increment( 421 | instance: Model, 422 | tableName: string, 423 | values: object, 424 | identifier: object, 425 | options?: QueryOptions 426 | ): Promise 427 | 428 | /** 429 | * Selects raw without parsing the string into an object 430 | */ 431 | public rawSelect( 432 | tableName: string, 433 | options: QueryOptions, 434 | attributeSelector: string | string[], 435 | model?: typeof Model 436 | ): Promise 437 | 438 | /** 439 | * Postgres only. Creates a trigger on specified table to call the specified function with supplied 440 | * parameters. 441 | */ 442 | public createTrigger( 443 | tableName: string, 444 | triggerName: string, 445 | timingType: string, 446 | fireOnArray: any[], 447 | functionName: string, 448 | functionParams: any[], 449 | optionsArray: string[], 450 | options?: QueryInterfaceOptions 451 | ): Promise 452 | 453 | /** 454 | * Postgres only. Drops the specified trigger. 455 | */ 456 | public dropTrigger(tableName: string, triggerName: string, options?: QueryInterfaceOptions): Promise 457 | 458 | /** 459 | * Postgres only. Renames a trigger 460 | */ 461 | public renameTrigger( 462 | tableName: string, 463 | oldTriggerName: string, 464 | newTriggerName: string, 465 | options?: QueryInterfaceOptions 466 | ): Promise 467 | 468 | /** 469 | * Postgres only. Create a function 470 | */ 471 | public createFunction( 472 | functionName: string, 473 | params: any[], 474 | returnType: string, 475 | language: string, 476 | body: string, 477 | options?: QueryOptions 478 | ): Promise 479 | 480 | /** 481 | * Postgres only. Drops a function 482 | */ 483 | public dropFunction(functionName: string, params: any[], options?: QueryInterfaceOptions): Promise 484 | 485 | /** 486 | * Postgres only. Rename a function 487 | */ 488 | public renameFunction( 489 | oldFunctionName: string, 490 | params: any[], 491 | newFunctionName: string, 492 | options?: QueryInterfaceOptions 493 | ): Promise 494 | 495 | /** 496 | * Escape an identifier (e.g. a table or attribute name). If force is true, the identifier will be quoted 497 | * even if the `quoteIdentifiers` option is false. 498 | */ 499 | public quoteIdentifier(identifier: string, force: boolean): string 500 | 501 | /** 502 | * Escape a table name 503 | */ 504 | public quoteTable(identifier: string): string 505 | 506 | /** 507 | * Split an identifier into .-separated tokens and quote each part. If force is true, the identifier will be 508 | * quoted even if the `quoteIdentifiers` option is false. 509 | */ 510 | public quoteIdentifiers(identifiers: string, force: boolean): string 511 | 512 | /** 513 | * Escape a value (e.g. a string, number or date) 514 | */ 515 | public escape(value?: string | number | Date): string 516 | 517 | /** 518 | * Set option for autocommit of a transaction 519 | */ 520 | public setAutocommit(transaction: Transaction, value: boolean, options?: QueryOptions): Promise 521 | 522 | /** 523 | * Set the isolation level of a transaction 524 | */ 525 | public setIsolationLevel(transaction: Transaction, value: string, options?: QueryOptions): Promise 526 | 527 | /** 528 | * Begin a new transaction 529 | */ 530 | public startTransaction(transaction: Transaction, options?: QueryOptions): Promise 531 | 532 | /** 533 | * Defer constraints 534 | */ 535 | public deferConstraints(transaction: Transaction, options?: QueryOptions): Promise 536 | 537 | /** 538 | * Commit an already started transaction 539 | */ 540 | public commitTransaction(transaction: Transaction, options?: QueryOptions): Promise 541 | 542 | /** 543 | * Rollback ( revert ) a transaction that has'nt been commited 544 | */ 545 | public rollbackTransaction(transaction: Transaction, options?: QueryOptions): Promise 546 | } 547 | -------------------------------------------------------------------------------- /lib/query-types.d.ts: -------------------------------------------------------------------------------- 1 | declare enum QueryTypes { 2 | SELECT = 'SELECT', 3 | INSERT = 'INSERT', 4 | UPDATE = 'UPDATE', 5 | BULKUPDATE = 'BULKUPDATE', 6 | BULKDELETE = 'BULKDELETE', 7 | DELETE = 'DELETE', 8 | UPSERT = 'UPSERT', 9 | VERSION = 'VERSION', 10 | SHOWTABLES = 'SHOWTABLES', 11 | SHOWINDEXES = 'SHOWINDEXES', 12 | DESCRIBE = 'DESCRIBE', 13 | RAW = 'RAW', 14 | FOREIGNKEYS = 'FOREIGNKEYS', 15 | } 16 | 17 | export = QueryTypes 18 | -------------------------------------------------------------------------------- /lib/sequelize.d.ts: -------------------------------------------------------------------------------- 1 | import * as DataTypes from './data-types' 2 | import { 3 | AndOperator, 4 | BulkCreateOptions, 5 | CreateOptions, 6 | DestroyOptions, 7 | DropOptions, 8 | FindOptions, 9 | InstanceDestroyOptions, 10 | Logging, 11 | Model, 12 | ModelAttributes, 13 | ModelOptions, 14 | OrOperator, 15 | UpdateOptions, 16 | WhereAttributeHash, 17 | WhereOperators, 18 | } from './model' 19 | import { ModelManager } from './model-manager' 20 | import { Promise } from './promise' 21 | import { QueryInterface, QueryOptions, QueryOptionsWithModel, QueryOptionsWithType } from './query-interface' 22 | import { Transaction, TransactionOptions } from './transaction' 23 | import { Cast, Col, Fn, Json, Literal, Where } from './utils' 24 | 25 | /** 26 | * Sync Options 27 | */ 28 | export interface SyncOptions extends Logging { 29 | /** 30 | * If force is true, each DAO will do DROP TABLE IF EXISTS ..., before it tries to create its own table 31 | */ 32 | force?: boolean 33 | 34 | /** 35 | * Match a regex against the database name before syncing, a safety check for cases where force: true is 36 | * used in tests but not live code 37 | */ 38 | match?: RegExp 39 | 40 | /** 41 | * The schema that the tables should be created in. This can be overriden for each table in sequelize.define 42 | */ 43 | schema?: string 44 | } 45 | 46 | export interface SetOptions {} 47 | 48 | /** 49 | * Connection Pool options 50 | */ 51 | export interface PoolOptions { 52 | /** 53 | * Maximum number of connections in pool. Default is 5 54 | */ 55 | max?: number 56 | 57 | /** 58 | * Minimum number of connections in pool. Default is 0 59 | */ 60 | min?: number 61 | 62 | /** 63 | * The maximum time, in milliseconds, that a connection can be idle before being released 64 | */ 65 | idle?: number 66 | 67 | /** 68 | * The maximum time, in milliseconds, that pool will try to get connection before throwing error 69 | */ 70 | acquire?: number 71 | 72 | /** 73 | * A function that validates a connection. Called with client. The default function checks that client is an 74 | * object, and that its state is not disconnected 75 | */ 76 | validate?: (client?: any) => boolean 77 | } 78 | 79 | /** 80 | * Interface for replication Options in the sequelize constructor 81 | */ 82 | export interface ReplicationOptions { 83 | read?: { 84 | host?: string 85 | port?: string | number 86 | username?: string 87 | password?: string 88 | database?: string 89 | } 90 | 91 | write?: { 92 | host?: string 93 | port?: string | number 94 | username?: string 95 | password?: string 96 | database?: string 97 | } 98 | } 99 | 100 | /** 101 | * object that holds all operator symbols 102 | */ 103 | export declare var Op: { 104 | eq: symbol 105 | ne: symbol 106 | gte: symbol 107 | gt: symbol 108 | lte: symbol 109 | lt: symbol 110 | not: symbol 111 | in: symbol 112 | notIn: symbol 113 | is: symbol 114 | like: symbol 115 | notLike: symbol 116 | iLike: symbol 117 | notILike: symbol 118 | regexp: symbol 119 | notRegexp: symbol 120 | iRegexp: symbol 121 | notIRegexp: symbol 122 | between: symbol 123 | notBetween: symbol 124 | overlap: symbol 125 | contains: symbol 126 | contained: symbol 127 | adjacent: symbol 128 | strictLeft: symbol 129 | strictRight: symbol 130 | noExtendRight: symbol 131 | noExtendLeft: symbol 132 | and: symbol 133 | or: symbol 134 | any: symbol 135 | all: symbol 136 | values: symbol 137 | co: symbol 138 | } 139 | 140 | /** 141 | * Used to map operators to their Symbol representations 142 | */ 143 | export interface OperatorsAliases { 144 | [K: string]: symbol 145 | } 146 | 147 | /** 148 | * Options for the constructor of Sequelize main class 149 | */ 150 | export interface Options extends Logging { 151 | /** 152 | * The dialect of the database you are connecting to. One of mysql, postgres, sqlite, mariadb and mssql. 153 | * 154 | * Defaults to 'mysql' 155 | */ 156 | dialect?: 'mysql' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql' 157 | 158 | /** 159 | * If specified, load the dialect library from this path. For example, if you want to use pg.js instead of 160 | * pg when connecting to a pg database, you should specify 'pg.js' here 161 | */ 162 | dialectModulePath?: string 163 | 164 | /** 165 | * An object of additional options, which are passed directly to the connection library 166 | */ 167 | dialectOptions?: object 168 | 169 | /** 170 | * Only used by sqlite. 171 | * 172 | * Defaults to ':memory:' 173 | */ 174 | storage?: string 175 | 176 | /** 177 | * The name of the database 178 | */ 179 | database?: string 180 | 181 | /** 182 | * The username which is used to authenticate against the database. 183 | */ 184 | username?: string 185 | 186 | /** 187 | * The password which is used to authenticate against the database. 188 | */ 189 | password?: string 190 | 191 | /** 192 | * The host of the relational database. 193 | * 194 | * Defaults to 'localhost' 195 | */ 196 | host?: string 197 | 198 | /** 199 | * The port of the relational database. 200 | */ 201 | port?: number 202 | 203 | /** 204 | * A flag that defines if is used SSL. 205 | */ 206 | ssl?: boolean 207 | 208 | /** 209 | * The protocol of the relational database. 210 | * 211 | * Defaults to 'tcp' 212 | */ 213 | protocol?: string 214 | 215 | /** 216 | * Default options for model definitions. See sequelize.define for options 217 | */ 218 | define?: ModelOptions 219 | 220 | /** 221 | * Default options for sequelize.query 222 | */ 223 | query?: QueryOptions 224 | 225 | /** 226 | * Default options for sequelize.set 227 | */ 228 | set?: SetOptions 229 | 230 | /** 231 | * Default options for sequelize.sync 232 | */ 233 | sync?: SyncOptions 234 | 235 | /** 236 | * The timezone used when converting a date from the database into a JavaScript date. The timezone is also 237 | * used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP 238 | * and other time related functions have in the right timezone. For best cross platform performance use the 239 | * format 240 | * +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles'); 241 | * this is useful to capture daylight savings time changes. 242 | * 243 | * Defaults to '+00:00' 244 | */ 245 | timezone?: string 246 | 247 | /** 248 | * A flag that defines if null values should be passed to SQL queries or not. 249 | * 250 | * Defaults to false 251 | */ 252 | omitNull?: boolean 253 | 254 | /** 255 | * A flag that defines if native library shall be used or not. Currently only has an effect for postgres 256 | * 257 | * Defaults to false 258 | */ 259 | native?: boolean 260 | 261 | /** 262 | * Use read / write replication. To enable replication, pass an object, with two properties, read and write. 263 | * Write should be an object (a single server for handling writes), and read an array of object (several 264 | * servers to handle reads). Each read/write server can have the following properties: `host`, `port`, 265 | * `username`, `password`, `database` 266 | * 267 | * Defaults to false 268 | */ 269 | replication?: ReplicationOptions 270 | 271 | /** 272 | * Connection pool options 273 | */ 274 | pool?: PoolOptions 275 | 276 | /** 277 | * Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of 278 | * them. 279 | * 280 | * Defaults to true 281 | */ 282 | quoteIdentifiers?: boolean 283 | 284 | /** 285 | * Set the default transaction isolation level. See `Sequelize.Transaction.ISOLATION_LEVELS` for possible 286 | * options. 287 | * 288 | * Defaults to 'REPEATABLE_READ' 289 | */ 290 | isolationLevel?: string 291 | 292 | /** 293 | * Run built in type validators on insert and update, e.g. validate that arguments passed to integer 294 | * fields are integer-like. 295 | * 296 | * Defaults to false 297 | */ 298 | typeValidation?: boolean 299 | 300 | /** 301 | * Sets available operator aliases. See (http://docs.sequelizejs.com/manual/tutorial/querying.html#operators) 302 | * for more information. Set to false to disable operator aliases completely (recommended) 303 | * 304 | * Defaults to all aliases 305 | */ 306 | operatorsAliases: OperatorsAliases | false 307 | } 308 | 309 | export interface QueryOptionsTransactionRequired {} 310 | 311 | /** 312 | * This is the main class, the entry point to sequelize. To use it, you just need to 313 | * import sequelize: 314 | * 315 | * ```js 316 | * var Sequelize = require('sequelize'); 317 | * ``` 318 | * 319 | * In addition to sequelize, the connection library for the dialect you want to use 320 | * should also be installed in your project. You don't need to import it however, as 321 | * sequelize will take care of that. 322 | */ 323 | export class Sequelize { 324 | /** 325 | * A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc. 326 | */ 327 | public Sequelize: typeof Sequelize 328 | 329 | public modelManager: ModelManager 330 | 331 | // -------------------- Utilities ------------------------------------------------------------------------ 332 | 333 | /** 334 | * Creates a object representing a database function. This can be used in search queries, both in where and 335 | * order parts, and as default values in column definitions. If you want to refer to columns in your 336 | * function, you should use `sequelize.col`, so that the columns are properly interpreted as columns and 337 | * not a strings. 338 | * 339 | * Convert a user's username to upper case 340 | * ```js 341 | * instance.updateAttributes({ 342 | * username: self.sequelize.fn('upper', self.sequelize.col('username')) 343 | * }) 344 | * ``` 345 | * @param fn The function you want to call 346 | * @param args All further arguments will be passed as arguments to the function 347 | */ 348 | public static fn: typeof fn 349 | 350 | /** 351 | * Creates a object representing a column in the DB. This is often useful in conjunction with 352 | * `sequelize.fn`, since raw string arguments to fn will be escaped. 353 | * 354 | * @param col The name of the column 355 | */ 356 | public static col: typeof col 357 | 358 | /** 359 | * Creates a object representing a call to the cast function. 360 | * 361 | * @param val The value to cast 362 | * @param type The type to cast it to 363 | */ 364 | public static cast: typeof cast 365 | 366 | /** 367 | * Creates a object representing a literal, i.e. something that will not be escaped. 368 | * 369 | * @param val 370 | */ 371 | public static literal: typeof literal 372 | public static asIs: typeof asIs 373 | 374 | /** 375 | * An AND query 376 | * 377 | * @param args Each argument will be joined by AND 378 | */ 379 | public static and: typeof and 380 | 381 | /** 382 | * An OR query 383 | * 384 | * @param args Each argument will be joined by OR 385 | */ 386 | public static or: typeof or 387 | 388 | /** 389 | * Creates an object representing nested where conditions for postgres's json data-type. 390 | * 391 | * @param conditionsOrPath A hash containing strings/numbers or other nested hash, a string using dot 392 | * notation or a string using postgres json syntax. 393 | * @param value An optional value to compare against. Produces a string of the form " = 394 | * ''". 395 | */ 396 | public static json: typeof json 397 | 398 | /** 399 | * A way of specifying attr = condition. 400 | * 401 | * The attr can either be an object taken from `Model.rawAttributes` (for example `Model.rawAttributes.id` 402 | * or 403 | * `Model.rawAttributes.name`). The attribute should be defined in your model definition. The attribute can 404 | * also be an object from one of the sequelize utility functions (`sequelize.fn`, `sequelize.col` etc.) 405 | * 406 | * For string attributes, use the regular `{ where: { attr: something }}` syntax. If you don't want your 407 | * string to be escaped, use `sequelize.literal`. 408 | * 409 | * @param attr The attribute, which can be either an attribute object from `Model.rawAttributes` or a 410 | * sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the 411 | * POJO syntax 412 | * @param comparator Comparator 413 | * @param logic The condition. Can be both a simply type, or a further condition (`.or`, `.and`, `.literal` 414 | * etc.) 415 | */ 416 | public static where: typeof where 417 | public static condition: typeof condition 418 | 419 | // -------------------- Static Hooks --------------------------------------------------------------------- 420 | 421 | /** 422 | * Add a hook to the model 423 | * 424 | * @param hookType 425 | * @param name Provide a name for the hook function. It can be used to remove the hook later or to order 426 | * hooks based on some sort of priority system in the future. 427 | * @param fn The hook function 428 | * 429 | * @alias hook 430 | */ 431 | public static addHook(hookType: string, name: string, fn: Function): typeof Sequelize 432 | public static addHook(hookType: string, fn: Function): typeof Sequelize 433 | public static hook(hookType: string, name: string, fn: Function): typeof Sequelize 434 | public static hook(hookType: string, fn: Function): typeof Sequelize 435 | 436 | /** 437 | * Remove hook from the model 438 | * 439 | * @param hookType 440 | * @param name 441 | */ 442 | public static removeHook(hookType: string, name: string): typeof Sequelize 443 | 444 | /** 445 | * Check whether the mode has any hooks of this type 446 | * 447 | * @param hookType 448 | * 449 | * @alias hasHooks 450 | */ 451 | public static hasHook(hookType: string): boolean 452 | public static hasHooks(hookType: string): boolean 453 | 454 | /** 455 | * A hook that is run before validation 456 | * 457 | * @param name 458 | * @param fn A callback function that is called with instance, options 459 | */ 460 | public static beforeValidate(name: string, fn: (instance: Model, options: object) => void): void 461 | public static beforeValidate(fn: (instance: Model, options: object) => void): void 462 | 463 | /** 464 | * A hook that is run after validation 465 | * 466 | * @param name 467 | * @param fn A callback function that is called with instance, options 468 | */ 469 | public static afterValidate(name: string, fn: (instance: Model, options: object) => void): void 470 | public static afterValidate(fn: (instance: Model, options: object) => void): void 471 | 472 | /** 473 | * A hook that is run before creating a single instance 474 | * 475 | * @param name 476 | * @param fn A callback function that is called with attributes, options 477 | */ 478 | public static beforeCreate(name: string, fn: (attributes: Model, options: CreateOptions) => void): void 479 | public static beforeCreate(fn: (attributes: Model, options: CreateOptions) => void): void 480 | 481 | /** 482 | * A hook that is run after creating a single instance 483 | * 484 | * @param name 485 | * @param fn A callback function that is called with attributes, options 486 | */ 487 | public static afterCreate(name: string, fn: (attributes: Model, options: CreateOptions) => void): void 488 | public static afterCreate(fn: (attributes: Model, options: CreateOptions) => void): void 489 | 490 | /** 491 | * A hook that is run before destroying a single instance 492 | * 493 | * @param name 494 | * @param fn A callback function that is called with instance, options 495 | * @alias beforeDelete 496 | */ 497 | public static beforeDestroy(name: string, fn: (instance: Model, options: InstanceDestroyOptions) => void): void 498 | public static beforeDestroy(fn: (instance: Model, options: InstanceDestroyOptions) => void): void 499 | public static beforeDelete(name: string, fn: (instance: Model, options: InstanceDestroyOptions) => void): void 500 | public static beforeDelete(fn: (instance: Model, options: InstanceDestroyOptions) => void): void 501 | 502 | /** 503 | * A hook that is run after destroying a single instance 504 | * 505 | * @param name 506 | * @param fn A callback function that is called with instance, options 507 | * @alias afterDelete 508 | */ 509 | public static afterDestroy(name: string, fn: (instance: Model, options: InstanceDestroyOptions) => void): void 510 | public static afterDestroy(fn: (instance: Model, options: InstanceDestroyOptions) => void): void 511 | public static afterDelete(name: string, fn: (instance: Model, options: InstanceDestroyOptions) => void): void 512 | public static afterDelete(fn: (instance: Model, options: InstanceDestroyOptions) => void): void 513 | 514 | /** 515 | * A hook that is run before updating a single instance 516 | * 517 | * @param name 518 | * @param fn A callback function that is called with instance, options 519 | */ 520 | public static beforeUpdate(name: string, fn: (instance: Model, options: UpdateOptions) => void): void 521 | public static beforeUpdate(fn: (instance: Model, options: UpdateOptions) => void): void 522 | 523 | /** 524 | * A hook that is run after updating a single instance 525 | * 526 | * @param name 527 | * @param fn A callback function that is called with instance, options 528 | */ 529 | public static afterUpdate(name: string, fn: (instance: Model, options: UpdateOptions) => void): void 530 | public static afterUpdate(fn: (instance: Model, options: UpdateOptions) => void): void 531 | 532 | /** 533 | * A hook that is run before creating instances in bulk 534 | * 535 | * @param name 536 | * @param fn A callback function that is called with instances, options 537 | */ 538 | public static beforeBulkCreate(name: string, fn: (instances: Model[], options: BulkCreateOptions) => void): void 539 | public static beforeBulkCreate(fn: (instances: Model[], options: BulkCreateOptions) => void): void 540 | 541 | /** 542 | * A hook that is run after creating instances in bulk 543 | * 544 | * @param name 545 | * @param fn A callback function that is called with instances, options 546 | * @name afterBulkCreate 547 | */ 548 | public static afterBulkCreate(name: string, fn: (instances: Model[], options: BulkCreateOptions) => void): void 549 | public static afterBulkCreate(fn: (instances: Model[], options: BulkCreateOptions) => void): void 550 | 551 | /** 552 | * A hook that is run before destroying instances in bulk 553 | * 554 | * @param name 555 | * @param fn A callback function that is called with options 556 | * 557 | * @alias beforeBulkDelete 558 | */ 559 | public static beforeBulkDestroy(name: string, fn: (options: BulkCreateOptions) => void): void 560 | public static beforeBulkDestroy(fn: (options: BulkCreateOptions) => void): void 561 | public static beforeBulkDelete(name: string, fn: (options: BulkCreateOptions) => void): void 562 | public static beforeBulkDelete(fn: (options: BulkCreateOptions) => void): void 563 | 564 | /** 565 | * A hook that is run after destroying instances in bulk 566 | * 567 | * @param name 568 | * @param fn A callback function that is called with options 569 | * 570 | * @alias afterBulkDelete 571 | */ 572 | public static afterBulkDestroy(name: string, fn: (options: DestroyOptions) => void): void 573 | public static afterBulkDestroy(fn: (options: DestroyOptions) => void): void 574 | public static afterBulkDelete(name: string, fn: (options: DestroyOptions) => void): void 575 | public static afterBulkDelete(fn: (options: DestroyOptions) => void): void 576 | 577 | /** 578 | * A hook that is run after updating instances in bulk 579 | * 580 | * @param name 581 | * @param fn A callback function that is called with options 582 | */ 583 | public static beforeBulkUpdate(name: string, fn: (options: UpdateOptions) => void): void 584 | public static beforeBulkUpdate(fn: (options: UpdateOptions) => void): void 585 | 586 | /** 587 | * A hook that is run after updating instances in bulk 588 | * 589 | * @param name 590 | * @param fn A callback function that is called with options 591 | */ 592 | public static afterBulkUpdate(name: string, fn: (options: UpdateOptions) => void): void 593 | public static afterBulkUpdate(fn: (options: UpdateOptions) => void): void 594 | 595 | /** 596 | * A hook that is run before a find (select) query 597 | * 598 | * @param name 599 | * @param fn A callback function that is called with options 600 | */ 601 | public static beforeFind(name: string, fn: (options: FindOptions) => void): void 602 | public static beforeFind(fn: (options: FindOptions) => void): void 603 | 604 | /** 605 | * A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded 606 | * 607 | * @param name 608 | * @param fn A callback function that is called with options 609 | */ 610 | public static beforeFindAfterExpandIncludeAll(name: string, fn: (options: FindOptions) => void): void 611 | public static beforeFindAfterExpandIncludeAll(fn: (options: FindOptions) => void): void 612 | 613 | /** 614 | * A hook that is run before a find (select) query, after all option parsing is complete 615 | * 616 | * @param name 617 | * @param fn A callback function that is called with options 618 | */ 619 | public static beforeFindAfterOptions(name: string, fn: (options: FindOptions) => void): void 620 | public static beforeFindAfterOptions(fn: (options: FindOptions) => void): void 621 | 622 | /** 623 | * A hook that is run after a find (select) query 624 | * 625 | * @param name 626 | * @param fn A callback function that is called with instance(s), options 627 | */ 628 | public static afterFind( 629 | name: string, 630 | fn: (instancesOrInstance: Model[] | Model, options: FindOptions, fn?: Function) => void 631 | ): void 632 | public static afterFind( 633 | fn: (instancesOrInstance: Model[] | Model, options: FindOptions, fn?: Function) => void 634 | ): void 635 | 636 | /** 637 | * A hook that is run before a define call 638 | * 639 | * @param name 640 | * @param fn A callback function that is called with attributes, options 641 | */ 642 | public static beforeDefine( 643 | name: string, 644 | fn: (attributes: ModelAttributes, options: ModelOptions) => void 645 | ): void 646 | public static beforeDefine( 647 | fn: (attributes: ModelAttributes, options: ModelOptions) => void 648 | ): void 649 | 650 | /** 651 | * A hook that is run after a define call 652 | * 653 | * @param name 654 | * @param fn A callback function that is called with factory 655 | */ 656 | public static afterDefine(name: string, fn: (model: typeof Model) => void): void 657 | public static afterDefine(fn: (model: typeof Model) => void): void 658 | 659 | /** 660 | * A hook that is run before Sequelize() call 661 | * 662 | * @param name 663 | * @param fn A callback function that is called with config, options 664 | */ 665 | public static beforeInit(name: string, fn: (config: object, options: object) => void): void 666 | public static beforeInit(fn: (config: object, options: object) => void): void 667 | 668 | /** 669 | * A hook that is run after Sequelize() call 670 | * 671 | * @param name 672 | * @param fn A callback function that is called with sequelize 673 | */ 674 | public static afterInit(name: string, fn: (sequelize: Sequelize) => void): void 675 | public static afterInit(fn: (sequelize: Sequelize) => void): void 676 | 677 | /** 678 | * A hook that is run before sequelize.sync call 679 | * @param {String} name 680 | * @param {Function} fn A callback function that is called with options passed to sequelize.sync 681 | * @name beforeBulkSync 682 | */ 683 | public static beforeBulkSync(name: string, fn: (options: SyncOptions) => any): void 684 | public static beforeBulkSync(fn: (options: SyncOptions) => any): void 685 | 686 | /** 687 | * A hook that is run after sequelize.sync call 688 | * @param {String} name 689 | * @param {Function} fn A callback function that is called with options passed to sequelize.sync 690 | * @name afterBulkSync 691 | */ 692 | public static afterBulkSync(name: string, fn: (options: SyncOptions) => any): void 693 | public static afterBulkSync(fn: (options: SyncOptions) => any): void 694 | 695 | /** 696 | * A hook that is run before Model.sync call 697 | * @param {String} name 698 | * @param {Function} fn A callback function that is called with options passed to Model.sync 699 | * @name beforeSync 700 | */ 701 | public static beforeSync(name: string, fn: (options: SyncOptions) => any): void 702 | public static beforeSync(fn: (options: SyncOptions) => any): void 703 | 704 | /** 705 | * A hook that is run after Model.sync call 706 | * @param {String} name 707 | * @param {Function} fn A callback function that is called with options passed to Model.sync 708 | * @name afterSync 709 | */ 710 | public static afterSync(name: string, fn: (options: SyncOptions) => any): void 711 | public static afterSync(fn: (options: SyncOptions) => any): void 712 | 713 | // --------------------------- instance hooks ----------------------------------------------------------- 714 | 715 | /** 716 | * Add a hook to the model 717 | * 718 | * @param hookType 719 | * @param name Provide a name for the hook function. It can be used to remove the hook later or to order 720 | * hooks based on some sort of priority system in the future. 721 | * @param fn The hook function 722 | * 723 | * @alias hook 724 | */ 725 | public addHook(hookType: string, name: string, fn: Function): typeof Sequelize 726 | public addHook(hookType: string, fn: Function): typeof Sequelize 727 | public hook(hookType: string, name: string, fn: Function): typeof Sequelize 728 | public hook(hookType: string, fn: Function): typeof Sequelize 729 | 730 | /** 731 | * Remove hook from the model 732 | * 733 | * @param hookType 734 | * @param name 735 | */ 736 | public removeHook(hookType: string, name: string): typeof Sequelize 737 | 738 | /** 739 | * Check whether the mode has any hooks of this type 740 | * 741 | * @param hookType 742 | * 743 | * @alias hasHooks 744 | */ 745 | public hasHook(hookType: string): boolean 746 | public hasHooks(hookType: string): boolean 747 | 748 | /** 749 | * A hook that is run before validation 750 | * 751 | * @param name 752 | * @param fn A callback function that is called with instance, options 753 | */ 754 | public beforeValidate(name: string, fn: (instance: Model, options: object) => void): void 755 | public beforeValidate(fn: (instance: Model, options: object) => void): void 756 | 757 | /** 758 | * A hook that is run after validation 759 | * 760 | * @param name 761 | * @param fn A callback function that is called with instance, options 762 | */ 763 | public afterValidate(name: string, fn: (instance: Model, options: object) => void): void 764 | public afterValidate(fn: (instance: Model, options: object) => void): void 765 | 766 | /** 767 | * A hook that is run before creating a single instance 768 | * 769 | * @param name 770 | * @param fn A callback function that is called with attributes, options 771 | */ 772 | public beforeCreate(name: string, fn: (attributes: Model, options: CreateOptions) => void): void 773 | public beforeCreate(fn: (attributes: Model, options: CreateOptions) => void): void 774 | 775 | /** 776 | * A hook that is run after creating a single instance 777 | * 778 | * @param name 779 | * @param fn A callback function that is called with attributes, options 780 | */ 781 | public afterCreate(name: string, fn: (attributes: Model, options: CreateOptions) => void): void 782 | public afterCreate(fn: (attributes: Model, options: CreateOptions) => void): void 783 | 784 | /** 785 | * A hook that is run before destroying a single instance 786 | * 787 | * @param name 788 | * @param fn A callback function that is called with instance, options 789 | * @alias beforeDelete 790 | */ 791 | public beforeDestroy(name: string, fn: (instance: Model, options: InstanceDestroyOptions) => void): void 792 | public beforeDestroy(fn: (instance: Model, options: InstanceDestroyOptions) => void): void 793 | public beforeDelete(name: string, fn: (instance: Model, options: InstanceDestroyOptions) => void): void 794 | public beforeDelete(fn: (instance: Model, options: InstanceDestroyOptions) => void): void 795 | 796 | /** 797 | * A hook that is run after destroying a single instance 798 | * 799 | * @param name 800 | * @param fn A callback function that is called with instance, options 801 | * @alias afterDelete 802 | */ 803 | public afterDestroy(name: string, fn: (instance: Model, options: InstanceDestroyOptions) => void): void 804 | public afterDestroy(fn: (instance: Model, options: InstanceDestroyOptions) => void): void 805 | public afterDelete(name: string, fn: (instance: Model, options: InstanceDestroyOptions) => void): void 806 | public afterDelete(fn: (instance: Model, options: InstanceDestroyOptions) => void): void 807 | 808 | /** 809 | * A hook that is run before updating a single instance 810 | * 811 | * @param name 812 | * @param fn A callback function that is called with instance, options 813 | */ 814 | public beforeUpdate(name: string, fn: (instance: Model, options: UpdateOptions) => void): void 815 | public beforeUpdate(fn: (instance: Model, options: UpdateOptions) => void): void 816 | 817 | /** 818 | * A hook that is run after updating a single instance 819 | * 820 | * @param name 821 | * @param fn A callback function that is called with instance, options 822 | */ 823 | public afterUpdate(name: string, fn: (instance: Model, options: UpdateOptions) => void): void 824 | public afterUpdate(fn: (instance: Model, options: UpdateOptions) => void): void 825 | 826 | /** 827 | * A hook that is run before creating instances in bulk 828 | * 829 | * @param name 830 | * @param fn A callback function that is called with instances, options 831 | */ 832 | public beforeBulkCreate(name: string, fn: (instances: Model[], options: BulkCreateOptions) => void): void 833 | public beforeBulkCreate(fn: (instances: Model[], options: BulkCreateOptions) => void): void 834 | 835 | /** 836 | * A hook that is run after creating instances in bulk 837 | * 838 | * @param name 839 | * @param fn A callback function that is called with instances, options 840 | * @name afterBulkCreate 841 | */ 842 | public afterBulkCreate(name: string, fn: (instances: Model[], options: BulkCreateOptions) => void): void 843 | public afterBulkCreate(fn: (instances: Model[], options: BulkCreateOptions) => void): void 844 | 845 | /** 846 | * A hook that is run before destroying instances in bulk 847 | * 848 | * @param name 849 | * @param fn A callback function that is called with options 850 | * 851 | * @alias beforeBulkDelete 852 | */ 853 | public beforeBulkDestroy(name: string, fn: (options: BulkCreateOptions) => void): void 854 | public beforeBulkDestroy(fn: (options: BulkCreateOptions) => void): void 855 | public beforeBulkDelete(name: string, fn: (options: BulkCreateOptions) => void): void 856 | public beforeBulkDelete(fn: (options: BulkCreateOptions) => void): void 857 | 858 | /** 859 | * A hook that is run after destroying instances in bulk 860 | * 861 | * @param name 862 | * @param fn A callback function that is called with options 863 | * 864 | * @alias afterBulkDelete 865 | */ 866 | public afterBulkDestroy(name: string, fn: (options: DestroyOptions) => void): void 867 | public afterBulkDestroy(fn: (options: DestroyOptions) => void): void 868 | public afterBulkDelete(name: string, fn: (options: DestroyOptions) => void): void 869 | public afterBulkDelete(fn: (options: DestroyOptions) => void): void 870 | 871 | /** 872 | * A hook that is run after updating instances in bulk 873 | * 874 | * @param name 875 | * @param fn A callback function that is called with options 876 | */ 877 | public beforeBulkUpdate(name: string, fn: (options: UpdateOptions) => void): void 878 | public beforeBulkUpdate(fn: (options: UpdateOptions) => void): void 879 | 880 | /** 881 | * A hook that is run after updating instances in bulk 882 | * 883 | * @param name 884 | * @param fn A callback function that is called with options 885 | */ 886 | public afterBulkUpdate(name: string, fn: (options: UpdateOptions) => void): void 887 | public afterBulkUpdate(fn: (options: UpdateOptions) => void): void 888 | 889 | /** 890 | * A hook that is run before a find (select) query 891 | * 892 | * @param name 893 | * @param fn A callback function that is called with options 894 | */ 895 | public beforeFind(name: string, fn: (options: FindOptions) => void): void 896 | public beforeFind(fn: (options: FindOptions) => void): void 897 | 898 | /** 899 | * A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded 900 | * 901 | * @param name 902 | * @param fn A callback function that is called with options 903 | */ 904 | public beforeFindAfterExpandIncludeAll(name: string, fn: (options: FindOptions) => void): void 905 | public beforeFindAfterExpandIncludeAll(fn: (options: FindOptions) => void): void 906 | 907 | /** 908 | * A hook that is run before a find (select) query, after all option parsing is complete 909 | * 910 | * @param name 911 | * @param fn A callback function that is called with options 912 | */ 913 | public beforeFindAfterOptions(name: string, fn: (options: FindOptions) => void): void 914 | public beforeFindAfterOptions(fn: (options: FindOptions) => void): void 915 | 916 | /** 917 | * A hook that is run after a find (select) query 918 | * 919 | * @param name 920 | * @param fn A callback function that is called with instance(s), options 921 | */ 922 | public afterFind( 923 | name: string, 924 | fn: (instancesOrInstance: Model[] | Model, options: FindOptions, fn?: Function) => void 925 | ): void 926 | public afterFind(fn: (instancesOrInstance: Model[] | Model, options: FindOptions, fn?: Function) => void): void 927 | 928 | /** 929 | * A hook that is run before a define call 930 | * 931 | * @param name 932 | * @param fn A callback function that is called with attributes, options 933 | */ 934 | public beforeDefine(name: string, fn: (attributes: ModelAttributes, options: ModelOptions) => void): void 935 | public beforeDefine(fn: (attributes: ModelAttributes, options: ModelOptions) => void): void 936 | 937 | /** 938 | * A hook that is run after a define call 939 | * 940 | * @param name 941 | * @param fn A callback function that is called with factory 942 | */ 943 | public afterDefine(name: string, fn: (model: typeof Model) => void): void 944 | public afterDefine(fn: (model: typeof Model) => void): void 945 | 946 | /** 947 | * A hook that is run before Sequelize() call 948 | * 949 | * @param name 950 | * @param fn A callback function that is called with config, options 951 | */ 952 | public beforeInit(name: string, fn: (config: object, options: object) => void): void 953 | public beforeInit(fn: (config: object, options: object) => void): void 954 | 955 | /** 956 | * A hook that is run after Sequelize() call 957 | * 958 | * @param name 959 | * @param fn A callback function that is called with sequelize 960 | */ 961 | public afterInit(name: string, fn: (sequelize: Sequelize) => void): void 962 | public afterInit(fn: (sequelize: Sequelize) => void): void 963 | 964 | /** 965 | * A hook that is run before sequelize.sync call 966 | * @param {String} name 967 | * @param {Function} fn A callback function that is called with options passed to sequelize.sync 968 | * @name beforeBulkSync 969 | */ 970 | public beforeBulkSync(name: string, fn: (options: SyncOptions) => any): void 971 | public beforeBulkSync(fn: (options: SyncOptions) => any): void 972 | 973 | /** 974 | * A hook that is run after sequelize.sync call 975 | * @param {String} name 976 | * @param {Function} fn A callback function that is called with options passed to sequelize.sync 977 | * @name afterBulkSync 978 | */ 979 | public afterBulkSync(name: string, fn: (options: SyncOptions) => any): void 980 | public afterBulkSync(fn: (options: SyncOptions) => any): void 981 | 982 | /** 983 | * A hook that is run before Model.sync call 984 | * @param {String} name 985 | * @param {Function} fn A callback function that is called with options passed to Model.sync 986 | * @name beforeSync 987 | */ 988 | public beforeSync(name: string, fn: (options: SyncOptions) => any): void 989 | public beforeSync(fn: (options: SyncOptions) => any): void 990 | 991 | /** 992 | * A hook that is run after Model.sync call 993 | * @param {String} name 994 | * @param {Function} fn A callback function that is called with options passed to Model.sync 995 | * @name afterSync 996 | */ 997 | public afterSync(name: string, fn: (options: SyncOptions) => any): void 998 | public afterSync(fn: (options: SyncOptions) => any): void 999 | 1000 | /** 1001 | * Instantiate sequelize with name of database, username and password 1002 | * 1003 | * #### Example usage 1004 | * 1005 | * ```javascript 1006 | * // without password and options 1007 | * var sequelize = new Sequelize('database', 'username') 1008 | * 1009 | * // without options 1010 | * var sequelize = new Sequelize('database', 'username', 'password') 1011 | * 1012 | * // without password / with blank password 1013 | * var sequelize = new Sequelize('database', 'username', null, {}) 1014 | * 1015 | * // with password and options 1016 | * var sequelize = new Sequelize('my_database', 'john', 'doe', {}) 1017 | * 1018 | * // with uri (see below) 1019 | * var sequelize = new Sequelize('mysql://localhost:3306/database', {}) 1020 | * ``` 1021 | * 1022 | * @param database The name of the database 1023 | * @param username The username which is used to authenticate against the 1024 | * database. 1025 | * @param password The password which is used to authenticate against the 1026 | * database. 1027 | * @param options An object with options. 1028 | */ 1029 | constructor(database: string, username: string, password?: string, options?: Options) 1030 | constructor(database: string, username: string, options?: Options) 1031 | constructor(options?: Options) 1032 | 1033 | /** 1034 | * Instantiate sequelize with an URI 1035 | * @name Sequelize 1036 | * @constructor 1037 | * 1038 | * @param uri A full database URI 1039 | * @param options See above for possible options 1040 | */ 1041 | constructor(uri: string, options?: Options) 1042 | 1043 | /** 1044 | * Returns the specified dialect. 1045 | */ 1046 | public getDialect(): string 1047 | 1048 | /** 1049 | * Returns an instance of QueryInterface. 1050 | */ 1051 | public getQueryInterface(): QueryInterface 1052 | 1053 | /** 1054 | * Define a new model, representing a table in the DB. 1055 | * 1056 | * The table columns are define by the hash that is given as the second argument. Each attribute of the 1057 | * hash 1058 | * represents a column. A short table definition might look like this: 1059 | * 1060 | * ```js 1061 | * sequelize.define('modelName', { 1062 | * columnA: { 1063 | * type: Sequelize.BOOLEAN, 1064 | * validate: { 1065 | * is: ["[a-z]",'i'], // will only allow letters 1066 | * max: 23, // only allow values <= 23 1067 | * isIn: { 1068 | * args: [['en', 'zh']], 1069 | * msg: "Must be English or Chinese" 1070 | * } 1071 | * }, 1072 | * field: 'column_a' 1073 | * // Other attributes here 1074 | * }, 1075 | * columnB: Sequelize.STRING, 1076 | * columnC: 'MY VERY OWN COLUMN TYPE' 1077 | * }) 1078 | * 1079 | * sequelize.models.modelName // The model will now be available in models under the name given to define 1080 | * ``` 1081 | * 1082 | * As shown above, column definitions can be either strings, a reference to one of the datatypes that are 1083 | * predefined on the Sequelize constructor, or an object that allows you to specify both the type of the 1084 | * column, and other attributes such as default values, foreign key constraints and custom setters and 1085 | * getters. 1086 | * 1087 | * For a list of possible data types, see 1088 | * http://docs.sequelizejs.com/en/latest/docs/models-definition/#data-types 1089 | * 1090 | * For more about getters and setters, see 1091 | * http://docs.sequelizejs.com/en/latest/docs/models-definition/#getters-setters 1092 | * 1093 | * For more about instance and class methods, see 1094 | * http://docs.sequelizejs.com/en/latest/docs/models-definition/#expansion-of-models 1095 | * 1096 | * For more about validation, see 1097 | * http://docs.sequelizejs.com/en/latest/docs/models-definition/#validations 1098 | * 1099 | * @param modelName The name of the model. The model will be stored in `sequelize.models` under this name 1100 | * @param attributes An object, where each attribute is a column of the table. Each column can be either a 1101 | * DataType, a string or a type-description object, with the properties described below: 1102 | * @param options These options are merged with the default define options provided to the Sequelize 1103 | * constructor 1104 | */ 1105 | public define(modelName: string, attributes: ModelAttributes, options?: ModelOptions): typeof Model 1106 | 1107 | /** 1108 | * Fetch a Model which is already defined 1109 | * 1110 | * @param modelName The name of a model defined with Sequelize.define 1111 | */ 1112 | public model(modelName: string): typeof Model 1113 | 1114 | /** 1115 | * Checks whether a model with the given name is defined 1116 | * 1117 | * @param modelName The name of a model defined with Sequelize.define 1118 | */ 1119 | public isDefined(modelName: string): boolean 1120 | 1121 | /** 1122 | * Imports a model defined in another file 1123 | * 1124 | * Imported models are cached, so multiple calls to import with the same path will not load the file 1125 | * multiple times 1126 | * 1127 | * See https://github.com/sequelize/sequelize/blob/master/examples/using-multiple-model-files/Task.js for a 1128 | * short example of how to define your models in separate files so that they can be imported by 1129 | * sequelize.import 1130 | * 1131 | * @param path The path to the file that holds the model you want to import. If the part is relative, it 1132 | * will be resolved relatively to the calling file 1133 | * 1134 | * @param defineFunction An optional function that provides model definitions. Useful if you do not 1135 | * want to use the module root as the define function 1136 | */ 1137 | public import( 1138 | path: string, 1139 | defineFunction?: (sequelize: Sequelize, dataTypes: typeof DataTypes) => T 1140 | ): T 1141 | 1142 | /** 1143 | * Execute a query on the DB, with the posibility to bypass all the sequelize goodness. 1144 | * 1145 | * By default, the function will return two arguments: an array of results, and a metadata object, 1146 | * containing number of affected rows etc. Use `.spread` to access the results. 1147 | * 1148 | * If you are running a type of query where you don't need the metadata, for example a `SELECT` query, you 1149 | * can pass in a query type to make sequelize format the results: 1150 | * 1151 | * ```js 1152 | * sequelize.query('SELECT...').spread(function (results, metadata) { 1153 | * // Raw query - use spread 1154 | * }); 1155 | * 1156 | * sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(function (results) { 1157 | * // SELECT query - use then 1158 | * }) 1159 | * ``` 1160 | * 1161 | * @param sql 1162 | * @param options Query options 1163 | */ 1164 | public query(sql: string | { query: string; values: any[] }, options?: QueryOptions): Promise 1165 | public query( 1166 | sql: string | { query: string; values: any[] }, 1167 | options: QueryOptionsWithModel 1168 | ): Promise 1169 | public query(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType): Promise 1170 | 1171 | /** 1172 | * Execute a query which would set an environment or user variable. The variables are set per connection, 1173 | * so this function needs a transaction. 1174 | * 1175 | * Only works for MySQL. 1176 | * 1177 | * @param variables object with multiple variables. 1178 | * @param options Query options. 1179 | */ 1180 | public set(variables: object, options: QueryOptionsTransactionRequired): Promise 1181 | 1182 | /** 1183 | * Escape value. 1184 | * 1185 | * @param value Value that needs to be escaped 1186 | */ 1187 | public escape(value: string | number | Date): string 1188 | 1189 | /** 1190 | * Create a new database schema. 1191 | * 1192 | * Note,that this is a schema in the 1193 | * [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), 1194 | * not a database table. In mysql and sqlite, this command will do nothing. 1195 | * 1196 | * @param schema Name of the schema 1197 | * @param options Options supplied 1198 | * @param options.logging A function that logs sql queries, or false for no logging 1199 | */ 1200 | public createSchema(schema: string, options: Logging): Promise 1201 | 1202 | /** 1203 | * Show all defined schemas 1204 | * 1205 | * Note,that this is a schema in the 1206 | * [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), 1207 | * not a database table. In mysql and sqlite, this will show all tables. 1208 | * 1209 | * @param options Options supplied 1210 | * @param options.logging A function that logs sql queries, or false for no logging 1211 | */ 1212 | public showAllSchemas(options: Logging): Promise 1213 | 1214 | /** 1215 | * Drop a single schema 1216 | * 1217 | * Note,that this is a schema in the 1218 | * [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), 1219 | * not a database table. In mysql and sqlite, this drop a table matching the schema name 1220 | * 1221 | * @param schema Name of the schema 1222 | * @param options Options supplied 1223 | * @param options.logging A function that logs sql queries, or false for no logging 1224 | */ 1225 | public dropSchema(schema: string, options: Logging): Promise 1226 | 1227 | /** 1228 | * Drop all schemas 1229 | * 1230 | * Note,that this is a schema in the 1231 | * [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), 1232 | * not a database table. In mysql and sqlite, this is the equivalent of drop all tables. 1233 | * 1234 | * @param options Options supplied 1235 | * @param options.logging A function that logs sql queries, or false for no logging 1236 | */ 1237 | public dropAllSchemas(options: Logging): Promise 1238 | 1239 | /** 1240 | * Sync all defined models to the DB. 1241 | * 1242 | * @param options Sync Options 1243 | */ 1244 | public sync(options?: SyncOptions): Promise 1245 | 1246 | /** 1247 | * Truncate all tables defined through the sequelize models. This is done 1248 | * by calling Model.truncate() on each model. 1249 | * 1250 | * @param {object} [options] The options passed to Model.destroy in addition to truncate 1251 | * @param {Boolean|function} [options.transaction] 1252 | * @param {Boolean|function} [options.logging] A function that logs sql queries, or false for no logging 1253 | */ 1254 | public truncate(options?: DestroyOptions): Promise 1255 | 1256 | /** 1257 | * Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model 1258 | * 1259 | * @param options The options passed to each call to Model.drop 1260 | */ 1261 | public drop(options?: DropOptions): Promise 1262 | 1263 | /** 1264 | * Test the connection by trying to authenticate 1265 | * 1266 | * @param options Query Options for authentication 1267 | */ 1268 | public authenticate(options?: QueryOptions): Promise 1269 | public validate(options?: QueryOptions): Promise 1270 | 1271 | /** 1272 | * Start a transaction. When using transactions, you should pass the transaction in the options argument 1273 | * in order for the query to happen under that transaction 1274 | * 1275 | * ```js 1276 | * sequelize.transaction().then(function (t) { 1277 | * return User.find(..., { transaction: t}).then(function (user) { 1278 | * return user.updateAttributes(..., { transaction: t}); 1279 | * }) 1280 | * .then(t.commit.bind(t)) 1281 | * .catch(t.rollback.bind(t)); 1282 | * }) 1283 | * ``` 1284 | * 1285 | * A syntax for automatically committing or rolling back based on the promise chain resolution is also 1286 | * supported: 1287 | * 1288 | * ```js 1289 | * sequelize.transaction(function (t) { // Note that we use a callback rather than a promise.then() 1290 | * return User.find(..., { transaction: t}).then(function (user) { 1291 | * return user.updateAttributes(..., { transaction: t}); 1292 | * }); 1293 | * }).then(function () { 1294 | * // Commited 1295 | * }).catch(function (err) { 1296 | * // Rolled back 1297 | * console.error(err); 1298 | * }); 1299 | * ``` 1300 | * 1301 | * If you have [CLS](https://github.com/othiym23/node-continuation-local-storage) enabled, the transaction 1302 | * will automatically be passed to any query that runs witin the callback. To enable CLS, add it do your 1303 | * project, create a namespace and set it on the sequelize constructor: 1304 | * 1305 | * ```js 1306 | * var cls = require('continuation-local-storage'), 1307 | * ns = cls.createNamespace('....'); 1308 | * var Sequelize = require('sequelize'); 1309 | * Sequelize.cls = ns; 1310 | * ``` 1311 | * Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace 1312 | * 1313 | * @param options Transaction Options 1314 | * @param autoCallback Callback for the transaction 1315 | */ 1316 | public transaction(options: TransactionOptions, autoCallback: (t: Transaction) => PromiseLike): Promise 1317 | public transaction(autoCallback: (t: Transaction) => PromiseLike): Promise 1318 | public transaction(options?: TransactionOptions): Promise 1319 | 1320 | /** 1321 | * Close all connections used by this sequelize instance, and free all references so the instance can be 1322 | * garbage collected. 1323 | * 1324 | * Normally this is done on process exit, so you only need to call this method if you are creating multiple 1325 | * instances, and want to garbage collect some of them. 1326 | */ 1327 | public close(): void 1328 | 1329 | /** 1330 | * Returns the database version 1331 | */ 1332 | public databaseVersion(): Promise 1333 | } 1334 | 1335 | // Utilities 1336 | 1337 | /** 1338 | * Creates a object representing a database function. This can be used in search queries, both in where and 1339 | * order parts, and as default values in column definitions. If you want to refer to columns in your 1340 | * function, you should use `sequelize.col`, so that the columns are properly interpreted as columns and 1341 | * not a strings. 1342 | * 1343 | * Convert a user's username to upper case 1344 | * ```js 1345 | * instance.updateAttributes({ 1346 | * username: self.sequelize.fn('upper', self.sequelize.col('username')) 1347 | * }) 1348 | * ``` 1349 | * @param fn The function you want to call 1350 | * @param args All further arguments will be passed as arguments to the function 1351 | */ 1352 | export function fn(fn: string, ...args: any[]): Fn 1353 | 1354 | /** 1355 | * Creates a object representing a column in the DB. This is often useful in conjunction with 1356 | * `sequelize.fn`, since raw string arguments to fn will be escaped. 1357 | * 1358 | * @param col The name of the column 1359 | */ 1360 | export function col(col: string): Col 1361 | 1362 | /** 1363 | * Creates a object representing a call to the cast function. 1364 | * 1365 | * @param val The value to cast 1366 | * @param type The type to cast it to 1367 | */ 1368 | export function cast(val: any, type: string): Cast 1369 | 1370 | /** 1371 | * Creates a object representing a literal, i.e. something that will not be escaped. 1372 | * 1373 | * @param val 1374 | */ 1375 | export function literal(val: any): Literal 1376 | export function asIs(val: any): Literal 1377 | 1378 | /** 1379 | * An AND query 1380 | * 1381 | * @param args Each argument will be joined by AND 1382 | */ 1383 | export function and(...args: (WhereOperators | WhereAttributeHash | Where)[]): AndOperator 1384 | 1385 | /** 1386 | * An OR query 1387 | * 1388 | * @param args Each argument will be joined by OR 1389 | */ 1390 | export function or(...args: (WhereOperators | WhereAttributeHash | Where)[]): OrOperator 1391 | 1392 | /** 1393 | * Creates an object representing nested where conditions for postgres's json data-type. 1394 | * 1395 | * @param conditionsOrPath A hash containing strings/numbers or other nested hash, a string using dot 1396 | * notation or a string using postgres json syntax. 1397 | * @param value An optional value to compare against. Produces a string of the form " = 1398 | * ''". 1399 | */ 1400 | export function json(conditionsOrPath: string | object, value?: string | number | boolean): Json 1401 | 1402 | /** 1403 | * A way of specifying attr = condition. 1404 | * 1405 | * The attr can either be an object taken from `Model.rawAttributes` (for example `Model.rawAttributes.id` 1406 | * or 1407 | * `Model.rawAttributes.name`). The attribute should be defined in your model definition. The attribute can 1408 | * also be an object from one of the sequelize utility functions (`sequelize.fn`, `sequelize.col` etc.) 1409 | * 1410 | * For string attributes, use the regular `{ where: { attr: something }}` syntax. If you don't want your 1411 | * string to be escaped, use `sequelize.literal`. 1412 | * 1413 | * @param attr The attribute, which can be either an attribute object from `Model.rawAttributes` or a 1414 | * sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the 1415 | * POJO syntax 1416 | * @param comparator Comparator 1417 | * @param logic The condition. Can be both a simply type, or a further condition (`.or`, `.and`, `.literal` 1418 | * etc.) 1419 | */ 1420 | export function where(attr: object, comparator: string, logic: string | object): Where 1421 | export function where(attr: object, logic: string | object): Where 1422 | export function condition(attr: object, logic: string | object): Where 1423 | 1424 | export { DataTypes } 1425 | export * from './model' 1426 | export * from './transaction' 1427 | export * from './model' 1428 | export * from './associations/index' 1429 | export * from './errors' 1430 | export { BaseError as Error } from './errors' 1431 | export { useInflection } from './utils' 1432 | import * as Deferrable from './deferrable' 1433 | export { Deferrable } 1434 | export { Promise } from './promise' 1435 | import * as Utils from './utils' 1436 | export { Utils } 1437 | export * from './utils' 1438 | 1439 | export { Validator as validator } from './utils/validator-extras' 1440 | import { validator } from './utils/validator-extras' 1441 | export { validator as Validator } 1442 | 1443 | import QueryTypes = require('./query-types') 1444 | export { QueryTypes } 1445 | 1446 | export default Sequelize 1447 | -------------------------------------------------------------------------------- /lib/sql-string.d.ts: -------------------------------------------------------------------------------- 1 | export function escapeId(val: string, forbidQualified?: boolean): string 2 | export function escape(val: any, timeZone?: string, dialect?: string, format?: string): string 3 | export function format(sql: string, values: any[], timeZone?: string, dialect?: string): string 4 | export function formatNamedParameters(sql: string, values: any[], timeZone?: string, dialect?: string): string 5 | -------------------------------------------------------------------------------- /lib/transaction.d.ts: -------------------------------------------------------------------------------- 1 | import { Logging } from './model' 2 | import { Promise } from './promise' 3 | import { Sequelize } from './sequelize' 4 | 5 | /** 6 | * The transaction object is used to identify a running transaction. It is created by calling 7 | * `Sequelize.transaction()`. 8 | * 9 | * To run a query under a transaction, you should pass the transaction in the options object. 10 | */ 11 | export class Transaction { 12 | constructor(sequelize: Sequelize, options: TransactionOptions) 13 | 14 | /** 15 | * Commit the transaction 16 | */ 17 | public commit(): Promise 18 | 19 | /** 20 | * Rollback (abort) the transaction 21 | */ 22 | public rollback(): Promise 23 | 24 | /** 25 | * A hook that is run after a transaction is committed 26 | * 27 | * @param fn A callback function that is called with the committed transaction 28 | */ 29 | public afterCommit(fn: () => Promise | void): void 30 | 31 | /** 32 | * Possible options for row locking. Used in conjunction with `find` calls: 33 | * 34 | * ```js 35 | * t1 // is a transaction 36 | * t1.LOCK.UPDATE, 37 | * t1.LOCK.SHARE, 38 | * t1.LOCK.KEY_SHARE, // Postgres 9.3+ only 39 | * t1.LOCK.NO_KEY_UPDATE // Postgres 9.3+ only 40 | * ``` 41 | * 42 | * Usage: 43 | * ```js 44 | * t1 // is a transaction 45 | * Model.findAll({ 46 | * where: ..., 47 | * transaction: t1, 48 | * lock: t1.LOCK... 49 | * }); 50 | * ``` 51 | * 52 | * Postgres also supports specific locks while eager loading by using OF: 53 | * ```js 54 | * UserModel.findAll({ 55 | * where: ..., 56 | * include: [TaskModel, ...], 57 | * transaction: t1, 58 | * lock: { 59 | * level: t1.LOCK..., 60 | * of: UserModel 61 | * } 62 | * }); 63 | * ``` 64 | * UserModel will be locked but TaskModel won't! 65 | * 66 | * @property LOCK 67 | */ 68 | public static LOCK: TransactionLock 69 | 70 | /** 71 | * @see {@link Transaction.LOCK} 72 | */ 73 | public LOCK: TransactionLock 74 | } 75 | 76 | export interface TransactionLock { 77 | UPDATE: 'UPDATE' 78 | SHARE: 'SHARE' 79 | KEY_SHARE: 'KEY SHARE' 80 | NO_KEY_UPDATE: 'NO KEY UPDATE' 81 | } 82 | 83 | export type TransactionType = 'DEFERRED' | 'IMMEDIATE' | 'EXCLUSIVE' 84 | export const TYPES: { 85 | DEFERRED: 'DEFERRED' 86 | IMMEDIATE: 'IMMEDIATE' 87 | EXCLUSIVE: 'EXCLUSIVE' 88 | } 89 | 90 | /** 91 | * Isolations levels can be set per-transaction by passing `options.isolationLevel` to `sequelize.transaction`. 92 | * Default to `REPEATABLE_READ` but you can override the default isolation level by passing `options.isolationLevel` in `new Sequelize`. 93 | * 94 | * The possible isolations levels to use when starting a transaction: 95 | * 96 | * ```js 97 | * { 98 | * READ_UNCOMMITTED: "READ UNCOMMITTED", 99 | * READ_COMMITTED: "READ COMMITTED", 100 | * REPEATABLE_READ: "REPEATABLE READ", 101 | * SERIALIZABLE: "SERIALIZABLE" 102 | * } 103 | * ``` 104 | * 105 | * Pass in the desired level as the first argument: 106 | * 107 | * ```js 108 | * return sequelize.transaction({isolationLevel: Sequelize.Transaction.SERIALIZABLE}, transaction => { 109 | * 110 | * // your transactions 111 | * 112 | * }).then(result => { 113 | * // transaction has been committed. Do something after the commit if required. 114 | * }).catch(err => { 115 | * // do something with the err. 116 | * }); 117 | * ``` 118 | */ 119 | export const ISOLATION_LEVELS: { 120 | READ_UNCOMMITTED: 'READ UNCOMMITTED' 121 | READ_COMMITTED: 'READ COMMITTED' 122 | REPEATABLE_READ: 'REPEATABLE READ' 123 | SERIALIZABLE: 'SERIALIZABLE' 124 | } 125 | 126 | /** 127 | * Options provided when the transaction is created 128 | */ 129 | export interface TransactionOptions extends Logging { 130 | autocommit?: boolean 131 | 132 | /** 133 | * See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options 134 | */ 135 | isolationLevel?: string 136 | 137 | type?: TransactionType 138 | deferrable?: string 139 | } 140 | 141 | export default Transaction 142 | -------------------------------------------------------------------------------- /lib/utils.d.ts: -------------------------------------------------------------------------------- 1 | import parameterValidator = require('./utils/parameter-validator') 2 | 3 | export type Primitive = 'string' | 'number' | 'boolean' 4 | 5 | export function useInflection(inflection: any): void 6 | 7 | export function camelizeIf(string: string, condition?: boolean): string 8 | export function underscoredIf(string: string, condition?: boolean): string 9 | export function isPrimitive(val: any): val is Primitive 10 | 11 | /** Same concept as _.merge, but don't overwrite properties that have already been assigned */ 12 | export function mergeDefaults(a: any, b: any): any 13 | export function lowercaseFirst(s: string): string 14 | export function uppercaseFirst(s: string): string 15 | export function spliceStr(str: string, index: number, count: number, add: string): string 16 | export function camelize(str: string): string 17 | export function format(arr: any[], dialect: string): string 18 | export function formatNamedParameters(sql: string, parameters: any, dialect: string): string 19 | export function cloneDeep(obj: T, fn?: Function): T 20 | 21 | /** Expand and normalize finder options */ 22 | export function mapFinderOptions(options: any, Model: any): any 23 | 24 | /* Used to map field names in attributes and where conditions */ 25 | export function mapOptionFieldNames(options: any, Model: any): any 26 | 27 | export function mapWhereFieldNames(attributes: any, Model: any): any 28 | /** Used to map field names in values */ 29 | export function mapValueFieldNames(dataValues: any, fields: any, Model: any): any 30 | 31 | export function isColString(value: string): boolean 32 | export function argsArePrimaryKeys(args: any, primaryKeys: any): boolean 33 | export function canTreatArrayAsAnd(arr: any[]): boolean 34 | export function combineTableNames(tableName1: string, tableName2: string): string 35 | 36 | export function singularize(s: string): string 37 | export function pluralize(s: string): string 38 | 39 | export function removeCommentsFromFunctionString(s: string): string 40 | export function toDefaultValue(value: any): any 41 | 42 | /** 43 | * Determine if the default value provided exists and can be described 44 | * in a db schema using the DEFAULT directive. 45 | * 46 | * @param {*} value Any default value. 47 | * @return {boolean} yes / no. 48 | */ 49 | export function defaultValueSchemable(value: any): boolean 50 | 51 | export function defaultValueSchemable(hash: any, omitNull: any, options: any): any 52 | export function inherit(SubClass: any, SuperClass: any): any 53 | export function stack(): string 54 | export function sliceArgs(args: any, begin: any): any[] 55 | export function now(dialect: string): Date 56 | export function tick(func: Function): void 57 | 58 | // Note: Use the `quoteIdentifier()` and `escape()` methods on the 59 | // `QueryInterface` instead for more portable code. 60 | export const TICK_CHAR: string 61 | export function addTicks(s: string, tickChar?: string): string 62 | export function removeTicks(s: string, tickChar?: string): string 63 | 64 | /* 65 | * Utility functions for representing SQL functions, and columns that should be escaped. 66 | * Please do not use these functions directly, use Sequelize.fn and Sequelize.col instead. 67 | */ 68 | export class Fn { 69 | private _isSequelizeMethod: boolean 70 | constructor(fn: any, args: any) 71 | public clone(): this 72 | } 73 | 74 | export class Col { 75 | public col: string 76 | private _isSequelizeMethod: boolean 77 | constructor(col: string) 78 | } 79 | 80 | export class Cast { 81 | public val: any 82 | public type: string 83 | private _isSequelizeMethod: boolean 84 | constructor(val: any, type?: string) 85 | } 86 | 87 | export class Literal { 88 | public val: any 89 | private _isSequelizeMethod: boolean 90 | constructor(val: any) 91 | } 92 | 93 | export class Json { 94 | public conditions: object 95 | public path: string 96 | public value: string | number | boolean 97 | private _isSequelizeMethod: boolean 98 | constructor(conditionsOrPath: string | object, value?: string | number | boolean) 99 | } 100 | 101 | export class Where { 102 | public attribute: object 103 | public comparator: string 104 | public logic: string | object 105 | private _isSequelizeMethod: boolean 106 | constructor(attr: object, comparator: string, logic: string | object) 107 | constructor(attr: object, logic: string | object) 108 | } 109 | 110 | export const validateParameter: typeof parameterValidator 111 | export function formatReferences(obj: any): any 112 | 113 | export { Promise } from './promise' 114 | -------------------------------------------------------------------------------- /lib/utils/parameter-validator.d.ts: -------------------------------------------------------------------------------- 1 | declare function check( 2 | value: any, 3 | expectation: any, 4 | options?: { 5 | deprecated?: boolean 6 | index?: any 7 | method?: any 8 | optional?: boolean 9 | } 10 | ): boolean 11 | export = check 12 | -------------------------------------------------------------------------------- /lib/utils/validator-extras.d.ts: -------------------------------------------------------------------------------- 1 | import * as val from 'validator' 2 | 3 | type OrigValidator = typeof val 4 | 5 | export interface Extensions { 6 | notEmpty(str: string): boolean 7 | len(str: string, min: number, max: number): boolean 8 | isUrl(str: string): boolean 9 | isIPv6(str: string): boolean 10 | isIPv4(str: string): boolean 11 | notIn(str: string, values: string[]): boolean 12 | regex(str: string, pattern: string, modifiers: string): boolean 13 | notRegex(str: string, pattern: string, modifiers: string): boolean 14 | isDecimal(str: string): boolean 15 | min(str: string, val: number): boolean 16 | max(str: string, val: number): boolean 17 | not(str: string, pattern: string, modifiers: string): boolean 18 | contains(str: string, elem: string[]): boolean 19 | notContains(str: string, elem: string[]): boolean 20 | is(str: string, pattern: string, modifiers: string): boolean 21 | } 22 | export const extensions: Extensions 23 | 24 | export interface Validator extends OrigValidator, Extensions { 25 | contains(str: string, elem: string[]): boolean 26 | } 27 | export const validator: Validator 28 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@types/sequelize", 3 | "version": "4.0.0", 4 | "private": true, 5 | "description": "Typescript Typings for Sequelize", 6 | "typings": "index.d.ts", 7 | "dependencies": { 8 | "@types/validator": "^6.3.0", 9 | "@types/bluebird": "^3.5.5" 10 | }, 11 | "peerDependencies": { 12 | "typescript": ">=2.0.0" 13 | }, 14 | "devDependencies": { 15 | "prettier": "^1.9.2", 16 | "tslint": "~5.8.0", 17 | "tslint-config-prettier": "^1.6.0", 18 | "typedoc": "^0.13.0", 19 | "typescript": "^2.5.3" 20 | }, 21 | "scripts": { 22 | "build": "tsc -p .", 23 | "prettier": "prettier --write --list-different '**/{*.{json,ts,md},.prettierrc}'", 24 | "test": "tsc -p test", 25 | "tslint": "npm run tslint-types && npm run tslint-test", 26 | "tslint-types": "tslint -p tsconfig.json -c tslint.json '**/*.d.ts' -e 'node_modules/**'", 27 | "tslint-test": "tslint -p test/tsconfig.json -c tslint.json 'test/**/*.ts'", 28 | "typedoc": "typedoc --tsconfig tsconfig.json --includeDeclarations --excludeExternals --readme docs_index.md --name \"TypeScript definitions for Sequelize\" --mode modules --out typedoc lib" 29 | }, 30 | "repository": { 31 | "type": "git", 32 | "url": "git+https://github.com/types/sequelize.git" 33 | }, 34 | "author": "Louay Alakkad", 35 | "license": "ISC", 36 | "contributors": [ 37 | "Felix Becker " 38 | ], 39 | "bugs": { 40 | "url": "https://github.com/types/sequelize/issues" 41 | }, 42 | "homepage": "https://typed-sequelize.surge.sh" 43 | } 44 | -------------------------------------------------------------------------------- /test/connection.ts: -------------------------------------------------------------------------------- 1 | import { QueryTypes, Sequelize, SyncOptions } from 'sequelize' 2 | 3 | export const sequelize = new Sequelize('uri') 4 | 5 | sequelize.afterBulkSync((options: SyncOptions) => { 6 | console.log('synced') 7 | }) 8 | 9 | sequelize 10 | .query('SELECT * FROM `test`', { 11 | type: QueryTypes.SELECT, 12 | }) 13 | .then((rows: any[]) => { 14 | rows.forEach(row => { 15 | console.log(row) 16 | }) 17 | }) 18 | -------------------------------------------------------------------------------- /test/define.ts: -------------------------------------------------------------------------------- 1 | import { DataTypes, Model } from 'sequelize' 2 | import { sequelize } from './connection' 3 | 4 | // I really wouldn't recommend this, but if you want you can still use define() and interfaces 5 | 6 | interface User extends Model { 7 | id: number 8 | username: string 9 | firstName: string 10 | lastName: string 11 | createdAt: Date 12 | updatedAt: Date 13 | } 14 | 15 | type UserModel = { 16 | new (): User 17 | customStaticMethod(): any 18 | } & typeof Model 19 | 20 | const User = sequelize.define('User', { firstName: DataTypes.STRING }, { tableName: 'users' }) as UserModel 21 | 22 | async function test() { 23 | User.customStaticMethod() 24 | 25 | const user: User = new User() 26 | 27 | const user2: User = (await User.find()) as User 28 | 29 | user2.firstName = 'John' 30 | 31 | await user2.save() 32 | } 33 | -------------------------------------------------------------------------------- /test/errors.ts: -------------------------------------------------------------------------------- 1 | // Error === BaseError 2 | import { BaseError, Error, UniqueConstraintError } from 'sequelize' 3 | import { User } from './models/User' 4 | 5 | async function test() { 6 | try { 7 | await User.create({ username: 'john_doe' }) 8 | } catch (e) { 9 | if (e instanceof UniqueConstraintError) { 10 | console.error((e as UniqueConstraintError).sql) 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /test/include.ts: -------------------------------------------------------------------------------- 1 | import { Model, Sequelize } from 'sequelize' 2 | 3 | class MyModel extends Model {} 4 | 5 | class AssociatedModel extends Model {} 6 | 7 | MyModel.findAll({ 8 | include: [ 9 | { 10 | model: AssociatedModel, 11 | where: { state: Sequelize.col('project.state') }, 12 | limit: 1, 13 | separate: true, 14 | order: [['id', 'DESC']], 15 | }, 16 | ], 17 | }) 18 | 19 | MyModel.findAll({ 20 | include: [{ all: true }], 21 | }) 22 | -------------------------------------------------------------------------------- /test/models/User.ts: -------------------------------------------------------------------------------- 1 | import { 2 | BelongsTo, 3 | BelongsToCreateAssociationMixin, 4 | BelongsToGetAssociationMixin, 5 | BelongsToSetAssociationMixin, 6 | DataTypes, 7 | FindOptions, 8 | Model, 9 | } from 'sequelize' 10 | import { sequelize } from '../connection' 11 | 12 | export class User extends Model { 13 | public static associations: { 14 | group: BelongsTo 15 | } 16 | 17 | public id: number 18 | public username: string 19 | public firstName: string 20 | public lastName: string 21 | public createdAt: Date 22 | public updatedAt: Date 23 | 24 | // mixins for association (optional) 25 | public groupId: number 26 | public group: UserGroup 27 | public getGroup: BelongsToGetAssociationMixin 28 | public setGroup: BelongsToSetAssociationMixin 29 | public createGroup: BelongsToCreateAssociationMixin 30 | } 31 | 32 | User.init( 33 | { 34 | username: DataTypes.STRING, 35 | firstName: DataTypes.STRING, 36 | lastName: DataTypes.STRING, 37 | }, 38 | { sequelize } 39 | ) 40 | 41 | // Hooks 42 | User.afterFind((users, options: FindOptions) => { 43 | console.log('found') 44 | }) 45 | 46 | // associate 47 | // it is important to import _after_ the model above is already exported so the circular reference works. 48 | import { UserGroup } from './UserGroup' 49 | export const Group = User.belongsTo(UserGroup, { as: 'group', foreignKey: 'groupId' }) 50 | -------------------------------------------------------------------------------- /test/models/UserGroup.ts: -------------------------------------------------------------------------------- 1 | import { 2 | DataTypes, 3 | HasMany, 4 | HasManyAddAssociationMixin, 5 | HasManyAddAssociationsMixin, 6 | HasManyCountAssociationsMixin, 7 | HasManyCreateAssociationMixin, 8 | HasManyGetAssociationsMixin, 9 | HasManyHasAssociationMixin, 10 | HasManyRemoveAssociationMixin, 11 | HasManyRemoveAssociationsMixin, 12 | HasManySetAssociationsMixin, 13 | Model, 14 | } from 'sequelize' 15 | import { sequelize } from '../connection' 16 | 17 | export class UserGroup extends Model { 18 | public static associations: { 19 | users: HasMany 20 | } 21 | 22 | public id: number 23 | public name: string 24 | 25 | // mixins for association (optional) 26 | public users: User[] 27 | public getUsers: HasManyGetAssociationsMixin 28 | public setUsers: HasManySetAssociationsMixin 29 | public addUser: HasManyAddAssociationMixin 30 | public addUsers: HasManyAddAssociationsMixin 31 | public createUser: HasManyCreateAssociationMixin 32 | public countUsers: HasManyCountAssociationsMixin 33 | public hasUser: HasManyHasAssociationMixin 34 | public removeUser: HasManyRemoveAssociationMixin 35 | public removeUsers: HasManyRemoveAssociationsMixin 36 | } 37 | 38 | // attach all the metadata to the model 39 | // instead of this, you could also use decorators 40 | UserGroup.init({ name: DataTypes.STRING }, { sequelize }) 41 | 42 | // associate 43 | // it is important to import _after_ the model above is already exported so the circular reference works. 44 | import { User } from './User' 45 | export const Users = UserGroup.hasMany(User, { as: 'users', foreignKey: 'groupId' }) 46 | -------------------------------------------------------------------------------- /test/promise.ts: -------------------------------------------------------------------------------- 1 | import { Promise } from 'sequelize' 2 | 3 | let promise: Promise = Promise.resolve(1) 4 | promise.then((arg: number) => ({})).then((a: {}) => void 0) 5 | 6 | promise = new Promise(resolve => resolve()) 7 | -------------------------------------------------------------------------------- /test/query-interface.ts: -------------------------------------------------------------------------------- 1 | import { DataTypes } from 'sequelize' 2 | import { QueryInterface } from 'sequelize/lib/query-interface' 3 | 4 | declare let queryInterface: QueryInterface 5 | 6 | queryInterface.createTable( 7 | 'nameOfTheNewTable', 8 | { 9 | id: { 10 | type: DataTypes.INTEGER, 11 | primaryKey: true, 12 | autoIncrement: true, 13 | }, 14 | createdAt: { 15 | type: DataTypes.DATE, 16 | }, 17 | updatedAt: { 18 | type: DataTypes.DATE, 19 | }, 20 | attr1: DataTypes.STRING, 21 | attr2: DataTypes.INTEGER, 22 | attr3: { 23 | type: DataTypes.BOOLEAN, 24 | defaultValue: false, 25 | allowNull: false, 26 | }, 27 | // foreign key usage 28 | attr4: { 29 | type: DataTypes.INTEGER, 30 | references: { 31 | model: 'another_table_name', 32 | key: 'id', 33 | }, 34 | onUpdate: 'cascade', 35 | onDelete: 'cascade', 36 | }, 37 | }, 38 | { 39 | engine: 'MYISAM', // default: 'InnoDB' 40 | collate: 'latin1_general_ci', 41 | charset: 'latin1', // default: null 42 | } 43 | ) 44 | 45 | queryInterface.dropTable('nameOfTheExistingTable') 46 | 47 | queryInterface.dropAllTables() 48 | 49 | queryInterface.renameTable('Person', 'User') 50 | 51 | queryInterface.showAllTables().then(tableNames => { 52 | // do nothing 53 | }) 54 | 55 | queryInterface.describeTable('Person').then(attributes => { 56 | /* 57 | attributes will be something like: 58 | 59 | { 60 | name: { 61 | type: 'VARCHAR(255)', // this will be 'CHARACTER VARYING' for pg! 62 | allowNull: true, 63 | defaultValue: null 64 | }, 65 | isBetaMember: { 66 | type: 'TINYINT(1)', // this will be 'BOOLEAN' for pg! 67 | allowNull: false, 68 | defaultValue: false 69 | } 70 | } 71 | */ 72 | }) 73 | 74 | queryInterface.addColumn('nameOfAnExistingTable', 'nameOfTheNewAttribute', DataTypes.STRING) 75 | 76 | // or 77 | 78 | queryInterface.addColumn( 79 | { tableName: 'nameOfAnExistingTable', schema: 'nameOfSchema' }, 80 | 'nameOfTheNewAttribute', 81 | DataTypes.STRING 82 | ) 83 | 84 | // or 85 | 86 | queryInterface.addColumn('nameOfAnExistingTable', 'nameOfTheNewAttribute', { 87 | type: DataTypes.STRING, 88 | allowNull: false, 89 | }) 90 | 91 | queryInterface.removeColumn('Person', 'signature') 92 | 93 | // or 94 | 95 | queryInterface.removeColumn({ tableName: 'Person', schema: 'nameOfSchema' }, 'signature') 96 | 97 | queryInterface.changeColumn('nameOfAnExistingTable', 'nameOfAnExistingAttribute', { 98 | type: DataTypes.FLOAT, 99 | allowNull: false, 100 | defaultValue: 0.0, 101 | }) 102 | 103 | // or 104 | 105 | queryInterface.changeColumn( 106 | { tableName: 'nameOfAnExistingTable', schema: 'nameOfSchema' }, 107 | 'nameOfAnExistingAttribute', 108 | { 109 | type: DataTypes.FLOAT, 110 | allowNull: false, 111 | defaultValue: 0.0, 112 | } 113 | ) 114 | 115 | queryInterface.renameColumn('Person', 'signature', 'sig') 116 | 117 | // This example will create the index person_firstname_lastname 118 | queryInterface.addIndex('Person', ['firstname', 'lastname']) 119 | 120 | // This example will create a unique index with the name SuperDuperIndex using the optional 'options' field. 121 | // Possible options: 122 | // - indicesType: UNIQUE|FULLTEXT|SPATIAL 123 | // - indexName: The name of the index. Default is __ 124 | // - parser: For FULLTEXT columns set your parser 125 | // - indexType: Set a type for the index, e.g. BTREE. See the documentation of the used dialect 126 | // - logging: A function that receives the sql query, e.g. console.log 127 | queryInterface.addIndex('Person', ['firstname', 'lastname'], { 128 | indexName: 'SuperDuperIndex', 129 | indicesType: 'UNIQUE', 130 | }) 131 | 132 | queryInterface.removeIndex('Person', 'SuperDuperIndex') 133 | 134 | // or 135 | 136 | queryInterface.removeIndex('Person', ['firstname', 'lastname']) 137 | 138 | queryInterface.addConstraint('Person', ['firstname', 'lastname'], { 139 | type: 'unique', 140 | name: 'firstnamexlastname', 141 | }) 142 | 143 | queryInterface.removeConstraint('Person', 'firstnamexlastname') 144 | -------------------------------------------------------------------------------- /test/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es6", 5 | "noEmit": true, 6 | "noImplicitAny": true, 7 | "noImplicitThis": true, 8 | "strictNullChecks": true, 9 | "strictFunctionTypes": true, 10 | "baseUrl": ".", 11 | "paths": { 12 | "sequelize": ["../"], 13 | "sequelize/*": ["../"] 14 | } 15 | }, 16 | "include": ["../index.d.ts", "./**/sequelize.d.ts", "./**/*.ts"] 17 | } 18 | -------------------------------------------------------------------------------- /test/usage.ts: -------------------------------------------------------------------------------- 1 | import { Group, User } from './models/User' 2 | 3 | async function test(): Promise { 4 | let user = await User.findOne({ include: [Group] }) 5 | if (!user) { 6 | return 7 | } 8 | User.update({}, { where: {} }) 9 | user.firstName = 'John' 10 | await user.save() 11 | await user.setGroup(2) 12 | 13 | user = new User() 14 | user = new User({ firstName: 'John' }) 15 | 16 | user = await User.findOne() 17 | 18 | const user2 = await User.create({ firstName: 'John', groupId: 1 }) 19 | await User.findAndCountAll({ distinct: true }) 20 | await User.findByPk(1) 21 | } 22 | -------------------------------------------------------------------------------- /test/where.ts: -------------------------------------------------------------------------------- 1 | import { AndOperator, fn, Model, Op, OrOperator, Sequelize, WhereOperators, WhereOptions } from 'sequelize' 2 | 3 | class MyModel extends Model { 4 | public hi: number 5 | } 6 | 7 | let where: WhereOptions 8 | 9 | // From http://docs.sequelizejs.com/en/v4/docs/querying/ 10 | 11 | // Operators 12 | 13 | const and: AndOperator = { 14 | $and: { a: 5 }, // AND (a = 5) 15 | } 16 | 17 | const or: OrOperator = { 18 | $or: [{ a: 5 }, { a: 6 }], // (a = 5 OR a = 6) 19 | } 20 | 21 | let operators: WhereOperators = { 22 | $gt: 6, // > 6 23 | $gte: 6, // >= 6 24 | $lt: 10, // < 10 25 | $lte: 10, // <= 10 26 | $ne: 20, // != 20 27 | $not: true, // IS NOT TRUE 28 | $between: [6, 10], // BETWEEN 6 AND 10 29 | $notBetween: [11, 15], // NOT BETWEEN 11 AND 15 30 | $in: [1, 2], // IN [1, 2] 31 | $notIn: [1, 2], // NOT IN [1, 2] 32 | $like: '%hat', // LIKE '%hat' 33 | $notLike: '%hat', // NOT LIKE '%hat' 34 | $iLike: '%hat', // ILIKE '%hat' (case insensitive) (PG only) 35 | $notILike: '%hat', // NOT ILIKE '%hat' (PG only) 36 | $overlap: [1, 2], // && [1, 2] (PG array overlap operator) 37 | $contains: [1, 2], // @> [1, 2] (PG array contains operator) 38 | $contained: [1, 2], // <@ [1, 2] (PG array contained by operator) 39 | $any: [2, 3], // ANY ARRAY[2, 3]::INTEGER (PG only) 40 | } 41 | 42 | operators = { 43 | $like: { $any: ['cat', 'hat'] }, // LIKE ANY ARRAY['cat', 'hat'] - also works for iLike and notLike 44 | } 45 | 46 | // Combinations 47 | 48 | MyModel.find({ where: or }) 49 | MyModel.find({ where: and }) 50 | 51 | where = Sequelize.and() 52 | 53 | where = Sequelize.or() 54 | 55 | where = { $and: [] } 56 | 57 | where = { 58 | rank: Sequelize.and({ $lt: 1000 }, { $eq: null }), 59 | } 60 | 61 | where = { 62 | rank: Sequelize.or({ $lt: 1000 }, { $eq: null }), 63 | } 64 | 65 | where = { 66 | rank: { 67 | $or: { 68 | $lt: 1000, 69 | $eq: null, 70 | }, 71 | }, 72 | } 73 | // rank < 1000 OR rank IS NULL 74 | 75 | where = { 76 | createdAt: { 77 | $lt: new Date(), 78 | $gt: new Date(Date.now() - 24 * 60 * 60 * 1000), 79 | }, 80 | } 81 | // createdAt < [timestamp] AND createdAt > [timestamp] 82 | 83 | where = { 84 | $or: [ 85 | { 86 | title: { 87 | $like: 'Boat%', 88 | }, 89 | }, 90 | { 91 | description: { 92 | $like: '%boat%', 93 | }, 94 | }, 95 | ], 96 | } 97 | // title LIKE 'Boat%' OR description LIKE '%boat%' 98 | 99 | // Containment 100 | 101 | where = { 102 | meta: { 103 | $contains: { 104 | site: { 105 | url: 'http://google.com', 106 | }, 107 | }, 108 | }, 109 | } 110 | 111 | // Relations / Associations 112 | // Find all projects with a least one task where task.state === project.task 113 | MyModel.findAll({ 114 | include: [ 115 | { 116 | model: MyModel, 117 | where: { state: Sequelize.col('project.state') }, 118 | }, 119 | ], 120 | }) 121 | 122 | MyModel.find({ 123 | where, 124 | include: [ 125 | { 126 | model: MyModel, 127 | where, 128 | include: [{ model: MyModel, where }], 129 | }, 130 | ], 131 | }) 132 | MyModel.destroy({ where }) 133 | MyModel.update({ hi: 1 }, { where }) 134 | 135 | // From http://docs.sequelizejs.com/en/v4/docs/models-usage/ 136 | 137 | // find multiple entries 138 | MyModel.findAll().then(projects => { 139 | // projects will be an array of all MyModel instances 140 | }) 141 | 142 | // also possible: 143 | MyModel.all().then(projects => { 144 | // projects will be an array of all MyModel instances 145 | }) 146 | 147 | // search for specific attributes - hash usage 148 | MyModel.findAll({ where: { name: 'A MyModel', enabled: true } }).then(projects => { 149 | // projects will be an array of MyModel instances with the specified name 150 | }) 151 | 152 | // search within a specific range 153 | MyModel.findAll({ where: { id: [1, 2, 3] } }).then(projects => { 154 | // projects will be an array of MyModels having the id 1, 2 or 3 155 | // this is actually doing an IN query 156 | }) 157 | 158 | MyModel.findAll({ 159 | where: { 160 | id: { 161 | // casting here to check a missing operator is not accepted as field name 162 | $and: { a: 5 }, // AND (a = 5) 163 | $or: [{ a: 5 }, { a: 6 }], // (a = 5 OR a = 6) 164 | $gt: 6, // id > 6 165 | $gte: 6, // id >= 6 166 | $lt: 10, // id < 10 167 | $lte: 10, // id <= 10 168 | $ne: 20, // id != 20 169 | $between: [6, 10], // BETWEEN 6 AND 10 170 | $notBetween: [11, 15], // NOT BETWEEN 11 AND 15 171 | $in: [1, 2], // IN [1, 2] 172 | $notIn: [1, 2], // NOT IN [1, 2] 173 | $like: '%hat', // LIKE '%hat' 174 | $notLike: '%hat', // NOT LIKE '%hat' 175 | $iLike: '%hat', // ILIKE '%hat' (case insensitive) (PG only) 176 | $notILike: '%hat', // NOT ILIKE '%hat' (PG only) 177 | $overlap: [1, 2], // && [1, 2] (PG array overlap operator) 178 | $contains: [1, 2], // @> [1, 2] (PG array contains operator) 179 | $contained: [1, 2], // <@ [1, 2] (PG array contained by operator) 180 | $any: [2, 3], // ANY ARRAY[2, 3]::INTEGER (PG only) 181 | } as WhereOperators, 182 | status: { 183 | $not: false, // status NOT FALSE 184 | }, 185 | }, 186 | }) 187 | 188 | // Complex filtering / NOT queries 189 | 190 | where = { 191 | name: 'a project', 192 | $or: [{ id: [1, 2, 3] }, { id: { $gt: 10 } }], 193 | } 194 | 195 | where = { 196 | name: 'a project', 197 | id: { 198 | $or: [[1, 2, 3], { $gt: 10 }], 199 | }, 200 | } 201 | 202 | where = { 203 | name: 'a project', 204 | type: { 205 | $and: [['a', 'b'], { $notLike: '%z' }], 206 | }, 207 | } 208 | 209 | // $not example: 210 | where = { 211 | name: 'a project', 212 | $not: [{ id: [1, 2, 3] }, { array: { $contains: [3, 4, 5] } }], 213 | } 214 | 215 | // JSONB 216 | 217 | // Nested object 218 | 219 | where = { 220 | meta: { 221 | video: { 222 | url: { 223 | $ne: null, 224 | }, 225 | }, 226 | }, 227 | } 228 | 229 | // Nested key 230 | where = { 231 | 'meta.audio.length': { 232 | $gt: 20, 233 | }, 234 | } 235 | 236 | // Operator symbols 237 | where = { 238 | [Op.and]: [{ id: [1, 2, 3] }, { array: { [Op.contains]: [3, 4, 5] } }], 239 | } 240 | 241 | // Fn as value 242 | where = { 243 | $gt: fn('NOW'), 244 | } 245 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "alwaysStrict": true, 4 | "noImplicitAny": true, 5 | "noImplicitThis": true, 6 | "strictNullChecks": true, 7 | "strictFunctionTypes": true, 8 | "module": "commonjs", 9 | "moduleResolution": "node", 10 | "noEmit": true, 11 | "lib": ["es2015", "es2015.collection", "dom"] 12 | }, 13 | "include": ["lib/**/*.d.ts", "index.d.ts"] 14 | } 15 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["tslint:recommended", "tslint-config-prettier"], 3 | "rules": { 4 | "array-type": [true, "array"], 5 | "ban-types": { 6 | "options": [ 7 | ["Object", "Avoid using the `Object` type. Did you mean `object`?"], 8 | ["Boolean", "Avoid using the `Boolean` type. Did you mean `boolean`?"], 9 | ["Number", "Avoid using the `Number` type. Did you mean `number`?"], 10 | ["String", "Avoid using the `String` type. Did you mean `string`?"], 11 | ["Symbol", "Avoid using the `Symbol` type. Did you mean `symbol`?"] 12 | ] 13 | }, 14 | "interface-name": false, 15 | "max-classes-per-file": false, 16 | "member-ordering": false, 17 | "no-console": false, 18 | "no-empty-interface": false, 19 | "object-literal-sort-keys": false, 20 | "unified-signatures": false, 21 | "variable-name": false 22 | } 23 | } 24 | --------------------------------------------------------------------------------