Skip to content

underscore / camelcase option should control all fields and table name generation #6423

Closed

Description

@alexey2baranov

It would be great if sequelize will generate PostgreSQL DDL with lower_case_underscored table name and column names. By now underscore option manage foreign keys and create_at, modifed_at fields only.

In short

CREATE TABLE IF NOT EXISTS "Male" ("CamelCase" VARCHAR(255), "created_at" TIMESTAMP WITH TIME ZONE NOT NULL, "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL);

should become

CREATE TABLE IF NOT EXISTS male (camel_case VARCHAR(255), "created_at" TIMESTAMP WITH TIME ZONE NOT NULL, "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL);

my global config is

{
    "username": "",
    "password": "",
    "database": "",
    "host": "127.0.0.1",
    "dialect": "postgres",
    "define":{
      "paranoid":false,
      "timestamps":true,
      "freezeTableName": true,
      "underscored": true
    }
}

Activity

  1. changed the title [-]model underscore should produce underscored table_name and field_name's[/-] [+]underscore option should produce underscored_table_name and underscored_field_name's[/+] on Aug 12, 2016
  2. sushantdhiman commented on Aug 12, 2016

    @sushantdhiman
    Contributor

    Sounds like a reasonable feature to me, @janmeier ?

  3. janmeier commented on Aug 12, 2016

    @janmeier
    Member

    I don't think this is needed - If users want underscored names, they can simply define them as such, or use the field option.

    The underscored option is for controlling auto-generated column names, but when a user tells us about the column fooBar, we call it fooBar ;)

    This can easily be solved with a beforeDefine hook

  4. sushantdhiman commented on Aug 12, 2016

    @sushantdhiman
    Contributor

    Correct, but there is lots of work involved with that 😆 , I would prefer one single option based control.

    If anyone can share their experiences from other ORMs like ActiveRecord (Rails) or Eloquent (Laravel / PHP), that will be really helpful to make this decision.

  5. changed the title [-]underscore option should produce underscored_table_name and underscored_field_name's[/-] [+]underscore / camelcase option should control all fields and table name generation[/+] on Aug 12, 2016
  6. felixfbecker commented on Aug 12, 2016

    @felixfbecker
    Contributor

    I also prefer underscored columns and tables and camelCase attributes and PascalCase model names. I think the ORM should allow to map this easily.

  7. added
    type: featureDEPRECATED: replace with the "feature" issue type
    status: in discussionFor issues and PRs. Community and maintainers are discussing the applicability of the issue.
    on Aug 13, 2016
  8. maxsummers commented on Jan 3, 2017

    @maxsummers

    It took me a long time to figure out why underscored option didn't convert my camelCase column names to under_scored ones.

    I would also prefer to declare my columns as camelCased ones to be automatically converted later to underscored ones in SQL.

  9. elvisgs commented on May 5, 2017

    @elvisgs

    +1

  10. quocvu commented on Jun 1, 2017

    @quocvu

    I also agree w/ @alexey2baranov. I know we use of the field option, but that makes the model more verbose. Typically, when we name a field fooBar, it is to keep it consistent w/ the rest of the javascript code and not that we really want fooBar as a column name.

    The current behavior is not desirable. Who would want mixed column naming scheme in their tables?

    At the minimum, the documentation should be fixed. It doesn't say underscored only applies to auto-generated fields.

    Converts all camelCased columns to underscored if true. Will not affect timestamp fields named explicitly by model options and will not affect fields with explicitly set field option
    
  11. pgollangi commented on Jun 5, 2017

    @pgollangi

    +1

  12. stale commented on Aug 12, 2017

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂

  13. alexey2baranov commented on Aug 12, 2017

    @alexey2baranov
    Author

    Up

  14. 38 remaining items

  15. knoxcard commented on Apr 4, 2018

    @knoxcard
    Contributor

    @rogerc - I currently use MariaDB, but good to know if I ever switch to PostgreSQL, one less thing to worry about!

  16. didac-wh commented on Apr 4, 2018

    @didac-wh

    I'm afraid that, although those cool hooks work when"force: true", they do not when using alter: true.
    Since Sequelize checks the db schema usinc describeTable() it can't do the decamelize/camelize process without editing the package code.

    Does anyone have a solution for this (apart from editing the Sequelize source code)?

  17. sushantdhiman commented on Apr 7, 2018

    @sushantdhiman
    Contributor

    I would like to propose / share how I envision implementation of this change. I would love to hear comments before this actually gets implemented.


    There will be only one option underscored (underscoredAll and underscored will be merged)

    Attributes

    Setting Model.options.underscored: true will

    1. set field to a name constructed by underscoring attribute. So attribute myColumn will have field my_column
    2. If an attribute already got field defined, underscore will not override field for that attribute

    Model.tableName

    1. If Model.options.tableName is defined use it
    2. if Model.options.freezeTableName: true set table name to model name
    3. Otherwise pluralize Model.name then underscore it if underscored: true

    Auto-generated Attributes (timestamps / version / foreignKeys)

    OLD (Current)

    If Model.options.underscored: true, then all attributes are generated with underscored name. like Model.rawAttributes.created_at / updated_at / foreign_key` etc

    NEW (Proposed)

    All attributes will be generated with camelcased name like Model.rawAttributes.createdAt / updateAt / foreignKey etc, but field will be set to underscored name like created_at / updated_at / foreign_key if Model.options.underscored: true

    TLDR;

    All attributes will be generated with camelcase naming by default, specifying underscore: true will set field by underscoring attribute name


    Still using custom attribute name

    1. Foreign keys, you will be able to pass association.options.foreignKey where applicable that attribute name will be used.
    // define Task.user_id, use of `user_id` attribute as foreignKey on Task
    
    User.hasMany(Task, { foreignKey: 'user_id' });
    Task.belongsTo(User, { foreignKey: 'user_id' });
    1. Timestamps
    sequelize.define('Model', {
      name: Sequelize.STRING
    }, {
      createdAt: 'created_at', // will define attribute created_at on Model
      updatedAt: 'updated_at' // will define attribute updated_at on Model
    })
  18. rogerc commented on Apr 7, 2018

    @rogerc
    Contributor

    Sounds good. My PR I think covered all attributes except foreignKeys. Table name was left untouched.

  19. pickfire commented on Mar 13, 2019

    @pickfire

    I am surprised that underscored does not affect association and user still need to use { as: 'something_underscored' }, maybe this specification should mentioned it? It is not really underscored mode that what have been expected.

  20. up9cloud commented on May 27, 2019

    @up9cloud
    Contributor

    Memo for whom upgrade v4 to v5 with underscored: true and get unexpected field names (createdAt, updatedAt, deletedAt) from query result:

    TL; DR

    In v4 you can just set underscored: true and ignore those

    {
        createdAt: 'created_at',
        updatedAt: 'updated_at',
        deletedAt: 'deleted_at'
    }

    In v5, you HAVE TO add them to your define options, otherwise you'll get camel cased field names in your query result 😭 .

    Details

    v4 original

    $ npx sequelize --version
    Sequelize CLI [Node: 10.15.3, CLI: 5.4.0, ORM: 4.43.2]
    // db/foo.js
    module.exports = function (sequelize, DataTypes) {
      const tableName = 'foo'
      return sequelize.define(tableName, {
        id: { type: DataTypes.INTEGER.UNSIGNED, primaryKey: true, autoIncrement: true }
      })
    }
    // ./db/index.js
    const fs = require('fs')
    const path = require('path')
    const Sequelize = require('sequelize')
    const sequelize = new Sequelize({
      ...
      define: {
        paranoid: true,
        underscored: true,
        freezeTableName: true
        // no need to add createdAt, ... options
      }
    })
    let db = { sequelize }
    fs
      .readdirSync(__dirname)
      .filter(file => {
        if (
          file.indexOf('.') === 0 ||
          file === path.basename(__filename)
        ) {
          return false
        }
        return true
      })
      .forEach(file => {
        let model = sequelize.import(path.join(__dirname, file))
        db[model.name] = model
      })
    module.exports = db

    v5

    $ npx sequelize --version
    Sequelize CLI [Node: 12.3.1, CLI: 5.4.0, ORM: 5.8.6]
    // ./db/foo.mjs
    import Sequelize from 'sequelize'
    export default function (sequelize, DataTypes) {
      const tableName = 'foo'
      class model extends Sequelize.Model { }
      model.init({
        id: { type: DataTypes.INTEGER.UNSIGNED, primaryKey: true, autoIncrement: true }
      }, {
        sequelize,
        modelName: tableName,
        tableName
      })
      return model
    }
    // ./db/config.mjs
    export default {
      ...
      define: {
        paranoid: true,
        underscored: true,
        freezeTableName: true
      }
    }
    // ./db/index.mjs
    import Sequelize from 'sequelize'
    import config from './config.mjs'
    import foo from './foo.mjs'
    const sequelize = new Sequelize(config)
    const DataTypes = Sequelize.DataTypes
    let db = {
      sequelize,
      foo: foo(sequelize, DataTypes)
    }
    export default db

    v5 fixed

    // ./db/fixedDb.mjs
    import Sequelize from 'sequelize'
    import config from './config.mjs'
    import foo from './foo.mjs'
    
    const fixedConfig = {
      ...config,
      define: {
        ...config.define,
        // You HAVE TO add those...
        createdAt: 'created_at',
        updatedAt: 'updated_at',
        deletedAt: 'deleted_at'
      }
    }
    const sequelize = new Sequelize(fixedConfig)
    const DataTypes = Sequelize.DataTypes
    let db = {
      sequelize,
      foo: foo(sequelize, DataTypes)
    }
    export default db

    Test

    // ./test.mjs
    import db from './db/index.mjs'
    import fixedDb from './db/fixedDb.mjs'
    async function main () {
      await db.foo.create()
    
      let r = await db.foo.findOne()
      console.log(r.get({ plain: true }))
    
      let rr = await fixedDb.foo.findOne()
      console.log(rr.get({ plain: true }))
    }
    main()
    $ node --experimental-modules ./test.mjs
    {
      id: 1,
      createdAt: 2019-05-27T17:33:17.000Z,
      updatedAt: 2019-05-27T17:33:17.000Z,
      deletedAt: null
    }
    {
      id: 1,
      created_at: 2019-05-27T17:33:17.000Z,
      updated_at: 2019-05-27T17:33:17.000Z,
      deleted_at: null
    }

  21. leodutra commented on May 28, 2019

    @leodutra

    The underscore is not common in JavaScript properties, so makes more sense to consider camel case first.

  22. papb commented on Aug 29, 2019

    @papb
    Member

    Related: #11225

  23. CarlosDanielDev commented on Jan 28, 2020

    @CarlosDanielDev
    module.exports = {
      dialect: 'mysql',
      host: 'localhost',
      username: 'root',
      password: 'root',
      database: 'awesome',
      port: 3306,
      define: {
        timestamps: true,
       cameCased: true,
       underscoredAll: true,
      }
    };

    How can I change underscoredAll to Camel Case ?

  24. codeyourwayup commented on Jan 25, 2022

    @codeyourwayup

    createdAt : 'created_at', // will define attribute created_at on Model
    updatedAt : 'updated_at' , // will define attribute updated_at on Model
    deletedAt: 'deleted_at' ,

        tableName: 'user',
        paranoid: true, //soft deleted
        timestamps: true, // 自动维护时间戳 [ created_at、updated_at ]
        underscored: true, // 不使用驼峰样式自动添加属性,而是下划线样式 [ createdAt => created_at ]
    
  25. codeyourwayup commented on Jan 25, 2022

    @codeyourwayup

    this is how to fix

    {

    , {
    createdAt : 'created_at', // will define attribute created_at on Model
    updatedAt : 'updated_at' , // will define attribute updated_at on Model
    deletedAt: 'deleted_at' ,

        tableName: 'user',
        paranoid: true, //soft deleted
        timestamps: true, // 自动维护时间戳 [ created_at、updated_at ]
        underscored: true, // 不使用驼峰样式自动添加属性,而是下划线样式 [ createdAt => created_at ]
    

    }}

  26. weijie0 commented on Mar 31, 2022

    @weijie0

    // 你可以通过 'field' 属性指定自定义列名称:
    fieldWithUnderscores: { type: DataTypes.STRING, field: 'field_with_underscores' },

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    breaking changeFor issues and PRs. Changes that break compatibility and require a major version increment.type: featureDEPRECATED: replace with the "feature" issue type

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions