An easy-to-use multi SQL dialect ORM tool for Node.js

Overview

Sequelize

npm version Build Status

npm downloads Merged PRs semantic-release

Sequelize is a promise-based Node.js ORM tool for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.

Sequelize follows Semantic Versioning and supports Node v10 and above.

New to Sequelize? Take a look at the Tutorials and Guides. You might also be interested in the API Reference.

v6 Release

You can find the detailed changelog here.

Note: Looking for maintainers!

Recently, a bigger part of the former core maintainers (thanks to all your hard work!) have been rather busy. Hence, the available time to look after our beloved ORM has been shrinking and shrinking drastically, generating a great chance for you:

We are looking for more core maintainers who are interested in improving/fixing our TypeScript typings, improving the documentation, organizing issues, reviewing PRs, streamlining the overall code base and planning the future roadmap.

If that sounds interesting to you, please reach out to us on our Slack channel by sending a direct message to Pedro A P B. If you don't have access, get yourself an invite automatically via this link. We are looking forward to meet you!

Installation

$ npm i sequelize # This will install v6

# And one of the following:
$ npm i pg pg-hstore # Postgres
$ npm i mysql2
$ npm i mariadb
$ npm i sqlite3
$ npm i tedious # Microsoft SQL Server

Documentation

Responsible disclosure

If you have security issues to report, please refer to our Responsible Disclosure Policy for more details.

Resources

Tools

Translations

Comments
  • TimeoutError: ResourceRequest timed out

    TimeoutError: ResourceRequest timed out

    What you are doing?

    Testing the connection to a postgres amazon rds instance

    const sequelize = new Sequelize('dbname', 'username', 'password', {
      host: 'example.rds.amazonaws.com',
      dialect: 'postgres'
    });
    
    
    sequelize
      .authenticate()
      .then(() => {
        console.log('Connection has been established successfully.');
      })
      .catch(err => {
        console.error('Unable to connect to the database:', err);
      });
    

    What do you expect to happen?

    App should connect and should output in console: "Connection has been established successfully"

    What is actually happening?

    Unable to connect to the database: { TimeoutError: ResourceRequest timed out
        at ResourceRequest._fireTimeout (\myapp\node_modules\generic-pool\lib\ResourceRequest.js:58:17)
        at Timeout.bound (\myapp\node_modules\generic-pool\lib\ResourceRequest.js:8:15)
        at ontimeout (timers.js:380:14)
        at tryOnTimeout (timers.js:244:5)
        at Timer.listOnTimeout (timers.js:214:5) name: 'TimeoutError' }
    

    Dialect: postgres Database version: 9.6 Sequelize version: 4.2.1

    type: bug dependency 
    opened by clutariomark 134
  • Sequelize.sync() should support ALTER statements instead of full DROP+CREATE statements

    Sequelize.sync() should support ALTER statements instead of full DROP+CREATE statements

    It would be nice if we could call sync() and have it compare the model schema to the database schema and make only the changes necessary using ALTER statements. The major benefit is preservation of data. If implemented correctly, this could probably eliminate most of the need for migration files.

    type: feature 
    opened by ShimShamSam 109
  • Deprecation warning for String based operators

    Deprecation warning for String based operators

    Since I upgraded to 4.13.2 I get a deprecation warning

    sequelize deprecated String based operators are now deprecated. Please use Symbol based operators for better security, read more at http://docs.sequelizejs.com/manual/tutorial/querying.html#operators node_modules/sequelize/lib/sequelize.js:236:13
    

    I do not use any string based operators, however, or any operators of any kind. I didn't even know what an operator was actually, which is why I was confused.

    I can fix this by adding operatorsAliases: false when instantiating the Sequellize object as below. Should this not be the default though? Or can we have the warning and documentation more clearly state that operatorsAliases: false must be set in order to avoid the warning?

    
    const sequelize = new Sequelize(
      config.RDS_DB_NAME,
      config.RDS_USERNAME, 
      config.RDS_PASSWORD,
      {
        host: config.RDS_HOSTNAME,
        dialect: 'mysql',
        logging: false,
        freezeTableName: true,
        operatorsAliases: false
      }
    )
    
    opened by krishangupta 106
  • Attribute scoping proposal

    Attribute scoping proposal

    Taking naming suggestions, 'scope' might confuse with Model.scope

    Allow users to scope attributes for retrieval when using get() & toJSON().

    Defining 'scopes' on attributes:

    sequelize.define('User', {
      email: {
        type: DataTypes.STRING,
        scopes: ['self'],
      },
      name: {
        type: DataTypes.STRING,
        scopes: ['self', 'public']
      },
      title: {
        type: DataTypes.STRING // No scopes is default all scopes
      },
      parent_id: {
        type: DataTypes.INTEGER,
        scopes: false||[] // Don't EVER include
      }
    });
    

    Defining attributes in scope:

    // found some user
    var values = user.get({scope: 'public'}); // {name: someValue, title: someValue}
    var values = user.get({scope: 'self'}); // {email: someValue, email: someValue, title: someValue}
    

    WIP

    type: feature status: in discussion 
    opened by mickhansen 93
  • Oracle Support on master

    Oracle Support on master

    Hi,

    This is the first version of Oracle support done by my company. The minor version is Oracle 12c. This pull request follows the first I've made (https://github.com/sequelize/sequelize/pull/6903). This one is on the master branch.

    This version contains everything needed for using Oracle :

    • Connecting to Oracle.
    • INSERT / UPDATE / SELECT / DELETE queries.
    • Managing transactions.
    • Call to stored procedure (with / without parameters).
    • All tests are passing
    • Docs are updated

    My company needs this Oracle version for our new server, so the work will continue soon.

    Connection Pooling is not relevant according to node-oracledb.

    TODO :

    • [ ] resultSets
    • [X] upsert
    • [X] long length aliases support

    ResultsSets needs some time to be implemented, for now, maxRows can be setted in the dialectOptions (default to 1000). I can't do the upsert support as I can't understand how Oracle works with it.

    Oracle doesn't support aliases / columns / tables with name's length > 31. For now, nothing has been done. It will come with another pull request. An aliases replacement is done to make all queries work.

    A docker image has been created and is available : https://hub.docker.com/r/konnecteam/oracle12c-database/

    I don't know how to integrate it with Sequelize builds, so if someone can help me.

    type: feature status: awaiting investigation hard 
    opened by ggrimbert 88
  • 4.0 Model definition syntax

    4.0 Model definition syntax

    Because the dicussion is spread across many issues and PRs, I wanted to open a new issue to discuss the future syntax for model definition.

    Currently, besides the old define(), this syntax is possible in v4.0.0-1:

    export class User extends Model {
     
        get fullName() {
            return this.firstName + ' ' + this.lastName;
        }
     
        set fullName(fullName) {
            const names = fullName.split(' ');
            this.lastName = names.pop();
            this.firstName = names.join(' ');
        }
    }
    User.init(({
        username: {
            type: DataTypes.STRING,
            primaryKey: true
        },
        lastName: DataTypes.STRING,
        firstName: DataTypes.STRING,
    }, { sequelize })
    

    If you prefer to not do the initialization (which also attaches the connection to the model) inside the model file, but rather from a model index file, this is also possible:

    export class User extends Model {
     
        get fullName() {
            return this.firstName + ' ' + this.lastName;
        }
     
        set fullName(fullName) {
            const names = fullName.split(' ');
            this.lastName = names.pop();
            this.firstName = names.join(' ');
        }
    
        static init(sequelize) {
            super.init({
                username: {
                    type: DataTypes.STRING,
                    primaryKey: true
                },
                lastName: DataTypes.STRING,
                firstName: DataTypes.STRING,
            }, { sequelize })
        }
    }
    

    With the help of a decorator library and Babel transpilation, this is also possible:

    @Options({ sequelize })
    @Attributes({
        username: {
            type: DataTypes.STRING,
            primaryKey: true
        },
        lastName: DataTypes.STRING,
        firstName: DataTypes.STRING,
    })
    export class User extends Model {
     
        get fullName() {
            return this.firstName + ' ' + this.lastName;
        }
     
        set fullName(fullName) {
            const names = fullName.split(' ');
            this.lastName = names.pop();
            this.firstName = names.join(' ');
        }
    }
    

    And with TypeScript you can go even further:

    @Options({ sequelize })
    export class User extends Model {
     
        @Attribute({
            type: DataTypes.STRING,
            primaryKey: true
        })
        public username: string;
     
        @Attribute(DataTypes.STRING)
        public firstName: string;
     
        @Attribute() // Type is inferred as DataTypes.STRING 
        public lastName: string;
     
        get fullName(): string {
            return this.firstName + ' ' + this.lastName;
        }
     
        set fullName(fullName: string) {
            const names = fullName.split(' ');
            this.lastName = names.pop();
            this.firstName = names.join(' ');
        }
    }
    

    BUT we definitely do not want to require the usage of any transpiler. The Model.init() API feels a bit weird, especially how the sequelize connection is passed. Some thoughts:

    • If we want to make models independent one day from connections, this is has the benefit of easily omitting the sequelize option
    • But we would probably still need to require that models are registered in a model manager, so we could inverse the syntax (something like sequelize.add(Model) instead of passing the connection. That is not implemented atm though, currently the model needs to know about the connection.

    Please chime in and share your thoughts and ideas!

    Issues/PRs for reference: https://github.com/sequelize/sequelize/issues/5898 https://github.com/sequelize/sequelize/pull/6439 https://github.com/sequelize/sequelize/pull/5877 https://github.com/sequelize/sequelize/pull/5924 https://github.com/sequelize/sequelize/issues/5205 https://github.com/sequelize/sequelize/issues/4728

    status: in discussion 
    opened by felixfbecker 83
  • Hooks refactor + new hooks

    Hooks refactor + new hooks

    This is just a issue for the milestone tracker. We'll keep track of the general hook update progress here.

    • [x] context/options on all hooks (#2240)
    • [x] find hooks
    • [x] connection hooks
    • [ ] query hooks
    • [ ] build hooks
    type: feature stale 
    opened by mickhansen 80
  • Preferred way to handle reconnect

    Preferred way to handle reconnect

    In case the db connection is lost, we need to reconnect to the database. I couldn't find a preferred way to handle this issue. Do you have a best practice? The issue can be solved on various ways:

    • handle in sequelize
    • handle in db module like pg
    • handle this issue outside of nodejs with connection handler

    Thanks in advance

    type: feature 
    opened by chris-rock 79
  • SequelizeConnectionAcquireTimeoutError randomly DB connections pool error

    SequelizeConnectionAcquireTimeoutError randomly DB connections pool error

    I'm running a very simple app that using sequelize basics, it was working for the recent year without any issues on sequelize v4. Recently, the app is crashing every day once a day, with the following error:

    TimeoutError: ResourceRequest timed out
        at ResourceRequest._fireTimeout (/usr/src/app/node_modules/generic-pool/lib/ResourceRequest.js:62:17)
        at Timeout.bound (/usr/src/app/node_modules/generic-pool/lib/ResourceRequest.js:8:15)
        at ontimeout (timers.js:498:11)
        at tryOnTimeout (timers.js:323:5)
        at Timer.listOnTimeout (timers.js:290:5)
    

    It was happening with sequelize 4.42.0, mysql2 v1.6.5, node carbon alpine. After reading a lot about this issue, I figured out that sequelize v5 might handle the connections pool better, so I've tried sequelize 5.7.6, mariadb v2.0.3, but nothing, now the error that I'm getting is:

    SequelizeConnectionAcquireTimeoutError: Operation timeout
        at pool.acquire.catch.err (/usr/src/app/node_modules/sequelize/lib/dialects/abstract/connection-manager.js:281:53)
        at tryCatcher (/usr/src/app/node_modules/bluebird/js/release/util.js:16:23)
        at /usr/src/app/node_modules/bluebird/js/release/catch_filter.js:17:41
        at tryCatcher (/usr/src/app/node_modules/bluebird/js/release/util.js:16:23)
        at Promise._settlePromiseFromHandler (/usr/src/app/node_modules/bluebird/js/release/promise.js:512:31)
        at Promise._settlePromise (/usr/src/app/node_modules/bluebird/js/release/promise.js:569:18)
        at Promise._settlePromise0 (/usr/src/app/node_modules/bluebird/js/release/promise.js:614:10)
        at Promise._settlePromises (/usr/src/app/node_modules/bluebird/js/release/promise.js:690:18)
        at _drainQueueStep (/usr/src/app/node_modules/bluebird/js/release/async.js:138:12)
        at _drainQueue (/usr/src/app/node_modules/bluebird/js/release/async.js:131:9)
        at Async._drainQueues (/usr/src/app/node_modules/bluebird/js/release/async.js:147:5)
        at Immediate.Async.drainQueues (/usr/src/app/node_modules/bluebird/js/release/async.js:17:14)
        at runCallback (timers.js:810:20)
        at tryOnImmediate (timers.js:768:5)
        at processImmediate [as _immediateCallback] (timers.js:745:5)
    

    It's very important to tell that I have different apps that run on the same K8s cluster with the same DB, same auth, and it's not crashing.

    Any suggestions?

    type: other 
    opened by idangozlan 78
  • Make model classes streamable

    Make model classes streamable

    I had an idea, I searched around and didnt see anyone else asking about it.

    I want to support the below test case.

    'use strict';
    //deps
    var streamArray = require('stream-array')
    var sequelize = require('sequelize')()
    var through2 = require('through2')
    
    //define module
    var People = sequelize.define('People',{
      name: {
        type: sequelize.DataTypes.STRING,
        allowNull: false
      }
    })
    
    //setup readable object stream
    var stream = streamArray([
      {name: 'Bob'},
      {name: 'Bill'},
      {name: 'Susan'}
    ])
    
    //setup a response handler
    var transform = through2.obj(function(inst,enc,next){
      console.log('Saved person: ' + inst.name)
      next(null,inst)
    })
    
    stream.pipe(People.createStream()).pipe(transform)
    

    I implemented this manually in a migrator but I think it would be an awesome feature to just be able to stream objects to a Model and have them create it and pass the resulting instance to a readable stream. Then this could be use with packages like promisepipe to make truly useful streams.

    Also I was thinking of making it to where options could be passed to use a findOrCreate, find, or even build so they can be saved in the response handler. I envision the options could be defined in the createStream method that the model would expose.

    It would make it much easier to deal with large amounts of data since streams implement all the back pressure automatically and there is no need for queuing. Extremely useful for doing transform update queries. (I am aware these are reasonably easy to implement manually but a macro would make it more useful for the average user)

    If anyone else is interested in this I could work on a PR for it.

    type: feature type: performance hard 
    opened by nullivex 77
  • Error: Include unexpected. Element has to be either a Model, an Association or an object.

    Error: Include unexpected. Element has to be either a Model, an Association or an object.

    Issue Description

    I am trying to make a big query with many joins and it seems sequelize doesn't like the way I am doing this.

    What are you doing?

    const ids = [/*Some integer here*/];
    models.Exercise.findAll({
      // no need for that part here
      attributes: [
        "id",
        "title",
        "description",
        "version",
        "createdAt",
        "updatedAt"
      ],
      where: {
        id: {
          [Op.in]: ids
        }
      },
      include: [
        // load exercise evaluation
        {
          models: models.Exercise_Metrics,
          as: "metrics",
          attributes: [
            ["vote_count", "votes"],
            ["avg_vote_score", "avg_vote"]
          ]
        },
        // load tags linked to this exercise ( with their category included )
        {
          models: models.Exercise_Tag,
          as: "tags",
          attributes: [],
          include: [
            {
              models: models.Tag,
              attributes: ["id", "text"],
              include: [
                {
                  models: models.Tag_Category,
                  as: "category",
                  attributes: [
                    ["kind", "category"],
                    ["id", "category_id"]
                  ]
                }
              ]
            }
          ]
        }
      ]
    });
    

    What do you expect to happen?

    I expect that to work when I use findAll

    What is actually happening?

    Error: Include unexpected. Element has to be either a Model, an Association or an object.
        at Function._conformInclude (D:\workspaceshit\exercises_library\node_modules\sequelize\lib\model.js:390:11)
        at options.include.options.include.map.include (D:\workspaceshit\exercises_library\node_modules\sequelize\lib\model.js:326:59)
        at Array.map (<anonymous>)
        at Function._conformIncludes (D:\workspaceshit\exercises_library\node_modules\sequelize\lib\model.js:326:39)
        at Function._baseMerge (D:\workspaceshit\exercises_library\node_modules\sequelize\lib\model.js:791:10)
        at Function._defaultsOptions (D:\workspaceshit\exercises_library\node_modules\sequelize\lib\model.js:828:17)
        at Function._injectScope (D:\workspaceshit\exercises_library\node_modules\sequelize\lib\model.js:3288:10)
        at Promise.try (D:\workspaceshit\exercises_library\node_modules\sequelize\lib\model.js:1707:12)
        at tryCatcher (D:\workspaceshit\exercises_library\node_modules\bluebird\js\release\util.js:16:23)
        at Function.Promise.attempt.Promise.try (D:\workspaceshit\exercises_library\node_modules\bluebird\js\release\method.js:39:29)
        at Function.findAll (D:\workspaceshit\exercises_library\node_modules\sequelize\lib\model.js:1706:23)
    

    Additional context

    Here are my models definitions if It could help you : Exercise Exercise_Metrics Exercise_Tag Tag Tag_Category

    Environment

    • Sequelize version: 5.21.2
    • Node.js version: v10.16.0
    • Operating System: Windows 10

    Issue Template Checklist

    How does this problem relate to dialects?

    • [x] I think this problem happens regardless of the dialect.
    • [ ] I think this problem happens only for the following dialect(s):
    • [ ] I don't know, I was using PUT-YOUR-DIALECT-HERE, with connector library version XXX and database version XXX

    Would you be willing to resolve this issue by submitting a Pull Request?

    • [ ] Yes, I have the time and I know how to start.
    • [ ] Yes, I have the time but I don't know how to start, I would need guidance.
    • [x] No, I don't have the time, although I believe I could do it if I had the time...
    • [ ] No, I don't have the time and I wouldn't even know how to start.
    opened by jy95 72
  • meta: unify createTableQuery unit tests and type createTableQuery

    meta: unify createTableQuery unit tests and type createTableQuery

    Pull Request Checklist

    • [X] Have you added new tests to prevent regressions?
    • [X] If a documentation update is necessary, have you opened a PR to the documentation repository?
    • [X] Did you update the typescript typings accordingly (if applicable)?
    • [X] Does the description below contain a link to an existing issue (Closes #[issue]) or a description of the issue you are solving?
    • [X] Does the name of your PR follow our conventions?

    Description Of Change

    This PR is smaller than the others; this time I just unified the tests, added missing expectations and quickly typed createTableQuery. Future PRs can migrate createTableQuery to TypeScript and clean up the test suite.

    Todos

    • [ ]
    • [ ]
    • [ ]
    opened by WikiRik 0
  • Issue in sync({alter: true}) with snowflake dialect

    Issue in sync({alter: true}) with snowflake dialect

    Issue Creation Checklist

    • [x] I understand that my issue will be automatically closed if I don't fill in the requested information
    • [x] I have read the contribution guidelines

    Bug Description

    I am using sequelize with snowflake dialect and when I am trying to change schema for any existing column by using sync({ alter: true }) I am getting the following error

    Executing (default): SHOW FULL COLUMNS FROM "TEST_BG";
    
    DatabaseError [SequelizeDatabaseError]: SQL compilation error:
    syntax error line 1 at position 5 unexpected 'FULL'.
    

    This is because on using alter: true SHOW FULL COLUMNS query gets executed but snowflake doesn't support this. Instead snowflake supports SHOW COLUMNS IN ${table};

    You can refer to this link(https://docs.snowflake.com/en/sql-reference/sql/show-columns.html)

    Reproducible Example

    Here is the link to the SSCCE for this issue:

    What do you expect to happen?

    What is actually happening?

    I am using sequelize with snowflake dialect and when I am trying to change schema for any existing column by using sync({ alter: true }) I am getting the following error

    Executing (default): SHOW FULL COLUMNS FROM "TEST_BG";
    
    DatabaseError [SequelizeDatabaseError]: SQL compilation error:
    syntax error line 1 at position 5 unexpected 'FULL'.
        at Query.formatError (C:\projects\snowflake\node-poc\node_modules\sequelize\lib\dialects\snowflake\query.js:207:16)
        at Query.run (C:\projects\snowflake\node-poc\node_modules\sequelize\lib\dialects\snowflake\query.js:57:18)
        at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
        at async C:\projects\snowflake\node-poc\node_modules\sequelize\lib\sequelize.js:314:16
        at async SnowflakeQueryInterface.describeTable (C:\projects\snowflake\node-poc\node_modules\sequelize\lib\dialects\abstract\query-interface.js:166:20)
        at async Promise.all (index 0)
        at async TEST_BG.sync (C:\projects\snowflake\node-poc\node_modules\sequelize\lib\model.js:947:26)
        at async Sequelize.sync (C:\projects\snowflake\node-poc\node_modules\sequelize\lib\sequelize.js:376:9)
        at async C:\projects\snowflake\node-poc\src\main.ts:47:3
    

    This is because on using sequelize.sync({ alter: true }); SHOW FULL COLUMNS query gets executed but snowflake doesn't support this. Instead snowflake supports SHOW COLUMNS IN ${table};

    You can refer to this link (https://docs.snowflake.com/en/sql-reference/sql/show-columns.html)

    Environment

    • Sequelize version: 6.28.0
    • Node.js version:
    • If TypeScript related: TypeScript version:
    • Database & Version: snowflake
    • Connector library & Version:

    Would you be willing to resolve this issue by submitting a Pull Request?

    • [x] Yes, I have the time and I know how to start.
    • [ ] Yes, I have the time but I will need guidance.
    • [ ] No, I don't have the time, but my company or I are supporting Sequelize through donations on OpenCollective.
    • [ ] No, I don't have the time, and I understand that I will need to wait until someone from the community or maintainers is interested in resolving my issue.

    Indicate your interest in the resolution of this issue by adding the 👍 reaction. Comments such as "+1" will be removed.

    type: bug dialect: snowflake 
    opened by bhushangoel 1
  • Ordering and Grouping

    Ordering and Grouping

    Issue Creation Checklist

    • [x] I understand that my issue will be automatically closed if I don't fill in the requested information
    • [x] I have read the contribution guidelines

    Bug Description

    Reproducible Example

    The result of the run is grouping before sorting

    group by always get the first , because sorting execute after grouping

    let data=await app.model.Topic.findAll({
      group:["course_id"],
      order:[["createdAt","desc"]]
    })
    
    

    What do you expect to happen?

    Sort before grouping Use query not very convenient

    What is actually happening?

    But create statement is simple statement So one select can't resolve order and group exist together . Except use query ,For example

     let data = await app.modelmysql.query(
                "SELECT * FROM ( SELECT`id`,`title`,`plate`,`updatedAt` FROM `topic_forum` AS `topic_forum` WHERE (`topic_forum`.`deletedAt`IS NULL AND(`topic_forum`.`course_id`= :course_id AND`topic_forum`.`school_id`= :school_id )) HAVING (0<>1) ORDER BY `topic_forum`.`updatedAt`DESC ) r GROUP BY r.`plate`"
                , {
                    replacements: { school_id, course_id },
                    type: QueryTypes.SELECT
     })
    

    Not very convenient

    Environment

    • Sequelize version:6.0.0
    • Node.js version:v16.13.0
    • If TypeScript related: TypeScript version:
    • Database & Version:8.0.25
    • Connector library & Version:

    Would you be willing to resolve this issue by submitting a Pull Request?

    • [ ] Yes, I have the time and I know how to start.
    • [ ] Yes, I have the time but I will need guidance.
    • [ ] No, I don't have the time, but my company or I are supporting Sequelize through donations on OpenCollective.
    • [x] No, I don't have the time, and I understand that I will need to wait until someone from the community or maintainers is interested in resolving my issue.

    Indicate your interest in the resolution of this issue by adding the 👍 reaction. Comments such as "+1" will be removed.

    type: bug pending-approval 
    opened by codecnmc 0
  • Models with cyclic foreign keys and ENUM-typed fields can't be synced in Postgres

    Models with cyclic foreign keys and ENUM-typed fields can't be synced in Postgres

    Issue Creation Checklist

    • [X] I understand that my issue will be automatically closed if I don't fill in the requested information
    • [X] I have read the contribution guidelines

    Bug Description

    In PostgreSQL, when there is a circular dependency between models (following foreign keys) and at least some model in the database has an ENUM-typed property, calls to sequelize.sync() will fail, as the enum type is attempted to be created twice.

    This bug seems to have been introduced in v6.20.0, when support for cyclic foreign keys was added. The implementation synchronizes the models twice, first to create the tables, and then to create the foreign keys. Both runs are attempting to create the types for the ENUM-typed fields, which is not an idempotent operation.

    Reproducible Example

    Here is the link to the SSCCE for this issue: https://github.com/francofrizzo/sequelize-sscce-cyclic-associations

    What do you expect to happen?

    Models should be correctly synced when sequelize.sync() is called.

    What is actually happening?

    A SequelizeDatabaseError is thrown, indicating that type "enum_<model>_<field>" already exists.

    Environment

    • Sequelize version: v6.28.0
    • Node.js version: v14.21.1
    • Database & Version: PostgreSQL 14.5
    • Connector library & Version: [email protected]

    Would you be willing to resolve this issue by submitting a Pull Request?

    • [ ] Yes, I have the time and I know how to start.
    • [X] Yes, I have the time but I will need guidance.
    • [ ] No, I don't have the time, but my company or I are supporting Sequelize through donations on OpenCollective.
    • [ ] No, I don't have the time, and I understand that I will need to wait until someone from the community or maintainers is interested in resolving my issue.

    Indicate your interest in the resolution of this issue by adding the 👍 reaction. Comments such as "+1" will be removed.

    type: bug 
    opened by francofrizzo 2
  • docs: Added `upsertKeys` property to `BulkCreateOptions` interface

    docs: Added `upsertKeys` property to `BulkCreateOptions` interface

    Pull Request Checklist

    • [ ] Have you added new tests to prevent regressions?
    • [ ] If a documentation update is necessary, have you opened a PR to the documentation repository?
    • [x] Did you update the typescript typings accordingly (if applicable)?
    • [x] Does the description below contain a link to an existing issue (Closes #[issue]) or a description of the issue you are solving?
    • [x] Does the name of your PR follow our conventions?

    Description Of Change

    Added documentation for the upsertKeys option in the BulkCreateOptions interface. fix #15226

    opened by lpizzinidev 0
  • Using a variable to define multiple fields cause them to become weird

    Using a variable to define multiple fields cause them to become weird

    Issue Creation Checklist

    • [X ] I understand that my issue will be automatically closed if I don't fill in the requested information
    • [ ] I have read the contribution guidelines

    Bug Description

    It seems when using variable as a way to reduce code lines it causes problem for sequelize.

    Reproducible Example

    Here is the link to the SSCCE for this issue:

    export default class MyModel extends Model {
      static init(sequelize) {
        const repeatedDefinition = {
          type: Sequelize.INTEGER,
            defaultValue: 0,
            validate: {
              min: {
                args: [0],
                msg: 'Value should be between 0 and 7',
              },
              max: {
                args: [7],
                msg: 'Value should be between 0 and 7',
              },
            },
        };
        super.init({
          field1: repeatedDefinition,
          field2: repeatedDefinition,
          field3: repeatedDefinition,
          field4: repeatedDefinition,
          field5: repeatedDefinition,
          field6: repeatedDefinition,
          field7: repeatedDefinition,
        }, {
          sequelize,
          freezeTableName: true,
          tableName: 'myModels',
        });
        return this;
    }
    

    What do you expect to happen?

    Quicken table field definition by using a variable and allow less lines of code.

    What is actually happening?

    It seems it confuses the fields in someway. I realized that when sending two fields with different values, it set one of the values to all other fields. Like

    mymodel.update({field1: 4, field2: 2})

    Expected this to update only field 1 and 2, but field1 = 4 // Correct field2 = 2 // Correct field(3 to 7) = either 2 or 4 // Sometimes one, sometimes the other

    Environment

    To find the version numbers for the three systems below use the following commands:

    Would you be willing to resolve this issue by submitting a Pull Request?

    • [ ] Yes, I have the time and I know how to start.
    • [ ] Yes, I have the time but I will need guidance.
    • [ ] No, I don't have the time, but my company or I are supporting Sequelize through donations on OpenCollective.
    • [X ] No, I don't have the time, and I understand that I will need to wait until someone from the community or maintainers is interested in resolving my issue.

    Indicate your interest in the resolution of this issue by adding the 👍 reaction. Comments such as "+1" will be removed.

    type: bug v6 
    opened by LCostaN 1
Releases(v7.0.0-alpha.20)
  • v7.0.0-alpha.20(Dec 22, 2022)

    7.0.0-alpha.20 (2022-12-22)

    Bug Fixes

    Features

    • add @Index, createIndexDecorator (#15482) (ab9aaba)
    • add @AllowNull, @AutoIncrement, @Comment, @Default, @PrimaryKey, and validation decorators (#15384) (08eb398)
    • add @Attribute & @Table decorators (#15336) (fb8603b)
    • add @Unique decorator, support specifying multiple unique indexes on the same attribute (#15342) (43bca57)
    • add association decorators (#15483) (3770827)
    • add model hook decorators (#15333) (bd037c8)
    • add new postgres JSONB operators ?| and ?& (#15073) (98dc4c2)
    • add support for add/drop column IF [NOT] EXISTS for mssql and mariadb (#15261) (096ed3a)
    • added support for index include (#14900) (dacc806)
    • allow using calculations in upsert on duplicate key by using literal values instead of VALUES() in mysql & mariadb (#14437) (9c2ae3c)
    • improved error reporting on associations (#14901) (8e3c626), closes #14161
    • Migrate createSchema() to TypeScript (#15339) (a3d164f)
    • migrate hooks to TypeScript (#15131) (9cd8d89)
    • migrate model definitions to TypeScript (#15431) (f57e5a0)
    • postgres: add support for lock_timeout [#15345] (#15347) (5e7cbe6)
    • postgres: support for ADD COLUMN IF NOT EXISTS and DROP COLUMN IF EXISTS (#15119) (76cc97f)
    • remove Utils export (#15305) (a4f8e62)
    • rename ALS back to CLS (#15427) (766b2ea)
    • replace CLS with ALS, enable ALS by default, discourage unmanaged transactions (#15292) (4cd43a4)
    • restrict instance methods if no primary key (#15108) (3095d99)
    • rewrite Data Types (#14505) (68b64f8)
    • throw if accessing databaseVersion before it is loaded (#15346) (151a458)
    • types: use retry-as-promised types for retry options to match documentation (#15400) (f2574ae)

    BREAKING CHANGES

    • Type ModelAttributeColumnOptions has been renamed AttributeOptions
    • setterMethods and getterMethods model options, which were deprecated in a previous major version, have been removed. See https://sequelize.org/docs/v6/core-concepts/getters-setters-virtuals/#deprecated-in-sequelize-v7-gettermethods-and-settermethods for alternatives.
    • In the "references" attribute option, the "model" option has been split in two options: "table" and "model". "table" references a database table, and "model" references a Sequelize model.
    • Sequelize will now throw if you try to define an attribute that conflicts (i.e. its options are incompatible) with one of the automatic timestamp or version attributes that are added on Models by Sequelize.
    • Model#validators and many private state and methods have been removed from models and moved to Model.modelDefinition
    • string attributes are always escaped as identifiers, including "*". See https://github.com/sequelize/sequelize/pull/15374 for details.
    • The where option will now throw if it receives an unsupported value
    • The "Utils" export has been removed. Classes Fn, Col, Cast, Literal, Json, and Where can be imported directly instead of using the Utils namespace. Other utilities are considered internal.
    • Some model instance methods cannot be used if the model doesn't have a primary key anymore. See https://github.com/sequelize/sequelize/pull/15108
    • ibmi - dropTableQuery does not accept schema in the options anymore, use a tableName object
    • The DataTypes API has changed. Custom DataTypes will need to be rewritten.
    • DataTypes.ENUM: Specifying the list of values through { type: DataTypes.ENUM, values: ['a', 'b'] } is no longer supported. Use { type: DataTypes.ENUM(['a', 'b']) } instead.
    • Int DataTypes will reject number values if they are outside of the safe integer range. Use JS bigints or strings for big values.
    • The typeValidation option is now noTypeValidation and is false by default, meaning type validation of values passed to Model.create and Model.update are now checked.
    • DataTypes.NUMERIC has been removed, use DataTypes.DECIMAL.
    • DataTypes.NUMBER has been removed (no alternative, internal).
    • DataTypes['DOUBLE PRECISION'] has been removed, use DataTypes.DOUBLE.
    • DataTypes.JSONTYPE has been removed, use DataTypes.JSON.
    • In raw queries that do not specify the JS DataType of a column, Dates are now returned as ISO 8601 strings instead of Date objects. This has been done in preparation for the arrival of Temporal.
    • DataTypes.BOOLEAN only accepts JS booleans. Strings, numbers, etc… will no longer be cast to boolean.
    • DataTypes.STRING, DataTypes.CITEXT, DataTypes.TEXT, and DataTypes.CHAR will only accept strings. Buffers & numbers will not be stringified anymore.
    • DataTypes.DECIMAL with scale & precision left unspecified is now interpreted as an unconstrained decimal, and throws in dialects that do not support unconstrained decimals.
    • BigInt attributes will be returned as strings instead of JavaScript numbers, because they cannot be safely represented using that type.
    • DataTypes.FLOAT(precision) is no longer accepted. FLOAT is now always be single-precision floating point. DOUBLE is now always be double-precision floating point.
    • DataTypes.JSON & DataTypes.JSONB throw in dialects that do not support JSON.
    • DataTypes.CHAR.BINARY and DataTypes.STRING.BINARY now mean "chars with a binary collation" and throw in dialects that do not support collations.
    • DataTypes.FLOAT now maps to REAL instead of FLOAT in all dialects except SQLite and MySQL
    • mssql - DataTypes.UUID now maps to UNIQUEIDENTIFIER instead of CHAR(36).
    Source code(tar.gz)
    Source code(zip)
  • v6.28.0(Dec 20, 2022)

  • v6.27.0(Dec 12, 2022)

  • v6.26.0(Nov 29, 2022)

  • v6.25.8(Nov 22, 2022)

  • v6.25.7(Nov 19, 2022)

  • v6.25.6(Nov 15, 2022)

  • v6.25.5(Nov 7, 2022)

  • v6.25.4(Nov 5, 2022)

  • v6.25.3(Oct 19, 2022)

  • v7.0.0-alpha.19(Oct 15, 2022)

  • v6.25.2(Oct 15, 2022)

  • v6.25.1(Oct 13, 2022)

  • v6.25.0(Oct 11, 2022)

  • v6.24.0(Oct 4, 2022)

  • v6.23.2(Sep 27, 2022)

  • v7.0.0-alpha.18(Sep 26, 2022)

  • v6.23.1(Sep 22, 2022)

  • v7.0.0-alpha.17(Sep 18, 2022)

    7.0.0-alpha.17 (2022-09-18)

    Bug Fixes

    Features

    • snowflake: Add support for QueryGenerator#tableExistsQuery (eedba90)
    Source code(tar.gz)
    Source code(zip)
  • v6.23.0(Sep 17, 2022)

  • v6.22.1(Sep 16, 2022)

  • v6.22.0(Sep 15, 2022)

  • v6.21.6(Sep 9, 2022)

  • v6.21.5(Sep 8, 2022)

  • v7.0.0-alpha.16(Aug 23, 2022)

  • v6.21.4(Aug 18, 2022)

  • v7.0.0-alpha.15(Aug 7, 2022)

    7.0.0-alpha.15 (2022-08-07)

    Bug Fixes

    • deps: update dependency retry-as-promised to v6 (#14676) (6a29e6e)
    • don't treat \ as escape in standard strings, support E-strings, support vars after ->> operator (#14700) (1c85d01)
    • fix sync duplicating existing foreign keys when a schema is used (#14570) (ab9a21d)
    • kill connection on commit/rollback error (v7) (#14574) (0610358)
    • minified aliases are now properly referenced in subqueries (#14804) (4abe16c)
    • mysql,mariadb: remove extra FROM from showIndexes (#14657) (0016739)
    • postgres: attach postgres error-handler earlier in lifecycle (#14742) (b74b130)
    • postgres: minifyAliases with through tables (#14629) (7a5f210)
    • postgres: treat lowercase e as valid e-string prefix (#14733) (7a15a4d)
    • postgres: use schema set in sequelize config by default (#14634) (751826a)
    • sequelize should take transaction from CLS everywhere (#13927) (be98856)
    • sqlite: Fix removeColumn and changeColumn foreign key issues for the sqlite dialect (#14070) (ee1d07b)
    • take scope into account when setting associated models with belongsToMany's .setX (#14738) (d7a501a)
    • types: add keepDefaultTimezone to Options interface (#14825) (5bccbbb)
    • types: align the return value of increment and decrement with actual behavior (#14704) (89dd2ec)
    • types: fix findAll() being treated as raw (#14668) (06f4429)
    • typings: make findX model methods return custom attributes if raw is true (#12921) (3cf2207)

    Features

    BREAKING CHANGES

    • The signature of connectionManager.pool when read replication is disabled is now the same as when read replication is enabled. If read replication is disabled, you can access the actual pool through connectionManager.pool.write. If read replication is enabled, you can use both connectionManager.pool.read and connectionManager.pool.write.
    • When instantiating Sequelize by providing the same options through both the URI and an option bag to the sequelize constructor, the option bag always takes priority over the URI
    Source code(tar.gz)
    Source code(zip)
  • v6.21.3(Jul 11, 2022)

  • v6.21.2(Jun 28, 2022)

  • v6.21.1(Jun 25, 2022)

Owner
Sequelize
Multi-dialect ORM and related tools for Node.js
Sequelize
An SQL-friendly ORM for Node.js

Objection.js Objection.js is an ORM for Node.js that aims to stay out of your way and make it as easy as possible to use the full power of SQL and the

Vincit 6.9k Jan 5, 2023
Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server & SQLite

Prisma Quickstart • Website • Docs • Examples • Blog • Slack • Twitter • Prisma 1 What is Prisma? Prisma is a next-generation ORM that consists of the

Prisma 28k Jan 2, 2023
An adapter-based ORM for Node.js with support for mysql, mongo, postgres, mssql (SQL Server), and more

Waterline is a next-generation storage and retrieval engine, and the default ORM used in the Sails framework. It provides a uniform API for accessing

Balderdash 5.4k Jan 4, 2023
ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

TypeORM is an ORM that can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms and can be used

null 30.1k Jan 3, 2023
Connect to private Google Cloud SQL instance through Cloud SQL Auth Proxy running in Kubernetes.

⛅ google-cloud-sql A CLI app which establishes a connection to a private Google Cloud SQL instance and port-forwards it to a local machine. Connection

Dinko Osrecki 10 Oct 16, 2022
A typesafe database ORM that exposes the full power of handwritten sql statements to the developer.

TORM A typesafe database ORM that exposes the full power of handwritten sql statements to the developer. import { torm, z } from 'https://deno.land/x/

Andrew Kaiser 15 Dec 22, 2022
Lovefield is a relational database for web apps. Written in JavaScript, works cross-browser. Provides SQL-like APIs that are fast, safe, and easy to use.

Lovefield Lovefield is a relational database written in pure JavaScript. It provides SQL-like syntax and works cross-browser (currently supporting Chr

Google 6.8k Jan 3, 2023
A typescript data mapping tool. To support mutual transforming between domain model and orm entity.

ts-data-mapper A typescript mapping tool supports mutual transforming between domain model and orm entity. In most case, domain model is not fully com

zed 8 Mar 26, 2022
A simple Node.js ORM for PostgreSQL, MySQL and SQLite3 built on top of Knex.js

bookshelf.js Bookshelf is a JavaScript ORM for Node.js, built on the Knex SQL query builder. It features both Promise-based and traditional callback i

Bookshelf.js 6.3k Jan 2, 2023
AlaSQL.js - JavaScript SQL database for browser and Node.js. Handles both traditional relational tables and nested JSON data (NoSQL). Export, store, and import data from localStorage, IndexedDB, or Excel.

Please use version 1.x as prior versions has a security flaw if you use user generated data to concat your SQL strings instead of providing them as a

Andrey Gershun 6.1k Jan 9, 2023
TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite databases.

TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite datab

MikroORM 5.4k Dec 31, 2022
Microsoft SQL Server client for Node.js

node-mssql Microsoft SQL Server client for Node.js Supported TDS drivers: Tedious (pure JavaScript - Windows/macOS/Linux, default) Microsoft / Contrib

null 2.1k Jan 4, 2023
A high performance MongoDB ORM for Node.js

Iridium A High Performance, IDE Friendly ODM for MongoDB Iridium is designed to offer a high performance, easy to use and above all, editor friendly O

Sierra Softworks 570 Dec 14, 2022
Adapter based JavaScript ORM for Node.js and the browser

firenze.js A database agnostic adapter-based object relational mapper (ORM) targetting node.js and the browser. Visit http://firenze.js.org for docume

Fahad Heylaal 130 Jul 14, 2022
The Blog system developed by nest.js based on node.js and the database orm used typeorm, the development language used TypeScript

考拉的 Nest 实战学习系列 readme 中有很多要说的,今天刚开源还没来及更新,晚些慢慢写,其实本人最近半年多没怎么写后端代码,主要在做低代码和中台么内容,操作的也不是原生数据库而是元数据Meta,文中的原生数据库操作也当作复习下,数据库的操作为了同时适合前端和Node开发小伙伴,所以并不是很

程序员成长指北 148 Dec 22, 2022
A Node.js ORM for MySQL, SQLite, PostgreSQL, MongoDB, GitHub and serverless service like Deta, InspireCloud, CloudBase, LeanCloud.

Dittorm A Node.js ORM for MySQL, SQLite, PostgreSQL, MongoDB, GitHub and serverless service like Deta, InspireCloud, CloudBase, LeanCloud. Installatio

Waline 21 Dec 25, 2022
TypeScript clients for databases that prevent SQL Injection

Safe From HTML Injection Using tagged template literals for queries, e.g. db.query(sql`SELECT * FROM users WHERE id=${userID}`); makes it virtually im

Forbes Lindesay 478 Dec 21, 2022
Conjure SQL from GraphQL queries 🧙🔮✨

Sqlmancer Conjure SQL from your GraphQL queries ?? ?? ✨ ⚠️ This project is currently on hiatus. I am hoping to resume working on Sqlmancer once I have

Daniel Rearden 132 Oct 30, 2022