UNPKG

@sequelize/core

Version:

Sequelize is a promise-based Node.js ORM tool for Postgres, MySQL, MariaDB, SQLite, Microsoft SQL Server, Amazon Redshift, Snowflake’s Data Cloud, Db2, Oracle, and IBM i. It features solid transaction support, relations, eager and lazy loading, read repli

451 lines (450 loc) 25.2 kB
import type { PartialBy } from '@sequelize/utils'; import type { Connection, CreateSchemaOptions, DataType, DataTypeClassOrInstance, DestroyOptions, ModelAttributes, ModelOptions, ModelStatic, QiListSchemasOptions, QueryOptions, SyncOptions, TruncateOptions } from '.'; import type { AbstractConnection, GetConnectionOptions } from './abstract-dialect/connection-manager.js'; import type { AbstractDataType } from './abstract-dialect/data-types.js'; import type { AbstractDialect, ConnectionOptions } from './abstract-dialect/dialect.js'; import type { EscapeOptions } from './abstract-dialect/query-generator-typescript.js'; import type { QiDropAllSchemasOptions } from './abstract-dialect/query-interface.types.js'; import type { AbstractQuery } from './abstract-dialect/query.js'; import type { AcquireConnectionOptions } from './abstract-dialect/replication-pool.js'; import { ReplicationPool } from './abstract-dialect/replication-pool.js'; import type { AsyncHookReturn, HookHandler } from './hooks.js'; import type { ModelHooks } from './model-hooks.js'; import { ModelSetView } from './model-set-view.js'; import type { QueryRawOptions } from './sequelize.js'; import { Sequelize } from './sequelize.js'; import type { NormalizedOptions, Options } from './sequelize.types.js'; import type { ManagedTransactionOptions, TransactionOptions } from './transaction.js'; import { Transaction } from './transaction.js'; export interface SequelizeHooks<Dialect extends AbstractDialect> extends ModelHooks { /** * A hook that is run at the start of {@link Sequelize#define} and {@link Model.init} */ beforeDefine(attributes: ModelAttributes<any>, options: ModelOptions): void; /** * A hook that is run at the end of {@link Sequelize#define} and {@link Model.init} */ afterDefine(model: ModelStatic): void; /** * A hook that is run before a connection is created */ beforeConnect(config: ConnectionOptions<Dialect>): AsyncHookReturn; /** * A hook that is run after a connection is created */ afterConnect(connection: AbstractConnection, config: ConnectionOptions<Dialect>): AsyncHookReturn; /** * A hook that is run before a connection is disconnected */ beforeDisconnect(connection: AbstractConnection): AsyncHookReturn; /** * A hook that is run after a connection is disconnected */ afterDisconnect(connection: unknown): AsyncHookReturn; beforeQuery(options: QueryOptions, query: AbstractQuery): AsyncHookReturn; afterQuery(options: QueryOptions, query: AbstractQuery): AsyncHookReturn; /** * A hook that is run at the start of {@link Sequelize#sync} */ beforeBulkSync(options: SyncOptions): AsyncHookReturn; /** * A hook that is run at the end of {@link Sequelize#sync} */ afterBulkSync(options: SyncOptions): AsyncHookReturn; /** * A hook that is run before a connection to the pool */ beforePoolAcquire(options?: AcquireConnectionOptions): AsyncHookReturn; /** * A hook that is run after a connection to the pool */ afterPoolAcquire(connection: AbstractConnection, options?: AcquireConnectionOptions): AsyncHookReturn; } export interface StaticSequelizeHooks { /** * A hook that is run at the beginning of the creation of a Sequelize instance. */ beforeInit(options: Options<AbstractDialect>): void; /** * A hook that is run at the end of the creation of a Sequelize instance. */ afterInit(sequelize: Sequelize): void; } export interface SequelizeTruncateOptions extends TruncateOptions { /** * Most dialects will not allow you to truncate a table while other tables have foreign key references to it (even if they are empty). * This option will disable those checks while truncating all tables, and re-enable them afterwards. * * This option is currently only supported for MySQL, SQLite, and MariaDB. * * Postgres can use {@link TruncateOptions.cascade} to achieve a similar goal. * * If you're experiencing this problem in other dialects, consider using {@link Sequelize.destroyAll} instead. */ withoutForeignKeyChecks?: boolean; } export interface WithConnectionOptions extends PartialBy<GetConnectionOptions, 'type'> { /** * Close the connection when the callback finishes instead of returning it to the pool. * This is useful if you want to ensure that the connection is not reused, * for example if you ran queries that changed session options. */ destroyConnection?: boolean; } type TransactionCallback<T> = (t: Transaction) => PromiseLike<T> | T; type SessionCallback<T> = (connection: AbstractConnection) => PromiseLike<T> | T; export declare const SUPPORTED_DIALECTS: readonly ["mysql", "postgres", "sqlite3", "mariadb", "mssql", "mariadb", "mssql", "db2", "snowflake", "ibmi", "oracle"]; /** * This is a temporary class used to progressively migrate the Sequelize class to TypeScript by slowly moving its functions here. * Always use {@link Sequelize} instead. */ export declare abstract class SequelizeTypeScript<Dialect extends AbstractDialect> { #private; readonly dialect: Dialect; readonly options: NormalizedOptions<Dialect>; /** * The options that were used to create this Sequelize instance. * These are an unmodified copy of the options passed to the constructor. * They are not normalized or validated. * * Mostly available for cloning the Sequelize instance. * For other uses, we recommend using {@link options} instead. */ readonly rawOptions: Options<Dialect>; static get hooks(): HookHandler<StaticSequelizeHooks>; static addHook: import("./hooks-legacy.js").LegacyAddAnyHookFunction<StaticSequelizeHooks>; static removeHook: <HookName extends keyof StaticSequelizeHooks>(this: { hooks: HookHandler<StaticSequelizeHooks>; }, hookName: HookName, listenerNameOrListener: string | StaticSequelizeHooks[HookName]) => void; static hasHook: <HookName extends keyof StaticSequelizeHooks>(this: { hooks: HookHandler<StaticSequelizeHooks>; }, hookName: HookName) => boolean; static hasHooks: <HookName extends keyof StaticSequelizeHooks>(this: { hooks: HookHandler<StaticSequelizeHooks>; }, hookName: HookName) => boolean; static runHooks: import("./hooks-legacy.js").LegacyRunHookFunction<StaticSequelizeHooks, void>; static beforeInit: import("./hooks-legacy.js").LegacyAddHookFunction<(options: Options<AbstractDialect>) => void>; static afterInit: import("./hooks-legacy.js").LegacyAddHookFunction<(sequelize: Sequelize) => void>; get hooks(): HookHandler<SequelizeHooks<Dialect>>; addHook: import("./hooks-legacy.js").LegacyAddAnyHookFunction<SequelizeHooks<AbstractDialect<object, object>>>; removeHook: <HookName extends keyof SequelizeHooks<AbstractDialect<object, object>>>(this: { hooks: HookHandler<SequelizeHooks<AbstractDialect<object, object>>>; }, hookName: HookName, listenerNameOrListener: string | SequelizeHooks<AbstractDialect<object, object>>[HookName]) => void; hasHook: <HookName extends keyof SequelizeHooks<AbstractDialect<object, object>>>(this: { hooks: HookHandler<SequelizeHooks<AbstractDialect<object, object>>>; }, hookName: HookName) => boolean; hasHooks: <HookName extends keyof SequelizeHooks<AbstractDialect<object, object>>>(this: { hooks: HookHandler<SequelizeHooks<AbstractDialect<object, object>>>; }, hookName: HookName) => boolean; runHooks: import("./hooks-legacy.js").LegacyRunHookFunction<SequelizeHooks<AbstractDialect<object, object>>, void>; beforeQuery: import("./hooks-legacy.js").LegacyAddHookFunction<(options: QueryOptions, query: AbstractQuery) => AsyncHookReturn>; afterQuery: import("./hooks-legacy.js").LegacyAddHookFunction<(options: QueryOptions, query: AbstractQuery) => AsyncHookReturn>; beforeBulkSync: import("./hooks-legacy.js").LegacyAddHookFunction<(options: SyncOptions) => AsyncHookReturn>; afterBulkSync: import("./hooks-legacy.js").LegacyAddHookFunction<(options: SyncOptions) => AsyncHookReturn>; beforeConnect: import("./hooks-legacy.js").LegacyAddHookFunction<(config: object) => AsyncHookReturn>; afterConnect: import("./hooks-legacy.js").LegacyAddHookFunction<(connection: AbstractConnection, config: object) => AsyncHookReturn>; beforeDisconnect: import("./hooks-legacy.js").LegacyAddHookFunction<(connection: AbstractConnection) => AsyncHookReturn>; afterDisconnect: import("./hooks-legacy.js").LegacyAddHookFunction<(connection: unknown) => AsyncHookReturn>; beforeDefine: import("./hooks-legacy.js").LegacyAddHookFunction<(attributes: ModelAttributes<any>, options: ModelOptions) => void>; afterDefine: import("./hooks-legacy.js").LegacyAddHookFunction<(model: ModelStatic) => void>; beforePoolAcquire: import("./hooks-legacy.js").LegacyAddHookFunction<(options?: AcquireConnectionOptions) => AsyncHookReturn>; afterPoolAcquire: import("./hooks-legacy.js").LegacyAddHookFunction<(connection: AbstractConnection, options?: AcquireConnectionOptions) => AsyncHookReturn>; beforeValidate: import("./hooks-legacy.js").LegacyAddHookFunction<(instance: import("./model").Model<any, any>, options: import("./instance-validator").ValidationOptions) => AsyncHookReturn>; afterValidate: import("./hooks-legacy.js").LegacyAddHookFunction<(instance: import("./model").Model<any, any>, options: import("./instance-validator").ValidationOptions) => AsyncHookReturn>; validationFailed: import("./hooks-legacy.js").LegacyAddHookFunction<(instance: import("./model").Model<any, any>, options: import("./instance-validator").ValidationOptions, error: unknown) => AsyncHookReturn>; beforeCreate: import("./hooks-legacy.js").LegacyAddHookFunction<(attributes: import("./model").Model<any, any>, options: import("./model").CreateOptions<any>) => AsyncHookReturn>; afterCreate: import("./hooks-legacy.js").LegacyAddHookFunction<(attributes: import("./model").Model<any, any>, options: import("./model").CreateOptions<any>) => AsyncHookReturn>; beforeDestroy: import("./hooks-legacy.js").LegacyAddHookFunction<(instance: import("./model").Model<any, any>, options: import("./model").InstanceDestroyOptions) => AsyncHookReturn>; afterDestroy: import("./hooks-legacy.js").LegacyAddHookFunction<(instance: import("./model").Model<any, any>, options: import("./model").InstanceDestroyOptions) => AsyncHookReturn>; beforeRestore: import("./hooks-legacy.js").LegacyAddHookFunction<(instance: import("./model").Model<any, any>, options: import("./model").InstanceRestoreOptions) => AsyncHookReturn>; afterRestore: import("./hooks-legacy.js").LegacyAddHookFunction<(instance: import("./model").Model<any, any>, options: import("./model").InstanceRestoreOptions) => AsyncHookReturn>; beforeUpdate: import("./hooks-legacy.js").LegacyAddHookFunction<(instance: import("./model").Model<any, any>, options: import("./model").InstanceUpdateOptions<any>) => AsyncHookReturn>; afterUpdate: import("./hooks-legacy.js").LegacyAddHookFunction<(instance: import("./model").Model<any, any>, options: import("./model").InstanceUpdateOptions<any>) => AsyncHookReturn>; beforeUpsert: import("./hooks-legacy.js").LegacyAddHookFunction<(attributes: import("./model").Model<any, any>, options: import("./model").UpsertOptions<any>) => AsyncHookReturn>; afterUpsert: import("./hooks-legacy.js").LegacyAddHookFunction<(attributes: [import("./model").Model<any, any>, boolean | null], options: import("./model").UpsertOptions<any>) => AsyncHookReturn>; beforeSave: import("./hooks-legacy.js").LegacyAddHookFunction<(instance: import("./model").Model<any, any>, options: import("./model").InstanceUpdateOptions<any> | import("./model").CreateOptions<any>) => AsyncHookReturn>; afterSave: import("./hooks-legacy.js").LegacyAddHookFunction<(instance: import("./model").Model<any, any>, options: import("./model").InstanceUpdateOptions<any> | import("./model").CreateOptions<any>) => AsyncHookReturn>; beforeBulkCreate: import("./hooks-legacy.js").LegacyAddHookFunction<(instances: import("./model").Model<any, any>[], options: import("./model").BulkCreateOptions<any>) => AsyncHookReturn>; afterBulkCreate: import("./hooks-legacy.js").LegacyAddHookFunction<(instances: readonly import("./model").Model<any, any>[], options: import("./model").BulkCreateOptions<any>) => AsyncHookReturn>; beforeBulkDestroy: import("./hooks-legacy.js").LegacyAddHookFunction<(options: DestroyOptions<any>) => AsyncHookReturn>; afterBulkDestroy: import("./hooks-legacy.js").LegacyAddHookFunction<(options: DestroyOptions<any>) => AsyncHookReturn>; beforeBulkRestore: import("./hooks-legacy.js").LegacyAddHookFunction<(options: import("./model").RestoreOptions<any>) => AsyncHookReturn>; afterBulkRestore: import("./hooks-legacy.js").LegacyAddHookFunction<(options: import("./model").RestoreOptions<any>) => AsyncHookReturn>; beforeBulkUpdate: import("./hooks-legacy.js").LegacyAddHookFunction<(options: import("./model").UpdateOptions<any>) => AsyncHookReturn>; afterBulkUpdate: import("./hooks-legacy.js").LegacyAddHookFunction<(options: import("./model").UpdateOptions<any>) => AsyncHookReturn>; beforeCount: import("./hooks-legacy.js").LegacyAddHookFunction<(options: import("./model").CountOptions<any>) => AsyncHookReturn>; beforeFind: import("./hooks-legacy.js").LegacyAddHookFunction<(options: import("./model").FindOptions<any>) => AsyncHookReturn>; beforeFindAfterExpandIncludeAll: import("./hooks-legacy.js").LegacyAddHookFunction<(options: import("./model").FindOptions<any>) => AsyncHookReturn>; beforeFindAfterOptions: import("./hooks-legacy.js").LegacyAddHookFunction<(options: import("./model").FindOptions<any>) => AsyncHookReturn>; afterFind: import("./hooks-legacy.js").LegacyAddHookFunction<(instancesOrInstance: import("./model").Model<any, any> | readonly import("./model").Model<any, any>[] | null, options: import("./model").FindOptions<any>) => AsyncHookReturn>; beforeSync: import("./hooks-legacy.js").LegacyAddHookFunction<(options: SyncOptions) => AsyncHookReturn>; afterSync: import("./hooks-legacy.js").LegacyAddHookFunction<(options: SyncOptions) => AsyncHookReturn>; beforeAssociate: import("./hooks-legacy.js").LegacyAddHookFunction<(data: import("./associations").BeforeAssociateEventData, options: import(".").AssociationOptions<any>) => AsyncHookReturn>; afterAssociate: import("./hooks-legacy.js").LegacyAddHookFunction<(data: import("./associations").AfterAssociateEventData, options: import(".").AssociationOptions<any>) => AsyncHookReturn>; /** * The QueryInterface instance, dialect dependant. */ get queryInterface(): Dialect['queryInterface']; /** * The QueryGenerator instance, dialect dependant. */ get queryGenerator(): Dialect['queryGenerator']; get connectionManager(): never; readonly models: ModelSetView<Dialect>; readonly pool: ReplicationPool<Connection<Dialect>, ConnectionOptions<Dialect>>; get modelManager(): never; /** * Instantiates sequelize. * * The options to connect to the database are specific to your dialect. * Please refer to the documentation of your dialect on https://sequelize.org to learn about the options you can use. * * @param options The option bag. * @example * import { PostgresDialect } from '@sequelize/postgres'; * * // with database, username, and password in the options object * const sequelize = new Sequelize({ database, user, password, dialect: PostgresDialect }); * * @example * // with url * import { MySqlDialect } from '@sequelize/mysql'; * * const sequelize = new Sequelize({ * dialect: MySqlDialect, * url: 'mysql://localhost:3306/database', * }) * * @example * // option examples * import { MsSqlDialect } from '@sequelize/mssql'; * * const sequelize = new Sequelize('database', 'username', 'password', { * // the dialect of the database * // It is a Dialect class exported from the dialect package * dialect: MsSqlDialect, * * // custom host; * host: 'my.server.tld', * // for postgres, you can also specify an absolute path to a directory * // containing a UNIX socket to connect over * // host: '/sockets/psql_sockets'. * * // custom port; * port: 12345, * * // disable logging or provide a custom logging function; default: console.log * logging: false, * * // This option is specific to MySQL and MariaDB * socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock', * * // the storage engine for sqlite * // - default ':memory:' * storage: 'path/to/database.sqlite', * * // disable inserting undefined values as NULL * // - default: false * omitNull: true, * * // A flag that defines if connection should be over ssl or not * // Dialect-dependent, check the dialect documentation * ssl: true, * * // Specify options, which are used when sequelize.define is called. * // The following example: * // define: { timestamps: false } * // is basically the same as: * // Model.init(attributes, { timestamps: false }); * // sequelize.define(name, attributes, { timestamps: false }); * // so defining the timestamps for each model will be not necessary * define: { * underscored: false, * freezeTableName: false, * charset: 'utf8', * collate: 'utf8_general_ci' * timestamps: true * }, * * // similar for sync: you can define this to always force sync for models * sync: { force: true }, * * // pool configuration used to pool database connections * pool: { * max: 5, * idle: 30000, * acquire: 60000, * }, * * // isolation level of each transaction * // defaults to dialect default * isolationLevel: IsolationLevel.REPEATABLE_READ * }) */ constructor(options: Options<Dialect>); /** * 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. * * @returns */ close(): Promise<void>; isClosed(): boolean; addModels(models: ModelStatic[]): void; removeAllModels(): void; /** * Escape value to be used in raw SQL. * * If you are using this to use the value in a {@link sql.literal}, consider using {@link sql} instead, which automatically * escapes interpolated values. * * @param value The value to escape * @param options */ escape(value: unknown, options?: EscapeOptions): string; /** * Returns the transaction that is associated to the current asynchronous operation. * This method returns undefined if no transaction is active in the current asynchronous operation, * or if the Sequelize "disableClsTransactions" option is true. */ getCurrentClsTransaction(): Transaction | undefined; /** * Start a managed transaction: Sequelize will create a transaction, pass it to your callback, and commit * it once the promise returned by your callback resolved, or execute a rollback if the promise rejects. * * ```ts * try { * await sequelize.transaction(() => { * const user = await User.findOne(...); * await user.update(...); * }); * * // By now, the transaction has been committed * } catch { * // If the transaction callback threw an error, the transaction has been rolled back * } * ``` * * By default, Sequelize uses AsyncLocalStorage to automatically pass the transaction to all queries executed inside the callback (unless you already pass one or set the `transaction` option to null). * This can be disabled by setting the Sequelize "disableClsTransactions" option to true. You will then need to pass transactions to your queries manually. * * ```ts * const sequelize = new Sequelize({ * // ... * disableClsTransactions: true, * }) * * await sequelize.transaction(transaction => { * // transactions are not automatically passed around anymore, you need to do it yourself: * const user = await User.findOne(..., { transaction }); * await user.update(..., { transaction }); * }); * ``` * * If you want to manage your transaction yourself, use {@link startUnmanagedTransaction}. * * @param callback Async callback during which the transaction will be active */ transaction<T>(callback: TransactionCallback<T>): Promise<T>; /** * @param options Transaction Options * @param callback Async callback during which the transaction will be active */ transaction<T>(options: ManagedTransactionOptions, callback: TransactionCallback<T>): Promise<T>; /** * We highly recommend using {@link Sequelize#transaction} instead. * If you really want to use the manual solution, don't forget to commit or rollback your transaction once you are done with it. * * Transactions started by this method are not automatically passed to queries. You must pass the transaction object manually, * even if the Sequelize "disableClsTransactions" option is false. * * @example * ```ts * try { * const transaction = await sequelize.startUnmanagedTransaction(); * const user = await User.findOne(..., { transaction }); * await user.update(..., { transaction }); * await transaction.commit(); * } catch(err) { * await transaction.rollback(); * } * ``` * * @param options */ startUnmanagedTransaction(options?: TransactionOptions): Promise<Transaction>; /** * A slower alternative to {@link truncate} that uses DELETE FROM instead of TRUNCATE, * but which works with foreign key constraints in dialects that don't support TRUNCATE CASCADE (postgres), * or temporarily disabling foreign key constraints (mysql, mariadb, sqlite). * * @param options */ destroyAll(options?: Omit<DestroyOptions, 'where' | 'limit' | 'truncate'>): Promise<void>; /** * Truncate all models registered in this instance. * This is done by calling {@link Model.truncate} on each model. * * @param options The options passed to {@link Model.truncate}, plus "withoutForeignKeyChecks". */ truncate(options?: SequelizeTruncateOptions): Promise<void>; withConnection<T>(options: WithConnectionOptions, callback: SessionCallback<T>): Promise<T>; withConnection<T>(callback: SessionCallback<T>): Promise<T>; /** * Alias of {@link AbstractQueryInterface#createSchema} * * @param schema Name of the schema * @param options */ createSchema(schema: string, options?: CreateSchemaOptions): Promise<void>; /** * Alias of {@link AbstractQueryInterface#showAllSchemas} * * @deprecated Use {@link AbstractQueryInterface#listSchemas} instead * @param options */ showAllSchemas(options?: QiListSchemasOptions): Promise<string[]>; /** * Alias of {@link AbstractQueryInterface#dropSchema} * * @param schema * @param options */ dropSchema(schema: string, options?: QueryRawOptions): Promise<void>; /** * Alias of {@link AbstractQueryInterface#dropAllSchemas} * * @param options */ dropAllSchemas(options?: QiDropAllSchemasOptions): Promise<void>; /** * Throws if the database version hasn't been loaded yet. * It is automatically loaded the first time Sequelize connects to your database. * * You can use {@link Sequelize#authenticate} to cause a first connection. * * @returns current version of the dialect that is internally loaded */ getDatabaseVersion(): string; getDatabaseVersionIfExist(): string | null; setDatabaseVersion(version: string): void; /** * Alias of {@link AbstractQueryInterface#fetchDatabaseVersion} * * @param options */ fetchDatabaseVersion(options?: QueryRawOptions): Promise<string>; /** * Validate a value against a field specification * * @param value The value to validate * @param type The DataType to validate against */ validateValue(value: unknown, type: DataType): void; normalizeDataType(Type: string): string; normalizeDataType(Type: DataTypeClassOrInstance): AbstractDataType<any>; normalizeDataType(Type: string | DataTypeClassOrInstance): string | AbstractDataType<any>; } export {};