Map SQL VARCHAR and TEXT to Sequelize STRING and TEXT
Understand how SQL string types like VARCHAR, CHAR, TEXT, and NVARCHAR are mapped to Sequelize DataTypes.STRING, DataTypes.CHAR, and DataTypes.TEXT.
Detailed Explanation
SQL String Types in Sequelize
SQL databases offer several string types with different storage characteristics. Sequelize provides matching DataTypes constants for each, and this converter handles all common variants automatically.
VARCHAR to DataTypes.STRING
The most common string type in SQL is VARCHAR(n), which maps to DataTypes.STRING(n) in Sequelize. The length parameter is preserved:
email VARCHAR(255) NOT NULL
-- becomes -->
email: { type: DataTypes.STRING(255), allowNull: false }
If no length is specified (VARCHAR without parentheses), the converter uses DataTypes.STRING which defaults to 255 characters.
CHAR to DataTypes.CHAR
Fixed-length CHAR(n) maps to DataTypes.CHAR(n). This is less common but useful for codes like country codes or currency codes:
country_code CHAR(2) NOT NULL
-- becomes -->
country_code: { type: DataTypes.CHAR(2), allowNull: false }
TEXT to DataTypes.TEXT
For unbounded text, SQL TEXT, LONGTEXT, MEDIUMTEXT, and TINYTEXT all map to DataTypes.TEXT:
bio TEXT
-- becomes -->
bio: { type: DataTypes.TEXT, allowNull: true }
NVARCHAR and NCHAR
Unicode-specific types like NVARCHAR (SQL Server) map to DataTypes.STRING since Sequelize handles Unicode encoding at the connection level rather than the column level.
Practical Considerations
When choosing between STRING and TEXT, remember that STRING (VARCHAR) columns can be indexed efficiently while TEXT columns typically cannot be used in indexes directly. If you need to search or sort on a column, prefer DataTypes.STRING with an explicit length.
Use Case
You are migrating a SQL Server database that uses NVARCHAR columns extensively and need to understand how each string type translates to Sequelize's DataTypes for your Node.js application.