drizzle-team / drizzle-orm

Headless TypeScript ORM with a head. Runs on Node, Bun and Deno. Lives on the Edge and yes, it's a JavaScript ORM too 😅
https://orm.drizzle.team
Apache License 2.0
21.52k stars 487 forks source link

[BUG]: NextJS Drizzle schema changes requires restarting dev server #2422

Open jericopulvera opened 1 month ago

jericopulvera commented 1 month ago

What version of drizzle-orm are you using?

0.30.10

What version of drizzle-kit are you using?

0.21.2

Describe the Bug

I was defining a one to many relations while in dev turbo mode and it does compile but it does not recognize the changes until I restarted the server.

Expected behavior

Any relation changes made in schema not require full dev restart or at least output an info saying you need to restart the dev server.

Environment & setup

No response

fdarian commented 1 week ago

How did you instantiate drizzle? did you memoize the instance in globalThis (similarly)?

jericopulvera commented 1 week ago

How did you instantiate drizzle? did you memoize the instance in globalThis (similarly)?

import { env } from "@/env/server";
import { drizzle, MySql2Database } from "drizzle-orm/mysql2";
import mysql from "mysql2/promise";
import config from "./config";
import * as schema from "./schema";

const poolConnection = mysql.createPool(config);

let db: MySql2Database<typeof schema>;

declare global {
  var db: MySql2Database<typeof schema>;
}

if (env.NODE_ENV === "production") {
  db = drizzle(poolConnection, { schema, mode: "default" });
} else {
  if (!global.db)
    global.db = drizzle(poolConnection, { schema, mode: "default" });
  db = global.db;
}

export { db };
fdarian commented 1 week ago

That is expected then. global doesn't get "remounted" on every hot-module-reload, in fact that is the reason why some recommended to implement singleton using global so it doesn't spam db connections every time nextjs do hmr