Repository navigation
Expand file tree
/
Copy pathmysql.ts
More file actions
54 lines (48 loc) · 1.5 KB
/
Copy pathmysql.ts
File metadata and controls
54 lines (48 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* MySQL dialect adapter.
*
* Uses the 'mysql2' package for MySQL connections.
* Install with: npm install mysql2
*/
import { Kysely, MysqlDialect } from 'kysely';
import type { ConnectionConfig, ConnectionResult } from '../types.js';
import { DEFAULT_PORTS, connectTimeoutFor } from '../defaults.js';
/**
* Create a MySQL connection.
*
* @example
* ```typescript
* const conn = createMysqlConnection({
* dialect: 'mysql',
* host: 'localhost',
* database: 'myapp',
* user: 'root',
* password: 'secret',
* })
* ```
*/
export async function createMysqlConnection(config: ConnectionConfig): Promise<ConnectionResult> {
// Dynamic import to avoid compile-time dependency
const mysql2 = await import('mysql2');
const createPool = mysql2.default?.createPool ?? mysql2.createPool;
const pool = createPool({
host: config.host ?? 'localhost',
port: config.port ?? DEFAULT_PORTS.mysql,
user: config.user,
password: config.password,
database: config.database,
connectionLimit: config.pool?.max ?? 10,
ssl: config.ssl ? {} : undefined,
// mysql2 defaults this to 10s. Set explicitly so every dialect gives
// up on the same schedule and one override moves all of them.
connectTimeout: connectTimeoutFor(config),
});
const db = new Kysely<unknown>({
dialect: new MysqlDialect({ pool }),
});
return {
db,
dialect: 'mysql',
destroy: () => db.destroy(),
};
}