Postgres sequences
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 Not on the roadmap - You're the first one requesting the functionality. What's your usecase?
@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.
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 Well you can manually create the sequences and just have sequelize point at the tables.
+1
@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)
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,
},
@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,
};
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.
@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
In case there is someone who wants to do this as well read this answer on StackOverflow
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.