3
2

Drizzleを使ったときに躓いたことの対処まとめ

Posted at

これはなに?

DrizzleというORMを使ってみたときに躓いたことの対処をまとめました。

リレーションテーブルを定義するとdrizzle studioが起動しない

例えば以下のようなスキーマを定義したとします。

export const master = createTable("master", {
  id: varchar("id", { length: 128 }).primaryKey(),
  createdAt: timestamp("created_at")
    .default(sql`CURRENT_TIMESTAMP`)
    .notNull(),
  updatedAt: timestamp("updatedAt"),
});

export const sub = createTable("sub", {
  id: varchar("id", { length: 128 }).primaryKey(),
  masterId: varchar("id", { length: 128 }),
  createdAt: timestamp("created_at")
    .default(sql`CURRENT_TIMESTAMP`)
    .notNull(),
  updatedAt: timestamp("updatedAt"),
});

このテーブルの内容から、masterからsubのリストを取得したいと考えてリレーションテーブルを定義します。

export const masterRelations = relations(master, ({ many }) => ({
  subs: many(sub),
}));

これで一見良さそうに見えますが、これでdrizzle-kit studioを起動しようとするとエラーが発生します。対処方法は簡単で、もう一方のテーブルのリレーションも作れば大丈夫です。

export const subRelations = relations(sub, ({ one }) => ({
  createdUser: one(master, {
    fields: [sub.master_id],
    references: [master.id],
  }),
}));

主キーを自動生成したい

Primary keyにCUIDを使って、それをスキーマ定義側で自動生成できるような実装ができないかと思って調べました。結論として、$defaultFnというメソッドを使って実現可能です。

export const table = createTable("table", {
  id: varchar("id", { length: 128 }).primaryKey().$defaultFn(createId),
  createdAt: timestamp("created_at")
    .default(sql`CURRENT_TIMESTAMP`)
    .notNull(),
  updatedAt: timestamp("updatedAt"),
});

createIdという関数を作って、一意なIDを返却するように実装します。

3
2
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
3
2