sequelize icon indicating copy to clipboard operation
sequelize copied to clipboard

Postgres sequences

Open leonprou opened this issue 11 years ago • 12 comments

Is there any intentions to implement postgres sequences? As I see the only option to use them now is with the raw query syntax

leonprou avatar Apr 18 '15 10:04 leonprou

@leonprou Not on the roadmap - You're the first one requesting the functionality. What's your usecase?

mickhansen avatar Apr 18 '15 10:04 mickhansen

@mickhansen thank for quick response I have users table with array of chats in it as a field, I would like to give an increment id for every new chat. I could use a separate table for chats, but then I'll have to join two tables. As I understand I can index an array or a JSONB field with Postgres, so this embedded solution (mongoDB style) sounds more suitable for my case.

leonprou avatar Apr 18 '15 14:04 leonprou

I'd like to :+1: this issue. My use case is migrating a legacy system which uses a 'global' sequence to generate IDs for multiple tables, as per this document:

CREATE SEQUENCE common_fruit_id_seq;

CREATE TABLE apples (
    id      INT4 DEFAULT nextval('common_fruit_id_seq') NOT NULL,
    price   NUMERIC
);

CREATE TABLE oranges (
    id      INT4 DEFAULT nextval('common_fruit_id_seq') NOT NULL,
    weight  NUMERIC
);

That said, this is probably just a sign of terrible database design, and having a central ID table/sequence is pants-on-head retarded.

jimmed avatar May 01 '15 16:05 jimmed

@jimmed Well you can manually create the sequences and just have sequelize point at the tables.

mickhansen avatar May 01 '15 16:05 mickhansen

+1

SerjoPepper avatar Jan 02 '16 23:01 SerjoPepper

@mickhansen can you elaborate on that? I currently have a column who's default value is nextval(' '). I create the object and left the field blank. But the sql query is rejected as it is not being recognized as an integer.

INSERT INTO client_table (client_id, name) VALUES (\'nextval(\'client_id_gen\')\', Johnny)

0xAlwaysDumpling avatar Mar 28 '17 00:03 0xAlwaysDumpling

I have solution for shis: Alter library sequelize file: squelize/lib/sql-string.js incluid on line 56 this:

change

if (dialect === 'postgres' || dialect === 'sqlite' || dialect === 'mssql'){
    // http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS
    // http://stackoverflow.com/q/603572/130598
    val = val.replace(/'/g, "''");
  } else {
    val = val.replace(/[\0\n\r\b\t\'"\x1a]/g, s => {
    switch (s) {
      case '\0': return '\0';
      case '\n': return '\n';
      case '\r': return '\r';
      case '\b': return '\b';
      case '\t': return '\t';
      case '\x1a': return '\Z';
      default: return '\' + s;
    }
  });
}

for

if (dialect === 'postgres' || dialect === 'sqlite' || dialect === 'mssql') {
  // http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS
  // http://stackoverflow.com/q/603572/130598
  if(val.indexOf('nextval(')>-1) {
    return val
  }
  val = val.replace(/'/g, "''");
  } else {
    val = val.replace(/[\0\n\r\b\t\'"\x1a]/g, s => {
    switch (s) {
      case '\0': return '\0';
      case '\n': return '\n';
      case '\r': return '\r';
      case '\b': return '\b';
      case '\t': return '\t';
      case '\x1a': return '\Z';

      default: return '\' + s;
    }
  });
}

On your model declare field with defaultValue = "nextval('xxxxxxx')", ex:

// ...
return sequelize.define('cgm', {
  z01_numcgm: {  
  type: DataTypes.INTEGER,
  defaultValue: "nextval('cgm_z01_numcgm_seq')",
  allowNull: false,
  primaryKey: true,
},

gstrtoint avatar Aug 29 '17 20:08 gstrtoint

@jimmed @jtan25 did you manage to solve this?

I need the primary key "id" prefixed with the table name.

But sequelize is autofilling the "id" column (which is given primaryKey=true) with "null" on insert thus I always get:

SequelizeDatabaseError: null value in column "id" violates not-null constraint

Here what I'm currently doing on my tables:

//custom sql after sync({ force: true }) 
//then for each model
const sequenceName = model.toLowerCase() + '_omniseq';
await database.query(`drop sequence if exists "${sequenceName}"`);
await database.query(`create sequence "${sequenceName}"`);
await database.query(`alter table "${model}" alter column id drop default`);
await database.query(`alter table "${model}" alter column id drop not null`);
await database.query(`alter table "${model}" alter column id set default '${model.toLowerCase()}'||nextval('${sequenceName}')::text not null`);
await database.query(`alter sequence "${sequenceName}" owned by "${model}".id`);             

//when defining models
definition.id = {
    type: Sequelize.TEXT,
    primaryKey: true,
    unique: true,
};

damianobarbati avatar Dec 08 '17 22:12 damianobarbati

I'd love to see this feature. Was looking for the same thing.

It seems like folks are still asking this question. See SO answer.

brian-human-interest avatar Dec 13 '19 22:12 brian-human-interest

@gstrtoint Thanks for solution. You saved me!!!! But when will this code merge in master branch? I have updated library on following path \node_modules\sequelize\lib\sql-string.js. Line No. 58. When I look there I found something interesting that the following comments are already presents

// http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS
// http://stackoverflow.com/q/603572/130598

But code is not present. So I put following code there at line no. 61 in \node_modules\sequelize\lib\sql-string.js

if(val.indexOf('nextval(')>-1) {
     return val
}

But it is not good practise to edit direct library file. So I am eager when should this comments will be merge in master? So on production server I don't need to edit manually this file. @gstrtoint @papb

yogeshbonzer avatar Feb 06 '20 09:02 yogeshbonzer

In case there is someone who wants to do this as well read this answer on StackOverflow

hikensensei avatar May 13 '21 18:05 hikensensei

We discussed this issue at our recent meeting. We're not convinced providing an API for this would be clearer than using raw SQL. We support using them on a single column using the autoIncrement option, but for other use cases I recommend just going with raw SQL.

We recommend doing it like on the StackOverflow post @hikensensei posted

In Models:

Use literal to use the sequence

import { literal, DataTypes } from 'sequelize';

sequelize.define("model", {
  ...attributes,
  customSequence: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: literal("nextval('custom_sequence')"),
  },
});

If you're using sequelize.sync, use the beforeSync hook to create the sequence (or create it before calling .sync):

sequelize.beforeSync(() => {
  await sequelize.query('CREATE SEQUENCE IF NOT EXISTS custom_sequence');
});

await sequelize.sync();

In Migrations

const { literal, DataTypes } = require('sequelize');

module.exports = {
  up: async (queryInterface) => {
    await queryInterface.sequelize.query('CREATE SEQUENCE custom_sequence');

    await queryInterface.addColumn('table', 'customSequence', {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: literal(`nextval('custom_sequence')`),
    });
  },

  down: async (queryInterface) => {
    await queryInterface.removeColumn('table', 'customSequence');
    await queryInterface.sequelize.query('DROP SEQUENCE custom_sequence');
  },
};

If you have use cases that could be demonstrably simplified by a built-in API for sequences, let us know.

ephys avatar May 20 '22 08:05 ephys