Repository navigation
Closed as not planned
Closed as not planned
Copy link
Labels
pending-approvalBug reports that have not been verified yet, or feature requests that have not been accepted yettype: bugDEPRECATED: replace with the "bug" issue type
Description
Issue Creation Checklist
- I understand that my issue will be automatically closed if I don't fill in the requested information
- I have read the contribution guidelines
Bug Description
Setting defaultValue with sequelize v6 with Microsoft SQL Server 2019 breaks sequelize.sync({ alter: true }).
It seems this is a know issue for years.
I created a docker-compose.yml file to spin up necessary mssql/server:2019 and node, Javascript is inline.
Run docker compose up --force-recreate to always have updated inline script.
Reproducible Example
# docker-compose.yml
services:
sqlserver:
image: mcr.microsoft.com/mssql/server:2019-latest
container_name: sqlserver
environment:
ACCEPT_EULA: 'Y'
SA_PASSWORD: 'Passw0rd!'
node:
image: node:20
container_name: node
configs:
- source: package.json
target: /home/node/package.json
- source: index.js
target: /home/node/index.js
entrypoint: ""
command: >
sh -c "cd /home/node && npm install sequelize tedious sqlite3 && node index.js"
configs:
package.json:
content: |
{
"name": "sequelize-mssql",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"license": "ISC"
}
index.js:
content: |
// ***** JAVASCRIPT STARTS HERE *****
import { Sequelize, DataTypes } from 'sequelize';
//const sequelize = new Sequelize('sqlite::memory:');
const sequelize = new Sequelize('tempdb', 'SA', 'Passw0rd!', {
host: 'sqlserver',
dialect: 'mssql',
dialectOptions: {
options: {
encrypt: true,
trustServerCertificate: true
}
}
});
await sequelize.authenticate();
const User = sequelize.define('User', {
username: DataTypes.STRING,
birthday: DataTypes.DATE,
default: {
type: DataTypes.STRING,
defaultValue: 'test'
},
enum: {
type: DataTypes.ENUM,
values: ['1', '2', '3']
}
});
console.log('Force table re-creation')
await sequelize.sync({ force: true })
const jane = await User.create({
username: 'janedoe',
birthday: new Date(1980, 6, 20),
});
const users = await User.findAll();
console.log('users', users)
console.log('Alter table')
await sequelize.sync({ alter: true })
What do you expect to happen?
Successful migration, in this case nothing should happen, no errors.
What is actually happening?
node | Alter table
node | Executing (default): SELECT TABLE_NAME, TABLE_SCHEMA FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = N'Users' AND TABLE_SCHEMA = N'dbo'
node | Executing (default): SELECT c.COLUMN_NAME AS 'Name', c.DATA_TYPE AS 'Type', c.CHARACTER_MAXIMUM_LENGTH AS 'Length', c.IS_NULLABLE as 'IsNull', COLUMN_DEFAULT AS 'Default', pk.CONSTRAINT_TYPE AS 'Constraint', COLUMNPROPERTY(OBJECT_ID('[' + c.TABLE_SCHEMA + '].[' + c.TABLE_NAME + ']'), c.COLUMN_NAME, 'IsIdentity') as 'IsIdentity', CAST(prop.value AS NVARCHAR) AS 'Comment' FROM INFORMATION_SCHEMA.TABLES t INNER JOIN INFORMATION_SCHEMA.COLUMNS c ON t.TABLE_NAME = c.TABLE_NAME AND t.TABLE_SCHEMA = c.TABLE_SCHEMA LEFT JOIN (SELECT tc.table_schema, tc.table_name, cu.column_name, tc.CONSTRAINT_TYPE FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE cu ON tc.table_schema=cu.table_schema and tc.table_name=cu.table_name and tc.constraint_name=cu.constraint_name and tc.CONSTRAINT_TYPE='PRIMARY KEY') pk ON pk.table_schema=c.table_schema AND pk.table_name=c.table_name AND pk.column_name=c.column_name INNER JOIN sys.columns AS sc ON sc.object_id = OBJECT_ID('[' + t.TABLE_SCHEMA + '].[' + t.TABLE_NAME + ']') AND sc.name = c.column_name LEFT JOIN sys.extended_properties prop ON prop.major_id = sc.object_id AND prop.minor_id = sc.column_id AND prop.name = 'MS_Description' WHERE t.TABLE_NAME = 'Users'
node | Executing (default): SELECT constraint_name = OBJ.NAME, constraintName = OBJ.NAME, constraintCatalog = 'tempdb', constraintSchema = SCHEMA_NAME(OBJ.SCHEMA_ID), tableName = TB.NAME, tableSchema = SCHEMA_NAME(TB.SCHEMA_ID), tableCatalog = 'tempdb', columnName = COL.NAME, referencedTableSchema = SCHEMA_NAME(RTB.SCHEMA_ID), referencedCatalog = 'tempdb', referencedTableName = RTB.NAME, referencedColumnName = RCOL.NAME FROM sys.foreign_key_columns FKC INNER JOIN sys.objects OBJ ON OBJ.OBJECT_ID = FKC.CONSTRAINT_OBJECT_ID INNER JOIN sys.tables TB ON TB.OBJECT_ID = FKC.PARENT_OBJECT_ID INNER JOIN sys.columns COL ON COL.COLUMN_ID = PARENT_COLUMN_ID AND COL.OBJECT_ID = TB.OBJECT_ID INNER JOIN sys.tables RTB ON RTB.OBJECT_ID = FKC.REFERENCED_OBJECT_ID INNER JOIN sys.columns RCOL ON RCOL.COLUMN_ID = REFERENCED_COLUMN_ID AND RCOL.OBJECT_ID = RTB.OBJECT_ID WHERE TB.NAME ='Users'
node | Executing (default): ALTER TABLE [Users] ALTER COLUMN [username] NVARCHAR(255) NULL;
node | Executing (default): ALTER TABLE [Users] ALTER COLUMN [birthday] DATETIMEOFFSET NULL;
node | Executing (default): ALTER TABLE [Users] ALTER COLUMN [default] NVARCHAR(255) DEFAULT N'test';
node | node:internal/modules/run_main:129
node | triggerUncaughtException(
node | ^
node |
node | Error
node | at Query.run (/home/node/node_modules/sequelize/lib/dialects/mssql/query.js:107:25)
node | at /home/node/node_modules/sequelize/lib/sequelize.js:315:28
node | at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
node | at async User.sync (/home/node/node_modules/sequelize/lib/model.js:984:11)
node | at async Sequelize.sync (/home/node/node_modules/sequelize/lib/sequelize.js:377:9)
node | at async file:///home/node/index.js:41:1 {
node | name: 'SequelizeDatabaseError',
node | parent: RequestError: Incorrect syntax near the keyword 'DEFAULT'.
node | at RequestTokenHandler.onErrorMessage (/home/node/node_modules/tedious/lib/token/handler.js:286:21)
node | at Readable.<anonymous> (/home/node/node_modules/tedious/lib/token/token-stream-parser.js:18:33)
node | at Readable.emit (node:events:519:28)
node | at addChunk (node:internal/streams/readable:559:12)
node | at readableAddChunkPushObjectMode (node:internal/streams/readable:536:3)
node | at Readable.push (node:internal/streams/readable:391:5)
node | at nextAsync (node:internal/streams/from:194:22)
node | at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
node | code: 'EREQUEST',
node | number: 156,
node | state: 1,
node | class: 15,
node | serverName: 'a7302390c4ae',
node | procName: '',
node | lineNumber: 1,
node | sql: "ALTER TABLE [Users] ALTER COLUMN [default] NVARCHAR(255) DEFAULT N'test';",
node | parameters: undefined
node | },
node | original: RequestError: Incorrect syntax near the keyword 'DEFAULT'.
node | at RequestTokenHandler.onErrorMessage (/home/node/node_modules/tedious/lib/token/handler.js:286:21)
node | at Readable.<anonymous> (/home/node/node_modules/tedious/lib/token/token-stream-parser.js:18:33)
node | at Readable.emit (node:events:519:28)
node | at addChunk (node:internal/streams/readable:559:12)
node | at readableAddChunkPushObjectMode (node:internal/streams/readable:536:3)
node | at Readable.push (node:internal/streams/readable:391:5)
node | at nextAsync (node:internal/streams/from:194:22)
node | at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
node | code: 'EREQUEST',
node | number: 156,
node | state: 1,
node | class: 15,
node | serverName: 'a7302390c4ae',
node | procName: '',
node | lineNumber: 1,
node | sql: "ALTER TABLE [Users] ALTER COLUMN [default] NVARCHAR(255) DEFAULT N'test';",
node | parameters: undefined
node | },
node | sql: "ALTER TABLE [Users] ALTER COLUMN [default] NVARCHAR(255) DEFAULT N'test';",
node | parameters: {}
node | }
node |
node | Node.js v20.15.0
node exited with code 1
Environment
- Sequelize version: [email protected], [email protected] /root/sequelize-mssql
- Node.js version: Node.js v20.15.0
- If TypeScript related: TypeScript version: n/a
- Database & Version: MS SQL Server 2019
- Connector library & Version: [email protected]
Would you be willing to resolve this issue by submitting a Pull Request?
- Yes, I have the time and I know how to start.
- Yes, I have the time but I will need guidance. (And don't know SQL, sequelize, tedious 😄)
- No, I don't have the time, but my company or I are supporting Sequelize through donations on OpenCollective.
- No, I don't have the time, and I understand that I will need to wait until someone from the community or maintainers is interested in resolving my issue.
Indicate your interest in the resolution of this issue by adding the 👍 reaction. Comments such as "+1" will be removed.
Metadata
Metadata
Assignees
Labels
pending-approvalBug reports that have not been verified yet, or feature requests that have not been accepted yettype: bugDEPRECATED: replace with the "bug" issue type
Activity
bluepuma77 commentedon Jun 26, 2024
Another related issue. I hope the easy option to reproduce helps.
bluepuma77 commentedon Jun 27, 2024
Interestingly, it works with
UUIDdefaultValue:but breaks with
STRINGdefaultValue:arunvvijayan commentedon Oct 7, 2024
ALTER TABLE [co_business] ALTER COLUMN [sites_allowed] INTEGER NOT NULL DEFAULT 1;
this not the write SQL query to Alter and add an default constraint
should be like this
ALTER TABLE [co_business] ALTER COLUMN [sites_allowed] INTEGER NOT NULL;
ALTER TABLE [co_business] ADD CONSTRAINT DF_sites_allowed DEFAULT 1 FOR [sites_allowed];
but in the sequelize node modules -> node_modules\sequelize\lib\dialects\mssql\query-generator.js.map
there is an function called changeColumnQuery(tableName, attributes)
the highlighted lines have to update properly by @sequelize team,
for the time being we can change the code,
this way we have add the default value to the MSSQL database table columns if you are using
db.sync{alter: true}But if already Default Value present you should delete first and then you have to use the command
appreciate if any find the proper solution
arunvvijayan commentedon Oct 7, 2024
if you are using
db.sync{alter: false}in -> node_modules\sequelize\lib\dialects\mssql\query-generator.js
Add the DataTypes you want to add default value
then
const itemvalue = this.escape(attribute.defaultValue);
let newValue = itemvalue.startsWith("N") ? itemvalue.slice(1) : itemvalue;
By Adding the bellow code you can eliminate the N before the default values like DEFAULT N'T' -> DEFAULT 'T'
this will be working solution if you are using db.sync({alter: false})
I have done this and working fine. until we go for an column updates in existing table with data this solution is fine
@nodejs @sequelize teams should solve this issue.
WikiRik commentedon Oct 9, 2024
I'm closing this in favour of #14294
As was mentioned there by one of the maintainers;