diff --git a/sequelize/sequelize-2.0.0.d.ts b/sequelize/sequelize-2.0.0.d.ts new file mode 100644 index 000000000..1bb6be593 --- /dev/null +++ b/sequelize/sequelize-2.0.0.d.ts @@ -0,0 +1,2787 @@ +// Type definitions for Sequelize 2.0.0 dev13 +// Project: http://sequelizejs.com +// Definitions by: samuelneff , Peter Harris +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Based on original work by: samuelneff + +/// +/// + +declare module "sequelize" +{ + module sequelize { + interface SequelizeStaticAndInstance { + + /** + * A reference to sequelize utilities. Most users will not need to use these utils directly. However, you might want + * to use Sequelize.Utils._, which is a reference to the lodash library, if you don't already have it imported in + * your project. + */ + Utils: Utils; + + /** + * A modified version of bluebird promises, that allows listening for sql events. + * + * @see Promise + */ + Promise: Promise; + + /** + * Exposes the validator.js object, so you can extend it with custom validation functions. The validator is exposed + * both on the instance, and on the constructor. + * + * @see Validator + */ + Validator: Validator; + + QueryTypes: QueryTypes; + + /** + * A general error class. + */ + Error: Error; + + /** + * Emitted when a validation fails. + * + * @see ValidationError + */ + ValidationError: ValidationError; + + /** + * Creates a object representing a database function. This can be used in search queries, both in where and order + * parts, and as default values in column definitions. If you want to refer to columns in your function, you should + * use sequelize.col, so that the columns are properly interpreted as columns and not a strings. + * + * @param fn The function you want to call. + * @param args All further arguments will be passed as arguments to the function. + */ + fn(fn: string, ...args: Array): any; + + /** + * Creates a object representing a column in the DB. This is often useful in conjunction with sequelize.fn, since + * raw string arguments to fn will be escaped. + * + * @param col The name of the column + */ + col(col: string): Col; + + /** + * Creates a object representing a call to the cast function. + * + * @param val The value to cast. + * @param type The type to cast it to. + */ + cast(val: any, type: string): Cast; + + /** + * Creates a object representing a literal, i.e. something that will not be escaped. + * + * @param val Value to convert to a literal. + */ + literal(val: any): Literal; + + /** + * An AND query. + * + * @param args Each argument (string or object) will be joined by AND. + */ + and(...args: Array): And; + + /** + * An OR query. + * + * @param args Each argument (string or object) will be joined by OR. + */ + or(...args: Array): Or; + + /** + * A way of specifying attr = condition. Mostly used internally. + * + * @param attr The attribute + * @param condition The condition. Can be both a simply type, or a further condition (.or, .and, .literal etc.) + */ + where(attr: string, condition: any): Where; + } + + interface SequelizeStatic extends SequelizeStaticAndInstance, DataTypes { + /** + * Instantiate sequelize with name of database and username + * @param database database name + * @param username user name + */ + new (database: string, username: string): Sequelize; + + /** + * Instantiate sequelize with name of database, username and password + * @param database database name + * @param username user name + * @param password password + */ + new (database: string, username: string, password: string): Sequelize; + + /** + * Instantiate sequelize with name of database, username, password, and options. + * @param database database name + * @param username user name + * @param password password + * @param options options. @see Options + */ + new (database: string, username: string, password: string, options: Options): Sequelize; + + /** + * Instantiate sequelize with name of database, username, and options. + * + * @param database database name + * @param username user name + * @param options options. @see Options + */ + new (database: string, username: string, options: Options): Sequelize; + + /** + * Instantiate sequlize with an URI + * @param connectionString A full database URI + * @param options Options for sequelize. @see Options + */ + new (connectionString: string, options?: Options): Sequelize; + } + + interface Sequelize extends SequelizeStaticAndInstance { + /** + * Sequelize configuration (undocumented). + */ + config: Config; + + /** + * Sequelize options (undocumented). + */ + options: Options; + + /** + * Models are stored here under the name given to sequelize.define + */ + models: any; + modelManager: ModelManager; + daoFactoryManager: ModelManager; + transactionManager: TransactionManager; + importCache: any; + + /** + * A reference to the sequelize transaction class. Use this to access isolationLevels when creating a transaction. + * + * @see Transaction + */ + Transaction: TransactionStatic; + + /** + * Returns the specified dialect. + */ + getDialect(): string; + + /** + * Returns the singleton instance of QueryInterface. + */ + getQueryInterface(): QueryInterface; + + /** + * Returns the singleton instance of Migrator. + * @param options Migration options + * @param force A flag that defines if the migrator should get instantiated or not. + */ + getMigrator(options?: MigratorOptions, force?: boolean): Migrator; + + /** + * Define a new model, representing a table in the DB. + * + * @param daoName The name of the entity (table). Typically specified in singular form. + * @param attributes A hash of attributes to define. Each attribute can be either a string name for the attribute + * or can be an object defining the attribute and its options. Note attributes is not fully + * typed since TypeScript does not support union types--it can be either a string or an + * options object. @see AttributeOptions. + * @param options Table options. @see DefineOptions. + */ + define(daoName: string, attributes: any, options?: DefineOptions): Model; + + /** + * Fetch a DAO factory which is already defined. + * + * @param daoName The name of a model defined with Sequelize.define. + */ + model(daoName: string): Model; + + /** + * Checks whether a model with the given name is defined. + * + * @param daoName The name of a model defined with Sequelize.define. + */ + isDefined(daoName: string): boolean; + + /** + * Imports a model defined in another file. + * + * @param path The path to the file that holds the model you want to import. If the part is relative, it will be + * resolved relatively to the calling file + */ + import(path: string): Model; + + /** + * Execute a query on the DB, with the possibility to bypass all the sequelize goodness. + * + * @param sql SQL statement to execute. + * + * @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented + * by the factory. Equivalent to calling Model.build with the values provided by the query. + * + * @param options Query options. + * + * @param replacements Either an object of named parameter replacements in the format :param or an array of + * unnamed replacements to replace ? in your SQL. + */ + query(sql: string, callee?: Model, options?: QueryOptions, replacements?: any): EventEmitter; + + query(sql: string, callee?: Model, options?: QueryOptions): EventEmitterT>; + + /** + * Create a new database schema. + * + * @param schema Name of the schema. + */ + createSchema(schema: string): EventEmitter; + + /** + * Show all defined schemas. + */ + showAllSchemas(): EventEmitter; + + /** + * Drop a single schema. + * + * @param schema Name of the schema. + */ + dropSchema(schema: string): EventEmitter; + + /** + * Drop all schemas. + */ + dropAllSchemas(): EventEmitter; + + /** + * Sync all defined DAOs to the DB. + * + * @param options Options. + */ + sync(options?: SyncOptions): EventEmitter; + + /** + * Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model. + * + * @param options The options passed to each call to Model.drop. + */ + drop(options: DropOptions): EventEmitter; + + /** + * Test the connection by trying to authenticate. Alias for 'validate'. + */ + authenticate(): EventEmitter; + + /** + * Alias for authenticate(). Test the connection by trying to authenticate. Alias for 'validate'. + */ + validate(): EventEmitter; + + /** + * !! DEPRECATED : When passing a callback to a transaction a promise chain is expected in return, + * the transaction will be committed or rejected based on the promise chain returned to the callback. + * + * Start a transaction. When using transactions, you should pass the transaction in the options argument in order + * for the query to happen under that transaction. + * + * @param callback Called when the transaction has been set up and is ready for use. Callback takes transaction + * argument (overload available for error and transaction arguments too). + */ + transaction(callback: (transaction: Transaction) => boolean): Promise; + + /** + * Start a transaction. When using transactions, you should pass the transaction in the options argument in order + * for the query to happen under that transaction. + * + * @param options Transaction options. + * @param callback Called when the transaction has been set up and is ready for use. Callback takes transaction + * argument (overload available for error and transaction arguments too). + */ + transaction(options?: TransactionOptions, callback?: (transaction: Transaction) => void): PromiseT; + + close(): void; + } + + interface Config { + database?: string; + username?: string; + password?: string; + host?: string; + port?: number; + pool?: PoolOptions; + protocol?: string; + queue?: boolean; + native?: boolean; + ssl?: boolean; + replication?: ReplicationOptions; + dialectModulePath?: string; + maxConcurrentQueries?: number; + dialectOptions?: any; + } + + interface Model extends Hooks, Associations { + /** + * A reference to the sequelize instance. + */ + sequelize: Sequelize; + + /** + * The name of the model, typically singular. + */ + name: string; + + /** + * The name of the underlying database table, typically plural. + */ + tableName: string; + + options: DefineOptions; + attributes: any; + rawAttributes: any; + modelManager: ModelManager; + daoFactoryManager: ModelManager; + associations: any; + scopeObj: any; + + /** + * Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the model + * instance (this). + */ + sync(options?: SyncOptions): PromiseT>; + + /** + * Drop the table represented by this Model. + * + * @param options + */ + drop(options?: DropOptions): Promise; + + /** + * Apply a schema to this model. For postgres, this will actually place the schema in front of the table name - + * "schema"."tableName", while the schema will be prepended to the table name for mysql and sqlite - + * 'schema.tablename'. + * + * @param schema The name of the schema. + * @param options Schema options. + */ + schema(schema: string, options?: SchemaOptions): Model; + + /** + * Get the tablename of the model, taking schema into account. The method will return The name as a string if the + * model has no schema, or an object with tableName, schema and delimiter properties. + */ + getTableName(): any; + + /** + * Apply a scope created in define to the model. + * + * @param options The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of + * arguments. To apply simple scopes, pass them as strings. For scope function, pass an object, + * with a method property. The value can either be a string, if the method does not take any + * arguments, or an array, where the first element is the name of the method, and consecutive + * elements are arguments to that method. Pass null to remove all scopes, including the default. + */ + scope(options: any): Model; + + /** + * Search for multiple instances.. + * + * @param options A hash of options to describe the scope of the search. + * @param queryOptions Set the query options, e.g. raw, specifying that you want raw data instead of built + * Instances. See sequelize.query for options. + */ + findAll(options?: FindOptions, queryOptions?: QueryOptions): PromiseT>; + + /** + * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance. + * + * @param options A hash of options to describe the scope of the search. + * @param queryOptions Set the query options, e.g. raw, specifying that you want raw data instead of built + * Instances. See sequelize.query for options + */ + find(options?: FindOptions, queryOptions?: QueryOptions): PromiseT; + + /** + * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance. + * + * @param options A number to search by id. + * @param queryOptions Set the query options, e.g. raw, specifying that you want raw data instead of built + * Instances. See sequelize.query for options + */ + find(id?: number, queryOptions?: QueryOptions): PromiseT; + + /** + * Run an aggregation method on the specified field. + * + * @param field The field to aggregate over. Can be a field name or *. + * @param aggregateFunction The function to use for aggregation, e.g. sum, max etc. + * @param options Query options, particularly options.dataType. + */ + aggregate(field: string, aggregateFunction: string, options: FindOptions): PromiseT; + + /** + * Count the number of records matching the provided where clause. + * + * @param options Conditions and options for the query. + */ + count(options?: FindOptions): PromiseT; + + /** + * Find all the rows matching your query, within a specified offset / limit, and get the total number of rows + * matching your query. This is very usefull for paging. + * + * @param findOptions Filtering options + * @param queryOptions Query options + */ + findAndCountAll(findOptions?: FindOptions, queryOptions?: QueryOptions): PromiseT>; + + /** + * Find the maximum value of field. + * + * @param field + * @param options + */ + max(field: string, options?: FindOptions): PromiseT; + + /** + * Find the minimum value of field. + * + * @param field + * @param options + */ + min(field: string, options?: FindOptions): PromiseT; + + /** + * Find the sum of field. + * + * @param field + * @param options + */ + sum(field: string, options?: FindOptions): PromiseT; + + /** + * Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty. + * + * @param values any from which to build entity instance. + * @param options any construction options. + */ + build(values: TPojo, options?: BuildOptions): TInstance; + + /** + * Builds a new model instance and calls save on it.. + * + * @param values + * @param options + */ + create(values: TPojo, options?: CopyOptions): PromiseT; + + /** + * Find a row that matches the query, or build (but don't save) the row if none is found. The successfull result + * of the promise will be (instance, initialized) - Make sure to use .spread(). + * + * @param where A hash of search attributes. Note that this method differs from finders, in that the syntax + * is { attr1: 42 } and NOT { where: { attr1: 42}}. This may be subject to change in 2.0 + * @param defaults Default values to use if building a new instance + * @param options Options passed to the find call + */ + findOrInitialize(where: any, defaults?: TPojo, options?: QueryOptions): PromiseT; + + /** + * Find a row that matches the query, or build and save the row if none is found The successfull result of the + * promise will be (instance, created) - Make sure to use .spread(). + * + * @param where A hash of search attributes. Note that this method differs from finders, in that the syntax is + * { attr1: 42 } and NOT { where: { attr1: 42}}. This is subject to change in 2.0 + * @param defaults Default values to use if creating a new instance + * @param options Options passed to the find and create calls. + */ + findOrCreate(where: any, defaults?: TPojo, options?: FindOrCreateOptions): PromiseT; + + /** + * Create and insert multiple instances in bulk. + * + * @param records List of objects (key/value pairs) to create instances from. + * @param options + */ + bulkCreate(records: Array, options?: BulkCreateOptions): PromiseT>; + + /** + * Delete multiple instances. + */ + destroy(where?: any, options?: DestroyOptions): Promise; + + /** + * Update multiple instances that match the where options. + * + * @param attrValueHash A hash of fields to change and their new values + * @param where Options to describe the scope of the search. Note that these options are not wrapped in a + * { where: ... } is in find / findAll calls etc. This is probably due to change in 2.0. + */ + update(attrValueHash: TPojo, where: any, options?: UpdateOptions): Promise; + + /** + * Run a describe query on the table. The result will be return to the listener as a hash of attributes and their + * types. + */ + describe(): PromiseT; + + /** + * A proxy to the node-sql query builder, which allows you to build your query through a chain of method calls. + * The returned instance already has all the fields property populated with the field of the model. + */ + dataset(): any; + } + + interface Instance { + /** + * Returns true if this instance has not yet been persisted to the database. + */ + isNewRecord: boolean; + + /** + * Returns the Model the instance was created from. + */ + Model: Model; + + /** + * A reference to the sequelize instance. + */ + sequelize: Sequelize; + + /** + * If timestamps and paranoid are enabled, returns whether the deletedAt timestamp of this instance is set. + * Otherwise, always returns false. + */ + isDeleted: boolean; + + /** + * Get the values of this Instance. Proxies to this.get. + */ + values: TPojo; + + /** + * A getter for this.changed(). Returns true if any keys have changed. + */ + isDirty: boolean; + + /** + * Get the values of the primary keys of this instance. + */ + primaryKeyValues: TPojo; + + /** + * Get the value of the underlying data value. + * + * @param key Field to retrieve. + */ + getDataValue(key: string): any; + + /** + * Update the underlying data value. + * + * @param key Field to set. + * @param value Value to set. + */ + setDataValue(key: string, value: any): void; + + /** + * Retrieves the value for the key when specified. If no key is given, returns all values of the instance, also + * invoking virtual getters. + */ + get(key?: string): any; + + /** + * Set is used to update values on the instance (the sequelize representation of the instance that is, remember + * that nothing will be persisted before you actually call save). + */ + set(key: string, value: any, options?: SetOptions): void; + + /** + * If changed is called with a string it will return a boolean indicating whether the value of that key in + * dataValues is different from the value in _previousDataValues. If changed is called without an argument, it will + * return an array of keys that have changed. + */ + changed(key: string): any; + + /** + * If changed is called with a string it will return a boolean indicating whether the value of that key in + * dataValues is different from the value in _previousDataValues. If changed is called without an argument, it will + * return an array of keys that have changed. + */ + changed(): Array; + + /** + * Returns the previous value for key from _previousDataValues. + */ + previous(key: string): any; + + /** + * Validate this instance, and if the validation passes, persist it to the database. + */ + save(fields?: Array, options?: SaveOptions): PromiseT; + + /** + * Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same + * object. This is different from doing a find(Instance.id), because that would create and return a new instance. + * With this method, all references to the Instance are updated with the new data and no new objects are created. + */ + reload(options?: FindOptions): PromiseT; + + /** + * Validate the attribute of this instance according to validation rules set in the model definition. + */ + validate(options?: ValidateOptions): PromiseT; + + /** + * This is the same as calling setAttributes, then calling save. + */ + updateAttributes(updates: TPojo, options: SaveOptions): PromiseT; + + /** + * Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will either be + * completely deleted, or have its deletedAt timestamp set to the current time. + * + * @param options Allows caller to specify if delete should be forced. + */ + destroy(options?: DestroyInstanceOptions): Promise; + + /** + * Increment the value of one or more columns. This is done in the database, which means it does not use the + * values currently stored on the Instance. + * + * @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. + * @param options Increment options. + */ + increment(fields: any, options?: IncrementOptions): Promise; + + /** + * Decrement the value of one or more columns. This is done in the database, which means it does not use the + * values currently stored on the Instance. + * + * @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. + * @param options Decrement options. + */ + decrement(fields: any, options?: IncrementOptions): Promise; + + /** + * Check whether all values of this and other Instance are the same. + */ + equal(other: TInstance): boolean; + + /** + * Check if this is eqaul to one of others by calling equals. + * + * @param others Other instances to compare to. + */ + equalsOneOf(others: Array): boolean; + + /** + * Convert the instance to a JSON representation. Proxies to calling get with no keys. This means get all values + * gotten from the DB, and apply all custom getters. + */ + toJSON(): TPojo; + } + + interface Transaction extends TransactionStatic { + /** + * Commit the transaction. + */ + commit(): Transaction; + + /** + * Rollback (abort) the transaction. + */ + rollback(): Transaction; + } + + interface TransactionStatic { + /** + * The possible isolation levels to use when starting a transaction + */ + ISOLATION_LEVELS: TransactionIsolationLevels; + + /** + * Possible options for row locking. Used in conjuction with find calls. + */ + LOCK: TransactionLocks; + } + + interface TransactionIsolationLevels { + READ_UNCOMMITTED: string;// "READ UNCOMMITTED" + READ_COMMITTED: string; // "READ COMMITTED" + REPEATABLE_READ: string; // "REPEATABLE READ" + SERIALIZABLE: string; // "SERIALIZABLE" + } + + interface TransactionLocks { + UPDATE: string; // UPDATE + SHARE: string; // SHARE + } + + interface Hooks { + + /** + * Add a named hook to the model. + * + * @param hooktype + */ + addHook(hooktype: string, name: string, fn: (...args: Array) => void): boolean; + + /** + * Add a hook to the model. + * + * @param hooktype + */ + addHook(hooktype: string, fn: (...args: Array) => void): boolean; + + /** + * A named hook that is run before validation. + */ + beforeValidate(name: string, validator: (dao: T, callback: (err?: Error) => void) => void): void; + + /** + * A hook that is run before validation. + */ + beforeValidate(validator: (dao: T, callback: (err?: Error) => void) => void): void; + + /** + * A named hook that is run before validation. + */ + afterValidate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run before validation. + */ + afterValidate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run before creating a single instance. + */ + beforeCreate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run before creating a single instance. + */ + beforeCreate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run after creating a single instance. + */ + afterCreate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run after creating a single instance. + */ + afterCreate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run before destroying a single instance. + */ + beforeDestroy(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run before destroying a single instance. + */ + beforeDestroy(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run after destroying a single instance. + */ + afterDestroy(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run after destroying a single instance. + */ + afterDestroy(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run before updating a single instance. + */ + beforeUpdate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run before updating a single instance. + */ + beforeUpdate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run after updating a single instance. + */ + afterUpdate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run after updating a single instance. + */ + afterUpdate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run before creating instances in bulk. + */ + beforeBulkCreate(name: string, validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run before creating instances in bulk. + */ + beforeBulkCreate(validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run after creating instances in bulk. + */ + afterBulkCreate(name: string, validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run after creating instances in bulk. + */ + afterBulkCreate(validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run before destroying instances in bulk. + */ + beforeBulkDestroy(name: string, validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; + + /** + * A hook that is run before destroying instances in bulk. + */ + beforeBulkDestroy(validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; + + /** + * A named hook that is run after destroying instances in bulk. + */ + afterBulkDestroy(name: string, validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; + + /** + * A hook that is run after destroying instances in bulk. + */ + afterBulkDestroy(validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; + + /** + * A named hook that is run before updating instances in bulk. + */ + beforeBulkUpdate(name: string, validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; + + /** + * A hook that is run before updating instances in bulk. + */ + beforeBulkUpdate(validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; + + /** + * A named hook that is run after updating instances in bulk. + */ + afterBulkUpdate(name: string, validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; + + /** + * A hook that is run after updating instances in bulk. + */ + afterBulkUpdate(validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; + } + + interface Associations { + /** + * Creates an association between this (the source) and the provided target. The foreign key is added on the target. + * + * @param target + * @param options + */ + hasOne(target: Model, options?: AssociationOptions): void; + + /** + * Creates an association between this (the source) and the provided target. The foreign key is added on the source. + * + * @param target + * @param options + */ + belongsTo(target: Model, options?: AssociationOptions): void; + + /** + * Creates an association to connect sources with multiple targets. Furthermore the targets can also have connections to multiple sources. + * + * @param target + * @param options + */ + belongsToMany(target: Model, options?: AssociationOptions): void; + + /** + * Create an association that is either 1:m or n:m. + * + * @param target + * @param options + */ + hasMany(target: Model, options?: AssociationOptions): void; + } + + /** + * Extension of external project that doesn't have definitions. + * + * See https://github.com/chriso/validator.js and https://github.com/sequelize/sequelize/blob/master/lib/instance-validator.js + */ + interface Validator { + + } + + /** + * Custom class defined, but no extra methods or functionality even. + */ + interface ValidationError extends Error { + + } + + interface QueryChainer { + /** + * Add an query to the chainer. This can be done in two ways - either by invoking the method like you would + * normally, and then adding the returned emitter to the chainer, or by passing the class that you want to call a + * method on, the name of the method, and its parameters to the chainer. The second form might sound a bit + * cumbersome, but it is used when you want to run queries in serial. + * + * @param emitterOrKlass + * @param method + * @param params + * @param options + */ + add(emitterOrKlass: any, method?: string, params?: any, options?: any): QueryChainer; + + /** + * Run the query chainer. In reality, this means, wait for all the added emitters to finish, since the queries + * began executing as soon as you invoked their methods. + */ + run(): EventEmitter; + + /** + * Run the chainer serially, so that each query waits for the previous one to finish before it starts. + * + * @param options @see QueryChainerRunSeriallyOptions + */ + runSerially(options?: QueryChainerRunSeriallyOptions): EventEmitter; + } + + interface QueryInterface { + + /** + * Returns the dialect-specific sql generator. + */ + QueryGenerator: QueryGenerator; + + /** + * Queries the schema (table list). + * + * @param schema The schema to query. Applies only to Postgres. + */ + createSchema(schema?: string): EventEmitter; + + /** + * Drops the specified schema (table). + * + * @param schema The name of the table to drop. + */ + dropSchema(schema: string): EventEmitter; + + /** + * Drops all tables. + */ + dropAllSchemas(): EventEmitter; + + /** + * Queries all table names in the database. + * + * @param options + */ + showAllSchemas(options?: QueryOptions): EventEmitter; + + /** + * 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 Query options. + * + * @return The return type will be a Promise when dialect is Postgres and an EventEmitter for MySQL and SQLite. + */ + createTable(tableName: string, attributes: any, options?: QueryOptions): any; + + /** + * Drops the specified table. + * + * @param tableName Table name. + * @param options Query options, particularly "force". + */ + dropTable(tableName: string, options?: QueryOptions): EventEmitter; + dropAllTables(options?: QueryOptions): EventEmitter; + dropAllEnums(options?: QueryOptions): EventEmitter; + renameTable(before: string, after: string): EventEmitter; + showAllTables(options?: QueryOptions): EventEmitter; + describeTable(tableName: string, options?: QueryOptions): EventEmitter; + addColumn(tableName: string, attributeName: any, dataTypeOrOptions?: any): EventEmitter; + removeColumn(tableName: string, attributeName: string): EventEmitter; + changeColumn(tableName: string, attributeName: string, dataTypeOrOptions: any): EventEmitter; + renameColumn(tableName: string, attrNameBefore: string, attrNameAfter: string): EventEmitter; + addIndex(tableName: string, attributes: Array, options?: QueryOptions): EventEmitter; + showIndex(tableName: string, options?: QueryOptions): EventEmitter; + getForeignKeysForTables(tableNames: Array): EventEmitter; + removeIndex(tableName: string, attributes: Array): EventEmitter; + removeIndex(tableName: string, indexName: string): EventEmitter; + insert(dao: TModel, tableName: string, values: any, options?: QueryOptions): EventEmitter; + /** + * Inserts several records into the specified table. + * @param tableName Table to insert into. + * @param records Array of key/value pairs to insert as records. + * @param options Query options + * @param attributes For Postgres only, used to identify if an attribute is auto-increment and thus handled specially. + */ + bulkInsert(tableName: string, records: Array, options?: QueryOptions, attributes?: any): EventEmitter; + + update(dao: TModel, tableName: string, values: Array, where: any, options?: QueryOptions): EventEmitter; + bulkUpdate(tableName: string, values: Array, where: any, options?: QueryOptions, attributes?: any): EventEmitter; + delete(dao: TModel, tableName: string, where: any, options?: QueryOptions): EventEmitter; + bulkDelete(tableName: string, where: any, options?: QueryOptions): EventEmitter; + bulkDelete(tableName: string, where: any, options: QueryOptions, model: TModel): EventEmitter; + select(factory: TModel, tableName: string, scope?: any, queryOptions?: QueryOptions): EventEmitter; + increment(dao: TModel, tableName: string, values: Array, where: any, options?: QueryOptions): EventEmitter; + rawSelect(tableName: string, options: QueryOptions, attributeSelector: string, model: TModel): EventEmitter; + /** + * Postgres only. Creates a trigger on specified table to call the specified function with supplied parameters. + * + * @param tableName + * @param triggerName + * @param timingType + * @param fireOnArray + * @param functionName + * @param functionParams + * @param optionsArray + */ + createTrigger(tableName: string, triggerName: string, timingType: string, fireOnArray: Array, functionName: string, functionParams: Array, optionsArray: Array): EventEmitter; + /** + * Postgres only. Drops the specified trigger. + * + * @param tableName + * @param triggerName + */ + dropTrigger(tableName: string, triggerName: string): EventEmitter; + renameTrigger(tableName: string, oldTriggerName: string, newTriggerName: string): EventEmitter; + createFunction(functionName: string, params: Array, returnType: string, language: string, body: string, options?: QueryOptions): EventEmitter; + dropFunction(functionName: string, params: Array): EventEmitter; + renameFunction(oldFunctionName: string, params: Array, newFunctionName: string): EventEmitter; + /** + * Escape an identifier (e.g. a table or attribute name). If force is true, + * the identifier will be quoted even if the `quoteIdentifiers` option is + * false. + */ + quoteIdentifier(identifier: string, force: boolean): EventEmitter; + quoteTable(tableName: string): EventEmitter; + quoteIdentifiers(identifiers: string, force: boolean): EventEmitter; + escape(value: string): EventEmitter; + setAutocommit(transaction: Transaction, value: boolean): EventEmitter; + setIsolationLevel(transaction: Transaction, value: string): EventEmitter; + startTransaction(transaction: Transaction, options?: QueryOptions): EventEmitter; + commitTransaction(transaction: Transaction, options?: QueryOptions): EventEmitter; + rollbackTransaction(transaction: Transaction, options?: QueryOptions): EventEmitter; + } + + interface QueryGenerator { + createSchema(schemaName: string): string; + dropSchema(schemaName: string): string; + showSchemasQuery(): string; + addSchema(param: Model): Schema; + createTableQuery(tableName: string, attributes: Array, options?: CreateTableQueryOptions): string; + describeTableQuery(tableName: string, schema: string, schemaDelimiter: string): string; + dropTableQuery(tableName: string, options?: { cascade: string }): string; + renameTableQuery(before: string, after: string): string; + showTablesQuery(): string; + addColumnQuery(tableName: string, attributes: any): string; + removeColumnQuery(tableName: string, attributeName: string): string; + changeColumnQuery(tableName: string, attributes: any): string; + renameColumnQuery(tableName: string, attrNameBefore: string, attrNameAfter: string): string; + insertQuery(table: string, valueHash: any, modelAttributes: any): string; + bulkInsertQuery(tableName: string, attrValueHashes: any): string; + updateQuery(tableName: string, attrValueHash: any, where: any, options: InsertOptions, attributes: any): string; + deleteQuery(tableName: string, where: any, options: DestroyOptions): string; + deleteQuery(tableName: string, where: any, options: DestroyOptions, model: Model): string; + /** + * Creates a query to increment a value. Note "options" here is an additional hash of values to update. + * + * @param tableName + * @param attrValueHash + * @param where + * @param options + */ + incrementQuery(tableName: string, attrValueHash: any, where: any, options?: any): string; + addIndexQuery(tableName: string, attributes: Array, options?: IndexOptions): string; + /** + * Return indices for a table. Not options may be passed but is not used, so can be anything. + * @param tableName + * @param options + */ + showIndexQuery(tableName: string, options?: any): string; // options is actually not used + removeIndexQuery(tableName: string, indexNameOrAttributes: string): string; + removeIndexQuery(tableName: string, indexNameOrAttributes: Array): string; + attributesToSQL(attributes: Array): string; + findAutoIncrementField(factory: Model): Array; + quoteTable(param: any, as: boolean): string; + quote(obj: any, parent: any, force: boolean): string; + createTrigger(tableName: string, triggerName: string, timingType: string, fireOnArray: TriggerOptions, functionName: string, functionParams: Array): string; + dropTrigger(tableName: string, triggerName: string): string; + renameTrigger(tableName: string, oldTriggerName: string, newTriggerName: string): string; + createFunction(functionName: string, params: Array, returnType: string, language: string, body: string, options?: Array): string; + dropFunction(functionName: string, params: Array): string; + renameFunction(oldFunctionName: string, params: Array, newFunctionName: string): string; + quoteIdentifier(identifier: string, force?: boolean): string; + quoteIdentifiers(identifiers: string, force?: boolean): string; + /** + * Not documented, and reading through the code, I'm not sure what all the options available are for value/field. + * + * @param value + * @param field + */ + escape(value: any, field: any): string; + getForeignKeysQuery(tableName: string, schemaName: string): string; + dropForeignKeyQuery(tableName: string, foreignKey: string): string; + selectQuery(tableName: string, options: SelectOptions, model?: Model): string; + selectQuery(tableName: Array, options: SelectOptions, model?: Model): string; + selectQuery(tableName: Array>, options: SelectOptions, model?: Model): string; + setAutocommitQuery(value: boolean): string; + setIsolationLevelQuery(value: string): string; + /** + * Returns start transaction query. Options is not used. + * @param options + */ + startTransactionQuery(options?: any): string; + /** + * Returns start transaction query. Options is not used. + * @param options + */ + commitTransactionQuery(options?: any): string; + /** + * Returns start transaction query. Options is not used. + * @param options + */ + rollbackTransactionQuery(options?: any): string; + addLimitAndOffset(options: SelectOptions, query?: string): string; + getWhereConditions(smth: any, tableName: string, factory: Model, options?: any, prepend?: boolean): string; + prependTableNameToHash(tableName: string, hash?: any): string; + findAssociation(attribute: string, dao: Model): string; + getAssociationFilterDAO(filterStr: string, dao: Model): string; + isAssociationFilter(filterStr: string, dao: Model, options?: any): string; + getAssociationFilterColumn(filterStr: string, dao: Model, options?: { include: boolean }): string; + getConditionalJoins(options: { where?: any }, originalDao: Model): string; + arrayValue(value: Array, key: string, _key: string, factory?: any, logicResult?: any): string; + hashToWhereConditions(hash: any, dao: Model, options?: HashToWhereConditionsOption): string; + booleanValue(value: boolean): string; + } + + interface Schema { + tableName: string; + table: string; + name: string; + schema: string; + delimiter: string; + } + + interface QueryTypes { + SELECT: string; + BULKUPDATE: string; + BULKDELETE: string; + } + + interface ModelManager { + daos: Array>; + sequelize: Sequelize; + addDAO(dao: Model): Model; + removeDAO(dao: Model): void; + getDAO(daoName: string, options?: ModelMangerGetDaoOptions): Model; + all: Array>; + + /** + * Iterate over DAOs in an order suitable for e.g. creating tables. Will + * take foreign key constraints into account so that dependencies are visited + * before dependents. + */ + forEachDAO(iterator: (dao: Model, name: string) => void, options?: ModelManagerForEachDaoOptions): void; + } + + interface TransactionManager { + sequelize: Sequelize; + connectorManagers: any; + getConnectorManager(uuid?: string): ConnectorManager; + releaseConnectionManager(uuid?: string): void; + + /** + * Execute a query on the DB, with the possibility to bypass all the sequelize goodness. + * + * @param sql SQL statement to execute. + * + * @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented + * by the factory. Equivalent to calling Model.build with the values provided by the query. + * + * @param options Query options. + * + */ + query(sql: string, callee?: Model, options?: QueryOptions): EventEmitter; + + query(sql: string, callee?: Model, options?: QueryOptions): EventEmitter; + } + + interface ConnectorManager { + + /** + * Execute a query on the DB, with the possibility to bypass all the sequelize goodness. + * + * @param sql SQL statement to execute. + * + * @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented + * by the factory. Equivalent to calling Model.build with the values provided by the query. + * + * @param options Query options. + * + */ + query(sql: string, callee?: Model, options?: QueryOptions): EventEmitter; + + afterTransactionSetup(callback: () => void): void; + connect(): void; + disconnect(): void; + reconnect(): void; + cleanup(): void; + } + + interface Migrator { + queryInterface: QueryInterface; + migrate(options?: MigratorOptions): EventEmitter; + getUndoneMigrations(callback: (err: Error, result: Array) => void): void; + findOrCreateMetaDAO(syncOptions?: SyncOptions): EventEmitter; + exec(filename: string, options?: MigratorExecOptions): EventEmitter; + getLastMigrationFromDatabase(): EventEmitter; + getLastMigrationIdFromDatabase(): EventEmitter; + getFormattedDateString(s: string): string; + stringToDate(s: string): Date; + saveSuccessfulMigration(from: Migration, to: Migration, callback: (metaData: MetaInstance) => void): void; + deleteUndoneMigration(from: Migration, to: Migration, callback: () => void): void; + execute(options?: MigrationExecuteOptions): EventEmitter; + isBefore(date: Date, options?: MigrationCompareOptions): boolean; + isAfter(date: Date, options?: MigrationCompareOptions): boolean; + + } + + interface Migration extends QueryInterface { + migrator: Migrator; + path: string; + filename: string; + migrationId: number; + date: Date; + queryInterface: QueryInterface; + migration: (err: Error, migration: Migration, dataTypes: any, callback: (err: Error) => void) => void; + + } + + interface EventEmitter extends EventEmitterT, NodeJS.EventEmitter { } + + interface EventEmitterT extends NodeJS.EventEmitter { + /** + * Create a new emitter instance. + * + * @param handler + */ + new (handler: (emitter: EventEmitterT) => void): EventEmitterT; + + /** + * Run the function that was passed when the emitter was instantiated. + */ + run(): EventEmitterT; + + /** + * Listen for success events. + * + * @param onSuccess + */ + success(onSuccess: (result: R) => void): EventEmitterT; + + /** + * Alias for success(handler). Listen for success events. + * + * @param onSuccess + */ + ok(onSuccess: (result: R) => void): EventEmitterT; + + /** + * Listen for error events. + * + * @param onError + */ + error(onError: (err: Error) => void): EventEmitterT; + + /** + * Alias for error(handler). Listen for error events. + * + * @param onError + */ + fail(onError: (err: Error) => void): EventEmitterT; + + /** + * Alias for error(handler). Listen for error events. + * + * @param onError + */ + failure(onError: (err: Error) => void): EventEmitterT; + + /** + * Listen for both success and error events. + * + * @param onDone + */ + done(onDone: (err: Error, result: R) => void): EventEmitterT; + + /** + * Alias for done(handler). Listen for both success and error events. + * + * @param onDone + */ + complete(onDone: (err: Error, result: R) => void): EventEmitterT; + + /** + * Attach a function that is called every time the function that created this emitter executes a query. + * + * @param onSQL + */ + sql(onSQL: (sql: string) => void): EventEmitterT; + + /** + * Proxy every event of this event emitter to another one. + * + * @param emitter The event emitter that should receive the events. + * @param options Contains an array of the events to proxy. Defaults to sql, error and success + */ + proxy(emitter: EventEmitterT, options?: ProxyOptions): EventEmitterT; + + + } + + interface Options { + /** + * The dialect you of the database you are connecting to. One of mysql, postgres, sqlite and mariadb. + * Default is mysql. + */ + dialect?: string; + + /** + * If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when + * connecting to a pg database, you should specify 'pg.js' here + */ + dialectModulePath?: string; + + /** + * The host of the relational database. Default 'localhost'. + */ + host?: string; + + /** + * Integer The port of the relational database. + */ + port?: number; + + /** + * The protocol of the relational database. Default 'tcp'. + */ + protocol?: string; + + /** + * Default options for model definitions. See sequelize.define for options. + */ + define?: DefineOptions; + + /** + * Default options for sequelize.query + */ + query?: QueryOptions; + + /** + * Default options for sequelize.sync + */ + sync?: SyncOptions; + + /** + * The timezone used when converting a date from the database into a javascript date. The timezone is also used to + * SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time + * related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. + * Default '+00:00'. + */ + timezone?: string; + + /** + * Logging options. Function used to log. Default is console.log. Signature is (message:string) => void. + * + * Set to "false" to disable logging. + */ + logging?: any; + + /** logging=console.log] Function A function that gets executed everytime Sequelize would log something. + * A flag that defines if null values should be passed to SQL queries or not. + */ + omitNull?: boolean; + + /** + * Boolean Queue queries, so that only maxConcurrentQueries number of queries are executing at once. If false, all + * queries will be executed immediately. + */ + queue?: boolean; + + /** + * The maximum number of queries that should be executed at once if queue is true. + */ + maxConcurrentQueries?: number; + + /** + * A flag that defines if native library shall be used or not. Currently only has an effect for postgres + */ + native?: boolean; + + /** + * Use read / write replication. To enable replication, pass an object, with two properties, read and write. Write + * should be an object (a single server for handling writes), and read an array of object (several servers to + * handle reads). Each read/write server can have the following properties?: host, port, username, password, database + */ + replication?: ReplicationOptions; + + /** + * Connection pool options. + * + */ + pool?: PoolOptions; + + /** + * Set to false to make table names and attributes case-insensitive on Postgres and skip double quoting of them. + * Default true. + */ + quoteIdentifiers?: boolean; + + /** + * Language. Default "en". + */ + language?: string; + } + + interface PoolOptions { + maxConnections?: number; + + minConnections?: number; + + /** + * The maximum time, in milliseconds, that a connection can be idle before being released. + */ + maxIdleTime?: number; + + /** + * A function that validates a connection. Called with client. The default function checks that client is an + * object, and that its state is not disconnected. + * + * Note, this is not documented, and after reading code I'm not sure what client's type is. + */ + validateConnection?: (client?: any) => boolean; + } + + interface AttributeOptions { + /** + * A string or a data type + */ + type?: string; + + /** + * If false, the column will have a NOT NULL constraint, and a not null validation will be run before an instance + * is saved. + */ + allowNull?: boolean; + + /** + * A literal default value, a javascript function, or an SQL function (see sequelize.fn) + */ + defaultValue?: any; + + /** + * If true, the column will get a unique constraint. If a string is provided, the column will be part of a + * composite unique index. If multiple columns have the same string, they will be part of the same unique index. + */ + unique?: any; + + primaryKey?: boolean; + + /** + * If set, sequelize will map the attribute name to a different name in the database. + */ + field?: string; + + autoIncrement?: boolean; + + comment?: string; + + /** + * If this column references another table, provide it here as a Model, or a string. + */ + references?: any; + + /** + * The column of the foreign table that this column references. Default 'id'. + */ + referencesKey?: string; + + /** + * What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or + * NO ACTION. + */ + onUpdate?: string; + + /** + * What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or + * NO ACTION. + */ + onDelete?: string; + + /** + * Provide a custom getter for this column. Use this.getDataValue(String) to manipulate the underlying values. + */ + get?: () => any; + + /** + * Provide a custom setter for this column. Use this.setDataValue(String, Value) to manipulate the underlying values. + */ + set?: (value?: any) => void; + + /** + * An object of validations to execute for this column every time the model is saved. Can be either the name of a + * validation provided by validator.js, a validation function provided by extending validator.js (see the + * DAOValidator property for more details), or a custom validation function. Custom validation functions are called + * with the value of the field, and can possibly take a second callback argument, to signal that they are + * asynchronous. If the validator is sync, it should throw in the case of a failed validation, it it is async, + * the callback should be called with the error text. + */ + validate?: any; + } + + interface ForeignKeyAttributeOptions extends AttributeOptions { + /** + * The name of the foreign key in the target table. Defaults to the name of source + primary key of source. + */ + fieldName: string; + } + + interface DefineOptions { + /** + * Define the default search scope to use for this model. Scopes have the same form as the options passed to + * find / findAll. + */ + defaultScope?: FindOptions; + + /** + * More scopes, defined in the same way as defaultScope above. See Model.scope for more information about how + * scopes are defined, and what you can do with them + */ + scopes?: any; + + /** + * Don't persits null values. This means that all columns with null values will not be saved. + */ + omitNull?: boolean; + + /** + * Adds createdAt and updatedAt timestamps to the model. Default true. + */ + timestamps?: boolean; + + /** + * Calling destroy will not delete the model, but instead set a deletedAt timestamp if this is true. Needs + * timestamps=true to work. Default false. + */ + paranoid?: boolean; + + /** + * Converts all camelCased columns to underscored if true. Default false. + */ + underscored?: boolean; + + /** + * Converts camelCased model names to underscored tablenames if true. Default false. + */ + underscoredAll?: boolean; + + /** + * If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. Otherwise, the + * dao name will be pluralized. Default false. + */ + freezeTableName?: boolean; + + /** + * Override the name of the createdAt column if a string is provided, or disable it if false. Timestamps must be true. + */ + createdAt?: any; + + /** + * Override the name of the updatedAt column if a string is provided, or disable it if false. Timestamps must be true. + */ + updatedAt?: any; + + /** + * Override the name of the deletedAt column if a string is provided, or disable it if false. Timestamps must be true. + */ + deletedAt?: any; + + /** + * Defaults to pluralized DAO name, unless freezeTableName is true, in which case it uses DAO name verbatim. + */ + tableName?: string; + + /** + * Provide getter functions that work like those defined per column. If you provide a getter method with the same + * name as a column, it will be used to access the value of that column. If you provide a name that does not match + * a column, this function will act as a virtual getter, that can fetch multiple other values. + */ + getterMethods?: any; + + /** + * Provide setter functions that work like those defined per column. If you provide a setter method with the same + * name as a column, it will be used to update the value of that column. If you provide a name that does not match + * a column, this function will act as a virtual setter, that can act on and set other values, but will not be + * persisted + */ + setterMethods?: any; + + /** + * Provide functions that are added to each instance (DAO). + */ + instanceMethods?: any; + + /** + * Provide functions that are added to the model (Model). + */ + classMethods?: any; + + /** + * Default 'public'. + */ + schema?: string; + schemaDelimiter?: string; + engine?: string; + charset?: string; + comment?: string; + collate?: string; + whereCollection?: any; + language?: string; + + /** + * An object of hook function that are called before and after certain lifecycle events. The possible hooks are?: + * beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, + * beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, afterBulkCreate, afterBulkDestory and + * afterBulkUpdate. See Hooks for more information about hook functions and their signatures. Each property can + * either be a function, or an array of functions. + */ + hooks?: Hooks; + + /** + * An object of model wide validations. Validations have access to all model values via this. If the validator + * function takes an argument, it is assumed to be async, and is called with a callback that accepts an optional + * error. + */ + validate?: any; + + /** + * + */ + indexes?: Array; + } + + interface DefineIndexOptions { + /** + * The name of the index. Defaults to model name + _ + fields concatenated. + */ + name?: string; + + /** + * Index type. Only used by mysql. One of UNIQUE, FULLTEXT and SPATIAL. + */ + type: string; + + /** + * The method to create the index by (USING statement in SQL). BTREE and HASH are supported by mysql and postgres, + * and postgres additionally supports GIST and GIN. + */ + method: string; + + /** + * Should the index by unique? Can also be triggered by setting type to UNIQUE. Default false (unless type = "UNIQUE", + * then true). + */ + unique?: boolean; + + /** + * PostgreSQL will build the index without taking any write locks. Postgres only. Default false. + */ + concurrently?: boolean; + + /** + * An array of the fields to index. Each field can either be a string containing the name of the field, or an object + * with the following attributes: attribute (field name), length (create a prefix index of length chars), order (the + * direction the column should be sorted in), collate (the collation (sort order) for the column) + */ + fields: Array; + } + + interface QueryOptions { + /** + * If true, sequelize will not try to format the results of the query, or build an instance of a model from the + * result. + */ + raw?: boolean; + + /** + * The transaction that the query should be executed under. + */ + transaction?: Transaction; + + /** + * The type of query you are executing. The query type affects how results are formatted before they are passed + * back. If no type is provided sequelize will try to guess the right type based on the sql, and fall back to + * SELECT. The type is a string, but Sequelize.QueryTypes is provided is convenience shortcuts. Current options + * are SELECT, BULKUPDATE and BULKDELETE. + * + * Default is SELECT. + */ + type?: string; + + /** + * Lock the selected rows in either share or update mode. Possible options are transaction.LOCK.UPDATE and + * transaction.LOCK.SHARE. See transaction.LOCK for an example. + */ + lock?: string; + + /** + * For aggregate function calls, the type of the result. If field is a field in this Model, the default will be the + * type of that field, otherwise defaults to float. + */ + dataType?: any; + + /** + * A function that logs sql queries, or false for no logging. + */ + logging?: any; + + /** + * If plain is true, then sequelize will only return the first record of the result set. In case of false it will + * all records. + */ + plain?: boolean; + } + + interface SyncOptions { + /** + * If force is true, each DAO will do DROP TABLE IF EXISTS ..., before it tries to create its own table. + * Default false. + */ + force?: boolean; + + /** + * A function that logs sql queries, or false for no logging. + */ + logging?: any; + + /** + * The schema that the tables should be created in. This can be overriden for each table in sequelize.define. + * Default 'public'. + */ + schema?: string; + } + + interface ReplicationOptions { + read?: Array; + write?: Server; + } + + interface Server { + host?: string; + port?: number; + database?: string; + username?: string; + password?: string; + } + + interface DropOptions { + /** + * Also drop all objects depending on this table, such as views. Only works in postgres. + * + * Default false. + */ + cascade?: boolean; + } + + interface SchemaOptions { + /** + * The character(s) that separates the schema name from the table name. Default '.'. + */ + schemaDelimiter?: string; + } + + interface FindOptions { + /** + * A hash of attributes to describe your search. + */ + where?: any; + + /** + * A list of the attributes that you want to select. To rename an attribute, you can pass an array, with two + * elements - the first is the name of the attribute in the DB (or some kind of expression such as + * Sequelize.literal, Sequelize.fn and so on), and the second is the name you want the attribute to have in the + * returned instance + */ + attributes?: Array; + + /** + * A list of associations to eagerly load. Supported is either { include?: [ Model1, Model2, ...] } or { include?: + * [ { model?: Model1, as?: 'Alias' } ] }. If your association are set up with an as (eg. X.hasMany(Y, { as?: 'Z }, + * you need to specify Z in the as attribute when eager loading Y). When using the object form, you can also + * specify attributes to specify what columns to load, where to limit the relations, and include to load further + * nested relations + */ + include?: any; + + /** + * Specifies an ordering. If a string is provided, it will be esacped. Using an array, you can provide several + * columns / functions to order by. Each element can be further wrapped in a two-element array. The first element + * is the column / function to order by, the second is the direction. For example?: order?: [['name', 'DESC']]. In + * this way the column will be escaped, but the direction will not. + */ + order?: any; + + limit?: number; + + offset?: number; + } + + interface BuildOptions { + /** + * If set to true, values will ignore field and virtual setters. Default false. + */ + raw?: boolean; + + /** + * Default true. + */ + isNewRecord?: boolean; + + /** + * Default true. + */ + isDirty?: boolean; + + /** + * an array of include options - Used to build prefetched/included model instances. See set. + */ + include?: Array; + } + + interface CopyOptions extends BuildOptions { + /** + * If set, only columns matching those in fields will be saved. + */ + fields?: Array; + + /** + * + */ + transaction?: Transaction; + } + + interface FindOrCreateOptions extends FindOptions, QueryOptions { + + } + + interface BulkCreateOptions { + /** + * Fields to insert (defaults to all fields). + */ + fields?: Array; + + /** + * Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails + * validation. Default false. + */ + validate?: boolean; + + /** + * Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run. Default false; + */ + hooks?: boolean; + + /** + * Ignore duplicate values for primary keys? (not supported by postgres). Default false. + */ + ignoreDuplicates?: boolean; + } + + interface DestroyOptions { + /** + * If set to true, destroy will find all records within the where parameter and will execute before-/ after + * bulkDestroy hooks on each row. + */ + hooks?: boolean; + + /** + * How many rows to delete + */ + limit?: number; + + /** + * If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is truncated the + * where and limit options are ignored. + */ + truncate?: boolean; + } + + interface DestroyInstanceOptions { + /** + * If set to true, paranoid models will actually be deleted. + */ + force: boolean; + } + + interface InsertOptions { + limit?: number; + returning?: string; + allowNull?: string; + } + + interface UpdateOptions { + /** + * Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails + * validation. Default true. + */ + validate?: boolean; + + /** + * Run before / after bulkUpdate hooks? Default false. + */ + hooks?: boolean; + + /** + * How many rows to update (only for mysql and mariadb). + */ + limit?: number; + } + + interface SetOptions { + /** + * If set to true, field and virtual setters will be ignored. Default false. + */ + raw?: boolean; + + /** + * Clear all previously set data values. Default false. + */ + reset?: boolean; + + include?: any; + } + + interface SaveOptions { + /** + * An alternative way of setting which fields should be persisted. + */ + fields?: any; + + /** + * If true, the updatedAt timestamp will not be updated. Default false. + */ + silent?: boolean; + + transaction?: Transaction; + } + + interface ValidateOptions { + /** + * An array of strings. All properties that are in this array will not be validated. + */ + skip: Array; + } + + interface IncrementOptions { + /** + * The number to increment by. Default 1. + */ + by?: number; + + transaction?: Transaction; + } + + interface IndexOptions { + indicesType?: string; + indexType?: string; + indexName?: string; + parser?: any; + } + + interface ProxyOptions { + /** + * An array of the events to proxy. Defaults to sql, error and success. + */ + events: Array; + } + + interface AssociationOptions { + /** + * Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For + * example if User.hasOne(Profile, {onDelete: 'cascade', hooks:true}), the before-/afterDestroy hooks for profile + * will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks. + * Default false. + */ + hooks?: boolean; + + /** + * The 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?: any; + + /** + * The alias of this model. If you create multiple associations between the same tables, you should provide an + * alias to be able to distinguish between them. If you provide an alias when creating the assocition, you should + * provide the same alias when eager loading and when getting assocated models. Defaults to the singularized + * version of target.name + */ + as?: string; + + /** + * The foreignKey can be either a string name of the foreign key in the target table, + * or can be an object defining the foreign key and its options. Note foreignKey is not fully + * typed since TypeScript does not support union types--it can be either a string or an + * options object. String name defaults to the name of source + primary key of source. + * + * @see ForeignKeyAttributeOptions. + */ + foreignKey?: any; + + /** + * What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or + * NO ACTION. Default SET NULL. + */ + onDelete?: string; + + /** + * What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or + * NO ACTION. Default CASCADE. + */ + onUpdate?: string; + + /** + * Should on update and on delete constraints be enabled on the foreign key. + */ + constraints?: boolean; + } + + interface TriggerOptions { + insert?: Array; + update?: Array; + delete?: Array; + truncate?: Array; + } + + interface TriggerParam { + type: string; + direction?: string; + name?: string; + } + + interface SelectOptions { + limit?: number; + offset?: number; + attributes?: Array; + hasIncludeWhere?: boolean; + hasIncludeRequired?: boolean; + hasMultiAssociation?: boolean; + tableAs?: string; + table?: string; + include?: Array; + includeIgnoreAttributes?: boolean; + where?: any; + /** + * String field name or array of strings of field names. + */ + group?: any; + having?: any; + order?: any; + lock?: string; + } + + interface HashToWhereConditionsOption { + include?: boolean; + keysEscaped?: boolean; + } + + interface ModelMangerGetDaoOptions { + attribute: string; + } + + interface ModelManagerForEachDaoOptions { + /** + * Default true. + */ + reverse: boolean; + } + + interface MigratorOptions { + /** + * A flag that defines if the migrator should get instantiated or not.. + */ + force: boolean; + } + + interface FindAndCountResult { + /** + * The matching model instances. + */ + rows?: Array; + + /** + * The total number of rows. This may be more than the rows returned if a limit and/or offset was supplied. + */ + count?: number; + } + + interface Col { + /** + * Column name. + */ + col: string; + } + + interface Cast { + /** + * The value to cast. + */ + val: any; + + /** + * The type to cast it to. + */ + type: string; + } + + interface Literal { + val: any; + } + + interface And { + /** + * Each argument (string or object) will be joined by AND. + */ + args: Array; + } + + interface Or { + /** + * Each argument (string or object) will be joined by OR. + */ + args: Array; + } + + interface Where { + /** + * The attribute. + */ + attribute: string; + + /** + * The condition. Can be both a simply type, or a further condition (.or, .and, .literal etc.). + */ + logic: any; + } + + interface TransactionOptions { + /** + * + */ + autocommit?: boolean; + + /** + * One of: 'READ UNCOMMITTED', 'READ COMMITTED', 'REPEATABLE READ', 'SERIALIZABLE'. Default 'REPEATABLE READ'. + */ + isolationLevel?: string; + } + + interface QueryChainerRunSeriallyOptions { + /** + * If set to true, all pending emitters will be skipped if a previous emitter failed. Default false. + */ + skipOnError: boolean; + } + + interface CreateTableQueryOptions { + comment?: string; + uniqueKeys?: Array; + charset?: string; + } + + interface MigratorExecOptions { + before?: (migrator: Migrator) => void; + after?: (migrator: Migrator) => void; + success?: (migrator: Migrator) => void; + } + + interface MigrationExecuteOptions { + method: string; + } + + interface MigrationCompareOptions { + /** + * Default false. + */ + withoutEquals: boolean; + } + + interface Promise { + /** + * Listen for events, event emitter style. Mostly for backwards compatibility with EventEmitter. + * + * @param evt Event + * @param fct Handler + */ + on(evt: string, fct: () => void): void; + + /** + * Emit an event from the emitter. + * + * @param type The type of event. + * @param value All other arguments will be passed to the event listeners. + */ + emit(type: string, ...value: Array): void; + + /** + * Listen for success events. + */ + success(onSuccess: () => void): Promise; + + /** + * Alias for success(handler). Listen for success events. + */ + ok(onSuccess: () => void): Promise; + + /** + * Listen for error events. + * + * @param onError Error handler. + */ + error(onError: (err?: Error) => void): Promise; + + /** + * Alias for error(handler). Listen for error events. + * + * @param onError Error handler. + */ + fail(onError: (err?: Error) => void): Promise; + + /** + * Alias for error(handler). Listen for error events. + * + * @param onError Error handler. + */ + failure(onError: (err?: Error) => void): Promise; + + /** + * Listen for both success and error events.. + */ + done(handler: (err: Error, result?: any) => void): Promise; + + /** + * Alias for done(handler). Listen for both success and error events.. + */ + complete(handler: (err: Error, result?: any) => void): Promise; + + /** + * Attach a function that is called every time the function that created this emitter executes a query. + * + * @param onSQL + */ + sql(onSQL: (sql: string) => void): Promise; + + /** + * Proxy every event of this promise to another one. + * + * @param promise The promise that should receive the events. + * @param options Contains an array of the events to proxy. Defaults to sql, error and success + */ + proxy(promise: Promise, options?: ProxyOptions): Promise; + + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => void, onRejected?: (result?: any) => void): Promise; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => Promise, onRejected?: (result?: any) => Promise): Promise; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => PromiseT, onRejected?: (result?: any) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => PromiseT, onRejected?: (result?: any) => void): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => void, onRejected?: (result?: any) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => PromiseT, onRejected?: (result?: any) => PromiseT): Promise; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => Promise, onRejected?: (...results: Array) => Promise): Promise; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => void, onRejected?: (...results: Array) => void): Promise; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => Promise, onRejected?: (...results: Array) => void): Promise; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => void, onRejected?: (...results: Array) => Promise): Promise; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => PromiseT, onRejected?: (...results: Array) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => void, onRejected?: (...results: Array) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => PromiseT, onRejected?: (...results: Array) => void): PromiseT; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => PromiseT, onRejected?: (...results: Array) => PromiseT): Promise; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: any) => Promise): Promise; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: any) => PromiseT): PromiseT; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: any) => void): Promise; + } + + interface PromiseT extends Promise { + /** + * Listen for events, event emitter style. Mostly for backwards compatibility with EventEmitter. + * + * @param evt Event + * @param fct Handler + */ + on(evt: string, fct: (t: T) => void): void; + + /** + * Emit an event from the emitter. + * + * @param type The type of event. + * @param value All other arguments will be passed to the event listeners. + */ + emit(type: string, ...value: Array): void; + + /** + * Listen for success events. + */ + success(onSuccess: (t: T) => void): PromiseT; + + /** + * Alias for success(handler). Listen for success events. + */ + ok(onSuccess: (t: T) => void): PromiseT; + + /** + * Listen for both success and error events.. + */ + done(handler: (err: Error, result: T) => void): PromiseT; + + /** + * Alias for done(handler). Listen for both success and error events.. + */ + complete(handler: (err: Error, result: T) => void): PromiseT; + + /** + * Attach a function that is called every time the function that created this emitter executes a query. + * + * @param onSQL + */ + sql(onSQL: (sql: string) => void): PromiseT; + + /** + * Proxy every event of this promise to another one. + * + * @param promise The promise that should receive the events. + * @param options Contains an array of the events to proxy. Defaults to sql, error and success + */ + proxy(promise: PromiseT, options?: ProxyOptions): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => void, onRejected?: (result?: T) => void): Promise; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => Promise, onRejected?: (result?: T) => Promise): Promise; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => PromiseT, onRejected?: (result?: T) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => PromiseT, onRejected?: (result?: T) => void): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => void, onRejected?: (result?: T) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => PromiseT, onRejected?: (result?: T) => PromiseT): Promise; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: T) => Promise): Promise; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: T) => PromiseT): PromiseT; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: T) => void): Promise; + } + + interface Utils { + _: Lodash; + + /** + * Formats a string to parse and interpolate values into the string based on the optionally provided SQL dialect. + * @param arr Array where first element is string with placeholders and remaining attributes are values to replace placeholders. + * @param dialect SQL Dialect. + */ + format(arr: Array, dialect?: string): string; + + /** + * Formats a SQL string replacing named placeholders with values from the parameters object with matching key names. + * + * @param sql String to format. + * @param parameters Key/value hash with values to replace in string. + * @param dialect SQL Dialect + */ + formatNamedParameters(sql: string, parameters: any, dialect?: string): string; + + injectScope(scope: string, merge: boolean): any; + + smartWhere(whereArg: any, dialect: string): any; + + compileSmartWhere(obj: any, dialect: string): Array; + + getWhereLogic(logic: string, val?: any): string; + + isHash(obj: any): boolean; + + hasChanged(attrValue: any, value: any): boolean; + + argsArePrimaryKeys(args: Array, primaryKeys: any): boolean; + + /** + * Consistently combines two table names such that the alphabetically first name always comes first when combined. + * + * @param table1 + * @param table2 + */ + combineTableNames(table1: string, table2: string): string; + + singularize(s: string, language?: string): string; + + pluralize(s: string, language: string): string; + + /** + * Same concept as _.merge, but don't overwrite properties that have already been assigned + */ + mergeDefaults: typeof _.merge; + + lowercaseFirst(str: string): string; + + uppercaseFirst(str: string): string; + + spliceStr(str: string, index: number, count: number, add: string): string; + + camelize(str: string): string; + + removeCommentsFromFunctionString(s: string): string; + + toDefaultValue(value: any): any; + + defaultValueSchemable(value: any): boolean; + setAttributes(hash: any, identifier: string, instance: any, prefix: string): any; + removeNullValuesFromHash(hash: any, omitNull: boolean, options: any): any; + firstValueOfHash(obj: any): any; + inherit(subClass: any, superClass: any): any; + stack(): string; + now(dialect: string): Date; + + /** + * Runs provided function on next tick, depending on environment. + * + * @param f + */ + tick(f: Function): void; + + /** + * Surrounds a string with tick marks while removing all existing tick marks from the string. + * @param s String to tick + * @param tickChar Tick mark. Default ` + */ + addTicks(s: string, tickChar?: string): string; + + removeTicks(s: string, tickChar?: string): string; + + generateUUID(): string; + + validateParameter(value: any, expectation: any): boolean; + + CustomEventEmitter: EventEmitter; + Promise: Promise; + QueryChainer: QueryChainer; + Lingo: any; // external project, no definitions yet} + } + + interface Lodash extends _.LoDashStatic { + camelizeIf(str: string, condition: boolean): string; + camelizeIf(str: string, condition: any): string; + underscoredIf(str: string, condition: boolean): string; + underscoredIf(str: string, condition: any): string; + /** + * * Returns an array with some falsy values removed. The values null, "", undefined and NaN are considered falsey. + * + * @param arr Array to compact. + */ + compactLite(arr: Array): Array; + } + + interface MetaPojo { + from: string; + to: string; + } + interface MetaInstance extends MetaPojo, Model { + + } + + interface DataTypeStringBase { + BINARY: DataTypeString; + } + interface DataTypeNumberBase { + UNSIGNED: boolean; + ZEROFILL: boolean; + } + + interface DataTypeString extends DataTypeStringBase { + } + interface DataTypeChar extends DataTypeStringBase { + } + interface DataTypeInteger extends DataTypeNumberBase { + } + interface DataTypeBigInt extends DataTypeNumberBase { + } + interface DataTypeFloat extends DataTypeNumberBase { + } + interface DataTypeBlob { + } + interface DataTypeDecimal { + PRECISION: number; + SCALE: number; + } + + interface DataTypeVirtual { + } + interface DataTypeEnum { + (...values: Array): DataTypeEnum; + } + interface DataTypeArray { + } + interface DataTypeHstore { + } + + interface DataTypes { + STRING: DataTypeString; + CHAR: DataTypeChar; + TEXT: string; + INTEGER: DataTypeInteger; + BIGINT: DataTypeBigInt; + DATE: string; + BOOLEAN: string; + FLOAT: DataTypeFloat; + NOW: string; + BLOB: DataTypeBlob; + DECIMAL: DataTypeDecimal; + UUID: string; + UUIDV1: string; + UUIDV4: string; + VIRTUAL: DataTypeVirtual; + NONE: DataTypeVirtual; + ENUM: DataTypeEnum; + ARRAY: DataTypeArray; + HSTORE: DataTypeHstore; + } + } + + var sequelize: sequelize.SequelizeStatic; + + export = sequelize; +} diff --git a/sequelize/sequelize-test.ts b/sequelize/sequelize-test.ts new file mode 100644 index 000000000..ebc8cc0ce --- /dev/null +++ b/sequelize/sequelize-test.ts @@ -0,0 +1,1284 @@ +/// + +import Sequelize = require("sequelize"); + +// +// Fixtures +// ~~~~~~~~~~ +// + +interface AnyAttributes { }; +interface AnyInstance extends Sequelize.Instance { }; + +var s = new Sequelize( '' ); +var sequelize = s; +var DataTypes = Sequelize; +var User = s.define( 'user', {} ); +var user = User.build(); +var Task = s.define( 'task', {} ); +var Group = s.define( 'group', {} ); +var Comment = s.define( 'comment', {} ); +var Post = s.define( 'post', {} ); +var t = null; +s.transaction().then( ( a ) => t = a ); + +// +// Generics +// ~~~~~~~~~~ +// + +interface GUserAttributes { + id? : number; + username? : string; +} + +interface GUserInstance extends Sequelize.Instance {} +var GUser = s.define( 'user', { id: Sequelize.INTEGER, username : Sequelize.STRING }); +GUser.create({ id : 1, username : 'one' }).then( ( guser ) => guser.save() ); + +var schema : Sequelize.DefineAttributes = { + key : { type : Sequelize.STRING, primaryKey : true }, + value : Sequelize.STRING +}; + +s.define('user', schema); + +interface GTaskAttributes { + revision? : number; + name? : string; +} +interface GTaskInstance extends Sequelize.Instance {} +var GTask = s.define( 'task', { revision : Sequelize.INTEGER, name : Sequelize.STRING }); + +GUser.hasMany(GTask); + + + +// +// Associations +// ~~~~~~~~~~~~~~ +// +// https://github.com/sequelize/sequelize/tree/v3.4.1/test/integration/associations +// + +User.hasOne( Task ); +User.hasOne( Task, { foreignKey : 'primaryGroupId', as : 'primaryUsers' } ); +User.hasOne( Task, { foreignKey : 'userCoolIdTag' } ); +User.hasOne( Task, { foreignKey : 'userId', keyType : Sequelize.STRING, constraints : false } ); +Task.hasOne( User, { foreignKey : { name : 'taskId', field : 'task_id' } } ); +User.hasOne( Task, { foreignKey : { name : 'uid', allowNull : false } } ); +User.hasOne( Task, { onDelete : 'cascade' } ); +User.hasOne( Task, { onUpdate : 'cascade' } ); +User.hasOne( Task, { onDelete : 'cascade', hooks : true } ); +User.hasOne( Task, { foreignKey : { allowNull : false } } ); +User.hasOne( Task, { foreignKeyConstraint : true } ); + +User.belongsTo( Task ); +User.belongsTo( Task, { foreignKey : 'primaryGroupId', as : 'primaryUsers' } ); +Task.belongsTo( User, { foreignKey : 'user_id' } ); +Task.belongsTo( User, { foreignKey : 'user_name', targetKey : 'username' } ); +User.belongsTo( User, { foreignKey : 'userId', keyType : Sequelize.STRING, constraints : false } ); +User.belongsTo( Post, { foreignKey : { name : 'AccountId', field : 'account_id' } } ); +Task.belongsTo( User, { foreignKey : { allowNull : false, name : 'uid' } } ); +Task.belongsTo( User, { constraints : false } ); +Task.belongsTo( User, { onDelete : 'cascade' } ); +Task.belongsTo( User, { onUpdate : 'restrict' } ); +User.belongsTo( User, { + as : 'parentBlocks', + foreignKey : 'child', + foreignKeyConstraint : true +} ); + +User.hasMany( User ); +User.hasMany( User, { foreignKey : 'primaryGroupId', as : 'primaryUsers' } ); +User.hasMany( Task, { foreignKey : 'userId' } ); +User.hasMany( Task, { foreignKey : 'userId', as : 'activeTasks', scope : { active : true } } ); +User.hasMany( Task, { foreignKey : 'userId', keyType : Sequelize.STRING, constraints : false } ); +User.hasMany( Task, { foreignKey : { name : 'uid', allowNull : false } } ); +User.hasMany( Task, { foreignKey : { allowNull : true } } ); +User.hasMany( Task, { as : 'Children' } ); +User.hasMany( Task, { as : { singular : 'task', plural : 'taskz' } } ); +User.hasMany( Task, { constraints : false } ); +User.hasMany( Task, { onDelete : 'cascade' } ); +User.hasMany( Task, { onUpdate : 'cascade' } ); +Post.hasMany( Task, { foreignKey : 'commentable_id', scope : { commentable : 'post' } } ); +User.hasMany( User, { + as : 'childBlocks', + foreignKey : 'parent', + foreignKeyConstraint : true +} ); + +User.belongsToMany( Task, { through : 'UserTasks' } ); +User.belongsToMany( User, { through : Task } ); +User.belongsToMany( Group, { as : 'groups', through : Task, foreignKey : 'id_user' } ); +User.belongsToMany( Task, { as : 'activeTasks', through : Task, scope : { active : true } } ); +User.belongsToMany( Task, { as : 'startedTasks', through : { model : Task, scope : { started : true } } } ); +User.belongsToMany( Group, { through : 'group_members', foreignKey : 'group_id', otherKey : 'member_id' } ); +User.belongsToMany( User, { as : 'Participants', through : User } ); +User.belongsToMany( Group, { through : 'user_places', foreignKey : 'user_id' } ); +User.belongsToMany( Group, { + through : 'user_projects', + as : 'Projects', + foreignKey : { + field : 'user_id', + name : 'userId' + }, + otherKey : { + field : 'project_id', + name : 'projectId' + } +} ); +User.belongsToMany( Task, { onDelete : 'RESTRICT', through : 'tasksusers' } ); +User.belongsToMany( Task, { constraints : false, through : 'tasksusers' } ); +User.belongsToMany( Task, { foreignKey : { name : 'user_id', defaultValue : 42 }, through : 'UserProjects' } ); +User.belongsToMany( Post, { through : User } ); +Post.belongsToMany( User, { as : 'categories', through : User, scope : { type : 'category' } } ); +Post.belongsToMany( User, { as : 'tags', through : User, scope : { type : 'tag' } } ); +Post.belongsToMany( User, { + through : { + model : User, + unique : false, + scope : { + taggable : 'post' + } + }, + foreignKey : 'taggable_id', + constraints : false +} ); +Post.belongsToMany( Post, { through : { model : Post, unique : false }, foreignKey : 'tag_id' } ); +Post.belongsToMany( Post, { as : 'Parents', through : 'Family', foreignKey : 'ChildId', otherKey : 'PersonId' } ); + +// +// DataTypes +// ~~~~~~~~~~~ +// +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/unit/sql/data-types.test.js +// + +Sequelize.STRING; +Sequelize.STRING( 1234 ); +Sequelize.STRING( { length : 1234 } ); +Sequelize.STRING( 1234 ).BINARY; +Sequelize.STRING.BINARY; +Sequelize.TEXT; +Sequelize.TEXT( 'tiny' ); +Sequelize.TEXT( { length : 'tiny' } ); +Sequelize.TEXT( 'medium' ); +Sequelize.TEXT( 'long' ); +Sequelize.CHAR; +Sequelize.CHAR( 12 ); +Sequelize.CHAR( { length : 12 } ); +Sequelize.CHAR( 12 ).BINARY; +Sequelize.CHAR.BINARY; +Sequelize.BOOLEAN; +Sequelize.DATE; +Sequelize.UUID; +Sequelize.UUIDV1; +Sequelize.UUIDV4; +Sequelize.NOW; +Sequelize.INTEGER; +Sequelize.INTEGER.UNSIGNED; +Sequelize.INTEGER.UNSIGNED.ZEROFILL; +Sequelize.INTEGER( 11 ); +Sequelize.INTEGER( { length : 11 } ); +Sequelize.INTEGER( 11 ).UNSIGNED; +Sequelize.INTEGER( 11 ).UNSIGNED.ZEROFILL; +Sequelize.INTEGER( 11 ).ZEROFILL; +Sequelize.INTEGER( 11 ).ZEROFILL.UNSIGNED; +Sequelize.BIGINT; +Sequelize.BIGINT.UNSIGNED; +Sequelize.BIGINT.UNSIGNED.ZEROFILL; +Sequelize.BIGINT( 11 ); +Sequelize.BIGINT( { length : 11 } ); +Sequelize.BIGINT( 11 ).UNSIGNED; +Sequelize.BIGINT( 11 ).UNSIGNED.ZEROFILL; +Sequelize.BIGINT( 11 ).ZEROFILL; +Sequelize.BIGINT( 11 ).ZEROFILL.UNSIGNED; +Sequelize.REAL.UNSIGNED; +Sequelize.REAL( 11 ); +Sequelize.REAL( { length : 11 } ); +Sequelize.REAL( 11 ).UNSIGNED; +Sequelize.REAL( 11 ).UNSIGNED.ZEROFILL; +Sequelize.REAL( 11 ).ZEROFILL; +Sequelize.REAL( 11 ).ZEROFILL.UNSIGNED; +Sequelize.REAL( 11, 12 ); +Sequelize.REAL( 11, 12 ).UNSIGNED; +Sequelize.REAL( { length : 11, decimals : 12 } ).UNSIGNED; +Sequelize.REAL( 11, 12 ).UNSIGNED.ZEROFILL; +Sequelize.REAL( 11, 12 ).ZEROFILL; +Sequelize.REAL( 11, 12 ).ZEROFILL.UNSIGNED; +Sequelize.DOUBLE; +Sequelize.DOUBLE.UNSIGNED; +Sequelize.DOUBLE( 11 ); +Sequelize.DOUBLE( 11 ).UNSIGNED; +Sequelize.DOUBLE( { length : 11 } ).UNSIGNED; +Sequelize.DOUBLE( 11 ).UNSIGNED.ZEROFILL; +Sequelize.DOUBLE( 11 ).ZEROFILL; +Sequelize.DOUBLE( 11 ).ZEROFILL.UNSIGNED; +Sequelize.DOUBLE( 11, 12 ); +Sequelize.DOUBLE( 11, 12 ).UNSIGNED; +Sequelize.DOUBLE( 11, 12 ).UNSIGNED.ZEROFILL; +Sequelize.DOUBLE( 11, 12 ).ZEROFILL; +Sequelize.DOUBLE( 11, 12 ).ZEROFILL.UNSIGNED; +Sequelize.FLOAT; +Sequelize.FLOAT.UNSIGNED; +Sequelize.FLOAT( 11 ); +Sequelize.FLOAT( 11 ).UNSIGNED; +Sequelize.FLOAT( 11 ).UNSIGNED.ZEROFILL; +Sequelize.FLOAT( 11 ).ZEROFILL; +Sequelize.FLOAT( { length : 11 } ).ZEROFILL; +Sequelize.FLOAT( 11 ).ZEROFILL.UNSIGNED; +Sequelize.FLOAT( 11, 12 ); +Sequelize.FLOAT( 11, 12 ).UNSIGNED; +Sequelize.FLOAT( { length : 11, decimals : 12 } ).UNSIGNED; +Sequelize.FLOAT( 11, 12 ).UNSIGNED.ZEROFILL; +Sequelize.FLOAT( 11, 12 ).ZEROFILL; +Sequelize.FLOAT( 11, 12 ).ZEROFILL.UNSIGNED; +Sequelize.NUMERIC; +Sequelize.NUMERIC( 15, 5 ); +Sequelize.DECIMAL; +Sequelize.DECIMAL( 10, 2 ); +Sequelize.DECIMAL( { precision : 10, scale : 2 } ); +Sequelize.DECIMAL( 10 ); +Sequelize.DECIMAL( { precision : 10 } ); +Sequelize.ENUM( 'value 1', 'value 2' ); +Sequelize.BLOB; +Sequelize.BLOB( 'tiny' ); +Sequelize.BLOB( 'medium' ); +Sequelize.BLOB( { length : 'medium' } ); +Sequelize.BLOB( 'long' ); +Sequelize.ARRAY( Sequelize.STRING ); +Sequelize.ARRAY( Sequelize.STRING( 100 ) ); +Sequelize.ARRAY( Sequelize.INTEGER ); +Sequelize.ARRAY( Sequelize.HSTORE ); +Sequelize.ARRAY( Sequelize.ARRAY( Sequelize.STRING ) ); +Sequelize.ARRAY( Sequelize.TEXT ); +Sequelize.ARRAY( Sequelize.DATE ); +Sequelize.ARRAY( Sequelize.BOOLEAN ); +Sequelize.ARRAY( Sequelize.DECIMAL ); +Sequelize.ARRAY( Sequelize.DECIMAL( 6 ) ); +Sequelize.ARRAY( Sequelize.DECIMAL( 6, 4 ) ); +Sequelize.ARRAY( Sequelize.DOUBLE ); +Sequelize.ARRAY( Sequelize.REAL ); +Sequelize.ARRAY( Sequelize.JSON ); +Sequelize.ARRAY( Sequelize.JSONB ); +Sequelize.GEOMETRY; +Sequelize.GEOMETRY( 'POINT' ); +Sequelize.GEOMETRY( 'LINESTRING' ); +Sequelize.GEOMETRY( 'POLYGON' ); +Sequelize.GEOMETRY( 'POINT', 4326 ); + +// +// Deferrable +// ~~~~~~~~~~~~ +// +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/sequelize/deferrable.test.js +// + +Sequelize.Deferrable.NOT; +Sequelize.Deferrable.INITIALLY_IMMEDIATE; +Sequelize.Deferrable.INITIALLY_DEFERRED; +Sequelize.Deferrable.SET_DEFERRED; +Sequelize.Deferrable.SET_DEFERRED( ['taskTableName_user_id_fkey'] ); +Sequelize.Deferrable.SET_IMMEDIATE; +Sequelize.Deferrable.SET_IMMEDIATE( ['taskTableName_user_id_fkey'] ); + +// +// Errors +// ~~~~~~~~ +// +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/error.test.js +// + +Sequelize.Error; +Sequelize.ValidationError; +s.Error; +s.ValidationError; +new s.ValidationError( 'Validation Error', [ + new s.ValidationErrorItem( ' cannot be null', 'notNull Violation', '', null ) + , new s.ValidationErrorItem( ' cannot be an array or an object', 'string violation', + '', null ) +] ); +new s.Error(); +new s.ValidationError(); +new s.ValidationErrorItem( 'invalid', 'type', 'first_name', null ); +new s.ValidationErrorItem( 'invalid', 'type', 'last_name', null ); +new s.DatabaseError( new Error( 'original database error message' ) ); +new s.ConnectionError( new Error( 'original connection error message' ) ); +new s.ConnectionRefusedError( new Error( 'original connection error message' ) ); +new s.AccessDeniedError( new Error( 'original connection error message' ) ); +new s.HostNotFoundError( new Error( 'original connection error message' ) ); +new s.HostNotReachableError( new Error( 'original connection error message' ) ); +new s.InvalidConnectionError( new Error( 'original connection error message' ) ); +new s.ConnectionTimedOutError( new Error( 'original connection error message' ) ); + +// +// Hooks +// ~~~~~~~ +// +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/hooks.test.js +// + +User.addHook( 'afterCreate', function( instance, options, next ) { next(); } ); +User.addHook( 'afterCreate', 'myHook', function( instance, options, next ) { next(); } ); +s.addHook( 'beforeInit', function( config, options ) { } ); +User.hook( 'afterCreate', 'myHook', function( instance, options, next ) { next(); } ); +User.hook( 'afterCreate', 'myHook', function( instance, options, next ) { next(); } ); + +User.removeHook( 'afterCreate', 'myHook' ); + +User.hasHook( 'afterCreate' ); +User.hasHooks( 'afterCreate' ); + +User.beforeValidate( function( user, options ) { user.isNewRecord; } ); +User.beforeValidate( 'myHook', function( user, options ) { user.isNewRecord; } ); + +User.afterValidate( function( user, options ) { user.isNewRecord; } ); +User.afterValidate( 'myHook', function( user, options ) { user.isNewRecord; } ); + +User.beforeCreate( function( user, options ) { user.isNewRecord; } ); +User.beforeCreate( function( user, options, fn ) {fn();} ); +User.beforeCreate( 'myHook', function( user, options ) { user.isNewRecord; } ); + +User.afterCreate( function( user, options ) { user.isNewRecord; } ); +User.afterCreate( function( user, options, fn ) {fn();} ); +User.afterCreate( 'myHook', function( user, options ) { user.isNewRecord; } ); + +User.beforeDestroy( function( user, options ) {throw new Error( 'Whoops!' );} ); +User.beforeDestroy( function( user, options, fn ) {fn();} ); +User.beforeDestroy( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); +User.beforeDelete( function( user, options ) {throw new Error( 'Whoops!' );} ); +User.beforeDelete( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); + +User.afterDestroy( function( user, options ) {throw new Error( 'Whoops!' );} ); +User.afterDestroy( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); +User.afterDestroy( function( user, options, fn ) {fn();} ); +User.afterDelete( function( user, options ) {throw new Error( 'Whoops!' );} ); +User.afterDelete( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); + +User.beforeUpdate( function( user, options ) {throw new Error( 'Whoops!' ); } ); +User.beforeUpdate( 'myHook', function( user, options ) {throw new Error( 'Whoops!' ); } ); + +User.afterUpdate( function( user, options ) {throw new Error( 'Whoops!' );} ); +User.afterUpdate( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); + +User.beforeBulkCreate( function( daos, options ) { throw new Error( 'Whoops!' );} ); +User.beforeBulkCreate( 'myHook', function( daos, options ) { throw new Error( 'Whoops!' );} ); +User.beforeBulkCreate( function( daos, options, fn ) {fn();} ); + +User.afterBulkCreate( function( daos, options ) {throw new Error( 'Whoops!' ); } ); +User.afterBulkCreate( 'myHook', function( daos, options ) {throw new Error( 'Whoops!' ); } ); +User.afterBulkCreate( function( daos, options, fn ) {fn();} ); + +User.beforeBulkDestroy( function( options ) {throw new Error( 'Whoops!' );} ); +User.beforeBulkDestroy( function( options, fn ) {fn();} ); +User.beforeBulkDestroy( 'myHook', function( options, fn ) {fn();} ); +User.beforeBulkDelete( 'myHook', function( options, fn ) {fn();} ); + +User.afterBulkDestroy( function( options ) {throw new Error( 'Whoops!' );} ); +User.afterBulkDestroy( function( options, fn ) {fn();} ); +User.afterBulkDestroy( 'myHook', function( options, fn ) {fn();} ); +User.afterBulkDelete( 'myHook', function( options, fn ) {fn();} ); + +User.beforeBulkUpdate( function( options ) {throw new Error( 'Whoops!' );} ); +User.beforeBulkUpdate( 'myHook', function( options ) {throw new Error( 'Whoops!' );} ); + +User.afterBulkUpdate( function( options ) {throw new Error( 'Whoops!' );} ); +User.afterBulkUpdate( 'myHook', function( options ) {throw new Error( 'Whoops!' );} ); + +User.beforeFind( function( options ) {} ); +User.beforeFind( 'myHook', function( options ) {} ); + +User.beforeFindAfterExpandIncludeAll( function( options ) {} ); +User.beforeFindAfterExpandIncludeAll( 'myHook', function( options ) {} ); + +User.beforeFindAfterOptions( function( options ) {} ); +User.beforeFindAfterOptions( 'myHook', function( options ) {} ); + +User.afterFind( function( user ) {} ); +User.afterFind( 'myHook', function( user ) {} ); + +s.beforeDefine( function( attributes, options ) {} ); +s.beforeDefine( 'myHook', function( attributes, options ) {} ); + +s.afterDefine( function( model ) {} ); +s.afterDefine( 'myHook', function( model ) {} ); + +s.beforeInit( function( config, options ) {} ); +s.beforeInit( 'myHook', function( attributes, options ) {} ); + +s.afterInit( function( model ) {} ); +s.afterInit( 'myHook', function( model ) {} ); + +s.define( 'User', {}, { + hooks : { + beforeValidate : function( user, options, fn ) {fn();}, + afterValidate : function( user, options, fn ) {fn();}, + beforeCreate : function( user, options, fn ) {fn();}, + afterCreate : function( user, options, fn ) {fn();}, + beforeDestroy : function( user, options, fn ) {fn();}, + afterDestroy : function( user, options, fn ) {fn();}, + beforeDelete : function( user, options, fn ) {fn();}, + afterDelete : function( user, options, fn ) {fn();}, + beforeUpdate : function( user, options, fn ) {fn();}, + afterUpdate : function( user, options, fn ) {fn();} + } +} ); + +// +// Instance +// ~~~~~~~~~~ +// +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/instance.test.js +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/instance/update.test.js +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/instance/values.test.js +// + +user.isNewRecord = true; + +user.Model.build( { a : 'b' } ); + +user.sequelize.close(); + +user.where(); + +user.getDataValue( '' ); + +user.setDataValue( '', '' ); +user.setDataValue( '', {} ); + +user.get( 'aNumber', { plain : true, clone : true } ); +user.get(); + +user.set( 'email', 'B' ); +user.set( { name : 'B', bio : 'B' } ).save().then( ( p ) => p ); +user.set( 'birthdate', new Date() ); +user.set( { id : 1, t : 'c', q : [{ id : 1, n : 'a' }, { id : 2, n : 'Beta' }], u : { id : 1, f : 'b', l : 'd' } } ); +user.setAttributes( { a : 3 } ); +user.setAttributes( { id : 1, a : 'n', c : [{ id : 1 }, { id : 2, f : 'e' }], x : { id : 1, f : 'h', l : 'd' } } ); + +user.changed( 'name' ); +user.changed(); + +user.previous( 'name' ); + +user.save().then( ( p ) => p ); +user.save( { fields : ['a'] } ).then( ( p ) => p ); +user.save( { transaction : t } ); + +user.reload(); +user.reload( { attributes : ['bNumber'] } ); +user.reload( { transaction : t } ); + +user.validate(); + +user.update( { bNumber : 2 }, { where : { id : 1 } } ); +user.update( { username : 'userman' }, { silent : true } ); +user.update( { username : 'yolo' }, { logging : function() { } } ); +user.update( { username : 'bar' }, { where : { username : 'foo' }, transaction : t } ).then( ( p ) => p ); +user.updateAttributes( { a : 3 } ).then( ( p ) => p ); +user.updateAttributes( { a : 3 }, { fields : ['secretValue'], logging : function( sql ) {} } ); + +user.destroy().then( ( p ) => p ); +user.destroy( { logging : function( sql ) {} } ); +user.destroy( { transaction : t } ).then( ( p ) => p ); + +user.restore(); + +user.increment( 'number', { by : 2 } ).then( ( p ) => p ); +user.increment( ['aNumber'], { by : 2, where : { bNumber : 1 } } ).then( ( p ) => p ); +user.increment( ['aNumber'], { by : 2 } ).then( ( p ) => p ); +user.increment( 'aNumber' ).then( ( p ) => p ); +user.increment( { 'aNumber' : 1, 'bNumber' : 2 } ).then( ( p ) => p ); +user.increment( 'number', { by : 2, transaction : t } ).then( ( p ) => p ); + +user.decrement( 'aNumber', { by : 2 } ).then( ( p ) => p ); +user.decrement( ['aNumber'], { by : 2 } ).then( ( p ) => p ); +user.decrement( 'aNumber' ).then( ( p ) => p ); +user.decrement( { 'aNumber' : 1, 'bNumber' : 2 } ).then( ( p ) => p ); +user.decrement( 'number', { by : 2, transaction : t } ).then( ( p ) => p ); + +user.equals( user ); + +user.equalsOneOf( [user, user] ); + +user.toJSON(); + +// +// Model +// ~~~~~~~ +// +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/model.test.js +// + +User.removeAttribute( 'id' ); + +User.sync( { force : true } ).then( function() { } ); +User.sync( { force : true, logging : function() { } } ); + +User.drop(); + +User.schema( 'special' ); +User.schema( 'special' ).create( { age : 3 }, { logging : function( UserSpecial ) {} } ); + +User.getTableName(); + +User.scope( 'lowAccess' ).count(); +User.scope( { where : { parent_id : 2 } } ); + +User.findAll(); +User.findAll( { where : { data : { employment : null } } } ); +User.findAll( { where : { aNumber : { gte : 10 } } } ).then( ( u ) => u[0].isNewRecord ); +User.findAll( { where : [s.or( { u : 'b' }, { u : ';' } ), s.and( { id : [1, 2] } )], include : [{ model : User }] } ); +User.findAll( { + where : [s.or( { a : 'b' }, { c : 'd' } ), s.and( { id : [1, 2, 3] }, + s.or( { deletedAt : null }, { deletedAt : { gt : new Date( 0 ) } } ) )] +} ); +User.findAll( { paranoid : false, where : [' IS NOT NULL '], include : [{ model : User }] } ); +User.findAll( { transaction : t } ); +User.findAll( { where : { data : { name : { last : 's' }, employment : { $ne : 'a' } } }, order : [['id', 'ASC']] } ); +User.findAll( { where : { username : ['boo', 'boo2'] } } ); +User.findAll( { where : { username : { like : '%2' } } } ); +User.findAll( { where : { theDate : { '..' : ['2013-01-02', '2013-01-11'] } } } ); +User.findAll( { where : { intVal : { '!..' : [8, 10] } } } ); +User.findAll( { where : { theDate : { between : ['2013-01-02', '2013-01-11'] } } } ); +User.findAll( { where : { theDate : { between : ['2013-01-02', '2013-01-11'] }, intVal : 10 } } ); +User.findAll( { where : { theDate : { between : ['2012-12-10', '2013-01-02'] } } } ); +User.findAll( { where : { theDate : { nbetween : ['2013-01-04', '2013-01-20'] } } } ); +User.findAll( { order : [s.col( 'name' )] } ); +User.findAll( { order : [['theDate', 'DESC']] } ); +User.findAll( { include : [User], order : [[User, User, 'numYears', 'c']] } ); +User.findAll( { include : [{ model : User, include : [User, { model : User, as : 'residents' }] }] } ); +User.findAll( { order : [[User, { model : User, as : 'residents' }, 'lastName', 'c']] } ); +User.findAll( { include : [User], order : [[User, 'name', 'c']] } ); +User.findAll( { include : [{ all : 'HasMany', attributes : ['name'] }] } ); +User.findAll( { include : [{ all : true }, { model : User, attributes : ['id'] }] } ); +User.findAll( { include : [{ all : 'BelongsTo' }] } ); +User.findAll( { include : [{ all : true }] } ); +User.findAll( { where : { username : 'barfooz' }, raw : true } ); +User.findAll( { where : { name : 'worker' }, include : [{ model : User, as : 'ToDos' }] } ); +User.findAll( { where : { user_id : 1 }, attributes : ['a', 'b'], include : [{ model : User, attributes : ['c'] }] } ); +User.findAll( { order : s.literal( 'email =' ) } ); +User.findAll( { order : [s.literal( 'email = ' + s.escape( 'test@sequelizejs.com' ) )] } ); +User.findAll( { order : [['id', ';DELETE YOLO INJECTIONS']] } ); +User.findAll( { include : [User], order : [[User, 'id', ';DELETE YOLO INJECTIONS']] } ); +User.findAll( { include : [User], order : [['id', 'ASC NULLS LAST'], [User, 'id', 'DESC NULLS FIRST']] } ); +User.findAll( { include : [{ model : User, where : { title : 'DoDat' }, include : [{ model : User }] }] } ); + +User.findById( 'a string' ); + +User.findOne( { where : { username : 'foo' } } ); +User.findOne( { where : { id : 1 }, attributes : ['id', ['username', 'name']] } ); +User.findOne( { where : { id : 1 }, attributes : ['id'] } ); +User.findOne( { where : { username : 'foo' }, logging : function( sql ) { } } ); +User.findOne( { limit : 10 } ); +User.findOne( { include : [1] } ); +User.findOne( { where : { title : 'homework' }, include : [User] } ); +User.findOne( { where : { name : 'environment' }, include : [{ model : User, as : 'PrivateDomain' }] } ); +User.findOne( { where : { username : 'foo' }, transaction : t } ).then( ( p ) => p ); +User.findOne( { include : [User] } ); +User.findOne( { include : [{ model : User, as : 'Work' }] } ); +User.findOne( { where : { name : 'worker' }, include : [{ model : User, as : 'ToDo' }] } ); +User.findOne( { include : [{ model : User, as : 'ToDo' }, { model : User, as : 'DoTo' }] } ); +User.findOne( { where : { name : 'worker' }, include : [User] } ); +User.findOne( { where : { name : 'Boris' }, include : [User, { model : User, as : 'Photos' }] } ); +User.findOne( { where : { username : 'someone' }, include : [User] } ); +User.findOne( { where : { username : 'barfooz' }, raw : true } ); +User.findOne( { updatedAt : { ne : null } } ); +User.find( { where : { intVal : { gt : 5 } } } ); +User.find( { where : { intVal : { lte : 5 } } } ); + +User.count(); +User.count( { transaction : t } ); +User.count().then( function( c ) { c.toFixed() } ); +User.count( { where : ["username LIKE '%us%'"] } ); +User.count( { include : [{ model : User, required : false }] } ); +User.count( { distinct : true, include : [{ model : User, required : false }] } ); +User.count( { attributes : ['data'], group : ['data'] } ); +User.count( { where : { access_level : { gt : 5 } } } ); + +User.findAndCountAll( { offset : 5, limit : 1, include : [User, { model : User, as : 'a' }] } ); + +User.max( 'age', { transaction : t } ); +User.max( 'age' ); +User.max( 'age', { logging : function( sql ) { } } ); + +User.min( 'age', { transaction : t } ); +User.min( 'age' ); +User.min( 'age', { logging : function( sql ) { } } ); + +User.sum( 'order' ); +User.sum( 'age', { where : { 'gender' : 'male' } } ); +User.sum( 'age', { logging : function( sql ) { } } ); + +User.build( { username : 'John Wayne' } ).save(); +User.build(); +User.build( { id : 1, T : [{ n : 'a' }, { id : 2 }], A : { id : 1, n : 'a', c : 'a' } }, { include : [User, Task] } ); +User.build( { id : 1, }, { include : [{ model : User, as : 'followers' }, { model : Task, as : 'categories' }] } ); + +User.create(); +User.create( { createdAt : 1, updatedAt : 2 }, { silent : true } ); +User.create( {}, { returning : true } ); +User.create( { intVal : s.literal( 'CAST(1-2 AS' ) } ); +User.create( { secretValue : s.fn( 'upper', 'sequelize' ) } ); +User.create( { myvals : [1, 2, 3, 4], mystr : ['One', 'Two', 'Three', 'Four'] } ); +User.create( { name : 'Fluffy Bunny', smth : 'else' }, { logging : function( sql ) {} } ); +User.create( {}, { fields : [] } ); +User.create( { name : 'Yolo Bear', email : 'yolo@bear.com' }, { fields : ['name'] } ); +User.create( { title : 'Chair', User : { first_name : 'Mick', last_name : 'Broadstone' } }, { include : [User] } ); +User.create( { title : 'Chair', creator : { first_name : 'Matt', last_name : 'Hansen' } }, { include : [User] } ); +User.create( { id : 1, title : 'e', Tags : [{ id : 1, name : 'c' }, { id : 2, name : 'd' }] }, { include : [User] } ); +User.create( { id : 'My own ID!' } ).then( ( i ) => i.isNewRecord ); + +User.findOrInitialize( { where : { username : 'foo' } } ).then( ( p ) => p ); +User.findOrInitialize( { where : { username : 'foo' }, transaction : t } ); +User.findOrInitialize( { where : { username : 'foo' }, defaults : { foo : 'asd' }, transaction : t } ); + +User.findOrCreate( { where : { a : 'b' }, defaults : { json : { a : { b : 'c' }, d : [1, 2, 3] } } } ); +User.findOrCreate( { where : { a : 'b' }, defaults : { json : 'a', data : 'b' } } ); +User.findOrCreate( { where : { a : 'b' }, transaction : t, lock : t.LOCK.UPDATE } ); +User.findOrCreate( { where : { a : 'b' }, logging : function( sql ) { } } ); +User.findOrCreate( { where : { username : 'Username' }, defaults : { data : 'some data' }, transaction : t } ); +User.findOrCreate( { where : { objectId : 'asdasdasd' }, defaults : { username : 'gottlieb' } } ); +User.findOrCreate( { where : { id : undefined }, defaults : { name : Math.random().toString() } } ); +User.findOrCreate( { where : { email : 'unique.email.@d.com', companyId : Math.floor( Math.random() * 5 ) } } ); +User.findOrCreate( { where : { objectId : 1 }, defaults : { bool : false } } ); +User.findOrCreate( { where : 'c', defaults : {} } ); + +User.upsert( { id : 42, username : 'doe', foo : s.fn( 'upper', 'mixedCase2' ) } ); + +User.bulkCreate( [{ aNumber : 10 }, { aNumber : 12 }] ).then( ( i ) => i[0].isNewRecord ); +User.bulkCreate( [{ username : 'bar' }, { username : 'bar' }, { username : 'bar' }] ); +User.bulkCreate( [{}, {}], { validate : true, individualHooks : true } ); +User.bulkCreate( [{ style : 'ipa' }], { logging : function() { } } ); +User.bulkCreate( [{ a : 'b', c : 'd', e : 'f' }, { a : 'b', c : 'd', e : 'f' }], { fields : ['a', 'b'] } ); +User.bulkCreate( [{ name : 'foo', code : '123' }, { code : 'c' }, { name : 'bar', code : '1' }], { validate : true } ); +User.bulkCreate( [{ name : 'foo', code : '123' }, { code : '1234' }], { fields : ['code'], validate : true } ); +User.bulkCreate( [{ name : 'a', c : 'b' }, { name : 'e', c : 'f' }], { fields : ['e', 'f'], ignoreDuplicates : true } ); + +User.truncate(); + +User.destroy( { where : { client_id : 13 } } ).then( ( a ) => a.toFixed() ); +User.destroy( { force : true } ); +User.destroy( { where : {}, transaction : t } ); +User.destroy( { where : { access_level : { lt : 5 } } } ); +User.destroy( { truncate : true } ); +User.destroy( { where : {} } ); + +User.restore( { where : { secretValue : '42' } } ); + +User.update( { username : 'ruben' }, { where : {} } ); +User.update( { username : 'ruben' }, { where : { access_level : { lt : 5 } } } ); +User.update( { username : 'ruben' }, { where : { username : 'dan' } } ); +User.update( { username : 'bar' }, { where : { username : 'foo' }, transaction : t } ); +User.update( { username : 'Bill', secretValue : '43' }, { where : { secretValue : '42' }, fields : ['username'] } ); +User.update( { username : s.cast( '1', 'char' ) }, { where : { username : 'John' } } ); +User.update( { username : s.fn( 'upper', s.col( 'username' ) ) }, { where : { username : 'John' } } ); +User.update( { username : 'Bill' }, { where : { secretValue : '42' }, returning : true } ); +User.update( { secretValue : '43' }, { where : { username : 'Peter' }, limit : 1 } ); +User.update( { name : Math.random().toString() }, { where : { id : '1' } } ); +User.update( { a : { b : 10, c : 'd' } }, { where : { username : 'Jan' }, sideEffects : false } ); +User.update( { geometry : { type : 'Point', coordinates : [49.807222, -86.984722] } }, { + where : { + u : { + u : 'u', + geometry : { type : 'Point', coordinates : [49.807222, -86.984722] } + } + } +} ); +User.update( { + geometry : { + type : 'Polygon', + coordinates : [[[100.0, 0.0], [102.0, 0.0], [102.0, 1.0], [100.0, 1.0], [100.0, 0.0]]] + } +}, { + where : { + username : { + username : 'username', + geometry : { type : 'Point', coordinates : [49.807222, -86.984722] } + } + } +} ); + +User.unscoped().find( { where : { username : 'bob' } } ); +User.unscoped().count(); + +// +// Query Interface +// ~~~~~~~~~~~~~~~~~ +// +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/query-interface.test.js +// + +var queryInterface = s.getQueryInterface(); + +queryInterface.dropAllTables(); +queryInterface.showAllTables( { logging : function() { } } ); +queryInterface.createTable( 'table', { name : Sequelize.STRING }, { logging : function() { } } ); +queryInterface.createTable( 'skipme', { name : Sequelize.STRING } ); +queryInterface.dropAllTables( { skip : ['skipme'] } ); +queryInterface.dropTable( 'Group', { logging : function() { } } ); +queryInterface.addIndex( 'Group', ['username', 'isAdmin'], { logging : function() { } } ); +queryInterface.showIndex( 'Group', { logging : function() { } } ); +queryInterface.removeIndex( 'Group', ['username', 'isAdmin'], { logging : function() { } } ); +queryInterface.showIndex( 'Group' ); +queryInterface.createTable( 'table', { name : { type : Sequelize.STRING } }, { schema : 'schema' } ); +queryInterface.addIndex( { schema : 'a', tableName : 'c' }, ['d', 'e'], { logging : function() {} }, 'schema_table' ); +queryInterface.showIndex( { schema : 'schema', tableName : 'table' }, { logging : function() {} } ); +queryInterface.addIndex( 'Group', ['from'] ); +queryInterface.describeTable( '_Users', { logging : function() {} } ); +queryInterface.createTable( 's', { table_id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } } ); +queryInterface.insert( null, 'TableWithPK', {}, { raw : true, returning : true, plain : true } ); +queryInterface.createTable( 'SomeTable', { someEnum : Sequelize.ENUM( 'value1', 'value2', 'value3' ) } ); +queryInterface.createTable( 'SomeTable', { someEnum : { type : Sequelize.ENUM, values : ['b1', 'b2', 'b3'] } } ); +queryInterface.createTable( 't', { someEnum : { type : Sequelize.ENUM, values : ['c1', 'c2', 'c3'], field : 'd' } } ); +queryInterface.createTable( 'User', { name : { type : Sequelize.STRING } }, { schema : 'hero' } ); +queryInterface.rawSelect( 'User', { schema : 'hero', logging : function() {} }, 'name' ); +queryInterface.renameColumn( '_Users', 'username', 'pseudo', { logging : function() {} } ); +queryInterface.renameColumn( { schema : 'archive', tableName : 'Users' }, 'username', 'pseudo' ); +queryInterface.renameColumn( '_Users', 'username', 'pseudo' ); +queryInterface.createTable( { tableName : 'y', schema : 'a' }, + { id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true }, currency : Sequelize.INTEGER } ); +queryInterface.changeColumn( { tableName : 'a', schema : 'b' }, 'c', { type : Sequelize.FLOAT }, + { logging : () => s } ); +queryInterface.createTable( 'users', { id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } } ); +queryInterface.createTable( 'level', { id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } } ); +queryInterface.addColumn( 'users', 'someEnum', Sequelize.ENUM( 'value1', 'value2', 'value3' ) ); +queryInterface.addColumn( 'users', 'so', { type : Sequelize.ENUM, values : ['value1', 'value2', 'value3'] } ); +queryInterface.createTable( 'hosts', { + id : { + type : Sequelize.INTEGER, + primaryKey : true, + autoIncrement : true + }, + admin : { + type : Sequelize.INTEGER, + references : { + model : User, + key : 'id' + } + }, + operator : { + type : Sequelize.INTEGER, + references : { + model : User, + key : 'id' + }, + onUpdate : 'cascade' + }, + owner : { + type : Sequelize.INTEGER, + references : { + model : User, + key : 'id' + }, + onUpdate : 'cascade', + onDelete : 'set null' + } +} ); + +// +// Query Types +// ~~~~~~~~~~~~~ +// + +s.getDialect(); +s.validate(); +s.authenticate(); +s.isDefined( '' ); +s.model( 'pp' ); +s.query( '', { raw : true } ); +s.query( '' ); +s.query( '' ).then( function( res ) {} ); +s.query( '' ).spread( function( a ) {}, function( b ) {} ); +s.query( { query : 'select ? as foo, ? as bar', values : [1, 2] }, { raw : true, replacements : [1, 2] } ); +s.query( '', { raw : true, nest : false } ); +s.query( 'select ? as foo, ? as bar', { type : this.sequelize.QueryTypes.SELECT, replacements : [1, 2] } ); +s.query( { query : 'select ? as foo, ? as bar', values : [1, 2] }, { type : s.QueryTypes.SELECT } ); +s.query( 'select :one as foo, :two as bar', { raw : true, replacements : { one : 1, two : 2 } } ); +s.transaction().then( function( t ) { s.set( { foo : 'bar' }, { transaction : t } ) } ); +s.define( 'foo', { bar : Sequelize.STRING }, { collate : 'utf8_bin' } ); +s.define( 'Foto', { name : Sequelize.STRING }, { tableName : 'photos' } ); +s.databaseVersion().then( function( version ) { } ); + +// +// Sequelize +// ~~~~~~~~~~~ +// + +new Sequelize( 'db', 'user', 'pw', { logging : false } ); +new Sequelize( 'db', 'user', 'pass', { + dialect : '', + port : 99999, + pool : {} +} ); +new Sequelize( '' ).query( '', { type : s.QueryTypes.FOREIGNKEYS, logging : function() {} } ); +new Sequelize( 'sqlite://test.sqlite' ); +new Sequelize( 'wat', 'trololo', 'wow', { port : 99999 } ); +new Sequelize( 'localhost', 'wtf', 'lol', { port : 99999 } ); +new Sequelize( 'sequelize', null, null, { + replication : { + read : { + host : 'localhost', + username : 'omg', + password : 'lol' + } + } +} ); + +s.model( 'Project' ); +s.define( 'Project', { + name : Sequelize.STRING +} ); + +var s = new Sequelize( '' ); +var testModel = s.define( 'User', { + username : Sequelize.STRING, + secretValue : Sequelize.STRING, + data : Sequelize.STRING, + intVal : Sequelize.INTEGER, + theDate : Sequelize.DATE, + aBool : Sequelize.BOOLEAN +} ); +var testModel = s.define( 'FrozenUser', {}, { freezeTableName : true } ); +s.define( 'UserWithClassAndInstanceMethods', {}, { + classMethods : { doSmth : function() { return 1; } }, + instanceMethods : { makeItSo : function() { return 2; } } +} ); +s.define( 'UserCol', { + id : { + type : Sequelize.STRING, + defaultValue : 'User', + primaryKey : true + } +} ); +s.define( 'UserWithTwoAutoIncrements', { + userid : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true }, + userscore : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } +} ); +s.define( 'Foo', { + field : Sequelize.INTEGER +}, { + validate : { + field : function() {} + } +} ); +var UserTable = s.define( 'UserCol', { + aNumber : Sequelize.INTEGER, + createdAt : { + type : Sequelize.DATE, + defaultValue : new Date() + }, + updatedAt : { + type : Sequelize.DATE, + defaultValue : new Date() + } +}, { timestamps : true } ); + +s.define( 'UserCol', { + aNumber : Sequelize.INTEGER +}, { + timestamps : true, + updatedAt : 'updatedOn', + createdAt : 'dateCreated', + deletedAt : 'deletedAtThisTime', + paranoid : true +} ); +s.define( 'UpdatingUser', { + name : Sequelize.STRING +}, { + timestamps : true, + updatedAt : false, + createdAt : false, + deletedAt : 'deletedAtThisTime', + paranoid : true +} ); +s.define( 'TaskBuild', { + title : { + type : Sequelize.STRING( 50 ), + allowNull : false, + defaultValue : '' + } +}, { + setterMethods : { + title : function() { } + } +} ); +s.define( 'UserCol', { + aNumber : Sequelize.INTEGER +}, { + paranoid : true, + underscored : true +} ); + +s.define( 'UserWithUniqueUsername', { + username : { type : Sequelize.STRING, unique : { name : 'user_and_email', msg : 'User and email must be unique' } }, + email : { type : Sequelize.STRING, unique : 'user_and_email' } +} ); +s.define( 'UserWithUniqueUsername', { + user_id : { type : Sequelize.INTEGER }, + email : { type : Sequelize.STRING } +}, { + indexes : [ + { + name : 'user_and_email_index', + msg : 'User and email must be unique', + unique : true, + method : 'BTREE', + fields : ['user_id', { attribute : 'email', collate : 'en_US', order : 'DESC', length : 5 }] + }] +} ); + +s.define( 'TaskBuild', { + title : { type : Sequelize.STRING, defaultValue : 'a task!' }, + foo : { type : Sequelize.INTEGER, defaultValue : 2 }, + bar : { type : Sequelize.DATE }, + foobar : { type : Sequelize.TEXT, defaultValue : 'asd' }, + flag : { type : Sequelize.BOOLEAN, defaultValue : false } +} ); +s.define( 'ProductWithSettersAndGetters1', { + price : { + type : Sequelize.INTEGER, + get : function() { + return 'answer = ' + this.getDataValue( 'price' ); + }, + set : function( v ) { + return this.setDataValue( 'price', v + 42 ); + } + } +} ); +s.define( 'ProductWithSettersAndGetters2', { + priceInCents : Sequelize.INTEGER +}, { + setterMethods : { + price : function( value ) { + this.dataValues.priceInCents = value * 100; + } + }, + getterMethods : { + price : function() { + return '$' + (this.getDataValue( 'priceInCents' ) / 100); + }, + + priceInCents : function() { + return this.dataValues.priceInCents; + } + } +} ); + +s.define( 'post', { + title : Sequelize.STRING, + authorId : { type : Sequelize.INTEGER, references : testModel, referencesKey : 'id' } +} ); +s.define( 'post', { + title : Sequelize.STRING, + authorId : { type : Sequelize.INTEGER, references : { model : testModel, key : 'id' } } +} ); + +s.define( 'User', { + username : Sequelize.STRING, + geometry : Sequelize.GEOMETRY( 'POINT' ) +} ); + +s.define( 'ScopeMe', { + username : Sequelize.STRING, + email : Sequelize.STRING, + access_level : Sequelize.INTEGER, + other_value : Sequelize.INTEGER, + parent_id : Sequelize.INTEGER +}, { + defaultScope : { + where : { + access_level : { + gte : 5 + } + } + }, + scopes : { + isTony : { + where : { + username : 'tony' + } + }, + } +} ); +s.define( 'company', { + active : Sequelize.BOOLEAN +}, { + defaultScope : { + where : { active : true } + }, + scopes : { + notActive : { + where : { + active : false + } + }, + reversed : { + order : [['id', 'DESC']] + } + } +} ); +s.define( 'profile', { + active : Sequelize.BOOLEAN +}, { + defaultScope : { + where : { active : true } + }, + scopes : { + notActive : { + where : { + active : false + } + }, + } +} ); + +s.define( 'ScopeMe', { + username : Sequelize.STRING, + email : Sequelize.STRING, + access_level : Sequelize.INTEGER, + other_value : Sequelize.INTEGER +}, { + defaultScope : { + where : { + access_level : { + gte : 5 + } + } + }, + scopes : { + lowAccess : { + where : { + access_level : { + lte : 5 + } + } + }, + withOrder : { + order : 'username' + } + } +} ); + +s.define( 'ScopeMe', { + username : Sequelize.STRING, + email : Sequelize.STRING, + access_level : Sequelize.INTEGER, + other_value : Sequelize.INTEGER +}, { + defaultScope : { + where : { + access_level : { + gte : 5 + } + } + }, + scopes : { + lowAccess : { + where : { + access_level : { + lte : 5 + } + } + } + } +} ); + +s.define( 'user', { + id : { + type : Sequelize.INTEGER, + allowNull : false, + primaryKey : true, + autoIncrement : true, + field : 'userId' + }, + name : { + type : Sequelize.STRING, + field : 'full_name' + }, + taskCount : { + type : Sequelize.INTEGER, + field : 'task_count', + defaultValue : 0, + allowNull : false + } +}, { + tableName : 'users', + timestamps : false +} ); +s.define( 'task', { + id : { + type : Sequelize.INTEGER, + allowNull : false, + primaryKey : true, + autoIncrement : true, + field : 'taskId' + }, + title : { + type : Sequelize.STRING, + field : 'name' + } +}, { + tableName : 'tasks', + timestamps : false +} ); +s.define( 'comment', { + id : { + type : Sequelize.INTEGER, + allowNull : false, + primaryKey : true, + autoIncrement : true, + field : 'commentId' + }, + text : { + type : Sequelize.STRING, + field : 'comment_text' + }, + notes : { + type : Sequelize.STRING, + field : 'notes' + } +}, { + tableName : 'comments', + timestamps : false +} ); +s.define( 'test', { + id : { + type : Sequelize.INTEGER, + field : 'test_id', + autoIncrement : true, + primaryKey : true, + validate : { + min : 1 + } + }, + title : { + allowNull : false, + type : Sequelize.STRING( 255 ), + field : 'test_title' + } +}, { + timestamps : true, + underscored : true, + freezeTableName : true +} ); + +s.define( 'User', { + deletedAt : { + type : Sequelize.DATE, + field : 'deleted_at' + } +}, { + timestamps : true, + paranoid : true +} ); + +// +// Transaction +// ~~~~~~~~~~~~~ +// +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/transaction.test.js +// + +s.transaction().then( function( t ) { + + t.commit(); + t.rollback(); + + User.find( { + where : { + username : 'John' + }, + include : [User], + lock : t.LOCK.UPDATE, + transaction : t + } ); + User.find( { + where : { + username : 'John' + }, + include : [User], + lock : { + level : t.LOCK.UPDATE, + of : User + }, + transaction : t + } ); + User.update( { + active : true + }, { + where : { + active : false + }, + transaction : t + } ); + User.find( { + where : { + username : 'jan' + }, + lock : t.LOCK.NO_KEY_UPDATE, + transaction : t + } ); + User.find( { + where : { + username : 'jan' + }, + lock : t.LOCK.KEY_SHARE, + transaction : t + } ); + +} ); + +s.transaction( function() { + return Promise.resolve(); +} ); +s.transaction( { isolationLevel : 'SERIALIZABLE' }, function( t ) { return Promise.resolve(); } ); +s.transaction( { isolationLevel : s.Transaction.ISOLATION_LEVELS.SERIALIZABLE }, (t) => Promise.resolve() ); +s.transaction( { isolationLevel : s.Transaction.ISOLATION_LEVELS.READ_COMMITTED }, (t) => Promise.resolve() ); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sequelize/sequelize-tests.ts b/sequelize/sequelize-tests-2.0.0.ts similarity index 99% rename from sequelize/sequelize-tests.ts rename to sequelize/sequelize-tests-2.0.0.ts index 8766745b8..b3a869a94 100644 --- a/sequelize/sequelize-tests.ts +++ b/sequelize/sequelize-tests-2.0.0.ts @@ -1,4 +1,4 @@ -/// +/// import Sequelize = require('sequelize'); diff --git a/sequelize/sequelize.d.ts b/sequelize/sequelize.d.ts index 1bb6be593..a97479d2b 100644 --- a/sequelize/sequelize.d.ts +++ b/sequelize/sequelize.d.ts @@ -1,1017 +1,2821 @@ -// Type definitions for Sequelize 2.0.0 dev13 +// Type definitions for Sequelize 3.4.1 // Project: http://sequelizejs.com -// Definitions by: samuelneff , Peter Harris +// Definitions by: samuelneff , Peter Harris , Ivan Drinchev // Definitions: https://github.com/borisyankov/DefinitelyTyped // Based on original work by: samuelneff -/// -/// +/// +/// +/// + +declare module "sequelize" { -declare module "sequelize" -{ module sequelize { - interface SequelizeStaticAndInstance { + + // + // Associations + // ~~~~~~~~~~~~~~ + // + // https://github.com/sequelize/sequelize/tree/v3.4.1/lib/associations + // + + /** + * Foreign Key Options + * + * @see AssociationOptions + */ + interface AssociationForeignKeyOptions extends ColumnOptions { /** - * A reference to sequelize utilities. Most users will not need to use these utils directly. However, you might want - * to use Sequelize.Utils._, which is a reference to the lodash library, if you don't already have it imported in - * your project. + * Attribute name for the relation */ - Utils: Utils; + name? : string; - /** - * A modified version of bluebird promises, that allows listening for sql events. - * - * @see Promise - */ - Promise: Promise; - - /** - * Exposes the validator.js object, so you can extend it with custom validation functions. The validator is exposed - * both on the instance, and on the constructor. - * - * @see Validator - */ - Validator: Validator; - - QueryTypes: QueryTypes; - - /** - * A general error class. - */ - Error: Error; - - /** - * Emitted when a validation fails. - * - * @see ValidationError - */ - ValidationError: ValidationError; - - /** - * Creates a object representing a database function. This can be used in search queries, both in where and order - * parts, and as default values in column definitions. If you want to refer to columns in your function, you should - * use sequelize.col, so that the columns are properly interpreted as columns and not a strings. - * - * @param fn The function you want to call. - * @param args All further arguments will be passed as arguments to the function. - */ - fn(fn: string, ...args: Array): any; - - /** - * Creates a object representing a column in the DB. This is often useful in conjunction with sequelize.fn, since - * raw string arguments to fn will be escaped. - * - * @param col The name of the column - */ - col(col: string): Col; - - /** - * Creates a object representing a call to the cast function. - * - * @param val The value to cast. - * @param type The type to cast it to. - */ - cast(val: any, type: string): Cast; - - /** - * Creates a object representing a literal, i.e. something that will not be escaped. - * - * @param val Value to convert to a literal. - */ - literal(val: any): Literal; - - /** - * An AND query. - * - * @param args Each argument (string or object) will be joined by AND. - */ - and(...args: Array): And; - - /** - * An OR query. - * - * @param args Each argument (string or object) will be joined by OR. - */ - or(...args: Array): Or; - - /** - * A way of specifying attr = condition. Mostly used internally. - * - * @param attr The attribute - * @param condition The condition. Can be both a simply type, or a further condition (.or, .and, .literal etc.) - */ - where(attr: string, condition: any): Where; } - interface SequelizeStatic extends SequelizeStaticAndInstance, DataTypes { - /** - * Instantiate sequelize with name of database and username - * @param database database name - * @param username user name - */ - new (database: string, username: string): Sequelize; + /** + * Options provided when associating models + * + * @see Association class + */ + interface AssociationOptions { /** - * Instantiate sequelize with name of database, username and password - * @param database database name - * @param username user name - * @param password password - */ - new (database: string, username: string, password: string): Sequelize; - - /** - * Instantiate sequelize with name of database, username, password, and options. - * @param database database name - * @param username user name - * @param password password - * @param options options. @see Options - */ - new (database: string, username: string, password: string, options: Options): Sequelize; - - /** - * Instantiate sequelize with name of database, username, and options. + * Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. + * For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks + * for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking + * any hooks. * - * @param database database name - * @param username user name - * @param options options. @see Options + * Defaults to false */ - new (database: string, username: string, options: Options): Sequelize; + hooks?: boolean; /** - * Instantiate sequlize with an URI - * @param connectionString A full database URI - * @param options Options for sequelize. @see Options + * The alias of this model, in singular form. See also the `name` option passed to `sequelize.define`. If + * you create multiple associations between the same tables, you should provide an alias to be able to + * distinguish between them. If you provide an alias when creating the assocition, you should provide the + * same alias when eager loading and when getting assocated models. Defaults to the singularized name of + * target */ - new (connectionString: string, options?: Options): Sequelize; + as?: string | { singular: string, plural: string }; + + /** + * The name of the foreign key in the target table or an object representing the type definition for the + * foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property + * to set the name of the column. Defaults to the name of source + primary key of source + */ + foreignKey?: string | AssociationForeignKeyOptions; + + /** + * What happens when delete occurs. + * + * Cascade if this is a n:m, and set null if it is a 1:m + * + * Defaults to 'SET NULL' or 'CASCADE' + */ + onDelete?: string; + + /** + * What happens when update occurs + * + * Defaults to 'CASCADE' + */ + onUpdate?: string; + + /** + * Should on update and on delete constraints be enabled on the foreign key. + */ + constraints?: boolean; + foreignKeyConstraint?: boolean; + } - interface Sequelize extends SequelizeStaticAndInstance { - /** - * Sequelize configuration (undocumented). - */ - config: Config; + /** + * Options for Association Scope + * + * @see AssociationOptionsManyToMany + */ + interface AssociationScope { /** - * Sequelize options (undocumented). + * The name of the column that will be used for the associated scope and it's value */ - options: Options; + [scopeName: string] : any; - /** - * Models are stored here under the name given to sequelize.define - */ - models: any; - modelManager: ModelManager; - daoFactoryManager: ModelManager; - transactionManager: TransactionManager; - importCache: any; - - /** - * A reference to the sequelize transaction class. Use this to access isolationLevels when creating a transaction. - * - * @see Transaction - */ - Transaction: TransactionStatic; - - /** - * Returns the specified dialect. - */ - getDialect(): string; - - /** - * Returns the singleton instance of QueryInterface. - */ - getQueryInterface(): QueryInterface; - - /** - * Returns the singleton instance of Migrator. - * @param options Migration options - * @param force A flag that defines if the migrator should get instantiated or not. - */ - getMigrator(options?: MigratorOptions, force?: boolean): Migrator; - - /** - * Define a new model, representing a table in the DB. - * - * @param daoName The name of the entity (table). Typically specified in singular form. - * @param attributes A hash of attributes to define. Each attribute can be either a string name for the attribute - * or can be an object defining the attribute and its options. Note attributes is not fully - * typed since TypeScript does not support union types--it can be either a string or an - * options object. @see AttributeOptions. - * @param options Table options. @see DefineOptions. - */ - define(daoName: string, attributes: any, options?: DefineOptions): Model; - - /** - * Fetch a DAO factory which is already defined. - * - * @param daoName The name of a model defined with Sequelize.define. - */ - model(daoName: string): Model; - - /** - * Checks whether a model with the given name is defined. - * - * @param daoName The name of a model defined with Sequelize.define. - */ - isDefined(daoName: string): boolean; - - /** - * Imports a model defined in another file. - * - * @param path The path to the file that holds the model you want to import. If the part is relative, it will be - * resolved relatively to the calling file - */ - import(path: string): Model; - - /** - * Execute a query on the DB, with the possibility to bypass all the sequelize goodness. - * - * @param sql SQL statement to execute. - * - * @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented - * by the factory. Equivalent to calling Model.build with the values provided by the query. - * - * @param options Query options. - * - * @param replacements Either an object of named parameter replacements in the format :param or an array of - * unnamed replacements to replace ? in your SQL. - */ - query(sql: string, callee?: Model, options?: QueryOptions, replacements?: any): EventEmitter; - - query(sql: string, callee?: Model, options?: QueryOptions): EventEmitterT>; - - /** - * Create a new database schema. - * - * @param schema Name of the schema. - */ - createSchema(schema: string): EventEmitter; - - /** - * Show all defined schemas. - */ - showAllSchemas(): EventEmitter; - - /** - * Drop a single schema. - * - * @param schema Name of the schema. - */ - dropSchema(schema: string): EventEmitter; - - /** - * Drop all schemas. - */ - dropAllSchemas(): EventEmitter; - - /** - * Sync all defined DAOs to the DB. - * - * @param options Options. - */ - sync(options?: SyncOptions): EventEmitter; - - /** - * Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model. - * - * @param options The options passed to each call to Model.drop. - */ - drop(options: DropOptions): EventEmitter; - - /** - * Test the connection by trying to authenticate. Alias for 'validate'. - */ - authenticate(): EventEmitter; - - /** - * Alias for authenticate(). Test the connection by trying to authenticate. Alias for 'validate'. - */ - validate(): EventEmitter; - - /** - * !! DEPRECATED : When passing a callback to a transaction a promise chain is expected in return, - * the transaction will be committed or rejected based on the promise chain returned to the callback. - * - * Start a transaction. When using transactions, you should pass the transaction in the options argument in order - * for the query to happen under that transaction. - * - * @param callback Called when the transaction has been set up and is ready for use. Callback takes transaction - * argument (overload available for error and transaction arguments too). - */ - transaction(callback: (transaction: Transaction) => boolean): Promise; - - /** - * Start a transaction. When using transactions, you should pass the transaction in the options argument in order - * for the query to happen under that transaction. - * - * @param options Transaction options. - * @param callback Called when the transaction has been set up and is ready for use. Callback takes transaction - * argument (overload available for error and transaction arguments too). - */ - transaction(options?: TransactionOptions, callback?: (transaction: Transaction) => void): PromiseT; - - close(): void; } - interface Config { - database?: string; - username?: string; - password?: string; - host?: string; - port?: number; - pool?: PoolOptions; - protocol?: string; - queue?: boolean; - native?: boolean; - ssl?: boolean; - replication?: ReplicationOptions; - dialectModulePath?: string; - maxConcurrentQueries?: number; - dialectOptions?: any; + /** + * Options provided for many-to-many relationships + * + * @see AssociationOptionsHasMany + * @see AssociationOptionsBelongsToMany + */ + interface AssociationOptionsManyToMany extends AssociationOptions { + + /** + * A key/value set that will be used for association create and find defaults on the target. + * (sqlite not supported for N:M) + */ + scope? : AssociationScope; + } - interface Model extends Hooks, Associations { - /** - * A reference to the sequelize instance. - */ - sequelize: Sequelize; + /** + * Options provided when associating models with hasOne relationship + * + * @see Association class hasOne method + */ + interface AssociationOptionsHasOne extends AssociationOptions { /** - * The name of the model, typically singular. + * A string or a data type to represent the identifier in the table */ - name: string; + keyType?: DataTypeAbstract; - /** - * The name of the underlying database table, typically plural. - */ - tableName: string; - - options: DefineOptions; - attributes: any; - rawAttributes: any; - modelManager: ModelManager; - daoFactoryManager: ModelManager; - associations: any; - scopeObj: any; - - /** - * Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the model - * instance (this). - */ - sync(options?: SyncOptions): PromiseT>; - - /** - * Drop the table represented by this Model. - * - * @param options - */ - drop(options?: DropOptions): Promise; - - /** - * Apply a schema to this model. For postgres, this will actually place the schema in front of the table name - - * "schema"."tableName", while the schema will be prepended to the table name for mysql and sqlite - - * 'schema.tablename'. - * - * @param schema The name of the schema. - * @param options Schema options. - */ - schema(schema: string, options?: SchemaOptions): Model; - - /** - * Get the tablename of the model, taking schema into account. The method will return The name as a string if the - * model has no schema, or an object with tableName, schema and delimiter properties. - */ - getTableName(): any; - - /** - * Apply a scope created in define to the model. - * - * @param options The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of - * arguments. To apply simple scopes, pass them as strings. For scope function, pass an object, - * with a method property. The value can either be a string, if the method does not take any - * arguments, or an array, where the first element is the name of the method, and consecutive - * elements are arguments to that method. Pass null to remove all scopes, including the default. - */ - scope(options: any): Model; - - /** - * Search for multiple instances.. - * - * @param options A hash of options to describe the scope of the search. - * @param queryOptions Set the query options, e.g. raw, specifying that you want raw data instead of built - * Instances. See sequelize.query for options. - */ - findAll(options?: FindOptions, queryOptions?: QueryOptions): PromiseT>; - - /** - * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance. - * - * @param options A hash of options to describe the scope of the search. - * @param queryOptions Set the query options, e.g. raw, specifying that you want raw data instead of built - * Instances. See sequelize.query for options - */ - find(options?: FindOptions, queryOptions?: QueryOptions): PromiseT; - - /** - * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance. - * - * @param options A number to search by id. - * @param queryOptions Set the query options, e.g. raw, specifying that you want raw data instead of built - * Instances. See sequelize.query for options - */ - find(id?: number, queryOptions?: QueryOptions): PromiseT; - - /** - * Run an aggregation method on the specified field. - * - * @param field The field to aggregate over. Can be a field name or *. - * @param aggregateFunction The function to use for aggregation, e.g. sum, max etc. - * @param options Query options, particularly options.dataType. - */ - aggregate(field: string, aggregateFunction: string, options: FindOptions): PromiseT; - - /** - * Count the number of records matching the provided where clause. - * - * @param options Conditions and options for the query. - */ - count(options?: FindOptions): PromiseT; - - /** - * Find all the rows matching your query, within a specified offset / limit, and get the total number of rows - * matching your query. This is very usefull for paging. - * - * @param findOptions Filtering options - * @param queryOptions Query options - */ - findAndCountAll(findOptions?: FindOptions, queryOptions?: QueryOptions): PromiseT>; - - /** - * Find the maximum value of field. - * - * @param field - * @param options - */ - max(field: string, options?: FindOptions): PromiseT; - - /** - * Find the minimum value of field. - * - * @param field - * @param options - */ - min(field: string, options?: FindOptions): PromiseT; - - /** - * Find the sum of field. - * - * @param field - * @param options - */ - sum(field: string, options?: FindOptions): PromiseT; - - /** - * Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty. - * - * @param values any from which to build entity instance. - * @param options any construction options. - */ - build(values: TPojo, options?: BuildOptions): TInstance; - - /** - * Builds a new model instance and calls save on it.. - * - * @param values - * @param options - */ - create(values: TPojo, options?: CopyOptions): PromiseT; - - /** - * Find a row that matches the query, or build (but don't save) the row if none is found. The successfull result - * of the promise will be (instance, initialized) - Make sure to use .spread(). - * - * @param where A hash of search attributes. Note that this method differs from finders, in that the syntax - * is { attr1: 42 } and NOT { where: { attr1: 42}}. This may be subject to change in 2.0 - * @param defaults Default values to use if building a new instance - * @param options Options passed to the find call - */ - findOrInitialize(where: any, defaults?: TPojo, options?: QueryOptions): PromiseT; - - /** - * Find a row that matches the query, or build and save the row if none is found The successfull result of the - * promise will be (instance, created) - Make sure to use .spread(). - * - * @param where A hash of search attributes. Note that this method differs from finders, in that the syntax is - * { attr1: 42 } and NOT { where: { attr1: 42}}. This is subject to change in 2.0 - * @param defaults Default values to use if creating a new instance - * @param options Options passed to the find and create calls. - */ - findOrCreate(where: any, defaults?: TPojo, options?: FindOrCreateOptions): PromiseT; - - /** - * Create and insert multiple instances in bulk. - * - * @param records List of objects (key/value pairs) to create instances from. - * @param options - */ - bulkCreate(records: Array, options?: BulkCreateOptions): PromiseT>; - - /** - * Delete multiple instances. - */ - destroy(where?: any, options?: DestroyOptions): Promise; - - /** - * Update multiple instances that match the where options. - * - * @param attrValueHash A hash of fields to change and their new values - * @param where Options to describe the scope of the search. Note that these options are not wrapped in a - * { where: ... } is in find / findAll calls etc. This is probably due to change in 2.0. - */ - update(attrValueHash: TPojo, where: any, options?: UpdateOptions): Promise; - - /** - * Run a describe query on the table. The result will be return to the listener as a hash of attributes and their - * types. - */ - describe(): PromiseT; - - /** - * A proxy to the node-sql query builder, which allows you to build your query through a chain of method calls. - * The returned instance already has all the fields property populated with the field of the model. - */ - dataset(): any; } - interface Instance { - /** - * Returns true if this instance has not yet been persisted to the database. - */ - isNewRecord: boolean; + /** + * Options provided when associating models with belongsTo relationship + * + * @see Association class belongsTo method + */ + interface AssociationOptionsBelongsTo extends AssociationOptions { /** - * Returns the Model the instance was created from. + * The name of the field to use as the key for the association in the target table. Defaults to the primary + * key of the target table */ - Model: Model; + targetKey? : string; /** - * A reference to the sequelize instance. + * A string or a data type to represent the identifier in the table */ - sequelize: Sequelize; + keyType?: DataTypeAbstract; - /** - * If timestamps and paranoid are enabled, returns whether the deletedAt timestamp of this instance is set. - * Otherwise, always returns false. - */ - isDeleted: boolean; - - /** - * Get the values of this Instance. Proxies to this.get. - */ - values: TPojo; - - /** - * A getter for this.changed(). Returns true if any keys have changed. - */ - isDirty: boolean; - - /** - * Get the values of the primary keys of this instance. - */ - primaryKeyValues: TPojo; - - /** - * Get the value of the underlying data value. - * - * @param key Field to retrieve. - */ - getDataValue(key: string): any; - - /** - * Update the underlying data value. - * - * @param key Field to set. - * @param value Value to set. - */ - setDataValue(key: string, value: any): void; - - /** - * Retrieves the value for the key when specified. If no key is given, returns all values of the instance, also - * invoking virtual getters. - */ - get(key?: string): any; - - /** - * Set is used to update values on the instance (the sequelize representation of the instance that is, remember - * that nothing will be persisted before you actually call save). - */ - set(key: string, value: any, options?: SetOptions): void; - - /** - * If changed is called with a string it will return a boolean indicating whether the value of that key in - * dataValues is different from the value in _previousDataValues. If changed is called without an argument, it will - * return an array of keys that have changed. - */ - changed(key: string): any; - - /** - * If changed is called with a string it will return a boolean indicating whether the value of that key in - * dataValues is different from the value in _previousDataValues. If changed is called without an argument, it will - * return an array of keys that have changed. - */ - changed(): Array; - - /** - * Returns the previous value for key from _previousDataValues. - */ - previous(key: string): any; - - /** - * Validate this instance, and if the validation passes, persist it to the database. - */ - save(fields?: Array, options?: SaveOptions): PromiseT; - - /** - * Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same - * object. This is different from doing a find(Instance.id), because that would create and return a new instance. - * With this method, all references to the Instance are updated with the new data and no new objects are created. - */ - reload(options?: FindOptions): PromiseT; - - /** - * Validate the attribute of this instance according to validation rules set in the model definition. - */ - validate(options?: ValidateOptions): PromiseT; - - /** - * This is the same as calling setAttributes, then calling save. - */ - updateAttributes(updates: TPojo, options: SaveOptions): PromiseT; - - /** - * Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will either be - * completely deleted, or have its deletedAt timestamp set to the current time. - * - * @param options Allows caller to specify if delete should be forced. - */ - destroy(options?: DestroyInstanceOptions): Promise; - - /** - * Increment the value of one or more columns. This is done in the database, which means it does not use the - * values currently stored on the Instance. - * - * @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. - * @param options Increment options. - */ - increment(fields: any, options?: IncrementOptions): Promise; - - /** - * Decrement the value of one or more columns. This is done in the database, which means it does not use the - * values currently stored on the Instance. - * - * @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. - * @param options Decrement options. - */ - decrement(fields: any, options?: IncrementOptions): Promise; - - /** - * Check whether all values of this and other Instance are the same. - */ - equal(other: TInstance): boolean; - - /** - * Check if this is eqaul to one of others by calling equals. - * - * @param others Other instances to compare to. - */ - equalsOneOf(others: Array): boolean; - - /** - * Convert the instance to a JSON representation. Proxies to calling get with no keys. This means get all values - * gotten from the DB, and apply all custom getters. - */ - toJSON(): TPojo; } - interface Transaction extends TransactionStatic { - /** - * Commit the transaction. - */ - commit(): Transaction; + /** + * Options provided when associating models with hasMany relationship + * + * @see Association class hasMany method + */ + interface AssociationOptionsHasMany extends AssociationOptionsManyToMany { /** - * Rollback (abort) the transaction. + * A string or a data type to represent the identifier in the table */ - rollback(): Transaction; + keyType?: DataTypeAbstract; + } - interface TransactionStatic { - /** - * The possible isolation levels to use when starting a transaction - */ - ISOLATION_LEVELS: TransactionIsolationLevels; + /** + * Options provided when associating models with belongsToMany relationship + * + * @see Association class belongsToMany method + */ + interface AssociationOptionsBelongsToMany extends AssociationOptionsManyToMany { /** - * Possible options for row locking. Used in conjuction with find calls. - */ - LOCK: TransactionLocks; - } - - interface TransactionIsolationLevels { - READ_UNCOMMITTED: string;// "READ UNCOMMITTED" - READ_COMMITTED: string; // "READ COMMITTED" - REPEATABLE_READ: string; // "REPEATABLE READ" - SERIALIZABLE: string; // "SERIALIZABLE" - } - - interface TransactionLocks { - UPDATE: string; // UPDATE - SHARE: string; // SHARE - } - - interface Hooks { - - /** - * Add a named hook to the model. + * 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. * - * @param hooktype - */ - addHook(hooktype: string, name: string, fn: (...args: Array) => void): boolean; - - /** - * Add a hook to the model. + * In 3.4.1 version of Sequelize, hasMany's use of through gives an error, and on the other hand through + * option for belongsToMany has been made required. * - * @param hooktype + * @see https://github.com/sequelize/sequelize/blob/v3.4.1/lib/associations/has-many.js + * @see https://github.com/sequelize/sequelize/blob/v3.4.1/lib/associations/belongs-to-many.js */ - addHook(hooktype: string, fn: (...args: Array) => void): boolean; + through : Model | string | ThroughOptions; /** - * A named hook that is run before validation. + * 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 */ - beforeValidate(name: string, validator: (dao: T, callback: (err?: Error) => void) => void): void; + otherKey? : string | AssociationForeignKeyOptions; - /** - * A hook that is run before validation. - */ - beforeValidate(validator: (dao: T, callback: (err?: Error) => void) => void): void; - - /** - * A named hook that is run before validation. - */ - afterValidate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run before validation. - */ - afterValidate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run before creating a single instance. - */ - beforeCreate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run before creating a single instance. - */ - beforeCreate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run after creating a single instance. - */ - afterCreate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run after creating a single instance. - */ - afterCreate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run before destroying a single instance. - */ - beforeDestroy(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run before destroying a single instance. - */ - beforeDestroy(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run after destroying a single instance. - */ - afterDestroy(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run after destroying a single instance. - */ - afterDestroy(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run before updating a single instance. - */ - beforeUpdate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run before updating a single instance. - */ - beforeUpdate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run after updating a single instance. - */ - afterUpdate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run after updating a single instance. - */ - afterUpdate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run before creating instances in bulk. - */ - beforeBulkCreate(name: string, validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run before creating instances in bulk. - */ - beforeBulkCreate(validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run after creating instances in bulk. - */ - afterBulkCreate(name: string, validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run after creating instances in bulk. - */ - afterBulkCreate(validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run before destroying instances in bulk. - */ - beforeBulkDestroy(name: string, validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; - - /** - * A hook that is run before destroying instances in bulk. - */ - beforeBulkDestroy(validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; - - /** - * A named hook that is run after destroying instances in bulk. - */ - afterBulkDestroy(name: string, validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; - - /** - * A hook that is run after destroying instances in bulk. - */ - afterBulkDestroy(validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; - - /** - * A named hook that is run before updating instances in bulk. - */ - beforeBulkUpdate(name: string, validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; - - /** - * A hook that is run before updating instances in bulk. - */ - beforeBulkUpdate(validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; - - /** - * A named hook that is run after updating instances in bulk. - */ - afterBulkUpdate(name: string, validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; - - /** - * A hook that is run after updating instances in bulk. - */ - afterBulkUpdate(validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; } + /** + * Used for a association table in n:m associations. + * + * @see AssociationOptionsBelongsToMany + */ + interface ThroughOptions { + + /** + * The model used to join both sides of the N:M association. + */ + model : Model; + + /** + * A key/value set that will be used for association create and find defaults on the through model. + * (Remember to add the attributes to the through model) + */ + scope? : AssociationScope; + + /** + * If true a unique key will be generated from the foreign keys used (might want to turn this off and create + * specific unique keys when using scopes) + * + * Defaults to true + */ + unique? : boolean; + + } + + /** + * Creating assocations in sequelize is done by calling one of the belongsTo / hasOne / hasMany functions on a + * model (the source), and providing another model as the first argument to the function (the target). + * + * * hasOne - adds a foreign key to target + * * belongsTo - add a foreign key to source + * * hasMany - adds a foreign key to target, unless you also specify that target hasMany source, in which case + * a + * junction table is created with sourceId and targetId + * + * Creating an association will add a foreign key constraint to the attributes. All associations use `CASCADE` + * on update and `SET NULL` on delete, except for n:m, which also uses `CASCADE` on delete. + * + * When creating associations, you can provide an alias, via the `as` option. This is useful if the same model + * is associated twice, or you want your association to be called something other than the name of the target + * model. + * + * As an example, consider the case where users have many pictures, one of which is their profile picture. All + * pictures have a `userId`, but in addition the user model also has a `profilePictureId`, to be able to easily + * load the user's profile picture. + * + * ```js + * User.hasMany(Picture) + * User.belongsTo(Picture, { as: 'ProfilePicture', constraints: false }) + * + * user.getPictures() // gets you all pictures + * user.getProfilePicture() // gets you only the profile picture + * + * User.findAll({ + * where: ..., + * include: [ + * { model: Picture }, // load all pictures + * { model: Picture, as: 'ProfilePicture' }, // load the profile picture. Notice that the spelling must be + * the exact same as the one in the association + * ] + * }) + * ``` + * To get full control over the foreign key column added by sequelize, you can use the `foreignKey` option. It + * can either be a string, that specifies the name, or and object type definition, + * equivalent to those passed to `sequelize.define`. + * + * ```js + * User.hasMany(Picture, { foreignKey: 'uid' }) + * ``` + * + * The foreign key column in Picture will now be called `uid` instead of the default `userId`. + * + * ```js + * User.hasMany(Picture, { + * foreignKey: { + * name: 'uid', + * allowNull: false + * } + * }) + * ``` + * + * This specifies that the `uid` column can not be null. In most cases this will already be covered by the + * foreign key costraints, which sequelize creates automatically, but can be useful in case where the foreign + * keys are disabled, e.g. due to circular references (see `constraints: false` below). + * + * When fetching associated models, you can limit your query to only load some models. These queries are + * written + * in the same way as queries to `find`/`findAll`. To only get pictures in JPG, you can do: + * + * ```js + * user.getPictures({ + * where: { + * format: 'jpg' + * } + * }) + * ``` + * + * There are several ways to update and add new assoications. Continuing with our example of users and + * pictures: + * ```js + * user.addPicture(p) // Add a single picture + * user.setPictures([p1, p2]) // Associate user with ONLY these two picture, all other associations will be + * deleted user.addPictures([p1, p2]) // Associate user with these two pictures, but don't touch any current + * associations + * ``` + * + * You don't have to pass in a complete object to the association functions, if your associated model has a + * single primary key: + * + * ```js + * user.addPicture(req.query.pid) // Here pid is just an integer, representing the primary key of the picture + * ``` + * + * In the example above we have specified that a user belongs to his profile picture. Conceptually, this might + * not make sense, but since we want to add the foreign key to the user model this is the way to do it. + * + * Note how we also specified `constraints: false` for profile picture. This is because we add a foreign key + * from user to picture (profilePictureId), and from picture to user (userId). If we were to add foreign keys + * to both, it would create a cyclic dependency, and sequelize would not know which table to create first, + * since user depends on picture, and picture depends on user. These kinds of problems are detected by + * sequelize before the models are synced to the database, and you will get an error along the lines of `Error: + * Cyclic dependency found. 'users' is dependent of itself`. If you encounter this, you should either disable + * some constraints, or rethink your associations completely. + * + * @see Sequelize.Model + */ interface Associations { - /** - * Creates an association between this (the source) and the provided target. The foreign key is added on the target. - * - * @param target - * @param options - */ - hasOne(target: Model, options?: AssociationOptions): void; /** - * Creates an association between this (the source) and the provided target. The foreign key is added on the source. + * Creates an association between this (the source) and the provided target. The foreign key is added + * on the target. * - * @param target - * @param options + * Example: `User.hasOne(Profile)`. This will add userId to the profile table. + * + * @param target The model that will be associated with hasOne relationship + * @param options Options for the association */ - belongsTo(target: Model, options?: AssociationOptions): void; + hasOne( target : Model, options? : AssociationOptionsHasOne ): void; /** - * Creates an association to connect sources with multiple targets. Furthermore the targets can also have connections to multiple sources. + * Creates an association between this (the source) and the provided target. The foreign key is added on the + * source. * - * @param target - * @param options + * Example: `Profile.belongsTo(User)`. This will add userId to the profile table. + * + * @param target The model that will be associated with hasOne relationship + * @param options Options for the association */ - belongsToMany(target: Model, options?: AssociationOptions): void; + belongsTo( target : Model, options? : AssociationOptionsBelongsTo ) : void; /** * Create an association that is either 1:m or n:m. * - * @param target - * @param options + * ```js + * // Create a 1:m association between user and project + * User.hasMany(Project) + * ``` + * ```js + * // Create a n:m association between user and project + * User.hasMany(Project) + * Project.hasMany(User) + * ``` + * By default, the name of the join table will be source+target, so in this case projectsusers. This can be + * overridden by providing either a string or a Model as `through` in the options. If you use a through + * model with custom attributes, these attributes can be set when adding / setting new associations in two + * ways. Consider users and projects from before with a join table that stores whether the project has been + * started yet: + * ```js + * var UserProjects = sequelize.define('userprojects', { + * started: Sequelize.BOOLEAN + * }) + * User.hasMany(Project, { through: UserProjects }) + * Project.hasMany(User, { through: UserProjects }) + * ``` + * ```js + * jan.addProject(homework, { started: false }) // The homework project is not started yet + * jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner have been + * started + * ``` + * + * If you want to set several target instances, but with different attributes you have to set the + * attributes on the instance, using a property with the name of the through model: + * + * ```js + * p1.userprojects { + * started: true + * } + * user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that. + * ``` + * + * Similarily, when fetching through a join table with custom attributes, these attributes will be + * available as an object with the name of the through model. + * ```js + * user.getProjects().then(function (projects) { + * var p1 = projects[0] + * p1.userprojects.started // Is this project started yet? + * }) + * ``` + * + * @param target The model that will be associated with hasOne relationship + * @param options Options for the association */ - hasMany(target: Model, options?: AssociationOptions): void; + hasMany( target : Model, options? : AssociationOptionsHasMany ) : void; + + /** + * Create an N:M association with a join table + * + * ```js + * User.belongsToMany(Project) + * Project.belongsToMany(User) + * ``` + * By default, the name of the join table will be source+target, so in this case projectsusers. This can be + * overridden by providing either a string or a Model as `through` in the options. + * + * If you use a through model with custom attributes, these attributes can be set when adding / setting new + * associations in two ways. Consider users and projects from before with a join table that stores whether + * the project has been started yet: + * ```js + * var UserProjects = sequelize.define('userprojects', { + * started: Sequelize.BOOLEAN + * }) + * User.belongsToMany(Project, { through: UserProjects }) + * Project.belongsToMany(User, { through: UserProjects }) + * ``` + * ```js + * jan.addProject(homework, { started: false }) // The homework project is not started yet + * jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner has been started + * ``` + * + * If you want to set several target instances, but with different attributes you have to set the + * attributes on the instance, using a property with the name of the through model: + * + * ```js + * p1.userprojects { + * started: true + * } + * user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that. + * ``` + * + * Similarily, when fetching through a join table with custom attributes, these attributes will be + * available as an object with the name of the through model. + * ```js + * user.getProjects().then(function (projects) { + * var p1 = projects[0] + * p1.userprojects.started // Is this project started yet? + * }) + * ``` + * + * @param target The model that will be associated with hasOne relationship + * @param options Options for the association + * + */ + belongsToMany( target : Model, options : AssociationOptionsBelongsToMany ) : void; + + } + + // + // DataTypes + // ~~~~~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/data-types.js + // + + /** + * Abstract DataType interface. Use this if you want to create an interface that has a value any of the + * DataTypes that Sequelize supports. + */ + interface DataTypeAbstract { + + /** + * Although this is not needed for the definitions itself, we want to make sure that DataTypeAbstract is not + * something than can be evaluated to an empty object. + */ + dialectTypes : string; + + } + + interface DataTypeAbstractString extends DataTypeAbstract { + + /** + * A variable length string. Default length 255 + */ + ( options? : { length: number } ) : T; + ( length : number ) : T; + + /** + * Property BINARY for the type + */ + BINARY : T; + + } + + interface DataTypeString extends DataTypeAbstractString { } + + interface DataTypeChar extends DataTypeAbstractString { } + + interface DataTypeText extends DataTypeAbstract { + + /** + * Length of the text field. + * + * Available lengths: `tiny`, `medium`, `long` + */ + ( options? : { length: string } ) : DataTypeText; + ( length : string ) : DataTypeText; + + } + + interface DataTypeAbstractNumber extends DataTypeAbstract { + UNSIGNED : T; + ZEROFILL : T; + } + + interface DataTypeNumber extends DataTypeAbstractNumber { } + + interface DataTypeInteger extends DataTypeAbstractNumber { + + /** + * Length of the number field. + */ + ( options? : { length: number } ) : DataTypeInteger; + ( length : number ) : DataTypeInteger; + + } + + interface DataTypeBigInt extends DataTypeAbstractNumber { + + /** + * Length of the number field. + */ + ( options? : { length: number } ) : DataTypeBigInt; + ( length : number ) : DataTypeBigInt; + + } + + interface DataTypeFloat extends DataTypeAbstractNumber { + + /** + * Length of the number field and decimals of the float + */ + ( options? : { length: number, decimals?: number } ) : DataTypeFloat; + ( length : number, decimals? : number ) : DataTypeFloat; + + } + + interface DataTypeReal extends DataTypeAbstractNumber { + + /** + * Length of the number field and decimals of the real + */ + ( options? : { length: number, decimals?: number } ) : DataTypeReal; + ( length : number, decimals? : number ) : DataTypeReal; + + } + + interface DataTypeDouble extends DataTypeAbstractNumber { + + /** + * Length of the number field and decimals of the real + */ + ( options? : { length: number, decimals?: number } ) : DataTypeDouble; + ( length : number, decimals? : number ) : DataTypeDouble; + + } + + interface DataTypeDecimal extends DataTypeAbstractNumber { + + /** + * Precision and scale for the decimal number + */ + ( options? : { precision: number, scale?: number } ) : DataTypeDecimal; + ( precision : number, scale? : number ) : DataTypeDecimal; + + } + + interface DataTypeBoolean extends DataTypeAbstract { } + + interface DataTypeTime extends DataTypeAbstract { } + + interface DataTypeDate extends DataTypeAbstract { } + + interface DataTypeDateOnly extends DataTypeAbstract { } + + interface DataTypeHStore extends DataTypeAbstract { } + + interface DataTypeJSONType extends DataTypeAbstract { } + + interface DataTypeJSONB extends DataTypeAbstract { } + + interface DataTypeNow extends DataTypeAbstract { } + + interface DataTypeBlob extends DataTypeAbstract { + + /** + * Length of the blob field. + * + * Available lengths: `tiny`, `medium`, `long` + */ + ( options? : { length: string } ) : DataTypeBlob; + ( length : string ) : DataTypeBlob; + + } + + interface DataTypeRange extends DataTypeAbstract { + + /** + * Range field for Postgre + * + * Accepts subtype any of the ranges + */ + ( options? : { subtype: DataTypeAbstract } ) : DataTypeRange; + ( subtype : DataTypeAbstract ) : DataTypeRange; + + } + + interface DataTypeUUID extends DataTypeAbstract { } + + interface DataTypeUUIDv1 extends DataTypeAbstract { } + + interface DataTypeUUIDv4 extends DataTypeAbstract { } + + interface DataTypeVirtual extends DataTypeAbstract { } + + interface DataTypeEnum extends DataTypeAbstract { + + /** + * Enum field + * + * Accepts values + */ + ( options? : { values: string | string[] } ) : DataTypeEnum; + ( values : string | string[] ) : DataTypeEnum; + ( ...args : string[] ) : DataTypeEnum; + + } + + interface DataTypeArray extends DataTypeAbstract { + + /** + * Array field for Postgre + * + * Accepts type any of the DataTypes + */ + ( options : { type: DataTypeAbstract } ) : DataTypeArray; + ( type : DataTypeAbstract ) : DataTypeArray; + + } + + interface DataTypeGeometry extends DataTypeAbstract { + + /** + * Geometry field for Postgres + */ + ( type : string, srid? : number ) : DataTypeGeometry; + } /** - * Extension of external project that doesn't have definitions. + * A convenience class holding commonly used data types. The datatypes are used when definining a new model + * using + * `Sequelize.define`, like this: * - * See https://github.com/chriso/validator.js and https://github.com/sequelize/sequelize/blob/master/lib/instance-validator.js + * ```js + * sequelize.define('model', { + * column: DataTypes.INTEGER + * }) + * ``` + * When defining a model you can just as easily pass a string as type, but often using the types defined here + * is + * beneficial. For example, using `DataTypes.BLOB`, mean that that column will be returned as an instance of + * `Buffer` when being fetched by sequelize. + * + * Some data types have special properties that can be accessed in order to change the data type. + * For example, to get an unsigned integer with zerofill you can do `DataTypes.INTEGER.UNSIGNED.ZEROFILL`. + * The order you access the properties in do not matter, so `DataTypes.INTEGER.ZEROFILL.UNSIGNED` is fine as + * well. The available properties are listed under each data type. + * + * To provide a length for the data type, you can invoke it like a function: `INTEGER(2)` + * + * Three of the values provided here (`NOW`, `UUIDV1` and `UUIDV4`) are special default values, that should not + * be used to define types. Instead they are used as shorthands for defining default values. For example, to + * get a uuid field with a default value generated following v1 of the UUID standard: + * + * ```js + * sequelize.define('model', { + * uuid: { + * type: DataTypes.UUID, + * defaultValue: DataTypes.UUIDV1, + * primaryKey: true + * } + * }) + * ``` */ - interface Validator { + interface DataTypes { + ABSTRACT : DataTypeAbstract; + STRING : DataTypeString; + CHAR : DataTypeChar; + TEXT : DataTypeText; + NUMBER : DataTypeNumber; + INTEGER : DataTypeInteger; + BIGINT : DataTypeBigInt; + FLOAT : DataTypeFloat; + TIME : DataTypeTime; + DATE : DataTypeDate; + DATEONLY: DataTypeDateOnly; + BOOLEAN: DataTypeBoolean; + NOW: DataTypeNow; + BLOB: DataTypeBlob; + DECIMAL: DataTypeDecimal; + NUMERIC: DataTypeDecimal; + UUID: DataTypeUUID; + UUIDV1: DataTypeUUIDv1; + UUIDV4: DataTypeUUIDv4; + HSTORE: DataTypeHStore; + JSON: DataTypeJSONType; + JSONB: DataTypeJSONB; + VIRTUAL: DataTypeVirtual; + ARRAY: DataTypeArray; + NONE: DataTypeVirtual; + ENUM: DataTypeEnum; + RANGE: DataTypeRange; + REAL: DataTypeReal; + DOUBLE: DataTypeDouble, + 'DOUBLE PRECISION': DataTypeDouble, + GEOMETRY: DataTypeGeometry + } + + // + // Deferrable + // ~~~~~~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/deferrable.js + // + + /** + * Abstract Deferrable interface. Use this if you want to create an interface that has a value any of the + * Deferrables that Sequelize supports. + */ + interface DeferrableAbstract { + + /** + * Although this is not needed for the definitions itself, we want to make sure that DeferrableAbstract is + * not something than can be evaluated to an empty object. + */ + toString() : string; + toSql() : string; + + } + + interface DeferrableInitiallyDeferred extends DeferrableAbstract { + + /** + * A property that will defer constraints checks to the end of transactions. + */ + () : DeferrableInitiallyDeferred; + + } + + interface DeferrableInitiallyImmediate extends DeferrableAbstract { + + /** + * A property that will trigger the constraint checks immediately + */ + () : DeferrableInitiallyImmediate; + + } + + interface DeferrableNot extends DeferrableAbstract { + + /** + * A property that will set the constraints to not deferred. This is the default in PostgreSQL and it make + * it impossible to dynamically defer the constraints within a transaction. + */ + () : DeferrableNot; + + } + + interface DeferrableSetDeferred extends DeferrableAbstract { + + /** + * A property that will trigger an additional query at the beginning of a + * transaction which sets the constraints to deferred. + * + * @param constraints An array of constraint names. Will defer all constraints by default. + */ + ( constraints : Array ) : DeferrableSetDeferred; + + } + + interface DeferrableSetImmediate extends DeferrableAbstract { + + /** + * A property that will trigger an additional query at the beginning of a + * transaction which sets the constraints to immediately. + * + * @param constraints An array of constraint names. Will defer all constraints by default. + */ + ( constraints : Array ) : DeferrableSetImmediate; } /** - * Custom class defined, but no extra methods or functionality even. + * A collection of properties related to deferrable constraints. It can be used to + * make foreign key constraints deferrable and to set the constaints within a + * transaction. This is only supported in PostgreSQL. + * + * The foreign keys can be configured like this. It will create a foreign key + * that will check the constraints immediately when the data was inserted. + * + * ```js + * sequelize.define('Model', { + * foreign_id: { + * type: Sequelize.INTEGER, + * references: { + * model: OtherModel, + * key: 'id', + * deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE + * } + * } + * }); + * ``` + * + * The constraints can be configured in a transaction like this. It will + * trigger a query once the transaction has been started and set the constraints + * to be checked at the very end of the transaction. + * + * ```js + * sequelize.transaction({ + * deferrable: Sequelize.Deferrable.SET_DEFERRED + * }); + * ``` */ - interface ValidationError extends Error { + interface Deferrable { + INITIALLY_DEFERRED: DeferrableInitiallyDeferred; + INITIALLY_IMMEDIATE: DeferrableInitiallyImmediate; + NOT: DeferrableNot; + SET_DEFERRED: DeferrableSetDeferred; + SET_IMMEDIATE: DeferrableSetImmediate + } + + // + // Errors + // ~~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/errors.js + // + + /** + * The Base Error all Sequelize Errors inherit from. + */ + interface BaseError extends ErrorConstructor { } + + interface ValidationError extends BaseError { + + /** + * Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` + * property, which is an array with 1 or more ValidationErrorItems, one for each validation that failed. + * + * @param message Error message + * @param errors Array of ValidationErrorItem objects describing the validation errors + */ + new ( message : string, errors? : Array ) : ValidationError; + + /** + * Gets all validation error items for the path / field specified. + * + * @param path The path to be checked for error items + */ + get( path : string ) : Array; } - interface QueryChainer { + interface ValidationErrorItem extends BaseError { + /** - * Add an query to the chainer. This can be done in two ways - either by invoking the method like you would - * normally, and then adding the returned emitter to the chainer, or by passing the class that you want to call a - * method on, the name of the method, and its parameters to the chainer. The second form might sound a bit - * cumbersome, but it is used when you want to run queries in serial. + * Validation Error Item + * Instances of this class are included in the `ValidationError.errors` property. + * + * @param message An error message + * @param type The type of the validation error + * @param path The field that triggered the validation error + * @param value The value that generated the error + */ + new ( message : string, type : string, path : string, value : string ) : ValidationErrorItem; + + } + + interface DatabaseError extends BaseError { + + /** + * A base class for all database related errors. + */ + new ( parent : Error ) : DatabaseError; + + } + + interface TimeoutError extends DatabaseError { + + /** + * Thrown when a database query times out because of a deadlock + */ + new ( parent : Error ) : TimeoutError; + + } + + interface UniqueConstraintError extends DatabaseError { + + /** + * Thrown when a unique constraint is violated in the database + */ + new ( options : { parent? : Error, message? : string, errors? : Object } ) : UniqueConstraintError; + + } + + interface ForeignKeyConstraintError extends DatabaseError { + + /** + * Thrown when a foreign key constraint is violated in the database + */ + new ( options : { parent? : Error, message? : string, index? : string, fields? : Array, table? : string } ) : ForeignKeyConstraintError; + + } + + interface ExclusionConstraintError extends DatabaseError { + + /** + * Thrown when an exclusion constraint is violated in the database + */ + new ( options : { parent? : Error, message? : string, constraint? : string, fields? : Array, table? : string } ) : ExclusionConstraintError; + + } + + interface ConnectionError extends BaseError { + + /** + * A base class for all connection related errors. + */ + new ( parent : Error ) : ConnectionError; + + } + + interface ConnectionRefusedError extends ConnectionError { + + /** + * Thrown when a connection to a database is refused + */ + new ( parent : Error ) : ConnectionRefusedError; + + } + + interface AccessDeniedError extends ConnectionError { + + /** + * Thrown when a connection to a database is refused due to insufficient privileges + */ + new ( parent : Error ) : AccessDeniedError; + + } + + interface HostNotFoundError extends ConnectionError { + + /** + * Thrown when a connection to a database has a hostname that was not found + */ + new ( parent : Error ) : HostNotFoundError; + + } + + interface HostNotReachableError extends ConnectionError { + + /** + * Thrown when a connection to a database has a hostname that was not reachable + */ + new ( parent : Error ) : HostNotReachableError; + + } + + interface InvalidConnectionError extends ConnectionError { + + /** + * Thrown when a connection to a database has invalid values for any of the connection parameters + */ + new ( parent : Error ) : InvalidConnectionError; + + } + + interface ConnectionTimedOutError extends ConnectionError { + + /** + * Thrown when a connection to a database times out + */ + new ( parent : Error ) : ConnectionTimedOutError; + + } + + /** + * Sequelize provides a host of custom error classes, to allow you to do easier debugging. All of these errors + * are exposed on the sequelize object and the sequelize constructor. All sequelize errors inherit from the + * base JS error object. + */ + interface Errors { + Error : BaseError; + ValidationError : ValidationError; + ValidationErrorItem : ValidationErrorItem; + DatabaseError : DatabaseError; + TimeoutError : TimeoutError; + UniqueConstraintError : UniqueConstraintError; + ExclusionConstraintError : ExclusionConstraintError; + ForeignKeyConstraintError : ForeignKeyConstraintError; + ConnectionError : ConnectionError; + ConnectionRefusedError : ConnectionRefusedError; + AccessDeniedError : AccessDeniedError; + HostNotFoundError : HostNotFoundError; + HostNotReachableError : HostNotReachableError; + InvalidConnectionError : InvalidConnectionError; + ConnectionTimedOutError : ConnectionTimedOutError; + } + + // + // Hooks + // ~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/hooks.js + // + + /** + * Options for Sequelize.define. We mostly duplicate the Hooks here, since there is no way to combine the two + * interfaces. + * + * beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, + * beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, afterBulkCreate, afterBulkDestroy and + * afterBulkUpdate. + */ + interface HooksDefineOptions { + + beforeValidate? : ( instance : TInstance, options : Object, fn? : Function ) => any; + afterValidate? : ( instance : TInstance, options : Object, fn? : Function ) => any; + beforeCreate? : ( attributes : TInstance, options : Object, fn? : Function ) => any; + afterCreate? : ( attributes : TInstance, options : Object, fn? : Function ) => any; + beforeDestroy? : ( instance : TInstance, options : Object, fn? : Function ) => any; + beforeDelete? : ( instance : TInstance, options : Object, fn? : Function ) => any; + afterDestroy? : ( instance : TInstance, options : Object, fn? : Function ) => any; + afterDelete? : ( instance : TInstance, options : Object, fn? : Function ) => any; + beforeUpdate? : ( instance : TInstance, options : Object, fn? : Function ) => any; + afterUpdate? : ( instance : TInstance, options : Object, fn? : Function ) => any; + beforeBulkCreate? : ( instances : Array, options : Object, fn? : Function ) => any; + afterBulkCreate? : ( instances : Array, options : Object, fn? : Function ) => any; + beforeBulkDestroy? : ( options : Object, fn? : Function ) => any; + beforeBulkDelete? : ( options : Object, fn? : Function ) => any; + afterBulkDestroy? : ( options : Object, fn? : Function ) => any; + afterBulkDelete? : ( options : Object, fn? : Function ) => any; + beforeBulkUpdate? : ( options : Object, fn? : Function ) => any; + afterBulkUpdate? : ( options : Object, fn? : Function ) => any; + beforeFind? : ( options : Object, fn? : Function ) => any; + beforeFindAfterExpandIncludeAll? : ( options : Object, fn? : Function ) => any; + beforeFindAfterOptions? : ( options : Object, fn? : Function ) => any; + afterFind? : ( instancesOrInstance : Array | TInstance, options : Object, + fn? : Function ) => any; + + } + + /** + * Hooks are function that are called before and after (bulk-) creation/updating/deletion and validation. + * Hooks can be added to you models in three ways: + * + * 1. By specifying them as options in `sequelize.define` + * 2. By calling `hook()` with a string and your hook handler function + * 3. By calling the function with the same name as the hook you want + * + * ```js + * // Method 1 + * sequelize.define(name, { attributes }, { + * hooks: { + * beforeBulkCreate: function () { + * // can be a single function + * }, + * beforeValidate: [ + * function () {}, + * function() {} // Or an array of several + * ] + * } + * }) + * + * // Method 2 + * Model.hook('afterDestroy', function () {}) + * + * // Method 3 + * Model.afterBulkUpdate(function () {}) + * ``` + * + * @see Sequelize.define + */ + interface Hooks { + + /** + * Add a hook to the model + * + * @param hookType + * @param name Provide a name for the hook function. It can be used to remove the hook later or to order + * hooks based on some sort of priority system in the future. + * @param fn The hook function + * + * @alias hook + */ + addHook( hookType : string, name : string, fn : Function ) : Hooks; + addHook( hookType : string, fn : Function ) : Hooks; + hook( hookType : string, name : string, fn : Function ) : Hooks; + hook( hookType : string, fn : Function ) : Hooks; + + /** + * Remove hook from the model + * + * @param hookType + * @param name + */ + removeHook( hookType : string, name : string ) : Hooks; + + /** + * Check whether the mode has any hooks of this type + * + * @param hookType + * + * @alias hasHooks + */ + hasHook( hookType : string ) : boolean; + hasHooks( hookType : string ) : boolean; + + /** + * A hook that is run before validation + * + * @param name + * @param fn A callback function that is called with instance, options + */ + beforeValidate( name : string, + fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + beforeValidate( fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after validation + * + * @param name + * @param fn A callback function that is called with instance, options + */ + afterValidate( name : string, + fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + afterValidate( fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run before creating a single instance + * + * @param name + * @param fn A callback function that is called with attributes, options + */ + beforeCreate( name : string, + fn : ( attributes : TInstance, options : Object, fn? : Function ) => void ): void; + beforeCreate( fn : ( attributes : TInstance, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after creating a single instance + * + * @param name + * @param fn A callback function that is called with attributes, options + */ + afterCreate( name : string, + fn : ( attributes : TInstance, options : Object, fn? : Function ) => void ): void; + afterCreate( fn : ( attributes : TInstance, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run before destroying a single instance + * + * @param name + * @param fn A callback function that is called with instance, options + * @alias beforeDelete + */ + beforeDestroy( name : string, + fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + beforeDestroy( fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + beforeDelete( name : string, + fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + beforeDelete( fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after destroying a single instance + * + * @param name + * @param fn A callback function that is called with instance, options + * @alias afterDelete + */ + afterDestroy( name : string, + fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + afterDestroy( fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + afterDelete( name : string, fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + afterDelete( fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run before updating a single instance + * + * @param name + * @param fn A callback function that is called with instance, options + */ + beforeUpdate( name : string, + fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + beforeUpdate( fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after updating a single instance + * + * @param name + * @param fn A callback function that is called with instance, options + */ + afterUpdate( name : string, fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + afterUpdate( fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run before creating instances in bulk + * + * @param name + * @param fn A callback function that is called with instances, options + */ + beforeBulkCreate( name : string, + fn : ( instances : Array, options : Object, fn? : Function ) => void ): void; + beforeBulkCreate( fn : ( instances : Array, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after creating instances in bulk + * + * @param name + * @param fn A callback function that is called with instances, options + * @name afterBulkCreate + */ + afterBulkCreate( name : string, + fn : ( instances : Array, options : Object, fn? : Function ) => void ): void; + afterBulkCreate( fn : ( instances : Array, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run before destroying instances in bulk + * + * @param name + * @param fn A callback function that is called with options + * + * @alias beforeBulkDelete + */ + beforeBulkDestroy( name : string, fn : ( options : Object, fn? : Function ) => void ): void; + beforeBulkDestroy( fn : ( options : Object, fn? : Function ) => void ): void; + beforeBulkDelete( name : string, fn : ( options : Object, fn? : Function ) => void ): void; + beforeBulkDelete( fn : ( options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after destroying instances in bulk + * + * @param name + * @param fn A callback function that is called with options + * + * @alias afterBulkDelete + */ + afterBulkDestroy( name : string, fn : ( options : Object, fn? : Function ) => void ): void; + afterBulkDestroy( fn : ( options : Object, fn? : Function ) => void ): void; + afterBulkDelete( name : string, fn : ( options : Object, fn? : Function ) => void ): void; + afterBulkDelete( fn : ( options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after updating instances in bulk + * + * @param name + * @param fn A callback function that is called with options + */ + beforeBulkUpdate( name : string, fn : ( options : Object, fn? : Function ) => void ): void; + beforeBulkUpdate( fn : ( options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after updating instances in bulk + * + * @param name + * @param fn A callback function that is called with options + */ + afterBulkUpdate( name : string, fn : ( options : Object, fn? : Function ) => void ): void; + afterBulkUpdate( fn : ( options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run before a find (select) query + * + * @param name + * @param fn A callback function that is called with options + */ + beforeFind( name : string, fn : ( options : Object, fn? : Function ) => void ): void; + beforeFind( fn : ( options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded + * + * @param name + * @param fn A callback function that is called with options + */ + beforeFindAfterExpandIncludeAll( name : string, + fn : ( options : Object, fn? : Function ) => void ): void; + beforeFindAfterExpandIncludeAll( fn : ( options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run before a find (select) query, after all option parsing is complete + * + * @param name + * @param fn A callback function that is called with options + */ + beforeFindAfterOptions( name : string, fn : ( options : Object, fn? : Function ) => void ): void; + beforeFindAfterOptions( fn : ( options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after a find (select) query + * + * @param name + * @param fn A callback function that is called with instance(s), options + */ + afterFind( name : string, + fn : ( instancesOrInstance : Array | TInstance, options : Object, + fn? : Function ) => void ): void; + afterFind( fn : ( instancesOrInstance : Array | TInstance, options : Object, + fn? : Function ) => void ): void; + + /** + * A hook that is run before a define call + * + * @param name + * @param fn A callback function that is called with attributes, options + */ + beforeDefine( name : string, fn : ( attributes : DefineAttributes, options : Object ) => void ): void; + beforeDefine( fn : ( attributes : DefineAttributes, options : Object ) => void ): void; + + /** + * A hook that is run after a define call + * + * @param name + * @param fn A callback function that is called with factory + */ + afterDefine( name : string, fn : ( model : Model ) => void ): void; + afterDefine( fn : ( model : Model ) => void ): void; + + /** + * A hook that is run before Sequelize() call + * + * @param name + * @param fn A callback function that is called with config, options + */ + beforeInit( name : string, fn : ( config : Object, options : Object ) => void ): void; + beforeInit( fn : ( config : Object, options : Object ) => void ): void; + + /** + * A hook that is run after Sequelize() call + * + * @param name + * @param fn A callback function that is called with sequelize + */ + afterInit( name : string, fn : ( sequelize : Sequelize ) => void ): void; + afterInit( fn : ( sequelize : Sequelize ) => void ): void; + + } + + // + // Instance + // ~~~~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/instance.js + // + + /** + * Options used for Instance.increment method + */ + interface InstanceIncrementDecrementOptions { + + /** + * The number to increment by + * + * Defaults to 1 + */ + by? : number; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + /** + * A hash of attributes to describe your search. See above for examples. + */ + where? : WhereOptions | Array; + + } + + /** + * Options used for Instance.restore method + */ + interface InstanceRestoreOptions { + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + } + + /** + * Options used for Instance.destroy method + */ + interface InstanceDestroyOptions { + + /** + * If set to true, paranoid models will actually be deleted + */ + force? : boolean; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + /** + * Transaction to run the query in + */ + transaction? : Transaction; + + } + + /** + * Options used for Instance.update method + */ + interface InstanceUpdateOptions extends InstanceSaveOptions, InstanceSetOptions { + + /** + * A hash of attributes to describe your search. See above for examples. + */ + where? : WhereOptions | Array; + + } + + /** + * Options used for Instance.set method + */ + interface InstanceSetOptions { + + /** + * If set to true, field and virtual setters will be ignored + */ + raw? : boolean; + + /** + * Clear all previously set data values + */ + reset? : boolean; + + } + + /** + * Options used for Instance.save method + */ + interface InstanceSaveOptions { + + /** + * An optional array of strings, representing database columns. If fields is provided, only those columns + * will be validated and saved. + */ + fields? : Array; + + /** + * If true, the updatedAt timestamp will not be updated. + * + * Defaults to false + */ + silent? : boolean; + + /** + * If false, validations won't be run. + * + * Defaults to true + */ + validate? : boolean; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + /** + * Transaction to run the query in + */ + transaction? : Transaction; + + } + + /** + * This class represents an single instance, a database row. You might see it referred to as both Instance and + * instance. You should not instantiate the Instance class directly, instead you access it using the finder and + * creation methods on the model. + * + * Instance instances operate with the concept of a `dataValues` property, which stores the actual values + * represented by the instance. By default, the values from dataValues can also be accessed directly from the + * Instance, that is: + * ```js + * instance.field + * // is the same as + * instance.get('field') + * // is the same as + * instance.getDataValue('field') + * ``` + * However, if getters and/or setters are defined for `field` they will be invoked, instead of returning the + * value from `dataValues`. Accessing properties directly or using `get` is preferred for regular use, + * `getDataValue` should only be used for custom getters. + * + * @see Sequelize.define for more information about getters and setters + */ + interface Instance { + + /** + * Returns true if this instance has not yet been persisted to the database + */ + isNewRecord : boolean; + + /** + * Returns the Model the instance was created from. + * + * @see Model + */ + Model : Model; + + /** + * A reference to the sequelize instance + */ + sequelize : Sequelize; + + /** + * Get an object representing the query for this instance, use with `options.where` + */ + where() : Object; + + /** + * Get the value of the underlying data value + */ + getDataValue( key : string ) : any; + + /** + * Update the underlying data value + */ + setDataValue( key : string, value : any ) : void; + + /** + * If no key is given, returns all values of the instance, also invoking virtual getters. + * + * If key is given and a field or virtual getter is present for the key it will call that getter - else it + * will return the value for key. + * + * @param options.plain If set to true, included instances will be returned as plain objects + */ + get( key : string, options? : { plain? : boolean, clone? : boolean } ) : any; + get( options? : { plain? : boolean, clone? : boolean } ) : Object; + + /** + * Set is used to update values on the instance (the sequelize representation of the instance that is, + * remember that nothing will be persisted before you actually call `save`). In its most basic form `set` + * will update a value stored in the underlying `dataValues` object. However, if a custom setter function + * is defined for the key, that function will be called instead. To bypass the setter, you can pass `raw: + * true` in the options object. + * + * If set is called with an object, it will loop over the object, and call set recursively for each key, + * value pair. If you set raw to true, the underlying dataValues will either be set directly to the object + * passed, or used to extend dataValues, if dataValues already contain values. + * + * When set is called, the previous value of the field is stored and sets a changed flag(see `changed`). + * + * Set can also be used to build instances for associations, if you have values for those. + * When using set with associations you need to make sure the property key matches the alias of the + * association while also making sure that the proper include options have been set (from .build() or + * .find()) + * + * If called with a dot.seperated key on a JSON/JSONB attribute it will set the value nested and flag the + * entire object as changed. + * + * @param options.raw If set to true, field and virtual setters will be ignored + * @param options.reset Clear all previously set data values + */ + set( key : string, value : any, options? : InstanceSetOptions ) : TInstance; + set( keys : Object, options? : InstanceSetOptions ) : TInstance; + setAttributes( key : string, value : any, options? : InstanceSetOptions ) : TInstance; + setAttributes( keys : Object, options? : InstanceSetOptions ) : TInstance; + + /** + * If changed is called with a string it will return a boolean indicating whether the value of that key in + * `dataValues` is different from the value in `_previousDataValues`. + * + * If changed is called without an argument, it will return an array of keys that have changed. + * + * If changed is called without an argument and no keys have changed, it will return `false`. + */ + changed( key : string ) : boolean; + changed() : boolean | Array; + + /** + * Returns the previous value for key from `_previousDataValues`. + */ + previous( key : string ) : any; + + /** + * Validate this instance, and if the validation passes, persist it to the database. + * + * On success, the callback will be called with this instance. On validation error, the callback will be + * called with an instance of `Sequelize.ValidationError`. This error will have a property for each of the + * fields for which validation failed, with the error message for that field. + */ + save( options? : InstanceSaveOptions ) : Promise; + + /** + * Refresh the current instance in-place, i.e. update the object with current data from the DB and return + * the same object. This is different from doing a `find(Instance.id)`, because that would create and + * return a new instance. With this method, all references to the Instance are updated with the new data + * and no new objects are created. + */ + reload( options? : FindOptions ) : Promise; + + /** + * Validate the attribute of this instance according to validation rules set in the model definition. + * + * Emits null if and only if validation successful; otherwise an Error instance containing + * { field name : [error msgs] } entries. + * + * @param options.skip An array of strings. All properties that are in this array will not be validated + */ + validate( options? : { skip?: Array } ) : Promise; + + /** + * This is the same as calling `set` and then calling `save`. + */ + update( key : string, value : any, options? : InstanceUpdateOptions ) : Promise; + update( keys : Object, options? : InstanceUpdateOptions ) : Promise; + updateAttributes( key : string, value : any, options? : InstanceUpdateOptions ) : Promise; + updateAttributes( keys : Object, options? : InstanceUpdateOptions ) : Promise; + + /** + * Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will + * either be completely deleted, or have its deletedAt timestamp set to the current time. + */ + destroy( options? : InstanceDestroyOptions ) : Promise; + + /** + * Restore the row corresponding to this instance. Only available for paranoid models. + */ + restore( options? : InstanceRestoreOptions ) : Promise; + + /** + * Increment the value of one or more columns. This is done in the database, which means it does not use + * the values currently stored on the Instance. The increment is done using a + * ```sql + * SET column = column + X + * ``` + * query. To get the correct value after an increment into the Instance you should do a reload. + * + *```js + * instance.increment('number') // increment number by 1 + * instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2 + * instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42, and tries by 1. + * // `by` is ignored, since each column has its own + * // value + * ``` + * + * @param fields If a string is provided, that column is incremented by the value of `by` given in options. + * If an array is provided, the same is true for each column. + * If and object is provided, each column is incremented by the value given. + */ + increment( fields : string | Array | Object, + options? : InstanceIncrementDecrementOptions ) : Promise; + + /** + * Decrement the value of one or more columns. This is done in the database, which means it does not use + * the values currently stored on the Instance. The decrement is done using a + * ```sql + * SET column = column - X + * ``` + * query. To get the correct value after an decrement into the Instance you should do a reload. + * + * ```js + * instance.decrement('number') // decrement number by 1 + * instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2 + * instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42, and tries by 1. + * // `by` is ignored, since each column has its own + * // value + * ``` + * + * @param fields If a string is provided, that column is decremented by the value of `by` given in options. + * If an array is provided, the same is true for each column. + * If and object is provided, each column is decremented by the value given + */ + decrement( fields : string | Array | Object, + options? : InstanceIncrementDecrementOptions ) : Promise; + + /** + * Check whether all values of this and `other` Instance are the same + */ + equals( other : Instance ) : boolean; + + /** + * Check if this is eqaul to one of `others` by calling equals + */ + equalsOneOf( others : Array> ) : boolean; + + /** + * Convert the instance to a JSON representation. Proxies to calling `get` with no keys. This means get all + * values gotten from the DB, and apply all custom getters. + */ + toJSON() : Object; + + } + + // + // Model + // ~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/model.js + // + + /** + * Options to pass to Model on drop + */ + interface DropOptions { + + /** + * Also drop all objects depending on this table, such as views. Only works in postgres + */ + cascade?: boolean; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging?: boolean | Function; + + } + + /** + * Schema Options provided for applying a schema to a model + */ + interface SchemaOptions { + + /** + * The character(s) that separates the schema name from the table name + */ + schemaDelimeter? : string, + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : Function | boolean + + } + + /** + * Scope Options for Model.scope + */ + interface ScopeOptions { + + /** + * The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments. + * To apply simple scopes and scope functions with no arguments, pass them as strings. For scope function, + * pass an object, with a `method` property. The value can either be a string, if the method does not take + * any arguments, or an array, where the first element is the name of the method, and consecutive elements + * are arguments to that method. Pass null to remove all scopes, including the default. + */ + method : string | Array; + + } + + /** + * Where Complex nested query + */ + interface WhereNested { + $and : Array; + $or : Array; + } + + /** + * Nested where Postgre Statement + */ + interface WherePGStatement { + $any : Array; + $all : Array; + } + + /** + * Where Geometry Options + */ + interface WhereGeometryOptions { + type: string; + coordinates: Array | number>; + } + + /** + * Logic of where statement + */ + interface WhereLogic { + $ne : string | number | WhereLogic; + $in : Array | literal; + $not : boolean | string | number | WhereOptions; + $notIn : Array | literal; + $gte : number | string | Date; + $gt : number | string | Date; + $lte : number | string | Date; + $lt : number | string | Date; + $like : string | WherePGStatement; + $iLike : string | WherePGStatement; + $ilike : string | WherePGStatement; + $notLike : string | WherePGStatement; + $notILike : string | WherePGStatement; + $between : [number, number]; + ".." : [number, number]; + $notBetween: [number, number]; + "!.." : [number, number]; + $overlap : [number, number]; + "&&" : [number, number]; + $contains: any; + "@>": any; + $contained: any; + "<@": any; + } + + /** + * A hash of attributes to describe your search. See above for examples. + * + * We did put Object in the end, because there where query might be a JSON Blob. It cripples a bit the + * typesafety, but there is no way to pass the tests if we just remove it. + */ + interface WhereOptions { + [field: string]: string | number | WhereLogic | WhereOptions | col | and | or | WhereGeometryOptions | Array | Object; + } + + /** + * Through options for Include Options + */ + interface IncludeThroughOptions { + + /** + * Filter on the join model for belongsToMany relations + */ + where? : WhereOptions; + + /** + * A list of attributes to select from the join model for belongsToMany relations + */ + attributes? : Array; + + } + + /** + * Association Object for Include Options + */ + interface IncludeAssociation { + source: Model; + target: Model; + identifier: string; + } + + /** + * Complex include options + */ + interface IncludeOptions { + + /** + * The model you want to eagerly load + */ + model? : Model; + + /** + * The alias of the relation, in case the model you want to eagerly load is aliassed. For `hasOne` / + * `belongsTo`, this should be the singular name, and for `hasMany`, it should be the plural + */ + as? : string; + + /** + * The association you want to eagerly load. (This can be used instead of providing a model/as pair) + */ + association? : IncludeAssociation; + + /** + * Where clauses to apply to the child models. Note that this converts the eager load to an inner join, + * unless you explicitly set `required: false` + */ + where? : WhereOptions; + + /** + * A list of attributes to select from the child model + */ + attributes? : Array; + + /** + * If true, converts to an inner join, which means that the parent model will only be loaded if it has any + * matching children. True if `include.where` is set, false otherwise. + */ + required? : boolean; + + /** + * Through Options + */ + through? : IncludeThroughOptions; + + /** + * Load further nested related models + */ + include? : Array | IncludeOptions>; + + } + + /** + * Options that are passed to any model creating a SELECT query + * + * A hash of options to describe the scope of the search + */ + interface FindOptions { + + /** + * A hash of attributes to describe your search. See above for examples. + */ + where? : WhereOptions | Array; + + /** + * A list of the attributes that you want to select. To rename an attribute, you can pass an array, with + * two elements - the first is the name of the attribute in the DB (or some kind of expression such as + * `Sequelize.literal`, `Sequelize.fn` and so on), and the second is the name you want the attribute to + * have in the returned instance + */ + attributes? : Array; + + /** + * If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will + * be returned. Only applies if `options.paranoid` is true for the model. + */ + paranoid?: boolean; + + /** + * A list of associations to eagerly load using a left join. Supported is either + * `{ include: [ Model1, Model2, ...]}` or `{ include: [{ model: Model1, as: 'Alias' }]}`. + * If your association are set up with an `as` (eg. `X.hasMany(Y, { as: 'Z }`, you need to specify Z in + * the as attribute when eager loading Y). + */ + include?: Array | IncludeOptions>; + + /** + * Specifies an ordering. If a string is provided, it will be escaped. Using an array, you can provide + * several columns / functions to order by. Each element can be further wrapped in a two-element array. The + * first element is the column / function to order by, the second is the direction. For example: + * `order: [['name', 'DESC']]`. In this way the column will be escaped, but the direction will not. + */ + order?: string | col | literal | Array | { model : Model, as? : string}> | Array | { model : Model, as? : string}>>; + + /** + * Limit the results + */ + limit?: number; + + /** + * Skip the results; + */ + offset?: number; + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + /** + * Lock the selected rows. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE. + * Postgres also supports transaction.LOCK.KEY_SHARE, transaction.LOCK.NO_KEY_UPDATE and specific model + * locks with joins. See [transaction.LOCK for an example](transaction#lock) + */ + lock? : string | { level: string, of: Model }; + + /** + * Return raw result. See sequelize.query for more information. + */ + raw? : boolean; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + /** + * having ?!? + */ + having? : WhereOptions; + + } + + /** + * Options for Model.count method + */ + interface CountOptions { + + /** + * A hash of search attributes. + */ + where? : WhereOptions | Array; + + /** + * Include options. See `find` for details + */ + include?: Array | IncludeOptions>; + + /** + * Apply COUNT(DISTINCT(col)) + */ + distinct? : boolean; + + /** + * Used in conjustion with `group` + */ + attributes? : Array; + + /** + * For creating complex counts. Will return multiple rows as needed. + * + * TODO: Check? + */ + group? : Object; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + } + + /** + * Options for Model.build method + */ + interface BuildOptions { + + /** + * If set to true, values will ignore field and virtual setters. + */ + raw? : boolean; + + /** + * Is this record new + */ + isNewRecord? : boolean; + + /** + * an array of include options - Used to build prefetched/included model instances. See `set` + * + * TODO: See set + */ + include? : Array | IncludeOptions>; + + } + + /** + * Options for Model.create method + */ + interface CreateOptions extends BuildOptions { + + /** + * If set, only columns matching those in fields will be saved + */ + fields? : Array; + + /** + * On Duplicate + */ + onDuplicate? : string; + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + } + + /** + * Options for Model.findOrInitialize method + */ + interface FindOrInitializeOptions { + + /** + * A hash of search attributes. + */ + where : string | WhereOptions; + + /** + * Default values to use if building a new instance + */ + defaults? : TAttributes; + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + } + + /** + * Options for Model.upsert method + */ + interface UpsertOptions { + + /** + * Run validations before the row is inserted + */ + validate? : boolean; + + /** + * The fields to insert / update. Defaults to all fields + */ + fields? : Array; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + } + + /** + * Options for Model.bulkCreate method + */ + interface BulkCreateOptions { + + /** + * Fields to insert (defaults to all fields) + */ + fields? : Array; + + /** + * Should each row be subject to validation before it is inserted. The whole insert will fail if one row + * fails validation + */ + validate? : boolean; + + /** + * Run before / after bulk create hooks? + */ + hooks? : boolean; + + /** + * Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run if + * options.hooks is true. + */ + individualHooks? : boolean; + + /** + * Ignore duplicate values for primary keys? (not supported by postgres) + * + * Defaults to false + */ + ignoreDuplicates? : boolean; + + /** + * Fields to update if row key already exists (on duplicate key update)? (only supported by mysql & + * mariadb). By default, all fields are updated. + */ + updateOnDuplicate? : Array; + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + } + + /** + * The options passed to Model.destroy in addition to truncate + */ + interface TruncateOptions { + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + /** + * Only used in conjuction with TRUNCATE. Truncates all tables that have foreign-key references to the + * named table, or to any tables added to the group due to CASCADE. + * + * Defaults to false; + */ + cascade? : boolean; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + } + + /** + * Options used for Model.destroy + */ + interface DestroyOptions extends TruncateOptions { + + /** + * Filter the destroy + */ + where? : WhereOptions; + + /** + * Run before / after bulk destroy hooks? + */ + hooks? : boolean; + + /** + * If set to true, destroy will SELECT all records matching the where parameter and will execute before / + * after destroy hooks on each row + */ + individualHooks? : boolean; + + /** + * How many rows to delete + */ + limit? : number; + + /** + * Delete instead of setting deletedAt to current timestamp (only applicable if `paranoid` is enabled) + */ + force? : boolean; + + /** + * If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is + * truncated the where and limit options are ignored + */ + truncate? : boolean; + + } + + /** + * Options for Model.restore + */ + interface RestoreOptions { + + /** + * Filter the restore + */ + where? : WhereOptions; + + /** + * Run before / after bulk restore hooks? + */ + hooks? : boolean; + + /** + * If set to true, restore will find all records within the where parameter and will execute before / after + * bulkRestore hooks on each row + */ + individualHooks? : boolean; + + /** + * How many rows to undelete + */ + limit? : number; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + } + + /** + * Options used for Model.update + */ + interface UpdateOptions { + + /** + * Options to describe the scope of the search. + */ + where: WhereOptions; + + /** + * Fields to update (defaults to all fields) + */ + fields? : Array; + + /** + * Should each row be subject to validation before it is inserted. The whole insert will fail if one row + * fails validation. + * + * Defaults to true + */ + validate? : boolean; + + /** + * Run before / after bulk update hooks? + * + * Defaults to true + */ + hooks? : boolean; + + /** + * Whether or not to update the side effects of any virtual setters. + * + * Defaults to true + */ + sideEffects? : boolean; + + /** + * Run before / after update hooks?. If true, this will execute a SELECT followed by individual UPDATEs. + * A select is needed, because the row data needs to be passed to the hooks + * + * Defaults to false + */ + individualHooks? : boolean; + + /** + * Return the affected rows (only for postgres) + */ + returning? : boolean; + + /** + * How many rows to update (only for mysql and mariadb) + */ + limit? : number; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + } + + /** + * Options used for Model.aggregate + */ + interface AggregateOptions extends QueryOptions { + + /** + * A hash of search attributes. + */ + where?: WhereOptions; + + /** + * The type of the result. If `field` is a field in this Model, the default will be the type of that field, + * otherwise defaults to float. + */ + dataType? : DataTypeAbstract | string; + + /** + * Applies DISTINCT to the field being aggregated over + */ + distinct? : boolean; + + } + + /** + * A Model represents a table in the database. Sometimes you might also see it referred to as model, or simply + * as factory. This class should _not_ be instantiated directly, it is created using `sequelize.define`, and + * already created models can be loaded using `sequelize.import` + */ + interface Model extends Hooks, Associations { + + /** + * The Instance class + */ + Instance() : Instance; + + /** + * Remove attribute from model definition + * + * @param attribute + */ + removeAttribute( attribute : string ) : void; + + /** + * Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the + * model instance (this) + */ + sync( options? : SyncOptions ) : Promise>; + + /** + * Drop the table represented by this Model * - * @param emitterOrKlass - * @param method - * @param params * @param options */ - add(emitterOrKlass: any, method?: string, params?: any, options?: any): QueryChainer; + drop( options? : DropOptions ) : Promise; /** - * Run the query chainer. In reality, this means, wait for all the added emitters to finish, since the queries - * began executing as soon as you invoked their methods. - */ - run(): EventEmitter; - - /** - * Run the chainer serially, so that each query waits for the previous one to finish before it starts. + * Apply a schema to this model. For postgres, this will actually place the schema in front of the table + * name + * - `"schema"."tableName"`, while the schema will be prepended to the table name for mysql and + * sqlite - `'schema.tablename'`. * - * @param options @see QueryChainerRunSeriallyOptions + * @param schema The name of the schema + * @param options */ - runSerially(options?: QueryChainerRunSeriallyOptions): EventEmitter; + schema( schema : string, options? : SchemaOptions ) : Model; + + /** + * Get the tablename of the model, taking schema into account. The method will return The name as a string + * if the model has no schema, or an object with `tableName`, `schema` and `delimiter` properties. + * + * @param options The hash of options from any query. You can use one model to access tables with matching + * schemas by overriding `getTableName` and using custom key/values to alter the name of the table. + * (eg. + * subscribers_1, subscribers_2) + * @param options.logging=false A function that gets executed while running the query to log the sql. + */ + getTableName( options? : { logging : Function } ) : string | Object; + + /** + * Apply a scope created in `define` to the model. First let's look at how to create scopes: + * ```js + * var Model = sequelize.define('model', attributes, { + * defaultScope: { + * where: { + * username: 'dan' + * }, + * limit: 12 + * }, + * scopes: { + * isALie: { + * where: { + * stuff: 'cake' + * } + * }, + * complexFunction: function(email, accessLevel) { + * return { + * where: { + * email: { + * $like: email + * }, + * accesss_level { + * $gte: accessLevel + * } + * } + * } + * } + * } + * }) + * ``` + * Now, since you defined a default scope, every time you do Model.find, the default scope is appended to + * your query. Here's a couple of examples: + * ```js + * Model.findAll() // WHERE username = 'dan' + * Model.findAll({ where: { age: { gt: 12 } } }) // WHERE age > 12 AND username = 'dan' + * ``` + * + * To invoke scope functions you can do: + * ```js + * Model.scope({ method: ['complexFunction' 'dan@sequelize.com', 42]}).findAll() + * // WHERE email like 'dan@sequelize.com%' AND access_level >= 42 + * ``` + * + * @return Model A reference to the model, with the scope(s) applied. Calling scope again on the returned + * model will clear the previous scope. + */ + scope( options? : string | Array | ScopeOptions | WhereOptions ) : Model; + + /** + * Search for multiple instances. + * + * __Simple search using AND and =__ + * ```js + * Model.findAll({ + * where: { + * attr1: 42, + * attr2: 'cake' + * } + * }) + * ``` + * ```sql + * WHERE attr1 = 42 AND attr2 = 'cake' + *``` + * + * __Using greater than, less than etc.__ + * ```js + * + * Model.findAll({ + * where: { + * attr1: { + * gt: 50 + * }, + * attr2: { + * lte: 45 + * }, + * attr3: { + * in: [1,2,3] + * }, + * attr4: { + * ne: 5 + * } + * } + * }) + * ``` + * ```sql + * WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5 + * ``` + * Possible options are: `$ne, $in, $not, $notIn, $gte, $gt, $lte, $lt, $like, $ilike/$iLike, $notLike, + * $notILike, '..'/$between, '!..'/$notBetween, '&&'/$overlap, '@>'/$contains, '<@'/$contained` + * + * __Queries using OR__ + * ```js + * Model.findAll({ + * where: Sequelize.and( + * { name: 'a project' }, + * Sequelize.or( + * { id: [1,2,3] }, + * { id: { gt: 10 } } + * ) + * ) + * }) + * ``` + * ```sql + * WHERE name = 'a project' AND (id` IN (1,2,3) OR id > 10) + * ``` + * + * The success listener is called with an array of instances if the query succeeds. + * + * @see {Sequelize#query} + */ + findAll( options? : FindOptions ) : Promise>; + all( optionz? : FindOptions ) : Promise>; + + /** + * Search for a single instance by its primary key. This applies LIMIT 1, so the listener will + * always be called with a single instance. + */ + findById( identifier? : number | string, options? : FindOptions ) : Promise; + findByPrimary( identifier? : number | string, options? : FindOptions ) : Promise; + + /** + * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single + * instance. + */ + findOne( options? : FindOptions ) : Promise; + find( optionz? : FindOptions ) : Promise; + + /** + * Run an aggregation method on the specified field + * + * @param field The field to aggregate over. Can be a field name or * + * @param aggregateFunction The function to use for aggregation, e.g. sum, max etc. + * @param options Query options. See sequelize.query for full options + * @return Returns the aggregate result cast to `options.dataType`, unless `options.plain` is false, in + * which case the complete data result is returned. + */ + aggregate( field : string, aggregateFunction : Function, options? : AggregateOptions ) : Promise; + + /** + * Count the number of records matching the provided where clause. + * + * If you provide an `include` option, the number of matching associations will be counted instead. + */ + count( options? : CountOptions ) : Promise; + + /** + * Find all the rows matching your query, within a specified offset / limit, and get the total number of + * rows matching your query. This is very usefull for paging + * + * ```js + * Model.findAndCountAll({ + * where: ..., + * limit: 12, + * offset: 12 + * }).then(function (result) { + * ... + * }) + * ``` + * In the above example, `result.rows` will contain rows 13 through 24, while `result.count` will return + * the + * total number of rows that matched your query. + * + * When you add includes, only those which are required (either because they have a where clause, or + * because + * `required` is explicitly set to true on the include) will be added to the count part. + * + * Suppose you want to find all users who have a profile attached: + * ```js + * User.findAndCountAll({ + * include: [ + * { model: Profile, required: true} + * ], + * limit 3 + * }); + * ``` + * Because the include for `Profile` has `required` set it will result in an inner join, and only the users + * who have a profile will be counted. If we remove `required` from the include, both users with and + * without + * profiles will be counted + */ + findAndCount( options? : FindOptions ) : Promise<{ rows : Array, count : number }>; + findAndCountAll( options? : FindOptions ) : Promise<{ rows : Array, count : number }>; + + /** + * Find the maximum value of field + */ + max( field : string, options? : AggregateOptions ) : Promise; + + /** + * Find the minimum value of field + */ + min( field : string, options? : AggregateOptions ) : Promise; + + /** + * Find the sum of field + */ + sum( field : string, options? : AggregateOptions ) : Promise; + + /** + * Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty. + */ + build( record? : TAttributes, options? : BuildOptions ) : TInstance; + + /** + * Undocumented bulkBuild + */ + bulkBuild( records : Array, options? : BuildOptions ) : Array; + + /** + * Builds a new model instance and calls save on it. + */ + create( values? : TAttributes, options? : CreateOptions ) : Promise; + + /** + * Find a row that matches the query, or build (but don't save) the row if none is found. + * The successfull result of the promise will be (instance, initialized) - Make sure to use .spread() + */ + findOrInitialize( options : FindOrInitializeOptions ) : Promise; + findOrBuild( options : FindOrInitializeOptions ) : Promise; + + /** + * Find a row that matches the query, or build and save the row if none is found + * The successful result of the promise will be (instance, created) - Make sure to use .spread() + * + * If no transaction is passed in the `options` object, a new transaction will be created internally, to + * prevent the race condition where a matching row is created by another connection after the find but + * before the insert call. However, it is not always possible to handle this case in SQLite, specifically + * if one transaction inserts and another tries to select before the first one has comitted. In this case, + * an instance of sequelize.TimeoutError will be thrown instead. If a transaction is created, a savepoint + * will be created instead, and any unique constraint violation will be handled internally. + */ + findOrCreate( options : FindOrInitializeOptions ) : Promise; + + /** + * Insert or update a single row. An update will be executed if a row which matches the supplied values on + * either the primary key or a unique key is found. Note that the unique index must be defined in your + * sequelize model and not just in the table. Otherwise you may experience a unique constraint violation, + * because sequelize fails to identify the row that should be updated. + * + * **Implementation details:** + * + * * MySQL - Implemented as a single query `INSERT values ON DUPLICATE KEY UPDATE values` + * * PostgreSQL - Implemented as a temporary function with exception handling: INSERT EXCEPTION WHEN + * unique_constraint UPDATE + * * SQLite - Implemented as two queries `INSERT; UPDATE`. This means that the update is executed + * regardless + * of whether the row already existed or not + * + * **Note** that SQLite returns undefined for created, no matter if the row was created or updated. This is + * because SQLite always runs INSERT OR IGNORE + UPDATE, in a single query, so there is no way to know + * whether the row was inserted or not. + */ + upsert( values : TAttributes, options? : UpsertOptions ) : Promise; + insertOrUpdate( values : TAttributes, options? : UpsertOptions ) : Promise; + + /** + * Create and insert multiple instances in bulk. + * + * The success handler is passed an array of instances, but please notice that these may not completely + * represent the state of the rows in the DB. This is because MySQL and SQLite do not make it easy to + * obtain + * back automatically generated IDs and other default values in a way that can be mapped to multiple + * records. To obtain Instances for the newly created values, you will need to query for them again. + * + * @param records List of objects (key/value pairs) to create instances from + */ + bulkCreate( records : Array, options? : BulkCreateOptions ) : Promise>; + + /** + * Truncate all instances of the model. This is a convenient method for Model.destroy({ truncate: true }). + */ + truncate( options? : TruncateOptions ) : Promise; + + /** + * Delete multiple instances, or set their deletedAt timestamp to the current time if `paranoid` is enabled. + * + * @return Promise The number of destroyed rows + */ + destroy( options? : DestroyOptions ) : Promise; + + /** + * Restore multiple instances if `paranoid` is enabled. + */ + restore( options? : RestoreOptions ) : Promise; + + /** + * Update multiple instances that match the where options. The promise returns an array with one or two + * elements. The first element is always the number of affected rows, while the second element is the actual + * affected rows (only supported in postgres with `options.returning` true.) + */ + update( values : TAttributes, options : UpdateOptions ) : Promise<[number, Array]>; + + /** + * Run a describe query on the table. The result will be return to the listener as a hash of attributes and + * their types. + */ + describe() : Promise; + + /** + * Unscope the model + */ + unscoped() : Model; + } + // + // Query Interface + // ~~~~~~~~~~~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/query-interface.js + // + + /** + * 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. + */ + interface QueryInterfaceOptions { + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + } + + /** + * 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. + */ interface 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. */ - QueryGenerator: QueryGenerator; + QueryGenerator: any; /** * Queries the schema (table list). * * @param schema The schema to query. Applies only to Postgres. */ - createSchema(schema?: string): EventEmitter; + createSchema( schema? : string, options? : QueryInterfaceOptions ): Promise; /** * Drops the specified schema (table). * - * @param schema The name of the table to drop. + * @param schema The schema to query. Applies only to Postgres. */ - dropSchema(schema: string): EventEmitter; + dropSchema( schema? : string, options? : QueryInterfaceOptions ): Promise; /** * Drops all tables. */ - dropAllSchemas(): EventEmitter; + dropAllSchemas( options? : QueryInterfaceOptions ): Promise; /** * Queries all table names in the database. * * @param options */ - showAllSchemas(options?: QueryOptions): EventEmitter; + showAllSchemas( options? : QueryOptions ): Promise; + + /** + * Return database version + */ + databaseVersion( options? : QueryInterfaceOptions ) : Promise; /** * 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 Query options. - * - * @return The return type will be a Promise when dialect is Postgres and an EventEmitter for MySQL and SQLite. */ - createTable(tableName: string, attributes: any, options?: QueryOptions): any; + createTable( tableName : string | { schema? : string, tableName? : string }, attributes : DefineAttributes, + options? : QueryOptions ): Promise; /** * Drops the specified table. @@ -1019,562 +2823,793 @@ declare module "sequelize" * @param tableName Table name. * @param options Query options, particularly "force". */ - dropTable(tableName: string, options?: QueryOptions): EventEmitter; - dropAllTables(options?: QueryOptions): EventEmitter; - dropAllEnums(options?: QueryOptions): EventEmitter; - renameTable(before: string, after: string): EventEmitter; - showAllTables(options?: QueryOptions): EventEmitter; - describeTable(tableName: string, options?: QueryOptions): EventEmitter; - addColumn(tableName: string, attributeName: any, dataTypeOrOptions?: any): EventEmitter; - removeColumn(tableName: string, attributeName: string): EventEmitter; - changeColumn(tableName: string, attributeName: string, dataTypeOrOptions: any): EventEmitter; - renameColumn(tableName: string, attrNameBefore: string, attrNameAfter: string): EventEmitter; - addIndex(tableName: string, attributes: Array, options?: QueryOptions): EventEmitter; - showIndex(tableName: string, options?: QueryOptions): EventEmitter; - getForeignKeysForTables(tableNames: Array): EventEmitter; - removeIndex(tableName: string, attributes: Array): EventEmitter; - removeIndex(tableName: string, indexName: string): EventEmitter; - insert(dao: TModel, tableName: string, values: any, options?: QueryOptions): EventEmitter; - /** - * Inserts several records into the specified table. - * @param tableName Table to insert into. - * @param records Array of key/value pairs to insert as records. - * @param options Query options - * @param attributes For Postgres only, used to identify if an attribute is auto-increment and thus handled specially. - */ - bulkInsert(tableName: string, records: Array, options?: QueryOptions, attributes?: any): EventEmitter; + dropTable( tableName : string, options? : QueryOptions ): Promise; - update(dao: TModel, tableName: string, values: Array, where: any, options?: QueryOptions): EventEmitter; - bulkUpdate(tableName: string, values: Array, where: any, options?: QueryOptions, attributes?: any): EventEmitter; - delete(dao: TModel, tableName: string, where: any, options?: QueryOptions): EventEmitter; - bulkDelete(tableName: string, where: any, options?: QueryOptions): EventEmitter; - bulkDelete(tableName: string, where: any, options: QueryOptions, model: TModel): EventEmitter; - select(factory: TModel, tableName: string, scope?: any, queryOptions?: QueryOptions): EventEmitter; - increment(dao: TModel, tableName: string, values: Array, where: any, options?: QueryOptions): EventEmitter; - rawSelect(tableName: string, options: QueryOptions, attributeSelector: string, model: TModel): EventEmitter; /** - * Postgres only. Creates a trigger on specified table to call the specified function with supplied parameters. + * Drops all tables. * - * @param tableName - * @param triggerName - * @param timingType - * @param fireOnArray - * @param functionName - * @param functionParams - * @param optionsArray + * @param options */ - createTrigger(tableName: string, triggerName: string, timingType: string, fireOnArray: Array, functionName: string, functionParams: Array, optionsArray: Array): EventEmitter; + dropAllTables( options? : QueryOptions ): Promise; + + /** + * Drops all defined enums + * + * @param options + */ + dropAllEnums( options? : QueryOptions ): Promise; + + /** + * Renames a table + */ + renameTable( before : string, after : string, options? : QueryInterfaceOptions ) : Promise; + + /** + * Returns all tables + */ + showAllTables( options? : QueryOptions ) : Promise>; + + /** + * Describe a table + */ + describeTable( tableName : string | { schema? : string, tableName? : string }, + options? : string | { schema? : string, schemaDelimeter? : string, logging? : boolean | Function } ) : Promise; + + /** + * Adds a new column to a table + */ + addColumn( table : string, key : string, attribute : DefineAttributeColumnOptions | DataTypeAbstract, + options? : QueryInterfaceOptions ) : Promise; + + /** + * Removes a column from a table + */ + removeColumn( table : string, attribute : string, options? : QueryInterfaceOptions ) : Promise; + + /** + * Changes a column + */ + changeColumn( tableName : string | { schema? : string, tableName? : string }, attributeName : string, + dataTypeOrOptions? : string | DataTypeAbstract | DefineAttributeColumnOptions, + options? : QueryInterfaceOptions ) : Promise; + + /** + * Renames a column + */ + renameColumn( tableName : string | { schema? : string, tableName? : string }, attrNameBefore : string, + attrNameAfter : string, + options? : QueryInterfaceOptions ) : Promise; + + /** + * Adds a new index to a table + */ + addIndex( tableName : string | Object, attributes : Array, options? : QueryOptions, + rawTablename? : string ) : Promise; + + /** + * Shows the index of a table + */ + showIndex( tableName : string | Object, options? : QueryOptions ) : Promise; + + /** + * Put a name to an index + */ + nameIndexes( indexes : Array, rawTablename : string ) : Promise; + + /** + * Returns all foreign key constraints of a table + */ + getForeignKeysForTables( tableNames : string, options? : QueryInterfaceOptions ) : Promise; + + /** + * Removes an index of a table + */ + removeIndex( tableName : string, indexNameOrAttributes : Array | string, + options? : QueryInterfaceOptions ) : Promise; + + /** + * Inserts a new record + */ + insert( instance : Instance, tableName : string, values : Object, + options? : QueryOptions ) : Promise; + + /** + * Inserts or Updates a record in the database + */ + upsert( tableName : string, values : Object, updateValues : Object, model : Model, + options? : QueryOptions ) : Promise; + + /** + * Inserts multiple records at once + */ + bulkInsert( tableName : string, records : Array, options? : QueryOptions, + attributes? : Array | string ) : Promise; + + /** + * Updates a row + */ + update( instance : Instance, tableName : string, values : Object, identifier : Object, + options? : QueryOptions ) : Promise; + + /** + * Updates multiple rows at once + */ + bulkUpdate( tableName : string, values : Object, identifier : Object, options? : QueryOptions, + attributes? : Array | string ) : Promise; + + /** + * Deletes a row + */ + "delete"( instance : Instance, tableName : string, identifier : Object, + options? : QueryOptions ) : Promise; + + /** + * Deletes multiple rows at once + */ + bulkDelete( tableName : string, identifier : Object, options? : QueryOptions, + model? : Model ) : Promise; + + /** + * Returns selected rows + */ + select( model : Model, tableName : string, options? : QueryOptions ) : Promise>; + + /** + * Increments a row value + */ + increment( instance : Instance, tableName : string, values : Object, identifier : Object, + options? : QueryOptions ) : Promise; + + /** + * Selects raw without parsing the string into an object + */ + rawSelect( tableName : string, options : QueryOptions, attributeSelector : string | Array, + model? : Model ) : Promise>; + + /** + * Postgres only. Creates a trigger on specified table to call the specified function with supplied + * parameters. + */ + createTrigger( tableName : string, triggerName : string, timingType : string, fireOnArray : Array, + functionName : string, functionParams : Array, optionsArray : Array, + options? : QueryInterfaceOptions ): Promise; + /** * Postgres only. Drops the specified trigger. - * - * @param tableName - * @param triggerName */ - dropTrigger(tableName: string, triggerName: string): EventEmitter; - renameTrigger(tableName: string, oldTriggerName: string, newTriggerName: string): EventEmitter; - createFunction(functionName: string, params: Array, returnType: string, language: string, body: string, options?: QueryOptions): EventEmitter; - dropFunction(functionName: string, params: Array): EventEmitter; - renameFunction(oldFunctionName: string, params: Array, newFunctionName: string): EventEmitter; + dropTrigger( tableName : string, triggerName : string, options? : QueryInterfaceOptions ): Promise; + /** - * Escape an identifier (e.g. a table or attribute name). If force is true, - * the identifier will be quoted even if the `quoteIdentifiers` option is - * false. + * Postgres only. Renames a trigger */ - quoteIdentifier(identifier: string, force: boolean): EventEmitter; - quoteTable(tableName: string): EventEmitter; - quoteIdentifiers(identifiers: string, force: boolean): EventEmitter; - escape(value: string): EventEmitter; - setAutocommit(transaction: Transaction, value: boolean): EventEmitter; - setIsolationLevel(transaction: Transaction, value: string): EventEmitter; - startTransaction(transaction: Transaction, options?: QueryOptions): EventEmitter; - commitTransaction(transaction: Transaction, options?: QueryOptions): EventEmitter; - rollbackTransaction(transaction: Transaction, options?: QueryOptions): EventEmitter; + renameTrigger( tableName : string, oldTriggerName : string, newTriggerName : string, + options? : QueryInterfaceOptions ) : Promise; + + /** + * Postgres only. Create a function + */ + createFunction( functionName : string, params : Array, returnType : string, language : string, + body : string, options? : QueryOptions ) : Promise; + + /** + * Postgres only. Drops a function + */ + dropFunction( functionName : string, params : Array, + options? : QueryInterfaceOptions ) : Promise; + + /** + * Postgres only. Rename a function + */ + renameFunction( oldFunctionName : string, params : Array, newFunctionName : string, + options? : QueryInterfaceOptions ) : Promise; + + /** + * Escape an identifier (e.g. a table or attribute name). If force is true, the identifier will be quoted + * even if the `quoteIdentifiers` option is false. + */ + quoteIdentifier( identifier : string, force : boolean ) : string; + + /** + * Escape a table name + */ + quoteTable( identifier : string ) : string; + + /** + * Split an identifier into .-separated tokens and quote each part. If force is true, the identifier will be + * quoted even if the `quoteIdentifiers` option is false. + */ + quoteIdentifiers( identifiers : string, force : boolean ) : string; + + /** + * Escape a value (e.g. a string, number or date) + */ + escape( value? : string | number | Date ) : string; + + /** + * Set option for autocommit of a transaction + */ + setAutocommit( transaction : Transaction, value : boolean, options? : QueryOptions ) : Promise; + + /** + * Set the isolation level of a transaction + */ + setIsolationLevel( transaction : Transaction, value : string, options? : QueryOptions ) : Promise; + + /** + * Begin a new transaction + */ + startTransaction( transaction : Transaction, options? : QueryOptions ) : Promise; + + /** + * Defer constraints + */ + deferConstraints( transaction : Transaction, options? : QueryOptions ) : Promise; + + /** + * Commit an already started transaction + */ + commitTransaction( transaction : Transaction, options? : QueryOptions ) : Promise; + + /** + * Rollback ( revert ) a transaction that has'nt been commited + */ + rollbackTransaction( transaction : Transaction, options? : QueryOptions ) : Promise; + } - interface QueryGenerator { - createSchema(schemaName: string): string; - dropSchema(schemaName: string): string; - showSchemasQuery(): string; - addSchema(param: Model): Schema; - createTableQuery(tableName: string, attributes: Array, options?: CreateTableQueryOptions): string; - describeTableQuery(tableName: string, schema: string, schemaDelimiter: string): string; - dropTableQuery(tableName: string, options?: { cascade: string }): string; - renameTableQuery(before: string, after: string): string; - showTablesQuery(): string; - addColumnQuery(tableName: string, attributes: any): string; - removeColumnQuery(tableName: string, attributeName: string): string; - changeColumnQuery(tableName: string, attributes: any): string; - renameColumnQuery(tableName: string, attrNameBefore: string, attrNameAfter: string): string; - insertQuery(table: string, valueHash: any, modelAttributes: any): string; - bulkInsertQuery(tableName: string, attrValueHashes: any): string; - updateQuery(tableName: string, attrValueHash: any, where: any, options: InsertOptions, attributes: any): string; - deleteQuery(tableName: string, where: any, options: DestroyOptions): string; - deleteQuery(tableName: string, where: any, options: DestroyOptions, model: Model): string; - /** - * Creates a query to increment a value. Note "options" here is an additional hash of values to update. - * - * @param tableName - * @param attrValueHash - * @param where - * @param options - */ - incrementQuery(tableName: string, attrValueHash: any, where: any, options?: any): string; - addIndexQuery(tableName: string, attributes: Array, options?: IndexOptions): string; - /** - * Return indices for a table. Not options may be passed but is not used, so can be anything. - * @param tableName - * @param options - */ - showIndexQuery(tableName: string, options?: any): string; // options is actually not used - removeIndexQuery(tableName: string, indexNameOrAttributes: string): string; - removeIndexQuery(tableName: string, indexNameOrAttributes: Array): string; - attributesToSQL(attributes: Array): string; - findAutoIncrementField(factory: Model): Array; - quoteTable(param: any, as: boolean): string; - quote(obj: any, parent: any, force: boolean): string; - createTrigger(tableName: string, triggerName: string, timingType: string, fireOnArray: TriggerOptions, functionName: string, functionParams: Array): string; - dropTrigger(tableName: string, triggerName: string): string; - renameTrigger(tableName: string, oldTriggerName: string, newTriggerName: string): string; - createFunction(functionName: string, params: Array, returnType: string, language: string, body: string, options?: Array): string; - dropFunction(functionName: string, params: Array): string; - renameFunction(oldFunctionName: string, params: Array, newFunctionName: string): string; - quoteIdentifier(identifier: string, force?: boolean): string; - quoteIdentifiers(identifiers: string, force?: boolean): string; - /** - * Not documented, and reading through the code, I'm not sure what all the options available are for value/field. - * - * @param value - * @param field - */ - escape(value: any, field: any): string; - getForeignKeysQuery(tableName: string, schemaName: string): string; - dropForeignKeyQuery(tableName: string, foreignKey: string): string; - selectQuery(tableName: string, options: SelectOptions, model?: Model): string; - selectQuery(tableName: Array, options: SelectOptions, model?: Model): string; - selectQuery(tableName: Array>, options: SelectOptions, model?: Model): string; - setAutocommitQuery(value: boolean): string; - setIsolationLevelQuery(value: string): string; - /** - * Returns start transaction query. Options is not used. - * @param options - */ - startTransactionQuery(options?: any): string; - /** - * Returns start transaction query. Options is not used. - * @param options - */ - commitTransactionQuery(options?: any): string; - /** - * Returns start transaction query. Options is not used. - * @param options - */ - rollbackTransactionQuery(options?: any): string; - addLimitAndOffset(options: SelectOptions, query?: string): string; - getWhereConditions(smth: any, tableName: string, factory: Model, options?: any, prepend?: boolean): string; - prependTableNameToHash(tableName: string, hash?: any): string; - findAssociation(attribute: string, dao: Model): string; - getAssociationFilterDAO(filterStr: string, dao: Model): string; - isAssociationFilter(filterStr: string, dao: Model, options?: any): string; - getAssociationFilterColumn(filterStr: string, dao: Model, options?: { include: boolean }): string; - getConditionalJoins(options: { where?: any }, originalDao: Model): string; - arrayValue(value: Array, key: string, _key: string, factory?: any, logicResult?: any): string; - hashToWhereConditions(hash: any, dao: Model, options?: HashToWhereConditionsOption): string; - booleanValue(value: boolean): string; - } - - interface Schema { - tableName: string; - table: string; - name: string; - schema: string; - delimiter: string; - } + // + // Query Types + // ~~~~~~~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/query-types.js + // interface QueryTypes { - SELECT: string; - BULKUPDATE: string; - BULKDELETE: string; + SELECT: string // 'SELECT' + INSERT: string // 'INSERT' + UPDATE: string // 'UPDATE' + BULKUPDATE: string // 'BULKUPDATE' + BULKDELETE: string // 'BULKDELETE' + DELETE: string // 'DELETE' + UPSERT: string // 'UPSERT' + VERSION: string // 'VERSION' + SHOWTABLES: string // 'SHOWTABLES' + SHOWINDEXES: string // 'SHOWINDEXES' + DESCRIBE: string // 'DESCRIBE' + RAW: string // 'RAW' + FOREIGNKEYS: string // 'FOREIGNKEYS' } - interface ModelManager { - daos: Array>; - sequelize: Sequelize; - addDAO(dao: Model): Model; - removeDAO(dao: Model): void; - getDAO(daoName: string, options?: ModelMangerGetDaoOptions): Model; - all: Array>; + // + // Sequelize + // ~~~~~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/sequelize.js + // + + /** + * General column options + * + * @see Define + * @see AssociationForeignKeyOptions + */ + interface ColumnOptions { /** - * Iterate over DAOs in an order suitable for e.g. creating tables. Will - * take foreign key constraints into account so that dependencies are visited - * before dependents. - */ - forEachDAO(iterator: (dao: Model, name: string) => void, options?: ModelManagerForEachDaoOptions): void; - } - - interface TransactionManager { - sequelize: Sequelize; - connectorManagers: any; - getConnectorManager(uuid?: string): ConnectorManager; - releaseConnectionManager(uuid?: string): void; - - /** - * Execute a query on the DB, with the possibility to bypass all the sequelize goodness. - * - * @param sql SQL statement to execute. - * - * @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented - * by the factory. Equivalent to calling Model.build with the values provided by the query. - * - * @param options Query options. - * - */ - query(sql: string, callee?: Model, options?: QueryOptions): EventEmitter; - - query(sql: string, callee?: Model, options?: QueryOptions): EventEmitter; - } - - interface ConnectorManager { - - /** - * Execute a query on the DB, with the possibility to bypass all the sequelize goodness. - * - * @param sql SQL statement to execute. - * - * @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented - * by the factory. Equivalent to calling Model.build with the values provided by the query. - * - * @param options Query options. - * - */ - query(sql: string, callee?: Model, options?: QueryOptions): EventEmitter; - - afterTransactionSetup(callback: () => void): void; - connect(): void; - disconnect(): void; - reconnect(): void; - cleanup(): void; - } - - interface Migrator { - queryInterface: QueryInterface; - migrate(options?: MigratorOptions): EventEmitter; - getUndoneMigrations(callback: (err: Error, result: Array) => void): void; - findOrCreateMetaDAO(syncOptions?: SyncOptions): EventEmitter; - exec(filename: string, options?: MigratorExecOptions): EventEmitter; - getLastMigrationFromDatabase(): EventEmitter; - getLastMigrationIdFromDatabase(): EventEmitter; - getFormattedDateString(s: string): string; - stringToDate(s: string): Date; - saveSuccessfulMigration(from: Migration, to: Migration, callback: (metaData: MetaInstance) => void): void; - deleteUndoneMigration(from: Migration, to: Migration, callback: () => void): void; - execute(options?: MigrationExecuteOptions): EventEmitter; - isBefore(date: Date, options?: MigrationCompareOptions): boolean; - isAfter(date: Date, options?: MigrationCompareOptions): boolean; - - } - - interface Migration extends QueryInterface { - migrator: Migrator; - path: string; - filename: string; - migrationId: number; - date: Date; - queryInterface: QueryInterface; - migration: (err: Error, migration: Migration, dataTypes: any, callback: (err: Error) => void) => void; - - } - - interface EventEmitter extends EventEmitterT, NodeJS.EventEmitter { } - - interface EventEmitterT extends NodeJS.EventEmitter { - /** - * Create a new emitter instance. - * - * @param handler - */ - new (handler: (emitter: EventEmitterT) => void): EventEmitterT; - - /** - * Run the function that was passed when the emitter was instantiated. - */ - run(): EventEmitterT; - - /** - * Listen for success events. - * - * @param onSuccess - */ - success(onSuccess: (result: R) => void): EventEmitterT; - - /** - * Alias for success(handler). Listen for success events. - * - * @param onSuccess - */ - ok(onSuccess: (result: R) => void): EventEmitterT; - - /** - * Listen for error events. - * - * @param onError - */ - error(onError: (err: Error) => void): EventEmitterT; - - /** - * Alias for error(handler). Listen for error events. - * - * @param onError - */ - fail(onError: (err: Error) => void): EventEmitterT; - - /** - * Alias for error(handler). Listen for error events. - * - * @param onError - */ - failure(onError: (err: Error) => void): EventEmitterT; - - /** - * Listen for both success and error events. - * - * @param onDone - */ - done(onDone: (err: Error, result: R) => void): EventEmitterT; - - /** - * Alias for done(handler). Listen for both success and error events. - * - * @param onDone - */ - complete(onDone: (err: Error, result: R) => void): EventEmitterT; - - /** - * Attach a function that is called every time the function that created this emitter executes a query. - * - * @param onSQL - */ - sql(onSQL: (sql: string) => void): EventEmitterT; - - /** - * Proxy every event of this event emitter to another one. - * - * @param emitter The event emitter that should receive the events. - * @param options Contains an array of the events to proxy. Defaults to sql, error and success - */ - proxy(emitter: EventEmitterT, options?: ProxyOptions): EventEmitterT; - - - } - - interface Options { - /** - * The dialect you of the database you are connecting to. One of mysql, postgres, sqlite and mariadb. - * Default is mysql. - */ - dialect?: string; - - /** - * If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when - * connecting to a pg database, you should specify 'pg.js' here - */ - dialectModulePath?: string; - - /** - * The host of the relational database. Default 'localhost'. - */ - host?: string; - - /** - * Integer The port of the relational database. - */ - port?: number; - - /** - * The protocol of the relational database. Default 'tcp'. - */ - protocol?: string; - - /** - * Default options for model definitions. See sequelize.define for options. - */ - define?: DefineOptions; - - /** - * Default options for sequelize.query - */ - query?: QueryOptions; - - /** - * Default options for sequelize.sync - */ - sync?: SyncOptions; - - /** - * The timezone used when converting a date from the database into a javascript date. The timezone is also used to - * SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time - * related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. - * Default '+00:00'. - */ - timezone?: string; - - /** - * Logging options. Function used to log. Default is console.log. Signature is (message:string) => void. - * - * Set to "false" to disable logging. - */ - logging?: any; - - /** logging=console.log] Function A function that gets executed everytime Sequelize would log something. - * A flag that defines if null values should be passed to SQL queries or not. - */ - omitNull?: boolean; - - /** - * Boolean Queue queries, so that only maxConcurrentQueries number of queries are executing at once. If false, all - * queries will be executed immediately. - */ - queue?: boolean; - - /** - * The maximum number of queries that should be executed at once if queue is true. - */ - maxConcurrentQueries?: number; - - /** - * A flag that defines if native library shall be used or not. Currently only has an effect for postgres - */ - native?: boolean; - - /** - * Use read / write replication. To enable replication, pass an object, with two properties, read and write. Write - * should be an object (a single server for handling writes), and read an array of object (several servers to - * handle reads). Each read/write server can have the following properties?: host, port, username, password, database - */ - replication?: ReplicationOptions; - - /** - * Connection pool options. - * - */ - pool?: PoolOptions; - - /** - * Set to false to make table names and attributes case-insensitive on Postgres and skip double quoting of them. - * Default true. - */ - quoteIdentifiers?: boolean; - - /** - * Language. Default "en". - */ - language?: string; - } - - interface PoolOptions { - maxConnections?: number; - - minConnections?: number; - - /** - * The maximum time, in milliseconds, that a connection can be idle before being released. - */ - maxIdleTime?: number; - - /** - * A function that validates a connection. Called with client. The default function checks that client is an - * object, and that its state is not disconnected. - * - * Note, this is not documented, and after reading code I'm not sure what client's type is. - */ - validateConnection?: (client?: any) => boolean; - } - - interface AttributeOptions { - /** - * A string or a data type - */ - type?: string; - - /** - * If false, the column will have a NOT NULL constraint, and a not null validation will be run before an instance - * is saved. + * If false, the column will have a NOT NULL constraint, and a not null validation will be run before an + * instance is saved. */ allowNull?: boolean; /** - * A literal default value, a javascript function, or an SQL function (see sequelize.fn) + * If set, sequelize will map the attribute name to a different name in the database + */ + field? : string; + + /** + * A literal default value, a JavaScript function, or an SQL function (see `sequelize.fn`) */ defaultValue?: any; + } + + /** + * References options for the column's attributes + * + * @see AttributeColumnOptions + */ + interface DefineAttributeColumnReferencesOptions { + + /** + * If this column references another table, provide it here as a Model, or a string + */ + model?: Model; + + /** + * The column of the foreign table that this column references + */ + key? : string; + + /** + * When to check for the foreign key constraing + * + * PostgreSQL only + */ + deferrable? : Deferrable; + + } + + /** + * Column options for the model schema attributes + * + * @see Attributes + */ + interface DefineAttributeColumnOptions extends ColumnOptions { + + /** + * A string or a data type + */ + type: string | DataTypeAbstract; + /** * If true, the column will get a unique constraint. If a string is provided, the column will be part of a - * composite unique index. If multiple columns have the same string, they will be part of the same unique index. + * composite unique index. If multiple columns have the same string, they will be part of the same unique + * index */ - unique?: any; + unique?: boolean | string | { name: string, msg: string }; + /** + * Primary key flag + */ primaryKey?: boolean; /** - * If set, sequelize will map the attribute name to a different name in the database. + * Is this field an auto increment field */ - field?: string; - autoIncrement?: boolean; + /** + * Comment for the database + */ comment?: string; /** - * If this column references another table, provide it here as a Model, or a string. + * An object with reference configurations */ - references?: any; - - /** - * The column of the foreign table that this column references. Default 'id'. - */ - referencesKey?: string; + references? : DefineAttributeColumnReferencesOptions; /** * What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or - * NO ACTION. + * NO ACTION */ - onUpdate?: string; + onUpdate? : string; /** * What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or - * NO ACTION. + * NO ACTION */ - onDelete?: string; + onDelete? : string; /** - * Provide a custom getter for this column. Use this.getDataValue(String) to manipulate the underlying values. + * Provide a custom getter for this column. Use `this.getDataValue(String)` to manipulate the underlying + * values. */ - get?: () => any; + get? : () => any; /** - * Provide a custom setter for this column. Use this.setDataValue(String, Value) to manipulate the underlying values. + * Provide a custom setter for this column. Use `this.setDataValue(String, Value)` to manipulate the + * underlying values. */ - set?: (value?: any) => void; + set? : ( val : any ) => void; /** - * An object of validations to execute for this column every time the model is saved. Can be either the name of a - * validation provided by validator.js, a validation function provided by extending validator.js (see the - * DAOValidator property for more details), or a custom validation function. Custom validation functions are called - * with the value of the field, and can possibly take a second callback argument, to signal that they are - * asynchronous. If the validator is sync, it should throw in the case of a failed validation, it it is async, - * the callback should be called with the error text. + * An object of validations to execute for this column every time the model is saved. Can be either the + * name of a validation provided by validator.js, a validation function provided by extending validator.js + * (see the + * `DAOValidator` property for more details), or a custom validation function. Custom validation functions + * are called with the value of the field, and can possibly take a second callback argument, to signal that + * they are asynchronous. If the validator is sync, it should throw in the case of a failed validation, it + * it is async, the callback should be called with the error text. */ - validate?: any; + validate? : DefineValidateOptions; + + /** + * Usage in object notation + * + * ```js + * sequelize.define('model', { + * states: { + * type: Sequelize.ENUM, + * values: ['active', 'pending', 'deleted'] + * } + * }) + * ``` + */ + values? : Array; + } - interface ForeignKeyAttributeOptions extends AttributeOptions { + /** + * Interface for Attributes provided for a column + * + * @see Sequelize.define + */ + interface DefineAttributes { + /** - * The name of the foreign key in the target table. Defaults to the name of source + primary key of source. + * The description of a database column */ - fieldName: string; + [name : string] : string | DataTypeAbstract | DefineAttributeColumnOptions; + } - interface DefineOptions { + /** + * Interface for query options + * + * @see Options + */ + interface QueryOptions { + + /** + * If true, sequelize will not try to format the results of the query, or build an instance of a model from + * the result + */ + raw?: boolean; + + /** + * The transaction that the query should be executed under + */ + transaction?: Transaction; + + /** + * The type of query you are executing. The query type affects how results are formatted before they are + * passed back. The type is a string, but `Sequelize.QueryTypes` is provided as convenience shortcuts. + */ + type?: string; + + /** + * If true, transforms objects with `.` separated property names into nested objects using + * [dottie.js](https://github.com/mickhansen/dottie.js). For example { 'user.username': 'john' } becomes + * { user: { username: 'john' }}. When `nest` is true, the query type is assumed to be `'SELECT'`, + * unless otherwise specified + * + * Defaults to false + */ + nest?: boolean; + + /** + * Sets the query type to `SELECT` and return a single row + */ + plain?: boolean; + + /** + * Either an object of named parameter replacements in the format `:param` or an array of unnamed + * replacements to replace `?` in your SQL. + */ + replacements? : Object | Array; + + /** + * Force the query to use the write pool, regardless of the query type. + * + * Defaults to false + */ + useMaster? : boolean; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : Function + + /** + * A sequelize instance used to build the return instance + */ + instance? : Instance; + + /** + * A sequelize model used to build the returned model instances (used to be called callee) + */ + model? : Model; + + // TODO: force, cascade + + } + + /** + * Model validations, allow you to specify format/content/inheritance validations for each attribute of the + * model. + * + * Validations are automatically run on create, update and save. You can also call validate() to manually + * validate an instance. + * + * The validations are implemented by validator.js. + */ + interface DefineValidateOptions { + + /** + * is: ["^[a-z]+$",'i'] // will only allow letters + * is: /^[a-z]+$/i // same as the previous example using real RegExp + */ + is?: string | Array | RegExp | { msg: string, args : string | Array | RegExp }; + + /** + * not: ["[a-z]",'i'] // will not allow letters + */ + not?: string | Array | RegExp | { msg: string, args : string | Array | RegExp }; + + /** + * checks for email format (foo@bar.com) + */ + isEmail?: boolean | { msg: string }; + + /** + * checks for url format (http://foo.com) + */ + isUrl?: boolean | { msg: string }; + + /** + * checks for IPv4 (129.89.23.1) or IPv6 format + */ + isIP?: boolean | { msg: string }; + + /** + * checks for IPv4 (129.89.23.1) + */ + isIPv4?: boolean | { msg: string }; + + /** + * checks for IPv6 format + */ + isIPv6?: boolean | { msg: string }; + + /** + * will only allow letters + */ + isAlpha?: boolean | { msg: string }; + + /** + * will only allow alphanumeric characters, so "_abc" will fail + */ + isAlphanumeric?: boolean | { msg: string }; + + /** + * will only allow numbers + */ + isNumeric?: boolean | { msg: string }; + + /** + * checks for valid integers + */ + isInt?: boolean | { msg: string }; + + /** + * checks for valid floating point numbers + */ + isFloat?: boolean | { msg: string }; + + /** + * checks for any numbers + */ + isDecimal?: boolean | { msg: string }; + + /** + * checks for lowercase + */ + isLowercase?: boolean | { msg: string }; + + /** + * checks for uppercase + */ + isUppercase?: boolean | { msg: string }; + + /** + * won't allow null + */ + notNull?: boolean | { msg: string }; + + /** + * only allows null + */ + isNull?: boolean | { msg: string }; + + /** + * don't allow empty strings + */ + notEmpty?: boolean | { msg: string }; + + /** + * only allow a specific value + */ + equals? : string | { msg: string }; + + /** + * force specific substrings + */ + contains? : string | { msg: string }; + + /** + * check the value is not one of these + */ + notIn? : Array> | { msg: string, args: Array> }; + + /** + * check the value is one of these + */ + isIn? : Array> | { msg: string, args: Array> }; + + /** + * don't allow specific substrings + */ + notContains? : Array | string | { msg: string, args: Array | string }; + + /** + * only allow values with length between 2 and 10 + */ + len?: [number, number] | { msg: string, args: [number, number] }; + + /** + * only allow uuids + */ + isUUID?: number | { msg: string, args: number }; + + /** + * only allow date strings + */ + isDate?: boolean | { msg: string, args: boolean }; + + /** + * only allow date strings after a specific date + */ + isAfter?: string | { msg: string, args: string }; + + /** + * only allow date strings before a specific date + */ + isBefore?: string | { msg: string, args: string }; + + /** + * only allow values + */ + max?: number | { msg: string, args: number }; + + /** + * only allow values >= 23 + */ + min?: number | { msg: string, args: number }; + + /** + * only allow arrays + */ + isArray?: boolean | { msg: string, args: boolean }; + + /** + * check for valid credit card numbers + */ + isCreditCard?: boolean | { msg: string, args: boolean }; + + /** + * custom validations are also possible + * + * Implementation notes : + * + * We can't enforce any other method to be a function, so : + * + * ```typescript + * [name: string] : ( value : any ) => boolean; + * ``` + * + * doesn't work in combination with the properties above + * + * @see https://github.com/Microsoft/TypeScript/issues/1889 + */ + [name: string] : any; + + } + + /** + * Interface for indexes property in DefineOptions + * + * @see DefineOptions + */ + interface DefineIndexesOptions { + + /** + * The name of the index. Defaults to model name + _ + fields concatenated + */ + name? : string, + + /** + * Index type. Only used by mysql. One of `UNIQUE`, `FULLTEXT` and `SPATIAL` + */ + index? : string, + + /** + * The method to create the index by (`USING` statement in SQL). BTREE and HASH are supported by mysql and + * postgres, and postgres additionally supports GIST and GIN. + */ + method? : string, + + /** + * Should the index by unique? Can also be triggered by setting type to `UNIQUE` + * + * Defaults to false + */ + unique? : boolean, + + /** + * PostgreSQL will build the index without taking any write locks. Postgres only + * + * Defaults to false + */ + concurrently? : boolean, + + /** + * An array of the fields to index. Each field can either be a string containing the name of the field, + * a sequelize object (e.g `sequelize.fn`), or an object with the following attributes: `attribute` + * (field name), `length` (create a prefix index of length chars), `order` (the direction the column + * should be sorted in), `collate` (the collation (sort order) for the column) + */ + fields? : Array + + } + + /** + * Interface for name property in DefineOptions + * + * @see DefineOptions + */ + interface DefineNameOptions { + + /** + * Singular model name + */ + singular? : string, + + /** + * Plural model name + */ + plural? : string, + + } + + /** + * Interface for getterMethods in DefineOptions + * + * @see DefineOptions + */ + interface DefineGetterMethodsOptions { + [name: string] : () => any; + } + + /** + * Interface for setterMethods in DefineOptions + * + * @see DefineOptions + */ + interface DefineSetterMethodsOptions { + [name: string] : ( val : any ) => void; + } + + /** + * Interface for Define Scope Options + * + * @see DefineOptions + */ + interface DefineScopeOptions { + + /** + * Name of the scope and it's query + */ + [scopeName: string] : FindOptions | Function; + + } + + /** + * Options for model definition + * + * @see Sequelize.define + */ + interface DefineOptions { + /** * Define the default search scope to use for this model. Scopes have the same form as the options passed to * find / findAll. @@ -1582,10 +3617,10 @@ declare module "sequelize" defaultScope?: FindOptions; /** - * More scopes, defined in the same way as defaultScope above. See Model.scope for more information about how - * scopes are defined, and what you can do with them + * More scopes, defined in the same way as defaultScope above. See `Model.scope` for more information about + * how scopes are defined, and what you can do with them */ - scopes?: any; + scopes?: DefineScopeOptions; /** * Don't persits null values. This means that all columns with null values will not be saved. @@ -1614,1174 +3649,1233 @@ declare module "sequelize" underscoredAll?: boolean; /** - * If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. Otherwise, the - * dao name will be pluralized. Default false. + * If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. + * Otherwise, the dao name will be pluralized. Default false. */ freezeTableName?: boolean; /** - * Override the name of the createdAt column if a string is provided, or disable it if false. Timestamps must be true. + * An object with two attributes, `singular` and `plural`, which are used when this model is associated to + * others. */ - createdAt?: any; + name?: DefineNameOptions; /** - * Override the name of the updatedAt column if a string is provided, or disable it if false. Timestamps must be true. + * Indexes for the provided database table */ - updatedAt?: any; + indexes? : Array; /** - * Override the name of the deletedAt column if a string is provided, or disable it if false. Timestamps must be true. + * Override the name of the createdAt column if a string is provided, or disable it if false. Timestamps + * must be true. Not affected by underscored setting. */ - deletedAt?: any; + createdAt? : string | boolean; /** - * Defaults to pluralized DAO name, unless freezeTableName is true, in which case it uses DAO name verbatim. + * Override the name of the deletedAt column if a string is provided, or disable it if false. Timestamps + * must be true. Not affected by underscored setting. */ - tableName?: string; + deletedAt? : string | boolean; /** - * Provide getter functions that work like those defined per column. If you provide a getter method with the same - * name as a column, it will be used to access the value of that column. If you provide a name that does not match - * a column, this function will act as a virtual getter, that can fetch multiple other values. + * Override the name of the updatedAt column if a string is provided, or disable it if false. Timestamps + * must be true. Not affected by underscored setting. */ - getterMethods?: any; + updatedAt? : string | boolean; /** - * Provide setter functions that work like those defined per column. If you provide a setter method with the same - * name as a column, it will be used to update the value of that column. If you provide a name that does not match - * a column, this function will act as a virtual setter, that can act on and set other values, but will not be - * persisted + * Defaults to pluralized model name, unless freezeTableName is true, in which case it uses model name + * verbatim */ - setterMethods?: any; + tableName? : string; /** - * Provide functions that are added to each instance (DAO). + * Provide getter functions that work like those defined per column. If you provide a getter method with + * the + * same name as a column, it will be used to access the value of that column. If you provide a name that + * does not match a column, this function will act as a virtual getter, that can fetch multiple other + * values */ - instanceMethods?: any; + getterMethods? : DefineGetterMethodsOptions; /** - * Provide functions that are added to the model (Model). + * Provide setter functions that work like those defined per column. If you provide a setter method with + * the + * same name as a column, it will be used to update the value of that column. If you provide a name that + * does not match a column, this function will act as a virtual setter, that can act on and set other + * values, but will not be persisted */ - classMethods?: any; + setterMethods? : DefineSetterMethodsOptions; /** - * Default 'public'. + * Provide functions that are added to each instance (DAO). If you override methods provided by sequelize, + * you can access the original method using `this.constructor.super_.prototype`, e.g. + * `this.constructor.super_.prototype.toJSON.apply(this, arguments)` */ - schema?: string; - schemaDelimiter?: string; - engine?: string; - charset?: string; - comment?: string; - collate?: string; - whereCollection?: any; - language?: string; + instanceMethods? : Object; /** - * An object of hook function that are called before and after certain lifecycle events. The possible hooks are?: - * beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, - * beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, afterBulkCreate, afterBulkDestory and - * afterBulkUpdate. See Hooks for more information about hook functions and their signatures. Each property can - * either be a function, or an array of functions. + * Provide functions that are added to the model (Model). If you override methods provided by sequelize, + * you can access the original method using `this.constructor.prototype`, e.g. + * `this.constructor.prototype.find.apply(this, arguments)` */ - hooks?: Hooks; + classMethods? : Object; + + schema? : string; /** - * An object of model wide validations. Validations have access to all model values via this. If the validator - * function takes an argument, it is assumed to be async, and is called with a callback that accepts an optional - * error. + * You can also change the database engine, e.g. to MyISAM. InnoDB is the default. */ - validate?: any; + engine? : string; + + charset? : string; /** - * + * Finaly you can specify a comment for the table in MySQL and PG */ - indexes?: Array; - } + comment? : string; - interface DefineIndexOptions { - /** - * The name of the index. Defaults to model name + _ + fields concatenated. - */ - name?: string; - - /** - * Index type. Only used by mysql. One of UNIQUE, FULLTEXT and SPATIAL. - */ - type: string; - - /** - * The method to create the index by (USING statement in SQL). BTREE and HASH are supported by mysql and postgres, - * and postgres additionally supports GIST and GIN. - */ - method: string; - - /** - * Should the index by unique? Can also be triggered by setting type to UNIQUE. Default false (unless type = "UNIQUE", - * then true). - */ - unique?: boolean; - - /** - * PostgreSQL will build the index without taking any write locks. Postgres only. Default false. - */ - concurrently?: boolean; + collate? : string; /** - * An array of the fields to index. Each field can either be a string containing the name of the field, or an object - * with the following attributes: attribute (field name), length (create a prefix index of length chars), order (the - * direction the column should be sorted in), collate (the collation (sort order) for the column) + * Set the initial AUTO_INCREMENT value for the table in MySQL. */ - fields: Array; - } + initialAutoIncrement? : string; - interface QueryOptions { /** - * If true, sequelize will not try to format the results of the query, or build an instance of a model from the - * result. + * An object of hook function that are called before and after certain lifecycle events. + * The possible hooks are: beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy, + * beforeBulkUpdate, beforeCreate, beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, + * afterBulkCreate, afterBulkDestory and afterBulkUpdate. See Hooks for more information about hook + * functions and their signatures. Each property can either be a function, or an array of functions. */ - raw?: boolean; + hooks? : HooksDefineOptions; /** - * The transaction that the query should be executed under. + * An object of model wide validations. Validations have access to all model values via `this`. If the + * validator function takes an argument, it is asumed to be async, and is called with a callback that + * accepts an optional error. */ - transaction?: Transaction; + validate? : DefineValidateOptions; - /** - * The type of query you are executing. The query type affects how results are formatted before they are passed - * back. If no type is provided sequelize will try to guess the right type based on the sql, and fall back to - * SELECT. The type is a string, but Sequelize.QueryTypes is provided is convenience shortcuts. Current options - * are SELECT, BULKUPDATE and BULKDELETE. - * - * Default is SELECT. - */ - type?: string; - - /** - * Lock the selected rows in either share or update mode. Possible options are transaction.LOCK.UPDATE and - * transaction.LOCK.SHARE. See transaction.LOCK for an example. - */ - lock?: string; - - /** - * For aggregate function calls, the type of the result. If field is a field in this Model, the default will be the - * type of that field, otherwise defaults to float. - */ - dataType?: any; - - /** - * A function that logs sql queries, or false for no logging. - */ - logging?: any; - - /** - * If plain is true, then sequelize will only return the first record of the result set. In case of false it will - * all records. - */ - plain?: boolean; } + /** + * Sync Options + * + * @see Sequelize.sync + */ interface SyncOptions { + /** - * If force is true, each DAO will do DROP TABLE IF EXISTS ..., before it tries to create its own table. - * Default false. + * If force is true, each DAO will do DROP TABLE IF EXISTS ..., before it tries to create its own table */ force?: boolean; /** - * A function that logs sql queries, or false for no logging. + * Match a regex against the database name before syncing, a safety check for cases where force: true is + * used in tests but not live code */ - logging?: any; + match?: RegExp; /** - * The schema that the tables should be created in. This can be overriden for each table in sequelize.define. - * Default 'public'. + * A function that logs sql queries, or false for no logging + */ + logging?: Function | boolean; + + /** + * The schema that the tables should be created in. This can be overriden for each table in sequelize.define */ schema?: string; + } + interface SetOptions { } + + /** + * Connection Pool options + * + * @see Options + */ + interface PoolOptions { + + /** + * Maximum connections of the pool + */ + maxConnections?: number; + + /** + * Minimum connections of the pool + */ + minConnections?: number; + + /** + * The maximum time, in milliseconds, that a connection can be idle before being released. + */ + maxIdleTime?: number; + + /** + * A function that validates a connection. Called with client. The default function checks that client is an + * object, and that its state is not disconnected. + */ + validateConnection?: ( client? : any ) => boolean; + + } + + /** + * Interface for replication Options in the sequelize constructor + * + * @see Options + */ interface ReplicationOptions { - read?: Array; - write?: Server; + + read?: { + host?: string, + port?: string | number, + username?: string, + password?: string, + database?: string + } + + write?: { + host?: string, + port?: string | number, + username?: string, + password?: string, + database?: string + } + } - interface Server { - host?: string; - port?: number; - database?: string; - username?: string; - password?: string; - } + /** + * Options for the constructor of Sequelize main class + */ + interface Options { - interface DropOptions { /** - * Also drop all objects depending on this table, such as views. Only works in postgres. + * The dialect of the database you are connecting to. One of mysql, postgres, sqlite, mariadb and mssql. * - * Default false. + * Defaults to 'mysql' */ - cascade?: boolean; - } - - interface SchemaOptions { - /** - * The character(s) that separates the schema name from the table name. Default '.'. - */ - schemaDelimiter?: string; - } - - interface FindOptions { - /** - * A hash of attributes to describe your search. - */ - where?: any; + dialect?: string; /** - * A list of the attributes that you want to select. To rename an attribute, you can pass an array, with two - * elements - the first is the name of the attribute in the DB (or some kind of expression such as - * Sequelize.literal, Sequelize.fn and so on), and the second is the name you want the attribute to have in the - * returned instance + * If specified, load the dialect library from this path. For example, if you want to use pg.js instead of + * pg when connecting to a pg database, you should specify 'pg.js' here */ - attributes?: Array; + dialectModulePath?: string; /** - * A list of associations to eagerly load. Supported is either { include?: [ Model1, Model2, ...] } or { include?: - * [ { model?: Model1, as?: 'Alias' } ] }. If your association are set up with an as (eg. X.hasMany(Y, { as?: 'Z }, - * you need to specify Z in the as attribute when eager loading Y). When using the object form, you can also - * specify attributes to specify what columns to load, where to limit the relations, and include to load further - * nested relations + * An object of additional options, which are passed directly to the connection library */ - include?: any; - - /** - * Specifies an ordering. If a string is provided, it will be esacped. Using an array, you can provide several - * columns / functions to order by. Each element can be further wrapped in a two-element array. The first element - * is the column / function to order by, the second is the direction. For example?: order?: [['name', 'DESC']]. In - * this way the column will be escaped, but the direction will not. - */ - order?: any; - - limit?: number; - - offset?: number; - } - - interface BuildOptions { - /** - * If set to true, values will ignore field and virtual setters. Default false. - */ - raw?: boolean; - - /** - * Default true. - */ - isNewRecord?: boolean; - - /** - * Default true. - */ - isDirty?: boolean; - - /** - * an array of include options - Used to build prefetched/included model instances. See set. - */ - include?: Array; - } - - interface CopyOptions extends BuildOptions { - /** - * If set, only columns matching those in fields will be saved. - */ - fields?: Array; + dialectOptions? : Object; /** + * Only used by sqlite. * + * Defaults to ':memory:' */ - transaction?: Transaction; - } + storage? : string; - interface FindOrCreateOptions extends FindOptions, QueryOptions { + /** + * The host of the relational database. + * + * Defaults to 'localhost' + */ + host? : string; + + /** + * The port of the relational database. + */ + port? : number; + + /** + * The protocol of the relational database. + * + * Defaults to 'tcp' + */ + protocol? : string; + + /** + * Default options for model definitions. See sequelize.define for options + */ + define? : DefineOptions; + + /** + * Default options for sequelize.query + */ + query? : QueryOptions; + + /** + * Default options for sequelize.set + */ + set? : SetOptions; + + /** + * Default options for sequelize.sync + */ + sync? : SyncOptions; + + /** + * The timezone used when converting a date from the database into a JavaScript date. The timezone is also + * used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP + * and other time related functions have in the right timezone. For best cross platform performance use the + * format + * +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles'); + * this is useful to capture daylight savings time changes. + * + * Defaults to '+00:00' + */ + timezone? : string; + + /** + * A function that gets executed everytime Sequelize would log something. + * + * Defaults to console.log + */ + logging? : boolean | Function; + + /** + * A flag that defines if null values should be passed to SQL queries or not. + * + * Defaults to false + */ + omitNull? : boolean; + + /** + * A flag that defines if native library shall be used or not. Currently only has an effect for postgres + * + * Defaults to false + */ + native? : boolean; + + /** + * Use read / write replication. To enable replication, pass an object, with two properties, read and write. + * Write should be an object (a single server for handling writes), and read an array of object (several + * servers to handle reads). Each read/write server can have the following properties: `host`, `port`, + * `username`, `password`, `database` + * + * Defaults to false + */ + replication? : ReplicationOptions; + + /** + * Connection pool options + */ + pool? : PoolOptions; + + /** + * Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of + * them. + * + * Defaults to true + */ + quoteIdentifiers? : boolean; + + /** + * Set the default transaction isolation level. See `Sequelize.Transaction.ISOLATION_LEVELS` for possible + * options. + * + * Defaults to 'REPEATABLE_READ' + */ + isolationLevel? : string; } - interface BulkCreateOptions { - /** - * Fields to insert (defaults to all fields). - */ - fields?: Array; + /** + * Sequelize methods that are available both for the static and the instance class of Sequelize + */ + interface SequelizeStaticAndInstance extends Errors { /** - * Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails - * validation. Default false. + * A reference to sequelize utilities. Most users will not need to use these utils directly. However, you + * might want to use `Sequelize.Utils._`, which is a reference to the lodash library, if you don't already + * have it imported in your project. */ - validate?: boolean; + Utils: Utils; /** - * Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run. Default false; + * A modified version of bluebird promises, that allows listening for sql events */ - hooks?: boolean; + Promise: typeof Promise; /** - * Ignore duplicate values for primary keys? (not supported by postgres). Default false. + * Available query types for use with `sequelize.query` */ - ignoreDuplicates?: boolean; + QueryTypes: QueryTypes; + + /** + * Exposes the validator.js object, so you can extend it with custom validation functions. + * The validator is exposed both on the instance, and on the constructor. + */ + Validator: Validator; + + /** + * A Model represents a table in the database. Sometimes you might also see it referred to as model, or + * simply as factory. This class should not be instantiated directly, it is created using sequelize.define, + * and already created models can be loaded using sequelize.import + */ + Model: Model; + + /** + * A reference to the sequelize transaction class. Use this to access isolationLevels when creating a + * transaction + */ + Transaction : TransactionStatic; + + /** + * A reference to the deferrable collection. Use this to access the different deferrable options. + */ + Deferrable : Deferrable; + + /** + * A reference to the sequelize instance class. + */ + Instance : Instance; + + /** + * Creates a object representing a database function. This can be used in search queries, both in where and + * order parts, and as default values in column definitions. If you want to refer to columns in your + * function, you should use `sequelize.col`, so that the columns are properly interpreted as columns and + * not a strings. + * + * Convert a user's username to upper case + * ```js + * instance.updateAttributes({ + * username: self.sequelize.fn('upper', self.sequelize.col('username')) + * }) + * ``` + * @param fn The function you want to call + * @param args All further arguments will be passed as arguments to the function + */ + fn( fn : string, ...args : any[] ) : fn; + + /** + * Creates a object representing a column in the DB. This is often useful in conjunction with + * `sequelize.fn`, since raw string arguments to fn will be escaped. + * + * @param col The name of the column + */ + col( col : string ) : col; + + /** + * Creates a object representing a call to the cast function. + * + * @param val The value to cast + * @param type The type to cast it to + */ + cast( val : any, type : string ) : cast; + + /** + * Creates a object representing a literal, i.e. something that will not be escaped. + * + * @param val + */ + literal( val : any ) : literal; + asIs( val : any ) : literal; + + /** + * An AND query + * + * @param args Each argument will be joined by AND + */ + and( ...args : Array ) : and; + + /** + * An OR query + * + * @param args Each argument will be joined by OR + */ + or( ...args : Array ) : or; + + /** + * Creates an object representing nested where conditions for postgres's json data-type. + * + * @param conditionsOrPath A hash containing strings/numbers or other nested hash, a string using dot + * notation or a string using postgres json syntax. + * @param value An optional value to compare against. Produces a string of the form " = + * ''". + */ + json( conditionsOrPath : string | Object, value? : string | number | boolean ) : json; + + /** + * A way of specifying attr = condition. + * + * The attr can either be an object taken from `Model.rawAttributes` (for example `Model.rawAttributes.id` + * or + * `Model.rawAttributes.name`). The attribute should be defined in your model definition. The attribute can + * also be an object from one of the sequelize utility functions (`sequelize.fn`, `sequelize.col` etc.) + * + * For string attributes, use the regular `{ where: { attr: something }}` syntax. If you don't want your + * string to be escaped, use `sequelize.literal`. + * + * @param attr The attribute, which can be either an attribute object from `Model.rawAttributes` or a + * sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the + * POJO syntax + * @param comparator Comparator + * @param logic The condition. Can be both a simply type, or a further condition (`.or`, `.and`, `.literal` + * etc.) + */ + where( attr : Object, comparator : string, logic : string | Object ) : where; + where( attr : Object, logic : string | Object ) : where; + condition( attr : Object, logic : string | Object ) : where; + } - interface DestroyOptions { - /** - * If set to true, destroy will find all records within the where parameter and will execute before-/ after - * bulkDestroy hooks on each row. - */ - hooks?: boolean; + /** + * Sequelize methods available only for the static class ( basically this is the constructor and some extends ) + */ + interface SequelizeStatic extends SequelizeStaticAndInstance, DataTypes { /** - * How many rows to delete + * Instantiate sequelize with name of database, username and password + * + * #### Example usage + * + * ```javascript + * // without password and options + * var sequelize = new Sequelize('database', 'username') + * + * // without options + * var sequelize = new Sequelize('database', 'username', 'password') + * + * // without password / with blank password + * var sequelize = new Sequelize('database', 'username', null, {}) + * + * // with password and options + * var sequelize = new Sequelize('my_database', 'john', 'doe', {}) + * + * // with uri (see below) + * var sequelize = new Sequelize('mysql://localhost:3306/database', {}) + * ``` + * + * @param database The name of the database + * @param username The username which is used to authenticate against the + * database. + * @param password The password which is used to authenticate against the + * database. + * @param options An object with options. */ - limit?: number; + new ( database : string, username : string, password : string, options? : Options ) : Sequelize; + new ( database : string, username : string, options? : Options ) : Sequelize; /** - * If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is truncated the - * where and limit options are ignored. + * Instantiate sequelize with an URI + * @name Sequelize + * @constructor + * + * @param uri A full database URI + * @param options See above for possible options */ - truncate?: boolean; + new ( uri : string, options? : Options ) : Sequelize; + } - interface DestroyInstanceOptions { + interface QueryOptionsTransactionRequired { } + + /** + * This is the main class, the entry point to sequelize. To use it, you just need to + * import sequelize: + * + * ```js + * var Sequelize = require('sequelize'); + * ``` + * + * In addition to sequelize, the connection library for the dialect you want to use + * should also be installed in your project. You don't need to import it however, as + * sequelize will take care of that. + */ + interface Sequelize extends SequelizeStaticAndInstance, Hooks { + /** - * If set to true, paranoid models will actually be deleted. + * A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc. */ - force: boolean; + Sequelize: SequelizeStatic; + + /** + * Returns the specified dialect. + */ + getDialect() : string; + + /** + * Returns an instance of QueryInterface. + */ + getQueryInterface(): QueryInterface; + + /** + * Define a new model, representing a table in the DB. + * + * The table columns are define by the hash that is given as the second argument. Each attribute of the + * hash + * represents a column. A short table definition might look like this: + * + * ```js + * sequelize.define('modelName', { + * columnA: { + * type: Sequelize.BOOLEAN, + * validate: { + * is: ["[a-z]",'i'], // will only allow letters + * max: 23, // only allow values <= 23 + * isIn: { + * args: [['en', 'zh']], + * msg: "Must be English or Chinese" + * } + * }, + * field: 'column_a' + * // Other attributes here + * }, + * columnB: Sequelize.STRING, + * columnC: 'MY VERY OWN COLUMN TYPE' + * }) + * + * sequelize.models.modelName // The model will now be available in models under the name given to define + * ``` + * + * As shown above, column definitions can be either strings, a reference to one of the datatypes that are + * predefined on the Sequelize constructor, or an object that allows you to specify both the type of the + * column, and other attributes such as default values, foreign key constraints and custom setters and + * getters. + * + * For a list of possible data types, see + * http://docs.sequelizejs.com/en/latest/docs/models-definition/#data-types + * + * For more about getters and setters, see + * http://docs.sequelizejs.com/en/latest/docs/models-definition/#getters-setters + * + * For more about instance and class methods, see + * http://docs.sequelizejs.com/en/latest/docs/models-definition/#expansion-of-models + * + * For more about validation, see + * http://docs.sequelizejs.com/en/latest/docs/models-definition/#validations + * + * @param modelName The name of the model. The model will be stored in `sequelize.models` under this name + * @param attributes An object, where each attribute is a column of the table. Each column can be either a + * DataType, a string or a type-description object, with the properties described below: + * @param options These options are merged with the default define options provided to the Sequelize + * constructor + */ + define( modelName : string, attributes : DefineAttributes, + options? : DefineOptions ) : Model; + + /** + * Fetch a Model which is already defined + * + * @param modelName The name of a model defined with Sequelize.define + */ + model( modelName : string ) : Model; + + /** + * Checks whether a model with the given name is defined + * + * @param modelName The name of a model defined with Sequelize.define + */ + isDefined( modelName : string ) : boolean; + + /** + * Imports a model defined in another file + * + * Imported models are cached, so multiple calls to import with the same path will not load the file + * multiple times + * + * See https://github.com/sequelize/sequelize/blob/master/examples/using-multiple-model-files/Task.js for a + * short example of how to define your models in separate files so that they can be imported by + * sequelize.import + * + * @param path The path to the file that holds the model you want to import. If the part is relative, it + * will be resolved relatively to the calling file + */ + import( path : string ) : Model; + + /** + * Execute a query on the DB, with the posibility to bypass all the sequelize goodness. + * + * By default, the function will return two arguments: an array of results, and a metadata object, + * containing number of affected rows etc. Use `.spread` to access the results. + * + * If you are running a type of query where you don't need the metadata, for example a `SELECT` query, you + * can pass in a query type to make sequelize format the results: + * + * ```js + * sequelize.query('SELECT...').spread(function (results, metadata) { + * // Raw query - use spread + * }); + * + * sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(function (results) { + * // SELECT query - use then + * }) + * ``` + * + * @param sql + * @param options Query options + */ + query( sql : string | { query: string, values: Array }, options? : QueryOptions ) : Promise; + + /** + * Execute a query which would set an environment or user variable. The variables are set per connection, + * so this function needs a transaction. + * + * Only works for MySQL. + * + * @param variables Object with multiple variables. + * @param options Query options. + */ + set( variables : Object, options : QueryOptionsTransactionRequired ) : Promise; + + /** + * Escape value. + * + * @param value Value that needs to be escaped + */ + escape( value : string ) : string; + + /** + * Create a new database schema. + * + * Note,that this is a schema in the + * [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), + * not a database table. In mysql and sqlite, this command will do nothing. + * + * @param schema Name of the schema + * @param options Options supplied + * @param options.logging A function that logs sql queries, or false for no logging + */ + createSchema( schema : string, options : { logging? : boolean | Function } ) : Promise; + + /** + * Show all defined schemas + * + * Note,that this is a schema in the + * [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), + * not a database table. In mysql and sqlite, this will show all tables. + * + * @param options Options supplied + * @param options.logging A function that logs sql queries, or false for no logging + */ + showAllSchemas( options : { logging? : boolean | Function } ) : Promise; + + /** + * Drop a single schema + * + * Note,that this is a schema in the + * [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), + * not a database table. In mysql and sqlite, this drop a table matching the schema name + * + * @param schema Name of the schema + * @param options Options supplied + * @param options.logging A function that logs sql queries, or false for no logging + */ + dropSchema( schema : string, options : { logging? : boolean | Function } ) : Promise; + + /** + * Drop all schemas + * + * Note,that this is a schema in the + * [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), + * not a database table. In mysql and sqlite, this is the equivalent of drop all tables. + * + * @param options Options supplied + * @param options.logging A function that logs sql queries, or false for no logging + */ + dropAllSchemas( options : { logging? : boolean | Function } ) : Promise; + + /** + * Sync all defined models to the DB. + * + * @param options Sync Options + */ + sync( options? : SyncOptions ) : Promise; + + /** + * Truncate all tables defined through the sequelize models. This is done + * by calling Model.truncate() on each model. + * + * @param {object} [options] The options passed to Model.destroy in addition to truncate + * @param {Boolean|function} [options.transaction] + * @param {Boolean|function} [options.logging] A function that logs sql queries, or false for no logging + */ + truncate( options? : DestroyOptions ) : Promise; + + /** + * Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model + * @see {Model#drop} for options + * + * @param options The options passed to each call to Model.drop + */ + drop( options? : DropOptions ) : Promise; + + /** + * Test the connection by trying to authenticate + * + * @param options Query Options for authentication + */ + authenticate( options? : QueryOptions ) : Promise; + validate( options? : QueryOptions ) : Promise; + + /** + * Start a transaction. When using transactions, you should pass the transaction in the options argument + * in order for the query to happen under that transaction + * + * ```js + * sequelize.transaction().then(function (t) { + * return User.find(..., { transaction: t}).then(function (user) { + * return user.updateAttributes(..., { transaction: t}); + * }) + * .then(t.commit.bind(t)) + * .catch(t.rollback.bind(t)); + * }) + * ``` + * + * A syntax for automatically committing or rolling back based on the promise chain resolution is also + * supported: + * + * ```js + * sequelize.transaction(function (t) { // Note that we use a callback rather than a promise.then() + * return User.find(..., { transaction: t}).then(function (user) { + * return user.updateAttributes(..., { transaction: t}); + * }); + * }).then(function () { + * // Commited + * }).catch(function (err) { + * // Rolled back + * console.error(err); + * }); + * ``` + * + * If you have [CLS](https://github.com/othiym23/node-continuation-local-storage) enabled, the transaction + * will automatically be passed to any query that runs witin the callback. To enable CLS, add it do your + * project, create a namespace and set it on the sequelize constructor: + * + * ```js + * var cls = require('continuation-local-storage'), + * ns = cls.createNamespace('....'); + * var Sequelize = require('sequelize'); + * Sequelize.cls = ns; + * ``` + * Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace + * + * @param options Transaction Options + * @param autoCallback Callback for the transaction + */ + transaction( options : TransactionOptions, + autoCallback : ( t : Transaction ) => Promise ) : Promise; + transaction( autoCallback : ( t : Transaction ) => Promise ) : Promise; + transaction() : Promise; + + /** + * Close all connections used by this sequelize instance, and free all references so the instance can be + * garbage collected. + * + * Normally this is done on process exit, so you only need to call this method if you are creating multiple + * instances, and want to garbage collect some of them. + */ + close() : void; + + /** + * Returns the database version + */ + databaseVersion() : Promise; + } - interface InsertOptions { - limit?: number; - returning?: string; - allowNull?: string; + // + // Validator + // ~~~~~~~~~~~ + + /** + * Validator Interface + */ + interface Validator extends IValidatorStatic { + + notEmpty( str : string ) : boolean; + len( str : string, min : number, max : number ) : boolean; + isUrl( str : string ) : boolean; + isIPv6( str : string ) : boolean + isIPv4( str : string ) : boolean + notIn( str : string, values : Array ) : boolean; + regex( str : string, pattern : string, modifiers : string ) : boolean; + notRegex( str : string, pattern : string, modifiers : string ) : boolean; + isDecimal( str : string ) : boolean; + min( str : string, val : number ) : boolean; + max( str : string, val : number ) : boolean; + not( str : string, pattern : string, modifiers : string ) : boolean; + contains( str : string, element : Array ) : boolean; + notContains( str : string, element : Array ) : boolean; + is( str : string, pattern : string, modifiers : string ) : boolean; + } - interface UpdateOptions { - /** - * Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails - * validation. Default true. - */ - validate?: boolean; + // + // Transaction + // ~~~~~~~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/transaction.js + // + + /** + * The transaction object is used to identify a running transaction. It is created by calling + * `Sequelize.transaction()`. + * + * To run a query under a transaction, you should pass the transaction in the options object. + */ + interface Transaction { /** - * Run before / after bulkUpdate hooks? Default false. + * Possible options for row locking. Used in conjuction with `find` calls: + * + * @see TransactionStatic */ - hooks?: boolean; + LOCK : TransactionLock; /** - * How many rows to update (only for mysql and mariadb). + * Commit the transaction */ - limit?: number; + commit() : Transaction; + + /** + * Rollback (abort) the transaction + */ + rollback() : Transaction; + } - interface SetOptions { - /** - * If set to true, field and virtual setters will be ignored. Default false. - */ - raw?: boolean; + /** + * The transaction static object + * + * @see Transaction + */ + interface TransactionStatic { /** - * Clear all previously set data values. Default false. + * Isolations levels can be set per-transaction by passing `options.isolationLevel` to + * `sequelize.transaction`. Default to `REPEATABLE_READ` but you can override the default isolation level + * by passing + * `options.isolationLevel` in `new Sequelize`. + * + * The possible isolations levels to use when starting a transaction: + * + * ```js + * { + * READ_UNCOMMITTED: "READ UNCOMMITTED", + * READ_COMMITTED: "READ COMMITTED", + * REPEATABLE_READ: "REPEATABLE READ", + * SERIALIZABLE: "SERIALIZABLE" + * } + * ``` + * + * Pass in the desired level as the first argument: + * + * ```js + * return sequelize.transaction({ + * isolationLevel: Sequelize.Transaction.SERIALIZABLE + * }, function (t) { + * + * // your transactions + * + * }).then(function(result) { + * // transaction has been committed. Do something after the commit if required. + * }).catch(function(err) { + * // do something with the err. + * }); + * ``` + * + * @see ISOLATION_LEVELS */ - reset?: boolean; + ISOLATION_LEVELS : TransactionIsolationLevels; + + /** + * Possible options for row locking. Used in conjuction with `find` calls: + * + * ```js + * t1 // is a transaction + * t1.LOCK.UPDATE, + * t1.LOCK.SHARE, + * t1.LOCK.KEY_SHARE, // Postgres 9.3+ only + * t1.LOCK.NO_KEY_UPDATE // Postgres 9.3+ only + * ``` + * + * Usage: + * ```js + * t1 // is a transaction + * Model.findAll({ + * where: ..., + * transaction: t1, + * lock: t1.LOCK... + * }); + * ``` + * + * Postgres also supports specific locks while eager loading by using OF: + * ```js + * UserModel.findAll({ + * where: ..., + * include: [TaskModel, ...], + * transaction: t1, + * lock: { + * level: t1.LOCK..., + * of: UserModel + * } + * }); + * ``` + * UserModel will be locked but TaskModel won't! + */ + LOCK : TransactionLock; - include?: any; } - interface SaveOptions { - /** - * An alternative way of setting which fields should be persisted. - */ - fields?: any; - - /** - * If true, the updatedAt timestamp will not be updated. Default false. - */ - silent?: boolean; - - transaction?: Transaction; + /** + * Isolations levels can be set per-transaction by passing `options.isolationLevel` to `sequelize.transaction`. + * Default to `REPEATABLE_READ` but you can override the default isolation level by passing + * `options.isolationLevel` in `new Sequelize`. + */ + interface TransactionIsolationLevels { + READ_UNCOMMITTED: string; // 'READ UNCOMMITTED' + READ_COMMITTED: string; // 'READ COMMITTED' + REPEATABLE_READ: string; // 'REPEATABLE READ' + SERIALIZABLE: string; // 'SERIALIZABLE' } - interface ValidateOptions { - /** - * An array of strings. All properties that are in this array will not be validated. - */ - skip: Array; - } - - interface IncrementOptions { - /** - * The number to increment by. Default 1. - */ - by?: number; - - transaction?: Transaction; - } - - interface IndexOptions { - indicesType?: string; - indexType?: string; - indexName?: string; - parser?: any; - } - - interface ProxyOptions { - /** - * An array of the events to proxy. Defaults to sql, error and success. - */ - events: Array; - } - - interface AssociationOptions { - /** - * Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For - * example if User.hasOne(Profile, {onDelete: 'cascade', hooks:true}), the before-/afterDestroy hooks for profile - * will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks. - * Default false. - */ - hooks?: boolean; - - /** - * The 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?: any; - - /** - * The alias of this model. If you create multiple associations between the same tables, you should provide an - * alias to be able to distinguish between them. If you provide an alias when creating the assocition, you should - * provide the same alias when eager loading and when getting assocated models. Defaults to the singularized - * version of target.name - */ - as?: string; - - /** - * The foreignKey can be either a string name of the foreign key in the target table, - * or can be an object defining the foreign key and its options. Note foreignKey is not fully - * typed since TypeScript does not support union types--it can be either a string or an - * options object. String name defaults to the name of source + primary key of source. - * - * @see ForeignKeyAttributeOptions. - */ - foreignKey?: any; - - /** - * What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or - * NO ACTION. Default SET NULL. - */ - onDelete?: string; - - /** - * What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or - * NO ACTION. Default CASCADE. - */ - onUpdate?: string; - - /** - * Should on update and on delete constraints be enabled on the foreign key. - */ - constraints?: boolean; - } - - interface TriggerOptions { - insert?: Array; - update?: Array; - delete?: Array; - truncate?: Array; - } - - interface TriggerParam { - type: string; - direction?: string; - name?: string; - } - - interface SelectOptions { - limit?: number; - offset?: number; - attributes?: Array; - hasIncludeWhere?: boolean; - hasIncludeRequired?: boolean; - hasMultiAssociation?: boolean; - tableAs?: string; - table?: string; - include?: Array; - includeIgnoreAttributes?: boolean; - where?: any; - /** - * String field name or array of strings of field names. - */ - group?: any; - having?: any; - order?: any; - lock?: string; - } - - interface HashToWhereConditionsOption { - include?: boolean; - keysEscaped?: boolean; - } - - interface ModelMangerGetDaoOptions { - attribute: string; - } - - interface ModelManagerForEachDaoOptions { - /** - * Default true. - */ - reverse: boolean; - } - - interface MigratorOptions { - /** - * A flag that defines if the migrator should get instantiated or not.. - */ - force: boolean; - } - - interface FindAndCountResult { - /** - * The matching model instances. - */ - rows?: Array; - - /** - * The total number of rows. This may be more than the rows returned if a limit and/or offset was supplied. - */ - count?: number; - } - - interface Col { - /** - * Column name. - */ - col: string; - } - - interface Cast { - /** - * The value to cast. - */ - val: any; - - /** - * The type to cast it to. - */ - type: string; - } - - interface Literal { - val: any; - } - - interface And { - /** - * Each argument (string or object) will be joined by AND. - */ - args: Array; - } - - interface Or { - /** - * Each argument (string or object) will be joined by OR. - */ - args: Array; - } - - interface Where { - /** - * The attribute. - */ - attribute: string; - - /** - * The condition. Can be both a simply type, or a further condition (.or, .and, .literal etc.). - */ - logic: any; + /** + * Possible options for row locking. Used in conjuction with `find` calls: + */ + interface TransactionLock { + UPDATE: string; // 'UPDATE' + SHARE: string; // 'SHARE' + KEY_SHARE: string; // 'KEY SHARE' + NO_KEY_UPDATE: string; // 'NO KEY UPDATE' } + /** + * Options provided when the transaction is created + * + * @see sequelize.transaction() + */ interface TransactionOptions { - /** - * - */ + autocommit?: boolean; /** - * One of: 'READ UNCOMMITTED', 'READ COMMITTED', 'REPEATABLE READ', 'SERIALIZABLE'. Default 'REPEATABLE READ'. + * See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options */ isolationLevel?: string; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging?: Function; + } - interface QueryChainerRunSeriallyOptions { - /** - * If set to true, all pending emitters will be skipped if a previous emitter failed. Default false. - */ - skipOnError: boolean; + // + // Utils + // ~~~~~~~ + + interface fn { + clone : fnStatic; } - interface CreateTableQueryOptions { - comment?: string; - uniqueKeys?: Array; - charset?: string; + interface fnStatic { + /** + * @param fn The function you want to call + * @param args All further arguments will be passed as arguments to the function + */ + new ( fn : string, ...args : Array ) : fn; } - interface MigratorExecOptions { - before?: (migrator: Migrator) => void; - after?: (migrator: Migrator) => void; - success?: (migrator: Migrator) => void; + interface col { + col: string; } - interface MigrationExecuteOptions { - method: string; + interface colStatic { + /** + * Creates a object representing a column in the DB. This is often useful in conjunction with + * `sequelize.fn`, since raw string arguments to fn will be escaped. + * @see {Sequelize#fn} + * + * @param col The name of the column + */ + new ( col : string ) : col; } - interface MigrationCompareOptions { - /** - * Default false. - */ - withoutEquals: boolean; + interface cast { + val: any; + type: string; } - interface Promise { + interface castStatic { /** - * Listen for events, event emitter style. Mostly for backwards compatibility with EventEmitter. + * Creates a object representing a call to the cast function. * - * @param evt Event - * @param fct Handler + * @param val The value to cast + * @param type The type to cast it to */ - on(evt: string, fct: () => void): void; - - /** - * Emit an event from the emitter. - * - * @param type The type of event. - * @param value All other arguments will be passed to the event listeners. - */ - emit(type: string, ...value: Array): void; - - /** - * Listen for success events. - */ - success(onSuccess: () => void): Promise; - - /** - * Alias for success(handler). Listen for success events. - */ - ok(onSuccess: () => void): Promise; - - /** - * Listen for error events. - * - * @param onError Error handler. - */ - error(onError: (err?: Error) => void): Promise; - - /** - * Alias for error(handler). Listen for error events. - * - * @param onError Error handler. - */ - fail(onError: (err?: Error) => void): Promise; - - /** - * Alias for error(handler). Listen for error events. - * - * @param onError Error handler. - */ - failure(onError: (err?: Error) => void): Promise; - - /** - * Listen for both success and error events.. - */ - done(handler: (err: Error, result?: any) => void): Promise; - - /** - * Alias for done(handler). Listen for both success and error events.. - */ - complete(handler: (err: Error, result?: any) => void): Promise; - - /** - * Attach a function that is called every time the function that created this emitter executes a query. - * - * @param onSQL - */ - sql(onSQL: (sql: string) => void): Promise; - - /** - * Proxy every event of this promise to another one. - * - * @param promise The promise that should receive the events. - * @param options Contains an array of the events to proxy. Defaults to sql, error and success - */ - proxy(promise: Promise, options?: ProxyOptions): Promise; - - - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: any) => void, onRejected?: (result?: any) => void): Promise; - - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: any) => Promise, onRejected?: (result?: any) => Promise): Promise; - - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: any) => PromiseT, onRejected?: (result?: any) => PromiseT): PromiseT; - - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: any) => PromiseT, onRejected?: (result?: any) => void): PromiseT; - - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: any) => void, onRejected?: (result?: any) => PromiseT): PromiseT; - - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: any) => PromiseT, onRejected?: (result?: any) => PromiseT): Promise; - - /** - * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, - * as opposed to then which will only recieve the first argument. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * @param onRejected - */ - spread(onFulfilled?: (...results: Array) => Promise, onRejected?: (...results: Array) => Promise): Promise; - - /** - * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, - * as opposed to then which will only recieve the first argument. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * @param onRejected - */ - spread(onFulfilled?: (...results: Array) => void, onRejected?: (...results: Array) => void): Promise; - - /** - * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, - * as opposed to then which will only recieve the first argument. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * @param onRejected - */ - spread(onFulfilled?: (...results: Array) => Promise, onRejected?: (...results: Array) => void): Promise; - - /** - * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, - * as opposed to then which will only recieve the first argument. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * @param onRejected - */ - spread(onFulfilled?: (...results: Array) => void, onRejected?: (...results: Array) => Promise): Promise; - - /** - * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, - * as opposed to then which will only recieve the first argument. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * @param onRejected - */ - spread(onFulfilled?: (...results: Array) => PromiseT, onRejected?: (...results: Array) => PromiseT): PromiseT; - - /** - * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, - * as opposed to then which will only recieve the first argument. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * @param onRejected - */ - spread(onFulfilled?: (...results: Array) => void, onRejected?: (...results: Array) => PromiseT): PromiseT; - - /** - * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, - * as opposed to then which will only recieve the first argument. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * @param onRejected - */ - spread(onFulfilled?: (...results: Array) => PromiseT, onRejected?: (...results: Array) => void): PromiseT; - - /** - * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, - * as opposed to then which will only recieve the first argument. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * @param onRejected - */ - spread(onFulfilled?: (...results: Array) => PromiseT, onRejected?: (...results: Array) => PromiseT): Promise; - - /** - * Shorthand for then(null, onRejected) - */ - catch(onRejected: (result?: any) => Promise): Promise; - - /** - * Shorthand for then(null, onRejected) - */ - catch(onRejected: (result?: any) => PromiseT): PromiseT; - - /** - * Shorthand for then(null, onRejected) - */ - catch(onRejected: (result?: any) => void): Promise; + new ( val : any, type : string ) : cast; } - interface PromiseT extends Promise { + interface literal { + val: any; + } + + interface literalStatic { /** - * Listen for events, event emitter style. Mostly for backwards compatibility with EventEmitter. + * Creates a object representing a literal, i.e. something that will not be escaped. * - * @param evt Event - * @param fct Handler + * @param val */ - on(evt: string, fct: (t: T) => void): void; + new ( val : any ) : literal; + } + interface and { + args: Array; + } + + interface andStatic { /** - * Emit an event from the emitter. + * An AND query * - * @param type The type of event. - * @param value All other arguments will be passed to the event listeners. + * @param args Each argument will be joined by AND */ - emit(type: string, ...value: Array): void; + new ( ...args : Array ) : and; + } - /** - * Listen for success events. - */ - success(onSuccess: (t: T) => void): PromiseT; + interface or { + args: Array; + } + interface orStatic { /** - * Alias for success(handler). Listen for success events. - */ - ok(onSuccess: (t: T) => void): PromiseT; - - /** - * Listen for both success and error events.. - */ - done(handler: (err: Error, result: T) => void): PromiseT; - - /** - * Alias for done(handler). Listen for both success and error events.. - */ - complete(handler: (err: Error, result: T) => void): PromiseT; - - /** - * Attach a function that is called every time the function that created this emitter executes a query. + * An OR query + * @see {Model#find} * - * @param onSQL + * @param args Each argument will be joined by OR */ - sql(onSQL: (sql: string) => void): PromiseT; + new ( ...args : Array ) : or; + } + interface json { + conditions?: Object; + path? : string; + value? : string | number | boolean; + } + + interface jsonStatic { /** - * Proxy every event of this promise to another one. + * Creates an object representing nested where conditions for postgres's json data-type. + * @see {Model#find} * - * @param promise The promise that should receive the events. - * @param options Contains an array of the events to proxy. Defaults to sql, error and success + * @method json + * @param conditionsOrPath A hash containing strings/numbers or other nested hash, a string using dot + * notation or a string using postgres json syntax. + * @param value An optional value to compare against. Produces a string of the form " = + * ''". */ - proxy(promise: PromiseT, options?: ProxyOptions): PromiseT; + new ( conditionsOrPath : string | Object, value? : string | number | boolean ) : json; + } - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: T) => void, onRejected?: (result?: T) => void): Promise; + interface where { + attribute : Object; + comparator? : string; + logic : string | Object; + } + interface whereStatic { /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected + * A way of specifying attr = condition. + * + * The attr can either be an object taken from `Model.rawAttributes` (for example `Model.rawAttributes.id` + * or + * `Model.rawAttributes.name`). The attribute should be defined in your model definition. The attribute can + * also be an object from one of the sequelize utility functions (`sequelize.fn`, `sequelize.col` etc.) + * + * For string attributes, use the regular `{ where: { attr: something }}` syntax. If you don't want your + * string to be escaped, use `sequelize.literal`. + * + * @param attr The attribute, which can be either an attribute object from `Model.rawAttributes` or a + * sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the + * POJO syntax + * @param comparator Comparator + * @param logic The condition. Can be both a simply type, or a further condition (`.or`, `.and`, `.literal` + * etc.) */ - then(onFulfilled?: (result?: T) => Promise, onRejected?: (result?: T) => Promise): Promise; + new ( attr : Object, comparator : string, logic : string | Object ) : where; + new ( attr : Object, logic : string | Object ) : where; + } - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: T) => PromiseT, onRejected?: (result?: T) => PromiseT): PromiseT; + interface SequelizeLoDash extends _.LoDashStatic { + camelizeIf( str : string, condition : boolean ): string; + underscoredIf( str : string, condition : boolean ): string; /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected + * * Returns an array with some falsy values removed. The values null, "", undefined and NaN are considered + * falsey. + * + * @param arr Array to compact. */ - then(onFulfilled?: (result?: T) => PromiseT, onRejected?: (result?: T) => void): PromiseT; + compactLite( arr : Array ): Array; + matchesDots( dots : string | Array, value : Object ) : ( item : Object ) => boolean; - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: T) => void, onRejected?: (result?: T) => PromiseT): PromiseT; - - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: T) => PromiseT, onRejected?: (result?: T) => PromiseT): Promise; - - /** - * Shorthand for then(null, onRejected) - */ - catch(onRejected: (result?: T) => Promise): Promise; - - /** - * Shorthand for then(null, onRejected) - */ - catch(onRejected: (result?: T) => PromiseT): PromiseT; - - /** - * Shorthand for then(null, onRejected) - */ - catch(onRejected: (result?: T) => void): Promise; } interface Utils { - _: Lodash; - /** - * Formats a string to parse and interpolate values into the string based on the optionally provided SQL dialect. - * @param arr Array where first element is string with placeholders and remaining attributes are values to replace placeholders. - * @param dialect SQL Dialect. - */ - format(arr: Array, dialect?: string): string; - - /** - * Formats a SQL string replacing named placeholders with values from the parameters object with matching key names. - * - * @param sql String to format. - * @param parameters Key/value hash with values to replace in string. - * @param dialect SQL Dialect - */ - formatNamedParameters(sql: string, parameters: any, dialect?: string): string; - - injectScope(scope: string, merge: boolean): any; - - smartWhere(whereArg: any, dialect: string): any; - - compileSmartWhere(obj: any, dialect: string): Array; - - getWhereLogic(logic: string, val?: any): string; - - isHash(obj: any): boolean; - - hasChanged(attrValue: any, value: any): boolean; - - argsArePrimaryKeys(args: Array, primaryKeys: any): boolean; - - /** - * Consistently combines two table names such that the alphabetically first name always comes first when combined. - * - * @param table1 - * @param table2 - */ - combineTableNames(table1: string, table2: string): string; - - singularize(s: string, language?: string): string; - - pluralize(s: string, language: string): string; + _ : SequelizeLoDash; /** * Same concept as _.merge, but don't overwrite properties that have already been assigned */ - mergeDefaults: typeof _.merge; + mergeDefaults : typeof _.merge; - lowercaseFirst(str: string): string; + lowercaseFirst( str : string ): string; + uppercaseFirst( str : string ): string; + spliceStr( str : string, index : number, count : number, add : string ): string; + camelize( str : string ): string; + format( arr : Array, dialect? : string ): string; + formatNamedParameters( sql : string, parameters : any, dialect? : string ): string; + cloneDeep( obj : T, fn? : ( value : T ) => any ) : T; + mapOptionFieldNames( options : T, Model : Model ) : T; + mapValueFieldNames( dataValues : Object, fields : Array, Model : Model ) : Object; + argsArePrimaryKeys( args : Array, primaryKeys : Object ) : boolean; + canTreatArrayAsAnd( arr : Array ) : boolean; + combineTableNames( tableName1 : string, tableName2 : string ): string; + singularize( s : string ): string; + pluralize( s : string ): string; + removeCommentsFromFunctionString( s : string ): string; + toDefaultValue( value : DataTypeAbstract ): any; + toDefaultValue( value : () => DataTypeAbstract ): any; - uppercaseFirst(str: string): string; + /** + * Determine if the default value provided exists and can be described + * in a db schema using the DEFAULT directive. + */ + defaultValueSchemable( value : any ) : boolean; - spliceStr(str: string, index: number, count: number, add: string): string; - - camelize(str: string): string; - - removeCommentsFromFunctionString(s: string): string; - - toDefaultValue(value: any): any; - - defaultValueSchemable(value: any): boolean; - setAttributes(hash: any, identifier: string, instance: any, prefix: string): any; - removeNullValuesFromHash(hash: any, omitNull: boolean, options: any): any; - firstValueOfHash(obj: any): any; - inherit(subClass: any, superClass: any): any; + removeNullValuesFromHash( hash : Object, omitNull? : boolean, options? : Object ): any; + inherit( subClass : Object, superClass : Object ): Object; stack(): string; - now(dialect: string): Date; + sliceArgs( args : Array, begin? : number ) : Array; + now( dialect : string ): Date; + tick( f : Function ): void; + addTicks( s : string, tickChar? : string ): string; + removeTicks( s : string, tickChar? : string ): string; - /** - * Runs provided function on next tick, depending on environment. - * - * @param f - */ - tick(f: Function): void; + fn: fnStatic; + col: colStatic; + cast: castStatic; + literal: literalStatic; + and: andStatic; + or: orStatic; + json: jsonStatic; + where: whereStatic; - /** - * Surrounds a string with tick marks while removing all existing tick marks from the string. - * @param s String to tick - * @param tickChar Tick mark. Default ` - */ - addTicks(s: string, tickChar?: string): string; - - removeTicks(s: string, tickChar?: string): string; - - generateUUID(): string; - - validateParameter(value: any, expectation: any): boolean; - - CustomEventEmitter: EventEmitter; - Promise: Promise; - QueryChainer: QueryChainer; - Lingo: any; // external project, no definitions yet} - } - - interface Lodash extends _.LoDashStatic { - camelizeIf(str: string, condition: boolean): string; - camelizeIf(str: string, condition: any): string; - underscoredIf(str: string, condition: boolean): string; - underscoredIf(str: string, condition: any): string; - /** - * * Returns an array with some falsy values removed. The values null, "", undefined and NaN are considered falsey. - * - * @param arr Array to compact. - */ - compactLite(arr: Array): Array; - } - - interface MetaPojo { - from: string; - to: string; - } - interface MetaInstance extends MetaPojo, Model { + validateParameter( value : Object, expectation : Object, options? : Object ) : boolean; + formatReferences( obj : Object ) : Object; + Promise : typeof Promise; } - interface DataTypeStringBase { - BINARY: DataTypeString; - } - interface DataTypeNumberBase { - UNSIGNED: boolean; - ZEROFILL: boolean; - } - - interface DataTypeString extends DataTypeStringBase { - } - interface DataTypeChar extends DataTypeStringBase { - } - interface DataTypeInteger extends DataTypeNumberBase { - } - interface DataTypeBigInt extends DataTypeNumberBase { - } - interface DataTypeFloat extends DataTypeNumberBase { - } - interface DataTypeBlob { - } - interface DataTypeDecimal { - PRECISION: number; - SCALE: number; - } - - interface DataTypeVirtual { - } - interface DataTypeEnum { - (...values: Array): DataTypeEnum; - } - interface DataTypeArray { - } - interface DataTypeHstore { - } - - interface DataTypes { - STRING: DataTypeString; - CHAR: DataTypeChar; - TEXT: string; - INTEGER: DataTypeInteger; - BIGINT: DataTypeBigInt; - DATE: string; - BOOLEAN: string; - FLOAT: DataTypeFloat; - NOW: string; - BLOB: DataTypeBlob; - DECIMAL: DataTypeDecimal; - UUID: string; - UUIDV1: string; - UUIDV4: string; - VIRTUAL: DataTypeVirtual; - NONE: DataTypeVirtual; - ENUM: DataTypeEnum; - ARRAY: DataTypeArray; - HSTORE: DataTypeHstore; - } } - var sequelize: sequelize.SequelizeStatic; + var sequelize : sequelize.SequelizeStatic; export = sequelize; + } +