[Postgres] Omitting defaultValue at model definition
Hello, I'm trying to create a model using a custom id field "id" with type UUID, setting a defaultValue as UUIDV4 as shown:
const User = sequelize.define('User', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4 ,
primaryKey: true
},
first_name: DataTypes.STRING,
last_name: DataTypes.STRING,
email: {
type: DataTypes.STRING,
isUnique: true,
allowNull: false,
validate: {
isEmail: true
}
},
test: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV1
}
});
But I'm getting this on sync():
CREATE TABLE IF NOT EXISTS "Users" ("id" UUID , "first_name" VARCHAR(255), "last_name" VARCHAR(255), "email" VARCHAR(255) NOT NULL, "test" UUID, "createdAt" TIMESTAMP WITH TIME ZONE NOT
NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY ("id"));
As you can see, it's not setting the default value neither at 'id' field nor 'test' field
Do you have any idea why I'm getting this? Thanks!
Dialect: postgres Dialect version: 7.4.0 Database version: 9.6.3 Sequelize version: 4.22.7
Well, now I see it already inserts correct data when using User.create(), but I get an "ERROR: null value in column "id" violates not-null constraint" when I use queryInterface.bulkInsert() at my seeder.
You guys know what's wrong with bulkInsert?
In sequelize model is one responsible for creating that UUID value, not dabase. Due to that, queryInterface.bulkInsert() requires you to insert uuid value to that id field.
example
queryInterface.bulkInsert('User', [{
id: '73ebadf2-49c2-4b05-8fad-66e49cabccf0',
first_name: 'John',
last_name: 'Smith',
email: '[email protected]
test: '32dfc5ec-d248-11e7-8941-cec278b6b50a'
}]);
@ezelohar what if I have a custom default value involving a custom sequence?
I have the same problem: I defined a custom "sequenced" default value for my primary key.
//when defining models
definition.id = {
type: Sequelize.TEXT,
primaryKey: true,
unique: true,
};
//custom sql after sync
await database.sync({ force: true });
//for each model/table
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 set default '${model.toLowerCase()}'||nextval('${sequenceName}')::text`);
But now I can't insert anything without explicit id!
SequelizeDatabaseError: null value in column "id" violates not-null constraint
at Query.formatError (node_modules/sequelize/lib/dialects/postgres/query.js:356:16)
at query.catch.err (node_modules/sequelize/lib/dialects/postgres/query.js:86:18)
....
console.log node_modules/better-console/index.js:22
Executing (default): INSERT INTO "user" ("id","identifier","secret","status","addedAt","editedAt") VALUES (NULL,'[email protected]','bruce.wayne','pending','2017-12-08 22:06:38.824 +00:00','2017-12-08 22:06:38.824 +00:00') RETURNING *;
@Rovaro did you manage to solve this?
Hi @damianobarbati , -
As i can see in your code above, you do not have a defaultValue. You set your id to be a text without a default value. This means that there is no default value for Sequelize model or sql database to fill in when you are inserting that data so it tries to insert null into the ID column.
My advice for you is to use uuids or integers for primary keys (ID) with default values. Or if you really need it to be type: TEXT, then provide value for ID every time you want to insert that data.
Help for ID definition for uuids/integers uuids
definition.id = {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
primaryKey: true,
};
Integers
definition.id = {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
};
@ezelohar thanks for helping!
Now I see the problem: sequelize is trying to insert anyway a defaultValue.
I cannot define a defaultValue on the model because I have no way to define with sequelize the needed logic (model+nextval, and I cannot use the UUID: I need that exact kind of pattern for the ids right now as defined manually on postgres schema).
When inserting manually from psql everything works fine and I have the expected ids (user1, user2, and so on).
@mickhansen is there a way to have sequelize "not set" a defaultValue on its own when creating new rows? If sequelize simply wasn't trying to set id to null, everything would work as expected. I'm stuck :(
Solved assigning explicitly to id Sequelize.literal('DEFAULT')
@ezelohar I have the same problem with integer primary keys. ` const Filter = sequelize.define('filters', { id: { type: SequelizeClass.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false }, filter:{ type: SequelizeClass.STRING, isUnique: true, allowNull: false } }, { timestamps: false, underscored: true } );
sequelize.transaction().then(function(t) { Filter.create( { filter: 'some string' }, {transaction: t} ).then(function() { t.commit(); }).catch(function(error) { node.error(error); t.rollback(); }); }); `
Results: "SequelizeDatabaseError: null value in column "id" violates not-null constraint"
I have the same problem, I migrated from version 3 to 4 in the version 3 I solved it adding allowNull: false but in the version 4, it doesn't work.
code:
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
}
SequelizeDatabaseError: null value in column "id" violates not-null constraint
@kesmile @teddybee You guys are setting autoIncrement: true so, why would you need to establish the allowNull option to false? Your model definition will autoset your id value whereby you don't need to use the non-null specification.
If you are trying to use bulkInsert() for creating your rows, I highly recommend you to take a look at @ezelohar 's first response (I'm not sure if this case could produce the same "problem" as if you were working with UUID identifiers) .
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 🙂
Hi I have the same problem with 4.42.0. Postgres 11 id: {type: Sql.INTEGER, primaryKey:true, autoIncrement: true } ,
I also tried omitNull: true, removing the id definition (allow postgres to handle the id field creation by itself). But with no avail. The error is caused by
Model.findOrCreate({})
Error is:
Executing (483d0bf1-3b84-44dd-9c1f-dd876ec0fbc3): START TRANSACTION;
Executing (483d0bf1-3b84-44dd-9c1f-dd876ec0fbc3): SELECT "id", "user_id", "socket_id", "event_id", "server_id", "active" FROM "socketlists" AS "socketlist" WHERE "socketlist"."socket_id" = '99h0dHdlDRYHgsMDAAAA' AND "socketlist"."active" = true LIMIT 1;
Executing (483d0bf1-3b84-44dd-9c1f-dd876ec0fbc3): CREATE OR REPLACE FUNCTION pg_temp.testfunc(OUT response "socketlists", OUT sequelize_caught_exception text) RETURNS RECORD AS $func_68e0d312ba9e41dd9f452e72c41133ea$ BEGIN INSERT INTO "socketlists" ("socket_id","active") VALUES ('99h0dHdlDRYHgsMDAAAA',true) RETURNING * INTO response; EXCEPTION WHEN unique_violation THEN GET STACKED DIAGNOSTICS sequelize_caught_exception = PG_EXCEPTION_DETAIL; END $func_68e0d312ba9e41dd9f452e72c41133ea$ LANGUAGE plpgsql; SELECT (testfunc.response).*, testfunc.sequelize_caught_exception FROM pg_temp.testfunc(); DROP FUNCTION IF EXISTS pg_temp.testfunc();
Executing (483d0bf1-3b84-44dd-9c1f-dd876ec0fbc3): COMMIT;
Socket was not saved for userId: 1 { SequelizeDatabaseError: null value in column "id" violates not-null constraint
at Query.formatError (C:\d\code\js\emps_bbone\node_modules\sequelize\lib\dialects\postgres\query.js:363:16)
at query.catch.err (C:\d\code\js\emps_bbone\node_modules\sequelize\lib\dialects\postgres\query.js:86:18)
at tryCatcher (C:\d\code\js\emps_bbone\node_modules\bluebird\js\release\util.js:16:23)
at Promise._settlePromiseFromHandler (C:\d\code\js\emps_bbone\node_modules\bluebird\js\release\promise.js:512:31)
at Promise._settlePromise (C:\d\code\js\emps_bbone\node_modules\bluebird\js\release\promise.js:569:18)
at Promise._settlePromise0 (C:\d\code\js\emps_bbone\node_modules\bluebird\js\release\promise.js:614:10)
at Promise._settlePromises (C:\d\code\js\emps_bbone\node_modules\bluebird\js\release\promise.js:690:18)
at _drainQueueStep (C:\d\code\js\emps_bbone\node_modules\bluebird\js\release\async.js:138:12)
at _drainQueue (C:\d\code\js\emps_bbone\node_modules\bluebird\js\release\async.js:131:9)
at Async._drainQueues (C:\d\code\js\emps_bbone\node_modules\bluebird\js\release\async.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (C:\d\code\js\emps_bbone\node_modules\bluebird\js\release\async.js:17:14)
at runCallback (timers.js:705:18)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)
name: 'SequelizeDatabaseError',
parent:
{ error: null value in column "id" violates not-null constraint
at Connection.parseE (C:\d\code\js\emps_bbone\node_modules\pg\lib\connection.js:601:11)
at Connection.parseMessage (C:\d\code\js\emps_bbone\node_modules\pg\lib\connection.js:398:19)
at Socket.
Solved assigning explicitly to id
Sequelize.literal('DEFAULT')
Thank you it so good, My sequelize generate ignore autoincrement
Edit from
User.init({
userId: {
type: DataTypes.INTEGER,
field: 'user_id',
primaryKey: true,
autoIncrement: true
}
}
To
User.init({
userId: {
type: DataTypes.INTEGER,
field: 'user_id',
primaryKey: true,
autoIncrement: true,
defaultValue: sequelize.literal('DEFAULT')
}
}