2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「"BLOB/TEXT column 'user_id' used in key specification without a key length"」の解決方法

2
Posted at

はじめに

Better AuthとDrizzle ORMを使って、ログインしたユーザーごとにTodoを管理する機能を実装していました。

TodoテーブルにユーザーIDを追加し、Better Authのユーザーテーブルを参照する外部キーを設定したところ、マイグレーションでエラーが発生しました。

問題

発生したエラー

Error: BLOB/TEXT column 'user_id' used in key specification without a key length

元のコード

Todoテーブルを次のように定義していました。

import {
  boolean,
  int,
  mysqlTable,
  text,
  timestamp,
  varchar,
} from "drizzle-orm/mysql-core";
import { user } from "../auth-schema.js";

export const todosTable = mysqlTable("todos_table", {
  id: int().primaryKey().autoincrement(),
  userId: text("user_id")
    .notNull()
    .references(() => user.id, { onDelete: "cascade" }),
  title: varchar({ length: 255 }).notNull(),
  completed: boolean().notNull(),
  createdAt: timestamp().notNull(),
});

原因は、外部キーに指定した user_id を text 型にしていたことです。

MySQLでは、TEXT 型や BLOB 型のカラムを外部キーに使用できません。これらの型のインデックスにはプレフィックス長の指定が必要ですが、外部キーではプレフィックス付きインデックスを利用できないためです。

Index prefixes on foreign key columns are not supported. Consequently, BLOB and TEXT columns cannot be included in a foreign key because indexes on those columns must always include a prefix length.

参考:MySQL公式ドキュメント:FOREIGN KEY Constraints

また、参照先であるBetter Authの user.id は、次のように varchar(36) で定義されていました。

export const user = mysqlTable("user", {
  id: varchar("id", { length: 36 }).primaryKey(),
  // ほかのカラムは省略
});

文字列のIDだからと text 型にしていましたが、参照先の定義を確認する必要がありました。

解決方法

外部キーの型を参照先に合わせる

todosTable.userId を、参照先の user.id と同じ varchar(36) に変更しました。

import {
  boolean,
  int,
  mysqlTable,
  timestamp,
  varchar,
} from "drizzle-orm/mysql-core";
import { user } from "../auth-schema.js";

export const todosTable = mysqlTable("todos_table", {
  id: int().primaryKey().autoincrement(),
  userId: varchar("user_id", { length: 36 })
    .notNull()
    .references(() => user.id, { onDelete: "cascade" }),
  title: varchar({ length: 255 }).notNull(),
  completed: boolean().notNull(),
  createdAt: timestamp().notNull(),
});

認証スキーマもマイグレーション対象に含める

あわせて確認すると、drizzle.config.ts の schema にTodoのスキーマしか指定していませんでした。

schema: "./src/db/schema.ts",

Better Authの認証テーブルもDrizzleで管理するため、両方のファイルを指定しました。

import "dotenv/config";
import { defineConfig } from "drizzle-kit";

export default defineConfig({
  out: "./drizzle",
  schema: [
    "./src/db/schema.ts",
    "./src/auth-schema.ts",
  ],
  dialect: "mysql",
  dbCredentials: {
    url: process.env.DATABASE_URL!,
  },
});

おわりに

今回の直接の原因は、MySQLの外部キーに使うカラムを text 型で定義していたことでした。

また、Better Authのスキーマを別ファイルに分けている場合は、そのファイルもDrizzleのマイグレーション対象に含める必要がありました。

参考文献

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?