乐闻世界logo
搜索文章和话题

How to set primary key type to UUID via Sequelize CLI

1个答案

1

When using Sequelize CLI, to set the primary key type to UUID, follow these steps:

1. Install Dependencies

Ensure that you have installed Sequelize and the corresponding database drivers (e.g., pg, mysql), as well as Sequelize CLI. If not installed, you can install them using the following commands:

bash
npm install sequelize sequelize-cli npm install pg # Example for PostgreSQL

2. Initialize Sequelize

In your project directory, execute the following command to initialize Sequelize:

bash
npx sequelize-cli init

This will create the necessary configuration files and directories, including models, migrations, seeders, and config.

3. Create a Model

Use Sequelize CLI to generate a new model with the primary key set to UUID type. For example, to create a model named User, use the following command:

bash
npx sequelize-cli model:generate --name User --attributes id:UUID,name:string

This command generates a user.js model file in the models directory. Open this file and manually adjust the model definition to ensure the id field is correctly configured as a UUID primary key.

4. Modify the Model Definition

Update the model definition in models/user.js as follows:

javascript
'use strict'; const { Model, DataTypes } = require('sequelize'); module.exports = (sequelize) => { class User extends Model {} User.init({ id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true, allowNull: false }, name: DataTypes.STRING }, { sequelize, modelName: 'User', }); return User; };

Here, the id field is set to DataTypes.UUID with a default value of DataTypes.UUIDV4, meaning Sequelize automatically generates a UUIDv4 for new records if id is not specified.

5. Create a Migration

Generate a migration file to reflect these changes in the database. You can manually create or modify the migration file generated by Sequelize CLI to ensure the id field is correctly configured:

javascript
'use strict'; module.exports = { async up(queryInterface, Sequelize) { await queryInterface.createTable('Users', { id: { type: Sequelize.UUID, defaultValue: Sequelize.UUIDV4, primaryKey: true, allowNull: false }, name: { type: Sequelize.STRING } }); }, async down(queryInterface, Sequelize) { await queryInterface.dropTable('Users'); } };

6. Execute the Migration

After modifying the model and migration files, apply the migration to the database using the following command:

bash
npx sequelize-cli db:migrate

7. Test

Finally, verify everything works correctly by adding test code to create and query User instances, confirming that the id is properly set as a UUID.

By following these steps, you successfully configure the primary key type to UUID in Sequelize CLI. This setup is highly valuable when ensuring global uniqueness, such as in distributed systems.

2024年7月24日 17:14 回复

你的答案