### Start pgAdmin4 Docker Instance Source: https://sequelize.org/api/v7/media/CONTRIBUTING.md Launches a pgAdmin4 Docker container, accessible at localhost:8888, for inspecting the PostgreSQL test database. Requires Docker to be installed. ```bash docker run -d --name pgadmin4 -p 8888:80 -e 'PGADMIN_DEFAULT_EMAIL=test@example.com' -e 'PGADMIN_DEFAULT_PASSWORD=sequelize_test' dpage/pgadmin4 ``` -------------------------------- ### Install Node.js Dependencies Source: https://sequelize.org/api/v7/media/CONTRIBUTING.md Install project dependencies using Yarn and then build the project. ```bash yarn install yarn build ``` -------------------------------- ### Start PostgreSQL Docker Container Source: https://sequelize.org/api/v7/media/CONTRIBUTING.md Starts a Docker container for PostgreSQL. Use 'oldest' for version 11 or 'latest' for version 15. ```bash yarn start-postgres-oldest ``` ```bash yarn start-postgres-latest ``` -------------------------------- ### Start MariaDB Docker Container Source: https://sequelize.org/api/v7/media/CONTRIBUTING.md Starts a Docker container for MariaDB. Use 'oldest' for version 10.4 or 'latest' for version 11.3. ```bash yarn start-mariadb-oldest ``` ```bash yarn start-mariadb-latest ``` -------------------------------- ### Start MySQL Docker Container Source: https://sequelize.org/api/v7/media/CONTRIBUTING.md Starts a Docker container for MySQL. Use 'oldest' for version 8.0 or 'latest' for version 8.3. ```bash yarn start-mysql-oldest ``` ```bash yarn start-mysql-latest ``` -------------------------------- ### Sequelize Constructor Options Examples Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.SequelizeTypeScript.html Provides a comprehensive example of various options available when instantiating Sequelize, including dialect-specific settings, logging, storage, and pool configuration. Refer to your specific dialect's documentation for detailed option information. ```typescript import { MsSqlDialect } from '@sequelize/mssql'; import { IsolationLevel } from 'sequelize'; 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 }) ``` -------------------------------- ### addConstraint Examples Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.AbstractQueryInterfaceTypeScript.html Examples demonstrating how to add various types of constraints to a table using Sequelize's query interface. ```APIDOC ## addConstraint Examples This section provides examples for adding different types of constraints to a table. ### UNIQUE Constraint ```javascript queryInterface.addConstraint('Users', { fields: ['email'], type: 'UNIQUE', name: 'custom_unique_constraint_name' }); ``` ### CHECK Constraint ```javascript queryInterface.addConstraint('Users', { fields: ['roles'], type: 'CHECK', where: { roles: ['user', 'admin', 'moderator', 'guest'] } }); ``` ### DEFAULT Constraint (MSSQL only) ```javascript queryInterface.addConstraint('Users', { fields: ['roles'], type: 'DEFAULT', defaultValue: 'guest' }); ``` ### PRIMARY KEY Constraint ```javascript queryInterface.addConstraint('Users', { fields: ['username'], type: 'PRIMARY KEY', name: 'custom_primary_constraint_name' }); ``` ### Composite PRIMARY KEY Constraint ```javascript queryInterface.addConstraint('Users', { fields: ['first_name', 'last_name'], type: 'PRIMARY KEY', name: 'custom_primary_constraint_name' }); ``` ### FOREIGN KEY Constraint ```javascript queryInterface.addConstraint('Posts', { fields: ['username'], type: 'FOREIGN KEY', name: 'custom_fkey_constraint_name', references: { table: 'target_table_name', field: 'target_column_name' }, onDelete: 'cascade', onUpdate: 'cascade' }); ``` ### Composite FOREIGN KEY Constraint ```javascript queryInterface.addConstraint('TableName', { fields: ['source_column_name', 'other_source_column_name'], type: 'FOREIGN KEY', name: 'custom_fkey_constraint_name', references: { table: 'target_table_name', fields: ['target_column_name', 'other_target_column_name'] }, onDelete: 'cascade', onUpdate: 'cascade' }); ``` ``` -------------------------------- ### Start Db2 Docker Container Source: https://sequelize.org/api/v7/media/CONTRIBUTING.md Starts a Docker container for Db2. Use 'oldest' for version 11.5.5.1 or 'latest' for version 11.5.9.0. ```bash yarn start-db2-oldest ``` ```bash yarn start-db2-latest ``` -------------------------------- ### Start MSSQL Docker Container Source: https://sequelize.org/api/v7/media/CONTRIBUTING.md Starts a Docker container for MSSQL. Use 'oldest' for version 2017 or 'latest' for version 2022. ```bash yarn start-mssql-oldest ``` ```bash yarn start-mssql-latest ``` -------------------------------- ### Example of using attributes with include Source: https://sequelize.org/api/v7/interfaces/_sequelize_core.index._internal_.IncludeOptionsWithMap.html Demonstrates how to include additional attributes for aggregations when using the `include` option. This example shows how to count a specific attribute and alias it. ```javascript { attributes: { include: [[literal('COUNT(id)'), 'total']] } ``` -------------------------------- ### Start and Manage Unmanaged Transaction Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.Sequelize.html Use this method to manually start a transaction. You must explicitly commit or rollback the transaction. Transactions started this way are not automatically passed to queries. ```javascript try { const transaction = await sequelize.startUnmanagedTransaction(); const user = await User.findOne(..., { transaction }); await user.update(..., { transaction }); await transaction.commit(); } catch(err) { await transaction.rollback(); } ``` -------------------------------- ### Order Option Example Source: https://sequelize.org/api/v7/interfaces/_sequelize_core.index.BelongsToManyAddAssociationsMixinOptions.html This example shows how to specify an ordering for query results using an array. The attribute will be escaped, but the direction will not. ```javascript `order: [['name', 'DESC']]`. ``` -------------------------------- ### Get Sequelize Version Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.Sequelize.html Returns the installed version string of the Sequelize library. ```javascript Sequelize.version ``` -------------------------------- ### startTransactionQuery Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.AbstractQueryGenerator.html Returns a query that starts a transaction. ```APIDOC ## startTransactionQuery ### Description Returns a query that starts a transaction. ### Method `startTransactionQuery(options?: StartTransactionQueryOptions): string` ### Parameters * `options` (StartTransactionQueryOptions) - Optional. Options for starting the transaction. ### Returns string - The SQL query string. ``` -------------------------------- ### Order Option Example Source: https://sequelize.org/api/v7/interfaces/_sequelize_core.index.BelongsToManySetAssociationsMixinOptions.html Demonstrates the usage of the 'order' option with an array of attribute and direction. ```javascript `order: [['name', 'DESC']]` ``` -------------------------------- ### STRING Data Type Example Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.STRING.html Demonstrates how to instantiate the STRING data type with a specified length. ```javascript DataTypes.STRING(255) ``` -------------------------------- ### StartTransactionQueryOptions Interface Source: https://sequelize.org/api/v7/interfaces/_sequelize_core.index.StartTransactionQueryOptions.html Defines the options that can be passed when starting a transaction. ```APIDOC ## Interface: StartTransactionQueryOptions ### Description This interface defines the optional properties that can be provided when starting a transaction in Sequelize. These options allow for customization of transaction behavior, such as read-only mode, transaction naming, and transaction type. ### Properties #### `readOnly` - **Type**: `boolean` - **Optional**: Yes - **Description**: If true, the transaction will be marked as read-only. #### `transactionName` - **Type**: `string` - **Optional**: Yes - **Description**: An optional name for the transaction, useful for debugging and identification. #### `transactionType` - **Type**: `TransactionType` - **Optional**: Yes - **Description**: Specifies the type of the transaction. The exact values depend on the `TransactionType` enum definition. ``` -------------------------------- ### options Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.AbstractQueryGenerator.html Gets the options for the query generator. ```APIDOC ## `Protected`options * get options(): NormalizedOptions #### Returns NormalizedOptions ``` -------------------------------- ### get Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.Model.html Retrieves all values of the instance or a specific field. ```APIDOC ## get ### Description Retrieves all values of the instance, including virtual getters, or a specific field's value. If `options.clone` is true, a copy of the instance data is returned. ### Method `get(options?: ModelGetOptions): TModelAttributes` ### Parameters * `options` (ModelGetOptions) - Optional. Options for retrieving instance data. ### Returns * `TModelAttributes` - An object containing all instance values. ## get> (specific key) ### Description Retrieves the value of a specific field or virtual getter from the instance. ### Method `get>(key: K, options?: ModelGetOptions): Model[K]` ### Type Parameters * `K` - The type of the key, extending the keys of the Model. ### Parameters * `key` (K) - The key of the field to retrieve. * `options` (ModelGetOptions) - Optional. Options for retrieving instance data. ### Returns * `Model[K]` - The value of the specified field or virtual getter. ``` -------------------------------- ### get Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.BelongsToManyAssociation.html Retrieves all associated instances for a given source instance. Supports an optional where clause and other find options. ```APIDOC ## get ### Description Gets everything currently associated with this, using an optional where clause. ### Method `get(instance: SourceModel, options?: BelongsToManyGetAssociationsMixinOptions): Promise` ### Parameters #### Path Parameters * **instance** (SourceModel) - The source instance. * **options** (BelongsToManyGetAssociationsMixinOptions) - Optional. Find options. See Model for a full explanation of options. ### Returns * Promise - A promise that resolves with an array of associated target instances. ``` -------------------------------- ### BelongsToManyAddAssociationsMixin Usage Example Source: https://sequelize.org/api/v7/types/_sequelize_core.index.BelongsToManyAddAssociationsMixin.html This example demonstrates how to declare and use the `addRoles` mixin, which is an instance of BelongsToManyAddAssociationsMixin, within a User model. It shows the typical setup for a belongsToMany relationship. ```typescript class User extends Model, InferCreationAttributes> { declare addRoles: BelongsToManyAddAssociationsMixin; } User.belongsToMany(Role, { through: UserRole }); ``` -------------------------------- ### BelongsToManyGetAssociationsMixin Usage Example Source: https://sequelize.org/api/v7/types/_sequelize_core.index.BelongsToManyGetAssociationsMixin.html This example demonstrates how to use the BelongsToManyGetAssociationsMixin to define and access associated roles for a User model. ```typescript class User extends Model, InferCreationAttributes> { declare getRoles: BelongsToManyGetAssociationsMixin; } User.belongsToMany(Role, { through: UserRole }); ``` -------------------------------- ### Run SSCCE for a Specific Dialect Source: https://sequelize.org/api/v7/media/CONTRIBUTING.md Execute the Single-File Source Code Example (SSCCE) for a chosen database dialect. Database instances must be set up prior to running. ```bash npm run sscce-mariadb ``` ```bash yarn sscce-mariadb ``` ```bash npm run sscce-mysql ``` ```bash yarn sscce-mysql ``` ```bash npm run sscce-postgres ``` ```bash yarn sscce-postgres ``` ```bash npm run sscce-sqlite3 ``` ```bash yarn sscce-sqlite3 ``` ```bash npm run sscce-mssql ``` ```bash yarn sscce-mssql ``` ```bash npm run sscce-db2 ``` ```bash yarn sscce-db2 ``` -------------------------------- ### Conventional Commit Message Example Source: https://sequelize.org/api/v7/media/CONTRIBUTING.md Example of a commit message following the Conventional Commits specification, including a type and scope. ```git feat(postgres): support specifying a custom name for enums ``` -------------------------------- ### Sequelize Constructor Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.Sequelize.html Initializes a new Sequelize instance. This is the primary way to connect to your database and start using Sequelize. ```APIDOC ## constructor Sequelize ### Description Initializes a new Sequelize instance. ### Parameters * **options**: Options - Configuration options for the Sequelize instance, including database connection details. ### Returns Sequelize - A new Sequelize instance. ``` -------------------------------- ### Instantiate Sequelize with Database, Username, and Password Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.SequelizeTypeScript.html Instantiates Sequelize using database credentials provided directly in the options object. Ensure you import the correct dialect class. ```typescript import { PostgresDialect } from '@sequelize/postgres'; // with database, username, and password in the options object const sequelize = new Sequelize({ database, user, password, dialect: PostgresDialect }); ``` -------------------------------- ### run Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.AbstractQuery.html Executes a raw SQL query with optional parameters and options. ```APIDOC ## run ### Description Executes a raw SQL query with optional parameters and options. ### Method Public ### Parameters - **_sql** (string) - The SQL query to execute. - **_parameters** (unknown) - Optional - Parameters for the SQL query. - **_options** (unknown) - Optional - Options for the query execution. ### Returns Promise ``` -------------------------------- ### BelongsToMany Get Associations Mixin Options Source: https://sequelize.org/api/v7/interfaces/_sequelize_core.index.BelongsToManyGetAssociationsMixinOptions.html Options that can be passed to the `get` mixin of a BelongsToMany association to customize the retrieval of associated records. ```APIDOC ## `Optional`limit limit?: number | Nullish | Literal Limits how many items will be retrieved by the operation. If `limit` and `include` are used together, Sequelize will turn the `subQuery` option on by default. This is done to ensure that `limit` only impacts the Model on the same level as the `limit` option. You can disable this behavior by explicitly setting `subQuery: false`, however `limit` will then affect the total count of returned values, including eager-loaded associations, instead of just one table. #### Example ``` // in the following query, `limit` only affects the "User" model. // This will return 2 users, each including all of their projects. User.findAll({ limit: 2, include: [User.associations.projects] }); ``` #### Example ``` // in the following query, `limit` affects the total number of returned values, eager-loaded associations included. // This may return 2 users, each with one project, // or 1 user with 2 projects. User.findAll({ limit: 2, include: [User.associations.projects], subQuery: false, }); ``` ## `Optional`lock lock?: boolean | Lock | { level: Lock; of: ModelStatic> } Lock the selected rows. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE. Postgres also supports transaction.LOCK.KEY_SHARE, transaction.LOCK.NO_KEY_UPDATE and specific model locks with joins. See Lock. ## `Optional`logging logging?: false | (sql: string, timing?: number) => void A function that gets executed while running the query to log the sql. ## `Optional`mapToModel mapToModel?: boolean Map returned fields to model's fields if `options.model` or `options.instance` is present. Mapping will occur before building the model instance. ## `Optional`maxExecutionTimeHintMs maxExecutionTimeHintMs?: number This sets the max execution time for MySQL. ## `Optional`minifyAliases minifyAliases?: boolean Controls whether aliases are minified in this query. This overrides the global option ## `Optional`nest nest?: boolean If true, transforms objects with `.` separated property names into nested objects using dottie.js. For example `{ 'user.username': 'john' }` becomes `{ user: { username: 'john' }}`. When `nest` is true, the query type is assumed to be `'SELECT'`, unless otherwise specified #### Default ``` false ``` ## `Optional`offset offset?: number | Nullish | Literal Skip the first n items of the results. ## `Optional`order order?: Order Specifies an ordering. If a string is provided, it will be escaped. Using an array, you can provide several attributes / functions to order by. Each element can be further wrapped in a two-element array: * The first element is the column / function to order by, * the second is the direction. #### Example ``` `order: [['name', 'DESC']]`. The attribute will be escaped, but the direction will not. ``` ## `Optional`paranoid paranoid?: boolean If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will be returned. Only applies if InitOptions.paranoid is true for the model. #### Default ``` true ``` ## `Optional`plain plain?: boolean Sets the query type to `SELECT` and return a single row ## `Optional`raw raw?: boolean Return raw result. See Sequelize#query for more information. ## `Optional`rejectOnEmpty rejectOnEmpty?: boolean | Error Throws an error if the query would return 0 results. ## `Optional`replacements replacements?: BindOrReplacements Either an object of named parameter replacements in the format `:param` or an array of unnamed replacements to replace `?` in your SQL. ## `Optional`retry retry?: Options ## `Optional`schema schema?: string Apply a schema on the related model ## `Optional`schemaDelimiter schemaDelimiter?: string ## `Optional`scope scope?: string | boolean Apply a scope on the related model, or remove its default scope by passing false. ## `Optional`searchPath searchPath?: string An optional parameter to specify the schema search_path (Postgres only) ## `Optional`skipLocked skipLocked?: boolean Skip locked rows. Only supported in Postgres. ## `Optional`subQuery subQuery?: boolean Use sub queries (internal). If unspecified, this will `true` by default if `limit` is specified, and `false` otherwise. See FindOptions#limit for more information. ## `Optional`supportsSearchPath supportsSearchPath?: boolean If false do not prepend the query with the search_path (Postgres only) ## `Optional`tableHints tableHints?: TableHints[] Use a table hint for the query, only supported in MSSQL. ## `Optional`through through?: { paranoid?: boolean; where?: WhereOptions } ``` -------------------------------- ### BelongsToManyHasAssociationMixin Usage Example Source: https://sequelize.org/api/v7/types/_sequelize_core.index.BelongsToManyHasAssociationMixin.html This example demonstrates how to declare and use the `hasRole` mixin, which is an instance of BelongsToManyHasAssociationMixin, within a User model that has a belongsToMany relationship with the Role model. ```typescript class User extends Model, InferCreationAttributes> { declare hasRole: BelongsToManyHasAssociationMixin; } User.belongsToMany(Role, { through: UserRole }); ``` -------------------------------- ### constructor Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.AbstractConnectionManager.html Initializes a new instance of the AbstractConnectionManager class. ```APIDOC ## constructor * new AbstractConnectionManager< Dialect extends AbstractDialect = AbstractDialect, TConnection extends AbstractConnection = AbstractConnection, >( dialect: Dialect, ): AbstractConnectionManager #### Type Parameters * Dialect extends AbstractDialect = AbstractDialect * TConnection extends AbstractConnection = AbstractConnection #### Parameters * dialect: Dialect #### Returns AbstractConnectionManager ``` -------------------------------- ### Start Managed Transaction with Disabled Auto-Passing Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.Sequelize.html Starts a managed transaction where Sequelize does not automatically pass the transaction to queries. You must manually provide the transaction object to your queries. ```javascript 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 }); }); ``` -------------------------------- ### Getting Model Instance Attributes Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.Model.html The `get` method retrieves instance data. Without arguments, it returns all values, potentially cloned. With a key, it returns the specific attribute's value or calls a virtual getter. ```javascript instance.get() instance.get('key') instance.get({ clone: true }) ``` -------------------------------- ### Configure Replication Source: https://sequelize.org/api/v7/interfaces/_sequelize_core.index._internal_.SequelizeCoreOptions.html Enable read/write replication by providing an object with `read` and `write` properties. `write` specifies a single server for writes, and `read` is an array of servers for reads. Connection details like host, port, username, password, and database can be configured for each server. ```javascript new Sequelize({ // ... other options replication: { write: { host: 'localhost', username: 'root', password: 'password', database: 'database_write' }, read: [ { host: 'localhost', username: 'root', password: 'password', database: 'database_read' } ] } }); ``` -------------------------------- ### Instantiate Sequelize with URL Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.SequelizeTypeScript.html Instantiates Sequelize using a database connection URL. This is a convenient way to configure your connection. Ensure you import the correct dialect class. ```typescript import { MySqlDialect } from '@sequelize/mysql'; const sequelize = new Sequelize({ dialect: MySqlDialect, url: 'mysql://localhost:3306/database', }) ``` -------------------------------- ### beforeCount Source: https://sequelize.org/api/v7/interfaces/_sequelize_core.index._internal_.ModelHooks.html Hook that runs at the start of Model.count. ```APIDOC ## beforeCount ### Description A hook that is run at the start of Model.count. ### Parameters * **options**: WritableObjectDeep> ### Returns AsyncHookReturn ``` -------------------------------- ### Run All Dialect Tests Sequentially Source: https://sequelize.org/api/v7/media/CONTRIBUTING.md Execute tests for all supported dialects sequentially. Ensure database instances are set up beforehand. ```bash DIALECT=mariadb yarn mocha && DIALECT=mysql yarn mocha && DIALECT=postgres yarn mocha && DIALECT=sqlite3 yarn mocha && DIALECT=mssql yarn mocha && DIALECT=db2 yarn mocha ``` -------------------------------- ### init Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.ModelTypeScript.html Initializes a model, defining its attributes and options for database interaction. This is a core method for setting up models. ```APIDOC ## `Static`init ### Description Initialize a model, representing a table in the DB, with attributes and options. The table columns are defined by the hash that is given as the first argument. Each attribute of the hash represents a column. ### Method `init, MS extends ModelStatic>(this: MS, attributes: ModelAttributes, BrandedKeysOf, typeof ForeignKeyBrand>>>, options: InitOptions): MS` ### Parameters #### `attributes` - **type**: `ModelAttributes, BrandedKeysOf, typeof ForeignKeyBrand>>>` - **description**: 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. #### `options` - **type**: `InitOptions` - **description**: These options are merged with the default define options provided to the Sequelize constructor ### Returns `MS` ### Example ```javascript Project.init({ columnA: { type: DataTypes.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: DataTypes.STRING, columnC: 'MY VERY OWN COLUMN TYPE' }, {sequelize}) ``` ### See - https://sequelize.org/docs/v7/core-concepts/model-basics/ - https://sequelize.org/docs/v7/core-concepts/validations-and-constraints/ ``` -------------------------------- ### MapView.size Source: https://sequelize.org/api/v7/classes/_sequelize_utils.common.MapView.html Gets the number of elements in the MapView. ```APIDOC ## size ### Description Returns the number of elements in the Map. ### Signature `get size(): number` ### Returns `number` - The number of elements in the Map. ``` -------------------------------- ### _startTransaction Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.AbstractQueryInterface.html Begins a new transaction. This is an internal method. ```APIDOC ### _startTransaction * _startTransaction( transaction: Transaction, options: StartTransactionOptions, ): Promise Begin a new transaction. This is an internal method used by `sequelize.transaction()` use at your own risk. #### Parameters * transaction: Transaction * options: StartTransactionOptions #### Returns Promise ``` -------------------------------- ### constructor Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.AbstractQueryGeneratorTypeScript.html Initializes a new instance of the AbstractQueryGeneratorTypeScript class. ```APIDOC ## constructor * new AbstractQueryGeneratorTypeScript = AbstractDialect>( dialect: Dialect, internals?: AbstractQueryGeneratorInternal, ): AbstractQueryGeneratorTypeScript #### Type Parameters * Dialect extends AbstractDialect = AbstractDialect #### Parameters * dialect: Dialect * internals: AbstractQueryGeneratorInternal = ... #### Returns AbstractQueryGeneratorTypeScript ``` -------------------------------- ### sequelize accessor Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.AbstractQueryGeneratorInternal.html Gets the Sequelize instance. ```APIDOC ## sequelize ### Description Gets the Sequelize instance. ### Returns Sequelize ``` -------------------------------- ### beforeInit Hook Source: https://sequelize.org/api/v7/interfaces/_sequelize_core.index._internal_.StaticSequelizeHooks.html The beforeInit hook is executed before the Sequelize instance creation process begins. It receives initialization options as an argument. ```APIDOC ## beforeInit ### Description A hook that is run at the beginning of the creation of a Sequelize instance. ### Method void ### Parameters #### options * **options** (Options>) - Description of the options parameter ### Returns void ``` -------------------------------- ### beforeSync Hook Source: https://sequelize.org/api/v7/interfaces/_sequelize_core.index._internal_.SequelizeHooks.html A hook that is run at the start of Model.sync. ```APIDOC ## beforeSync ### Description A hook that is run at the start of Model.sync. ### Parameters * `options`: SyncOptions - Options for the sync operation. ### Returns AsyncHookReturn ``` -------------------------------- ### Instance Methods Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.Sequelize.html Core instance methods for managing models, database connections, and schemas. ```APIDOC ### addModels * addModels(models: ModelStatic[]): void #### Parameters * models: ModelStatic[] #### Returns void ### authenticate * authenticate(options?: QueryOptions): Promise Test the connection by trying to authenticate #### Parameters * `Optional`options: QueryOptions Query Options for authentication #### Returns Promise ### close * close(): Promise Close all connections used by this sequelize instance, and free all references so the instance can be garbage collected. Normally this is done on process exit, so you only need to call this method if you are creating multiple instances, and want to garbage collect some of them. #### Returns Promise ### createSchema * createSchema(schema: string, options?: CreateSchemaOptions): Promise Alias of AbstractQueryInterface#createSchema #### Parameters * schema: string Name of the schema * `Optional`options: CreateSchemaOptions #### Returns Promise ### define * define, TAttributes = Attributes>( modelName: string, attributes?: ModelAttributes, options?: ModelOptions, ): ModelStatic 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: DataTypes.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: DataTypes.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 Copy ``` 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/docs/v7/other-topics/other-data-types For more about getters and setters, see https://sequelize.org/docs/v7/core-concepts/getters-setters-virtuals/ For more about instance and class methods, see https://sequelize.org/docs/v7/core-concepts/model-basics/#taking-advantage-of-models-being-classes For more about validation, see https://sequelize.org/docs/v7/core-concepts/validations-and-constraints/ ``` -------------------------------- ### beforeBulkSync Source: https://sequelize.org/api/v7/interfaces/_sequelize_core.index._internal_.SequelizeHooks.html A hook that is run at the start of Sequelize#sync. ```APIDOC ## beforeBulkSync ### Description A hook that is run at the start of Sequelize#sync. ### Signature beforeBulkSync(options: SyncOptions): AsyncHookReturn ### Parameters * **options** (SyncOptions) - Options passed to the sync method. ### Returns AsyncHookReturn ``` -------------------------------- ### ENUM Constructor Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.ENUM.html Demonstrates the different ways to instantiate the ENUM class, accepting values as an array, variadic arguments, or an options object. ```APIDOC ## `new ENUM(options: EnumOptions)` ### Description Instantiates a new ENUM object with the provided options. ### Parameters * `options` (EnumOptions) - Either an array of values or an options object with a `values` array. It also supports variadic values. ### Returns * `ENUM` ## `new ENUM(members: EnumValues)` ### Description Instantiates a new ENUM object with the provided array of members. ### Parameters * `members` (EnumValues) - An array of enum member values. ### Returns * `ENUM` ## `new ENUM(...members: Member[])` ### Description Instantiates a new ENUM object with the provided variadic member values. ### Parameters * `...members` (Member[]) - A list of enum member values. ### Returns * `ENUM` ``` -------------------------------- ### get Method Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.ModelSetView.html Retrieves a model from the set by its name. ```APIDOC ## get = Model>(modelName: string): undefined | ModelStatic ### Description Retrieves a model from the set by its name. ### Parameters * **modelName**: string - The name of the model to retrieve. ### Returns undefined | ModelStatic - The model if found, otherwise undefined. ``` -------------------------------- ### RANGE Constructor and Usage Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.RANGE.html Demonstrates how to instantiate the RANGE data type with different subtypes and provides an example of its usage in Sequelize. ```APIDOC ## Class RANGE Range types are data types representing a range of values of some element type (called the range's subtype). Only available in Postgres. See the Postgres documentation for more details **Fallback policy:** If this type is not supported, an error will be raised. #### Example ```javascript // A range of integers DataTypes.RANGE(DataTypes.INTEGER) // A range of bigints DataTypes.RANGE(DataTypes.BIGINT) // A range of decimals DataTypes.RANGE(DataTypes.DECIMAL) // A range of timestamps DataTypes.RANGE(DataTypes.DATE) // A range of dates DataTypes.RANGE(DataTypes.DATEONLY) ``` #### Type Parameters * T extends BaseNumberDataType | DATE | DATEONLY = INTEGER #### Hierarchy (View Summary, Expand) * ABSTRACT> | AcceptableTypeOf> * RANGE ##### ### Constructors constructor ### Properties options usageContext ### Methods _checkOptionSupport _construct _getDialect acceptsNull areValuesEqual belongsToDialect clone escape getBindParamSql getDataTypeId parseDatabaseValue sanitize toBindableValue toDialectDataType toSql toString validate withUsageContext getDataTypeId toString ## ### constructor * new RANGE< T extends DATE | DATEONLY | BaseNumberDataType = INTEGER, >( subtypeOrOptions: DataTypeClassOrInstance | RangeOptions, ): RANGE #### Type Parameters * T extends DATE | DATEONLY | BaseNumberDataType = INTEGER #### Parameters * subtypeOrOptions: DataTypeClassOrInstance | RangeOptions A subtype for range, like RANGE(DATE) #### Returns RANGE ## ### `Readonly`options options: { subtype: ABSTRACT } ### usageContext usageContext: undefined | DataTypeUseContext Where this DataType is being used. ## ### `Protected`_checkOptionSupport * _checkOptionSupport(dialect: AbstractDialect): void Override this method to emit an error or a warning if the Data Type, as it is configured, is not compatible with the current dialect. #### Parameters * dialect: AbstractDialect The dialect using this data type. #### Returns void ### `Protected`_construct * _construct ABSTRACT>( ...args: ConstructorParameters, ): this #### Type Parameters * Constructor extends new () => ABSTRACT #### Parameters * ...args: ConstructorParameters #### Returns this ### `Protected`_getDialect * _getDialect(): AbstractDialect #### Returns AbstractDialect ### acceptsNull * acceptsNull(): boolean Whether this DataType wishes to handle NULL values itself. This is almost exclusively used by JSON and JSONB which serialize `null` as the JSON string `'null'`. #### Returns boolean ### areValuesEqual * areValuesEqual( value: AcceptableTypeOf | Rangable>, originalValue: AcceptableTypeOf | Rangable>, ): boolean #### Parameters * value: AcceptableTypeOf | Rangable> * originalValue: AcceptableTypeOf | Rangable> #### Returns boolean ### belongsToDialect * belongsToDialect(dialect: AbstractDialect): boolean #### Parameters * dialect: AbstractDialect #### Returns boolean ### clone * clone(): this Returns a copy of this DataType, without usage context. Designed to re-use a DataType on another Model. #### Returns this ### escape * escape(value: AcceptableTypeOf | Rangable>): string Escapes a value for the purposes of inlining it in a SQL query. The resulting value will be inlined as-is with no further escaping. #### Parameters * value: AcceptableTypeOf | Rangable> The value to escape. #### Returns string ### getBindParamSql * getBindParamSql( value: AcceptableTypeOf | Rangable>, options: BindParamOptions, ): string This method is called when AbstractQueryGenerator needs to add a bind parameter to a query it is building. This method allows for customizing both the SQL to add to the query, and convert the bind parameter value to a DB-compatible value. If you only need to prepare the bind param value, implement toBindableValue instead. This method must return the SQL to add to the query. You can obtain a bind parameter ID by calling BindParamOptions#bindParam with the value associated to that bind parameter. An example of a data type that requires customizing the SQL is the GEOMETRY data type. #### Parameters * value: AcceptableTypeOf | Rangable> The value to bind. * options: BindParamOptions Options. #### Returns string ### getDataTypeId * getDataTypeId(): string #### Returns string ``` -------------------------------- ### size Accessor Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.ModelSetView.html Gets the number of elements in the ModelSetView. ```APIDOC ## size ### Description Gets the number of elements in the ModelSetView. ### Returns number - The number of elements in the set. ``` -------------------------------- ### TEXT Data Type Initialization Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.TEXT.html Demonstrates how to initialize the TEXT data type with different length specifiers. ```javascript DataTypes.TEXT('tiny') // TINYTEXT ``` -------------------------------- ### connect Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.AbstractConnectionManager.html Establishes a new connection to the database. ```APIDOC ## connect * connect(_config: ConnectionOptions): Promise #### Parameters * _config: ConnectionOptions #### Returns Promise ``` -------------------------------- ### dialect Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.AbstractQueryGenerator.html Gets the dialect associated with this query generator. ```APIDOC ## `Readonly`dialect * dialect: Dialect #### Returns Dialect ``` -------------------------------- ### beforeDefine Source: https://sequelize.org/api/v7/interfaces/_sequelize_core.index._internal_.SequelizeHooks.html A hook that is run at the start of Sequelize#define and Model.init. ```APIDOC ## beforeDefine ### Description A hook that is run at the start of Sequelize#define and Model.init. ### Signature beforeDefine(attributes: ModelAttributes, options: ModelOptions): void ### Parameters * **attributes** (ModelAttributes) - The attributes of the model being defined. * **options** (ModelOptions) - Options passed to the define or init method. ### Returns void ``` -------------------------------- ### constructor Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.AbstractQueryGenerator.html Initializes a new instance of the AbstractQueryGenerator class. ```APIDOC ## constructor * new AbstractQueryGenerator< Dialect extends AbstractDialect = AbstractDialect, >( dialect: Dialect, internals?: AbstractQueryGeneratorInternal, ): AbstractQueryGenerator #### Type Parameters * Dialect extends AbstractDialect = AbstractDialect #### Parameters * dialect: Dialect * internals: AbstractQueryGeneratorInternal = ... #### Returns AbstractQueryGenerator ``` -------------------------------- ### getDatabaseVersionIfExist Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.SequelizeTypeScript.html Gets the internally loaded database version if it exists. ```APIDOC ## getDatabaseVersionIfExist ### Description Safely retrieves the internally loaded database version. If the version has not been loaded, it returns `null` instead of throwing an error. ### Method GET ### Endpoint /getDatabaseVersionIfExist ### Response #### Success Response (200) - **null | string** - The database version string or null if not loaded. ``` -------------------------------- ### SetView.size Accessor Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.SetView.html Gets the number of unique elements in the SetView. ```APIDOC ## size ### Description Gets the number of (unique) elements in the Set. ### Returns number - The number of elements in the Set. ``` -------------------------------- ### Managing Associations: Add and Set Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.Association.html Provides examples of how to add single or multiple associated models, and how to set associations to a specific subset, potentially removing others. ```javascript user.addPicture(p) // Add a single picture user.setPictures([p1, p2]) // Associate user with ONLY these two picture, all other associations will be deleted user.addPictures([p1, p2]) // Associate user with these two pictures, but don't touch any current associations ``` -------------------------------- ### Adding Associated Instances with Primary Keys Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.BelongsToManyAssociation.html Demonstrates adding associated projects to a user, accepting an array that can contain either persisted instances or their primary keys. ```javascript const project = await Project.create({ id: 11 }); await user.addProjects([project, 12]); ``` -------------------------------- ### queryGenerator accessor Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.AbstractQueryGeneratorInternal.html Gets the query generator associated with the dialect. ```APIDOC ## queryGenerator ### Description Gets the query generator associated with the dialect. ### Returns Dialect["queryGenerator"] ``` -------------------------------- ### get Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.BelongsToAssociation.html Retrieves the associated instance(s) for the given source instance(s). ```APIDOC ## get ### Description Gets the associated instance(s). See `BelongsToGetAssociationMixinOptions` for a full explanation of options. This method is mixed-in the source model prototype. See `BelongsToGetAssociationMixin`. ### Method Overloads 1. `get(instances: S, options?: BelongsToGetAssociationMixinOptions): Promise` 2. `get(instances: S[], options?: BelongsToGetAssociationMixinOptions): Promise>` ### Parameters #### Path Parameters - `instances` (S or S[]) - Required - The source instance(s). - `options` (BelongsToGetAssociationMixinOptions) - Optional - Find options. ### Returns `Promise` or `Promise>` - The associated instance(s) or null if not found. ``` -------------------------------- ### withConnection Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.Sequelize.html Establishes a connection and executes a callback function within that connection's context. This is useful for operations requiring a specific database connection. ```APIDOC ## withConnection ### Description Executes a callback function within a database connection's context. This is useful for operations requiring a specific database connection. ### Method `withConnection(options: WithConnectionOptions, callback: SessionCallback): Promise` ### Type Parameters * `T` - The return type of the callback function. ### Parameters * `options` (WithConnectionOptions) - Options for establishing the connection. * `callback` (SessionCallback) - The callback function to execute with the connection. ### Returns * `Promise` - A promise that resolves with the return value of the callback. ### Method Overload `withConnection(callback: SessionCallback): Promise` ### Type Parameters * `T` - The return type of the callback function. ### Parameters * `callback` (SessionCallback) - The callback function to execute with the connection. ### Returns * `Promise` - A promise that resolves with the return value of the callback. ``` -------------------------------- ### constructor Source: https://sequelize.org/api/v7/classes/_sequelize_core.index.AbstractQuery.html Constructs a new AbstractQuery instance. Initializes the query with connection, sequelize instance, and optional options. ```APIDOC ## constructor ### Description Constructs a new AbstractQuery instance. Initializes the query with connection, sequelize instance, and optional options. ### Parameters * **connection**: AbstractConnection * **sequelize**: Sequelize * **`Optional`options**: AbstractQueryOptions ### Returns AbstractQuery ``` -------------------------------- ### size Accessor Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.MultiMap.html Gets the number of keys currently stored in the MultiMap. ```APIDOC ## size ### Description Gets the number of keys currently stored in the MultiMap. ### Returns number ``` -------------------------------- ### Static getDataTypeId Source: https://sequelize.org/api/v7/classes/_sequelize_core.index._internal_.DECIMAL.html Gets the unique identifier for the DECIMAL data type. ```APIDOC ## Static getDataTypeId ### Description Gets the unique identifier for the DECIMAL data type. ### Returns - string: The data type identifier. ```