isidore
isidore

Reputation: 25

Why does sequlize transform OID attribut to `o_i_d`?

I'm trying to create a new entity "OrderInfo" but sequelize convert the OID attribut to o_i_d when requesting sql

OrderInfo class:

const { Model, DataTypes } = require('sequelize');
const sequelize = require('../db/db');

class OrderInfo extends Model {}

OrderInfo.init({
  OID: {
    type: DataTypes.INTEGER,
    primaryKey: true,
  },
  id_client: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  id_commande: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  date: {
    type: DataTypes.STRING,
    allowNull: false,
  },
}, {
  sequelize,
  createdAt: 'date',
  tableName: 'commande_info',
});

module.exports = OrderInfo;

addOrderToOrderInfo: async (idClient, idCommande) => {
    const newOrderInfo = await OrderInfo.create({
      id_client: idClient,
      id_commande: idCommande,
      date: `${new Date()}`,
    });

Sequelize error:

 code: 'ER_BAD_FIELD_ERROR',
    errno: 1054,
    sqlState: '42S22',
    sqlMessage: "Unknown column 'o_i_d' in 'field list'",
    sql: 'INSERT INTO `commande_info` (`o_i_d`,`id_client`,`id_commande`,`date`,`updated_at`) VALUES (?,?,?,?,?);',

I've tried to change OID to oid and when i do it Sequelize request 'oid' as agreed, but if i do so i need to update my databse and all my others programs

Upvotes: 1

Views: 91

Answers (2)

madflow
madflow

Reputation: 8520

Funny enough - I cannot replicate this just by using a simple sqlite connection and the code above. Maybe there is something in the config module?

But - for legacy tables, there is:

https://sequelize.org/docs/v6/other-topics/legacy/#fields

So

    OID: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      field: "OID",
    },

could do the trick.

Upvotes: 0

Martijn
Martijn

Reputation: 16123

I'm going to guess its the upper case. Try the following:

oid: {
  type: DataTypes.INTEGER,
  primaryKey: true,
},

You can verify this by changing the following example. If I'm right this should keep working:

oid: {
  ...
},
idClient: {
  ...
},
idCommande: {
  ...
},

It's common for ORM/mappers to apply the following rules:

  • Lowercase first char
  • Replace each capital for [underscore + lowercase version]
    • FooBar -> fooBar -> foo_bar
    • idClient -> idClient -> id_client
    • OID -> oID -> o_i_d

This is often done because the camelCase reads easier, but database definitions are almost always lowercase and snake_cased.

Upvotes: 0

Related Questions