@storehouse/sequelize - v2.0.0
    Preparing search index...

    Class SequelizeManager

    Manager class for Sequelize ORM integration with Storehouse. Provides connection management, model registration, and health checking for SQL databases supported by Sequelize (PostgreSQL, MySQL, SQLite, MariaDB, SQL Server, etc.).

    This manager extends the Sequelize class, offering a unified interface for working with relational databases through the Storehouse registry system.

    const manager = new SequelizeManager({
    name: 'primary-db',
    config: {
    options: {
    dialect: 'postgres',
    host: 'localhost',
    port: 5432,
    database: 'myapp',
    username: 'postgres',
    password: 'password',
    logging: console.log,
    pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
    }
    },
    models: [
    {
    attributes: {
    id: { type: DataTypes.INTEGER, primaryKey: true },
    name: { type: DataTypes.STRING }
    },
    options: { modelName: 'User' }
    }
    ]
    }
    });

    const User = manager.getModel('User');
    const users = await User.findAll();

    Hierarchy

    • Sequelize
      • SequelizeManager

    Implements

    • IManager
    Index

    Constructors

    • Creates a new SequelizeManager instance.

      Parameters

      Returns SequelizeManager

      The Sequelize connection is created immediately and models are initialized. If logging is not specified in options, it defaults to debug logging via @novice1/logger. Models can be initialized either by providing a pre-defined model class or by defining attributes and options directly.

    Properties

    _attributes: any

    A similar dummy variable that doesn't exist on the real object. Do not try to access this in real code.

    This property will become a Symbol in v7 to prevent collisions. Use Attributes instead of this property to be forward-compatible.

    _creationAttributes: any

    A similar dummy variable that doesn't exist on the real object. Do not try to access this in real code.

    This property will become a Symbol in v7 to prevent collisions. Use CreationAttributes instead of this property to be forward-compatible.

    _model: Model

    A dummy variable that doesn't exist on the real object. This exists so Typescript can infer the type of the attributes in static functions. Don't try to access this!

    and: <T extends any[]>(...args: T) => { "[and]": T }

    Type Declaration

      • <T extends any[]>(...args: T): { "[and]": T }
      • An AND query

        Type Parameters

        • T extends any[]

        Parameters

        • ...args: T

          Each argument will be joined by AND

        Returns { "[and]": T }

    cast: (val: unknown, type: string) => Cast

    Type Declaration

      • (val: unknown, type: string): Cast
      • Creates a object representing a call to the cast function.

        Parameters

        • val: unknown

          The value to cast

        • type: string

          The type to cast it to

        Returns Cast

    col: (col: string) => Col

    Type Declaration

      • (col: string): Col
      • 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.

        Parameters

        • col: string

          The name of the column

        Returns Col

    config: Config

    Final config that is used by sequelize.

    connectionManager: ConnectionManager
    fn: (fn: string, ...args: unknown[]) => Fn

    Type Declaration

      • (fn: string, ...args: unknown[]): Fn
      • 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

        instance.update({
        username: self.sequelize.fn('upper', self.sequelize.col('username'))
        })

        Parameters

        • fn: string

          The function you want to call

        • ...args: unknown[]

          All further arguments will be passed as arguments to the function

        Returns Fn

    json: (
        conditionsOrPath: string | object,
        value?: string | number | boolean,
    ) => Json

    Type Declaration

      • (conditionsOrPath: string | object, value?: string | number | boolean): Json
      • Creates an object representing nested where conditions for postgres's json data-type.

        Parameters

        • conditionsOrPath: string | object

          A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres json syntax.

        • Optionalvalue: string | number | boolean

          An optional value to compare against. Produces a string of the form " = ''".

        Returns Json

    literal: (val: string) => Literal

    Type Declaration

      • (val: string): Literal
      • Creates a object representing a literal, i.e. something that will not be escaped.

        Parameters

        • val: string

        Returns Literal

    modelManager: ModelManager
    models: { [key: string]: ModelCtor<Model<any, any>> }

    Dictionary of all models linked with this instance.

    name: string

    The name of this manager instance.

    or: <T extends any[]>(...args: T) => { "[or]": T }

    Type Declaration

      • <T extends any[]>(...args: T): { "[or]": T }
      • An OR query

        Type Parameters

        • T extends any[]

        Parameters

        • ...args: T

          Each argument will be joined by OR

        Returns { "[or]": T }

    Sequelize: typeof Sequelize

    A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc.

    where: {
        <Op extends keyof WhereOperators<any>>(
            leftOperand: Where | WhereLeftOperand,
            operator: Op,
            rightOperand: WhereOperators<any>[Op],
        ): Where;
        <Op extends keyof WhereOperators<any>>(
            leftOperand: any,
            operator: string,
            rightOperand: any,
        ): Where;
        (leftOperand: WhereLeftOperand, rightOperand: any): Where;
    }

    Type Declaration

      • <Op extends keyof WhereOperators<any>>(
            leftOperand: Where | WhereLeftOperand,
            operator: Op,
            rightOperand: WhereOperators<any>[Op],
        ): Where
      • A way of specifying "attr = condition". Can be used as a replacement for the POJO syntax (e.g. where: { name: 'Lily' }) when you need to compare a column that the POJO syntax cannot represent.

        Type Parameters

        • Op extends keyof WhereOperators<any>

        Parameters

        • leftOperand: Where | WhereLeftOperand

          The left side of the comparison.

          • A value taken from YourModel.rawAttributes, to reference an attribute. The attribute must be defined in your model definition.
          • A Literal (using Sequelize#literal)
          • A SQL Function (using Sequelize#fn)
          • A Column name (using Sequelize#col) Note that simple strings to reference an attribute are not supported. You can use the POJO syntax instead.
        • operator: Op

          The comparison operator to use. If unspecified, defaults to Op.eq.

        • rightOperand: WhereOperators<any>[Op]

          The right side of the comparison. Its value depends on the used operator. See WhereOperators for information about what value is valid for each operator.

        Returns Where

        // Using an attribute as the left operand.
        // Equal to: WHERE first_name = 'Lily'
        where(User.rawAttributes.firstName, Op.eq, 'Lily');
        // Using a column name as the left operand.
        // Equal to: WHERE first_name = 'Lily'
        where(col('first_name'), Op.eq, 'Lily');
        // Using a SQL function on the left operand.
        // Equal to: WHERE LOWER(first_name) = 'lily'
        where(fn('LOWER', col('first_name')), Op.eq, 'lily');
        // Using raw SQL as the left operand.
        // Equal to: WHERE 'Lily' = 'Lily'
        where(literal(`'Lily'`), Op.eq, 'Lily');
      • <Op extends keyof WhereOperators<any>>(
            leftOperand: any,
            operator: string,
            rightOperand: any,
        ): Where
      • A way of specifying "attr = condition". Can be used as a replacement for the POJO syntax (e.g. where: { name: 'Lily' }) when you need to compare a column that the POJO syntax cannot represent.

        Type Parameters

        • Op extends keyof WhereOperators<any>

        Parameters

        • leftOperand: any

          The left side of the comparison.

          • A value taken from YourModel.rawAttributes, to reference an attribute. The attribute must be defined in your model definition.
          • A Literal (using Sequelize#literal)
          • A SQL Function (using Sequelize#fn)
          • A Column name (using Sequelize#col) Note that simple strings to reference an attribute are not supported. You can use the POJO syntax instead.
        • operator: string

          The comparison operator to use. If unspecified, defaults to Op.eq.

        • rightOperand: any

          The right side of the comparison. Its value depends on the used operator. See WhereOperators for information about what value is valid for each operator.

        Returns Where

        // Using an attribute as the left operand.
        // Equal to: WHERE first_name = 'Lily'
        where(User.rawAttributes.firstName, Op.eq, 'Lily');
        // Using a column name as the left operand.
        // Equal to: WHERE first_name = 'Lily'
        where(col('first_name'), Op.eq, 'Lily');
        // Using a SQL function on the left operand.
        // Equal to: WHERE LOWER(first_name) = 'lily'
        where(fn('LOWER', col('first_name')), Op.eq, 'lily');
        // Using raw SQL as the left operand.
        // Equal to: WHERE 'Lily' = 'Lily'
        where(literal(`'Lily'`), Op.eq, 'Lily');
      • (leftOperand: WhereLeftOperand, rightOperand: any): Where
      • A way of specifying "attr = condition". Can be used as a replacement for the POJO syntax (e.g. where: { name: 'Lily' }) when you need to compare a column that the POJO syntax cannot represent.

        Parameters

        • leftOperand: WhereLeftOperand

          The left side of the comparison.

          • A value taken from YourModel.rawAttributes, to reference an attribute. The attribute must be defined in your model definition.
          • A Literal (using Sequelize#literal)
          • A SQL Function (using Sequelize#fn)
          • A Column name (using Sequelize#col) Note that simple strings to reference an attribute are not supported. You can use the POJO syntax instead.
        • rightOperand: any

          The right side of the comparison. Its value depends on the used operator. See WhereOperators for information about what value is valid for each operator.

        Returns Where

        // Using an attribute as the left operand.
        // Equal to: WHERE first_name = 'Lily'
        where(User.rawAttributes.firstName, Op.eq, 'Lily');
        // Using a column name as the left operand.
        // Equal to: WHERE first_name = 'Lily'
        where(col('first_name'), Op.eq, 'Lily');
        // Using a SQL function on the left operand.
        // Equal to: WHERE LOWER(first_name) = 'lily'
        where(fn('LOWER', col('first_name')), Op.eq, 'lily');
        // Using raw SQL as the left operand.
        // Equal to: WHERE 'Lily' = 'Lily'
        where(literal(`'Lily'`), Op.eq, 'Lily');
    and: <T extends any[]>(...args: T) => { "[and]": T }

    An AND query

    Type Declaration

      • <T extends any[]>(...args: T): { "[and]": T }
      • An AND query

        Type Parameters

        • T extends any[]

        Parameters

        • ...args: T

          Each argument will be joined by AND

        Returns { "[and]": T }

    Each argument will be joined by AND

    cast: (val: unknown, type: string) => Cast

    Creates a object representing a call to the cast function.

    Type Declaration

      • (val: unknown, type: string): Cast
      • Creates a object representing a call to the cast function.

        Parameters

        • val: unknown

          The value to cast

        • type: string

          The type to cast it to

        Returns Cast

    The value to cast

    The type to cast it to

    col: (col: string) => Col

    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.

    Type Declaration

      • (col: string): Col
      • 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.

        Parameters

        • col: string

          The name of the column

        Returns Col

    The name of the column

    fn: (fn: string, ...args: unknown[]) => Fn

    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

    instance.update({
    username: self.sequelize.fn('upper', self.sequelize.col('username'))
    })

    Type Declaration

      • (fn: string, ...args: unknown[]): Fn
      • 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

        instance.update({
        username: self.sequelize.fn('upper', self.sequelize.col('username'))
        })

        Parameters

        • fn: string

          The function you want to call

        • ...args: unknown[]

          All further arguments will be passed as arguments to the function

        Returns Fn

    The function you want to call

    All further arguments will be passed as arguments to the function

    json: (
        conditionsOrPath: string | object,
        value?: string | number | boolean,
    ) => Json

    Creates an object representing nested where conditions for postgres's json data-type.

    Type Declaration

      • (conditionsOrPath: string | object, value?: string | number | boolean): Json
      • Creates an object representing nested where conditions for postgres's json data-type.

        Parameters

        • conditionsOrPath: string | object

          A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres json syntax.

        • Optionalvalue: string | number | boolean

          An optional value to compare against. Produces a string of the form " = ''".

        Returns Json

    A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres json syntax.

    An optional value to compare against. Produces a string of the form " = ''".

    literal: (val: string) => Literal

    Creates a object representing a literal, i.e. something that will not be escaped.

    Type Declaration

      • (val: string): Literal
      • Creates a object representing a literal, i.e. something that will not be escaped.

        Parameters

        • val: string

        Returns Literal

    or: <T extends any[]>(...args: T) => { "[or]": T }

    An OR query

    Type Declaration

      • <T extends any[]>(...args: T): { "[or]": T }
      • An OR query

        Type Parameters

        • T extends any[]

        Parameters

        • ...args: T

          Each argument will be joined by OR

        Returns { "[or]": T }

    Each argument will be joined by OR

    type: "@storehouse/sequelize" = '@storehouse/sequelize'

    Identifier for the manager type.

    where: {
        <Op extends keyof WhereOperators<any>>(
            leftOperand: Where | WhereLeftOperand,
            operator: Op,
            rightOperand: WhereOperators<any>[Op],
        ): Where;
        <Op extends keyof WhereOperators<any>>(
            leftOperand: any,
            operator: string,
            rightOperand: any,
        ): Where;
        (leftOperand: WhereLeftOperand, rightOperand: any): Where;
    }

    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.

    Type Declaration

      • <Op extends keyof WhereOperators<any>>(
            leftOperand: Where | WhereLeftOperand,
            operator: Op,
            rightOperand: WhereOperators<any>[Op],
        ): Where
      • A way of specifying "attr = condition". Can be used as a replacement for the POJO syntax (e.g. where: { name: 'Lily' }) when you need to compare a column that the POJO syntax cannot represent.

        Type Parameters

        • Op extends keyof WhereOperators<any>

        Parameters

        • leftOperand: Where | WhereLeftOperand

          The left side of the comparison.

          • A value taken from YourModel.rawAttributes, to reference an attribute. The attribute must be defined in your model definition.
          • A Literal (using Sequelize#literal)
          • A SQL Function (using Sequelize#fn)
          • A Column name (using Sequelize#col) Note that simple strings to reference an attribute are not supported. You can use the POJO syntax instead.
        • operator: Op

          The comparison operator to use. If unspecified, defaults to Op.eq.

        • rightOperand: WhereOperators<any>[Op]

          The right side of the comparison. Its value depends on the used operator. See WhereOperators for information about what value is valid for each operator.

        Returns Where

        // Using an attribute as the left operand.
        // Equal to: WHERE first_name = 'Lily'
        where(User.rawAttributes.firstName, Op.eq, 'Lily');
        // Using a column name as the left operand.
        // Equal to: WHERE first_name = 'Lily'
        where(col('first_name'), Op.eq, 'Lily');
        // Using a SQL function on the left operand.
        // Equal to: WHERE LOWER(first_name) = 'lily'
        where(fn('LOWER', col('first_name')), Op.eq, 'lily');
        // Using raw SQL as the left operand.
        // Equal to: WHERE 'Lily' = 'Lily'
        where(literal(`'Lily'`), Op.eq, 'Lily');
      • <Op extends keyof WhereOperators<any>>(
            leftOperand: any,
            operator: string,
            rightOperand: any,
        ): Where
      • A way of specifying "attr = condition". Can be used as a replacement for the POJO syntax (e.g. where: { name: 'Lily' }) when you need to compare a column that the POJO syntax cannot represent.

        Type Parameters

        • Op extends keyof WhereOperators<any>

        Parameters

        • leftOperand: any

          The left side of the comparison.

          • A value taken from YourModel.rawAttributes, to reference an attribute. The attribute must be defined in your model definition.
          • A Literal (using Sequelize#literal)
          • A SQL Function (using Sequelize#fn)
          • A Column name (using Sequelize#col) Note that simple strings to reference an attribute are not supported. You can use the POJO syntax instead.
        • operator: string

          The comparison operator to use. If unspecified, defaults to Op.eq.

        • rightOperand: any

          The right side of the comparison. Its value depends on the used operator. See WhereOperators for information about what value is valid for each operator.

        Returns Where

        // Using an attribute as the left operand.
        // Equal to: WHERE first_name = 'Lily'
        where(User.rawAttributes.firstName, Op.eq, 'Lily');
        // Using a column name as the left operand.
        // Equal to: WHERE first_name = 'Lily'
        where(col('first_name'), Op.eq, 'Lily');
        // Using a SQL function on the left operand.
        // Equal to: WHERE LOWER(first_name) = 'lily'
        where(fn('LOWER', col('first_name')), Op.eq, 'lily');
        // Using raw SQL as the left operand.
        // Equal to: WHERE 'Lily' = 'Lily'
        where(literal(`'Lily'`), Op.eq, 'Lily');
      • (leftOperand: WhereLeftOperand, rightOperand: any): Where
      • A way of specifying "attr = condition". Can be used as a replacement for the POJO syntax (e.g. where: { name: 'Lily' }) when you need to compare a column that the POJO syntax cannot represent.

        Parameters

        • leftOperand: WhereLeftOperand

          The left side of the comparison.

          • A value taken from YourModel.rawAttributes, to reference an attribute. The attribute must be defined in your model definition.
          • A Literal (using Sequelize#literal)
          • A SQL Function (using Sequelize#fn)
          • A Column name (using Sequelize#col) Note that simple strings to reference an attribute are not supported. You can use the POJO syntax instead.
        • rightOperand: any

          The right side of the comparison. Its value depends on the used operator. See WhereOperators for information about what value is valid for each operator.

        Returns Where

        // Using an attribute as the left operand.
        // Equal to: WHERE first_name = 'Lily'
        where(User.rawAttributes.firstName, Op.eq, 'Lily');
        // Using a column name as the left operand.
        // Equal to: WHERE first_name = 'Lily'
        where(col('first_name'), Op.eq, 'Lily');
        // Using a SQL function on the left operand.
        // Equal to: WHERE LOWER(first_name) = 'lily'
        where(fn('LOWER', col('first_name')), Op.eq, 'lily');
        // Using raw SQL as the left operand.
        // Equal to: WHERE 'Lily' = 'Lily'
        where(literal(`'Lily'`), Op.eq, 'Lily');

    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

    Comparator

    The condition. Can be both a simply type, or a further condition (.or, .and, .literal etc.)

    Methods

    • Add a hook to the model

      Type Parameters

      • K extends keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

      Parameters

      • hookType: K
      • name: string

        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.

      • fn: SequelizeHooks<Model<any, any>, any, any>[K]

      Returns this

    • Add a hook to the model

      Type Parameters

      • K extends keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

      Parameters

      • hookType: K
      • fn: SequelizeHooks<Model<any, any>, any, any>[K]

      Returns this

    • A hook that is run after creating instances in bulk

      Parameters

      • name: string
      • fn: (instances: Model<any, any>[], options: BulkCreateOptions<any>) => void

        A callback function that is called with instances, options

      Returns void

    • A hook that is run after creating instances in bulk

      Parameters

      • fn: (instances: Model<any, any>[], options: BulkCreateOptions<any>) => void

        A callback function that is called with instances, options

      Returns void

    • A hook that is run after destroying instances in bulk

      Parameters

      • name: string
      • fn: (options: DestroyOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run after destroying instances in bulk

      Parameters

      • fn: (options: DestroyOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run after sequelize.sync call

      Parameters

      • name: string
      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to sequelize.sync

      Returns void

    • A hook that is run after sequelize.sync call

      Parameters

      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to sequelize.sync

      Returns void

    • A hook that is run after updating instances in bulk

      Parameters

      • name: string
      • fn: (options: UpdateOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run after updating instances in bulk

      Parameters

      • fn: (options: UpdateOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run after creating a single instance

      Parameters

      • name: string
      • fn: (attributes: Model, options: CreateOptions<any>) => void

        A callback function that is called with attributes, options

      Returns void

    • A hook that is run after creating a single instance

      Parameters

      • fn: (attributes: Model, options: CreateOptions<any>) => void

        A callback function that is called with attributes, options

      Returns void

    • A hook that is run after a define call

      Parameters

      • name: string
      • fn: (model: ModelType) => void

        A callback function that is called with factory

      Returns void

    • A hook that is run after a define call

      Parameters

      • fn: (model: ModelType) => void

        A callback function that is called with factory

      Returns void

    • A hook that is run after destroying a single instance

      Parameters

      • name: string
      • fn: (instance: Model, options: InstanceDestroyOptions) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run after destroying a single instance

      Parameters

      • fn: (instance: Model, options: InstanceDestroyOptions) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run after a find (select) query

      Parameters

      • name: string
      • fn: (
            instancesOrInstance: Model<any, any> | Model<any, any>[] | null,
            options: FindOptions<any>,
        ) => void

        A callback function that is called with instance(s), options

      Returns void

    • A hook that is run after a find (select) query

      Parameters

      • fn: (
            instancesOrInstance: Model<any, any> | Model<any, any>[] | null,
            options: FindOptions<any>,
        ) => void

        A callback function that is called with instance(s), options

      Returns void

    • A hook that is run after Sequelize() call

      Parameters

      • name: string
      • fn: (sequelize: Sequelize) => void

        A callback function that is called with sequelize

      Returns void

    • A hook that is run after Sequelize() call

      Parameters

      • fn: (sequelize: Sequelize) => void

        A callback function that is called with sequelize

      Returns void

    • A hook that is run after Model.sync call

      Parameters

      • name: string
      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to Model.sync

      Returns void

    • A hook that is run after Model.sync call

      Parameters

      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to Model.sync

      Returns void

    • A hook that is run after updating a single instance

      Parameters

      • name: string
      • fn: (instance: Model, options: UpdateOptions<any>) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run after updating a single instance

      Parameters

      • fn: (instance: Model, options: UpdateOptions<any>) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run after validation

      Parameters

      • name: string
      • fn: (instance: Model, options: ValidationOptions) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run after validation

      Parameters

      • fn: (instance: Model, options: ValidationOptions) => void

        A callback function that is called with instance, options

      Returns void

    • Test the connection by trying to authenticate

      Parameters

      • Optionaloptions: QueryOptions

        Query Options for authentication

      Returns Promise<void>

    • A hook that is run before creating instances in bulk

      Parameters

      • name: string
      • fn: (instances: Model<any, any>[], options: BulkCreateOptions<any>) => void

        A callback function that is called with instances, options

      Returns void

    • A hook that is run before creating instances in bulk

      Parameters

      • fn: (instances: Model<any, any>[], options: BulkCreateOptions<any>) => void

        A callback function that is called with instances, options

      Returns void

    • A hook that is run before destroying instances in bulk

      Parameters

      • name: string
      • fn: (options: BulkCreateOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before destroying instances in bulk

      Parameters

      • fn: (options: BulkCreateOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before sequelize.sync call

      Parameters

      • name: string
      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to sequelize.sync

      Returns void

    • A hook that is run before sequelize.sync call

      Parameters

      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to sequelize.sync

      Returns void

    • A hook that is run after updating instances in bulk

      Parameters

      • name: string
      • fn: (options: UpdateOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run after updating instances in bulk

      Parameters

      • fn: (options: UpdateOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before creating a single instance

      Parameters

      • name: string
      • fn: (attributes: Model, options: CreateOptions<any>) => void

        A callback function that is called with attributes, options

      Returns void

    • A hook that is run before creating a single instance

      Parameters

      • fn: (attributes: Model, options: CreateOptions<any>) => void

        A callback function that is called with attributes, options

      Returns void

    • A hook that is run before a define call

      Parameters

      • name: string
      • fn: (attributes: ModelAttributes<Model, any>, options: ModelOptions) => void

        A callback function that is called with attributes, options

      Returns void

    • A hook that is run before a define call

      Parameters

      • fn: (attributes: ModelAttributes<Model, any>, options: ModelOptions) => void

        A callback function that is called with attributes, options

      Returns void

    • A hook that is run before destroying a single instance

      Parameters

      • name: string
      • fn: (instance: Model, options: InstanceDestroyOptions) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run before destroying a single instance

      Parameters

      • fn: (instance: Model, options: InstanceDestroyOptions) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run before a find (select) query

      Parameters

      • name: string
      • fn: (options: FindOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before a find (select) query

      Parameters

      • fn: (options: FindOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded

      Parameters

      • name: string
      • fn: (options: FindOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded

      Parameters

      • fn: (options: FindOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before a find (select) query, after all option parsing is complete

      Parameters

      • name: string
      • fn: (options: FindOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before a find (select) query, after all option parsing is complete

      Parameters

      • fn: (options: FindOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before Sequelize() call

      Parameters

      • name: string
      • fn: (config: Config, options: Options) => void

        A callback function that is called with config, options

      Returns void

    • A hook that is run before Sequelize() call

      Parameters

      • fn: (config: Config, options: Options) => void

        A callback function that is called with config, options

      Returns void

    • A hook that is run before Model.sync call

      Parameters

      • name: string
      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to Model.sync

      Returns void

    • A hook that is run before Model.sync call

      Parameters

      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to Model.sync

      Returns void

    • A hook that is run before updating a single instance

      Parameters

      • name: string
      • fn: (instance: Model, options: UpdateOptions<any>) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run before updating a single instance

      Parameters

      • fn: (instance: Model, options: UpdateOptions<any>) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run before validation

      Parameters

      • name: string
      • fn: (instance: Model, options: ValidationOptions) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run before validation

      Parameters

      • fn: (instance: Model, options: ValidationOptions) => void

        A callback function that is called with instance, options

      Returns void

    • 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 Promise<void>

    • Closes the Sequelize connection. Terminates all active connections in the pool.

      Returns Promise<void>

      A promise that resolves when the connection is closed

      await manager.closeConnection();
      
    • Create a new database schema.

      Note,that this is a schema in the postgres sense of the word, not a database table. In mysql and sqlite, this command will do nothing.

      Parameters

      • schema: string

        Name of the schema

      • options: Logging

        Options supplied

      Returns Promise<unknown>

    • Returns the database version

      Returns Promise<string>

    • Define a new model, representing a table in the DB.

      The table columns are defined by the hash that is given as the second argument. Each attribute of the hash represents a column. A short table definition might look like this:

      class MyModel extends Model {}
      MyModel.init({
      columnA: {
      type: Sequelize.BOOLEAN,
      validate: {
      is: ["[a-z]",'i'], // will only allow letters
      max: 23, // only allow values <= 23
      isIn: {
      args: [['en', 'zh']],
      msg: "Must be English or Chinese"
      }
      },
      field: 'column_a'
      // Other attributes here
      },
      columnB: Sequelize.STRING,
      columnC: 'MY VERY OWN COLUMN TYPE'
      }, { sequelize })

      sequelize.models.modelName // The model will now be available in models under the 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 https://sequelize.org/master/en/latest/docs/models-definition/#data-types

      For more about getters and setters, see https://sequelize.org/master/en/latest/docs/models-definition/#getters-setters

      For more about instance and class methods, see https://sequelize.org/master/en/latest/docs/models-definition/#expansion-of-models

      For more about validation, see https://sequelize.org/master/en/latest/docs/models-definition/#validations

      Type Parameters

      • M extends Model<any, any>
      • TAttributes = Attributes<M>

      Parameters

      • modelName: string

        The name of the model. The model will be stored in sequelize.models under this name

      • attributes: ModelAttributes<M, TAttributes>

        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:

      • Optionaloptions: ModelOptions<M>

        These options are merged with the default define options provided to the Sequelize constructor

      Returns ModelCtor<M>

    • Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model

      Parameters

      • Optionaloptions: DropOptions

        The options passed to each call to Model.drop

      Returns Promise<unknown[]>

    • Drop all schemas

      Note,that this is a schema in the postgres sense of the word, not a database table. In mysql and sqlite, this is the equivalent of drop all tables.

      Parameters

      • options: Logging

        Options supplied

      Returns Promise<unknown[]>

    • Drop a single schema

      Note,that this is a schema in the postgres sense of the word, not a database table. In mysql and sqlite, this drop a table matching the schema name

      Parameters

      • schema: string

        Name of the schema

      • options: Logging

        Options supplied

      Returns Promise<unknown[]>

    • Escape value.

      Parameters

      • value: string | number | Date

        Value that needs to be escaped

      Returns string

    • Retrieves the Sequelize connection instance.

      Returns Sequelize

      The Sequelize instance (this manager itself)

      const sequelize = manager.getConnection();
      const [results] = await sequelize.query('SELECT NOW()');
    • Returns the database name.

      Returns string

    • Returns the specified dialect.

      Returns string

    • Fetches a model that has already been defined in this Sequelize instance.

      Type Parameters

      • M extends ModelStatic<Model<any, any>> = ModelStatic<Model<any, any>>

        The ModelStatic type, defaults to ModelStatic

      Parameters

      • name: string

        The name of the model to retrieve

      Returns M

      The requested model class

      const User = manager.getModel('User');
      const user = await User.findOne({ where: { email: 'user@example.com' } });
    • Fetches a model that has already been defined in this Sequelize instance.

      Type Parameters

      • M extends Model<any, any> = Model<any, any>

        The Model type, defaults to Model

      Parameters

      • name: string

        The name of the model to retrieve

      Returns ModelStatic<M>

      The requested model class

    • Fetches a model that has already been defined in this Sequelize instance.

      Type Parameters

      • TModelAttributes extends Record<string, unknown> = AnyJsonObject

        The model attributes type

      • TCreationAttributes extends Record<string, unknown> = AnyJsonObject

        The creation attributes type

      Parameters

      • name: string

        The name of the model to retrieve

      Returns ModelStatic<Model<TModelAttributes, TCreationAttributes>>

      The requested model class

    • Returns an instance of QueryInterface.

      Returns QueryInterface

    • Check whether the mode has any hooks of this type

      Type Parameters

      • K extends keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

      Parameters

      • hookType: K

      Returns boolean

    • Type Parameters

      • K extends keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

      Parameters

      • hookType: K

      Returns boolean

    • Performs a comprehensive health check on the Sequelize connection. Tests connectivity by authenticating with the database and gathering connection information.

      Returns Promise<SequelizeHealthCheckResult>

      A promise that resolves to a detailed health check result including:

      • Connection status
      • Database dialect and version
      • Registered models
      • Authentication latency
      • Error details (if unhealthy)
      const health = await manager.healthCheck();
      if (health.healthy) {
      console.log(`Sequelize is healthy. Latency: ${health.details.latency}`);
      console.log(`Database: ${health.details.dialect} v${health.details.databaseVersion}`);
      console.log(`Models: ${health.details.models?.join(', ')}`);
      } else {
      console.error(`Sequelize is unhealthy: ${health.message}`);
      }
    • Checks if the Sequelize connection is active and can authenticate with the database.

      Returns Promise<boolean>

      A promise that resolves to true if authentication succeeds, false otherwise

      This method tests the connection by running the authenticate() method, which verifies that the database credentials are correct and the database is accessible. For a more comprehensive check with additional metrics, use healthCheck.

      if (await manager.isConnected()) {
      console.log('Sequelize connection is active');
      } else {
      console.log('Cannot connect to database');
      }
    • Checks whether a model with the given name is defined

      Parameters

      • modelName: string

        The name of a model defined with Sequelize.define

      Returns boolean

    • Fetch a Model which is already defined

      Parameters

      • modelName: string

        The name of a model defined with Sequelize.define

      Returns ModelCtor<Model<any, any>>

    • Execute a query on the DB, optionally bypassing 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 const [results, meta] = await ... 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:

      const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring

      const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring

      Parameters

      • sql: string | { query: string; values: unknown[] }
      • options: QueryOptionsWithType<UPDATE>

        Query options

      Returns Promise<[undefined, number]>

    • Execute a query on the DB, optionally bypassing 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 const [results, meta] = await ... 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:

      const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring

      const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring

      Parameters

      • sql: string | { query: string; values: unknown[] }
      • options: QueryOptionsWithType<BULKUPDATE>

        Query options

      Returns Promise<number>

    • Execute a query on the DB, optionally bypassing 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 const [results, meta] = await ... 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:

      const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring

      const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring

      Parameters

      • sql: string | { query: string; values: unknown[] }
      • options: QueryOptionsWithType<INSERT>

        Query options

      Returns Promise<[number, number]>

    • Execute a query on the DB, optionally bypassing 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 const [results, meta] = await ... 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:

      const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring

      const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring

      Parameters

      • sql: string | { query: string; values: unknown[] }
      • options: QueryOptionsWithType<UPSERT>

        Query options

      Returns Promise<number>

    • Execute a query on the DB, optionally bypassing 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 const [results, meta] = await ... 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:

      const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring

      const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring

      Parameters

      • sql: string | { query: string; values: unknown[] }
      • options: QueryOptionsWithType<DELETE>

        Query options

      Returns Promise<void>

    • Execute a query on the DB, optionally bypassing 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 const [results, meta] = await ... 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:

      const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring

      const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring

      Parameters

      • sql: string | { query: string; values: unknown[] }
      • options: QueryOptionsWithType<BULKDELETE>

        Query options

      Returns Promise<number>

    • Execute a query on the DB, optionally bypassing 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 const [results, meta] = await ... 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:

      const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring

      const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring

      Parameters

      • sql: string | { query: string; values: unknown[] }
      • options: QueryOptionsWithType<SHOWTABLES>

        Query options

      Returns Promise<string[]>

    • Execute a query on the DB, optionally bypassing 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 const [results, meta] = await ... 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:

      const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring

      const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring

      Parameters

      • sql: string | { query: string; values: unknown[] }
      • options: QueryOptionsWithType<DESCRIBE>

        Query options

      Returns Promise<ColumnsDescription>

    • Execute a query on the DB, optionally bypassing 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 const [results, meta] = await ... 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:

      const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring

      const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring

      Type Parameters

      • M extends Model<any, any>

      Parameters

      • sql: string | { query: string; values: unknown[] }
      • options: QueryOptionsWithModel<M> & { plain: true }

        Query options

      Returns Promise<M | null>

    • Execute a query on the DB, optionally bypassing 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 const [results, meta] = await ... 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:

      const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring

      const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring

      Type Parameters

      • M extends Model<any, any>

      Parameters

      • sql: string | { query: string; values: unknown[] }
      • options: QueryOptionsWithModel<M>

        Query options

      Returns Promise<M[]>

    • Execute a query on the DB, optionally bypassing 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 const [results, meta] = await ... 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:

      const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring

      const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring

      Type Parameters

      • T extends object

      Parameters

      • sql: string | { query: string; values: unknown[] }
      • options: QueryOptionsWithType<SELECT> & { plain: true }

        Query options

      Returns Promise<T | null>

    • Execute a query on the DB, optionally bypassing 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 const [results, meta] = await ... 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:

      const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring

      const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring

      Type Parameters

      • T extends object

      Parameters

      • sql: string | { query: string; values: unknown[] }
      • options: QueryOptionsWithType<SELECT>

        Query options

      Returns Promise<T[]>

    • Execute a query on the DB, optionally bypassing 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 const [results, meta] = await ... 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:

      const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring

      const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring

      Parameters

      • sql: string | { query: string; values: unknown[] }
      • options: (QueryOptions | QueryOptionsWithType<RAW>) & { plain: true }

        Query options

      Returns Promise<{ [key: string]: unknown } | null>

    • Execute a query on the DB, optionally bypassing 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 const [results, meta] = await ... 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:

      const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring

      const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring

      Parameters

      • sql: string | { query: string; values: unknown[] }
      • Optionaloptions: QueryOptions | QueryOptionsWithType<RAW>

        Query options

      Returns Promise<[unknown[], unknown]>

    • Get the fn for random based on the dialect

      Returns Fn

    • Remove hook from the model

      Type Parameters

      • K extends keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

      Parameters

      • hookType: K
      • name: string

      Returns this

    • 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.

      Parameters

      • variables: object

        object with multiple variables.

      • options: QueryOptionsTransactionRequired

        Query options.

      Returns Promise<unknown>

    • Show all defined schemas

      Note,that this is a schema in the postgres sense of the word, not a database table. In mysql and sqlite, this will show all tables.

      Parameters

      • options: Logging

        Options supplied

      Returns Promise<object[]>

    • Sync all defined models to the DB.

      Parameters

      • Optionaloptions: SyncOptions

        Sync Options

      Returns Promise<SequelizeManager>

    • 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

        try {
      const transaction = await sequelize.transaction();
      const user = await User.findOne(..., { transaction });
      await user.update(..., { transaction });
      await transaction.commit();
      } catch(err) {
      await transaction.rollback();
      }
      })

      A syntax for automatically committing or rolling back based on the promise chain resolution is also supported:

      try {
      await sequelize.transaction(transaction => { // Note that we pass a callback rather than awaiting the call with no arguments
      const user = await User.findOne(..., {transaction});
      await user.update(..., {transaction});
      });
      // Committed
      } catch(err) {
      // Rolled back
      console.error(err);
      }

      If you have CLS 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:

      const cls = require('cls-hooked');
      const namespace = cls.createNamespace('....');
      const Sequelize = require('sequelize');
      Sequelize.useCLS(namespace);

      Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace

      Type Parameters

      • T

      Parameters

      • options: TransactionOptions

        Transaction Options

      • autoCallback: (t: Transaction) => PromiseLike<T>

        Callback for the transaction

      Returns Promise<T>

    • 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

        try {
      const transaction = await sequelize.transaction();
      const user = await User.findOne(..., { transaction });
      await user.update(..., { transaction });
      await transaction.commit();
      } catch(err) {
      await transaction.rollback();
      }
      })

      A syntax for automatically committing or rolling back based on the promise chain resolution is also supported:

      try {
      await sequelize.transaction(transaction => { // Note that we pass a callback rather than awaiting the call with no arguments
      const user = await User.findOne(..., {transaction});
      await user.update(..., {transaction});
      });
      // Committed
      } catch(err) {
      // Rolled back
      console.error(err);
      }

      If you have CLS 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:

      const cls = require('cls-hooked');
      const namespace = cls.createNamespace('....');
      const Sequelize = require('sequelize');
      Sequelize.useCLS(namespace);

      Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace

      Type Parameters

      • T

      Parameters

      • autoCallback: (t: Transaction) => PromiseLike<T>

        Callback for the transaction

      Returns Promise<T>

    • 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

        try {
      const transaction = await sequelize.transaction();
      const user = await User.findOne(..., { transaction });
      await user.update(..., { transaction });
      await transaction.commit();
      } catch(err) {
      await transaction.rollback();
      }
      })

      A syntax for automatically committing or rolling back based on the promise chain resolution is also supported:

      try {
      await sequelize.transaction(transaction => { // Note that we pass a callback rather than awaiting the call with no arguments
      const user = await User.findOne(..., {transaction});
      await user.update(..., {transaction});
      });
      // Committed
      } catch(err) {
      // Rolled back
      console.error(err);
      }

      If you have CLS 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:

      const cls = require('cls-hooked');
      const namespace = cls.createNamespace('....');
      const Sequelize = require('sequelize');
      Sequelize.useCLS(namespace);

      Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace

      Parameters

      • Optionaloptions: TransactionOptions

        Transaction Options

      Returns Promise<Transaction>

    • Truncate all tables defined through the sequelize models. This is done by calling Model.truncate() on each model.

      Parameters

      • Optionaloptions: DestroyOptions<any>

        The options passed to Model.destroy in addition to truncate

      Returns Promise<unknown[]>

    • Parameters

      • Optionaloptions: QueryOptions

      Returns Promise<void>

    • Add a hook to the model

      Type Parameters

      • H extends Hooks<Model<any, any>, any, any>
      • K extends keyof SequelizeHooks<H["_model"], Attributes<H>, CreationAttributes<H>>

      Parameters

      • this: HooksStatic<H>
      • hookType: K
      • name: string

        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.

      • fn: SequelizeHooks<H["_model"], Attributes<H>, CreationAttributes<H>>[K]

      Returns HooksCtor<H>

    • Add a hook to the model

      Type Parameters

      • H extends Hooks<Model<any, any>, any, any>
      • K extends keyof SequelizeHooks<H["_model"], Attributes<H>, CreationAttributes<H>>

      Parameters

      • this: HooksStatic<H>
      • hookType: K
      • fn: SequelizeHooks<H["_model"], Attributes<H>, CreationAttributes<H>>[K]

      Returns HooksCtor<H>

    • A hook that is run after creating instances in bulk

      Parameters

      • name: string
      • fn: (instances: Model<any, any>[], options: BulkCreateOptions<any>) => void

        A callback function that is called with instances, options

      Returns void

    • A hook that is run after creating instances in bulk

      Parameters

      • fn: (instances: Model<any, any>[], options: BulkCreateOptions<any>) => void

        A callback function that is called with instances, options

      Returns void

    • A hook that is run after destroying instances in bulk

      Parameters

      • name: string
      • fn: (options: DestroyOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run after destroying instances in bulk

      Parameters

      • fn: (options: DestroyOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run after sequelize.sync call

      Parameters

      • name: string
      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to sequelize.sync

      Returns void

    • A hook that is run after sequelize.sync call

      Parameters

      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to sequelize.sync

      Returns void

    • A hook that is run after updating instances in bulk

      Parameters

      • name: string
      • fn: (options: UpdateOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run after updating instances in bulk

      Parameters

      • fn: (options: UpdateOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run after a connection is established

      Parameters

      • name: string
      • fn: (connection: unknown, options: Config) => void

        A callback function that is called with options

      Returns void

    • A hook that is run after a connection is established

      Parameters

      • fn: (connection: unknown, options: Config) => void

        A callback function that is called with options

      Returns void

    • A hook that is run after creating a single instance

      Parameters

      • name: string
      • fn: (attributes: Model, options: CreateOptions<any>) => void

        A callback function that is called with attributes, options

      Returns void

    • A hook that is run after creating a single instance

      Parameters

      • fn: (attributes: Model, options: CreateOptions<any>) => void

        A callback function that is called with attributes, options

      Returns void

    • A hook that is run after a define call

      Parameters

      • name: string
      • fn: (model: ModelType) => void

        A callback function that is called with factory

      Returns void

    • A hook that is run after a define call

      Parameters

      • fn: (model: ModelType) => void

        A callback function that is called with factory

      Returns void

    • A hook that is run after destroying a single instance

      Parameters

      • name: string
      • fn: (instance: Model, options: InstanceDestroyOptions) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run after destroying a single instance

      Parameters

      • fn: (instance: Model, options: InstanceDestroyOptions) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run after a connection is released

      Parameters

      • name: string
      • fn: (connection: unknown) => void

        A callback function that is called with options

      Returns void

    • A hook that is run after a connection is released

      Parameters

      • fn: (connection: unknown) => void

        A callback function that is called with options

      Returns void

    • A hook that is run after a find (select) query

      Parameters

      • name: string
      • fn: (
            instancesOrInstance: Model<any, any> | Model<any, any>[] | null,
            options: FindOptions<any>,
        ) => void

        A callback function that is called with instance(s), options

      Returns void

    • A hook that is run after a find (select) query

      Parameters

      • fn: (
            instancesOrInstance: Model<any, any> | Model<any, any>[] | null,
            options: FindOptions<any>,
        ) => void

        A callback function that is called with instance(s), options

      Returns void

    • A hook that is run after Sequelize() call

      Parameters

      • name: string
      • fn: (sequelize: Sequelize) => void

        A callback function that is called with sequelize

      Returns void

    • A hook that is run after Sequelize() call

      Parameters

      • fn: (sequelize: Sequelize) => void

        A callback function that is called with sequelize

      Returns void

    • A hook that is run after successfully acquiring a connection from the pool

      Parameters

      • name: string
      • fn: (connection: object, options: GetConnectionOptions) => void

        A callback function that is called with options

      Returns void

    • A hook that is run after successfully acquiring a connection from the pool

      Parameters

      • fn: (connection: object, options: GetConnectionOptions) => void

        A callback function that is called with options

      Returns void

    • A hook that is run after creating or updating a single instance, It proxies afterCreate and afterUpdate

      Parameters

      • name: string
      • fn: (instance: Model, options: CreateOptions<any> | UpdateOptions<any>) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run after creating or updating a single instance, It proxies afterCreate and afterUpdate

      Parameters

      • fn: (instance: Model, options: CreateOptions<any> | UpdateOptions<any>) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run after Model.sync call

      Parameters

      • name: string
      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to Model.sync

      Returns void

    • A hook that is run after Model.sync call

      Parameters

      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to Model.sync

      Returns void

    • A hook that is run after updating a single instance

      Parameters

      • name: string
      • fn: (instance: Model, options: UpdateOptions<any>) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run after updating a single instance

      Parameters

      • fn: (instance: Model, options: UpdateOptions<any>) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run after validation

      Parameters

      • name: string
      • fn: (instance: Model, options: ValidationOptions) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run after validation

      Parameters

      • fn: (instance: Model, options: ValidationOptions) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run before creating instances in bulk

      Parameters

      • name: string
      • fn: (instances: Model<any, any>[], options: BulkCreateOptions<any>) => void

        A callback function that is called with instances, options

      Returns void

    • A hook that is run before creating instances in bulk

      Parameters

      • fn: (instances: Model<any, any>[], options: BulkCreateOptions<any>) => void

        A callback function that is called with instances, options

      Returns void

    • A hook that is run before destroying instances in bulk

      Parameters

      • name: string
      • fn: (options: BulkCreateOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before destroying instances in bulk

      Parameters

      • fn: (options: BulkCreateOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before sequelize.sync call

      Parameters

      • dname: string
      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to sequelize.sync

      Returns void

    • A hook that is run before sequelize.sync call

      Parameters

      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to sequelize.sync

      Returns void

    • A hook that is run after updating instances in bulk

      Parameters

      • name: string
      • fn: (options: UpdateOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run after updating instances in bulk

      Parameters

      • fn: (options: UpdateOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before a connection is established

      Parameters

      • name: string
      • fn: (options: DeepWriteable<Config>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before a connection is established

      Parameters

      • fn: (options: DeepWriteable<Config>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before creating a single instance

      Parameters

      • name: string
      • fn: (attributes: Model, options: CreateOptions<any>) => void

        A callback function that is called with attributes, options

      Returns void

    • A hook that is run before creating a single instance

      Parameters

      • fn: (attributes: Model, options: CreateOptions<any>) => void

        A callback function that is called with attributes, options

      Returns void

    • A hook that is run before a define call

      Type Parameters

      • M extends Model<any, any>

      Parameters

      • name: string
      • fn: (
            attributes: ModelAttributes<M, CreationAttributes<M>>,
            options: ModelOptions<M>,
        ) => void

        A callback function that is called with attributes, options

      Returns void

    • A hook that is run before a define call

      Type Parameters

      • M extends Model<any, any>

      Parameters

      • fn: (
            attributes: ModelAttributes<M, CreationAttributes<M>>,
            options: ModelOptions<M>,
        ) => void

        A callback function that is called with attributes, options

      Returns void

    • A hook that is run before destroying a single instance

      Parameters

      • name: string
      • fn: (instance: Model, options: InstanceDestroyOptions) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run before destroying a single instance

      Parameters

      • fn: (instance: Model, options: InstanceDestroyOptions) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run before a connection is released

      Parameters

      • name: string
      • fn: (connection: unknown) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before a connection is released

      Parameters

      • fn: (connection: unknown) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before a find (select) query

      Parameters

      • name: string
      • fn: (options: FindOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before a find (select) query

      Parameters

      • fn: (options: FindOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded

      Parameters

      • name: string
      • fn: (options: FindOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded

      Parameters

      • fn: (options: FindOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before a find (select) query, after all option parsing is complete

      Parameters

      • name: string
      • fn: (options: FindOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before a find (select) query, after all option parsing is complete

      Parameters

      • fn: (options: FindOptions<any>) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before Sequelize() call

      Parameters

      • name: string
      • fn: (config: Config, options: Options) => void

        A callback function that is called with config, options

      Returns void

    • A hook that is run before Sequelize() call

      Parameters

      • fn: (config: Config, options: Options) => void

        A callback function that is called with config, options

      Returns void

    • A hook that is run before attempting to acquire a connection from the pool

      Parameters

      • name: string
      • fn: (options: GetConnectionOptions) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before attempting to acquire a connection from the pool

      Parameters

      • fn: (options: GetConnectionOptions) => void

        A callback function that is called with options

      Returns void

    • A hook that is run before creating or updating a single instance, It proxies beforeCreate and beforeUpdate

      Parameters

      • name: string
      • fn: (instance: Model, options: CreateOptions<any> | UpdateOptions<any>) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run before creating or updating a single instance, It proxies beforeCreate and beforeUpdate

      Parameters

      • fn: (instance: Model, options: CreateOptions<any> | UpdateOptions<any>) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run before Model.sync call

      Parameters

      • name: string
      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to Model.sync

      Returns void

    • A hook that is run before Model.sync call

      Parameters

      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to Model.sync

      Returns void

    • A hook that is run before updating a single instance

      Parameters

      • name: string
      • fn: (instance: Model, options: UpdateOptions<any>) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run before updating a single instance

      Parameters

      • fn: (instance: Model, options: UpdateOptions<any>) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run before validation

      Parameters

      • name: string
      • fn: (instance: Model, options: ValidationOptions) => void

        A callback function that is called with instance, options

      Returns void

    • A hook that is run before validation

      Parameters

      • fn: (instance: Model, options: ValidationOptions) => void

        A callback function that is called with instance, options

      Returns void

    • Check whether the mode has any hooks of this type

      Type Parameters

      • H extends Hooks<Model<any, any>, any, any>

      Parameters

      • this: HooksStatic<H>
      • hookType: keyof SequelizeHooks<H["_model"], Attributes<H>, CreationAttributes<H>>

      Returns boolean

    • Type Parameters

      • H extends Hooks<Model<any, any>, any, any>

      Parameters

      • this: HooksStatic<H>
      • hookType: keyof SequelizeHooks<H["_model"], Attributes<H>, CreationAttributes<H>>

      Returns boolean

    • Remove hook from the model

      Type Parameters

      • H extends Hooks<Model<any, any>, any, any>

      Parameters

      • this: HooksStatic<H>
      • hookType: keyof SequelizeHooks<H["_model"], Attributes<H>, CreationAttributes<H>>
      • name: string

      Returns HooksCtor<H>

    • Use CLS with Sequelize. CLS namespace provided is stored as Sequelize._cls and Promise is patched to use the namespace, using cls-hooked module.

      Parameters

      • namespace: object

      Returns typeof Sequelize