@milkio/template-milkio 1.3.66 → 1.3.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "type": "git",
5
5
  "url": "https://github.com/akirarika/milkio"
6
6
  },
7
- "version": "1.3.66",
7
+ "version": "1.3.68",
8
8
  "keywords": [
9
9
  "template"
10
10
  ],
@@ -1,7 +1,9 @@
1
+ import { fileURLToPath } from 'node:url';
1
2
  import mysql from 'mysql2/promise';
2
3
  import { drizzle } from 'drizzle-orm/mysql2';
3
4
  import { getTestDatabaseId, withTestDatabase } from '@milkio/drizzle';
4
5
  import * as schema from '../../../.milkio/drizzle-schema.ts';
6
+ import { prepareTestDatabase } from '../../utils/drizzle-test.ts';
5
7
  import type { MilkioWorld } from 'milkio';
6
8
  import type { generated } from '../../../.milkio/index.ts';
7
9
 
@@ -14,6 +16,36 @@ const pools = new Map<string, mysql.Pool | mysql.Connection>();
14
16
  // 因此给缓存的连接数加上限,超出时按插入顺序淘汰最旧的(LRU)。
15
17
  const MAX_CACHED_CLIENTS = 32;
16
18
 
19
+ // ---- 测试库懒初始化 ----
20
+ // astra 的 mirror world 在创建时就携带随机测试库名,即使测试从未调用
21
+ // cleanDatabase(),请求也会带上 x-milkio-test-db。这里保证该随机库真实存在:
22
+ // 首次遇到时检查库是否存在,不存在则从黄金库克隆 DDL + seed(与 cleanDatabase
23
+ // 同一套逻辑)。已处理过的库名缓存起来,避免每次请求都做存在性检查。
24
+ const MIGRATIONS_FOLDER = fileURLToPath(new URL('../../../drizzle', import.meta.url));
25
+ const handledTestDatabaseIds = new Set<string>();
26
+
27
+ async function ensureTestDatabaseReady(baseUrl: string, databaseId: string): Promise<void> {
28
+ if (handledTestDatabaseIds.has(databaseId)) return;
29
+ const adminUrl = new URL(baseUrl);
30
+ adminUrl.pathname = '/';
31
+ const admin = await mysql.createConnection({ uri: adminUrl.toString(), timezone: '+00:00' });
32
+ let exists = false;
33
+ try {
34
+ const [rows] = await admin.query(`SHOW DATABASES LIKE '${databaseId}'`);
35
+ exists = (rows as Array<any>).length > 0;
36
+ } finally {
37
+ await admin.end();
38
+ }
39
+ if (exists) {
40
+ // 测试进程的 cleanDatabase 已建好并 seed 过,直接复用
41
+ handledTestDatabaseIds.add(databaseId);
42
+ return;
43
+ }
44
+ console.log(`[MySQL] Lazy preparing test database ${databaseId}...`);
45
+ await prepareTestDatabase(baseUrl, databaseId, MIGRATIONS_FOLDER);
46
+ handledTestDatabaseIds.add(databaseId);
47
+ }
48
+
17
49
  export function loadDrizzle(world: MilkioWorld<typeof generated>) {
18
50
  world.on('milkio:executeBefore', async (event) => {
19
51
  const baseUrl = world.config.drizzle.url;
@@ -21,6 +53,10 @@ export function loadDrizzle(world: MilkioWorld<typeof generated>) {
21
53
  // 测试模式下,astra 会携带 x-milkio-test-db 请求头指明本次请求的随机数据库;
22
54
  // 没有携带时(本地网页调试 / 生产环境)走默认库,行为与旧版完全一致。
23
55
  const databaseId = getTestDatabaseId(event.context.headers);
56
+ // 测试模式下确保随机测试库已就绪;无头请求走默认库,不影响本地调试/生产
57
+ if (world.isTestMode && databaseId) {
58
+ await ensureTestDatabaseReady(baseUrl, databaseId);
59
+ }
24
60
  const url = withTestDatabase(baseUrl, databaseId);
25
61
 
26
62
  let pool = pools.get(url);
@@ -142,6 +142,25 @@ export function getCurrentTestDbUrl(baseUrl: string): string {
142
142
  return withTestDatabase(baseUrl, testDbState.databaseId);
143
143
  }
144
144
 
145
+ /**
146
+ * 确保随机测试库已就绪:从黄金库克隆 DDL + 迁移记录,再执行 seed。
147
+ * 测试进程的 cleanDatabase 钩子和服务端懒初始化(bootstrap/drizzle)都复用这里,
148
+ * 保证「没调 cleanDatabase 的测试请求」落在隔离随机库时同样能正常执行。
149
+ */
150
+ export async function prepareTestDatabase(baseUrl: string, databaseId: string, migrationsFolder: string): Promise<void> {
151
+ await ensureGoldenDatabase({ baseUrl, migrationsFolder });
152
+ await cloneGoldenDatabase(baseUrl, databaseId);
153
+
154
+ const connection = await mysql.createConnection({ uri: withTestDatabase(baseUrl, databaseId), timezone: '+00:00' });
155
+ try {
156
+ await connection.query("SET time_zone = '+00:00'");
157
+ const db = drizzle(connection, { schema, mode: 'default' });
158
+ await db.transaction(async (tx) => executeSeed({ db: tx }));
159
+ } finally {
160
+ await connection.end();
161
+ }
162
+ }
163
+
145
164
  /**
146
165
  * 跟随当前随机测试库的直连 db。cleanDatabase 每次切库都会重建底层连接,
147
166
  * 测试文件直接 import 这个 db 使用即可,无需关心当前库名。
@@ -167,16 +186,13 @@ export function drizzleCleanHook(options: {
167
186
  }): CleanDatabaseHook {
168
187
  return async ({ databaseId }) => {
169
188
  const baseUrl = (await options.baseUrl()).replace(/\/$/, '');
170
- await ensureGoldenDatabase({ baseUrl, migrationsFolder: options.migrationsFolder });
171
- await cloneGoldenDatabase(baseUrl, databaseId);
189
+ await prepareTestDatabase(baseUrl, databaseId, options.migrationsFolder);
172
190
 
173
191
  const url = withTestDatabase(baseUrl, databaseId);
174
192
  const connection = await mysql.createConnection({ uri: url, timezone: '+00:00' });
175
193
  await connection.query("SET time_zone = '+00:00'");
176
194
  const db = drizzle(connection, { schema, mode: 'default' });
177
195
 
178
- await db.transaction(async (tx) => executeSeed({ db: tx }));
179
-
180
196
  // 切换到新库:关闭上一个测试库的连接并删除该库。
181
197
  // 分区表克隆每库可达 100MB+,只增不减会撑爆磁盘;切库即删让同时存在的
182
198
  // 测试库数量 = 并行测试文件数(个位数),磁盘占用保持个位数 GB 以内。
@@ -9,10 +9,10 @@
9
9
  },
10
10
  "trustedDependencies": [],
11
11
  "dependencies": {
12
- "@milkio/astra": "1.3.66",
13
- "@milkio/drizzle": "1.3.66",
14
- "@milkio/redis": "1.3.66",
15
- "@milkio/stargate": "1.3.66",
12
+ "@milkio/astra": "1.3.68",
13
+ "@milkio/drizzle": "1.3.68",
14
+ "@milkio/redis": "1.3.68",
15
+ "@milkio/stargate": "1.3.68",
16
16
  "drizzle-orm": "^0.43.1",
17
17
  "mysql2": "^3.11.0",
18
18
  "redis": "^4.7.0"