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

Commit 1d3714a2 by Simon Schick Committed by Sushant

chore: misc cleanup (#10483)

1 parent 24291467
......@@ -235,7 +235,7 @@ const sequelize = new Sequelize('database', 'username', 'password', {
### MSSQL
The library for MSSQL is`tedious@^1.7.0` You'll just need to define the dialect:
The library for MSSQL is`tedious@^3.0.0` You'll just need to define the dialect:
```js
const sequelize = new Sequelize('database', 'username', 'password', {
......
......@@ -132,6 +132,10 @@ class Association {
});
}
[Symbol.for('nodejs.util.inspect.custom')]() {
return this.as;
}
inspect() {
return this.as;
}
......
......@@ -96,7 +96,7 @@ module.exports = BaseTypes => {
if (!(this instanceof DATEONLY)) {
return new DATEONLY();
}
BaseTypes.DATEONLY.apply(this, arguments);
BaseTypes.DATEONLY.call(this);
}
inherits(DATEONLY, BaseTypes.DATEONLY);
......@@ -109,7 +109,7 @@ module.exports = BaseTypes => {
if (!(this instanceof UUID)) {
return new UUID();
}
BaseTypes.UUID.apply(this, arguments);
BaseTypes.UUID.call(this);
}
inherits(UUID, BaseTypes.UUID);
......@@ -156,7 +156,7 @@ module.exports = BaseTypes => {
if (!(this instanceof JSONTYPE)) {
return new JSONTYPE();
}
BaseTypes.JSON.apply(this, arguments);
BaseTypes.JSON.call(this);
}
inherits(JSONTYPE, BaseTypes.JSON);
......
......@@ -116,7 +116,7 @@ module.exports = BaseTypes => {
function BOOLEAN() {
if (!(this instanceof BOOLEAN)) return new BOOLEAN();
BaseTypes.BOOLEAN.apply(this, arguments);
BaseTypes.BOOLEAN.call(this);
}
inherits(BOOLEAN, BaseTypes.BOOLEAN);
......@@ -126,7 +126,7 @@ module.exports = BaseTypes => {
function UUID() {
if (!(this instanceof UUID)) return new UUID();
BaseTypes.UUID.apply(this, arguments);
BaseTypes.UUID.call(this);
}
inherits(UUID, BaseTypes.UUID);
......@@ -136,7 +136,7 @@ module.exports = BaseTypes => {
function NOW() {
if (!(this instanceof NOW)) return new NOW();
BaseTypes.NOW.apply(this, arguments);
BaseTypes.NOW.call(this);
}
inherits(NOW, BaseTypes.NOW);
......@@ -156,7 +156,7 @@ module.exports = BaseTypes => {
function DATEONLY() {
if (!(this instanceof DATEONLY)) return new DATEONLY();
BaseTypes.DATEONLY.apply(this, arguments);
BaseTypes.DATEONLY.call(this);
}
inherits(DATEONLY, BaseTypes.DATEONLY);
......
......@@ -94,7 +94,7 @@ module.exports = BaseTypes => {
function DATEONLY() {
if (!(this instanceof DATEONLY)) return new DATEONLY();
BaseTypes.DATEONLY.apply(this, arguments);
BaseTypes.DATEONLY.call(this);
}
inherits(DATEONLY, BaseTypes.DATEONLY);
......@@ -104,7 +104,7 @@ module.exports = BaseTypes => {
function UUID() {
if (!(this instanceof UUID)) return new UUID();
BaseTypes.UUID.apply(this, arguments);
BaseTypes.UUID.call(this);
}
inherits(UUID, BaseTypes.UUID);
......@@ -164,7 +164,7 @@ module.exports = BaseTypes => {
function JSONTYPE() {
if (!(this instanceof JSONTYPE)) return new JSONTYPE();
BaseTypes.JSON.apply(this, arguments);
BaseTypes.JSON.call(this);
}
inherits(JSONTYPE, BaseTypes.JSON);
......
......@@ -41,7 +41,7 @@ module.exports = BaseTypes => {
function DATEONLY() {
if (!(this instanceof DATEONLY)) return new DATEONLY();
BaseTypes.DATEONLY.apply(this, arguments);
BaseTypes.DATEONLY.call(this);
}
inherits(DATEONLY, BaseTypes.DATEONLY);
......@@ -134,7 +134,7 @@ module.exports = BaseTypes => {
function CITEXT() {
if (!(this instanceof CITEXT)) return new CITEXT();
BaseTypes.CITEXT.apply(this, arguments);
BaseTypes.CITEXT.call(this);
}
inherits(CITEXT, BaseTypes.CITEXT);
......@@ -159,7 +159,7 @@ module.exports = BaseTypes => {
function BOOLEAN() {
if (!(this instanceof BOOLEAN)) return new BOOLEAN();
BaseTypes.BOOLEAN.apply(this, arguments);
BaseTypes.BOOLEAN.call(this);
}
inherits(BOOLEAN, BaseTypes.BOOLEAN);
......
......@@ -47,7 +47,7 @@ module.exports = BaseTypes => {
function JSONTYPE() {
if (!(this instanceof JSONTYPE)) return new JSONTYPE();
BaseTypes.JSON.apply(this, arguments);
BaseTypes.JSON.call(this);
}
inherits(JSONTYPE, BaseTypes.JSON);
......@@ -71,7 +71,7 @@ module.exports = BaseTypes => {
function DATEONLY() {
if (!(this instanceof DATEONLY)) return new DATEONLY();
BaseTypes.DATEONLY.apply(this, arguments);
BaseTypes.DATEONLY.call(this);
}
inherits(DATEONLY, BaseTypes.DATEONLY);
......@@ -108,7 +108,7 @@ module.exports = BaseTypes => {
function CITEXT() {
if (!(this instanceof CITEXT)) return new CITEXT();
BaseTypes.CITEXT.apply(this, arguments);
BaseTypes.CITEXT.call(this);
}
inherits(CITEXT, BaseTypes.CITEXT);
......
......@@ -27,9 +27,7 @@ class ModelManager {
attribute: 'name'
});
const model = this.models.filter(model => model[options.attribute] === against);
return model ? model[0] : null;
return this.models.find(model => model[options.attribute] === against);
}
get all() {
......
......@@ -3068,6 +3068,10 @@ class Model {
this._defaultsOptions(options, scope);
}
static [Symbol.for('nodejs.util.inspect.custom')]() {
return this.name;
}
static inspect() {
return this.name;
}
......
......@@ -50,9 +50,9 @@
"devDependencies": {
"@commitlint/cli": "^7.3.2",
"@commitlint/config-angular": "^7.3.1",
"@types/bluebird": "^3.5.25",
"@types/node": "^10.12.18",
"@types/validator": "^9.4.4",
"@types/bluebird": "^3.5.26",
"@types/node": "^10.12.27",
"@types/validator": "^10.9.0",
"chai": "^4.x",
"chai-as-promised": "^7.x",
"chai-datetime": "^1.x",
......@@ -72,18 +72,18 @@
"lcov-result-merger": "^3.0.0",
"lint-staged": "^8.1.0",
"mariadb": "^2.0.3",
"mocha": "^5.x",
"mysql2": "^1.6.4",
"mocha": "^6.0.2",
"mysql2": "^1.6.5",
"nyc": "^13.3.0",
"pg": "^7.8.0",
"pg-hstore": "^2.x",
"pg-types": "^2.0.0",
"rimraf": "^2.x",
"sinon": "^6.3.5",
"rimraf": "^2.6.3",
"sinon": "^7.2.4",
"sinon-chai": "^3.2.0",
"sqlite3": "^4.0.6",
"tedious": "^3.0.1",
"typescript": "^3.2.2"
"typescript": "^3.3.3333"
},
"keywords": [
"mysql",
......@@ -121,7 +121,7 @@
"test-docker-integration": "env-cmd $npm_package_options_env_cmd npm run test-integration",
"docs": "esdoc && cp docs/ROUTER esdoc/ROUTER && cp docs/favicon.ico esdoc/favicon.ico",
"teaser": "node scripts/teaser",
"test-unit": "mocha --require scripts/mocha-bootload --globals setImmediate,clearImmediate --ui tdd --exit --check-leaks --colors -t 30000 --reporter spec \"test/unit/**/*.js\"",
"test-unit": "mocha --require scripts/mocha-bootload --globals setImmediate,clearImmediate --exit --check-leaks --colors -t 30000 --reporter spec \"test/unit/**/*.js\"",
"test-unit-mariadb": "cross-env DIALECT=mariadb npm run test-unit",
"test-unit-mysql": "cross-env DIALECT=mysql npm run test-unit",
"test-unit-postgres": "cross-env DIALECT=postgres npm run test-unit",
......@@ -129,7 +129,7 @@
"test-unit-sqlite": "cross-env DIALECT=sqlite npm run test-unit",
"test-unit-mssql": "cross-env DIALECT=mssql npm run test-unit",
"test-unit-all": "npm run test-unit-mariadb && npm run test-unit-mysql && npm run test-unit-postgres && npm run test-unit-postgres-native && npm run test-unit-mssql && npm run test-unit-sqlite",
"test-integration": "mocha --require scripts/mocha-bootload --globals setImmediate,clearImmediate --ui tdd --exit --check-leaks --colors -t 30000 --reporter spec \"test/integration/**/*.test.js\"",
"test-integration": "mocha --require scripts/mocha-bootload --globals setImmediate,clearImmediate --exit --check-leaks --colors -t 30000 --reporter spec \"test/integration/**/*.test.js\"",
"test-integration-mariadb": "cross-env DIALECT=mariadb npm run test-integration",
"test-integration-mysql": "cross-env DIALECT=mysql npm run test-integration",
"test-integration-postgres": "cross-env DIALECT=postgres npm run test-integration",
......@@ -148,8 +148,8 @@
"test-all": "npm run test-mariadb && npm run test-mysql && npm run test-sqlite && npm run test-postgres && npm run test-postgres-native && npm run test-mssql",
"test-typings": "tsc -b types/tsconfig.json && tsc -b types/test/tsconfig.json",
"cover": "rimraf coverage && npm run teaser && npm run cover-integration && npm run cover-unit && npm run merge-coverage",
"cover-integration": "cross-env COVERAGE=true nyc --reporter=lcovonly mocha --require scripts/mocha-bootload -t 30000 --exit --ui tdd \"test/integration/**/*.test.js\" && node -e \"require('fs').renameSync('coverage/lcov.info', 'coverage/integration.info')\"",
"cover-unit": "cross-env COVERAGE=true nyc --reporter=lcovonly mocha --require scripts/mocha-bootload -t 30000 --exit --ui tdd \"test/unit/**/*.test.js\" && node -e \"require('fs').renameSync('coverage/lcov.info', 'coverage/unit.info')\"",
"cover-integration": "cross-env COVERAGE=true nyc --reporter=lcovonly mocha --require scripts/mocha-bootload -t 30000 --exit \"test/integration/**/*.test.js\" && node -e \"require('fs').renameSync('coverage/lcov.info', 'coverage/integration.info')\"",
"cover-unit": "cross-env COVERAGE=true nyc --reporter=lcovonly mocha --require scripts/mocha-bootload -t 30000 --exit \"test/unit/**/*.test.js\" && node -e \"require('fs').renameSync('coverage/lcov.info', 'coverage/unit.info')\"",
"merge-coverage": "lcov-result-merger \"coverage/*.info\" \"coverage/lcov.info\"",
"sscce": "env-cmd $npm_package_options_env_cmd node sscce.js",
"sscce-mariadb": "cross-env DIALECT=mariadb npm run sscce",
......
......@@ -101,7 +101,7 @@ export interface AssociationScope {
/**
* The name of the column that will be used for the associated scope and it's value
*/
[scopeName: string]: any;
[scopeName: string]: unknown;
}
/**
......
import {
BulkCreateOptions,
CreateOptions,
Filterable,
FindOptions,
InstanceDestroyOptions,
InstanceUpdateOptions,
Model,
Transactionable,
WhereOptions,
BulkCreateOptions,
CreateOptions,
Filterable,
FindOptions,
InstanceDestroyOptions,
InstanceUpdateOptions,
Model,
Transactionable,
WhereOptions,
} from '../model';
import { Promise } from '../promise';
import { Transaction } from '../transaction';
......@@ -17,61 +17,61 @@ import { Association, AssociationScope, ForeignKeyOptions, ManyToManyOptions, Mu
* Used for a association table in n:m associations.
*/
export interface ThroughOptions {
/**
* The model used to join both sides of the N:M association.
*/
model: typeof Model;
/**
* The model used to join both sides of the N:M association.
*/
model: typeof Model;
/**
* A key/value set that will be used for association create and find defaults on the through model.
* (Remember to add the attributes to the through model)
*/
scope?: AssociationScope;
/**
* A key/value set that will be used for association create and find defaults on the through model.
* (Remember to add the attributes to the through model)
*/
scope?: AssociationScope;
/**
* If true a unique key will be generated from the foreign keys used (might want to turn this off and create
* specific unique keys when using scopes)
*
* @default true
*/
unique?: boolean;
/**
* If true a unique key will be generated from the foreign keys used (might want to turn this off and create
* specific unique keys when using scopes)
*
* @default true
*/
unique?: boolean;
}
/**
* Attributes for the join table
*/
export interface JoinTableAttributes {
[attribute: string]: any;
[attribute: string]: unknown;
}
/**
* Options provided when associating models with belongsToMany relationship
*/
export interface BelongsToManyOptions extends ManyToManyOptions {
/**
* The name of the table that is used to join source and target in n:m associations. Can also be a
* sequelize model if you want to define the junction table yourself and add extra attributes to it.
*/
through: typeof Model | string | ThroughOptions;
/**
* The name of the table that is used to join source and target in n:m associations. Can also be a
* sequelize model if you want to define the junction table yourself and add extra attributes to it.
*/
through: typeof Model | string | ThroughOptions;
/**
* The name of the foreign key in the join table (representing the target model) or an object representing
* the type definition for the other column (see `Sequelize.define` for syntax). When using an object, you
* can add a `name` property to set the name of the colum. Defaults to the name of target + primary key of
* target
*/
otherKey?: string | ForeignKeyOptions;
/**
* The name of the foreign key in the join table (representing the target model) or an object representing
* the type definition for the other column (see `Sequelize.define` for syntax). When using an object, you
* can add a `name` property to set the name of the colum. Defaults to the name of target + primary key of
* target
*/
otherKey?: string | ForeignKeyOptions;
/**
* Should the join model have timestamps
*/
timestamps?: boolean;
/**
* Should the join model have timestamps
*/
timestamps?: boolean;
}
export class BelongsToMany extends Association {
public otherKey: string;
public accessors: MultiAssociationAccessors;
constructor(source: typeof Model, target: typeof Model, options: BelongsToManyOptions);
public otherKey: string;
public accessors: MultiAssociationAccessors;
constructor(source: typeof Model, target: typeof Model, options: BelongsToManyOptions);
}
/**
......@@ -79,10 +79,10 @@ export class BelongsToMany extends Association {
* @see BelongsToManyGetAssociationsMixin
*/
export interface BelongsToManyGetAssociationsMixinOptions extends FindOptions {
/**
* Apply a scope on the related model, or remove its default scope by passing false.
*/
scope?: string | boolean;
/**
* Apply a scope on the related model, or remove its default scope by passing false.
*/
scope?: string | boolean;
}
/**
......@@ -94,16 +94,16 @@ export interface BelongsToManyGetAssociationsMixinOptions extends FindOptions {
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* getRoles: Sequelize.BelongsToManyGetAssociationsMixin<RoleInstance>;
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* getRoles: Sequelize.BelongsToManyGetAssociationsMixin<RoleInstance>;
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
......@@ -111,7 +111,7 @@ export interface BelongsToManyGetAssociationsMixinOptions extends FindOptions {
* @see Instance
*/
export type BelongsToManyGetAssociationsMixin<TModel> = (
options?: BelongsToManyGetAssociationsMixinOptions
options?: BelongsToManyGetAssociationsMixinOptions
) => Promise<TModel[]>;
/**
......@@ -119,11 +119,11 @@ export type BelongsToManyGetAssociationsMixin<TModel> = (
* @see BelongsToManySetAssociationsMixin
*/
export interface BelongsToManySetAssociationsMixinOptions
extends FindOptions,
BulkCreateOptions,
InstanceUpdateOptions,
InstanceDestroyOptions {
through?: JoinTableAttributes;
extends FindOptions,
BulkCreateOptions,
InstanceUpdateOptions,
InstanceDestroyOptions {
through?: JoinTableAttributes;
}
/**
......@@ -135,16 +135,16 @@ export interface BelongsToManySetAssociationsMixinOptions
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* setRoles: Sequelize.BelongsToManySetAssociationsMixin<RoleInstance, RoleId, UserRoleAttributes>;
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* // getRoles...
* setRoles: Sequelize.BelongsToManySetAssociationsMixin<RoleInstance, RoleId, UserRoleAttributes>;
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
......@@ -152,8 +152,8 @@ export interface BelongsToManySetAssociationsMixinOptions
* @see Instance
*/
export type BelongsToManySetAssociationsMixin<TModel, TModelPrimaryKey> = (
newAssociations?: (TModel | TModelPrimaryKey)[],
options?: BelongsToManySetAssociationsMixinOptions
newAssociations?: (TModel | TModelPrimaryKey)[],
options?: BelongsToManySetAssociationsMixinOptions
) => Promise<void>;
/**
......@@ -161,11 +161,11 @@ export type BelongsToManySetAssociationsMixin<TModel, TModelPrimaryKey> = (
* @see BelongsToManyAddAssociationsMixin
*/
export interface BelongsToManyAddAssociationsMixinOptions
extends FindOptions,
BulkCreateOptions,
InstanceUpdateOptions,
InstanceDestroyOptions {
through?: JoinTableAttributes;
extends FindOptions,
BulkCreateOptions,
InstanceUpdateOptions,
InstanceDestroyOptions {
through?: JoinTableAttributes;
}
/**
......@@ -177,16 +177,16 @@ export interface BelongsToManyAddAssociationsMixinOptions
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* addRoles: Sequelize.BelongsToManyAddAssociationsMixin<RoleInstance, RoleId, UserRoleAttributes>;
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* // getRoles...
* // setRoles...
* addRoles: Sequelize.BelongsToManyAddAssociationsMixin<RoleInstance, RoleId, UserRoleAttributes>;
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
......@@ -194,8 +194,8 @@ export interface BelongsToManyAddAssociationsMixinOptions
* @see Instance
*/
export type BelongsToManyAddAssociationsMixin<TModel, TModelPrimaryKey> = (
newAssociations?: (TModel | TModelPrimaryKey)[],
options?: BelongsToManyAddAssociationsMixinOptions
newAssociations?: (TModel | TModelPrimaryKey)[],
options?: BelongsToManyAddAssociationsMixinOptions
) => Promise<void>;
/**
......@@ -203,11 +203,11 @@ export type BelongsToManyAddAssociationsMixin<TModel, TModelPrimaryKey> = (
* @see BelongsToManyAddAssociationMixin
*/
export interface BelongsToManyAddAssociationMixinOptions
extends FindOptions,
BulkCreateOptions,
InstanceUpdateOptions,
InstanceDestroyOptions {
through?: JoinTableAttributes;
extends FindOptions,
BulkCreateOptions,
InstanceUpdateOptions,
InstanceDestroyOptions {
through?: JoinTableAttributes;
}
/**
......@@ -219,16 +219,16 @@ export interface BelongsToManyAddAssociationMixinOptions
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* addRole: Sequelize.BelongsToManyAddAssociationMixin<RoleInstance, RoleId, UserRoleAttributes>;
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* // getRoles...
* // setRoles...
* // addRoles...
* addRole: Sequelize.BelongsToManyAddAssociationMixin<RoleInstance, RoleId, UserRoleAttributes>;
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
......@@ -236,8 +236,8 @@ export interface BelongsToManyAddAssociationMixinOptions
* @see Instance
*/
export type BelongsToManyAddAssociationMixin<TModel, TModelPrimaryKey> = (
newAssociation?: TModel | TModelPrimaryKey,
options?: BelongsToManyAddAssociationMixinOptions
newAssociation?: TModel | TModelPrimaryKey,
options?: BelongsToManyAddAssociationMixinOptions
) => Promise<void>;
/**
......@@ -245,7 +245,7 @@ export type BelongsToManyAddAssociationMixin<TModel, TModelPrimaryKey> = (
* @see BelongsToManyCreateAssociationMixin
*/
export interface BelongsToManyCreateAssociationMixinOptions extends CreateOptions {
through?: JoinTableAttributes;
through?: JoinTableAttributes;
}
/**
* The createAssociation mixin applied to models with belongsToMany.
......@@ -256,16 +256,16 @@ export interface BelongsToManyCreateAssociationMixinOptions extends CreateOption
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* createRole: Sequelize.BelongsToManyCreateAssociationMixin<RoleAttributes, UserRoleAttributes>;
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* createRole: Sequelize.BelongsToManyCreateAssociationMixin<RoleAttributes, UserRoleAttributes>;
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
......@@ -273,8 +273,8 @@ export interface BelongsToManyCreateAssociationMixinOptions extends CreateOption
* @see Instance
*/
export type BelongsToManyCreateAssociationMixin<TModel> = (
values?: { [attribute: string]: any },
options?: BelongsToManyCreateAssociationMixinOptions
values?: { [attribute: string]: unknown },
options?: BelongsToManyCreateAssociationMixinOptions
) => Promise<TModel>;
/**
......@@ -292,16 +292,16 @@ export interface BelongsToManyRemoveAssociationMixinOptions extends InstanceDest
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* removeRole: Sequelize.BelongsToManyRemoveAssociationMixin<RoleInstance, RoleId>;
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* removeRole: Sequelize.BelongsToManyRemoveAssociationMixin<RoleInstance, RoleId>;
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
......@@ -309,8 +309,8 @@ export interface BelongsToManyRemoveAssociationMixinOptions extends InstanceDest
* @see Instance
*/
export type BelongsToManyRemoveAssociationMixin<TModel, TModelPrimaryKey> = (
oldAssociated?: TModel | TModelPrimaryKey,
options?: BelongsToManyRemoveAssociationMixinOptions
oldAssociated?: TModel | TModelPrimaryKey,
options?: BelongsToManyRemoveAssociationMixinOptions
) => Promise<void>;
/**
......@@ -328,16 +328,16 @@ export interface BelongsToManyRemoveAssociationsMixinOptions extends InstanceDes
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* removeRoles: Sequelize.BelongsToManyRemoveAssociationsMixin<RoleInstance, RoleId>;
* // hasRole...
* // hasRoles...
* // countRoles...
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* removeRoles: Sequelize.BelongsToManyRemoveAssociationsMixin<RoleInstance, RoleId>;
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
......@@ -345,8 +345,8 @@ export interface BelongsToManyRemoveAssociationsMixinOptions extends InstanceDes
* @see Instance
*/
export type BelongsToManyRemoveAssociationsMixin<TModel, TModelPrimaryKey> = (
oldAssociateds?: (TModel | TModelPrimaryKey)[],
options?: BelongsToManyRemoveAssociationsMixinOptions
oldAssociateds?: (TModel | TModelPrimaryKey)[],
options?: BelongsToManyRemoveAssociationsMixinOptions
) => Promise<void>;
/**
......@@ -364,16 +364,16 @@ export interface BelongsToManyHasAssociationMixinOptions extends BelongsToManyGe
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* hasRole: Sequelize.BelongsToManyHasAssociationMixin<RoleInstance, RoleId>;
* // hasRoles...
* // countRoles...
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* hasRole: Sequelize.BelongsToManyHasAssociationMixin<RoleInstance, RoleId>;
* // hasRoles...
* // countRoles...
* }
* ```
*
......@@ -381,8 +381,8 @@ export interface BelongsToManyHasAssociationMixinOptions extends BelongsToManyGe
* @see Instance
*/
export type BelongsToManyHasAssociationMixin<TModel, TModelPrimaryKey> = (
target: TModel | TModelPrimaryKey,
options?: BelongsToManyHasAssociationMixinOptions
target: TModel | TModelPrimaryKey,
options?: BelongsToManyHasAssociationMixinOptions
) => Promise<boolean>;
/**
......@@ -400,16 +400,16 @@ export interface BelongsToManyHasAssociationsMixinOptions extends BelongsToManyG
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles
* // hasRole...
* hasRoles: Sequelize.BelongsToManyHasAssociationsMixin<RoleInstance, RoleId>;
* // countRoles...
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles
* // hasRole...
* hasRoles: Sequelize.BelongsToManyHasAssociationsMixin<RoleInstance, RoleId>;
* // countRoles...
* }
* ```
*
......@@ -417,8 +417,8 @@ export interface BelongsToManyHasAssociationsMixinOptions extends BelongsToManyG
* @see Instance
*/
export type BelongsToManyHasAssociationsMixin<TModel, TModelPrimaryKey> = (
targets: (TModel | TModelPrimaryKey)[],
options?: BelongsToManyHasAssociationsMixinOptions
targets: (TModel | TModelPrimaryKey)[],
options?: BelongsToManyHasAssociationsMixinOptions
) => Promise<boolean>;
/**
......@@ -426,10 +426,10 @@ export type BelongsToManyHasAssociationsMixin<TModel, TModelPrimaryKey> = (
* @see BelongsToManyCountAssociationsMixin
*/
export interface BelongsToManyCountAssociationsMixinOptions extends Transactionable, Filterable {
/**
* Apply a scope on the related model, or remove its default scope by passing false.
*/
scope?: string | boolean;
/**
* Apply a scope on the related model, or remove its default scope by passing false.
*/
scope?: string | boolean;
}
/**
......@@ -441,16 +441,16 @@ export interface BelongsToManyCountAssociationsMixinOptions extends Transactiona
* User.belongsToMany(Role, { through: UserRole });
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* countRoles: Sequelize.BelongsToManyCountAssociationsMixin;
* // getRoles...
* // setRoles...
* // addRoles...
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* countRoles: Sequelize.BelongsToManyCountAssociationsMixin;
* }
* ```
*
......@@ -458,5 +458,5 @@ export interface BelongsToManyCountAssociationsMixinOptions extends Transactiona
* @see Instance
*/
export type BelongsToManyCountAssociationsMixin = (
options?: BelongsToManyCountAssociationsMixinOptions
options?: BelongsToManyCountAssociationsMixinOptions
) => Promise<number>;
......@@ -116,7 +116,7 @@ export interface BelongsToCreateAssociationMixinOptions extends CreateOptions, B
* @see Instance
*/
export type BelongsToCreateAssociationMixin<TModel> = (
values?: { [attribute: string]: any },
values?: { [attribute: string]: unknown },
options?: BelongsToCreateAssociationMixinOptions
) => Promise<TModel>;
......
......@@ -205,7 +205,7 @@ export interface HasManyCreateAssociationMixinOptions extends CreateOptions {}
* @see Instance
*/
export type HasManyCreateAssociationMixin<TModel> = (
values?: { [attribute: string]: any },
values?: { [attribute: string]: unknown },
options?: HasManyCreateAssociationMixinOptions
) => Promise<TModel>;
......
......@@ -108,6 +108,6 @@ export interface HasOneCreateAssociationMixinOptions extends HasOneSetAssociatio
* @see Instance
*/
export type HasOneCreateAssociationMixin<TModel> = (
values?: { [attribute: string]: any },
values?: { [attribute: string]: unknown },
options?: HasOneCreateAssociationMixinOptions
) => Promise<TModel>;
......@@ -78,7 +78,7 @@ interface StringDataTypeConstructor extends AbstractDataTypeConstructor {
export interface StringDataType extends AbstractDataType {
options?: StringDataTypeOptions;
BINARY: this;
validate(value: any): boolean;
validate(value: unknown): boolean;
}
export interface StringDataTypeOptions {
......@@ -119,7 +119,7 @@ interface TextDataTypeConstructor extends AbstractDataTypeConstructor {
export interface TextDataType extends AbstractDataType {
options: TextDataTypeOptions;
validate(value: any): boolean;
validate(value: unknown): boolean;
}
export interface TextDataTypeOptions {
......@@ -134,14 +134,14 @@ interface NumberDataTypeConstructor extends AbstractDataTypeConstructor {
ZEROFILL: this;
new (options?: NumberDataTypeOptions): NumberDataType;
(options?: NumberDataTypeOptions): NumberDataType;
validate(value: any): boolean;
validate(value: unknown): boolean;
}
export interface NumberDataType extends AbstractDataType {
options: NumberDataTypeOptions;
UNSIGNED: this;
ZEROFILL: this;
validate(value: any): boolean;
validate(value: unknown): boolean;
}
export interface NumberDataTypeOptions {
......@@ -297,9 +297,9 @@ export const TIME: AbstractDataTypeConstructor;
export const DATE: DateDataTypeConstructor;
interface DateDataTypeConstructor extends AbstractDataTypeConstructor {
new (length?: any): DateDataType;
new (length?: string | number): DateDataType;
new (options?: DateDataTypeOptions): DateDataType;
(length?: any): DateDataType;
(length?: string | number): DateDataType;
(options?: DateDataTypeOptions): DateDataType;
}
......@@ -308,7 +308,7 @@ export interface DateDataType extends AbstractDataTypeConstructor {
}
export interface DateDataTypeOptions {
length?: any;
length?: string | number;
}
/**
......@@ -317,19 +317,13 @@ export interface DateDataTypeOptions {
export const DATEONLY: DateOnlyDataTypeConstructor;
interface DateOnlyDataTypeConstructor extends AbstractDataTypeConstructor {
new (length: any): DateOnlyDataType;
new (options: DateOnlyDataTypeOptions): DateOnlyDataType;
(length: any): DateOnlyDataType;
(options: DateOnlyDataTypeOptions): DateOnlyDataType;
new (): DateOnlyDataType;
(): DateOnlyDataType;
}
export interface DateOnlyDataType extends AbstractDataType {
options: DateOnlyDataTypeOptions;
}
export interface DateOnlyDataTypeOptions {
length?: any;
}
/**
* A key / value column. Only available in postgres.
......@@ -510,7 +504,7 @@ interface ArrayDataTypeConstructor extends AbstractDataTypeConstructor {
new <T extends AbstractDataTypeConstructor | AbstractDataType>(options: ArrayDataTypeOptions<T>): ArrayDataType<T>;
<T extends AbstractDataTypeConstructor | AbstractDataType>(type: T): ArrayDataType<T>;
<T extends AbstractDataTypeConstructor | AbstractDataType>(options: ArrayDataTypeOptions<T>): ArrayDataType<T>;
is<T extends AbstractDataTypeConstructor | AbstractDataType>(obj: any, type: T): obj is ArrayDataType<T>;
is<T extends AbstractDataTypeConstructor | AbstractDataType>(obj: unknown, type: T): obj is ArrayDataType<T>;
}
export interface ArrayDataType<T extends AbstractDataTypeConstructor | AbstractDataType> extends AbstractDataType {
......
......@@ -93,7 +93,7 @@ export interface UniqueConstraintErrorOptions {
parent?: Error;
message?: string;
errors?: ValidationErrorItem[];
fields?: { [key: string]: any };
fields?: { [key: string]: unknown };
original?: Error;
}
......@@ -104,7 +104,7 @@ export class UniqueConstraintError extends ValidationError implements CommonErro
public readonly parent: Error;
public readonly original: Error;
public readonly sql: string;
public readonly fields: { [key: string]: any };
public readonly fields: { [key: string]: unknown };
constructor(options?: UniqueConstraintErrorOptions);
}
......@@ -114,7 +114,7 @@ export class UniqueConstraintError extends ValidationError implements CommonErro
export class ForeignKeyConstraintError extends DatabaseError {
public table: string;
public fields: { [field: string]: string };
public value: any;
public value: unknown;
public index: string;
constructor(options: { parent?: Error; message?: string; index?: string; fields?: string[]; table?: string });
}
......
......@@ -54,7 +54,7 @@ export interface AllModelHooks extends ModelHookOptions {
export interface SequelizeHooks extends AllModelHooks {
beforeConnect(config: Config): HookReturn;
afterConnect(connection: any, config: Config): HookReturn;
afterConnect(connection: unknown, config: Config): HookReturn;
}
/**
......
......@@ -9,7 +9,7 @@ export class ModelManager {
constructor(sequelize: Sequelize);
public addModel<T extends typeof Model>(model: T): T;
public removeModel(model: typeof Model): void;
public getModel(against: any, options?: { attribute?: string }): typeof Model;
public getModel(against: unknown, options?: { attribute?: string }): typeof Model;
}
export default ModelManager;
......@@ -105,7 +105,7 @@ export interface ScopeOptions {
* any arguments, or an array, where the first element is the name of the method, and consecutive elements
* are arguments to that method. Pass null to remove all scopes, including the default.
*/
method: string | any[];
method: string | [string, ...unknown[]];
}
/**
......@@ -199,14 +199,14 @@ export interface WhereOperators {
*
* Example: `[Op.contains]: [1, 2]` becomes `@> [1, 2]`
*/
[Op.contains]?: any[];
[Op.contains]?: [number, number] | [Date, Date];
/**
* PG array contained by operator
*
* Example: `[Op.contained]: [1, 2]` becomes `<@ [1, 2]`
*/
[Op.contained]?: any[];
[Op.contained]?: [number, number] | [Date, Date];
/** Example: `[Op.gt]: 6,` becomes `> 6` */
[Op.gt]?: number | string | Date;
......@@ -283,11 +283,11 @@ export interface WhereAttributeHash {
* - A simple attribute name
* - A nested key for JSON columns
*
* {
* "meta.audio.length": {
* [Op.gt]: 20
* }
* }
* {
* "meta.audio.length": {
* [Op.gt]: 20
* }
* }
*/
[field: string]: WhereValue | WhereOptions;
}
......@@ -322,6 +322,11 @@ export interface IncludeOptions extends Filterable, Projectable {
association?: Association;
/**
* Custom `on` clause, overrides default.
*/
on?: WhereOptions;
/**
* Note that this converts the eager load to an inner join,
* unless you explicitly set `required: false`
*/
......@@ -830,7 +835,7 @@ export interface SaveOptions extends Logging, Transactionable, Silent {
export interface ModelValidateOptions {
/**
* is: ["^[a-z]+$",'i'] // will only allow letters
* is: /^[a-z]+[Op./i] // same as the previous example using real RegExp
* is: /^[a-z]+[Op./i] // same as the previous example using real RegExp
*/
is?: string | (string | RegExp)[] | RegExp | { msg: string; args: string | (string | RegExp)[] | RegExp };
......@@ -997,14 +1002,14 @@ export interface ModelValidateOptions {
* We can't enforce any other method to be a function, so :
*
* ```typescript
* [name: string] : ( value : any ) => boolean;
* [name: string] : ( value : unknown ) => boolean;
* ```
*
* doesn't work in combination with the properties above
*
* @see https://github.com/Microsoft/TypeScript/issues/1889
*/
[name: string]: any;
[name: string]: unknown;
}
/**
......@@ -1069,14 +1074,14 @@ export interface ModelNameOptions {
* Interface for getterMethods in DefineOptions
*/
export interface ModelGetterOptions {
[name: string]: () => any;
[name: string]: (this: Model) => unknown;
}
/**
* Interface for setterMethods in DefineOptions
*/
export interface ModelSetterOptions {
[name: string]: (val: any) => void;
[name: string]: (this: Model, val: any) => void;
}
/**
......@@ -1107,7 +1112,7 @@ export interface ColumnOptions {
/**
* A literal default value, a JavaScript function, or an SQL function (see `sequelize.fn`)
*/
defaultValue?: any;
defaultValue?: unknown;
}
/**
......@@ -1197,10 +1202,10 @@ export interface ModelAttributeColumnOptions extends ColumnOptions {
*
* ```js
* sequelize.define('model', {
* states: {
* type: Sequelize.ENUM,
* values: ['active', 'pending', 'deleted']
* }
* states: {
* type: Sequelize.ENUM,
* values: ['active', 'pending', 'deleted']
* }
* })
* ```
*/
......@@ -1210,13 +1215,13 @@ export interface ModelAttributeColumnOptions extends ColumnOptions {
* Provide a custom getter for this column. Use `this.getDataValue(String)` to manipulate the underlying
* values.
*/
get?(): any;
get?(): unknown;
/**
* Provide a custom setter for this column. Use `this.setDataValue(String, Value)` to manipulate the
* underlying values.
*/
set?(val: any): void;
set?(val: unknown): void;
}
/**
......@@ -1351,6 +1356,16 @@ export interface ModelOptions<M extends Model = Model> {
* accepts an optional error.
*/
validate?: ModelValidateOptions;
/**
* Allows defining additional setters that will be available on model instances.
*/
setterMethods?: ModelSetterOptions;
/**
* Allows defining additional getters that will be available on model instances.
*/
getterMethods?: ModelGetterOptions;
}
/**
......@@ -1375,47 +1390,54 @@ export interface AddScopeOptions {
export abstract class Model<T = any, T2 = any> extends Hooks {
/** The name of the database table */
public static tableName: string;
public static readonly tableName: string;
/**
* The name of the primary key attribute
*/
public static primaryKeyAttribute: string;
public static readonly primaryKeyAttribute: string;
/**
* An object hash from alias to association object
*/
public static associations: any;
public static readonly associations: {
[key: string]: Association;
};
/**
* The options that the model was initialized with
*/
public static options: InitOptions;
public static readonly options: InitOptions;
/**
* The attributes of the model
*/
public static rawAttributes: { [attribute: string]: ModelAttributeColumnOptions };
public static readonly rawAttributes: { [attribute: string]: ModelAttributeColumnOptions };
/**
* Reference to the sequelize instance the model was initialized with
*/
public static readonly sequelize?: Sequelize;
/**
* Initialize a model, representing a table in the DB, with attributes and options.
*
* The table columns are defined by the hash that is given as the second argument. Each attribute of the hash represents a column. A short table definition might look like this:
*
* The table columns are define by the hash that is given as the second argument. Each attribute of the hash represents a column. A short table definition might look like this:
*
* ```js
* Project.init({
* columnA: {
* type: Sequelize.BOOLEAN,
* validate: {
* is: ['[a-z]','i'], // will only allow letters
* max: 23, // only allow values <= 23
* isIn: {
* args: [['en', 'zh']],
* msg: "Must be English or Chinese"
* }
* },
* field: 'column_a'
* // Other attributes here
* type: Sequelize.BOOLEAN,
* validate: {
* is: ['[a-z]','i'], // will only allow letters
* max: 23, // only allow values <= 23
* isIn: {
* args: [['en', 'zh']],
* msg: "Must be English or Chinese"
* }
* },
* field: 'column_a'
* // Other attributes here
* },
* columnB: Sequelize.STRING,
* columnC: 'MY VERY OWN COLUMN TYPE'
......@@ -1481,9 +1503,9 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
* if the model has no schema, or an object with `tableName`, `schema` and `delimiter` properties.
*
* @param options The hash of options from any query. You can use one model to access tables with matching
* schemas by overriding `getTableName` and using custom key/values to alter the name of the table.
* (eg.
* subscribers_1, subscribers_2)
* schemas by overriding `getTableName` and using custom key/values to alter the name of the table.
* (eg.
* subscribers_1, subscribers_2)
*/
public static getTableName(): string | {
tableName: string;
......@@ -1496,29 +1518,29 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
* ```js
* var Model = sequelize.define('model', attributes, {
* defaultScope: {
* where: {
* username: 'dan'
* },
* limit: 12
* },
* scopes: {
* isALie: {
* where: {
* stuff: 'cake'
* }
* username: 'dan'
* },
* limit: 12
* },
* complexFunction: function(email, accessLevel) {
* return {
* where: {
* email: {
* [Op.like]: email
* },
* accesss_level {
* [Op.gte]: accessLevel
* scopes: {
* isALie: {
* where: {
* stuff: 'cake'
* }
* },
* complexFunction: function(email, accessLevel) {
* return {
* where: {
* email: {
* [Op.like]: email
* },
* accesss_level {
* [Op.gte]: accessLevel
* }
* }
* }
* }
* }
* }
* }
* })
* ```
......@@ -1536,7 +1558,7 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
* ```
*
* @return Model A reference to the model, with the scope(s) applied. Calling scope again on the returned
* model will clear the previous scope.
* model will clear the previous scope.
*/
public static scope<M extends { new (): Model }>(
this: M,
......@@ -1552,8 +1574,8 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
* ```js
* Model.findAll({
* where: {
* attr1: 42,
* attr2: 'cake'
* attr1: 42,
* attr2: 'cake'
* }
* })
* ```
......@@ -1566,18 +1588,18 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
*
* Model.findAll({
* where: {
* attr1: {
* gt: 50
* },
* attr2: {
* lte: 45
* },
* attr3: {
* in: [1,2,3]
* },
* attr4: {
* ne: 5
* }
* attr1: {
* gt: 50
* },
* attr2: {
* lte: 45
* },
* attr3: {
* in: [1,2,3]
* },
* attr4: {
* ne: 5
* }
* }
* })
* ```
......@@ -1591,11 +1613,11 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
* ```js
* Model.findAll({
* where: Sequelize.and(
* { name: 'a project' },
* Sequelize.or(
* { id: [1,2,3] },
* { id: { gt: 10 } }
* )
* { name: 'a project' },
* Sequelize.or(
* { id: [1,2,3] },
* { id: { gt: 10 } }
* )
* )
* })
* ```
......@@ -1641,7 +1663,7 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
* @param aggregateFunction The function to use for aggregation, e.g. sum, max etc.
* @param options Query options. See sequelize.query for full options
* @return Returns the aggregate result cast to `options.dataType`, unless `options.plain` is false, in
* which case the complete data result is returned.
* which case the complete data result is returned.
*/
public static aggregate<M extends Model, T extends DataType | unknown>(
this: { new (): M } & typeof Model,
......@@ -1682,7 +1704,7 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
* ```js
* User.findAndCountAll({
* include: [
* { model: Profile, required: true}
* { model: Profile, required: true}
* ],
* limit 3
* });
......@@ -2370,7 +2392,7 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
* @param options.plain If set to true, included instances will be returned as plain objects
*/
public get(options?: { plain?: boolean; clone?: boolean }): object;
public get(key: string, options?: { plain?: boolean; clone?: boolean }): any;
public get(key: string, options?: { plain?: boolean; clone?: boolean }): unknown;
public get<K extends keyof this>(key: K, options?: { plain?: boolean; clone?: boolean }): this[K];
/**
......@@ -2477,13 +2499,13 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
* instance.increment('number') // increment number by 1
* instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2
* instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42, and tries by 1.
* // `by` is ignored, since each column has its own
* // value
* // `by` is ignored, since each column has its own
* // value
* ```
*
* @param fields If a string is provided, that column is incremented by the value of `by` given in options.
* If an array is provided, the same is true for each column.
* If and object is provided, each column is incremented by the value given.
* If an array is provided, the same is true for each column.
* If and object is provided, each column is incremented by the value given.
*/
public increment<K extends keyof this>(
fields: K | K[] | Partial<this>,
......@@ -2502,13 +2524,13 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
* instance.decrement('number') // decrement number by 1
* instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2
* instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42, and tries by 1.
* // `by` is ignored, since each column has its own
* // value
* // `by` is ignored, since each column has its own
* // value
* ```
*
* @param fields If a string is provided, that column is decremented by the value of `by` given in options.
* If an array is provided, the same is true for each column.
* If and object is provided, each column is decremented by the value given
* If an array is provided, the same is true for each column.
* If and object is provided, each column is decremented by the value given
*/
public decrement<K extends keyof this>(
fields: K | K[] | Partial<this>,
......
import { DataType } from './data-types';
import { Logging, Model, ModelAttributeColumnOptions, ModelAttributes, Transactionable, WhereOptions } from './model';
import { Logging, Model, ModelAttributeColumnOptions, ModelAttributes, Transactionable, WhereOptions, Filterable } from './model';
import { Promise } from './promise';
import QueryTypes = require('./query-types');
import { Sequelize } from './sequelize';
......@@ -57,6 +57,10 @@ export interface QueryOptions extends Logging, Transactionable {
instance?: Model;
}
export interface QueryOptionsWithWhere extends QueryOptions, Filterable {
}
export interface QueryOptionsWithModel {
/**
* A sequelize model used to build the returned model instances (used to be called callee)
......@@ -73,9 +77,9 @@ export interface QueryOptionsWithType<T extends QueryTypes> extends QueryOptions
}
/**
* Most of the methods accept options and use only the logger property of the options. That's why the most used
* interface type for options in a method is separated here as another interface.
*/
* Most of the methods accept options and use only the logger property of the options. That's why the most used
* interface type for options in a method is separated here as another interface.
*/
export interface QueryInterfaceOptions extends Logging, Transactionable {}
export interface CollateCharsetOptions {
......@@ -126,7 +130,7 @@ export interface AddUniqueConstraintOptions {
export interface AddDefaultConstraintOptions {
type: 'default';
name?: string;
defaultValue?: any;
defaultValue?: unknown;
}
export interface AddCheckConstraintOptions {
......@@ -152,29 +156,35 @@ export interface AddForeignKeyConstraintOptions {
}
export type AddConstraintOptions =
| AddUniqueConstraintOptions
| AddDefaultConstraintOptions
| AddCheckConstraintOptions
| AddPrimaryKeyConstraintOptions
| AddForeignKeyConstraintOptions;
| AddUniqueConstraintOptions
| AddDefaultConstraintOptions
| AddCheckConstraintOptions
| AddPrimaryKeyConstraintOptions
| AddForeignKeyConstraintOptions;
export interface CreateDatabaseOptions extends CollateCharsetOptions, QueryOptions {
encoding?: string;
}
export interface FunctionParam {
type: string;
name?: string;
direction?: string;
}
/**
* The interface that Sequelize uses to talk to all databases.
*
* This interface is available through sequelize.QueryInterface. It should not be commonly used, but it's
* referenced anyway, so it can be used.
*/
* The interface that Sequelize uses to talk to all databases.
*
* This interface is available through sequelize.QueryInterface. It should not be commonly used, but it's
* referenced anyway, so it can be used.
*/
export class QueryInterface {
/**
* Returns the dialect-specific sql generator.
*
* We don't have a definition for the QueryGenerator, because I doubt it is commonly in use separately.
*/
public QueryGenerator: any;
public QueryGenerator: unknown;
/**
* Returns the current sequelize instance.
......@@ -217,9 +227,9 @@ export class QueryInterface {
/**
* Creates a table with specified attributes.
*
* @param tableName Name of table to create
* @param attributes Hash of attributes, key is attribute name, value is data type
* @param options Table options.
* @param tableName Name of table to create
* @param attributes Hash of attributes, key is attribute name, value is data type
* @param options Table options.
*/
public createTable(
tableName: string | { schema?: string; tableName?: string },
......@@ -389,7 +399,7 @@ export class QueryInterface {
instance: Model,
tableName: string,
values: object,
identifier: object,
identifier: WhereOptions,
options?: QueryOptions
): Promise<object>;
......@@ -399,7 +409,7 @@ export class QueryInterface {
public bulkUpdate(
tableName: string,
values: object,
identifier: object,
identifier: WhereOptions,
options?: QueryOptions,
attributes?: string[] | string
): Promise<object>;
......@@ -407,14 +417,14 @@ export class QueryInterface {
/**
* Deletes a row
*/
public delete(instance: Model, tableName: string, identifier: object, options?: QueryOptions): Promise<object>;
public delete(instance: Model | null, tableName: string, identifier: WhereOptions, options?: QueryOptions): Promise<object>;
/**
* Deletes multiple rows at once
*/
public bulkDelete(
tableName: string,
identifier: object,
identifier: WhereOptions,
options?: QueryOptions,
model?: typeof Model
): Promise<object>;
......@@ -422,7 +432,7 @@ export class QueryInterface {
/**
* Returns selected rows
*/
public select(model: typeof Model, tableName: string, options?: QueryOptions): Promise<object[]>;
public select(model: typeof Model | null, tableName: string, options?: QueryOptionsWithWhere): Promise<object[]>;
/**
* Increments a row value
......@@ -431,7 +441,7 @@ export class QueryInterface {
instance: Model,
tableName: string,
values: object,
identifier: object,
identifier: WhereOptions,
options?: QueryOptions
): Promise<object>;
......@@ -440,7 +450,7 @@ export class QueryInterface {
*/
public rawSelect(
tableName: string,
options: QueryOptions,
options: QueryOptionsWithWhere,
attributeSelector: string | string[],
model?: typeof Model
): Promise<string[]>;
......@@ -453,9 +463,11 @@ export class QueryInterface {
tableName: string,
triggerName: string,
timingType: string,
fireOnArray: any[],
fireOnArray: {
[key: string]: unknown;
}[],
functionName: string,
functionParams: any[],
functionParams: FunctionParam[],
optionsArray: string[],
options?: QueryInterfaceOptions
): Promise<void>;
......@@ -480,7 +492,7 @@ export class QueryInterface {
*/
public createFunction(
functionName: string,
params: any[],
params: FunctionParam[],
returnType: string,
language: string,
body: string,
......@@ -490,14 +502,14 @@ export class QueryInterface {
/**
* Postgres only. Drops a function
*/
public dropFunction(functionName: string, params: any[], options?: QueryInterfaceOptions): Promise<void>;
public dropFunction(functionName: string, params: FunctionParam[], options?: QueryInterfaceOptions): Promise<void>;
/**
* Postgres only. Rename a function
*/
public renameFunction(
oldFunctionName: string,
params: any[],
params: FunctionParam[],
newFunctionName: string,
options?: QueryInterfaceOptions
): Promise<void>;
......
......@@ -83,7 +83,7 @@ export interface PoolOptions {
* A function that validates a connection. Called with client. The default function checks that client is an
* object, and that its state is not disconnected
*/
validate?(client?: any): boolean;
validate?(client?: unknown): boolean;
}
/**
......@@ -131,7 +131,7 @@ export interface Config {
};
readonly protocol: 'tcp';
readonly native: boolean;
readonly ssl: any;
readonly ssl: boolean;
readonly replication: boolean;
readonly dialectModulePath: null | string;
readonly keepDefaultTimezone?: boolean;
......@@ -1052,14 +1052,14 @@ export class Sequelize extends Hooks {
* @param sql
* @param options Query options
*/
public query(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.UPDATE>): Promise<[undefined, number]>;
public query(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.BULKUPDATE>): Promise<number>;
public query(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.INSERT>): Promise<[number, number]>;
public query(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.UPSERT>): Promise<number>;
public query(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.DELETE>): Promise<void>;
public query(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.BULKDELETE>): Promise<number>;
public query(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.SHOWTABLES>): Promise<string[]>;
public query(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.DESCRIBE>): Promise<{
public query(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.UPDATE>): Promise<[undefined, number]>;
public query(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.BULKUPDATE>): Promise<number>;
public query(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.INSERT>): Promise<[number, number]>;
public query(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.UPSERT>): Promise<number>;
public query(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.DELETE>): Promise<void>;
public query(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.BULKDELETE>): Promise<number>;
public query(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.SHOWTABLES>): Promise<string[]>;
public query(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.DESCRIBE>): Promise<{
[key: string]: {
type: string;
allowNull: boolean;
......@@ -1070,11 +1070,11 @@ export class Sequelize extends Hooks {
}
}>;
public query<M extends Model>(
sql: string | { query: string; values: any[] },
sql: string | { query: string; values: unknown[] },
options: QueryOptionsWithModel
): Promise<M[]>;
public query<T extends object>(sql: string | { query: string; values: any[] }, options: QueryOptionsWithType<QueryTypes.SELECT>): Promise<T[]>;
public query(sql: string | { query: string; values: any[] }, options?: QueryOptions | QueryOptionsWithType<QueryTypes.RAW>): Promise<unknown[]>;
public query<T extends object>(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.SELECT>): Promise<T[]>;
public query(sql: string | { query: string; values: unknown[] }, options?: QueryOptions | QueryOptionsWithType<QueryTypes.RAW>): Promise<unknown[]>;
/**
* Execute a query which would set an environment or user variable. The variables are set per connection,
......@@ -1251,7 +1251,7 @@ export class Sequelize extends Hooks {
* @param fn The function you want to call
* @param args All further arguments will be passed as arguments to the function
*/
export function fn(fn: string, ...args: any[]): Fn;
export function fn(fn: string, ...args: unknown[]): Fn;
/**
* Creates a object representing a column in the DB. This is often useful in conjunction with
......@@ -1267,14 +1267,14 @@ export function col(col: string): Col;
* @param val The value to cast
* @param type The type to cast it to
*/
export function cast(val: any, type: string): Cast;
export function cast(val: unknown, type: string): Cast;
/**
* Creates a object representing a literal, i.e. something that will not be escaped.
*
* @param val
*/
export function literal(val: any): Literal;
export function literal(val: string): Literal;
/**
* An AND query
......
export type Escapable = undefined | null | boolean | number | string | Date;
export function escapeId(val: string, forbidQualified?: boolean): string;
export function escape(val: Escapable | Escapable[], timeZone?: string, dialect?: string, format?: string): string;
export function format(sql: string, values: any[], timeZone?: string, dialect?: string): string;
export function formatNamedParameters(sql: string, values: any[], timeZone?: string, dialect?: string): string;
export function format(sql: string, values: unknown[], timeZone?: string, dialect?: string): string;
export function formatNamedParameters(sql: string, values: unknown[], timeZone?: string, dialect?: string): string;
import { DataType } from './data-types';
import { Model, WhereOptions } from './model';
export type Primitive = 'string' | 'number' | 'boolean';
......@@ -21,17 +22,22 @@ export function format(arr: string[], dialect: string): string;
export function formatNamedParameters(sql: string, parameters: {
[key: string]: string | number | boolean;
}, dialect: string): string;
export function cloneDeep<T>(obj: T, fn?: (el: any) => any): T;
export function cloneDeep<T>(obj: T, fn?: (el: unknown) => unknown): T;
export interface OptionsForMapping {
attributes?: string[];
where?: WhereOptions;
}
/** Expand and normalize finder options */
export function mapFinderOptions(options: any, Model: any): any;
export function mapFinderOptions<T extends OptionsForMapping>(options: T, model: typeof Model): T;
/* Used to map field names in attributes and where conditions */
export function mapOptionFieldNames(options: any, Model: any): any;
export function mapOptionFieldNames<T extends OptionsForMapping>(options: T, model: typeof Model): T;
export function mapWhereFieldNames(attributes: any, Model: any): any;
export function mapWhereFieldNames(attributes: object, model: typeof Model): object;
/** Used to map field names in values */
export function mapValueFieldNames(dataValues: any, fields: any, Model: any): any;
export function mapValueFieldNames(dataValues: object, fields: string[], model: typeof Model): object;
export function isColString(value: string): boolean;
export function canTreatArrayAsAnd(arr: unknown[]): boolean;
......@@ -40,7 +46,7 @@ export function combineTableNames(tableName1: string, tableName2: string): strin
export function singularize(s: string): string;
export function pluralize(s: string): string;
export function toDefaultValue(value: any): any;
export function toDefaultValue<T>(value: unknown): unknown;
/**
* Determine if the default value provided exists and can be described
......@@ -67,7 +73,7 @@ export class SequelizeMethod {
* Please do not use these functions directly, use Sequelize.fn and Sequelize.col instead.
*/
export class Fn extends SequelizeMethod {
constructor(fn: string, args: any);
constructor(fn: string, args: unknown[]);
public clone(): this;
}
......@@ -77,14 +83,14 @@ export class Col extends SequelizeMethod {
}
export class Cast extends SequelizeMethod {
public val: any;
public val: unknown;
public type: string;
constructor(val: any, type?: string);
constructor(val: unknown, type?: string);
}
export class Literal extends SequelizeMethod {
public val: any;
constructor(val: any);
public val: unknown;
constructor(val: unknown);
}
export class Json extends SequelizeMethod {
......
......@@ -14,7 +14,7 @@ interface User extends Model {
type UserModel = {
new (): User
customStaticMethod(): any
customStaticMethod(): unknown
} & typeof Model;
const User = sequelize.define('User', { firstName: DataTypes.STRING }, { tableName: 'users' }) as UserModel;
......
......@@ -9,6 +9,9 @@ MyModel.findAll({
{
limit: 1,
model: AssociatedModel,
on: {
a: 1,
},
order: [['id', 'DESC']],
separate: true,
where: { state: Sequelize.col('project.state') },
......
import { Association, HasOne, Model } from 'sequelize';
class MyModel extends Model {
public static associations: {
other: HasOne;
};
public static async customStuff() {
return this.sequelize!.query('select 1');
}
}
const assoc: Association = MyModel.associations.other;
import {
BelongsTo,
BelongsToCreateAssociationMixin,
BelongsToGetAssociationMixin,
BelongsToSetAssociationMixin,
DataTypes,
FindOptions,
Model,
BelongsTo,
BelongsToCreateAssociationMixin,
BelongsToGetAssociationMixin,
BelongsToSetAssociationMixin,
DataTypes,
FindOptions,
Model,
} from 'sequelize';
import { sequelize } from '../connection';
export class User extends Model {
public static associations: {
group: BelongsTo
};
public static associations: {
group: BelongsTo
};
public id: number;
public username: string;
public firstName: string;
public lastName: string;
public createdAt: Date;
public updatedAt: Date;
public id: number;
public username: string;
public firstName: string;
public lastName: string;
public createdAt: Date;
public updatedAt: Date;
// mixins for association (optional)
public groupId: number;
public group: UserGroup;
public getGroup: BelongsToGetAssociationMixin<UserGroup>;
public setGroup: BelongsToSetAssociationMixin<UserGroup, number>;
public createGroup: BelongsToCreateAssociationMixin<UserGroup>;
// mixins for association (optional)
public groupId: number;
public group: UserGroup;
public getGroup: BelongsToGetAssociationMixin<UserGroup>;
public setGroup: BelongsToSetAssociationMixin<UserGroup, number>;
public createGroup: BelongsToCreateAssociationMixin<UserGroup>;
}
User.init(
{
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
username: DataTypes.STRING,
{
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
username: DataTypes.STRING,
},
{
getterMethods: {
a() {
return 1;
},
{
scopes: {
custom(a: number) {
return {
where: {
firstName: a,
},
};
}
},
sequelize,
}
},
setterMethods: {
b(val: string) {
(<User>this).username = val;
},
},
scopes: {
custom(a: number) {
return {
where: {
firstName: a,
},
};
}
},
sequelize,
}
);
// Hooks
User.afterFind((users, options) => {
console.log('found');
console.log('found');
});
// TODO: VSCode shows the typing being correctly narrowed but doesn't do it correctly
User.addHook('beforeFind', 'test', (options: FindOptions) => {
return undefined;
return undefined;
});
// associate
// it is important to import _after_ the model above is already exported so the circular reference works.
......
......@@ -5,48 +5,48 @@ import { QueryInterface } from 'sequelize/lib/query-interface';
declare let queryInterface: QueryInterface;
queryInterface.createTable(
'nameOfTheNewTable',
{
attr1: DataTypes.STRING,
attr2: DataTypes.INTEGER,
attr3: {
allowNull: false,
defaultValue: false,
type: DataTypes.BOOLEAN,
},
// foreign key usage
attr4: {
onDelete: 'cascade',
onUpdate: 'cascade',
references: {
key: 'id',
model: 'another_table_name',
},
type: DataTypes.INTEGER,
},
createdAt: {
type: DataTypes.DATE,
},
id: {
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
updatedAt: {
type: DataTypes.DATE,
},
'nameOfTheNewTable',
{
attr1: DataTypes.STRING,
attr2: DataTypes.INTEGER,
attr3: {
allowNull: false,
defaultValue: false,
type: DataTypes.BOOLEAN,
},
{
charset: 'latin1', // default: null
collate: 'latin1_general_ci',
engine: 'MYISAM', // default: 'InnoDB'
uniqueKeys: {
test: {
customIndex: true,
fields: ['attr2', 'attr3'],
}
}
// foreign key usage
attr4: {
onDelete: 'cascade',
onUpdate: 'cascade',
references: {
key: 'id',
model: 'another_table_name',
},
type: DataTypes.INTEGER,
},
createdAt: {
type: DataTypes.DATE,
},
id: {
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
updatedAt: {
type: DataTypes.DATE,
},
},
{
charset: 'latin1', // default: null
collate: 'latin1_general_ci',
engine: 'MYISAM', // default: 'InnoDB'
uniqueKeys: {
test: {
customIndex: true,
fields: ['attr2', 'attr3'],
}
}
}
);
queryInterface.dropTable('nameOfTheExistingTable');
......@@ -56,25 +56,25 @@ queryInterface.dropAllTables();
queryInterface.renameTable('Person', 'User');
queryInterface.showAllTables().then(tableNames => {
// do nothing
// do nothing
});
queryInterface.describeTable('Person').then(attributes => {
/*
attributes will be something like:
{
name: {
type: 'VARCHAR(255)', // this will be 'CHARACTER VARYING' for pg!
allowNull: true,
defaultValue: null
},
isBetaMember: {
type: 'TINYINT(1)', // this will be 'BOOLEAN' for pg!
allowNull: false,
defaultValue: false
}
/*
attributes will be something like:
{
name: {
type: 'VARCHAR(255)', // this will be 'CHARACTER VARYING' for pg!
allowNull: true,
defaultValue: null
},
isBetaMember: {
type: 'TINYINT(1)', // this will be 'BOOLEAN' for pg!
allowNull: false,
defaultValue: false
}
}
*/
});
......@@ -83,16 +83,16 @@ queryInterface.addColumn('nameOfAnExistingTable', 'nameOfTheNewAttribute', DataT
// or
queryInterface.addColumn(
{ tableName: 'nameOfAnExistingTable', schema: 'nameOfSchema' },
'nameOfTheNewAttribute',
DataTypes.STRING
{ tableName: 'nameOfAnExistingTable', schema: 'nameOfSchema' },
'nameOfTheNewAttribute',
DataTypes.STRING
);
// or
queryInterface.addColumn('nameOfAnExistingTable', 'nameOfTheNewAttribute', {
allowNull: false,
type: DataTypes.STRING,
allowNull: false,
type: DataTypes.STRING,
});
queryInterface.removeColumn('Person', 'signature');
......@@ -102,21 +102,21 @@ queryInterface.removeColumn('Person', 'signature');
queryInterface.removeColumn({ tableName: 'Person', schema: 'nameOfSchema' }, 'signature');
queryInterface.changeColumn('nameOfAnExistingTable', 'nameOfAnExistingAttribute', {
allowNull: false,
defaultValue: 0.0,
type: DataTypes.FLOAT,
allowNull: false,
defaultValue: 0.0,
type: DataTypes.FLOAT,
});
// or
queryInterface.changeColumn(
{ tableName: 'nameOfAnExistingTable', schema: 'nameOfSchema' },
'nameOfAnExistingAttribute',
{
allowNull: false,
defaultValue: 0.0,
type: DataTypes.FLOAT,
}
{ tableName: 'nameOfAnExistingTable', schema: 'nameOfSchema' },
'nameOfAnExistingAttribute',
{
allowNull: false,
defaultValue: 0.0,
type: DataTypes.FLOAT,
}
);
queryInterface.renameColumn('Person', 'signature', 'sig');
......@@ -132,8 +132,8 @@ queryInterface.addIndex('Person', ['firstname', 'lastname']);
// - indexType: Set a type for the index, e.g. BTREE. See the documentation of the used dialect
// - logging: A function that receives the sql query, e.g. console.log
queryInterface.addIndex('Person', ['firstname', 'lastname'], {
indexName: 'SuperDuperIndex',
indicesType: 'UNIQUE',
indexName: 'SuperDuperIndex',
indicesType: 'UNIQUE',
});
queryInterface.removeIndex('Person', 'SuperDuperIndex');
......@@ -143,8 +143,20 @@ queryInterface.removeIndex('Person', 'SuperDuperIndex');
queryInterface.removeIndex('Person', ['firstname', 'lastname']);
queryInterface.addConstraint('Person', ['firstname', 'lastname'], {
name: 'firstnamexlastname',
type: 'unique',
name: 'firstnamexlastname',
type: 'unique',
});
queryInterface.removeConstraint('Person', 'firstnamexlastname');
queryInterface.select(null, 'Person', {
where: {
a: 1,
},
});
queryInterface.delete(null, 'Person', {
where: {
a: 1,
},
});
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!