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
24.67k stars 650 forks source link

[FEATURE]: mysql2 wait_timeout in createConnection #2634

Open vinibgoulart opened 4 months ago

vinibgoulart commented 4 months ago

Describe what you want

Allow to set the wait_timeout for new mysql connections in drizzle. https://confluence.atlassian.com/stashkb/connection-timeout-with-mysql-database-297676189.html#:~:text=MySQL%20has%20its%20wait_timeout%20variable,connection%20before%20Stash%20does%20it.

I'm having issues related with this timeout, I'm using the same instance of mysql for all application but when the database stays without requests in the last 8 hours the connection is closed.

vinibgoulart commented 1 week ago

Any update for this? Is my architecture or configuration wrong?

// dbWrapper.ts
import { MySql2Database } from 'drizzle-orm/mysql2';

export const dbWrapper =
  <T>(db: () => MySql2Database<Record<string, never>>) =>
  (router: unknown) => {
    return {
      router: router as () => T,
      dbConnection: db,
    };
  };
// drizzle.ts
import { drizzle } from 'drizzle-orm/mysql2';
import { mysqlConnection } from './mysql';

export const db = () => drizzle({ client: mysqlConnection });
// mysql.ts
import { MySql2Database } from 'drizzle-orm/mysql2';
import mysql from 'mysql2/promise';
import { config } from 'src/config';

export type TDb = () => MySql2Database<Record<string, never>>;

export const mysqlConnection = mysql.createPool({
  host: config.MY_SQL_HOST,
  user: config.MY_SQL_USER,
  password: config.MY_SQL_PASSWORD || undefined,
  database: config.MY_SQL_DATABASE,
});
// app.ts
const appWrapper = dbWrapper<Express>(db)(express);

const dbConnection = appWrapper.dbConnection;
const app = appWrapper.router();

routesPublic(app, dbConnection);
// routesPublic.ts
import express from 'express';
import { TDb } from 'src/db/mysql';
import { userLogin } from 'src/user/userLogin';
import { userLogout } from 'src/user/userLogout';

export const routesPublic = (app: express.Express, dbConnection: TDb) => {
  app.post('/login', userLogin(dbConnection));
};

export default routesPublic;
// userLogin.ts
export const userLogin =
  (dbConnection: TDb) => async (req: Request, res: Response) => {
    const { username, password } = req.body;

    const [user] = await dbConnection()
      .select()
      .from(usuarios)
      .where(eq(usuarios.loginUsuario, username))
      .limit(1);
}