解决NextAuth搭配Prisma适配MySQL时的‘指定键过长’错误
解决NextAuth + Prisma适配器连接MySQL 5.7时的索引长度错误
错误原因
MySQL 5.7的InnoDB引擎默认单索引最大长度为1000字节,而Prisma默认使用utf8mb4编码(每个字符占4字节),NextAuth提供的Prisma Schema中,部分联合索引(如Account表的@@unique([provider, providerAccountId]))或长字段唯一索引的总字节数超过了这个限制,导致迁移失败。
解决方法
方法1:修改数据库默认字符集为utf8
utf8编码每个字符占3字节,能有效降低索引总字节数:
- 手动修改数据库字符集:
ALTER DATABASE prisma_mysql CHARACTER SET utf8 COLLATE utf8_general_ci;
- 在Prisma Schema的
datasource块中指定字符集配置:
datasource db { provider = "mysql" url = env("DATABASE_URL") characterSet = "utf8" collate = "utf8_general_ci" }
- 重新执行迁移命令:
npx prisma migrate dev
方法2:限制索引字段的长度
如果需要保留utf8mb4编码(支持emoji等特殊字符),可以给涉及索引的String字段添加长度限制(推荐191字节,因为191*4=764 < 1000):
修改Prisma Schema中的模型字段:
model Account { id String @id @default(cuid()) userId String type String provider String @db.VarChar(191) providerAccountId String @db.VarChar(191) refresh_token String? @db.Text access_token String? @db.Text expires_at Int? token_type String? scope String? id_token String? @db.Text session_state String? user User @relation(fields: [userId], references: [id], onDelete: Cascade) @@unique([provider, providerAccountId]) } model Session { id String @id @default(cuid()) sessionToken String @unique @db.VarChar(191) userId String expires DateTime user User @relation(fields: [userId], references: [id], onDelete: Cascade) } model User { id String @id @default(cuid()) name String? email String? @unique @db.VarChar(191) emailVerified DateTime? image String? accounts Account[] sessions Session[] } model VerificationToken { identifier String @db.VarChar(191) token String @unique @db.VarChar(191) expires DateTime @@unique([identifier, token]) }
修改完成后重新执行迁移:
npx prisma migrate dev
方法3:升级MySQL到8.0(备选)
MySQL 8.0的InnoDB引擎索引最大长度提升至3072字节,默认即可兼容utf8mb4编码的长索引,但如果必须保留MySQL 5.7,此方法不适用。
内容的提问来源于stack exchange,提问作者Siddhant Kumar
相关产品推荐
相关产品推荐

